From 3e2050d0f024be3ec758741f670da55c0ba6941f Mon Sep 17 00:00:00 2001 From: Francisco Gindre Date: Fri, 18 Oct 2019 17:09:13 -0300 Subject: [PATCH] Swiftlint (#5) * Swiftlint + tests * Added Swiftlint to README.md --- .swiftlint.yml | 45 +++++++++++++++++++ README.md | 2 + ZcashLightClientKit.xcodeproj/project.pbxproj | 18 ++++++++ .../DatabaseStorage/CompactBlockStorage.swift | 2 - .../Block/DatabaseStorage/SQLDatabase.swift | 15 +++---- .../Block/Downloader/BlockDownloader.swift | 4 -- .../CompactBlockProcessingOperation.swift | 2 +- .../Processor/CompactBlockProcessor.swift | 18 ++------ .../Block/Storage/BlockRepository.swift | 1 - .../Block/Storage/CompactBlockStoring.swift | 5 +-- .../Block/Storage/Storage.swift | 3 -- .../Providers/ResourceProvider.swift | 1 - .../Rust/ZcashRustBackend.swift | 32 +++++-------- .../Service/LightWalletGRPCService.swift | 15 +++---- .../Service/LightWalletService.swift | 5 +-- .../Service/Model/ZcashCompactBlock.swift | 4 -- .../Protocolbuffer+Extensions.swift | 4 +- ZcashLightClientKit/Wallet.swift | 45 +++++++++---------- .../BlockDownloaderTests.swift | 7 +-- .../BlockScanOperationTests.swift | 2 +- .../CompactBlockProcessorTests.swift | 5 --- .../CompactBlockStorageTests.swift | 2 - .../DownloadOperationTests.swift | 1 - .../LightWalletServiceTests.swift | 1 - .../ZcashLightClientKitTests.swift | 2 - .../ZcashRustBackendTests.swift | 1 - .../utils/FakeStorage.swift | 3 -- ZcashLightClientKitTests/utils/Stubs.swift | 3 +- .../utils/TestDbBuilder.swift | 5 +-- .../utils/Tests+Utils.swift | 4 -- zcash.swiftformat | 8 ++++ 31 files changed, 131 insertions(+), 134 deletions(-) create mode 100644 .swiftlint.yml create mode 100644 zcash.swiftformat diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 00000000..cc29a493 --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,45 @@ +whitelist_rules: + - closure_spacing + - colon + - empty_enum_arguments + - fatal_error_message + - force_cast + - force_try + - force_unwrapping + - implicitly_unwrapped_optional + - legacy_cggeometry_functions + - legacy_constant + - legacy_constructor + - legacy_nsgeometry_functions + - operator_usage_whitespace + - redundant_string_enum_value + - redundant_void_return + - return_arrow_whitespace + - trailing_newline + - type_name + - unused_closure_parameter + - unused_optional_binding + - vertical_whitespace + - void_return + - custom_rules + +excluded: + - Carthage + - Pods + - ZcashLightClientKit/Service/ProtoBuf/compact_formats.pb.swift + - ZcashLightClientKit/Service/ProtoBuf/service.grpc.swift + - ZcashLightClientKit/Service/ProtoBuf/service.pb.swift + - Example + - ZcashLightClientKitTests + +colon: + apply_to_dictionaries: false + +indentation: 2 + +custom_rules: + no_objcMembers: + name: "@objcMembers" + regex: "@objcMembers" + message: "Explicitly use @objc on each member you want to expose to Objective-C" + severity: error diff --git a/README.md b/README.md index 9feb656d..3ccc7f0d 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,8 @@ The ```LIGHTWALLETD_ADDRESS``` environment variable can also be added to your sh We advice setting this value as a secret variable on your CD/CI environment when possible +# Swiftlint +We don't like reinveing the wheel, so be gently borrowed swift lint rules from AirBnB which we find pretty cool and reasonable. ## Troubleshooting diff --git a/ZcashLightClientKit.xcodeproj/project.pbxproj b/ZcashLightClientKit.xcodeproj/project.pbxproj index 623a18ac..0f822d7b 100644 --- a/ZcashLightClientKit.xcodeproj/project.pbxproj +++ b/ZcashLightClientKit.xcodeproj/project.pbxproj @@ -401,6 +401,7 @@ buildPhases = ( 103AFE80228312A30074BC98 /* Headers */, 103AFE9F2283152F0074BC98 /* ShellScript */, + 0D3BA6B1235A420B00E0E0F4 /* ShellScript */, 103AFE81228312A30074BC98 /* Sources */, 103AFE82228312A30074BC98 /* Frameworks */, 103AFE83228312A30074BC98 /* Resources */, @@ -512,6 +513,23 @@ shellPath = /bin/sh; shellScript = "/usr/local/bin/carthage copy-frameworks\n"; }; + 0D3BA6B1235A420B00E0E0F4 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint lint --config .swiftlint.yml\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n"; + }; 0DC64E65232848F10053EFAC /* ShellScript */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; diff --git a/ZcashLightClientKit/Block/DatabaseStorage/CompactBlockStorage.swift b/ZcashLightClientKit/Block/DatabaseStorage/CompactBlockStorage.swift index 8f0a1049..f2773ef5 100644 --- a/ZcashLightClientKit/Block/DatabaseStorage/CompactBlockStorage.swift +++ b/ZcashLightClientKit/Block/DatabaseStorage/CompactBlockStorage.swift @@ -9,7 +9,6 @@ import Foundation import SQLite - struct CompactBlockStorage: CompactBlockDAO { var db: Connection @@ -120,5 +119,4 @@ extension CompactBlockStorage: CompactBlockStoring { } } - } diff --git a/ZcashLightClientKit/Block/DatabaseStorage/SQLDatabase.swift b/ZcashLightClientKit/Block/DatabaseStorage/SQLDatabase.swift index 76f529d2..63457e78 100644 --- a/ZcashLightClientKit/Block/DatabaseStorage/SQLDatabase.swift +++ b/ZcashLightClientKit/Block/DatabaseStorage/SQLDatabase.swift @@ -19,7 +19,6 @@ class SQLiteStorage: Storage { self.connection = connection } - func open(at path: String) throws { do { connection = try Connection(path) @@ -35,15 +34,13 @@ class SQLiteStorage: Storage { func closeDatabase() {} } - /** Set schema version */ // TODO: define a better way to do this -extension Connection { - public var userVersion: Int32 { - get { return Int32(try! scalar("PRAGMA user_version") as! Int64)} - set { try! run("PRAGMA user_version = \(newValue)")} - } -} - +//extension Connection { +// public var userVersion: Int32 { +// get { return Int32(try scalar("PRAGMA user_version") as Int64)} +// set { try! run("PRAGMA user_version = \(newValue)")} +// } +//} diff --git a/ZcashLightClientKit/Block/Downloader/BlockDownloader.swift b/ZcashLightClientKit/Block/Downloader/BlockDownloader.swift index 7768866b..3bd81a0c 100644 --- a/ZcashLightClientKit/Block/Downloader/BlockDownloader.swift +++ b/ZcashLightClientKit/Block/Downloader/BlockDownloader.swift @@ -57,7 +57,6 @@ class CompactBlockDownloader { extension CompactBlockDownloader: CompactBlockDownloading { - /** Downloads and stores the given block range. Non-Blocking @@ -89,7 +88,6 @@ extension CompactBlockDownloader: CompactBlockDownloading { try storage.write(blocks: blocks) } - func rewind(to height: BlockHeight, completion: @escaping (Error?) -> Void){ storage.rewind(to: height) { (e) in @@ -121,6 +119,4 @@ extension CompactBlockDownloader: CompactBlockDownloading { try self.storage.latestHeight() } - } - diff --git a/ZcashLightClientKit/Block/Processor/CompactBlockProcessingOperation.swift b/ZcashLightClientKit/Block/Processor/CompactBlockProcessingOperation.swift index e13d94ed..5f493962 100644 --- a/ZcashLightClientKit/Block/Processor/CompactBlockProcessingOperation.swift +++ b/ZcashLightClientKit/Block/Processor/CompactBlockProcessingOperation.swift @@ -18,7 +18,7 @@ class CompactBlockScanningOperation: ZcashOperation { private var cacheDb: URL private var dataDb: URL - init(rustWelding: ZcashRustBackendWelding.Type, cacheDb: URL, dataDb:URL) { + init(rustWelding: ZcashRustBackendWelding.Type, cacheDb: URL, dataDb: URL) { rustBackend = rustWelding self.cacheDb = cacheDb self.dataDb = dataDb diff --git a/ZcashLightClientKit/Block/Processor/CompactBlockProcessor.swift b/ZcashLightClientKit/Block/Processor/CompactBlockProcessor.swift index 0b10f1a9..1c86efaa 100644 --- a/ZcashLightClientKit/Block/Processor/CompactBlockProcessor.swift +++ b/ZcashLightClientKit/Block/Processor/CompactBlockProcessor.swift @@ -8,7 +8,6 @@ import Foundation - enum CompactBlockProcessorError: Error { case invalidConfiguration case missingDbPath(path: String) @@ -16,16 +15,14 @@ enum CompactBlockProcessorError: Error { extension Notification.Name { static let blockProcessorUpdated = Notification.Name(rawValue: "CompactBlockProcessorUpdated") - static let blockProcessorStarted = Notification.Name(rawValue:"CompactBlockProcessorStarted") - static let blockProcessorStopped = Notification.Name(rawValue:"CompactBlockProcessorStopped") - static let blockProcessorFinished = Notification.Name(rawValue:"CompactBlockProcessorFinished") - static let blockProcessorFailed = Notification.Name(rawValue:"CompactBlockProcessorFinished") + static let blockProcessorStarted = Notification.Name(rawValue: "CompactBlockProcessorStarted") + static let blockProcessorStopped = Notification.Name(rawValue: "CompactBlockProcessorStopped") + static let blockProcessorFinished = Notification.Name(rawValue: "CompactBlockProcessorFinished") + static let blockProcessorFailed = Notification.Name(rawValue: "CompactBlockProcessorFinished") } - class CompactBlockProcessor { - enum State { /** @@ -66,12 +63,10 @@ class CompactBlockProcessor { config.retries } - private var batchSize: BlockHeight { BlockHeight(self.config.downloadBatchSize) } - private var processingError: Error? init(downloader: CompactBlockDownloading, backend: ZcashRustBackendWelding.Type, config: Configuration, service: LightWalletService) { @@ -91,7 +86,6 @@ class CompactBlockProcessor { } - deinit { self.queue.suspend() self.unsuscribeToSystemNotifications() @@ -180,14 +174,12 @@ class CompactBlockProcessor { self.processNewBlocks(latestHeight: latestBlockHeight, latestDownloadedHeight: latestDownloadedBlockHeight) } - } func processNewBlocks(latestHeight: BlockHeight, latestDownloadedHeight: BlockHeight) { let dispatchGroup = DispatchGroup() - let validateBlocksTask = DispatchWorkItem { dispatchGroup.enter() self.state = .scanning @@ -252,7 +244,6 @@ class CompactBlockProcessor { self.state = .stopped } - func fail(_ error: Error) { // todo specify: failure print(error.localizedDescription) @@ -264,7 +255,6 @@ class CompactBlockProcessor { } - extension CompactBlockProcessor.Configuration { static var standard: CompactBlockProcessor.Configuration { diff --git a/ZcashLightClientKit/Block/Storage/BlockRepository.swift b/ZcashLightClientKit/Block/Storage/BlockRepository.swift index 83cdf316..bd8c2ec6 100644 --- a/ZcashLightClientKit/Block/Storage/BlockRepository.swift +++ b/ZcashLightClientKit/Block/Storage/BlockRepository.swift @@ -8,7 +8,6 @@ import Foundation - protocol BlockRepository { func lastScannedBlockHeight() -> BlockHeight } diff --git a/ZcashLightClientKit/Block/Storage/CompactBlockStoring.swift b/ZcashLightClientKit/Block/Storage/CompactBlockStoring.swift index e2f391a3..6742a9ad 100644 --- a/ZcashLightClientKit/Block/Storage/CompactBlockStoring.swift +++ b/ZcashLightClientKit/Block/Storage/CompactBlockStoring.swift @@ -33,7 +33,7 @@ protocol CompactBlockStoring { /** Write the given blocks to this store, which may be anything from an in-memory cache to a DB. */ - func write(blocks: [ZcashCompactBlock]) throws -> Void + func write(blocks: [ZcashCompactBlock]) throws /** Write the given blocks to this store, which may be anything from an in-memory cache to a DB. @@ -49,7 +49,7 @@ protocol CompactBlockStoring { Meaning, if max height is 100 block and rewindTo(50) is called, then the highest block remaining will be 49. */ - func rewind(to height: BlockHeight) throws -> Void + func rewind(to height: BlockHeight) throws /** Remove every block above and including the given height. @@ -60,4 +60,3 @@ protocol CompactBlockStoring { */ func rewind(to height: BlockHeight, completion: ((Error?) -> Void)?) } - diff --git a/ZcashLightClientKit/Block/Storage/Storage.swift b/ZcashLightClientKit/Block/Storage/Storage.swift index 96527c86..f37518d1 100644 --- a/ZcashLightClientKit/Block/Storage/Storage.swift +++ b/ZcashLightClientKit/Block/Storage/Storage.swift @@ -8,7 +8,6 @@ import Foundation - protocol Storage { func createDatabase(at path: String) throws @@ -24,5 +23,3 @@ enum StorageError: Error { case closeFailed case operationFailed } - - diff --git a/ZcashLightClientKit/Providers/ResourceProvider.swift b/ZcashLightClientKit/Providers/ResourceProvider.swift index ed1cdcad..d539b174 100644 --- a/ZcashLightClientKit/Providers/ResourceProvider.swift +++ b/ZcashLightClientKit/Providers/ResourceProvider.swift @@ -18,7 +18,6 @@ public protocol ResourceProvider { } - public struct DefaultResourceProvider: ResourceProvider { public var dataDbPath: String { diff --git a/ZcashLightClientKit/Rust/ZcashRustBackend.swift b/ZcashLightClientKit/Rust/ZcashRustBackend.swift index 57058ed2..2d4525fa 100644 --- a/ZcashLightClientKit/Rust/ZcashRustBackend.swift +++ b/ZcashLightClientKit/Rust/ZcashRustBackend.swift @@ -24,7 +24,7 @@ class ZcashRustBackend: ZcashRustBackendWelding { let error = UnsafeMutablePointer.allocate(capacity: Int(errorLen)) zcashlc_error_message_utf8(error, errorLen) zcashlc_clear_last_error() - return String(validatingUTF8: error)! + return String(validatingUTF8: error) } else { return nil } @@ -45,9 +45,10 @@ class ZcashRustBackend: ZcashRustBackendWelding { return nil } - let extsks = UnsafeBufferPointer(start: extsksCStr, count: Int(accounts)).map { - String(cString: $0!) - } + let extsks = UnsafeBufferPointer(start: extsksCStr, count: Int(accounts)).compactMap({ (cStr) -> String? in + guard let str = cStr else { return nil } + return String(cString: str) + }) zcashlc_vec_string_free(extsksCStr, UInt(accounts)) return extsks } @@ -60,12 +61,9 @@ class ZcashRustBackend: ZcashRustBackendWelding { static func getAddress(dbData: URL, account: Int32) -> String? { let dbData = dbData.osStr() - let addressCStr = zcashlc_get_address(dbData.0, dbData.1, account) - if addressCStr == nil { - return nil - } + guard let addressCStr = zcashlc_get_address(dbData.0, dbData.1, account) else { return nil } - let address = String(validatingUTF8: addressCStr!) + let address = String(validatingUTF8: addressCStr) zcashlc_string_free(addressCStr) return address } @@ -83,12 +81,9 @@ class ZcashRustBackend: ZcashRustBackendWelding { static func getReceivedMemoAsUTF8(dbData: URL, idNote: Int64) -> String? { let dbData = dbData.osStr() - let memoCStr = zcashlc_get_received_memo_as_utf8(dbData.0, dbData.1, idNote) - if memoCStr == nil { - return nil - } - - let memo = String(validatingUTF8: memoCStr!) + guard let memoCStr = zcashlc_get_received_memo_as_utf8(dbData.0, dbData.1, idNote) else { return nil } + + let memo = String(validatingUTF8: memoCStr) zcashlc_string_free(memoCStr) return memo } @@ -96,12 +91,9 @@ class ZcashRustBackend: ZcashRustBackendWelding { static func getSentMemoAsUTF8(dbData: URL, idNote: Int64) -> String? { let dbData = dbData.osStr() - let memoCStr = zcashlc_get_sent_memo_as_utf8(dbData.0, dbData.1, idNote) - if memoCStr == nil { - return nil - } + guard let memoCStr = zcashlc_get_sent_memo_as_utf8(dbData.0, dbData.1, idNote) else { return nil } - let memo = String(validatingUTF8: memoCStr!) + let memo = String(validatingUTF8: memoCStr) zcashlc_string_free(memoCStr) return memo } diff --git a/ZcashLightClientKit/Service/LightWalletGRPCService.swift b/ZcashLightClientKit/Service/LightWalletGRPCService.swift index 6918eb43..07376ce2 100644 --- a/ZcashLightClientKit/Service/LightWalletGRPCService.swift +++ b/ZcashLightClientKit/Service/LightWalletGRPCService.swift @@ -21,7 +21,7 @@ class LightWalletGRPCService { compactTxStreamer = CompactTxStreamerServiceClient(channel: self.channel) } - func blockRange(startHeight: BlockHeight, endHeight: BlockHeight? = nil, result: @escaping (CallResult)->()) throws -> CompactTxStreamerGetBlockRangeCall { + func blockRange(startHeight: BlockHeight, endHeight: BlockHeight? = nil, result: @escaping (CallResult) -> Void) throws -> CompactTxStreamerGetBlockRangeCall { try compactTxStreamer.getBlockRange(BlockRange(startHeight: startHeight, endHeight: endHeight)) { result($0) } } @@ -29,17 +29,16 @@ class LightWalletGRPCService { try compactTxStreamer.getLatestBlock(ChainSpec()) } - func getTx(hash:String) throws -> RawTransaction { + func getTx(hash: String) throws -> RawTransaction { var filter = TxFilter() filter.hash = Data(hash.utf8) return try compactTxStreamer.getTransaction(filter) } - func getAllBlocksSinceSaplingLaunch(_ result: @escaping (CallResult)->()) throws -> CompactTxStreamerGetBlockRangeCall { + func getAllBlocksSinceSaplingLaunch(_ result: @escaping (CallResult) -> Void) throws -> CompactTxStreamerGetBlockRangeCall { try compactTxStreamer.getBlockRange(BlockRange.sinceSaplingActivation(), completion: result) } - } extension LightWalletGRPCService: LightWalletService { @@ -63,9 +62,9 @@ extension LightWalletGRPCService: LightWalletService { return blocks } - func latestBlockHeight(result: @escaping (Result) -> ()) { + func latestBlockHeight(result: @escaping (Result) -> Void) { do { - try compactTxStreamer.getLatestBlock(ChainSpec()) { (blockID, callResult) in + try compactTxStreamer.getLatestBlock(ChainSpec()) { (blockID, _) in guard let rawHeight = blockID?.height, let blockHeight = Int(exactly: rawHeight) else { result(.failure(LightWalletServiceError.generalError)) return @@ -82,7 +81,6 @@ extension LightWalletGRPCService: LightWalletService { // TODO: Make cancellable func blockRange(_ range: CompactBlockRange, result: @escaping (Result<[ZcashCompactBlock], LightWalletServiceError>) -> Void) { - queue.async { var blocks = [CompactBlock]() var isSyncing = true @@ -101,7 +99,6 @@ extension LightWalletGRPCService: LightWalletService { result(.failure(LightWalletServiceError.failed(statusCode: code))) } - } else { result(.failure(LightWalletServiceError.generalError)) return @@ -129,7 +126,7 @@ extension LightWalletGRPCService: LightWalletService { func latestBlockHeight() throws -> BlockHeight { - guard let height = try? latestBlock().compactBlockHeight() else { + guard let height = try? latestBlock().compactBlockHeight() else { throw LightWalletServiceError.invalidBlock } return height diff --git a/ZcashLightClientKit/Service/LightWalletService.swift b/ZcashLightClientKit/Service/LightWalletService.swift index d1c7589a..7a9d4819 100644 --- a/ZcashLightClientKit/Service/LightWalletService.swift +++ b/ZcashLightClientKit/Service/LightWalletService.swift @@ -51,8 +51,7 @@ public protocol LightWalletService { - Parameter result: a result containing the height or an Error */ - func latestBlockHeight(result: @escaping (Result) -> ()) - + func latestBlockHeight(result: @escaping (Result) -> Void) /** Return the latest block height known to the service. @@ -81,5 +80,3 @@ public protocol LightWalletService { func blockRange(_ range: CompactBlockRange) throws -> [ZcashCompactBlock] } - - diff --git a/ZcashLightClientKit/Service/Model/ZcashCompactBlock.swift b/ZcashLightClientKit/Service/Model/ZcashCompactBlock.swift index d9995fe9..3570e144 100644 --- a/ZcashLightClientKit/Service/Model/ZcashCompactBlock.swift +++ b/ZcashLightClientKit/Service/Model/ZcashCompactBlock.swift @@ -11,8 +11,6 @@ import Foundation public typealias BlockHeight = Int public typealias CompactBlockRange = Range - - enum ZcashCompactBlockError: Error { case unreadableBlock(compactBlock: CompactBlock) } @@ -52,5 +50,3 @@ extension ZcashCompactBlock: Hashable { hasher.combine(data) } } - - diff --git a/ZcashLightClientKit/Service/ProtoBuf/Extensions/Protocolbuffer+Extensions.swift b/ZcashLightClientKit/Service/ProtoBuf/Extensions/Protocolbuffer+Extensions.swift index d83da19d..50d02b37 100644 --- a/ZcashLightClientKit/Service/ProtoBuf/Extensions/Protocolbuffer+Extensions.swift +++ b/ZcashLightClientKit/Service/ProtoBuf/Extensions/Protocolbuffer+Extensions.swift @@ -14,7 +14,6 @@ extension CompactBlockRange { } } - extension BlockID { static let saplingActivationHeight: UInt64 = 280_000 @@ -41,7 +40,7 @@ extension BlockRange { init(startHeight: Int, endHeight: Int? = nil) { self = BlockRange() - self.start = BlockID(height: UInt64(startHeight)) + self.start = BlockID(height: UInt64(startHeight)) if let endHeight = endHeight { self.end = BlockID(height: UInt64(endHeight)) } @@ -59,7 +58,6 @@ extension BlockRange { } - extension Array where Element == CompactBlock { func asZcashCompactBlocks() throws -> [ZcashCompactBlock] { var result = [ZcashCompactBlock]() diff --git a/ZcashLightClientKit/Wallet.swift b/ZcashLightClientKit/Wallet.swift index e7a2e2a4..53e9a1e6 100644 --- a/ZcashLightClientKit/Wallet.swift +++ b/ZcashLightClientKit/Wallet.swift @@ -12,7 +12,6 @@ import Foundation capabilities and the supporting data required to exercise those abilities. */ - public enum WalletError: Error { case cacheDbInitFailed case dataDbInitFailed @@ -29,7 +28,7 @@ public class Wallet { private var walletBirthday: WalletBirthday private var storage: Storage? - init(rustWelding: ZcashRustBackendWelding.Type, cacheDbURL:URL, dataDbURL: URL, paramDestination: URL, seedProvider: SeedProvider, walletBirthday: WalletBirthday, accountIDs: [Int] = [0]) { + init(rustWelding: ZcashRustBackendWelding.Type, cacheDbURL: URL, dataDbURL: URL, paramDestination: URL, seedProvider: SeedProvider, walletBirthday: WalletBirthday, accountIDs: [Int] = [0]) { self.rustBackend = rustWelding.self self.dataDbURL = dataDbURL @@ -41,8 +40,7 @@ public class Wallet { } - - public func initalize(firstRunStartHeight: BlockHeight = SAPLING_ACTIVATION_HEIGHT) throws { + public func initalize(firstRunStartHeight: BlockHeight = SAPLING_ACTIVATION_HEIGHT) throws { guard let storage = StorageBuilder.cacheDb(at: cacheDbURL) else { throw WalletError.cacheDbInitFailed @@ -54,7 +52,6 @@ public class Wallet { self.storage = storage - } public func latestBlockHeight() -> Int? { @@ -62,27 +59,25 @@ public class Wallet { } } - - /** - Represents the wallet's birthday which can be thought of as a checkpoint at the earliest moment in history where - transactions related to this wallet could exist. Ideally, this would correspond to the latest block height at the - time the wallet key was created. Worst case, the height of Sapling activation could be used (280000). - - Knowing a wallet's birthday can significantly reduce the amount of data that it needs to download because none of - the data before that height needs to be scanned for transactions. However, we do need the Sapling tree data in - order to construct valid transactions from that point forward. This birthday contains that tree data, allowing us - to avoid downloading all the compact blocks required in order to generate it. - - New wallets can ignore any blocks created before their birthday. - - - Parameter height the height at the time the wallet was born - - Parameter hash the block hash corresponding to the given height - - Parameter time the time the wallet was born, in seconds - - Parameter tree the sapling tree corresponding to the given height. This takes around 15 minutes of processing to - generate from scratch because all blocks since activation need to be considered. So when it is calculated in - advance it can save the user a lot of time. - */ + Represents the wallet's birthday which can be thought of as a checkpoint at the earliest moment in history where + transactions related to this wallet could exist. Ideally, this would correspond to the latest block height at the + time the wallet key was created. Worst case, the height of Sapling activation could be used (280000). + + Knowing a wallet's birthday can significantly reduce the amount of data that it needs to download because none of + the data before that height needs to be scanned for transactions. However, we do need the Sapling tree data in + order to construct valid transactions from that point forward. This birthday contains that tree data, allowing us + to avoid downloading all the compact blocks required in order to generate it. + + New wallets can ignore any blocks created before their birthday. + + - Parameter height the height at the time the wallet was born + - Parameter hash the block hash corresponding to the given height + - Parameter time the time the wallet was born, in seconds + - Parameter tree the sapling tree corresponding to the given height. This takes around 15 minutes of processing to + generate from scratch because all blocks since activation need to be considered. So when it is calculated in + advance it can save the user a lot of time. + */ public struct WalletBirthday { var height: BlockHeight = -1 var hash: String = "" diff --git a/ZcashLightClientKitTests/BlockDownloaderTests.swift b/ZcashLightClientKitTests/BlockDownloaderTests.swift index 4920c732..0ebe7b2a 100644 --- a/ZcashLightClientKitTests/BlockDownloaderTests.swift +++ b/ZcashLightClientKitTests/BlockDownloaderTests.swift @@ -15,7 +15,7 @@ class BlockDownloaderTests: XCTestCase { var storage: CompactBlockStoring! override func setUp() { service = LightWalletGRPCService(channel: ChannelProvider().channel()) - storage = try! TestDbBuilder.inMemoryCompactBlockStorage() + storage = try! TestDbBuilder.inMemoryCompactBlockStorage() downloader = CompactBlockDownloader(service: service, storage: storage) } @@ -26,7 +26,6 @@ class BlockDownloaderTests: XCTestCase { downloader = nil } - func testSmallDownloadAsync() { let expect = XCTestExpectation(description: self.description) @@ -55,17 +54,14 @@ class BlockDownloaderTests: XCTestCase { wait(for: [expect], timeout: 2) } - func testSmallDownload() { - let lowerRange: BlockHeight = SAPLING_ACTIVATION_HEIGHT let upperRange: BlockHeight = SAPLING_ACTIVATION_HEIGHT + 99 let range = CompactBlockRange(uncheckedBounds: (lowerRange,upperRange)) var latest: BlockHeight = 0 - do { latest = try downloader.latestBlockHeight() } catch { @@ -105,7 +101,6 @@ class BlockDownloaderTests: XCTestCase { } } - /// Helper functions extension BlockDownloaderTests { diff --git a/ZcashLightClientKitTests/BlockScanOperationTests.swift b/ZcashLightClientKitTests/BlockScanOperationTests.swift index 71b682c2..ce2d41bc 100644 --- a/ZcashLightClientKitTests/BlockScanOperationTests.swift +++ b/ZcashLightClientKitTests/BlockScanOperationTests.swift @@ -28,7 +28,7 @@ class BlockScanOperationTests: XCTestCase { operationQueue.cancelAllOperations() // try! FileManager.default.removeItem(at: cacheDbURL) - try! FileManager.default.removeItem(at: dataDbURL) + try? FileManager.default.removeItem(at: dataDbURL) } func testSingleDownloadAndScanOperation() { diff --git a/ZcashLightClientKitTests/CompactBlockProcessorTests.swift b/ZcashLightClientKitTests/CompactBlockProcessorTests.swift index 196e6ea9..7a7b0fe0 100644 --- a/ZcashLightClientKitTests/CompactBlockProcessorTests.swift +++ b/ZcashLightClientKitTests/CompactBlockProcessorTests.swift @@ -20,8 +20,6 @@ class CompactBlockProcessorTests: XCTestCase { XCTAssertTrue(MockDbInit.emptyFile(at: processorConfig.cacheDbPath)) XCTAssertTrue(MockDbInit.emptyFile(at: processorConfig.dataDbPath)) - - let service = LightWalletGRPCService(channel: ChannelProvider().channel()) let storage = ZcashConsoleFakeStorage() let downloader = CompactBlockDownloader(service: service, storage: storage) @@ -43,13 +41,10 @@ class CompactBlockProcessorTests: XCTestCase { expect.unsuscribeFromNotifications() - } - func testStartNotifiesSuscriptors() { - XCTAssertNotNil(processor) expect.suscribe(to: Notification.Name.blockProcessorStarted, object: processor) diff --git a/ZcashLightClientKitTests/CompactBlockStorageTests.swift b/ZcashLightClientKitTests/CompactBlockStorageTests.swift index f97e7e74..babd7c0d 100644 --- a/ZcashLightClientKitTests/CompactBlockStorageTests.swift +++ b/ZcashLightClientKitTests/CompactBlockStorageTests.swift @@ -11,7 +11,6 @@ import XCTest @testable import ZcashLightClientKit class CompactBlockStorageTests: XCTestCase { - var storage: Storage = try! TestDbBuilder.inMemory() func testEmptyStorage() { @@ -61,7 +60,6 @@ class CompactBlockStorageTests: XCTestCase { } } - func testRewindTo() { let startHeight = SAPLING_ACTIVATION_HEIGHT diff --git a/ZcashLightClientKitTests/DownloadOperationTests.swift b/ZcashLightClientKitTests/DownloadOperationTests.swift index 6f18103b..a9d1f75f 100644 --- a/ZcashLightClientKitTests/DownloadOperationTests.swift +++ b/ZcashLightClientKitTests/DownloadOperationTests.swift @@ -12,7 +12,6 @@ import SQLite class DownloadOperationTests: XCTestCase { var operationQueue = OperationQueue() - override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. diff --git a/ZcashLightClientKitTests/LightWalletServiceTests.swift b/ZcashLightClientKitTests/LightWalletServiceTests.swift index 58ec5d9d..300fcb51 100644 --- a/ZcashLightClientKitTests/LightWalletServiceTests.swift +++ b/ZcashLightClientKitTests/LightWalletServiceTests.swift @@ -59,7 +59,6 @@ class LightWalletServiceTests: XCTestCase { wait(for: [expect], timeout: 5) } - func testSyncBlockRange() { let lowerRange: BlockHeight = SAPLING_ACTIVATION_HEIGHT let upperRange: BlockHeight = SAPLING_ACTIVATION_HEIGHT + 99 diff --git a/ZcashLightClientKitTests/ZcashLightClientKitTests.swift b/ZcashLightClientKitTests/ZcashLightClientKitTests.swift index 3d5553c7..11489706 100644 --- a/ZcashLightClientKitTests/ZcashLightClientKitTests.swift +++ b/ZcashLightClientKitTests/ZcashLightClientKitTests.swift @@ -62,7 +62,6 @@ class ZcashLightClientKitTests: XCTestCase { func testBlockRangeServiceTilLastest() { let expectedCount: BlockHeight = 99 var count: BlockHeight = 0 - let startHeight = latestBlockHeight - expectedCount let endHeight = latestBlockHeight! @@ -75,7 +74,6 @@ class ZcashLightClientKitTests: XCTestCase { XCTFail("failed to create getBlockRange( \(startHeight) ..<= \(endHeight)") return } - var blocks = [CompactBlock]() while true { diff --git a/ZcashLightClientKitTests/ZcashRustBackendTests.swift b/ZcashLightClientKitTests/ZcashRustBackendTests.swift index fb74c75a..63d447dc 100644 --- a/ZcashLightClientKitTests/ZcashRustBackendTests.swift +++ b/ZcashLightClientKitTests/ZcashRustBackendTests.swift @@ -60,6 +60,5 @@ class ZcashRustBackendTests: XCTestCase { XCTAssertTrue(ZcashRustBackend.scanBlocks(dbCache: cacheDb, dbData: dbData)) - } } diff --git a/ZcashLightClientKitTests/utils/FakeStorage.swift b/ZcashLightClientKitTests/utils/FakeStorage.swift index 3f2f96d1..9fb6045f 100644 --- a/ZcashLightClientKitTests/utils/FakeStorage.swift +++ b/ZcashLightClientKitTests/utils/FakeStorage.swift @@ -22,7 +22,6 @@ class ZcashConsoleFakeStorage: CompactBlockStoring { fakeRewind(to: height) } - var latestBlockHeight: BlockHeight = 0 var delay = DispatchTimeInterval.milliseconds(300) @@ -62,6 +61,4 @@ class ZcashConsoleFakeStorage: CompactBlockStoring { self.latestBlockHeight = min(self.latestBlockHeight, height) } - - } diff --git a/ZcashLightClientKitTests/utils/Stubs.swift b/ZcashLightClientKitTests/utils/Stubs.swift index a022d492..db6fbd9e 100644 --- a/ZcashLightClientKitTests/utils/Stubs.swift +++ b/ZcashLightClientKitTests/utils/Stubs.swift @@ -18,7 +18,7 @@ class AwfulLightWalletService: LightWalletService { throw LightWalletServiceError.invalidBlock } - func latestBlockHeight(result: @escaping (Result) -> ()) { + func latestBlockHeight(result: @escaping (Result) -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { result(.failure(LightWalletServiceError.generalError)) } @@ -31,5 +31,4 @@ class AwfulLightWalletService: LightWalletService { } } - } diff --git a/ZcashLightClientKitTests/utils/TestDbBuilder.swift b/ZcashLightClientKitTests/utils/TestDbBuilder.swift index ee2f2275..df83b19e 100644 --- a/ZcashLightClientKitTests/utils/TestDbBuilder.swift +++ b/ZcashLightClientKitTests/utils/TestDbBuilder.swift @@ -33,14 +33,13 @@ struct TestDbBuilder { return compactBlockDao } - static func diskCompactBlockStorage(at url:URL) throws -> CompactBlockStorage { + static func diskCompactBlockStorage(at url: URL) throws -> CompactBlockStorage { let connection = try Connection(url.absoluteString) let compactBlockDao = CompactBlockStorage(connection: connection) try compactBlockDao.createTable() return compactBlockDao } - - + static func seed(db: Storage, with blockRange: CompactBlockRange) throws { guard let blocks = StubBlockCreator.createBlockRange(blockRange) else { diff --git a/ZcashLightClientKitTests/utils/Tests+Utils.swift b/ZcashLightClientKitTests/utils/Tests+Utils.swift index ea2f425a..05456e25 100644 --- a/ZcashLightClientKitTests/utils/Tests+Utils.swift +++ b/ZcashLightClientKitTests/utils/Tests+Utils.swift @@ -16,14 +16,11 @@ class ChannelProvider { } } - struct MockDbInit { @discardableResult static func emptyFile(at path: String) -> Bool { - FileManager.default.createFile(atPath: path, contents: Data("".utf8), attributes: nil) - } static func destroy(at path: String) throws { @@ -46,7 +43,6 @@ extension XCTestExpectation { } } - func __documentsDirectory() throws -> URL { try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) } diff --git a/zcash.swiftformat b/zcash.swiftformat new file mode 100644 index 00000000..2e89e4b0 --- /dev/null +++ b/zcash.swiftformat @@ -0,0 +1,8 @@ +# options +--self remove # redundantSelf +--importgrouping testable-bottom # sortedImports +--commas always # trailingCommas +--trimwhitespace always # trailingSpace + +# rules +--rules redundantParens,redundantSelf,sortedImports,trailingCommas,trailingSpace