Merge pull request #524 from LukasKorba/483_OutboundTransactionManager_Async

[483] OutboundTransactionManager To Async/Await
This commit is contained in:
Lukas Korba 2022-09-12 14:25:34 +02:00 committed by GitHub
commit 9cf2e07d25
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 133 additions and 186 deletions

View File

@ -527,27 +527,18 @@ public class SDKSynchronizer: Synchronizer {
let shieldingSpend = try transactionManager.initSpend(zatoshi: tBalance.verified, toAddress: zAddr, memo: memo, from: 0) let shieldingSpend = try transactionManager.initSpend(zatoshi: tBalance.verified, toAddress: zAddr, memo: memo, from: 0)
transactionManager.encodeShieldingTransaction( // TODO: Task will be removed when this method is changed to async, issue 487, https://github.com/zcash/ZcashLightClientKit/issues/487
spendingKey: spendingKey, Task {
tsk: transparentSecretKey, do {
pendingTransaction: shieldingSpend let transaction = try await transactionManager.encodeShieldingTransaction(
) { [weak self] result in spendingKey: spendingKey,
guard let self = self else { return } tsk: transparentSecretKey,
pendingTransaction: shieldingSpend
switch result { )
case .success(let transaction):
self.transactionManager.submit(pendingTransaction: transaction) { submitResult in
switch submitResult {
case .success(let submittedTx):
resultBlock(.success(submittedTx))
case .failure(let submissionError):
DispatchQueue.main.async {
resultBlock(.failure(submissionError))
}
}
}
case .failure(let error): let submittedTx = try await transactionManager.submit(pendingTransaction: transaction)
resultBlock(.success(submittedTx))
} catch {
resultBlock(.failure(error)) resultBlock(.failure(error))
} }
} }
@ -574,22 +565,16 @@ public class SDKSynchronizer: Synchronizer {
from: accountIndex from: accountIndex
) )
transactionManager.encode(spendingKey: spendingKey, pendingTransaction: spend) { [weak self] result in // TODO: Task will be removed when this method is changed to async, issue 487, https://github.com/zcash/ZcashLightClientKit/issues/487
guard let self = self else { return } Task {
switch result { do {
case .success(let transaction): let transaction = try await transactionManager.encode(
self.transactionManager.submit(pendingTransaction: transaction) { submitResult in spendingKey: spendingKey,
switch submitResult { pendingTransaction: spend
case .success(let submittedTx): )
resultBlock(.success(submittedTx)) let submittedTx = try await transactionManager.submit(pendingTransaction: transaction)
case .failure(let submissionError): resultBlock(.success(submittedTx))
DispatchQueue.main.async { } catch {
resultBlock(.failure(submissionError))
}
}
}
case .failure(let error):
resultBlock(.failure(error)) resultBlock(.failure(error))
} }
} }

View File

@ -67,167 +67,129 @@ class PersistentTransactionManager: OutboundTransactionManager {
func encodeShieldingTransaction( func encodeShieldingTransaction(
spendingKey: String, spendingKey: String,
tsk: String, tsk: String,
pendingTransaction: PendingTransactionEntity, pendingTransaction: PendingTransactionEntity
result: @escaping (Result<PendingTransactionEntity, Error>) -> Void ) async throws -> PendingTransactionEntity {
) { let derivationTool = DerivationTool(networkType: self.network)
queue.async { [weak self] in
guard let self = self else { return } guard
let viewingKey = try? derivationTool.deriveViewingKey(spendingKey: spendingKey),
let derivationTool = DerivationTool(networkType: self.network) let zAddr = try? derivationTool.deriveShieldedAddress(viewingKey: viewingKey)
else {
guard throw TransactionManagerError.shieldingEncodingFailed(
let viewingKey = try? derivationTool.deriveViewingKey(spendingKey: spendingKey), pendingTransaction,
let zAddr = try? derivationTool.deriveShieldedAddress(viewingKey: viewingKey) reason: "There was an error Deriving your keys"
else { )
result( }
.failure(
TransactionManagerError.shieldingEncodingFailed( guard pendingTransaction.toAddress == zAddr else {
pendingTransaction, throw TransactionManagerError.shieldingEncodingFailed(
reason: "There was an error Deriving your keys" pendingTransaction,
) reason: """
) the recipient address does not match your
) derived shielded address. Shielding transactions
return addresses must match the ones derived from your keys.
} This is a serious error. We are not letting you encode
this shielding transaction because it can lead to loss
of funds
"""
)
}
do {
let encodedTransaction = try self.encoder.createShieldingTransaction(
spendingKey: spendingKey,
tSecretKey: tsk,
memo: pendingTransaction.memo?.asZcashTransactionMemo(),
from: pendingTransaction.accountIndex
)
let transaction = try self.encoder.expandEncodedTransaction(encodedTransaction)
guard pendingTransaction.toAddress == zAddr else { var pending = pendingTransaction
result( pending.encodeAttempts += 1
.failure( pending.raw = encodedTransaction.raw
TransactionManagerError.shieldingEncodingFailed( pending.rawTransactionId = encodedTransaction.transactionId
pendingTransaction, pending.expiryHeight = transaction.expiryHeight ?? BlockHeight.empty()
reason: """ pending.minedHeight = transaction.minedHeight ?? BlockHeight.empty()
the recipient address does not match your
derived shielded address. Shielding transactions try self.repository.update(pending)
addresses must match the ones derived from your keys.
This is a serious error. We are not letting you encode return pending
this shielding transaction because it can lead to loss } catch StorageError.updateFailed {
of funds throw TransactionManagerError.updateFailed(pendingTransaction)
""" } catch {
) throw error
)
)
return
}
do {
let encodedTransaction = try self.encoder.createShieldingTransaction(
spendingKey: spendingKey,
tSecretKey: tsk,
memo: pendingTransaction.memo?.asZcashTransactionMemo(),
from: pendingTransaction.accountIndex
)
let transaction = try self.encoder.expandEncodedTransaction(encodedTransaction)
var pending = pendingTransaction
pending.encodeAttempts += 1
pending.raw = encodedTransaction.raw
pending.rawTransactionId = encodedTransaction.transactionId
pending.expiryHeight = transaction.expiryHeight ?? BlockHeight.empty()
pending.minedHeight = transaction.minedHeight ?? BlockHeight.empty()
try self.repository.update(pending)
result(.success(pending))
} catch StorageError.updateFailed {
DispatchQueue.main.async {
result(.failure(TransactionManagerError.updateFailed(pendingTransaction)))
}
} catch {
DispatchQueue.main.async {
result(.failure(error))
}
}
} }
} }
func encode( func encode(
spendingKey: String, spendingKey: String,
pendingTransaction: PendingTransactionEntity, pendingTransaction: PendingTransactionEntity
result: @escaping (Result<PendingTransactionEntity, Error>) -> Void ) async throws -> PendingTransactionEntity {
) { do {
queue.async { [weak self] in let encodedTransaction = try self.encoder.createTransaction(
guard let self = self else { return } spendingKey: spendingKey,
zatoshi: pendingTransaction.intValue,
to: pendingTransaction.toAddress,
memo: pendingTransaction.memo?.asZcashTransactionMemo(),
from: pendingTransaction.accountIndex
)
let transaction = try self.encoder.expandEncodedTransaction(encodedTransaction)
var pending = pendingTransaction
pending.encodeAttempts += 1
pending.raw = encodedTransaction.raw
pending.rawTransactionId = encodedTransaction.transactionId
pending.expiryHeight = transaction.expiryHeight ?? BlockHeight.empty()
pending.minedHeight = transaction.minedHeight ?? BlockHeight.empty()
try self.repository.update(pending)
return pending
} catch StorageError.updateFailed {
throw TransactionManagerError.updateFailed(pendingTransaction)
} catch {
do { do {
let encodedTransaction = try self.encoder.createTransaction( try self.updateOnFailure(transaction: pendingTransaction, error: error)
spendingKey: spendingKey,
zatoshi: pendingTransaction.intValue,
to: pendingTransaction.toAddress,
memo: pendingTransaction.memo?.asZcashTransactionMemo(),
from: pendingTransaction.accountIndex
)
let transaction = try self.encoder.expandEncodedTransaction(encodedTransaction)
var pending = pendingTransaction
pending.encodeAttempts += 1
pending.raw = encodedTransaction.raw
pending.rawTransactionId = encodedTransaction.transactionId
pending.expiryHeight = transaction.expiryHeight ?? BlockHeight.empty()
pending.minedHeight = transaction.minedHeight ?? BlockHeight.empty()
try self.repository.update(pending)
result(.success(pending))
} catch StorageError.updateFailed {
DispatchQueue.main.async {
result(.failure(TransactionManagerError.updateFailed(pendingTransaction)))
}
} catch { } catch {
do { throw TransactionManagerError.updateFailed(pendingTransaction)
try self.updateOnFailure(transaction: pendingTransaction, error: error)
} catch {
DispatchQueue.main.async {
result(.failure(TransactionManagerError.updateFailed(pendingTransaction)))
}
}
DispatchQueue.main.async {
result(.failure(error))
}
} }
throw error
} }
} }
func submit( func submit(
pendingTransaction: PendingTransactionEntity, pendingTransaction: PendingTransactionEntity
result: @escaping (Result<PendingTransactionEntity, Error>) -> Void ) async throws -> PendingTransactionEntity {
) {
guard let txId = pendingTransaction.id else { guard let txId = pendingTransaction.id else {
result(.failure(TransactionManagerError.notPending(pendingTransaction)))// this transaction is not stored throw TransactionManagerError.notPending(pendingTransaction) // this transaction is not stored
return
} }
queue.async { [weak self] in do {
guard let self = self else { return } guard let storedTx = try self.repository.find(by: txId) else {
throw TransactionManagerError.notPending(pendingTransaction)
do {
guard let storedTx = try self.repository.find(by: txId) else {
result(.failure(TransactionManagerError.notPending(pendingTransaction)))
return
}
guard !storedTx.isCancelled else {
LoggerProxy.debug("ignoring cancelled transaction \(storedTx)")
result(.failure(TransactionManagerError.cancelled(storedTx)))
return
}
guard let raw = storedTx.raw else {
LoggerProxy.debug("INCONSISTENCY: attempt to send pending transaction \(txId) that has not raw data")
result(.failure(TransactionManagerError.internalInconsistency(storedTx)))
return
}
let response = try self.service.submit(spendTransaction: raw)
let transaction = try self.update(transaction: storedTx, on: response)
guard response.errorCode >= 0 else {
result(.failure(TransactionManagerError.submitFailed(transaction, errorCode: Int(response.errorCode))))
return
}
result(.success(transaction))
} catch {
try? self.updateOnFailure(transaction: pendingTransaction, error: error)
result(.failure(error))
} }
guard !storedTx.isCancelled else {
LoggerProxy.debug("ignoring cancelled transaction \(storedTx)")
throw TransactionManagerError.cancelled(storedTx)
}
guard let raw = storedTx.raw else {
LoggerProxy.debug("INCONSISTENCY: attempt to send pending transaction \(txId) that has not raw data")
throw TransactionManagerError.internalInconsistency(storedTx)
}
let response = try self.service.submit(spendTransaction: raw)
let transaction = try self.update(transaction: storedTx, on: response)
guard response.errorCode >= 0 else {
throw TransactionManagerError.submitFailed(transaction, errorCode: Int(response.errorCode))
}
return transaction
} catch {
try? self.updateOnFailure(transaction: pendingTransaction, error: error)
throw error
} }
} }

View File

@ -16,12 +16,12 @@ transactions through to completion.
protocol OutboundTransactionManager { protocol OutboundTransactionManager {
func initSpend(zatoshi: Zatoshi, toAddress: String, memo: String?, from accountIndex: Int) throws -> PendingTransactionEntity func initSpend(zatoshi: Zatoshi, toAddress: String, memo: String?, from accountIndex: Int) throws -> PendingTransactionEntity
func encodeShieldingTransaction(spendingKey: String, tsk: String, pendingTransaction: PendingTransactionEntity, result: @escaping (Result<PendingTransactionEntity, Error>) -> Void) func encodeShieldingTransaction(spendingKey: String, tsk: String, pendingTransaction: PendingTransactionEntity) async throws -> PendingTransactionEntity
func encode(spendingKey: String, pendingTransaction: PendingTransactionEntity, result: @escaping (Result<PendingTransactionEntity, Error>) -> Void) func encode(spendingKey: String, pendingTransaction: PendingTransactionEntity) async throws -> PendingTransactionEntity
func submit(pendingTransaction: PendingTransactionEntity, result: @escaping (Result<PendingTransactionEntity, Error>) -> Void) func submit(pendingTransaction: PendingTransactionEntity) async throws -> PendingTransactionEntity
func applyMinedHeight(pendingTransaction: PendingTransactionEntity, minedHeight: BlockHeight) throws -> PendingTransactionEntity func applyMinedHeight(pendingTransaction: PendingTransactionEntity, minedHeight: BlockHeight) throws -> PendingTransactionEntity
func monitorChanges(byId: Int, observer: Any) // check this out. code smell func monitorChanges(byId: Int, observer: Any) // check this out. code smell