diff --git a/.gitignore b/.gitignore index b001e3c7..ff4f2d5e 100644 --- a/.gitignore +++ b/.gitignore @@ -49,7 +49,7 @@ playground.xcworkspace # # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata # hence it is not needed unless you have added a package configuration file to your project -# .swiftpm +.swiftpm/ .build/ @@ -59,7 +59,7 @@ playground.xcworkspace # you should judge for yourself, the pros and cons are mentioned at: # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control # -# Pods/ +Pods/ # # Add this line if you want to avoid checking in source code from the Xcode workspace # *.xcworkspace diff --git a/Package.resolved b/Package.resolved index a01aac7a..c04146e2 100644 --- a/Package.resolved +++ b/Package.resolved @@ -3,7 +3,7 @@ "pins": [ { "package": "BigInt", - "repositoryURL": "https://github.com/attaswift/BigInt.git", + "repositoryURL": "https://github.com/attaswift/BigInt", "state": { "branch": null, "revision": "889a1ecacd73ccc189c5cb29288048f186c44ed9", @@ -24,17 +24,17 @@ "repositoryURL": "https://github.com/krzyzanowskim/CryptoSwift.git", "state": { "branch": null, - "revision": "5669f222e46c8134fb1f399c745fa6882b43532e", - "version": "1.3.8" + "revision": "8d4f6384e0a8cc41f2005247241dd553963a492a", + "version": "1.4.1" } }, { "package": "FetchNodeDetails", "repositoryURL": "https://github.com/torusresearch/fetch-node-details-swift", "state": { - "branch": null, - "revision": "7d93d8c98d45c723d4836e9406282dda237e48cb", - "version": "0.1.2" + "branch": "feat/argentweb3", + "revision": "94e8385fafe8ecd52465043c12e9da38a98f7fa2", + "version": null } }, { @@ -42,8 +42,26 @@ "repositoryURL": "https://github.com/PromiseKit/Foundation.git", "state": { "branch": null, - "revision": "1a276e598dac59489ed904887e0740fa75e571e0", - "version": "3.3.4" + "revision": "985f17fa69ee0e5b7eb3ff9be87ffc4e05fc0927", + "version": "3.4.0" + } + }, + { + "package": "GenericJSON", + "repositoryURL": "https://github.com/zoul/generic-json-swift", + "state": { + "branch": null, + "revision": "a137894b2a217abe489cdf1ea287e6f7819b1051", + "version": "2.0.1" + } + }, + { + "package": "jwt-kit", + "repositoryURL": "https://github.com/vapor/jwt-kit.git", + "state": { + "branch": null, + "revision": "df7955305940ea0fcd1626a0a6d1a1556623f95e", + "version": "4.2.3" } }, { @@ -51,44 +69,44 @@ "repositoryURL": "https://github.com/mxcl/PromiseKit.git", "state": { "branch": null, - "revision": "aea48ea1855f5d82e2dffa6027afce3aab8f3dd7", - "version": "6.13.3" + "revision": "d2f7ba14bcdc45e18f4f60ad9df883fb9055f081", + "version": "6.15.3" } }, { - "package": "Starscream", - "repositoryURL": "https://github.com/daltoniam/Starscream.git", + "package": "secp256k1", + "repositoryURL": "https://github.com/Boilertalk/secp256k1.swift", "state": { "branch": null, - "revision": "e6b65c6d9077ea48b4a7bdda8994a1d3c6969c8d", - "version": "3.1.1" + "revision": "823281fe9def21b384099b72a9a53ca988317b20", + "version": "0.1.4" } }, { - "package": "BestLogger", - "repositoryURL": "https://github.com/rathishubham7/swift-logger", + "package": "swift-crypto", + "repositoryURL": "https://github.com/apple/swift-crypto.git", "state": { "branch": null, - "revision": "e1e2fa0a6ee9f572432835b70f980a8b36449575", - "version": "0.0.3" + "revision": "3bea268b223651c4ab7b7b9ad62ef9b2d4143eb6", + "version": "1.1.6" } }, { - "package": "swift-nio-zlib-support", - "repositoryURL": "https://github.com/apple/swift-nio-zlib-support.git", + "package": "BestLogger", + "repositoryURL": "https://github.com/rathishubham7/swift-logger", "state": { "branch": null, - "revision": "37760e9a52030bb9011972c5213c3350fa9d41fd", - "version": "1.0.0" + "revision": "e1e2fa0a6ee9f572432835b70f980a8b36449575", + "version": "0.0.3" } }, { - "package": "Web3swift", - "repositoryURL": "https://github.com/rathishubham7/web3swift", + "package": "web3.swift", + "repositoryURL": "https://github.com/argentlabs/web3.swift", "state": { "branch": null, - "revision": "95c8cb18bc8a664963f55e095318c1a180c3f5ec", - "version": "2.2.2" + "revision": "8205d3f671e0248af7d2e0537664d1a85d1ee11e", + "version": "0.8.1" } } ] diff --git a/Package.swift b/Package.swift index a7546221..69f1095c 100644 --- a/Package.swift +++ b/Package.swift @@ -1,30 +1,37 @@ -// swift-tools-version:5.1 +// swift-tools-version:5.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "TorusUtils", + platforms: [ + .iOS(.v13), + ], products: [ .library( name: "TorusUtils", targets: ["TorusUtils"]), ], dependencies: [ - .package(url: "https://github.com/rathishubham7/web3swift", from:"2.0.0"), - .package(url: "https://github.com/rathishubham7/swift-logger", from:"0.0.1"), - .package(url: "https://github.com/torusresearch/fetch-node-details-swift", from:"0.1.0"), - .package(url: "https://github.com/PromiseKit/Foundation.git", from: "3.0.0"), - .package(url: "https://github.com/IBM-Swift/BlueECC.git", from: "1.2.4"), + // .package(url: "https://github.com/skywinder/web3swift", .branch("master")), + .package(name:"BestLogger", url: "https://github.com/rathishubham7/swift-logger", from:"0.0.1"), + // .package(name:"FetchNodeDetails", path: "../fetch-node-details-swift"), + .package(name:"PromiseKit", url: "https://github.com/mxcl/PromiseKit.git", from: "6.0.0"), + .package(name:"PMKFoundation", url: "https://github.com/PromiseKit/Foundation.git", from: "3.0.0"), + .package(name:"CryptorECC", url: "https://github.com/IBM-Swift/BlueECC.git", from: "1.2.4"), + .package(name:"CryptoSwift", url: "https://github.com/krzyzanowskim/CryptoSwift.git", from: "1.0.0"), + .package(name:"jwt-kit", url: "https://github.com/vapor/jwt-kit.git", from: "4.0.0"), + .package(name:"FetchNodeDetails", url: "https://github.com/torusresearch/fetch-node-details-swift", .branch("feat/argentweb3")), + .package(name:"web3.swift", url: "https://github.com/argentlabs/web3.swift", from:"0.7.0"), + .package(name:"secp256k1", url: "https://github.com/Boilertalk/secp256k1.swift", from: "0.1.0"), ], targets: [ - // Targets are the basic building blocks of a package. A target can define a module or a test suite. - // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "TorusUtils", - dependencies: ["FetchNodeDetails", "web3swift", "PMKFoundation", "CryptorECC", "BestLogger"]), + dependencies: [.product(name: "FetchNodeDetails", package: "FetchNodeDetails"), "CryptoSwift", "web3.swift", "CryptorECC", "secp256k1", "PMKFoundation", "PromiseKit", "BestLogger"]), .testTarget( name: "torus-utils-swiftTests", - dependencies: ["TorusUtils"]), + dependencies: ["TorusUtils", .product(name: "JWTKit", package: "jwt-kit"), .product(name: "FetchNodeDetails", package: "FetchNodeDetails"), "web3.swift", "PMKFoundation", "PromiseKit", "CryptorECC", "BestLogger"]), ] ) diff --git a/Sources/TorusUtils/AbstractTorusUtils.swift b/Sources/TorusUtils/AbstractTorusUtils.swift new file mode 100644 index 00000000..efcd89cf --- /dev/null +++ b/Sources/TorusUtils/AbstractTorusUtils.swift @@ -0,0 +1,19 @@ +// +// File.swift +// +// +// Created by Shubham on 1/8/21. +// + +import Foundation +import PromiseKit +import FetchNodeDetails + +public protocol AbstractTorusUtils { + + func setTorusNodePubKeys(nodePubKeys: Array) + + func retrieveShares(endpoints : Array, verifierIdentifier: String, verifierId:String, idToken: String, extraParams: Data) -> Promise<[String:String]> + + func getPublicAddress(endpoints : Array, torusNodePubs : Array, verifier : String, verifierId : String, isExtended: Bool) -> Promise<[String:String]> +} diff --git a/Sources/TorusUtils/Convenience/CryptoExtensions.swift b/Sources/TorusUtils/Convenience/CryptoExtensions.swift index 737da519..5dfb0099 100755 --- a/Sources/TorusUtils/Convenience/CryptoExtensions.swift +++ b/Sources/TorusUtils/Convenience/CryptoExtensions.swift @@ -3,18 +3,18 @@ // Created by Alex Vlasov. // Copyright © 2018 Alex Vlasov. All rights reserved. // - -import Foundation -import CryptoSwift - -func toByteArray(_ 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) -} +// +//import Foundation +//import CryptoSwift +// +//func toByteArray(_ 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/Sources/TorusUtils/Convenience/Data+Extension.swift b/Sources/TorusUtils/Convenience/Data+Extension.swift index fb2d4aeb..4d8acae6 100755 --- a/Sources/TorusUtils/Convenience/Data+Extension.swift +++ b/Sources/TorusUtils/Convenience/Data+Extension.swift @@ -124,6 +124,18 @@ public extension Data { return uintRepresentation } + static func randomOfLength(_ length: Int) -> Data? { + var data = [UInt8](repeating: 0, count: length) + let result = SecRandomCopyBytes(kSecRandomDefault, + data.count, + &data) + if result == errSecSuccess { + return Data(data) + } + + return nil + } + // 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] diff --git a/Sources/TorusUtils/Convenience/SECP256k1.swift b/Sources/TorusUtils/Convenience/SECP256k1.swift index b01b17a8..70989184 100755 --- a/Sources/TorusUtils/Convenience/SECP256k1.swift +++ b/Sources/TorusUtils/Convenience/SECP256k1.swift @@ -1,385 +1,379 @@ -//// -//// 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 { (a: UnsafeRawBufferPointer) -> Int32? in -// if let pkRawPointer = a.baseAddress, a.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.. (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..(elements: ArraySlice, k: Int) -> [[T]] { if k == 0 { return [[]] @@ -51,7 +52,6 @@ extension TorusUtils { } func thresholdSame(arr: Array, threshold: Int) -> T?{ - // print(threshold) var hashmap = [T:Int]() for (_, value) in arr.enumerated(){ if((hashmap[value]) != nil) {hashmap[value]! += 1} @@ -59,18 +59,17 @@ extension TorusUtils { if (hashmap[value] == threshold){ return value } - //print(hashmap) } return nil } func ecdh(pubKey: secp256k1_pubkey, privateKey: Data) -> secp256k1_pubkey? { - var pubKey2 = pubKey // Pointer takes a variable + var localPubkey = pubKey // Pointer takes a variable if (privateKey.count != 32) {return nil} let result = privateKey.withUnsafeBytes { (a: UnsafeRawBufferPointer) -> Int32? in if let pkRawPointer = a.baseAddress, a.count > 0 { let privateKeyPointer = pkRawPointer.assumingMemoryBound(to: UInt8.self) - let res = secp256k1_ec_pubkey_tweak_mul(TorusUtils.context!, UnsafeMutablePointer(&pubKey2), privateKeyPointer) + let res = secp256k1_ec_pubkey_tweak_mul(TorusUtils.context!, UnsafeMutablePointer(&localPubkey), privateKeyPointer) return res } else { return nil @@ -79,29 +78,38 @@ extension TorusUtils { guard let res = result, res != 0 else { return nil } - return pubKey2 + return localPubkey } - // MARK: metadata API + // MARK:- metadata API func getMetadata(dictionary: [String:String]) -> Promise{ + let (promise, seal) = Promise.pending() - // Enode data - let encoded = try! JSONSerialization.data(withJSONObject: dictionary, options: []) - let rq = self.makeUrlRequest(url: "https://metadata.tor.us/get"); - let request = URLSession.shared.uploadTask(.promise, with: rq, from: encoded) + let encoded: Data? + do { + encoded = try JSONSerialization.data(withJSONObject: dictionary, options: []) + } catch { + seal.reject(error) + return promise + } - let (tempPromise, seal) = Promise.pending() + guard let encoded = encoded else { + seal.reject(TorusError.runtime("Unable to serialize dictionary into JSON.")) + return promise + } - request.compactMap { + let request = self.makeUrlRequest(url: "https://metadata.tor.us/get"); + let task = URLSession.shared.uploadTask(.promise, with: request, from: encoded) + task.compactMap { try JSONSerialization.jsonObject(with: $0.data) as? [String: Any] }.done{ data in - self.logger.info("metdata response: ", data) + self.logger.info("getMetadata:", data) seal.fulfill(BigUInt(data["message"] as! String, radix: 16)!) }.catch{ err in seal.fulfill(BigUInt("0", radix: 16)!) } - return tempPromise + return promise } // MARK:- retreiveDecryptAndReconstuct @@ -110,108 +118,105 @@ extension TorusUtils { var rpcdata : Data = Data.init() do { if let loadedStrings = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(extraParams) as? [String:Any] { - let newValue = ["verifieridentifier":verifier, "verifier_id": verifierId, "nodesignatures": nodeSignatures, "idtoken": tokenCommitment] as [String:AnyObject] - let keepingCurrent = loadedStrings.merging(newValue) { (current, _) in current } - - // todo : look into hetrogeneous array encoding + let value = ["verifieridentifier":verifier, "verifier_id": verifierId, "nodesignatures": nodeSignatures, "idtoken": tokenCommitment] as [String : Any] + let keepingCurrent = loadedStrings.merging(value) { (current, _) in current } + // TODO : Look into hetrogeneous array encoding let dataForRequest = ["jsonrpc": "2.0", "id":10, "method": "ShareRequest", "params": ["encrypted": "yes", "item": [keepingCurrent]]] as [String : Any] - rpcdata = try! JSONSerialization.data(withJSONObject: dataForRequest) + rpcdata = try JSONSerialization.data(withJSONObject: dataForRequest) } } catch { - self.logger.error("RetrieveIndividualNodeShare: Couldn't read file.") + self.logger.error("retrieveDecryptAndReconstruct - error:", error) } // Build promises array - var promisesArrayReq = Array >() + var requestPromises = Array >() for el in endpoints { let rq = self.makeUrlRequest(url: el); - promisesArrayReq.append(URLSession.shared.uploadTask(.promise, with: rq, from: rpcdata)) + requestPromises.append(URLSession.shared.uploadTask(.promise, with: rq, from: rpcdata)) } - // Promise to return - let (tempPromise, seal) = Promise<(String, String, String)>.pending() + // Return promise + let (promise, seal) = Promise<(String, String, String)>.pending() var globalCount = 0 - - var ShareResponses = Array<[String:String]?>.init(repeating: nil, count: promisesArrayReq.count) + var shareResponses = Array<[String:String]?>.init(repeating: nil, count: requestPromises.count) var resultArray = [Int:[String:String]]() - var ErrorStack = [Error]() - - for (i, pr) in promisesArrayReq.enumerated(){ - pr.then{ data, response -> Promise<[Int:String]> in - self.logger.info("retrieveDecryptAndReconstuct: ",String(decoding: data, as: UTF8.self)) + var errorStack = [Error]() + for (i, rq) in requestPromises.enumerated(){ + rq.then{ data, response -> Promise<[Int:String]> in + self.logger.info("retrieveDecryptAndReconstuct:", String(decoding: data, as: UTF8.self)) let decoded = try JSONDecoder().decode(JSONRPCresponse.self, from: data) if(decoded.error != nil) { - self.logger.info("retrieveDecryptAndReconstuct: err: ", decoded) - throw TorusError.decodingError + self.logger.error("retrieveDecryptAndReconstuct - error:", decoded) + throw TorusError.decodingFailed } - let decodedResult = decoded.result as? [String:Any] - let keyObj = decodedResult!["keys"] as? [[String:Any]] + guard + let decodedResult = decoded.result as? [String:Any], + let keyObj = decodedResult["keys"] as? [[String:Any]] + else { throw TorusError.decodingFailed } // Due to multiple keyAssign - if let temp = keyObj?.first{ - let metadata = temp["Metadata"] as! [String : String] - let share = temp["Share"] as! String - let publicKey = temp["PublicKey"] as! [String : String] - - ShareResponses[i] = publicKey //For threshold - + if let first = keyObj.first{ + guard + let metadata = first["Metadata"] as? [String : String], + let share = first["Share"] as? String, + let publicKey = first["PublicKey"] as? [String : String] + else { throw TorusError.decodingFailed } + shareResponses[i] = publicKey // For threshold resultArray[i] = ["iv": metadata["iv"]!, "ephermalPublicKey": metadata["ephemPublicKey"]!, "share": share, "pubKeyX": publicKey["X"]!, "pubKeyY": publicKey["Y"]!] } - let lookupShares = ShareResponses.filter{ $0 != nil } // Nonnil elements + let lookupShares = shareResponses.filter{ $0 != nil } // Nonnil elements // Comparing dictionaries, so the order of keys doesn't matter let keyResult = self.thresholdSame(arr: lookupShares.map{$0}, threshold: Int(endpoints.count/2)+1) // Check if threshold is satisfied - if(keyResult != nil && !tempPromise.isFulfilled){ - self.logger.info("retreiveIndividualNodeShares: fulfill: ", resultArray) + if(keyResult != nil && !promise.isFulfilled){ + self.logger.info("retreiveIndividualNodeShares - result:", resultArray) return self.decryptIndividualShares(shares: resultArray, privateKey: privateKey) }else{ throw TorusError.empty } }.then{ data -> Promise<(String, String, String)> in - self.logger.trace("retrieveDecryptAndReconstuct: data after decryptIndividualShares", data) - let filteredData = data.filter{$0.value != TorusError.decodingError.debugDescription} + self.logger.trace("retrieveDecryptAndReconstuct - data after decryptIndividualShares:", data) + let filteredData = data.filter{$0.value != TorusError.decodingFailed.debugDescription} if(filteredData.count < Int(endpoints.count/2)+1){ throw TorusError.thresholdError } return self.thresholdLagrangeInterpolation(data: filteredData, endpoints: endpoints, lookupPubkeyX: lookupPubkeyX, lookupPubkeyY: lookupPubkeyY) }.done{ x, y, z in seal.fulfill((x, y, z)) }.catch{ err in - ErrorStack.append(err) - - let tmpError = err as NSError - let userInfo = tmpError.userInfo as [String: Any] - if(tmpError.code == -1003){ + errorStack.append(err) + let nsErr = err as NSError + let userInfo = nsErr.userInfo as [String: Any] + if(nsErr.code == -1003){ // In case node is offline - self.logger.error("retrieveDecryptAndReconstuct: DNS lookup failed. Node (\(userInfo["NSErrorFailingURLKey"] ?? "")) is probably offline") - }else if let tempError = (err as? TorusError) { - if(tempError == TorusError.thresholdError){ - self.logger.error("retrieveDecryptAndReconstuct: ", TorusError.thresholdError.debugDescription) + self.logger.error("retrieveDecryptAndReconstuct: DNS lookup failed, node (\(userInfo["NSErrorFailingURLKey"] ?? "")) is probably offline.") + }else if let err = (err as? TorusError) { + if(err == TorusError.thresholdError){ + self.logger.error("retrieveDecryptAndReconstuct - error:", err) } }else{ - self.logger.error("retrieveDecryptAndReconstuct: err: ", err) + self.logger.error("retrieveDecryptAndReconstuct - error:", err) } }.finally{ globalCount+=1; - if (globalCount == endpoints.count && tempPromise.isPending) { - seal.reject("Reconstruction failed, \(ErrorStack)") + if (globalCount == endpoints.count && promise.isPending) { + seal.reject(TorusError.runtime("Unable to reconstruct: \(errorStack)")) } } } - return tempPromise + return promise } - // MARK:- commitment request func commitmentRequest(endpoints : Array, verifier: String, pubKeyX: String, pubKeyY: String, timestamp: String, tokenCommitment: String) -> Promise<[[String:String]]>{ + let (promise, seal) = Promise<[[String:String]]>.pending() - // Todo: Add try catch for encoding block let encoder = JSONEncoder() - let rpcdata = try! encoder.encode(JSONRPCrequest( + guard let rpcdata = try? encoder.encode(JSONRPCrequest( method: "CommitmentRequest", params: ["messageprefix": "mug00", "tokencommitment": tokenCommitment, @@ -220,146 +225,149 @@ extension TorusUtils { "verifieridentifier":verifier, "timestamp": timestamp] )) + else { + seal.reject(TorusError.runtime("Unable to encode request.")) + return promise + } // Build promises array - var promisesArray = Array >() + var requestPromises = Array >() for el in endpoints { let rq = self.makeUrlRequest(url: el); - promisesArray.append(URLSession.shared.uploadTask(.promise, with: rq, from: rpcdata)) + requestPromises.append(URLSession.shared.uploadTask(.promise, with: rq, from: rpcdata)) } // Array to store intermediate results - var resultArrayStrings = Array.init(repeating: nil, count: promisesArray.count) - var resultArrayObjects = Array.init(repeating: nil, count: promisesArray.count) + var resultArrayStrings = Array.init(repeating: nil, count: requestPromises.count) + var resultArrayObjects = Array.init(repeating: nil, count: requestPromises.count) var lookupCount = 0 var globalCount = 0 - let (tempPromise, seal) = Promise<[[String:String]]>.pending() - for (i, pr) in promisesArray.enumerated(){ - pr.done{ data, response in - + for (i, rq) in requestPromises.enumerated(){ + rq.done{ data, response in let encoder = JSONEncoder() let decoded = try JSONDecoder().decode(JSONRPCresponse.self, from: data) - self.logger.info("commitmentRequest: reponse: ", decoded) + self.logger.info("commitmentRequest - reponse:", decoded) if(decoded.error != nil) { - self.logger.warning("CommitmentRequest: error: ", decoded) + self.logger.warning("commitmentRequest - error:", decoded) throw TorusError.commitmentRequestFailed } - // check if k+t responses are back + // Check if k+t responses are back resultArrayStrings[i] = String(data: try encoder.encode(decoded), encoding: .utf8) resultArrayObjects[i] = decoded let lookupShares = resultArrayStrings.filter{ $0 as? String != nil } // Nonnil elements - if(lookupShares.count >= Int(endpoints.count/4)*3+1 && !tempPromise.isFulfilled){ + if(lookupShares.count >= Int(endpoints.count/4)*3+1 && !promise.isFulfilled){ let nodeSignatures = resultArrayObjects.compactMap{ $0 }.map{return $0.result as! [String:String]} - self.logger.trace("CommitmentRequest: nodeSignatures: ", nodeSignatures) + self.logger.trace("commitmentRequest - nodeSignatures:", nodeSignatures) seal.fulfill(nodeSignatures) } }.catch{ err in - let tmpError = err as NSError - let userInfo = tmpError.userInfo as [String: Any] - if(tmpError.code == -1003){ + let nsErr = err as NSError + let userInfo = nsErr.userInfo as [String: Any] + if(nsErr.code == -1003){ // In case node is offline - self.logger.error("CommitmentRequest: DNS lookup failed. Node (\(userInfo["NSErrorFailingURLKey"] ?? "")) is probably offline") - // reject if threshold nodes unavailable + self.logger.error("commitmentRequest: DNS lookup failed, node (\(userInfo["NSErrorFailingURLKey"] ?? "")) is probably offline.") + + // Reject if threshold nodes unavailable lookupCount+=1 - - if(!tempPromise.isFulfilled && (lookupCount > endpoints.count)){ + if(!promise.isFulfilled && (lookupCount > endpoints.count)){ seal.reject(TorusError.nodesUnavailable) } }else{ - self.logger.error("CommitmentRequest: err: ", err) + self.logger.error("commitmentRequest - error:", err) } }.finally{ globalCount+=1; - if (globalCount == endpoints.count && tempPromise.isPending) { + if (globalCount == endpoints.count && promise.isPending) { seal.reject(TorusError.commitmentRequestFailed) } } } - return tempPromise + return promise } // MARK:- retrieve each node shares func retrieveIndividualNodeShare(endpoints : Array, extraParams: Data, verifier: String, tokenCommitment:String, nodeSignatures: [[String:String]], verifierId: String) -> Promise<[Int:[String:String]]>{ - // Rebuild extraParams var rpcdata : Data = Data.init() do { if let loadedStrings = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(extraParams) as? [String:Any] { // print(loadedStrings) - let newValue = ["verifieridentifier":verifier, "verifier_id": verifierId, "nodesignatures": nodeSignatures, "idtoken": tokenCommitment] as [String:AnyObject] + let newValue = ["verifieridentifier":verifier, "verifier_id": verifierId, "nodesignatures": nodeSignatures, "idtoken": tokenCommitment] as [String : Any] let keepingCurrent = loadedStrings.merging(newValue) { (current, _) in current } - // todo : look into hetrogeneous array encoding + // TODO : look into hetrogeneous array encoding let dataForRequest = ["jsonrpc": "2.0", "id":10, "method": "ShareRequest", "params": ["encrypted": "yes", "item": [keepingCurrent]]] as [String : Any] - rpcdata = try! JSONSerialization.data(withJSONObject: dataForRequest) + rpcdata = try JSONSerialization.data(withJSONObject: dataForRequest) } } catch { - self.logger.error("RetrieveIndividualNodeShare: Couldn't read file.") + self.logger.error("retrieveIndividualNodeShare - error:", error) } // Build promises array - var promisesArrayReq = Array >() + var requestPromises = Array>() for el in endpoints { let rq = self.makeUrlRequest(url: el); - promisesArrayReq.append(URLSession.shared.uploadTask(.promise, with: rq, from: rpcdata)) + requestPromises.append(URLSession.shared.uploadTask(.promise, with: rq, from: rpcdata)) } - let (tempPromise, seal) = Promise<[Int:[String:String]]>.pending() - var ShareResponses = Array<[String:String]?>.init(repeating: nil, count: promisesArrayReq.count) + let (promise, seal) = Promise<[Int:[String:String]]>.pending() + var shareResponses = Array<[String:String]?>.init(repeating: nil, count: requestPromises.count) var resultArray = [Int:[String:String]]() - - for (i, pr) in promisesArrayReq.enumerated(){ - pr.done{ data, response in - self.logger.info("retreiveIndividualNodeShares: ",String(decoding: data, as: UTF8.self)) + for (i, rq) in requestPromises.enumerated(){ + rq.done{ data, response in + self.logger.info("retreiveIndividualNodeShares:", String(decoding: data, as: UTF8.self)) let decoded = try JSONDecoder().decode(JSONRPCresponse.self, from: data) if(decoded.error != nil) { - self.logger.info("retreiveIndividualNodeShares: err: ", decoded) - throw TorusError.decodingError + self.logger.error("retreiveIndividualNodeShares - error:", decoded) + throw TorusError.decodingFailed } - let decodedResult = decoded.result as? [String:Any] - let keyObj = decodedResult!["keys"] as? [[String:Any]] + guard + let decodedResult = decoded.result as? [String:Any], + let keyObj = decodedResult["keys"] as? [[String:Any]] + else { throw TorusError.decodingFailed } // Due to multiple keyAssign - if let temp = keyObj?.first{ - let metadata = temp["Metadata"] as! [String : String] - let share = temp["Share"] as! String - let publicKey = temp["PublicKey"] as! [String : String] - - ShareResponses[i] = publicKey //For threshold + if let first = keyObj.first{ + guard + let metadata = first["Metadata"] as? [String : String], + let share = first["Share"] as? String, + let publicKey = first["PublicKey"] as? [String : String] + else { throw TorusError.decodingFailed } + shareResponses[i] = publicKey // For threshold resultArray[i] = ["iv": metadata["iv"]!, "ephermalPublicKey": metadata["ephemPublicKey"]!, "share": share, "pubKeyX": publicKey["X"]!, "pubKeyY": publicKey["Y"]!] } - let lookupShares = ShareResponses.filter{ $0 != nil } // Nonnil elements + let lookupShares = shareResponses.filter{ $0 != nil } // Nonnil elements // Comparing dictionaries, so the order of keys doesn't matter let keyResult = self.thresholdSame(arr: lookupShares.map{$0}, threshold: Int(endpoints.count/2)+1) // Check if threshold is satisfied - if(keyResult != nil && !tempPromise.isFulfilled){ - self.logger.info("retreiveIndividualNodeShares: fulfill: ", resultArray) + if(keyResult != nil && !promise.isFulfilled){ + self.logger.info("retreiveIndividualNodeShares - fulfill:", resultArray) seal.fulfill(resultArray) } }.catch{ err in - let tmpError = err as NSError - let userInfo = tmpError.userInfo as [String: Any] - if(tmpError.code == -1003){ + let nsErr = err as NSError + let userInfo = nsErr.userInfo as [String: Any] + if(nsErr.code == -1003){ // In case node is offline - self.logger.error("keyLookup: DNS lookup failed. Node (\(userInfo["NSErrorFailingURLKey"] ?? "")) is probably offline") + self.logger.error("retreiveIndividualNodeShares: DNS lookup failed, node (\(userInfo["NSErrorFailingURLKey"] ?? "")) is probably offline.") }else{ - self.logger.error("retreiveIndividualNodeShares: errReject: ", err) + self.logger.error("retreiveIndividualNodeShares - error:", err) seal.reject(err) } } } - return tempPromise + return promise } // MARK:- decrypt shares @@ -401,7 +409,7 @@ extension TorusUtils { let decrypt = try aes.decrypt(share) result[nodeIndex] = decrypt.hexa }catch{ - result[nodeIndex] = TorusError.decodingError.debugDescription + result[nodeIndex] = TorusError.decodingFailed.debugDescription } if(shares.count == result.count) { seal.fulfill(result) // Resolve if all shares decrypt @@ -422,15 +430,19 @@ extension TorusUtils { shareIndexSet.forEach{ sharesToInterpolate[$0] = filteredData[$0]} self.lagrangeInterpolation(shares: sharesToInterpolate).done{data -> Void in // Split key in 2 parts, X and Y - let finalPrivateKey = Data.init(hex: data) - let publicKey = SECP256K1.privateToPublic(privateKey: finalPrivateKey , compressed: false)?.suffix(64) - let pubKeyX = publicKey?.prefix(publicKey!.count/2).toHexString() - let pubKeyY = publicKey?.suffix(publicKey!.count/2).toHexString() + let finalPrivateKey = data.web3.hexData! + guard let publicKey = SECP256K1.privateToPublic(privateKey: finalPrivateKey)?.subdata(in: 1..<65) else{ + seal.reject(TorusError.decodingFailed) + return + } + + let pubKeyX = publicKey.prefix(publicKey.count/2).toHexString() + let pubKeyY = publicKey.suffix(publicKey.count/2).toHexString() self.logger.trace("retrieveDecryptAndReconstuct: private key rebuild", data, pubKeyX as Any, pubKeyY as Any) // Verify if( pubKeyX == lookupPubkeyX && pubKeyY == lookupPubkeyY) { - seal.fulfill((pubKeyX!, pubKeyY!, data)) + seal.fulfill((pubKeyX, pubKeyY, data)) }else{ self.logger.error("retrieveDecryptAndReconstuct: verification failed") } @@ -529,9 +541,10 @@ extension TorusUtils { for (i, pr) in promisesArray.enumerated() { pr.done{ data, response in // print("keyLookup", String(data: data, encoding: .utf8)) + self.logger.trace(String(data: data, encoding: .utf8)) let decoder = try? JSONDecoder().decode(JSONRPCresponse.self, from: data) // User decoder to covert to struct - if(decoder == nil) { throw TorusError.decodingError } - //print(decoder) + if(decoder == nil) { throw TorusError.decodingFailed } + let result = decoder!.result let error = decoder?.error if(error == nil){ @@ -542,7 +555,7 @@ extension TorusUtils { resultArray[i] = ["err": "keyLookupfailed"] } - // print(resultArray[i]) + let lookupShares = resultArray.filter{ $0 != nil } // Nonnil elements let keyResult = self.thresholdSame(arr: lookupShares, threshold: Int(endpoints.count/2)+1) // Check if threshold is satisfied // print("threshold result", keyResult) @@ -648,12 +661,16 @@ extension TorusUtils { } // MARK:- Helper functions - - public func privateKeyToAddress(key: Data) -> Data{ - print(key) - let publicKey = SECP256K1.privateToPublic(privateKey: key)! - let address = Data(publicKey.sha3(.keccak256).suffix(20)) - return address +// +// public func privateKeyToAddress(key: Data) -> Data{ +// print(key) +// let publicKey = SECP256K1.privateToPublic(privateKey: key)! +// let address = Data(publicKey.sha3(.keccak256).suffix(20)) +// return address +// } +// + func generatePrivateKeyData() -> Data? { + return Data.randomOfLength(32) } public func publicKeyToAddress(key: Data) -> Data{ @@ -670,24 +687,6 @@ extension TorusUtils { return (added?.toHexString())! } - func privateKeyToPublicKey4(privateKey: Data) -> secp256k1_pubkey? { - if (privateKey.count != 32) {return nil} - var publicKey = secp256k1_pubkey() - let result = privateKey.withUnsafeBytes { (a: UnsafeRawBufferPointer) -> Int32? in - if let pkRawPointer = a.baseAddress, a.count > 0 { - let privateKeyPointer = pkRawPointer.assumingMemoryBound(to: UInt8.self) - let res = secp256k1_ec_pubkey_create(TorusUtils.context!, UnsafeMutablePointer(&publicKey), privateKeyPointer) - return res - } else { - return nil - } - } - guard let res = result, res != 0 else { - return nil - } - return publicKey - } - func tupleToArray(_ tuple: Any) -> [UInt8] { // var result = [UInt8]() let tupleMirror = Mirror(reflecting: tuple) @@ -781,4 +780,3 @@ extension Data { Data(hex: self.toHexString().addLeading0sForLength64()) } } - diff --git a/Sources/TorusUtils/Helpers/Error.swift b/Sources/TorusUtils/Helpers/Error.swift index a36e720b..ba016a58 100644 --- a/Sources/TorusUtils/Helpers/Error.swift +++ b/Sources/TorusUtils/Helpers/Error.swift @@ -8,9 +8,10 @@ import Foundation public enum TorusError: Error{ + case configurationError case apiRequestFailed case errInResponse(Any) - case decodingError + case decodingFailed case commitmentRequestFailed case decryptionFailed case thresholdError @@ -19,15 +20,18 @@ public enum TorusError: Error{ case unableToDerive case interpolationFailed case nodesUnavailable + case runtime(_ msg: String) case empty } extension TorusError: CustomDebugStringConvertible{ public var debugDescription: String{ switch self { + case .configurationError: + return "SDK Configuration incorrect. Network is probably incorrect" case .apiRequestFailed: return "API request failed or No response from the node" - case .decodingError: + case .decodingFailed: return "JSON Decoding error" case .errInResponse(let str): return "API response error \(str)" @@ -49,6 +53,8 @@ extension TorusError: CustomDebugStringConvertible{ return "One or more nodes unavailable" case .empty: return "" + case .runtime(let msg): + return msg } } diff --git a/Sources/TorusUtils/Helpers/JSONRPCRequest.swift b/Sources/TorusUtils/Helpers/JSONRPCRequest.swift index 321dfa39..912307fe 100644 --- a/Sources/TorusUtils/Helpers/JSONRPCRequest.swift +++ b/Sources/TorusUtils/Helpers/JSONRPCRequest.swift @@ -68,10 +68,10 @@ public struct KeyAssignRequest: Encodable{ try container.encode(jsonrpc, forKey: .jsonrpc) try container.encode(method, forKey: .method) - if let newParams = params as? [String:String] { + if let _ = params as? [String:String] { try container.encode(params as! [String:String], forKey: .params) } - if let newParams = params as? [String: [String:[String:String]]] { + if let _ = params as? [String: [String:[String:String]]] { try container.encode(params as! [String: [String:[String:String]]], forKey: .params) } @@ -107,10 +107,10 @@ public struct JSONRPCrequest: Encodable { try container.encode(jsonrpc, forKey: .jsonrpc) try container.encode(method, forKey: .method) - if let newParams = params as? [String:String] { + if let _ = params as? [String:String] { try container.encode(params as! [String:String], forKey: .params) } - if let newParams = params as? [String: [String:[String:String]]] { + if let _ = params as? [String: [String:[String:String]]] { try container.encode(params as! [String: [String:[String:String]]], forKey: .params) } diff --git a/Sources/TorusUtils/TorusUtils.swift b/Sources/TorusUtils/TorusUtils.swift index aaa2bcd1..01a61417 100644 --- a/Sources/TorusUtils/TorusUtils.swift +++ b/Sources/TorusUtils/TorusUtils.swift @@ -5,40 +5,62 @@ import Foundation import FetchNodeDetails -import web3swift +import web3 import PromiseKit -#if canImport(secp256k1) import secp256k1 -#endif -import CryptoSwift import BigInt import BestLogger -public class TorusUtils{ - static let context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN|SECP256K1_CONTEXT_VERIFY)) - let nodePubKeys: Array +public class TorusUtils: AbstractTorusUtils{ + + static let context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY)) + + var nodePubKeys: Array let logger: BestLogger - public init(label: String = "Torus utils", loglevel: BestLogger.Level = .info, nodePubKeys: Array = [TorusNodePub(_X: "4086d123bd8b370db29e84604cd54fa9f1aeb544dba1cc9ff7c856f41b5bf269", _Y: "fde2ac475d8d2796aab2dea7426bc57571c26acad4f141463c036c9df3a8b8e8"),TorusNodePub(_X: "1d6ae1e674fdc1849e8d6dacf193daa97c5d484251aa9f82ff740f8277ee8b7d", _Y: "43095ae6101b2e04fa187e3a3eb7fbe1de706062157f9561b1ff07fe924a9528"),TorusNodePub(_X: "fd2af691fe4289ffbcb30885737a34d8f3f1113cbf71d48968da84cab7d0c262", _Y: "c37097edc6d6323142e0f310f0c2fb33766dbe10d07693d73d5d490c1891b8dc"),TorusNodePub(_X: "e078195f5fd6f58977531135317a0f8d3af6d3b893be9762f433686f782bec58", _Y: "843f87df076c26bf5d4d66120770a0aecf0f5667d38aa1ec518383d50fa0fb88"),TorusNodePub(_X: "a127de58df2e7a612fd256c42b57bb311ce41fd5d0ab58e6426fbf82c72e742f", _Y: "388842e57a4df814daef7dceb2065543dd5727f0ee7b40d527f36f905013fa96")]){ + public init(label: String, loglevel: BestLogger.Level = .none, nodePubKeys: Array){ self.logger = BestLogger(label: label, level: loglevel) self.nodePubKeys = nodePubKeys } + public convenience init(){ + self.init(label: "Torus Utils", loglevel: .info, nodePubKeys: [] ) + } + + public convenience init(nodePubKeys: Array){ + self.init(label: "Torus Utils", loglevel: .info, nodePubKeys: nodePubKeys ) + } + + public convenience init(nodePubKeys: Array, loglevel: BestLogger.Level){ + self.init(label: "Torus Utils", loglevel: loglevel, nodePubKeys: nodePubKeys ) + } + + + public func setTorusNodePubKeys(nodePubKeys: Array){ + self.nodePubKeys = nodePubKeys + } + +// public func setEndpoints(endpoints: Array){ +// self.endpoints = endpoints +// } + public func getPublicAddress(endpoints : Array, torusNodePubs : Array, verifier : String, verifierId : String, isExtended: Bool) -> Promise<[String:String]>{ - - let (tempPromise, seal) = Promise<[String:String]>.pending() + let (promise, seal) = Promise<[String:String]>.pending() let keyLookup = self.keyLookup(endpoints: endpoints, verifier: verifier, verifierId: verifierId) keyLookup.then{ lookupData -> Promise<[String: String]> in let error = lookupData["err"] if(error != nil){ - // Assign key to the user and return (wraped in a promise) + // Assign key to the user and return (wrapped in a promise) return self.keyAssign(endpoints: endpoints, torusNodePubs: torusNodePubs, verifier: verifier, verifierId: verifierId).then{ data -> Promise<[String:String]> in // Do keylookup again return self.keyLookup(endpoints: endpoints, verifier: verifier, verifierId: verifierId) }.then{ data -> Promise<[String: String]> in - + let error = data["err"] + if(error != nil) { + throw TorusError.configurationError + } return Promise<[String: String]>.value(data) } }else{ @@ -48,10 +70,15 @@ public class TorusUtils{ return self.getMetadata(dictionary: ["pub_key_X": data["pub_key_X"]!, "pub_key_Y": data["pub_key_Y"]!]).map{ ($0, data) } // Tuple }.done{ nonce, data in var newData = data + guard + let localPubkeyX = newData["pub_key_X"], + let localPubkeyY = newData["pub_key_Y"] + else { throw TorusError.runtime("Empty pubkey returned from getMetadata.") } + // Convert to BigInt for modulus let nonce2 = BigInt(nonce).modulus(BigInt("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", radix: 16)!) if(nonce != BigInt(0)) { - let actualPublicKey = "04" + newData["pub_key_X"]!.addLeading0sForLength64() + newData["pub_key_Y"]!.addLeading0sForLength64() + let actualPublicKey = "04" + localPubkeyX.addLeading0sForLength64() + localPubkeyY.addLeading0sForLength64() let noncePublicKey = SECP256K1.privateToPublic(privateKey: BigUInt(nonce2).serialize().addLeading0sForLength64()) let addedPublicKeys = self.combinePublicKeys(keys: [actualPublicKey, noncePublicKey!.toHexString()], compressed: false) newData["address"] = self.publicKeyToAddress(key: addedPublicKeys) @@ -62,60 +89,63 @@ public class TorusUtils{ }else{ seal.fulfill(newData) } - }.catch{err in self.logger.error("getPublicAddress: err: ", err) - if let tmpError = err as? TorusError{ - if(tmpError == TorusError.nodesUnavailable){ - seal.reject(TorusError.nodesUnavailable) + if let err = err as? TorusError{ + if(err == TorusError.nodesUnavailable){ + seal.reject(err) } + seal.reject(err) } } - return tempPromise - + return promise } public func retrieveShares(endpoints : Array, verifierIdentifier: String, verifierId:String, idToken: String, extraParams: Data) -> Promise<[String:String]>{ + let (promise, seal) = Promise<[String:String]>.pending() + + // Generate keypair + guard + let privateKey = self.generatePrivateKeyData(), + let publicKey = SECP256K1.privateToPublic(privateKey: privateKey)?.subdata(in: 1..<65) + else { + seal.reject(TorusError.runtime("Unable to generate SECP256K1 keypair.")) + return promise + } - // Generate privatekey - let privateKey = SECP256K1.generatePrivateKey() - let publicKey = SECP256K1.privateToPublic(privateKey: privateKey!, compressed: false)?.suffix(64) // take last 64 // Split key in 2 parts, X and Y - let publicKeyHex = publicKey?.toHexString() - let pubKeyX = publicKey?.prefix(publicKey!.count/2).toHexString().addLeading0sForLength64() - let pubKeyY = publicKey?.suffix(publicKey!.count/2).toHexString().addLeading0sForLength64() + let publicKeyHex = publicKey.toHexString() + let pubKeyX = publicKey.prefix(publicKey.count/2).toHexString().addLeading0sForLength64() + let pubKeyY = publicKey.suffix(publicKey.count/2).toHexString().addLeading0sForLength64() // Hash the token from OAuth login - // let tempIDToken = verifierParams.map{$0["idtoken"]!}.joined(separator: "\u{001d}") - - let hashedOnce = idToken.sha3(.keccak256) - // let tokenCommitment = hashedOnce.sha3(.keccak256) let timestamp = String(Int(Date().timeIntervalSince1970)) + let hashedToken = idToken.sha3(.keccak256) var publicAddress: String = "" var lookupPubkeyX: String = "" var lookupPubkeyY: String = "" - self.logger.debug("RetrieveShares: ", privateKey?.toHexString() as Any, publicKeyHex as Any, pubKeyX as Any, pubKeyY as Any, hashedOnce) - - let (tempPromise, seal) = Promise<[String:String]>.pending() - + self.logger.debug("retrieveShares:", privateKey.toHexString(), publicKeyHex, pubKeyX, pubKeyY, hashedToken) + // Reject if not resolved in 30 seconds after(.seconds(300)).done { seal.reject(TorusError.timeout) } - - getPublicAddress(endpoints: endpoints, torusNodePubs: nodePubKeys, verifier: verifierIdentifier, verifierId: verifierId, isExtended: true).then{ data -> Promise<[[String:String]]> in publicAddress = data["address"] ?? "" - lookupPubkeyX = data["pub_key_X"]!.addLeading0sForLength64() - lookupPubkeyY = data["pub_key_Y"]!.addLeading0sForLength64() - return self.commitmentRequest(endpoints: endpoints, verifier: verifierIdentifier, pubKeyX: pubKeyX!, pubKeyY: pubKeyY!, timestamp: timestamp, tokenCommitment: hashedOnce) + guard + let localPubkeyX = data["pub_key_X"]?.addLeading0sForLength64(), + let localPubkeyY = data["pub_key_Y"]?.addLeading0sForLength64() + else { throw TorusError.runtime("Empty pubkey returned from getPublicAddress.") } + lookupPubkeyX = localPubkeyX + lookupPubkeyY = localPubkeyY + return self.commitmentRequest(endpoints: endpoints, verifier: verifierIdentifier, pubKeyX: pubKeyX, pubKeyY: pubKeyY, timestamp: timestamp, tokenCommitment: hashedToken) }.then{ data -> Promise<(String, String, String)> in - self.logger.info("retrieveShares: data after commitment request", data) - return self.retrieveDecryptAndReconstruct(endpoints: endpoints, extraParams: extraParams, verifier: verifierIdentifier, tokenCommitment: idToken, nodeSignatures: data, verifierId: verifierId, lookupPubkeyX: lookupPubkeyX, lookupPubkeyY: lookupPubkeyY, privateKey: (privateKey?.toHexString())!) + self.logger.info("retrieveShares - data after commitment request:", data) + return self.retrieveDecryptAndReconstruct(endpoints: endpoints, extraParams: extraParams, verifier: verifierIdentifier, tokenCommitment: idToken, nodeSignatures: data, verifierId: verifierId, lookupPubkeyX: lookupPubkeyX, lookupPubkeyY: lookupPubkeyY, privateKey: privateKey.toHexString()) }.then{ x, y, key in return self.getMetadata(dictionary: ["pub_key_X": x, "pub_key_Y": y]).map{ ($0, key) } // Tuple }.done{ nonce, key in @@ -126,17 +156,16 @@ public class TorusUtils{ seal.fulfill(["privateKey": BigUInt(newKey).serialize().suffix(64).toHexString(), "publicAddress": publicAddress]) } seal.fulfill(["privateKey":key, "publicAddress": publicAddress]) - }.catch{ err in - self.logger.error("retrieveShares: err: ",err) + self.logger.error("retrieveShares - error:",err) seal.reject(err) }.finally { - if(tempPromise.isPending){ + if(promise.isPending){ seal.reject(TorusError.unableToDerive) } } - return tempPromise + return promise } - } + diff --git a/Tests/torus-utils-swiftTests/IntegrationTest.swift b/Tests/torus-utils-swiftTests/IntegrationTest.swift new file mode 100644 index 00000000..4cf044b4 --- /dev/null +++ b/Tests/torus-utils-swiftTests/IntegrationTest.swift @@ -0,0 +1,194 @@ +import XCTest +import PromiseKit +import FetchNodeDetails +import CryptoSwift +import BigInt +import web3 +import secp256k1 +import CryptorECC +import JWTKit + +@testable import TorusUtils + +@available(iOS 11.0, *) +final class IntegrationTests: XCTestCase { + static var fetchNodeDetails: FetchNodeDetails? + static var nodeDetails: NodeDetails? + static var utils: TorusUtils? + static var endpoints: Array = [] + static var nodePubKeys: Array = [] + static var privKey: String = "" + + let TORUS_TEST_VERIFIER = "torus-test-ios-public"; + let TORUS_TEST_AGGREGATE_VERIFIER = "torus-ios-public-agg"; + let TORUS_TEST_AGGREGATE_VERIFIER_SUB1 = "torus-test-ios-public-agg1" + let TORUS_TEST_AGGREGATE_VERIFIER_SUB2 = "torus-test-ios-public-agg2" + let TORUS_TEST_EMAIL = "hello@tor.us"; + + override class func setUp() { + IntegrationTests.fetchNodeDetails = FetchNodeDetails(proxyAddress: "0x4023d2a0D330bF11426B12C6144Cfb96B7fa6183", network: .ROPSTEN) +// IntegrationTests.nodeDetails = IntegrationTests.fetchNodeDetails?.getNodeDetails() +// IntegrationTests.endpoints = IntegrationTests.nodeDetails?.getTorusNodeEndpoints() ?? [] +// IntegrationTests.nodePubKeys = IntegrationTests.nodeDetails?.getTorusNodePub() ?? [] + + // Faster logins by mocking data. + IntegrationTests.endpoints = ROPSTEN_CONSTANTS.endpoints + IntegrationTests.nodePubKeys = ROPSTEN_CONSTANTS.nodePubKeys + + IntegrationTests.utils = TorusUtils(nodePubKeys: IntegrationTests.nodePubKeys, loglevel: .none) + } + + func test_getPublicAddress(){ + let exp1 = XCTestExpectation(description: "Should be able to getPublicAddress") + IntegrationTests.utils?.getPublicAddress(endpoints: IntegrationTests.endpoints, torusNodePubs: IntegrationTests.nodePubKeys, verifier: self.TORUS_TEST_VERIFIER, verifierId: TORUS_TEST_EMAIL, isExtended: false).done{ data in + XCTAssertEqual(data["address"], "0xF2c682Fc2e053D03Bb91846d6755C3A31ed34C0f") + exp1.fulfill() + }.catch{ error in + print(error) + XCTFail() + } + + wait(for: [exp1], timeout: 5) + } + + func test_keyAssign(){ + + let email = generateRandomEmail(of: 6) + + let exp1 = XCTestExpectation(description: "Should be able to do a keyAssign") + IntegrationTests.utils?.keyAssign(endpoints: IntegrationTests.endpoints, torusNodePubs: IntegrationTests.nodePubKeys, verifier: self.TORUS_TEST_VERIFIER, verifierId: email).done{ data in + let result = data.result as! [String:Any] + let keys = result["keys"] as! [[String:String]] + let address = keys[0]["address"] + + // Add more check to see if address is valid + XCTAssertNotNil(address) + exp1.fulfill() + }.catch{error in + XCTFail() + } + + wait(for: [exp1], timeout: 5) + + } + + func test_keyLookup(){ + let exp1 = XCTestExpectation(description: "Should be able to do a keyLookup") + + IntegrationTests.utils?.keyLookup(endpoints: IntegrationTests.endpoints, verifier: "google-lrc", verifierId: TORUS_TEST_EMAIL).done{ data in + XCTAssertEqual(data["address"], "0xFf5aDad69F4e97AF4D4567e7C333C12df6836a70") + exp1.fulfill() + }.catch{error in + XCTFail() + } + + wait(for: [exp1], timeout: 5) + + } + + func test_shouldLogin(){ + let exp1 = XCTestExpectation(description: "Should be able to do a Login") + + do{ + let jwt = try generateIdToken(email: self.TORUS_TEST_EMAIL) + let extraParams = ["verifieridentifier": self.TORUS_TEST_VERIFIER, "verifier_id": self.TORUS_TEST_EMAIL] as [String : Any] + let buffer: Data = try! NSKeyedArchiver.archivedData(withRootObject: extraParams, requiringSecureCoding: false) + + IntegrationTests.utils?.retrieveShares(endpoints: IntegrationTests.endpoints, verifierIdentifier: self.TORUS_TEST_VERIFIER, verifierId: self.TORUS_TEST_EMAIL, idToken: jwt, extraParams: buffer).done{ data in + XCTAssertEqual(data["publicAddress"], "0xF2c682Fc2e053D03Bb91846d6755C3A31ed34C0f") + exp1.fulfill() + }.catch{ error in + print(error) + XCTFail() + } + }catch{ + XCTFail("\(error)") + } + + wait(for: [exp1], timeout: 10) + } + + // MARK: Aggregate tests + + func test_getPublicAddressAggregateLogin(){ + let exp1 = XCTestExpectation(description: "Should be able to getPublicAddress") + IntegrationTests.utils?.getPublicAddress(endpoints: IntegrationTests.endpoints, torusNodePubs: IntegrationTests.nodePubKeys, verifier: TORUS_TEST_AGGREGATE_VERIFIER, verifierId: TORUS_TEST_EMAIL, isExtended: false).done{ data in + XCTAssertEqual(data["address"], "0xF9f6742d29B4524a3e56f2d7EBE718a31E73CAD1") + exp1.fulfill() + }.catch{ error in + print(error) + XCTFail() + } + + wait(for: [exp1], timeout: 5) + } + + + func test_keyAssignAggregateLogin(){ + + let email = generateRandomEmail(of: 6) + + let exp1 = XCTestExpectation(description: "Should be able to do a keyAssign") + IntegrationTests.utils?.keyAssign(endpoints: IntegrationTests.endpoints, torusNodePubs: IntegrationTests.nodePubKeys, verifier: self.TORUS_TEST_AGGREGATE_VERIFIER, verifierId: email).done{ data in + let result = data.result as! [String:Any] + let keys = result["keys"] as! [[String:String]] + let address = keys[0]["address"] + + // Add more check to see if address is valid + XCTAssertNotNil(address) + exp1.fulfill() + }.catch{error in + XCTFail() + } + + wait(for: [exp1], timeout: 5) + + } + + func test_keyLookupAggregateLogin(){ + let exp1 = XCTestExpectation(description: "Should be able to do a keyLookupAggregateLogin") + + IntegrationTests.utils?.keyLookup(endpoints: IntegrationTests.endpoints, verifier: self.TORUS_TEST_AGGREGATE_VERIFIER, verifierId: TORUS_TEST_EMAIL).done{ data in + XCTAssertEqual(data["address"], "0xF9f6742d29B4524a3e56f2d7EBE718a31E73CAD1") + exp1.fulfill() + }.catch{error in + XCTFail() + } + + wait(for: [exp1], timeout: 5) + + } + + func test_shouldAggregateLogin(){ + let exp1 = XCTestExpectation(description: "Should be able to do a aggregate login") + do{ + let jwt = try generateIdToken(email: self.TORUS_TEST_EMAIL) + let extraParams = ["verifieridentifier": self.TORUS_TEST_AGGREGATE_VERIFIER, "verifier_id": self.TORUS_TEST_EMAIL, "sub_verifier_ids":[self.TORUS_TEST_AGGREGATE_VERIFIER_SUB1], "verify_params": [["verifier_id": self.TORUS_TEST_EMAIL, "idtoken": jwt]]] as [String : Any] + let buffer: Data = try! NSKeyedArchiver.archivedData(withRootObject: extraParams, requiringSecureCoding: false) + + IntegrationTests.utils?.retrieveShares(endpoints: IntegrationTests.endpoints, verifierIdentifier: self.TORUS_TEST_AGGREGATE_VERIFIER, verifierId: self.TORUS_TEST_EMAIL, idToken: jwt.sha3(.keccak256), extraParams: buffer).done{ data in + XCTAssertEqual(data["publicAddress"], "0xF9f6742d29B4524a3e56f2d7EBE718a31E73CAD1") + exp1.fulfill() + }.catch{ error in + XCTFail() + } + }catch{ + XCTFail("\(error)") + } + + wait(for: [exp1], timeout: 10) + } + + var allTests = [ + ("getPublicAddress", test_getPublicAddress), + ] +} + +struct ROPSTEN_CONSTANTS { + static let endpoints = ["https://teal-15-1.torusnode.com/jrpc", "https://teal-15-3.torusnode.com/jrpc", "https://teal-15-4.torusnode.com/jrpc", "https://teal-15-5.torusnode.com/jrpc", "https://teal-15-2.torusnode.com/jrpc"] + static let nodePubKeys = [TorusNodePub(_X: "1363AAD8868CACD7F8946C590325CD463106FB3731F08811AB4302D2DEAE35C3" , _Y: "D77EEBE5CDF466B475EC892D5B4CFFBE0C1670525DEBBD97EEE6DAE2F87A7CBE" ), + TorusNodePub(_X: "7C8CC521C48690F016BEA593F67F88AD24F447DD6C31BBAB541E59E207BF029D" , _Y: "B359F0A82608DB2E06B953B36D0C9A473A00458117CA32A5B0F4563A7D539636" ), + TorusNodePub(_X: "8A86543CA17DF5687719E2549CAA024CF17FE0361E119E741EAEE668F8DD0A6F" , _Y: "9CDB254FF915A76950D6D13D78EF054D5D0DC34E2908C00BB009A6E4DA701891" ), + TorusNodePub(_X: "25A98D9AE006AED1D77E81D58BE8F67193D13D01A9888E2923841894F4B0BF9C" , _Y: "F63D40DF480DACF68922004ED36DBAB9E2969181B047730A5CE0797FB6958249" ), + TorusNodePub(_X: "D908F41F8E06324A8A7ABCF702ADB6A273CE3AE63D86A3D22723E1BBF1438C9A" , _Y: "F977530B3EC0E525438C72D1E768380CBC5FB3B38A760EE925053B2E169428CE" )] +} diff --git a/Tests/torus-utils-swiftTests/JWTUtils.swift b/Tests/torus-utils-swiftTests/JWTUtils.swift new file mode 100644 index 00000000..8cd44fc2 --- /dev/null +++ b/Tests/torus-utils-swiftTests/JWTUtils.swift @@ -0,0 +1,85 @@ +// +// File.swift +// +// +// Created by Shubham on 3/8/21. +// + +import Foundation +import JWTKit + + +// JWT payload structure. +struct TestPayload: JWTPayload, Equatable { + enum CodingKeys: String, CodingKey { + case subject = "sub" + case expiration = "exp" + case isAdmin = "admin" + case emailVerified = "email_verified" + case issuer = "iss" + case iat = "iat" + case email = "email" + case audience = "aud" + } + + var subject: SubjectClaim + var expiration: ExpirationClaim + var audience: AudienceClaim + var isAdmin: Bool + let emailVerified: Bool + var issuer: IssuerClaim + var iat: IssuedAtClaim + var email: String + + // call its verify method. + func verify(using signer: JWTSigner) throws { + try self.expiration.verifyNotExpired() + } +} + +func generateRandomEmail(of length: Int) -> String { + let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + var s = "" + for _ in 0 ..< length { + s.append(letters.randomElement()!) + } + return s + "@gmail.com" +} + +func generateIdToken(email: String) throws -> String{ + let verifierPrivateKeyForSigning = + """ + -----BEGIN PRIVATE KEY----- + MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCA3pdm53N0jlj3+7st1 + kIxw9aogvHfbq09TlWKRFPGJjA== + -----END PRIVATE KEY----- + """ + + do{ + let signers = JWTSigners() + let keys = try ECDSAKey.private(pem: verifierPrivateKeyForSigning) + signers.use(.es256(key: keys)) + + // Parses the JWT and verifies its signature. + let today = Date.init() + let modifiedDate = Calendar.current.date(byAdding: .hour, value: 1, to: today)! + + let emailComponent = email.components(separatedBy: "@")[0] + let subject = "email|"+emailComponent + + let payload = TestPayload(subject: SubjectClaim(stringLiteral: subject), expiration: ExpirationClaim(value: modifiedDate), audience: "torus-key-test" , isAdmin: false, emailVerified: true, issuer: "torus-key-test", iat: IssuedAtClaim(value: Date.init()), email: "hello@tor.us") + let jwt = try signers.sign(payload) + return jwt + }catch{ + print(error) + throw error + } +} + + +//key 2 +// +//-----BEGIN PRIVATE KEY----- +//MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCCTK9Ly1QItO9QLoX12 +//IJC5lTMiO+7eZXQDiYi8mGLMvg== +//-----END PRIVATE KEY----- diff --git a/Tests/torus-utils-swiftTests/MockTorusUtils.swift b/Tests/torus-utils-swiftTests/MockTorusUtils.swift new file mode 100644 index 00000000..3c05e765 --- /dev/null +++ b/Tests/torus-utils-swiftTests/MockTorusUtils.swift @@ -0,0 +1,33 @@ +// +// File.swift +// +// +// Created by Shubham on 2/8/21. +// + +import Foundation +import TorusUtils +import PromiseKit +import FetchNodeDetails + +class MockTorusUtils: AbstractTorusUtils{ + var nodePubKeys: Array + + init(){ + self.nodePubKeys = [] + } + + func setTorusNodePubKeys(nodePubKeys: Array) { + self.nodePubKeys = nodePubKeys + } + + func retrieveShares(endpoints: Array, verifierIdentifier: String, verifierId: String, idToken: String, extraParams: Data) -> Promise<[String : String]> { + return Promise.value([:]) + } + + func getPublicAddress(endpoints: Array, torusNodePubs: Array, verifier: String, verifierId: String, isExtended: Bool) -> Promise<[String : String]> { + return Promise.value([:]) + } + + +} diff --git a/Tests/torus-utils-swiftTests/unit_test.swift b/Tests/torus-utils-swiftTests/unit_test.swift index 01dae28d..f9056b0e 100644 --- a/Tests/torus-utils-swiftTests/unit_test.swift +++ b/Tests/torus-utils-swiftTests/unit_test.swift @@ -3,7 +3,7 @@ import PromiseKit import FetchNodeDetails import CryptoSwift import BigInt -import web3swift +import web3 import secp256k1 /** @@ -20,185 +20,185 @@ import secp256k1 @available(iOS 11.0, *) final class torus_utils_swiftTests: XCTestCase { - let context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN|SECP256K1_CONTEXT_VERIFY)) - let nodeList = ["https://teal-15-1.torusnode.com/jrpc", "https://teal-15-3.torusnode.com/jrpc", "https://teal-15-4.torusnode.com/jrpc", "https://teal-15-5.torusnode.com/jrpc", "https://teal-15-2.torusnode.com/jrpc"] - let nodePubKeys : Array = [TorusNodePub(_X: "4086d123bd8b370db29e84604cd54fa9f1aeb544dba1cc9ff7c856f41b5bf269", _Y: "fde2ac475d8d2796aab2dea7426bc57571c26acad4f141463c036c9df3a8b8e8"),TorusNodePub(_X: "1d6ae1e674fdc1849e8d6dacf193daa97c5d484251aa9f82ff740f8277ee8b7d", _Y: "43095ae6101b2e04fa187e3a3eb7fbe1de706062157f9561b1ff07fe924a9528"),TorusNodePub(_X: "fd2af691fe4289ffbcb30885737a34d8f3f1113cbf71d48968da84cab7d0c262", _Y: "c37097edc6d6323142e0f310f0c2fb33766dbe10d07693d73d5d490c1891b8dc"),TorusNodePub(_X: "e078195f5fd6f58977531135317a0f8d3af6d3b893be9762f433686f782bec58", _Y: "843f87df076c26bf5d4d66120770a0aecf0f5667d38aa1ec518383d50fa0fb88"),TorusNodePub(_X: "a127de58df2e7a612fd256c42b57bb311ce41fd5d0ab58e6426fbf82c72e742f", _Y: "388842e57a4df814daef7dceb2065543dd5727f0ee7b40d527f36f905013fa96")] - let verifierId = "shubham@tor.us" - let verifier = "google-google" - let token = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImMxNzcxODE0YmE2YTcwNjkzZmI5NDEyZGEzYzZlOTBjMmJmNWI5MjciLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiIyMzg5NDE3NDY3MTMtcXFlNGE3cmR1dWsyNTZkOG9pNWwwcTM0cXR1OWdwZmcuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIyMzg5NDE3NDY3MTMtcXFlNGE3cmR1dWsyNTZkOG9pNWwwcTM0cXR1OWdwZmcuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDk1ODQzNTA5MTA3Mjc0NzAzNDkiLCJoZCI6InRvci51cyIsImVtYWlsIjoic2h1YmhhbUB0b3IudXMiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXRfaGFzaCI6IjltMjRLWXhXWVJZbkRxSlphV0NmdVEiLCJub25jZSI6IjEyMyIsIm5hbWUiOiJTaHViaGFtIFJhdGhpIiwicGljdHVyZSI6Imh0dHBzOi8vbGg0Lmdvb2dsZXVzZXJjb250ZW50LmNvbS8tT19SUi1aYlQwZVUvQUFBQUFBQUFBQUkvQUFBQUFBQUFBQUEvQU1adXVjazdCR2hkRkhZdEtfQVN6T01wZlpTSWVHU2NmZy9zOTYtYy9waG90by5qcGciLCJnaXZlbl9uYW1lIjoiU2h1YmhhbSIsImZhbWlseV9uYW1lIjoiUmF0aGkiLCJsb2NhbGUiOiJlbiIsImlhdCI6MTU4OTg4NTk0NCwiZXhwIjoxNTg5ODg5NTQ0LCJqdGkiOiI3N2MxMmE3YjM4NzIxNDk3MGVkZmU4ZjE1N2JmZWNlNzk4ODI2MDZiIn0.X7zcizaLeSNA8H1Wli_UIvvS9XRrlKsN42QOgNi4AxUGrQNVfECvFP8TeXeY0iDkZ9rfKCo-M9UTg0DDxPV2epyDD_Y6TphvfKUz-dU5rMYB0i89eYYJNSX5fQZXzn6K_ANe1XSdjvnHWxoYHUdGtzxxb98XqeP4OWGUD23hhwovOhD_d1NXuXEVeckq3FFXpt218lTOllbK2sEKb_bO0U7WNiJTGg983MnYDiWmnAeAB63HKJyZvAGy2gfoCJWCNV2_GqmcNDChHdSqAS8Ypola_HkJTIBZuh5OneOhhGi2CFtMFyQ5h-rsomLcW3Tui5qtzl-yQK_9Gqe2c_vfRw" - - let verifyParams = [["GOOGLE_CLIENT_ID": "238941746713-qqe4a7rduuk256d8oi5l0q34qtu9gpfg.apps.googleusercontent.com", - "typeOfLogin": "google", - "verifier": "google-shubs",]] - - override class func setUp() { - super.setUp() -// let fnd = FetchNodeDetails() -// let nodeDetails = fnd.getNodeDetails() -// let nodeEndpoints = nodeDetails.getTorusNodeEndpoints() -// let nodePubkeys = nodeDetails.getTorusNodePub() - } - - func testKeyLookup() { - let obj = TorusUtils() - - let exp1 = XCTestExpectation(description: "Do keylookup with success") - let keyLookupSuccess = obj.keyLookup(endpoints: nodeList, verifier: self.verifier, verifierId: self.verifierId) - keyLookupSuccess.done { data in - XCTAssert(data["address"]=="0x5533572d0b2b69Ae31bfDeA351B67B1C05F724Bc", "Address verified") - exp1.fulfill() - }.catch{err in - print(err) - XCTFail() - exp1.fulfill() - } - - let exp2 = XCTestExpectation(description: "Do keylookup with failure") - let keyLookupFailure = obj.keyLookup(endpoints: nodeList, verifier: self.verifier, verifierId: self.verifierId + "someRandomString") - keyLookupFailure.done { data in - XCTAssert(data["err"]=="keyLookupfailed", "error verified") - exp2.fulfill() - }.catch{err in - print("keylookup failed", err) - XCTFail() - exp2.fulfill() - } - - wait(for: [exp1, exp2], timeout: 5) - } - - func testKeyAssign(){ - let exp1 = XCTestExpectation(description: "Do keyAssign success") - let obj = TorusUtils(nodePubKeys: nodePubKeys) - let keyAssign = obj.keyAssign(endpoints: self.nodeList, torusNodePubs: nodePubKeys, verifier: verifier, verifierId: self.verifierId) - keyAssign.done{ data in - // print(data) - XCTAssertNotNil(data) - exp1.fulfill() - }.catch{ err in - print("keyAssign failed", err) - XCTFail() - exp1.fulfill() - } - wait(for: [exp1], timeout: 5) - } - - func testGetPublicAddress(){ - let exp1 = XCTestExpectation(description: "testing get public address") - let obj = TorusUtils(nodePubKeys: nodePubKeys) - let getpublicaddress = obj.getPublicAddress(endpoints: self.nodeList, torusNodePubs: nodePubKeys, verifier: "google", verifierId: self.verifierId, isExtended: true) - getpublicaddress.done{ data in - print("data", data) - // Specific to address of shubham@tor.us. Change this to your public address for the above nodelist - XCTAssert(data["address"]=="0x5533572d0b2b69Ae31bfDeA351B67B1C05F724Bc", "Address verified") - exp1.fulfill() - }.catch{ err in - print("getpublicaddress failed", err) - XCTFail() - exp1.fulfill() - } - wait(for: [exp1], timeout: 10) - } - - func testRetreiveShares(){ - let exp1 = XCTestExpectation(description: "reterive privatekey") - let obj = TorusUtils(nodePubKeys: nodePubKeys) - - let extraParams = ["verifieridentifier": verifier, "verifier_id":verifierId, "sub_verifier_ids":["google-shubs"], "verify_params": [["verifier_id": verifierId, "idtoken": token]]] as [String : Any] - let extraParams2 = ["verifieridentifier": verifier, "verifier_id":verifierId] as [String : Any] - - let dataExample: Data = try! NSKeyedArchiver.archivedData(withRootObject: extraParams, requiringSecureCoding: false) - let dataExample2: Data = try! NSKeyedArchiver.archivedData(withRootObject: extraParams2, requiringSecureCoding: false) - - - let key = obj.retrieveShares(endpoints: self.nodeList, verifierIdentifier: verifier, verifierId: verifierId, idToken: token, extraParams: dataExample2) - - key.done{ data in - print("data", data) - XCTAssertEqual(64, data.count) - exp1.fulfill() - }.catch{err in - print("testRetreiveShares failed", err) - XCTFail() - exp1.fulfill() - } - - wait(for: [exp1], timeout: 10) - } - - // 8b288671081621975c9d4af918a15a5358a793c7bea4c066c37effe2f0c8d1ee unused private key - -// generateMetadataParams(message, privateKey) { -// const key = this.ec.keyFromPrivate(privateKey.toString('hex', 64)) -// const setData = { -// data: message, -// timestamp: new BN(Date.now()).toString(16), +// let context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN|SECP256K1_CONTEXT_VERIFY)) +// let nodeList = ["https://teal-15-1.torusnode.com/jrpc", "https://teal-15-3.torusnode.com/jrpc", "https://teal-15-4.torusnode.com/jrpc", "https://teal-15-5.torusnode.com/jrpc", "https://teal-15-2.torusnode.com/jrpc"] +// let nodePubKeys : Array = [TorusNodePub(_X: "4086d123bd8b370db29e84604cd54fa9f1aeb544dba1cc9ff7c856f41b5bf269", _Y: "fde2ac475d8d2796aab2dea7426bc57571c26acad4f141463c036c9df3a8b8e8"),TorusNodePub(_X: "1d6ae1e674fdc1849e8d6dacf193daa97c5d484251aa9f82ff740f8277ee8b7d", _Y: "43095ae6101b2e04fa187e3a3eb7fbe1de706062157f9561b1ff07fe924a9528"),TorusNodePub(_X: "fd2af691fe4289ffbcb30885737a34d8f3f1113cbf71d48968da84cab7d0c262", _Y: "c37097edc6d6323142e0f310f0c2fb33766dbe10d07693d73d5d490c1891b8dc"),TorusNodePub(_X: "e078195f5fd6f58977531135317a0f8d3af6d3b893be9762f433686f782bec58", _Y: "843f87df076c26bf5d4d66120770a0aecf0f5667d38aa1ec518383d50fa0fb88"),TorusNodePub(_X: "a127de58df2e7a612fd256c42b57bb311ce41fd5d0ab58e6426fbf82c72e742f", _Y: "388842e57a4df814daef7dceb2065543dd5727f0ee7b40d527f36f905013fa96")] +// let verifierId = "shubham@tor.us" +// let verifier = "google-google" +// let token = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImMxNzcxODE0YmE2YTcwNjkzZmI5NDEyZGEzYzZlOTBjMmJmNWI5MjciLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiIyMzg5NDE3NDY3MTMtcXFlNGE3cmR1dWsyNTZkOG9pNWwwcTM0cXR1OWdwZmcuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIyMzg5NDE3NDY3MTMtcXFlNGE3cmR1dWsyNTZkOG9pNWwwcTM0cXR1OWdwZmcuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDk1ODQzNTA5MTA3Mjc0NzAzNDkiLCJoZCI6InRvci51cyIsImVtYWlsIjoic2h1YmhhbUB0b3IudXMiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXRfaGFzaCI6IjltMjRLWXhXWVJZbkRxSlphV0NmdVEiLCJub25jZSI6IjEyMyIsIm5hbWUiOiJTaHViaGFtIFJhdGhpIiwicGljdHVyZSI6Imh0dHBzOi8vbGg0Lmdvb2dsZXVzZXJjb250ZW50LmNvbS8tT19SUi1aYlQwZVUvQUFBQUFBQUFBQUkvQUFBQUFBQUFBQUEvQU1adXVjazdCR2hkRkhZdEtfQVN6T01wZlpTSWVHU2NmZy9zOTYtYy9waG90by5qcGciLCJnaXZlbl9uYW1lIjoiU2h1YmhhbSIsImZhbWlseV9uYW1lIjoiUmF0aGkiLCJsb2NhbGUiOiJlbiIsImlhdCI6MTU4OTg4NTk0NCwiZXhwIjoxNTg5ODg5NTQ0LCJqdGkiOiI3N2MxMmE3YjM4NzIxNDk3MGVkZmU4ZjE1N2JmZWNlNzk4ODI2MDZiIn0.X7zcizaLeSNA8H1Wli_UIvvS9XRrlKsN42QOgNi4AxUGrQNVfECvFP8TeXeY0iDkZ9rfKCo-M9UTg0DDxPV2epyDD_Y6TphvfKUz-dU5rMYB0i89eYYJNSX5fQZXzn6K_ANe1XSdjvnHWxoYHUdGtzxxb98XqeP4OWGUD23hhwovOhD_d1NXuXEVeckq3FFXpt218lTOllbK2sEKb_bO0U7WNiJTGg983MnYDiWmnAeAB63HKJyZvAGy2gfoCJWCNV2_GqmcNDChHdSqAS8Ypola_HkJTIBZuh5OneOhhGi2CFtMFyQ5h-rsomLcW3Tui5qtzl-yQK_9Gqe2c_vfRw" +// +// let verifyParams = [["GOOGLE_CLIENT_ID": "238941746713-qqe4a7rduuk256d8oi5l0q34qtu9gpfg.apps.googleusercontent.com", +// "typeOfLogin": "google", +// "verifier": "google-shubs",]] +// +// override class func setUp() { +// super.setUp() +//// let fnd = FetchNodeDetails() +//// let nodeDetails = fnd.getNodeDetails() +//// let nodeEndpoints = nodeDetails.getTorusNodeEndpoints() +//// let nodePubkeys = nodeDetails.getTorusNodePub() +// } +// +// func testKeyLookup() { +// let obj = TorusUtils() +// +// let exp1 = XCTestExpectation(description: "Do keylookup with success") +// let keyLookupSuccess = obj.keyLookup(endpoints: nodeList, verifier: self.verifier, verifierId: self.verifierId) +// keyLookupSuccess.done { data in +// XCTAssert(data["address"]=="0x5533572d0b2b69Ae31bfDeA351B67B1C05F724Bc", "Address verified") +// exp1.fulfill() +// }.catch{err in +// print(err) +// XCTFail() +// exp1.fulfill() // } -// const sig = key.sign(keccak256(JSON.stringify(setData)).slice(2)) -// return { -// pub_key_X: key.getPublic().getX().toString('hex'), -// pub_key_Y: key.getPublic().getY().toString('hex'), -// set_data: setData, -// signature: Buffer.from(sig.r.toString(16, 64) + sig.s.toString(16, 64) + new BN(sig.v).toString(16, 2), 'hex').toString('base64'), +// +// let exp2 = XCTestExpectation(description: "Do keylookup with failure") +// let keyLookupFailure = obj.keyLookup(endpoints: nodeList, verifier: self.verifier, verifierId: self.verifierId + "someRandomString") +// keyLookupFailure.done { data in +// XCTAssert(data["err"]=="keyLookupfailed", "error verified") +// exp2.fulfill() +// }.catch{err in +// print("keylookup failed", err) +// XCTFail() +// exp2.fulfill() // } +// +// wait(for: [exp1, exp2], timeout: 5) // } - - func testSetMetadata(){ - - let keystore = try! EthereumKeystoreV3(privateKey: Data(hex: "8b288671081621975c9d4af918a15a5358a793c7bea4c066c37effe2f0c8d1ee")) - let setData = [ - "data": "8", - "timestamp": String(Int(Date().timeIntervalSince1970)) - ] - // print(try! JSONSerialization.data(withJSONObject: setData, options: [])) - let setDataString = try! JSONSerialization.data(withJSONObject: setData, options: []) - let hash = setDataString.sha3(.keccak256) - let sign = SECP256K1.signForRecovery(hash: hash, privateKey: Data(hex: "8b288671081621975c9d4af918a15a5358a793c7bea4c066c37effe2f0c8d1ee")) - let unmarshallSig = SECP256K1.unmarshalSignature(signatureData: sign.serializedSignature!)! - print(String(data: unmarshallSig.r, encoding: .utf8)) - - let newData = [ - "pub_key_X": "83ebc5515a6f3ad8d1d83c53b324afb7f88edc499e3bdbbd149492e460018292", - "pub_key_Y": "a0de020d476f558d69e0b54ce83277df5f6305dbe065e337be313a51ad397958", - "set_data": setData, - "signature": "SECP256K1.unmarshalSignature(signatureData: sign)" - ] as [String : Any] - - } - - func testSECPLib(){ - let secp256k1N = BigInt("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", radix: 16)!; - - - let privkey1 = "60a9a56b271e94cc2e8b52107fcb7c4698e7e2d0a4525a797dbe2330a074fdf6" - let privkey2 = "f730f0a92f8d2b97bc7a1937afad3d2bb47f41418d697de8001797472225ee94" - let privkey1Data = Data(hex: privkey1) - let privkey2Data = Data(hex: privkey2) - let publicKey1 = SECP256K1.privateToPublic(privateKey: privkey1Data, compressed: false) - let publicKey2 = SECP256K1.privateToPublic(privateKey: privkey2Data, compressed: false) - var keys: [Data] = [] - - keys.append(publicKey2!) - keys.append(publicKey1!) - - let added = SECP256K1.combineSerializedPublicKeys(keys: keys) - print(publicKey1?.toHexString(), publicKey2?.toHexString(), added?.toHexString()) - - let bigInt1 = BigInt(privkey1, radix: 16)! - let bigInt2 = BigInt(privkey2, radix: 16)! - let addedKeys = bigInt1 + bigInt2 - let mod = BigUInt(addedKeys.modulus(secp256k1N)) - let modData = mod.serialize() - let publickey3 = SECP256K1.privateToPublic(privateKey: modData, compressed: false) - - print(publickey3?.toHexString()) - - } - - var allTests = [ - ("testKeyLookup", testKeyLookup), - ("testKeyAssign", testKeyAssign), - ("testGetPublicAddress", testGetPublicAddress), - ("testRetreiveShares", testRetreiveShares) - ] +// +// func testKeyAssign(){ +// let exp1 = XCTestExpectation(description: "Do keyAssign success") +// let obj = TorusUtils(nodePubKeys: nodePubKeys) +// let keyAssign = obj.keyAssign(endpoints: self.nodeList, torusNodePubs: nodePubKeys, verifier: verifier, verifierId: self.verifierId) +// keyAssign.done{ data in +// // print(data) +// XCTAssertNotNil(data) +// exp1.fulfill() +// }.catch{ err in +// print("keyAssign failed", err) +// XCTFail() +// exp1.fulfill() +// } +// wait(for: [exp1], timeout: 5) +// } +// +// func testGetPublicAddress(){ +// let exp1 = XCTestExpectation(description: "testing get public address") +// let obj = TorusUtils(nodePubKeys: nodePubKeys) +// let getpublicaddress = obj.getPublicAddress(endpoints: self.nodeList, torusNodePubs: nodePubKeys, verifier: "google", verifierId: self.verifierId, isExtended: true) +// getpublicaddress.done{ data in +// print("data", data) +// // Specific to address of shubham@tor.us. Change this to your public address for the above nodelist +// XCTAssert(data["address"]=="0x5533572d0b2b69Ae31bfDeA351B67B1C05F724Bc", "Address verified") +// exp1.fulfill() +// }.catch{ err in +// print("getpublicaddress failed", err) +// XCTFail() +// exp1.fulfill() +// } +// wait(for: [exp1], timeout: 10) +// } +// +// func testRetreiveShares(){ +// let exp1 = XCTestExpectation(description: "reterive privatekey") +// let obj = TorusUtils(nodePubKeys: nodePubKeys) +// +// let extraParams = ["verifieridentifier": verifier, "verifier_id":verifierId, "sub_verifier_ids":["google-shubs"], "verify_params": [["verifier_id": verifierId, "idtoken": token]]] as [String : Any] +// let extraParams2 = ["verifieridentifier": verifier, "verifier_id":verifierId] as [String : Any] +// +// let dataExample: Data = try! NSKeyedArchiver.archivedData(withRootObject: extraParams, requiringSecureCoding: false) +// let dataExample2: Data = try! NSKeyedArchiver.archivedData(withRootObject: extraParams2, requiringSecureCoding: false) +// +// +// let key = obj.retrieveShares(endpoints: self.nodeList, verifierIdentifier: verifier, verifierId: verifierId, idToken: token, extraParams: dataExample2) +// +// key.done{ data in +// print("data", data) +// XCTAssertEqual(64, data.count) +// exp1.fulfill() +// }.catch{err in +// print("testRetreiveShares failed", err) +// XCTFail() +// exp1.fulfill() +// } +// +// wait(for: [exp1], timeout: 10) +// } +// +// // 8b288671081621975c9d4af918a15a5358a793c7bea4c066c37effe2f0c8d1ee unused private key +// +//// generateMetadataParams(message, privateKey) { +//// const key = this.ec.keyFromPrivate(privateKey.toString('hex', 64)) +//// const setData = { +//// data: message, +//// timestamp: new BN(Date.now()).toString(16), +//// } +//// const sig = key.sign(keccak256(JSON.stringify(setData)).slice(2)) +//// return { +//// pub_key_X: key.getPublic().getX().toString('hex'), +//// pub_key_Y: key.getPublic().getY().toString('hex'), +//// set_data: setData, +//// signature: Buffer.from(sig.r.toString(16, 64) + sig.s.toString(16, 64) + new BN(sig.v).toString(16, 2), 'hex').toString('base64'), +//// } +//// } +// +// func testSetMetadata(){ +// +// let keystore = try! EthereumKeystoreV3(privateKey: Data(hex: "8b288671081621975c9d4af918a15a5358a793c7bea4c066c37effe2f0c8d1ee")) +// let setData = [ +// "data": "8", +// "timestamp": String(Int(Date().timeIntervalSince1970)) +// ] +// // print(try! JSONSerialization.data(withJSONObject: setData, options: [])) +// let setDataString = try! JSONSerialization.data(withJSONObject: setData, options: []) +// let hash = setDataString.sha3(.keccak256) +// let sign = SECP256K1.signForRecovery(hash: hash, privateKey: Data(hex: "8b288671081621975c9d4af918a15a5358a793c7bea4c066c37effe2f0c8d1ee")) +// let unmarshallSig = SECP256K1.unmarshalSignature(signatureData: sign.serializedSignature!)! +// print(String(data: unmarshallSig.r, encoding: .utf8)) +// +// let newData = [ +// "pub_key_X": "83ebc5515a6f3ad8d1d83c53b324afb7f88edc499e3bdbbd149492e460018292", +// "pub_key_Y": "a0de020d476f558d69e0b54ce83277df5f6305dbe065e337be313a51ad397958", +// "set_data": setData, +// "signature": "SECP256K1.unmarshalSignature(signatureData: sign)" +// ] as [String : Any] +// +// } +// +// func testSECPLib(){ +// let secp256k1N = BigInt("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", radix: 16)!; +// +// +// let privkey1 = "60a9a56b271e94cc2e8b52107fcb7c4698e7e2d0a4525a797dbe2330a074fdf6" +// let privkey2 = "f730f0a92f8d2b97bc7a1937afad3d2bb47f41418d697de8001797472225ee94" +// let privkey1Data = Data(hex: privkey1) +// let privkey2Data = Data(hex: privkey2) +// let publicKey1 = SECP256K1.privateToPublic(privateKey: privkey1Data, compressed: false) +// let publicKey2 = SECP256K1.privateToPublic(privateKey: privkey2Data, compressed: false) +// var keys: [Data] = [] +// +// keys.append(publicKey2!) +// keys.append(publicKey1!) +// +// let added = SECP256K1.combineSerializedPublicKeys(keys: keys) +// print(publicKey1?.toHexString(), publicKey2?.toHexString(), added?.toHexString()) +// +// let bigInt1 = BigInt(privkey1, radix: 16)! +// let bigInt2 = BigInt(privkey2, radix: 16)! +// let addedKeys = bigInt1 + bigInt2 +// let mod = BigUInt(addedKeys.modulus(secp256k1N)) +// let modData = mod.serialize() +// let publickey3 = SECP256K1.privateToPublic(privateKey: modData, compressed: false) +// +// print(publickey3?.toHexString()) +// +// } +// +// var allTests = [ +// ("testKeyLookup", testKeyLookup), +// ("testKeyAssign", testKeyAssign), +// ("testGetPublicAddress", testGetPublicAddress), +// ("testRetreiveShares", testRetreiveShares) +// ] } diff --git a/Torus-utils.podspec b/Torus-utils.podspec index a8c466db..0bf0b908 100644 --- a/Torus-utils.podspec +++ b/Torus-utils.podspec @@ -1,7 +1,7 @@ Pod::Spec.new do |spec| spec.name = "Torus-utils" - spec.version = "0.1.4" - spec.platform = :ios, "10.0" + spec.version = "1.0.0" + spec.platform = :ios, "11.0" spec.summary = "Retrieve user shares" spec.homepage = "https://github.com/torusresearch/torus-utils-swift" spec.license = { :type => 'BSD', :file => 'License.md' } @@ -10,7 +10,9 @@ Pod::Spec.new do |spec| spec.module_name = "TorusUtils" spec.source = { :git => "https://github.com/torusresearch/torus-utils-swift.git", :tag => spec.version } spec.source_files = "Sources/TorusUtils/*.{swift,json}","Sources/TorusUtils/**/*.{swift,json}" - spec.dependency 'Torus-fetchNodeDetails', '~> 0.0.1' + spec.dependency 'Torus-fetchNodeDetails', '~> 1.0.0' + spec.dependency 'CryptoSwift', '~> 1.4.1' + spec.dependency 'secp256k1.swift', '~> 0.1.4' spec.dependency 'PromiseKit/Foundation', '~> 6.0' spec.dependency 'BestLogger', '~> 0.0.1' spec.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' } diff --git a/cocoapods/Podfile b/cocoapods/Podfile index c2076fcc..04f607aa 100644 --- a/cocoapods/Podfile +++ b/cocoapods/Podfile @@ -1,14 +1,12 @@ # Uncomment the next line to define a global platform for your project - platform :ios, '10.0' - + platform :ios, '11.0' target 'TestApplication' do - # Comment the next line if you don't want to use dynamic frameworks use_frameworks! - # pod 'Torus-fetchNodeDetails', :git=>'https://github.com/torusresearch/fetch-node-details-swift' + +# pod 'Torus-fetchNodeDetails', :git=>'https://github.com/torusresearch/fetch-node-details-swift' pod "Torus-utils", :path => '../' # Pods for TestApplication - target 'TestApplicationTests' do # Pods for testing end diff --git a/cocoapods/Podfile.lock b/cocoapods/Podfile.lock index 6078c5d6..7187f565 100644 --- a/cocoapods/Podfile.lock +++ b/cocoapods/Podfile.lock @@ -1,31 +1,26 @@ PODS: - BestLogger (0.0.3) - - 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): + - BigInt (5.0.0) + - CryptoSwift (1.4.1) + - GenericJSON (2.0.1) + - PromiseKit/CorePromise (6.15.3) + - PromiseKit/Foundation (6.15.3): - PromiseKit/CorePromise - - PromiseKit/UIKit (6.8.5): - - PromiseKit/CorePromise - - secp256k1.c (0.1.2) - - Starscream (3.1.1) - - Torus-fetchNodeDetails (0.0.20): + - secp256k1.swift (0.1.4) + - Torus-fetchNodeDetails (1.0.0): - BestLogger (~> 0.0.1) - - web3swift (~> 2.3.0) - - Torus-utils (0.1.1): + - PromiseKit/Foundation (~> 6.0) + - web3.swift (~> 0.8.0) + - Torus-utils (1.0.0): - BestLogger (~> 0.0.1) + - CryptoSwift (~> 1.4.1) - PromiseKit/Foundation (~> 6.0) - - Torus-fetchNodeDetails (~> 0.0.1) - - web3swift (2.3.0): - - BigInt (~> 4.0) - - CryptoSwift (~> 1.0.0) - - PromiseKit (~> 6.8.4) - - secp256k1.c (~> 0.1) - - Starscream (~> 3.1.0) + - secp256k1.swift (~> 0.1.4) + - Torus-fetchNodeDetails (~> 1.0.0) + - web3.swift (0.8.1): + - BigInt (~> 5.0.0) + - GenericJSON (~> 2.0) + - secp256k1.swift (~> 0.1) DEPENDENCIES: - Torus-utils (from `../`) @@ -35,11 +30,11 @@ SPEC REPOS: - BestLogger - BigInt - CryptoSwift + - GenericJSON - PromiseKit - - secp256k1.c - - Starscream + - secp256k1.swift - Torus-fetchNodeDetails - - web3swift + - web3.swift EXTERNAL SOURCES: Torus-utils: @@ -47,15 +42,15 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: BestLogger: 70475db073dfab3ec1ba9b58b0bb78126b068eee - BigInt: 2aad1a9942dc932ec8b84290d2c564a3d76f97ab - CryptoSwift: d81eeaa59dc5a8d03720fe919a6fd07b51f7439f - PromiseKit: 9616b0afef31eae56ab9ce044c8ec2b8612a15cd - secp256k1.c: db47b726585d80f027423682eb369729e61b3b20 - Starscream: 4bb2f9942274833f7b4d296a55504dcfc7edb7b0 - Torus-fetchNodeDetails: 567d0c73c1b318c8811abcef0b2f31cfdcd5a4a4 - Torus-utils: cd8ac44a3397d1dac0132ca414478f9dd55a8825 - web3swift: 0f097eafe1d08f478694b882581b85a01afb6633 + BigInt: 74b4d88367b0e819d9f77393549226d36faeb0d8 + CryptoSwift: 0bc800a7e6a24c4fc9ebeab97d44b0d5f73a78bd + GenericJSON: a6e74e2c457f8693caab08e0eafde7d97e6666de + PromiseKit: 3b2b6995e51a954c46dbc550ce3da44fbfb563c5 + secp256k1.swift: a7e7a214f6db6ce5db32cc6b2b45e5c4dd633634 + Torus-fetchNodeDetails: 03827b5d6481ffd52bfae26cce97fcb7964bd23e + Torus-utils: f18ee7f2556cad65c9e4f511eac05a82cc9c7708 + web3.swift: ce00a5e6e39fb184e33e3622e8be22ae53205e57 -PODFILE CHECKSUM: de6dc705fbcaee4478a78e83fe706aec34cc08c1 +PODFILE CHECKSUM: 2f38241f146b211ba5492f621b56eb48a9318a55 COCOAPODS: 1.10.1 diff --git a/cocoapods/Pods/BestLogger/License.md b/cocoapods/Pods/BestLogger/License.md deleted file mode 100644 index 1b39e537..00000000 --- a/cocoapods/Pods/BestLogger/License.md +++ /dev/null @@ -1,7 +0,0 @@ -Copyright 2020 Shubham Rathi - -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/cocoapods/Pods/BestLogger/README.md b/cocoapods/Pods/BestLogger/README.md deleted file mode 100644 index 639f2e83..00000000 --- a/cocoapods/Pods/BestLogger/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# BestLogger - -**THE REASON ITS CALLED BEST LOGGER IS BECAUSE EASYLOGGER WAS TAKEN AND SUBDEPENDECIES MIGHT HAVE LOGGER ALREADY DECLARED** - -This is a very simple, one file, swift logger which supports multiple arguments. - -We support 6 logging levels -* .trace = 0 // should be used for application flow. e.g., viewdidload executed -* .debug // used for debugging -* .info // used for informative messages. e.g., application started from app delegate -* .warning // e.g., this method could lead to memory leaks -* .error // e.g., JSONDecoder() failed to while casting -* .none // Abosolutely no logs. logger.none() doesn't exist. - -## Usage - -```swift -import BestLogger -let logger = BestLogger(label: "TestLogger", level: .debug) // .trace = 0, .debug, .info, .warning, .error, .none - -logger.debug("this is the best swift logger :P") // will print -logger.warning("Fix me:") // will print -logger.trace("application started") // will not print -``` - -## Development - -* Add static method to be used across different classes -* Make a PR for any improvements -* Contact - Shubham Rathi (twitter @metallicalfa) diff --git a/cocoapods/Pods/BestLogger/Sources/BestLogger/BestLogger.swift b/cocoapods/Pods/BestLogger/Sources/BestLogger/BestLogger.swift deleted file mode 100644 index 4bf2150a..00000000 --- a/cocoapods/Pods/BestLogger/Sources/BestLogger/BestLogger.swift +++ /dev/null @@ -1,149 +0,0 @@ -// -// BestLogger.swift -// -// Author - Shubham Rathi 15/06/2020 - -import Foundation - -/// A `Logger` is the a struc in `BestLogger`. You can use its method to print various variables depending on set `logLevel` -/// corresponding to a log level. -/// -/// The most basic usage of a `BestLogger` is -/// -/// logger.info("Hello World!") -/// - -public struct BestLogger{ - - /// Logger identifier - public let label: String - - /// Log level identifier - public var logLevel: Level - - /// Construct a `BestLogger` given a `label` and level `logLevel` - /// - /// The `label` should identify the creator of the `Logger`. This can be an application, a sub-system, or even - /// a datatype. - /// - /// - parameters: - /// - label: An identifier for the creator of a `Logger`. - /// - logLevel: A Identifier for log level - public init(label: String, level: Level) { - self.label = label - self.logLevel = level - } - - /// The log level. - /// - /// Log levels are ordered by their severity, with `.trace` being the least severe and - /// `.none` being nothing. - public enum Level: Int, Comparable { - case trace = 0 - case debug - case info - case warning - case error - case none - - public static func < (a: Level, b: Level) -> Bool { - return a.rawValue < b.rawValue - } - } - -} - -extension BestLogger{ - /// Log a message passing with the `Logger.Level.trace` log level. - /// - /// will be logged if `.trace` is at least as severe as the `Logger`'s `logLevel` - /// - /// - parameters: - /// - message: The message to be logged, pass multiple vairables to be logged. e.g, .trace(1,2,3) - /// - metadata: One-off metadata to attach to this log message - /// - file: The file this log message originates from - /// - function: The function this log message originates from - /// - line: The line this log message originates from - @inlinable - public func trace(_ message: Any..., file: String = #file, function: String = #function, line: UInt = #line) { - if self.logLevel <= .trace{ - print("[TRACE] \((file as NSString).lastPathComponent) [\(line)]:", terminator: " ") - _ = message.map{ return print($0, terminator: " ")} - print("\n") - } - } - - - /// Log a message passing with the `Logger.Level.debug` log level. - /// - /// will be logged if `.debug` is at least as severe as the `Logger`'s `logLevel` - /// - /// - parameters: - /// - message: The message to be logged, pass multiple vairables to be logged. e.g, .debug(1,2,3) - /// - metadata: One-off metadata to attach to this log message - /// - file: The file this log message originates from - /// - function: The function this log message originates from - /// - line: The line this log message originates from - public func debug(_ message: Any..., file: String = #file, function: String = #function, line: UInt = #line) { - if self.logLevel <= .debug{ - print("[DEBUG] \((file as NSString).lastPathComponent) [\(line)]:", terminator: " ") - _ = message.map{ print($0, terminator: " ")} - print("\n") - } - } - - /// Log a message passing with the `Logger.Level.info` log level. - /// - /// will be logged if `.info` is at least as severe as the `Logger`'s `logLevel` - /// - /// - parameters: - /// - message: The message to be logged, pass multiple vairables to be logged. e.g, .info(1,2,3) - /// - metadata: One-off metadata to attach to this log message - /// - file: The file this log message originates from - /// - function: The function this log message originates from - /// - line: The line this log message originates from - public func info(_ message: Any..., file: String = #file, function: String = #function, line: UInt = #line) { - if self.logLevel <= .info{ - print("[INFO] \((file as NSString).lastPathComponent) [\(line)]:", terminator: " ") - _ = message.map{ print($0, terminator: " ")} - print("\n") - } - } - - /// Log a message passing with the `Logger.Level.warning` log level. - /// - /// will be logged if `.warning` is at least as severe as the `Logger`'s `logLevel` - /// - /// - parameters: - /// - message: The message to be logged, pass multiple vairables to be logged. e.g, .trace(1,2,3) - /// - metadata: One-off metadata to attach to this log message - /// - file: The file this log message originates from - /// - function: The function this log message originates from - /// - line: The line this log message originates from - public func warning(_ message: Any..., file: String = #file, function: String = #function, line: UInt = #line) { - if self.logLevel <= .warning{ - print("[WARNING] \((file as NSString).lastPathComponent) [\(line)]:", terminator: " ") - _ = message.map{ print($0, terminator: " ")} - print("\n") - } - } - - /// Log a message passing with the `Logger.Level.error` log level. - /// - /// will be logged if `.error` is at least as severe as the `Logger`'s `logLevel` - /// - /// - parameters: - /// - message: The message to be logged, pass multiple vairables to be logged. e.g, .error(1,2,3) - /// - metadata: One-off metadata to attach to this log message - /// - file: The file this log message originates from - /// - function: The function this log message originates from - /// - line: The line this log message originates from - public func error(_ message: Any..., file: String = #file, function: String = #function, line: UInt = #line) { - if self.logLevel <= .error{ - print("[ERROR] \((file as NSString).lastPathComponent) [\(line)]:", terminator: " ") - _ = message.map{ print($0, terminator: " ")} - print("\n") - } - } - -} diff --git a/cocoapods/Pods/BigInt/LICENSE.md b/cocoapods/Pods/BigInt/LICENSE.md deleted file mode 100644 index 18cefd11..00000000 --- a/cocoapods/Pods/BigInt/LICENSE.md +++ /dev/null @@ -1,20 +0,0 @@ - -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/cocoapods/Pods/BigInt/README.md b/cocoapods/Pods/BigInt/README.md deleted file mode 100644 index e65483bb..00000000 --- a/cocoapods/Pods/BigInt/README.md +++ /dev/null @@ -1,440 +0,0 @@ -[![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/cocoapods/Pods/BigInt/Sources/Addition.swift b/cocoapods/Pods/BigInt/Sources/Addition.swift deleted file mode 100644 index 34f4d44e..00000000 --- a/cocoapods/Pods/BigInt/Sources/Addition.swift +++ /dev/null @@ -1,126 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/BigInt.swift b/cocoapods/Pods/BigInt/Sources/BigInt.swift deleted file mode 100644 index 11318ffc..00000000 --- a/cocoapods/Pods/BigInt/Sources/BigInt.swift +++ /dev/null @@ -1,74 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/BigUInt.swift b/cocoapods/Pods/BigInt/Sources/BigUInt.swift deleted file mode 100644 index 81aa9a83..00000000 --- a/cocoapods/Pods/BigInt/Sources/BigUInt.swift +++ /dev/null @@ -1,386 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Bitwise Ops.swift b/cocoapods/Pods/BigInt/Sources/Bitwise Ops.swift deleted file mode 100644 index 0d00148b..00000000 --- a/cocoapods/Pods/BigInt/Sources/Bitwise Ops.swift +++ /dev/null @@ -1,121 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Codable.swift b/cocoapods/Pods/BigInt/Sources/Codable.swift deleted file mode 100644 index b53b30be..00000000 --- a/cocoapods/Pods/BigInt/Sources/Codable.swift +++ /dev/null @@ -1,155 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Comparable.swift b/cocoapods/Pods/BigInt/Sources/Comparable.swift deleted file mode 100644 index d9ab87e7..00000000 --- a/cocoapods/Pods/BigInt/Sources/Comparable.swift +++ /dev/null @@ -1,63 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Data Conversion.swift b/cocoapods/Pods/BigInt/Sources/Data Conversion.swift deleted file mode 100644 index ffc0ac20..00000000 --- a/cocoapods/Pods/BigInt/Sources/Data Conversion.swift +++ /dev/null @@ -1,107 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Division.swift b/cocoapods/Pods/BigInt/Sources/Division.swift deleted file mode 100644 index 4393f52e..00000000 --- a/cocoapods/Pods/BigInt/Sources/Division.swift +++ /dev/null @@ -1,374 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Exponentiation.swift b/cocoapods/Pods/BigInt/Sources/Exponentiation.swift deleted file mode 100644 index 9d7ee85d..00000000 --- a/cocoapods/Pods/BigInt/Sources/Exponentiation.swift +++ /dev/null @@ -1,119 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Floating Point Conversion.swift b/cocoapods/Pods/BigInt/Sources/Floating Point Conversion.swift deleted file mode 100644 index 6c2395a3..00000000 --- a/cocoapods/Pods/BigInt/Sources/Floating Point Conversion.swift +++ /dev/null @@ -1,73 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/GCD.swift b/cocoapods/Pods/BigInt/Sources/GCD.swift deleted file mode 100644 index d55605dc..00000000 --- a/cocoapods/Pods/BigInt/Sources/GCD.swift +++ /dev/null @@ -1,80 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Hashable.swift b/cocoapods/Pods/BigInt/Sources/Hashable.swift deleted file mode 100644 index c5dc0e64..00000000 --- a/cocoapods/Pods/BigInt/Sources/Hashable.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Integer Conversion.swift b/cocoapods/Pods/BigInt/Sources/Integer Conversion.swift deleted file mode 100644 index 9a210e4a..00000000 --- a/cocoapods/Pods/BigInt/Sources/Integer Conversion.swift +++ /dev/null @@ -1,89 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Multiplication.swift b/cocoapods/Pods/BigInt/Sources/Multiplication.swift deleted file mode 100644 index 635c36a5..00000000 --- a/cocoapods/Pods/BigInt/Sources/Multiplication.swift +++ /dev/null @@ -1,165 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Prime Test.swift b/cocoapods/Pods/BigInt/Sources/Prime Test.swift deleted file mode 100644 index 7f187110..00000000 --- a/cocoapods/Pods/BigInt/Sources/Prime Test.swift +++ /dev/null @@ -1,153 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Random.swift b/cocoapods/Pods/BigInt/Sources/Random.swift deleted file mode 100644 index 5813b4bd..00000000 --- a/cocoapods/Pods/BigInt/Sources/Random.swift +++ /dev/null @@ -1,71 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Shifts.swift b/cocoapods/Pods/BigInt/Sources/Shifts.swift deleted file mode 100644 index e676e414..00000000 --- a/cocoapods/Pods/BigInt/Sources/Shifts.swift +++ /dev/null @@ -1,211 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Square Root.swift b/cocoapods/Pods/BigInt/Sources/Square Root.swift deleted file mode 100644 index 68db0691..00000000 --- a/cocoapods/Pods/BigInt/Sources/Square Root.swift +++ /dev/null @@ -1,41 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Strideable.swift b/cocoapods/Pods/BigInt/Sources/Strideable.swift deleted file mode 100644 index 2b79babd..00000000 --- a/cocoapods/Pods/BigInt/Sources/Strideable.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/String Conversion.swift b/cocoapods/Pods/BigInt/Sources/String Conversion.swift deleted file mode 100644 index d6f340c9..00000000 --- a/cocoapods/Pods/BigInt/Sources/String Conversion.swift +++ /dev/null @@ -1,236 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Subtraction.swift b/cocoapods/Pods/BigInt/Sources/Subtraction.swift deleted file mode 100644 index 5ac872e6..00000000 --- a/cocoapods/Pods/BigInt/Sources/Subtraction.swift +++ /dev/null @@ -1,169 +0,0 @@ -// -// 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/cocoapods/Pods/BigInt/Sources/Words and Bits.swift b/cocoapods/Pods/BigInt/Sources/Words and Bits.swift deleted file mode 100644 index 040accdd..00000000 --- a/cocoapods/Pods/BigInt/Sources/Words and Bits.swift +++ /dev/null @@ -1,202 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/LICENSE b/cocoapods/Pods/CryptoSwift/LICENSE deleted file mode 100644 index b70d6de9..00000000 --- a/cocoapods/Pods/CryptoSwift/LICENSE +++ /dev/null @@ -1,11 +0,0 @@ -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/cocoapods/Pods/CryptoSwift/README.md b/cocoapods/Pods/CryptoSwift/README.md deleted file mode 100644 index a239407d..00000000 --- a/cocoapods/Pods/CryptoSwift/README.md +++ /dev/null @@ -1,527 +0,0 @@ -[![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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEAD.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEAD.swift deleted file mode 100644 index 67179c59..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEAD.swift +++ /dev/null @@ -1,40 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift deleted file mode 100644 index 791f9a44..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift +++ /dev/null @@ -1,59 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/AES.Cryptors.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/AES.Cryptors.swift deleted file mode 100644 index a461cd61..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/AES.Cryptors.swift +++ /dev/null @@ -1,35 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/AES.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/AES.swift deleted file mode 100644 index 631b7d51..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/AES.swift +++ /dev/null @@ -1,539 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Array+Extension.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Array+Extension.swift deleted file mode 100644 index 752dcb82..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Array+Extension.swift +++ /dev/null @@ -1,148 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Authenticator.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Authenticator.swift deleted file mode 100644 index 03215a64..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Authenticator.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift deleted file mode 100644 index 575bc1fc..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift +++ /dev/null @@ -1,63 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Bit.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Bit.swift deleted file mode 100644 index 2e9552ed..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Bit.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockCipher.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockCipher.swift deleted file mode 100644 index b3c1ffa9..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockCipher.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockDecryptor.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockDecryptor.swift deleted file mode 100644 index 7990a402..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockDecryptor.swift +++ /dev/null @@ -1,85 +0,0 @@ -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockEncryptor.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockEncryptor.swift deleted file mode 100644 index ba3fe281..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockEncryptor.swift +++ /dev/null @@ -1,57 +0,0 @@ -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockMode.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockMode.swift deleted file mode 100644 index b78e2746..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockMode.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockModeOptions.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockModeOptions.swift deleted file mode 100644 index 64618494..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/BlockModeOptions.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CBC.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CBC.swift deleted file mode 100644 index f98d9bf6..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CBC.swift +++ /dev/null @@ -1,70 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CCM.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CCM.swift deleted file mode 100644 index fb59ebe9..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CCM.swift +++ /dev/null @@ -1,359 +0,0 @@ -//// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CFB.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CFB.swift deleted file mode 100644 index 316283cb..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CFB.swift +++ /dev/null @@ -1,70 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift deleted file mode 100644 index 2dc6a9ec..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift +++ /dev/null @@ -1,134 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/ECB.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/ECB.swift deleted file mode 100644 index ce410b30..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/ECB.swift +++ /dev/null @@ -1,51 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/GCM.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/GCM.swift deleted file mode 100644 index d9bf5d94..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/GCM.swift +++ /dev/null @@ -1,370 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OFB.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OFB.swift deleted file mode 100644 index 0f5c66a4..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OFB.swift +++ /dev/null @@ -1,70 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift deleted file mode 100644 index 846015d6..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift +++ /dev/null @@ -1,70 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Blowfish.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Blowfish.swift deleted file mode 100644 index 34c771c2..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Blowfish.swift +++ /dev/null @@ -1,537 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/CBCMAC.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/CBCMAC.swift deleted file mode 100644 index e14f2bd5..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/CBCMAC.swift +++ /dev/null @@ -1,104 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/ChaCha20.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/ChaCha20.swift deleted file mode 100644 index 250ee9d0..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/ChaCha20.swift +++ /dev/null @@ -1,347 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Checksum.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Checksum.swift deleted file mode 100644 index 1c4fd48c..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Checksum.swift +++ /dev/null @@ -1,193 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Cipher.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Cipher.swift deleted file mode 100644 index 6e2b6362..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Cipher.swift +++ /dev/null @@ -1,47 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Collection+Extension.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Collection+Extension.swift deleted file mode 100644 index 1b79faad..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Collection+Extension.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/CompactMap.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/CompactMap.swift deleted file mode 100644 index 74cf92a9..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/CompactMap.swift +++ /dev/null @@ -1,23 +0,0 @@ -//// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Cryptor.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Cryptor.swift deleted file mode 100644 index f79f4b35..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Cryptor.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Cryptors.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Cryptors.swift deleted file mode 100644 index 4baa53bd..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Cryptors.swift +++ /dev/null @@ -1,44 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Digest.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Digest.swift deleted file mode 100644 index c3976ead..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Digest.swift +++ /dev/null @@ -1,78 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/DigestType.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/DigestType.swift deleted file mode 100644 index 48c40d68..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/DigestType.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/AES+Foundation.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/AES+Foundation.swift deleted file mode 100644 index ba797337..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/AES+Foundation.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Array+Foundation.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Array+Foundation.swift deleted file mode 100644 index ffab35d4..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Array+Foundation.swift +++ /dev/null @@ -1,32 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift deleted file mode 100644 index be065b92..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift +++ /dev/null @@ -1,23 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift deleted file mode 100644 index c1f36768..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Data+Extension.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Data+Extension.swift deleted file mode 100644 index 5da7329a..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Data+Extension.swift +++ /dev/null @@ -1,95 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/HMAC+Foundation.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/HMAC+Foundation.swift deleted file mode 100644 index fd4d77cd..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/HMAC+Foundation.swift +++ /dev/null @@ -1,22 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift deleted file mode 100644 index 2a497e66..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/String+FoundationExtension.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/String+FoundationExtension.swift deleted file mode 100644 index 5cd7e9dc..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/String+FoundationExtension.swift +++ /dev/null @@ -1,41 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Utils+Foundation.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Utils+Foundation.swift deleted file mode 100644 index f9453650..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Foundation/Utils+Foundation.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Generics.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Generics.swift deleted file mode 100644 index 51797ce4..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Generics.swift +++ /dev/null @@ -1,55 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/HKDF.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/HKDF.swift deleted file mode 100644 index daa8bbff..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/HKDF.swift +++ /dev/null @@ -1,84 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/HMAC.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/HMAC.swift deleted file mode 100644 index c5bfe3d3..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/HMAC.swift +++ /dev/null @@ -1,102 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Int+Extension.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Int+Extension.swift deleted file mode 100644 index 98b14762..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Int+Extension.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift deleted file mode 100644 index 7f44b4a2..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift +++ /dev/null @@ -1,165 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/NoPadding.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/NoPadding.swift deleted file mode 100644 index 57670ad3..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/NoPadding.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Operators.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Operators.swift deleted file mode 100644 index a15fe3c9..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Operators.swift +++ /dev/null @@ -1,32 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PBKDF1.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PBKDF1.swift deleted file mode 100644 index 953b36eb..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PBKDF1.swift +++ /dev/null @@ -1,87 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7.swift deleted file mode 100644 index 9c012849..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7.swift +++ /dev/null @@ -1,18 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7Padding.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7Padding.swift deleted file mode 100644 index 37cd165e..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/PKCS/PKCS7Padding.swift +++ /dev/null @@ -1,64 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Poly1305.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Poly1305.swift deleted file mode 100644 index c97f9404..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Poly1305.swift +++ /dev/null @@ -1,165 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift deleted file mode 100644 index 974ae90c..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift +++ /dev/null @@ -1,217 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/RandomBytesSequence.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/RandomBytesSequence.swift deleted file mode 100644 index be7bdcb7..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/RandomBytesSequence.swift +++ /dev/null @@ -1,50 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/SHA1.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/SHA1.swift deleted file mode 100644 index 61f6bce3..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/SHA1.swift +++ /dev/null @@ -1,151 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift deleted file mode 100644 index 2e9940d3..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/SHA2.swift +++ /dev/null @@ -1,353 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/SHA3.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/SHA3.swift deleted file mode 100644 index b22fb5a1..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/SHA3.swift +++ /dev/null @@ -1,289 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/SecureBytes.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/SecureBytes.swift deleted file mode 100644 index 61e7f693..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/SecureBytes.swift +++ /dev/null @@ -1,77 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/StreamDecryptor.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/StreamDecryptor.swift deleted file mode 100644 index 81ab2705..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/StreamDecryptor.swift +++ /dev/null @@ -1,78 +0,0 @@ -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/StreamEncryptor.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/StreamEncryptor.swift deleted file mode 100644 index 7cd54e3f..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/StreamEncryptor.swift +++ /dev/null @@ -1,56 +0,0 @@ -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/String+Extension.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/String+Extension.swift deleted file mode 100644 index b186e341..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/String+Extension.swift +++ /dev/null @@ -1,81 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift deleted file mode 100644 index 20157902..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt128.swift +++ /dev/null @@ -1,90 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt16+Extension.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt16+Extension.swift deleted file mode 100644 index 65f62898..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt16+Extension.swift +++ /dev/null @@ -1,37 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt32+Extension.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt32+Extension.swift deleted file mode 100644 index 0901148e..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt32+Extension.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt64+Extension.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt64+Extension.swift deleted file mode 100644 index 44a77d93..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt64+Extension.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt8+Extension.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt8+Extension.swift deleted file mode 100644 index 481d57fd..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/UInt8+Extension.swift +++ /dev/null @@ -1,76 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift deleted file mode 100644 index 23f16545..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift +++ /dev/null @@ -1,98 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Utils.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Utils.swift deleted file mode 100644 index 17b368af..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/Utils.swift +++ /dev/null @@ -1,115 +0,0 @@ -// -// 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/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/ZeroPadding.swift b/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/ZeroPadding.swift deleted file mode 100644 index 7d1d8276..00000000 --- a/cocoapods/Pods/CryptoSwift/Sources/CryptoSwift/ZeroPadding.swift +++ /dev/null @@ -1,38 +0,0 @@ -// -// 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.. 0.0.1" - ], - "PromiseKit/Foundation": [ - "~> 6.0" - ], - "BestLogger": [ - "~> 0.0.1" - ] - }, - "pod_target_xcconfig": { - "EXCLUDED_ARCHS[sdk=iphonesimulator*]": "arm64" - }, - "user_target_xcconfig": { - "EXCLUDED_ARCHS[sdk=iphonesimulator*]": "arm64" - }, - "swift_version": "5.0" -} diff --git a/cocoapods/Pods/Manifest.lock b/cocoapods/Pods/Manifest.lock deleted file mode 100644 index 6078c5d6..00000000 --- a/cocoapods/Pods/Manifest.lock +++ /dev/null @@ -1,61 +0,0 @@ -PODS: - - BestLogger (0.0.3) - - 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) - - Torus-fetchNodeDetails (0.0.20): - - BestLogger (~> 0.0.1) - - web3swift (~> 2.3.0) - - Torus-utils (0.1.1): - - BestLogger (~> 0.0.1) - - PromiseKit/Foundation (~> 6.0) - - Torus-fetchNodeDetails (~> 0.0.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: - - Torus-utils (from `../`) - -SPEC REPOS: - trunk: - - BestLogger - - BigInt - - CryptoSwift - - PromiseKit - - secp256k1.c - - Starscream - - Torus-fetchNodeDetails - - web3swift - -EXTERNAL SOURCES: - Torus-utils: - :path: "../" - -SPEC CHECKSUMS: - BestLogger: 70475db073dfab3ec1ba9b58b0bb78126b068eee - BigInt: 2aad1a9942dc932ec8b84290d2c564a3d76f97ab - CryptoSwift: d81eeaa59dc5a8d03720fe919a6fd07b51f7439f - PromiseKit: 9616b0afef31eae56ab9ce044c8ec2b8612a15cd - secp256k1.c: db47b726585d80f027423682eb369729e61b3b20 - Starscream: 4bb2f9942274833f7b4d296a55504dcfc7edb7b0 - Torus-fetchNodeDetails: 567d0c73c1b318c8811abcef0b2f31cfdcd5a4a4 - Torus-utils: cd8ac44a3397d1dac0132ca414478f9dd55a8825 - web3swift: 0f097eafe1d08f478694b882581b85a01afb6633 - -PODFILE CHECKSUM: de6dc705fbcaee4478a78e83fe706aec34cc08c1 - -COCOAPODS: 1.10.1 diff --git a/cocoapods/Pods/Pods.xcodeproj/project.pbxproj b/cocoapods/Pods/Pods.xcodeproj/project.pbxproj deleted file mode 100644 index 464726a5..00000000 --- a/cocoapods/Pods/Pods.xcodeproj/project.pbxproj +++ /dev/null @@ -1,4057 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 51; - objects = { - -/* Begin PBXBuildFile section */ - 0049EB7DC74BEFCDC5740A4FFBE89170 /* Data+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = A6D43ECDBFBD5966FA8C97853B7A6744 /* Data+Extension.swift */; }; - 00542E749518733F88FD9339F521159E /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 44050EDD065DFF0F59D2C7D56487174A /* UIKit.framework */; }; - 009C0525EBF2E8717C45835B5FF73504 /* Web3+ERC820.swift in Sources */ = {isa = PBXBuildFile; fileRef = 92E67E4F9997B00CBAEF6DC5180B804E /* Web3+ERC820.swift */; }; - 00C6A45F25B7C9567ABD4B6CEBB8F3A0 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08859518C8A8BA3027D2209AEDBC64AC /* Utils.swift */; }; - 0135B4BBC91F702B043FAA03FBE81DC7 /* Dictionary+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43B2A6CA1E4D2F7A4D32596BA2E04F4E /* Dictionary+Extension.swift */; }; - 0204978073AA06F1FD718B73A86E4F72 /* scalar_8x32.h in Headers */ = {isa = PBXBuildFile; fileRef = 2BF0E5B419AE36443D1D1F57ECB5323F /* scalar_8x32.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 025EED6A44FE486DD84DA9D38AC02AA0 /* Thenable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84CFB5E7DC25C41F593E110F7CA2CF94 /* Thenable.swift */; }; - 029030C307564BA7D0CB3EE6F5D36823 /* Web3+Instance.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2029C65F287FB4F3DF0A12F1340C4A2E /* Web3+Instance.swift */; }; - 02B4FB8FC9F72608C82C7058FBE47514 /* EIP681.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9FC4A128639B3C17CBDB3AE67BD61BBE /* EIP681.swift */; }; - 03B17518831570C6E89FFEEC86102D2C /* BIP39.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0247C8EEE7B4D5D0983AAC08DC69FF1B /* BIP39.swift */; }; - 04C4B5D00750E2E4DFD4C4C7CC47283A /* Bitwise Ops.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5795FBFDECE1EE5D44334B0E86704C3 /* Bitwise Ops.swift */; }; - 0526AEB2FAAA1D80AC6245AB71BE994F /* BlockEncryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AF1CFD2C9895A1EDAFD919380565FB3 /* BlockEncryptor.swift */; }; - 05958032576427EDBC47854025783311 /* Utils+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C0DC37E22F8903645A132FC89D8C1DC /* Utils+Foundation.swift */; }; - 062A929DF69235998607A846BBBEEC53 /* Web3+ERC1644.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8F20F5D5E82BF2A3C986523F803A02D /* Web3+ERC1644.swift */; }; - 06733C6BD5DAA3E1DF17B52F58A972EE /* hash_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 69CC6C3B6338B8B1D8CBAF297925E3EB /* hash_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 068E5963381B58D7D8CD321462F567ED /* Compression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 623192767A29965E6C002E99496ADB9E /* Compression.swift */; }; - 06DC6E69AE67D84EEECFEBD7B463E857 /* Array+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EFBB66B08AAC29D6B283076F7CF0951 /* Array+Extension.swift */; }; - 07CF202BCE4D1383BA86DA1200BB411A /* ENSBaseRegistrar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4542D87C52957FA0E8DD89915A7F699C /* ENSBaseRegistrar.swift */; }; - 080DAC1FE3D34C0D47DD2950FEB831DA /* ecdsa_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 9CF17921439863D5241B29B9DCC9D6CA /* ecdsa_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 0B22F5E17A03A7A96699018F9133297A /* NativeTypesEncoding+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77A9E9B7B569F09BB85D9AA4D7B47A61 /* NativeTypesEncoding+Extensions.swift */; }; - 0C872EAB484331F031EB6E9196B46E1E /* web3swift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 975066EE84D12EED3FB768B684207672 /* web3swift-dummy.m */; }; - 0C99989CEA8113F15AF6309676D37664 /* BIP32KeystoreJSONStructure.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D48B83EF23A08BDB8BF4F2E68A6A921 /* BIP32KeystoreJSONStructure.swift */; }; - 0DF63A4C8FA0E53FB630F5B5429FF066 /* Exponentiation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62878F4D3CFBB00EBD025FF63E76375F /* Exponentiation.swift */; }; - 0E6F0E8337D8928B164D18FC54D6C7F9 /* Bit.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8A94D85576CA4545A9A0095CCE8D476 /* Bit.swift */; }; - 0EA61F34CB7EEE8820E2934C8AD1E6BB /* Array+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9B012F1E432805425ECF952C85B24A2 /* Array+Extension.swift */; }; - 0F1B490475785F1E8F6C6870AB6051C2 /* Web3+ERC1633.swift in Sources */ = {isa = PBXBuildFile; fileRef = 266F457FE7F2E756EA9EFE30B0F6B05A /* Web3+ERC1633.swift */; }; - 0F77D140F8BC6AF9C76A646A1A1DB167 /* NSRegularExpressionExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0457C62F928892E60662C7AFEB6B2EE7 /* NSRegularExpressionExtension.swift */; }; - 0FD1EA8AE4D8EB148DC21C25366F33BF /* secp256k1.h in Headers */ = {isa = PBXBuildFile; fileRef = 14D268E0C6A9A8606B2F5F1A263791A3 /* secp256k1.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 104671798BC62876A0EAF4843E8DD214 /* TorusUtils+extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1C5DA46A837EAE231568713CEE6CBA9 /* TorusUtils+extension.swift */; }; - 126ED2C348D7F4EE990502382C1759A9 /* Web3+Wallet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AB8CB5005FBD2930B346BD37D0CE897 /* Web3+Wallet.swift */; }; - 129B12C551894C2CF7CB421ECF79F719 /* browser.js in Resources */ = {isa = PBXBuildFile; fileRef = 7084A45BBF491661009BA2F1F1FFA83D /* browser.js */; }; - 13A4BA994DAE26C3B22F1842D5E186BD /* Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30F3E8F002317CB34DEBAC0F376015B0 /* Padding.swift */; }; - 14D34E32263C8D334AC63CA775357BA8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 93DA1DCA9F62B5CF3199108FB90AF568 /* Foundation.framework */; }; - 15901C26A398A72C746D1369042356B6 /* join.m in Sources */ = {isa = PBXBuildFile; fileRef = C8DAA386BC2D44F1C22D3A73622A2899 /* join.m */; }; - 161AAF0DF4B937AE2AC3AC7DB45EEF8C /* hash.h in Headers */ = {isa = PBXBuildFile; fileRef = C517F94DAEE3BC8B1A82A8B17EB4760A /* hash.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 1627E6FA0453D6DB472BA444F1D32AE7 /* SSLClientCertificate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B065DE7641AB7C6FF473D09055AA810 /* SSLClientCertificate.swift */; }; - 16C2B82A6557C0809704DC0E5334160F /* field_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 7C4E4C5A7B89BAC92AF3CDF8A3DF20C5 /* field_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 16F71F20D31B7EEC6A60DB14135AB7A9 /* Comparable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C0584AA4F770CFB96D81C2F740F5B48 /* Comparable.swift */; }; - 170175D902933C1C550280534923EA7A /* RLP.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B85A6893CDE4B4C76734554A0BB3969 /* RLP.swift */; }; - 18280888DBABC792A624CDC9F963EECD /* Web3+ERC888.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09954F8AE56A9731301D95657001486A /* Web3+ERC888.swift */; }; - 18DF6A317CCB7F5BEE8D7AF5D79AEB38 /* PromiseKit-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 6ACB6795469A1198FA61AA30CBCE452B /* PromiseKit-dummy.m */; }; - 1A179BAE7E3ED81BB708D5DF5F97A8FB /* BrowserViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2BB30C009589E527A7DAB4ECB42B0559 /* BrowserViewController.swift */; }; - 1C482705924CA6C3DF716EC60624900B /* Generics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 532AD590CA6E6DFA10973018D68A00B9 /* Generics.swift */; }; - 1C5D3593B983B9369EFCFDE7D4DE0D19 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6DE54368C1B3E8A157270E9BA06F283 /* Configuration.swift */; }; - 1D323AAF728E32DCE9727046EC1D4A31 /* basic-config.h in Headers */ = {isa = PBXBuildFile; fileRef = EE10CF5EF112C5175D61542352045BE4 /* basic-config.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 1E40B27B27DD44482412FF909F0EA60D /* field_5x52_asm_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = FAB928F1FDD4C97ED194CDF22569830E /* field_5x52_asm_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 1E42E056D28167CBC2C73291256A980C /* Promise+Web3+Eth+EstimateGas.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90BE69904F143992674611FD87C10FF0 /* Promise+Web3+Eth+EstimateGas.swift */; }; - 1E6C33DE401D9AEFE660851A3E3394E6 /* NoPadding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11B2495717C3300B60C1D01F85E169CD /* NoPadding.swift */; }; - 208EDAA1D258CAA2BD08E462359D4FFF /* when.m in Sources */ = {isa = PBXBuildFile; fileRef = BA45C8CD81E3BEC7324DA061D9811272 /* when.m */; }; - 2181AAB3F159DD95540528F9C435F5F7 /* fetchNodeDetails.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A1A105339FBDCF49E1692DAC870181F /* fetchNodeDetails.swift */; }; - 21D920F436749D387F2454336B2049E0 /* ecmult_gen_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = BB6C5C1E585BD8D5914604BB64EFBD57 /* ecmult_gen_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 2228B8549F0F5445D1B2D346E12A20CD /* Floating Point Conversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 432B19CC00325EAC433376693879C00D /* Floating Point Conversion.swift */; }; - 22E90BB147F27F078FA546193B14C035 /* Web3+Eth.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E58EE8091E64202823382773372E51D /* Web3+Eth.swift */; }; - 252264684AE3A115807C7493BC63C281 /* Web3+SecurityToken.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44A6E724DEAED085EEFF9F277E653728 /* Web3+SecurityToken.swift */; }; - 25252C54530A36B1CEF487F1A9B497C8 /* Web3+ST20.swift in Sources */ = {isa = PBXBuildFile; fileRef = D92F9E70385EBF2A8803AC9161D1CACB /* Web3+ST20.swift */; }; - 25F360948AF8160C0EB0662D7BB9C422 /* Web3+ERC777.swift in Sources */ = {isa = PBXBuildFile; fileRef = 833C4372749433AEF2DDCFD5ACD4F288 /* Web3+ERC777.swift */; }; - 28EBBB674FB096ED103EC7B4C3837194 /* SECP256k1.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECFD101D49866DB9A64325CAE0CB66D7 /* SECP256k1.swift */; }; - 294C60E5E562CF3C2917335BDD910F42 /* Checksum.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D6CF27A12D3F3EF5494307E376E9EAD /* Checksum.swift */; }; - 294D61E8A195B6A1F6AEDCF0F73599A5 /* Starscream-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = E5C0758AF7131C4B8811CC48D12EC15D /* Starscream-dummy.m */; }; - 29643F7A000899634C9174BCB8D1A1AB /* NSNotificationCenter+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F0E9FE8589A3E747F1C6E49D1F665B6 /* NSNotificationCenter+Promise.swift */; }; - 29A17D1EA209DF3349FBEBAD35D59F53 /* epochInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68565345731E54A07E8961540F271397 /* epochInfo.swift */; }; - 2A8A3DAA61C2DDA353F06CE7C36F0C65 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 93DA1DCA9F62B5CF3199108FB90AF568 /* Foundation.framework */; }; - 2BB55BEE3AC7D418CF79CE1B3CC03CB6 /* torusNodePub.swift in Sources */ = {isa = PBXBuildFile; fileRef = C451C115F7D090FDCDB0F35DC85231E4 /* torusNodePub.swift */; }; - 2BE848F4DD3274E28DE44DDDCD72CF8B /* ContractProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = B640F3F6BEEA3F00C6EC949A3247B36B /* ContractProtocol.swift */; }; - 2DD9959CD5493A978BCB3B3CC0D2EB49 /* ECB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30B0D8BAF890F4EFCB9D256CC130AAA5 /* ECB.swift */; }; - 2E938A3C33EE9130C959EFA811DFB2EE /* Rabbit+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 304513EC2F0CF7D352C919E34D643691 /* Rabbit+Foundation.swift */; }; - 2F24F334AE17BA825EDB27FE7153278B /* EthereumContract.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5410B105EBAA327591B7B1178127F21A /* EthereumContract.swift */; }; - 2F97EAB4BE6AEF9EB32A9B1F5EE03C16 /* PlainKeystore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F71BAAE30889A3196D3F193BD7EAE93 /* PlainKeystore.swift */; }; - 2FDD3DAC4E9D0C03A16D3F838A8E15F5 /* SHA2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7068BB4E0872B6DEC38E77F1B04ECDB7 /* SHA2.swift */; }; - 301B5F7669D2DC7E46384FBAC71B7C19 /* hang.m in Sources */ = {isa = PBXBuildFile; fileRef = D66EC39D540DA888CAC8F3E40E894EEE /* hang.m */; }; - 305F15EFFE12FF60509C8C5A08FD4792 /* Promise+Web3+Eth+GetAccounts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8080BE88E5AD32344368207217955275 /* Promise+Web3+Eth+GetAccounts.swift */; }; - 3198D535165A8276A8A7A5CA7644FC0F /* scratch.h in Headers */ = {isa = PBXBuildFile; fileRef = 9A55358BC9BF9260CA0B353D1E198EDD /* scratch.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 31DBA98917ACA7AF6C5D9C9D3D3D8B32 /* Promise+Web3+Eth+GetBlockNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B6B7AECEFE99816B8FBCB33CA41BA5A /* Promise+Web3+Eth+GetBlockNumber.swift */; }; - 3208DDEB9CAC16AC7D2C7E9A7F057DC1 /* NSURLSession+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25329BA0B75B6EC317AF079B1D15542A /* NSURLSession+Promise.swift */; }; - 327E70522102D2171C98B880D3CA692F /* Web3+Eventloop.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46D72FD9B676F8CDC9814462C4FAFD62 /* Web3+Eventloop.swift */; }; - 3378C1EEFC149B899433AF30F147CE32 /* after.swift in Sources */ = {isa = PBXBuildFile; fileRef = D046A51420E0E9E3D0C5811918D9FDF8 /* after.swift */; }; - 33B79E4BFF8D25E1A705E2C469BBCA9B /* PromiseKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 3B4F23EB6DCEE0E727D49E697D2F4602 /* PromiseKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 3607067F46CCABE732B2E0078149F8B2 /* Array+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = B199C90B54B508CC6863DC3B86C34A12 /* Array+Foundation.swift */; }; - 363DDC37B77721F9814603B8461DBA19 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 93DA1DCA9F62B5CF3199108FB90AF568 /* Foundation.framework */; }; - 36652DE8FF55772FB33C419FD6153FC5 /* RIPEMD160+StackOveflow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9362939A3FBFC35D559726BAAEE2D8 /* RIPEMD160+StackOveflow.swift */; }; - 36B12BDADD70855F21118BA8C653366A /* browser.min.js in Resources */ = {isa = PBXBuildFile; fileRef = 93BBFE788270709884A832C695A7D9B1 /* browser.min.js */; }; - 37018D3DC554A00E9B3E306A28296316 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA6E5EE30B00CACE5169C7B53F93C899 /* Error.swift */; }; - 373598EE21A99D2E8088520F8E4E985D /* Pods-TestApplication-TestApplicationTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = CEC31D6A49140A8533DE7811B519DB98 /* Pods-TestApplication-TestApplicationTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 37E4E0A4F2459F27ACC0DDD7E826F219 /* KeyAssignRequestResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89D859F38B40E4EBC5C9E12D681363A1 /* KeyAssignRequestResponse.swift */; }; - 39137B0D7B8FB5BF554BDE012BD85061 /* Data Conversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97BA2657F2505CCC7EEA41D25BB7CD60 /* Data Conversion.swift */; }; - 3957B5C0220F087BC1B336A5BFC2B5CC /* TransactionSigner.swift in Sources */ = {isa = PBXBuildFile; fileRef = F503884ECADE82608ACA72266F494DED /* TransactionSigner.swift */; }; - 3A685604A59A0AA77824B0729BF62F5A /* Web3+ERC1376.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC8D6E6A3C65F1625E166907BAFC6DB9 /* Web3+ERC1376.swift */; }; - 3AAE347ADDFEFAC7DDECBC744D1BD6AC /* NSTask+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 1266EFA379D86490C2F8DE7D3FD4F149 /* NSTask+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 3B22E2EB53E57009FD12A3DF86E2D91C /* ecdsa.h in Headers */ = {isa = PBXBuildFile; fileRef = C092ED0FA8FE817ECF8A7DC1D8EC6B35 /* ecdsa.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 3B9A2601095A9A72843D76CA44B37782 /* Division.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F765D728D60C038B07F08BE54D2913F /* Division.swift */; }; - 3BBD967EE05C6195B23F9C77BD9DFC40 /* Web3+ERC1400.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9360628224445199F11C25D8F17488D /* Web3+ERC1400.swift */; }; - 3BC67BD4E21453CA5AC8B893A16B246B /* String+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDA50BF1534C414EDA586E4C6C654C29 /* String+Extension.swift */; }; - 3CCB015D6F0C4DB48F8C0E542FFFC076 /* BestLogger.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D4A6E662E95C1F325699B62C766A94B8 /* BestLogger.framework */; }; - 3D92BDF4B0DC217CBAC5C6122151C435 /* BIP39+WordLists.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DF1B2B15BA23A2536CCE7230A326820 /* BIP39+WordLists.swift */; }; - 3E0122134CE56BF279E308565FD40B5E /* JSONRPCRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = A82C338D47D72E5E229B666E9FB29815 /* JSONRPCRequest.swift */; }; - 3E3FE29D83B6DB4B229CB38CCB4E1C86 /* CBCMAC.swift in Sources */ = {isa = PBXBuildFile; fileRef = EECF5BB5E32E6387F8543F14699C8A69 /* CBCMAC.swift */; }; - 405BBFBA40C80C1F0C1C2A45FD1F548B /* secp256k1.c-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 6B65A61831421C6750C3861BC12E0C45 /* secp256k1.c-dummy.m */; }; - 40C047E8319F21196D029C8C76819F23 /* BigUInt+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58BF3F08DDC701824F81D3D3A3888DCC /* BigUInt+Extensions.swift */; }; - 41423C7054638D60AF039BE3D8DD0DC3 /* EthereumAddress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3254F0C43CE6414EB81E1FD3C3ACA595 /* EthereumAddress.swift */; }; - 420C87B493B70746472899A82479242F /* String+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43D6002B89854A8CA87F6E11D2A4774B /* String+Extension.swift */; }; - 42495A8941D9B42B07F032390AA2389F /* UIViewPropertyAnimator+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = D34674A4FB818DC9CB7B920E2180B2CB /* UIViewPropertyAnimator+Promise.swift */; }; - 42B66F10E610FB5F799FFC5BC91BCD9D /* BIP32Keystore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66367BD14E3729FBAE3EEC75BFF93DC9 /* BIP32Keystore.swift */; }; - 42CB6A5D231637354B9D38588E817DDF /* Web3.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE75DAE76B1194C740ECB38E07E66E27 /* Web3.swift */; }; - 42E3AC2A6C8415B6645B956C38EF9409 /* Torus-fetchNodeDetails-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 610164D574FDBA5D2B86AD20803A34C7 /* Torus-fetchNodeDetails-dummy.m */; }; - 4362503059C68DFCDCB8621F4FD9E325 /* Square Root.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB66295E387734C568DC4F306928B9E7 /* Square Root.swift */; }; - 4382AFE23DB6803BBB77D5B0283D56D9 /* Promise+Web3+Eth+GetTransactionDetails.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37BB11C3206A9AF2E5FB14349F0A0C72 /* Promise+Web3+Eth+GetTransactionDetails.swift */; }; - 438DAC7813FDB677252FB52A8FA3E708 /* Updatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 648384FDC27C062F3B5B39565DC0B287 /* Updatable.swift */; }; - 4418281931C4D1176F2C541CDD770F14 /* Catchable.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF0BEE4B0224AC7B0C9583A79622855A /* Catchable.swift */; }; - 448506F29495E3B3BAB56D093D681C1A /* Authenticator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31C3703C315175092D73AECC95DE71B7 /* Authenticator.swift */; }; - 45746D692A8E7F09C0EED2675231EF41 /* StreamEncryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66D8D2442F980738A4DF46016A1C658B /* StreamEncryptor.swift */; }; - 45A5D20354B11CD25B17F0D877CF02F4 /* EthereumKeystoreV3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 61DE2FCF270DEB55C69AE65F3614A934 /* EthereumKeystoreV3.swift */; }; - 45B48F57B1039D463A2CB04349F22C5A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 93DA1DCA9F62B5CF3199108FB90AF568 /* Foundation.framework */; }; - 46C4120B8C66DBCBEEC55D09F043D618 /* race.m in Sources */ = {isa = PBXBuildFile; fileRef = 137378E4AD849849095296939E1F272F /* race.m */; }; - 487AB9E125898D80AF91388DC79B8667 /* Promise+Web3+Eth+GetGasPrice.swift in Sources */ = {isa = PBXBuildFile; fileRef = F6EC47A89FC36ABDD81383BB895520CD /* Promise+Web3+Eth+GetGasPrice.swift */; }; - 49696DF6233801BF2D0F0BE214E56304 /* SecureBytes.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAAD698E863ED4A0CCEEBB0C78DCA770 /* SecureBytes.swift */; }; - 4981C37D541CDA8BCB7DE77E6607AC50 /* after.m in Sources */ = {isa = PBXBuildFile; fileRef = DF0F7BE2BFEE5598CFE63E715EBA3758 /* after.m */; }; - 49C8C4DFD859391ED9CB7EBC50DDBBD1 /* MD5.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9D4E09DA60B39BABA588D1D5927338B /* MD5.swift */; }; - 4A8B21596204A43258F4EC69A7AEC66E /* Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 898923CC0589827D44FC74523112C46C /* Hashable.swift */; }; - 4CE14AF6A9D5BAB9A775D78B9AA80B22 /* ecmult_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 805A95545687CAF1C10291D688FFBA5E /* ecmult_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 4D65C782220C5E27BF8A3B61EBBDAB3E /* Guarantee.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74CD34049D056134BF4391B03E13C4A2 /* Guarantee.swift */; }; - 4EC7BD8654B3587F1F725E812C9D828C /* race.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B4BB1950A7E59A2522D593BBB8B7488 /* race.swift */; }; - 51FE9E33966223FEF5EC69BA3EE1ED0F /* Torus-utils-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 70C8D6D69E1A13C98E13C5399927DBCF /* Torus-utils-dummy.m */; }; - 52E2ACD870A7CA9F355C21B694120694 /* ABITypeParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EAC7939CF4AA08B18DE951258B603FE /* ABITypeParser.swift */; }; - 52F57EB35132E86D75FE9443258EFDBF /* UIView+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 65772FBA70CCA564031A7DB655375942 /* UIView+AnyPromise.m */; }; - 5300EB86348ED2DD35A9339104F21842 /* CBC.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB346C38513FA9E9018CE31D0EB8E613 /* CBC.swift */; }; - 530876118555FFAFE97180FF28BD962A /* Web3+ERC721x.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64406043FA5C8662A25B01ECBD9A167B /* Web3+ERC721x.swift */; }; - 531B8470043B78207C1F4270BD7A6EBC /* Web3+ERC1155.swift in Sources */ = {isa = PBXBuildFile; fileRef = F138B36B651F1298A2480F35906F9395 /* Web3+ERC1155.swift */; }; - 53DB39909A5A1D49D2E03CAB692BD8B5 /* scalar_4x64.h in Headers */ = {isa = PBXBuildFile; fileRef = BD452434C32536EDBC8CAD6DC25620BA /* scalar_4x64.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 54BDD3BC1B92330FEF7F64FA1660BB13 /* AES.swift in Sources */ = {isa = PBXBuildFile; fileRef = 547193FFA17662EE95EF699A2570D30B /* AES.swift */; }; - 56B4C57D519DC4203D61A2F64BFF8E45 /* Promise+Web3+Eth+SendRawTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB01F38BCDDBFAE68CF0096A471DCAA4 /* Promise+Web3+Eth+SendRawTransaction.swift */; }; - 57E56900F1BE1DC4665FBCF865BEB375 /* Pods-TestApplication-TestApplicationTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = CA38481A10469E72124DD89F5DC85BDD /* Pods-TestApplication-TestApplicationTests-dummy.m */; }; - 5802BD2A7E671D3015BE4E98C13D10CB /* NSURLSession+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 2E57FB97B6281DDB98BEC36EA0CE3C0E /* NSURLSession+AnyPromise.m */; }; - 58AD203AF555F9B8416F7F9B4C7DA435 /* Rabbit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F9D9BAC5011C578C942C96A9193C5A2 /* Rabbit.swift */; }; - 58F25F7F0904CC29E369DC94270B8017 /* Web3+EventParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B5549F6AF497C5E9C8BD220E77944F1 /* Web3+EventParser.swift */; }; - 591736E2D0696757E8762B5481687162 /* NativeTypesEncoding+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAC5419747B4F5C0A8F7F53295E16194 /* NativeTypesEncoding+Extensions.swift */; }; - 59AA176600E91A56BC244B381305060B /* UIView+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 7865861740168F97EBF3471A1E99D0C4 /* UIView+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 59CB2BC19644CCDCE0A6B59528348FD1 /* UInt32+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E31FB5291F104D8F312D4A179031B59 /* UInt32+Extension.swift */; }; - 5B8A5FDFCDA736C6929320348B66149D /* CMAC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FC83725DA96C508A8896086BFAF1B1F /* CMAC.swift */; }; - 5BF67CC8A596E6D8F6095F0F9F76F054 /* FetchNodeDetails.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1225388F468617B747120B6063E2688D /* FetchNodeDetails.framework */; }; - 5CEFD4F8821A3A1BD6C78FFCBCC98DA4 /* AES+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FB42BBCB8503EAD2C9CB5548BD0EEEF /* AES+Foundation.swift */; }; - 5D2D358E754D92564B259BBACFBA8271 /* PMKFoundation.h in Headers */ = {isa = PBXBuildFile; fileRef = 7B3934C6F60ADD7B7235930EEC358D0F /* PMKFoundation.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 5D3CFC3E2CCAA272A2003762AFD66B41 /* secp256k1_main.h in Headers */ = {isa = PBXBuildFile; fileRef = 36596C1155BCF36D4AC1E20D7F7DD4E0 /* secp256k1_main.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 5DE56A1F1C10D196C20635E96533B98C /* Web3+Personal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F13C642230A43992D825AC6F75C9DE4 /* Web3+Personal.swift */; }; - 5E2574B7162EED00A81237F56CDC0BE4 /* BigInt.swift in Sources */ = {isa = PBXBuildFile; fileRef = B53A9F8E880B31A0E6C1649C07767374 /* BigInt.swift */; }; - 5E47C7CE3D7F87F4116FC7B83A1199E5 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 93DA1DCA9F62B5CF3199108FB90AF568 /* Foundation.framework */; }; - 5E5EBD7039DC8763BFB20616B2AFE5F6 /* CryptoSwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 6AB74F071919892DEDA2B20512603D17 /* CryptoSwift-dummy.m */; }; - 5EE0235F01C86FC15C90D3F673082571 /* fetchNodeDetails+promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B9B33F9B214514D6A7B86948424A1AB /* fetchNodeDetails+promise.swift */; }; - 5F79C41D8A8DAAD57BEAF48FC641A06E /* ETHRegistrarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDE31A309088ACB19C211A0737B07083 /* ETHRegistrarController.swift */; }; - 5FDAD3F1739595982080BE2DD789C697 /* CipherModeWorker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54E37A2DF9578412AA69A5BEFC18EE7B /* CipherModeWorker.swift */; }; - 6002AD14210CBE9C34EB848031CFD7E6 /* Addition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9591EFA1AE71B666915FB5B8C763A34F /* Addition.swift */; }; - 60F874ED0F6234A4417CAFDE554D088D /* PMKUIKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 4B9B3D2E1749E19CD5247226FC2A0DE9 /* PMKUIKit.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 611450D9423EB6D78CBEBCBC60FC3BE4 /* BestLogger-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 283CC747FD0DCC168EE28C22BE24FB13 /* BestLogger-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 61330480364F92D57CB181E890C8896B /* Collection+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = F250225BFF25426CFF2F1925C181742C /* Collection+Extension.swift */; }; - 61D2F48325DD4A8443C3B44163084052 /* PublicKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0ACE6FCC5FCCB682084B1E58B8DEB240 /* PublicKey.swift */; }; - 629009B19A29C3EF75B2854F9FB40832 /* Web3+ERC1410.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB4F895E66EF6D86F159E98B5E36B539 /* Web3+ERC1410.swift */; }; - 636A216DCBEBED81DA2DB1A12C7639E0 /* Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = A17BF4AEEC01E419833321F0C76BF3A3 /* Operators.swift */; }; - 639C6438CD01AE7A36FE1E551F2E7A8F /* CryptoSwift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 21EEF7760B023045FC31EC473557A490 /* CryptoSwift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 64B5AE496D617B5B58DCE09E69055CF0 /* Bridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1E53313719F7918997A997F6DF22863 /* Bridge.swift */; }; - 65D833120C79B4C06F9AD721F871AB2D /* Base58.swift in Sources */ = {isa = PBXBuildFile; fileRef = C733688975F1D4437EFCBDE5960EF023 /* Base58.swift */; }; - 6641A7D860C65EBFD8268CB4123E74B3 /* Web3+Constants.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4251BC1432EB0343A2E8895B0371187 /* Web3+Constants.swift */; }; - 672C52B2CBF9425B272A5845B0A38ABF /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 94C4B2C4BB3ED30A768BCD9DCE993A60 /* PromiseKit.framework */; }; - 67F33D45B4C0091959CEA9B92420E8A2 /* num_gmp.h in Headers */ = {isa = PBXBuildFile; fileRef = 79FFF2FD3F5D49331504AD9FB3B06AF7 /* num_gmp.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 68A92231E087567C6A9AD700359DAE80 /* AEADChaCha20Poly1305.swift in Sources */ = {isa = PBXBuildFile; fileRef = 861D5F94C97320DB5B5A576B7DE1046A /* AEADChaCha20Poly1305.swift */; }; - 694B1EB8CB94A408E480334B70D3CCAF /* String+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32E81D97829DA786CB8BCB3CE12AAD57 /* String+Extension.swift */; }; - 694E630570AB4DB0BCDF003411CF2B63 /* SHA3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 280BDA4851FC9E3A332073A8A1E52A71 /* SHA3.swift */; }; - 69DBAB1E3A8EEBFCC466D95509DE7125 /* UIView+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 403758DEF6A4E7BB2F98889B82A135A9 /* UIView+Promise.swift */; }; - 69E62D35A7043AEBAFF100D522F38A30 /* DigestType.swift in Sources */ = {isa = PBXBuildFile; fileRef = E89EF6F927A69D30F1E0B5E83254DF68 /* DigestType.swift */; }; - 6BD149F5D90C9E30F95C829791EB97B9 /* Web3+Structures.swift in Sources */ = {isa = PBXBuildFile; fileRef = 367EEC90C25E5957B79AF83B5F8C8040 /* Web3+Structures.swift */; }; - 6C6A1C4DAA7FBC889B951609C91956BF /* ComparisonExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4153FE15958FE1F02ACA05376FB555AF /* ComparisonExtensions.swift */; }; - 6D78DA2799A948EFEBBDDCDB21181B6E /* HMAC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98302BCB7B2D63FE1C809B7EED544A31 /* HMAC.swift */; }; - 6DE830042E36FDE326546970CA90F9B6 /* Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC4196F01C84C79E6BA8B684CC7FE8CF /* Promise.swift */; }; - 6E7EFAD55429703AC4F4161824C2949D /* Promise+Batching.swift in Sources */ = {isa = PBXBuildFile; fileRef = 321B1BD0CEA3B32021B68BF7BC9E90E7 /* Promise+Batching.swift */; }; - 6F3C398006A16F975B7E62763B365286 /* Web3+JSONRPC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B00928391D9D697250F52FE2928539E /* Web3+JSONRPC.swift */; }; - 6FA8655716F022363C98FCA802982E91 /* NSRegularExpressionExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B27B50B07301DC15A482B96A4F84F6A /* NSRegularExpressionExtension.swift */; }; - 73B852F1F6A54C72C500CA87816C86BE /* PromiseKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 94C4B2C4BB3ED30A768BCD9DCE993A60 /* PromiseKit.framework */; }; - 73EA1C553B580637369E1D5A72A425B3 /* when.swift in Sources */ = {isa = PBXBuildFile; fileRef = F938C6C5E22B543C6076CD531A83ADC7 /* when.swift */; }; - 74BEDC20360FEDC36867D3F4988EE59D /* BestLogger.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D4A6E662E95C1F325699B62C766A94B8 /* BestLogger.framework */; }; - 758E6699C3AD8153FBC5BDE6B78C7B7C /* Decodable+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CBB573AF014CEB32442B64D32A7D855 /* Decodable+Extensions.swift */; }; - 76C80FC45C606963585582CDF0449A98 /* field_5x52_int128_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 20400A55C671EE455F595599C28C01CB /* field_5x52_int128_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 77000A8F4524AF0977F1AECE1852DD69 /* scalar_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = CD3D2A6042B0466EC93ED0D38E38186A /* scalar_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 7747F57C44FAF3D0E493D3C45F5ADDA9 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 93DA1DCA9F62B5CF3199108FB90AF568 /* Foundation.framework */; }; - 78A6CCB8C142F78011B6E203678B6A93 /* eckey_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 1E3A34EECA0DC99C3A8F3294B0270E41 /* eckey_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 792AECF194FD9EEC68866D1499302916 /* BlockModeOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 49E00ED54B318307C4DE75639CE0317B /* BlockModeOptions.swift */; }; - 7997EAE951EAB362280E2CE750810231 /* Cryptors.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4F8314521B826E9B32104ECF4AB4267 /* Cryptors.swift */; }; - 79F73BA854A7EC559E464EC446493D52 /* AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 1464B14DC813EA19C660522609E95C34 /* AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 79FA64DB3735227282FEB38CA6907626 /* wk.bridge.min.js in Resources */ = {isa = PBXBuildFile; fileRef = 0AE7A1D74F6EEDB965C2CFF1D9C301F5 /* wk.bridge.min.js */; }; - 7B18811164294FD7DB336597B32420B3 /* ENSReverseRegistrar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18ADBE7A86B9A9960F9B87F732421591 /* ENSReverseRegistrar.swift */; }; - 7C9416E409920031F918C78D3F8BC73A /* ecmult_const.h in Headers */ = {isa = PBXBuildFile; fileRef = BAEE2319C8E8D77C6DB2627C66E80708 /* ecmult_const.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 7CA57460C1D6652FD0CF4B62C596849B /* PCBC.swift in Sources */ = {isa = PBXBuildFile; fileRef = B586613F92A74DDD67224217EF339232 /* PCBC.swift */; }; - 7CF67378B4BE4B976A00E814A1685ED2 /* Web3+ERC1594.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E8A9E477BF48B7A910D0892FC633B77 /* Web3+ERC1594.swift */; }; - 7DC7F7509014FFB20EDBC7A1CE475B56 /* BIP32HDNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE760851799E2CCC3C0E2B498E5306FC /* BIP32HDNode.swift */; }; - 7E3E6309C4EB4C70BC8AF5EB9CA3B6FB /* Poly1305.swift in Sources */ = {isa = PBXBuildFile; fileRef = E79A0111B1CF47529D54C51594F84539 /* Poly1305.swift */; }; - 7E6F4EFB85936E0B3EB9AD287F074C36 /* PKCS7.swift in Sources */ = {isa = PBXBuildFile; fileRef = E935BCC5B06D492AD6FE80DEAE1A1346 /* PKCS7.swift */; }; - 7EECE9FCF5E07473E6D0FE80BFCB94C9 /* BigInt-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = FB486A8F96DF68360671507371DA8BDB /* BigInt-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 8039DF4C1AE7378FB41921D22A44AEF7 /* UInt16+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2835A01E0247A5156E927DCA5C1A2A5 /* UInt16+Extension.swift */; }; - 8071BF845736086C92F8A1205859AFA8 /* num_gmp_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 749DDD6C8309DAD6BBCF7410355CB4D3 /* num_gmp_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 818A0A10A4D1B841846F05457AB3F3F0 /* Data+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9A42A5D1E2D850B1F7F8E8F6F7F7188 /* Data+Extension.swift */; }; - 8214F77DF0A13B64C70D1AFE1467B169 /* ecmult_const_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = A9C317513ED6A8C8924B31F5F8E6FB58 /* ecmult_const_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 83C23054E1B9A6DF1663F730478D608B /* Web3+Methods.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5EDA937DD9FF68A701B5FB8C2C6E2991 /* Web3+Methods.swift */; }; - 84CD5D70E2922378C0ECE1373D1633C4 /* Promise+Web3+Eth+GetBalance.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0FD9289C7B8FFD71A3CDCF3C99B18967 /* Promise+Web3+Eth+GetBalance.swift */; }; - 8532AFAE5B4DE21DCAFB19AB0E4434EB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 93DA1DCA9F62B5CF3199108FB90AF568 /* Foundation.framework */; }; - 854AF7B141389D5512E8E73DF38FEBEA /* BlockMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = AE4102418DE6E7E4CED7680542ACA596 /* BlockMode.swift */; }; - 855818063255040AB02A45C9C0838048 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE7153C49C1795F5BC69C8C58121A921 /* String.swift */; }; - 8573D5547D4AC8CEE69AB545148A72B6 /* CCM.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDF0C91FFEDE03691C23477F55016C10 /* CCM.swift */; }; - 8599E23B2946C6F3F6DA3D63EC82C4A3 /* Words and Bits.swift in Sources */ = {isa = PBXBuildFile; fileRef = F184694494B0B73998E4F10C109A5087 /* Words and Bits.swift */; }; - 88A625D7DE0B008427478A41F87E97CB /* Encodable+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCFEC24438294C64187419C5B2729D05 /* Encodable+Extensions.swift */; }; - 8A02CDD77D0E9F6526C79A7054493D64 /* Web3+MutatingTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF3C134A5177178545920680F7DB264A /* Web3+MutatingTransaction.swift */; }; - 8B3350D96B15B975184C8EE0819F9623 /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16952F2E0ADCB355DC96DB022B63B1B9 /* SSLSecurity.swift */; }; - 8BC9AC20D0E20E6BDB7764930FCBCAE4 /* web3swift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 6DB520E20CDE817BAE8A2B30E91FC879 /* web3swift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 8C05403EC0F455CB86CFD8060C1C5DC2 /* Cryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3467A6DA60C93415C18CAD34E5B58ADD /* Cryptor.swift */; }; - 8D58B7BD460D20FFEC478698F7F52222 /* PKCS7Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AFDF177A0326BCF4BF54E5BAA19ADB3 /* PKCS7Padding.swift */; }; - 8DB55C794C3FD2E43D8CCC550B1AF94B /* Web3+ERC1643.swift in Sources */ = {isa = PBXBuildFile; fileRef = C793B6404EE0B8793B81F5E7CDE85FA0 /* Web3+ERC1643.swift */; }; - 8E5D0FE361952FD38109FF9A30E48752 /* field.h in Headers */ = {isa = PBXBuildFile; fileRef = 0D10FB3C6D3EF1393133CA34261D1B70 /* field.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 8ED7D4847260B4F398ECF4351280AB31 /* Digest.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE9A11071391F38D682BE1F3CC599D97 /* Digest.swift */; }; - 8EF954AAF4CA9B832FF21DAF4B962F46 /* Web3+ERC721.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B7B8BE2B958EF73B7920669D0A6165E /* Web3+ERC721.swift */; }; - 90545D61932E0A667E3AFC17E5594116 /* field_5x52_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 9BB35F4C313D91EE8AFBFA7D34E85B04 /* field_5x52_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 91A59A657AB2118D4FFFC913EAD87EC9 /* BatchedCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26E93968E466D33AED110C6354F60201 /* BatchedCollection.swift */; }; - 91AB404500559BAB19421D2B8CF13CAD /* KeystoreManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE9D82014458E89E6539B74D54A41391 /* KeystoreManager.swift */; }; - 9447BD0FB408B2A7C9BFDFF99BBE1EBE /* UIViewController+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = D7C6C331D727E9B470A6449D98B0F0FC /* UIViewController+AnyPromise.m */; }; - 958258232333A86232628AE1C3DBD69F /* scalar_low.h in Headers */ = {isa = PBXBuildFile; fileRef = 100310643E25D378253348B194F083D1 /* scalar_low.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 95A14745491525816393D954F72FC9BD /* scalar_8x32_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = C547686949AD5C067704A7A6C2A068BE /* scalar_8x32_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 95C8E48FF5AF28FFD8F6C3612447D238 /* Data+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = D222E59F523707BFCD3EBD7E857537C6 /* Data+Extension.swift */; }; - 95CBDAE64A9D521D5122CF592CE78744 /* web3swift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1C5B04A9867B38C1C1A41A67D56372C9 /* web3swift.framework */; }; - 95DB083F6029B95881E389992A82565E /* Promise+Web3+Eth+GetTransactionReceipt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14BE8AE7EA4C25E7A07F8C1C54461A52 /* Promise+Web3+Eth+GetTransactionReceipt.swift */; }; - 968B5CC9B9B0A7E92FACEEBEA3C0DA13 /* PromiseKit-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 80EDBAF33DE530B669F36DB988B3F7D4 /* PromiseKit-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 9723687056497A67C00ECCB2D77BBF44 /* NameHash.swift in Sources */ = {isa = PBXBuildFile; fileRef = FC6C7738B7BEA2A7AEE22DCE0FCF8F3F /* NameHash.swift */; }; - 98ADDD9D6F83BBC98DB001AF4857E9A3 /* NonceMiddleware.swift in Sources */ = {isa = PBXBuildFile; fileRef = AED6B05BDFA0F12F0E5B61393689B89B /* NonceMiddleware.swift */; }; - 997870D5F490326F024B4D8687FF18DC /* Resolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA9CBD83FD7987D94630D1C21A5709ED /* Resolver.swift */; }; - 99EE8A649068210DF711EA2FFBE1C3BF /* PBKDF2.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8B766BB142215E16DA4BD1E055A6DC1 /* PBKDF2.swift */; }; - 99F35D362CDAA3F01D59E05FAB02907D /* Strideable.swift in Sources */ = {isa = PBXBuildFile; fileRef = E85769E3AFFF9C65DAB6FE5D344B5E33 /* Strideable.swift */; }; - 9A80311C79CED9486D2E9FA4DEC3D45A /* StreamDecryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99D17C88D422705B026AAE3CB31EA369 /* StreamDecryptor.swift */; }; - 9B21076A76E97F640E952E7B129AAD7A /* Promise+HttpProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7849FB52B2A2A77E6E9988F206012FF /* Promise+HttpProvider.swift */; }; - 9B65647B927085E2366117D59DC1586D /* CustomStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00B4A1544453A6ED5BD2446D6CAE4A12 /* CustomStringConvertible.swift */; }; - 9B91881DDB3AB10DFB528A0C66F4B9E3 /* ecdh_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 44F01E43FBF03BD38D6D6F7AE02BEB9C /* ecdh_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - 9BBD5BF22F94C3FA1DBD161E18992FEC /* ABIParameterTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55AF878927A572E76B0E6A029A8505D3 /* ABIParameterTypes.swift */; }; - 9BFE70DD7ECA3C6183B82DE691FE4491 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECDEAD373131E976FC9A426507249B78 /* Box.swift */; }; - 9D22006C799C6F6E9452B97B760F7CD1 /* UInt64+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 736C7B0AB9E592CCF99B60A020F609C4 /* UInt64+Extension.swift */; }; - 9F385EB89EED043C900452A3BA9FC0D3 /* AbstractKeystore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15B3D07F707B020B4A06817C46F852E3 /* AbstractKeystore.swift */; }; - 9F96D351A8225DDC4D57740307E8EB30 /* ABI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 29998CFB49DFB2CA39D28E60FC7607CD /* ABI.swift */; }; - 9FEB740EDA57EC914F073B89EF3A5902 /* num.h in Headers */ = {isa = PBXBuildFile; fileRef = 46D25574FD61890717200D7A5ECA5244 /* num.h */; settings = {ATTRIBUTES = (Project, ); }; }; - A0DC1D0C81DBA577E20484ACF7DE9CF2 /* field_5x52.h in Headers */ = {isa = PBXBuildFile; fileRef = 3311A7DB3CE6CA76C4B56C03CFA175A1 /* field_5x52.h */; settings = {ATTRIBUTES = (Project, ); }; }; - A1DD10F57D1D429E4897EBEB75043E71 /* ethereumNetwork.swift in Sources */ = {isa = PBXBuildFile; fileRef = E581299139437BE8AF562F501F03C4AB /* ethereumNetwork.swift */; }; - A1E6C35C5B3ECB558FE1AF9B1FAAB53B /* AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = F6325783586F8C962155E191969A643C /* AnyPromise.m */; }; - A287E1A244C84D2C5A301B3A897F0787 /* Promise+Web3+Contract+GetIndexedEvents.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAC31B8DC645DD739D2550D2520A8253 /* Promise+Web3+Contract+GetIndexedEvents.swift */; }; - A32C099C519A1F0E8739B010BC8B38F0 /* Base58.swift in Sources */ = {isa = PBXBuildFile; fileRef = 394B571CD3DA252BF198EDE8DBD75729 /* Base58.swift */; }; - A3486EA68E3FC1B1FCD0865841CC4333 /* abi.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B1BE46004B0E262840E88B6B4316CEF /* abi.swift */; }; - A3B3B08F5E6C2AA6356FD7145F442858 /* SECP256k1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26062370F3F43B0CCD0DB727059493EC /* SECP256k1.swift */; }; - A3B7DA364283BD761ECB3A8116F81298 /* ABIParsing.swift in Sources */ = {isa = PBXBuildFile; fileRef = C81F263315CE868909527F13C8B601CA /* ABIParsing.swift */; }; - A3EBB1CCF2E5716F98B66439C31F31A2 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C9026A1A42B2C5EC3F4055F65D29F50 /* Error.swift */; }; - A5F5D7A20264221D4A7F489FB0060D34 /* afterlife.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B3B1825555DBF0206F9CEE6071AD20E /* afterlife.swift */; }; - A626B96EC7D7689ABE43C6DAE9B0CCB1 /* Web3+Options.swift in Sources */ = {isa = PBXBuildFile; fileRef = EE0340F448C109ACD9C1CCAD62F38283 /* Web3+Options.swift */; }; - A65BC55FFE138090EF77D9EC1F72A88B /* HKDF.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3F19A59C557ADA87DA85B082C792879 /* HKDF.swift */; }; - A80957DA592E1405E3352F073FA2C309 /* Encodable+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62A74443599E879E0E975121A027F655 /* Encodable+Extensions.swift */; }; - A93275D5C1DAD3CA7CCC2A9586AC9ADE /* AEAD.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68F29EE2740CD5F7D9F2742ACB0C68AC /* AEAD.swift */; }; - AAA648FE58CC4A49EF39BFDBCBA7C1FA /* PBKDF1.swift in Sources */ = {isa = PBXBuildFile; fileRef = F9A2F264946D78178A080F59A13179EE /* PBKDF1.swift */; }; - AB5121F3168D67D98548D1716917044C /* EthereumTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BAEE36B30C5FB7510EFE984E167F4C8 /* EthereumTransaction.swift */; }; - ABD6C819D2E3692C97351FAF2FB647F9 /* ABIElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 013F4DECB84F1398372538F6B5122028 /* ABIElements.swift */; }; - ABF5E5F45D270B8B7CE386D4BB8E614D /* Int+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAF16D4E2084BD41DAE5259DAB8FB662 /* Int+Extension.swift */; }; - AC4E061C6A2D21210122B471D8BCC81E /* Random.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28336DCCBEBDD902BCD17311A29807FC /* Random.swift */; }; - AC7DBF3AD44B3E7644068E6F09F9EBF2 /* BigUInt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 929A382CB9CC2554AB704DB58025119C /* BigUInt.swift */; }; - ADE26A6317E68C1CB7FC86D68B4EB8BF /* RandomBytesSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = C59FBCFF1F570E941E9FE5F8C78723AB /* RandomBytesSequence.swift */; }; - AE242F808DE761641CF108E8844745D6 /* Cipher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 37E49D3B34BDED405190E64976AE77B2 /* Cipher.swift */; }; - AE49720A728B0152AD532A1B94A16D32 /* Web3+TxPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A09CDC8DE8F23E69BFDFE003EFCFBB8 /* Web3+TxPool.swift */; }; - AF813D5EF055223C9D676862A88E83EC /* ecmult_gen.h in Headers */ = {isa = PBXBuildFile; fileRef = DE689BD3F8DF79153838FEB2BE1E2348 /* ecmult_gen.h */; settings = {ATTRIBUTES = (Project, ); }; }; - B15E0CD8A2E6D29E9849F092CD078773 /* GCM.swift in Sources */ = {isa = PBXBuildFile; fileRef = E00279CE0936ACEEEBC44C2574B16DC7 /* GCM.swift */; }; - B1A16E15906745982091B5B83E707F8A /* Web3+Eth+Websocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3A9281D74A2B5E87D9CF6464C7066F6 /* Web3+Eth+Websocket.swift */; }; - B202FAAE49238B713536A1BA965EE05E /* EventFiltering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 106ED3C331045B72BCD8F2EBED8DEEEB /* EventFiltering.swift */; }; - B454FD1963E4ABBCABBAF87B653A675C /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86B7A860A95575E515952D768A8DF41C /* Extensions.swift */; }; - B4733F9C8DFFA3F09BD8772F6FB1F4ED /* secp256k1.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 107AEC95463B537BD9F7623284A1BDA7 /* secp256k1.framework */; }; - B49A87F0F8FBA70623BE46585311B343 /* BigUInt+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCF0C2B61C0E69C47E9851BA327B091D /* BigUInt+Extensions.swift */; }; - B4A6283FDFA04E3A7B6FD0C13B6FEF32 /* Starscream-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 8F2AFB6AD39C5E71058F032B2081D300 /* Starscream-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - B4E0F6805D68577613B95A18651FC167 /* Blowfish.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17FBF1870F76BBA85154777D12F92DD0 /* Blowfish.swift */; }; - B593B56495A204E756BAA753BA2D6E9C /* Deprecations.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4B962A49197959211418558342805EE /* Deprecations.swift */; }; - B68D596196CB33B19ABFC17CD0583B9A /* Web3+ReadingTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = AE80079DF00F0A5DEDAAAD710234F15A /* Web3+ReadingTransaction.swift */; }; - B695FB618AFBED4E2FB35139D4073A45 /* Web3+Contract.swift in Sources */ = {isa = PBXBuildFile; fileRef = C43626EDF665B4B69437F35D9138008F /* Web3+Contract.swift */; }; - B74B5EEA58E2923AD043F773FB9E7A1F /* scratch_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 0DF19828A60D0F07C54CF9F4EBF91996 /* scratch_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - B758241FBF6592EFBE6283378D16F9FD /* NSObject+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 66FBE58D0DE5590C2C0843EF48B824BF /* NSObject+Promise.swift */; }; - B7CBF8311A63CA00B39F9FF2D35B6390 /* TorusUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD6FC58247337A77A51732D694282647 /* TorusUtils.swift */; }; - B93F56B6778CCE0FEF087E13CB6DABDD /* eckey.h in Headers */ = {isa = PBXBuildFile; fileRef = 60C1AAE2EB5DABD8D89F4408AB5E3F08 /* eckey.h */; settings = {ATTRIBUTES = (Project, ); }; }; - BA0B0E473CAF77498DBF253B48C05EC8 /* CryptoExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6082721A37AB0726E7E2B183208F595E /* CryptoExtensions.swift */; }; - BA73CEF44001DF2292AC6FBA94E2996F /* EthereumFilterEncodingExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98043C01CB253479FAA51D0483638C79 /* EthereumFilterEncodingExtensions.swift */; }; - BAA052C302D45F8DAB72606E997CAD69 /* Subtraction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 493D56F05A52E5B4339485C92C6232F6 /* Subtraction.swift */; }; - BC4EF03F29F068EEB3CDB41FA39CF2C8 /* EIP67Code.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1EDD544B32FC12296D15FFDB8DB3CEEC /* EIP67Code.swift */; }; - BC8D548C4074AB6CBE46B40918B555A6 /* secp256k1_ec_mult_static_context.h in Headers */ = {isa = PBXBuildFile; fileRef = 2232E13ECA21F9463469D2356DD59817 /* secp256k1_ec_mult_static_context.h */; settings = {ATTRIBUTES = (Project, ); }; }; - BDE43A3AB8E927087E4E8765C6D2B2E1 /* util.h in Headers */ = {isa = PBXBuildFile; fileRef = 0A289037323484D2BB6891F50AC0966C /* util.h */; settings = {ATTRIBUTES = (Project, ); }; }; - BE29AFA73FEDAFA471F35F8AB1C3EA99 /* Shifts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 958577E37A0C6899FA8F40D1ECF43198 /* Shifts.swift */; }; - BE7AB9F4BA1330BF6148611506DA8735 /* Torus-utils-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = D8633CD3434757180B44615D96BDA870 /* Torus-utils-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - BEFDEE737D0E3E1D1CFB9D7925893D22 /* Web3+InfuraProviders.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7837B720C51246FB222DAFBB154A7EFD /* Web3+InfuraProviders.swift */; }; - BF33883B6C96B31DE4692BFD912ACF82 /* Decodable+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = D24EA038E3E35A59264E498AA94ECB87 /* Decodable+Extensions.swift */; }; - BFBBBF490B164BD2F4D95CEE74E8A1EF /* Promise+Web3+Personal+Sign.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87266A5B0B28E9E194A437D7509E8113 /* Promise+Web3+Personal+Sign.swift */; }; - C004AE6E4897816A1BF56255234CCFE6 /* ENS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 910707A9E3436E68FCDF05631CA0B2CA /* ENS.swift */; }; - C02D9FEB295BDA1359D2F52C80F8E75A /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB3377F02EA7E24B1239A7648440A236 /* WebSocket.swift */; }; - C05EFD99EA258A792A2B983A1E156F5A /* Web3+ERC165.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BB00E6935E0F6473686F43BA42E47DD /* Web3+ERC165.swift */; }; - C138FACCB027B81AE55814AA990543D5 /* OFB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BF39D2D98FFC5533B5BA217BCDB7AD9 /* OFB.swift */; }; - C17E552920AF110E9DB7AB635C65A12D /* Scrypt.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF9BC92C2E27EE31FB82EBC7672E15CF /* Scrypt.swift */; }; - C1B03B2B30A3FAFFA89B490625A663CB /* secp256k1-config.h in Headers */ = {isa = PBXBuildFile; fileRef = 0296EB918A3A6BC54B0A83486D15B463 /* secp256k1-config.h */; settings = {ATTRIBUTES = (Project, ); }; }; - C29BCDE99B11853F0190C2248562EF7A /* secp256k1.c in Sources */ = {isa = PBXBuildFile; fileRef = 9574BD191822B8CA2B44360C0DAFEE0D /* secp256k1.c */; }; - C426E30A28E2545BCA2824DBCF90816F /* NSNotificationCenter+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = 2DA6191B2FC6B5538F9C1FF662985ED9 /* NSNotificationCenter+AnyPromise.m */; }; - C48EC56BB7C14ABC19E3BA2ACD91F6A9 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 93DA1DCA9F62B5CF3199108FB90AF568 /* Foundation.framework */; }; - C5AAECAB4C5679728CF2D7AAF3D689D8 /* Promise+Web3+Personal+UnlockAccount.swift in Sources */ = {isa = PBXBuildFile; fileRef = CEA6D1C1DD153D88A1AC3CDA4DAA1BBF /* Promise+Web3+Personal+UnlockAccount.swift */; }; - C5EF8FBC11CA9E66100F6489B57E35A6 /* LogEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = B79CB3EFA0565779F964A732017D23F8 /* LogEvent.swift */; }; - C680444C2E2E5076D981C2A8452AC067 /* CFB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7E09DE6376C302F500D47F146994DBCE /* CFB.swift */; }; - C6FC6A13DB02CC3DBBDBC0E0EB8F97A2 /* Web3+HttpProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95588ED1054704883B313B15AF39B29B /* Web3+HttpProvider.swift */; }; - C72C803D5CD5CF33BDC24F328B8AD35E /* Promise+Web3+Eth+GetTransactionCount.swift in Sources */ = {isa = PBXBuildFile; fileRef = 20032C66FBFC8D534B0E014C41B3FC31 /* Promise+Web3+Eth+GetTransactionCount.swift */; }; - C7ECF714064C1188A6D042C6ACFD9504 /* dispatch_promise.m in Sources */ = {isa = PBXBuildFile; fileRef = 8800939F03C2C23BCFC7AC6D89B3E29A /* dispatch_promise.m */; }; - C829EE08BBA51E4F85528D4D6B4D8DEB /* CTR.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A7C7440F23854147993BEA3BF179B7A /* CTR.swift */; }; - CA5F0FF46E700A877E1ED5C9EF6BDECB /* BlockCipher.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC79DFF5B9C04D7FE20DD358512F0C5E /* BlockCipher.swift */; }; - CA6442060FC70151AF0F4B17DD3B9178 /* Promise+Web3+TxPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 55A212FC43612F76263F35C276405A36 /* Promise+Web3+TxPool.swift */; }; - CABB0902B30DA778305D8821AB2E1F83 /* Starscream.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D602E155ACAA4143210F7BFF844AC1C4 /* Starscream.framework */; }; - CB90B94A89B6991F61E2B64DD331B30A /* nodeDetails.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3509820FD1FC52A8BD603D3560AC9E37 /* nodeDetails.swift */; }; - CBBC28505A75D43175AE463477F019D9 /* Promise+Web3+Eth+GetBlockByNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7E1CE33CE4EC974DADA9A94C05B3949 /* Promise+Web3+Eth+GetBlockByNumber.swift */; }; - CBC5D17000C155FEAFBFBDA26E369DD6 /* Pods-TestApplication-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F35ACAD54CA4C8BA1628EEC5C9C803A /* Pods-TestApplication-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - CC03E31F122F91A26DD22BEEF813D779 /* UInt128.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A0B5C4DD84A6A8B0E535041C9CFF6AE /* UInt128.swift */; }; - CC1C395F714F206E55948FB255DE823C /* RIPEMD160+StackOveflow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33D0155668F1AEAFE580678B049CB98F /* RIPEMD160+StackOveflow.swift */; }; - CC8C5CECDBD51CCA0082D1E4789781B1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 93DA1DCA9F62B5CF3199108FB90AF568 /* Foundation.framework */; }; - CCCF46865AC2CF9EE10BED47E2656C0C /* secp256k1.c-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9A83CE7F4E5E202D7F1C4F4CAFE68D5A /* secp256k1.c-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - CCF4CA4137C1BD997D4EB189DE3CFD23 /* Web3+Protocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 356E6CD41F459A448BB24F82F2CFDBF3 /* Web3+Protocols.swift */; }; - CE6361BC8CD979FE0A5FF9E8CD756D3C /* ABIEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EE4D3F9E080E3BDB6D9D8E58DE55F54 /* ABIEncoding.swift */; }; - CEBCF331C938EE470C11962CDFFD30E1 /* group_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = FFEC637A0E4A6FB4540D200256F65DEE /* group_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - CF7CF7EF1EEDCE7754590741CEE6E55A /* Dictionary+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = A449726AD38C7BCC6A4476FB6FCC57BD /* Dictionary+Extension.swift */; }; - CFDE61D4C8680399EBFEF2861E86A231 /* Promise+Web3+Eth+Call.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFA40A9F7963D95FF63F17BD122257B2 /* Promise+Web3+Eth+Call.swift */; }; - D16C45BC77A0F61CE24F4D5933DCE9AC /* CoreImage.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AD4460059743B10EB585030DEAE55679 /* CoreImage.framework */; }; - D22003E7E728AAB1A58658A0067226E7 /* IBAN.swift in Sources */ = {isa = PBXBuildFile; fileRef = E73B92A342365008203DB7ADFA39818A /* IBAN.swift */; }; - D34F15C1BB10760B46E56479250B2FF8 /* ecmult.h in Headers */ = {isa = PBXBuildFile; fileRef = 8607984D28231447D07695D87FC3465E /* ecmult.h */; settings = {ATTRIBUTES = (Project, ); }; }; - D48A4410A7C8CE6B6A0787A0F4999DE5 /* Multiplication.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC594840B7ACD8661A072BE4D284BAC0 /* Multiplication.swift */; }; - D4C52546E7DEE38CEE04F2B6D61BB9E2 /* fwd.h in Headers */ = {isa = PBXBuildFile; fileRef = F10C8577314FE9669A54B2816A0F88C5 /* fwd.h */; settings = {ATTRIBUTES = (Public, ); }; }; - D650178F82DCCE4B52CFF4ED7A88812C /* CryptoExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F36005F31C0A72C79F5F6570FDF07C5 /* CryptoExtensions.swift */; }; - D65A4FA559A3D7D1F3C578E126B4A955 /* Browser.bundle in Resources */ = {isa = PBXBuildFile; fileRef = 12DC6A0FDF284A2C935F5EA9F6111B0B /* Browser.bundle */; }; - D7AB2759CDCFA67777AFCD910BB7CE27 /* Web3+Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 371A1B4989607A2FE45007122EB5DB1A /* Web3+Utils.swift */; }; - D820172C124F8B10D0C72B31F1819FDC /* String+FoundationExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC681896D4212B9DA6C9384F3344234F /* String+FoundationExtension.swift */; }; - D8BA9690176DD63FEC7F0D85AFC26CC1 /* scalar_low_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = BBE375A431A0CAAD97FE1B50B09ECFBC /* scalar_low_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - D8C90AFD1D666460C3FE007172ED052E /* CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12E4A924E952E7332BA0F49D08661F92 /* CompactMap.swift */; }; - DB0BAF0951B4A5CAB52F37A1D4566F44 /* num_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = ABD51BF16E0DBDE492E7FEEBBEBA6EBA /* num_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - DBCA1194814B520897C3D81C016F51DB /* BlockDecryptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1EDB95C55FE665B44017C14EF40CA8F /* BlockDecryptor.swift */; }; - DBE9A6D9CB82D8605F4C25B9426B1557 /* Codable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9645F90AD29640672EB3F4C6306E2CA8 /* Codable.swift */; }; - DBEF0F49E57B3321CC7067EEF33AB582 /* NSNotificationCenter+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 07C576511994B0486926E0C9AF187971 /* NSNotificationCenter+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - DBF232C5CC6FB8EDF32D69E0FF8A50BD /* BestLogger-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F838B5783FF850387FCD0760324B7F31 /* BestLogger-dummy.m */; }; - DC7E37950268DD0C5106737A12086DB4 /* ENSRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FCCD54F9BF290744B30BD7C76B31F60 /* ENSRegistry.swift */; }; - DD7CAA2463A742FC740431ED674892FD /* ChaCha20.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A71430DAF19B7345290774BF3DF061A /* ChaCha20.swift */; }; - DE14FDEEE8418BB914CE507B8099E589 /* ENSResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40F19205E66DD1450EFD8E3E2032957B /* ENSResolver.swift */; }; - E0067342787B93C845546321EF1DC7D8 /* AES.Cryptors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33814A070AAF84C7E6D9C47D4A9DA47A /* AES.Cryptors.swift */; }; - E0B84D75D0F7E7EA2E905C05774CC361 /* Integer Conversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF8387102D69B2377094DD61EC92FEDB /* Integer Conversion.swift */; }; - E277A99D7950D81D1B80AFA4171E61ED /* Promise+Web3+Eth+GetBlockByHash.swift in Sources */ = {isa = PBXBuildFile; fileRef = 895FA234293490054981FB4B1FF1A2A0 /* Promise+Web3+Eth+GetBlockByHash.swift */; }; - E402E7140E9A2FF8C9D0E14AA2D72ED9 /* field_10x26_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 54E2DF0C1A7123CBD20FD3B19C8EDF57 /* field_10x26_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - E425FBEC27FF20E38E5F71856145D72C /* UIViewController+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = 458A8AB2661A57F37E4E70311F75F5FE /* UIViewController+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - E43D7ED7482761C992D3E42B32D606A6 /* abi.json in Sources */ = {isa = PBXBuildFile; fileRef = BB147247ABF7F4DAFD652DD4A718F13F /* abi.json */; }; - E763CD8F8813167D15632AF5042B88A3 /* group.h in Headers */ = {isa = PBXBuildFile; fileRef = F57CB5EBA08457BE3A768B4A2D7998B4 /* group.h */; settings = {ATTRIBUTES = (Project, ); }; }; - E7A03A06824777BBCFD78A0EDF2C016C /* BigInt.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 975A89B5D0199DE1636D45DA30498CA6 /* BigInt.framework */; }; - E8ABBB87CFEBE721FC2D14B71A719BC2 /* String Conversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54255A778D9AA0DB0A5D3A32AA4B0276 /* String Conversion.swift */; }; - E9342EFD486C4DE0C3B6E72379D3BE13 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 93DA1DCA9F62B5CF3199108FB90AF568 /* Foundation.framework */; }; - E93CF504980B3D653BB4530E7F98E9F6 /* Prime Test.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86E812F60C2C434B4835413EBC00BE04 /* Prime Test.swift */; }; - EA95317C04FA46F08399A9F6DFE82119 /* Blowfish+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF2A784B822F1600850625C29FB9C104 /* Blowfish+Foundation.swift */; }; - EAC994EA457048CA6AA49B82C9F05DF4 /* NSURLSession+AnyPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = D69C06C96418E899C7F19C5ED2930255 /* NSURLSession+AnyPromise.h */; settings = {ATTRIBUTES = (Public, ); }; }; - EB0450140F0DE8EC373CE3173F9CD9AF /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 93DA1DCA9F62B5CF3199108FB90AF568 /* Foundation.framework */; }; - EB75901A5DCC720A5AEC6BA4B6369B86 /* Promise+Web3+Eth+SendTransaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F595E5162AE7A4525F876A2F65D7767 /* Promise+Web3+Eth+SendTransaction.swift */; }; - EC1F98C6E1424F6190176058FAA43C5A /* UInt8+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = F050DD99A94F00775D165DCE83830FF4 /* UInt8+Extension.swift */; }; - ED4ED80104798E648B2B82A10DA586F1 /* HMAC+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84B27F6051F06DF5A4E6F7214D0B0BF3 /* HMAC+Foundation.swift */; }; - EF8241DFA90BCDBB97B8C504BB80D05C /* AnyPromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0BBF0C44022F9BD5C7E2A44A669C5B /* AnyPromise.swift */; }; - EF9BBCE851B820D4F5DA3163BF466A38 /* Process+Promise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 627F7A45BFD915D896B8B858F59427E9 /* Process+Promise.swift */; }; - F13925E2206A7647AC326ECFA6ED2856 /* GCD.swift in Sources */ = {isa = PBXBuildFile; fileRef = A57FA60848C2DC82A2D474D2DE260055 /* GCD.swift */; }; - F1A6525CB04998529CBCAC5BCEE57878 /* ABIDecoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1E0D2E2DA2F63AF7BDEFD1902EC933E5 /* ABIDecoding.swift */; }; - F2438C9C6471ED878FD9FD686421CBC3 /* Web3ERROR.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16D7F4711610137560DC47C298FA7A92 /* Web3ERROR.swift */; }; - F2F06D9CD7A942F7EEC6426CC2F1A794 /* scalar_4x64_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = CF6609F1E57DECC7C1DA6D137C3DA0A5 /* scalar_4x64_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - F318FAB73E570060E66B089513A58F7F /* nodeInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4A09751392B322E31DEAC69C3FE848F /* nodeInfo.swift */; }; - F3B9FF17CD827482C5FCDE987FCBA026 /* SHA1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A8C1DF42DDB1B2C7A3407B3FC998671 /* SHA1.swift */; }; - F44208FA90F7B7118E5A3CA21AB37A84 /* PKCS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = E420C52E00AB438D30BF7A43B76F93C2 /* PKCS5.swift */; }; - F4A5AED589CFC8C527E096E52CFE1C14 /* Torus-fetchNodeDetails-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 7E9C126C1E762F5A9CBB417F5BEDC4BA /* Torus-fetchNodeDetails-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - F4A8CF610DFE908313068A1B3C909854 /* Web3+ERC20.swift in Sources */ = {isa = PBXBuildFile; fileRef = 394CB452CF5827603CAB1A624E0DB36B /* Web3+ERC20.swift */; }; - F4DB8BAA8CC2482A2F0408BB78DC5636 /* Array+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB1204BA343D2E4FE433DF065E5739C8 /* Array+Extension.swift */; }; - F4EB4FFB5BFE253769101209CBD7BA13 /* ChaCha20+Foundation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 917B6EFF40524BB04100155BBFBA26F5 /* ChaCha20+Foundation.swift */; }; - F5655B01E4FFFA3F21CB0B12807A55C3 /* field_10x26.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FCE859A1C898EFD329CC8D11538DEA6 /* field_10x26.h */; settings = {ATTRIBUTES = (Project, ); }; }; - F6490DA2E9325384B1F7AEA92E477065 /* Pods-TestApplication-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9480EC5419F2059D80BD085B2DBF2323 /* Pods-TestApplication-dummy.m */; }; - F71E1C98CAB16FE66EDE761BB1C50F0A /* KeystoreV3JSONStructure.swift in Sources */ = {isa = PBXBuildFile; fileRef = DF3DFD6E474AAF0850E29CF9CE9A81D0 /* KeystoreV3JSONStructure.swift */; }; - F7B35CF494CCC4BFFD950D55B0609D2E /* Web3+WebsocketProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECCDACE97518A2B351C94A17D61D9C02 /* Web3+WebsocketProvider.swift */; }; - F85DFBE8857FCD8AB07C888A5C3DBBCA /* CryptoSwift.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C9493E9FCDA044080B2F1FD5E08DABA8 /* CryptoSwift.framework */; }; - F934C45EC70FF710ACC02400EB9B7159 /* BloomFilter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C399168B633166C7713975ED1A8F8B6 /* BloomFilter.swift */; }; - FB797FAA96B41ACE7474B8ADEF8107EC /* firstly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C956D6C93CE03F2CDC414E5EAC7F680 /* firstly.swift */; }; - FC30CC6BA8A2FA705C8300DD21012638 /* recovery_impl.h in Headers */ = {isa = PBXBuildFile; fileRef = 6E7A807E2744EF86C0208B7213A91F86 /* recovery_impl.h */; settings = {ATTRIBUTES = (Project, ); }; }; - FC380F439D913681D738F1BE7B739646 /* ZeroPadding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 343893B600C18CE40D9AB491CBE66E9B /* ZeroPadding.swift */; }; - FDE029DAFA820243AF70BF9D73569E1E /* scalar.h in Headers */ = {isa = PBXBuildFile; fileRef = 24D977E748EAED64A5418C6749B97C72 /* scalar.h */; settings = {ATTRIBUTES = (Project, ); }; }; - FDF12428281F08B3F5F2B7DB68E3925D /* NSTask+AnyPromise.m in Sources */ = {isa = PBXBuildFile; fileRef = A9A22D3ECB8CA971A45DBDF492F36ACB /* NSTask+AnyPromise.m */; }; - FE0D3AEBDA7E74DCB8F81D86A89127B4 /* BestLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60E1AD875946CE4A244B1EC878A90E0B /* BestLogger.swift */; }; - FE2685F4B1138D722007167CC42F6902 /* Promise+Web3+Personal+CreateAccount.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12F5212F39D5EBDBC1CC6EC843E38E30 /* Promise+Web3+Personal+CreateAccount.swift */; }; - FE5D81875AA74482B69274A57F371827 /* Web3+BrowserFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EEFC3B86751C2FA06B78C50AC203259 /* Web3+BrowserFunctions.swift */; }; - FED8C9BB577D35DBB6E5347B750C184C /* hang.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC767EA373C6A47D8C0E5B877E98F1BF /* hang.swift */; }; - FFF7E224F5F3094210837EC8C7FE4960 /* BigInt-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 54C9D3822228221ABF33D464A3046A0B /* BigInt-dummy.m */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 035A966A9251F66DFE7DD464FC309D75 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 09DD83B7D075842A3A5105AD410BD38A; - remoteInfo = BigInt; - }; - 0C4B2D2C752AC66EEA4CEBB97824655F /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 161C26511FC920CB146236AB7295D5E0; - remoteInfo = secp256k1.c; - }; - 0CA171B90CCA0AD442DA0EDA2CADD751 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 7C579CE66A1E7A9AA33CA5F97F9C22C5; - remoteInfo = PromiseKit; - }; - 325D87D58EA705B8FD080AF609E0C3A9 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 1365165D183E4C35E57FE0E71450F0E2; - remoteInfo = BestLogger; - }; - 48EBA5DD88ACF312C19C165273C50965 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 3744C58A953D980BCF08B0FEAE449C91; - remoteInfo = "Torus-fetchNodeDetails"; - }; - 4E62C4E8A6EAE64384F464A55A70CEE5 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 7C579CE66A1E7A9AA33CA5F97F9C22C5; - remoteInfo = PromiseKit; - }; - 508710B1FFBAB260097ABE53A2181700 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; - remoteInfo = Starscream; - }; - 69FB91E6200FFE4E68C43C1194167D6B /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 09DD83B7D075842A3A5105AD410BD38A; - remoteInfo = BigInt; - }; - 74F6A47B6FFEDA0173E19BF5107FEA09 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; - remoteInfo = Starscream; - }; - 77FFB9A136F68B001BEB687B18FF6BE2 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 161C26511FC920CB146236AB7295D5E0; - remoteInfo = secp256k1.c; - }; - 7E45002E076C7B22DEAE0884030C971B /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; - remoteInfo = Starscream; - }; - 809E52C9C40695AA4C26379173922C09 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 50BD5410DB90F893AE68CE9925FD066E; - remoteInfo = "Torus-utils"; - }; - 8429E728150E527A1DD3A7DE71BA9829 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 8CDD759A6130CA265C6D157F4407C39B; - remoteInfo = "web3swift-Browser"; - }; - 84CD5A070282E25C00A6BD279B641C2B /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 161C26511FC920CB146236AB7295D5E0; - remoteInfo = secp256k1.c; - }; - 8C54AFFF3813705D5075D1A9A479DE3D /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 99313990C1D76A6D1D017868B6975CC8; - remoteInfo = CryptoSwift; - }; - 8DE8A0BACD14578177A63553CF8E2D9F /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 3744C58A953D980BCF08B0FEAE449C91; - remoteInfo = "Torus-fetchNodeDetails"; - }; - 930F0EED1326004036B24C1EB3C4D8E3 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 3744C58A953D980BCF08B0FEAE449C91; - remoteInfo = "Torus-fetchNodeDetails"; - }; - 997F37EC00CC81D87F0407AC7B1AFE24 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 7C579CE66A1E7A9AA33CA5F97F9C22C5; - remoteInfo = PromiseKit; - }; - A88B3C305EDB7145219C050901B264A8 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 7C579CE66A1E7A9AA33CA5F97F9C22C5; - remoteInfo = PromiseKit; - }; - B11F4D5EFFE97A6716B50AFBE2C62F67 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 99364D9FB07EF3FA5DFE1237001805EC; - remoteInfo = web3swift; - }; - C4A1F0D626FC4F33F5A7033E0B5C9CE4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 99313990C1D76A6D1D017868B6975CC8; - remoteInfo = CryptoSwift; - }; - D6032235584FDF4785D50A688D7284E2 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 99313990C1D76A6D1D017868B6975CC8; - remoteInfo = CryptoSwift; - }; - DDBA525B2C029F42CEA3CE860AC43A05 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 09DD83B7D075842A3A5105AD410BD38A; - remoteInfo = BigInt; - }; - DFCBFCC4F61508638E33B0D5ECA30632 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 99364D9FB07EF3FA5DFE1237001805EC; - remoteInfo = web3swift; - }; - DFF19C21652CDF589A3CC5013929D8A6 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 1365165D183E4C35E57FE0E71450F0E2; - remoteInfo = BestLogger; - }; - E063E5B763FEEDE4C4DEF58E2CFEA48C /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 50BD5410DB90F893AE68CE9925FD066E; - remoteInfo = "Torus-utils"; - }; - E3686186A0CBB35F6BCAC97C00316D4D /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 99364D9FB07EF3FA5DFE1237001805EC; - remoteInfo = web3swift; - }; - F411C2769E42AACB71CAA1EC456A3075 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 1365165D183E4C35E57FE0E71450F0E2; - remoteInfo = BestLogger; - }; - FD72BE9CCE1A40865017FFC0CD11C34D /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 1365165D183E4C35E57FE0E71450F0E2; - remoteInfo = BestLogger; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXFileReference section */ - 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = PromiseKit.framework; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 00B4A1544453A6ED5BD2446D6CAE4A12 /* CustomStringConvertible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CustomStringConvertible.swift; path = Sources/CustomStringConvertible.swift; sourceTree = ""; }; - 013F4DECB84F1398372538F6B5122028 /* ABIElements.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIElements.swift; path = Sources/web3swift/EthereumABI/ABIElements.swift; sourceTree = ""; }; - 0247C8EEE7B4D5D0983AAC08DC69FF1B /* BIP39.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BIP39.swift; path = Sources/web3swift/KeystoreManager/BIP39.swift; sourceTree = ""; }; - 0296EB918A3A6BC54B0A83486D15B463 /* secp256k1-config.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "secp256k1-config.h"; path = "secp256k1/secp256k1-config.h"; sourceTree = ""; }; - 02A8B3CDF2934BC18CF61B46AEDBB749 /* Torus-utils-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Torus-utils-Info.plist"; sourceTree = ""; }; - 0457C62F928892E60662C7AFEB6B2EE7 /* NSRegularExpressionExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NSRegularExpressionExtension.swift; path = Sources/web3swift/Convenience/NSRegularExpressionExtension.swift; sourceTree = ""; }; - 0572A9443DE659BEF362369E4A6F2BC6 /* web3swift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "web3swift-Info.plist"; sourceTree = ""; }; - 0658C457030E48C8199E56F034689824 /* Torus-utils.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Torus-utils.debug.xcconfig"; sourceTree = ""; }; - 07C576511994B0486926E0C9AF187971 /* NSNotificationCenter+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSNotificationCenter+AnyPromise.h"; path = "Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h"; sourceTree = ""; }; - 08859518C8A8BA3027D2209AEDBC64AC /* Utils.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Utils.swift; path = Sources/CryptoSwift/Utils.swift; sourceTree = ""; }; - 09954F8AE56A9731301D95657001486A /* Web3+ERC888.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC888.swift"; path = "Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift"; sourceTree = ""; }; - 0A09CDC8DE8F23E69BFDFE003EFCFBB8 /* Web3+TxPool.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+TxPool.swift"; path = "Sources/web3swift/Web3/Web3+TxPool.swift"; sourceTree = ""; }; - 0A289037323484D2BB6891F50AC0966C /* util.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = util.h; path = secp256k1/util.h; sourceTree = ""; }; - 0ACE6FCC5FCCB682084B1E58B8DEB240 /* PublicKey.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublicKey.swift; path = Sources/web3swift/Utils/ENS/PublicKey.swift; sourceTree = ""; }; - 0AE7A1D74F6EEDB965C2CFF1D9C301F5 /* wk.bridge.min.js */ = {isa = PBXFileReference; includeInIndex = 1; name = wk.bridge.min.js; path = Sources/web3swift/Browser/wk.bridge.min.js; sourceTree = ""; }; - 0B00928391D9D697250F52FE2928539E /* Web3+JSONRPC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+JSONRPC.swift"; path = "Sources/web3swift/Web3/Web3+JSONRPC.swift"; sourceTree = ""; }; - 0B27B50B07301DC15A482B96A4F84F6A /* NSRegularExpressionExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NSRegularExpressionExtension.swift; sourceTree = ""; }; - 0B3B1825555DBF0206F9CEE6071AD20E /* afterlife.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = afterlife.swift; path = Extensions/Foundation/Sources/afterlife.swift; sourceTree = ""; }; - 0BF39D2D98FFC5533B5BA217BCDB7AD9 /* OFB.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OFB.swift; path = Sources/CryptoSwift/BlockMode/OFB.swift; sourceTree = ""; }; - 0D10FB3C6D3EF1393133CA34261D1B70 /* field.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field.h; path = secp256k1/field.h; sourceTree = ""; }; - 0DF19828A60D0F07C54CF9F4EBF91996 /* scratch_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scratch_impl.h; path = secp256k1/scratch_impl.h; sourceTree = ""; }; - 0EE4D3F9E080E3BDB6D9D8E58DE55F54 /* ABIEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIEncoding.swift; path = Sources/web3swift/EthereumABI/ABIEncoding.swift; sourceTree = ""; }; - 0EEFC3B86751C2FA06B78C50AC203259 /* Web3+BrowserFunctions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+BrowserFunctions.swift"; path = "Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift"; sourceTree = ""; }; - 0FB42BBCB8503EAD2C9CB5548BD0EEEF /* AES+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "AES+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/AES+Foundation.swift"; sourceTree = ""; }; - 0FCE859A1C898EFD329CC8D11538DEA6 /* field_10x26.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_10x26.h; path = secp256k1/field_10x26.h; sourceTree = ""; }; - 0FD9289C7B8FFD71A3CDCF3C99B18967 /* 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 = ""; }; - 100310643E25D378253348B194F083D1 /* scalar_low.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_low.h; path = secp256k1/scalar_low.h; sourceTree = ""; }; - 106ED3C331045B72BCD8F2EBED8DEEEB /* EventFiltering.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EventFiltering.swift; path = Sources/web3swift/Contract/EventFiltering.swift; sourceTree = ""; }; - 107AEC95463B537BD9F7623284A1BDA7 /* secp256k1.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = secp256k1.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 11B2495717C3300B60C1D01F85E169CD /* NoPadding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NoPadding.swift; path = Sources/CryptoSwift/NoPadding.swift; sourceTree = ""; }; - 1225388F468617B747120B6063E2688D /* FetchNodeDetails.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = FetchNodeDetails.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 1266EFA379D86490C2F8DE7D3FD4F149 /* NSTask+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSTask+AnyPromise.h"; path = "Extensions/Foundation/Sources/NSTask+AnyPromise.h"; sourceTree = ""; }; - 12DC6A0FDF284A2C935F5EA9F6111B0B /* Browser.bundle */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; name = Browser.bundle; path = "web3swift-Browser.bundle"; sourceTree = BUILT_PRODUCTS_DIR; }; - 12E4A924E952E7332BA0F49D08661F92 /* CompactMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompactMap.swift; path = Sources/CryptoSwift/CompactMap.swift; sourceTree = ""; }; - 12F5212F39D5EBDBC1CC6EC843E38E30 /* 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 = ""; }; - 137378E4AD849849095296939E1F272F /* race.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = race.m; path = Sources/race.m; sourceTree = ""; }; - 1464B14DC813EA19C660522609E95C34 /* AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AnyPromise.h; path = Sources/AnyPromise.h; sourceTree = ""; }; - 14BE8AE7EA4C25E7A07F8C1C54461A52 /* 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 = ""; }; - 14D268E0C6A9A8606B2F5F1A263791A3 /* secp256k1.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = secp256k1.h; path = secp256k1/include/secp256k1.h; sourceTree = ""; }; - 15B3D07F707B020B4A06817C46F852E3 /* AbstractKeystore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AbstractKeystore.swift; path = Sources/web3swift/KeystoreManager/AbstractKeystore.swift; sourceTree = ""; }; - 16952F2E0ADCB355DC96DB022B63B1B9 /* SSLSecurity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SSLSecurity.swift; path = Sources/Starscream/SSLSecurity.swift; sourceTree = ""; }; - 16D7F4711610137560DC47C298FA7A92 /* Web3ERROR.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Web3ERROR.swift; sourceTree = ""; }; - 1764C73C5A2BAF6D7920A5164D0CD86C /* Pods-TestApplication-TestApplicationTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-TestApplication-TestApplicationTests-frameworks.sh"; sourceTree = ""; }; - 17FBF1870F76BBA85154777D12F92DD0 /* Blowfish.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Blowfish.swift; path = Sources/CryptoSwift/Blowfish.swift; sourceTree = ""; }; - 18ADBE7A86B9A9960F9B87F732421591 /* ENSReverseRegistrar.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENSReverseRegistrar.swift; path = Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift; sourceTree = ""; }; - 1A049A6FF6D386AEB2F79B80D8F58201 /* Starscream-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Starscream-Info.plist"; sourceTree = ""; }; - 1A0B5C4DD84A6A8B0E535041C9CFF6AE /* UInt128.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = UInt128.swift; path = Sources/CryptoSwift/UInt128.swift; sourceTree = ""; }; - 1A8C1DF42DDB1B2C7A3407B3FC998671 /* SHA1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SHA1.swift; path = Sources/CryptoSwift/SHA1.swift; sourceTree = ""; }; - 1B5549F6AF497C5E9C8BD220E77944F1 /* Web3+EventParser.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+EventParser.swift"; path = "Sources/web3swift/Web3/Web3+EventParser.swift"; sourceTree = ""; }; - 1C5B04A9867B38C1C1A41A67D56372C9 /* web3swift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = web3swift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 1E0D2E2DA2F63AF7BDEFD1902EC933E5 /* ABIDecoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIDecoding.swift; path = Sources/web3swift/EthereumABI/ABIDecoding.swift; sourceTree = ""; }; - 1E3A34EECA0DC99C3A8F3294B0270E41 /* eckey_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = eckey_impl.h; path = secp256k1/eckey_impl.h; sourceTree = ""; }; - 1EDD544B32FC12296D15FFDB8DB3CEEC /* EIP67Code.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EIP67Code.swift; path = Sources/web3swift/Utils/EIP/EIP67Code.swift; sourceTree = ""; }; - 1F35ACAD54CA4C8BA1628EEC5C9C803A /* Pods-TestApplication-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-TestApplication-umbrella.h"; sourceTree = ""; }; - 1F71BAAE30889A3196D3F193BD7EAE93 /* PlainKeystore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PlainKeystore.swift; path = Sources/web3swift/KeystoreManager/PlainKeystore.swift; sourceTree = ""; }; - 20032C66FBFC8D534B0E014C41B3FC31 /* 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 = ""; }; - 2029C65F287FB4F3DF0A12F1340C4A2E /* Web3+Instance.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Instance.swift"; path = "Sources/web3swift/Web3/Web3+Instance.swift"; sourceTree = ""; }; - 20400A55C671EE455F595599C28C01CB /* 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 = ""; }; - 215B7D5D806DA1CEC59F24ABC7E54AA2 /* web3swift.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = web3swift.debug.xcconfig; sourceTree = ""; }; - 21EEF7760B023045FC31EC473557A490 /* CryptoSwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "CryptoSwift-umbrella.h"; sourceTree = ""; }; - 2232E13ECA21F9463469D2356DD59817 /* 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 = ""; }; - 24D977E748EAED64A5418C6749B97C72 /* scalar.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar.h; path = secp256k1/scalar.h; sourceTree = ""; }; - 25329BA0B75B6EC317AF079B1D15542A /* NSURLSession+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSURLSession+Promise.swift"; path = "Extensions/Foundation/Sources/NSURLSession+Promise.swift"; sourceTree = ""; }; - 26062370F3F43B0CCD0DB727059493EC /* SECP256k1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SECP256k1.swift; path = Sources/web3swift/Convenience/SECP256k1.swift; sourceTree = ""; }; - 266F457FE7F2E756EA9EFE30B0F6B05A /* Web3+ERC1633.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1633.swift"; path = "Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift"; sourceTree = ""; }; - 26A30E0DA2419B1831A942110E9826A2 /* BestLogger.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = BestLogger.framework; path = BestLogger.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 26E93968E466D33AED110C6354F60201 /* BatchedCollection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BatchedCollection.swift; path = Sources/CryptoSwift/BatchedCollection.swift; sourceTree = ""; }; - 280BDA4851FC9E3A332073A8A1E52A71 /* SHA3.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SHA3.swift; path = Sources/CryptoSwift/SHA3.swift; sourceTree = ""; }; - 28336DCCBEBDD902BCD17311A29807FC /* Random.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Random.swift; path = Sources/Random.swift; sourceTree = ""; }; - 283CC747FD0DCC168EE28C22BE24FB13 /* BestLogger-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "BestLogger-umbrella.h"; sourceTree = ""; }; - 289E1FCEA10E48367C2D0CCABD86802C /* Starscream-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Starscream-prefix.pch"; sourceTree = ""; }; - 28E24C7638C3C9F480F6DE1C4E8D3DD0 /* BestLogger-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "BestLogger-Info.plist"; sourceTree = ""; }; - 29998CFB49DFB2CA39D28E60FC7607CD /* ABI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABI.swift; path = Sources/web3swift/EthereumABI/ABI.swift; sourceTree = ""; }; - 2B065DE7641AB7C6FF473D09055AA810 /* SSLClientCertificate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SSLClientCertificate.swift; path = Sources/Starscream/SSLClientCertificate.swift; sourceTree = ""; }; - 2B85A6893CDE4B4C76734554A0BB3969 /* RLP.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RLP.swift; path = Sources/web3swift/SwiftRLP/RLP.swift; sourceTree = ""; }; - 2B9B33F9B214514D6A7B86948424A1AB /* fetchNodeDetails+promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "fetchNodeDetails+promise.swift"; path = "Sources/FetchNodeDetails/fetchNodeDetails+promise.swift"; sourceTree = ""; }; - 2BB30C009589E527A7DAB4ECB42B0559 /* BrowserViewController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BrowserViewController.swift; path = Sources/web3swift/Browser/BrowserViewController.swift; sourceTree = ""; }; - 2BF0E5B419AE36443D1D1F57ECB5323F /* scalar_8x32.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_8x32.h; path = secp256k1/scalar_8x32.h; sourceTree = ""; }; - 2CA8362AD3A3AE16C1B934C3B653BE05 /* CryptoSwift.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = CryptoSwift.release.xcconfig; sourceTree = ""; }; - 2D6CF27A12D3F3EF5494307E376E9EAD /* Checksum.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Checksum.swift; path = Sources/CryptoSwift/Checksum.swift; sourceTree = ""; }; - 2DA6191B2FC6B5538F9C1FF662985ED9 /* NSNotificationCenter+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSNotificationCenter+AnyPromise.m"; path = "Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m"; sourceTree = ""; }; - 2DAAC1D359C5B25F5C9C011AF77E1CB5 /* secp256k1.c.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = secp256k1.c.modulemap; sourceTree = ""; }; - 2E31FB5291F104D8F312D4A179031B59 /* UInt32+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UInt32+Extension.swift"; path = "Sources/CryptoSwift/UInt32+Extension.swift"; sourceTree = ""; }; - 2E57FB97B6281DDB98BEC36EA0CE3C0E /* NSURLSession+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSURLSession+AnyPromise.m"; path = "Extensions/Foundation/Sources/NSURLSession+AnyPromise.m"; sourceTree = ""; }; - 2F765D728D60C038B07F08BE54D2913F /* Division.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Division.swift; path = Sources/Division.swift; sourceTree = ""; }; - 304513EC2F0CF7D352C919E34D643691 /* Rabbit+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Rabbit+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/Rabbit+Foundation.swift"; sourceTree = ""; }; - 30B0D8BAF890F4EFCB9D256CC130AAA5 /* ECB.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ECB.swift; path = Sources/CryptoSwift/BlockMode/ECB.swift; sourceTree = ""; }; - 30EBA7B0DD66CEFFA209B8C22C1C96B3 /* ResourceBundle-Browser-web3swift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "ResourceBundle-Browser-web3swift-Info.plist"; sourceTree = ""; }; - 30F3E8F002317CB34DEBAC0F376015B0 /* Padding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Padding.swift; path = Sources/CryptoSwift/Padding.swift; sourceTree = ""; }; - 31C3703C315175092D73AECC95DE71B7 /* Authenticator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Authenticator.swift; path = Sources/CryptoSwift/Authenticator.swift; sourceTree = ""; }; - 321B1BD0CEA3B32021B68BF7BC9E90E7 /* Promise+Batching.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+Batching.swift"; path = "Sources/web3swift/Promises/Promise+Batching.swift"; sourceTree = ""; }; - 3253FCDF51FD3CCA40CFC041548584F1 /* BigInt.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = BigInt.release.xcconfig; sourceTree = ""; }; - 3254F0C43CE6414EB81E1FD3C3ACA595 /* EthereumAddress.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumAddress.swift; path = Sources/web3swift/EthereumAddress/EthereumAddress.swift; sourceTree = ""; }; - 32E81D97829DA786CB8BCB3CE12AAD57 /* String+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+Extension.swift"; path = "Sources/web3swift/Convenience/String+Extension.swift"; sourceTree = ""; }; - 3311A7DB3CE6CA76C4B56C03CFA175A1 /* field_5x52.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_5x52.h; path = secp256k1/field_5x52.h; sourceTree = ""; }; - 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = secp256k1.framework; path = secp256k1.c.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 33814A070AAF84C7E6D9C47D4A9DA47A /* AES.Cryptors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AES.Cryptors.swift; path = Sources/CryptoSwift/AES.Cryptors.swift; sourceTree = ""; }; - 33D0155668F1AEAFE580678B049CB98F /* RIPEMD160+StackOveflow.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "RIPEMD160+StackOveflow.swift"; sourceTree = ""; }; - 343893B600C18CE40D9AB491CBE66E9B /* ZeroPadding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ZeroPadding.swift; path = Sources/CryptoSwift/ZeroPadding.swift; sourceTree = ""; }; - 3467A6DA60C93415C18CAD34E5B58ADD /* Cryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cryptor.swift; path = Sources/CryptoSwift/Cryptor.swift; sourceTree = ""; }; - 3509820FD1FC52A8BD603D3560AC9E37 /* nodeDetails.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = nodeDetails.swift; path = Sources/FetchNodeDetails/nodeDetails.swift; sourceTree = ""; }; - 356E6CD41F459A448BB24F82F2CFDBF3 /* Web3+Protocols.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Protocols.swift"; path = "Sources/web3swift/Web3/Web3+Protocols.swift"; sourceTree = ""; }; - 36596C1155BCF36D4AC1E20D7F7DD4E0 /* secp256k1_main.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = secp256k1_main.h; path = secp256k1/secp256k1_main.h; sourceTree = ""; }; - 367EEC90C25E5957B79AF83B5F8C8040 /* Web3+Structures.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Structures.swift"; path = "Sources/web3swift/Web3/Web3+Structures.swift"; sourceTree = ""; }; - 36B22267AF4D657854BDCBC896BAA6BE /* FetchNodeDetails.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = FetchNodeDetails.framework; path = "Torus-fetchNodeDetails.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - 371A1B4989607A2FE45007122EB5DB1A /* Web3+Utils.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Utils.swift"; path = "Sources/web3swift/Web3/Web3+Utils.swift"; sourceTree = ""; }; - 37BB11C3206A9AF2E5FB14349F0A0C72 /* 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 = ""; }; - 37E49D3B34BDED405190E64976AE77B2 /* Cipher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cipher.swift; path = Sources/CryptoSwift/Cipher.swift; sourceTree = ""; }; - 3936ADAF803ACF9C9AF43E3304CF7768 /* TorusUtils.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = TorusUtils.framework; path = "Torus-utils.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - 394B571CD3DA252BF198EDE8DBD75729 /* Base58.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Base58.swift; path = Sources/web3swift/Convenience/Base58.swift; sourceTree = ""; }; - 394CB452CF5827603CAB1A624E0DB36B /* Web3+ERC20.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC20.swift"; path = "Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift"; sourceTree = ""; }; - 3A0A98AFF43BCAD42BA27652FF57E754 /* PromiseKit.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = PromiseKit.modulemap; sourceTree = ""; }; - 3B4F23EB6DCEE0E727D49E697D2F4602 /* PromiseKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PromiseKit.h; path = Sources/PromiseKit.h; sourceTree = ""; }; - 3C9026A1A42B2C5EC3F4055F65D29F50 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Error.swift; sourceTree = ""; }; - 3DDBF242F10DF61068E5BC1FC6DC2E65 /* Torus-fetchNodeDetails.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Torus-fetchNodeDetails.debug.xcconfig"; sourceTree = ""; }; - 3E945AEB44FCBEDA491D75A9A46BC158 /* secp256k1.c.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = secp256k1.c.release.xcconfig; sourceTree = ""; }; - 3EAC7939CF4AA08B18DE951258B603FE /* ABITypeParser.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABITypeParser.swift; path = Sources/web3swift/EthereumABI/ABITypeParser.swift; sourceTree = ""; }; - 3EFBB66B08AAC29D6B283076F7CF0951 /* Array+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "Array+Extension.swift"; sourceTree = ""; }; - 3F13C642230A43992D825AC6F75C9DE4 /* Web3+Personal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Personal.swift"; path = "Sources/web3swift/Web3/Web3+Personal.swift"; sourceTree = ""; }; - 3FC83725DA96C508A8896086BFAF1B1F /* CMAC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CMAC.swift; path = Sources/CryptoSwift/CMAC.swift; sourceTree = ""; }; - 403758DEF6A4E7BB2F98889B82A135A9 /* UIView+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIView+Promise.swift"; path = "Extensions/UIKit/Sources/UIView+Promise.swift"; sourceTree = ""; }; - 40F19205E66DD1450EFD8E3E2032957B /* ENSResolver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENSResolver.swift; path = Sources/web3swift/Utils/ENS/ENSResolver.swift; sourceTree = ""; }; - 4153FE15958FE1F02ACA05376FB555AF /* ComparisonExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ComparisonExtensions.swift; path = Sources/web3swift/Contract/ComparisonExtensions.swift; sourceTree = ""; }; - 421F491B9F8AB1BC9C6616B284D46A65 /* Pods-TestApplication.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TestApplication.release.xcconfig"; sourceTree = ""; }; - 428775C0D794A0F3B8EB12C991CE5DE9 /* web3swift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = web3swift.modulemap; sourceTree = ""; }; - 432B19CC00325EAC433376693879C00D /* Floating Point Conversion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Floating Point Conversion.swift"; path = "Sources/Floating Point Conversion.swift"; sourceTree = ""; }; - 43B2A6CA1E4D2F7A4D32596BA2E04F4E /* Dictionary+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "Dictionary+Extension.swift"; sourceTree = ""; }; - 43D6002B89854A8CA87F6E11D2A4774B /* String+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+Extension.swift"; path = "Sources/CryptoSwift/String+Extension.swift"; sourceTree = ""; }; - 44050EDD065DFF0F59D2C7D56487174A /* 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; }; - 44A6E724DEAED085EEFF9F277E653728 /* Web3+SecurityToken.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+SecurityToken.swift"; path = "Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift"; sourceTree = ""; }; - 44F01E43FBF03BD38D6D6F7AE02BEB9C /* ecdh_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecdh_impl.h; path = secp256k1/ecdh_impl.h; sourceTree = ""; }; - 4542D87C52957FA0E8DD89915A7F699C /* ENSBaseRegistrar.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENSBaseRegistrar.swift; path = Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift; sourceTree = ""; }; - 458A8AB2661A57F37E4E70311F75F5FE /* UIViewController+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIViewController+AnyPromise.h"; path = "Extensions/UIKit/Sources/UIViewController+AnyPromise.h"; sourceTree = ""; }; - 46D25574FD61890717200D7A5ECA5244 /* num.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = num.h; path = secp256k1/num.h; sourceTree = ""; }; - 46D72FD9B676F8CDC9814462C4FAFD62 /* Web3+Eventloop.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Eventloop.swift"; path = "Sources/web3swift/Web3/Web3+Eventloop.swift"; sourceTree = ""; }; - 4769E2DFCF57A68EF19CA75CB8034B8C /* web3swift.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = web3swift.release.xcconfig; sourceTree = ""; }; - 493D56F05A52E5B4339485C92C6232F6 /* Subtraction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Subtraction.swift; path = Sources/Subtraction.swift; sourceTree = ""; }; - 49E00ED54B318307C4DE75639CE0317B /* BlockModeOptions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockModeOptions.swift; path = Sources/CryptoSwift/BlockMode/BlockModeOptions.swift; sourceTree = ""; }; - 49E9940B89C37FD51942B42F1C5657D3 /* Starscream.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Starscream.release.xcconfig; sourceTree = ""; }; - 4B9B3D2E1749E19CD5247226FC2A0DE9 /* PMKUIKit.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PMKUIKit.h; path = Extensions/UIKit/Sources/PMKUIKit.h; sourceTree = ""; }; - 4CBB573AF014CEB32442B64D32A7D855 /* Decodable+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Decodable+Extensions.swift"; path = "Sources/web3swift/Convenience/Decodable+Extensions.swift"; sourceTree = ""; }; - 4CFC14BE3601EA8C363263E0B5679F6F /* Starscream.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Starscream.modulemap; sourceTree = ""; }; - 4D48B83EF23A08BDB8BF4F2E68A6A921 /* BIP32KeystoreJSONStructure.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BIP32KeystoreJSONStructure.swift; path = Sources/web3swift/KeystoreManager/BIP32KeystoreJSONStructure.swift; sourceTree = ""; }; - 4E3960E268984162FF5DDA0F17BCE57F /* Pods-TestApplication-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TestApplication-acknowledgements.plist"; sourceTree = ""; }; - 532AD590CA6E6DFA10973018D68A00B9 /* Generics.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Generics.swift; path = Sources/CryptoSwift/Generics.swift; sourceTree = ""; }; - 5410B105EBAA327591B7B1178127F21A /* EthereumContract.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumContract.swift; path = Sources/web3swift/Contract/EthereumContract.swift; sourceTree = ""; }; - 54255A778D9AA0DB0A5D3A32AA4B0276 /* String Conversion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String Conversion.swift"; path = "Sources/String Conversion.swift"; sourceTree = ""; }; - 547193FFA17662EE95EF699A2570D30B /* AES.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AES.swift; path = Sources/CryptoSwift/AES.swift; sourceTree = ""; }; - 54C9D3822228221ABF33D464A3046A0B /* BigInt-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "BigInt-dummy.m"; sourceTree = ""; }; - 54E2DF0C1A7123CBD20FD3B19C8EDF57 /* field_10x26_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_10x26_impl.h; path = secp256k1/field_10x26_impl.h; sourceTree = ""; }; - 54E37A2DF9578412AA69A5BEFC18EE7B /* CipherModeWorker.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CipherModeWorker.swift; path = Sources/CryptoSwift/BlockMode/CipherModeWorker.swift; sourceTree = ""; }; - 55A212FC43612F76263F35C276405A36 /* 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 = ""; }; - 55AF878927A572E76B0E6A029A8505D3 /* ABIParameterTypes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIParameterTypes.swift; path = Sources/web3swift/EthereumABI/ABIParameterTypes.swift; sourceTree = ""; }; - 588AE181250B323137C9868209035ECB /* Pods-TestApplication.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-TestApplication.modulemap"; sourceTree = ""; }; - 58BF3F08DDC701824F81D3D3A3888DCC /* BigUInt+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "BigUInt+Extensions.swift"; path = "Sources/web3swift/Convenience/BigUInt+Extensions.swift"; sourceTree = ""; }; - 59A3D848262E8740C07120707959C110 /* Torus-utils.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Torus-utils.modulemap"; sourceTree = ""; }; - 5AB8CB5005FBD2930B346BD37D0CE897 /* Web3+Wallet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Wallet.swift"; path = "Sources/web3swift/HookedFunctions/Web3+Wallet.swift"; sourceTree = ""; }; - 5AF1CFD2C9895A1EDAFD919380565FB3 /* BlockEncryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockEncryptor.swift; path = Sources/CryptoSwift/BlockEncryptor.swift; sourceTree = ""; }; - 5BAEE36B30C5FB7510EFE984E167F4C8 /* EthereumTransaction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumTransaction.swift; path = Sources/web3swift/Transaction/EthereumTransaction.swift; sourceTree = ""; }; - 5BB00E6935E0F6473686F43BA42E47DD /* Web3+ERC165.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC165.swift"; path = "Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift"; sourceTree = ""; }; - 5C0584AA4F770CFB96D81C2F740F5B48 /* Comparable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Comparable.swift; path = Sources/Comparable.swift; sourceTree = ""; }; - 5E8A9E477BF48B7A910D0892FC633B77 /* Web3+ERC1594.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1594.swift"; path = "Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift"; sourceTree = ""; }; - 5EB72F7C7F019D09A7B0DF1DAB426080 /* CryptoSwift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = CryptoSwift.modulemap; sourceTree = ""; }; - 5EDA937DD9FF68A701B5FB8C2C6E2991 /* Web3+Methods.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Methods.swift"; path = "Sources/web3swift/Web3/Web3+Methods.swift"; sourceTree = ""; }; - 6082721A37AB0726E7E2B183208F595E /* CryptoExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CryptoExtensions.swift; sourceTree = ""; }; - 60C1AAE2EB5DABD8D89F4408AB5E3F08 /* eckey.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = eckey.h; path = secp256k1/eckey.h; sourceTree = ""; }; - 60E1AD875946CE4A244B1EC878A90E0B /* BestLogger.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BestLogger.swift; path = Sources/BestLogger/BestLogger.swift; sourceTree = ""; }; - 610164D574FDBA5D2B86AD20803A34C7 /* Torus-fetchNodeDetails-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Torus-fetchNodeDetails-dummy.m"; sourceTree = ""; }; - 61DE2FCF270DEB55C69AE65F3614A934 /* EthereumKeystoreV3.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumKeystoreV3.swift; path = Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift; sourceTree = ""; }; - 623192767A29965E6C002E99496ADB9E /* Compression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Compression.swift; path = Sources/Starscream/Compression.swift; sourceTree = ""; }; - 627F7A45BFD915D896B8B858F59427E9 /* Process+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Process+Promise.swift"; path = "Extensions/Foundation/Sources/Process+Promise.swift"; sourceTree = ""; }; - 62878F4D3CFBB00EBD025FF63E76375F /* Exponentiation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Exponentiation.swift; path = Sources/Exponentiation.swift; sourceTree = ""; }; - 62A74443599E879E0E975121A027F655 /* Encodable+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "Encodable+Extensions.swift"; sourceTree = ""; }; - 636F14D1D805465AFBED7A23DCC80AF4 /* Pods-TestApplication-TestApplicationTests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TestApplication-TestApplicationTests-Info.plist"; sourceTree = ""; }; - 64406043FA5C8662A25B01ECBD9A167B /* Web3+ERC721x.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC721x.swift"; path = "Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift"; sourceTree = ""; }; - 648384FDC27C062F3B5B39565DC0B287 /* Updatable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Updatable.swift; path = Sources/CryptoSwift/Updatable.swift; sourceTree = ""; }; - 64CB563CCEBFB9464AC885324FCD2528 /* Torus-utils.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Torus-utils.release.xcconfig"; sourceTree = ""; }; - 65772FBA70CCA564031A7DB655375942 /* UIView+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+AnyPromise.m"; path = "Extensions/UIKit/Sources/UIView+AnyPromise.m"; sourceTree = ""; }; - 66367BD14E3729FBAE3EEC75BFF93DC9 /* BIP32Keystore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BIP32Keystore.swift; path = Sources/web3swift/KeystoreManager/BIP32Keystore.swift; sourceTree = ""; }; - 66D8D2442F980738A4DF46016A1C658B /* StreamEncryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StreamEncryptor.swift; path = Sources/CryptoSwift/StreamEncryptor.swift; sourceTree = ""; }; - 66FBE58D0DE5590C2C0843EF48B824BF /* NSObject+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Promise.swift"; path = "Extensions/Foundation/Sources/NSObject+Promise.swift"; sourceTree = ""; }; - 67D4DF46AEC809E807D0A8ECEF69B7BE /* secp256k1.c-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "secp256k1.c-Info.plist"; sourceTree = ""; }; - 68565345731E54A07E8961540F271397 /* epochInfo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = epochInfo.swift; path = Sources/FetchNodeDetails/epochInfo.swift; sourceTree = ""; }; - 68F29EE2740CD5F7D9F2742ACB0C68AC /* AEAD.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AEAD.swift; path = Sources/CryptoSwift/AEAD/AEAD.swift; sourceTree = ""; }; - 69CC6C3B6338B8B1D8CBAF297925E3EB /* hash_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = hash_impl.h; path = secp256k1/hash_impl.h; sourceTree = ""; }; - 69E3B99D314855023E8E56ED2D273292 /* Torus-fetchNodeDetails-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Torus-fetchNodeDetails-Info.plist"; sourceTree = ""; }; - 6AB74F071919892DEDA2B20512603D17 /* CryptoSwift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "CryptoSwift-dummy.m"; sourceTree = ""; }; - 6ACB6795469A1198FA61AA30CBCE452B /* PromiseKit-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "PromiseKit-dummy.m"; sourceTree = ""; }; - 6B4BB1950A7E59A2522D593BBB8B7488 /* race.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = race.swift; path = Sources/race.swift; sourceTree = ""; }; - 6B65A61831421C6750C3861BC12E0C45 /* secp256k1.c-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "secp256k1.c-dummy.m"; sourceTree = ""; }; - 6DB520E20CDE817BAE8A2B30E91FC879 /* web3swift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "web3swift-umbrella.h"; sourceTree = ""; }; - 6E7A807E2744EF86C0208B7213A91F86 /* recovery_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = recovery_impl.h; path = secp256k1/recovery_impl.h; sourceTree = ""; }; - 7068BB4E0872B6DEC38E77F1B04ECDB7 /* SHA2.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SHA2.swift; path = Sources/CryptoSwift/SHA2.swift; sourceTree = ""; }; - 7084A45BBF491661009BA2F1F1FFA83D /* browser.js */ = {isa = PBXFileReference; includeInIndex = 1; name = browser.js; path = Sources/web3swift/Browser/browser.js; sourceTree = ""; }; - 70C8D6D69E1A13C98E13C5399927DBCF /* Torus-utils-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Torus-utils-dummy.m"; sourceTree = ""; }; - 736C7B0AB9E592CCF99B60A020F609C4 /* UInt64+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UInt64+Extension.swift"; path = "Sources/CryptoSwift/UInt64+Extension.swift"; sourceTree = ""; }; - 741C3A5883AB6FC983592C617CE51CAC /* License.md */ = {isa = PBXFileReference; includeInIndex = 1; path = License.md; sourceTree = ""; }; - 749DDD6C8309DAD6BBCF7410355CB4D3 /* num_gmp_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = num_gmp_impl.h; path = secp256k1/num_gmp_impl.h; sourceTree = ""; }; - 74CD34049D056134BF4391B03E13C4A2 /* Guarantee.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Guarantee.swift; path = Sources/Guarantee.swift; sourceTree = ""; }; - 74F9436D309E5C0320E2BF39B33369DC /* Pods-TestApplication-TestApplicationTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-TestApplication-TestApplicationTests.modulemap"; sourceTree = ""; }; - 77A9E9B7B569F09BB85D9AA4D7B47A61 /* NativeTypesEncoding+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NativeTypesEncoding+Extensions.swift"; path = "Sources/web3swift/Convenience/NativeTypesEncoding+Extensions.swift"; sourceTree = ""; }; - 7837B720C51246FB222DAFBB154A7EFD /* Web3+InfuraProviders.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+InfuraProviders.swift"; path = "Sources/web3swift/Web3/Web3+InfuraProviders.swift"; sourceTree = ""; }; - 7865861740168F97EBF3471A1E99D0C4 /* UIView+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+AnyPromise.h"; path = "Extensions/UIKit/Sources/UIView+AnyPromise.h"; sourceTree = ""; }; - 78AED03C814501A370FDB3B77A13D1AC /* Torus-utils-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Torus-utils-prefix.pch"; sourceTree = ""; }; - 79FFF2FD3F5D49331504AD9FB3B06AF7 /* num_gmp.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = num_gmp.h; path = secp256k1/num_gmp.h; sourceTree = ""; }; - 7AFDF177A0326BCF4BF54E5BAA19ADB3 /* PKCS7Padding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PKCS7Padding.swift; path = Sources/CryptoSwift/PKCS/PKCS7Padding.swift; sourceTree = ""; }; - 7B02652C920852E623D9F913E0B1F5EA /* web3swift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "web3swift-prefix.pch"; sourceTree = ""; }; - 7B1BE46004B0E262840E88B6B4316CEF /* abi.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = abi.swift; path = Sources/FetchNodeDetails/contract/abi.swift; sourceTree = ""; }; - 7B3934C6F60ADD7B7235930EEC358D0F /* PMKFoundation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = PMKFoundation.h; path = Extensions/Foundation/Sources/PMKFoundation.h; sourceTree = ""; }; - 7C4E4C5A7B89BAC92AF3CDF8A3DF20C5 /* field_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_impl.h; path = secp256k1/field_impl.h; sourceTree = ""; }; - 7D0BBF0C44022F9BD5C7E2A44A669C5B /* AnyPromise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyPromise.swift; path = Sources/AnyPromise.swift; sourceTree = ""; }; - 7D0E11BE6137B9B807EEF01BBBF24181 /* BigInt.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = BigInt.debug.xcconfig; sourceTree = ""; }; - 7D9362939A3FBFC35D559726BAAEE2D8 /* RIPEMD160+StackOveflow.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "RIPEMD160+StackOveflow.swift"; path = "Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift"; sourceTree = ""; }; - 7E09DE6376C302F500D47F146994DBCE /* CFB.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CFB.swift; path = Sources/CryptoSwift/BlockMode/CFB.swift; sourceTree = ""; }; - 7E9C126C1E762F5A9CBB417F5BEDC4BA /* Torus-fetchNodeDetails-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Torus-fetchNodeDetails-umbrella.h"; sourceTree = ""; }; - 7F0E9FE8589A3E747F1C6E49D1F665B6 /* NSNotificationCenter+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSNotificationCenter+Promise.swift"; path = "Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift"; sourceTree = ""; }; - 7F36005F31C0A72C79F5F6570FDF07C5 /* CryptoExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CryptoExtensions.swift; path = Sources/web3swift/Convenience/CryptoExtensions.swift; sourceTree = ""; }; - 7F595E5162AE7A4525F876A2F65D7767 /* 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 = ""; }; - 7F673FD14D4ABF76640791855FBB0BB6 /* Pods-TestApplication-TestApplicationTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TestApplication-TestApplicationTests.release.xcconfig"; sourceTree = ""; }; - 7F9D9BAC5011C578C942C96A9193C5A2 /* Rabbit.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Rabbit.swift; path = Sources/CryptoSwift/Rabbit.swift; sourceTree = ""; }; - 7FCCD54F9BF290744B30BD7C76B31F60 /* ENSRegistry.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENSRegistry.swift; path = Sources/web3swift/Utils/ENS/ENSRegistry.swift; sourceTree = ""; }; - 805A95545687CAF1C10291D688FFBA5E /* ecmult_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_impl.h; path = secp256k1/ecmult_impl.h; sourceTree = ""; }; - 8080BE88E5AD32344368207217955275 /* 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 = ""; }; - 80EDBAF33DE530B669F36DB988B3F7D4 /* PromiseKit-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-umbrella.h"; sourceTree = ""; }; - 833C4372749433AEF2DDCFD5ACD4F288 /* Web3+ERC777.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC777.swift"; path = "Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift"; sourceTree = ""; }; - 84B27F6051F06DF5A4E6F7214D0B0BF3 /* HMAC+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "HMAC+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/HMAC+Foundation.swift"; sourceTree = ""; }; - 84CFB5E7DC25C41F593E110F7CA2CF94 /* Thenable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Thenable.swift; path = Sources/Thenable.swift; sourceTree = ""; }; - 8607984D28231447D07695D87FC3465E /* ecmult.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult.h; path = secp256k1/ecmult.h; sourceTree = ""; }; - 861D5F94C97320DB5B5A576B7DE1046A /* AEADChaCha20Poly1305.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AEADChaCha20Poly1305.swift; path = Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift; sourceTree = ""; }; - 86B7A860A95575E515952D768A8DF41C /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Extensions.swift; path = Sources/web3swift/EthereumAddress/Extensions.swift; sourceTree = ""; }; - 86E812F60C2C434B4835413EBC00BE04 /* Prime Test.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Prime Test.swift"; path = "Sources/Prime Test.swift"; sourceTree = ""; }; - 87266A5B0B28E9E194A437D7509E8113 /* 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 = ""; }; - 8747A39C94995D4E8E4A0BF717CE8C0B /* PromiseKit-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "PromiseKit-prefix.pch"; sourceTree = ""; }; - 8800939F03C2C23BCFC7AC6D89B3E29A /* dispatch_promise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = dispatch_promise.m; path = Sources/dispatch_promise.m; sourceTree = ""; }; - 891B2270823847ED23F2ECFC28F935EC /* Starscream.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Starscream.framework; path = Starscream.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 895FA234293490054981FB4B1FF1A2A0 /* 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 = ""; }; - 898923CC0589827D44FC74523112C46C /* Hashable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Hashable.swift; path = Sources/Hashable.swift; sourceTree = ""; }; - 89D859F38B40E4EBC5C9E12D681363A1 /* KeyAssignRequestResponse.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = KeyAssignRequestResponse.swift; sourceTree = ""; }; - 89DE8CC0478156EF8E36CDA5F88E6218 /* secp256k1.c.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = secp256k1.c.debug.xcconfig; sourceTree = ""; }; - 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = web3swift.framework; path = web3swift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 8B075CA53091CACB97CA1EC16B1B8CAC /* Pods_TestApplication.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_TestApplication.framework; path = "Pods-TestApplication.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - 8B7B8BE2B958EF73B7920669D0A6165E /* Web3+ERC721.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC721.swift"; path = "Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift"; sourceTree = ""; }; - 8DF1B2B15BA23A2536CCE7230A326820 /* BIP39+WordLists.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "BIP39+WordLists.swift"; path = "Sources/web3swift/KeystoreManager/BIP39+WordLists.swift"; sourceTree = ""; }; - 8E58EE8091E64202823382773372E51D /* Web3+Eth.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Eth.swift"; path = "Sources/web3swift/Web3/Web3+Eth.swift"; sourceTree = ""; }; - 8F2AFB6AD39C5E71058F032B2081D300 /* Starscream-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Starscream-umbrella.h"; sourceTree = ""; }; - 90BE69904F143992674611FD87C10FF0 /* 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 = ""; }; - 910707A9E3436E68FCDF05631CA0B2CA /* ENS.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ENS.swift; path = Sources/web3swift/Utils/ENS/ENS.swift; sourceTree = ""; }; - 9148A4156B244104E844B817FB162F4C /* Starscream.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Starscream.debug.xcconfig; sourceTree = ""; }; - 917B6EFF40524BB04100155BBFBA26F5 /* ChaCha20+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ChaCha20+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/ChaCha20+Foundation.swift"; sourceTree = ""; }; - 91BB24BA472AF523E913108C9AA301F2 /* BigInt.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = BigInt.framework; path = BigInt.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 929A382CB9CC2554AB704DB58025119C /* BigUInt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BigUInt.swift; path = Sources/BigUInt.swift; sourceTree = ""; }; - 92E67E4F9997B00CBAEF6DC5180B804E /* Web3+ERC820.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC820.swift"; path = "Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift"; sourceTree = ""; }; - 93BBFE788270709884A832C695A7D9B1 /* browser.min.js */ = {isa = PBXFileReference; includeInIndex = 1; name = browser.min.js; path = Sources/web3swift/Browser/browser.min.js; sourceTree = ""; }; - 93DA1DCA9F62B5CF3199108FB90AF568 /* 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; }; - 9480EC5419F2059D80BD085B2DBF2323 /* Pods-TestApplication-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-TestApplication-dummy.m"; sourceTree = ""; }; - 94C4B2C4BB3ED30A768BCD9DCE993A60 /* PromiseKit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PromiseKit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 95588ED1054704883B313B15AF39B29B /* Web3+HttpProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+HttpProvider.swift"; path = "Sources/web3swift/Web3/Web3+HttpProvider.swift"; sourceTree = ""; }; - 9574BD191822B8CA2B44360C0DAFEE0D /* secp256k1.c */ = {isa = PBXFileReference; includeInIndex = 1; name = secp256k1.c; path = secp256k1/secp256k1.c; sourceTree = ""; }; - 958577E37A0C6899FA8F40D1ECF43198 /* Shifts.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Shifts.swift; path = Sources/Shifts.swift; sourceTree = ""; }; - 9591EFA1AE71B666915FB5B8C763A34F /* Addition.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Addition.swift; path = Sources/Addition.swift; sourceTree = ""; }; - 9645F90AD29640672EB3F4C6306E2CA8 /* Codable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Codable.swift; path = Sources/Codable.swift; sourceTree = ""; }; - 96B1C06C49366D9076D665592EECCC28 /* BestLogger-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "BestLogger-prefix.pch"; sourceTree = ""; }; - 96F6072F2F4703F5643796E5AE8EF7D0 /* Torus-utils.podspec */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; path = "Torus-utils.podspec"; sourceTree = ""; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - 97241BE1FCAA933EA8779E01EEA25CB6 /* Pods_TestApplication_TestApplicationTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_TestApplication_TestApplicationTests.framework; path = "Pods-TestApplication-TestApplicationTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - 975066EE84D12EED3FB768B684207672 /* web3swift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "web3swift-dummy.m"; sourceTree = ""; }; - 975A89B5D0199DE1636D45DA30498CA6 /* BigInt.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = BigInt.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 97BA2657F2505CCC7EEA41D25BB7CD60 /* Data Conversion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Data Conversion.swift"; path = "Sources/Data Conversion.swift"; sourceTree = ""; }; - 98043C01CB253479FAA51D0483638C79 /* EthereumFilterEncodingExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EthereumFilterEncodingExtensions.swift; path = Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift; sourceTree = ""; }; - 98302BCB7B2D63FE1C809B7EED544A31 /* HMAC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HMAC.swift; path = Sources/CryptoSwift/HMAC.swift; sourceTree = ""; }; - 99D17C88D422705B026AAE3CB31EA369 /* StreamDecryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StreamDecryptor.swift; path = Sources/CryptoSwift/StreamDecryptor.swift; sourceTree = ""; }; - 9A1A105339FBDCF49E1692DAC870181F /* fetchNodeDetails.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = fetchNodeDetails.swift; path = Sources/FetchNodeDetails/fetchNodeDetails.swift; sourceTree = ""; }; - 9A55358BC9BF9260CA0B353D1E198EDD /* scratch.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scratch.h; path = secp256k1/scratch.h; sourceTree = ""; }; - 9A71430DAF19B7345290774BF3DF061A /* ChaCha20.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ChaCha20.swift; path = Sources/CryptoSwift/ChaCha20.swift; sourceTree = ""; }; - 9A7C7440F23854147993BEA3BF179B7A /* CTR.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CTR.swift; path = Sources/CryptoSwift/BlockMode/CTR.swift; sourceTree = ""; }; - 9A83CE7F4E5E202D7F1C4F4CAFE68D5A /* secp256k1.c-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "secp256k1.c-umbrella.h"; sourceTree = ""; }; - 9B6B7AECEFE99816B8FBCB33CA41BA5A /* 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 = ""; }; - 9BB35F4C313D91EE8AFBFA7D34E85B04 /* field_5x52_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = field_5x52_impl.h; path = secp256k1/field_5x52_impl.h; sourceTree = ""; }; - 9C0DC37E22F8903645A132FC89D8C1DC /* Utils+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Utils+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/Utils+Foundation.swift"; sourceTree = ""; }; - 9C399168B633166C7713975ED1A8F8B6 /* BloomFilter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BloomFilter.swift; path = Sources/web3swift/Transaction/BloomFilter.swift; sourceTree = ""; }; - 9C956D6C93CE03F2CDC414E5EAC7F680 /* firstly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = firstly.swift; path = Sources/firstly.swift; sourceTree = ""; }; - 9CF17921439863D5241B29B9DCC9D6CA /* ecdsa_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecdsa_impl.h; path = secp256k1/ecdsa_impl.h; 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; }; - 9F77F548DB5C2368A36DA59A671FD248 /* BestLogger.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = BestLogger.modulemap; sourceTree = ""; }; - 9FC4A128639B3C17CBDB3AE67BD61BBE /* EIP681.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = EIP681.swift; path = Sources/web3swift/Utils/EIP/EIP681.swift; sourceTree = ""; }; - A17BF4AEEC01E419833321F0C76BF3A3 /* Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Operators.swift; path = Sources/CryptoSwift/Operators.swift; sourceTree = ""; }; - A1EDB95C55FE665B44017C14EF40CA8F /* BlockDecryptor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockDecryptor.swift; path = Sources/CryptoSwift/BlockDecryptor.swift; sourceTree = ""; }; - A2835A01E0247A5156E927DCA5C1A2A5 /* UInt16+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UInt16+Extension.swift"; path = "Sources/CryptoSwift/UInt16+Extension.swift"; sourceTree = ""; }; - A3ABFE3667AA01A217809D9BE0B80D1F /* Pods-TestApplication-TestApplicationTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TestApplication-TestApplicationTests.debug.xcconfig"; sourceTree = ""; }; - A449726AD38C7BCC6A4476FB6FCC57BD /* Dictionary+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Dictionary+Extension.swift"; path = "Sources/web3swift/Convenience/Dictionary+Extension.swift"; sourceTree = ""; }; - A4A09751392B322E31DEAC69C3FE848F /* nodeInfo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = nodeInfo.swift; path = Sources/FetchNodeDetails/nodeInfo.swift; sourceTree = ""; }; - A5795FBFDECE1EE5D44334B0E86704C3 /* Bitwise Ops.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Bitwise Ops.swift"; path = "Sources/Bitwise Ops.swift"; sourceTree = ""; }; - A57FA60848C2DC82A2D474D2DE260055 /* GCD.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GCD.swift; path = Sources/GCD.swift; sourceTree = ""; }; - A6D43ECDBFBD5966FA8C97853B7A6744 /* Data+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Data+Extension.swift"; path = "Sources/CryptoSwift/Foundation/Data+Extension.swift"; sourceTree = ""; }; - A82C338D47D72E5E229B666E9FB29815 /* JSONRPCRequest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = JSONRPCRequest.swift; sourceTree = ""; }; - A8F20F5D5E82BF2A3C986523F803A02D /* Web3+ERC1644.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1644.swift"; path = "Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift"; sourceTree = ""; }; - A9360628224445199F11C25D8F17488D /* Web3+ERC1400.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1400.swift"; path = "Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift"; sourceTree = ""; }; - A9A22D3ECB8CA971A45DBDF492F36ACB /* NSTask+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSTask+AnyPromise.m"; path = "Extensions/Foundation/Sources/NSTask+AnyPromise.m"; sourceTree = ""; }; - A9C317513ED6A8C8924B31F5F8E6FB58 /* ecmult_const_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_const_impl.h; path = secp256k1/ecmult_const_impl.h; sourceTree = ""; }; - AA6E5EE30B00CACE5169C7B53F93C899 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = Sources/Error.swift; sourceTree = ""; }; - ABD51BF16E0DBDE492E7FEEBBEBA6EBA /* num_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = num_impl.h; path = secp256k1/num_impl.h; sourceTree = ""; }; - AC767EA373C6A47D8C0E5B877E98F1BF /* hang.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = hang.swift; path = Sources/hang.swift; sourceTree = ""; }; - AD4460059743B10EB585030DEAE55679 /* 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; }; - AE4102418DE6E7E4CED7680542ACA596 /* BlockMode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockMode.swift; path = Sources/CryptoSwift/BlockMode/BlockMode.swift; sourceTree = ""; }; - AE5DDB66F7A93C648396E85324B6FB21 /* BigInt-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "BigInt-prefix.pch"; sourceTree = ""; }; - AE80079DF00F0A5DEDAAAD710234F15A /* Web3+ReadingTransaction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ReadingTransaction.swift"; path = "Sources/web3swift/Web3/Web3+ReadingTransaction.swift"; sourceTree = ""; }; - AED6B05BDFA0F12F0E5B61393689B89B /* NonceMiddleware.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NonceMiddleware.swift; path = Sources/web3swift/Utils/Hooks/NonceMiddleware.swift; sourceTree = ""; }; - AF0BEE4B0224AC7B0C9583A79622855A /* Catchable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Catchable.swift; path = Sources/Catchable.swift; sourceTree = ""; }; - B199C90B54B508CC6863DC3B86C34A12 /* Array+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Array+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/Array+Foundation.swift"; sourceTree = ""; }; - B22522DBF599DA791D7EE3F3D10BE027 /* Torus-fetchNodeDetails-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Torus-fetchNodeDetails-prefix.pch"; sourceTree = ""; }; - B2EAA5F612FE999334D6B0F6B413F776 /* Pods-TestApplication-TestApplicationTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-TestApplication-TestApplicationTests-acknowledgements.markdown"; sourceTree = ""; }; - B3F19A59C557ADA87DA85B082C792879 /* HKDF.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HKDF.swift; path = Sources/CryptoSwift/HKDF.swift; sourceTree = ""; }; - B4B962A49197959211418558342805EE /* Deprecations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deprecations.swift; path = Sources/Deprecations.swift; sourceTree = ""; }; - B5359F2F46F8C6AC35F1007EE324CE53 /* Pods-TestApplication.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TestApplication.debug.xcconfig"; sourceTree = ""; }; - B53A9F8E880B31A0E6C1649C07767374 /* BigInt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BigInt.swift; path = Sources/BigInt.swift; sourceTree = ""; }; - B586613F92A74DDD67224217EF339232 /* PCBC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PCBC.swift; path = Sources/CryptoSwift/BlockMode/PCBC.swift; sourceTree = ""; }; - B640F3F6BEEA3F00C6EC949A3247B36B /* ContractProtocol.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ContractProtocol.swift; path = Sources/web3swift/Contract/ContractProtocol.swift; sourceTree = ""; }; - B6F035EFCF554B9F05F6CDFAB107782C /* PromiseKit-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "PromiseKit-Info.plist"; sourceTree = ""; }; - B79CB3EFA0565779F964A732017D23F8 /* LogEvent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LogEvent.swift; path = Sources/LogEvent.swift; sourceTree = ""; }; - B88A9BF2B3A86B0BD42B03214218D438 /* BestLogger.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = BestLogger.debug.xcconfig; sourceTree = ""; }; - B99D9981AEBF8D8652D52D14D95114E4 /* Pods-TestApplication-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-TestApplication-acknowledgements.markdown"; sourceTree = ""; }; - BA00FA25D79D42904906782ED589D977 /* Pods-TestApplication-TestApplicationTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TestApplication-TestApplicationTests-acknowledgements.plist"; sourceTree = ""; }; - BA45C8CD81E3BEC7324DA061D9811272 /* when.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = when.m; path = Sources/when.m; sourceTree = ""; }; - BAAD698E863ED4A0CCEEBB0C78DCA770 /* SecureBytes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SecureBytes.swift; path = Sources/CryptoSwift/SecureBytes.swift; sourceTree = ""; }; - BAEE2319C8E8D77C6DB2627C66E80708 /* ecmult_const.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_const.h; path = secp256k1/ecmult_const.h; sourceTree = ""; }; - BB1204BA343D2E4FE433DF065E5739C8 /* Array+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Array+Extension.swift"; path = "Sources/CryptoSwift/Array+Extension.swift"; sourceTree = ""; }; - BB147247ABF7F4DAFD652DD4A718F13F /* abi.json */ = {isa = PBXFileReference; includeInIndex = 1; name = abi.json; path = Sources/FetchNodeDetails/contract/abi.json; sourceTree = ""; }; - BB346C38513FA9E9018CE31D0EB8E613 /* CBC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CBC.swift; path = Sources/CryptoSwift/BlockMode/CBC.swift; sourceTree = ""; }; - BB66295E387734C568DC4F306928B9E7 /* Square Root.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Square Root.swift"; path = "Sources/Square Root.swift"; sourceTree = ""; }; - BB6C5C1E585BD8D5914604BB64EFBD57 /* ecmult_gen_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_gen_impl.h; path = secp256k1/ecmult_gen_impl.h; sourceTree = ""; }; - BBE375A431A0CAAD97FE1B50B09ECFBC /* scalar_low_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_low_impl.h; path = secp256k1/scalar_low_impl.h; sourceTree = ""; }; - BC594840B7ACD8661A072BE4D284BAC0 /* Multiplication.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Multiplication.swift; path = Sources/Multiplication.swift; sourceTree = ""; }; - BC681896D4212B9DA6C9384F3344234F /* String+FoundationExtension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+FoundationExtension.swift"; path = "Sources/CryptoSwift/Foundation/String+FoundationExtension.swift"; sourceTree = ""; }; - BC79DFF5B9C04D7FE20DD358512F0C5E /* BlockCipher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BlockCipher.swift; path = Sources/CryptoSwift/BlockCipher.swift; sourceTree = ""; }; - BCF0C2B61C0E69C47E9851BA327B091D /* BigUInt+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "BigUInt+Extensions.swift"; sourceTree = ""; }; - BCFEC24438294C64187419C5B2729D05 /* Encodable+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Encodable+Extensions.swift"; path = "Sources/web3swift/Convenience/Encodable+Extensions.swift"; sourceTree = ""; }; - BD25E05B1FE21A77A6BC5DD264324691 /* BigInt-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "BigInt-Info.plist"; sourceTree = ""; }; - BD452434C32536EDBC8CAD6DC25620BA /* scalar_4x64.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_4x64.h; path = secp256k1/scalar_4x64.h; sourceTree = ""; }; - BE9D82014458E89E6539B74D54A41391 /* KeystoreManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KeystoreManager.swift; path = Sources/web3swift/KeystoreManager/KeystoreManager.swift; sourceTree = ""; }; - C092ED0FA8FE817ECF8A7DC1D8EC6B35 /* ecdsa.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecdsa.h; path = secp256k1/ecdsa.h; sourceTree = ""; }; - C43626EDF665B4B69437F35D9138008F /* Web3+Contract.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Contract.swift"; path = "Sources/web3swift/Web3/Web3+Contract.swift"; sourceTree = ""; }; - C451C115F7D090FDCDB0F35DC85231E4 /* torusNodePub.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = torusNodePub.swift; path = Sources/FetchNodeDetails/torusNodePub.swift; sourceTree = ""; }; - C517F94DAEE3BC8B1A82A8B17EB4760A /* hash.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = hash.h; path = secp256k1/hash.h; sourceTree = ""; }; - C547686949AD5C067704A7A6C2A068BE /* scalar_8x32_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_8x32_impl.h; path = secp256k1/scalar_8x32_impl.h; sourceTree = ""; }; - C59FBCFF1F570E941E9FE5F8C78723AB /* RandomBytesSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RandomBytesSequence.swift; path = Sources/CryptoSwift/RandomBytesSequence.swift; sourceTree = ""; }; - C733688975F1D4437EFCBDE5960EF023 /* Base58.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Base58.swift; sourceTree = ""; }; - C793B6404EE0B8793B81F5E7CDE85FA0 /* Web3+ERC1643.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1643.swift"; path = "Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift"; sourceTree = ""; }; - C7EF73D81E9A87A047E023330053C98E /* README.md */ = {isa = PBXFileReference; includeInIndex = 1; path = README.md; sourceTree = ""; }; - C81F263315CE868909527F13C8B601CA /* ABIParsing.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ABIParsing.swift; path = Sources/web3swift/EthereumABI/ABIParsing.swift; sourceTree = ""; }; - C8DAA386BC2D44F1C22D3A73622A2899 /* join.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = join.m; path = Sources/join.m; sourceTree = ""; }; - C9493E9FCDA044080B2F1FD5E08DABA8 /* CryptoSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = CryptoSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - C9A42A5D1E2D850B1F7F8E8F6F7F7188 /* Data+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Data+Extension.swift"; path = "Sources/web3swift/Convenience/Data+Extension.swift"; sourceTree = ""; }; - CA38481A10469E72124DD89F5DC85BDD /* Pods-TestApplication-TestApplicationTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-TestApplication-TestApplicationTests-dummy.m"; sourceTree = ""; }; - CAA68AAE05D4D14071FB751CAC510CF7 /* BigInt.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = BigInt.modulemap; sourceTree = ""; }; - CC4196F01C84C79E6BA8B684CC7FE8CF /* Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Promise.swift; path = Sources/Promise.swift; sourceTree = ""; }; - CD3D2A6042B0466EC93ED0D38E38186A /* scalar_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_impl.h; path = secp256k1/scalar_impl.h; sourceTree = ""; }; - CD6FC58247337A77A51732D694282647 /* TorusUtils.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TorusUtils.swift; path = Sources/TorusUtils/TorusUtils.swift; sourceTree = ""; }; - CD73768AF6E3FE9580E85BFF3E217FEE /* Torus-fetchNodeDetails.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Torus-fetchNodeDetails.release.xcconfig"; sourceTree = ""; }; - CEA6D1C1DD153D88A1AC3CDA4DAA1BBF /* 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 = ""; }; - CEC31D6A49140A8533DE7811B519DB98 /* Pods-TestApplication-TestApplicationTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-TestApplication-TestApplicationTests-umbrella.h"; sourceTree = ""; }; - CF2A784B822F1600850625C29FB9C104 /* Blowfish+Foundation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Blowfish+Foundation.swift"; path = "Sources/CryptoSwift/Foundation/Blowfish+Foundation.swift"; sourceTree = ""; }; - CF6609F1E57DECC7C1DA6D137C3DA0A5 /* scalar_4x64_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = scalar_4x64_impl.h; path = secp256k1/scalar_4x64_impl.h; sourceTree = ""; }; - CFA40A9F7963D95FF63F17BD122257B2 /* 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 = ""; }; - D046A51420E0E9E3D0C5811918D9FDF8 /* after.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = after.swift; path = Sources/after.swift; sourceTree = ""; }; - D05EFFB2585F856465241E04BE6B4437 /* BestLogger.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = BestLogger.release.xcconfig; sourceTree = ""; }; - D1E53313719F7918997A997F6DF22863 /* Bridge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bridge.swift; path = Sources/web3swift/Browser/Bridge.swift; sourceTree = ""; }; - D222E59F523707BFCD3EBD7E857537C6 /* Data+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "Data+Extension.swift"; sourceTree = ""; }; - D24EA038E3E35A59264E498AA94ECB87 /* Decodable+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "Decodable+Extensions.swift"; sourceTree = ""; }; - D34674A4FB818DC9CB7B920E2180B2CB /* UIViewPropertyAnimator+Promise.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIViewPropertyAnimator+Promise.swift"; path = "Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift"; sourceTree = ""; }; - D3A9281D74A2B5E87D9CF6464C7066F6 /* 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 = ""; }; - D4251BC1432EB0343A2E8895B0371187 /* Web3+Constants.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Constants.swift"; path = "Sources/web3swift/Web3/Web3+Constants.swift"; sourceTree = ""; }; - D4A6E662E95C1F325699B62C766A94B8 /* BestLogger.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = BestLogger.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - D4F8314521B826E9B32104ECF4AB4267 /* Cryptors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cryptors.swift; path = Sources/CryptoSwift/Cryptors.swift; sourceTree = ""; }; - D51B46D48CE0BC8E8AFF1AA7E29FE50B /* PromiseKit.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.debug.xcconfig; sourceTree = ""; }; - D5367E61AF3C21C9DCDC55B6114FAE7C /* CryptoSwift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "CryptoSwift-Info.plist"; sourceTree = ""; }; - D602E155ACAA4143210F7BFF844AC1C4 /* Starscream.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Starscream.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - D66EC39D540DA888CAC8F3E40E894EEE /* hang.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = hang.m; path = Sources/hang.m; sourceTree = ""; }; - D69C06C96418E899C7F19C5ED2930255 /* NSURLSession+AnyPromise.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSURLSession+AnyPromise.h"; path = "Extensions/Foundation/Sources/NSURLSession+AnyPromise.h"; sourceTree = ""; }; - D7C6C331D727E9B470A6449D98B0F0FC /* UIViewController+AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIViewController+AnyPromise.m"; path = "Extensions/UIKit/Sources/UIViewController+AnyPromise.m"; sourceTree = ""; }; - D7E1CE33CE4EC974DADA9A94C05B3949 /* 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 = ""; }; - D8633CD3434757180B44615D96BDA870 /* Torus-utils-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Torus-utils-umbrella.h"; sourceTree = ""; }; - D8A94D85576CA4545A9A0095CCE8D476 /* Bit.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bit.swift; path = Sources/CryptoSwift/Bit.swift; sourceTree = ""; }; - D8B766BB142215E16DA4BD1E055A6DC1 /* PBKDF2.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PBKDF2.swift; path = Sources/CryptoSwift/PKCS/PBKDF2.swift; sourceTree = ""; }; - D92F9E70385EBF2A8803AC9161D1CACB /* Web3+ST20.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ST20.swift"; path = "Sources/web3swift/Tokens/ST20/Web3+ST20.swift"; sourceTree = ""; }; - D9D4E09DA60B39BABA588D1D5927338B /* MD5.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MD5.swift; path = Sources/CryptoSwift/MD5.swift; sourceTree = ""; }; - DA9CBD83FD7987D94630D1C21A5709ED /* Resolver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Resolver.swift; path = Sources/Resolver.swift; sourceTree = ""; }; - DAC31B8DC645DD739D2550D2520A8253 /* 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 = ""; }; - DAC5419747B4F5C0A8F7F53295E16194 /* NativeTypesEncoding+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "NativeTypesEncoding+Extensions.swift"; sourceTree = ""; }; - DB3377F02EA7E24B1239A7648440A236 /* WebSocket.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Sources/Starscream/WebSocket.swift; sourceTree = ""; }; - DB4F895E66EF6D86F159E98B5E36B539 /* Web3+ERC1410.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1410.swift"; path = "Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift"; sourceTree = ""; }; - DB8657E6956CA0FF8B97C41696F5799E /* CryptoSwift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "CryptoSwift-prefix.pch"; sourceTree = ""; }; - DDF0C91FFEDE03691C23477F55016C10 /* CCM.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CCM.swift; path = Sources/CryptoSwift/BlockMode/CCM.swift; sourceTree = ""; }; - DE689BD3F8DF79153838FEB2BE1E2348 /* ecmult_gen.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = ecmult_gen.h; path = secp256k1/ecmult_gen.h; sourceTree = ""; }; - DE7153C49C1795F5BC69C8C58121A921 /* String.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = String.swift; path = Sources/FetchNodeDetails/extensions/String.swift; sourceTree = ""; }; - DE760851799E2CCC3C0E2B498E5306FC /* BIP32HDNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BIP32HDNode.swift; path = Sources/web3swift/KeystoreManager/BIP32HDNode.swift; sourceTree = ""; }; - DF0F7BE2BFEE5598CFE63E715EBA3758 /* after.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = after.m; path = Sources/after.m; sourceTree = ""; }; - DF3DFD6E474AAF0850E29CF9CE9A81D0 /* KeystoreV3JSONStructure.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KeystoreV3JSONStructure.swift; path = Sources/web3swift/KeystoreManager/KeystoreV3JSONStructure.swift; sourceTree = ""; }; - DF8387102D69B2377094DD61EC92FEDB /* Integer Conversion.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Integer Conversion.swift"; path = "Sources/Integer Conversion.swift"; sourceTree = ""; }; - DF9BC92C2E27EE31FB82EBC7672E15CF /* Scrypt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Scrypt.swift; path = Sources/CryptoSwift/Scrypt.swift; sourceTree = ""; }; - E00279CE0936ACEEEBC44C2574B16DC7 /* GCM.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GCM.swift; path = Sources/CryptoSwift/BlockMode/GCM.swift; sourceTree = ""; }; - E3A0A3391596928CD25051A18A1F50C3 /* secp256k1.c-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "secp256k1.c-prefix.pch"; sourceTree = ""; }; - E420C52E00AB438D30BF7A43B76F93C2 /* PKCS5.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PKCS5.swift; path = Sources/CryptoSwift/PKCS/PKCS5.swift; sourceTree = ""; }; - E581299139437BE8AF562F501F03C4AB /* ethereumNetwork.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ethereumNetwork.swift; path = Sources/FetchNodeDetails/ethereumNetwork.swift; sourceTree = ""; }; - E5C0758AF7131C4B8811CC48D12EC15D /* Starscream-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Starscream-dummy.m"; sourceTree = ""; }; - E73B92A342365008203DB7ADFA39818A /* IBAN.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = IBAN.swift; path = Sources/web3swift/KeystoreManager/IBAN.swift; sourceTree = ""; }; - E7849FB52B2A2A77E6E9988F206012FF /* Promise+HttpProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Promise+HttpProvider.swift"; path = "Sources/web3swift/Promises/Promise+HttpProvider.swift"; sourceTree = ""; }; - E79A0111B1CF47529D54C51594F84539 /* Poly1305.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Poly1305.swift; path = Sources/CryptoSwift/Poly1305.swift; sourceTree = ""; }; - E85769E3AFFF9C65DAB6FE5D344B5E33 /* Strideable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Strideable.swift; path = Sources/Strideable.swift; sourceTree = ""; }; - E89EF6F927A69D30F1E0B5E83254DF68 /* DigestType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DigestType.swift; path = Sources/CryptoSwift/DigestType.swift; sourceTree = ""; }; - E935BCC5B06D492AD6FE80DEAE1A1346 /* PKCS7.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PKCS7.swift; path = Sources/CryptoSwift/PKCS/PKCS7.swift; sourceTree = ""; }; - EA59B6CDFAF9792622891F2261B4E3DF /* Torus-fetchNodeDetails.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Torus-fetchNodeDetails.modulemap"; sourceTree = ""; }; - EAF16D4E2084BD41DAE5259DAB8FB662 /* Int+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Int+Extension.swift"; path = "Sources/CryptoSwift/Int+Extension.swift"; sourceTree = ""; }; - EC487C9F7E57FB6A764595EB00029AAD /* PromiseKit.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = PromiseKit.release.xcconfig; sourceTree = ""; }; - ECCDACE97518A2B351C94A17D61D9C02 /* Web3+WebsocketProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+WebsocketProvider.swift"; path = "Sources/web3swift/Web3/Web3+WebsocketProvider.swift"; sourceTree = ""; }; - ECDEAD373131E976FC9A426507249B78 /* Box.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Box.swift; path = Sources/Box.swift; sourceTree = ""; }; - ECFD101D49866DB9A64325CAE0CB66D7 /* SECP256k1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SECP256k1.swift; sourceTree = ""; }; - EDA50BF1534C414EDA586E4C6C654C29 /* String+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "String+Extension.swift"; sourceTree = ""; }; - EDE31A309088ACB19C211A0737B07083 /* ETHRegistrarController.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ETHRegistrarController.swift; path = Sources/web3swift/Utils/ENS/ETHRegistrarController.swift; sourceTree = ""; }; - EE0340F448C109ACD9C1CCAD62F38283 /* Web3+Options.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+Options.swift"; path = "Sources/web3swift/Web3/Web3+Options.swift"; sourceTree = ""; }; - EE10CF5EF112C5175D61542352045BE4 /* basic-config.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "basic-config.h"; path = "secp256k1/basic-config.h"; sourceTree = ""; }; - EE75DAE76B1194C740ECB38E07E66E27 /* Web3.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Web3.swift; path = Sources/web3swift/Web3/Web3.swift; sourceTree = ""; }; - EE9A11071391F38D682BE1F3CC599D97 /* Digest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Digest.swift; path = Sources/CryptoSwift/Digest.swift; sourceTree = ""; }; - EECF5BB5E32E6387F8543F14699C8A69 /* CBCMAC.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CBCMAC.swift; path = Sources/CryptoSwift/CBCMAC.swift; sourceTree = ""; }; - EF3C134A5177178545920680F7DB264A /* Web3+MutatingTransaction.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+MutatingTransaction.swift"; path = "Sources/web3swift/Web3/Web3+MutatingTransaction.swift"; sourceTree = ""; }; - F050DD99A94F00775D165DCE83830FF4 /* UInt8+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UInt8+Extension.swift"; path = "Sources/CryptoSwift/UInt8+Extension.swift"; sourceTree = ""; }; - F10C8577314FE9669A54B2816A0F88C5 /* fwd.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = fwd.h; path = Sources/fwd.h; sourceTree = ""; }; - F138B36B651F1298A2480F35906F9395 /* Web3+ERC1155.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1155.swift"; path = "Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift"; sourceTree = ""; }; - F184694494B0B73998E4F10C109A5087 /* Words and Bits.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Words and Bits.swift"; path = "Sources/Words and Bits.swift"; sourceTree = ""; }; - F1C5DA46A837EAE231568713CEE6CBA9 /* TorusUtils+extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "TorusUtils+extension.swift"; sourceTree = ""; }; - F250225BFF25426CFF2F1925C181742C /* Collection+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Collection+Extension.swift"; path = "Sources/CryptoSwift/Collection+Extension.swift"; sourceTree = ""; }; - F39B9C1518AEEE1320C383DE7547FB56 /* Pods-TestApplication-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TestApplication-Info.plist"; sourceTree = ""; }; - F503884ECADE82608ACA72266F494DED /* TransactionSigner.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TransactionSigner.swift; path = Sources/web3swift/Transaction/TransactionSigner.swift; sourceTree = ""; }; - F57CB5EBA08457BE3A768B4A2D7998B4 /* group.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = group.h; path = secp256k1/group.h; sourceTree = ""; }; - F6325783586F8C962155E191969A643C /* AnyPromise.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AnyPromise.m; path = Sources/AnyPromise.m; sourceTree = ""; }; - F6DE54368C1B3E8A157270E9BA06F283 /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Configuration.swift; path = Sources/Configuration.swift; sourceTree = ""; }; - F6EC47A89FC36ABDD81383BB895520CD /* 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 = ""; }; - F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = CryptoSwift.framework; path = CryptoSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - F838B5783FF850387FCD0760324B7F31 /* BestLogger-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "BestLogger-dummy.m"; sourceTree = ""; }; - F938C6C5E22B543C6076CD531A83ADC7 /* when.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = when.swift; path = Sources/when.swift; sourceTree = ""; }; - F9A2F264946D78178A080F59A13179EE /* PBKDF1.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PBKDF1.swift; path = Sources/CryptoSwift/PKCS/PBKDF1.swift; sourceTree = ""; }; - F9B012F1E432805425ECF952C85B24A2 /* Array+Extension.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Array+Extension.swift"; path = "Sources/web3swift/Convenience/Array+Extension.swift"; sourceTree = ""; }; - FAB928F1FDD4C97ED194CDF22569830E /* 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 = ""; }; - FB01F38BCDDBFAE68CF0096A471DCAA4 /* 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 = ""; }; - FB486A8F96DF68360671507371DA8BDB /* BigInt-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "BigInt-umbrella.h"; sourceTree = ""; }; - FC6C7738B7BEA2A7AEE22DCE0FCF8F3F /* NameHash.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NameHash.swift; path = Sources/web3swift/Utils/ENS/NameHash.swift; sourceTree = ""; }; - FC8D6E6A3C65F1625E166907BAFC6DB9 /* Web3+ERC1376.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Web3+ERC1376.swift"; path = "Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift"; sourceTree = ""; }; - FD0DBF02AE93049A9ED0ACBDD9170770 /* CryptoSwift.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = CryptoSwift.debug.xcconfig; sourceTree = ""; }; - FFEC637A0E4A6FB4540D200256F65DEE /* group_impl.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = group_impl.h; path = secp256k1/group_impl.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; - }; - 1951A36938A1B10F21ABD0E54F1FFEE8 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 3CCB015D6F0C4DB48F8C0E542FFFC076 /* BestLogger.framework in Frameworks */, - 5BF67CC8A596E6D8F6095F0F9F76F054 /* FetchNodeDetails.framework in Frameworks */, - 2A8A3DAA61C2DDA353F06CE7C36F0C65 /* Foundation.framework in Frameworks */, - 73B852F1F6A54C72C500CA87816C86BE /* PromiseKit.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 2191BF40D32BDF3F13E0864F5A0AFFF2 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 363DDC37B77721F9814603B8461DBA19 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 46F9214900CE1F500D4E081AC05BDD61 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 45B48F57B1039D463A2CB04349F22C5A /* Foundation.framework in Frameworks */, - 00542E749518733F88FD9339F521159E /* UIKit.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 6F1D48CE76242B39358287D0EBA8F869 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - E7A03A06824777BBCFD78A0EDF2C016C /* BigInt.framework in Frameworks */, - D16C45BC77A0F61CE24F4D5933DCE9AC /* CoreImage.framework in Frameworks */, - F85DFBE8857FCD8AB07C888A5C3DBBCA /* CryptoSwift.framework in Frameworks */, - CC8C5CECDBD51CCA0082D1E4789781B1 /* Foundation.framework in Frameworks */, - 672C52B2CBF9425B272A5845B0A38ABF /* PromiseKit.framework in Frameworks */, - B4733F9C8DFFA3F09BD8772F6FB1F4ED /* secp256k1.framework in Frameworks */, - CABB0902B30DA778305D8821AB2E1F83 /* Starscream.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 876782AD48A8E8FF0A08B2FDDD142D07 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 5E47C7CE3D7F87F4116FC7B83A1199E5 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 9923BD363056DBE15F71F4DEE261D183 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 74BEDC20360FEDC36867D3F4988EE59D /* BestLogger.framework in Frameworks */, - E9342EFD486C4DE0C3B6E72379D3BE13 /* Foundation.framework in Frameworks */, - 95CBDAE64A9D521D5122CF592CE78744 /* web3swift.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - A4BECEAC373E87C8B4007F4EAFC81092 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 7747F57C44FAF3D0E493D3C45F5ADDA9 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - AD14A83BF9B6A00656C3E87EB8D818A2 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - EB0450140F0DE8EC373CE3173F9CD9AF /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - E0B8A7B2CF1F2164CC1A302E7AFABD5B /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 14D34E32263C8D334AC63CA775357BA8 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - E10A92CBDE9335E7361E7E9800EE6900 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 02C5ECEA382E41FB54FF5DA325E18878 /* Targets Support Files */ = { - isa = PBXGroup; - children = ( - A15D84FBC186D019445F1DEAE83631FF /* Pods-TestApplication */, - 0BD2E917C6DA4408E22079D33E189D5A /* Pods-TestApplication-TestApplicationTests */, - ); - name = "Targets Support Files"; - sourceTree = ""; - }; - 0393D9A2B378C2E9F5269CD2F4977F9E /* Support Files */ = { - isa = PBXGroup; - children = ( - 59A3D848262E8740C07120707959C110 /* Torus-utils.modulemap */, - 70C8D6D69E1A13C98E13C5399927DBCF /* Torus-utils-dummy.m */, - 02A8B3CDF2934BC18CF61B46AEDBB749 /* Torus-utils-Info.plist */, - 78AED03C814501A370FDB3B77A13D1AC /* Torus-utils-prefix.pch */, - D8633CD3434757180B44615D96BDA870 /* Torus-utils-umbrella.h */, - 0658C457030E48C8199E56F034689824 /* Torus-utils.debug.xcconfig */, - 64CB563CCEBFB9464AC885324FCD2528 /* Torus-utils.release.xcconfig */, - ); - name = "Support Files"; - path = "cocoapods/Pods/Target Support Files/Torus-utils"; - sourceTree = ""; - }; - 0BCBA8988DA9074B994BF54DA0F90C88 /* CorePromise */ = { - isa = PBXGroup; - children = ( - DF0F7BE2BFEE5598CFE63E715EBA3758 /* after.m */, - D046A51420E0E9E3D0C5811918D9FDF8 /* after.swift */, - 1464B14DC813EA19C660522609E95C34 /* AnyPromise.h */, - F6325783586F8C962155E191969A643C /* AnyPromise.m */, - 7D0BBF0C44022F9BD5C7E2A44A669C5B /* AnyPromise.swift */, - ECDEAD373131E976FC9A426507249B78 /* Box.swift */, - AF0BEE4B0224AC7B0C9583A79622855A /* Catchable.swift */, - F6DE54368C1B3E8A157270E9BA06F283 /* Configuration.swift */, - 00B4A1544453A6ED5BD2446D6CAE4A12 /* CustomStringConvertible.swift */, - B4B962A49197959211418558342805EE /* Deprecations.swift */, - 8800939F03C2C23BCFC7AC6D89B3E29A /* dispatch_promise.m */, - AA6E5EE30B00CACE5169C7B53F93C899 /* Error.swift */, - 9C956D6C93CE03F2CDC414E5EAC7F680 /* firstly.swift */, - F10C8577314FE9669A54B2816A0F88C5 /* fwd.h */, - 74CD34049D056134BF4391B03E13C4A2 /* Guarantee.swift */, - D66EC39D540DA888CAC8F3E40E894EEE /* hang.m */, - AC767EA373C6A47D8C0E5B877E98F1BF /* hang.swift */, - C8DAA386BC2D44F1C22D3A73622A2899 /* join.m */, - B79CB3EFA0565779F964A732017D23F8 /* LogEvent.swift */, - CC4196F01C84C79E6BA8B684CC7FE8CF /* Promise.swift */, - 3B4F23EB6DCEE0E727D49E697D2F4602 /* PromiseKit.h */, - 137378E4AD849849095296939E1F272F /* race.m */, - 6B4BB1950A7E59A2522D593BBB8B7488 /* race.swift */, - DA9CBD83FD7987D94630D1C21A5709ED /* Resolver.swift */, - 84CFB5E7DC25C41F593E110F7CA2CF94 /* Thenable.swift */, - BA45C8CD81E3BEC7324DA061D9811272 /* when.m */, - F938C6C5E22B543C6076CD531A83ADC7 /* when.swift */, - ); - name = CorePromise; - sourceTree = ""; - }; - 0BD2E917C6DA4408E22079D33E189D5A /* Pods-TestApplication-TestApplicationTests */ = { - isa = PBXGroup; - children = ( - 74F9436D309E5C0320E2BF39B33369DC /* Pods-TestApplication-TestApplicationTests.modulemap */, - B2EAA5F612FE999334D6B0F6B413F776 /* Pods-TestApplication-TestApplicationTests-acknowledgements.markdown */, - BA00FA25D79D42904906782ED589D977 /* Pods-TestApplication-TestApplicationTests-acknowledgements.plist */, - CA38481A10469E72124DD89F5DC85BDD /* Pods-TestApplication-TestApplicationTests-dummy.m */, - 1764C73C5A2BAF6D7920A5164D0CD86C /* Pods-TestApplication-TestApplicationTests-frameworks.sh */, - 636F14D1D805465AFBED7A23DCC80AF4 /* Pods-TestApplication-TestApplicationTests-Info.plist */, - CEC31D6A49140A8533DE7811B519DB98 /* Pods-TestApplication-TestApplicationTests-umbrella.h */, - A3ABFE3667AA01A217809D9BE0B80D1F /* Pods-TestApplication-TestApplicationTests.debug.xcconfig */, - 7F673FD14D4ABF76640791855FBB0BB6 /* Pods-TestApplication-TestApplicationTests.release.xcconfig */, - ); - name = "Pods-TestApplication-TestApplicationTests"; - path = "Target Support Files/Pods-TestApplication-TestApplicationTests"; - sourceTree = ""; - }; - 0D22D2311D94AB2734676268FD773320 /* Support Files */ = { - isa = PBXGroup; - children = ( - 30EBA7B0DD66CEFFA209B8C22C1C96B3 /* ResourceBundle-Browser-web3swift-Info.plist */, - 428775C0D794A0F3B8EB12C991CE5DE9 /* web3swift.modulemap */, - 975066EE84D12EED3FB768B684207672 /* web3swift-dummy.m */, - 0572A9443DE659BEF362369E4A6F2BC6 /* web3swift-Info.plist */, - 7B02652C920852E623D9F913E0B1F5EA /* web3swift-prefix.pch */, - 6DB520E20CDE817BAE8A2B30E91FC879 /* web3swift-umbrella.h */, - 215B7D5D806DA1CEC59F24ABC7E54AA2 /* web3swift.debug.xcconfig */, - 4769E2DFCF57A68EF19CA75CB8034B8C /* web3swift.release.xcconfig */, - ); - name = "Support Files"; - path = "../Target Support Files/web3swift"; - sourceTree = ""; - }; - 11496463912582F119AE0FEC533758EB /* PromiseKit */ = { - isa = PBXGroup; - children = ( - 0BCBA8988DA9074B994BF54DA0F90C88 /* CorePromise */, - D243B07F94CC97815E71972813E5A2F1 /* Foundation */, - EB3E67278082B0B98484CE94FBCA7B31 /* Support Files */, - 640B6B4C279558DD1DD8C0500CD7DF06 /* UIKit */, - ); - name = PromiseKit; - path = PromiseKit; - sourceTree = ""; - }; - 135F7A04C86564D393751FD10E213A07 /* Convenience */ = { - isa = PBXGroup; - children = ( - 3EFBB66B08AAC29D6B283076F7CF0951 /* Array+Extension.swift */, - C733688975F1D4437EFCBDE5960EF023 /* Base58.swift */, - BCF0C2B61C0E69C47E9851BA327B091D /* BigUInt+Extensions.swift */, - 6082721A37AB0726E7E2B183208F595E /* CryptoExtensions.swift */, - D222E59F523707BFCD3EBD7E857537C6 /* Data+Extension.swift */, - D24EA038E3E35A59264E498AA94ECB87 /* Decodable+Extensions.swift */, - 43B2A6CA1E4D2F7A4D32596BA2E04F4E /* Dictionary+Extension.swift */, - 62A74443599E879E0E975121A027F655 /* Encodable+Extensions.swift */, - DAC5419747B4F5C0A8F7F53295E16194 /* NativeTypesEncoding+Extensions.swift */, - 0B27B50B07301DC15A482B96A4F84F6A /* NSRegularExpressionExtension.swift */, - 33D0155668F1AEAFE580678B049CB98F /* RIPEMD160+StackOveflow.swift */, - ECFD101D49866DB9A64325CAE0CB66D7 /* SECP256k1.swift */, - EDA50BF1534C414EDA586E4C6C654C29 /* String+Extension.swift */, - ); - name = Convenience; - path = Sources/TorusUtils/Convenience; - sourceTree = ""; - }; - 1364E7A61CA967CA78CD34C1E9840250 /* Extensions */ = { - isa = PBXGroup; - children = ( - F1C5DA46A837EAE231568713CEE6CBA9 /* TorusUtils+extension.swift */, - ); - name = Extensions; - path = Sources/TorusUtils/Extensions; - sourceTree = ""; - }; - 1CAEF47010418B633229E0AE08F3DCE5 /* BestLogger */ = { - isa = PBXGroup; - children = ( - 60E1AD875946CE4A244B1EC878A90E0B /* BestLogger.swift */, - 95CD06C1883CE48C609D59FB97CE9462 /* Support Files */, - ); - name = BestLogger; - path = BestLogger; - sourceTree = ""; - }; - 26D4A1B0E973DFFF3950BB99CFAC4062 /* Starscream */ = { - isa = PBXGroup; - children = ( - 623192767A29965E6C002E99496ADB9E /* Compression.swift */, - 2B065DE7641AB7C6FF473D09055AA810 /* SSLClientCertificate.swift */, - 16952F2E0ADCB355DC96DB022B63B1B9 /* SSLSecurity.swift */, - DB3377F02EA7E24B1239A7648440A236 /* WebSocket.swift */, - A26A99C15833538C57371E94B6BA4749 /* Support Files */, - ); - name = Starscream; - path = Starscream; - sourceTree = ""; - }; - 2DC1A883F419692EC104E907B23AF169 /* Products */ = { - isa = PBXGroup; - children = ( - 26A30E0DA2419B1831A942110E9826A2 /* BestLogger.framework */, - 91BB24BA472AF523E913108C9AA301F2 /* BigInt.framework */, - 12DC6A0FDF284A2C935F5EA9F6111B0B /* Browser.bundle */, - F81274EDB681F11E7CB05F7DCA2BB33C /* CryptoSwift.framework */, - 36B22267AF4D657854BDCBC896BAA6BE /* FetchNodeDetails.framework */, - 8B075CA53091CACB97CA1EC16B1B8CAC /* Pods_TestApplication.framework */, - 97241BE1FCAA933EA8779E01EEA25CB6 /* Pods_TestApplication_TestApplicationTests.framework */, - 002B1E88BA14EBF633CD66EBFBA107E9 /* PromiseKit.framework */, - 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.framework */, - 891B2270823847ED23F2ECFC28F935EC /* Starscream.framework */, - 3936ADAF803ACF9C9AF43E3304CF7768 /* TorusUtils.framework */, - 8A2449DF78D58AD33A7C7504BB3F38A0 /* web3swift.framework */, - ); - name = Products; - sourceTree = ""; - }; - 2EF31D253B59338BEF2E62AE08BA003F /* iOS */ = { - isa = PBXGroup; - children = ( - AD4460059743B10EB585030DEAE55679 /* CoreImage.framework */, - 93DA1DCA9F62B5CF3199108FB90AF568 /* Foundation.framework */, - 44050EDD065DFF0F59D2C7D56487174A /* UIKit.framework */, - ); - name = iOS; - sourceTree = ""; - }; - 328A6FB6559117887EF2F5254C34EBD3 /* Helpers */ = { - isa = PBXGroup; - children = ( - 3C9026A1A42B2C5EC3F4055F65D29F50 /* Error.swift */, - A82C338D47D72E5E229B666E9FB29815 /* JSONRPCRequest.swift */, - 89D859F38B40E4EBC5C9E12D681363A1 /* KeyAssignRequestResponse.swift */, - 16D7F4711610137560DC47C298FA7A92 /* Web3ERROR.swift */, - ); - name = Helpers; - path = Sources/TorusUtils/Helpers; - sourceTree = ""; - }; - 3426A4A3914A3305999E6C743445BF65 /* Frameworks */ = { - isa = PBXGroup; - children = ( - D4A6E662E95C1F325699B62C766A94B8 /* BestLogger.framework */, - 975A89B5D0199DE1636D45DA30498CA6 /* BigInt.framework */, - C9493E9FCDA044080B2F1FD5E08DABA8 /* CryptoSwift.framework */, - 1225388F468617B747120B6063E2688D /* FetchNodeDetails.framework */, - 94C4B2C4BB3ED30A768BCD9DCE993A60 /* PromiseKit.framework */, - 107AEC95463B537BD9F7623284A1BDA7 /* secp256k1.framework */, - D602E155ACAA4143210F7BFF844AC1C4 /* Starscream.framework */, - 1C5B04A9867B38C1C1A41A67D56372C9 /* web3swift.framework */, - 2EF31D253B59338BEF2E62AE08BA003F /* iOS */, - ); - name = Frameworks; - sourceTree = ""; - }; - 531578DDDEFC634E7FC9E999D6E1A0B5 /* Support Files */ = { - isa = PBXGroup; - children = ( - CAA68AAE05D4D14071FB751CAC510CF7 /* BigInt.modulemap */, - 54C9D3822228221ABF33D464A3046A0B /* BigInt-dummy.m */, - BD25E05B1FE21A77A6BC5DD264324691 /* BigInt-Info.plist */, - AE5DDB66F7A93C648396E85324B6FB21 /* BigInt-prefix.pch */, - FB486A8F96DF68360671507371DA8BDB /* BigInt-umbrella.h */, - 7D0E11BE6137B9B807EEF01BBBF24181 /* BigInt.debug.xcconfig */, - 3253FCDF51FD3CCA40CFC041548584F1 /* BigInt.release.xcconfig */, - ); - name = "Support Files"; - path = "../Target Support Files/BigInt"; - sourceTree = ""; - }; - 5643890D33A7A18BC19900008241C824 /* secp256k1.c */ = { - isa = PBXGroup; - children = ( - EE10CF5EF112C5175D61542352045BE4 /* basic-config.h */, - 44F01E43FBF03BD38D6D6F7AE02BEB9C /* ecdh_impl.h */, - C092ED0FA8FE817ECF8A7DC1D8EC6B35 /* ecdsa.h */, - 9CF17921439863D5241B29B9DCC9D6CA /* ecdsa_impl.h */, - 60C1AAE2EB5DABD8D89F4408AB5E3F08 /* eckey.h */, - 1E3A34EECA0DC99C3A8F3294B0270E41 /* eckey_impl.h */, - 8607984D28231447D07695D87FC3465E /* ecmult.h */, - BAEE2319C8E8D77C6DB2627C66E80708 /* ecmult_const.h */, - A9C317513ED6A8C8924B31F5F8E6FB58 /* ecmult_const_impl.h */, - DE689BD3F8DF79153838FEB2BE1E2348 /* ecmult_gen.h */, - BB6C5C1E585BD8D5914604BB64EFBD57 /* ecmult_gen_impl.h */, - 805A95545687CAF1C10291D688FFBA5E /* ecmult_impl.h */, - 0D10FB3C6D3EF1393133CA34261D1B70 /* field.h */, - 0FCE859A1C898EFD329CC8D11538DEA6 /* field_10x26.h */, - 54E2DF0C1A7123CBD20FD3B19C8EDF57 /* field_10x26_impl.h */, - 3311A7DB3CE6CA76C4B56C03CFA175A1 /* field_5x52.h */, - FAB928F1FDD4C97ED194CDF22569830E /* field_5x52_asm_impl.h */, - 9BB35F4C313D91EE8AFBFA7D34E85B04 /* field_5x52_impl.h */, - 20400A55C671EE455F595599C28C01CB /* field_5x52_int128_impl.h */, - 7C4E4C5A7B89BAC92AF3CDF8A3DF20C5 /* field_impl.h */, - F57CB5EBA08457BE3A768B4A2D7998B4 /* group.h */, - FFEC637A0E4A6FB4540D200256F65DEE /* group_impl.h */, - C517F94DAEE3BC8B1A82A8B17EB4760A /* hash.h */, - 69CC6C3B6338B8B1D8CBAF297925E3EB /* hash_impl.h */, - 46D25574FD61890717200D7A5ECA5244 /* num.h */, - 79FFF2FD3F5D49331504AD9FB3B06AF7 /* num_gmp.h */, - 749DDD6C8309DAD6BBCF7410355CB4D3 /* num_gmp_impl.h */, - ABD51BF16E0DBDE492E7FEEBBEBA6EBA /* num_impl.h */, - 6E7A807E2744EF86C0208B7213A91F86 /* recovery_impl.h */, - 24D977E748EAED64A5418C6749B97C72 /* scalar.h */, - BD452434C32536EDBC8CAD6DC25620BA /* scalar_4x64.h */, - CF6609F1E57DECC7C1DA6D137C3DA0A5 /* scalar_4x64_impl.h */, - 2BF0E5B419AE36443D1D1F57ECB5323F /* scalar_8x32.h */, - C547686949AD5C067704A7A6C2A068BE /* scalar_8x32_impl.h */, - CD3D2A6042B0466EC93ED0D38E38186A /* scalar_impl.h */, - 100310643E25D378253348B194F083D1 /* scalar_low.h */, - BBE375A431A0CAAD97FE1B50B09ECFBC /* scalar_low_impl.h */, - 9A55358BC9BF9260CA0B353D1E198EDD /* scratch.h */, - 0DF19828A60D0F07C54CF9F4EBF91996 /* scratch_impl.h */, - 9574BD191822B8CA2B44360C0DAFEE0D /* secp256k1.c */, - 14D268E0C6A9A8606B2F5F1A263791A3 /* secp256k1.h */, - 0296EB918A3A6BC54B0A83486D15B463 /* secp256k1-config.h */, - 2232E13ECA21F9463469D2356DD59817 /* secp256k1_ec_mult_static_context.h */, - 36596C1155BCF36D4AC1E20D7F7DD4E0 /* secp256k1_main.h */, - 0A289037323484D2BB6891F50AC0966C /* util.h */, - B0168558E4820C54C9DB1F8D5C91E9D8 /* Support Files */, - ); - name = secp256k1.c; - path = secp256k1.c; - sourceTree = ""; - }; - 640B6B4C279558DD1DD8C0500CD7DF06 /* UIKit */ = { - isa = PBXGroup; - children = ( - 4B9B3D2E1749E19CD5247226FC2A0DE9 /* PMKUIKit.h */, - 7865861740168F97EBF3471A1E99D0C4 /* UIView+AnyPromise.h */, - 65772FBA70CCA564031A7DB655375942 /* UIView+AnyPromise.m */, - 403758DEF6A4E7BB2F98889B82A135A9 /* UIView+Promise.swift */, - 458A8AB2661A57F37E4E70311F75F5FE /* UIViewController+AnyPromise.h */, - D7C6C331D727E9B470A6449D98B0F0FC /* UIViewController+AnyPromise.m */, - D34674A4FB818DC9CB7B920E2180B2CB /* UIViewPropertyAnimator+Promise.swift */, - ); - name = UIKit; - sourceTree = ""; - }; - 65E7D577089527AAE8752FD1322016A2 /* Pod */ = { - isa = PBXGroup; - children = ( - 741C3A5883AB6FC983592C617CE51CAC /* License.md */, - C7EF73D81E9A87A047E023330053C98E /* README.md */, - 96F6072F2F4703F5643796E5AE8EF7D0 /* Torus-utils.podspec */, - ); - name = Pod; - sourceTree = ""; - }; - 66ADD914349696422483C1F117586DDD /* Torus-utils */ = { - isa = PBXGroup; - children = ( - CD6FC58247337A77A51732D694282647 /* TorusUtils.swift */, - 135F7A04C86564D393751FD10E213A07 /* Convenience */, - 1364E7A61CA967CA78CD34C1E9840250 /* Extensions */, - 328A6FB6559117887EF2F5254C34EBD3 /* Helpers */, - 65E7D577089527AAE8752FD1322016A2 /* Pod */, - 0393D9A2B378C2E9F5269CD2F4977F9E /* Support Files */, - ); - name = "Torus-utils"; - path = ../..; - sourceTree = ""; - }; - 82810480A5E655B7E0EE4FC290DA89C1 /* Torus-fetchNodeDetails */ = { - isa = PBXGroup; - children = ( - BB147247ABF7F4DAFD652DD4A718F13F /* abi.json */, - 7B1BE46004B0E262840E88B6B4316CEF /* abi.swift */, - 68565345731E54A07E8961540F271397 /* epochInfo.swift */, - E581299139437BE8AF562F501F03C4AB /* ethereumNetwork.swift */, - 9A1A105339FBDCF49E1692DAC870181F /* fetchNodeDetails.swift */, - 2B9B33F9B214514D6A7B86948424A1AB /* fetchNodeDetails+promise.swift */, - 3509820FD1FC52A8BD603D3560AC9E37 /* nodeDetails.swift */, - A4A09751392B322E31DEAC69C3FE848F /* nodeInfo.swift */, - DE7153C49C1795F5BC69C8C58121A921 /* String.swift */, - C451C115F7D090FDCDB0F35DC85231E4 /* torusNodePub.swift */, - C8EA9872DAA2D05B9053BF0758B92979 /* Support Files */, - ); - name = "Torus-fetchNodeDetails"; - path = "Torus-fetchNodeDetails"; - sourceTree = ""; - }; - 95CD06C1883CE48C609D59FB97CE9462 /* Support Files */ = { - isa = PBXGroup; - children = ( - 9F77F548DB5C2368A36DA59A671FD248 /* BestLogger.modulemap */, - F838B5783FF850387FCD0760324B7F31 /* BestLogger-dummy.m */, - 28E24C7638C3C9F480F6DE1C4E8D3DD0 /* BestLogger-Info.plist */, - 96B1C06C49366D9076D665592EECCC28 /* BestLogger-prefix.pch */, - 283CC747FD0DCC168EE28C22BE24FB13 /* BestLogger-umbrella.h */, - B88A9BF2B3A86B0BD42B03214218D438 /* BestLogger.debug.xcconfig */, - D05EFFB2585F856465241E04BE6B4437 /* BestLogger.release.xcconfig */, - ); - name = "Support Files"; - path = "../Target Support Files/BestLogger"; - sourceTree = ""; - }; - 9F74157617248C069B0CCD9559CF6B07 /* CryptoSwift */ = { - isa = PBXGroup; - children = ( - 68F29EE2740CD5F7D9F2742ACB0C68AC /* AEAD.swift */, - 861D5F94C97320DB5B5A576B7DE1046A /* AEADChaCha20Poly1305.swift */, - 547193FFA17662EE95EF699A2570D30B /* AES.swift */, - 0FB42BBCB8503EAD2C9CB5548BD0EEEF /* AES+Foundation.swift */, - 33814A070AAF84C7E6D9C47D4A9DA47A /* AES.Cryptors.swift */, - BB1204BA343D2E4FE433DF065E5739C8 /* Array+Extension.swift */, - B199C90B54B508CC6863DC3B86C34A12 /* Array+Foundation.swift */, - 31C3703C315175092D73AECC95DE71B7 /* Authenticator.swift */, - 26E93968E466D33AED110C6354F60201 /* BatchedCollection.swift */, - D8A94D85576CA4545A9A0095CCE8D476 /* Bit.swift */, - BC79DFF5B9C04D7FE20DD358512F0C5E /* BlockCipher.swift */, - A1EDB95C55FE665B44017C14EF40CA8F /* BlockDecryptor.swift */, - 5AF1CFD2C9895A1EDAFD919380565FB3 /* BlockEncryptor.swift */, - AE4102418DE6E7E4CED7680542ACA596 /* BlockMode.swift */, - 49E00ED54B318307C4DE75639CE0317B /* BlockModeOptions.swift */, - 17FBF1870F76BBA85154777D12F92DD0 /* Blowfish.swift */, - CF2A784B822F1600850625C29FB9C104 /* Blowfish+Foundation.swift */, - BB346C38513FA9E9018CE31D0EB8E613 /* CBC.swift */, - EECF5BB5E32E6387F8543F14699C8A69 /* CBCMAC.swift */, - DDF0C91FFEDE03691C23477F55016C10 /* CCM.swift */, - 7E09DE6376C302F500D47F146994DBCE /* CFB.swift */, - 9A71430DAF19B7345290774BF3DF061A /* ChaCha20.swift */, - 917B6EFF40524BB04100155BBFBA26F5 /* ChaCha20+Foundation.swift */, - 2D6CF27A12D3F3EF5494307E376E9EAD /* Checksum.swift */, - 37E49D3B34BDED405190E64976AE77B2 /* Cipher.swift */, - 54E37A2DF9578412AA69A5BEFC18EE7B /* CipherModeWorker.swift */, - 3FC83725DA96C508A8896086BFAF1B1F /* CMAC.swift */, - F250225BFF25426CFF2F1925C181742C /* Collection+Extension.swift */, - 12E4A924E952E7332BA0F49D08661F92 /* CompactMap.swift */, - 3467A6DA60C93415C18CAD34E5B58ADD /* Cryptor.swift */, - D4F8314521B826E9B32104ECF4AB4267 /* Cryptors.swift */, - 9A7C7440F23854147993BEA3BF179B7A /* CTR.swift */, - A6D43ECDBFBD5966FA8C97853B7A6744 /* Data+Extension.swift */, - EE9A11071391F38D682BE1F3CC599D97 /* Digest.swift */, - E89EF6F927A69D30F1E0B5E83254DF68 /* DigestType.swift */, - 30B0D8BAF890F4EFCB9D256CC130AAA5 /* ECB.swift */, - E00279CE0936ACEEEBC44C2574B16DC7 /* GCM.swift */, - 532AD590CA6E6DFA10973018D68A00B9 /* Generics.swift */, - B3F19A59C557ADA87DA85B082C792879 /* HKDF.swift */, - 98302BCB7B2D63FE1C809B7EED544A31 /* HMAC.swift */, - 84B27F6051F06DF5A4E6F7214D0B0BF3 /* HMAC+Foundation.swift */, - EAF16D4E2084BD41DAE5259DAB8FB662 /* Int+Extension.swift */, - D9D4E09DA60B39BABA588D1D5927338B /* MD5.swift */, - 11B2495717C3300B60C1D01F85E169CD /* NoPadding.swift */, - 0BF39D2D98FFC5533B5BA217BCDB7AD9 /* OFB.swift */, - A17BF4AEEC01E419833321F0C76BF3A3 /* Operators.swift */, - 30F3E8F002317CB34DEBAC0F376015B0 /* Padding.swift */, - F9A2F264946D78178A080F59A13179EE /* PBKDF1.swift */, - D8B766BB142215E16DA4BD1E055A6DC1 /* PBKDF2.swift */, - B586613F92A74DDD67224217EF339232 /* PCBC.swift */, - E420C52E00AB438D30BF7A43B76F93C2 /* PKCS5.swift */, - E935BCC5B06D492AD6FE80DEAE1A1346 /* PKCS7.swift */, - 7AFDF177A0326BCF4BF54E5BAA19ADB3 /* PKCS7Padding.swift */, - E79A0111B1CF47529D54C51594F84539 /* Poly1305.swift */, - 7F9D9BAC5011C578C942C96A9193C5A2 /* Rabbit.swift */, - 304513EC2F0CF7D352C919E34D643691 /* Rabbit+Foundation.swift */, - C59FBCFF1F570E941E9FE5F8C78723AB /* RandomBytesSequence.swift */, - DF9BC92C2E27EE31FB82EBC7672E15CF /* Scrypt.swift */, - BAAD698E863ED4A0CCEEBB0C78DCA770 /* SecureBytes.swift */, - 1A8C1DF42DDB1B2C7A3407B3FC998671 /* SHA1.swift */, - 7068BB4E0872B6DEC38E77F1B04ECDB7 /* SHA2.swift */, - 280BDA4851FC9E3A332073A8A1E52A71 /* SHA3.swift */, - 99D17C88D422705B026AAE3CB31EA369 /* StreamDecryptor.swift */, - 66D8D2442F980738A4DF46016A1C658B /* StreamEncryptor.swift */, - 43D6002B89854A8CA87F6E11D2A4774B /* String+Extension.swift */, - BC681896D4212B9DA6C9384F3344234F /* String+FoundationExtension.swift */, - 1A0B5C4DD84A6A8B0E535041C9CFF6AE /* UInt128.swift */, - A2835A01E0247A5156E927DCA5C1A2A5 /* UInt16+Extension.swift */, - 2E31FB5291F104D8F312D4A179031B59 /* UInt32+Extension.swift */, - 736C7B0AB9E592CCF99B60A020F609C4 /* UInt64+Extension.swift */, - F050DD99A94F00775D165DCE83830FF4 /* UInt8+Extension.swift */, - 648384FDC27C062F3B5B39565DC0B287 /* Updatable.swift */, - 08859518C8A8BA3027D2209AEDBC64AC /* Utils.swift */, - 9C0DC37E22F8903645A132FC89D8C1DC /* Utils+Foundation.swift */, - 343893B600C18CE40D9AB491CBE66E9B /* ZeroPadding.swift */, - C09A6683D4053151F5AE9530BA321F17 /* Support Files */, - ); - name = CryptoSwift; - path = CryptoSwift; - sourceTree = ""; - }; - A15D84FBC186D019445F1DEAE83631FF /* Pods-TestApplication */ = { - isa = PBXGroup; - children = ( - 588AE181250B323137C9868209035ECB /* Pods-TestApplication.modulemap */, - B99D9981AEBF8D8652D52D14D95114E4 /* Pods-TestApplication-acknowledgements.markdown */, - 4E3960E268984162FF5DDA0F17BCE57F /* Pods-TestApplication-acknowledgements.plist */, - 9480EC5419F2059D80BD085B2DBF2323 /* Pods-TestApplication-dummy.m */, - F39B9C1518AEEE1320C383DE7547FB56 /* Pods-TestApplication-Info.plist */, - 1F35ACAD54CA4C8BA1628EEC5C9C803A /* Pods-TestApplication-umbrella.h */, - B5359F2F46F8C6AC35F1007EE324CE53 /* Pods-TestApplication.debug.xcconfig */, - 421F491B9F8AB1BC9C6616B284D46A65 /* Pods-TestApplication.release.xcconfig */, - ); - name = "Pods-TestApplication"; - path = "Target Support Files/Pods-TestApplication"; - sourceTree = ""; - }; - A26A99C15833538C57371E94B6BA4749 /* Support Files */ = { - isa = PBXGroup; - children = ( - 4CFC14BE3601EA8C363263E0B5679F6F /* Starscream.modulemap */, - E5C0758AF7131C4B8811CC48D12EC15D /* Starscream-dummy.m */, - 1A049A6FF6D386AEB2F79B80D8F58201 /* Starscream-Info.plist */, - 289E1FCEA10E48367C2D0CCABD86802C /* Starscream-prefix.pch */, - 8F2AFB6AD39C5E71058F032B2081D300 /* Starscream-umbrella.h */, - 9148A4156B244104E844B817FB162F4C /* Starscream.debug.xcconfig */, - 49E9940B89C37FD51942B42F1C5657D3 /* Starscream.release.xcconfig */, - ); - name = "Support Files"; - path = "../Target Support Files/Starscream"; - sourceTree = ""; - }; - A58205C21E81FDEE6DFD4917812B8D16 /* Development Pods */ = { - isa = PBXGroup; - children = ( - 66ADD914349696422483C1F117586DDD /* Torus-utils */, - ); - name = "Development Pods"; - sourceTree = ""; - }; - A6D653C62B39629E238524F2AF7ECA72 /* Pods */ = { - isa = PBXGroup; - children = ( - 1CAEF47010418B633229E0AE08F3DCE5 /* BestLogger */, - CBE3AD78AA9718DA8467D0961AAC0B16 /* BigInt */, - 9F74157617248C069B0CCD9559CF6B07 /* CryptoSwift */, - 11496463912582F119AE0FEC533758EB /* PromiseKit */, - 5643890D33A7A18BC19900008241C824 /* secp256k1.c */, - 26D4A1B0E973DFFF3950BB99CFAC4062 /* Starscream */, - 82810480A5E655B7E0EE4FC290DA89C1 /* Torus-fetchNodeDetails */, - E100F5255FF53A72F24B4A6390218CAE /* web3swift */, - ); - name = Pods; - sourceTree = ""; - }; - B0168558E4820C54C9DB1F8D5C91E9D8 /* Support Files */ = { - isa = PBXGroup; - children = ( - 2DAAC1D359C5B25F5C9C011AF77E1CB5 /* secp256k1.c.modulemap */, - 6B65A61831421C6750C3861BC12E0C45 /* secp256k1.c-dummy.m */, - 67D4DF46AEC809E807D0A8ECEF69B7BE /* secp256k1.c-Info.plist */, - E3A0A3391596928CD25051A18A1F50C3 /* secp256k1.c-prefix.pch */, - 9A83CE7F4E5E202D7F1C4F4CAFE68D5A /* secp256k1.c-umbrella.h */, - 89DE8CC0478156EF8E36CDA5F88E6218 /* secp256k1.c.debug.xcconfig */, - 3E945AEB44FCBEDA491D75A9A46BC158 /* secp256k1.c.release.xcconfig */, - ); - name = "Support Files"; - path = "../Target Support Files/secp256k1.c"; - sourceTree = ""; - }; - B14A5EEB3D0AC4743FDB21F26647539A /* Resources */ = { - isa = PBXGroup; - children = ( - 7084A45BBF491661009BA2F1F1FFA83D /* browser.js */, - 93BBFE788270709884A832C695A7D9B1 /* browser.min.js */, - 0AE7A1D74F6EEDB965C2CFF1D9C301F5 /* wk.bridge.min.js */, - ); - name = Resources; - sourceTree = ""; - }; - C09A6683D4053151F5AE9530BA321F17 /* Support Files */ = { - isa = PBXGroup; - children = ( - 5EB72F7C7F019D09A7B0DF1DAB426080 /* CryptoSwift.modulemap */, - 6AB74F071919892DEDA2B20512603D17 /* CryptoSwift-dummy.m */, - D5367E61AF3C21C9DCDC55B6114FAE7C /* CryptoSwift-Info.plist */, - DB8657E6956CA0FF8B97C41696F5799E /* CryptoSwift-prefix.pch */, - 21EEF7760B023045FC31EC473557A490 /* CryptoSwift-umbrella.h */, - FD0DBF02AE93049A9ED0ACBDD9170770 /* CryptoSwift.debug.xcconfig */, - 2CA8362AD3A3AE16C1B934C3B653BE05 /* CryptoSwift.release.xcconfig */, - ); - name = "Support Files"; - path = "../Target Support Files/CryptoSwift"; - sourceTree = ""; - }; - C8EA9872DAA2D05B9053BF0758B92979 /* Support Files */ = { - isa = PBXGroup; - children = ( - EA59B6CDFAF9792622891F2261B4E3DF /* Torus-fetchNodeDetails.modulemap */, - 610164D574FDBA5D2B86AD20803A34C7 /* Torus-fetchNodeDetails-dummy.m */, - 69E3B99D314855023E8E56ED2D273292 /* Torus-fetchNodeDetails-Info.plist */, - B22522DBF599DA791D7EE3F3D10BE027 /* Torus-fetchNodeDetails-prefix.pch */, - 7E9C126C1E762F5A9CBB417F5BEDC4BA /* Torus-fetchNodeDetails-umbrella.h */, - 3DDBF242F10DF61068E5BC1FC6DC2E65 /* Torus-fetchNodeDetails.debug.xcconfig */, - CD73768AF6E3FE9580E85BFF3E217FEE /* Torus-fetchNodeDetails.release.xcconfig */, - ); - name = "Support Files"; - path = "../Target Support Files/Torus-fetchNodeDetails"; - sourceTree = ""; - }; - CBE3AD78AA9718DA8467D0961AAC0B16 /* BigInt */ = { - isa = PBXGroup; - children = ( - 9591EFA1AE71B666915FB5B8C763A34F /* Addition.swift */, - B53A9F8E880B31A0E6C1649C07767374 /* BigInt.swift */, - 929A382CB9CC2554AB704DB58025119C /* BigUInt.swift */, - A5795FBFDECE1EE5D44334B0E86704C3 /* Bitwise Ops.swift */, - 9645F90AD29640672EB3F4C6306E2CA8 /* Codable.swift */, - 5C0584AA4F770CFB96D81C2F740F5B48 /* Comparable.swift */, - 97BA2657F2505CCC7EEA41D25BB7CD60 /* Data Conversion.swift */, - 2F765D728D60C038B07F08BE54D2913F /* Division.swift */, - 62878F4D3CFBB00EBD025FF63E76375F /* Exponentiation.swift */, - 432B19CC00325EAC433376693879C00D /* Floating Point Conversion.swift */, - A57FA60848C2DC82A2D474D2DE260055 /* GCD.swift */, - 898923CC0589827D44FC74523112C46C /* Hashable.swift */, - DF8387102D69B2377094DD61EC92FEDB /* Integer Conversion.swift */, - BC594840B7ACD8661A072BE4D284BAC0 /* Multiplication.swift */, - 86E812F60C2C434B4835413EBC00BE04 /* Prime Test.swift */, - 28336DCCBEBDD902BCD17311A29807FC /* Random.swift */, - 958577E37A0C6899FA8F40D1ECF43198 /* Shifts.swift */, - BB66295E387734C568DC4F306928B9E7 /* Square Root.swift */, - E85769E3AFFF9C65DAB6FE5D344B5E33 /* Strideable.swift */, - 54255A778D9AA0DB0A5D3A32AA4B0276 /* String Conversion.swift */, - 493D56F05A52E5B4339485C92C6232F6 /* Subtraction.swift */, - F184694494B0B73998E4F10C109A5087 /* Words and Bits.swift */, - 531578DDDEFC634E7FC9E999D6E1A0B5 /* Support Files */, - ); - name = BigInt; - path = BigInt; - sourceTree = ""; - }; - CF1408CF629C7361332E53B88F7BD30C = { - isa = PBXGroup; - children = ( - 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, - A58205C21E81FDEE6DFD4917812B8D16 /* Development Pods */, - 3426A4A3914A3305999E6C743445BF65 /* Frameworks */, - A6D653C62B39629E238524F2AF7ECA72 /* Pods */, - 2DC1A883F419692EC104E907B23AF169 /* Products */, - 02C5ECEA382E41FB54FF5DA325E18878 /* Targets Support Files */, - ); - sourceTree = ""; - }; - D243B07F94CC97815E71972813E5A2F1 /* Foundation */ = { - isa = PBXGroup; - children = ( - 0B3B1825555DBF0206F9CEE6071AD20E /* afterlife.swift */, - 07C576511994B0486926E0C9AF187971 /* NSNotificationCenter+AnyPromise.h */, - 2DA6191B2FC6B5538F9C1FF662985ED9 /* NSNotificationCenter+AnyPromise.m */, - 7F0E9FE8589A3E747F1C6E49D1F665B6 /* NSNotificationCenter+Promise.swift */, - 66FBE58D0DE5590C2C0843EF48B824BF /* NSObject+Promise.swift */, - 1266EFA379D86490C2F8DE7D3FD4F149 /* NSTask+AnyPromise.h */, - A9A22D3ECB8CA971A45DBDF492F36ACB /* NSTask+AnyPromise.m */, - D69C06C96418E899C7F19C5ED2930255 /* NSURLSession+AnyPromise.h */, - 2E57FB97B6281DDB98BEC36EA0CE3C0E /* NSURLSession+AnyPromise.m */, - 25329BA0B75B6EC317AF079B1D15542A /* NSURLSession+Promise.swift */, - 7B3934C6F60ADD7B7235930EEC358D0F /* PMKFoundation.h */, - 627F7A45BFD915D896B8B858F59427E9 /* Process+Promise.swift */, - ); - name = Foundation; - sourceTree = ""; - }; - E100F5255FF53A72F24B4A6390218CAE /* web3swift */ = { - isa = PBXGroup; - children = ( - 29998CFB49DFB2CA39D28E60FC7607CD /* ABI.swift */, - 1E0D2E2DA2F63AF7BDEFD1902EC933E5 /* ABIDecoding.swift */, - 013F4DECB84F1398372538F6B5122028 /* ABIElements.swift */, - 0EE4D3F9E080E3BDB6D9D8E58DE55F54 /* ABIEncoding.swift */, - 55AF878927A572E76B0E6A029A8505D3 /* ABIParameterTypes.swift */, - C81F263315CE868909527F13C8B601CA /* ABIParsing.swift */, - 3EAC7939CF4AA08B18DE951258B603FE /* ABITypeParser.swift */, - 15B3D07F707B020B4A06817C46F852E3 /* AbstractKeystore.swift */, - F9B012F1E432805425ECF952C85B24A2 /* Array+Extension.swift */, - 394B571CD3DA252BF198EDE8DBD75729 /* Base58.swift */, - 58BF3F08DDC701824F81D3D3A3888DCC /* BigUInt+Extensions.swift */, - DE760851799E2CCC3C0E2B498E5306FC /* BIP32HDNode.swift */, - 66367BD14E3729FBAE3EEC75BFF93DC9 /* BIP32Keystore.swift */, - 4D48B83EF23A08BDB8BF4F2E68A6A921 /* BIP32KeystoreJSONStructure.swift */, - 0247C8EEE7B4D5D0983AAC08DC69FF1B /* BIP39.swift */, - 8DF1B2B15BA23A2536CCE7230A326820 /* BIP39+WordLists.swift */, - 9C399168B633166C7713975ED1A8F8B6 /* BloomFilter.swift */, - D1E53313719F7918997A997F6DF22863 /* Bridge.swift */, - 2BB30C009589E527A7DAB4ECB42B0559 /* BrowserViewController.swift */, - 4153FE15958FE1F02ACA05376FB555AF /* ComparisonExtensions.swift */, - B640F3F6BEEA3F00C6EC949A3247B36B /* ContractProtocol.swift */, - 7F36005F31C0A72C79F5F6570FDF07C5 /* CryptoExtensions.swift */, - C9A42A5D1E2D850B1F7F8E8F6F7F7188 /* Data+Extension.swift */, - 4CBB573AF014CEB32442B64D32A7D855 /* Decodable+Extensions.swift */, - A449726AD38C7BCC6A4476FB6FCC57BD /* Dictionary+Extension.swift */, - 1EDD544B32FC12296D15FFDB8DB3CEEC /* EIP67Code.swift */, - 9FC4A128639B3C17CBDB3AE67BD61BBE /* EIP681.swift */, - BCFEC24438294C64187419C5B2729D05 /* Encodable+Extensions.swift */, - 910707A9E3436E68FCDF05631CA0B2CA /* ENS.swift */, - 4542D87C52957FA0E8DD89915A7F699C /* ENSBaseRegistrar.swift */, - 7FCCD54F9BF290744B30BD7C76B31F60 /* ENSRegistry.swift */, - 40F19205E66DD1450EFD8E3E2032957B /* ENSResolver.swift */, - 18ADBE7A86B9A9960F9B87F732421591 /* ENSReverseRegistrar.swift */, - 3254F0C43CE6414EB81E1FD3C3ACA595 /* EthereumAddress.swift */, - 5410B105EBAA327591B7B1178127F21A /* EthereumContract.swift */, - 98043C01CB253479FAA51D0483638C79 /* EthereumFilterEncodingExtensions.swift */, - 61DE2FCF270DEB55C69AE65F3614A934 /* EthereumKeystoreV3.swift */, - 5BAEE36B30C5FB7510EFE984E167F4C8 /* EthereumTransaction.swift */, - EDE31A309088ACB19C211A0737B07083 /* ETHRegistrarController.swift */, - 106ED3C331045B72BCD8F2EBED8DEEEB /* EventFiltering.swift */, - 86B7A860A95575E515952D768A8DF41C /* Extensions.swift */, - E73B92A342365008203DB7ADFA39818A /* IBAN.swift */, - BE9D82014458E89E6539B74D54A41391 /* KeystoreManager.swift */, - DF3DFD6E474AAF0850E29CF9CE9A81D0 /* KeystoreV3JSONStructure.swift */, - FC6C7738B7BEA2A7AEE22DCE0FCF8F3F /* NameHash.swift */, - 77A9E9B7B569F09BB85D9AA4D7B47A61 /* NativeTypesEncoding+Extensions.swift */, - AED6B05BDFA0F12F0E5B61393689B89B /* NonceMiddleware.swift */, - 0457C62F928892E60662C7AFEB6B2EE7 /* NSRegularExpressionExtension.swift */, - 1F71BAAE30889A3196D3F193BD7EAE93 /* PlainKeystore.swift */, - 321B1BD0CEA3B32021B68BF7BC9E90E7 /* Promise+Batching.swift */, - E7849FB52B2A2A77E6E9988F206012FF /* Promise+HttpProvider.swift */, - DAC31B8DC645DD739D2550D2520A8253 /* Promise+Web3+Contract+GetIndexedEvents.swift */, - CFA40A9F7963D95FF63F17BD122257B2 /* Promise+Web3+Eth+Call.swift */, - 90BE69904F143992674611FD87C10FF0 /* Promise+Web3+Eth+EstimateGas.swift */, - 8080BE88E5AD32344368207217955275 /* Promise+Web3+Eth+GetAccounts.swift */, - 0FD9289C7B8FFD71A3CDCF3C99B18967 /* Promise+Web3+Eth+GetBalance.swift */, - 895FA234293490054981FB4B1FF1A2A0 /* Promise+Web3+Eth+GetBlockByHash.swift */, - D7E1CE33CE4EC974DADA9A94C05B3949 /* Promise+Web3+Eth+GetBlockByNumber.swift */, - 9B6B7AECEFE99816B8FBCB33CA41BA5A /* Promise+Web3+Eth+GetBlockNumber.swift */, - F6EC47A89FC36ABDD81383BB895520CD /* Promise+Web3+Eth+GetGasPrice.swift */, - 20032C66FBFC8D534B0E014C41B3FC31 /* Promise+Web3+Eth+GetTransactionCount.swift */, - 37BB11C3206A9AF2E5FB14349F0A0C72 /* Promise+Web3+Eth+GetTransactionDetails.swift */, - 14BE8AE7EA4C25E7A07F8C1C54461A52 /* Promise+Web3+Eth+GetTransactionReceipt.swift */, - FB01F38BCDDBFAE68CF0096A471DCAA4 /* Promise+Web3+Eth+SendRawTransaction.swift */, - 7F595E5162AE7A4525F876A2F65D7767 /* Promise+Web3+Eth+SendTransaction.swift */, - 12F5212F39D5EBDBC1CC6EC843E38E30 /* Promise+Web3+Personal+CreateAccount.swift */, - 87266A5B0B28E9E194A437D7509E8113 /* Promise+Web3+Personal+Sign.swift */, - CEA6D1C1DD153D88A1AC3CDA4DAA1BBF /* Promise+Web3+Personal+UnlockAccount.swift */, - 55A212FC43612F76263F35C276405A36 /* Promise+Web3+TxPool.swift */, - 0ACE6FCC5FCCB682084B1E58B8DEB240 /* PublicKey.swift */, - 7D9362939A3FBFC35D559726BAAEE2D8 /* RIPEMD160+StackOveflow.swift */, - 2B85A6893CDE4B4C76734554A0BB3969 /* RLP.swift */, - 26062370F3F43B0CCD0DB727059493EC /* SECP256k1.swift */, - 32E81D97829DA786CB8BCB3CE12AAD57 /* String+Extension.swift */, - F503884ECADE82608ACA72266F494DED /* TransactionSigner.swift */, - EE75DAE76B1194C740ECB38E07E66E27 /* Web3.swift */, - 0EEFC3B86751C2FA06B78C50AC203259 /* Web3+BrowserFunctions.swift */, - D4251BC1432EB0343A2E8895B0371187 /* Web3+Constants.swift */, - C43626EDF665B4B69437F35D9138008F /* Web3+Contract.swift */, - F138B36B651F1298A2480F35906F9395 /* Web3+ERC1155.swift */, - FC8D6E6A3C65F1625E166907BAFC6DB9 /* Web3+ERC1376.swift */, - A9360628224445199F11C25D8F17488D /* Web3+ERC1400.swift */, - DB4F895E66EF6D86F159E98B5E36B539 /* Web3+ERC1410.swift */, - 5E8A9E477BF48B7A910D0892FC633B77 /* Web3+ERC1594.swift */, - 266F457FE7F2E756EA9EFE30B0F6B05A /* Web3+ERC1633.swift */, - C793B6404EE0B8793B81F5E7CDE85FA0 /* Web3+ERC1643.swift */, - A8F20F5D5E82BF2A3C986523F803A02D /* Web3+ERC1644.swift */, - 5BB00E6935E0F6473686F43BA42E47DD /* Web3+ERC165.swift */, - 394CB452CF5827603CAB1A624E0DB36B /* Web3+ERC20.swift */, - 8B7B8BE2B958EF73B7920669D0A6165E /* Web3+ERC721.swift */, - 64406043FA5C8662A25B01ECBD9A167B /* Web3+ERC721x.swift */, - 833C4372749433AEF2DDCFD5ACD4F288 /* Web3+ERC777.swift */, - 92E67E4F9997B00CBAEF6DC5180B804E /* Web3+ERC820.swift */, - 09954F8AE56A9731301D95657001486A /* Web3+ERC888.swift */, - 8E58EE8091E64202823382773372E51D /* Web3+Eth.swift */, - D3A9281D74A2B5E87D9CF6464C7066F6 /* Web3+Eth+Websocket.swift */, - 46D72FD9B676F8CDC9814462C4FAFD62 /* Web3+Eventloop.swift */, - 1B5549F6AF497C5E9C8BD220E77944F1 /* Web3+EventParser.swift */, - 95588ED1054704883B313B15AF39B29B /* Web3+HttpProvider.swift */, - 7837B720C51246FB222DAFBB154A7EFD /* Web3+InfuraProviders.swift */, - 2029C65F287FB4F3DF0A12F1340C4A2E /* Web3+Instance.swift */, - 0B00928391D9D697250F52FE2928539E /* Web3+JSONRPC.swift */, - 5EDA937DD9FF68A701B5FB8C2C6E2991 /* Web3+Methods.swift */, - EF3C134A5177178545920680F7DB264A /* Web3+MutatingTransaction.swift */, - EE0340F448C109ACD9C1CCAD62F38283 /* Web3+Options.swift */, - 3F13C642230A43992D825AC6F75C9DE4 /* Web3+Personal.swift */, - 356E6CD41F459A448BB24F82F2CFDBF3 /* Web3+Protocols.swift */, - AE80079DF00F0A5DEDAAAD710234F15A /* Web3+ReadingTransaction.swift */, - 44A6E724DEAED085EEFF9F277E653728 /* Web3+SecurityToken.swift */, - D92F9E70385EBF2A8803AC9161D1CACB /* Web3+ST20.swift */, - 367EEC90C25E5957B79AF83B5F8C8040 /* Web3+Structures.swift */, - 0A09CDC8DE8F23E69BFDFE003EFCFBB8 /* Web3+TxPool.swift */, - 371A1B4989607A2FE45007122EB5DB1A /* Web3+Utils.swift */, - 5AB8CB5005FBD2930B346BD37D0CE897 /* Web3+Wallet.swift */, - ECCDACE97518A2B351C94A17D61D9C02 /* Web3+WebsocketProvider.swift */, - B14A5EEB3D0AC4743FDB21F26647539A /* Resources */, - 0D22D2311D94AB2734676268FD773320 /* Support Files */, - ); - name = web3swift; - path = web3swift; - sourceTree = ""; - }; - EB3E67278082B0B98484CE94FBCA7B31 /* Support Files */ = { - isa = PBXGroup; - children = ( - 3A0A98AFF43BCAD42BA27652FF57E754 /* PromiseKit.modulemap */, - 6ACB6795469A1198FA61AA30CBCE452B /* PromiseKit-dummy.m */, - B6F035EFCF554B9F05F6CDFAB107782C /* PromiseKit-Info.plist */, - 8747A39C94995D4E8E4A0BF717CE8C0B /* PromiseKit-prefix.pch */, - 80EDBAF33DE530B669F36DB988B3F7D4 /* PromiseKit-umbrella.h */, - D51B46D48CE0BC8E8AFF1AA7E29FE50B /* PromiseKit.debug.xcconfig */, - EC487C9F7E57FB6A764595EB00029AAD /* PromiseKit.release.xcconfig */, - ); - name = "Support Files"; - path = "../Target Support Files/PromiseKit"; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXHeadersBuildPhase section */ - 03E54AC2179905C71D1054BF76534E0E /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - CBC5D17000C155FEAFBFBDA26E369DD6 /* Pods-TestApplication-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 161A02771B21A722138EE16CEDF4ECF9 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 7EECE9FCF5E07473E6D0FE80BFCB94C9 /* BigInt-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 2D668541D016BFB8E06990C1107A2F01 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 8BC9AC20D0E20E6BDB7764930FCBCAE4 /* web3swift-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4A128368392A2813452844C7B5CE1638 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 1D323AAF728E32DCE9727046EC1D4A31 /* basic-config.h in Headers */, - 9B91881DDB3AB10DFB528A0C66F4B9E3 /* ecdh_impl.h in Headers */, - 3B22E2EB53E57009FD12A3DF86E2D91C /* ecdsa.h in Headers */, - 080DAC1FE3D34C0D47DD2950FEB831DA /* ecdsa_impl.h in Headers */, - B93F56B6778CCE0FEF087E13CB6DABDD /* eckey.h in Headers */, - 78A6CCB8C142F78011B6E203678B6A93 /* eckey_impl.h in Headers */, - D34F15C1BB10760B46E56479250B2FF8 /* ecmult.h in Headers */, - 7C9416E409920031F918C78D3F8BC73A /* ecmult_const.h in Headers */, - 8214F77DF0A13B64C70D1AFE1467B169 /* ecmult_const_impl.h in Headers */, - AF813D5EF055223C9D676862A88E83EC /* ecmult_gen.h in Headers */, - 21D920F436749D387F2454336B2049E0 /* ecmult_gen_impl.h in Headers */, - 4CE14AF6A9D5BAB9A775D78B9AA80B22 /* ecmult_impl.h in Headers */, - 8E5D0FE361952FD38109FF9A30E48752 /* field.h in Headers */, - F5655B01E4FFFA3F21CB0B12807A55C3 /* field_10x26.h in Headers */, - E402E7140E9A2FF8C9D0E14AA2D72ED9 /* field_10x26_impl.h in Headers */, - A0DC1D0C81DBA577E20484ACF7DE9CF2 /* field_5x52.h in Headers */, - 1E40B27B27DD44482412FF909F0EA60D /* field_5x52_asm_impl.h in Headers */, - 90545D61932E0A667E3AFC17E5594116 /* field_5x52_impl.h in Headers */, - 76C80FC45C606963585582CDF0449A98 /* field_5x52_int128_impl.h in Headers */, - 16C2B82A6557C0809704DC0E5334160F /* field_impl.h in Headers */, - E763CD8F8813167D15632AF5042B88A3 /* group.h in Headers */, - CEBCF331C938EE470C11962CDFFD30E1 /* group_impl.h in Headers */, - 161AAF0DF4B937AE2AC3AC7DB45EEF8C /* hash.h in Headers */, - 06733C6BD5DAA3E1DF17B52F58A972EE /* hash_impl.h in Headers */, - 9FEB740EDA57EC914F073B89EF3A5902 /* num.h in Headers */, - 67F33D45B4C0091959CEA9B92420E8A2 /* num_gmp.h in Headers */, - 8071BF845736086C92F8A1205859AFA8 /* num_gmp_impl.h in Headers */, - DB0BAF0951B4A5CAB52F37A1D4566F44 /* num_impl.h in Headers */, - FC30CC6BA8A2FA705C8300DD21012638 /* recovery_impl.h in Headers */, - FDE029DAFA820243AF70BF9D73569E1E /* scalar.h in Headers */, - 53DB39909A5A1D49D2E03CAB692BD8B5 /* scalar_4x64.h in Headers */, - F2F06D9CD7A942F7EEC6426CC2F1A794 /* scalar_4x64_impl.h in Headers */, - 0204978073AA06F1FD718B73A86E4F72 /* scalar_8x32.h in Headers */, - 95A14745491525816393D954F72FC9BD /* scalar_8x32_impl.h in Headers */, - 77000A8F4524AF0977F1AECE1852DD69 /* scalar_impl.h in Headers */, - 958258232333A86232628AE1C3DBD69F /* scalar_low.h in Headers */, - D8BA9690176DD63FEC7F0D85AFC26CC1 /* scalar_low_impl.h in Headers */, - 3198D535165A8276A8A7A5CA7644FC0F /* scratch.h in Headers */, - B74B5EEA58E2923AD043F773FB9E7A1F /* scratch_impl.h in Headers */, - C1B03B2B30A3FAFFA89B490625A663CB /* secp256k1-config.h in Headers */, - CCCF46865AC2CF9EE10BED47E2656C0C /* secp256k1.c-umbrella.h in Headers */, - 0FD1EA8AE4D8EB148DC21C25366F33BF /* secp256k1.h in Headers */, - BC8D548C4074AB6CBE46B40918B555A6 /* secp256k1_ec_mult_static_context.h in Headers */, - 5D3CFC3E2CCAA272A2003762AFD66B41 /* secp256k1_main.h in Headers */, - BDE43A3AB8E927087E4E8765C6D2B2E1 /* util.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 709DAB71C5595424D21973A3833F1C93 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 639C6438CD01AE7A36FE1E551F2E7A8F /* CryptoSwift-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 77A21E1C7F5685DF8F0990D92456D311 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 611450D9423EB6D78CBEBCBC60FC3BE4 /* BestLogger-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; - }; - A0AB3D74FDD535AA18110BC68E6CB109 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 373598EE21A99D2E8088520F8E4E985D /* Pods-TestApplication-TestApplicationTests-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - ABD37AF9B9F78580D159AE761C456202 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - B4A6283FDFA04E3A7B6FD0C13B6FEF32 /* Starscream-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - BA3F20EE291309DD3200BD3A1281F617 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - F4A5AED589CFC8C527E096E52CFE1C14 /* Torus-fetchNodeDetails-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - E6B50EF4C0FA7CCC66434EC674014875 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - BE7AB9F4BA1330BF6148611506DA8735 /* Torus-utils-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXHeadersBuildPhase section */ - -/* Begin PBXNativeTarget section */ - 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"; - }; - 1365165D183E4C35E57FE0E71450F0E2 /* BestLogger */ = { - isa = PBXNativeTarget; - buildConfigurationList = 47DD81E71F994C9108524A55AAEEB9EC /* Build configuration list for PBXNativeTarget "BestLogger" */; - buildPhases = ( - 77A21E1C7F5685DF8F0990D92456D311 /* Headers */, - 61B656CA6111EF7346F0709ED4C73963 /* Sources */, - AD14A83BF9B6A00656C3E87EB8D818A2 /* Frameworks */, - 360BB160359946F8E60C262EE8C7D98F /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = BestLogger; - productName = BestLogger; - productReference = 26A30E0DA2419B1831A942110E9826A2 /* BestLogger.framework */; - productType = "com.apple.product-type.framework"; - }; - 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */ = { - isa = PBXNativeTarget; - buildConfigurationList = 63BC0292CB8FB77ACDC99F046FDA3BAA /* Build configuration list for PBXNativeTarget "secp256k1.c" */; - buildPhases = ( - 4A128368392A2813452844C7B5CE1638 /* Headers */, - 8E841F3E12B784834EE4F6825BFDBF6D /* Sources */, - A4BECEAC373E87C8B4007F4EAFC81092 /* Frameworks */, - 0605BFC1112477431A019A1F3E850D24 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = secp256k1.c; - productName = secp256k1.c; - productReference = 332A47430CFF99501D563788C7AAF1D2 /* secp256k1.framework */; - productType = "com.apple.product-type.framework"; - }; - 3744C58A953D980BCF08B0FEAE449C91 /* Torus-fetchNodeDetails */ = { - isa = PBXNativeTarget; - buildConfigurationList = 0668D6CDE8A81138E917FD2045CB9FB3 /* Build configuration list for PBXNativeTarget "Torus-fetchNodeDetails" */; - buildPhases = ( - BA3F20EE291309DD3200BD3A1281F617 /* Headers */, - 4EF1A248C63F6C55EA073F252AECBE48 /* Sources */, - 9923BD363056DBE15F71F4DEE261D183 /* Frameworks */, - 534B587E3C1322AC86FA5CCF39D1A76F /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 4A3925600219EEC2AA9CF6664ADEED3C /* PBXTargetDependency */, - 7496563C92D36AF93CC2327B75FB00A8 /* PBXTargetDependency */, - ); - name = "Torus-fetchNodeDetails"; - productName = "Torus-fetchNodeDetails"; - productReference = 36B22267AF4D657854BDCBC896BAA6BE /* FetchNodeDetails.framework */; - productType = "com.apple.product-type.framework"; - }; - 50BD5410DB90F893AE68CE9925FD066E /* Torus-utils */ = { - isa = PBXNativeTarget; - buildConfigurationList = F41F5761FAC46D6078B4B3EFE8CEFD19 /* Build configuration list for PBXNativeTarget "Torus-utils" */; - buildPhases = ( - E6B50EF4C0FA7CCC66434EC674014875 /* Headers */, - 1978B7F5123CA32AB4120A118357AE2D /* Sources */, - 1951A36938A1B10F21ABD0E54F1FFEE8 /* Frameworks */, - C96C0BD49FFE19AF01D84EE0FEF60B3C /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 3B6AEA680D70AD40DAF657E32DBBD85D /* PBXTargetDependency */, - 04B404AFED96235B05E4F9EDF24BB166 /* PBXTargetDependency */, - 488D91B8B82C3CF7BDF31F0E9634AC69 /* PBXTargetDependency */, - ); - name = "Torus-utils"; - productName = "Torus-utils"; - productReference = 3936ADAF803ACF9C9AF43E3304CF7768 /* TorusUtils.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"; - }; - 847B6D40CFA89C55F0587E1F1625AB4F /* Pods-TestApplication */ = { - isa = PBXNativeTarget; - buildConfigurationList = 82D919DAE1EFF866656A47F3F89217BA /* Build configuration list for PBXNativeTarget "Pods-TestApplication" */; - buildPhases = ( - 03E54AC2179905C71D1054BF76534E0E /* Headers */, - 82B121BC7E2C3F5A84BDD7E3C2B3D6C7 /* Sources */, - 2191BF40D32BDF3F13E0864F5A0AFFF2 /* Frameworks */, - A8F3F5FE8C9CFAF6EE97E3993971A632 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ECC326EF0DC9C5D76E9C2B4DC48A32E8 /* PBXTargetDependency */, - 1EFED165F8576358614C60234EAD55CB /* PBXTargetDependency */, - 360F92BCE702A64DF55F394FB9A118FC /* PBXTargetDependency */, - 4D9E88C1A13B7119C1A4D652D74C57F3 /* PBXTargetDependency */, - FB5F26AB8A73942C96D9F22AD95A0707 /* PBXTargetDependency */, - 1BAC323DDDCC4A76738A96AD28725DA0 /* PBXTargetDependency */, - D7157579C012F755AAA737101FC2BFC0 /* PBXTargetDependency */, - E1674CFABAB182F1C0498FE69E3B4370 /* PBXTargetDependency */, - A9C6F5E34C6116EC788FA828E07F7299 /* PBXTargetDependency */, - ); - name = "Pods-TestApplication"; - productName = "Pods-TestApplication"; - productReference = 8B075CA53091CACB97CA1EC16B1B8CAC /* Pods_TestApplication.framework */; - productType = "com.apple.product-type.framework"; - }; - 8CDD759A6130CA265C6D157F4407C39B /* web3swift-Browser */ = { - isa = PBXNativeTarget; - buildConfigurationList = 52A724D063AD106CEAF6FAE1E89E5612 /* Build configuration list for PBXNativeTarget "web3swift-Browser" */; - buildPhases = ( - E2B3B7EACB075F9DB6F2D367F6370924 /* Sources */, - E10A92CBDE9335E7361E7E9800EE6900 /* Frameworks */, - 8E839AE438A56391217A8465CD92BA14 /* 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 = DE06027054BC8F9ED34F0BEB097E3BA5 /* Build configuration list for PBXNativeTarget "web3swift" */; - buildPhases = ( - 2D668541D016BFB8E06990C1107A2F01 /* Headers */, - F8EE1690E7DA3593D8166C89B86BC266 /* Sources */, - 6F1D48CE76242B39358287D0EBA8F869 /* Frameworks */, - D875B505E2ADA9D6389F91126439F06D /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - A7B7BBAAC3D3FD4BDC9C0074F835E08A /* PBXTargetDependency */, - BB3843295992B2B481B560F6EE17B4DB /* PBXTargetDependency */, - 101BCB1566C0A4168EFE1232052C1002 /* PBXTargetDependency */, - 12ED813765A1C02D5BCCE47856B858D9 /* PBXTargetDependency */, - 1F3F407B2FE6EDBCF430B800BD1C47A6 /* PBXTargetDependency */, - F01599AEB4158AD551A2C466179FC824 /* 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"; - }; - AF0283A04CCE8FC5D2315224AFC78ECB /* Pods-TestApplication-TestApplicationTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = FFFC1490F67E25181D429A1AAB343F60 /* Build configuration list for PBXNativeTarget "Pods-TestApplication-TestApplicationTests" */; - buildPhases = ( - A0AB3D74FDD535AA18110BC68E6CB109 /* Headers */, - 5265C59ACA1015847D2C3E6DEA05BDFB /* Sources */, - 876782AD48A8E8FF0A08B2FDDD142D07 /* Frameworks */, - B0316ABA7C0A26A622A69463BF85DE73 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - CFA996160A80EE7F0A100DA5370FF1CE /* PBXTargetDependency */, - D289C42B2017010E87556B15C367561D /* PBXTargetDependency */, - DE2FA189021321443D825B3758121154 /* PBXTargetDependency */, - C4B9DD1852727D8040138D4C9CEE26AE /* PBXTargetDependency */, - A3E02E207CE184CB6E62BCD69BEE943F /* PBXTargetDependency */, - 8900C8DA9E01C5C0DE70B88659ACA2B3 /* PBXTargetDependency */, - 5AA605EF8FAB26F2923C803C6A4DEEED /* PBXTargetDependency */, - 4BF5958ACF36CAEF8B3EBAFFFC3DEF2B /* PBXTargetDependency */, - 880EADACDC53A51C77E2806E562916CC /* PBXTargetDependency */, - ); - name = "Pods-TestApplication-TestApplicationTests"; - productName = "Pods-TestApplication-TestApplicationTests"; - productReference = 97241BE1FCAA933EA8779E01EEA25CB6 /* Pods_TestApplication_TestApplicationTests.framework */; - productType = "com.apple.product-type.framework"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - BFDFE7DC352907FC980B868725387E98 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 1100; - LastUpgradeCheck = 1100; - }; - buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; - compatibilityVersion = "Xcode 10.0"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = CF1408CF629C7361332E53B88F7BD30C; - productRefGroup = 2DC1A883F419692EC104E907B23AF169 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 1365165D183E4C35E57FE0E71450F0E2 /* BestLogger */, - 09DD83B7D075842A3A5105AD410BD38A /* BigInt */, - 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */, - 847B6D40CFA89C55F0587E1F1625AB4F /* Pods-TestApplication */, - AF0283A04CCE8FC5D2315224AFC78ECB /* Pods-TestApplication-TestApplicationTests */, - 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */, - 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */, - 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */, - 3744C58A953D980BCF08B0FEAE449C91 /* Torus-fetchNodeDetails */, - 50BD5410DB90F893AE68CE9925FD066E /* Torus-utils */, - 99364D9FB07EF3FA5DFE1237001805EC /* web3swift */, - 8CDD759A6130CA265C6D157F4407C39B /* web3swift-Browser */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 0605BFC1112477431A019A1F3E850D24 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 360BB160359946F8E60C262EE8C7D98F /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 409EA903AAA7848EE17474A886579F4C /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 534B587E3C1322AC86FA5CCF39D1A76F /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 5C193E54B44DAEF03EE281A99BB02E30 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 7ACD25997C01FD960F9B4331D0A5D21F /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 8E839AE438A56391217A8465CD92BA14 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 129B12C551894C2CF7CB421ECF79F719 /* browser.js in Resources */, - 36B12BDADD70855F21118BA8C653366A /* browser.min.js in Resources */, - 79FA64DB3735227282FEB38CA6907626 /* wk.bridge.min.js in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - A8F3F5FE8C9CFAF6EE97E3993971A632 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - B0316ABA7C0A26A622A69463BF85DE73 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - BE174469BA3F43D1B5CE60520CA93EB3 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - C96C0BD49FFE19AF01D84EE0FEF60B3C /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - D875B505E2ADA9D6389F91126439F06D /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - D65A4FA559A3D7D1F3C578E126B4A955 /* Browser.bundle in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 1978B7F5123CA32AB4120A118357AE2D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 06DC6E69AE67D84EEECFEBD7B463E857 /* Array+Extension.swift in Sources */, - 65D833120C79B4C06F9AD721F871AB2D /* Base58.swift in Sources */, - B49A87F0F8FBA70623BE46585311B343 /* BigUInt+Extensions.swift in Sources */, - BA0B0E473CAF77498DBF253B48C05EC8 /* CryptoExtensions.swift in Sources */, - 95C8E48FF5AF28FFD8F6C3612447D238 /* Data+Extension.swift in Sources */, - BF33883B6C96B31DE4692BFD912ACF82 /* Decodable+Extensions.swift in Sources */, - 0135B4BBC91F702B043FAA03FBE81DC7 /* Dictionary+Extension.swift in Sources */, - A80957DA592E1405E3352F073FA2C309 /* Encodable+Extensions.swift in Sources */, - A3EBB1CCF2E5716F98B66439C31F31A2 /* Error.swift in Sources */, - 3E0122134CE56BF279E308565FD40B5E /* JSONRPCRequest.swift in Sources */, - 37E4E0A4F2459F27ACC0DDD7E826F219 /* KeyAssignRequestResponse.swift in Sources */, - 591736E2D0696757E8762B5481687162 /* NativeTypesEncoding+Extensions.swift in Sources */, - 6FA8655716F022363C98FCA802982E91 /* NSRegularExpressionExtension.swift in Sources */, - CC1C395F714F206E55948FB255DE823C /* RIPEMD160+StackOveflow.swift in Sources */, - 28EBBB674FB096ED103EC7B4C3837194 /* SECP256k1.swift in Sources */, - 3BC67BD4E21453CA5AC8B893A16B246B /* String+Extension.swift in Sources */, - 51FE9E33966223FEF5EC69BA3EE1ED0F /* Torus-utils-dummy.m in Sources */, - 104671798BC62876A0EAF4843E8DD214 /* TorusUtils+extension.swift in Sources */, - B7CBF8311A63CA00B39F9FF2D35B6390 /* TorusUtils.swift in Sources */, - F2438C9C6471ED878FD9FD686421CBC3 /* Web3ERROR.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4EF1A248C63F6C55EA073F252AECBE48 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - E43D7ED7482761C992D3E42B32D606A6 /* abi.json in Sources */, - A3486EA68E3FC1B1FCD0865841CC4333 /* abi.swift in Sources */, - 29A17D1EA209DF3349FBEBAD35D59F53 /* epochInfo.swift in Sources */, - A1DD10F57D1D429E4897EBEB75043E71 /* ethereumNetwork.swift in Sources */, - 5EE0235F01C86FC15C90D3F673082571 /* fetchNodeDetails+promise.swift in Sources */, - 2181AAB3F159DD95540528F9C435F5F7 /* fetchNodeDetails.swift in Sources */, - CB90B94A89B6991F61E2B64DD331B30A /* nodeDetails.swift in Sources */, - F318FAB73E570060E66B089513A58F7F /* nodeInfo.swift in Sources */, - 855818063255040AB02A45C9C0838048 /* String.swift in Sources */, - 42E3AC2A6C8415B6645B956C38EF9409 /* Torus-fetchNodeDetails-dummy.m in Sources */, - 2BB55BEE3AC7D418CF79CE1B3CC03CB6 /* torusNodePub.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 5265C59ACA1015847D2C3E6DEA05BDFB /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 57E56900F1BE1DC4665FBCF865BEB375 /* Pods-TestApplication-TestApplicationTests-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; - }; - 61B656CA6111EF7346F0709ED4C73963 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - DBF232C5CC6FB8EDF32D69E0FF8A50BD /* BestLogger-dummy.m in Sources */, - FE0D3AEBDA7E74DCB8F81D86A89127B4 /* BestLogger.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; - }; - 82B121BC7E2C3F5A84BDD7E3C2B3D6C7 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - F6490DA2E9325384B1F7AEA92E477065 /* Pods-TestApplication-dummy.m in Sources */, - ); - 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; - }; - 8E841F3E12B784834EE4F6825BFDBF6D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - C29BCDE99B11853F0190C2248562EF7A /* secp256k1.c in Sources */, - 405BBFBA40C80C1F0C1C2A45FD1F548B /* secp256k1.c-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; - }; - E2B3B7EACB075F9DB6F2D367F6370924 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F8EE1690E7DA3593D8166C89B86BC266 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 9F96D351A8225DDC4D57740307E8EB30 /* ABI.swift in Sources */, - F1A6525CB04998529CBCAC5BCEE57878 /* ABIDecoding.swift in Sources */, - ABD6C819D2E3692C97351FAF2FB647F9 /* ABIElements.swift in Sources */, - CE6361BC8CD979FE0A5FF9E8CD756D3C /* ABIEncoding.swift in Sources */, - 9BBD5BF22F94C3FA1DBD161E18992FEC /* ABIParameterTypes.swift in Sources */, - A3B7DA364283BD761ECB3A8116F81298 /* ABIParsing.swift in Sources */, - 52E2ACD870A7CA9F355C21B694120694 /* ABITypeParser.swift in Sources */, - 9F385EB89EED043C900452A3BA9FC0D3 /* AbstractKeystore.swift in Sources */, - 0EA61F34CB7EEE8820E2934C8AD1E6BB /* Array+Extension.swift in Sources */, - A32C099C519A1F0E8739B010BC8B38F0 /* Base58.swift in Sources */, - 40C047E8319F21196D029C8C76819F23 /* BigUInt+Extensions.swift in Sources */, - 7DC7F7509014FFB20EDBC7A1CE475B56 /* BIP32HDNode.swift in Sources */, - 42B66F10E610FB5F799FFC5BC91BCD9D /* BIP32Keystore.swift in Sources */, - 0C99989CEA8113F15AF6309676D37664 /* BIP32KeystoreJSONStructure.swift in Sources */, - 3D92BDF4B0DC217CBAC5C6122151C435 /* BIP39+WordLists.swift in Sources */, - 03B17518831570C6E89FFEEC86102D2C /* BIP39.swift in Sources */, - F934C45EC70FF710ACC02400EB9B7159 /* BloomFilter.swift in Sources */, - 64B5AE496D617B5B58DCE09E69055CF0 /* Bridge.swift in Sources */, - 1A179BAE7E3ED81BB708D5DF5F97A8FB /* BrowserViewController.swift in Sources */, - 6C6A1C4DAA7FBC889B951609C91956BF /* ComparisonExtensions.swift in Sources */, - 2BE848F4DD3274E28DE44DDDCD72CF8B /* ContractProtocol.swift in Sources */, - D650178F82DCCE4B52CFF4ED7A88812C /* CryptoExtensions.swift in Sources */, - 818A0A10A4D1B841846F05457AB3F3F0 /* Data+Extension.swift in Sources */, - 758E6699C3AD8153FBC5BDE6B78C7B7C /* Decodable+Extensions.swift in Sources */, - CF7CF7EF1EEDCE7754590741CEE6E55A /* Dictionary+Extension.swift in Sources */, - BC4EF03F29F068EEB3CDB41FA39CF2C8 /* EIP67Code.swift in Sources */, - 02B4FB8FC9F72608C82C7058FBE47514 /* EIP681.swift in Sources */, - 88A625D7DE0B008427478A41F87E97CB /* Encodable+Extensions.swift in Sources */, - C004AE6E4897816A1BF56255234CCFE6 /* ENS.swift in Sources */, - 07CF202BCE4D1383BA86DA1200BB411A /* ENSBaseRegistrar.swift in Sources */, - DC7E37950268DD0C5106737A12086DB4 /* ENSRegistry.swift in Sources */, - DE14FDEEE8418BB914CE507B8099E589 /* ENSResolver.swift in Sources */, - 7B18811164294FD7DB336597B32420B3 /* ENSReverseRegistrar.swift in Sources */, - 41423C7054638D60AF039BE3D8DD0DC3 /* EthereumAddress.swift in Sources */, - 2F24F334AE17BA825EDB27FE7153278B /* EthereumContract.swift in Sources */, - BA73CEF44001DF2292AC6FBA94E2996F /* EthereumFilterEncodingExtensions.swift in Sources */, - 45A5D20354B11CD25B17F0D877CF02F4 /* EthereumKeystoreV3.swift in Sources */, - AB5121F3168D67D98548D1716917044C /* EthereumTransaction.swift in Sources */, - 5F79C41D8A8DAAD57BEAF48FC641A06E /* ETHRegistrarController.swift in Sources */, - B202FAAE49238B713536A1BA965EE05E /* EventFiltering.swift in Sources */, - B454FD1963E4ABBCABBAF87B653A675C /* Extensions.swift in Sources */, - D22003E7E728AAB1A58658A0067226E7 /* IBAN.swift in Sources */, - 91AB404500559BAB19421D2B8CF13CAD /* KeystoreManager.swift in Sources */, - F71E1C98CAB16FE66EDE761BB1C50F0A /* KeystoreV3JSONStructure.swift in Sources */, - 9723687056497A67C00ECCB2D77BBF44 /* NameHash.swift in Sources */, - 0B22F5E17A03A7A96699018F9133297A /* NativeTypesEncoding+Extensions.swift in Sources */, - 98ADDD9D6F83BBC98DB001AF4857E9A3 /* NonceMiddleware.swift in Sources */, - 0F77D140F8BC6AF9C76A646A1A1DB167 /* NSRegularExpressionExtension.swift in Sources */, - 2F97EAB4BE6AEF9EB32A9B1F5EE03C16 /* PlainKeystore.swift in Sources */, - 6E7EFAD55429703AC4F4161824C2949D /* Promise+Batching.swift in Sources */, - 9B21076A76E97F640E952E7B129AAD7A /* Promise+HttpProvider.swift in Sources */, - A287E1A244C84D2C5A301B3A897F0787 /* Promise+Web3+Contract+GetIndexedEvents.swift in Sources */, - CFDE61D4C8680399EBFEF2861E86A231 /* Promise+Web3+Eth+Call.swift in Sources */, - 1E42E056D28167CBC2C73291256A980C /* Promise+Web3+Eth+EstimateGas.swift in Sources */, - 305F15EFFE12FF60509C8C5A08FD4792 /* Promise+Web3+Eth+GetAccounts.swift in Sources */, - 84CD5D70E2922378C0ECE1373D1633C4 /* Promise+Web3+Eth+GetBalance.swift in Sources */, - E277A99D7950D81D1B80AFA4171E61ED /* Promise+Web3+Eth+GetBlockByHash.swift in Sources */, - CBBC28505A75D43175AE463477F019D9 /* Promise+Web3+Eth+GetBlockByNumber.swift in Sources */, - 31DBA98917ACA7AF6C5D9C9D3D3D8B32 /* Promise+Web3+Eth+GetBlockNumber.swift in Sources */, - 487AB9E125898D80AF91388DC79B8667 /* Promise+Web3+Eth+GetGasPrice.swift in Sources */, - C72C803D5CD5CF33BDC24F328B8AD35E /* Promise+Web3+Eth+GetTransactionCount.swift in Sources */, - 4382AFE23DB6803BBB77D5B0283D56D9 /* Promise+Web3+Eth+GetTransactionDetails.swift in Sources */, - 95DB083F6029B95881E389992A82565E /* Promise+Web3+Eth+GetTransactionReceipt.swift in Sources */, - 56B4C57D519DC4203D61A2F64BFF8E45 /* Promise+Web3+Eth+SendRawTransaction.swift in Sources */, - EB75901A5DCC720A5AEC6BA4B6369B86 /* Promise+Web3+Eth+SendTransaction.swift in Sources */, - FE2685F4B1138D722007167CC42F6902 /* Promise+Web3+Personal+CreateAccount.swift in Sources */, - BFBBBF490B164BD2F4D95CEE74E8A1EF /* Promise+Web3+Personal+Sign.swift in Sources */, - C5AAECAB4C5679728CF2D7AAF3D689D8 /* Promise+Web3+Personal+UnlockAccount.swift in Sources */, - CA6442060FC70151AF0F4B17DD3B9178 /* Promise+Web3+TxPool.swift in Sources */, - 61D2F48325DD4A8443C3B44163084052 /* PublicKey.swift in Sources */, - 36652DE8FF55772FB33C419FD6153FC5 /* RIPEMD160+StackOveflow.swift in Sources */, - 170175D902933C1C550280534923EA7A /* RLP.swift in Sources */, - A3B3B08F5E6C2AA6356FD7145F442858 /* SECP256k1.swift in Sources */, - 694B1EB8CB94A408E480334B70D3CCAF /* String+Extension.swift in Sources */, - 3957B5C0220F087BC1B336A5BFC2B5CC /* TransactionSigner.swift in Sources */, - FE5D81875AA74482B69274A57F371827 /* Web3+BrowserFunctions.swift in Sources */, - 6641A7D860C65EBFD8268CB4123E74B3 /* Web3+Constants.swift in Sources */, - B695FB618AFBED4E2FB35139D4073A45 /* Web3+Contract.swift in Sources */, - 531B8470043B78207C1F4270BD7A6EBC /* Web3+ERC1155.swift in Sources */, - 3A685604A59A0AA77824B0729BF62F5A /* Web3+ERC1376.swift in Sources */, - 3BBD967EE05C6195B23F9C77BD9DFC40 /* Web3+ERC1400.swift in Sources */, - 629009B19A29C3EF75B2854F9FB40832 /* Web3+ERC1410.swift in Sources */, - 7CF67378B4BE4B976A00E814A1685ED2 /* Web3+ERC1594.swift in Sources */, - 0F1B490475785F1E8F6C6870AB6051C2 /* Web3+ERC1633.swift in Sources */, - 8DB55C794C3FD2E43D8CCC550B1AF94B /* Web3+ERC1643.swift in Sources */, - 062A929DF69235998607A846BBBEEC53 /* Web3+ERC1644.swift in Sources */, - C05EFD99EA258A792A2B983A1E156F5A /* Web3+ERC165.swift in Sources */, - F4A8CF610DFE908313068A1B3C909854 /* Web3+ERC20.swift in Sources */, - 8EF954AAF4CA9B832FF21DAF4B962F46 /* Web3+ERC721.swift in Sources */, - 530876118555FFAFE97180FF28BD962A /* Web3+ERC721x.swift in Sources */, - 25F360948AF8160C0EB0662D7BB9C422 /* Web3+ERC777.swift in Sources */, - 009C0525EBF2E8717C45835B5FF73504 /* Web3+ERC820.swift in Sources */, - 18280888DBABC792A624CDC9F963EECD /* Web3+ERC888.swift in Sources */, - B1A16E15906745982091B5B83E707F8A /* Web3+Eth+Websocket.swift in Sources */, - 22E90BB147F27F078FA546193B14C035 /* Web3+Eth.swift in Sources */, - 327E70522102D2171C98B880D3CA692F /* Web3+Eventloop.swift in Sources */, - 58F25F7F0904CC29E369DC94270B8017 /* Web3+EventParser.swift in Sources */, - C6FC6A13DB02CC3DBBDBC0E0EB8F97A2 /* Web3+HttpProvider.swift in Sources */, - BEFDEE737D0E3E1D1CFB9D7925893D22 /* Web3+InfuraProviders.swift in Sources */, - 029030C307564BA7D0CB3EE6F5D36823 /* Web3+Instance.swift in Sources */, - 6F3C398006A16F975B7E62763B365286 /* Web3+JSONRPC.swift in Sources */, - 83C23054E1B9A6DF1663F730478D608B /* Web3+Methods.swift in Sources */, - 8A02CDD77D0E9F6526C79A7054493D64 /* Web3+MutatingTransaction.swift in Sources */, - A626B96EC7D7689ABE43C6DAE9B0CCB1 /* Web3+Options.swift in Sources */, - 5DE56A1F1C10D196C20635E96533B98C /* Web3+Personal.swift in Sources */, - CCF4CA4137C1BD997D4EB189DE3CFD23 /* Web3+Protocols.swift in Sources */, - B68D596196CB33B19ABFC17CD0583B9A /* Web3+ReadingTransaction.swift in Sources */, - 252264684AE3A115807C7493BC63C281 /* Web3+SecurityToken.swift in Sources */, - 25252C54530A36B1CEF487F1A9B497C8 /* Web3+ST20.swift in Sources */, - 6BD149F5D90C9E30F95C829791EB97B9 /* Web3+Structures.swift in Sources */, - AE49720A728B0152AD532A1B94A16D32 /* Web3+TxPool.swift in Sources */, - D7AB2759CDCFA67777AFCD910BB7CE27 /* Web3+Utils.swift in Sources */, - 126ED2C348D7F4EE990502382C1759A9 /* Web3+Wallet.swift in Sources */, - F7B35CF494CCC4BFFD950D55B0609D2E /* Web3+WebsocketProvider.swift in Sources */, - 42CB6A5D231637354B9D38588E817DDF /* Web3.swift in Sources */, - 0C872EAB484331F031EB6E9196B46E1E /* web3swift-dummy.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 04B404AFED96235B05E4F9EDF24BB166 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = PromiseKit; - target = 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */; - targetProxy = A88B3C305EDB7145219C050901B264A8 /* PBXContainerItemProxy */; - }; - 101BCB1566C0A4168EFE1232052C1002 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = PromiseKit; - target = 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */; - targetProxy = 997F37EC00CC81D87F0407AC7B1AFE24 /* PBXContainerItemProxy */; - }; - 12ED813765A1C02D5BCCE47856B858D9 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Starscream; - target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; - targetProxy = 508710B1FFBAB260097ABE53A2181700 /* PBXContainerItemProxy */; - }; - 1BAC323DDDCC4A76738A96AD28725DA0 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "Torus-fetchNodeDetails"; - target = 3744C58A953D980BCF08B0FEAE449C91 /* Torus-fetchNodeDetails */; - targetProxy = 8DE8A0BACD14578177A63553CF8E2D9F /* PBXContainerItemProxy */; - }; - 1EFED165F8576358614C60234EAD55CB /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = BigInt; - target = 09DD83B7D075842A3A5105AD410BD38A /* BigInt */; - targetProxy = 035A966A9251F66DFE7DD464FC309D75 /* PBXContainerItemProxy */; - }; - 1F3F407B2FE6EDBCF430B800BD1C47A6 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = secp256k1.c; - target = 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */; - targetProxy = 84CD5A070282E25C00A6BD279B641C2B /* PBXContainerItemProxy */; - }; - 360F92BCE702A64DF55F394FB9A118FC /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = CryptoSwift; - target = 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */; - targetProxy = C4A1F0D626FC4F33F5A7033E0B5C9CE4 /* PBXContainerItemProxy */; - }; - 3B6AEA680D70AD40DAF657E32DBBD85D /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = BestLogger; - target = 1365165D183E4C35E57FE0E71450F0E2 /* BestLogger */; - targetProxy = DFF19C21652CDF589A3CC5013929D8A6 /* PBXContainerItemProxy */; - }; - 488D91B8B82C3CF7BDF31F0E9634AC69 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "Torus-fetchNodeDetails"; - target = 3744C58A953D980BCF08B0FEAE449C91 /* Torus-fetchNodeDetails */; - targetProxy = 48EBA5DD88ACF312C19C165273C50965 /* PBXContainerItemProxy */; - }; - 4A3925600219EEC2AA9CF6664ADEED3C /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = BestLogger; - target = 1365165D183E4C35E57FE0E71450F0E2 /* BestLogger */; - targetProxy = FD72BE9CCE1A40865017FFC0CD11C34D /* PBXContainerItemProxy */; - }; - 4BF5958ACF36CAEF8B3EBAFFFC3DEF2B /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = secp256k1.c; - target = 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */; - targetProxy = 0C4B2D2C752AC66EEA4CEBB97824655F /* PBXContainerItemProxy */; - }; - 4D9E88C1A13B7119C1A4D652D74C57F3 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = PromiseKit; - target = 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */; - targetProxy = 0CA171B90CCA0AD442DA0EDA2CADD751 /* PBXContainerItemProxy */; - }; - 5AA605EF8FAB26F2923C803C6A4DEEED /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "Torus-utils"; - target = 50BD5410DB90F893AE68CE9925FD066E /* Torus-utils */; - targetProxy = E063E5B763FEEDE4C4DEF58E2CFEA48C /* PBXContainerItemProxy */; - }; - 7496563C92D36AF93CC2327B75FB00A8 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = web3swift; - target = 99364D9FB07EF3FA5DFE1237001805EC /* web3swift */; - targetProxy = DFCBFCC4F61508638E33B0D5ECA30632 /* PBXContainerItemProxy */; - }; - 880EADACDC53A51C77E2806E562916CC /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = web3swift; - target = 99364D9FB07EF3FA5DFE1237001805EC /* web3swift */; - targetProxy = B11F4D5EFFE97A6716B50AFBE2C62F67 /* PBXContainerItemProxy */; - }; - 8900C8DA9E01C5C0DE70B88659ACA2B3 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "Torus-fetchNodeDetails"; - target = 3744C58A953D980BCF08B0FEAE449C91 /* Torus-fetchNodeDetails */; - targetProxy = 930F0EED1326004036B24C1EB3C4D8E3 /* PBXContainerItemProxy */; - }; - A3E02E207CE184CB6E62BCD69BEE943F /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Starscream; - target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; - targetProxy = 74F6A47B6FFEDA0173E19BF5107FEA09 /* PBXContainerItemProxy */; - }; - A7B7BBAAC3D3FD4BDC9C0074F835E08A /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = BigInt; - target = 09DD83B7D075842A3A5105AD410BD38A /* BigInt */; - targetProxy = 69FB91E6200FFE4E68C43C1194167D6B /* PBXContainerItemProxy */; - }; - A9C6F5E34C6116EC788FA828E07F7299 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = web3swift; - target = 99364D9FB07EF3FA5DFE1237001805EC /* web3swift */; - targetProxy = E3686186A0CBB35F6BCAC97C00316D4D /* PBXContainerItemProxy */; - }; - BB3843295992B2B481B560F6EE17B4DB /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = CryptoSwift; - target = 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */; - targetProxy = D6032235584FDF4785D50A688D7284E2 /* PBXContainerItemProxy */; - }; - C4B9DD1852727D8040138D4C9CEE26AE /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = PromiseKit; - target = 7C579CE66A1E7A9AA33CA5F97F9C22C5 /* PromiseKit */; - targetProxy = 4E62C4E8A6EAE64384F464A55A70CEE5 /* PBXContainerItemProxy */; - }; - CFA996160A80EE7F0A100DA5370FF1CE /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = BestLogger; - target = 1365165D183E4C35E57FE0E71450F0E2 /* BestLogger */; - targetProxy = 325D87D58EA705B8FD080AF609E0C3A9 /* PBXContainerItemProxy */; - }; - D289C42B2017010E87556B15C367561D /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = BigInt; - target = 09DD83B7D075842A3A5105AD410BD38A /* BigInt */; - targetProxy = DDBA525B2C029F42CEA3CE860AC43A05 /* PBXContainerItemProxy */; - }; - D7157579C012F755AAA737101FC2BFC0 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "Torus-utils"; - target = 50BD5410DB90F893AE68CE9925FD066E /* Torus-utils */; - targetProxy = 809E52C9C40695AA4C26379173922C09 /* PBXContainerItemProxy */; - }; - DE2FA189021321443D825B3758121154 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = CryptoSwift; - target = 99313990C1D76A6D1D017868B6975CC8 /* CryptoSwift */; - targetProxy = 8C54AFFF3813705D5075D1A9A479DE3D /* PBXContainerItemProxy */; - }; - E1674CFABAB182F1C0498FE69E3B4370 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = secp256k1.c; - target = 161C26511FC920CB146236AB7295D5E0 /* secp256k1.c */; - targetProxy = 77FFB9A136F68B001BEB687B18FF6BE2 /* PBXContainerItemProxy */; - }; - ECC326EF0DC9C5D76E9C2B4DC48A32E8 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = BestLogger; - target = 1365165D183E4C35E57FE0E71450F0E2 /* BestLogger */; - targetProxy = F411C2769E42AACB71CAA1EC456A3075 /* PBXContainerItemProxy */; - }; - F01599AEB4158AD551A2C466179FC824 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "web3swift-Browser"; - target = 8CDD759A6130CA265C6D157F4407C39B /* web3swift-Browser */; - targetProxy = 8429E728150E527A1DD3A7DE71BA9829 /* PBXContainerItemProxy */; - }; - FB5F26AB8A73942C96D9F22AD95A0707 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Starscream; - target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; - targetProxy = 7E45002E076C7B22DEAE0884030C971B /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin XCBuildConfiguration section */ - 2A23120A24F374C8C24CD74DAAE06138 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 421F491B9F8AB1BC9C6616B284D46A65 /* Pods-TestApplication.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-TestApplication/Pods-TestApplication-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-TestApplication/Pods-TestApplication.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; - }; - 379A38D54224CE5CCCB650DD6D490308 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = D05EFFB2585F856465241E04BE6B4437 /* BestLogger.release.xcconfig */; - buildSettings = { - 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"; - GCC_PREFIX_HEADER = "Target Support Files/BestLogger/BestLogger-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/BestLogger/BestLogger-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/BestLogger/BestLogger.modulemap"; - PRODUCT_MODULE_NAME = BestLogger; - PRODUCT_NAME = BestLogger; - 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; - }; - 37DF8208956F36EBDF0808C00F2A449A /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = B88A9BF2B3A86B0BD42B03214218D438 /* BestLogger.debug.xcconfig */; - buildSettings = { - 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"; - GCC_PREFIX_HEADER = "Target Support Files/BestLogger/BestLogger-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/BestLogger/BestLogger-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/BestLogger/BestLogger.modulemap"; - PRODUCT_MODULE_NAME = BestLogger; - PRODUCT_NAME = BestLogger; - 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; - }; - 3A012096506880F41D5BD1E4C583CDA7 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 3DDBF242F10DF61068E5BC1FC6DC2E65 /* Torus-fetchNodeDetails.debug.xcconfig */; - buildSettings = { - 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"; - GCC_PREFIX_HEADER = "Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails.modulemap"; - PRODUCT_MODULE_NAME = FetchNodeDetails; - PRODUCT_NAME = FetchNodeDetails; - 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; - }; - 3BE0CA2BAB19A000867078C53C867438 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 3253FCDF51FD3CCA40CFC041548584F1 /* 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; - }; - 4C1BFADBCE2B57C22989C55835A0C6C3 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = EC487C9F7E57FB6A764595EB00029AAD /* 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.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 51948B6774930113DB32555B9F30DE5A /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 215B7D5D806DA1CEC59F24ABC7E54AA2 /* 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; - }; - 57C239758A1C51A6952D04A4E52ECDC2 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7D0E11BE6137B9B807EEF01BBBF24181 /* 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; - }; - 5991E07319D48F881A3F8C4C2068D546 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = B5359F2F46F8C6AC35F1007EE324CE53 /* Pods-TestApplication.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-TestApplication/Pods-TestApplication-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-TestApplication/Pods-TestApplication.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; - }; - 5C485EDD9A137EED2388EE0583A131E0 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9148A4156B244104E844B817FB162F4C /* 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; - }; - 5DD11A33BE96CDA2FE7CEEB91D21E06C /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = FD0DBF02AE93049A9ED0ACBDD9170770 /* 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 = 8.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; - }; - 5FDC657BB2A500AFFD37BCA5C2F16C83 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 64CB563CCEBFB9464AC885324FCD2528 /* Torus-utils.release.xcconfig */; - buildSettings = { - 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"; - GCC_PREFIX_HEADER = "Target Support Files/Torus-utils/Torus-utils-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Torus-utils/Torus-utils-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/Torus-utils/Torus-utils.modulemap"; - PRODUCT_MODULE_NAME = TorusUtils; - PRODUCT_NAME = TorusUtils; - 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; - }; - 643CCC97567720C00FDF838E7698A9F3 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = A3ABFE3667AA01A217809D9BE0B80D1F /* Pods-TestApplication-TestApplicationTests.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-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests.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; - }; - 668B0D4ED797EC4BF2B33108B50B9869 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 0658C457030E48C8199E56F034689824 /* Torus-utils.debug.xcconfig */; - buildSettings = { - 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"; - GCC_PREFIX_HEADER = "Target Support Files/Torus-utils/Torus-utils-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Torus-utils/Torus-utils-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/Torus-utils/Torus-utils.modulemap"; - PRODUCT_MODULE_NAME = TorusUtils; - PRODUCT_NAME = TorusUtils; - 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; - }; - 716A212D58A6DCB2DDD681A27633676A /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 4769E2DFCF57A68EF19CA75CB8034B8C /* 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; - }; - 7EE7A78859F657F6BEFC651185B43192 /* 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; - "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = arm64; - 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 = 10.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; - }; - 85DA0ED56B2ADCC36EAEB97AE31E8148 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7F673FD14D4ABF76640791855FBB0BB6 /* Pods-TestApplication-TestApplicationTests.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-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests.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; - }; - 89E1D99263B43EA138698B60700386FB /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 49E9940B89C37FD51942B42F1C5657D3 /* 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; - }; - 93FD7C9DC8C587CA00553448791509A5 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = CD73768AF6E3FE9580E85BFF3E217FEE /* Torus-fetchNodeDetails.release.xcconfig */; - buildSettings = { - 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"; - GCC_PREFIX_HEADER = "Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 10.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails.modulemap"; - PRODUCT_MODULE_NAME = FetchNodeDetails; - PRODUCT_NAME = FetchNodeDetails; - 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; - }; - 9EB7695FE0BC834DB945B93CDD41E4F3 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = D51B46D48CE0BC8E8AFF1AA7E29FE50B /* 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.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - A93BAE8A9662892BFCA59989ABE100ED /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 89DE8CC0478156EF8E36CDA5F88E6218 /* 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; - }; - D299434AB35E7FD6F7921C8EF24742FF /* 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; - "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = arm64; - 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 = 10.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; - }; - D7D72B111F1A87424023C3B30B9D729A /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 2CA8362AD3A3AE16C1B934C3B653BE05 /* 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 = 8.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; - }; - DB6E506229BAF6115E61933D83F8228B /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 4769E2DFCF57A68EF19CA75CB8034B8C /* 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; - }; - F0608AA8CCA45E5B7E4F8F186FAA3478 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 3E945AEB44FCBEDA491D75A9A46BC158 /* 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; - }; - F9B657D518214B301EF49FD0E4B3FD2F /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 215B7D5D806DA1CEC59F24ABC7E54AA2 /* 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; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 058DF38F5922F24842B97693B0188F2D /* Build configuration list for PBXNativeTarget "PromiseKit" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 9EB7695FE0BC834DB945B93CDD41E4F3 /* Debug */, - 4C1BFADBCE2B57C22989C55835A0C6C3 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 0668D6CDE8A81138E917FD2045CB9FB3 /* Build configuration list for PBXNativeTarget "Torus-fetchNodeDetails" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 3A012096506880F41D5BD1E4C583CDA7 /* Debug */, - 93FD7C9DC8C587CA00553448791509A5 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 47DD81E71F994C9108524A55AAEEB9EC /* Build configuration list for PBXNativeTarget "BestLogger" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 37DF8208956F36EBDF0808C00F2A449A /* Debug */, - 379A38D54224CE5CCCB650DD6D490308 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - D299434AB35E7FD6F7921C8EF24742FF /* Debug */, - 7EE7A78859F657F6BEFC651185B43192 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 5104F4CC467A363177DF298548DA476E /* Build configuration list for PBXNativeTarget "BigInt" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 57C239758A1C51A6952D04A4E52ECDC2 /* Debug */, - 3BE0CA2BAB19A000867078C53C867438 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 52A724D063AD106CEAF6FAE1E89E5612 /* Build configuration list for PBXNativeTarget "web3swift-Browser" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - F9B657D518214B301EF49FD0E4B3FD2F /* Debug */, - 716A212D58A6DCB2DDD681A27633676A /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 63BC0292CB8FB77ACDC99F046FDA3BAA /* Build configuration list for PBXNativeTarget "secp256k1.c" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - A93BAE8A9662892BFCA59989ABE100ED /* Debug */, - F0608AA8CCA45E5B7E4F8F186FAA3478 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 82D919DAE1EFF866656A47F3F89217BA /* Build configuration list for PBXNativeTarget "Pods-TestApplication" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 5991E07319D48F881A3F8C4C2068D546 /* Debug */, - 2A23120A24F374C8C24CD74DAAE06138 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - CF129DCD30773EF2C3A3E9B2EFFB4A7E /* Build configuration list for PBXNativeTarget "CryptoSwift" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 5DD11A33BE96CDA2FE7CEEB91D21E06C /* Debug */, - D7D72B111F1A87424023C3B30B9D729A /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - DE06027054BC8F9ED34F0BEB097E3BA5 /* Build configuration list for PBXNativeTarget "web3swift" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 51948B6774930113DB32555B9F30DE5A /* Debug */, - DB6E506229BAF6115E61933D83F8228B /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - ED5C15C705AB67930733A7E237A0A33A /* Build configuration list for PBXNativeTarget "Starscream" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 5C485EDD9A137EED2388EE0583A131E0 /* Debug */, - 89E1D99263B43EA138698B60700386FB /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - F41F5761FAC46D6078B4B3EFE8CEFD19 /* Build configuration list for PBXNativeTarget "Torus-utils" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 668B0D4ED797EC4BF2B33108B50B9869 /* Debug */, - 5FDC657BB2A500AFFD37BCA5C2F16C83 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - FFFC1490F67E25181D429A1AAB343F60 /* Build configuration list for PBXNativeTarget "Pods-TestApplication-TestApplicationTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 643CCC97567720C00FDF838E7698A9F3 /* Debug */, - 85DA0ED56B2ADCC36EAEB97AE31E8148 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; -} diff --git a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h b/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h deleted file mode 100644 index 351a93b9..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.h +++ /dev/null @@ -1,44 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m b/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m deleted file mode 100644 index f8aee710..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+AnyPromise.m +++ /dev/null @@ -1,18 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift b/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift deleted file mode 100644 index 3b7f8434..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSNotificationCenter+Promise.swift +++ /dev/null @@ -1,33 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift b/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift deleted file mode 100644 index 135719bf..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSObject+Promise.swift +++ /dev/null @@ -1,57 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h b/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h deleted file mode 100644 index 29c2c038..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.h +++ /dev/null @@ -1,53 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m b/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m deleted file mode 100644 index beae2775..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSTask+AnyPromise.m +++ /dev/null @@ -1,59 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h b/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h deleted file mode 100644 index 71952d48..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.h +++ /dev/null @@ -1,79 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m b/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m deleted file mode 100644 index 901eb281..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+AnyPromise.m +++ /dev/null @@ -1,113 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift b/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift deleted file mode 100644 index 13259a0c..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/NSURLSession+Promise.swift +++ /dev/null @@ -1,241 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h b/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h deleted file mode 100644 index 8796c0d1..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/PMKFoundation.h +++ /dev/null @@ -1,3 +0,0 @@ -#import "NSNotificationCenter+AnyPromise.h" -#import "NSURLSession+AnyPromise.h" -#import "NSTask+AnyPromise.h" diff --git a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift b/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift deleted file mode 100644 index 03cab3cf..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/Process+Promise.swift +++ /dev/null @@ -1,190 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift b/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift deleted file mode 100644 index 232c8da9..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift +++ /dev/null @@ -1,26 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h b/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h deleted file mode 100644 index 75cbf90f..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/PMKUIKit.h +++ /dev/null @@ -1,8 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h b/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h deleted file mode 100644 index 0a19cd6f..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.h +++ /dev/null @@ -1,80 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m b/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m deleted file mode 100644 index 04ee9403..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+AnyPromise.m +++ /dev/null @@ -1,64 +0,0 @@ -// -// 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/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift b/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift deleted file mode 100644 index 1bbb8c64..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIView+Promise.swift +++ /dev/null @@ -1,115 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h b/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h deleted file mode 100644 index 0e60ca9e..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.h +++ /dev/null @@ -1,71 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m b/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m deleted file mode 100644 index 5231e55b..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewController+AnyPromise.m +++ /dev/null @@ -1,140 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift b/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift deleted file mode 100644 index 34ee1408..00000000 --- a/cocoapods/Pods/PromiseKit/Extensions/UIKit/Sources/UIViewPropertyAnimator+Promise.swift +++ /dev/null @@ -1,14 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/LICENSE b/cocoapods/Pods/PromiseKit/LICENSE deleted file mode 100644 index 50f758c8..00000000 --- a/cocoapods/Pods/PromiseKit/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -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/cocoapods/Pods/PromiseKit/README.md b/cocoapods/Pods/PromiseKit/README.md deleted file mode 100644 index c06b464f..00000000 --- a/cocoapods/Pods/PromiseKit/README.md +++ /dev/null @@ -1,207 +0,0 @@ -![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/cocoapods/Pods/PromiseKit/Sources/AnyPromise+Private.h b/cocoapods/Pods/PromiseKit/Sources/AnyPromise+Private.h deleted file mode 100644 index cd28c418..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/AnyPromise+Private.h +++ /dev/null @@ -1,32 +0,0 @@ -@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/cocoapods/Pods/PromiseKit/Sources/AnyPromise.h b/cocoapods/Pods/PromiseKit/Sources/AnyPromise.h deleted file mode 100644 index fd1ad3a9..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/AnyPromise.h +++ /dev/null @@ -1,299 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Sources/AnyPromise.m b/cocoapods/Pods/PromiseKit/Sources/AnyPromise.m deleted file mode 100644 index af663100..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/AnyPromise.m +++ /dev/null @@ -1,175 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Sources/AnyPromise.swift b/cocoapods/Pods/PromiseKit/Sources/AnyPromise.swift deleted file mode 100644 index 5dfa1df4..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/AnyPromise.swift +++ /dev/null @@ -1,204 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Sources/Box.swift b/cocoapods/Pods/PromiseKit/Sources/Box.swift deleted file mode 100644 index 43cd3d1b..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/Box.swift +++ /dev/null @@ -1,101 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Sources/Catchable.swift b/cocoapods/Pods/PromiseKit/Sources/Catchable.swift deleted file mode 100644 index 596abdcb..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/Catchable.swift +++ /dev/null @@ -1,256 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Sources/Configuration.swift b/cocoapods/Pods/PromiseKit/Sources/Configuration.swift deleted file mode 100644 index 9d4fc22f..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/Configuration.swift +++ /dev/null @@ -1,35 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Sources/CustomStringConvertible.swift b/cocoapods/Pods/PromiseKit/Sources/CustomStringConvertible.swift deleted file mode 100644 index eee0b020..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/CustomStringConvertible.swift +++ /dev/null @@ -1,44 +0,0 @@ - -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/cocoapods/Pods/PromiseKit/Sources/Deprecations.swift b/cocoapods/Pods/PromiseKit/Sources/Deprecations.swift deleted file mode 100644 index a837dcb8..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/Deprecations.swift +++ /dev/null @@ -1,93 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Sources/Error.swift b/cocoapods/Pods/PromiseKit/Sources/Error.swift deleted file mode 100644 index 7229e6f4..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/Error.swift +++ /dev/null @@ -1,103 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Sources/Guarantee.swift b/cocoapods/Pods/PromiseKit/Sources/Guarantee.swift deleted file mode 100644 index b87fad18..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/Guarantee.swift +++ /dev/null @@ -1,212 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Sources/LogEvent.swift b/cocoapods/Pods/PromiseKit/Sources/LogEvent.swift deleted file mode 100644 index 99683bdb..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/LogEvent.swift +++ /dev/null @@ -1,30 +0,0 @@ -/** - 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/cocoapods/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m b/cocoapods/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m deleted file mode 100644 index 700c1b37..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/NSMethodSignatureForBlock.m +++ /dev/null @@ -1,77 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m b/cocoapods/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m deleted file mode 100644 index 1453a7d2..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/PMKCallVariadicBlock.m +++ /dev/null @@ -1,120 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Sources/Promise.swift b/cocoapods/Pods/PromiseKit/Sources/Promise.swift deleted file mode 100644 index da9f6aa2..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/Promise.swift +++ /dev/null @@ -1,179 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Sources/PromiseKit.h b/cocoapods/Pods/PromiseKit/Sources/PromiseKit.h deleted file mode 100644 index 2651530c..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/PromiseKit.h +++ /dev/null @@ -1,7 +0,0 @@ -#import "fwd.h" -#import "AnyPromise.h" - -#import // `FOUNDATION_EXPORT` - -FOUNDATION_EXPORT double PromiseKitVersionNumber; -FOUNDATION_EXPORT const unsigned char PromiseKitVersionString[]; diff --git a/cocoapods/Pods/PromiseKit/Sources/Resolver.swift b/cocoapods/Pods/PromiseKit/Sources/Resolver.swift deleted file mode 100644 index 78531adb..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/Resolver.swift +++ /dev/null @@ -1,99 +0,0 @@ -/// 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/cocoapods/Pods/PromiseKit/Sources/Thenable.swift b/cocoapods/Pods/PromiseKit/Sources/Thenable.swift deleted file mode 100644 index 77623720..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/Thenable.swift +++ /dev/null @@ -1,424 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Sources/after.m b/cocoapods/Pods/PromiseKit/Sources/after.m deleted file mode 100644 index 25f9966f..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/after.m +++ /dev/null @@ -1,14 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Sources/after.swift b/cocoapods/Pods/PromiseKit/Sources/after.swift deleted file mode 100644 index cdaeccd9..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/after.swift +++ /dev/null @@ -1,46 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Sources/dispatch_promise.m b/cocoapods/Pods/PromiseKit/Sources/dispatch_promise.m deleted file mode 100644 index ecb89f71..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/dispatch_promise.m +++ /dev/null @@ -1,10 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Sources/firstly.swift b/cocoapods/Pods/PromiseKit/Sources/firstly.swift deleted file mode 100644 index a5b477da..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/firstly.swift +++ /dev/null @@ -1,39 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Sources/fwd.h b/cocoapods/Pods/PromiseKit/Sources/fwd.h deleted file mode 100644 index 480d1480..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/fwd.h +++ /dev/null @@ -1,165 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Sources/hang.m b/cocoapods/Pods/PromiseKit/Sources/hang.m deleted file mode 100644 index 913339e5..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/hang.m +++ /dev/null @@ -1,29 +0,0 @@ -#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/cocoapods/Pods/PromiseKit/Sources/hang.swift b/cocoapods/Pods/PromiseKit/Sources/hang.swift deleted file mode 100644 index 53d54dec..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/hang.swift +++ /dev/null @@ -1,55 +0,0 @@ -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/cocoapods/Pods/PromiseKit/Sources/join.m b/cocoapods/Pods/PromiseKit/Sources/join.m deleted file mode 100644 index 979f092d..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/join.m +++ /dev/null @@ -1,54 +0,0 @@ -@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/cocoapods/Pods/PromiseKit/Sources/race.m b/cocoapods/Pods/PromiseKit/Sources/race.m deleted file mode 100644 index cab38ec1..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/race.m +++ /dev/null @@ -1,9 +0,0 @@ -#import "AnyPromise+Private.h" - -AnyPromise *PMKRace(NSArray *promises) { - return [AnyPromise promiseWithResolverBlock:^(PMKResolver resolve) { - for (AnyPromise *promise in promises) { - [promise __pipe:resolve]; - } - }]; -} diff --git a/cocoapods/Pods/PromiseKit/Sources/race.swift b/cocoapods/Pods/PromiseKit/Sources/race.swift deleted file mode 100644 index 2b817de2..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/race.swift +++ /dev/null @@ -1,57 +0,0 @@ -@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/cocoapods/Pods/PromiseKit/Sources/when.m b/cocoapods/Pods/PromiseKit/Sources/when.m deleted file mode 100644 index 43e5fedd..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/when.m +++ /dev/null @@ -1,107 +0,0 @@ -@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/cocoapods/Pods/PromiseKit/Sources/when.swift b/cocoapods/Pods/PromiseKit/Sources/when.swift deleted file mode 100644 index 0913c64f..00000000 --- a/cocoapods/Pods/PromiseKit/Sources/when.swift +++ /dev/null @@ -1,262 +0,0 @@ -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/cocoapods/Pods/Starscream/LICENSE b/cocoapods/Pods/Starscream/LICENSE deleted file mode 100644 index d6ab2f1f..00000000 --- a/cocoapods/Pods/Starscream/LICENSE +++ /dev/null @@ -1,176 +0,0 @@ - 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/cocoapods/Pods/Starscream/README.md b/cocoapods/Pods/Starscream/README.md deleted file mode 100644 index 90a7e0e6..00000000 --- a/cocoapods/Pods/Starscream/README.md +++ /dev/null @@ -1,438 +0,0 @@ -![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/cocoapods/Pods/Starscream/Sources/Starscream/Compression.swift b/cocoapods/Pods/Starscream/Sources/Starscream/Compression.swift deleted file mode 100644 index ab657902..00000000 --- a/cocoapods/Pods/Starscream/Sources/Starscream/Compression.swift +++ /dev/null @@ -1,177 +0,0 @@ -////////////////////////////////////////////////////////////////////////////////////////////////// -// -// 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/cocoapods/Pods/Starscream/Sources/Starscream/SSLClientCertificate.swift b/cocoapods/Pods/Starscream/Sources/Starscream/SSLClientCertificate.swift deleted file mode 100644 index 34109122..00000000 --- a/cocoapods/Pods/Starscream/Sources/Starscream/SSLClientCertificate.swift +++ /dev/null @@ -1,92 +0,0 @@ -// -// 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/cocoapods/Pods/Starscream/Sources/Starscream/SSLSecurity.swift b/cocoapods/Pods/Starscream/Sources/Starscream/SSLSecurity.swift deleted file mode 100644 index 6a14dd15..00000000 --- a/cocoapods/Pods/Starscream/Sources/Starscream/SSLSecurity.swift +++ /dev/null @@ -1,266 +0,0 @@ -////////////////////////////////////////////////////////////////////////////////////////////////// -// -// 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/cocoapods/Pods/Starscream/Sources/Starscream/WebSocket.swift b/cocoapods/Pods/Starscream/Sources/Starscream/WebSocket.swift deleted file mode 100644 index 7d48a20d..00000000 --- a/cocoapods/Pods/Starscream/Sources/Starscream/WebSocket.swift +++ /dev/null @@ -1,1356 +0,0 @@ -////////////////////////////////////////////////////////////////////////////////////////////////// -// -// 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/cocoapods/Pods/Target Support Files/BestLogger/BestLogger-Info.plist b/cocoapods/Pods/Target Support Files/BestLogger/BestLogger-Info.plist deleted file mode 100644 index 3f038707..00000000 --- a/cocoapods/Pods/Target Support Files/BestLogger/BestLogger-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 0.0.3 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/cocoapods/Pods/Target Support Files/BestLogger/BestLogger-dummy.m b/cocoapods/Pods/Target Support Files/BestLogger/BestLogger-dummy.m deleted file mode 100644 index 4cc344d6..00000000 --- a/cocoapods/Pods/Target Support Files/BestLogger/BestLogger-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_BestLogger : NSObject -@end -@implementation PodsDummy_BestLogger -@end diff --git a/cocoapods/Pods/Target Support Files/BestLogger/BestLogger-prefix.pch b/cocoapods/Pods/Target Support Files/BestLogger/BestLogger-prefix.pch deleted file mode 100644 index beb2a244..00000000 --- a/cocoapods/Pods/Target Support Files/BestLogger/BestLogger-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/BestLogger/BestLogger-umbrella.h b/cocoapods/Pods/Target Support Files/BestLogger/BestLogger-umbrella.h deleted file mode 100644 index b50986fc..00000000 --- a/cocoapods/Pods/Target Support Files/BestLogger/BestLogger-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#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 BestLoggerVersionNumber; -FOUNDATION_EXPORT const unsigned char BestLoggerVersionString[]; - diff --git a/cocoapods/Pods/Target Support Files/BestLogger/BestLogger.debug.xcconfig b/cocoapods/Pods/Target Support Files/BestLogger/BestLogger.debug.xcconfig deleted file mode 100644 index d722054d..00000000 --- a/cocoapods/Pods/Target Support Files/BestLogger/BestLogger.debug.xcconfig +++ /dev/null @@ -1,12 +0,0 @@ -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/BestLogger -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}/BestLogger -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/cocoapods/Pods/Target Support Files/BestLogger/BestLogger.modulemap b/cocoapods/Pods/Target Support Files/BestLogger/BestLogger.modulemap deleted file mode 100644 index 5f37c7c5..00000000 --- a/cocoapods/Pods/Target Support Files/BestLogger/BestLogger.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module BestLogger { - umbrella header "BestLogger-umbrella.h" - - export * - module * { export * } -} diff --git a/cocoapods/Pods/Target Support Files/BestLogger/BestLogger.release.xcconfig b/cocoapods/Pods/Target Support Files/BestLogger/BestLogger.release.xcconfig deleted file mode 100644 index d722054d..00000000 --- a/cocoapods/Pods/Target Support Files/BestLogger/BestLogger.release.xcconfig +++ /dev/null @@ -1,12 +0,0 @@ -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/BestLogger -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}/BestLogger -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/cocoapods/Pods/Target Support Files/BigInt/BigInt-Info.plist b/cocoapods/Pods/Target Support Files/BigInt/BigInt-Info.plist deleted file mode 100644 index 3424ca66..00000000 --- a/cocoapods/Pods/Target Support Files/BigInt/BigInt-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - 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/cocoapods/Pods/Target Support Files/BigInt/BigInt-dummy.m b/cocoapods/Pods/Target Support Files/BigInt/BigInt-dummy.m deleted file mode 100644 index 7367f860..00000000 --- a/cocoapods/Pods/Target Support Files/BigInt/BigInt-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_BigInt : NSObject -@end -@implementation PodsDummy_BigInt -@end diff --git a/cocoapods/Pods/Target Support Files/BigInt/BigInt-prefix.pch b/cocoapods/Pods/Target Support Files/BigInt/BigInt-prefix.pch deleted file mode 100644 index beb2a244..00000000 --- a/cocoapods/Pods/Target Support Files/BigInt/BigInt-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/BigInt/BigInt-umbrella.h b/cocoapods/Pods/Target Support Files/BigInt/BigInt-umbrella.h deleted file mode 100644 index e3d2506e..00000000 --- a/cocoapods/Pods/Target Support Files/BigInt/BigInt-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/BigInt/BigInt.debug.xcconfig b/cocoapods/Pods/Target Support Files/BigInt/BigInt.debug.xcconfig deleted file mode 100644 index 14420073..00000000 --- a/cocoapods/Pods/Target Support Files/BigInt/BigInt.debug.xcconfig +++ /dev/null @@ -1,12 +0,0 @@ -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/cocoapods/Pods/Target Support Files/BigInt/BigInt.modulemap b/cocoapods/Pods/Target Support Files/BigInt/BigInt.modulemap deleted file mode 100644 index 48a38d1c..00000000 --- a/cocoapods/Pods/Target Support Files/BigInt/BigInt.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module BigInt { - umbrella header "BigInt-umbrella.h" - - export * - module * { export * } -} diff --git a/cocoapods/Pods/Target Support Files/BigInt/BigInt.release.xcconfig b/cocoapods/Pods/Target Support Files/BigInt/BigInt.release.xcconfig deleted file mode 100644 index 14420073..00000000 --- a/cocoapods/Pods/Target Support Files/BigInt/BigInt.release.xcconfig +++ /dev/null @@ -1,12 +0,0 @@ -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/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift-Info.plist b/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift-Info.plist deleted file mode 100644 index 2243fe6e..00000000 --- a/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - 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/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift-dummy.m b/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift-dummy.m deleted file mode 100644 index 657061bc..00000000 --- a/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_CryptoSwift : NSObject -@end -@implementation PodsDummy_CryptoSwift -@end diff --git a/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift-prefix.pch b/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift-prefix.pch deleted file mode 100644 index beb2a244..00000000 --- a/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift-umbrella.h b/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift-umbrella.h deleted file mode 100644 index e93efa88..00000000 --- a/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift.debug.xcconfig b/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift.debug.xcconfig deleted file mode 100644 index f8490fbf..00000000 --- a/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift.debug.xcconfig +++ /dev/null @@ -1,17 +0,0 @@ -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/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift.modulemap b/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift.modulemap deleted file mode 100644 index f090f6a3..00000000 --- a/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module CryptoSwift { - umbrella header "CryptoSwift-umbrella.h" - - export * - module * { export * } -} diff --git a/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift.release.xcconfig b/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift.release.xcconfig deleted file mode 100644 index f8490fbf..00000000 --- a/cocoapods/Pods/Target Support Files/CryptoSwift/CryptoSwift.release.xcconfig +++ /dev/null @@ -1,17 +0,0 @@ -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/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-Info.plist b/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-Info.plist deleted file mode 100644 index 2243fe6e..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - 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/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-acknowledgements.markdown b/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-acknowledgements.markdown deleted file mode 100644 index 016130e9..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-acknowledgements.markdown +++ /dev/null @@ -1,515 +0,0 @@ -# Acknowledgements -This application makes use of the following third party libraries: - -## BestLogger - -Copyright 2020 Shubham Rathi - -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. - - -## 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. - -## Torus-fetchNodeDetails - -Copyright (c) 2020 Torus Labs Private Limited (https://tor.us) - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -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. - - -## Torus-utils - -Copyright (c) 2020 Torus Labs Private Limited (https://tor.us) - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -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. - - -## 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/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-acknowledgements.plist b/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-acknowledgements.plist deleted file mode 100644 index 3ae7dba3..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-acknowledgements.plist +++ /dev/null @@ -1,595 +0,0 @@ - - - - - PreferenceSpecifiers - - - FooterText - This application makes use of the following third party libraries: - Title - Acknowledgements - Type - PSGroupSpecifier - - - FooterText - Copyright 2020 Shubham Rathi - -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 - BestLogger - 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) 2020 Torus Labs Private Limited (https://tor.us) - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -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. - - License - BSD - Title - Torus-fetchNodeDetails - Type - PSGroupSpecifier - - - FooterText - Copyright (c) 2020 Torus Labs Private Limited (https://tor.us) - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -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. - - License - BSD - Title - Torus-utils - 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/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-dummy.m b/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-dummy.m deleted file mode 100644 index f4bf837c..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Pods_TestApplication_TestApplicationTests : NSObject -@end -@implementation PodsDummy_Pods_TestApplication_TestApplicationTests -@end diff --git a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks-Debug-input-files.xcfilelist b/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks-Debug-input-files.xcfilelist deleted file mode 100644 index d845f7c1..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks-Debug-input-files.xcfilelist +++ /dev/null @@ -1,10 +0,0 @@ -${PODS_ROOT}/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks.sh -${BUILT_PRODUCTS_DIR}/BestLogger/BestLogger.framework -${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}/Torus-fetchNodeDetails/FetchNodeDetails.framework -${BUILT_PRODUCTS_DIR}/Torus-utils/TorusUtils.framework -${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework -${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework \ No newline at end of file diff --git a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks-Debug-output-files.xcfilelist b/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks-Debug-output-files.xcfilelist deleted file mode 100644 index f207f537..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks-Debug-output-files.xcfilelist +++ /dev/null @@ -1,9 +0,0 @@ -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/BestLogger.framework -${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}/FetchNodeDetails.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/TorusUtils.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/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks-Release-input-files.xcfilelist b/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks-Release-input-files.xcfilelist deleted file mode 100644 index d845f7c1..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks-Release-input-files.xcfilelist +++ /dev/null @@ -1,10 +0,0 @@ -${PODS_ROOT}/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks.sh -${BUILT_PRODUCTS_DIR}/BestLogger/BestLogger.framework -${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}/Torus-fetchNodeDetails/FetchNodeDetails.framework -${BUILT_PRODUCTS_DIR}/Torus-utils/TorusUtils.framework -${BUILT_PRODUCTS_DIR}/secp256k1.c/secp256k1.framework -${BUILT_PRODUCTS_DIR}/web3swift/web3swift.framework \ No newline at end of file diff --git a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks-Release-output-files.xcfilelist b/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks-Release-output-files.xcfilelist deleted file mode 100644 index f207f537..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks-Release-output-files.xcfilelist +++ /dev/null @@ -1,9 +0,0 @@ -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/BestLogger.framework -${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}/FetchNodeDetails.framework -${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/TorusUtils.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/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks.sh b/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks.sh deleted file mode 100755 index 5a52e8f7..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-frameworks.sh +++ /dev/null @@ -1,201 +0,0 @@ -#!/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}/BestLogger/BestLogger.framework" - 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}/Torus-fetchNodeDetails/FetchNodeDetails.framework" - install_framework "${BUILT_PRODUCTS_DIR}/Torus-utils/TorusUtils.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}/BestLogger/BestLogger.framework" - 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}/Torus-fetchNodeDetails/FetchNodeDetails.framework" - install_framework "${BUILT_PRODUCTS_DIR}/Torus-utils/TorusUtils.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/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-umbrella.h b/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-umbrella.h deleted file mode 100644 index a55dc480..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#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_TestApplication_TestApplicationTestsVersionNumber; -FOUNDATION_EXPORT const unsigned char Pods_TestApplication_TestApplicationTestsVersionString[]; - diff --git a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests.debug.xcconfig b/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests.debug.xcconfig deleted file mode 100644 index 9fee1f31..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests.debug.xcconfig +++ /dev/null @@ -1,15 +0,0 @@ -ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -EXCLUDED_ARCHS[sdk=iphonesimulator*] = arm64 -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BestLogger" "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-fetchNodeDetails" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-utils" "${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}/BestLogger/BestLogger.framework/Headers" "${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}/Torus-fetchNodeDetails/FetchNodeDetails.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-utils/TorusUtils.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 "BestLogger" -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "FetchNodeDetails" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "TorusUtils" -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/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests.modulemap b/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests.modulemap deleted file mode 100644 index a11a866b..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Pods_TestApplication_TestApplicationTests { - umbrella header "Pods-TestApplication-TestApplicationTests-umbrella.h" - - export * - module * { export * } -} diff --git a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests.release.xcconfig b/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests.release.xcconfig deleted file mode 100644 index 9fee1f31..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication-TestApplicationTests/Pods-TestApplication-TestApplicationTests.release.xcconfig +++ /dev/null @@ -1,15 +0,0 @@ -ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -EXCLUDED_ARCHS[sdk=iphonesimulator*] = arm64 -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BestLogger" "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-fetchNodeDetails" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-utils" "${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}/BestLogger/BestLogger.framework/Headers" "${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}/Torus-fetchNodeDetails/FetchNodeDetails.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-utils/TorusUtils.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 "BestLogger" -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "FetchNodeDetails" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "TorusUtils" -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/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-Info.plist b/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-Info.plist deleted file mode 100644 index 2243fe6e..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - 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/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-acknowledgements.markdown b/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-acknowledgements.markdown deleted file mode 100644 index 016130e9..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-acknowledgements.markdown +++ /dev/null @@ -1,515 +0,0 @@ -# Acknowledgements -This application makes use of the following third party libraries: - -## BestLogger - -Copyright 2020 Shubham Rathi - -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. - - -## 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. - -## Torus-fetchNodeDetails - -Copyright (c) 2020 Torus Labs Private Limited (https://tor.us) - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -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. - - -## Torus-utils - -Copyright (c) 2020 Torus Labs Private Limited (https://tor.us) - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -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. - - -## 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/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-acknowledgements.plist b/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-acknowledgements.plist deleted file mode 100644 index 3ae7dba3..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-acknowledgements.plist +++ /dev/null @@ -1,595 +0,0 @@ - - - - - PreferenceSpecifiers - - - FooterText - This application makes use of the following third party libraries: - Title - Acknowledgements - Type - PSGroupSpecifier - - - FooterText - Copyright 2020 Shubham Rathi - -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 - BestLogger - 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) 2020 Torus Labs Private Limited (https://tor.us) - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -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. - - License - BSD - Title - Torus-fetchNodeDetails - Type - PSGroupSpecifier - - - FooterText - Copyright (c) 2020 Torus Labs Private Limited (https://tor.us) - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -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. - - License - BSD - Title - Torus-utils - 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/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-dummy.m b/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-dummy.m deleted file mode 100644 index 4c310b7b..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Pods_TestApplication : NSObject -@end -@implementation PodsDummy_Pods_TestApplication -@end diff --git a/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-umbrella.h b/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-umbrella.h deleted file mode 100644 index 5365201d..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#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_TestApplicationVersionNumber; -FOUNDATION_EXPORT const unsigned char Pods_TestApplicationVersionString[]; - diff --git a/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication.debug.xcconfig b/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication.debug.xcconfig deleted file mode 100644 index 7c94a367..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication.debug.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -EXCLUDED_ARCHS[sdk=iphonesimulator*] = arm64 -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BestLogger" "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-fetchNodeDetails" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-utils" "${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}/BestLogger/BestLogger.framework/Headers" "${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}/Torus-fetchNodeDetails/FetchNodeDetails.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-utils/TorusUtils.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' '@executable_path/../../Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "BestLogger" -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "FetchNodeDetails" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "TorusUtils" -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/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication.modulemap b/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication.modulemap deleted file mode 100644 index a18fd9b7..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Pods_TestApplication { - umbrella header "Pods-TestApplication-umbrella.h" - - export * - module * { export * } -} diff --git a/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication.release.xcconfig b/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication.release.xcconfig deleted file mode 100644 index 7c94a367..00000000 --- a/cocoapods/Pods/Target Support Files/Pods-TestApplication/Pods-TestApplication.release.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -EXCLUDED_ARCHS[sdk=iphonesimulator*] = arm64 -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BestLogger" "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-fetchNodeDetails" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-utils" "${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}/BestLogger/BestLogger.framework/Headers" "${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}/Torus-fetchNodeDetails/FetchNodeDetails.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-utils/TorusUtils.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' '@executable_path/../../Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "BestLogger" -framework "BigInt" -framework "CoreImage" -framework "CryptoSwift" -framework "FetchNodeDetails" -framework "Foundation" -framework "PromiseKit" -framework "Starscream" -framework "TorusUtils" -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/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit-Info.plist b/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit-Info.plist deleted file mode 100644 index d4e60cc2..00000000 --- a/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - 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/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m b/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m deleted file mode 100644 index ce924513..00000000 --- a/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_PromiseKit : NSObject -@end -@implementation PodsDummy_PromiseKit -@end diff --git a/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch b/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch deleted file mode 100644 index beb2a244..00000000 --- a/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h b/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h deleted file mode 100644 index 4a0b02de..00000000 --- a/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit-umbrella.h +++ /dev/null @@ -1,26 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit.debug.xcconfig b/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit.debug.xcconfig deleted file mode 100644 index 3dfb3d92..00000000 --- a/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit.debug.xcconfig +++ /dev/null @@ -1,13 +0,0 @@ -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/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap b/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap deleted file mode 100644 index 2b26033e..00000000 --- a/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module PromiseKit { - umbrella header "PromiseKit-umbrella.h" - - export * - module * { export * } -} diff --git a/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit.release.xcconfig b/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit.release.xcconfig deleted file mode 100644 index 3dfb3d92..00000000 --- a/cocoapods/Pods/Target Support Files/PromiseKit/PromiseKit.release.xcconfig +++ /dev/null @@ -1,13 +0,0 @@ -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/cocoapods/Pods/Target Support Files/Starscream/Starscream-Info.plist b/cocoapods/Pods/Target Support Files/Starscream/Starscream-Info.plist deleted file mode 100644 index 793d31a9..00000000 --- a/cocoapods/Pods/Target Support Files/Starscream/Starscream-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - 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/cocoapods/Pods/Target Support Files/Starscream/Starscream-dummy.m b/cocoapods/Pods/Target Support Files/Starscream/Starscream-dummy.m deleted file mode 100644 index 94456b3b..00000000 --- a/cocoapods/Pods/Target Support Files/Starscream/Starscream-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Starscream : NSObject -@end -@implementation PodsDummy_Starscream -@end diff --git a/cocoapods/Pods/Target Support Files/Starscream/Starscream-prefix.pch b/cocoapods/Pods/Target Support Files/Starscream/Starscream-prefix.pch deleted file mode 100644 index beb2a244..00000000 --- a/cocoapods/Pods/Target Support Files/Starscream/Starscream-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/Starscream/Starscream-umbrella.h b/cocoapods/Pods/Target Support Files/Starscream/Starscream-umbrella.h deleted file mode 100644 index 7bffee0b..00000000 --- a/cocoapods/Pods/Target Support Files/Starscream/Starscream-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/Starscream/Starscream.debug.xcconfig b/cocoapods/Pods/Target Support Files/Starscream/Starscream.debug.xcconfig deleted file mode 100644 index 23e1409b..00000000 --- a/cocoapods/Pods/Target Support Files/Starscream/Starscream.debug.xcconfig +++ /dev/null @@ -1,12 +0,0 @@ -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/cocoapods/Pods/Target Support Files/Starscream/Starscream.modulemap b/cocoapods/Pods/Target Support Files/Starscream/Starscream.modulemap deleted file mode 100644 index 2b909707..00000000 --- a/cocoapods/Pods/Target Support Files/Starscream/Starscream.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Starscream { - umbrella header "Starscream-umbrella.h" - - export * - module * { export * } -} diff --git a/cocoapods/Pods/Target Support Files/Starscream/Starscream.release.xcconfig b/cocoapods/Pods/Target Support Files/Starscream/Starscream.release.xcconfig deleted file mode 100644 index 23e1409b..00000000 --- a/cocoapods/Pods/Target Support Files/Starscream/Starscream.release.xcconfig +++ /dev/null @@ -1,12 +0,0 @@ -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/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-Info.plist b/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-Info.plist deleted file mode 100644 index a54a1c88..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 0.0.20 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-dummy.m b/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-dummy.m deleted file mode 100644 index 82d0a187..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Torus_fetchNodeDetails : NSObject -@end -@implementation PodsDummy_Torus_fetchNodeDetails -@end diff --git a/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-prefix.pch b/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-prefix.pch deleted file mode 100644 index beb2a244..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-umbrella.h b/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-umbrella.h deleted file mode 100644 index c914edb9..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#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 FetchNodeDetailsVersionNumber; -FOUNDATION_EXPORT const unsigned char FetchNodeDetailsVersionString[]; - diff --git a/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails.debug.xcconfig b/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails.debug.xcconfig deleted file mode 100644 index bc6f20fb..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails.debug.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Torus-fetchNodeDetails -EXCLUDED_ARCHS[sdk=iphonesimulator*] = arm64 -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BestLogger" "${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 -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}/Torus-fetchNodeDetails -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/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails.modulemap b/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails.modulemap deleted file mode 100644 index 5d5f414f..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module FetchNodeDetails { - umbrella header "Torus-fetchNodeDetails-umbrella.h" - - export * - module * { export * } -} diff --git a/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails.release.xcconfig b/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails.release.xcconfig deleted file mode 100644 index bc6f20fb..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-fetchNodeDetails/Torus-fetchNodeDetails.release.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Torus-fetchNodeDetails -EXCLUDED_ARCHS[sdk=iphonesimulator*] = arm64 -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BestLogger" "${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 -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}/Torus-fetchNodeDetails -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/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils-Info.plist b/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils-Info.plist deleted file mode 100644 index 97eeedab..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 0.1.1 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils-dummy.m b/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils-dummy.m deleted file mode 100644 index dddd9d0a..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Torus_utils : NSObject -@end -@implementation PodsDummy_Torus_utils -@end diff --git a/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils-prefix.pch b/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils-prefix.pch deleted file mode 100644 index beb2a244..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils-umbrella.h b/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils-umbrella.h deleted file mode 100644 index ef1b3428..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#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 TorusUtilsVersionNumber; -FOUNDATION_EXPORT const unsigned char TorusUtilsVersionString[]; - diff --git a/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils.debug.xcconfig b/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils.debug.xcconfig deleted file mode 100644 index 8590efda..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils.debug.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Torus-utils -EXCLUDED_ARCHS[sdk=iphonesimulator*] = arm64 -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BestLogger" "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-fetchNodeDetails" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" -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}/../.. -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/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils.modulemap b/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils.modulemap deleted file mode 100644 index fb3cff6d..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module TorusUtils { - umbrella header "Torus-utils-umbrella.h" - - export * - module * { export * } -} diff --git a/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils.release.xcconfig b/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils.release.xcconfig deleted file mode 100644 index 8590efda..00000000 --- a/cocoapods/Pods/Target Support Files/Torus-utils/Torus-utils.release.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Torus-utils -EXCLUDED_ARCHS[sdk=iphonesimulator*] = arm64 -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/BestLogger" "${PODS_CONFIGURATION_BUILD_DIR}/BigInt" "${PODS_CONFIGURATION_BUILD_DIR}/CryptoSwift" "${PODS_CONFIGURATION_BUILD_DIR}/PromiseKit" "${PODS_CONFIGURATION_BUILD_DIR}/Starscream" "${PODS_CONFIGURATION_BUILD_DIR}/Torus-fetchNodeDetails" "${PODS_CONFIGURATION_BUILD_DIR}/secp256k1.c" "${PODS_CONFIGURATION_BUILD_DIR}/web3swift" -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}/../.. -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/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c-Info.plist b/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c-Info.plist deleted file mode 100644 index 7c241fa9..00000000 --- a/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - 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/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c-dummy.m b/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c-dummy.m deleted file mode 100644 index 965dbb1b..00000000 --- a/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_secp256k1_c : NSObject -@end -@implementation PodsDummy_secp256k1_c -@end diff --git a/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c-prefix.pch b/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c-prefix.pch deleted file mode 100644 index beb2a244..00000000 --- a/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c-umbrella.h b/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c-umbrella.h deleted file mode 100644 index 6943b49f..00000000 --- a/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c-umbrella.h +++ /dev/null @@ -1,17 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c.debug.xcconfig b/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c.debug.xcconfig deleted file mode 100644 index 93ba0a8c..00000000 --- a/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c.debug.xcconfig +++ /dev/null @@ -1,13 +0,0 @@ -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/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c.modulemap b/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c.modulemap deleted file mode 100644 index 94da377c..00000000 --- a/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module secp256k1 { - umbrella header "secp256k1.c-umbrella.h" - - export * - module * { export * } -} diff --git a/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c.release.xcconfig b/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c.release.xcconfig deleted file mode 100644 index 93ba0a8c..00000000 --- a/cocoapods/Pods/Target Support Files/secp256k1.c/secp256k1.c.release.xcconfig +++ /dev/null @@ -1,13 +0,0 @@ -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/cocoapods/Pods/Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist b/cocoapods/Pods/Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist deleted file mode 100644 index 86717ece..00000000 --- a/cocoapods/Pods/Target Support Files/web3swift/ResourceBundle-Browser-web3swift-Info.plist +++ /dev/null @@ -1,24 +0,0 @@ - - - - - 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/cocoapods/Pods/Target Support Files/web3swift/web3swift-Info.plist b/cocoapods/Pods/Target Support Files/web3swift/web3swift-Info.plist deleted file mode 100644 index d135faf1..00000000 --- a/cocoapods/Pods/Target Support Files/web3swift/web3swift-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - 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/cocoapods/Pods/Target Support Files/web3swift/web3swift-dummy.m b/cocoapods/Pods/Target Support Files/web3swift/web3swift-dummy.m deleted file mode 100644 index ee2665c9..00000000 --- a/cocoapods/Pods/Target Support Files/web3swift/web3swift-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_web3swift : NSObject -@end -@implementation PodsDummy_web3swift -@end diff --git a/cocoapods/Pods/Target Support Files/web3swift/web3swift-prefix.pch b/cocoapods/Pods/Target Support Files/web3swift/web3swift-prefix.pch deleted file mode 100644 index beb2a244..00000000 --- a/cocoapods/Pods/Target Support Files/web3swift/web3swift-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/web3swift/web3swift-umbrella.h b/cocoapods/Pods/Target Support Files/web3swift/web3swift-umbrella.h deleted file mode 100644 index 9ec6a0b4..00000000 --- a/cocoapods/Pods/Target Support Files/web3swift/web3swift-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#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/cocoapods/Pods/Target Support Files/web3swift/web3swift.debug.xcconfig b/cocoapods/Pods/Target Support Files/web3swift/web3swift.debug.xcconfig deleted file mode 100644 index b9fd5fdd..00000000 --- a/cocoapods/Pods/Target Support Files/web3swift/web3swift.debug.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -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/cocoapods/Pods/Target Support Files/web3swift/web3swift.modulemap b/cocoapods/Pods/Target Support Files/web3swift/web3swift.modulemap deleted file mode 100644 index 241e217a..00000000 --- a/cocoapods/Pods/Target Support Files/web3swift/web3swift.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module web3swift { - umbrella header "web3swift-umbrella.h" - - export * - module * { export * } -} diff --git a/cocoapods/Pods/Target Support Files/web3swift/web3swift.release.xcconfig b/cocoapods/Pods/Target Support Files/web3swift/web3swift.release.xcconfig deleted file mode 100644 index b9fd5fdd..00000000 --- a/cocoapods/Pods/Target Support Files/web3swift/web3swift.release.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -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/cocoapods/Pods/Torus-fetchNodeDetails/License.md b/cocoapods/Pods/Torus-fetchNodeDetails/License.md deleted file mode 100644 index 5eec43ec..00000000 --- a/cocoapods/Pods/Torus-fetchNodeDetails/License.md +++ /dev/null @@ -1,11 +0,0 @@ -Copyright (c) 2020 Torus Labs Private Limited (https://tor.us) - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -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. diff --git a/cocoapods/Pods/Torus-fetchNodeDetails/README.md b/cocoapods/Pods/Torus-fetchNodeDetails/README.md deleted file mode 100644 index d9942ebc..00000000 --- a/cocoapods/Pods/Torus-fetchNodeDetails/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# fetch-node-details - -A description of this package. - -## Installation - -### Swift Package Manage - -``` -.package(url: "https://github.com/torusresearch/fetch-node-details-swift5.git", from: "0.0.1"), -``` diff --git a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/contract/abi.json b/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/contract/abi.json deleted file mode 100644 index f5e6f92b..00000000 --- a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/contract/abi.json +++ /dev/null @@ -1,116 +0,0 @@ -{ - "abi": [ - { - "constant": true, - "inputs": [], - "name": "currentEpoch", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "internalType": "uint256", - "name": "epoch", - "type": "uint256" - } - ], - "name": "getEpochInfo", - "outputs": [ - { - "internalType": "uint256", - "name": "id", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "n", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "k", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "t", - "type": "uint256" - }, - { - "internalType": "address[]", - "name": "nodeList", - "type": "address[]" - }, - { - "internalType": "uint256", - "name": "prevEpoch", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "nextEpoch", - "type": "uint256" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - }, - { - "constant": true, - "inputs": [ - { - "internalType": "address", - "name": "nodeAddress", - "type": "address" - } - ], - "name": "getNodeDetails", - "outputs": [ - { - "internalType": "string", - "name": "declaredIp", - "type": "string" - }, - { - "internalType": "uint256", - "name": "position", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "pubKx", - "type": "uint256" - }, - { - "internalType": "uint256", - "name": "pubKy", - "type": "uint256" - }, - { - "internalType": "string", - "name": "tmP2PListenAddress", - "type": "string" - }, - { - "internalType": "string", - "name": "p2pListenAddress", - "type": "string" - } - ], - "payable": false, - "stateMutability": "view", - "type": "function" - } - ] -} diff --git a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/contract/abi.swift b/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/contract/abi.swift deleted file mode 100644 index 3f5b555b..00000000 --- a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/contract/abi.swift +++ /dev/null @@ -1,10 +0,0 @@ -// -// contractABIString.swift -// -// -// Created by Shubham on 13/3/20. -// - -import Foundation - -var contractABIString = "[{\"constant\":true,\"inputs\":[],\"name\":\"currentEpoch\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"epoch\",\"type\":\"uint256\"}],\"name\":\"getEpochInfo\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"id\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"n\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"k\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"t\",\"type\":\"uint256\"},{\"internalType\":\"address[]\",\"name\":\"nodeList\",\"type\":\"address[]\"},{\"internalType\":\"uint256\",\"name\":\"prevEpoch\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"nextEpoch\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"address\",\"name\":\"nodeAddress\",\"type\":\"address\"}],\"name\":\"getNodeDetails\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"declaredIp\",\"type\":\"string\"},{\"internalType\":\"uint256\",\"name\":\"position\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"pubKx\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"pubKy\",\"type\":\"uint256\"},{\"internalType\":\"string\",\"name\":\"tmP2PListenAddress\",\"type\":\"string\"},{\"internalType\":\"string\",\"name\":\"p2pListenAddress\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" diff --git a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/epochInfo.swift b/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/epochInfo.swift deleted file mode 100644 index c3275fec..00000000 --- a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/epochInfo.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// epochInfo.swift -// -// -// Created by Shubham on 13/3/20. -// - -import Foundation - -public class EpochInfo { - private var id:String = ""; - private var n:String = ""; - private var k:String = ""; - private var t:String = ""; - private var nodeList: Array = []; - private var prevEpoch:String = ""; - private var nextEpoch:String = ""; - - init(_id : String, _n : String, _k : String, _t : String, _nodeList: Array, _prevEpoch : String, _nextEpoch : String) { - self.id = _id; - self.n = _n; - self.k = _k; - self.t = _t; - self.nodeList = _nodeList; - self.prevEpoch = _prevEpoch; - self.nextEpoch = _nextEpoch; - } - - public func getId() -> String { - return self.id; - } - - public func getK() -> String{ - return self.k; - } - - public func getN() -> String{ - return self.n; - } - - public func getNextEpoch() -> String{ - return self.nextEpoch; - } - - public func getPrevEpoch() -> String{ - return self.prevEpoch; - } - - public func getT() -> String{ - return self.t; - } - - public func getNodeList() -> Array { - return self.nodeList; - } -} diff --git a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/ethereumNetwork.swift b/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/ethereumNetwork.swift deleted file mode 100644 index 7f92f6ca..00000000 --- a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/ethereumNetwork.swift +++ /dev/null @@ -1,16 +0,0 @@ -// -// ethereumNetwork.swift -// -// -// Created by Shubham on 13/3/20. -// - -import Foundation - -public enum EthereumNetwork : String{ - case MAINNET = "mainnet" - case RINKEBY = "rinkeby" - case ROPSTEN = "ropsten" - case KOVAN = "kovan" - case GOERLI = "goerli" -} diff --git a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/extensions/String.swift b/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/extensions/String.swift deleted file mode 100644 index 7225391f..00000000 --- a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/extensions/String.swift +++ /dev/null @@ -1,13 +0,0 @@ -// -// String.swift -// -// -// Created by Shubham on 18/3/20. -// -import Foundation - -// Used in error thrown from guard let -extension String: LocalizedError { - public var errorDescription: String? { return self } -} - diff --git a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/fetchNodeDetails+promise.swift b/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/fetchNodeDetails+promise.swift deleted file mode 100644 index 83aec414..00000000 --- a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/fetchNodeDetails+promise.swift +++ /dev/null @@ -1,174 +0,0 @@ -// -// File.swift -// -// -// Created by Shubham on 13/3/20. -// - -import Foundation -import web3swift -import BigInt -import PromiseKit - -extension FetchNodeDetails { - - public func getCurrentEpochPromise() throws -> Promise{ - let contractMethod = "currentEpoch" // Contract method you want to call - let parameters: [AnyObject] = [] // Parameters for contract method - let extraData: Data = Data() // Extra data for contract method - var options = TransactionOptions.defaultOptions - options.from = walletAddress - options.gasPrice = .automatic - options.gasLimit = .automatic - let tx = self.contract.read( - contractMethod, - parameters: parameters, - extraData: extraData, - transactionOptions: options)! - - let txPromise = tx.callPromise() - let (tempPromise, seal) = Promise.pending() - - txPromise.done{ data in - let epoch = data.first?.value - guard let newEpoch = epoch else { throw "some error"} - seal.fulfill(Int("\(newEpoch)")!) - }.catch{ err in - seal.reject(err) - } - - return tempPromise - } - - public func getEpochInfoPromise(epoch : Int) throws -> Promise{ - let contractMethod = "getEpochInfo" - let parameters: [AnyObject] = [epoch as AnyObject] // Parameters for contract method - let extraData: Data = Data() // Extra data for contract method - var options = TransactionOptions.defaultOptions - options.from = walletAddress - options.gasPrice = .automatic - options.gasLimit = .automatic - - let tx = self.contract.read( - contractMethod, - parameters: parameters, - extraData: extraData, - transactionOptions: options)! - - let returnPromise = Promise{ seal in - let txPromise = tx.callPromise() - txPromise.done{ response in - var nodeList = response["nodeList"] as! Array //Unable to convert to Array - nodeList = nodeList.map{ (el) -> String in - let address = el as! EthereumAddress - return String(describing: address.address) - } - //print(nodeList) - - guard let id = response["id"] else { throw "Casting for id from Any? -> Any failed"} - guard let n = response["n"] else { throw "Casting for n from Any? -> Any failed"} - guard let k = response["k"] else { throw "Casting for k from Any? -> Any failed"} - guard let t = response["t"] else { throw "Casting for t from Any? -> Any failed"} - guard let prevEpoch = response["prevEpoch"] else { throw "Casting for prevEpoch from Any? -> Any failed"} - guard let nextEpoch = response["nextEpoch"] else { throw "Casting for nextEpoch from Any? -> Any failed"} - - let object = EpochInfo(_id: "\(id)", _n: "\(n)", _k: "\(k)", _t: "\(t)", _nodeList: nodeList as! Array, _prevEpoch: "\(prevEpoch)", _nextEpoch: "\(nextEpoch)") - //print() - seal.fulfill(object) - - }.catch{error in - seal.reject(error) - } - - } - return returnPromise - } - - public func getNodeEndpointPromise(nodeEthAddress: String) -> Promise { - let contractMethod = "getNodeDetails" - let parameters: [AnyObject] = [nodeEthAddress as AnyObject] // Parameters for contract method - let extraData: Data = Data() // Extra data for contract method - var options = TransactionOptions.defaultOptions - options.from = walletAddress - options.gasPrice = .automatic - options.gasLimit = .automatic - //print(extraData) - - let tx = self.contract.read( - contractMethod, - parameters: parameters, - extraData: extraData, - transactionOptions: options)! - - let returnPromise = Promise{ seal in - let txPromise = tx.callPromise() - txPromise.done{ response in - // Unwraping Any? -> Any - guard let declaredIp = response["declaredIp"] else { throw "Casting for declaredIp from Any? to Any failed" } - guard let position = response["position"] else { throw "Casting for position from Any? to Any failed" } - guard var pubKx = response["pubKx"] else { throw "Casting for pubKx from Any? to Any failed" } - guard var pubKy = response["pubKy"] else { throw "Casting for pubKy from Any? to Any failed" } - guard let tmP2PListenAddress = response["tmP2PListenAddress"] else { throw "Casting for tmP2PListenAddress from Any? to Any failed" } - guard let p2pListenAddress = response["p2pListenAddress"] else { throw "Casting for p2pListenAddress from Any? to Any failed" } - - //Change to hex - pubKx = String(BigInt("\(pubKx)", radix:10)!, radix:16, uppercase: true) - pubKy = String(BigInt("\(pubKy)", radix:10)!, radix:16, uppercase: true) - - let object = NodeInfo(_declaredIp: "\(declaredIp)", _position: "\(position)", _pubKx: "\(pubKx)", _pubKy: "\(pubKy)", _tmP2PListenAddress: "\(tmP2PListenAddress)", _p2pListenAddress: "\(p2pListenAddress)") - seal.fulfill(object) - }.catch{err in seal.reject(err)} - } - return returnPromise - } - - public func getNodeDetailsPromise() throws -> Promise{ - var currentEpoch: Int = -1; - var torusIndexes:[BigInt] = Array() - - let returnPromise = Promise { seal in - let currentEpochPromise = try self.getCurrentEpochPromise(); - currentEpochPromise.then{ response -> Promise in - currentEpoch = response - return try self.getEpochInfoPromise(epoch: response) - }.then{epochInfo -> Guarantee<[Result]> in - let nodelist = epochInfo.getNodeList(); - var getNodeInfoPromisesArray:[Promise] = Array() - for i in 0.. = Array() - var updatedNodePub:Array = Array() - - for result in results{ - switch result { - case .fulfilled(let value): - let endPointElement:NodeInfo = value; - let endpoint = "https://" + endPointElement.getDeclaredIp().split(separator: ":")[0] + "/jrpc"; - updatedEndpoints.append(endpoint) - - let hexPubX = endPointElement.getPubKx() - let hexPubY = endPointElement.getPubKy() - updatedNodePub.append(TorusNodePub(_X: hexPubX, _Y: hexPubY)) - default: - seal.reject("error with node info") - } - - } - - self.nodeDetails = NodeDetails(_currentEpoch: "\(currentEpoch)", _nodeListAddress: self.proxyAddress.address, _torusNodeEndpoints: updatedEndpoints, _torusIndexes: torusIndexes, _torusNodePub: updatedNodePub, _updated: true) - - seal.fulfill(self.nodeDetails!) - }.catch { error in - //print(error) - seal.reject("get epoch info failed") - } - } - - return returnPromise - } - -} diff --git a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/fetchNodeDetails.swift b/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/fetchNodeDetails.swift deleted file mode 100644 index 3d74eb4f..00000000 --- a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/fetchNodeDetails.swift +++ /dev/null @@ -1,176 +0,0 @@ -// -// File.swift -// -// -// Created by Shubham on 13/3/20. -// - -import Foundation -import web3swift -import BigInt -import BestLogger - -public final class FetchNodeDetails { - - var web3 : web3 - var network : EthereumNetwork = EthereumNetwork.ROPSTEN; - var proxyAddress : EthereumAddress - var walletAddress : EthereumAddress = EthereumAddress("0x5F7A02a42bF621da3211aCE9c120a47AA5229fBA")! - let yourContractABI: String = contractABIString - var contract : web3.web3contract - var nodeDetails : NodeDetails? - let logger: BestLogger? - - public init(proxyAddress: String, network: EthereumNetwork, logLevel: BestLogger.Level = .none){ - - // mainnet proxy contract address - 0x638646503746d5456209e33a2ff5e3226d698bea - // testnet proxt contract address - 0x4023d2a0D330bF11426B12C6144Cfb96B7fa6183 - self.proxyAddress = EthereumAddress(proxyAddress)! - self.network = network - - if(network == EthereumNetwork.MAINNET){ - self.web3 = Web3.InfuraMainnetWeb3(accessToken: "b8cdb0e4cff24599a286bf8e87ff1c96") - self.contract = web3.contract(yourContractABI, at: self.proxyAddress, abiVersion: 2)! - }else{ - self.web3 = Web3.InfuraRopstenWeb3(accessToken: "b8cdb0e4cff24599a286bf8e87ff1c96") - self.contract = web3.contract(yourContractABI, at: self.proxyAddress, abiVersion: 2)! - } - - self.logger = BestLogger(label: "fetch node details", level: logLevel) - } - - public func getCurrentEpoch() -> Int{ - let contractMethod = "currentEpoch" // Contract method you want to call - let parameters: [AnyObject] = [] // Parameters for contract method - let extraData: Data = Data() // Extra data for contract method - var options = TransactionOptions.defaultOptions - options.from = walletAddress - options.gasPrice = .automatic - options.gasLimit = .automatic - let tx = self.contract.read( - contractMethod, - parameters: parameters, - extraData: extraData, - transactionOptions: options)! - - let result:[String:Any] = try! tx.call() // Explicit Conversion from Any? -> Any -> String -> Int - let epoch = result.first?.value - - // Explicit Conversion from Any? -> Any -> String -> Int - guard let newEpoch = epoch else { return 0} - return Int("\(newEpoch)")! - } - - public func getEpochInfo(epoch : Int) throws -> EpochInfo{ - let contractMethod = "getEpochInfo" - let parameters: [AnyObject] = [epoch as AnyObject] // Parameters for contract method - let extraData: Data = Data() // Extra data for contract method - var options = TransactionOptions.defaultOptions - options.from = walletAddress - options.gasPrice = .automatic - options.gasLimit = .automatic - - let tx = self.contract.read( - contractMethod, - parameters: parameters, - extraData: extraData, - transactionOptions: options)! - - let result = try! tx.call() - //print(result.keys) - //print(result["prevEpoch"]) - - var nodeList = result["nodeList"] as! Array //Unable to convert to Array - nodeList = nodeList.map{ (el) -> String in - let address = el as! EthereumAddress - return String(describing: address.address) - } - //print(nodeList) - - guard let id = result["id"] else { throw "Casting for id from Any? -> Any failed"} - guard let n = result["n"] else { throw "Casting for n from Any? -> Any failed"} - guard let k = result["k"] else { throw "Casting for k from Any? -> Any failed"} - guard let t = result["t"] else { throw "Casting for t from Any? -> Any failed"} - guard let prevEpoch = result["prevEpoch"] else { throw "Casting for prevEpoch from Any? -> Any failed"} - guard let nextEpoch = result["nextEpoch"] else { throw "Casting for nextEpoch from Any? -> Any failed"} - - let object = EpochInfo(_id: "\(id)", _n: "\(n)", _k: "\(k)", _t: "\(t)", _nodeList: nodeList as! Array, _prevEpoch: "\(prevEpoch)", _nextEpoch: "\(nextEpoch)") - return object - } - - public func getNodeEndpoint(nodeEthAddress: String) throws -> NodeInfo { - let contractMethod = "getNodeDetails" - let parameters: [AnyObject] = [nodeEthAddress as AnyObject] // Parameters for contract method - let extraData: Data = Data() // Extra data for contract method - var options = TransactionOptions.defaultOptions - options.from = walletAddress - options.gasPrice = .automatic - options.gasLimit = .automatic - //print(extraData) - - let tx = self.contract.read( - contractMethod, - parameters: parameters, - extraData: extraData, - transactionOptions: options)! - //print(tx) - - let result = try! tx.call() - - // Unwraping Any? -> Any - guard let declaredIp = result["declaredIp"] else { throw "Casting for declaredIp from Any? to Any failed" } - guard let position = result["position"] else { throw "Casting for position from Any? to Any failed" } - guard var pubKx = result["pubKx"] else { throw "Casting for pubKx from Any? to Any failed" } - guard var pubKy = result["pubKy"] else { throw "Casting for pubKy from Any? to Any failed" } - guard let tmP2PListenAddress = result["tmP2PListenAddress"] else { throw "Casting for tmP2PListenAddress from Any? to Any failed" } - guard let p2pListenAddress = result["p2pListenAddress"] else { throw "Casting for p2pListenAddress from Any? to Any failed" } - - //Change to hex - pubKx = String(BigInt("\(pubKx)", radix:10)!, radix:16, uppercase: true) - pubKy = String(BigInt("\(pubKy)", radix:10)!, radix:16, uppercase: true) - - let object = NodeInfo(_declaredIp: "\(declaredIp)", _position: "\(position)", _pubKx: "\(pubKx)", _pubKy: "\(pubKy)", _tmP2PListenAddress: "\(tmP2PListenAddress)", _p2pListenAddress: "\(p2pListenAddress)") - return object - } - - public func getNodeDetails() -> NodeDetails{ - if((self.nodeDetails?.getUpdated()) != nil) { return self.nodeDetails! } - - let currentEpoch = self.getCurrentEpoch(); - let epochInfo = try! getEpochInfo(epoch: currentEpoch); - let nodelist = epochInfo.getNodeList(); - - var torusIndexes:[BigInt] = Array() - var nodeEndPoints:[NodeInfo] = Array() - - for i in 0.. = Array() - var updatedNodePub:Array = Array() - - for i in 0.. String{ -// return "https://api.infura.io/v3/b8cdb0e4cff24599a286bf8e87ff1c96/"; -// } -} diff --git a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/nodeDetails.swift b/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/nodeDetails.swift deleted file mode 100644 index b7133f6d..00000000 --- a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/nodeDetails.swift +++ /dev/null @@ -1,76 +0,0 @@ -// -// NodeDetails.swift -// -// -// Created by Shubham on 13/3/20. -// - -import Foundation -import BigInt - -public class NodeDetails { - private var currentEpoch : String?; - private var nodeListAddress : String?; - private var torusNodeEndpoints : Array?; - private var torusIndexes : Array?; - private var torusNodePub : Array?; - private var updated = false; - - // Not currently in use - public init(_currentEpoch : String, _nodeListAddress : String, _torusNodeEndpoints : Array, _torusIndexes : Array, _torusNodePub : Array, _updated : Bool) { - self.currentEpoch = _currentEpoch; - self.nodeListAddress = _nodeListAddress; - self.torusNodeEndpoints = _torusNodeEndpoints; - self.torusIndexes = _torusIndexes; - self.torusNodePub = _torusNodePub; - self.updated = _updated; - } - - public func getTorusIndexes() -> Array { - return self.torusIndexes!; - } - - public func setTorusIndexes(torusIndexes : Array){ - self.torusIndexes = torusIndexes; - } - - public func getUpdated() -> Bool { - return updated; - } - - public func setUpdated(updated : Bool){ - self.updated = updated; - } - - public func getCurrentEpoch() -> String{ - return currentEpoch!; - } - - public func setCurrentEpoch( currentEpoch : String) { - self.currentEpoch = currentEpoch; - } - - public func getNodeListAddress() -> String { - return nodeListAddress!; - } - - public func setNodeListAddress(nodeListAddress : String) { - self.nodeListAddress = nodeListAddress; - } - - public func getTorusNodeEndpoints() -> Array { - return torusNodeEndpoints!; - } - - public func setTorusNodeEndpoints(torusNodeEndpoints : Array) { - self.torusNodeEndpoints = torusNodeEndpoints; - } - - public func getTorusNodePub() -> Array { - return torusNodePub!; - } - - public func setTorusNodePub(torusNodePub : Array) { - self.torusNodePub = torusNodePub; - } -} diff --git a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/nodeInfo.swift b/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/nodeInfo.swift deleted file mode 100644 index 7032c693..00000000 --- a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/nodeInfo.swift +++ /dev/null @@ -1,50 +0,0 @@ -// -// nodeInfo.swift -// -// -// Created by Shubham on 13/3/20. -// - -import Foundation - -public class NodeInfo { - private var declaredIp: String; - private var position: String; - private var pubKx: String; - private var pubKy: String; - private var tmP2PListenAddress: String; - private var p2pListenAddress: String; - - public init(_declaredIp : String, _position : String, _pubKx : String, _pubKy : String, _tmP2PListenAddress : String, _p2pListenAddress : String) { - self.declaredIp = _declaredIp; - self.position = _position; - self.pubKx = _pubKx; - self.pubKy = _pubKy; - self.tmP2PListenAddress = _tmP2PListenAddress; - self.p2pListenAddress = _p2pListenAddress; - } - - public func getDeclaredIp() -> String { - return declaredIp; - } - - public func getP2pListenAddress() -> String { - return p2pListenAddress; - } - - public func getPosition() -> String { - return position; - } - - public func getPubKx() -> String { - return pubKx; - } - - public func getPubKy() -> String { - return pubKy; - } - - public func getTmP2PListenAddress() -> String { - return tmP2PListenAddress; - } -} diff --git a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/torusNodePub.swift b/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/torusNodePub.swift deleted file mode 100644 index b4727206..00000000 --- a/cocoapods/Pods/Torus-fetchNodeDetails/Sources/FetchNodeDetails/torusNodePub.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// TorusNodePub.swift -// -// -// Created by Shubham on 13/3/20. -// - -import Foundation - -public class TorusNodePub { - private let X : String; - private let Y : String; - - public init(_X : String, _Y : String) { - self.X = _X; - self.Y = _Y; - } - - public func getX() -> String { - return X; - } - - public func getY() -> String { - return Y; - } -} diff --git a/cocoapods/Pods/secp256k1.c/License.md b/cocoapods/Pods/secp256k1.c/License.md deleted file mode 100644 index 4522a599..00000000 --- a/cocoapods/Pods/secp256k1.c/License.md +++ /dev/null @@ -1,19 +0,0 @@ -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/cocoapods/Pods/secp256k1.c/secp256k1/basic-config.h b/cocoapods/Pods/secp256k1.c/secp256k1/basic-config.h deleted file mode 100644 index fc588061..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/basic-config.h +++ /dev/null @@ -1,33 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/ecdh_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/ecdh_impl.h deleted file mode 100644 index c6820b8c..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/ecdh_impl.h +++ /dev/null @@ -1,54 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/ecdsa.h b/cocoapods/Pods/secp256k1.c/secp256k1/ecdsa.h deleted file mode 100644 index 80590c7c..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/ecdsa.h +++ /dev/null @@ -1,21 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/ecdsa_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/ecdsa_impl.h deleted file mode 100644 index 31a4c0d4..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/ecdsa_impl.h +++ /dev/null @@ -1,313 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/eckey.h b/cocoapods/Pods/secp256k1.c/secp256k1/eckey.h deleted file mode 100644 index b621f1e6..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/eckey.h +++ /dev/null @@ -1,25 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/eckey_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/eckey_impl.h deleted file mode 100644 index 1ab9a68e..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/eckey_impl.h +++ /dev/null @@ -1,100 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/ecmult.h b/cocoapods/Pods/secp256k1.c/secp256k1/ecmult.h deleted file mode 100644 index ea1cd8a2..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/ecmult.h +++ /dev/null @@ -1,47 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_const.h b/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_const.h deleted file mode 100644 index d4804b8b..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_const.h +++ /dev/null @@ -1,17 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_const_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_const_impl.h deleted file mode 100644 index f4c36a1f..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_const_impl.h +++ /dev/null @@ -1,257 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_gen.h b/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_gen.h deleted file mode 100644 index 7564b701..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_gen.h +++ /dev/null @@ -1,43 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_gen_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_gen_impl.h deleted file mode 100644 index f99be8c9..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_gen_impl.h +++ /dev/null @@ -1,210 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_impl.h deleted file mode 100644 index feab1b74..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/ecmult_impl.h +++ /dev/null @@ -1,1027 +0,0 @@ -/***************************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/field.h b/cocoapods/Pods/secp256k1.c/secp256k1/field.h deleted file mode 100644 index ce3aa462..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/field.h +++ /dev/null @@ -1,130 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/field_10x26.h b/cocoapods/Pods/secp256k1.c/secp256k1/field_10x26.h deleted file mode 100644 index 727c5267..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/field_10x26.h +++ /dev/null @@ -1,48 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/field_10x26_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/field_10x26_impl.h deleted file mode 100644 index 06be299c..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/field_10x26_impl.h +++ /dev/null @@ -1,1161 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/field_5x52.h b/cocoapods/Pods/secp256k1.c/secp256k1/field_5x52.h deleted file mode 100644 index bccd8feb..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/field_5x52.h +++ /dev/null @@ -1,47 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/field_5x52_asm_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/field_5x52_asm_impl.h deleted file mode 100644 index 1fc3171f..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/field_5x52_asm_impl.h +++ /dev/null @@ -1,502 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/field_5x52_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/field_5x52_impl.h deleted file mode 100644 index 004dd8bd..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/field_5x52_impl.h +++ /dev/null @@ -1,494 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/field_5x52_int128_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/field_5x52_int128_impl.h deleted file mode 100644 index 95a0d179..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/field_5x52_int128_impl.h +++ /dev/null @@ -1,277 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/field_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/field_impl.h deleted file mode 100644 index 685e74b7..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/field_impl.h +++ /dev/null @@ -1,313 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/group.h b/cocoapods/Pods/secp256k1.c/secp256k1/group.h deleted file mode 100644 index 3947ea2d..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/group.h +++ /dev/null @@ -1,147 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/group_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/group_impl.h deleted file mode 100644 index b1ace87b..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/group_impl.h +++ /dev/null @@ -1,706 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/hash.h b/cocoapods/Pods/secp256k1.c/secp256k1/hash.h deleted file mode 100644 index de26e4b8..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/hash.h +++ /dev/null @@ -1,41 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/hash_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/hash_impl.h deleted file mode 100644 index 5e015a51..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/hash_impl.h +++ /dev/null @@ -1,282 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/include/secp256k1.h b/cocoapods/Pods/secp256k1.c/secp256k1/include/secp256k1.h deleted file mode 100644 index ea2bc015..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/include/secp256k1.h +++ /dev/null @@ -1,767 +0,0 @@ -#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/cocoapods/Pods/secp256k1.c/secp256k1/num.h b/cocoapods/Pods/secp256k1.c/secp256k1/num.h deleted file mode 100644 index 7aadf7c6..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/num.h +++ /dev/null @@ -1,72 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/num_gmp.h b/cocoapods/Pods/secp256k1.c/secp256k1/num_gmp.h deleted file mode 100644 index 3619844b..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/num_gmp.h +++ /dev/null @@ -1,20 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/num_gmp_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/num_gmp_impl.h deleted file mode 100644 index 0ae2a8ba..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/num_gmp_impl.h +++ /dev/null @@ -1,288 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/num_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/num_impl.h deleted file mode 100644 index 59dd6f7a..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/num_impl.h +++ /dev/null @@ -1,22 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/recovery_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/recovery_impl.h deleted file mode 100755 index eb705193..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/recovery_impl.h +++ /dev/null @@ -1,193 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/scalar.h b/cocoapods/Pods/secp256k1.c/secp256k1/scalar.h deleted file mode 100644 index c909a43f..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/scalar.h +++ /dev/null @@ -1,104 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/scalar_4x64.h b/cocoapods/Pods/secp256k1.c/secp256k1/scalar_4x64.h deleted file mode 100644 index 19c7495d..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/scalar_4x64.h +++ /dev/null @@ -1,19 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/scalar_4x64_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/scalar_4x64_impl.h deleted file mode 100644 index 685bc99e..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/scalar_4x64_impl.h +++ /dev/null @@ -1,949 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/scalar_8x32.h b/cocoapods/Pods/secp256k1.c/secp256k1/scalar_8x32.h deleted file mode 100644 index 2c9a348e..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/scalar_8x32.h +++ /dev/null @@ -1,19 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/scalar_8x32_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/scalar_8x32_impl.h deleted file mode 100644 index b2c0581c..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/scalar_8x32_impl.h +++ /dev/null @@ -1,721 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/scalar_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/scalar_impl.h deleted file mode 100644 index 732d7c85..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/scalar_impl.h +++ /dev/null @@ -1,331 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/scalar_low.h b/cocoapods/Pods/secp256k1.c/secp256k1/scalar_low.h deleted file mode 100644 index 5836febc..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/scalar_low.h +++ /dev/null @@ -1,15 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/scalar_low_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/scalar_low_impl.h deleted file mode 100644 index c80e70c5..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/scalar_low_impl.h +++ /dev/null @@ -1,114 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/scratch.h b/cocoapods/Pods/secp256k1.c/secp256k1/scratch.h deleted file mode 100644 index fef377af..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/scratch.h +++ /dev/null @@ -1,39 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/scratch_impl.h b/cocoapods/Pods/secp256k1.c/secp256k1/scratch_impl.h deleted file mode 100644 index abed713b..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/scratch_impl.h +++ /dev/null @@ -1,86 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/secp256k1-config.h b/cocoapods/Pods/secp256k1.c/secp256k1/secp256k1-config.h deleted file mode 100644 index e22848b5..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/secp256k1-config.h +++ /dev/null @@ -1,169 +0,0 @@ -/* 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/cocoapods/Pods/secp256k1.c/secp256k1/secp256k1.c b/cocoapods/Pods/secp256k1.c/secp256k1/secp256k1.c deleted file mode 100644 index 25fd5019..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/secp256k1.c +++ /dev/null @@ -1,597 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/secp256k1.c/secp256k1/secp256k1_ec_mult_static_context.h b/cocoapods/Pods/secp256k1.c/secp256k1/secp256k1_ec_mult_static_context.h deleted file mode 100644 index 61d93734..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/secp256k1_ec_mult_static_context.h +++ /dev/null @@ -1,1160 +0,0 @@ -#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/cocoapods/Pods/secp256k1.c/secp256k1/secp256k1_main.h b/cocoapods/Pods/secp256k1.c/secp256k1/secp256k1_main.h deleted file mode 100644 index ff54afff..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/secp256k1_main.h +++ /dev/null @@ -1,5 +0,0 @@ -//! Project version number for secp256k1. -FOUNDATION_EXPORT double secp256k1VersionNumber; - -//! Project version string for secp256k1. -FOUNDATION_EXPORT const unsigned char secp256k1VersionString[]; diff --git a/cocoapods/Pods/secp256k1.c/secp256k1/util.h b/cocoapods/Pods/secp256k1.c/secp256k1/util.h deleted file mode 100644 index de2a002b..00000000 --- a/cocoapods/Pods/secp256k1.c/secp256k1/util.h +++ /dev/null @@ -1,119 +0,0 @@ -/********************************************************************** - * 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/cocoapods/Pods/web3swift/LICENSE.md b/cocoapods/Pods/web3swift/LICENSE.md deleted file mode 100755 index ed25277c..00000000 --- a/cocoapods/Pods/web3swift/LICENSE.md +++ /dev/null @@ -1,203 +0,0 @@ -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/cocoapods/Pods/web3swift/README.md b/cocoapods/Pods/web3swift/README.md deleted file mode 100755 index 7d5f3090..00000000 --- a/cocoapods/Pods/web3swift/README.md +++ /dev/null @@ -1,329 +0,0 @@ -# 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/cocoapods/Pods/web3swift/Sources/web3swift/Browser/Bridge.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Browser/Bridge.swift deleted file mode 100644 index b31db12b..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Browser/Bridge.swift +++ /dev/null @@ -1,250 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Browser/BrowserViewController.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Browser/BrowserViewController.swift deleted file mode 100644 index 90ea08d1..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Browser/BrowserViewController.swift +++ /dev/null @@ -1,128 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Browser/browser.js b/cocoapods/Pods/web3swift/Sources/web3swift/Browser/browser.js deleted file mode 100644 index 6f7d8ea2..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Browser/browser.js +++ /dev/null @@ -1,68351 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Browser/browser.min.js b/cocoapods/Pods/web3swift/Sources/web3swift/Browser/browser.min.js deleted file mode 100644 index f838d4a4..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Browser/browser.min.js +++ /dev/null @@ -1,2 +0,0 @@ -!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/cocoapods/Pods/web3swift/Sources/web3swift/Contract/ComparisonExtensions.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Contract/ComparisonExtensions.swift deleted file mode 100755 index 33f525ff..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Contract/ComparisonExtensions.swift +++ /dev/null @@ -1,95 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Contract/ContractProtocol.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Contract/ContractProtocol.swift deleted file mode 100755 index 60a31251..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Contract/ContractProtocol.swift +++ /dev/null @@ -1,109 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Contract/EthereumContract.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Contract/EthereumContract.swift deleted file mode 100755 index 203c5151..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Contract/EthereumContract.swift +++ /dev/null @@ -1,297 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift deleted file mode 100755 index d590a87d..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Contract/EthereumFilterEncodingExtensions.swift +++ /dev/null @@ -1,44 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Contract/EventFiltering.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Contract/EventFiltering.swift deleted file mode 100755 index b170285c..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Contract/EventFiltering.swift +++ /dev/null @@ -1,170 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Array+Extension.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Array+Extension.swift deleted file mode 100755 index 3fc7e80f..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Array+Extension.swift +++ /dev/null @@ -1,16 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Base58.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Base58.swift deleted file mode 100755 index 397b389c..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Base58.swift +++ /dev/null @@ -1,170 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Data+Extension.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Data+Extension.swift deleted file mode 100755 index fb2d4aeb..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Data+Extension.swift +++ /dev/null @@ -1,142 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Decodable+Extensions.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Decodable+Extensions.swift deleted file mode 100644 index 59f82fb0..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Decodable+Extensions.swift +++ /dev/null @@ -1,146 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Dictionary+Extension.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Dictionary+Extension.swift deleted file mode 100755 index ee1a6813..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Dictionary+Extension.swift +++ /dev/null @@ -1,18 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Encodable+Extensions.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Encodable+Extensions.swift deleted file mode 100644 index 84bad03e..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/Encodable+Extensions.swift +++ /dev/null @@ -1,130 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/NSRegularExpressionExtension.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/NSRegularExpressionExtension.swift deleted file mode 100755 index 1b511a62..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/NSRegularExpressionExtension.swift +++ /dev/null @@ -1,83 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift deleted file mode 100755 index df4cfb3c..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/RIPEMD160+StackOveflow.swift +++ /dev/null @@ -1,534 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/SECP256k1.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/SECP256k1.swift deleted file mode 100755 index 800a4476..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Convenience/SECP256k1.swift +++ /dev/null @@ -1,385 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABI.swift b/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABI.swift deleted file mode 100755 index d139fd3b..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABI.swift +++ /dev/null @@ -1,28 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIDecoding.swift b/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIDecoding.swift deleted file mode 100755 index eae5c332..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIDecoding.swift +++ /dev/null @@ -1,286 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIElements.swift b/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIElements.swift deleted file mode 100755 index 7f76012f..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIElements.swift +++ /dev/null @@ -1,286 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIEncoding.swift b/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIEncoding.swift deleted file mode 100755 index 16c358f9..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIEncoding.swift +++ /dev/null @@ -1,388 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParameterTypes.swift b/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParameterTypes.swift deleted file mode 100755 index 0bbd8038..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParameterTypes.swift +++ /dev/null @@ -1,250 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParsing.swift b/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParsing.swift deleted file mode 100755 index bc4610d0..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABIParsing.swift +++ /dev/null @@ -1,186 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABITypeParser.swift b/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABITypeParser.swift deleted file mode 100755 index 27471247..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/EthereumABI/ABITypeParser.swift +++ /dev/null @@ -1,110 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/EthereumAddress/EthereumAddress.swift b/cocoapods/Pods/web3swift/Sources/web3swift/EthereumAddress/EthereumAddress.swift deleted file mode 100755 index da47d982..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/EthereumAddress/EthereumAddress.swift +++ /dev/null @@ -1,136 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/EthereumAddress/Extensions.swift b/cocoapods/Pods/web3swift/Sources/web3swift/EthereumAddress/Extensions.swift deleted file mode 100755 index f82edee1..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/EthereumAddress/Extensions.swift +++ /dev/null @@ -1,60 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift b/cocoapods/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift deleted file mode 100755 index ed1576a3..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift +++ /dev/null @@ -1,209 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+Wallet.swift b/cocoapods/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+Wallet.swift deleted file mode 100755 index c7b0e8c4..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/HookedFunctions/Web3+Wallet.swift +++ /dev/null @@ -1,73 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/AbstractKeystore.swift b/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/AbstractKeystore.swift deleted file mode 100755 index d8a19f97..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/AbstractKeystore.swift +++ /dev/null @@ -1,23 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32HDNode.swift b/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32HDNode.swift deleted file mode 100755 index 267b7f02..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32HDNode.swift +++ /dev/null @@ -1,302 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32Keystore.swift b/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32Keystore.swift deleted file mode 100755 index 79a3c378..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32Keystore.swift +++ /dev/null @@ -1,279 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32KeystoreJSONStructure.swift b/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32KeystoreJSONStructure.swift deleted file mode 100755 index 97a25334..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP32KeystoreJSONStructure.swift +++ /dev/null @@ -1,26 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39+WordLists.swift b/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39+WordLists.swift deleted file mode 100755 index 79b68efc..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39+WordLists.swift +++ /dev/null @@ -1,35 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39.swift b/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39.swift deleted file mode 100755 index 5ce5238a..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/BIP39.swift +++ /dev/null @@ -1,164 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift b/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift deleted file mode 100755 index db03f98b..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/EthereumKeystoreV3.swift +++ /dev/null @@ -1,193 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/IBAN.swift b/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/IBAN.swift deleted file mode 100755 index 500f9560..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/IBAN.swift +++ /dev/null @@ -1,138 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/KeystoreV3JSONStructure.swift b/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/KeystoreV3JSONStructure.swift deleted file mode 100755 index 8ab80e57..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/KeystoreV3JSONStructure.swift +++ /dev/null @@ -1,46 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/PlainKeystore.swift b/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/PlainKeystore.swift deleted file mode 100755 index 25ee86ff..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/KeystoreManager/PlainKeystore.swift +++ /dev/null @@ -1,36 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Batching.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Batching.swift deleted file mode 100755 index 0d218458..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Batching.swift +++ /dev/null @@ -1,139 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+HttpProvider.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+HttpProvider.swift deleted file mode 100755 index 94b1b5a5..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+HttpProvider.swift +++ /dev/null @@ -1,109 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Contract+GetIndexedEvents.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Contract+GetIndexedEvents.swift deleted file mode 100755 index 66391e1f..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Contract+GetIndexedEvents.swift +++ /dev/null @@ -1,11 +0,0 @@ -// web3swift -// -// Created by Alex Vlasov. -// Copyright © 2018 Alex Vlasov. All rights reserved. -// - - -// placeholder - - - diff --git a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift deleted file mode 100755 index ee206b34..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+Call.swift +++ /dev/null @@ -1,36 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+EstimateGas.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+EstimateGas.swift deleted file mode 100755 index 7c2a68bf..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+EstimateGas.swift +++ /dev/null @@ -1,38 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift deleted file mode 100755 index f8ccd0cd..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetAccounts.swift +++ /dev/null @@ -1,39 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBalance.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBalance.swift deleted file mode 100755 index 5bdb6030..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBalance.swift +++ /dev/null @@ -1,31 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByHash.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByHash.swift deleted file mode 100755 index 90710d4f..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByHash.swift +++ /dev/null @@ -1,31 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByNumber.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByNumber.swift deleted file mode 100755 index ac92584e..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockByNumber.swift +++ /dev/null @@ -1,36 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockNumber.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockNumber.swift deleted file mode 100755 index e8bc2676..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetBlockNumber.swift +++ /dev/null @@ -1,26 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift deleted file mode 100755 index fbda2ace..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetGasPrice.swift +++ /dev/null @@ -1,26 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionCount.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionCount.swift deleted file mode 100755 index cbd1f470..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionCount.swift +++ /dev/null @@ -1,32 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionDetails.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionDetails.swift deleted file mode 100755 index 522f0430..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionDetails.swift +++ /dev/null @@ -1,31 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionReceipt.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionReceipt.swift deleted file mode 100755 index 517a007e..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+GetTransactionReceipt.swift +++ /dev/null @@ -1,31 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendRawTransaction.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendRawTransaction.swift deleted file mode 100755 index 7aa3b83a..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendRawTransaction.swift +++ /dev/null @@ -1,51 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendTransaction.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendTransaction.swift deleted file mode 100755 index 7fe53fd9..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Eth+SendTransaction.swift +++ /dev/null @@ -1,79 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+CreateAccount.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+CreateAccount.swift deleted file mode 100755 index e5e83d55..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+CreateAccount.swift +++ /dev/null @@ -1,37 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+Sign.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+Sign.swift deleted file mode 100755 index bf71b10c..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+Sign.swift +++ /dev/null @@ -1,44 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+UnlockAccount.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+UnlockAccount.swift deleted file mode 100755 index 62512f6d..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+Personal+UnlockAccount.swift +++ /dev/null @@ -1,43 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+TxPool.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+TxPool.swift deleted file mode 100755 index 996fae70..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Promises/Promise+Web3+TxPool.swift +++ /dev/null @@ -1,56 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/SwiftRLP/RLP.swift b/cocoapods/Pods/web3swift/Sources/web3swift/SwiftRLP/RLP.swift deleted file mode 100755 index e9f904ad..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/SwiftRLP/RLP.swift +++ /dev/null @@ -1,320 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift deleted file mode 100644 index 2daebddb..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift +++ /dev/null @@ -1,147 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift deleted file mode 100644 index 7e1c6b94..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift +++ /dev/null @@ -1,502 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift deleted file mode 100644 index 8db216c4..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift +++ /dev/null @@ -1,931 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift deleted file mode 100644 index 836dcdf6..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift +++ /dev/null @@ -1,664 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift deleted file mode 100644 index 7e8b9461..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift +++ /dev/null @@ -1,409 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift deleted file mode 100644 index 13ccdaf4..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift +++ /dev/null @@ -1,254 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift deleted file mode 100644 index e18bbead..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift +++ /dev/null @@ -1,267 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift deleted file mode 100644 index fffbe660..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift +++ /dev/null @@ -1,283 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift deleted file mode 100644 index 5abd3e95..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC165/Web3+ERC165.swift +++ /dev/null @@ -1,16 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift deleted file mode 100644 index f3000f57..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC20/Web3+ERC20.swift +++ /dev/null @@ -1,228 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift deleted file mode 100644 index 08dba2cd..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift +++ /dev/null @@ -1,280 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift deleted file mode 100644 index 94e9f571..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift +++ /dev/null @@ -1,332 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift deleted file mode 100644 index 775ff9c1..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift +++ /dev/null @@ -1,445 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift deleted file mode 100644 index 4e805e9a..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC820/Web3+ERC820.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift deleted file mode 100644 index ce98f9b7..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ERC888/Web3+ERC888.swift +++ /dev/null @@ -1,138 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+ST20.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+ST20.swift deleted file mode 100644 index cc6b7734..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+ST20.swift +++ /dev/null @@ -1,314 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift deleted file mode 100644 index 2412616d..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Tokens/ST20/Web3+SecurityToken.swift +++ /dev/null @@ -1,473 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Transaction/BloomFilter.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Transaction/BloomFilter.swift deleted file mode 100755 index 4daded40..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Transaction/BloomFilter.swift +++ /dev/null @@ -1,110 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Transaction/EthereumTransaction.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Transaction/EthereumTransaction.swift deleted file mode 100755 index d799d3ab..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Transaction/EthereumTransaction.swift +++ /dev/null @@ -1,403 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Transaction/TransactionSigner.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Transaction/TransactionSigner.swift deleted file mode 100755 index 52ab27be..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Transaction/TransactionSigner.swift +++ /dev/null @@ -1,118 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP67Code.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP67Code.swift deleted file mode 100755 index 39ad909d..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP67Code.swift +++ /dev/null @@ -1,138 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP681.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP681.swift deleted file mode 100755 index d00e76ba..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Utils/EIP/EIP681.swift +++ /dev/null @@ -1,232 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENS.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENS.swift deleted file mode 100755 index ec8af0c2..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENS.swift +++ /dev/null @@ -1,286 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift deleted file mode 100644 index 4c1c8987..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSBaseRegistrar.swift +++ /dev/null @@ -1,82 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSRegistry.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSRegistry.swift deleted file mode 100644 index b89f0508..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSRegistry.swift +++ /dev/null @@ -1,110 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSResolver.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSResolver.swift deleted file mode 100755 index 67176af8..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSResolver.swift +++ /dev/null @@ -1,196 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift deleted file mode 100644 index b6440a0c..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift +++ /dev/null @@ -1,68 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift deleted file mode 100644 index 88c8a7f8..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift +++ /dev/null @@ -1,93 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/NameHash.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/NameHash.swift deleted file mode 100755 index 2a96a9ca..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/NameHash.swift +++ /dev/null @@ -1,52 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/PublicKey.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/PublicKey.swift deleted file mode 100644 index f7b000d4..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Utils/ENS/PublicKey.swift +++ /dev/null @@ -1,26 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Utils/Hooks/NonceMiddleware.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Utils/Hooks/NonceMiddleware.swift deleted file mode 100755 index 127f302f..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Utils/Hooks/NonceMiddleware.swift +++ /dev/null @@ -1,111 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Constants.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Constants.swift deleted file mode 100644 index e975b617..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Constants.swift +++ /dev/null @@ -1,15 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Contract.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Contract.swift deleted file mode 100755 index 93e49f3a..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Contract.swift +++ /dev/null @@ -1,116 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth+Websocket.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth+Websocket.swift deleted file mode 100644 index 46d76146..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth+Websocket.swift +++ /dev/null @@ -1,42 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth.swift deleted file mode 100755 index 134791c1..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Eth.swift +++ /dev/null @@ -1,358 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+EventParser.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+EventParser.swift deleted file mode 100755 index 2d22054f..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+EventParser.swift +++ /dev/null @@ -1,307 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Eventloop.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Eventloop.swift deleted file mode 100755 index d59a0e9e..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Eventloop.swift +++ /dev/null @@ -1,103 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+HttpProvider.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+HttpProvider.swift deleted file mode 100755 index 683f7d36..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+HttpProvider.swift +++ /dev/null @@ -1,57 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+InfuraProviders.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+InfuraProviders.swift deleted file mode 100755 index a3a26ace..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+InfuraProviders.swift +++ /dev/null @@ -1,275 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Instance.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Instance.swift deleted file mode 100755 index f87c354c..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Instance.swift +++ /dev/null @@ -1,229 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+JSONRPC.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+JSONRPC.swift deleted file mode 100755 index 283ecbaf..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+JSONRPC.swift +++ /dev/null @@ -1,278 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Methods.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Methods.swift deleted file mode 100755 index f3ab0f28..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Methods.swift +++ /dev/null @@ -1,90 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+MutatingTransaction.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+MutatingTransaction.swift deleted file mode 100755 index 75bfc87e..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+MutatingTransaction.swift +++ /dev/null @@ -1,170 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Options.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Options.swift deleted file mode 100755 index d9a9b7f5..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Options.swift +++ /dev/null @@ -1,246 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Personal.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Personal.swift deleted file mode 100755 index 73029fd1..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Personal.swift +++ /dev/null @@ -1,86 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Protocols.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Protocols.swift deleted file mode 100755 index 42745d8e..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Protocols.swift +++ /dev/null @@ -1,90 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+ReadingTransaction.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+ReadingTransaction.swift deleted file mode 100755 index 0effcba1..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+ReadingTransaction.swift +++ /dev/null @@ -1,109 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Structures.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Structures.swift deleted file mode 100755 index 32180fbc..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Structures.swift +++ /dev/null @@ -1,691 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+TxPool.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+TxPool.swift deleted file mode 100755 index ccf9efc5..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+TxPool.swift +++ /dev/null @@ -1,25 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Utils.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Utils.swift deleted file mode 100755 index 82ca74a7..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+Utils.swift +++ /dev/null @@ -1,6212 +0,0 @@ -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+WebsocketProvider.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+WebsocketProvider.swift deleted file mode 100644 index e25122ac..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3+WebsocketProvider.swift +++ /dev/null @@ -1,300 +0,0 @@ -// -// 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/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3.swift b/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3.swift deleted file mode 100755 index 91ab2d54..00000000 --- a/cocoapods/Pods/web3swift/Sources/web3swift/Web3/Web3.swift +++ /dev/null @@ -1,79 +0,0 @@ -// 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) - } - -}