ZcashLightClientKit/Tests/OfflineTests/ZcashRustBackendTests.swift

216 lines
7.3 KiB
Swift
Raw Normal View History

2019-07-02 02:01:55 -07:00
//
// ZcashRustBackendTests.swift
// ZcashLightClientKitTests
//
// Created by Jack Grigg on 28/06/2019.
// Copyright © 2019 Electric Coin Company. All rights reserved.
//
import XCTest
2022-02-28 09:03:20 -08:00
@testable import TestUtils
2019-07-02 02:01:55 -07:00
@testable import ZcashLightClientKit
2021-09-23 06:26:41 -07:00
// swiftlint:disable force_unwrapping implicitly_unwrapped_optional force_try
2019-07-02 02:01:55 -07:00
class ZcashRustBackendTests: XCTestCase {
var dbData: URL!
var dataDbHandle = TestDbHandle(originalDb: TestDbBuilder.prePopulatedDataDbURL()!)
var cacheDbHandle = TestDbHandle(originalDb: TestDbBuilder.prePopulatedCacheDbURL()!)
2021-09-23 06:26:41 -07:00
let spendingKey =
// swiftlint:disable:next line_length
"secret-extended-key-test1qvpevftsqqqqpqy52ut2vv24a2qh7nsukew7qg9pq6djfwyc3xt5vaxuenshp2hhspp9qmqvdh0gs2ljpwxders5jkwgyhgln0drjqaguaenfhehz4esdl4kwlm5t9q0l6wmzcrvcf5ed6dqzvct3e2ge7f6qdvzhp02m7sp5a0qjssrwpdh7u6tq89hl3wchuq8ljq8r8rwd6xdwh3nry9at80z7amnj3s6ah4jevnvfr08gxpws523z95g6dmn4wm6l3658kd4xcq9rc0qn"
let recipientAddress = "ztestsapling1ctuamfer5xjnnrdr3xdazenljx0mu0gutcf9u9e74tr2d3jwjnt0qllzxaplu54hgc2tyjdc2p6"
let zpend: Int = 500_000
2021-07-28 09:59:10 -07:00
let networkType = NetworkType.testnet
2019-07-02 02:01:55 -07:00
override func setUp() {
2021-09-23 06:26:41 -07:00
super.setUp()
dbData = try! __dataDbURL()
try? dataDbHandle.setUp()
2019-07-02 02:01:55 -07:00
}
2019-07-02 02:01:55 -07:00
override func tearDown() {
2021-09-23 06:26:41 -07:00
super.tearDown()
try? FileManager.default.removeItem(at: dbData!)
dataDbHandle.dispose()
2019-07-02 02:01:55 -07:00
}
func testInitWithShortSeedAndFail() throws {
let seed = "testreferencealice"
var dbInit: DbInitResult!
XCTAssertNoThrow(try { dbInit = try ZcashRustBackend.initDataDb(dbData: self.dbData!, seed: nil, networkType: self.networkType) }())
guard case .success = dbInit else {
XCTFail("Failed to initDataDb. Expected `.success` got: \(String(describing: dbInit))")
return
}
XCTAssertThrowsError(try ZcashRustBackend.createAccount(dbData: dbData!, seed: Array(seed.utf8), networkType: networkType))
}
func testInitAndScanBlocks() throws {
guard let cacheDb = TestDbBuilder.prePopulatedCacheDbURL() else {
XCTFail("pre populated Db not present")
return
}
let seed = "testreferencealicetestreferencealice"
var dbInit: DbInitResult!
XCTAssertNoThrow(try { dbInit = try ZcashRustBackend.initDataDb(dbData: self.dbData!, seed: Array(seed.utf8), networkType: self.networkType) }())
guard case .success = dbInit else {
XCTFail("Failed to initDataDb. Expected `.success` got: \(String(describing: dbInit))")
return
}
XCTAssertEqual(ZcashRustBackend.getLastError(), nil)
let ufvks = [
try DerivationTool(networkType: networkType).deriveUnifiedSpendingKey(seed: Array(seed.utf8), accountIndex: 0)
.deriveFullViewingKey()
]
guard try ZcashRustBackend.initAccountsTable(dbData: dbData!, ufvks: ufvks, networkType: networkType) else {
XCTFail("failed with error: \(String(describing: ZcashRustBackend.lastError()))")
return
}
XCTAssertNotNil(
try ZcashRustBackend.createAccount(
dbData: dbData!,
seed: Array(seed.utf8),
networkType: networkType
)
)
XCTAssertEqual(ZcashRustBackend.getLastError(), nil)
let addr = try ZcashRustBackend.getCurrentAddress(dbData: dbData!, account: 0, networkType: networkType)
XCTAssertEqual(ZcashRustBackend.getLastError(), nil)
XCTAssertEqual(addr.saplingReceiver()?.stringEncoded, Optional("ztestsapling12k9m98wmpjts2m56wc60qzhgsfvlpxcwah268xk5yz4h942sd58jy3jamqyxjwums6hw7kfa4cc"))
2021-07-28 09:59:10 -07:00
XCTAssertTrue(ZcashRustBackend.scanBlocks(dbCache: cacheDb, dbData: dbData, networkType: networkType))
}
func testIsValidTransparentAddressFalse() {
XCTAssertFalse(
ZcashRustBackend.isValidTransparentAddress(
"ztestsapling12k9m98wmpjts2m56wc60qzhgsfvlpxcwah268xk5yz4h942sd58jy3jamqyxjwums6hw7kfa4cc",
networkType: networkType
)
2021-09-23 06:26:41 -07:00
)
}
func testIsValidTransparentAddressTrue() {
XCTAssertTrue(
ZcashRustBackend.isValidTransparentAddress(
"tmSwpioc7reeoNrYB9SKpWkurJz3yEj3ee7",
networkType: networkType
)
2021-09-23 06:26:41 -07:00
)
}
[#461] Adopt a Type-Safe Keys and Addresses API This PR creates data types for Addresses and Keys so that they are not represented by Strings anymore. This avoids mistakenly use the wrong keys because they are all alike for the type system. New Protocols: ============= StringEncoded -> Protocol that makes a type can be expressed in an string-encoded fashion either for UI or Interchange purposes. Undescribable -> A protocol that implements methods that override default decriptions used by debuggers, loggers and event trackers to avoid types conforming to it to be leaked to logs. Deleted Protocols: ================== UnifiedFullViewingKey --> turned into a struct. UnifiedAddress --> turned into a struct new Error Type: ================ ```` enum KeyEncodingError: Error { case invalidEncoding } ```` This error is thrown when an Address or Key type (addresses are public keys in the end) can be decoded from their String representation, typically upon initialization from a User input. New Types: ========= SaplingExtendedSpendingKey -> Type for Sapling Extended Full Viewing Keys this type will be replaced with Unified Spending Keys soon. SaplingExtendedFullViewingKey -> Extended Full Viewing Key for Sapling. Maintains existing funcionality. Will be probably deprecated in favor of UFVK. TransparentAccountPrivKey -> Private key for transparent account. Used only for shielding operations. Note: this will probably be deprecated soon. UnifiedFullViewingKey -> Replaces the protocol that had the same name. TransparentAddress -> Replaces a type alias with a struct SaplingAddress --> Represents a Sapling receiver address. Comonly called zAddress. This address corresponds to the Zcash Sapling shielded pool. Although this it is fully functional, we encourage developers to choose `UnifiedAddress` before Sapling or Transparent ones. UnifiedAddress -> Represents a UA. String-encodable and Equatable. Use of UAs must be favored instead of individual receivers for different pools. This type can't be decomposed into their Receiver types yet. Recipient -> This represents all valid receiver types to be used as inputs for outgoing transactions. ```` public enum Recipient: Equatable, StringEncoded { case transparent(TransparentAddress) case sapling(SaplingAddress) case unified(UnifiedAddress) ```` The wrapped concrete receiver is a valid receiver type. Deleted Type Aliases: ===================== The following aliases were deleted and turned into types ```` public typealias TransparentAddress = String public typealias SaplingShieldedAddress = String ```` Changes to Derivation Tool ========================== DerivationTool has been changed to accomodate this new types and remove Strings whenever possible. Changes to Synchronizer and CompactBlockProcessor ================================================= Accordingly these to components have been modified to accept the new types intead of strings when possible. Changes to Demo App =================== The demo App has been patch to compile and work with the new types. Developers must consider that the use (and abuse) of forced_try and forced unwrapping is a "license" that maintainers are using for the sake of brevity. We consider that clients of this SDK do know how to handle Errors and Optional and it is not the objective of the demo code to show good practices on those matters. Closes #461
2022-08-20 15:10:22 -07:00
func testIsValidSaplingAddressTrue() {
XCTAssertTrue(
ZcashRustBackend.isValidSaplingAddress(
"ztestsapling12k9m98wmpjts2m56wc60qzhgsfvlpxcwah268xk5yz4h942sd58jy3jamqyxjwums6hw7kfa4cc",
networkType: networkType
)
2021-09-23 06:26:41 -07:00
)
}
[#461] Adopt a Type-Safe Keys and Addresses API This PR creates data types for Addresses and Keys so that they are not represented by Strings anymore. This avoids mistakenly use the wrong keys because they are all alike for the type system. New Protocols: ============= StringEncoded -> Protocol that makes a type can be expressed in an string-encoded fashion either for UI or Interchange purposes. Undescribable -> A protocol that implements methods that override default decriptions used by debuggers, loggers and event trackers to avoid types conforming to it to be leaked to logs. Deleted Protocols: ================== UnifiedFullViewingKey --> turned into a struct. UnifiedAddress --> turned into a struct new Error Type: ================ ```` enum KeyEncodingError: Error { case invalidEncoding } ```` This error is thrown when an Address or Key type (addresses are public keys in the end) can be decoded from their String representation, typically upon initialization from a User input. New Types: ========= SaplingExtendedSpendingKey -> Type for Sapling Extended Full Viewing Keys this type will be replaced with Unified Spending Keys soon. SaplingExtendedFullViewingKey -> Extended Full Viewing Key for Sapling. Maintains existing funcionality. Will be probably deprecated in favor of UFVK. TransparentAccountPrivKey -> Private key for transparent account. Used only for shielding operations. Note: this will probably be deprecated soon. UnifiedFullViewingKey -> Replaces the protocol that had the same name. TransparentAddress -> Replaces a type alias with a struct SaplingAddress --> Represents a Sapling receiver address. Comonly called zAddress. This address corresponds to the Zcash Sapling shielded pool. Although this it is fully functional, we encourage developers to choose `UnifiedAddress` before Sapling or Transparent ones. UnifiedAddress -> Represents a UA. String-encodable and Equatable. Use of UAs must be favored instead of individual receivers for different pools. This type can't be decomposed into their Receiver types yet. Recipient -> This represents all valid receiver types to be used as inputs for outgoing transactions. ```` public enum Recipient: Equatable, StringEncoded { case transparent(TransparentAddress) case sapling(SaplingAddress) case unified(UnifiedAddress) ```` The wrapped concrete receiver is a valid receiver type. Deleted Type Aliases: ===================== The following aliases were deleted and turned into types ```` public typealias TransparentAddress = String public typealias SaplingShieldedAddress = String ```` Changes to Derivation Tool ========================== DerivationTool has been changed to accomodate this new types and remove Strings whenever possible. Changes to Synchronizer and CompactBlockProcessor ================================================= Accordingly these to components have been modified to accept the new types intead of strings when possible. Changes to Demo App =================== The demo App has been patch to compile and work with the new types. Developers must consider that the use (and abuse) of forced_try and forced unwrapping is a "license" that maintainers are using for the sake of brevity. We consider that clients of this SDK do know how to handle Errors and Optional and it is not the objective of the demo code to show good practices on those matters. Closes #461
2022-08-20 15:10:22 -07:00
func testIsValidSaplingAddressFalse() {
XCTAssertFalse(
ZcashRustBackend.isValidSaplingAddress(
"tmSwpioc7reeoNrYB9SKpWkurJz3yEj3ee7",
networkType: networkType
)
2021-09-23 06:26:41 -07:00
)
}
func testListTransparentReceivers() throws {
let testVector = [TestVector](TestVector.testVectors![0 ... 2])
let network = NetworkType.mainnet
let tempDBs = TemporaryDbBuilder.build()
let seed = testVector[0].root_seed!
XCTAssertEqual(
try ZcashRustBackend.initDataDb(
dbData: tempDBs.dataDB,
seed: seed,
networkType: network
),
.success
)
var usk: UnifiedSpendingKey?;
XCTAssertNoThrow(
usk = try ZcashRustBackend.createAccount(
dbData: tempDBs.dataDB,
seed: seed,
networkType: network
)
)
XCTAssertEqual(usk?.account, 0)
let expectedReceivers = testVector.map {
UnifiedAddress(validatedEncoding: $0.unified_addr!)
}
.compactMap({ $0.transparentReceiver() })
let expectedUAs = testVector.map{
UnifiedAddress(validatedEncoding: $0.unified_addr!)
}
guard expectedReceivers.count >= 2 else {
XCTFail("not enough transparent receivers")
return
}
var uAddresses = [UnifiedAddress]()
for i in (0 ... 2) {
uAddresses.append(
try ZcashRustBackend.getCurrentAddress(
dbData: tempDBs.dataDB,
account: 0,
networkType: network
)
)
if (i < 2) {
_ = try ZcashRustBackend.getNextAvailableAddress(
dbData: tempDBs.dataDB,
account: 0,
networkType: network
)
}
}
XCTAssertEqual(
uAddresses,
expectedUAs
)
let actualReceivers = try ZcashRustBackend.listTransparentReceivers(
dbData: tempDBs.dataDB,
account: 0,
networkType: network
)
XCTAssertEqual(
expectedReceivers.sorted(),
actualReceivers.sorted()
)
}
func testGetMetadataFromAddress() throws {
let recipientAddress = "zs17mg40levjezevuhdp5pqrd52zere7r7vrjgdwn5sj4xsqtm20euwahv9anxmwr3y3kmwuz8k55a"
let metadata = ZcashRustBackend.getAddressMetadata(recipientAddress)
XCTAssertEqual(metadata?.networkType, .mainnet)
XCTAssertEqual(metadata?.addressType, .sapling)
}
2019-07-02 02:01:55 -07:00
}