From 23f06b9dd7ba1c5998bbf5a37e06af207d7cb997 Mon Sep 17 00:00:00 2001 From: Andrei Ashikhmin Date: Fri, 25 Aug 2023 20:34:10 +0700 Subject: [PATCH 01/32] fix: accept a prompt argument for identity.registerOnNetwork --- .../shared/Models/Identity/DSBlockchainIdentity.h | 4 ++-- .../shared/Models/Identity/DSBlockchainIdentity.m | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/DashSync/shared/Models/Identity/DSBlockchainIdentity.h b/DashSync/shared/Models/Identity/DSBlockchainIdentity.h index f2f7dd613..6f62e921c 100644 --- a/DashSync/shared/Models/Identity/DSBlockchainIdentity.h +++ b/DashSync/shared/Models/Identity/DSBlockchainIdentity.h @@ -227,9 +227,9 @@ FOUNDATION_EXPORT NSString *const DSBlockchainIdentityUpdateEventDashpaySyncroni // MARK: - Identity -- (void)registerOnNetwork:(DSBlockchainIdentityRegistrationStep)steps withFundingAccount:(DSAccount *)account forTopupAmount:(uint64_t)topupDuffAmount stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion; +- (void)registerOnNetwork:(DSBlockchainIdentityRegistrationStep)steps withFundingAccount:(DSAccount *)account forTopupAmount:(uint64_t)topupDuffAmount pinPrompt:(NSString *)prompt stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion; -- (void)continueRegisteringOnNetwork:(DSBlockchainIdentityRegistrationStep)steps withFundingAccount:(DSAccount *)fundingAccount forTopupAmount:(uint64_t)topupDuffAmount stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion; +- (void)continueRegisteringOnNetwork:(DSBlockchainIdentityRegistrationStep)steps withFundingAccount:(DSAccount *)fundingAccount forTopupAmount:(uint64_t)topupDuffAmount pinPrompt:(NSString *)prompt stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion; - (void)continueRegisteringIdentityOnNetwork:(DSBlockchainIdentityRegistrationStep)steps stepsCompleted:(DSBlockchainIdentityRegistrationStep)stepsAlreadyCompleted stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion; diff --git a/DashSync/shared/Models/Identity/DSBlockchainIdentity.m b/DashSync/shared/Models/Identity/DSBlockchainIdentity.m index 8b4c4b682..f62ffd288 100644 --- a/DashSync/shared/Models/Identity/DSBlockchainIdentity.m +++ b/DashSync/shared/Models/Identity/DSBlockchainIdentity.m @@ -477,13 +477,13 @@ - (void)continueRegisteringIdentityOnNetwork:(DSBlockchainIdentityRegistrationSt }]; } -- (void)continueRegisteringOnNetwork:(DSBlockchainIdentityRegistrationStep)steps withFundingAccount:(DSAccount *)fundingAccount forTopupAmount:(uint64_t)topupDuffAmount stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion { - [self continueRegisteringOnNetwork:steps withFundingAccount:fundingAccount forTopupAmount:topupDuffAmount inContext:self.platformContext stepCompletion:stepCompletion completion:completion]; +- (void)continueRegisteringOnNetwork:(DSBlockchainIdentityRegistrationStep)steps withFundingAccount:(DSAccount *)fundingAccount forTopupAmount:(uint64_t)topupDuffAmount pinPrompt:(NSString *)prompt stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion { + [self continueRegisteringOnNetwork:steps withFundingAccount:fundingAccount forTopupAmount:topupDuffAmount pinPrompt:prompt inContext:self.platformContext stepCompletion:stepCompletion completion:completion]; } -- (void)continueRegisteringOnNetwork:(DSBlockchainIdentityRegistrationStep)steps withFundingAccount:(DSAccount *)fundingAccount forTopupAmount:(uint64_t)topupDuffAmount inContext:(NSManagedObjectContext *)context stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion { +- (void)continueRegisteringOnNetwork:(DSBlockchainIdentityRegistrationStep)steps withFundingAccount:(DSAccount *)fundingAccount forTopupAmount:(uint64_t)topupDuffAmount pinPrompt:(NSString *)prompt inContext:(NSManagedObjectContext *)context stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion { if (!self.registrationCreditFundingTransaction) { - [self registerOnNetwork:steps withFundingAccount:fundingAccount forTopupAmount:topupDuffAmount stepCompletion:stepCompletion completion:completion]; + [self registerOnNetwork:steps withFundingAccount:fundingAccount forTopupAmount:topupDuffAmount pinPrompt:prompt stepCompletion:stepCompletion completion:completion]; } else if (self.registrationStatus != DSBlockchainIdentityRegistrationStatus_Registered) { [self continueRegisteringIdentityOnNetwork:steps stepsCompleted:DSBlockchainIdentityRegistrationStep_L1Steps stepCompletion:stepCompletion completion:completion]; } else if ([self.unregisteredUsernameFullPaths count]) { @@ -494,7 +494,7 @@ - (void)continueRegisteringOnNetwork:(DSBlockchainIdentityRegistrationStep)steps } -- (void)registerOnNetwork:(DSBlockchainIdentityRegistrationStep)steps withFundingAccount:(DSAccount *)fundingAccount forTopupAmount:(uint64_t)topupDuffAmount stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion { +- (void)registerOnNetwork:(DSBlockchainIdentityRegistrationStep)steps withFundingAccount:(DSAccount *)fundingAccount forTopupAmount:(uint64_t)topupDuffAmount pinPrompt:(NSString *)prompt stepCompletion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepCompleted))stepCompletion completion:(void (^_Nullable)(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *error))completion { __block DSBlockchainIdentityRegistrationStep stepsCompleted = DSBlockchainIdentityRegistrationStep_None; if (![self hasBlockchainIdentityExtendedPublicKeys]) { if (completion) { @@ -526,7 +526,7 @@ - (void)registerOnNetwork:(DSBlockchainIdentityRegistrationStep)steps withFundin return; } [fundingAccount signTransaction:fundingTransaction - withPrompt:@"Would you like to create this user?" + withPrompt:prompt completion:^(BOOL signedTransaction, BOOL cancelled) { if (!signedTransaction) { if (completion) { From cf0ff78b58f5c17935e78a8b4398b6dbd4e3d77e Mon Sep 17 00:00:00 2001 From: pankcuf Date: Tue, 24 Oct 2023 18:26:55 +0700 Subject: [PATCH 02/32] chore: silence c warnings --- DashSync/shared/Categories/NSData/NSMutableData+Dash.m | 2 +- .../Networking/Private/SPTDataLoaderExponentialTimer.m | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/DashSync/shared/Categories/NSData/NSMutableData+Dash.m b/DashSync/shared/Categories/NSData/NSMutableData+Dash.m index a4865b010..4a79f9667 100644 --- a/DashSync/shared/Categories/NSData/NSMutableData+Dash.m +++ b/DashSync/shared/Categories/NSData/NSMutableData+Dash.m @@ -65,7 +65,7 @@ static void secureDeallocate(void *ptr, void *info) { } // Since iOS does not page memory to storage, all we need to do is cleanse allocated memory prior to deallocation. -CFAllocatorRef SecureAllocator() { +CFAllocatorRef SecureAllocator(void) { static CFAllocatorRef alloc = NULL; static dispatch_once_t onceToken = 0; diff --git a/DashSync/shared/Libraries/Networking/Private/SPTDataLoaderExponentialTimer.m b/DashSync/shared/Libraries/Networking/Private/SPTDataLoaderExponentialTimer.m index 3693a1c9c..dc48ff635 100644 --- a/DashSync/shared/Libraries/Networking/Private/SPTDataLoaderExponentialTimer.m +++ b/DashSync/shared/Libraries/Networking/Private/SPTDataLoaderExponentialTimer.m @@ -128,7 +128,7 @@ - (NSTimeInterval)timeIntervalAndCalculateNext { #define EXPT_MODULO ((u_int32_t)RAND_MAX) #define EXPT_MODULO_F64 ((double)(EXPT_MODULO)) -NS_INLINE double SPTExptRandom() { +NS_INLINE double SPTExptRandom(void) { // We need [0, 1) interval return arc4random_uniform(EXPT_MODULO); } From 3585d27f7fda069058ebfe8a9a95ad3048700230 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Tue, 24 Oct 2023 18:28:29 +0700 Subject: [PATCH 03/32] feat: core v0.20 support: dash_shared_core changes adaptation --- .../DashSync.xcdatamodeld/.xccurrentversion | 2 +- .../DashSync 20.xcdatamodel/contents | 518 ++++++++++++++++++ .../shared/Models/Chain/DSChainConstants.h | 4 +- DashSync/shared/Models/Chain/DSChainLock.m | 4 +- DashSync/shared/Models/Chain/DSFullBlock.m | 2 +- ...SCoinbaseTransactionEntity+CoreDataClass.m | 19 + ...baseTransactionEntity+CoreDataProperties.h | 6 + ...baseTransactionEntity+CoreDataProperties.m | 4 + .../Managers/Chain Managers/DSChainManager.m | 2 +- .../DSMasternodeManager+Mndiff.h | 2 +- .../DSMasternodeManager+Mndiff.m | 32 +- .../DSMasternodeManager+Protected.h | 2 +- .../Chain Managers/DSMasternodeManager.h | 4 + .../Chain Managers/DSMasternodeManager.m | 59 +- .../Masternode/DSMasternodeList+Mndiff.m | 2 +- .../Masternode/DSMasternodeListService.m | 1 - .../Models/Masternode/DSMasternodeListStore.h | 4 +- .../Models/Masternode/DSMasternodeListStore.m | 4 +- .../Masternode/DSMasternodeProcessorContext.h | 3 + .../Masternode/DSMasternodeProcessorContext.m | 11 + .../Masternode/DSMnDiffProcessingResult.h | 2 +- .../Masternode/DSMnDiffProcessingResult.m | 6 +- .../Models/Masternode/DSQuorumEntry+Mndiff.h | 3 +- .../Models/Masternode/DSQuorumEntry+Mndiff.m | 10 +- .../shared/Models/Masternode/DSQuorumEntry.h | 2 +- .../shared/Models/Masternode/DSQuorumEntry.m | 7 +- .../Internal/DSCoreDataMigrationVersion.h | 1 + .../Internal/DSCoreDataMigrationVersion.m | 1 + .../Coinbase/DSCoinbaseTransaction+Mndiff.m | 1 - .../Coinbase/DSCoinbaseTransaction.h | 4 +- .../Coinbase/DSCoinbaseTransaction.m | 39 +- .../xcschemes/DashSync-Example.xcscheme | 5 + Example/DashSync/DSPeersViewController.m | 2 +- Example/Podfile | 4 +- Example/Podfile.lock | 14 +- .../DSDeterministicMasternodeListTests.m | 30 +- 36 files changed, 729 insertions(+), 87 deletions(-) create mode 100644 DashSync/shared/DashSync.xcdatamodeld/DashSync 20.xcdatamodel/contents diff --git a/DashSync/shared/DashSync.xcdatamodeld/.xccurrentversion b/DashSync/shared/DashSync.xcdatamodeld/.xccurrentversion index 7bc3c9385..5cbe4fe8d 100644 --- a/DashSync/shared/DashSync.xcdatamodeld/.xccurrentversion +++ b/DashSync/shared/DashSync.xcdatamodeld/.xccurrentversion @@ -3,6 +3,6 @@ _XCCurrentVersionName - DashSync 19.xcdatamodel + DashSync 20.xcdatamodel diff --git a/DashSync/shared/DashSync.xcdatamodeld/DashSync 20.xcdatamodel/contents b/DashSync/shared/DashSync.xcdatamodeld/DashSync 20.xcdatamodel/contents new file mode 100644 index 000000000..559561efb --- /dev/null +++ b/DashSync/shared/DashSync.xcdatamodeld/DashSync 20.xcdatamodel/contents @@ -0,0 +1,518 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/DashSync/shared/Models/Chain/DSChainConstants.h b/DashSync/shared/Models/Chain/DSChainConstants.h index f352c2000..7776a9e2a 100644 --- a/DashSync/shared/Models/Chain/DSChainConstants.h +++ b/DashSync/shared/Models/Chain/DSChainConstants.h @@ -34,10 +34,10 @@ #define PROTOCOL_VERSION_MAINNET 70228 #define DEFAULT_MIN_PROTOCOL_VERSION_MAINNET 70228 -#define PROTOCOL_VERSION_TESTNET 70228 +#define PROTOCOL_VERSION_TESTNET 70230 #define DEFAULT_MIN_PROTOCOL_VERSION_TESTNET 70228 -#define PROTOCOL_VERSION_DEVNET 70228 +#define PROTOCOL_VERSION_DEVNET 70230 #define DEFAULT_MIN_PROTOCOL_VERSION_DEVNET 70228 #define PLATFORM_PROTOCOL_VERSION_MAINNET 1 diff --git a/DashSync/shared/Models/Chain/DSChainLock.m b/DashSync/shared/Models/Chain/DSChainLock.m index 2f5b0ed9d..8413cc2df 100644 --- a/DashSync/shared/Models/Chain/DSChainLock.m +++ b/DashSync/shared/Models/Chain/DSChainLock.m @@ -119,9 +119,9 @@ - (BOOL)verifySignatureAgainstQuorum:(DSQuorumEntry *)quorumEntry { UInt256 signId = [self signIDForQuorumEntry:quorumEntry]; BOOL verified = key_bls_verify(quorumEntry.quorumPublicKey.u8, quorumEntry.useLegacyBLSScheme, signId.u8, self.signature.u8); #if DEBUG - DSLog(@"verifySignatureAgainstQuorum (%u): %u: %u: %@: %@: %@: %@: %u", verified, quorumEntry.llmqType, quorumEntry.verified, uint256_hex(quorumEntry.llmqQuorumHash), @"", uint384_hex(quorumEntry.quorumPublicKey), @"", quorumEntry.useLegacyBLSScheme); + DSLog(@"verifySignatureAgainstQuorum (%u): %u: %u: %@: %@: %@: %@: %u", verified, quorumEntry.llmqType, quorumEntry.verified, uint256_hex([quorumEntry buildQuorumHash:nil]), @"", uint384_hex(quorumEntry.quorumPublicKey), @"", quorumEntry.useLegacyBLSScheme); #else - DSLogPrivate(@"verifySignatureAgainstQuorum (%u): %u: %u: %@: %@: %@: %@: %u", verified, quorumEntry.llmqType, quorumEntry.verified, uint256_hex(quorumEntry.llmqQuorumHash), uint256_hex(signId), uint384_hex(quorumEntry.quorumPublicKey), uint768_hex(self.signature), quorumEntry.useLegacyBLSScheme); + DSLogPrivate(@"verifySignatureAgainstQuorum (%u): %u: %u: %@: %@: %@: %@: %u", verified, quorumEntry.llmqType, quorumEntry.verified, uint256_hex([quorumEntry buildQuorumHash:nil]), uint256_hex(signId), uint384_hex(quorumEntry.quorumPublicKey), uint768_hex(self.signature), quorumEntry.useLegacyBLSScheme); #endif return verified; } diff --git a/DashSync/shared/Models/Chain/DSFullBlock.m b/DashSync/shared/Models/Chain/DSFullBlock.m index 3f486b019..cc268d002 100644 --- a/DashSync/shared/Models/Chain/DSFullBlock.m +++ b/DashSync/shared/Models/Chain/DSFullBlock.m @@ -99,7 +99,7 @@ - (instancetype)initWithMessage:(NSData *)message onChain:(DSChain *)chain { } - (instancetype)initWithCoinbaseTransaction:(DSCoinbaseTransaction *)coinbaseTransaction transactions:(NSSet *)transactions previousBlockHash:(UInt256)previousBlockHash previousBlocks:(NSDictionary *)previousBlocks timestamp:(uint32_t)timestamp height:(uint32_t)height onChain:(DSChain *)chain { - if (!(self = [super initWithVersion:2 timestamp:timestamp height:height onChain:chain])) return nil; + if (!(self = [super initWithVersion:COINBASE_TX_CORE_19 timestamp:timestamp height:height onChain:chain])) return nil; NSMutableSet *totalTransactionsSet = [transactions mutableCopy]; [totalTransactionsSet addObject:coinbaseTransaction]; self.totalTransactions = (uint32_t)[totalTransactionsSet count]; diff --git a/DashSync/shared/Models/Entities/DSCoinbaseTransactionEntity+CoreDataClass.m b/DashSync/shared/Models/Entities/DSCoinbaseTransactionEntity+CoreDataClass.m index 80299c462..ef06f6804 100644 --- a/DashSync/shared/Models/Entities/DSCoinbaseTransactionEntity+CoreDataClass.m +++ b/DashSync/shared/Models/Entities/DSCoinbaseTransactionEntity+CoreDataClass.m @@ -20,6 +20,14 @@ - (instancetype)setAttributesFromTransaction:(DSTransaction *)tx { self.specialTransactionVersion = coinbaseTransaction.coinbaseTransactionVersion; self.height = coinbaseTransaction.height; self.merkleRootMNList = uint256_data(coinbaseTransaction.merkleRootMNList); + if (self.specialTransactionVersion >= COINBASE_TX_CORE_19) { + self.merkleRootLLMQList = uint256_data(coinbaseTransaction.merkleRootLLMQList); + if (self.specialTransactionVersion >= COINBASE_TX_CORE_20) { + self.bestCLHeightDiff = coinbaseTransaction.bestCLHeightDiff; + self.bestCLSignature = uint768_data(coinbaseTransaction.bestCLSignature); + self.creditPoolBalance = coinbaseTransaction.creditPoolBalance; + } + } }]; return self; @@ -32,11 +40,22 @@ - (DSTransaction *)transactionForChain:(DSChain *)chain { transaction.coinbaseTransactionVersion = self.specialTransactionVersion; transaction.height = self.height; transaction.merkleRootMNList = self.merkleRootMNList.UInt256; + + if (self.specialTransactionVersion >= COINBASE_TX_CORE_19) { + transaction.merkleRootLLMQList = self.merkleRootLLMQList.UInt256; + if (self.specialTransactionVersion >= COINBASE_TX_CORE_20) { + transaction.bestCLHeightDiff = self.bestCLHeightDiff; + transaction.bestCLSignature = self.bestCLSignature.UInt768; + transaction.creditPoolBalance = self.creditPoolBalance; + } + } }]; return transaction; } + + - (Class)transactionClass { return [DSCoinbaseTransaction class]; } diff --git a/DashSync/shared/Models/Entities/DSCoinbaseTransactionEntity+CoreDataProperties.h b/DashSync/shared/Models/Entities/DSCoinbaseTransactionEntity+CoreDataProperties.h index ce6fc7c70..c6e29af60 100644 --- a/DashSync/shared/Models/Entities/DSCoinbaseTransactionEntity+CoreDataProperties.h +++ b/DashSync/shared/Models/Entities/DSCoinbaseTransactionEntity+CoreDataProperties.h @@ -16,7 +16,13 @@ NS_ASSUME_NONNULL_BEGIN + (NSFetchRequest *)fetchRequest; @property (assign, nonatomic) uint32_t height; + @property (nullable, nonatomic, retain) NSData *merkleRootMNList; +@property (nullable, nonatomic, retain) NSData *merkleRootLLMQList; + +@property (assign, nonatomic) uint32_t bestCLHeightDiff; +@property (nullable, nonatomic, retain) NSData *bestCLSignature; +@property (assign, nonatomic) int64_t creditPoolBalance; @end diff --git a/DashSync/shared/Models/Entities/DSCoinbaseTransactionEntity+CoreDataProperties.m b/DashSync/shared/Models/Entities/DSCoinbaseTransactionEntity+CoreDataProperties.m index c83ac6d9c..22a99d984 100644 --- a/DashSync/shared/Models/Entities/DSCoinbaseTransactionEntity+CoreDataProperties.m +++ b/DashSync/shared/Models/Entities/DSCoinbaseTransactionEntity+CoreDataProperties.m @@ -16,5 +16,9 @@ @implementation DSCoinbaseTransactionEntity (CoreDataProperties) @dynamic height; @dynamic merkleRootMNList; +@dynamic merkleRootLLMQList; +@dynamic bestCLHeightDiff; +@dynamic bestCLSignature; +@dynamic creditPoolBalance; @end diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m index 3d43643c8..ac679349f 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m @@ -676,7 +676,7 @@ - (void)chainFinishedSyncingTransactionsAndBlocks:(DSChain *)chain fromPeer:(DSP } - (void)syncBlockchain { - DSLog(@"syncBlockchain connected peers: %d phase: %d", self.peerManager.connectedPeerCount, self.syncPhase); + DSLog(@"syncBlockchain connected peers: %lu phase: %d", self.peerManager.connectedPeerCount, self.syncPhase); if (self.peerManager.connectedPeerCount == 0) { if (self.syncPhase == DSChainSyncPhase_InitialTerminalBlocks) { self.syncPhase = DSChainSyncPhase_ChainSync; diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.h b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.h index faff3b684..e94622df3 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.h +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.h @@ -34,7 +34,7 @@ NS_ASSUME_NONNULL_BEGIN MasternodeList *getMasternodeListByBlockHash(uint8_t (*block_hash)[32], const void *context); bool saveMasternodeList(uint8_t (*block_hash)[32], MasternodeList *masternode_list, const void *context); void destroyMasternodeList(MasternodeList *masternode_list); -void destroyHash(uint8_t *block_hash); +void destroyU8(uint8_t *block_hash); uint32_t getBlockHeightByHash(uint8_t (*block_hash)[32], const void *context); uint8_t *getBlockHashByHeight(uint32_t block_height, const void *context); uint8_t *getMerkleRootByHash(uint8_t (*block_hash)[32], const void *context); diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.m b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.m index b308e0d99..8c9e644f6 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.m @@ -68,7 +68,7 @@ void destroyMasternodeList(MasternodeList *masternode_list) { [DSMasternodeList ffi_free:masternode_list]; } -void destroyHash(uint8_t *block_hash) { // UInt256 +void destroyU8(uint8_t *block_hash) { // big uint if (block_hash) { free(block_hash); } @@ -149,13 +149,33 @@ void destroyLLMQSnapshot(LLMQSnapshot *snapshot) { [DSQuorumSnapshot ffi_free:snapshot]; } -void addInsightForBlockHash(uint8_t (*block_hash)[32], const void *context) { +uint8_t *getCLSignatureByBlockHash(uint8_t (*block_hash)[32], const void *context) { DSMasternodeProcessorContext *processorContext = NULL; UInt256 blockHash = *((UInt256 *)block_hash); + uint8_t (*cl_signature)[96] = NULL; @synchronized (context) { processorContext = (__bridge DSMasternodeProcessorContext *)context; - DSChain *chain = processorContext.chain; - [chain blockUntilGetInsightForBlockHash:blockHash]; + NSData *signature = [processorContext.chain.chainManager.masternodeManager CLSignatureForBlockHash:blockHash]; + if (signature) { + cl_signature = uint768_malloc(signature.UInt768); + } + } + processor_destroy_block_hash(block_hash); + return (uint8_t *)cl_signature; +} +bool saveCLSignature(uint8_t (*block_hash)[32], uint8_t (*cl_signature)[96], const void *context) { + BOOL saved = NO; + @synchronized (context) { + saved = [(__bridge DSMasternodeProcessorContext *)context saveCLSignature:*((UInt256 *)block_hash) signature:*((UInt768 *)cl_signature)]; + } + processor_destroy_block_hash(block_hash); + processor_destroy_cl_signature(cl_signature); + return saved; +} + +void addInsightForBlockHash(uint8_t (*block_hash)[32], const void *context) { + @synchronized (context) { + [(__bridge DSMasternodeProcessorContext *)context blockUntilGetInsightForBlockHash:*((UInt256 *)block_hash)]; } processor_destroy_block_hash(block_hash); } @@ -215,11 +235,13 @@ + (MasternodeProcessor *)registerProcessor { getBlockHashByHeight, getLLMQSnapshotByBlockHash, saveLLMQSnapshot, + getCLSignatureByBlockHash, + saveCLSignature, getMasternodeListByBlockHash, saveMasternodeList, destroyMasternodeList, addInsightForBlockHash, - destroyHash, + destroyU8, destroyLLMQSnapshot, shouldProcessDiffWithRange); } diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Protected.h b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Protected.h index 32b8f8e07..c5b813f93 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Protected.h +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Protected.h @@ -46,7 +46,7 @@ NS_ASSUME_NONNULL_BEGIN - (DSLocalMasternode *)localMasternodeFromSimplifiedMasternodeEntry:(DSSimplifiedMasternodeEntry *)simplifiedMasternodeEntry claimedWithOwnerWallet:(DSWallet *)wallet ownerKeyIndex:(uint32_t)ownerKeyIndex; -+ (void)saveMasternodeList:(DSMasternodeList *)masternodeList toChain:(DSChain *)chain havingModifiedMasternodes:(NSDictionary *)modifiedMasternodes addedQuorums:(NSDictionary *)addedQuorums createUnknownBlocks:(BOOL)createUnknownBlocks inContext:(NSManagedObjectContext *)context completion:(void (^)(NSError *error))completion; ++ (void)saveMasternodeList:(DSMasternodeList *)masternodeList toChain:(DSChain *)chain havingModifiedMasternodes:(NSDictionary *)modifiedMasternodes createUnknownBlocks:(BOOL)createUnknownBlocks inContext:(NSManagedObjectContext *)context completion:(void (^)(NSError *error))completion; @end diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.h b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.h index 3f78b4f48..aeba8e9ab 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.h +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.h @@ -86,6 +86,10 @@ NS_ASSUME_NONNULL_BEGIN - (BOOL)saveQuorumSnapshot:(DSQuorumSnapshot *)snapshot; - (BOOL)saveMasternodeList:(DSMasternodeList *)masternodeList forBlockHash:(UInt256)blockHash; +- (NSData *_Nullable)CLSignatureForBlockHeight:(uint32_t)blockHeight; +- (NSData *_Nullable)CLSignatureForBlockHash:(UInt256)blockHash; +- (BOOL)saveCLSignature:(NSData *)blockHashData signatureData:(NSData *)signatureData; + - (void)startSync; - (BOOL)requestMasternodeListForBlockHeight:(uint32_t)blockHeight error:(NSError *_Nullable *_Nullable)error; - (BOOL)requestMasternodeListForBlockHash:(UInt256)blockHash; diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m index bdb984a3d..79c90f2c7 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m @@ -297,6 +297,27 @@ - (BOOL)saveQuorumSnapshot:(DSQuorumSnapshot *)snapshot { return YES; } +// MARK: - ChainLock Signature List Helpers +- (NSData *_Nullable)CLSignatureForBlockHeight:(uint32_t)blockHeight { + DSBlock *block = [self.chain blockAtHeight:blockHeight]; + if (!block) { + DSLog(@"No block for snapshot at height: %ul: ", blockHeight); + return nil; + } + return [self.store.cachedCLSignatures objectForKey:uint256_data(block.blockHash)]; +} + +- (NSData *_Nullable)CLSignatureForBlockHash:(UInt256)blockHash { + return [self.store.cachedCLSignatures objectForKey:uint256_data(blockHash)]; +} + +- (BOOL)saveCLSignature:(NSData *)blockHashData signatureData:(NSData *)signatureData { + [self.store.cachedCLSignatures setObject:signatureData forKey:blockHashData]; + return YES; +} + +// MARK: - Masternode List Helpers + - (BOOL)saveMasternodeList:(DSMasternodeList *)masternodeList forBlockHash:(UInt256)blockHash { /// TODO: need to properly store in CoreData or wait for rust SQLite DSLog(@"••• addMasternodeList (saveMasternodeList) -> %@: %@", uint256_hex(blockHash), masternodeList); @@ -304,8 +325,6 @@ - (BOOL)saveMasternodeList:(DSMasternodeList *)masternodeList forBlockHash:(UInt return YES; } -// MARK: - Masternode List Helpers - - (DSMasternodeList *)masternodeListForBlockHash:(UInt256)blockHash { return [self masternodeListForBlockHash:blockHash withBlockHeightLookup:nil]; } @@ -411,7 +430,6 @@ - (DSMasternodeList *__nullable)processRequestFromFileForBlockHash:(UInt256)bloc [self.store saveMasternodeList:masternodeList addedMasternodes:result.addedMasternodes modifiedMasternodes:result.modifiedMasternodes - addedQuorums:result.addedQuorums completion:^(NSError *_Nonnull error) { DSLog(@"MNL Saved from file"); }]; @@ -522,7 +540,7 @@ - (void)processMasternodeListDiffResult:(DSMnDiffProcessingResult *)result forPe } } DSLog(@"••• updateStoreWithMasternodeList: %u: %@ (%@)", masternodeList.height, uint256_hex(masternodeListBlockHash), uint256_reverse_hex(masternodeListBlockHash)); - [self updateStoreWithMasternodeList:masternodeList addedMasternodes:result.addedMasternodes modifiedMasternodes:result.modifiedMasternodes addedQuorums:result.addedQuorums completion:^(NSError *error) { + [self updateStoreWithMasternodeList:masternodeList addedMasternodes:result.addedMasternodes modifiedMasternodes:result.modifiedMasternodes completion:^(NSError *error) { if ([result hasRotatedQuorumsForChain:self.chain] && !self.chain.isRotatedQuorumsPresented) { uint32_t masternodeListBlockHeight = [self heightForBlockHash:masternodeListBlockHash]; DSLog(@"•••• processMasternodeListDiffResult: rotated quorums are presented at height %u: %@, so we'll switch into consuming qrinfo", masternodeListBlockHeight, uint256_hex(masternodeListBlockHash)); @@ -598,31 +616,31 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH4C count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH4C]) { DSLog(@"••• updateStoreWithMasternodeList (h-4c): %u: %@ (%@)", masternodeListAtH4C.height, uint256_hex(blockHashAtH4C), uint256_reverse_hex(blockHashAtH4C)); - [self updateStoreWithMasternodeList:masternodeListAtH4C addedMasternodes:mnListDiffResultAtH4C.addedMasternodes modifiedMasternodes:mnListDiffResultAtH4C.modifiedMasternodes addedQuorums:mnListDiffResultAtH4C.addedQuorums completion:^(NSError *error) {}]; + [self updateStoreWithMasternodeList:masternodeListAtH4C addedMasternodes:mnListDiffResultAtH4C.addedMasternodes modifiedMasternodes:mnListDiffResultAtH4C.modifiedMasternodes completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH3C skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH3C count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH3C]) { DSLog(@"••• updateStoreWithMasternodeList (h-3c): %u: %@ (%@)", masternodeListAtH3C.height, uint256_hex(blockHashAtH3C), uint256_reverse_hex(blockHashAtH3C)); - [self updateStoreWithMasternodeList:masternodeListAtH3C addedMasternodes:mnListDiffResultAtH3C.addedMasternodes modifiedMasternodes:mnListDiffResultAtH3C.modifiedMasternodes addedQuorums:mnListDiffResultAtH3C.addedQuorums completion:^(NSError *error) {}]; + [self updateStoreWithMasternodeList:masternodeListAtH3C addedMasternodes:mnListDiffResultAtH3C.addedMasternodes modifiedMasternodes:mnListDiffResultAtH3C.modifiedMasternodes completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH2C skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH2C count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH2C]) { DSLog(@"••• updateStoreWithMasternodeList (h-2c): %u: %@ (%@)", masternodeListAtH2C.height, uint256_hex(blockHashAtH2C), uint256_reverse_hex(blockHashAtH2C)); - [self updateStoreWithMasternodeList:masternodeListAtH2C addedMasternodes:mnListDiffResultAtH2C.addedMasternodes modifiedMasternodes:mnListDiffResultAtH2C.modifiedMasternodes addedQuorums:mnListDiffResultAtH2C.addedQuorums completion:^(NSError *error) {}]; + [self updateStoreWithMasternodeList:masternodeListAtH2C addedMasternodes:mnListDiffResultAtH2C.addedMasternodes modifiedMasternodes:mnListDiffResultAtH2C.modifiedMasternodes completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtHC skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtHC count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtHC]) { DSLog(@"••• updateStoreWithMasternodeList (h-c): %u: %@ (%@)", masternodeListAtHC.height, uint256_hex(blockHashAtHC), uint256_reverse_hex(blockHashAtHC)); - [self updateStoreWithMasternodeList:masternodeListAtHC addedMasternodes:mnListDiffResultAtHC.addedMasternodes modifiedMasternodes:mnListDiffResultAtHC.modifiedMasternodes addedQuorums:mnListDiffResultAtHC.addedQuorums completion:^(NSError *error) {}]; + [self updateStoreWithMasternodeList:masternodeListAtHC addedMasternodes:mnListDiffResultAtHC.addedMasternodes modifiedMasternodes:mnListDiffResultAtHC.modifiedMasternodes completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH]) { DSLog(@"••• updateStoreWithMasternodeList (h): %u: %@ (%@)", masternodeListAtH.height, uint256_hex(blockHashAtH), uint256_reverse_hex(blockHashAtH)); - [self updateStoreWithMasternodeList:masternodeListAtH addedMasternodes:mnListDiffResultAtH.addedMasternodes modifiedMasternodes:mnListDiffResultAtH.modifiedMasternodes addedQuorums:mnListDiffResultAtH.addedQuorums completion:^(NSError *error) {}]; + [self updateStoreWithMasternodeList:masternodeListAtH addedMasternodes:mnListDiffResultAtH.addedMasternodes modifiedMasternodes:mnListDiffResultAtH.modifiedMasternodes completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtTip skipPresenceInRetrieval:YES]) { @@ -639,7 +657,7 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * } } DSLog(@"••• updateStoreWithMasternodeList (tip): %u: %@ (%@)", masternodeListAtTip.height, uint256_hex(blockHashAtTip), uint256_reverse_hex(blockHashAtTip)); - [self updateStoreWithMasternodeList:masternodeListAtTip addedMasternodes:mnListDiffResultAtTip.addedMasternodes modifiedMasternodes:mnListDiffResultAtTip.modifiedMasternodes addedQuorums:mnListDiffResultAtTip.addedQuorums completion:^(NSError *error) {}]; + [self updateStoreWithMasternodeList:masternodeListAtTip addedMasternodes:mnListDiffResultAtTip.addedMasternodes modifiedMasternodes:mnListDiffResultAtTip.modifiedMasternodes completion:^(NSError *error) {}]; [self.quorumRotationService updateAfterProcessingMasternodeListWithBlockHash:blockHashDataAtTip fromPeer:peer]; } } @@ -657,7 +675,7 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * if (![self.quorumRotationService shouldProcessDiffResult:diffResult skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![diffResult.neededMissingMasternodeLists count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:diffBlockHashData]) { - [self updateStoreWithMasternodeList:diffMasternodeList addedMasternodes:diffResult.addedMasternodes modifiedMasternodes:diffResult.modifiedMasternodes addedQuorums:diffResult.addedQuorums completion:^(NSError *error) {}]; + [self updateStoreWithMasternodeList:diffMasternodeList addedMasternodes:diffResult.addedMasternodes modifiedMasternodes:diffResult.modifiedMasternodes completion:^(NSError *error) {}]; } } for (DSQuorumSnapshot *snapshot in result.snapshotList) { @@ -665,7 +683,7 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * } for (DSQuorumEntry *entry in result.lastQuorumPerIndex) { - [self.store.activeQuorums setObject:entry forKey:uint256_data(entry.llmqQuorumHash)]; + [self.store.activeQuorums setObject:entry forKey:uint256_data([entry buildQuorumHash:nil])]; } } @@ -678,14 +696,13 @@ - (void)processMissingMasternodeLists:(NSOrderedSet *)neededMissingMasternodeLis [self getMasternodeListsForBlockHashes:neededMasternodeLists]; } -- (void)updateStoreWithMasternodeList:(DSMasternodeList *)masternodeList addedMasternodes:(NSDictionary *)addedMasternodes modifiedMasternodes:(NSDictionary *)modifiedMasternodes addedQuorums:(NSDictionary *)addedQuorums completion:(void (^)(NSError *error))completion { +- (void)updateStoreWithMasternodeList:(DSMasternodeList *)masternodeList addedMasternodes:(NSDictionary *)addedMasternodes modifiedMasternodes:(NSDictionary *)modifiedMasternodes completion:(void (^)(NSError *error))completion { if (uint256_eq(self.store.masternodeListAwaitingQuorumValidation.blockHash, masternodeList.blockHash)) { self.store.masternodeListAwaitingQuorumValidation = nil; } [self.store saveMasternodeList:masternodeList addedMasternodes:addedMasternodes modifiedMasternodes:modifiedMasternodes - addedQuorums:addedQuorums completion:^(NSError *error) { completion(error); if (!error || !([self.masternodeListDiffService retrievalQueueCount] + [self.quorumRotationService retrievalQueueCount])) { //if it is 0 then we most likely have wiped chain info @@ -802,8 +819,18 @@ - (BOOL)hasMasternodeListCurrentlyBeingSaved { return [self.store hasMasternodeListCurrentlyBeingSaved]; } -+ (void)saveMasternodeList:(DSMasternodeList *)masternodeList toChain:(DSChain *)chain havingModifiedMasternodes:(NSDictionary *)modifiedMasternodes addedQuorums:(NSDictionary *)addedQuorums createUnknownBlocks:(BOOL)createUnknownBlocks inContext:(NSManagedObjectContext *)context completion:(void (^)(NSError *error))completion { - [DSMasternodeListStore saveMasternodeList:masternodeList toChain:chain havingModifiedMasternodes:modifiedMasternodes addedQuorums:addedQuorums createUnknownBlocks:createUnknownBlocks inContext:context completion:completion]; ++ (void)saveMasternodeList:(DSMasternodeList *)masternodeList + toChain:(DSChain *)chain + havingModifiedMasternodes:(NSDictionary *)modifiedMasternodes + createUnknownBlocks:(BOOL)createUnknownBlocks + inContext:(NSManagedObjectContext *)context + completion:(void (^)(NSError *error))completion { + [DSMasternodeListStore saveMasternodeList:masternodeList + toChain:chain + havingModifiedMasternodes:modifiedMasternodes + createUnknownBlocks:createUnknownBlocks + inContext:context + completion:completion]; } // MARK: - Quorums diff --git a/DashSync/shared/Models/Masternode/DSMasternodeList+Mndiff.m b/DashSync/shared/Models/Masternode/DSMasternodeList+Mndiff.m index a7c22a838..7eb40bdd4 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeList+Mndiff.m +++ b/DashSync/shared/Models/Masternode/DSMasternodeList+Mndiff.m @@ -26,7 +26,7 @@ @implementation DSMasternodeList (Mndiff) + (instancetype)masternodeListWith:(MasternodeList *)list onChain:(DSChain *)chain { uintptr_t masternodes_count = list->masternodes_count; NSDictionary *masternodes = [DSSimplifiedMasternodeEntry simplifiedEntriesWith:list->masternodes count:masternodes_count onChain:chain]; - NSDictionary *> *quorums = [DSQuorumEntry entriesWith:list->llmq_type_maps count:list->llmq_type_maps_count onChain:chain]; + NSDictionary *> *quorums = [DSQuorumEntry entriesWithMap:list->llmq_type_maps count:list->llmq_type_maps_count onChain:chain]; UInt256 masternodeMerkleRoot = list->masternode_merkle_root ? *((UInt256 *)list->masternode_merkle_root) : UINT256_ZERO; UInt256 quorumMerkleRoot = list->llmq_merkle_root ? *((UInt256 *)list->llmq_merkle_root) : UINT256_ZERO; UInt256 blockHash = *((UInt256 *)list->block_hash); diff --git a/DashSync/shared/Models/Masternode/DSMasternodeListService.m b/DashSync/shared/Models/Masternode/DSMasternodeListService.m index 0c1546362..3bdc7a787 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeListService.m +++ b/DashSync/shared/Models/Masternode/DSMasternodeListService.m @@ -69,7 +69,6 @@ - (void)startTimeOutObserver { } dispatch_after(timeout, self.chain.networkingQueue, ^{ __block NSSet *requestsInRetrieval2; - __block NSUInteger masternodeListCount2; @synchronized (self) { if (!self.retrievalQueueMaxAmount || self.timeOutObserverTry != timeOutObserverTry) { return; diff --git a/DashSync/shared/Models/Masternode/DSMasternodeListStore.h b/DashSync/shared/Models/Masternode/DSMasternodeListStore.h index 6f4115ccc..f63207b00 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeListStore.h +++ b/DashSync/shared/Models/Masternode/DSMasternodeListStore.h @@ -44,6 +44,7 @@ FOUNDATION_EXPORT NSString *const DSQuorumListDidChangeNotification; @property (nonatomic, readonly) BOOL masternodeListsAndQuorumsIsSynced; @property (nonatomic, readonly) NSMutableDictionary *cachedQuorumSnapshots; +@property (nonatomic, readonly) NSMutableDictionary *cachedCLSignatures; - (instancetype)initWithChain:(DSChain *)chain; - (void)setUp:(void (^)(DSMasternodeList *masternodeList))completion; @@ -65,13 +66,12 @@ FOUNDATION_EXPORT NSString *const DSQuorumListDidChangeNotification; - (void)saveMasternodeList:(DSMasternodeList *)masternodeList addedMasternodes:(NSDictionary *)addedMasternodes modifiedMasternodes:(NSDictionary *)modifiedMasternodes - addedQuorums:(NSDictionary *)addedQuorums completion:(void (^)(NSError *error))completion; - (void)saveQuorumSnapshot:(DSQuorumSnapshot *)quorumSnapshot toChain:(DSChain *)chain completion:(void (^)(NSError *error))completion; -+ (void)saveMasternodeList:(DSMasternodeList *)masternodeList toChain:(DSChain *)chain havingModifiedMasternodes:(NSDictionary *)modifiedMasternodes addedQuorums:(NSDictionary *)addedQuorums createUnknownBlocks:(BOOL)createUnknownBlocks inContext:(NSManagedObjectContext *)context completion:(void (^)(NSError *error))completion; ++ (void)saveMasternodeList:(DSMasternodeList *)masternodeList toChain:(DSChain *)chain havingModifiedMasternodes:(NSDictionary *)modifiedMasternodes createUnknownBlocks:(BOOL)createUnknownBlocks inContext:(NSManagedObjectContext *)context completion:(void (^)(NSError *error))completion; - (DSQuorumEntry *_Nullable)quorumEntryForPlatformHavingQuorumHash:(UInt256)quorumHash forBlockHeight:(uint32_t)blockHeight; diff --git a/DashSync/shared/Models/Masternode/DSMasternodeListStore.m b/DashSync/shared/Models/Masternode/DSMasternodeListStore.m index bfe90dd4a..69473b1cb 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeListStore.m +++ b/DashSync/shared/Models/Masternode/DSMasternodeListStore.m @@ -421,7 +421,7 @@ - (void)notifyMasternodeListUpdate { }); } -- (void)saveMasternodeList:(DSMasternodeList *)masternodeList addedMasternodes:(NSDictionary *)addedMasternodes modifiedMasternodes:(NSDictionary *)modifiedMasternodes addedQuorums:(NSDictionary *)addedQuorums completion:(void (^)(NSError *error))completion { +- (void)saveMasternodeList:(DSMasternodeList *)masternodeList addedMasternodes:(NSDictionary *)addedMasternodes modifiedMasternodes:(NSDictionary *)modifiedMasternodes completion:(void (^)(NSError *error))completion { UInt256 blockHash = masternodeList.blockHash; NSData *blockHashData = uint256_data(blockHash); DSLog(@"•••• store (%d) masternode list at: %u: %@", [self hasMasternodeListAt:blockHashData], [self heightForBlockHash:blockHash], uint256_hex(blockHash)); @@ -451,7 +451,6 @@ - (void)saveMasternodeList:(DSMasternodeList *)masternodeList addedMasternodes:( [DSMasternodeListStore saveMasternodeList:masternodeList toChain:self.chain havingModifiedMasternodes:modifiedMasternodes - addedQuorums:addedQuorums createUnknownBlocks:createUnknownBlocks inContext:self.managedObjectContext completion:^(NSError *error) { @@ -522,7 +521,6 @@ - (void)saveQuorumSnapshot:(DSQuorumSnapshot *)quorumSnapshot + (void)saveMasternodeList:(DSMasternodeList *)masternodeList toChain:(DSChain *)chain havingModifiedMasternodes:(NSDictionary *)modifiedMasternodes - addedQuorums:(NSDictionary *)addedQuorums createUnknownBlocks:(BOOL)createUnknownBlocks inContext:(NSManagedObjectContext *)context completion:(void (^)(NSError *error))completion { diff --git a/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.h b/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.h index 96665af4c..bbfb58fde 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.h +++ b/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.h @@ -38,6 +38,9 @@ typedef DSMerkleBlock *_Nullable(^_Nullable MerkleBlockFinder)(UInt256 blockHash @property (nonatomic, copy) BlockHeightFinder blockHeightLookup; @property (nonatomic, copy) MerkleRootFinder merkleRootLookup; +- (BOOL)saveCLSignature:(UInt256)blockHash signature:(UInt768)signature; +- (void)blockUntilGetInsightForBlockHash:(UInt256)blockHash; + @end NS_ASSUME_NONNULL_END diff --git a/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.m b/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.m index 6b162e596..e4a9e9db9 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.m +++ b/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.m @@ -17,6 +17,9 @@ #import "DSMasternodeProcessorContext.h" #import "NSData+Dash.h" +#import "DSChain+Protected.h" +#import "DSChainManager.h" +#import "DSMasternodeManager.h" @implementation DSMasternodeProcessorContext @@ -24,4 +27,12 @@ - (NSString *)description { return [[super description] stringByAppendingString:[NSString stringWithFormat:@" {%@}: [%@: %@ (%u)] genesis: %@ protocol: %u, insight: %i, from_snapshot: %i, dip-24: %i}", self.chain.name, self.peer.location, self.peer.useragent, self.peer.version, uint256_hex(self.chain.genesisHash), self.chain.protocolVersion, self.useInsightAsBackup, self.isFromSnapshot, self.isDIP0024]]; } +- (BOOL)saveCLSignature:(UInt256)blockHash signature:(UInt768)signature { + return [self.chain.chainManager.masternodeManager saveCLSignature:uint256_data(blockHash) signatureData:uint768_data(signature)]; +} + +- (void)blockUntilGetInsightForBlockHash:(UInt256)blockHash { + [self.chain blockUntilGetInsightForBlockHash:blockHash]; +} + @end diff --git a/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.h b/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.h index 09e92001a..e00fc3837 100644 --- a/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.h +++ b/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.h @@ -34,7 +34,7 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic) DSMasternodeList *masternodeList; @property (nonatomic) NSDictionary *addedMasternodes; @property (nonatomic) NSDictionary *modifiedMasternodes; -@property (nonatomic) NSDictionary *addedQuorums; +@property (nonatomic) NSArray *addedQuorums; @property (nonatomic) NSOrderedSet *neededMissingMasternodeLists; + (instancetype)processingResultWith:(MNListDiffResult *)result onChain:(DSChain *)chain; diff --git a/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.m b/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.m index fcaa7efe0..3c2965e69 100644 --- a/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.m +++ b/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.m @@ -49,7 +49,7 @@ + (instancetype)processingResultWith:(MNListDiffResult *)result onChain:(DSChain [processingResult setAddedMasternodes:addedMasternodes]; NSDictionary *modifiedMasternodes = [DSSimplifiedMasternodeEntry simplifiedEntriesWith:result->modified_masternodes count:result->modified_masternodes_count onChain:chain]; [processingResult setModifiedMasternodes:modifiedMasternodes]; - NSDictionary *addedQuorums = [DSQuorumEntry entriesWith:result->added_llmq_type_maps count:result->added_llmq_type_maps_count onChain:chain]; + NSArray *addedQuorums = [DSQuorumEntry entriesWith:result->added_quorums count:result->added_quorums_count onChain:chain]; [processingResult setAddedQuorums:addedQuorums]; uint8_t(**needed_masternode_lists)[32] = result->needed_masternode_lists; uintptr_t needed_masternode_lists_count = result->needed_masternode_lists_count; @@ -71,9 +71,9 @@ - (BOOL)isTotallyValid { } - (BOOL)hasRotatedQuorumsForChain:(DSChain*)chain { - return [[self.addedQuorums keysOfEntriesPassingTest:^BOOL(NSNumber *_Nonnull llmqType, id _Nonnull obj, BOOL *_Nonnull stop) { + return [[self.addedQuorums indexesOfObjectsPassingTest:^BOOL(DSQuorumEntry * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { // TODO: make it more reliable as quorum type values may change - return ([llmqType unsignedIntValue] == quorum_type_for_isd_locks(chain.chainType)) && (*stop = TRUE); + return obj.llmqType == quorum_type_for_isd_locks(chain.chainType) && (*stop = TRUE); }] count] > 0; } diff --git a/DashSync/shared/Models/Masternode/DSQuorumEntry+Mndiff.h b/DashSync/shared/Models/Masternode/DSQuorumEntry+Mndiff.h index 4b415fb89..5427ea640 100644 --- a/DashSync/shared/Models/Masternode/DSQuorumEntry+Mndiff.h +++ b/DashSync/shared/Models/Masternode/DSQuorumEntry+Mndiff.h @@ -24,7 +24,8 @@ NS_ASSUME_NONNULL_BEGIN @interface DSQuorumEntry (Mndiff) -+ (NSDictionary *> *)entriesWith:(LLMQMap *_Nullable *_Nonnull)entries count:(uintptr_t)count onChain:(DSChain *)chain; ++ (NSDictionary *> *)entriesWithMap:(LLMQMap *_Nullable *_Nonnull)entries count:(uintptr_t)count onChain:(DSChain *)chain; ++ (NSArray *)entriesWith:(LLMQEntry *_Nullable *_Nonnull)entries count:(uintptr_t)count onChain:(DSChain *)chain; - (LLMQEntry *)ffi_malloc; + (void)ffi_free:(LLMQEntry *)entry; diff --git a/DashSync/shared/Models/Masternode/DSQuorumEntry+Mndiff.m b/DashSync/shared/Models/Masternode/DSQuorumEntry+Mndiff.m index 6f827b2f7..da662b673 100644 --- a/DashSync/shared/Models/Masternode/DSQuorumEntry+Mndiff.m +++ b/DashSync/shared/Models/Masternode/DSQuorumEntry+Mndiff.m @@ -20,7 +20,7 @@ @implementation DSQuorumEntry (Mndiff) -+ (NSDictionary *> *)entriesWith:(LLMQMap *_Nullable *_Nonnull)entries count:(uintptr_t)count onChain:(DSChain *)chain { ++ (NSDictionary *> *)entriesWithMap:(LLMQMap *_Nullable *_Nonnull)entries count:(uintptr_t)count onChain:(DSChain *)chain { NSMutableDictionary *> *quorums = [NSMutableDictionary dictionaryWithCapacity:count]; for (NSUInteger i = 0; i < count; i++) { LLMQMap *llmq_map = entries[i]; @@ -37,6 +37,14 @@ @implementation DSQuorumEntry (Mndiff) return quorums; } ++ (NSArray *)entriesWith:(LLMQEntry *_Nullable *_Nonnull)entries count:(uintptr_t)count onChain:(DSChain *)chain { + NSMutableArray *result = [NSMutableArray arrayWithCapacity:count]; + for (NSUInteger i = 0; i < count; i++) { + [result addObject:[[DSQuorumEntry alloc] initWithEntry:entries[i] onChain:chain]]; + } + return result; +} + - (LLMQEntry *)ffi_malloc { LLMQEntry *quorum_entry = malloc(sizeof(LLMQEntry)); quorum_entry->all_commitment_aggregated_signature = uint768_malloc([self allCommitmentAggregatedSignature]); diff --git a/DashSync/shared/Models/Masternode/DSQuorumEntry.h b/DashSync/shared/Models/Masternode/DSQuorumEntry.h index abe1ee54f..c984de2b8 100644 --- a/DashSync/shared/Models/Masternode/DSQuorumEntry.h +++ b/DashSync/shared/Models/Masternode/DSQuorumEntry.h @@ -19,7 +19,6 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic, readonly) uint16_t version; @property (nonatomic, readonly) uint32_t quorumIndex; @property (nonatomic, readonly) UInt256 quorumHash; -@property (nonatomic, readonly) UInt256 llmqQuorumHash; @property (nonatomic, readonly) UInt384 quorumPublicKey; @property (nonatomic, readonly) UInt768 quorumThresholdSignature; @property (nonatomic, readonly) UInt256 quorumVerificationVectorHash; @@ -67,6 +66,7 @@ allCommitmentAggregatedSignature:(UInt768)allCommitmentAggregatedSignature - (void)mergedWithQuorumEntry:(DSQuorumEntry *)quorumEntry; - (BOOL)useLegacyBLSScheme; +- (UInt256)buildQuorumHash:(NSData *_Nullable)bestCLSignature; @end diff --git a/DashSync/shared/Models/Masternode/DSQuorumEntry.m b/DashSync/shared/Models/Masternode/DSQuorumEntry.m index aeebf7375..aef787aff 100644 --- a/DashSync/shared/Models/Masternode/DSQuorumEntry.m +++ b/DashSync/shared/Models/Masternode/DSQuorumEntry.m @@ -187,8 +187,9 @@ - (uint32_t)quorumThreshold { return quorum_threshold_for_type(self.llmqType); } -- (UInt256)llmqQuorumHash { - return [DSKeyManager NSDataFrom:quorum_build_llmq_hash(self.llmqType, self.quorumHash.u8)].UInt256; +- (UInt256)buildQuorumHash:(NSData *_Nullable)bestCLSignature /*UInt768*/{ + return [DSKeyManager NSDataFrom:quorum_build_llmq_hash(self.llmqType, self.quorumHash.u8, bestCLSignature.bytes)].UInt256; + } - (BOOL)validateWithMasternodeList:(DSMasternodeList *)masternodeList { @@ -210,7 +211,7 @@ - (BOOL)validateWithMasternodeList:(DSMasternodeList *)masternodeList blockHeigh } MasternodeList *list = [masternodeList ffi_malloc]; LLMQEntry *quorum = [self ffi_malloc]; - BOOL is_valid = validate_masternode_list(list, quorum, blockHeightLookup(masternodeList.blockHash), self.chain.chainType); + BOOL is_valid = validate_masternode_list(list, quorum, blockHeightLookup(masternodeList.blockHash), self.chain.chainType, NULL); [DSMasternodeList ffi_free:list]; [DSQuorumEntry ffi_free:quorum]; self.verified = is_valid; diff --git a/DashSync/shared/Models/Persistence/Migration/Internal/DSCoreDataMigrationVersion.h b/DashSync/shared/Models/Persistence/Migration/Internal/DSCoreDataMigrationVersion.h index 54c595b35..066472548 100644 --- a/DashSync/shared/Models/Persistence/Migration/Internal/DSCoreDataMigrationVersion.h +++ b/DashSync/shared/Models/Persistence/Migration/Internal/DSCoreDataMigrationVersion.h @@ -40,6 +40,7 @@ typedef NS_ENUM(NSInteger, DSCoreDataMigrationVersionValue) DSCoreDataMigrationVersionValue_17 = 17, DSCoreDataMigrationVersionValue_18 = 18, DSCoreDataMigrationVersionValue_19 = 19, + DSCoreDataMigrationVersionValue_20 = 20, }; @interface DSCoreDataMigrationVersion : NSObject diff --git a/DashSync/shared/Models/Persistence/Migration/Internal/DSCoreDataMigrationVersion.m b/DashSync/shared/Models/Persistence/Migration/Internal/DSCoreDataMigrationVersion.m index 08f7e1e44..3fed0b6bd 100644 --- a/DashSync/shared/Models/Persistence/Migration/Internal/DSCoreDataMigrationVersion.m +++ b/DashSync/shared/Models/Persistence/Migration/Internal/DSCoreDataMigrationVersion.m @@ -44,6 +44,7 @@ + (NSString *)modelResourceForVersion:(DSCoreDataMigrationVersionValue)version { case DSCoreDataMigrationVersionValue_17: return @"DashSync 17"; case DSCoreDataMigrationVersionValue_18: return @"DashSync 18"; case DSCoreDataMigrationVersionValue_19: return @"DashSync 19"; + case DSCoreDataMigrationVersionValue_20: return @"DashSync 20"; default: return [NSString stringWithFormat:@"DashSync %ld", (long)version]; } diff --git a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction+Mndiff.m b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction+Mndiff.m index 9361e8eb2..493351f89 100644 --- a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction+Mndiff.m +++ b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction+Mndiff.m @@ -61,7 +61,6 @@ @implementation DSCoinbaseTransaction (Mndiff) ctx.version = tx->version; ctx.txHash = *(UInt256 *)tx->tx_hash; ctx.type = tx->tx_type; - ctx.payloadOffset = (uint32_t)tx->payload_offset; ctx.blockHeight = tx->block_height; return ctx; }*/ diff --git a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.h b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.h index ad0a27605..d5e5b7bd0 100644 --- a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.h +++ b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.h @@ -13,7 +13,9 @@ @property (nonatomic, assign) uint32_t height; @property (nonatomic, assign) UInt256 merkleRootMNList; @property (nonatomic, assign) UInt256 merkleRootLLMQList; -@property (nonatomic, assign) uint64_t lockedAmount; +@property (nonatomic, assign) uint32_t bestCLHeightDiff; +@property (nonatomic, assign) UInt768 bestCLSignature; +@property (nonatomic, assign) int64_t creditPoolBalance; - (instancetype)initWithCoinbaseMessage:(NSString *)coinbaseMessage atHeight:(uint32_t)height onChain:(DSChain *)chain; - (instancetype)initWithCoinbaseMessage:(NSString *)coinbaseMessage paymentAddresses:(NSArray *)paymentAddresses atHeight:(uint32_t)height onChain:(DSChain *)chain; diff --git a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m index 0a440e773..339cdfb8e 100644 --- a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m +++ b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m @@ -27,27 +27,31 @@ - (instancetype)initWithMessage:(NSData *)message onChain:(DSChain *)chain { uint16_t version = [message UInt16AtOffset:off]; off += 2; if (length - off < 4) return nil; - uint32_t height = [message UInt32AtOffset:off]; + self.height = [message UInt32AtOffset:off]; off += 4; if (length - off < 32) return nil; - UInt256 merkleRootMNList = [message UInt256AtOffset:off]; + self.merkleRootMNList = [message UInt256AtOffset:off]; off += 32; - if (version >= 2) { + if (version >= COINBASE_TX_CORE_19) { if (length - off < 32) return nil; self.merkleRootLLMQList = [message UInt256AtOffset:off]; off += 32; + + if (version >= COINBASE_TX_CORE_20) { + if (length - off < 4) return nil; + self.bestCLHeightDiff = [message UInt32AtOffset:off]; + off += 4; + if (length - off < 96) return nil; + self.bestCLSignature = [message UInt768AtOffset:off]; + off += 96; + if (length - off < 8) return nil; + NSNumber *len; + self.creditPoolBalance = [message varIntAtOffset:off length:&len]; + off += len.unsignedIntegerValue; + } } - - if (version >= 3) { - if (length - off < 8) return nil; - self.lockedAmount = [message UInt64AtOffset:off]; - off += 8; - } - self.coinbaseTransactionVersion = version; - self.height = height; - self.merkleRootMNList = merkleRootMNList; self.payloadOffset = off; self.txHash = self.data.SHA256_2; @@ -86,11 +90,14 @@ - (NSData *)payloadData { [data appendUInt16:self.coinbaseTransactionVersion]; [data appendUInt32:self.height]; [data appendUInt256:self.merkleRootMNList]; - if (self.coinbaseTransactionVersion >= 2) { + if (self.coinbaseTransactionVersion >= COINBASE_TX_CORE_19) { [data appendUInt256:self.merkleRootLLMQList]; - } - if (self.coinbaseTransactionVersion >= 3) { - [data appendUInt64:self.lockedAmount]; + if (self.coinbaseTransactionVersion >= COINBASE_TX_CORE_20) { + [data appendUInt32:self.bestCLHeightDiff]; + // TODO: check whether it matters to check for optionals + [data appendUInt768:self.bestCLSignature]; + [data appendInt64:self.creditPoolBalance]; + } } return data; } diff --git a/Example/DashSync.xcodeproj/xcshareddata/xcschemes/DashSync-Example.xcscheme b/Example/DashSync.xcodeproj/xcshareddata/xcschemes/DashSync-Example.xcscheme index 42d0e7b91..88c79c32d 100644 --- a/Example/DashSync.xcodeproj/xcshareddata/xcschemes/DashSync-Example.xcscheme +++ b/Example/DashSync.xcodeproj/xcshareddata/xcschemes/DashSync-Example.xcscheme @@ -176,6 +176,11 @@ value = "" isEnabled = "YES"> + + 'https://github.com/dashpay/dash-shared-core.git', :branch => 'fix/revert-bls-legacy-scheme-derivation' -# pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :commit => '27157c7' + pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :branch => 'feat/core-20-beacons' +# pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :commit => 'e2dc943' pod 'DashSync', :path => '../' pod 'SDWebImage', '5.14.3' pod 'CocoaImageHashing', :git => 'https://github.com/ameingast/cocoaimagehashing.git', :commit => 'ad01eee' diff --git a/Example/Podfile.lock b/Example/Podfile.lock index bb8df6c35..885558aa1 100644 --- a/Example/Podfile.lock +++ b/Example/Podfile.lock @@ -657,7 +657,7 @@ PODS: - gRPC/Interface-Legacy (1.49.0): - gRPC-RxLibrary/Interface (= 1.49.0) - KVO-MVVM (0.5.1) - - Protobuf (3.24.3) + - Protobuf (3.24.4) - SDWebImage (5.14.3): - SDWebImage/Core (= 5.14.3) - SDWebImage/Core (5.14.3) @@ -667,6 +667,7 @@ PODS: DEPENDENCIES: - CocoaImageHashing (from `https://github.com/ameingast/cocoaimagehashing.git`, commit `ad01eee`) + - DashSharedCore (from `https://github.com/dashpay/dash-shared-core.git`, branch `feat/core-20-beacons`) - DashSync (from `../`) - KVO-MVVM (= 0.5.1) - SDWebImage (= 5.14.3) @@ -679,7 +680,6 @@ SPEC REPOS: - BoringSSL-GRPC - CocoaLumberjack - DAPI-GRPC - - DashSharedCore - DSDynamicOptions - DWAlertController - gRPC @@ -696,6 +696,9 @@ EXTERNAL SOURCES: CocoaImageHashing: :commit: ad01eee :git: https://github.com/ameingast/cocoaimagehashing.git + DashSharedCore: + :branch: feat/core-20-beacons + :git: https://github.com/dashpay/dash-shared-core.git DashSync: :path: "../" @@ -703,6 +706,9 @@ CHECKOUT OPTIONS: CocoaImageHashing: :commit: ad01eee :git: https://github.com/ameingast/cocoaimagehashing.git + DashSharedCore: + :commit: 3a53d7b73cc7fccc9424afb41fbe6574f02bf5fe + :git: https://github.com/dashpay/dash-shared-core.git SPEC CHECKSUMS: "!ProtoCompiler": e9c09244955a8565817aa59a4787b6bb849a63c6 @@ -721,11 +727,11 @@ SPEC CHECKSUMS: gRPC-ProtoRPC: 1c223e0f1732bb8d0b9e9e0ea60cc0fe995b8e2d gRPC-RxLibrary: 92327f150e11cf3b1c0f52e083944fd9f5cb5d1e KVO-MVVM: 4df3afd1f7ebcb69735458b85db59c4271ada7c6 - Protobuf: 970f7ee93a3a08e3cf64859b8efd95ee32b4f87f + Protobuf: 351e9022fe13a6e2af00e9aefc22077cb88520f8 SDWebImage: 9c36e66c8ce4620b41a7407698dda44211a96764 tinycbor: d4d71dddda1f8392fbb4249f63faf8552f327590 TinyCborObjc: 5204540fb90ff0c40fb22d408fa51bab79d78a80 -PODFILE CHECKSUM: 65ee9c6b1d7ae6ab3bc40337f53a5135ff99a2f1 +PODFILE CHECKSUM: c382cb539927295cdbcdf3aa448986de5d8df251 COCOAPODS: 1.12.1 diff --git a/Example/Tests/DSDeterministicMasternodeListTests.m b/Example/Tests/DSDeterministicMasternodeListTests.m index bc090350d..ab58853b5 100644 --- a/Example/Tests/DSDeterministicMasternodeListTests.m +++ b/Example/Tests/DSDeterministicMasternodeListTests.m @@ -634,7 +634,6 @@ - (void)loadMasternodeListsForFiles:(NSArray *)files [DSMasternodeManager saveMasternodeList:masternodeList toChain:chain havingModifiedMasternodes:result.modifiedMasternodes - addedQuorums:result.addedQuorums createUnknownBlocks:YES inContext:context completion:^(NSError *_Nonnull error) { @@ -747,7 +746,6 @@ - (void)testMainnetMasternodeSaving { [DSMasternodeManager saveMasternodeList:result.masternodeList toChain:chain havingModifiedMasternodes:result.modifiedMasternodes - addedQuorums:result.addedQuorums createUnknownBlocks:YES inContext:context completion:^(NSError *_Nonnull error) { @@ -812,7 +810,6 @@ - (void)testMNLSavingToDisk { [DSMasternodeManager saveMasternodeList:masternodeList toChain:chain havingModifiedMasternodes:result.modifiedMasternodes - addedQuorums:result.addedQuorums createUnknownBlocks:YES inContext:context completion:^(NSError *_Nonnull error) { @@ -888,7 +885,6 @@ - (void)testMNLSavingAndRetrievingFromDisk { [DSMasternodeManager saveMasternodeList:masternodeList122064 toChain:chain havingModifiedMasternodes:result.modifiedMasternodes - addedQuorums:result.addedQuorums createUnknownBlocks:YES inContext:context completion:^(NSError *_Nonnull error) { @@ -936,7 +932,6 @@ - (void)testMNLSavingAndRetrievingFromDisk { [DSMasternodeManager saveMasternodeList:masternodeList122088 toChain:chain havingModifiedMasternodes:result122088.modifiedMasternodes - addedQuorums:result122088.addedQuorums createUnknownBlocks:YES inContext:context completion:^(NSError *_Nonnull error) { @@ -2839,7 +2834,6 @@ - (void)testMNLSavingAndRetrievingInIncorrectOrderFromDisk { [DSMasternodeManager saveMasternodeList:masternodeList1092912 toChain:chain havingModifiedMasternodes:result.modifiedMasternodes - addedQuorums:result.addedQuorums createUnknownBlocks:YES inContext:context completion:^(NSError *_Nonnull error) { @@ -2879,10 +2873,10 @@ - (void)testMNLSavingAndRetrievingInIncorrectOrderFromDisk { XCTAssert(result1092940.rootMNListValid, @"rootMNListValid not valid at height %u", [chain heightForBlockHash:blockHash1092940]); XCTAssert(result1092940.rootQuorumListValid, @"rootQuorumListValid not valid at height %u", [chain heightForBlockHash:blockHash1092940]); XCTAssert(result1092940.validQuorums, @"validQuorums not valid at height %u", [chain heightForBlockHash:blockHash1092940]); - DSQuorumEntry *quorum1092912 = [[[[result1092940.addedQuorums allValues] firstObject] allValues] firstObject]; + DSQuorumEntry *quorum1092912 = [result1092940.addedQuorums firstObject]; // 1092912 and 1092916 are the same, 1092916 is older though and is original 1092912 is based off a reloaded 109 - NSArray *masternodeScores1092912 = [masternodeList1092912 scoresForQuorumModifier:quorum1092912.llmqQuorumHash atBlockHeight:1092912]; - NSArray *masternodeScores1092916 = [masternodeList1092916 scoresForQuorumModifier:quorum1092912.llmqQuorumHash atBlockHeight:1092912]; + NSArray *masternodeScores1092912 = [masternodeList1092912 scoresForQuorumModifier:[quorum1092912 buildQuorumHash:nil] atBlockHeight:1092912]; + NSArray *masternodeScores1092916 = [masternodeList1092916 scoresForQuorumModifier:[quorum1092912 buildQuorumHash: nil] atBlockHeight:1092912]; // BOOL a = [quorum1092912 validateWithMasternodeList:masternodeList1092912]; // @@ -2908,9 +2902,9 @@ - (void)testMNLSavingAndRetrievingInIncorrectOrderFromDisk { XCTAssertEqualObjects(masternodeScores1092912, masternodeScores1092916, @"These should be the same"); - NSArray *masternodes1092912 = [masternodeList1092912 validMasternodesForQuorumModifier:quorum1092912.llmqQuorumHash quorumCount:[DSQuorumEntry quorumSizeForType:quorum1092912.llmqType] blockHeight:blockHeightLookup(masternodeList1092912.blockHash)]; + NSArray *masternodes1092912 = [masternodeList1092912 validMasternodesForQuorumModifier:[quorum1092912 buildQuorumHash:nil] quorumCount:[DSQuorumEntry quorumSizeForType:quorum1092912.llmqType] blockHeight:blockHeightLookup(masternodeList1092912.blockHash)]; - NSArray *masternodes1092916 = [masternodeList1092916 validMasternodesForQuorumModifier:quorum1092912.llmqQuorumHash quorumCount:[DSQuorumEntry quorumSizeForType:quorum1092912.llmqType] blockHeight:blockHeightLookup(masternodeList1092916.blockHash)]; + NSArray *masternodes1092916 = [masternodeList1092916 validMasternodesForQuorumModifier:[quorum1092912 buildQuorumHash:nil] quorumCount:[DSQuorumEntry quorumSizeForType:quorum1092912.llmqType] blockHeight:blockHeightLookup(masternodeList1092916.blockHash)]; XCTAssertEqualObjects(masternodes1092912, masternodes1092916, @"These should be the same"); // NSMutableArray * publicKeyArray = [NSMutableArray array]; // uint32_t i = 0; @@ -2927,7 +2921,6 @@ - (void)testMNLSavingAndRetrievingInIncorrectOrderFromDisk { [DSMasternodeManager saveMasternodeList:masternodeList1092940 toChain:chain havingModifiedMasternodes:result1092940.modifiedMasternodes - addedQuorums:result1092940.addedQuorums createUnknownBlocks:YES inContext:context completion:^(NSError *_Nonnull error) { @@ -3059,7 +3052,11 @@ - (void)testTestnetQuorumVerification { XCTAssert(result119200.rootQuorumListValid, @"rootQuorumListValid not valid at height %u", [chain heightForBlockHash:blockHash]); XCTAssert(result119200.validQuorums, @"validQuorums not valid at height %u", [chain heightForBlockHash:blockHash]); - DSQuorumEntry *quorumToVerify = [result119200.addedQuorums[@1] objectForKey:uint256_data(blockHash119064)]; + NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(DSQuorumEntry *entry, NSDictionary *bindings) { + return uint256_eq(entry.quorumHash, blockHash119064) && entry.llmqType == LLMQType_Llmqtype50_60; + }]; + + DSQuorumEntry *quorumToVerify = [[result119200.addedQuorums filteredArrayUsingPredicate:predicate] firstObject]; XCTAssert(quorumToVerify, @"There should be a quorum using 119064"); [quorumToVerify validateWithMasternodeList:masternodeList119064]; XCTAssert(quorumToVerify.verified, @"Unable to verify quorum"); @@ -3211,11 +3208,14 @@ - (void)testTestnetSizeQuorumVerification { XCTAssert(result370944.rootQuorumListValid, @"rootQuorumListValid not valid at height %u", [chain heightForBlockHash:blockHash]); XCTAssert(result370944.validQuorums, @"validQuorums not valid at height %u", [chain heightForBlockHash:blockHash]); - DSQuorumEntry *quorumToVerify = [result370944.addedQuorums[@1] objectForKey:uint256_data(blockHash370368)]; + NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(DSQuorumEntry *entry, NSDictionary *bindings) { + return uint256_eq(entry.quorumHash, blockHash370368) && entry.llmqType == LLMQType_Llmqtype50_60; + }]; + DSQuorumEntry *quorumToVerify = [[result370944.addedQuorums filteredArrayUsingPredicate:predicate] firstObject]; XCTAssert(quorumToVerify, @"There should be a quorum using 119064"); DSMasternodeList *masternodeList370944 = result370944.masternodeList; - NSArray *masternodes = [masternodeList370944 validMasternodesForQuorumModifier:quorumToVerify.llmqQuorumHash quorumCount:[DSQuorumEntry quorumSizeForType:quorumToVerify.llmqType] blockHeight:370944]; + NSArray *masternodes = [masternodeList370944 validMasternodesForQuorumModifier:[quorumToVerify buildQuorumHash:NULL] quorumCount:[DSQuorumEntry quorumSizeForType:quorumToVerify.llmqType] blockHeight:370944]; NSArray *masternodeHashOrder = [masternodes map:^(DSSimplifiedMasternodeEntry *masternode) { return uint256_reverse_hex([masternode providerRegistrationTransactionHash]); From 659db356a622466c4798d0415ee6ba78327901d7 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Wed, 25 Oct 2023 16:09:36 +0700 Subject: [PATCH 04/32] chore: DashSharedCore 0.4.12 --- DashSync.podspec | 2 +- Example/Podfile | 2 +- Example/Podfile.lock | 18 ++++++------------ 3 files changed, 8 insertions(+), 14 deletions(-) diff --git a/DashSync.podspec b/DashSync.podspec index 3c258b0d5..6e9644157 100644 --- a/DashSync.podspec +++ b/DashSync.podspec @@ -34,7 +34,7 @@ Pod::Spec.new do |s| s.ios.framework = 'UIKit' s.macos.framework = 'Cocoa' s.compiler_flags = '-Wno-comma' - s.dependency 'DashSharedCore', '0.4.11' + s.dependency 'DashSharedCore', '0.4.12' s.dependency 'CocoaLumberjack', '3.7.2' s.ios.dependency 'DWAlertController', '0.2.1' s.dependency 'DSDynamicOptions', '0.1.2' diff --git a/Example/Podfile b/Example/Podfile index 96bda4851..c244c6668 100644 --- a/Example/Podfile +++ b/Example/Podfile @@ -1,5 +1,5 @@ def common_pods - pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :branch => 'feat/core-20-beacons' +# pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :branch => 'feat/core-20-beacons' # pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :commit => 'e2dc943' pod 'DashSync', :path => '../' pod 'SDWebImage', '5.14.3' diff --git a/Example/Podfile.lock b/Example/Podfile.lock index 885558aa1..25c2ac872 100644 --- a/Example/Podfile.lock +++ b/Example/Podfile.lock @@ -586,11 +586,11 @@ PODS: - "!ProtoCompiler-gRPCPlugin (~> 1.0)" - DAPI-GRPC/Messages - gRPC-ProtoRPC - - DashSharedCore (0.4.11) + - DashSharedCore (0.4.12) - DashSync (0.1.0): - CocoaLumberjack (= 3.7.2) - DAPI-GRPC (= 0.22.0-dev.8) - - DashSharedCore (= 0.4.11) + - DashSharedCore (= 0.4.12) - DSDynamicOptions (= 0.1.2) - DWAlertController (= 0.2.1) - TinyCborObjc (= 0.4.6) @@ -667,7 +667,6 @@ PODS: DEPENDENCIES: - CocoaImageHashing (from `https://github.com/ameingast/cocoaimagehashing.git`, commit `ad01eee`) - - DashSharedCore (from `https://github.com/dashpay/dash-shared-core.git`, branch `feat/core-20-beacons`) - DashSync (from `../`) - KVO-MVVM (= 0.5.1) - SDWebImage (= 5.14.3) @@ -680,6 +679,7 @@ SPEC REPOS: - BoringSSL-GRPC - CocoaLumberjack - DAPI-GRPC + - DashSharedCore - DSDynamicOptions - DWAlertController - gRPC @@ -696,9 +696,6 @@ EXTERNAL SOURCES: CocoaImageHashing: :commit: ad01eee :git: https://github.com/ameingast/cocoaimagehashing.git - DashSharedCore: - :branch: feat/core-20-beacons - :git: https://github.com/dashpay/dash-shared-core.git DashSync: :path: "../" @@ -706,9 +703,6 @@ CHECKOUT OPTIONS: CocoaImageHashing: :commit: ad01eee :git: https://github.com/ameingast/cocoaimagehashing.git - DashSharedCore: - :commit: 3a53d7b73cc7fccc9424afb41fbe6574f02bf5fe - :git: https://github.com/dashpay/dash-shared-core.git SPEC CHECKSUMS: "!ProtoCompiler": e9c09244955a8565817aa59a4787b6bb849a63c6 @@ -718,8 +712,8 @@ SPEC CHECKSUMS: CocoaImageHashing: 8656031d0899abe6c1c415827de43e9798189c53 CocoaLumberjack: b7e05132ff94f6ae4dfa9d5bce9141893a21d9da DAPI-GRPC: 138d62523bbfe7e88a39896f1053c0bc12390d9f - DashSharedCore: d4dc11749f3555702dbe10c563087e6b48399394 - DashSync: 2d80784e399b869aede6d5bd476a149733451651 + DashSharedCore: 842f752df2a9cdb357b377c1a1abebdac5c0cefa + DashSync: 86a678ae3bc1600245ade93c22acd90377ffb3b6 DSDynamicOptions: 347cc5d2c4e080eb3de6a86719ad3d861b82adfc DWAlertController: 5f4cd8adf90336331c054857f709f5f8d4b16a5b gRPC: 64f36d689b2ecd99c4351f74e6f91347cdc65d9f @@ -732,6 +726,6 @@ SPEC CHECKSUMS: tinycbor: d4d71dddda1f8392fbb4249f63faf8552f327590 TinyCborObjc: 5204540fb90ff0c40fb22d408fa51bab79d78a80 -PODFILE CHECKSUM: c382cb539927295cdbcdf3aa448986de5d8df251 +PODFILE CHECKSUM: b185f6b2705cc13f4d1d87e4fa3fbfb6e4b1597f COCOAPODS: 1.12.1 From 4a31f8faee244e0df1e776291d3b7388c2f8dc29 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Wed, 25 Oct 2023 16:56:43 +0700 Subject: [PATCH 05/32] refactor: move helper methods into DSMasternodeProcessorContext + macro for bridging --- .../DSMasternodeManager+Mndiff.m | 95 +++++-------------- .../Masternode/DSMasternodeProcessorContext.h | 15 +++ .../Masternode/DSMasternodeProcessorContext.m | 72 +++++++++++++- 3 files changed, 110 insertions(+), 72 deletions(-) diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.m b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.m index 8c9e644f6..c46a523ba 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.m @@ -29,18 +29,20 @@ #import "DSSimplifiedMasternodeEntry+Mndiff.h" #import "NSData+Dash.h" +#define AS_OBJC(context) ((__bridge DSMasternodeProcessorContext *)(context)) +#define AS_RUST(context) ((__bridge void *)(context)) + @implementation DSMasternodeManager (Mndiff) + /// /// MARK: Rust FFI callbacks /// MasternodeList *getMasternodeListByBlockHash(uint8_t (*block_hash)[32], const void *context) { UInt256 blockHash = *((UInt256 *)block_hash); - DSMasternodeProcessorContext *processorContext = NULL; MasternodeList *c_list = NULL; @synchronized (context) { - processorContext = (__bridge DSMasternodeProcessorContext *)context; - DSMasternodeList *list = processorContext.masternodeListLookup(blockHash); + DSMasternodeList *list = [AS_OBJC(context) masternodeListForBlockHash:blockHash]; if (list) { c_list = [list ffi_malloc]; } @@ -51,13 +53,11 @@ @implementation DSMasternodeManager (Mndiff) bool saveMasternodeList(uint8_t (*block_hash)[32], MasternodeList *masternode_list, const void *context) { UInt256 blockHash = *((UInt256 *)block_hash); - DSMasternodeProcessorContext *processorContext = NULL; BOOL saved = NO; @synchronized (context) { - processorContext = (__bridge DSMasternodeProcessorContext *)context; - DSChain *chain = processorContext.chain; - DSMasternodeList *masternodeList = [DSMasternodeList masternodeListWith:masternode_list onChain:chain]; - saved = [chain.chainManager.masternodeManager saveMasternodeList:masternodeList forBlockHash:blockHash]; + DSMasternodeProcessorContext *processorContext = AS_OBJC(context); + DSMasternodeList *masternodeList = [DSMasternodeList masternodeListWith:masternode_list onChain:processorContext.chain]; + saved = [processorContext saveMasternodeList:masternodeList forBlockHash:blockHash]; } processor_destroy_block_hash(block_hash); processor_destroy_masternode_list(masternode_list); @@ -75,24 +75,19 @@ void destroyU8(uint8_t *block_hash) { // big uint } uint32_t getBlockHeightByHash(uint8_t (*block_hash)[32], const void *context) { - DSMasternodeProcessorContext *processorContext = NULL; UInt256 blockHash = *((UInt256 *)block_hash); uint32_t block_height = UINT32_MAX; @synchronized (context) { - processorContext = (__bridge DSMasternodeProcessorContext *)context; - block_height = processorContext.blockHeightLookup(blockHash); + block_height = [AS_OBJC(context) blockHeightForBlockHash:blockHash]; } processor_destroy_block_hash(block_hash); return block_height; } uint8_t *getBlockHashByHeight(uint32_t block_height, const void *context) { - DSMasternodeProcessorContext *processorContext = NULL; uint8_t (*block_hash)[32] = NULL; @synchronized (context) { - processorContext = (__bridge DSMasternodeProcessorContext *)context; - DSChain *chain = processorContext.chain; - DSBlock *block = [chain blockAtHeight:block_height]; + DSBlock *block = [AS_OBJC(context) blockForBlockHeight:block_height]; if (block) { block_hash = uint256_malloc(block.blockHash); } @@ -102,12 +97,10 @@ uint32_t getBlockHeightByHash(uint8_t (*block_hash)[32], const void *context) { uint8_t *getMerkleRootByHash(uint8_t (*block_hash)[32], const void *context) { - DSMasternodeProcessorContext *processorContext = NULL; UInt256 blockHash = *((UInt256 *)block_hash); uint8_t (*merkle_root)[32] = NULL; @synchronized (context) { - processorContext = (__bridge DSMasternodeProcessorContext *)context; - UInt256 merkleRoot = processorContext.merkleRootLookup(blockHash); + UInt256 merkleRoot = [AS_OBJC(context) merkleRootForBlockHash:blockHash]; merkle_root = uint256_malloc(merkleRoot); } processor_destroy_block_hash(block_hash); @@ -115,13 +108,10 @@ uint32_t getBlockHeightByHash(uint8_t (*block_hash)[32], const void *context) { } LLMQSnapshot *getLLMQSnapshotByBlockHash(uint8_t (*block_hash)[32], const void *context) { - DSMasternodeProcessorContext *processorContext = NULL; UInt256 blockHash = *((UInt256 *)block_hash); LLMQSnapshot *c_snapshot = NULL; @synchronized (context) { - processorContext = (__bridge DSMasternodeProcessorContext *)context; - DSChain *chain = processorContext.chain; - DSQuorumSnapshot *snapshot = [chain.chainManager.masternodeManager quorumSnapshotForBlockHash:blockHash]; + DSQuorumSnapshot *snapshot = [AS_OBJC(context) quorumSnapshotForBlockHash:blockHash]; if (snapshot) { c_snapshot = [snapshot ffi_malloc]; } @@ -132,14 +122,10 @@ uint32_t getBlockHeightByHash(uint8_t (*block_hash)[32], const void *context) { bool saveLLMQSnapshot(uint8_t (*block_hash)[32], LLMQSnapshot *snapshot, const void *context) { - DSMasternodeProcessorContext *processorContext = NULL; UInt256 blockHash = *((UInt256 *)block_hash); BOOL saved = NO; @synchronized (context) { - processorContext = (__bridge DSMasternodeProcessorContext *)context; - DSChain *chain = processorContext.chain; - DSQuorumSnapshot *quorumSnapshot = [DSQuorumSnapshot quorumSnapshotWith:snapshot forBlockHash:blockHash]; - saved = [chain.chainManager.masternodeManager saveQuorumSnapshot:quorumSnapshot]; + saved = [AS_OBJC(context) saveQuorumSnapshot:[DSQuorumSnapshot quorumSnapshotWith:snapshot forBlockHash:blockHash]]; } processor_destroy_block_hash(block_hash); processor_destroy_llmq_snapshot(snapshot); @@ -150,12 +136,10 @@ void destroyLLMQSnapshot(LLMQSnapshot *snapshot) { } uint8_t *getCLSignatureByBlockHash(uint8_t (*block_hash)[32], const void *context) { - DSMasternodeProcessorContext *processorContext = NULL; UInt256 blockHash = *((UInt256 *)block_hash); uint8_t (*cl_signature)[96] = NULL; @synchronized (context) { - processorContext = (__bridge DSMasternodeProcessorContext *)context; - NSData *signature = [processorContext.chain.chainManager.masternodeManager CLSignatureForBlockHash:blockHash]; + NSData *signature = [AS_OBJC(context) CLSignatureForBlockHash:blockHash]; if (signature) { cl_signature = uint768_malloc(signature.UInt768); } @@ -164,9 +148,11 @@ void destroyLLMQSnapshot(LLMQSnapshot *snapshot) { return (uint8_t *)cl_signature; } bool saveCLSignature(uint8_t (*block_hash)[32], uint8_t (*cl_signature)[96], const void *context) { + UInt256 blockHash = *((UInt256 *)block_hash); + UInt768 clSignature = *((UInt768 *)cl_signature); BOOL saved = NO; @synchronized (context) { - saved = [(__bridge DSMasternodeProcessorContext *)context saveCLSignature:*((UInt256 *)block_hash) signature:*((UInt768 *)cl_signature)]; + saved = [AS_OBJC(context) saveCLSignature:blockHash signature:clSignature]; } processor_destroy_block_hash(block_hash); processor_destroy_cl_signature(cl_signature); @@ -174,54 +160,23 @@ bool saveCLSignature(uint8_t (*block_hash)[32], uint8_t (*cl_signature)[96], con } void addInsightForBlockHash(uint8_t (*block_hash)[32], const void *context) { + UInt256 blockHash = *((UInt256 *)block_hash); @synchronized (context) { - [(__bridge DSMasternodeProcessorContext *)context blockUntilGetInsightForBlockHash:*((UInt256 *)block_hash)]; + [AS_OBJC(context) blockUntilGetInsightForBlockHash:blockHash]; } processor_destroy_block_hash(block_hash); } ProcessingError shouldProcessDiffWithRange(uint8_t (*base_block_hash)[32], uint8_t (*block_hash)[32], const void *context) { - DSMasternodeProcessorContext *processorContext = NULL; UInt256 baseBlockHash = *((UInt256 *)base_block_hash); UInt256 blockHash = *((UInt256 *)block_hash); processor_destroy_block_hash(base_block_hash); processor_destroy_block_hash(block_hash); + ProcessingError error = ProcessingError_None; @synchronized (context) { - processorContext = (__bridge DSMasternodeProcessorContext *)context; - uint32_t baseBlockHeight = processorContext.blockHeightLookup(baseBlockHash); - uint32_t blockHeight = processorContext.blockHeightLookup(blockHash); - if (blockHeight == UINT32_MAX) { - DSLog(@"•••• shouldProcessDiffWithRange: unknown blockHash: %u..%u %@ .. %@", baseBlockHeight, blockHeight, uint256_reverse_hex(baseBlockHash), uint256_reverse_hex(blockHash)); - return ProcessingError_UnknownBlockHash; - } - DSChain *chain = processorContext.chain; - DSMasternodeManager *manager = chain.chainManager.masternodeManager; - DSMasternodeListService *service = processorContext.isDIP0024 ? manager.quorumRotationService : manager.masternodeListDiffService; - BOOL hasRemovedFromRetrieval = [service removeRequestInRetrievalForBaseBlockHash:baseBlockHash blockHash:blockHash]; - if (!hasRemovedFromRetrieval) { - DSLog(@"•••• shouldProcessDiffWithRange: persist in retrieval: %u..%u %@ .. %@", baseBlockHeight, blockHeight, uint256_reverse_hex(baseBlockHash), uint256_reverse_hex(blockHash)); - return ProcessingError_PersistInRetrieval; - } - NSData *blockHashData = uint256_data(blockHash); - DSMasternodeList *list = processorContext.masternodeListLookup(blockHash); - BOOL needToVerifyRotatedQuorums = processorContext.isDIP0024 && (!manager.quorumRotationService.masternodeListAtH || [manager.quorumRotationService.masternodeListAtH hasUnverifiedRotatedQuorums]); - BOOL needToVerifyNonRotatedQuorums = !processorContext.isDIP0024 && [list hasUnverifiedNonRotatedQuorums]; - BOOL noNeedToVerifyQuorums = !(needToVerifyRotatedQuorums || needToVerifyNonRotatedQuorums); - BOOL hasLocallyStored = [manager.store hasMasternodeListAt:blockHashData]; - if (hasLocallyStored && noNeedToVerifyQuorums) { - DSLog(@"•••• shouldProcessDiffWithRange: already persist: %u: %@ needToVerifyRotatedQuorums: %d needToVerifyNonRotatedQuorums: %d", blockHeight, uint256_reverse_hex(blockHash), needToVerifyRotatedQuorums, needToVerifyNonRotatedQuorums); - [service removeFromRetrievalQueue:blockHashData]; - return ProcessingError_LocallyStored; - } - DSMasternodeList *baseMasternodeList = processorContext.masternodeListLookup(baseBlockHash); - if (!baseMasternodeList && !uint256_eq(chain.genesisHash, baseBlockHash) && uint256_is_not_zero(baseBlockHash)) { - // this could have been deleted in the meantime, if so rerequest - [service issueWithMasternodeListFromPeer:processorContext.peer]; - DSLog(@"•••• No base masternode list at: %d: %@", baseBlockHeight, uint256_reverse_hex(baseBlockHash)); - return ProcessingError_HasNoBaseBlockHash; - } + error = [AS_OBJC(context) shouldProcessDiffWithRange:baseBlockHash blockHash:blockHash]; } - return ProcessingError_None; + return error; } /// @@ -277,7 +232,7 @@ - (void)processMasternodeDiffWith:(NSData *)message context:(DSMasternodeProcess context.peer ? context.peer.version : context.chain.protocolVersion, self.processor, self.processorCache, - (__bridge void *)(context)); + AS_RUST(context)); DSMnDiffProcessingResult *processingResult = [DSMnDiffProcessingResult processingResultWith:result onChain:context.chain]; processor_destroy_mnlistdiff_result(result); completion(processingResult); @@ -296,7 +251,7 @@ - (void)processQRInfoWith:(NSData *)message context:(DSMasternodeProcessorContex context.peer ? context.peer.version : context.chain.protocolVersion, self.processor, self.processorCache, - (__bridge void *)(context)); + AS_RUST(context)); DSQRInfoProcessingResult *processingResult = [DSQRInfoProcessingResult processingResultWith:result onChain:context.chain]; processor_destroy_qr_info_result(result); completion(processingResult); @@ -316,7 +271,7 @@ - (DSMnDiffProcessingResult *)processMasternodeDiffFromFile:(NSData *)message pr protocolVersion, self.processor, self.processorCache, - (__bridge void *)(context)); + AS_RUST(context)); } DSMnDiffProcessingResult *processingResult = [DSMnDiffProcessingResult processingResultWith:result onChain:context.chain]; processor_destroy_mnlistdiff_result(result); diff --git a/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.h b/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.h index bbfb58fde..22d5c5743 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.h +++ b/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.h @@ -18,6 +18,7 @@ #import "BigIntTypes.h" #import "DSChain.h" #import "DSMasternodeList.h" +#import "DSQuorumSnapshot.h" #import "DSPeer.h" #import @@ -38,8 +39,22 @@ typedef DSMerkleBlock *_Nullable(^_Nullable MerkleBlockFinder)(UInt256 blockHash @property (nonatomic, copy) BlockHeightFinder blockHeightLookup; @property (nonatomic, copy) MerkleRootFinder merkleRootLookup; + +- (uint32_t)blockHeightForBlockHash:(UInt256)blockHash; +- (UInt256)merkleRootForBlockHash:(UInt256)blockHash; +- (DSBlock *_Nullable)blockForBlockHeight:(uint32_t)blockHeight; +- (NSData *_Nullable)CLSignatureForBlockHash:(UInt256)blockHash; +- (DSQuorumSnapshot *_Nullable)quorumSnapshotForBlockHash:(UInt256)blockHash; +- (DSMasternodeList *_Nullable)masternodeListForBlockHash:(UInt256)blockHash; + - (BOOL)saveCLSignature:(UInt256)blockHash signature:(UInt768)signature; +- (BOOL)saveQuorumSnapshot:(DSQuorumSnapshot *)snapshot; +- (BOOL)saveMasternodeList:(DSMasternodeList *)masternodeList forBlockHash:(UInt256)blockHash; + + + - (void)blockUntilGetInsightForBlockHash:(UInt256)blockHash; +- (ProcessingError)shouldProcessDiffWithRange:(UInt256)baseBlockHash blockHash:(UInt256)blockHash; @end diff --git a/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.m b/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.m index e4a9e9db9..1e53060b1 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.m +++ b/DashSync/shared/Models/Masternode/DSMasternodeProcessorContext.m @@ -23,16 +23,84 @@ @implementation DSMasternodeProcessorContext -- (NSString *)description { - return [[super description] stringByAppendingString:[NSString stringWithFormat:@" {%@}: [%@: %@ (%u)] genesis: %@ protocol: %u, insight: %i, from_snapshot: %i, dip-24: %i}", self.chain.name, self.peer.location, self.peer.useragent, self.peer.version, uint256_hex(self.chain.genesisHash), self.chain.protocolVersion, self.useInsightAsBackup, self.isFromSnapshot, self.isDIP0024]]; +- (uint32_t)blockHeightForBlockHash:(UInt256)blockHash { + return self.blockHeightLookup(blockHash); +} + +- (DSMerkleBlock *_Nullable)blockForBlockHeight:(uint32_t)blockHeight { + return [self.chain blockAtHeight:blockHeight]; + +} +- (UInt256)merkleRootForBlockHash:(UInt256)blockHash { + return self.merkleRootLookup(blockHash); +} + +- (NSData *_Nullable)CLSignatureForBlockHash:(UInt256)blockHash { + return [self.chain.chainManager.masternodeManager CLSignatureForBlockHash:blockHash]; +} + +- (DSQuorumSnapshot *_Nullable)quorumSnapshotForBlockHash:(UInt256)blockHash { + return [self.chain.chainManager.masternodeManager quorumSnapshotForBlockHash:blockHash]; +} + +- (DSMasternodeList *_Nullable)masternodeListForBlockHash:(UInt256)blockHash { + return self.masternodeListLookup(blockHash); } - (BOOL)saveCLSignature:(UInt256)blockHash signature:(UInt768)signature { return [self.chain.chainManager.masternodeManager saveCLSignature:uint256_data(blockHash) signatureData:uint768_data(signature)]; } +- (BOOL)saveQuorumSnapshot:(DSQuorumSnapshot *)snapshot { + return [self.chain.chainManager.masternodeManager saveQuorumSnapshot:snapshot]; +} + +- (BOOL)saveMasternodeList:(DSMasternodeList *)masternodeList forBlockHash:(UInt256)blockHash { + return [self.chain.chainManager.masternodeManager saveMasternodeList:masternodeList forBlockHash:blockHash]; +} + - (void)blockUntilGetInsightForBlockHash:(UInt256)blockHash { [self.chain blockUntilGetInsightForBlockHash:blockHash]; } +- (NSString *)description { + return [[super description] stringByAppendingString:[NSString stringWithFormat:@" {%@}: [%@: %@ (%u)] genesis: %@ protocol: %u, insight: %i, from_snapshot: %i, dip-24: %i}", self.chain.name, self.peer.location, self.peer.useragent, self.peer.version, uint256_hex(self.chain.genesisHash), self.chain.protocolVersion, self.useInsightAsBackup, self.isFromSnapshot, self.isDIP0024]]; +} + +- (ProcessingError)shouldProcessDiffWithRange:(UInt256)baseBlockHash blockHash:(UInt256)blockHash { + uint32_t baseBlockHeight = [self blockHeightForBlockHash:baseBlockHash]; + uint32_t blockHeight = [self blockHeightForBlockHash:blockHash]; + if (blockHeight == UINT32_MAX) { + DSLog(@"•••• shouldProcessDiffWithRange: unknown blockHash: %u..%u %@ .. %@", baseBlockHeight, blockHeight, uint256_reverse_hex(baseBlockHash), uint256_reverse_hex(blockHash)); + return ProcessingError_UnknownBlockHash; + } + DSChain *chain = self.chain; + DSMasternodeManager *manager = chain.chainManager.masternodeManager; + DSMasternodeListService *service = self.isDIP0024 ? manager.quorumRotationService : manager.masternodeListDiffService; + BOOL hasRemovedFromRetrieval = [service removeRequestInRetrievalForBaseBlockHash:baseBlockHash blockHash:blockHash]; + if (!hasRemovedFromRetrieval) { + DSLog(@"•••• shouldProcessDiffWithRange: persist in retrieval: %u..%u %@ .. %@", baseBlockHeight, blockHeight, uint256_reverse_hex(baseBlockHash), uint256_reverse_hex(blockHash)); + return ProcessingError_PersistInRetrieval; + } + NSData *blockHashData = uint256_data(blockHash); + DSMasternodeList *list = self.masternodeListLookup(blockHash); + BOOL needToVerifyRotatedQuorums = self.isDIP0024 && (!manager.quorumRotationService.masternodeListAtH || [manager.quorumRotationService.masternodeListAtH hasUnverifiedRotatedQuorums]); + BOOL needToVerifyNonRotatedQuorums = !self.isDIP0024 && [list hasUnverifiedNonRotatedQuorums]; + BOOL noNeedToVerifyQuorums = !(needToVerifyRotatedQuorums || needToVerifyNonRotatedQuorums); + BOOL hasLocallyStored = [manager.store hasMasternodeListAt:blockHashData]; + if (hasLocallyStored && noNeedToVerifyQuorums) { + DSLog(@"•••• shouldProcessDiffWithRange: already persist: %u: %@ needToVerifyRotatedQuorums: %d needToVerifyNonRotatedQuorums: %d", blockHeight, uint256_reverse_hex(blockHash), needToVerifyRotatedQuorums, needToVerifyNonRotatedQuorums); + [service removeFromRetrievalQueue:blockHashData]; + return ProcessingError_LocallyStored; + } + DSMasternodeList *baseMasternodeList = self.masternodeListLookup(baseBlockHash); + if (!baseMasternodeList && !uint256_eq(chain.genesisHash, baseBlockHash) && uint256_is_not_zero(baseBlockHash)) { + // this could have been deleted in the meantime, if so rerequest + [service issueWithMasternodeListFromPeer:self.peer]; + DSLog(@"•••• No base masternode list at: %d: %@", baseBlockHeight, uint256_reverse_hex(baseBlockHash)); + return ProcessingError_HasNoBaseBlockHash; + } + return ProcessingError_None; +} + @end From aa33ef7a47fbaacfacef9f557757e593f5ccb81c Mon Sep 17 00:00:00 2001 From: pankcuf Date: Mon, 30 Oct 2023 20:33:10 +0700 Subject: [PATCH 06/32] fix: migration sqlite --- .../Persistence/Migration/Internal/DSCoreDataMigrationVersion.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DashSync/shared/Models/Persistence/Migration/Internal/DSCoreDataMigrationVersion.m b/DashSync/shared/Models/Persistence/Migration/Internal/DSCoreDataMigrationVersion.m index 3fed0b6bd..5703cf186 100644 --- a/DashSync/shared/Models/Persistence/Migration/Internal/DSCoreDataMigrationVersion.m +++ b/DashSync/shared/Models/Persistence/Migration/Internal/DSCoreDataMigrationVersion.m @@ -20,7 +20,7 @@ @implementation DSCoreDataMigrationVersion + (DSCoreDataMigrationVersionValue)current { - return DSCoreDataMigrationVersionValue_19; + return DSCoreDataMigrationVersionValue_20; } + (NSString *)modelResourceForVersion:(DSCoreDataMigrationVersionValue)version { From a814e30af0a693c4802e84307fda9c7930557a0b Mon Sep 17 00:00:00 2001 From: Andrei Ashikhmin Date: Tue, 31 Oct 2023 19:10:25 +0700 Subject: [PATCH 07/32] fix: change the source of exchange rates from dashretail.org to ctx.com --- .../Price/FetchOperations/DSFetchDashRetailPricesOperation.m | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DashSync/shared/Models/Managers/Service Managers/Price/FetchOperations/DSFetchDashRetailPricesOperation.m b/DashSync/shared/Models/Managers/Service Managers/Price/FetchOperations/DSFetchDashRetailPricesOperation.m index a3d26fabd..9db2a44fc 100644 --- a/DashSync/shared/Models/Managers/Service Managers/Price/FetchOperations/DSFetchDashRetailPricesOperation.m +++ b/DashSync/shared/Models/Managers/Service Managers/Price/FetchOperations/DSFetchDashRetailPricesOperation.m @@ -21,7 +21,7 @@ NS_ASSUME_NONNULL_BEGIN -#define DASHRETAIL_TICKER_URL @"https://rates2.dashretail.org/rates?source=dashretail" +#define DASHRETAIL_TICKER_URL @"https://rates.ctx.com/rates?source=ctx" // former https://rates2.dashretail.org/ @interface DSFetchDashRetailPricesOperation () @@ -61,7 +61,7 @@ - (void)finishedWithErrors:(NSArray *)errors { } + (NSString *)priceSourceInfo { - return @"dashretail.org"; + return @"ctx.com"; } @end From 0b383ce9f80a1cc64b5588565ce87b6b63076174 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Wed, 1 Nov 2023 13:26:22 +0700 Subject: [PATCH 08/32] chore: dash-shared-core fix/core-20-test 824b34b521ed9f4865400daf7ae65c6b453218a2 --- Example/Podfile | 2 +- Example/Podfile.lock | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/Example/Podfile b/Example/Podfile index c244c6668..f76fc4671 100644 --- a/Example/Podfile +++ b/Example/Podfile @@ -1,5 +1,5 @@ def common_pods -# pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :branch => 'feat/core-20-beacons' + pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :branch => 'fix/core-20-test' # pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :commit => 'e2dc943' pod 'DashSync', :path => '../' pod 'SDWebImage', '5.14.3' diff --git a/Example/Podfile.lock b/Example/Podfile.lock index 25c2ac872..9a2a832cd 100644 --- a/Example/Podfile.lock +++ b/Example/Podfile.lock @@ -667,6 +667,7 @@ PODS: DEPENDENCIES: - CocoaImageHashing (from `https://github.com/ameingast/cocoaimagehashing.git`, commit `ad01eee`) + - DashSharedCore (from `https://github.com/dashpay/dash-shared-core.git`, branch `fix/core-20-test`) - DashSync (from `../`) - KVO-MVVM (= 0.5.1) - SDWebImage (= 5.14.3) @@ -679,7 +680,6 @@ SPEC REPOS: - BoringSSL-GRPC - CocoaLumberjack - DAPI-GRPC - - DashSharedCore - DSDynamicOptions - DWAlertController - gRPC @@ -696,6 +696,9 @@ EXTERNAL SOURCES: CocoaImageHashing: :commit: ad01eee :git: https://github.com/ameingast/cocoaimagehashing.git + DashSharedCore: + :branch: fix/core-20-test + :git: https://github.com/dashpay/dash-shared-core.git DashSync: :path: "../" @@ -703,6 +706,9 @@ CHECKOUT OPTIONS: CocoaImageHashing: :commit: ad01eee :git: https://github.com/ameingast/cocoaimagehashing.git + DashSharedCore: + :commit: 824b34b521ed9f4865400daf7ae65c6b453218a2 + :git: https://github.com/dashpay/dash-shared-core.git SPEC CHECKSUMS: "!ProtoCompiler": e9c09244955a8565817aa59a4787b6bb849a63c6 @@ -726,6 +732,6 @@ SPEC CHECKSUMS: tinycbor: d4d71dddda1f8392fbb4249f63faf8552f327590 TinyCborObjc: 5204540fb90ff0c40fb22d408fa51bab79d78a80 -PODFILE CHECKSUM: b185f6b2705cc13f4d1d87e4fa3fbfb6e4b1597f +PODFILE CHECKSUM: 1db7bfe9fa728d3d9ee296b3b5513864533505cf -COCOAPODS: 1.12.1 +COCOAPODS: 1.14.2 From d4d0eb1f9c36992033a5634b71adeaba6048ce21 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Mon, 6 Nov 2023 15:19:16 +0700 Subject: [PATCH 09/32] feat: chainlocks flow for core 20 llmq verification --- DashSync/shared/Models/Chain/DSChainLock.m | 4 +- .../Managers/Chain Managers/DSChainManager.h | 2 + .../Managers/Chain Managers/DSChainManager.m | 4 ++ .../Chain Managers/DSMasternodeManager.h | 1 + .../Chain Managers/DSMasternodeManager.m | 46 +++++++++++++------ .../DSTransactionManager+Protected.h | 2 + .../Chain Managers/DSTransactionManager.m | 5 ++ .../Masternode/DSMnDiffProcessingResult.h | 1 + .../Masternode/DSMnDiffProcessingResult.m | 10 ++++ .../shared/Models/Masternode/DSQuorumEntry.h | 1 - .../shared/Models/Masternode/DSQuorumEntry.m | 5 -- Example/Podfile.lock | 6 +-- .../DSDeterministicMasternodeListTests.m | 13 +++--- Example/Tests/DSTestnetSyncTests.m | 2 +- 14 files changed, 68 insertions(+), 34 deletions(-) diff --git a/DashSync/shared/Models/Chain/DSChainLock.m b/DashSync/shared/Models/Chain/DSChainLock.m index 8413cc2df..4f50f3e10 100644 --- a/DashSync/shared/Models/Chain/DSChainLock.m +++ b/DashSync/shared/Models/Chain/DSChainLock.m @@ -119,9 +119,9 @@ - (BOOL)verifySignatureAgainstQuorum:(DSQuorumEntry *)quorumEntry { UInt256 signId = [self signIDForQuorumEntry:quorumEntry]; BOOL verified = key_bls_verify(quorumEntry.quorumPublicKey.u8, quorumEntry.useLegacyBLSScheme, signId.u8, self.signature.u8); #if DEBUG - DSLog(@"verifySignatureAgainstQuorum (%u): %u: %u: %@: %@: %@: %@: %u", verified, quorumEntry.llmqType, quorumEntry.verified, uint256_hex([quorumEntry buildQuorumHash:nil]), @"", uint384_hex(quorumEntry.quorumPublicKey), @"", quorumEntry.useLegacyBLSScheme); + DSLog(@"verifySignatureAgainstQuorum (%u): %u: %u: %@: %@: %@: %u", verified, quorumEntry.llmqType, quorumEntry.verified, @"", uint384_hex(quorumEntry.quorumPublicKey), @"", quorumEntry.useLegacyBLSScheme); #else - DSLogPrivate(@"verifySignatureAgainstQuorum (%u): %u: %u: %@: %@: %@: %@: %u", verified, quorumEntry.llmqType, quorumEntry.verified, uint256_hex([quorumEntry buildQuorumHash:nil]), uint256_hex(signId), uint384_hex(quorumEntry.quorumPublicKey), uint768_hex(self.signature), quorumEntry.useLegacyBLSScheme); + DSLogPrivate(@"verifySignatureAgainstQuorum (%u): %u: %u: %@: %@: %@: %u", verified, quorumEntry.llmqType, quorumEntry.verified, uint256_hex(signId), uint384_hex(quorumEntry.quorumPublicKey), uint768_hex(self.signature), quorumEntry.useLegacyBLSScheme); #endif return verified; } diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.h b/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.h index 113c34187..500977193 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.h +++ b/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.h @@ -97,6 +97,8 @@ typedef void (^MultipleBlockMiningCompletionBlock)(NSArray *block - (void)mineBlockAfterBlock:(DSBlock *)block toPaymentAddress:(NSString *)paymentAddress withTransactions:(NSArray *_Nullable)transactions previousBlocks:(NSDictionary *)previousBlocks nonceOffset:(uint32_t)nonceOffset withTimeout:(NSTimeInterval)timeout completion:(BlockMiningCompletionBlock)completion; +- (DSChainLock * _Nullable)chainLockForBlockHash:(UInt256)blockHash; + @end NS_ASSUME_NONNULL_END diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m index ac679349f..d83a39795 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m @@ -794,4 +794,8 @@ - (void)wipeMasternodeInfo { [self.masternodeManager wipeMasternodeInfo]; } +- (DSChainLock * _Nullable)chainLockForBlockHash:(UInt256)blockHash { + return [self.transactionManager chainLockForBlockHash:blockHash]; +} + @end diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.h b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.h index aeba8e9ab..6f931d3c0 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.h +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.h @@ -101,6 +101,7 @@ NS_ASSUME_NONNULL_BEGIN - (void)checkPingTimesForCurrentMasternodeListInContext:(NSManagedObjectContext *)context withCompletion:(void (^)(NSMutableDictionary *pingTimes, NSMutableDictionary *errors))completion; +- (UInt256)buildLLMQHashFor:(DSQuorumEntry *)quorum; @end NS_ASSUME_NONNULL_END diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m index 79c90f2c7..67403741c 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m @@ -25,6 +25,7 @@ #import "DSMasternodeManager.h" #import "DSChain+Protected.h" +#import "DSChainLock.h" #import "DSChainManager+Protected.h" #import "DSCheckpoint.h" #import "DSGetMNListDiffRequest.h" @@ -308,7 +309,14 @@ - (NSData *_Nullable)CLSignatureForBlockHeight:(uint32_t)blockHeight { } - (NSData *_Nullable)CLSignatureForBlockHash:(UInt256)blockHash { - return [self.store.cachedCLSignatures objectForKey:uint256_data(blockHash)]; + NSData *cachedSig = [self.store.cachedCLSignatures objectForKey:uint256_data(blockHash)]; + if (!cachedSig) { + DSChainLock *chainLock = [self.chain.chainManager chainLockForBlockHash:blockHash]; + if (chainLock) { + return uint768_data(chainLock.signature); + } + } + return cachedSig; } - (BOOL)saveCLSignature:(NSData *)blockHashData signatureData:(NSData *)signatureData { @@ -540,7 +548,7 @@ - (void)processMasternodeListDiffResult:(DSMnDiffProcessingResult *)result forPe } } DSLog(@"••• updateStoreWithMasternodeList: %u: %@ (%@)", masternodeList.height, uint256_hex(masternodeListBlockHash), uint256_reverse_hex(masternodeListBlockHash)); - [self updateStoreWithMasternodeList:masternodeList addedMasternodes:result.addedMasternodes modifiedMasternodes:result.modifiedMasternodes completion:^(NSError *error) { + [self updateStoreWithProcessingResult:masternodeList result:result completion:^(NSError *error) { if ([result hasRotatedQuorumsForChain:self.chain] && !self.chain.isRotatedQuorumsPresented) { uint32_t masternodeListBlockHeight = [self heightForBlockHash:masternodeListBlockHash]; DSLog(@"•••• processMasternodeListDiffResult: rotated quorums are presented at height %u: %@, so we'll switch into consuming qrinfo", masternodeListBlockHeight, uint256_hex(masternodeListBlockHash)); @@ -616,31 +624,31 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH4C count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH4C]) { DSLog(@"••• updateStoreWithMasternodeList (h-4c): %u: %@ (%@)", masternodeListAtH4C.height, uint256_hex(blockHashAtH4C), uint256_reverse_hex(blockHashAtH4C)); - [self updateStoreWithMasternodeList:masternodeListAtH4C addedMasternodes:mnListDiffResultAtH4C.addedMasternodes modifiedMasternodes:mnListDiffResultAtH4C.modifiedMasternodes completion:^(NSError *error) {}]; + [self updateStoreWithProcessingResult:masternodeListAtH4C result:mnListDiffResultAtH4C completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH3C skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH3C count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH3C]) { DSLog(@"••• updateStoreWithMasternodeList (h-3c): %u: %@ (%@)", masternodeListAtH3C.height, uint256_hex(blockHashAtH3C), uint256_reverse_hex(blockHashAtH3C)); - [self updateStoreWithMasternodeList:masternodeListAtH3C addedMasternodes:mnListDiffResultAtH3C.addedMasternodes modifiedMasternodes:mnListDiffResultAtH3C.modifiedMasternodes completion:^(NSError *error) {}]; + [self updateStoreWithProcessingResult:masternodeListAtH3C result:mnListDiffResultAtH3C completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH2C skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH2C count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH2C]) { DSLog(@"••• updateStoreWithMasternodeList (h-2c): %u: %@ (%@)", masternodeListAtH2C.height, uint256_hex(blockHashAtH2C), uint256_reverse_hex(blockHashAtH2C)); - [self updateStoreWithMasternodeList:masternodeListAtH2C addedMasternodes:mnListDiffResultAtH2C.addedMasternodes modifiedMasternodes:mnListDiffResultAtH2C.modifiedMasternodes completion:^(NSError *error) {}]; + [self updateStoreWithProcessingResult:masternodeListAtH2C result:mnListDiffResultAtH2C completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtHC skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtHC count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtHC]) { DSLog(@"••• updateStoreWithMasternodeList (h-c): %u: %@ (%@)", masternodeListAtHC.height, uint256_hex(blockHashAtHC), uint256_reverse_hex(blockHashAtHC)); - [self updateStoreWithMasternodeList:masternodeListAtHC addedMasternodes:mnListDiffResultAtHC.addedMasternodes modifiedMasternodes:mnListDiffResultAtHC.modifiedMasternodes completion:^(NSError *error) {}]; + [self updateStoreWithProcessingResult:masternodeListAtHC result:mnListDiffResultAtHC completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH]) { DSLog(@"••• updateStoreWithMasternodeList (h): %u: %@ (%@)", masternodeListAtH.height, uint256_hex(blockHashAtH), uint256_reverse_hex(blockHashAtH)); - [self updateStoreWithMasternodeList:masternodeListAtH addedMasternodes:mnListDiffResultAtH.addedMasternodes modifiedMasternodes:mnListDiffResultAtH.modifiedMasternodes completion:^(NSError *error) {}]; + [self updateStoreWithProcessingResult:masternodeListAtH result:mnListDiffResultAtH completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtTip skipPresenceInRetrieval:YES]) { @@ -657,7 +665,7 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * } } DSLog(@"••• updateStoreWithMasternodeList (tip): %u: %@ (%@)", masternodeListAtTip.height, uint256_hex(blockHashAtTip), uint256_reverse_hex(blockHashAtTip)); - [self updateStoreWithMasternodeList:masternodeListAtTip addedMasternodes:mnListDiffResultAtTip.addedMasternodes modifiedMasternodes:mnListDiffResultAtTip.modifiedMasternodes completion:^(NSError *error) {}]; + [self updateStoreWithProcessingResult:masternodeListAtTip result:mnListDiffResultAtTip completion:^(NSError *error) {}]; [self.quorumRotationService updateAfterProcessingMasternodeListWithBlockHash:blockHashDataAtTip fromPeer:peer]; } } @@ -675,7 +683,7 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * if (![self.quorumRotationService shouldProcessDiffResult:diffResult skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![diffResult.neededMissingMasternodeLists count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:diffBlockHashData]) { - [self updateStoreWithMasternodeList:diffMasternodeList addedMasternodes:diffResult.addedMasternodes modifiedMasternodes:diffResult.modifiedMasternodes completion:^(NSError *error) {}]; + [self updateStoreWithProcessingResult:diffMasternodeList result:diffResult completion:^(NSError *error) {}]; } } for (DSQuorumSnapshot *snapshot in result.snapshotList) { @@ -683,7 +691,7 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * } for (DSQuorumEntry *entry in result.lastQuorumPerIndex) { - [self.store.activeQuorums setObject:entry forKey:uint256_data([entry buildQuorumHash:nil])]; + [self.store.activeQuorums setObject:entry forKey:uint256_data([self buildLLMQHashFor:entry])]; } } @@ -695,14 +703,14 @@ - (void)processMissingMasternodeLists:(NSOrderedSet *)neededMissingMasternodeLis [neededMasternodeLists addObject:masternodeListBlockHashData]; //also get the current one again [self getMasternodeListsForBlockHashes:neededMasternodeLists]; } - -- (void)updateStoreWithMasternodeList:(DSMasternodeList *)masternodeList addedMasternodes:(NSDictionary *)addedMasternodes modifiedMasternodes:(NSDictionary *)modifiedMasternodes completion:(void (^)(NSError *error))completion { +- (void)updateStoreWithProcessingResult:(DSMasternodeList *)masternodeList result:(DSMnDiffProcessingResult *)result completion:(void (^)(NSError *error))completion { if (uint256_eq(self.store.masternodeListAwaitingQuorumValidation.blockHash, masternodeList.blockHash)) { self.store.masternodeListAwaitingQuorumValidation = nil; } + [self.store.cachedCLSignatures addEntriesFromDictionary:result.clSignatures]; [self.store saveMasternodeList:masternodeList - addedMasternodes:addedMasternodes - modifiedMasternodes:modifiedMasternodes + addedMasternodes:result.addedMasternodes + modifiedMasternodes:result.modifiedMasternodes completion:^(NSError *error) { completion(error); if (!error || !([self.masternodeListDiffService retrievalQueueCount] + [self.quorumRotationService retrievalQueueCount])) { //if it is 0 then we most likely have wiped chain info @@ -713,7 +721,6 @@ - (void)updateStoreWithMasternodeList:(DSMasternodeList *)masternodeList addedMa [self getRecentMasternodeList]; }); }]; - } - (void)peer:(DSPeer *)peer relayedMasternodeDiffMessage:(NSData *)message { @@ -873,4 +880,13 @@ - (void)checkPingTimesForCurrentMasternodeListInContext:(NSManagedObjectContext } +- (UInt256)buildLLMQHashFor:(DSQuorumEntry *)quorum { + uint32_t workHeight = [self heightForBlockHash:quorum.quorumHash] - 8; + if (workHeight >= chain_core20_activation_height(self.chain.chainType)) { + NSData *bestCLSignature = [self CLSignatureForBlockHeight:workHeight]; + return [DSKeyManager NSDataFrom:quorum_build_llmq_hash_v20(quorum.llmqType, workHeight, bestCLSignature.bytes)].UInt256; + } else { + return [DSKeyManager NSDataFrom:quorum_build_llmq_hash(quorum.llmqType, quorum.quorumHash.u8)].UInt256; + } +} @end diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager+Protected.h b/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager+Protected.h index ef6c30ac3..a3d5b915e 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager+Protected.h +++ b/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager+Protected.h @@ -44,6 +44,8 @@ NS_ASSUME_NONNULL_BEGIN - (void)fetchMempoolFromPeer:(DSPeer *)peer; - (void)fetchMempoolFromNetwork; +- (DSChainLock * _Nullable)chainLockForBlockHash:(UInt256)blockHash; + @end NS_ASSUME_NONNULL_END diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m index 58cbb9e8d..866e476e8 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m @@ -1787,4 +1787,9 @@ - (void)checkWaitingForQuorums { [self checkChainLocksWaitingForQuorums]; } +- (DSChainLock * _Nullable)chainLockForBlockHash:(UInt256)blockHash { + DSChainLock *chainLock = [self.chainLocksWaitingForQuorums objectForKey:uint256_data(blockHash)]; + return chainLock; +} + @end diff --git a/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.h b/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.h index e00fc3837..629096b54 100644 --- a/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.h +++ b/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.h @@ -36,6 +36,7 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic) NSDictionary *modifiedMasternodes; @property (nonatomic) NSArray *addedQuorums; @property (nonatomic) NSOrderedSet *neededMissingMasternodeLists; +@property (nonatomic) NSDictionary *clSignatures; + (instancetype)processingResultWith:(MNListDiffResult *)result onChain:(DSChain *)chain; diff --git a/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.m b/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.m index 3c2965e69..7e3ddd912 100644 --- a/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.m +++ b/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.m @@ -15,6 +15,7 @@ // limitations under the License. // +#import "NSData+Dash.h" #import "DSMnDiffProcessingResult.h" #import "DSMasternodeList+Mndiff.h" #import "DSQuorumEntry+Mndiff.h" @@ -59,6 +60,15 @@ + (instancetype)processingResultWith:(MNListDiffResult *)result onChain:(DSChain [neededMissingMasternodeLists addObject:hash]; } [processingResult setNeededMissingMasternodeLists:[neededMissingMasternodeLists copy]]; + uint8_t (**quorums_cl_signatures_hashes)[32] = result->quorums_cl_signatures_hashes; + uint8_t (**quorums_cl_signatures)[96] = result->quorums_cl_signatures; + uintptr_t quorums_cl_sigs_count = result->quorums_cl_sigs_count; + NSMutableDictionary *clSignatures = [NSMutableDictionary dictionaryWithCapacity:quorums_cl_sigs_count]; + for (NSUInteger i = 0; i < quorums_cl_sigs_count; i++) { + [clSignatures setObject:uint768_data(*(UInt768 *)quorums_cl_signatures[i]) + forKey:uint256_data(*(UInt256 *)quorums_cl_signatures_hashes[i])]; + } + [processingResult setClSignatures:clSignatures]; return processingResult; } diff --git a/DashSync/shared/Models/Masternode/DSQuorumEntry.h b/DashSync/shared/Models/Masternode/DSQuorumEntry.h index c984de2b8..c211c2633 100644 --- a/DashSync/shared/Models/Masternode/DSQuorumEntry.h +++ b/DashSync/shared/Models/Masternode/DSQuorumEntry.h @@ -66,7 +66,6 @@ allCommitmentAggregatedSignature:(UInt768)allCommitmentAggregatedSignature - (void)mergedWithQuorumEntry:(DSQuorumEntry *)quorumEntry; - (BOOL)useLegacyBLSScheme; -- (UInt256)buildQuorumHash:(NSData *_Nullable)bestCLSignature; @end diff --git a/DashSync/shared/Models/Masternode/DSQuorumEntry.m b/DashSync/shared/Models/Masternode/DSQuorumEntry.m index aef787aff..f47957964 100644 --- a/DashSync/shared/Models/Masternode/DSQuorumEntry.m +++ b/DashSync/shared/Models/Masternode/DSQuorumEntry.m @@ -187,11 +187,6 @@ - (uint32_t)quorumThreshold { return quorum_threshold_for_type(self.llmqType); } -- (UInt256)buildQuorumHash:(NSData *_Nullable)bestCLSignature /*UInt768*/{ - return [DSKeyManager NSDataFrom:quorum_build_llmq_hash(self.llmqType, self.quorumHash.u8, bestCLSignature.bytes)].UInt256; - -} - - (BOOL)validateWithMasternodeList:(DSMasternodeList *)masternodeList { return [self validateWithMasternodeList:masternodeList blockHeightLookup:^uint32_t(UInt256 blockHash) { diff --git a/Example/Podfile.lock b/Example/Podfile.lock index 9a2a832cd..007eb6b62 100644 --- a/Example/Podfile.lock +++ b/Example/Podfile.lock @@ -657,7 +657,7 @@ PODS: - gRPC/Interface-Legacy (1.49.0): - gRPC-RxLibrary/Interface (= 1.49.0) - KVO-MVVM (0.5.1) - - Protobuf (3.24.4) + - Protobuf (3.25.0) - SDWebImage (5.14.3): - SDWebImage/Core (= 5.14.3) - SDWebImage/Core (5.14.3) @@ -707,7 +707,7 @@ CHECKOUT OPTIONS: :commit: ad01eee :git: https://github.com/ameingast/cocoaimagehashing.git DashSharedCore: - :commit: 824b34b521ed9f4865400daf7ae65c6b453218a2 + :commit: bd73bff9593cee5c7ee9c80231808b3f21e3b387 :git: https://github.com/dashpay/dash-shared-core.git SPEC CHECKSUMS: @@ -727,7 +727,7 @@ SPEC CHECKSUMS: gRPC-ProtoRPC: 1c223e0f1732bb8d0b9e9e0ea60cc0fe995b8e2d gRPC-RxLibrary: 92327f150e11cf3b1c0f52e083944fd9f5cb5d1e KVO-MVVM: 4df3afd1f7ebcb69735458b85db59c4271ada7c6 - Protobuf: 351e9022fe13a6e2af00e9aefc22077cb88520f8 + Protobuf: 6a4183ec1d51649eb2be7b86ccc286e5c539219c SDWebImage: 9c36e66c8ce4620b41a7407698dda44211a96764 tinycbor: d4d71dddda1f8392fbb4249f63faf8552f327590 TinyCborObjc: 5204540fb90ff0c40fb22d408fa51bab79d78a80 diff --git a/Example/Tests/DSDeterministicMasternodeListTests.m b/Example/Tests/DSDeterministicMasternodeListTests.m index ab58853b5..f8e9b31e6 100644 --- a/Example/Tests/DSDeterministicMasternodeListTests.m +++ b/Example/Tests/DSDeterministicMasternodeListTests.m @@ -2875,9 +2875,9 @@ - (void)testMNLSavingAndRetrievingInIncorrectOrderFromDisk { XCTAssert(result1092940.validQuorums, @"validQuorums not valid at height %u", [chain heightForBlockHash:blockHash1092940]); DSQuorumEntry *quorum1092912 = [result1092940.addedQuorums firstObject]; // 1092912 and 1092916 are the same, 1092916 is older though and is original 1092912 is based off a reloaded 109 - NSArray *masternodeScores1092912 = [masternodeList1092912 scoresForQuorumModifier:[quorum1092912 buildQuorumHash:nil] atBlockHeight:1092912]; - NSArray *masternodeScores1092916 = [masternodeList1092916 scoresForQuorumModifier:[quorum1092912 buildQuorumHash: nil] atBlockHeight:1092912]; - + UInt256 llmqHash1092912 = [chain.chainManager.masternodeManager buildLLMQHashFor:quorum1092912]; + NSArray *masternodeScores1092912 = [masternodeList1092912 scoresForQuorumModifier:llmqHash1092912 atBlockHeight:1092912]; + NSArray *masternodeScores1092916 = [masternodeList1092916 scoresForQuorumModifier:llmqHash1092912 atBlockHeight:1092912]; // BOOL a = [quorum1092912 validateWithMasternodeList:masternodeList1092912]; // // BOOL b = [quorum1092912 validateWithMasternodeList:masternodeList1092916]; @@ -2901,10 +2901,9 @@ - (void)testMNLSavingAndRetrievingInIncorrectOrderFromDisk { // NSDictionary * interesting = [masternodeList1092912 compare:masternodeList1092916]; XCTAssertEqualObjects(masternodeScores1092912, masternodeScores1092916, @"These should be the same"); + NSArray *masternodes1092912 = [masternodeList1092912 validMasternodesForQuorumModifier:llmqHash1092912 quorumCount:[DSQuorumEntry quorumSizeForType:quorum1092912.llmqType] blockHeight:blockHeightLookup(masternodeList1092912.blockHash)]; - NSArray *masternodes1092912 = [masternodeList1092912 validMasternodesForQuorumModifier:[quorum1092912 buildQuorumHash:nil] quorumCount:[DSQuorumEntry quorumSizeForType:quorum1092912.llmqType] blockHeight:blockHeightLookup(masternodeList1092912.blockHash)]; - - NSArray *masternodes1092916 = [masternodeList1092916 validMasternodesForQuorumModifier:[quorum1092912 buildQuorumHash:nil] quorumCount:[DSQuorumEntry quorumSizeForType:quorum1092912.llmqType] blockHeight:blockHeightLookup(masternodeList1092916.blockHash)]; + NSArray *masternodes1092916 = [masternodeList1092916 validMasternodesForQuorumModifier:llmqHash1092912 quorumCount:[DSQuorumEntry quorumSizeForType:quorum1092912.llmqType] blockHeight:blockHeightLookup(masternodeList1092916.blockHash)]; XCTAssertEqualObjects(masternodes1092912, masternodes1092916, @"These should be the same"); // NSMutableArray * publicKeyArray = [NSMutableArray array]; // uint32_t i = 0; @@ -3215,7 +3214,7 @@ - (void)testTestnetSizeQuorumVerification { XCTAssert(quorumToVerify, @"There should be a quorum using 119064"); DSMasternodeList *masternodeList370944 = result370944.masternodeList; - NSArray *masternodes = [masternodeList370944 validMasternodesForQuorumModifier:[quorumToVerify buildQuorumHash:NULL] quorumCount:[DSQuorumEntry quorumSizeForType:quorumToVerify.llmqType] blockHeight:370944]; + NSArray *masternodes = [masternodeList370944 validMasternodesForQuorumModifier:[chain.chainManager.masternodeManager buildLLMQHashFor:quorumToVerify] quorumCount:[DSQuorumEntry quorumSizeForType:quorumToVerify.llmqType] blockHeight:370944]; NSArray *masternodeHashOrder = [masternodes map:^(DSSimplifiedMasternodeEntry *masternode) { return uint256_reverse_hex([masternode providerRegistrationTransactionHash]); diff --git a/Example/Tests/DSTestnetSyncTests.m b/Example/Tests/DSTestnetSyncTests.m index 1f43c5e62..36a151e8a 100644 --- a/Example/Tests/DSTestnetSyncTests.m +++ b/Example/Tests/DSTestnetSyncTests.m @@ -94,7 +94,7 @@ - (void)testTestnetFullHeadersSync { [headerFinishedExpectation fulfill]; }]; }); - [self waitForExpectations:@[headerFinishedExpectation] timeout:600]; + [self waitForExpectations:@[headerFinishedExpectation] timeout:900]; [[NSNotificationCenter defaultCenter] removeObserver:self.txStatusObserver]; } From c2e281b5e5d0159dc107f5df7bb9ea0c9c96575f Mon Sep 17 00:00:00 2001 From: pankcuf Date: Mon, 6 Nov 2023 16:06:16 +0700 Subject: [PATCH 10/32] chore: refactor lastQuorumPerIndex --- .../Models/Managers/Chain Managers/DSMasternodeManager.m | 6 +++--- DashSync/shared/Models/Masternode/DSMasternodeListStore.h | 2 +- DashSync/shared/Models/Masternode/DSMasternodeListStore.m | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m index 67403741c..27a1aea41 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m @@ -690,9 +690,7 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * [self.store saveQuorumSnapshot:snapshot toChain:self.chain completion:^(NSError * _Nonnull error) {}]; } - for (DSQuorumEntry *entry in result.lastQuorumPerIndex) { - [self.store.activeQuorums setObject:entry forKey:uint256_data([self buildLLMQHashFor:entry])]; - } + [self.store.activeQuorums unionOrderedSet:result.lastQuorumPerIndex]; } - (void)processMissingMasternodeLists:(NSOrderedSet *)neededMissingMasternodeLists forMasternodeList:(DSMasternodeList *)masternodeList { @@ -883,9 +881,11 @@ - (void)checkPingTimesForCurrentMasternodeListInContext:(NSManagedObjectContext - (UInt256)buildLLMQHashFor:(DSQuorumEntry *)quorum { uint32_t workHeight = [self heightForBlockHash:quorum.quorumHash] - 8; if (workHeight >= chain_core20_activation_height(self.chain.chainType)) { + DSLog(@"buildLLMQHashFor: [%u: %u] (core 20): %@", quorum.llmqType, workHeight, uint256_hex(quorum.quorumHash)); NSData *bestCLSignature = [self CLSignatureForBlockHeight:workHeight]; return [DSKeyManager NSDataFrom:quorum_build_llmq_hash_v20(quorum.llmqType, workHeight, bestCLSignature.bytes)].UInt256; } else { + DSLog(@"buildLLMQHashFor: [%u: %u] (pre core 20): %@", quorum.llmqType, workHeight, uint256_hex(quorum.quorumHash)); return [DSKeyManager NSDataFrom:quorum_build_llmq_hash(quorum.llmqType, quorum.quorumHash.u8)].UInt256; } } diff --git a/DashSync/shared/Models/Masternode/DSMasternodeListStore.h b/DashSync/shared/Models/Masternode/DSMasternodeListStore.h index f63207b00..939f15720 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeListStore.h +++ b/DashSync/shared/Models/Masternode/DSMasternodeListStore.h @@ -39,7 +39,7 @@ FOUNDATION_EXPORT NSString *const DSQuorumListDidChangeNotification; @property (nonatomic, readonly) uint32_t lastMasternodeListBlockHeight; @property (nonatomic, readonly) NSMutableDictionary *masternodeListsByBlockHash; @property (nonatomic, readonly) NSMutableSet *masternodeListsBlockHashStubs; -@property (nonatomic, readonly) NSMutableDictionary *activeQuorums; +@property (nonatomic, readonly) NSMutableOrderedSet *activeQuorums; @property (nonatomic, readonly) uint32_t masternodeListsToSync; @property (nonatomic, readonly) BOOL masternodeListsAndQuorumsIsSynced; diff --git a/DashSync/shared/Models/Masternode/DSMasternodeListStore.m b/DashSync/shared/Models/Masternode/DSMasternodeListStore.m index 69473b1cb..bd56eca67 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeListStore.m +++ b/DashSync/shared/Models/Masternode/DSMasternodeListStore.m @@ -49,7 +49,7 @@ @interface DSMasternodeListStore () @property (nonatomic, strong) dispatch_queue_t masternodeSavingQueue; @property (nonatomic, assign) UInt256 lastQueriedBlockHash; //last by height, not by time queried @property (atomic, assign) uint32_t masternodeListCurrentlyBeingSavedCount; -@property (nonatomic, strong) NSMutableDictionary *activeQuorums; +@property (nonatomic, strong) NSMutableOrderedSet *activeQuorums; @property (nonatomic, strong) dispatch_group_t savingGroup; @end From c9ee6fd7843ba46262dc0e0f6410fcf60d13fe41 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Mon, 6 Nov 2023 17:26:43 +0700 Subject: [PATCH 11/32] chore: bump up DashSharedCore 0.4.13 --- DashSync.podspec | 2 +- DashSync/shared/Models/Masternode/DSMasternodeListService.m | 2 +- Example/Podfile | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/DashSync.podspec b/DashSync.podspec index 6e9644157..985e1d19e 100644 --- a/DashSync.podspec +++ b/DashSync.podspec @@ -34,7 +34,7 @@ Pod::Spec.new do |s| s.ios.framework = 'UIKit' s.macos.framework = 'Cocoa' s.compiler_flags = '-Wno-comma' - s.dependency 'DashSharedCore', '0.4.12' + s.dependency 'DashSharedCore', '0.4.13' s.dependency 'CocoaLumberjack', '3.7.2' s.ios.dependency 'DWAlertController', '0.2.1' s.dependency 'DSDynamicOptions', '0.1.2' diff --git a/DashSync/shared/Models/Masternode/DSMasternodeListService.m b/DashSync/shared/Models/Masternode/DSMasternodeListService.m index 3bdc7a787..38d78b3dc 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeListService.m +++ b/DashSync/shared/Models/Masternode/DSMasternodeListService.m @@ -198,7 +198,7 @@ - (BOOL)shouldProcessDiffResult:(DSMnDiffProcessingResult *)diffResult skipPrese BOOL hasInRetrieval = [self.retrievalQueue containsObject:masternodeListBlockHashData]; uint32_t masternodeListBlockHeight = [self.store heightForBlockHash:masternodeListBlockHash]; BOOL shouldNot = !hasInRetrieval && !skipPresenceInRetrieval; - DSLog(@"•••• shouldProcessDiffResult: %d: %@ %d", masternodeListBlockHeight, uint256_reverse_hex(masternodeListBlockHash), !shouldNot); + //DSLog(@"•••• shouldProcessDiffResult: %d: %@ %d", masternodeListBlockHeight, uint256_reverse_hex(masternodeListBlockHash), !shouldNot); if (shouldNot) { //We most likely wiped data in the meantime [self cleanRequestsInRetrieval]; diff --git a/Example/Podfile b/Example/Podfile index f76fc4671..725f93d95 100644 --- a/Example/Podfile +++ b/Example/Podfile @@ -1,5 +1,5 @@ def common_pods - pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :branch => 'fix/core-20-test' +# pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :branch => 'fix/core-20-test' # pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :commit => 'e2dc943' pod 'DashSync', :path => '../' pod 'SDWebImage', '5.14.3' From 9308e62ee204a26826ccdf7816573c1fbf4a0d09 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Mon, 6 Nov 2023 18:08:11 +0700 Subject: [PATCH 12/32] chore: up Podfile.lock --- Example/Podfile.lock | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/Example/Podfile.lock b/Example/Podfile.lock index 007eb6b62..dc078a858 100644 --- a/Example/Podfile.lock +++ b/Example/Podfile.lock @@ -586,11 +586,11 @@ PODS: - "!ProtoCompiler-gRPCPlugin (~> 1.0)" - DAPI-GRPC/Messages - gRPC-ProtoRPC - - DashSharedCore (0.4.12) + - DashSharedCore (0.4.13) - DashSync (0.1.0): - CocoaLumberjack (= 3.7.2) - DAPI-GRPC (= 0.22.0-dev.8) - - DashSharedCore (= 0.4.12) + - DashSharedCore (= 0.4.13) - DSDynamicOptions (= 0.1.2) - DWAlertController (= 0.2.1) - TinyCborObjc (= 0.4.6) @@ -667,7 +667,6 @@ PODS: DEPENDENCIES: - CocoaImageHashing (from `https://github.com/ameingast/cocoaimagehashing.git`, commit `ad01eee`) - - DashSharedCore (from `https://github.com/dashpay/dash-shared-core.git`, branch `fix/core-20-test`) - DashSync (from `../`) - KVO-MVVM (= 0.5.1) - SDWebImage (= 5.14.3) @@ -680,6 +679,7 @@ SPEC REPOS: - BoringSSL-GRPC - CocoaLumberjack - DAPI-GRPC + - DashSharedCore - DSDynamicOptions - DWAlertController - gRPC @@ -696,9 +696,6 @@ EXTERNAL SOURCES: CocoaImageHashing: :commit: ad01eee :git: https://github.com/ameingast/cocoaimagehashing.git - DashSharedCore: - :branch: fix/core-20-test - :git: https://github.com/dashpay/dash-shared-core.git DashSync: :path: "../" @@ -706,9 +703,6 @@ CHECKOUT OPTIONS: CocoaImageHashing: :commit: ad01eee :git: https://github.com/ameingast/cocoaimagehashing.git - DashSharedCore: - :commit: bd73bff9593cee5c7ee9c80231808b3f21e3b387 - :git: https://github.com/dashpay/dash-shared-core.git SPEC CHECKSUMS: "!ProtoCompiler": e9c09244955a8565817aa59a4787b6bb849a63c6 @@ -718,8 +712,8 @@ SPEC CHECKSUMS: CocoaImageHashing: 8656031d0899abe6c1c415827de43e9798189c53 CocoaLumberjack: b7e05132ff94f6ae4dfa9d5bce9141893a21d9da DAPI-GRPC: 138d62523bbfe7e88a39896f1053c0bc12390d9f - DashSharedCore: 842f752df2a9cdb357b377c1a1abebdac5c0cefa - DashSync: 86a678ae3bc1600245ade93c22acd90377ffb3b6 + DashSharedCore: 46e9d9fb8b934933f319ece1ae35b9914e4c1a24 + DashSync: 81344e983fe2afe12c2b98c32ea50e20fed186f9 DSDynamicOptions: 347cc5d2c4e080eb3de6a86719ad3d861b82adfc DWAlertController: 5f4cd8adf90336331c054857f709f5f8d4b16a5b gRPC: 64f36d689b2ecd99c4351f74e6f91347cdc65d9f @@ -732,6 +726,6 @@ SPEC CHECKSUMS: tinycbor: d4d71dddda1f8392fbb4249f63faf8552f327590 TinyCborObjc: 5204540fb90ff0c40fb22d408fa51bab79d78a80 -PODFILE CHECKSUM: 1db7bfe9fa728d3d9ee296b3b5513864533505cf +PODFILE CHECKSUM: e9255ead15dc2359c99dacd021e2a7861c085334 COCOAPODS: 1.14.2 From 64132d414dd9959ebf14fe94b829239375dc25e0 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Tue, 7 Nov 2023 22:40:57 +0700 Subject: [PATCH 13/32] chore: add logger without timestamps for some testing cases --- DashSync/shared/Libraries/DSLogger.m | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/DashSync/shared/Libraries/DSLogger.m b/DashSync/shared/Libraries/DSLogger.m index 4089ed18b..1393e0157 100644 --- a/DashSync/shared/Libraries/DSLogger.m +++ b/DashSync/shared/Libraries/DSLogger.m @@ -19,6 +19,14 @@ NS_ASSUME_NONNULL_BEGIN +@interface NoTimestampLogFormatter : NSObject +@end +@implementation NoTimestampLogFormatter +- (nullable NSString *)formatLogMessage:(DDLogMessage *)logMessage { + return logMessage.message; +} +@end + @interface DSLogger () @property (readonly, nonatomic, strong) DDFileLogger *fileLogger; @@ -44,6 +52,8 @@ - (instancetype)init { DDFileLogger *fileLogger = [[DDFileLogger alloc] init]; fileLogger.rollingFrequency = 60 * 60 * 24; // 24 hour rolling fileLogger.logFileManager.maximumNumberOfLogFiles = 3; // keep a 3 days worth of log files + [fileLogger setLogFormatter:[[NoTimestampLogFormatter alloc] init]]; // Use the custom formatter + [DDLog addLogger:fileLogger]; _fileLogger = fileLogger; } From 143e7eba74672357dfb5b9d8a299dd8255983c95 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Tue, 7 Nov 2023 22:41:19 +0700 Subject: [PATCH 14/32] chore: disable no ts logger --- DashSync/shared/Libraries/DSLogger.m | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/DashSync/shared/Libraries/DSLogger.m b/DashSync/shared/Libraries/DSLogger.m index 1393e0157..5f59dc9c7 100644 --- a/DashSync/shared/Libraries/DSLogger.m +++ b/DashSync/shared/Libraries/DSLogger.m @@ -52,8 +52,7 @@ - (instancetype)init { DDFileLogger *fileLogger = [[DDFileLogger alloc] init]; fileLogger.rollingFrequency = 60 * 60 * 24; // 24 hour rolling fileLogger.logFileManager.maximumNumberOfLogFiles = 3; // keep a 3 days worth of log files - [fileLogger setLogFormatter:[[NoTimestampLogFormatter alloc] init]]; // Use the custom formatter - + //[fileLogger setLogFormatter:[[NoTimestampLogFormatter alloc] init]]; // Use the custom formatter [DDLog addLogger:fileLogger]; _fileLogger = fileLogger; } From 9fd8930bc92c4264dc3f323ba8d31e88a3451691 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Tue, 7 Nov 2023 22:41:58 +0700 Subject: [PATCH 15/32] chore: bump up DashSharedCore to 0.4.14 --- DashSync.podspec | 2 +- .../Managers/Chain Managers/DSMasternodeManager.m | 13 ++++++------- .../Models/Masternode/DSMnDiffProcessingResult.h | 3 ++- Example/Podfile | 2 +- Example/Podfile.lock | 10 +++++----- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/DashSync.podspec b/DashSync.podspec index 985e1d19e..24d4e3756 100644 --- a/DashSync.podspec +++ b/DashSync.podspec @@ -34,7 +34,7 @@ Pod::Spec.new do |s| s.ios.framework = 'UIKit' s.macos.framework = 'Cocoa' s.compiler_flags = '-Wno-comma' - s.dependency 'DashSharedCore', '0.4.13' + s.dependency 'DashSharedCore', '0.4.14' s.dependency 'CocoaLumberjack', '3.7.2' s.ios.dependency 'DWAlertController', '0.2.1' s.dependency 'DSDynamicOptions', '0.1.2' diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m index 27a1aea41..c4609b2fc 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m @@ -623,31 +623,31 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH4C skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH4C count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH4C]) { - DSLog(@"••• updateStoreWithMasternodeList (h-4c): %u: %@ (%@)", masternodeListAtH4C.height, uint256_hex(blockHashAtH4C), uint256_reverse_hex(blockHashAtH4C)); +// DSLog(@"••• updateStoreWithMasternodeList (h-4c): %u: %@ (%@)", masternodeListAtH4C.height, uint256_hex(blockHashAtH4C), uint256_reverse_hex(blockHashAtH4C)); [self updateStoreWithProcessingResult:masternodeListAtH4C result:mnListDiffResultAtH4C completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH3C skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH3C count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH3C]) { - DSLog(@"••• updateStoreWithMasternodeList (h-3c): %u: %@ (%@)", masternodeListAtH3C.height, uint256_hex(blockHashAtH3C), uint256_reverse_hex(blockHashAtH3C)); +// DSLog(@"••• updateStoreWithMasternodeList (h-3c): %u: %@ (%@)", masternodeListAtH3C.height, uint256_hex(blockHashAtH3C), uint256_reverse_hex(blockHashAtH3C)); [self updateStoreWithProcessingResult:masternodeListAtH3C result:mnListDiffResultAtH3C completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH2C skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH2C count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH2C]) { - DSLog(@"••• updateStoreWithMasternodeList (h-2c): %u: %@ (%@)", masternodeListAtH2C.height, uint256_hex(blockHashAtH2C), uint256_reverse_hex(blockHashAtH2C)); +// DSLog(@"••• updateStoreWithMasternodeList (h-2c): %u: %@ (%@)", masternodeListAtH2C.height, uint256_hex(blockHashAtH2C), uint256_reverse_hex(blockHashAtH2C)); [self updateStoreWithProcessingResult:masternodeListAtH2C result:mnListDiffResultAtH2C completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtHC skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtHC count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtHC]) { - DSLog(@"••• updateStoreWithMasternodeList (h-c): %u: %@ (%@)", masternodeListAtHC.height, uint256_hex(blockHashAtHC), uint256_reverse_hex(blockHashAtHC)); +// DSLog(@"••• updateStoreWithMasternodeList (h-c): %u: %@ (%@)", masternodeListAtHC.height, uint256_hex(blockHashAtHC), uint256_reverse_hex(blockHashAtHC)); [self updateStoreWithProcessingResult:masternodeListAtHC result:mnListDiffResultAtHC completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH]) { - DSLog(@"••• updateStoreWithMasternodeList (h): %u: %@ (%@)", masternodeListAtH.height, uint256_hex(blockHashAtH), uint256_reverse_hex(blockHashAtH)); +// DSLog(@"••• updateStoreWithMasternodeList (h): %u: %@ (%@)", masternodeListAtH.height, uint256_hex(blockHashAtH), uint256_reverse_hex(blockHashAtH)); [self updateStoreWithProcessingResult:masternodeListAtH result:mnListDiffResultAtH completion:^(NSError *error) {}]; } @@ -664,12 +664,11 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * [self.store.masternodeListQueriesNeedingQuorumsValidated removeObject:blockHashDataAtTip]; } } - DSLog(@"••• updateStoreWithMasternodeList (tip): %u: %@ (%@)", masternodeListAtTip.height, uint256_hex(blockHashAtTip), uint256_reverse_hex(blockHashAtTip)); +// DSLog(@"••• updateStoreWithMasternodeList (tip): %u: %@ (%@)", masternodeListAtTip.height, uint256_hex(blockHashAtTip), uint256_reverse_hex(blockHashAtTip)); [self updateStoreWithProcessingResult:masternodeListAtTip result:mnListDiffResultAtTip completion:^(NSError *error) {}]; [self.quorumRotationService updateAfterProcessingMasternodeListWithBlockHash:blockHashDataAtTip fromPeer:peer]; } } - [self.store saveQuorumSnapshot:result.snapshotAtHC toChain:self.chain completion:^(NSError * _Nonnull error) {}]; [self.store saveQuorumSnapshot:result.snapshotAtH2C toChain:self.chain completion:^(NSError * _Nonnull error) {}]; [self.store saveQuorumSnapshot:result.snapshotAtH3C toChain:self.chain completion:^(NSError * _Nonnull error) {}]; diff --git a/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.h b/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.h index 629096b54..43b097dea 100644 --- a/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.h +++ b/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.h @@ -36,7 +36,8 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic) NSDictionary *modifiedMasternodes; @property (nonatomic) NSArray *addedQuorums; @property (nonatomic) NSOrderedSet *neededMissingMasternodeLists; -@property (nonatomic) NSDictionary *clSignatures; +/// +@property (nonatomic) NSDictionary *clSignatures; + (instancetype)processingResultWith:(MNListDiffResult *)result onChain:(DSChain *)chain; diff --git a/Example/Podfile b/Example/Podfile index 725f93d95..85e92f967 100644 --- a/Example/Podfile +++ b/Example/Podfile @@ -1,5 +1,5 @@ def common_pods -# pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :branch => 'fix/core-20-test' +# pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :branch => 'fix/core-20-test-additional' # pod 'DashSharedCore', :git => 'https://github.com/dashpay/dash-shared-core.git', :commit => 'e2dc943' pod 'DashSync', :path => '../' pod 'SDWebImage', '5.14.3' diff --git a/Example/Podfile.lock b/Example/Podfile.lock index dc078a858..c46846c3c 100644 --- a/Example/Podfile.lock +++ b/Example/Podfile.lock @@ -586,11 +586,11 @@ PODS: - "!ProtoCompiler-gRPCPlugin (~> 1.0)" - DAPI-GRPC/Messages - gRPC-ProtoRPC - - DashSharedCore (0.4.13) + - DashSharedCore (0.4.14) - DashSync (0.1.0): - CocoaLumberjack (= 3.7.2) - DAPI-GRPC (= 0.22.0-dev.8) - - DashSharedCore (= 0.4.13) + - DashSharedCore (= 0.4.14) - DSDynamicOptions (= 0.1.2) - DWAlertController (= 0.2.1) - TinyCborObjc (= 0.4.6) @@ -712,8 +712,8 @@ SPEC CHECKSUMS: CocoaImageHashing: 8656031d0899abe6c1c415827de43e9798189c53 CocoaLumberjack: b7e05132ff94f6ae4dfa9d5bce9141893a21d9da DAPI-GRPC: 138d62523bbfe7e88a39896f1053c0bc12390d9f - DashSharedCore: 46e9d9fb8b934933f319ece1ae35b9914e4c1a24 - DashSync: 81344e983fe2afe12c2b98c32ea50e20fed186f9 + DashSharedCore: dc766715605effeed166d39701825bd1f4c3c500 + DashSync: 3c7c4c0385b8c18dd764c0ef63fc02eef1c38f4f DSDynamicOptions: 347cc5d2c4e080eb3de6a86719ad3d861b82adfc DWAlertController: 5f4cd8adf90336331c054857f709f5f8d4b16a5b gRPC: 64f36d689b2ecd99c4351f74e6f91347cdc65d9f @@ -726,6 +726,6 @@ SPEC CHECKSUMS: tinycbor: d4d71dddda1f8392fbb4249f63faf8552f327590 TinyCborObjc: 5204540fb90ff0c40fb22d408fa51bab79d78a80 -PODFILE CHECKSUM: e9255ead15dc2359c99dacd021e2a7861c085334 +PODFILE CHECKSUM: 8cb419eb95422ed65fbdc41960e405e8cc54dda7 COCOAPODS: 1.14.2 From 634011f3ef0b66faeb4b2b6d16c4c2afc81c48d2 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Wed, 8 Nov 2023 19:01:36 +0700 Subject: [PATCH 16/32] fix: adapt changed identity methods for example app --- ...DSCreateBlockchainIdentityViewController.m | 38 +++++++++---------- .../DSCreateInvitationViewController.m | 38 +++++++++---------- 2 files changed, 36 insertions(+), 40 deletions(-) diff --git a/Example/DashSync/DSCreateBlockchainIdentityViewController.m b/Example/DashSync/DSCreateBlockchainIdentityViewController.m index 279986e17..5ba18a4e8 100644 --- a/Example/DashSync/DSCreateBlockchainIdentityViewController.m +++ b/Example/DashSync/DSCreateBlockchainIdentityViewController.m @@ -154,26 +154,24 @@ - (IBAction)done:(id)sender { } [blockchainIdentity generateBlockchainIdentityExtendedPublicKeysWithPrompt:@"Update wallet to allow for Evolution features?" completion:^(BOOL registered) { - [blockchainIdentity createFundingPrivateKeyWithPrompt:@"Register?" - completion:^(BOOL success, BOOL cancelled) { - if (success && !cancelled) { - [blockchainIdentity registerOnNetwork:steps - withFundingAccount:self.fundingAccount - forTopupAmount:topupAmount - stepCompletion:^(DSBlockchainIdentityRegistrationStep stepCompleted) { - - } - completion:^(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *_Nonnull error) { - if (error) { - [self raiseIssue:@"Error" message:error.localizedDescription]; - return; - } else { - [self.presentingViewController dismissViewControllerAnimated:TRUE completion:nil]; - } - }]; - } - }]; - }]; + [blockchainIdentity createFundingPrivateKeyWithPrompt:@"Register?" completion:^(BOOL success, BOOL cancelled) { + if (success && !cancelled) { + [blockchainIdentity registerOnNetwork:steps + withFundingAccount:self.fundingAccount + forTopupAmount:topupAmount + pinPrompt:@"Enter your PIN?" + stepCompletion:^(DSBlockchainIdentityRegistrationStep stepCompleted) {} + completion:^(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *_Nonnull error) { + if (error) { + [self raiseIssue:@"Error" message:error.localizedDescription]; + return; + } else { + [self.presentingViewController dismissViewControllerAnimated:TRUE completion:nil]; + } + }]; + } + }]; + }]; } - (void)viewController:(UIViewController *)controller didChooseWallet:(DSWallet *)wallet { diff --git a/Example/DashSync/DSCreateInvitationViewController.m b/Example/DashSync/DSCreateInvitationViewController.m index 6d21a7966..ee4691d0a 100644 --- a/Example/DashSync/DSCreateInvitationViewController.m +++ b/Example/DashSync/DSCreateInvitationViewController.m @@ -123,26 +123,24 @@ - (IBAction)done:(id)sender { DSBlockchainIdentityRegistrationStep steps = DSBlockchainIdentityRegistrationStep_L1Steps; [blockchainInvitation generateBlockchainInvitationsExtendedPublicKeysWithPrompt:@"Update wallet to allow for Evolution features?" completion:^(BOOL registered) { - [blockchainInvitation.identity createFundingPrivateKeyForInvitationWithPrompt:@"Register?" - completion:^(BOOL success, BOOL cancelled) { - if (success && !cancelled) { - [blockchainInvitation.identity registerOnNetwork:steps - withFundingAccount:self.fundingAccount - forTopupAmount:topupAmount - stepCompletion:^(DSBlockchainIdentityRegistrationStep stepCompleted) { - - } - completion:^(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *_Nonnull error) { - if (error) { - [self raiseIssue:@"Error" message:error.localizedDescription]; - return; - } else { - [self.presentingViewController dismissViewControllerAnimated:TRUE completion:nil]; - } - }]; - } - }]; - }]; + [blockchainInvitation.identity createFundingPrivateKeyForInvitationWithPrompt:@"Register?" completion:^(BOOL success, BOOL cancelled) { + if (success && !cancelled) { + [blockchainInvitation.identity registerOnNetwork:steps + withFundingAccount:self.fundingAccount + forTopupAmount:topupAmount + pinPrompt:@"Enter your PIN?" + stepCompletion:^(DSBlockchainIdentityRegistrationStep stepCompleted) {} + completion:^(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *_Nonnull error) { + if (error) { + [self raiseIssue:@"Error" message:error.localizedDescription]; + return; + } else { + [self.presentingViewController dismissViewControllerAnimated:TRUE completion:nil]; + } + }]; + } + }]; + }]; } - (void)viewController:(UIViewController *)controller didChooseWallet:(DSWallet *)wallet { From ec9554d64511c5fcf4986453ec699a3ccc8bab32 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Wed, 8 Nov 2023 23:43:37 +0700 Subject: [PATCH 17/32] fix: cbtx v3 bestCLHeightDiff & self.creditPoolBalance --- DashSync/shared/Categories/NSData/NSData+Dash.h | 1 + DashSync/shared/Categories/NSData/NSData+Dash.m | 5 +++++ .../Models/Transactions/Coinbase/DSCoinbaseTransaction.m | 9 ++++----- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/DashSync/shared/Categories/NSData/NSData+Dash.h b/DashSync/shared/Categories/NSData/NSData+Dash.h index 5edf772ae..bb9e37585 100644 --- a/DashSync/shared/Categories/NSData/NSData+Dash.h +++ b/DashSync/shared/Categories/NSData/NSData+Dash.h @@ -193,6 +193,7 @@ size_t chacha20Poly1305AEADDecrypt(void *_Nullable out, size_t outLen, const voi - (uint32_t)UInt32AtOffset:(NSUInteger)offset; - (uint32_t)UInt32BigToHostAtOffset:(NSUInteger)offset; - (uint64_t)UInt64AtOffset:(NSUInteger)offset; +- (int64_t)Int64AtOffset:(NSUInteger)offset; - (UInt128)UInt128AtOffset:(NSUInteger)offset; - (UInt160)UInt160AtOffset:(NSUInteger)offset; - (UInt256)UInt256AtOffset:(NSUInteger)offset; diff --git a/DashSync/shared/Categories/NSData/NSData+Dash.m b/DashSync/shared/Categories/NSData/NSData+Dash.m index 2093d4eeb..8efea528a 100644 --- a/DashSync/shared/Categories/NSData/NSData+Dash.m +++ b/DashSync/shared/Categories/NSData/NSData+Dash.m @@ -1211,6 +1211,11 @@ - (uint64_t)UInt64AtOffset:(NSUInteger)offset { return CFSwapInt64LittleToHost(*(const uint64_t *)((const uint8_t *)self.bytes + offset)); } +- (int64_t)Int64AtOffset:(NSUInteger)offset { + if (self.length < offset + sizeof(int64_t)) return 0; + return CFSwapInt64LittleToHost(*(const int64_t *)((const uint8_t *)self.bytes + offset)); +} + - (UInt128)UInt128AtOffset:(NSUInteger)offset { if (self.length < offset + sizeof(UInt128)) return UINT128_ZERO; return *(UInt128 *)(self.bytes + offset); diff --git a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m index 339cdfb8e..762aa1b44 100644 --- a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m +++ b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m @@ -39,15 +39,14 @@ - (instancetype)initWithMessage:(NSData *)message onChain:(DSChain *)chain { off += 32; if (version >= COINBASE_TX_CORE_20) { - if (length - off < 4) return nil; - self.bestCLHeightDiff = [message UInt32AtOffset:off]; - off += 4; + NSNumber *len; + self.bestCLHeightDiff = [message varIntAtOffset:off length:&len]; + off += len.unsignedIntegerValue; if (length - off < 96) return nil; self.bestCLSignature = [message UInt768AtOffset:off]; off += 96; if (length - off < 8) return nil; - NSNumber *len; - self.creditPoolBalance = [message varIntAtOffset:off length:&len]; + self.creditPoolBalance = [message Int64AtOffset:off]; off += len.unsignedIntegerValue; } } From 26c550f1c8e895030ed00d5eb7a9ec6bf1802120 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Wed, 8 Nov 2023 23:44:13 +0700 Subject: [PATCH 18/32] fix: track evo node addresses --- .../shared/Models/Managers/Chain Managers/DSTransactionManager.m | 1 + 1 file changed, 1 insertion(+) diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m index 866e476e8..1b0d19ba9 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m @@ -1016,6 +1016,7 @@ - (void)updateTransactionsBloomFilter { [allAddressesArray addObjectsFromArray:[wallet providerOwnerAddresses]]; [allAddressesArray addObjectsFromArray:[wallet providerVotingAddresses]]; [allAddressesArray addObjectsFromArray:[wallet providerOperatorAddresses]]; + [allAddressesArray addObjectsFromArray:[wallet platformNodeAddresses]]; } for (DSFundsDerivationPath *derivationPath in self.chain.standaloneDerivationPaths) { From 4a1e912540c790264d461143b6f6c4136721bf56 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Wed, 8 Nov 2023 23:47:11 +0700 Subject: [PATCH 19/32] chore: fix log info --- DashSync/shared/Models/Network/DSPeer.m | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/DashSync/shared/Models/Network/DSPeer.m b/DashSync/shared/Models/Network/DSPeer.m index ebd8ed663..1392ae61f 100644 --- a/DashSync/shared/Models/Network/DSPeer.m +++ b/DashSync/shared/Models/Network/DSPeer.m @@ -755,13 +755,14 @@ - (void)acceptMessage:(NSData *)message type:(NSString *)type { DSLog(@"%@:%u accept message %@", self.host, self.port, type); } #endif - if (self.currentBlock && (!([MSG_TX isEqual:type] || [MSG_IX isEqual:type] || [MSG_ISLOCK isEqual:type]))) { // if we receive a non-tx message, merkleblock is done + if (self.currentBlock && (!([MSG_TX isEqual:type] || [MSG_IX isEqual:type] || [MSG_ISLOCK isEqual:type]))) { + // if we receive a non-tx message, merkleblock is done UInt256 hash = self.currentBlock.blockHash; - + NSUInteger txExpected = self.currentBlockTxHashes.count; self.currentBlock = nil; self.currentBlockTxHashes = nil; - [self error:@"incomplete merkleblock %@, expected %u more tx, got %@", - uint256_obj(hash), (int)self.currentBlockTxHashes.count, type]; + [self error:@"incomplete merkleblock %@, expected %lu more tx, got %@", + uint256_obj(hash), txExpected, type]; } else if ([MSG_VERSION isEqual:type]) [self acceptVersionMessage:message]; else if ([MSG_VERACK isEqual:type]) From 6739f65c823ea2c611714bff67b51f5a25830163 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Thu, 9 Nov 2023 02:46:04 +0700 Subject: [PATCH 20/32] fix: add evo node addresses to bloom filter from other entry point --- DashSync/shared/Models/Chain/DSChain.m | 1 + 1 file changed, 1 insertion(+) diff --git a/DashSync/shared/Models/Chain/DSChain.m b/DashSync/shared/Models/Chain/DSChain.m index cd560f147..85b2f2155 100644 --- a/DashSync/shared/Models/Chain/DSChain.m +++ b/DashSync/shared/Models/Chain/DSChain.m @@ -1239,6 +1239,7 @@ - (DSBloomFilter *)bloomFilterWithFalsePositiveRate:(double)falsePositiveRate wi [allAddresses addObjectsFromArray:[wallet providerOwnerAddresses]]; [allAddresses addObjectsFromArray:[wallet providerVotingAddresses]]; [allAddresses addObjectsFromArray:[wallet providerOperatorAddresses]]; + [allAddresses addObjectsFromArray:[wallet platformNodeAddresses]]; } for (DSFundsDerivationPath *derivationPath in self.standaloneDerivationPaths) { From 2c276633390042d377961433cfc5168b96e36ec0 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Fri, 10 Nov 2023 14:52:38 +0700 Subject: [PATCH 21/32] chore: laconize timestamp assign --- .../Models/Managers/Chain Managers/DSTransactionManager.m | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m index 1b0d19ba9..dd5271b23 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m @@ -1217,11 +1217,7 @@ - (void)peer:(DSPeer *)peer relayedTransaction:(DSTransaction *)transaction inBl #endif } - if (block) { - transaction.timestamp = block.timestamp; - } else { - transaction.timestamp = [NSDate timeIntervalSince1970]; - } + transaction.timestamp = block ? block.timestamp : [NSDate timeIntervalSince1970]; NSArray *accounts = [self.chain accountsThatCanContainTransaction:transaction]; NSMutableArray *accountsAcceptingTransaction = [NSMutableArray array]; NSMutableArray *accountsWithValidTransaction = [NSMutableArray array]; From 1e0c19779ce1910ece76e52bc2e4eade56748f48 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Fri, 10 Nov 2023 20:25:13 +0700 Subject: [PATCH 22/32] chore: make some logs more laconic --- DashSync/shared/Models/Masternode/DSMasternodeListStore.m | 5 ++--- DashSync/shared/Models/Network/DSPeer.m | 8 ++++---- DashSync/shared/Models/Transactions/Base/DSTransaction.m | 2 +- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/DashSync/shared/Models/Masternode/DSMasternodeListStore.m b/DashSync/shared/Models/Masternode/DSMasternodeListStore.m index bd56eca67..148bfa85a 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeListStore.m +++ b/DashSync/shared/Models/Masternode/DSMasternodeListStore.m @@ -424,7 +424,6 @@ - (void)notifyMasternodeListUpdate { - (void)saveMasternodeList:(DSMasternodeList *)masternodeList addedMasternodes:(NSDictionary *)addedMasternodes modifiedMasternodes:(NSDictionary *)modifiedMasternodes completion:(void (^)(NSError *error))completion { UInt256 blockHash = masternodeList.blockHash; NSData *blockHashData = uint256_data(blockHash); - DSLog(@"•••• store (%d) masternode list at: %u: %@", [self hasMasternodeListAt:blockHashData], [self heightForBlockHash:blockHash], uint256_hex(blockHash)); if ([self hasMasternodeListAt:blockHashData]) { // in rare race conditions this might already exist // but also as we can get it from different sources @@ -524,7 +523,7 @@ + (void)saveMasternodeList:(DSMasternodeList *)masternodeList createUnknownBlocks:(BOOL)createUnknownBlocks inContext:(NSManagedObjectContext *)context completion:(void (^)(NSError *error))completion { - DSLog(@"Queued saving MNL at height %u", masternodeList.height); + DSLog(@"Queued saving MNL at height %u: %@", masternodeList.height, uint256_hex(masternodeList.blockHash)); [context performBlockAndWait:^{ //masternodes @autoreleasepool { @@ -607,7 +606,7 @@ + (void)saveMasternodeList:(DSMasternodeList *)masternodeList } } chainEntity.baseBlockHash = mnlBlockHashData; - DSLog(@"Finished merging MNL at height %u", mnlHeight); + DSLog(@"Finished merging MNL at height %u: %@", mnlHeight, mnlBlockHashData.hexString); } else if (!error) { DSMasternodeListEntity *masternodeListEntity = [DSMasternodeListEntity managedObjectInBlockedContext:context]; diff --git a/DashSync/shared/Models/Network/DSPeer.m b/DashSync/shared/Models/Network/DSPeer.m index 1392ae61f..0a6e1d86f 100644 --- a/DashSync/shared/Models/Network/DSPeer.m +++ b/DashSync/shared/Models/Network/DSPeer.m @@ -1265,9 +1265,9 @@ - (void)acceptTxMessage:(NSData *)message { #endif #else #if DEBUG - DSLogPrivate(@"%@:%u got tx %@", self.host, self.port, uint256_obj(tx.txHash)); + DSLogPrivate(@"%@:%u got tx (%lu): %@", self.host, self.port, tx.type, uint256_obj(tx.txHash)); #else - DSLog(@"%@:%u got tx %@", self.host, self.port, @""); + DSLog(@"%@:%u got tx (%lu): %@", self.host, self.port, tx.type, @""); #endif #endif } @@ -1640,8 +1640,8 @@ - (void)acceptMerkleblockMessage:(NSData *)message { [self error:@"got merkleblock message before loading a filter"]; return; } - //else DSLog(@"%@:%u got merkleblock %@", self.host, self.port, block.blockHash); - + //else DSLog(@"%@:%u got merkleblock %@", self.host, self.port, uint256_hex(block.blockHash)); + NSMutableOrderedSet *txHashes = [NSMutableOrderedSet orderedSetWithArray:block.transactionHashes]; @synchronized (self.knownTxHashes) { [txHashes minusOrderedSet:self.knownTxHashes]; diff --git a/DashSync/shared/Models/Transactions/Base/DSTransaction.m b/DashSync/shared/Models/Transactions/Base/DSTransaction.m index 5ecc3c53d..485880905 100644 --- a/DashSync/shared/Models/Transactions/Base/DSTransaction.m +++ b/DashSync/shared/Models/Transactions/Base/DSTransaction.m @@ -307,7 +307,7 @@ - (NSArray *)outputAddresses { - (NSString *)description { NSString *txid = [NSString hexWithData:[NSData dataWithBytes:self.txHash.u8 length:sizeof(UInt256)].reverse]; - return [NSString stringWithFormat:@"%@(id=%@-block=%@) + (%@)", [self class], txid, (self.blockHeight == TX_UNCONFIRMED) ? @"Not mined" : @(self.blockHeight), [super description]]; + return [NSString stringWithFormat:@"%@(id=%@-block=%@)", [super description], txid, (self.blockHeight == TX_UNCONFIRMED) ? @"Not mined" : @(self.blockHeight)]; } - (NSString *)longDescription { From 49b53565509dc7b07d7587a97d600bd84d2fa19c Mon Sep 17 00:00:00 2001 From: pankcuf Date: Fri, 10 Nov 2023 20:26:49 +0700 Subject: [PATCH 23/32] fix: cbtx encode --- .../shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.h | 2 +- .../shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.h b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.h index d5e5b7bd0..8b504d7f4 100644 --- a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.h +++ b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.h @@ -13,7 +13,7 @@ @property (nonatomic, assign) uint32_t height; @property (nonatomic, assign) UInt256 merkleRootMNList; @property (nonatomic, assign) UInt256 merkleRootLLMQList; -@property (nonatomic, assign) uint32_t bestCLHeightDiff; +@property (nonatomic, assign) NSUInteger bestCLHeightDiff; @property (nonatomic, assign) UInt768 bestCLSignature; @property (nonatomic, assign) int64_t creditPoolBalance; diff --git a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m index 762aa1b44..16d0d71c1 100644 --- a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m +++ b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m @@ -92,7 +92,7 @@ - (NSData *)payloadData { if (self.coinbaseTransactionVersion >= COINBASE_TX_CORE_19) { [data appendUInt256:self.merkleRootLLMQList]; if (self.coinbaseTransactionVersion >= COINBASE_TX_CORE_20) { - [data appendUInt32:self.bestCLHeightDiff]; + [data appendVarInt:self.bestCLHeightDiff]; // TODO: check whether it matters to check for optionals [data appendUInt768:self.bestCLSignature]; [data appendInt64:self.creditPoolBalance]; From 95d4009b421187ece60bc31bf24763c647f9dba3 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Fri, 10 Nov 2023 23:29:59 +0700 Subject: [PATCH 24/32] chore: bump up DashSharedCore to 0.4.15 --- DashSync.podspec | 2 +- Example/Podfile.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/DashSync.podspec b/DashSync.podspec index 24d4e3756..4e7b1273a 100644 --- a/DashSync.podspec +++ b/DashSync.podspec @@ -34,7 +34,7 @@ Pod::Spec.new do |s| s.ios.framework = 'UIKit' s.macos.framework = 'Cocoa' s.compiler_flags = '-Wno-comma' - s.dependency 'DashSharedCore', '0.4.14' + s.dependency 'DashSharedCore', '0.4.15' s.dependency 'CocoaLumberjack', '3.7.2' s.ios.dependency 'DWAlertController', '0.2.1' s.dependency 'DSDynamicOptions', '0.1.2' diff --git a/Example/Podfile.lock b/Example/Podfile.lock index c46846c3c..2429e3887 100644 --- a/Example/Podfile.lock +++ b/Example/Podfile.lock @@ -586,11 +586,11 @@ PODS: - "!ProtoCompiler-gRPCPlugin (~> 1.0)" - DAPI-GRPC/Messages - gRPC-ProtoRPC - - DashSharedCore (0.4.14) + - DashSharedCore (0.4.15) - DashSync (0.1.0): - CocoaLumberjack (= 3.7.2) - DAPI-GRPC (= 0.22.0-dev.8) - - DashSharedCore (= 0.4.14) + - DashSharedCore (= 0.4.15) - DSDynamicOptions (= 0.1.2) - DWAlertController (= 0.2.1) - TinyCborObjc (= 0.4.6) @@ -712,8 +712,8 @@ SPEC CHECKSUMS: CocoaImageHashing: 8656031d0899abe6c1c415827de43e9798189c53 CocoaLumberjack: b7e05132ff94f6ae4dfa9d5bce9141893a21d9da DAPI-GRPC: 138d62523bbfe7e88a39896f1053c0bc12390d9f - DashSharedCore: dc766715605effeed166d39701825bd1f4c3c500 - DashSync: 3c7c4c0385b8c18dd764c0ef63fc02eef1c38f4f + DashSharedCore: 837242d84149ee9d1cce1037cc583751553421fa + DashSync: 9c5355f4cd18808ef1eeb0d61cce174f52a1f27f DSDynamicOptions: 347cc5d2c4e080eb3de6a86719ad3d861b82adfc DWAlertController: 5f4cd8adf90336331c054857f709f5f8d4b16a5b gRPC: 64f36d689b2ecd99c4351f74e6f91347cdc65d9f From 67f7f94c0b4ff0b9cec96d324955666ef560fb99 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Sat, 11 Nov 2023 02:50:12 +0700 Subject: [PATCH 25/32] fix: tests --- Example/Tests/DSTestnetE2ETests.m | 114 ++++++++++++++--------------- Example/Tests/DSTestnetSyncTests.m | 2 +- 2 files changed, 54 insertions(+), 62 deletions(-) diff --git a/Example/Tests/DSTestnetE2ETests.m b/Example/Tests/DSTestnetE2ETests.m index 7bef9f332..6dee83dc7 100644 --- a/Example/Tests/DSTestnetE2ETests.m +++ b/Example/Tests/DSTestnetE2ETests.m @@ -266,71 +266,63 @@ - (void)testFRegisterIdentities { XCTestExpectation *identityRegistrationFinishedExpectation1a = [[XCTestExpectation alloc] init]; [blockchainIdentity1a generateBlockchainIdentityExtendedPublicKeysWithPrompt:@"" completion:^(BOOL registered) { - [blockchainIdentity1a createFundingPrivateKeyWithPrompt:@"" - completion:^(BOOL success, BOOL cancelled) { - if (success && !cancelled) { - [blockchainIdentity1a registerOnNetwork:steps - withFundingAccount:self.fundingAccount1 - forTopupAmount:10000 - stepCompletion:^(DSBlockchainIdentityRegistrationStep stepCompleted) { - - } - completion:^(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *_Nonnull error) { - XCTAssertNil(error, @"There should not be an error"); - XCTAssert(stepsCompleted = steps, @"We should have completed the same amount of steps that were requested"); - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - [identityRegistrationFinishedExpectation1a fulfill]; - }); - }]; - } - }]; - }]; + [blockchainIdentity1a createFundingPrivateKeyWithPrompt:@"" completion:^(BOOL success, BOOL cancelled) { + if (success && !cancelled) { + [blockchainIdentity1a registerOnNetwork:steps + withFundingAccount:self.fundingAccount1 + forTopupAmount:10000 + pinPrompt:@"PIN?" + stepCompletion:^(DSBlockchainIdentityRegistrationStep stepCompleted) {} + completion:^(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *_Nonnull error) { + XCTAssertNil(error, @"There should not be an error"); + XCTAssert(stepsCompleted = steps, @"We should have completed the same amount of steps that were requested"); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [identityRegistrationFinishedExpectation1a fulfill]; + }); + }]; + } + }]; + }]; [self waitForExpectations:@[identityRegistrationFinishedExpectation1a] timeout:600]; XCTestExpectation *identityRegistrationFinishedExpectation1b = [[XCTestExpectation alloc] init]; - [blockchainIdentity1b generateBlockchainIdentityExtendedPublicKeysWithPrompt:@"" - completion:^(BOOL registered) { - [blockchainIdentity1b createFundingPrivateKeyWithPrompt:@"" - completion:^(BOOL success, BOOL cancelled) { - if (success && !cancelled) { - [blockchainIdentity1b registerOnNetwork:steps - withFundingAccount:self.fundingAccount1 - forTopupAmount:10000 - stepCompletion:^(DSBlockchainIdentityRegistrationStep stepCompleted) { - - } - completion:^(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *_Nonnull error) { - XCTAssertNil(error, @"There should not be an error"); - XCTAssert(stepsCompleted = steps, @"We should have completed the same amount of steps that were requested"); - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - [identityRegistrationFinishedExpectation1b fulfill]; - }); - }]; - } - }]; - }]; + [blockchainIdentity1b generateBlockchainIdentityExtendedPublicKeysWithPrompt:@"" completion:^(BOOL registered) { + [blockchainIdentity1b createFundingPrivateKeyWithPrompt:@"" completion:^(BOOL success, BOOL cancelled) { + if (success && !cancelled) { + [blockchainIdentity1b registerOnNetwork:steps + withFundingAccount:self.fundingAccount1 + forTopupAmount:10000 + pinPrompt:@"PIN?" + stepCompletion:^(DSBlockchainIdentityRegistrationStep stepCompleted) {} + completion:^(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *_Nonnull error) { + XCTAssertNil(error, @"There should not be an error"); + XCTAssert(stepsCompleted = steps, @"We should have completed the same amount of steps that were requested"); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [identityRegistrationFinishedExpectation1b fulfill]; + }); + }]; + } + }]; + }]; [self waitForExpectations:@[identityRegistrationFinishedExpectation1b] timeout:600]; XCTestExpectation *identityRegistrationFinishedExpectation2a = [[XCTestExpectation alloc] init]; - [blockchainIdentity2a generateBlockchainIdentityExtendedPublicKeysWithPrompt:@"" - completion:^(BOOL registered) { - [blockchainIdentity2a createFundingPrivateKeyWithPrompt:@"" - completion:^(BOOL success, BOOL cancelled) { - if (success && !cancelled) { - [blockchainIdentity2a registerOnNetwork:steps - withFundingAccount:self.fundingAccount1 - forTopupAmount:10000 - stepCompletion:^(DSBlockchainIdentityRegistrationStep stepCompleted) { - - } - completion:^(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *_Nonnull error) { - XCTAssertNil(error, @"There should not be an error"); - XCTAssert(stepsCompleted = steps, @"We should have completed the same amount of steps that were requested"); - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - [identityRegistrationFinishedExpectation2a fulfill]; - }); - }]; - } - }]; - }]; + [blockchainIdentity2a generateBlockchainIdentityExtendedPublicKeysWithPrompt:@"" completion:^(BOOL registered) { + [blockchainIdentity2a createFundingPrivateKeyWithPrompt:@"" completion:^(BOOL success, BOOL cancelled) { + if (success && !cancelled) { + [blockchainIdentity2a registerOnNetwork:steps + withFundingAccount:self.fundingAccount1 + forTopupAmount:10000 + pinPrompt:@"PIN?" + stepCompletion:^(DSBlockchainIdentityRegistrationStep stepCompleted) {} + completion:^(DSBlockchainIdentityRegistrationStep stepsCompleted, NSError *_Nonnull error) { + XCTAssertNil(error, @"There should not be an error"); + XCTAssert(stepsCompleted = steps, @"We should have completed the same amount of steps that were requested"); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [identityRegistrationFinishedExpectation2a fulfill]; + }); + }]; + } + }]; + }]; [self waitForExpectations:@[identityRegistrationFinishedExpectation2a] timeout:600]; } diff --git a/Example/Tests/DSTestnetSyncTests.m b/Example/Tests/DSTestnetSyncTests.m index 36a151e8a..31a437cee 100644 --- a/Example/Tests/DSTestnetSyncTests.m +++ b/Example/Tests/DSTestnetSyncTests.m @@ -102,7 +102,7 @@ - (void)testTestnetFullSync { // give time for saving of other tests to complete XCTestExpectation *headerFinishedExpectation = [[XCTestExpectation alloc] init]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - [self.chain useCheckpointBeforeOrOnHeightForSyncingChainBlocks:2000]; + [self.chain useCheckpointBeforeOrOnHeightForSyncingChainBlocks:530000]; [self.chain useCheckpointBeforeOrOnHeightForTerminalBlocksSync:UINT32_MAX]; [[DashSync sharedSyncController] wipePeerDataForChain:self.chain inContext:[NSManagedObjectContext chainContext]]; [[DashSync sharedSyncController] wipeBlockchainDataForChain:self.chain inContext:[NSManagedObjectContext chainContext]]; From 8a4a259dbe37e45157b8fc885854844742d9f82d Mon Sep 17 00:00:00 2001 From: pankcuf Date: Mon, 13 Nov 2023 20:12:40 +0700 Subject: [PATCH 26/32] fix: some tx offsets --- DashSync/shared/Models/Chain/DSChain.m | 6 +++++- DashSync/shared/Models/Network/DSPeer.m | 2 +- .../Models/Transactions/Coinbase/DSCoinbaseTransaction.m | 2 +- .../Provider/DSProviderRegistrationTransaction.m | 8 ++++---- .../Provider/DSProviderUpdateServiceTransaction.m | 4 ++-- Example/DashSync/DSWalletInputPhraseViewController.m | 9 ++------- 6 files changed, 15 insertions(+), 16 deletions(-) diff --git a/DashSync/shared/Models/Chain/DSChain.m b/DashSync/shared/Models/Chain/DSChain.m index 85b2f2155..df45e447e 100644 --- a/DashSync/shared/Models/Chain/DSChain.m +++ b/DashSync/shared/Models/Chain/DSChain.m @@ -3249,6 +3249,7 @@ - (BOOL)transactionHasLocalReferences:(DSTransaction *)transaction { if ([self walletHavingProviderOwnerAuthenticationHash:providerRegistrationTransaction.ownerKeyHash foundAtIndex:nil]) return TRUE; if ([self walletHavingProviderVotingAuthenticationHash:providerRegistrationTransaction.votingKeyHash foundAtIndex:nil]) return TRUE; if ([self walletHavingProviderOperatorAuthenticationKey:providerRegistrationTransaction.operatorKey foundAtIndex:nil]) return TRUE; + if ([self walletHavingPlatformNodeAuthenticationHash:providerRegistrationTransaction.platformNodeID foundAtIndex:nil]) return TRUE; if ([self walletContainingMasternodeHoldingAddressForProviderRegistrationTransaction:providerRegistrationTransaction foundAtIndex:nil]) return TRUE; if ([self accountContainingAddress:providerRegistrationTransaction.payoutAddress]) return TRUE; } else if ([transaction isKindOfClass:[DSProviderUpdateServiceTransaction class]]) { @@ -3287,7 +3288,10 @@ - (BOOL)transactionHasLocalReferences:(DSTransaction *)transaction { - (void)triggerUpdatesForLocalReferences:(DSTransaction *)transaction { if ([transaction isKindOfClass:[DSProviderRegistrationTransaction class]]) { DSProviderRegistrationTransaction *providerRegistrationTransaction = (DSProviderRegistrationTransaction *)transaction; - if ([self walletHavingProviderOwnerAuthenticationHash:providerRegistrationTransaction.ownerKeyHash foundAtIndex:nil] || [self walletHavingProviderVotingAuthenticationHash:providerRegistrationTransaction.votingKeyHash foundAtIndex:nil] || [self walletHavingProviderOperatorAuthenticationKey:providerRegistrationTransaction.operatorKey foundAtIndex:nil]) { + if ([self walletHavingProviderOwnerAuthenticationHash:providerRegistrationTransaction.ownerKeyHash foundAtIndex:nil] || + [self walletHavingProviderVotingAuthenticationHash:providerRegistrationTransaction.votingKeyHash foundAtIndex:nil] || + [self walletHavingProviderOperatorAuthenticationKey:providerRegistrationTransaction.operatorKey foundAtIndex:nil] || + [self walletHavingPlatformNodeAuthenticationHash:providerRegistrationTransaction.platformNodeID foundAtIndex:nil]) { [self.chainManager.masternodeManager localMasternodeFromProviderRegistrationTransaction:providerRegistrationTransaction save:TRUE]; } } else if ([transaction isKindOfClass:[DSProviderUpdateServiceTransaction class]]) { diff --git a/DashSync/shared/Models/Network/DSPeer.m b/DashSync/shared/Models/Network/DSPeer.m index 0a6e1d86f..bf64ecdfb 100644 --- a/DashSync/shared/Models/Network/DSPeer.m +++ b/DashSync/shared/Models/Network/DSPeer.m @@ -1265,7 +1265,7 @@ - (void)acceptTxMessage:(NSData *)message { #endif #else #if DEBUG - DSLogPrivate(@"%@:%u got tx (%lu): %@", self.host, self.port, tx.type, uint256_obj(tx.txHash)); + DSLogPrivate(@"%@:%u got tx (%hu): %@", self.host, self.port, tx.type, uint256_obj(tx.txHash)); #else DSLog(@"%@:%u got tx (%lu): %@", self.host, self.port, tx.type, @""); #endif diff --git a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m index 16d0d71c1..3c2370ba6 100644 --- a/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m +++ b/DashSync/shared/Models/Transactions/Coinbase/DSCoinbaseTransaction.m @@ -47,7 +47,7 @@ - (instancetype)initWithMessage:(NSData *)message onChain:(DSChain *)chain { off += 96; if (length - off < 8) return nil; self.creditPoolBalance = [message Int64AtOffset:off]; - off += len.unsignedIntegerValue; + off += 8; } } self.coinbaseTransactionVersion = version; diff --git a/DashSync/shared/Models/Transactions/Provider/DSProviderRegistrationTransaction.m b/DashSync/shared/Models/Transactions/Provider/DSProviderRegistrationTransaction.m index a0bc90e2f..fc58c3a65 100644 --- a/DashSync/shared/Models/Transactions/Provider/DSProviderRegistrationTransaction.m +++ b/DashSync/shared/Models/Transactions/Provider/DSProviderRegistrationTransaction.m @@ -90,12 +90,12 @@ - (instancetype)initWithMessage:(NSData *)message onChain:(DSChain *)chain { off += 32; if ([self usesBasicBLS] && [self usesHPMN]) { - if (length - off < 32) return nil; + if (length - off < 20) return nil; self.platformNodeID = [message UInt160AtOffset:off]; - off += 32; + off += 20; if (length - off < 2) return nil; self.platformP2PPort = CFSwapInt16HostToBig([message UInt16AtOffset:off]); - off += 2; + off += 2; if (length - off < 2) return nil; self.platformHTTPPort = CFSwapInt16HostToBig([message UInt16AtOffset:off]); off += 2; @@ -334,7 +334,7 @@ - (NSUInteger)masternodeOutputIndex { } - (BOOL)usesBasicBLS { - return self.version == 2; + return self.providerRegistrationTransactionVersion == 2; } - (BOOL)usesHPMN { diff --git a/DashSync/shared/Models/Transactions/Provider/DSProviderUpdateServiceTransaction.m b/DashSync/shared/Models/Transactions/Provider/DSProviderUpdateServiceTransaction.m index dd7345ab0..9f44a04f8 100644 --- a/DashSync/shared/Models/Transactions/Provider/DSProviderUpdateServiceTransaction.m +++ b/DashSync/shared/Models/Transactions/Provider/DSProviderUpdateServiceTransaction.m @@ -71,9 +71,9 @@ - (instancetype)initWithMessage:(NSData *)message onChain:(DSChain *)chain { off += 32; if (self.version == 2 /*BLS Basic*/ && self.providerType == 1 /*High Performance*/) { - if (length - off < 32) return nil; + if (length - off < 20) return nil; self.platformNodeID = [message UInt160AtOffset:off]; - off += 32; + off += 20; if (length - off < 2) return nil; self.platformP2PPort = CFSwapInt16HostToBig([message UInt16AtOffset:off]); off += 2; diff --git a/Example/DashSync/DSWalletInputPhraseViewController.m b/Example/DashSync/DSWalletInputPhraseViewController.m index a3aec0fbc..712742fdf 100644 --- a/Example/DashSync/DSWalletInputPhraseViewController.m +++ b/Example/DashSync/DSWalletInputPhraseViewController.m @@ -49,11 +49,7 @@ - (IBAction)generateRandomPassphrase:(id)sender { - (void)textViewDidChange:(UITextView *)textView { - if ([[DSBIP39Mnemonic sharedInstance] phraseIsValid:textView.text] || [textView.text isValidDashExtendedPublicKeyOnChain:self.chain]) { - self.saveButton.enabled = TRUE; - } else { - self.saveButton.enabled = FALSE; - } + self.saveButton.enabled = [[DSBIP39Mnemonic sharedInstance] phraseIsValid:textView.text] || [textView.text isValidDashExtendedPublicKeyOnChain:self.chain]; } - (IBAction)createWallet:(id)sender { @@ -61,12 +57,11 @@ - (IBAction)createWallet:(id)sender { NSTimeInterval creationDate = [self.inputSeedPhraseTextView.text isEqualToString:self.randomPassphrase] ? [NSDate timeIntervalSince1970] : 0; DSWallet *wallet = [DSWallet standardWalletWithSeedPhrase:self.inputSeedPhraseTextView.text setCreationDate:creationDate forChain:self.chain storeSeedPhrase:YES isTransient:NO]; [self.chain registerWallet:wallet]; - [self.navigationController popViewControllerAnimated:TRUE]; } else if ([self.inputSeedPhraseTextView.text isValidDashExtendedPublicKeyOnChain:self.chain]) { DSDerivationPath *derivationPath = [DSDerivationPath derivationPathWithSerializedExtendedPublicKey:self.inputSeedPhraseTextView.text onChain:self.chain]; [self.chain registerStandaloneDerivationPath:derivationPath]; - [self.navigationController popViewControllerAnimated:TRUE]; } + [self.navigationController popViewControllerAnimated:TRUE]; } @end From fb63f5893abd665b22268daf78b2bbbca92ea985 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Mon, 13 Nov 2023 23:19:54 +0700 Subject: [PATCH 27/32] fix: proregtx operator key version --- .../Provider/DSProviderRegistrationTransaction.m | 7 +------ .../Provider/DSProviderUpdateRegistrarTransaction.m | 1 + Example/Tests/DSProviderTransactionsTests.m | 7 +++++++ 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/DashSync/shared/Models/Transactions/Provider/DSProviderRegistrationTransaction.m b/DashSync/shared/Models/Transactions/Provider/DSProviderRegistrationTransaction.m index fc58c3a65..4ca170d6d 100644 --- a/DashSync/shared/Models/Transactions/Provider/DSProviderRegistrationTransaction.m +++ b/DashSync/shared/Models/Transactions/Provider/DSProviderRegistrationTransaction.m @@ -67,12 +67,6 @@ - (instancetype)initWithMessage:(NSData *)message onChain:(DSChain *)chain { self.operatorKey = [message UInt384AtOffset:off]; off += 48; - if ([self usesBasicBLS]) { - if (length - off < 2) return nil; - self.operatorKeyVersion = [message UInt16AtOffset:off]; - off += 2; - } - if (length - off < 20) return nil; self.votingKeyHash = [message UInt160AtOffset:off]; off += 20; @@ -206,6 +200,7 @@ - (NSData *)basePayloadData { [data appendUInt128:self.ipAddress]; //212 [data appendUInt16:CFSwapInt16BigToHost(self.port)]; //228 [data appendUInt160:self.ownerKeyHash]; //388 + // TODO: check case with legacy/non-legacy [data appendUInt384:self.operatorKey]; //772 [data appendUInt160:self.votingKeyHash]; //788 [data appendUInt16:self.operatorReward]; //804 diff --git a/DashSync/shared/Models/Transactions/Provider/DSProviderUpdateRegistrarTransaction.m b/DashSync/shared/Models/Transactions/Provider/DSProviderUpdateRegistrarTransaction.m index 714304687..07a340f71 100644 --- a/DashSync/shared/Models/Transactions/Provider/DSProviderUpdateRegistrarTransaction.m +++ b/DashSync/shared/Models/Transactions/Provider/DSProviderUpdateRegistrarTransaction.m @@ -157,6 +157,7 @@ - (NSData *)basePayloadData { [data appendUInt16:self.providerUpdateRegistrarTransactionVersion]; [data appendUInt256:self.providerRegistrationTransactionHash]; [data appendUInt16:self.providerMode]; + // TODO: check case with legacy/non-legacy [data appendUInt384:self.operatorKey]; [data appendUInt160:self.votingKeyHash]; [data appendVarInt:self.scriptPayout.length]; diff --git a/Example/Tests/DSProviderTransactionsTests.m b/Example/Tests/DSProviderTransactionsTests.m index 60369bb44..38e33bac3 100644 --- a/Example/Tests/DSProviderTransactionsTests.m +++ b/Example/Tests/DSProviderTransactionsTests.m @@ -424,5 +424,12 @@ - (void)testCollectionOperations { } +- (void)testProRegTransactionMalformed { + DSChain *testnet = [DSChain testnet]; + NSData *message = [NSData dataFromHexString:@"03000100019ecbf18dffb20ab5c6499b4b3aac3baa681b394cc9ffdbfcf0d7e105b9546737000000006a473044022054ad48d685d295bc25bceabe295136902233b5a58eb66592ae846a0c03c13c2502206f5c9ae6e26d889a39b671466fd647cbe44457c5d8b6adc66d70360c20dccff1012103ba9f974f2630f464d49385eb0a2946b3e1ddc0181a7704764f0182c1ff6f9efafeffffff015e2fb72d000000001976a91437602dadad1764d71349c4d7731957b1ac94586b88ac00000000fd2a0102000100000008ab76de940cf703fbe15c5aa392856d0e8efa3e2b2818ba9d5aa63c8f89ef1b0100000000000000000000000000ffff7284acd7270fc3bbc92e1e7a6625440a08a32b3b0beeb301041f87ea31e0e46c5c74d3978bd4243229b9d003f56294459115e2abc01da6da1072459ce6ffba23d5d79f1852472dcb505b6c8e9794ddf93656d611dea979cc1e04175c79b500001976a914a8b6c41585b4c74bd23f9525726e6a9573743fa388ac6120d06b781953c80cd8a1966cb6074a57519a5bd518d5a98d763cd4ad973d98285b1b5b1214011a0c0a6515adaa8e6422700fbb2068bb01411f01752dfecb1661282dd5732f177f21a6a31b1c13b5d1a9646b4ee40f97695fd7715f8286d9e6d1f7e56359681b4dc3b2d09d3e59117af902d8d195ae46d907fe"]; + DSTransaction *tx = [DSTransactionFactory transactionWithMessage:message onChain:testnet]; + XCTAssert(tx, @"Malformed TX"); +} + @end From 5aaec2b87a72087dfa06f69fe0484df2634c73c2 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Tue, 14 Nov 2023 00:52:34 +0700 Subject: [PATCH 28/32] chore: fix proupsrvtx --- .../DSProviderUpdateServiceTransaction.m | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/DashSync/shared/Models/Transactions/Provider/DSProviderUpdateServiceTransaction.m b/DashSync/shared/Models/Transactions/Provider/DSProviderUpdateServiceTransaction.m index 9f44a04f8..cbd2ee993 100644 --- a/DashSync/shared/Models/Transactions/Provider/DSProviderUpdateServiceTransaction.m +++ b/DashSync/shared/Models/Transactions/Provider/DSProviderUpdateServiceTransaction.m @@ -43,7 +43,7 @@ - (instancetype)initWithMessage:(NSData *)message onChain:(DSChain *)chain { self.providerUpdateServiceTransactionVersion = [message UInt16AtOffset:off]; off += 2; - if (self.version == 2 /*BLS Basic*/) { + if ([self usesBasicBLS]) { if (length - off < 2) return nil; self.providerType = [message UInt16AtOffset:off]; off += 2; @@ -70,7 +70,7 @@ - (instancetype)initWithMessage:(NSData *)message onChain:(DSChain *)chain { self.inputsHash = [message UInt256AtOffset:off]; off += 32; - if (self.version == 2 /*BLS Basic*/ && self.providerType == 1 /*High Performance*/) { + if ([self usesBasicBLS] && [self usesHPMN]) { if (length - off < 20) return nil; self.platformNodeID = [message UInt160AtOffset:off]; off += 20; @@ -166,7 +166,7 @@ - (NSString *_Nullable)payoutAddress { - (NSData *)basePayloadData { NSMutableData *data = [NSMutableData data]; [data appendUInt16:self.providerUpdateServiceTransactionVersion]; - if (self.version == 2 /*BLS Basic*/) { + if ([self usesBasicBLS]) { [data appendUInt16:self.providerType]; } [data appendUInt256:self.providerRegistrationTransactionHash]; @@ -175,7 +175,7 @@ - (NSData *)basePayloadData { [data appendVarInt:self.scriptPayout.length]; [data appendData:self.scriptPayout]; [data appendUInt256:self.inputsHash]; - if (self.version == 2 /*BLS Basic*/ && self.providerType == 1 /*High Performance*/) { + if ([self usesBasicBLS] && [self usesHPMN]) { [data appendUInt160:self.platformNodeID]; [data appendUInt16:CFSwapInt16BigToHost(self.platformP2PPort)]; [data appendUInt16:CFSwapInt16BigToHost(self.platformHTTPPort)]; @@ -231,4 +231,12 @@ - (void)hasSetInputsAndOutputs { [self updateInputsHash]; } +- (BOOL)usesBasicBLS { + return self.providerUpdateServiceTransactionVersion == 2; +} + +- (BOOL)usesHPMN { + return self.providerType == 1; +} + @end From 42764d8eb0364540638796e1a7117d2aee2dae0d Mon Sep 17 00:00:00 2001 From: pankcuf Date: Wed, 15 Nov 2023 22:26:39 +0700 Subject: [PATCH 29/32] chore: just encapsulate rust calls, since rust calls shouldn't be used directly in the wallet --- DashSync/shared/Models/Chain/DSChain.h | 2 ++ DashSync/shared/Models/Chain/DSChain.m | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/DashSync/shared/Models/Chain/DSChain.h b/DashSync/shared/Models/Chain/DSChain.h index 6836ffcb6..f28612750 100644 --- a/DashSync/shared/Models/Chain/DSChain.h +++ b/DashSync/shared/Models/Chain/DSChain.h @@ -480,6 +480,8 @@ typedef NS_ENUM(uint16_t, DSChainSyncPhase) - (BOOL)isEvolutionEnabled; - (BOOL)isDevnetWithGenesisHash:(UInt256)genesisHash; - (BOOL)isCore19Active; +- (BOOL)isCore20Active; +- (BOOL)isCore20ActiveAtHeight:(uint32_t)height; - (KeyKind)activeBLSType; @end diff --git a/DashSync/shared/Models/Chain/DSChain.m b/DashSync/shared/Models/Chain/DSChain.m index df45e447e..e7759de95 100644 --- a/DashSync/shared/Models/Chain/DSChain.m +++ b/DashSync/shared/Models/Chain/DSChain.m @@ -413,6 +413,14 @@ - (BOOL)isCore19Active { return self.lastTerminalBlockHeight >= chain_core19_activation_height(self.chainType); } +- (BOOL)isCore20Active { + return self.lastTerminalBlockHeight >= chain_core20_activation_height(self.chainType); +} + +- (BOOL)isCore20ActiveAtHeight:(uint32_t)height { + return height >= chain_core20_activation_height(self.chainType); +} + - (KeyKind)activeBLSType { return [self isCore19Active] ? KeyKind_BLSBasic : KeyKind_BLS; } From a9be629975b72786bbd15201093e95f7a597e5a3 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Fri, 17 Nov 2023 12:43:22 +0700 Subject: [PATCH 30/32] chore: make logs distinctive for chains --- DashSync/shared/Models/Chain/DSBlock.m | 8 +- DashSync/shared/Models/Chain/DSChain.m | 77 +++---- DashSync/shared/Models/Chain/DSChainLock.m | 22 +- DashSync/shared/Models/Chain/DSFullBlock.m | 12 +- DashSync/shared/Models/Chain/DSMerkleBlock.m | 4 +- .../DSAuthenticationKeysDerivationPath.m | 6 +- .../Derivation Paths/DSDerivationPath.m | 4 +- .../Derivation Paths/DSFundsDerivationPath.m | 6 +- .../DSIncomingFundsDerivationPath.m | 6 +- .../DSSimpleIndexedDerivationPath.m | 6 +- .../Managers/Chain Managers/DSChainManager.m | 26 +-- .../Chain Managers/DSGovernanceSyncManager.m | 26 +-- .../Managers/Chain Managers/DSKeyManager.m | 2 +- .../DSMasternodeManager+Mndiff.m | 6 +- .../Chain Managers/DSMasternodeManager.m | 74 +++---- .../Managers/Chain Managers/DSPeerManager.m | 83 ++++--- .../Managers/Chain Managers/DSSporkManager.m | 4 +- .../Chain Managers/DSTransactionManager.m | 205 +++++++++--------- .../Auth/DSAuthenticationManager.m | 2 +- .../Models/Masternode/DSLocalMasternode.m | 1 - .../Masternode/DSMasternodeListDiffService.m | 6 +- .../Masternode/DSMasternodeListService.m | 18 +- .../Models/Masternode/DSMasternodeListStore.h | 1 - .../Models/Masternode/DSMasternodeListStore.m | 53 +++-- .../Masternode/DSMnDiffProcessingResult.m | 2 +- .../Masternode/DSQRInfoProcessingResult.m | 4 +- .../shared/Models/Masternode/DSQuorumEntry.m | 4 +- .../Masternode/DSQuorumRotationService.m | 10 +- .../Masternode/DSSimplifiedMasternodeEntry.m | 2 +- DashSync/shared/Models/Network/DSPeer.m | 184 ++++++++-------- .../Base/DSInstantSendTransactionLock.m | 16 +- .../Models/Transactions/Base/DSTransaction.m | 2 +- .../DSProviderRegistrationTransaction.m | 4 +- DashSync/shared/Models/Wallet/DSAccount.m | 22 +- .../DSSpecialTransactionsWalletHolder.m | 4 +- DashSync/shared/Models/Wallet/DSWallet.m | 8 +- 36 files changed, 452 insertions(+), 468 deletions(-) diff --git a/DashSync/shared/Models/Chain/DSBlock.m b/DashSync/shared/Models/Chain/DSBlock.m index 4aee84c40..f0400d26e 100644 --- a/DashSync/shared/Models/Chain/DSBlock.m +++ b/DashSync/shared/Models/Chain/DSBlock.m @@ -133,7 +133,7 @@ - (BOOL)canCalculateDifficultyWithPreviousBlocks:(NSDictionary *)previousBlocks } currentBlock = previousBlocks[uint256_obj(currentBlock.prevBlock)]; if (!currentBlock) { - DSLog(@"Could not retrieve previous block"); + DSLog(@"[%@] Could not retrieve previous block", self.chain.name); return FALSE; } } @@ -150,7 +150,7 @@ - (BOOL)verifyDifficultyWithPreviousBlocks:(NSDictionary *)previousBlocks rDiffi } int32_t diff = self.target - darkGravityWaveTarget; if (abs(diff) > 1) { - DSLog(@"weird difficulty for block at height %u with target %@ (off by %u)", self.height, uint256_hex(setCompactBE(self.target)), diff); + DSLog(@"[%@] weird difficulty for block at height %u with target %@ (off by %u)", self.chain.name, self.height, uint256_hex(setCompactBE(self.target)), diff); } return (abs(diff) < 2); //the core client is less precise with a rounding error that can sometimes cause a problem. We are very rarely 1 off } @@ -173,7 +173,7 @@ - (int32_t)darkGravityWaveTargetWithPreviousBlocks:(NSDictionary *)previousBlock if (self.chain.allowMinDifficultyBlocks) { // recent block is more than 2 hours old if (self.timestamp > (previousBlock.timestamp + 2 * 60 * 60)) { - DSLog(@"Our block is way ahead of previous block %d > %d", self.timestamp, previousBlock.timestamp); + DSLog(@"[%@] Our block is way ahead of previous block %d > %d", self.chain.name, self.timestamp, previousBlock.timestamp); return self.chain.maxProofOfWorkTarget; } // recent block is more than 10 minutes old @@ -218,7 +218,7 @@ - (int32_t)darkGravityWaveTargetWithPreviousBlocks:(NSDictionary *)previousBlock DSBlock *oldCurrentBlock = currentBlock; currentBlock = previousBlocks[uint256_obj(currentBlock.prevBlock)]; if (!currentBlock) { - DSLog(@"Block %d missing for dark gravity wave calculation", oldCurrentBlock.height - 1); + DSLog(@"[%@] Block %d missing for dark gravity wave calculation", self.chain.name, oldCurrentBlock.height - 1); } } UInt256 blockCount256 = ((UInt256){.u64 = {blockCount, 0, 0, 0}}); diff --git a/DashSync/shared/Models/Chain/DSChain.m b/DashSync/shared/Models/Chain/DSChain.m index e7759de95..d9b0e0d2a 100644 --- a/DashSync/shared/Models/Chain/DSChain.m +++ b/DashSync/shared/Models/Chain/DSChain.m @@ -1516,7 +1516,7 @@ - (void)setLastTerminalBlockFromCheckpoints { } if (_lastTerminalBlock) { - DSLog(@"last terminal block at height %d chosen from checkpoints (hash is %@)", _lastTerminalBlock.height, [NSData dataWithUInt256:_lastTerminalBlock.blockHash].hexString); + DSLog(@"[%@] last terminal block at height %d chosen from checkpoints (hash is %@)", self.name, _lastTerminalBlock.height, [NSData dataWithUInt256:_lastTerminalBlock.blockHash].hexString); } } @@ -1544,7 +1544,7 @@ - (void)setLastSyncBlockFromCheckpoints { } if (_lastSyncBlock) { - DSLog(@"last sync block at height %d chosen from checkpoints for chain %@ (hash is %@)", _lastSyncBlock.height, self.name, [NSData dataWithUInt256:_lastSyncBlock.blockHash].hexString); + DSLog(@"[%@] last sync block at height %d chosen from checkpoints (hash is %@)", self.name, _lastSyncBlock.height, self.name, [NSData dataWithUInt256:_lastSyncBlock.blockHash].hexString); } } @@ -1564,7 +1564,7 @@ - (DSBlock *)lastSyncBlockWithUseCheckpoints:(BOOL)useCheckpoints { } if (!_lastSyncBlock && useCheckpoints) { - DSLog(@"No last Sync Block, setting it from checkpoints"); + DSLog(@"[%@] No last Sync Block, setting it from checkpoints", self.name); [self setLastSyncBlockFromCheckpoints]; } @@ -1789,8 +1789,9 @@ - (BOOL)addMinedFullBlock:(DSFullBlock *)block { //TRUE if it was added to the end of the chain - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:(DSPeer *)peer { + NSString *prefix = [NSString stringWithFormat:@"[%@: %@:%d]", self.name, peer.host ? peer.host : @"TEST", peer.port]; if (peer && !self.chainManager.syncPhase) { - DSLog(@"Block was received from peer after reset, ignoring it"); + DSLog(@"%@ Block was received from peer after reset, ignoring it", prefix); return FALSE; } //DSLog(@"a block %@",uint256_hex(block.blockHash)); @@ -1835,10 +1836,10 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( #if LOG_PREV_BLOCKS_ON_ORPHAN NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:TRUE]; for (DSBlock *merkleBlock in [[self.blocks allValues] sortedArrayUsingDescriptors:@[sortDescriptor]]) { - DSLog(@"printing previous block at height %d : %@", merkleBlock.height, merkleBlock.blockHashValue); + DSLog(@"%@ printing previous block at height %d : %@", prefix, merkleBlock.height, merkleBlock.blockHashValue); } #endif - DSLog(@"%@:%d relayed orphan block %@, previous %@, height %d, last block is %@, lastBlockHeight %d, time %@", peer.host ? peer.host : @"TEST", peer.port, + DSLog(@"%@ relayed orphan block %@, previous %@, height %d, last block is %@, lastBlockHeight %d, time %@", prefix, uint256_reverse_hex(block.blockHash), uint256_reverse_hex(block.prevBlock), block.height, uint256_reverse_hex(self.lastTerminalBlock.blockHash), self.lastSyncBlockHeight, [NSDate dateWithTimeIntervalSince1970:block.timestamp]); if (peer) { @@ -1903,7 +1904,7 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( uint32_t foundDifficulty = 0; if ((block.height > self.minimumDifficultyBlocks) && (block.height > (lastCheckpoint.height + DGW_PAST_BLOCKS_MAX)) && ![block verifyDifficultyWithPreviousBlocks:(blockPosition & DSBlockPosition_Terminal) ? self.mTerminalBlocks : self.mSyncBlocks rDifficulty:&foundDifficulty]) { - DSLog(@"%@:%d relayed block with invalid difficulty height %d target %x foundTarget %x, blockHash: %@", peer.host, peer.port, + DSLog(@"%@ relayed block with invalid difficulty height %d target %x foundTarget %x, blockHash: %@", prefix, block.height, block.target, foundDifficulty, blockHash); if (peer) { @@ -1914,7 +1915,7 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( UInt256 difficulty = setCompactLE(block.target); if (uint256_sup(block.blockHash, difficulty)) { - DSLog(@"%@:%d relayed block with invalid block hash %d target %x, blockHash: %@ difficulty: %@", peer.host, peer.port, + DSLog(@"%@ relayed block with invalid block hash %d target %x, blockHash: %@ difficulty: %@", prefix, block.height, block.target, uint256_bin(block.blockHash), uint256_bin(difficulty)); if (peer) { @@ -1928,8 +1929,8 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( if ((!equivalentTerminalBlock) && (checkpoint && !uint256_eq(block.blockHash, checkpoint.blockHash))) { // verify block chain checkpoints - DSLog(@"%@:%d relayed a block that differs from the checkpoint at height %d, blockHash: %@, expected: %@", - peer.host, peer.port, block.height, blockHash, uint256_hex(checkpoint.blockHash)); + DSLog(@"%@ relayed a block that differs from the checkpoint at height %d, blockHash: %@, expected: %@", + prefix, block.height, blockHash, uint256_hex(checkpoint.blockHash)); if (peer) { [self.chainManager chain:self badBlockReceivedFromPeer:peer]; } @@ -1941,7 +1942,7 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( uint32_t h = block.height; if ((phase == DSChainSyncPhase_ChainSync || phase == DSChainSyncPhase_Synced) && uint256_eq(block.prevBlock, self.lastSyncBlockHash)) { // new block extends sync chain if ((block.height % 1000) == 0 || txHashes.count > 0 || h > peer.lastBlockHeight) { - DSLog(@"[%@: %@] + sync block at: %d: %@", self.name, peer.host ? peer.host : @"TEST", h, uint256_hex(block.blockHash)); + DSLog(@"%@ + sync block at: %d: %@", prefix, h, uint256_hex(block.blockHash)); } self.mSyncBlocks[blockHash] = block; if (equivalentTerminalBlock && equivalentTerminalBlock.chainLocked && !block.chainLocked) { @@ -1951,7 +1952,7 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( if (!equivalentTerminalBlock && uint256_eq(block.prevBlock, self.lastTerminalBlock.blockHash)) { if ((h % 1000) == 0 || txHashes.count > 0 || h > peer.lastBlockHeight) { - DSLog(@"[%@: %@] + terminal block (caught up) at: %d: %@", self.name, peer.host ? peer.host : @"TEST", h, uint256_hex(block.blockHash)); + DSLog(@"%@ + terminal block (caught up) at: %d: %@", prefix, h, uint256_hex(block.blockHash)); } self.mTerminalBlocks[blockHash] = block; self.lastTerminalBlock = block; @@ -1972,7 +1973,7 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( } else if (uint256_eq(block.prevBlock, self.lastTerminalBlock.blockHash)) { // new block extends terminal chain if ((h % 500) == 0 || txHashes.count > 0 || h > peer.lastBlockHeight) { - DSLog(@"[%@: %@] + terminal block at: %d: %@", self.name, peer.host ? peer.host : @"TEST", h, uint256_hex(block.blockHash)); + DSLog(@"%@ + terminal block at: %d: %@", prefix, h, uint256_hex(block.blockHash)); } self.mTerminalBlocks[blockHash] = block; self.lastTerminalBlock = block; @@ -1985,7 +1986,7 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( onMainChain = TRUE; } else if ((phase == DSChainSyncPhase_ChainSync || phase == DSChainSyncPhase_Synced) && self.mSyncBlocks[blockHash] != nil) { // we already have the block (or at least the header) if ((h % 1) == 0 || txHashes.count > 0 || h > peer.lastBlockHeight) { - DSLog(@"%@:%d relayed existing sync block at height %d", peer.host, peer.port, h); + DSLog(@"%@ relayed existing sync block at height %d", prefix, h); } self.mSyncBlocks[blockHash] = block; if (equivalentTerminalBlock && equivalentTerminalBlock.chainLocked && !block.chainLocked) { @@ -2008,7 +2009,7 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( } } else if (self.mTerminalBlocks[blockHash] != nil && (blockPosition & DSBlockPosition_Terminal)) { // we already have the block (or at least the header) if ((h % 1) == 0 || txHashes.count > 0 || h > peer.lastBlockHeight) { - DSLog(@"%@:%d relayed existing terminal block at height %d (last sync height %d)", peer.host, peer.port, h, self.lastSyncBlockHeight); + DSLog(@"%@ relayed existing terminal block at height %d (last sync height %d)", prefix, h, self.lastSyncBlockHeight); } self.mTerminalBlocks[blockHash] = block; @synchronized(peer) { @@ -2027,21 +2028,21 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( } } else { // new block is on a fork if (h <= [self lastCheckpoint].height) { // fork is older than last checkpoint - DSLog(@"ignoring block on fork older than most recent checkpoint, fork height: %d, blockHash: %@", h, blockHash); + DSLog(@"%@ ignoring block on fork older than most recent checkpoint, fork height: %d, blockHash: %@", prefix, h, blockHash); return TRUE; } if (h <= self.lastChainLock.height) { - DSLog(@"ignoring block on fork when main chain is chainlocked: %d, blockHash: %@", h, blockHash); + DSLog(@"%@ ignoring block on fork when main chain is chainlocked: %d, blockHash: %@", prefix, h, blockHash); return TRUE; } - DSLog(@"potential chain fork to height %d blockPosition %d", block.height, blockPosition); + DSLog(@"%@ potential chain fork to height %d blockPosition %d", prefix, block.height, blockPosition); if (!(blockPosition & DSBlockPosition_Sync)) { //this is only a reorg of the terminal blocks self.mTerminalBlocks[blockHash] = block; if (uint256_supeq(self.lastTerminalBlock.chainWork, block.chainWork)) return TRUE; // if fork is shorter than main chain, ignore it for now - DSLog(@"found potential chain fork on height %d", block.height); + DSLog(@"%@ found potential chain fork on height %d", prefix, block.height); DSBlock *b = block, *b2 = self.lastTerminalBlock; @@ -2051,11 +2052,11 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( } if (!uint256_eq(b.blockHash, b2.blockHash) && b2.chainLocked) { //intermediate chain locked block - DSLog(@"no reorganizing chain to height %d because of chainlock at height %d", h, b2.height); + DSLog(@"%@ no reorganizing chain to height %d because of chainlock at height %d", prefix, h, b2.height); return TRUE; } - DSLog(@"reorganizing terminal chain from height %d, new height is %d", b.height, h); + DSLog(@"%@ reorganizing terminal chain from height %d, new height is %d", prefix, b.height, h); self.lastTerminalBlock = block; @synchronized(peer) { @@ -2075,7 +2076,7 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( } if (uint256_supeq(self.lastSyncBlock.chainWork, block.chainWork)) return TRUE; // if fork is shorter than main chain, ignore it for now - DSLog(@"found sync chain fork on height %d", h); + DSLog(@"%@ found sync chain fork on height %d", prefix, h); if ((phase == DSChainSyncPhase_ChainSync || phase == DSChainSyncPhase_Synced) && !uint256_supeq(self.lastTerminalBlock.chainWork, block.chainWork)) { DSBlock *b = block, *b2 = self.lastTerminalBlock; @@ -2085,9 +2086,9 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( } if (!uint256_eq(b.blockHash, b2.blockHash) && b2.chainLocked) { //intermediate chain locked block - DSLog(@"no reorganizing chain to height %d because of chainlock at height %d", h, b2.height); + DSLog(@"%@ no reorganizing chain to height %d because of chainlock at height %d", prefix, h, b2.height); } else { - DSLog(@"reorganizing terminal chain from height %d, new height is %d", b.height, h); + DSLog(@"%@ reorganizing terminal chain from height %d, new height is %d", prefix, b.height, h); self.lastTerminalBlock = block; @synchronized(peer) { if (peer) { @@ -2105,11 +2106,11 @@ - (BOOL)addBlock:(DSBlock *)block receivedAsHeader:(BOOL)isHeaderOnly fromPeer:( } if (!uint256_eq(b.blockHash, b2.blockHash) && b2.chainLocked) { //intermediate chain locked block - DSLog(@"no reorganizing sync chain to height %d because of chainlock at height %d", h, b2.height); + DSLog(@"%@ no reorganizing sync chain to height %d because of chainlock at height %d", prefix, h, b2.height); return TRUE; } - DSLog(@"reorganizing sync chain from height %d, new height is %d", b.height, h); + DSLog(@"%@ reorganizing sync chain from height %d, new height is %d", prefix, b.height, h); NSMutableArray *txHashes = [NSMutableArray array]; // mark transactions after the join point as unconfirmed @@ -2274,7 +2275,7 @@ - (DSBlock *)lastTerminalBlock { @synchronized (self) { self->_lastTerminalBlock = lastTerminalBlock; if (lastTerminalBlock) { - DSLog(@"last terminal block at height %d recovered from db (hash is %@)", lastTerminalBlock.height, [NSData dataWithUInt256:lastTerminalBlock.blockHash].hexString); + DSLog(@"[%@] last terminal block at height %d recovered from db (hash is %@)", self.name, lastTerminalBlock.height, [NSData dataWithUInt256:lastTerminalBlock.blockHash].hexString); } } }]; @@ -2343,7 +2344,7 @@ - (BOOL)addChainLock:(DSChainLock *)chainLock { [terminalBlock setChainLockedWithChainLock:chainLock]; if ((terminalBlock.chainLocked) && (![self recentTerminalBlockForBlockHash:terminalBlock.blockHash])) { //the newly chain locked block is not in the main chain, we will need to reorg to it - NSLog(@"Added a chain lock for block %@ that was not on the main terminal chain ending in %@, reorginizing", terminalBlock, self.lastSyncBlock); + DSLog(@"[%@] Added a chain lock for block %@ that was not on the main terminal chain ending in %@, reorginizing", self.name, terminalBlock, self.lastSyncBlock); //clb chain locked block //tbmc terminal block DSBlock *clb = terminalBlock, *tbmc = self.lastTerminalBlock; @@ -2365,9 +2366,9 @@ - (BOOL)addChainLock:(DSChainLock *)chainLock { } if (cancelReorg) { - NSLog(@"Cancelling terminal reorg because block %@ is already chain locked", tbmc); + DSLog(@"[%@] Cancelling terminal reorg because block %@ is already chain locked", self.name, tbmc); } else { - NSLog(@"Reorginizing to height %d", clb.height); + DSLog(@"[%@] Reorginizing to height %d", self.name, clb.height); self.lastTerminalBlock = terminalBlock; NSMutableDictionary *forkChainsTerminalBlocks = [[self forkChainsTerminalBlocks] mutableCopy]; @@ -2396,7 +2397,7 @@ - (BOOL)addChainLock:(DSChainLock *)chainLock { DSBlock *sbmc = self.lastSyncBlockDontUseCheckpoints; if (sbmc && (syncBlock.chainLocked) && ![self recentSyncBlockForBlockHash:syncBlock.blockHash]) { //!OCLINT //the newly chain locked block is not in the main chain, we will need to reorg to it - NSLog(@"Added a chain lock for block %@ that was not on the main sync chain ending in %@, reorginizing", syncBlock, self.lastSyncBlock); + DSLog(@"[%@] Added a chain lock for block %@ that was not on the main sync chain ending in %@, reorginizing", self.name, syncBlock, self.lastSyncBlock); //clb chain locked block //sbmc sync block main chain @@ -2418,11 +2419,11 @@ - (BOOL)addChainLock:(DSChainLock *)chainLock { } if (cancelReorg) { - NSLog(@"Cancelling sync reorg because block %@ is already chain locked", sbmc); + DSLog(@"[%@] Cancelling sync reorg because block %@ is already chain locked", self.name, sbmc); } else { self.lastSyncBlock = syncBlock; - NSLog(@"Reorginizing to height %d (last sync block %@)", clb.height, self.lastSyncBlock); + DSLog(@"[%@] Reorginizing to height %d (last sync block %@)", self.name, clb.height, self.lastSyncBlock); NSMutableArray *txHashes = [NSMutableArray array]; @@ -2910,7 +2911,7 @@ - (DSTransactionDirection)directionOfTransaction:(DSTransaction *)transaction { // MARK: - Wiping - (void)wipeBlockchainInfoInContext:(NSManagedObjectContext *)context { - DSLog(@"Wiping Blockchain Info"); + DSLog(@"[%@] Wiping Blockchain Info", self.name); for (DSWallet *wallet in self.wallets) { [wallet wipeBlockchainInfoInContext:context]; } @@ -2938,7 +2939,7 @@ - (void)wipeBlockchainInfoInContext:(NSManagedObjectContext *)context { } - (void)wipeBlockchainNonTerminalInfoInContext:(NSManagedObjectContext *)context { - DSLog(@"Wiping Blockchain Non Terminal Info"); + DSLog(@"[%@] Wiping Blockchain Non Terminal Info", self.name); for (DSWallet *wallet in self.wallets) { [wallet wipeBlockchainInfoInContext:context]; } @@ -2961,7 +2962,7 @@ - (void)wipeBlockchainNonTerminalInfoInContext:(NSManagedObjectContext *)context } - (void)wipeMasternodesInContext:(NSManagedObjectContext *)context { - DSLog(@"Wiping Masternode Info"); + DSLog(@"[%@] Wiping Masternode Info", self.name); DSChainEntity *chainEntity = [self chainEntityInContext:context]; [DSLocalMasternodeEntity deleteAllOnChainEntity:chainEntity]; [DSSimplifiedMasternodeEntryEntity deleteAllOnChainEntity:chainEntity]; @@ -2973,7 +2974,7 @@ - (void)wipeMasternodesInContext:(NSManagedObjectContext *)context { } - (void)wipeWalletsAndDerivatives { - DSLog(@"Wiping Wallets and Derivatives"); + DSLog(@"[%@] Wiping Wallets and Derivatives", self.name); [self unregisterAllWallets]; [self unregisterAllStandaloneDerivationPaths]; self.mWallets = [NSMutableArray array]; @@ -3516,7 +3517,7 @@ - (void)saveBlockLocators { [entities addObject:e]; } for (DSTransactionHashEntity *e in entities) { - DSLogPrivate(@"blockHeight is %u for %@", e.blockHeight, e.txHash); + DSLogPrivate(@"[%@] blockHeight is %u for %@", self.name, e.blockHeight, e.txHash); } self.transactionHashHeights = [NSMutableDictionary dictionary]; self.transactionHashTimestamps = [NSMutableDictionary dictionary]; diff --git a/DashSync/shared/Models/Chain/DSChainLock.m b/DashSync/shared/Models/Chain/DSChainLock.m index 4f50f3e10..3d9af3dea 100644 --- a/DashSync/shared/Models/Chain/DSChainLock.m +++ b/DashSync/shared/Models/Chain/DSChainLock.m @@ -74,7 +74,7 @@ - (instancetype)initWithMessage:(NSData *)message onChain:(DSChain *)chain { off += sizeof(UInt768); self.chain = chain; - DSLog(@"the chain lock signature received for height %d (sig %@) (blockhash %@)", self.height, uint768_hex(_signature), uint256_hex(_blockHash)); + DSLog(@"[%@] the chain lock signature received for height %d (sig %@) (blockhash %@)", chain.name, self.height, uint768_hex(_signature), uint256_hex(_blockHash)); return self; } @@ -102,7 +102,7 @@ - (UInt256)requestID { [data appendString:@"clsig"]; [data appendUInt32:self.height]; _requestID = [data SHA256_2]; - DSLog(@"the chain lock request ID is %@ for height %d", uint256_hex(_requestID), self.height); + DSLog(@"[%@] the chain lock request ID is %@ for height %d", self.chain.name, uint256_hex(_requestID), self.height); return _requestID; } @@ -119,9 +119,9 @@ - (BOOL)verifySignatureAgainstQuorum:(DSQuorumEntry *)quorumEntry { UInt256 signId = [self signIDForQuorumEntry:quorumEntry]; BOOL verified = key_bls_verify(quorumEntry.quorumPublicKey.u8, quorumEntry.useLegacyBLSScheme, signId.u8, self.signature.u8); #if DEBUG - DSLog(@"verifySignatureAgainstQuorum (%u): %u: %u: %@: %@: %@: %u", verified, quorumEntry.llmqType, quorumEntry.verified, @"", uint384_hex(quorumEntry.quorumPublicKey), @"", quorumEntry.useLegacyBLSScheme); + DSLog(@"[%@] verifySignatureAgainstQuorum (%u): %u: %u: %@: %@: %@: %u", self.chain.name, verified, quorumEntry.llmqType, quorumEntry.verified, @"", uint384_hex(quorumEntry.quorumPublicKey), @"", quorumEntry.useLegacyBLSScheme); #else - DSLogPrivate(@"verifySignatureAgainstQuorum (%u): %u: %u: %@: %@: %@: %u", verified, quorumEntry.llmqType, quorumEntry.verified, uint256_hex(signId), uint384_hex(quorumEntry.quorumPublicKey), uint768_hex(self.signature), quorumEntry.useLegacyBLSScheme); + DSLogPrivate(@"[%@] verifySignatureAgainstQuorum (%u): %u: %u: %@: %@: %@: %u", self.chain.name, verified, quorumEntry.llmqType, quorumEntry.verified, uint256_hex(signId), uint384_hex(quorumEntry.quorumPublicKey), uint768_hex(self.signature), quorumEntry.useLegacyBLSScheme); #endif return verified; } @@ -147,15 +147,15 @@ - (BOOL)verifySignatureWithQuorumOffset:(uint32_t)offset { if (quorumEntry && quorumEntry.verified) { self.signatureVerified = [self verifySignatureAgainstQuorum:quorumEntry]; if (!self.signatureVerified) { - DSLog(@"unable to verify signature with offset %d", offset); + DSLog(@"[%@] unable to verify signature with offset %d", self.chain.name, offset); } else { - DSLog(@"signature verified with offset %d", offset); + DSLog(@"[%@] signature verified with offset %d", self.chain.name, offset); } } else if (quorumEntry) { - DSLog(@"quorum entry %@ found but is not yet verified", uint256_hex(quorumEntry.quorumHash)); + DSLog(@"[%@] quorum entry %@ found but is not yet verified", self.chain.name, uint256_hex(quorumEntry.quorumHash)); } else { - DSLog(@"no quorum entry found"); + DSLog(@"[%@] no quorum entry found", self.chain.name); } if (self.signatureVerified) { self.intendedQuorum = quorumEntry; @@ -166,14 +166,14 @@ - (BOOL)verifySignatureWithQuorumOffset:(uint32_t)offset { } } else if (quorumEntry.verified && offset == 8) { //try again a few blocks more in the past - DSLog(@"trying with offset 0"); + DSLog(@"[%@] trying with offset 0", self.chain.name); return [self verifySignatureWithQuorumOffset:0]; } else if (quorumEntry.verified && offset == 0) { //try again a few blocks more in the future - DSLog(@"trying with offset 16"); + DSLog(@"[%@] trying with offset 16", self.chain.name); return [self verifySignatureWithQuorumOffset:16]; } - DSLog(@"returning chain lock signature verified %d with offset %d", self.signatureVerified, offset); + DSLog(@"[%@] returning chain lock signature verified %d with offset %d", self.chain.name, self.signatureVerified, offset); return self.signatureVerified; } diff --git a/DashSync/shared/Models/Chain/DSFullBlock.m b/DashSync/shared/Models/Chain/DSFullBlock.m index cc268d002..585f6f9f4 100644 --- a/DashSync/shared/Models/Chain/DSFullBlock.m +++ b/DashSync/shared/Models/Chain/DSFullBlock.m @@ -83,15 +83,15 @@ - (instancetype)initWithMessage:(NSData *)message onChain:(DSChain *)chain { self.totalTransactions = (uint32_t)transactions.count; if (![self isMerkleTreeValid]) { - DSLog(@"Merkle tree not valid for block"); + DSLog(@"[%@] Merkle tree not valid for block", self.chain.name); return nil; } #if LOG_BLOCKS || LOG_BLOCKS_FULL #if LOG_BLOCKS_FULL - DSLog(@"%d - block %@ (%@) has %d transactions", self.height, uint256_hex(self.blockHash), message.hexString, self.totalTransactions); + DSLog(@"[%@] %d - block %@ (%@) has %d transactions", self.chain.name, self.height, uint256_hex(self.blockHash), message.hexString, self.totalTransactions); #else - DSLog(@"%d - block %@ has %d transactions", self.height, uint256_hex(self.blockHash), self.totalTransactions); + DSLog(@"[%@] %d - block %@ has %d transactions", self.chain.name, self.height, uint256_hex(self.blockHash), self.totalTransactions); #endif #endif @@ -171,7 +171,7 @@ - (BOOL)mineBlockAfterBlock:(DSBlock *)block withNonceOffset:(uint32_t)nonceOffs NSMutableData *preNonceMutableData = [self preNonceMutableData]; uint32_t i = 0; UInt256 fullTarget = setCompactLE(block.target); - DSLog(@"Trying to mine a block at height %d with target %@", block.height, uint256_bin(fullTarget)); + DSLog(@"[%@] Trying to mine a block at height %d with target %@", self.chain.name, block.height, uint256_bin(fullTarget)); #if LOG_MINING_BEST_TRIES UInt256 bestTry = UINT256_MAX; #endif @@ -182,14 +182,14 @@ - (BOOL)mineBlockAfterBlock:(DSBlock *)block withNonceOffset:(uint32_t)nonceOffs if (!uint256_sup(potentialBlockHash, fullTarget)) { //We found a block - DSLog(@"A Block was found %@ %@", uint256_bin(fullTarget), uint256_bin(potentialBlockHash)); + DSLog(@"[%@] A Block was found %@ %@", self.chain.name, uint256_bin(fullTarget), uint256_bin(potentialBlockHash)); self.blockHash = potentialBlockHash; found = TRUE; break; } #if LOG_MINING_BEST_TRIES else if (uint256_sup(bestTry, potentialBlockHash)) { - DSLog(@"New best try (%d) found for target %@ %@", i, uint256_bin(fullTarget), uint256_bin(potentialBlockHash)); + DSLog(@"[%@] New best try (%d) found for target %@ %@", self.chain.name, i, uint256_bin(fullTarget), uint256_bin(potentialBlockHash)); bestTry = potentialBlockHash; } #endif diff --git a/DashSync/shared/Models/Chain/DSMerkleBlock.m b/DashSync/shared/Models/Chain/DSMerkleBlock.m index 0c73ab263..ebdf7a2da 100644 --- a/DashSync/shared/Models/Chain/DSMerkleBlock.m +++ b/DashSync/shared/Models/Chain/DSMerkleBlock.m @@ -95,9 +95,9 @@ - (instancetype)initWithMessage:(NSData *)message onChain:(DSChain *)chain { #if LOG_MERKLE_BLOCKS || LOG_MERKLE_BLOCKS_FULL #if LOG_MERKLE_BLOCKS_FULL - DSLog(@"%d - merkle block %@ (%@) has %d transactions", self.height, uint256_hex(self.blockHash), message.hexString, self.totalTransactions); + DSLog(@"[%@] %d - merkle block %@ (%@) has %d transactions", self.chain.name, self.height, uint256_hex(self.blockHash), message.hexString, self.totalTransactions); #else - DSLog(@"%d - merkle block %@ has %d transactions", self.height, uint256_hex(self.blockHash), self.totalTransactions); + DSLog(@"[%@] %d - merkle block %@ has %d transactions", self.chain.name, self.height, uint256_hex(self.blockHash), self.totalTransactions); #endif #endif diff --git a/DashSync/shared/Models/Derivation Paths/DSAuthenticationKeysDerivationPath.m b/DashSync/shared/Models/Derivation Paths/DSAuthenticationKeysDerivationPath.m index 3c92666c2..55b753183 100644 --- a/DashSync/shared/Models/Derivation Paths/DSAuthenticationKeysDerivationPath.m +++ b/DashSync/shared/Models/Derivation Paths/DSAuthenticationKeysDerivationPath.m @@ -126,9 +126,9 @@ - (void)loadAddresses { if (![DSKeyManager isValidDashAddress:e.address forChain:self.wallet.chain]) { #if DEBUG - DSLogPrivate(@"address %@ loaded but was not valid on chain %@", e.address, self.wallet.chain.name); + DSLogPrivate(@"[%@] address %@ loaded but was not valid on chain", self.wallet.chain.name, e.address); #else - DSLog(@"address %@ loaded but was not valid on chain %@", @"", self.wallet.chain.name); + DSLog(@"[%@] address %@ loaded but was not valid on chain", self.wallet.chain.name, @""); #endif continue; } @@ -199,7 +199,7 @@ - (NSArray *)registerAddressesWithGapLimit:(NSUInteger)gapLimit forIdentityIndex NSString *addr = [DSKeyManager NSStringFrom:key_address_with_public_key_data(pubKey.bytes, pubKey.length, self.chain.chainType)]; if (!addr) { - DSLog(@"error generating keys"); + DSLog(@"[%@] error generating keys", self.chain.name); if (error) { *error = [NSError errorWithCode:500 localizedDescriptionKey:@"Error generating public keys"]; } diff --git a/DashSync/shared/Models/Derivation Paths/DSDerivationPath.m b/DashSync/shared/Models/Derivation Paths/DSDerivationPath.m index ee85bb487..4bf8267bf 100644 --- a/DashSync/shared/Models/Derivation Paths/DSDerivationPath.m +++ b/DashSync/shared/Models/Derivation Paths/DSDerivationPath.m @@ -290,9 +290,9 @@ - (OpaqueKey *)extendedPublicKey { DSBlockchainIdentityUsernameEntity *sourceUsernameEntity = [friendRequest.sourceContact.associatedBlockchainIdentity.usernames anyObject]; DSBlockchainIdentityUsernameEntity *destinationUsernameEntity = [friendRequest.destinationContact.associatedBlockchainIdentity.usernames anyObject]; #if DEBUG - DSLogPrivate(@"No extended public key set for the relationship between %@ and %@ (%@ receiving payments) ", sourceUsernameEntity.stringValue, destinationUsernameEntity.stringValue, sourceUsernameEntity.stringValue); + DSLogPrivate(@"[%@] No extended public key set for the relationship between %@ and %@ (%@ receiving payments) ", self.chain.name, sourceUsernameEntity.stringValue, destinationUsernameEntity.stringValue, sourceUsernameEntity.stringValue); #else - DSLog(@"No extended public key set for the relationship between %@ and %@ (%@ receiving payments) ", + DSLog(@"[%@] No extended public key set for the relationship between %@ and %@ (%@ receiving payments) ", self.chain.name, @"", @"", @""); diff --git a/DashSync/shared/Models/Derivation Paths/DSFundsDerivationPath.m b/DashSync/shared/Models/Derivation Paths/DSFundsDerivationPath.m index 6de0e83f5..1e8493331 100644 --- a/DashSync/shared/Models/Derivation Paths/DSFundsDerivationPath.m +++ b/DashSync/shared/Models/Derivation Paths/DSFundsDerivationPath.m @@ -92,9 +92,9 @@ - (void)loadAddresses { while (e.index >= a.count) [a addObject:[NSNull null]]; if (![DSKeyManager isValidDashAddress:e.address forChain:self.account.wallet.chain]) { #if DEBUG - DSLogPrivate(@"address %@ loaded but was not valid on chain %@", e.address, self.account.wallet.chain.name); + DSLogPrivate(@"[%@] address %@ loaded but was not valid on chain", self.account.wallet.chain.name, e.address); #else - DSLog(@"address %@ loaded but was not valid on chain %@", @"", self.account.wallet.chain.name); + DSLog(@"[%@] address %@ loaded but was not valid on chain %@", self.account.wallet.chain.name, @""); #endif /* DEBUG */ continue; } @@ -174,7 +174,7 @@ - (NSArray *)registerAddressesWithGapLimit:(NSUInteger)gapLimit internal:(BOOL)i NSString *addr = [DSKeyManager ecdsaKeyAddressFromPublicKeyData:pubKey forChainType:self.chain.chainType]; if (!addr) { - DSLog(@"error generating keys"); + DSLog(@"[%@] error generating keys", self.account.wallet.chain.name); if (error) { *error = [NSError errorWithCode:500 localizedDescriptionKey:@"Error generating public keys"]; } diff --git a/DashSync/shared/Models/Derivation Paths/DSIncomingFundsDerivationPath.m b/DashSync/shared/Models/Derivation Paths/DSIncomingFundsDerivationPath.m index f0ce741dc..7bbc16d2f 100644 --- a/DashSync/shared/Models/Derivation Paths/DSIncomingFundsDerivationPath.m +++ b/DashSync/shared/Models/Derivation Paths/DSIncomingFundsDerivationPath.m @@ -112,9 +112,9 @@ - (void)loadAddressesInContext:(NSManagedObjectContext *)context { while (e.index >= a.count) [a addObject:[NSNull null]]; if (![DSKeyManager isValidDashAddress:e.address forChain:self.account.wallet.chain]) { #if DEBUG - DSLogPrivate(@"address %@ loaded but was not valid on chain %@", e.address, self.account.wallet.chain.name); + DSLogPrivate(@"[%@] address %@ loaded but was not valid on chain", self.account.wallet.chain.name, e.address); #else - DSLog(@"address %@ loaded but was not valid on chain %@", @"", self.account.wallet.chain.name); + DSLog(@"[%@] address %@ loaded but was not valid on chain", self.account.wallet.chain.name, @""); #endif /* DEBUG */ continue; } @@ -212,7 +212,7 @@ - (NSArray *)registerAddressesWithGapLimit:(NSUInteger)gapLimit inContext:(NSMan while (a.count < upperLimit) { // generate new addresses up to gapLimit NSString *address = [self addressAtIndex:n]; if (!address) { - DSLog(@"error generating keys"); + DSLog(@"[%@] error generating keys", self.chain.name); if (error) { *error = [NSError errorWithCode:500 localizedDescriptionKey:@"Error generating public keys"]; } diff --git a/DashSync/shared/Models/Derivation Paths/DSSimpleIndexedDerivationPath.m b/DashSync/shared/Models/Derivation Paths/DSSimpleIndexedDerivationPath.m index 5191ff5df..41254a03c 100644 --- a/DashSync/shared/Models/Derivation Paths/DSSimpleIndexedDerivationPath.m +++ b/DashSync/shared/Models/Derivation Paths/DSSimpleIndexedDerivationPath.m @@ -32,9 +32,9 @@ - (void)loadAddresses { while (e.index >= self.mOrderedAddresses.count) [self.mOrderedAddresses addObject:[NSNull null]]; if (![DSKeyManager isValidDashAddress:e.address forChain:self.wallet.chain]) { #if DEBUG - DSLogPrivate(@"address %@ loaded but was not valid on chain %@", e.address, self.account.wallet.chain.name); + DSLogPrivate(@"[%@] address %@ loaded but was not valid on chain", self.account.wallet.chain.name, e.address); #else - DSLog(@"address %@ loaded but was not valid on chain %@", @"", self.account.wallet.chain.name); + DSLog(@"[%@] address %@ loaded but was not valid on chain", self.account.wallet.chain.name, @""); #endif /* DEBUG */ continue; } @@ -121,7 +121,7 @@ - (NSArray *)registerAddressesWithGapLimit:(NSUInteger)gapLimit error:(NSError * NSData *pubKey = [self publicKeyDataAtIndex:n]; NSString *addr = [DSKeyManager addressWithPublicKeyData:pubKey forChain:self.chain]; if (!addr) { - DSLog(@"error generating keys"); + DSLog(@"[%@] error generating keys", self.chain.name); if (error) { *error = [NSError errorWithCode:500 localizedDescriptionKey:@"Error generating public keys"]; } diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m index d83a39795..bec1e9000 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m @@ -107,7 +107,7 @@ - (instancetype)initWithChain:(DSChain *)chain { //[self loadHeightTransactionZones]; _miningQueue = dispatch_queue_create([[NSString stringWithFormat:@"org.dashcore.dashsync.mining.%@", self.chain.uniqueID] UTF8String], DISPATCH_QUEUE_SERIAL); - DSLog(@"DSChainManager.initWithChain %@", chain); + DSLog(@"[%@] DSChainManager.initWithChain %@", chain.name, chain); return self; } @@ -343,7 +343,7 @@ - (double)terminalHeaderSyncProgress { - (double)combinedSyncProgress { #if LOG_COMBINED_SYNC_PROGRESS - DSLog(@"combinedSyncProgress breakdown %f %f %f", self.terminalHeaderSyncProgress, self.masternodeManager.masternodeListAndQuorumsSyncProgress, self.chainSyncProgress); + DSLog(@"[%@] combinedSyncProgress breakdown %f %f %f", self.chain.name, self.terminalHeaderSyncProgress, self.masternodeManager.masternodeListAndQuorumsSyncProgress, self.chainSyncProgress); #endif if ((self.terminalHeaderSyncWeight + self.chainSyncWeight + self.masternodeListSyncWeight) == 0) { @synchronized (self.peerManager) { @@ -469,7 +469,7 @@ - (void)startSync { object:nil userInfo:@{DSChainManagerNotificationChainKey: self.chain}]; }); - DSLog(@"startSync -> peerManager::connect"); + DSLog(@"[%@] startSync -> peerManager::connect", self.chain.name); [self.peerManager connect]; } @@ -496,7 +496,7 @@ - (void)disconnectedMasternodeListAndBlocksRescan { object:nil userInfo:@{DSChainManagerNotificationChainKey: self.chain}]; }); - DSLog(@"disconnectedMasternodeListAndBlocksRescan -> peerManager::connect"); + DSLog(@"[%@] disconnectedMasternodeListAndBlocksRescan -> peerManager::connect", self.chain.name); [self.peerManager connect]; } @@ -510,7 +510,7 @@ - (void)disconnectedMasternodeListRescan { object:nil userInfo:@{DSChainManagerNotificationChainKey: self.chain}]; }); - DSLog(@"disconnectedMasternodeListRescan -> peerManager::connect"); + DSLog(@"[%@] disconnectedMasternodeListRescan -> peerManager::connect", self.chain.name); [self.peerManager connect]; } @@ -524,7 +524,7 @@ - (void)disconnectedSyncBlocksRescan { object:nil userInfo:@{DSChainManagerNotificationChainKey: self.chain}]; }); - DSLog(@"disconnectedSyncBlocksRescan -> peerManager::connect"); + DSLog(@"[%@] disconnectedSyncBlocksRescan -> peerManager::connect", self.chain.name); [self.peerManager connect]; } @@ -663,7 +663,7 @@ - (void)chainFinishedSyncingInitialHeaders:(DSChain *)chain fromPeer:(DSPeer *)p - (void)chainFinishedSyncingTransactionsAndBlocks:(DSChain *)chain fromPeer:(DSPeer *)peer onMainChain:(BOOL)onMainChain { if (onMainChain && peer && (peer == self.peerManager.downloadPeer)) [self relayedNewItem]; - DSLog(@"chain finished syncing"); + DSLog(@"[%@] finished syncing", self.chain.name); self.chainSyncStartHeight = 0; self.syncPhase = DSChainSyncPhase_Synced; [self.transactionManager fetchMempoolFromNetwork]; @@ -676,12 +676,12 @@ - (void)chainFinishedSyncingTransactionsAndBlocks:(DSChain *)chain fromPeer:(DSP } - (void)syncBlockchain { - DSLog(@"syncBlockchain connected peers: %lu phase: %d", self.peerManager.connectedPeerCount, self.syncPhase); + DSLog(@"[%@] syncBlockchain connected peers: %lu phase: %d", self.chain.name, self.peerManager.connectedPeerCount, self.syncPhase); if (self.peerManager.connectedPeerCount == 0) { if (self.syncPhase == DSChainSyncPhase_InitialTerminalBlocks) { self.syncPhase = DSChainSyncPhase_ChainSync; } - DSLog(@"syncBlockchain -> peerManager::connect"); + DSLog(@"[%@] syncBlockchain -> peerManager::connect", self.chain.name); [self.peerManager connect]; } else if (!self.peerManager.masternodeList && self.masternodeManager.currentMasternodeList) { [self.peerManager useMasternodeList:self.masternodeManager.currentMasternodeList withConnectivityNonce:self.sessionConnectivityNonce]; @@ -692,7 +692,7 @@ - (void)syncBlockchain { } - (void)chainFinishedSyncingMasternodeListsAndQuorums:(DSChain *)chain { - DSLog(@"Chain finished syncing masternode list and quorums, it should start syncing chain"); + DSLog(@"[%@] finished syncing masternode list and quorums, it should start syncing chain", self.chain.name); if (chain.isEvolutionEnabled) { [self.identitiesManager syncBlockchainIdentitiesWithCompletion:^(NSArray *_Nullable blockchainIdentities) { [self syncBlockchain]; @@ -703,7 +703,7 @@ - (void)chainFinishedSyncingMasternodeListsAndQuorums:(DSChain *)chain { } - (void)chain:(DSChain *)chain badBlockReceivedFromPeer:(DSPeer *)peer { - DSLog(@"peer at address %@ is misbehaving", peer.host); + DSLog(@"[%@: %@:%d] peer is misbehaving", self.chain.name, peer.host, peer.port); [self.peerManager peerMisbehaving:peer errorMessage:@"Bad block received from peer"]; } @@ -713,7 +713,7 @@ - (void)chain:(DSChain *)chain receivedOrphanBlock:(DSBlock *)block fromPeer:(DS // call getblocks, unless we already did with the previous block, or we're still downloading the chain if (self.chain.lastSyncBlockHeight >= peer.lastBlockHeight && !uint256_eq(self.chain.lastOrphan.blockHash, block.prevBlock)) { - DSLog(@"%@:%d calling getblocks", peer.host, peer.port); + DSLog(@"[%@: %@:%d] calling getblocks", self.chain.name, peer.host, peer.port); [peer sendGetblocksMessageWithLocators:[self.chain chainSyncBlockLocatorArray] andHashStop:UINT256_ZERO]; } } @@ -769,7 +769,7 @@ - (void)peer:(DSPeer *)peer relayedSyncInfo:(DSSyncCountInfo)syncCountInfo count if (peer.governanceRequestState == DSGovernanceRequestState_GovernanceObjectVoteHashesReceived) { if (count == 0) { //there were no votes - DSLog(@"no votes on object, going to next object"); + DSLog(@"[%@: %@:%d] no votes on object, going to next object", self.chain.name, peer.host, peer.port); peer.governanceRequestState = DSGovernanceRequestState_GovernanceObjectVotes; [self.governanceSyncManager finishedGovernanceVoteSyncWithPeer:peer]; } else { diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSGovernanceSyncManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSGovernanceSyncManager.m index 3398b51c3..6d004a78e 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSGovernanceSyncManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSGovernanceSyncManager.m @@ -89,7 +89,7 @@ - (DSPeerManager *)peerManager { // MARK: - Governance Sync - (void)continueGovernanceSync { - DSLog(@"--> Continuing Governance Sync"); + DSLog(@"[%@] --> Continuing Governance Sync", self.chain.name); NSUInteger last3HoursStandaloneBroadcastHashesCount = [self last3HoursStandaloneGovernanceObjectHashesCount]; if (last3HoursStandaloneBroadcastHashesCount) { DSPeer *downloadPeer = nil; @@ -144,13 +144,13 @@ - (void)startGovernanceSync { } //We need to sync - DSLog(@"--> Trying to start governance sync"); + DSLog(@"[%@] --> Trying to start governance sync", self.chain.name); NSArray *sortedPeers = [self.peerManager.connectedPeers sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"lastRequestedGovernanceSync" ascending:YES]]]; BOOL startedGovernanceSync = FALSE; for (DSPeer *peer in sortedPeers) { if (peer.status != DSPeerStatus_Connected) continue; if ([[NSDate date] timeIntervalSince1970] - peer.lastRequestedGovernanceSync < 10800) { - DSLog(@"--> Peer recently used"); + DSLog(@"[%@] --> Peer recently used", self.chain.name); continue; //don't request less than every 3 hours from a peer } peer.lastRequestedGovernanceSync = [[NSDate date] timeIntervalSince1970]; //we are requesting the list from this peer @@ -186,7 +186,7 @@ - (void)publishVotes:(NSArray *)votes { - (void)startNextGoveranceVoteSyncWithPeer:(DSPeer *)peer { self.currentGovernanceSyncObject = [self.needVoteSyncGovernanceObjects firstObject]; self.currentGovernanceSyncObject.delegate = self; - DSLog(@"Getting votes for %@", self.currentGovernanceSyncObject.identifier); + DSLog(@"[%@] Getting votes for %@", self.chain.name, self.currentGovernanceSyncObject.identifier); [peer sendGovernanceSyncRequest:[DSGovernanceVotesSyncRequest requestWithParentHash:self.currentGovernanceSyncObject.governanceObjectHash]]; } @@ -354,7 +354,7 @@ - (void)peer:(DSPeer *)peer hasGovernanceObjectHashes:(NSSet *)governanceObjectH return; } } - DSLog(@"peer %@ relayed governance objects", peer.host); + DSLog(@"[%@: %@:%d] peer relayed governance objects", self.chain.name, peer.host, peer.port); NSMutableOrderedSet *hashesToInsert = [[NSOrderedSet orderedSetWithSet:governanceObjectHashes] mutableCopy]; NSMutableOrderedSet *hashesToUpdate = [[NSOrderedSet orderedSetWithSet:governanceObjectHashes] mutableCopy]; NSMutableOrderedSet *hashesToQuery = [[NSOrderedSet orderedSetWithSet:governanceObjectHashes] mutableCopy]; @@ -382,7 +382,7 @@ - (void)peer:(DSPeer *)peer hasGovernanceObjectHashes:(NSSet *)governanceObjectH NSError *error = nil; [self.managedObjectContext save:&error]; if (error) { - DSLog(@"%@", error); + DSLog(@"[%@: %@:%d]: %@", self.chain.name, peer.host, peer.port, error); } }]; if ([hashesToInsert count]) { @@ -396,11 +396,11 @@ - (void)peer:(DSPeer *)peer hasGovernanceObjectHashes:(NSSet *)governanceObjectH } self.knownGovernanceObjectHashes = rHashes; - DSLog(@"-> %lu - %lu", (unsigned long)[self.knownGovernanceObjectHashes count], (unsigned long)self.chain.totalGovernanceObjectsCount); + DSLog(@"[%@: %@:%d] -> %lu - %lu", self.chain.name, peer.host, peer.port, (unsigned long)[self.knownGovernanceObjectHashes count], (unsigned long)self.chain.totalGovernanceObjectsCount); NSUInteger countAroundNow = [self recentGovernanceObjectHashesCount]; if ([self.knownGovernanceObjectHashes count] > self.chain.totalGovernanceObjectsCount) { [self.managedObjectContext performBlockAndWait:^{ - DSLog(@"countAroundNow -> %lu - %lu", (unsigned long)countAroundNow, (unsigned long)self.chain.totalGovernanceObjectsCount); + DSLog(@"[%@: %@:%d] countAroundNow -> %lu - %lu", self.chain.name, peer.host, peer.port, (unsigned long)countAroundNow, (unsigned long)self.chain.totalGovernanceObjectsCount); if (countAroundNow > self.chain.totalGovernanceObjectsCount) { [DSGovernanceObjectHashEntity removeOldest:countAroundNow - self.chain.totalGovernanceObjectsCount onChainEntity:[self.chain chainEntityInContext:self.managedObjectContext]]; [self.managedObjectContext ds_save]; @@ -413,7 +413,7 @@ - (void)peer:(DSPeer *)peer hasGovernanceObjectHashes:(NSSet *)governanceObjectH } }]; } else if (countAroundNow == self.chain.totalGovernanceObjectsCount) { - DSLog(@"All governance object hashes received"); + DSLog(@"[%@: %@:%d] All governance object hashes received", self.chain.name, peer.host, peer.port); //we have all hashes, let's request objects. if (peer.governanceRequestState == DSGovernanceRequestState_GovernanceObjectHashesCountReceived) { peer.governanceRequestState = DSGovernanceRequestState_GovernanceObjects; @@ -463,7 +463,7 @@ - (DSGovernanceObject *)peer:(DSPeer *_Nullable)peer requestedGovernanceObject:( if (!([[DSOptionsManager sharedInstance] syncType] & DSSyncType_Governance)) return nil; // make sure we care about Governance objects DSGovernanceObject *proposal = [self.publishGovernanceObjects objectForKey:[NSData dataWithUInt256:governanceObjectHash]]; if (!proposal) { - DSLog(@"Peer requested unknown proposal"); + DSLog(@"[%@: %@:%d] Peer requested unknown proposal", self.chain.name, peer.host, peer.port); } return proposal; } @@ -502,7 +502,7 @@ - (void)peer:(DSPeer *_Nullable)peer relayedGovernanceVote:(DSGovernanceVote *)g [self finishedGovernanceVoteSyncWithPeer:peer]; } } else { - DSLog(@"no parent hash"); + DSLog(@"[%@: %@:%d] no parent hash", self.chain.name, peer.host, peer.port); } } @@ -516,7 +516,7 @@ - (DSGovernanceVote *)peer:(DSPeer *_Nullable)peer requestedVote:(UInt256)voteHa DSGovernanceVoteEntity *voteEntity = [votes firstObject]; vote = [voteEntity governanceVote]; } else { - DSLog(@"Peer requested unknown vote"); + DSLog(@"[%@: %@:%d] Peer requested unknown vote", self.chain.name, peer.host, peer.port); } }]; } @@ -525,7 +525,7 @@ - (DSGovernanceVote *)peer:(DSPeer *_Nullable)peer requestedVote:(UInt256)voteHa - (void)peer:(DSPeer *)peer ignoredGovernanceSync:(DSGovernanceRequestState)governanceRequestState { [self.peerManager peerMisbehaving:peer errorMessage:@"Ignored Governance Sync"]; - DSLog(@"ignoredGovernanceSync -> peerManager::connect"); + DSLog(@"[%@: %@:%d] ignoredGovernanceSync -> peerManager::connect", self.chain.name, peer.host, peer.port); [self.peerManager connect]; } diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSKeyManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSKeyManager.m index a1d7b9a42..de71bac40 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSKeyManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSKeyManager.m @@ -37,7 +37,7 @@ - (instancetype)initWithChain:(DSChain *)chain { NSParameterAssert(chain); if (!(self = [super init])) return nil; _keysCache = [DSKeyManager createKeysCache]; - NSLog(@"DSKeyManager.initWithChain: %@: ", chain); + DSLog(@"[%@] DSKeyManager.initWithChain: %@: ", chain.name, chain); return self; } diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.m b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.m index c46a523ba..1d1955269 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager+Mndiff.m @@ -223,7 +223,7 @@ + (void)destroyProcessorCache:(MasternodeProcessorCache *)processorCache { /// - (void)processMasternodeDiffWith:(NSData *)message context:(DSMasternodeProcessorContext *)context completion:(void (^)(DSMnDiffProcessingResult *result))completion { NSAssert(self.processor, @"processMasternodeDiffMessage: No processor created"); - DSLog(@"processMasternodeDiffWith: %@", context); + DSLog(@"[%@] processMasternodeDiffWith: %@", context.chain.name, context); MNListDiffResult *result = process_mnlistdiff_from_message(message.bytes, message.length, context.chain.chainType, @@ -241,7 +241,7 @@ - (void)processMasternodeDiffWith:(NSData *)message context:(DSMasternodeProcess - (void)processQRInfoWith:(NSData *)message context:(DSMasternodeProcessorContext *)context completion:(void (^)(DSQRInfoProcessingResult *result))completion { NSAssert(self.processor, @"processQRInfoMessage: No processor created"); NSAssert(self.processorCache, @"processQRInfoMessage: No processorCache created"); - DSLog(@"processQRInfoWith: %@", context); + DSLog(@"[%@] processQRInfoWith: %@", context.chain.name, context); QRInfoResult *result = process_qrinfo_from_message(message.bytes, message.length, context.chain.chainType, @@ -259,7 +259,7 @@ - (void)processQRInfoWith:(NSData *)message context:(DSMasternodeProcessorContex - (DSMnDiffProcessingResult *)processMasternodeDiffFromFile:(NSData *)message protocolVersion:(uint32_t)protocolVersion withContext:(DSMasternodeProcessorContext *)context { NSAssert(self.processor, @"processMasternodeDiffMessage: No processor created"); - DSLog(@"processMasternodeDiffMessage: %@", context); + DSLog(@"[%@] processMasternodeDiffMessage: %@", context.chain.name, context); MNListDiffResult *result = NULL; @synchronized (context) { result = process_mnlistdiff_from_message( diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m index c4609b2fc..363b6b350 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m @@ -268,7 +268,7 @@ - (DSMasternodeList *)loadMasternodeListAtBlockHash:(NSData *)blockHash withBloc } - (void)wipeMasternodeInfo { - DSLog(@"wipeMasternodeInfo"); + DSLog(@"[%@] wipeMasternodeInfo", self.chain.name); [self clearProcessorCache]; [self.store removeAllMasternodeLists]; [self.masternodeListDiffService cleanAllLists]; @@ -283,7 +283,7 @@ - (void)wipeMasternodeInfo { - (DSQuorumSnapshot *_Nullable)quorumSnapshotForBlockHeight:(uint32_t)blockHeight { DSBlock *block = [self.chain blockAtHeight:blockHeight]; if (!block) { - DSLog(@"No block for snapshot at height: %ul: ", blockHeight); + DSLog(@"[%@] No block for snapshot at height: %ul: ", self.chain.name, blockHeight); return nil; } return [self.store.cachedQuorumSnapshots objectForKey:uint256_data(block.blockHash)]; @@ -302,7 +302,7 @@ - (BOOL)saveQuorumSnapshot:(DSQuorumSnapshot *)snapshot { - (NSData *_Nullable)CLSignatureForBlockHeight:(uint32_t)blockHeight { DSBlock *block = [self.chain blockAtHeight:blockHeight]; if (!block) { - DSLog(@"No block for snapshot at height: %ul: ", blockHeight); + DSLog(@"[%@] No block for snapshot at height: %ul: ", self.chain.name, blockHeight); return nil; } return [self.store.cachedCLSignatures objectForKey:uint256_data(block.blockHash)]; @@ -328,7 +328,7 @@ - (BOOL)saveCLSignature:(NSData *)blockHashData signatureData:(NSData *)signatur - (BOOL)saveMasternodeList:(DSMasternodeList *)masternodeList forBlockHash:(UInt256)blockHash { /// TODO: need to properly store in CoreData or wait for rust SQLite - DSLog(@"••• addMasternodeList (saveMasternodeList) -> %@: %@", uint256_hex(blockHash), masternodeList); + DSLog(@"[%@] ••• cache mnlist -> %@: %@", self.chain.name, uint256_hex(blockHash), masternodeList); [self.store.masternodeListsByBlockHash setObject:masternodeList forKey:uint256_data(blockHash)]; return YES; } @@ -352,7 +352,7 @@ - (void)startSync { } - (void)getRecentMasternodeList { - DSLog(@"getRecentMasternodeList at tip"); + DSLog(@"[%@] getRecentMasternodeList at tip", self.chain.name); [self.masternodeListDiffService getRecentMasternodeList]; if (self.chain.isRotatedQuorumsPresented) { [self.quorumRotationService getRecentMasternodeList]; @@ -426,12 +426,12 @@ - (DSMasternodeList *__nullable)processRequestFromFileForBlockHash:(UInt256)bloc __block DSMerkleBlock *block = blockFinder(blockHash); if (![result isValid]) { - DSLog(@"Invalid File for block at height %u with merkleRoot %@ (foundCoinbase %@ | validQuorums %@ | rootMNListValid %@ | rootQuorumListValid %@)", block.height, uint256_hex(block.merkleRoot), result.foundCoinbase?@"Yes":@"No", result.validQuorums?@"Yes":@"No", result.rootMNListValid?@"Yes":@"No", result.rootQuorumListValid?@"Yes":@"No"); + DSLog(@"[%@] Invalid File for block at height %u with merkleRoot %@ (foundCoinbase %@ | validQuorums %@ | rootMNListValid %@ | rootQuorumListValid %@)", self.chain.name, block.height, uint256_hex(block.merkleRoot), result.foundCoinbase?@"Yes":@"No", result.validQuorums?@"Yes":@"No", result.rootMNListValid?@"Yes":@"No", result.rootQuorumListValid?@"Yes":@"No"); return NULL; } // valid Coinbase might be false if no merkle block if (block && !result.validCoinbase) { - DSLog(@"Invalid Coinbase for block at height %u with merkleRoot %@", block.height, uint256_hex(block.merkleRoot)); + DSLog(@"[%@] Invalid Coinbase for block at height %u with merkleRoot %@", self.chain.name, block.height, uint256_hex(block.merkleRoot)); return NULL; } DSMasternodeList *masternodeList = result.masternodeList; @@ -439,7 +439,7 @@ - (DSMasternodeList *__nullable)processRequestFromFileForBlockHash:(UInt256)bloc addedMasternodes:result.addedMasternodes modifiedMasternodes:result.modifiedMasternodes completion:^(NSError *_Nonnull error) { - DSLog(@"MNL Saved from file"); + DSLog(@"[%@] MNL Saved from file", self.chain.name); }]; return masternodeList; } @@ -510,7 +510,7 @@ - (void)removeOutdatedMasternodeListsBeforeBlockHash:(UInt256)blockHash { return; } if (heightToDelete > 0 && heightToDelete != UINT32_MAX) { - DSLog(@"--> removeOldMasternodeLists (removeOutdatedMasternodeListsBeforeBlockHash): %u (%u, %u)", heightToDelete, diffMasternodeList.height, qrinfoMasternodeList.height); + DSLog(@"[%@] --> removeOldMasternodeLists (removeOutdatedMasternodeListsBeforeBlockHash): %u (%u, %u)", self.chain.name, heightToDelete, diffMasternodeList.height, qrinfoMasternodeList.height); uint32_t h = heightToDelete - 50; NSDictionary *lists = [[self.store masternodeListsByBlockHash] copy]; for (NSData *proRegTxHashData in lists) { @@ -525,10 +525,10 @@ - (void)removeOutdatedMasternodeListsBeforeBlockHash:(UInt256)blockHash { - (void)processMasternodeListDiffResult:(DSMnDiffProcessingResult *)result forPeer:(DSPeer *)peer skipPresenceInRetrieval:(BOOL)skipPresenceInRetrieval completion:(void (^)(void))completion { DSMasternodeList *masternodeList = result.masternodeList; - DSLog(@"•••• processMasternodeListDiffResult: isValid: %d validCoinbase: %d", [result isValid], result.validCoinbase); + DSLog(@"[%@] •••• processMasternodeListDiffResult: isValid: %d validCoinbase: %d", self.chain.name, [result isValid], result.validCoinbase); if ([self.masternodeListDiffService shouldProcessDiffResult:result skipPresenceInRetrieval:skipPresenceInRetrieval]) { NSOrderedSet *neededMissingMasternodeLists = result.neededMissingMasternodeLists; - DSLog(@"•••• processMasternodeListDiffResult: missingMasternodeLists: %@", [self logListSet:neededMissingMasternodeLists]); + DSLog(@"[%@] •••• processMasternodeListDiffResult: missingMasternodeLists: %@", self.chain.name, [self logListSet:neededMissingMasternodeLists]); UInt256 masternodeListBlockHash = masternodeList.blockHash; NSData *masternodeListBlockHashData = uint256_data(masternodeListBlockHash); BOOL hasAwaitingQuorumValidation; @@ -547,11 +547,11 @@ - (void)processMasternodeListDiffResult:(DSMnDiffProcessingResult *)result forPe [self.store.masternodeListQueriesNeedingQuorumsValidated removeObject:masternodeListBlockHashData]; } } - DSLog(@"••• updateStoreWithMasternodeList: %u: %@ (%@)", masternodeList.height, uint256_hex(masternodeListBlockHash), uint256_reverse_hex(masternodeListBlockHash)); + DSLog(@"[%@] ••• updateStoreWithMasternodeList: %u: %@ (%@)", self.chain.name, masternodeList.height, uint256_hex(masternodeListBlockHash), uint256_reverse_hex(masternodeListBlockHash)); [self updateStoreWithProcessingResult:masternodeList result:result completion:^(NSError *error) { if ([result hasRotatedQuorumsForChain:self.chain] && !self.chain.isRotatedQuorumsPresented) { uint32_t masternodeListBlockHeight = [self heightForBlockHash:masternodeListBlockHash]; - DSLog(@"•••• processMasternodeListDiffResult: rotated quorums are presented at height %u: %@, so we'll switch into consuming qrinfo", masternodeListBlockHeight, uint256_hex(masternodeListBlockHash)); + DSLog(@"[%@] •••• processMasternodeListDiffResult: rotated quorums are presented at height %u: %@, so we'll switch into consuming qrinfo", self.chain.name, masternodeListBlockHeight, uint256_hex(masternodeListBlockHash)); self.chain.isRotatedQuorumsPresented = YES; self.rotatedQuorumsActivationHeight = masternodeListBlockHeight; [self.quorumRotationService addToRetrievalQueue:masternodeListBlockHashData]; @@ -574,7 +574,7 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * DSMnDiffProcessingResult *mnListDiffResultAtH2C = result.mnListDiffResultAtH2C; DSMnDiffProcessingResult *mnListDiffResultAtH3C = result.mnListDiffResultAtH3C; DSMnDiffProcessingResult *mnListDiffResultAtH4C = result.mnListDiffResultAtH4C; - DSLog(@"•••• processQRInfoResult tip: %d", [mnListDiffResultAtTip isValid]); + DSLog(@"[%@] •••• processQRInfoResult tip: %d", self.chain.name, [mnListDiffResultAtTip isValid]); NSOrderedSet *missingMasternodeListsAtTip = mnListDiffResultAtTip.neededMissingMasternodeLists; NSOrderedSet *missingMasternodeListsAtH = mnListDiffResultAtH.neededMissingMasternodeLists; @@ -590,7 +590,7 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * [missingMasternodeLists addObjectsFromArray:[missingMasternodeListsAtH2C array]]; [missingMasternodeLists addObjectsFromArray:[missingMasternodeListsAtH3C array]]; [missingMasternodeLists addObjectsFromArray:[missingMasternodeListsAtH4C array]]; - DSLog(@"•••• processQRInfoResult: missingMasternodeLists: %@", [self logListSet:missingMasternodeLists]); + DSLog(@"[%@] •••• processQRInfoResult: missingMasternodeLists: %@", self.chain.name, [self logListSet:missingMasternodeLists]); DSMasternodeList *masternodeListAtTip = mnListDiffResultAtTip.masternodeList; DSMasternodeList *masternodeListAtH = mnListDiffResultAtH.masternodeList; @@ -669,13 +669,13 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * [self.quorumRotationService updateAfterProcessingMasternodeListWithBlockHash:blockHashDataAtTip fromPeer:peer]; } } - [self.store saveQuorumSnapshot:result.snapshotAtHC toChain:self.chain completion:^(NSError * _Nonnull error) {}]; - [self.store saveQuorumSnapshot:result.snapshotAtH2C toChain:self.chain completion:^(NSError * _Nonnull error) {}]; - [self.store saveQuorumSnapshot:result.snapshotAtH3C toChain:self.chain completion:^(NSError * _Nonnull error) {}]; - [self.store saveQuorumSnapshot:result.snapshotAtH4C toChain:self.chain completion:^(NSError * _Nonnull error) {}]; + [self.store saveQuorumSnapshot:result.snapshotAtHC completion:^(NSError * _Nonnull error) {}]; + [self.store saveQuorumSnapshot:result.snapshotAtH2C completion:^(NSError * _Nonnull error) {}]; + [self.store saveQuorumSnapshot:result.snapshotAtH3C completion:^(NSError * _Nonnull error) {}]; + [self.store saveQuorumSnapshot:result.snapshotAtH4C completion:^(NSError * _Nonnull error) {}]; for (DSMnDiffProcessingResult *diffResult in result.mnListDiffList) { - DSLog(@"•••• -> processed qrinfo +++ %u..%u %@ .. %@", [self heightForBlockHash:diffResult.baseBlockHash], [self heightForBlockHash:diffResult.blockHash], uint256_hex(diffResult.baseBlockHash), uint256_hex(diffResult.blockHash)); + DSLog(@"[%@] •••• -> processed qrinfo +++ %u..%u %@ .. %@", self.chain.name, [self heightForBlockHash:diffResult.baseBlockHash], [self heightForBlockHash:diffResult.blockHash], uint256_hex(diffResult.baseBlockHash), uint256_hex(diffResult.blockHash)); DSMasternodeList *diffMasternodeList = diffResult.masternodeList; UInt256 diffBlockHash = diffMasternodeList.blockHash; NSData *diffBlockHashData = uint256_data(diffBlockHash); @@ -686,7 +686,7 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * } } for (DSQuorumSnapshot *snapshot in result.snapshotList) { - [self.store saveQuorumSnapshot:snapshot toChain:self.chain completion:^(NSError * _Nonnull error) {}]; + [self.store saveQuorumSnapshot:snapshot completion:^(NSError * _Nonnull error) {}]; } [self.store.activeQuorums unionOrderedSet:result.lastQuorumPerIndex]; @@ -721,7 +721,7 @@ - (void)updateStoreWithProcessingResult:(DSMasternodeList *)masternodeList resul } - (void)peer:(DSPeer *)peer relayedMasternodeDiffMessage:(NSData *)message { - DSLog(@"•••• -> received mnlistdiff: %@", uint256_hex(message.SHA256)); + DSLog(@"[%@: %@:%d] •••• -> received mnlistdiff: %@", self.chain.name, peer.host, peer.port, uint256_hex(message.SHA256)); @synchronized (self.masternodeListDiffService) { self.masternodeListDiffService.timedOutAttempt = 0; } @@ -731,7 +731,7 @@ - (void)peer:(DSPeer *)peer relayedMasternodeDiffMessage:(NSData *)message { DSBlock *lastBlock = [self lastBlockForBlockHash:blockHash fromPeer:peer]; if (!lastBlock) { [self.masternodeListDiffService issueWithMasternodeListFromPeer:peer]; - DSLog(@"Last Block missing"); + DSLog(@"[%@] Last Block missing", self.chain.name); return UINT256_ZERO; } return lastBlock.merkleRoot; @@ -739,14 +739,14 @@ - (void)peer:(DSPeer *)peer relayedMasternodeDiffMessage:(NSData *)message { [self processMasternodeDiffWith:message context:ctx completion:^(DSMnDiffProcessingResult * _Nonnull result) { UInt256 baseBlockHash = result.baseBlockHash; UInt256 blockHash = result.blockHash; - DSLog(@"•••• -> processed mnlistdiff %u..%u %@ .. %@", [self heightForBlockHash:baseBlockHash], [self heightForBlockHash:blockHash], uint256_hex(baseBlockHash), uint256_hex(blockHash)); + DSLog(@"[%@] •••• -> processed mnlistdiff %u..%u %@ .. %@", self.chain.name, [self heightForBlockHash:baseBlockHash], [self heightForBlockHash:blockHash], uint256_hex(baseBlockHash), uint256_hex(blockHash)); #if SAVE_MASTERNODE_DIFF_TO_FILE NSString *fileName = [NSString stringWithFormat:@"MNL_%@_%@__%d.dat", @([self heightForBlockHash:baseBlockHash]), @([self heightForBlockHash:blockHash]), peer.version]; - DSLog(@"•-• File %@ saved", fileName); + DSLog(@"[%@] •-• File %@ saved", self.chain.name, fileName); [message saveToFile:fileName inDirectory:NSCachesDirectory]; #endif if (result.errorStatus) { - DSLog(@"Processing status: %ul", result.errorStatus); + DSLog(@"[%@] Processing status: %ul", self.chain.name, result.errorStatus); dispatch_group_leave(self.processingGroup); return; } @@ -758,7 +758,7 @@ - (void)peer:(DSPeer *)peer relayedMasternodeDiffMessage:(NSData *)message { } - (void)peer:(DSPeer *)peer relayedQuorumRotationInfoMessage:(NSData *)message { - DSLog(@"•••• -> received qrinfo: %@", uint256_hex(message.SHA256)); + DSLog(@"[%@: %@:%d] •••• -> received qrinfo: %@", self.chain.name, peer.host, peer.port, uint256_hex(message.SHA256)); @synchronized (self.quorumRotationService) { self.quorumRotationService.timedOutAttempt = 0; } @@ -768,7 +768,7 @@ - (void)peer:(DSPeer *)peer relayedQuorumRotationInfoMessage:(NSData *)message { DSBlock *lastBlock = [self lastBlockForBlockHash:blockHash fromPeer:peer]; if (!lastBlock) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; - DSLog(@"Last Block missing"); + DSLog(@"[%@] Last Block missing", self.chain.name); return UINT256_ZERO; } return lastBlock.merkleRoot; @@ -776,23 +776,23 @@ - (void)peer:(DSPeer *)peer relayedQuorumRotationInfoMessage:(NSData *)message { DSMasternodeProcessorContext *ctx = [self createDiffMessageContext:self.chain.isTestnet isFromSnapshot:NO isDIP0024:YES peer:peer merkleRootLookup:merkleRootLookup]; [self processQRInfoWith:message context:ctx completion:^(DSQRInfoProcessingResult * _Nonnull result) { if (result.errorStatus) { - DSLog(@"•••• Processing status: %u", result.errorStatus); + DSLog(@"[%@] •••• Processing status: %u", self.chain.name, result.errorStatus); dispatch_group_leave(self.processingGroup); return; } UInt256 baseBlockHash = result.mnListDiffResultAtTip.baseBlockHash; UInt256 blockHash = result.mnListDiffResultAtTip.blockHash; - DSLog(@"•••• -> processed qrinfo tip %u..%u %@ .. %@", [self heightForBlockHash:baseBlockHash], [self heightForBlockHash:blockHash], uint256_hex(baseBlockHash), uint256_hex(blockHash)); - DSLog(@"•••• -> processed qrinfo h %u..%u %@ .. %@", [self heightForBlockHash:result.mnListDiffResultAtH.baseBlockHash], [self heightForBlockHash:result.mnListDiffResultAtH.blockHash], uint256_hex(result.mnListDiffResultAtH.baseBlockHash), uint256_hex(result.mnListDiffResultAtH.blockHash)); - DSLog(@"•••• -> processed qrinfo h-c %u..%u %@ .. %@", [self heightForBlockHash:result.mnListDiffResultAtHC.baseBlockHash], [self heightForBlockHash:result.mnListDiffResultAtHC.blockHash], uint256_hex(result.mnListDiffResultAtHC.baseBlockHash), uint256_hex(result.mnListDiffResultAtHC.blockHash)); - DSLog(@"•••• -> processed qrinfo h-2c %u..%u %@ .. %@", [self heightForBlockHash:result.mnListDiffResultAtH2C.baseBlockHash], [self heightForBlockHash:result.mnListDiffResultAtH2C.blockHash], uint256_hex(result.mnListDiffResultAtH2C.baseBlockHash), uint256_hex(result.mnListDiffResultAtH2C.blockHash)); - DSLog(@"•••• -> processed qrinfo h-3c %u..%u %@ .. %@", [self heightForBlockHash:result.mnListDiffResultAtH3C.baseBlockHash], [self heightForBlockHash:result.mnListDiffResultAtH3C.blockHash], uint256_hex(result.mnListDiffResultAtH3C.baseBlockHash), uint256_hex(result.mnListDiffResultAtH3C.blockHash)); + DSLog(@"[%@] •••• -> processed qrinfo tip %u..%u %@ .. %@", self.chain.name, [self heightForBlockHash:baseBlockHash], [self heightForBlockHash:blockHash], uint256_hex(baseBlockHash), uint256_hex(blockHash)); + DSLog(@"[%@] •••• -> processed qrinfo h %u..%u %@ .. %@", self.chain.name, [self heightForBlockHash:result.mnListDiffResultAtH.baseBlockHash], [self heightForBlockHash:result.mnListDiffResultAtH.blockHash], uint256_hex(result.mnListDiffResultAtH.baseBlockHash), uint256_hex(result.mnListDiffResultAtH.blockHash)); + DSLog(@"[%@] •••• -> processed qrinfo h-c %u..%u %@ .. %@", self.chain.name, [self heightForBlockHash:result.mnListDiffResultAtHC.baseBlockHash], [self heightForBlockHash:result.mnListDiffResultAtHC.blockHash], uint256_hex(result.mnListDiffResultAtHC.baseBlockHash), uint256_hex(result.mnListDiffResultAtHC.blockHash)); + DSLog(@"[%@] •••• -> processed qrinfo h-2c %u..%u %@ .. %@", self.chain.name, [self heightForBlockHash:result.mnListDiffResultAtH2C.baseBlockHash], [self heightForBlockHash:result.mnListDiffResultAtH2C.blockHash], uint256_hex(result.mnListDiffResultAtH2C.baseBlockHash), uint256_hex(result.mnListDiffResultAtH2C.blockHash)); + DSLog(@"[%@] •••• -> processed qrinfo h-3c %u..%u %@ .. %@", self.chain.name, [self heightForBlockHash:result.mnListDiffResultAtH3C.baseBlockHash], [self heightForBlockHash:result.mnListDiffResultAtH3C.blockHash], uint256_hex(result.mnListDiffResultAtH3C.baseBlockHash), uint256_hex(result.mnListDiffResultAtH3C.blockHash)); if (result.extraShare) { - DSLog(@"•••• -> processed qrinfo h-4c %u..%u %@ .. %@", [self heightForBlockHash:result.mnListDiffResultAtH4C.baseBlockHash], [self heightForBlockHash:result.mnListDiffResultAtH4C.blockHash], uint256_hex(result.mnListDiffResultAtH4C.baseBlockHash), uint256_hex(result.mnListDiffResultAtH4C.blockHash)); + DSLog(@"[%@] •••• -> processed qrinfo h-4c %u..%u %@ .. %@", self.chain.name, [self heightForBlockHash:result.mnListDiffResultAtH4C.baseBlockHash], [self heightForBlockHash:result.mnListDiffResultAtH4C.blockHash], uint256_hex(result.mnListDiffResultAtH4C.baseBlockHash), uint256_hex(result.mnListDiffResultAtH4C.blockHash)); } #if SAVE_MASTERNODE_DIFF_TO_FILE NSString *fileName = [NSString stringWithFormat:@"QRINFO_%@_%@__%d.dat", @([self heightForBlockHash:baseBlockHash]), @([self heightForBlockHash:blockHash]), peer.version]; - DSLog(@"•-• File %@ saved", fileName); + DSLog(@"[%@] •-• File %@ saved", self.chain.name, fileName); [message saveToFile:fileName inDirectory:NSCachesDirectory]; #endif [self processQRInfoResult:result forPeer:peer completion:^{ @@ -880,11 +880,9 @@ - (void)checkPingTimesForCurrentMasternodeListInContext:(NSManagedObjectContext - (UInt256)buildLLMQHashFor:(DSQuorumEntry *)quorum { uint32_t workHeight = [self heightForBlockHash:quorum.quorumHash] - 8; if (workHeight >= chain_core20_activation_height(self.chain.chainType)) { - DSLog(@"buildLLMQHashFor: [%u: %u] (core 20): %@", quorum.llmqType, workHeight, uint256_hex(quorum.quorumHash)); NSData *bestCLSignature = [self CLSignatureForBlockHeight:workHeight]; return [DSKeyManager NSDataFrom:quorum_build_llmq_hash_v20(quorum.llmqType, workHeight, bestCLSignature.bytes)].UInt256; } else { - DSLog(@"buildLLMQHashFor: [%u: %u] (pre core 20): %@", quorum.llmqType, workHeight, uint256_hex(quorum.quorumHash)); return [DSKeyManager NSDataFrom:quorum_build_llmq_hash(quorum.llmqType, quorum.quorumHash.u8)].UInt256; } } diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSPeerManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSPeerManager.m index 09922f025..7b54d5808 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSPeerManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSPeerManager.m @@ -320,7 +320,7 @@ - (NSMutableOrderedSet *)peers { struct addrinfo hints = {0, AF_UNSPEC, SOCK_STREAM, 0, 0, 0, NULL, NULL}, *servinfo, *p; UInt128 addr = {.u32 = {0, 0, CFSwapInt32HostToBig(0xffff), 0}}; - DSLog(@"DNS lookup %@", [dnsSeeds objectAtIndex:i]); + DSLog(@"[%@] [DSPeerManager] DNS lookup %@", self.chain.name, [dnsSeeds objectAtIndex:i]); NSString *dnsSeed = [dnsSeeds objectAtIndex:i]; if (getaddrinfo([dnsSeed UTF8String], servname.UTF8String, &hints, &servinfo) == 0) { for (p = servinfo; p != NULL; p = p->ai_next) { @@ -346,7 +346,7 @@ - (NSMutableOrderedSet *)peers { freeaddrinfo(servinfo); } else { - DSLog(@"failed getaddrinfo for %@", dnsSeeds[i]); + DSLog(@"[%@] [DSPeerManager] failed getaddrinfo for %@", self.chain.name, dnsSeeds[i]); } }); } @@ -369,7 +369,7 @@ - (NSMutableOrderedSet *)peers { uint32_t ip = ntohl(addrV4.s_addr); ipAddress.u32[3] = CFSwapInt32HostToBig(ip); } else { - DSLog(@"invalid address"); + DSLog(@"[%@] [DSPeerManager] invalid address", self.chain.name); } [_peers addObject:[[DSPeer alloc] initWithAddress:ipAddress port:port ? [port intValue] : self.chain.standardPort @@ -431,7 +431,7 @@ - (void)peerMisbehaving:(DSPeer *)peer errorMessage:(NSString *)errorMessage { } [peer disconnectWithError:[NSError errorWithCode:500 localizedDescriptionKey:errorMessage]]; - DSLog(@"peerMisbehaving -> peerManager::connect"); + DSLog(@"[%@] [DSPeerManager] peerMisbehaving -> peerManager::connect", self.chain.name); [self connect]; } } @@ -462,11 +462,11 @@ - (void)sortPeers { // for (DSPeer * peer in _peers) { // DSLog(@"%@:%d lastRequestedMasternodeList(%f) lastRequestedGovernanceSync(%f)",peer.host,peer.port,peer.lastRequestedMasternodeList, peer.lastRequestedGovernanceSync); // } - DSLog(@"peers sorted"); + DSLog(@"[%@] [DSPeerManager] peers sorted", self.chain.name); } - (void)savePeers { - DSLog(@"[DSPeerManager] save peers"); + DSLog(@"[%@] [DSPeerManager] save peers", self.chain.name); NSMutableSet *peers = [[self.peers.set setByAddingObjectsFromSet:self.misbehavingPeers] mutableCopy]; NSMutableSet *addrs = [NSMutableSet set]; @@ -566,7 +566,7 @@ - (void)resumeBlockchainSynchronizationOnPeers { if (self.downloadPeer) { [self updateFilterOnPeers]; } else { - DSLog(@"resumeBlockchainSynchronizationOnPeers -> peerManager::connect"); + DSLog(@"[%@] [DSPeerManager] resumeBlockchainSynchronizationOnPeers", self.chain.name); [self connect]; } } @@ -574,12 +574,12 @@ - (void)resumeBlockchainSynchronizationOnPeers { - (void)updateFilterOnPeers { if (self.downloadPeer.needsFilterUpdate) return; self.downloadPeer.needsFilterUpdate = YES; - DSLog(@"filter update needed, waiting for pong"); + DSLog(@"[%@] [DSPeerManager] filter update needed, waiting for pong", self.chain.name); [self.downloadPeer sendPingMessageWithPongHandler:^(BOOL success) { // wait for pong so we include already sent tx if (!success) return; //we are on chainPeerManagerQueue - DSLog(@"updating filter with newly created wallet addresses"); + DSLog(@"[%@] [DSPeerManager] updating filter with newly created wallet addresses", self.chain.name); [self.transactionManager clearTransactionsBloomFilter]; if (self.chain.lastSyncBlockHeight < self.chain.estimatedBlockHeight) { // if we're syncing, only update download peer @@ -684,7 +684,7 @@ - (void)useMasternodeList:(DSMasternodeList *)masternodeList withConnectivityNon if (peers.count > 1 && peers.count < 1000) [self savePeers]; // peer relaying is complete when we receive <1000 if (connected) { - DSLog(@"useMasternodeList -> peerManager::connect"); + DSLog(@"[%@] [DSPeerManager] useMasternodeList -> connect", self.chain.name); [self connect]; } dispatch_async(dispatch_get_main_queue(), ^{ @@ -697,7 +697,7 @@ - (void)useMasternodeList:(DSMasternodeList *)masternodeList withConnectivityNon // MARK: - Connectivity - (void)connect { - DSLog(@"[DSPeerManager] connect"); + DSLog(@"[%@] [DSPeerManager] connect", self.chain.name); self.desiredState = DSPeerManagerDesiredState_Connected; dispatch_async(self.networkingQueue, ^{ if ([self.chain syncsBlockchain] && ![self.chain canConstructAFilter]) return; // check to make sure the wallet has been created if only are a basic wallet with no dash features @@ -773,7 +773,7 @@ - (void)connect { [self.mutableConnectedPeers addObject:peer]; - DSLog(@"Will attempt to connect to peer %@", peer.host); + DSLog(@"[%@: %@:%d] [DSPeerManager] Will attempt to connect to peer", self.chain.name, peer.host, peer.port); [peer connect]; } @@ -856,7 +856,7 @@ - (void)peerConnected:(DSPeer *)peer { if (peer.timestamp > now + 2 * 60 * 60 || peer.timestamp < now - 2 * 60 * 60) peer.timestamp = now; //timestamp sanity check self.connectFailures = 0; - DSLog(@"%@:%d connected with lastblock %d (our last header %d - last block %d)", peer.host, peer.port, peer.lastBlockHeight, self.chain.lastTerminalBlockHeight, self.chain.lastSyncBlockHeight); + DSLog(@"[%@: %@:%d] [DSPeerManager] connected with lastblock %d (our last header %d - last block %d)", self.chain.name, peer.host, peer.port, peer.lastBlockHeight, self.chain.lastTerminalBlockHeight, self.chain.lastSyncBlockHeight); // drop peers that don't carry full blocks, or aren't synced yet // TODO: XXXX does this work with 0.11 pruned nodes? @@ -881,41 +881,38 @@ - (void)peerConnected:(DSPeer *)peer { } if (self.chain.estimatedBlockHeight >= peer.lastBlockHeight || self.chain.lastSyncBlockHeight >= peer.lastBlockHeight) { if (self.chain.lastSyncBlockHeight < self.chain.estimatedBlockHeight) { - DSLog(@"self.chain.lastSyncBlockHeight %u, self.chain.estimatedBlockHeight %u", self.chain.lastSyncBlockHeight, self.chain.estimatedBlockHeight); + DSLog(@"[%@: %@:%d] [DSPeerManager] lastSyncBlockHeight %u, estimatedBlockHeight %u", self.chain.name, peer.host, peer.port, self.chain.lastSyncBlockHeight, self.chain.estimatedBlockHeight); return; // don't get mempool yet if we're syncing } [peer sendPingMessageWithPongHandler:^(BOOL success) { if (!success) { - DSLog(@"[DSTransactionManager] fetching mempool ping on connection failure peer %@", peer.host); + DSLog(@"[%@: %@:%d] [DSPeerManager] fetching mempool ping on connection failure peer", self.chain.name, peer.host, peer.port); return; } - DSLog(@"[DSTransactionManager] fetching mempool ping on connection success peer %@", peer.host); + DSLog(@"[%@: %@:%d] [DSPeerManager] fetching mempool ping on connection success peer", self.chain.name, peer.host, peer.port); [peer sendMempoolMessage:self.transactionManager.publishedTx.allKeys completion:^(BOOL success, BOOL needed, BOOL interruptedByDisconnect) { - if (!success) { - if (!needed) { - DSLog(@"[DSTransactionManager] fetching mempool message on connection not needed (already happening) peer %@", peer.host); - } else if (interruptedByDisconnect) { - DSLog(@"[DSTransactionManager] fetching mempool message on connection failure peer %@", peer.host); - } else { - DSLog(@"[DSTransactionManager] fetching mempool message on connection failure disconnect peer %@", peer.host); - } - return; - } - DSLog(@"[DSTransactionManager] fetching mempool message on connection success peer %@", peer.host); - peer.synced = YES; - [self.transactionManager removeUnrelayedTransactionsFromPeer:peer]; - if (!self.masternodeList) { - [peer sendGetaddrMessage]; // request a list of other dash peers - } - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:DSTransactionManagerTransactionStatusDidChangeNotification - object:nil - userInfo:@{DSChainManagerNotificationChainKey: self.chain}]; - }); - }]; + if (!success) { + if (!needed) { + DSLog(@"[%@: %@:%d] [DSPeerManager] fetching mempool message on connection not needed (already happening) peer", self.chain.name, peer.host, peer.port); + } else if (interruptedByDisconnect) { + DSLog(@"[%@: %@:%d] [DSPeerManager] fetching mempool message on connection failure peer", self.chain.name, peer.host, peer.port); + } else { + DSLog(@"[%@: %@:%d] [DSPeerManager] fetching mempool message on connection failure disconnect peer", self.chain.name, peer.host, peer.port); + } + return; + } + DSLog(@"[%@: %@:%d] [DSPeerManager] fetching mempool message on connection success peer", self.chain.name, peer.host, peer.port); + peer.synced = YES; + [self.transactionManager removeUnrelayedTransactionsFromPeer:peer]; + if (!self.masternodeList) { + [peer sendGetaddrMessage]; // request a list of other dash peers + } + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:DSTransactionManagerTransactionStatusDidChangeNotification object:nil userInfo:@{DSChainManagerNotificationChainKey: self.chain}]; + }); + }]; }]; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:DSPeerManagerConnectedPeersDidChangeNotification @@ -983,7 +980,7 @@ - (void)peerConnected:(DSPeer *)peer { } - (void)peer:(DSPeer *)peer disconnectedWithError:(NSError *)error { - DSLog(@"%@:%d disconnected%@%@", peer.host, peer.port, (error ? @", " : @""), (error ? error : @"")); + DSLog(@"[%@: %@:%d] [DSPeerManager] disconnected %@%@", self.chain.name, peer.host, peer.port, (error ? @", " : @""), (error ? error : @"")); BOOL banned = NO; if ([error.domain isEqual:@"DashSync"]) { //} && error.code != DASH_PEER_TIMEOUT_CODE) { [self peerMisbehaving:peer errorMessage:error.localizedDescription]; // if it's protocol error other than timeout, the peer isn't following the rules @@ -1015,7 +1012,7 @@ - (void)peer:(DSPeer *)peer disconnectedWithError:(NSError *)error { [self.managedObjectContext deleteObject:obj]; } }]; - DSLog(@"[DSPeerManager] disconnectedWithError: max connect failures exceeded"); + DSLog(@"[%@: %@:%d] [DSPeerManager] disconnectedWithError: max connect failures exceeded", self.chain.name, peer.host, peer.port); @synchronized(self) { _peers = nil; } @@ -1029,7 +1026,7 @@ - (void)peer:(DSPeer *)peer disconnectedWithError:(NSError *)error { #if TARGET_OS_IOS if ((self.desiredState == DSPeerManagerDesiredState_Connected) && (self.terminalHeadersSaveTaskId != UIBackgroundTaskInvalid || [UIApplication sharedApplication].applicationState != UIApplicationStateBackground)) { - DSLog(@"peer disconnectedWithError -> peerManager::connect"); + DSLog(@"[%@: %@:%d] [DSPeerManager] peer disconnectedWithError -> peerManager::connect", self.chain.name, peer.host, peer.port); if (!banned) [self connect]; // try connecting to another peer } #else @@ -1052,7 +1049,7 @@ - (void)peer:(DSPeer *)peer disconnectedWithError:(NSError *)error { - (void)peer:(DSPeer *)peer relayedPeers:(NSArray *)peers { if (self.masternodeList) return; - DSLog(@"%@:%d relayed %d peer(s)", peer.host, peer.port, (int)peers.count); + DSLog(@"[%@: %@:%d] [DSPeerManager] relayed %d peer(s)", self.chain.name, peer.host, peer.port, (int)peers.count); [self.peers addObjectsFromArray:peers]; [self.peers minusSet:self.misbehavingPeers]; [self sortPeers]; diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSSporkManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSSporkManager.m index 5689e075f..bba224268 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSSporkManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSSporkManager.m @@ -175,7 +175,7 @@ - (void)peer:(DSPeer *_Nonnull)peer hasSporkHashes:(NSSet *_Nonnull)sporkHashes - (void)peer:(DSPeer *)peer relayedSpork:(NSData *)message { DSSpork *spork = [DSSpork sporkWithMessage:message onChain:self.chain]; - DSLog(@"received spork %u (%@) with message %@", spork.identifier, spork.identifierString, message.hexString); + DSLog(@"[%@: %@:%d] received spork %u (%@) with message %@", self.chain.name, peer.host, peer.port, spork.identifier, spork.identifierString, message.hexString); if (!spork.isValid) { [self.peerManager peerMisbehaving:peer errorMessage:@"Spork is not valid"]; return; @@ -214,7 +214,7 @@ - (void)peer:(DSPeer *)peer relayedSpork:(NSData *)message { [sporkEntity setAttributesFromSpork:spork withSporkHash:hashEntity]; // add new peers [self.managedObjectContext ds_save]; } else { - DSLog(@"Spork was received that wasn't requested"); + DSLog(@"[%@: %@:%d] Spork was received that wasn't requested", self.chain.name, peer.host, peer.port); } } }]; diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m index dd5271b23..2943c83fe 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSTransactionManager.m @@ -159,9 +159,9 @@ - (UIViewController *)presentingViewController { - (void)addUnconfirmedTransactionToPublishList:(DSTransaction *)transaction { if (transaction.blockHeight == TX_UNCONFIRMED) { #if DEBUG - DSLogPrivate(@"[DSTransactionManager] add transaction to publish list %@ (%@)", transaction, transaction.toData); + DSLogPrivate(@"[%@] [DSTransactionManager] add transaction to publish list %@ (%@)", self.chain.name, transaction, transaction.toData); #else - DSLog(@"[DSTransactionManager] add transaction to publish list"); + DSLog(@"[%@] [DSTransactionManager] add transaction to publish list", self.chain.name); #endif if (!self.publishedTx[uint256_obj(transaction.txHash)]) { self.publishedTx[uint256_obj(transaction.txHash)] = transaction; @@ -178,9 +178,9 @@ - (void)addUnconfirmedTransactionToPublishList:(DSTransaction *)transaction { - (void)publishTransaction:(DSTransaction *)transaction completion:(void (^)(NSError * _Nullable error))completion { #if DEBUG - DSLogPrivate(@"[DSTransactionManager] publish transaction %@ %@", transaction, transaction.toData); + DSLogPrivate(@"[%@] [DSTransactionManager] publish transaction %@ %@", self.chain.name, transaction, transaction.toData); #else - DSLog(@"[DSTransactionManager] publish transaction"); + DSLog(@"[%@] [DSTransactionManager] publish transaction", self.chain.name); #endif if ([transaction transactionTypeRequiresInputs] && !transaction.isSigned) { if (completion) { @@ -251,15 +251,15 @@ - (void)removeUnrelayedTransactionsFromPeer:(DSPeer *)peer { [self.removeUnrelayedTransactionsLocalRequests addObject:peer.location]; // don't remove transactions until we're connected to maxConnectCount peers if (self.removeUnrelayedTransactionsLocalRequests.count < 2) { - DSLog(@"[DSTransactionManager] not removing unrelayed transactions until we have synced mempools from 2 peers %lu", (unsigned long)self.peerManager.connectedPeerCount); + DSLog(@"[%@] [DSTransactionManager] not removing unrelayed transactions until we have synced mempools from 2 peers %lu", self.chain.name, (unsigned long)self.peerManager.connectedPeerCount); return; } - for (DSPeer *p in self.peerManager.connectedPeers) { // don't remove tx until all peers have finished relaying their mempools - DSLog(@"[DSTransactionManager] not removing unrelayed transactions because %@ is not synced yet", p.host); + for (DSPeer *p in self.peerManager.connectedPeers) { // don't remove tx until sendMempoolMessage + DSLog(@"[%@: %@:%d] [DSTransactionManager] not removing unrelayed transactions because peer is not synced yet", self.chain.name, p.host, p.port); if (!p.synced) return; } - DSLog(@"[DSTransactionManager] removing unrelayed transactions"); + DSLog(@"[%@] [DSTransactionManager] removing unrelayed transactions", self.chain.name); NSMutableSet *transactionsSet = [NSMutableSet set]; NSMutableSet *specialTransactionsSet = [NSMutableSet set]; @@ -279,9 +279,9 @@ - (void)removeUnrelayedTransactionsFromPeer:(DSPeer *)peer { for (DSTransaction *transaction in transactionsSet) { if (transaction.blockHeight != TX_UNCONFIRMED) continue; hash = uint256_obj(transaction.txHash); - DSLog(@"checking published callback -> %@", self.publishedCallback[hash] ? @"OK" : @"no callback"); + DSLog(@"[%@] checking published callback -> %@", self.chain.name, self.publishedCallback[hash] ? @"OK" : @"no callback"); if (self.publishedCallback[hash] != NULL) continue; - DSLog(@"transaction relays count %lu, transaction requests count %lu", (unsigned long)[self.txRelays[hash] count], (unsigned long)[self.txRequests[hash] count]); + DSLog(@"[%@] transaction relays count %lu, transaction requests count %lu", self.chain.name, (unsigned long)[self.txRelays[hash] count], (unsigned long)[self.txRequests[hash] count]); DSAccount *account = [self.chain firstAccountThatCanContainTransaction:transaction]; if (!account && ![specialTransactionsSet containsObject:transaction]) { //the following might be needed, it was in evopayments branch @@ -295,9 +295,9 @@ - (void)removeUnrelayedTransactionsFromPeer:(DSPeer *)peer { // if this is for a transaction we sent, and it wasn't already known to be invalid, notify user of failure if (!rescan && account && [account amountSentByTransaction:transaction] > 0 && [account transactionIsValid:transaction]) { #if DEBUG - DSLogPrivate(@"failed transaction %@", transaction); + DSLogPrivate(@"[%@] failed transaction %@", self.chain.name, transaction); #else - DSLog(@"failed transaction "); + DSLog(@"[%@] failed transaction ", self.chain.name); #endif rescan = notify = YES; @@ -308,30 +308,30 @@ - (void)removeUnrelayedTransactionsFromPeer:(DSPeer *)peer { } } else if (!account) { #if DEBUG - DSLogPrivate(@"serious issue in masternode transaction %@", transaction); + DSLogPrivate(@"[%@] serious issue in masternode transaction %@", self.chain.name, transaction); #else - DSLog(@"serious issue in masternode transaction "); + DSLog(@"[%@] serious issue in masternode transaction ", self.chain.name); #endif } else { #if DEBUG - DSLogPrivate(@"serious issue in transaction %@", transaction); + DSLogPrivate(@"[%@] serious issue in transaction %@", self.chain.name, transaction); #else - DSLog(@"serious issue in transaction "); + DSLog(@"[%@] serious issue in transaction ", self.chain.name); #endif } #if DEBUG - DSLogPrivate(@"removing transaction %@", transaction); + DSLogPrivate(@"[%@] removing transaction %@", self.chain.name, transaction); #else - DSLog(@"removing transaction "); + DSLog(@"[%@] removing transaction ", self.chain.name); #endif [transactionsToBeRemoved addObject:transaction]; } else if ([self.txRelays[hash] count] < self.peerManager.maxConnectCount) { // set timestamp 0 to mark as unverified #if DEBUG - DSLogPrivate(@"setting transaction as unverified %@", transaction); + DSLogPrivate(@"[%@] setting transaction as unverified %@", self.chain.name, transaction); #else - DSLog(@"setting transaction as unverified "); + DSLog(@"[%@] setting transaction as unverified ", self.chain.name); #endif [self.chain setBlockHeight:TX_UNCONFIRMED andTimestamp:0 @@ -738,9 +738,9 @@ - (void)publishSignedTransaction:(DSTransaction *)tx createdFromProtocolRequest: onChain:account.wallet.chain]; #if DEBUG - DSLogPrivate(@"posting payment to: %@", protocolRequest.details.paymentURL); + DSLogPrivate(@"[%@] posting payment to: %@", self.chain.name, protocolRequest.details.paymentURL); #else - DSLog(@"posting payment to: "); + DSLog(@"[%@] posting payment to: ", self.chain.name); #endif [DSPaymentRequest postPayment:payment @@ -878,57 +878,48 @@ - (void)confirmPaymentRequest:(DSPaymentRequest *)paymentRequest usingUserBlockc // MARK: - Mempools Sync - (void)fetchMempoolFromPeer:(DSPeer *)peer { - DSLog(@"[DSTransactionManager] fetching mempool from peer %@", peer.host); + DSLog(@"[%@: %@:%d] [DSTransactionManager] fetching mempool from peer", self.chain.name, peer.host, peer.port); if (peer.status != DSPeerStatus_Connected) return; if ([self.chain canConstructAFilter] && (peer != self.peerManager.downloadPeer || self.transactionsBloomFilterFalsePositiveRate > BLOOM_REDUCED_FALSEPOSITIVE_RATE * 5.0)) { - DSLog(@"[DSTransactionManager] sending filterload message from peer %@", peer.host); + DSLog(@"[%@: %@:%d] [DSTransactionManager] sending filterload message from peer", self.chain.name, peer.host, peer.port); [peer sendFilterloadMessage:[self transactionsBloomFilterForPeer:peer].data]; } [peer sendInvMessageForHashes:self.publishedTx.allKeys ofType:DSInvType_Tx]; // publish pending tx [peer sendPingMessageWithPongHandler:^(BOOL success) { if (success) { - DSLog(@"[DSTransactionManager] fetching mempool ping success peer %@", peer.host); + DSLog(@"[%@: %@:%d] [DSTransactionManager] fetching mempool ping success peer", self.chain.name, peer.host, peer.port); [peer sendMempoolMessage:self.publishedTx.allKeys completion:^(BOOL success, BOOL needed, BOOL interruptedByDisconnect) { - if (success) { - DSLog(@"[DSTransactionManager] fetching mempool message success peer %@", peer.host); - peer.synced = YES; - [self removeUnrelayedTransactionsFromPeer:peer]; - if (!self.chainManager.peerManager.masternodeList) { - [peer sendGetaddrMessage]; // request a list of other dash peers - } - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] - postNotificationName:DSTransactionManagerTransactionStatusDidChangeNotification - object:nil - userInfo:@{DSChainManagerNotificationChainKey: self.chain}]; - }); - } else { - if (!needed) { - DSLog(@"[DSTransactionManager] fetching mempool message not needed peer %@", peer.host); - } else if (interruptedByDisconnect) { - DSLog(@"[DSTransactionManager] fetching mempool message failure by disconnect peer %@", peer.host); - } else { - DSLog(@"[DSTransactionManager] fetching mempool message failure peer %@", peer.host); - } - } - - if (peer == self.peerManager.downloadPeer) { - [self.peerManager chainSyncStopped]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] - postNotificationName:DSChainManagerSyncFinishedNotification - object:nil - userInfo:@{DSChainManagerNotificationChainKey: self.chain}]; - }); - } - }]; + if (success) { + DSLog(@"[%@: %@:%d] [DSTransactionManager] fetching mempool message success peer", self.chain.name, peer.host, peer.port); + peer.synced = YES; + [self removeUnrelayedTransactionsFromPeer:peer]; + if (!self.chainManager.peerManager.masternodeList) { + [peer sendGetaddrMessage]; // request a list of other dash peers + } + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:DSTransactionManagerTransactionStatusDidChangeNotification object:nil userInfo:@{DSChainManagerNotificationChainKey: self.chain}]; + }); + } else { + if (!needed) { + DSLog(@"[%@: %@:%d] [DSTransactionManager] fetching mempool message not needed peer", self.chain.name, peer.host, peer.port); + } else if (interruptedByDisconnect) { + DSLog(@"[%@: %@:%d] [DSTransactionManager] fetching mempool message failure by disconnect peer", self.chain.name, peer.host, peer.port); + } else { + DSLog(@"[%@: %@:%d] [DSTransactionManager] fetching mempool message failure peer", self.chain.name, peer.host, peer.port); + } + } + if (peer == self.peerManager.downloadPeer) { + [self.peerManager chainSyncStopped]; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:DSChainManagerSyncFinishedNotification object:nil userInfo:@{DSChainManagerNotificationChainKey: self.chain}]; + }); + } + }]; } else if (peer == self.peerManager.downloadPeer) { - DSLog(@"[DSTransactionManager] fetching mempool ping failure on download peer %@", peer.host); + DSLog(@"[%@: %@:%d] [DSTransactionManager] fetching mempool ping failure on download peer", self.chain.name, peer.host, peer.port); [self.peerManager chainSyncStopped]; dispatch_async(dispatch_get_main_queue(), ^{ @@ -938,7 +929,7 @@ - (void)fetchMempoolFromPeer:(DSPeer *)peer { userInfo:@{DSChainManagerNotificationChainKey: self.chain}]; }); } else { - DSLog(@"[DSTransactionManager] fetching mempool ping failure on peer %@", peer.host); + DSLog(@"[%@: %@:%d] [DSTransactionManager] fetching mempool ping failure on peer", self.chain.name, peer.host, peer.port); } }]; } @@ -1065,9 +1056,9 @@ - (void)chainWasWiped:(DSChain *)chain { - (DSTransaction *)peer:(DSPeer *)peer requestedTransaction:(UInt256)txHash { NSValue *hash = uint256_obj(txHash); #if DEBUG - DSLogPrivate(@"Peer requested transaction with hash %@", hash); + DSLogPrivate(@"[%@: %@:%d] Peer requested transaction with hash %@", self.chain.name, peer.host, peer.port, hash); #else - DSLog(@"Peer requested transaction with hash "); + DSLog(@"[%@: %@:%d] Peer requested transaction with hash ", self.chain.name, peer.host, peer.port); #endif DSTransaction *transaction = self.publishedTx[hash]; BOOL transactionIsPublished = !!transaction; @@ -1084,9 +1075,9 @@ - (DSTransaction *)peer:(DSPeer *)peer requestedTransaction:(UInt256)txHash { } if (![accounts count]) { #if DEBUG - DSLogPrivate(@"No transaction could be found on any account for hash %@", hash); + DSLogPrivate(@"[%@: %@:%d] No transaction could be found on any account for hash %@", self.chain.name, peer.host, peer.port, hash); #else - DSLog(@"No transaction could be found on any account for hash "); + DSLog(@"[%@: %@:%d] No transaction could be found on any account for hash ", self.chain.name, peer.host, peer.port); #endif return nil; } @@ -1154,18 +1145,18 @@ - (void)peer:(DSPeer *)peer hasTransactionWithHash:(UInt256)txHash { void (^callback)(NSError *error) = self.publishedCallback[hash]; #if DEBUG - DSLogPrivate(@"%@:%d has transaction %@", peer.host, peer.port, hash); + DSLogPrivate(@"[%@: %@:%d] has transaction %@", self.chain.name, peer.host, peer.port, hash); #else - DSLog(@"%@:%d has transaction %@", peer.host, peer.port, @""); + DSLog(@"[%@: %@:%d] has transaction %@", self.chain.name, peer.host, peer.port, @""); #endif if (!transaction) transaction = [self.chain transactionForHash:txHash]; if (!transaction) { - DSLog(@"No transaction found on chain for this transaction"); + DSLog(@"[%@: %@:%d] No transaction found on chain for this transaction", self.chain.name, peer.host, peer.port); return; } DSAccount *account = [self.chain firstAccountThatCanContainTransaction:transaction]; if (syncing && !account) { - DSLog(@"No account found for this transaction"); + DSLog(@"[%@: %@:%d] No account found for this transaction", self.chain.name, peer.host, peer.port); return; } if (![account registerTransaction:transaction saveImmediately:YES]) return; @@ -1205,15 +1196,15 @@ - (void)peer:(DSPeer *)peer relayedTransaction:(DSTransaction *)transaction inBl if (peer) { #if DEBUG - DSLogPrivate(@"%@:%d relayed transaction %@", peer.host, peer.port, hash); + DSLogPrivate(@"[%@: %@:%d] relayed transaction %@", self.chain.name, peer.host, peer.port, hash); #else - DSLog(@"%@:%d relayed transaction %@", peer.host, peer.port, @""); + DSLog(@"[%@: %@:%d] relayed transaction %@", self.chain.name, peer.host, peer.port, @""); #endif } else { #if DEBUG - DSLogPrivate(@"accepting local transaction %@", hash); + DSLogPrivate(@"[%@: %@:%d] accepting local transaction %@", self.chain.name, peer.host, peer.port, hash); #else - DSLog(@"accepting local transaction %@", @""); + DSLog(@"[%@: %@:%d] accepting local transaction %@", self.chain.name, peer.host, peer.port, @""); #endif } @@ -1226,30 +1217,30 @@ - (void)peer:(DSPeer *)peer relayedTransaction:(DSTransaction *)transaction inBl if (![self.chain transactionHasLocalReferences:transaction]) { if (peer) { #if DEBUG - DSLogPrivate(@"%@:%d no account or local references for transaction %@", peer.host, peer.port, hash); + DSLogPrivate(@"[%@: %@:%d] no account or local references for transaction %@", self.chain.name, peer.host, peer.port, hash); #else - DSLog(@"%@:%d no account or local references for transaction %@", peer.host, peer.port, @""); + DSLog(@"[%@: %@:%d] no account or local references for transaction %@", self.chain.name, peer.host, peer.port, @""); #endif } else { #if DEBUG - DSLogPrivate(@"no account or local references for transaction %@", hash); + DSLogPrivate(@"[%@: %@:%d] no account or local references for transaction %@", self.chain.name, peer.host, peer.port, hash); #else - DSLog(@"no account or local references for transaction %@", @""); + DSLog(@"[%@: %@:%d] no account or local references for transaction %@", self.chain.name, peer.host, peer.port, @""); #endif } return; } else { if (peer) { #if DEBUG - DSLogPrivate(@"%@:%d no account for transaction with local references %@", peer.host, peer.port, hash); + DSLogPrivate(@"[%@: %@:%d] no account for transaction with local references %@", self.chain.name, peer.host, peer.port, hash); #else - DSLog(@"%@:%d no account for transaction with local references %@", peer.host, peer.port, @""); + DSLog(@"[%@: %@:%d] no account for transaction with local references %@", self.chain.name, peer.host, peer.port, @""); #endif } else { #if DEBUG - DSLogPrivate(@"no account for transaction with local references %@", hash); + DSLogPrivate(@"[%@: %@:%d] no account for transaction with local references %@", self.chain.name, peer.host, peer.port, hash); #else - DSLog(@"no account for transaction with local references %@", @""); + DSLog(@"[%@: %@:%d] no account for transaction with local references %@", self.chain.name, peer.host, peer.port, @""); #endif } } @@ -1266,15 +1257,15 @@ - (void)peer:(DSPeer *)peer relayedTransaction:(DSTransaction *)transaction inBl } else { if (peer) { #if DEBUG - DSLogPrivate(@"%@:%d could not register transaction %@", peer.host, peer.port, hash); + DSLogPrivate(@"[%@: %@:%d] could not register transaction %@", self.chain.name, peer.host, peer.port, hash); #else - DSLog(@"%@:%d could not register transaction %@", peer.host, peer.port, @""); + DSLog(@"[%@: %@:%d] could not register transaction %@", self.chain.name, peer.host, peer.port, @""); #endif } else { #if DEBUG - DSLogPrivate(@"could not register transaction %@", hash); + DSLogPrivate(@"[%@: %@:%d] could not register transaction %@", self.chain.name, peer.host, peer.port, hash); #else - DSLog(@"could not register transaction %@", @""); + DSLog(@"[%@: %@:%d] could not register transaction %@", self.chain.name, peer.host, peer.port, @""); #endif } } @@ -1521,9 +1512,9 @@ - (void)peer:(DSPeer *)peer relayedInstantSendTransactionLock:(DSInstantSendTran BOOL verified = [instantSendTransactionLock verifySignature]; #if DEBUG - DSLogPrivate(@"%@:%d relayed instant send transaction lock %@ %@", peer.host, peer.port, verified ? @"Verified" : @"Not Verified", uint256_reverse_hex(instantSendTransactionLock.transactionHash)); + DSLogPrivate(@"[%@: %@:%d] relayed instant send transaction lock %@ %@", self.chain.name, peer.host, peer.port, verified ? @"Verified" : @"Not Verified", uint256_reverse_hex(instantSendTransactionLock.transactionHash)); #else - DSLog(@"%@:%d relayed instant send transaction lock %@ %@", peer.host, peer.port, verified ? @"Verified" : @"Not Verified", @""); + DSLog(@"[%@: %@:%d] relayed instant send transaction lock %@ %@", self.chain.name, peer.host, peer.port, verified ? @"Verified" : @"Not Verified", @""); #endif @@ -1548,13 +1539,13 @@ - (void)peer:(DSPeer *)peer relayedInstantSendTransactionLock:(DSInstantSendTran } - (void)checkInstantSendLocksWaitingForQuorums { - DSLog(@"Checking InstantSendLocks Waiting For Quorums"); + DSLog(@"[%@] Checking InstantSendLocks Waiting For Quorums", self.chain.name); for (NSData *transactionHashData in [self.instantSendLocksWaitingForQuorums copy]) { if (self.instantSendLocksWaitingForTransactions[transactionHashData]) continue; DSInstantSendTransactionLock *instantSendTransactionLock = self.instantSendLocksWaitingForQuorums[transactionHashData]; BOOL verified = [instantSendTransactionLock verifySignature]; if (verified) { - DSLogPrivate(@"Verified %@", instantSendTransactionLock); + DSLogPrivate(@"[%@] Verified %@", self.chain.name, instantSendTransactionLock); [instantSendTransactionLock saveSignatureValid]; DSTransaction *transaction = nil; DSWallet *wallet = nil; @@ -1589,10 +1580,10 @@ - (void)checkInstantSendLocksWaitingForQuorums { if (quorum && masternodeList) { NSArray *quorumEntries = [masternodeList quorumEntriesRankedForInstantSendRequestID:[instantSendTransactionLock requestID]]; NSUInteger index = [quorumEntries indexOfObject:quorum]; - DSLog(@"Quorum %@ found at index %lu for masternodeList at height %lu", quorum, (unsigned long)index, (unsigned long)masternodeList.height); - DSLog(@"Quorum entries are %@", quorumEntries); + DSLog(@"[%@] Quorum %@ found at index %lu for masternodeList at height %lu", self.chain.name, quorum, (unsigned long)index, (unsigned long)masternodeList.height); + DSLog(@"[%@] Quorum entries are %@", self.chain.name, quorumEntries); } - DSLog(@"Could not verify %@", instantSendTransactionLock); + DSLog(@"[%@] Could not verify %@", self.chain.name, instantSendTransactionLock); #endif } } @@ -1607,7 +1598,7 @@ - (void)peer:(DSPeer *)peer relayedHeader:(DSMerkleBlock *)block { if (!self.chain.needsInitialTerminalHeadersSync && (self.chain.earliestWalletCreationTime < block.timestamp + DAY_TIME_INTERVAL * 2) && !self.chainManager.chainSynchronizationFingerprint) { - DSLog(@"ignoring header %@", uint256_hex(block.blockHash)); + DSLog(@"[%@: %@:%d] ignoring header %@", self.chain.name, peer.host, peer.port, uint256_hex(block.blockHash)); return; } @@ -1618,14 +1609,14 @@ - (void)peer:(DSPeer *)peer relayedHeader:(DSMerkleBlock *)block { - (void)peer:(DSPeer *)peer relayedBlock:(DSMerkleBlock *)block { if (!self.chainManager.syncPhase) { - DSLog(@"Block was received after reset, ignoring it"); + DSLog(@"[%@: %@:%d] Block was received after reset, ignoring it", self.chain.name, peer.host, peer.port); return; } //DSLog(@"relayed block %@ total transactions %d %u",uint256_hex(block.blockHash), block.totalTransactions,block.timestamp); // ignore block headers that are newer than 2 days before earliestKeyTime (headers have 0 totalTransactions) if (block.totalTransactions == 0 && block.timestamp + DAY_TIME_INTERVAL * 2 > self.chain.earliestWalletCreationTime) { - DSLog(@"ignoring block %@", uint256_hex(block.blockHash)); + DSLog(@"[%@: %@:%d] ignoring block %@", self.chain.name, peer.host, peer.port, uint256_hex(block.blockHash)); return; } @@ -1642,11 +1633,11 @@ - (void)peer:(DSPeer *)peer relayedBlock:(DSMerkleBlock *)block { // false positive rate sanity check if (self.peerManager.downloadPeer.status == DSPeerStatus_Connected && self.transactionsBloomFilterFalsePositiveRate > BLOOM_DEFAULT_FALSEPOSITIVE_RATE * 10.0) { - DSLog(@"%@:%d bloom filter false positive rate %f too high after %d blocks, disconnecting...", peer.host, + DSLog(@"[%@: %@:%d] bloom filter false positive rate %f too high after %d blocks, disconnecting...", self.chain.name, peer.host, peer.port, self.transactionsBloomFilterFalsePositiveRate, self.chain.lastSyncBlockHeight + 1 - self.filterUpdateHeight); [self.peerManager.downloadPeer disconnect]; } else if (self.chain.lastSyncBlockHeight + 500 < peer.lastBlockHeight && self.transactionsBloomFilterFalsePositiveRate > BLOOM_REDUCED_FALSEPOSITIVE_RATE * 10.0) { - DSLog(@"%@:%d bloom filter false positive rate %f too high after %d blocks, rebuilding", peer.host, + DSLog(@"[%@: %@:%d] bloom filter false positive rate %f too high after %d blocks, rebuilding", self.chain.name, peer.host, peer.port, self.transactionsBloomFilterFalsePositiveRate, self.chain.lastSyncBlockHeight + 1 - self.filterUpdateHeight); [self updateTransactionsBloomFilter]; // rebuild bloom filter when it starts to degrade } @@ -1655,7 +1646,7 @@ - (void)peer:(DSPeer *)peer relayedBlock:(DSMerkleBlock *)block { if (peer == self.peerManager.downloadPeer) [self.chainManager relayedNewItem]; if (!_bloomFilter) { // ignore potentially incomplete blocks when a filter update is pending - DSLog(@"ignoring block due to filter update %@", uint256_hex(block.blockHash)); + DSLog(@"[%@: %@:%d] ignoring block due to filter update %@", self.chain.name, peer.host, peer.port, uint256_hex(block.blockHash)); return; } @@ -1693,7 +1684,7 @@ - (void)peer:(DSPeer *)peer relayedBlock:(DSMerkleBlock *)block { [self.totalTransactionData appendUInt16:(block.height - 499) / 500]; [self.totalTransactionData appendUInt16:self.totalTransactionsSum / self.totalTransactionsQueue.count]; [self.totalTransactionData appendUInt16:self.totalTransactionsMax]; - DSLog(@"%d;%lu;%u", block.height - 499, self.totalTransactionsSum / self.totalTransactionsQueue.count, self.totalTransactionsMax); + DSLog(@"[%@: %@:%d] max total tx %d;%lu;%u", self.chain.name, peer.host, peer.port, block.height - 499, self.totalTransactionsSum / self.totalTransactionsQueue.count, self.totalTransactionsMax); } if (block.height == self.chain.lastTerminalBlockHeight) { NSString *fileName = [NSString stringWithFormat:@"MaxTransactionInfo_%@.dat", self.chain.name]; @@ -1711,7 +1702,7 @@ - (void)peer:(DSPeer *)peer relayedTooManyOrphanBlocks:(NSUInteger)orphanBlockCo - (void)peer:(DSPeer *)peer relayedChainLock:(DSChainLock *)chainLock { BOOL verified = [chainLock verifySignature]; - DSLog(@"%@:%d relayed chain lock %@", peer.host, peer.port, uint256_reverse_hex(chainLock.blockHash)); + DSLog(@"[%@: %@:%d] relayed chain lock %@", self.chain.name, peer.host, peer.port, uint256_reverse_hex(chainLock.blockHash)); DSMerkleBlock *block = [self.chain blockForBlockHash:chainLock.blockHash]; @@ -1733,13 +1724,13 @@ - (void)peer:(DSPeer *)peer relayedChainLock:(DSChainLock *)chainLock { } - (void)checkChainLocksWaitingForQuorums { - DSLog(@"Checking ChainLocks Waiting For Quorums"); + DSLog(@"[%@] Checking ChainLocks Waiting For Quorums", self.chain.name); for (NSData *chainLockHashData in [self.chainLocksWaitingForQuorums copy]) { if (self.chainLocksWaitingForMerkleBlocks[chainLockHashData]) continue; DSChainLock *chainLock = self.chainLocksWaitingForQuorums[chainLockHashData]; BOOL verified = [chainLock verifySignature]; if (verified) { - DSLog(@"Verified %@", chainLock); + DSLog(@"[%@] Verified %@", self.chain.name, chainLock); [chainLock saveSignatureValid]; DSMerkleBlock *block = [self.chain blockForBlockHash:chainLock.blockHash]; [self.chainLocksWaitingForQuorums removeObjectForKey:chainLockHashData]; @@ -1753,10 +1744,10 @@ - (void)checkChainLocksWaitingForQuorums { if (quorum && masternodeList) { NSArray *quorumEntries = [masternodeList quorumEntriesRankedForInstantSendRequestID:[chainLock requestID]]; NSUInteger index = [quorumEntries indexOfObject:quorum]; - DSLog(@"Quorum %@ found at index %lu for masternodeList at height %lu", quorum, (unsigned long)index, (unsigned long)masternodeList.height); - DSLog(@"Quorum entries are %@", quorumEntries); + DSLog(@"[%@] Quorum %@ found at index %lu for masternodeList at height %lu", self.chain.name, quorum, (unsigned long)index, (unsigned long)masternodeList.height); + DSLog(@"[%@] Quorum entries are %@", self.chain.name, quorumEntries); } - DSLog(@"Could not verify %@", chainLock); + DSLog(@"[%@] Could not verify %@", self.chain.name, chainLock); #endif } } @@ -1774,7 +1765,7 @@ - (void)peer:(DSPeer *)peer setFeePerByte:(uint64_t)feePerKb { if (secondFeePerByte * 2 > MIN_FEE_PER_B && secondFeePerByte * 2 <= MAX_FEE_PER_B && secondFeePerByte * 2 > self.chain.feePerByte) { - DSLog(@"increasing feePerKb to %llu based on feefilter messages from peers", secondFeePerByte * 2); + DSLog(@"[%@] increasing feePerKb to %llu based on feefilter messages from peers", self.chain.name, secondFeePerByte * 2); self.chain.feePerByte = secondFeePerByte * 2; } } diff --git a/DashSync/shared/Models/Managers/Service Managers/Auth/DSAuthenticationManager.m b/DashSync/shared/Models/Managers/Service Managers/Auth/DSAuthenticationManager.m index 34d94e80d..4fd1e78a5 100644 --- a/DashSync/shared/Models/Managers/Service Managers/Auth/DSAuthenticationManager.m +++ b/DashSync/shared/Models/Managers/Service Managers/Auth/DSAuthenticationManager.m @@ -203,7 +203,7 @@ - (NSString *)promptForAmount:(uint64_t)amount if (!isSecure && errorMessage.length > 0) prompt = [prompt stringByAppendingString:REDX @" "]; if (name.length > 0) prompt = [prompt stringByAppendingString:sanitizeString(name)]; if (!isSecure && prompt.length > 0) prompt = [prompt stringByAppendingString:@"\n"]; - if (!isSecure || prompt.length == 0) prompt = [prompt stringByAppendingString:address]; + if (!isSecure || prompt.length == 0) prompt = [prompt stringByAppendingString:address ? address : @""]; if (memo.length > 0) prompt = [prompt stringByAppendingFormat:@"\n\n%@", sanitizeString(memo)]; prompt = [prompt stringByAppendingFormat:DSLocalizedString(@"\n\n amount %@ (%@)", nil), [manager stringForDashAmount:amount - fee], [manager localCurrencyStringForDashAmount:amount - fee]]; diff --git a/DashSync/shared/Models/Masternode/DSLocalMasternode.m b/DashSync/shared/Models/Masternode/DSLocalMasternode.m index 067909eda..695931daa 100644 --- a/DashSync/shared/Models/Masternode/DSLocalMasternode.m +++ b/DashSync/shared/Models/Masternode/DSLocalMasternode.m @@ -149,7 +149,6 @@ - (instancetype)initWithProviderTransactionRegistration:(DSProviderRegistrationT DSWallet *operatorWallet = [providerRegistrationTransaction.chain walletHavingProviderOperatorAuthenticationKey:providerRegistrationTransaction.operatorKey foundAtIndex:&operatorAddressIndex]; DSWallet *holdingWallet = [providerRegistrationTransaction.chain walletContainingMasternodeHoldingAddressForProviderRegistrationTransaction:providerRegistrationTransaction foundAtIndex:&holdingAddressIndex]; DSWallet *platformNodeWallet = [providerRegistrationTransaction.chain walletHavingPlatformNodeAuthenticationHash:providerRegistrationTransaction.platformNodeID foundAtIndex:&platformNodeAddressIndex]; - //DSLogPrivate(@"%@",[uint160_data(providerRegistrationTransaction.ownerKeyHash) addressFromHash160DataForChain:providerRegistrationTransaction.chain]); self.operatorKeysWallet = operatorWallet; self.holdingKeysWallet = holdingWallet; self.ownerKeysWallet = ownerWallet; diff --git a/DashSync/shared/Models/Masternode/DSMasternodeListDiffService.m b/DashSync/shared/Models/Masternode/DSMasternodeListDiffService.m index 6157bb373..8bb336468 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeListDiffService.m +++ b/DashSync/shared/Models/Masternode/DSMasternodeListDiffService.m @@ -48,7 +48,7 @@ - (void)composeMasternodeListRequest:(NSOrderedSet *)list { [self requestMasternodeListDiff:previousBlockHash forBlockHash:blockHash]; } } else { - DSLog(@"Missing block (%@)", blockHashData.hexString); + DSLog(@"[%@] Missing block (%@)", self.chain.name, blockHashData.hexString); [self removeFromRetrievalQueue:blockHashData]; } } @@ -58,10 +58,10 @@ - (void)requestMasternodeListDiff:(UInt256)previousBlockHash forBlockHash:(UInt2 DSGetMNListDiffRequest *request = [DSGetMNListDiffRequest requestWithBaseBlockHash:previousBlockHash blockHash:blockHash]; DSMasternodeListRequest *matchedRequest = [self requestInRetrievalFor:previousBlockHash blockHash:blockHash]; if (matchedRequest) { - NSLog(@"•••• mnlistdiff request with such a range already in retrieval: %u..%u %@ .. %@", [self.store heightForBlockHash:previousBlockHash], [self.store heightForBlockHash:blockHash], uint256_hex(previousBlockHash), uint256_hex(blockHash)); + DSLog(@"[%@] •••• mnlistdiff request with such a range already in retrieval: %u..%u %@ .. %@", self.chain.name, [self.store heightForBlockHash:previousBlockHash], [self.store heightForBlockHash:blockHash], uint256_hex(previousBlockHash), uint256_hex(blockHash)); return; } - NSLog(@"•••• requestMasternodeListDiff: %u..%u %@ .. %@", [self.store heightForBlockHash:previousBlockHash], [self.store heightForBlockHash:blockHash], uint256_hex(previousBlockHash), uint256_hex(blockHash)); + DSLog(@"[%@] •••• requestMasternodeListDiff: %u..%u %@ .. %@", self.chain.name, [self.store heightForBlockHash:previousBlockHash], [self.store heightForBlockHash:blockHash], uint256_hex(previousBlockHash), uint256_hex(blockHash)); [self sendMasternodeListRequest:request]; } diff --git a/DashSync/shared/Models/Masternode/DSMasternodeListService.m b/DashSync/shared/Models/Masternode/DSMasternodeListService.m index 38d78b3dc..70dfa6cd2 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeListService.m +++ b/DashSync/shared/Models/Masternode/DSMasternodeListService.m @@ -78,7 +78,7 @@ - (void)startTimeOutObserver { NSMutableSet *leftToGet = [requestsInRetrieval mutableCopy]; [leftToGet intersectSet:requestsInRetrieval2]; if ((masternodeListCount == [self.store knownMasternodeListsCount]) && [requestsInRetrieval isEqualToSet:leftToGet]) { - DSLog(@"TimedOut"); + DSLog(@"[%@] TimedOut", self.chain.name); self.timedOutAttempt++; [self disconnectFromDownloadPeer]; [self cleanRequestsInRetrieval]; @@ -120,7 +120,7 @@ - (void)getRecentMasternodeList { DSMerkleBlock *merkleBlock = [self.chain blockFromChainTip:0]; if (!merkleBlock) { // sometimes it happens while rescan - DSLog(@"getRecentMasternodeList: (no block exist) for tip: "); + DSLog(@"[%@] getRecentMasternodeList: (no block exist) for tip", self.chain.name); return; } UInt256 merkleBlockHash = merkleBlock.blockHash; @@ -129,7 +129,7 @@ - (void)getRecentMasternodeList { return; } if ([self.store addBlockToValidationQueue:merkleBlock]) { - DSLog(@"MasternodeListService.Getting masternode list %u", merkleBlock.height); + DSLog(@"[%@] MasternodeListService.Getting masternode list %u", self.chain.name, merkleBlock.height); NSData *merkleBlockHashData = uint256_data(merkleBlockHash); BOOL emptyRequestQueue = ![self retrievalQueueCount]; [self addToRetrievalQueue:merkleBlockHashData]; @@ -207,7 +207,7 @@ - (BOOL)shouldProcessDiffResult:(DSMnDiffProcessingResult *)diffResult skipPrese } BOOL isValid = [diffResult isTotallyValid]; if (!isValid) { - DSLog(@"••• Invalid result: %@", diffResult.debugDescription); + DSLog(@"[%@] ••• Invalid result: %@", self.chain.name, diffResult.debugDescription); } return isValid; @@ -243,7 +243,7 @@ - (void)removeFromRetrievalQueue:(NSData *)masternodeBlockHashData { } - (void)cleanRequestsInRetrieval { - NSLog(@"•••• cleanRequestsInRetrieval: %@", self); + DSLog(@"[%@] •••• cleanRequestsInRetrieval: %@", self.chain.name, self); [self.requestsInRetrieval removeAllObjects]; } @@ -277,12 +277,12 @@ - (void)updateMasternodeRetrievalQueue { - (void)fetchMasternodeListsToRetrieve:(void (^)(NSOrderedSet *listsToRetrieve))completion { if (![self retrievalQueueCount]) { - DSLog(@"No masternode lists in retrieval: %@", self); + DSLog(@"[%@] No masternode lists in retrieval: %@", self.chain.name, self); [self.delegate masternodeListSerivceEmptiedRetrievalQueue:self]; return; } if ([self.requestsInRetrieval count]) { - DSLog(@"A masternode list is already in retrieval: %@", self); + DSLog(@"[%@] A masternode list is already in retrieval: %@", self.chain.name, self); return; } BOOL peerIsDisconnected; @@ -325,7 +325,7 @@ - (BOOL)removeRequestInRetrievalForBaseBlockHash:(UInt256)baseBlockHash blockHas return [self.store heightForBlockHash:blockHash]; }]]; } - DSLog(@"•••• A masternode list (%@ .. %@) was received that is not set to be retrieved (%@)", uint256_hex(baseBlockHash), uint256_hex(blockHash), [requestsInRetrievalStrings componentsJoinedByString:@", "]); + DSLog(@"[%@] •••• A masternode list (%@ .. %@) was received that is not set to be retrieved (%@)", self.chain.name, uint256_hex(baseBlockHash), uint256_hex(blockHash), [requestsInRetrievalStrings componentsJoinedByString:@", "]); #endif /* DEBUG */ return NO; } @@ -347,7 +347,7 @@ - (void)issueWithMasternodeListFromPeer:(DSPeer *)peer { [self.peerManager peerMisbehaving:peer errorMessage:@"Issue with Deterministic Masternode list"]; NSArray *faultyPeers = [[NSUserDefaults standardUserDefaults] arrayForKey:CHAIN_FAULTY_DML_MASTERNODE_PEERS]; if (faultyPeers.count >= MAX_FAULTY_DML_PEERS) { - DSLog(@"Exceeded max failures for masternode list, starting from scratch"); + DSLog(@"[%@] Exceeded max failures for masternode list, starting from scratch", self.chain.name); //no need to remove local masternodes [self cleanListsRetrievalQueue]; [self.store deleteAllOnChain]; diff --git a/DashSync/shared/Models/Masternode/DSMasternodeListStore.h b/DashSync/shared/Models/Masternode/DSMasternodeListStore.h index 939f15720..50092f0c8 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeListStore.h +++ b/DashSync/shared/Models/Masternode/DSMasternodeListStore.h @@ -68,7 +68,6 @@ FOUNDATION_EXPORT NSString *const DSQuorumListDidChangeNotification; modifiedMasternodes:(NSDictionary *)modifiedMasternodes completion:(void (^)(NSError *error))completion; - (void)saveQuorumSnapshot:(DSQuorumSnapshot *)quorumSnapshot - toChain:(DSChain *)chain completion:(void (^)(NSError *error))completion; + (void)saveMasternodeList:(DSMasternodeList *)masternodeList toChain:(DSChain *)chain havingModifiedMasternodes:(NSDictionary *)modifiedMasternodes createUnknownBlocks:(BOOL)createUnknownBlocks inContext:(NSManagedObjectContext *)context completion:(void (^)(NSError *error))completion; diff --git a/DashSync/shared/Models/Masternode/DSMasternodeListStore.m b/DashSync/shared/Models/Masternode/DSMasternodeListStore.m index 148bfa85a..92f68184e 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeListStore.m +++ b/DashSync/shared/Models/Masternode/DSMasternodeListStore.m @@ -154,7 +154,7 @@ - (UInt256)closestKnownBlockHashForBlockHash:(UInt256)blockHash { } - (void)deleteAllOnChain { - DSLog(@"DSMasternodeListStore.deleteAllOnChain"); + DSLog(@"[%@] DSMasternodeListStore.deleteAllOnChain", self.chain.name); [self.managedObjectContext performBlockAndWait:^{ DSChainEntity *chainEntity = [self.chain chainEntityInContext:self.managedObjectContext]; [DSSimplifiedMasternodeEntryEntity deleteAllOnChainEntity:chainEntity]; @@ -171,7 +171,7 @@ - (void)deleteEmptyMasternodeLists { [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"block.chain == %@ && masternodes.@count == 0", [self.chain chainEntityInContext:self.managedObjectContext]]]; NSArray *masternodeListEntities = [DSMasternodeListEntity fetchObjects:fetchRequest inContext:self.managedObjectContext]; for (DSMasternodeListEntity *entity in [masternodeListEntities copy]) { - DSLog(@"DSMasternodeListStore.deleteEmptyMasternodeLists: %@", entity); + DSLog(@"[%@] DSMasternodeListStore.deleteEmptyMasternodeLists: %@", self.chain.name, entity); [self.managedObjectContext deleteObject:entity]; } [self.managedObjectContext ds_save]; @@ -255,14 +255,14 @@ - (DSMasternodeList *)loadMasternodeListAtBlockHash:(NSData *)blockHash withBloc NSMutableDictionary *quorumEntryPool = [NSMutableDictionary dictionary]; masternodeList = [masternodeListEntity masternodeListWithSimplifiedMasternodeEntryPool:[simplifiedMasternodeEntryPool copy] quorumEntryPool:quorumEntryPool withBlockHeightLookup:blockHeightLookup]; if (masternodeList) { - DSLog(@"••• addMasternodeList (loadMasternodeListAtBlockHash) -> %@: %@", blockHash.hexString, masternodeList); + DSLog(@"[%@] ••• addMasternodeList (loadMasternodeListAtBlockHash) -> %@: %@", self.chain.name, blockHash.hexString, masternodeList); @synchronized (self.masternodeListsByBlockHash) { [self.masternodeListsByBlockHash setObject:masternodeList forKey:blockHash]; } @synchronized (self.masternodeListsByBlockHash) { [self.masternodeListsBlockHashStubs removeObject:blockHash]; } - DSLog(@"Loading Masternode List at height %u for blockHash %@ with %lu entries", masternodeList.height, uint256_hex(masternodeList.blockHash), (unsigned long)masternodeList.simplifiedMasternodeEntries.count); + DSLog(@"[%@] Loading Masternode List at height %u for blockHash %@ with %lu entries", self.chain.name, masternodeList.height, uint256_hex(masternodeList.blockHash), (unsigned long)masternodeList.simplifiedMasternodeEntries.count); } }]; dispatch_group_leave(self.savingGroup); @@ -288,7 +288,7 @@ - (DSMasternodeList *)loadMasternodeListsWithBlockHeightLookup:(BlockHeightFinde [self.cachedBlockHashHeights setObject:@(masternodeListEntity.block.height) forKey:uint256_data(masternodeList.blockHash)]; [simplifiedMasternodeEntryPool addEntriesFromDictionary:masternodeList.simplifiedMasternodeListDictionaryByReversedRegistrationTransactionHash]; [quorumEntryPool addEntriesFromDictionary:masternodeList.quorums]; - DSLog(@"Loading Masternode List at height %u for blockHash %@ with %lu entries", masternodeList.height, uint256_hex(masternodeList.blockHash), (unsigned long)masternodeList.simplifiedMasternodeEntries.count); + DSLog(@"[%@] Loading Masternode List at height %u for blockHash %@ with %lu entries", self.chain.name, masternodeList.height, uint256_hex(masternodeList.blockHash), (unsigned long)masternodeList.simplifiedMasternodeEntries.count); if (i == masternodeListEntities.count - 1) { currentList = masternodeList; } @@ -339,7 +339,7 @@ - (DSMasternodeList *)masternodeListForBlockHash:(UInt256)blockHash withBlockHei } - (void)removeAllMasternodeLists { - DSLog(@"••• removeAllMasternodeLists -> "); + DSLog(@"[%@] ••• removeAllMasternodeLists -> ", self.chain.name); @synchronized (self.masternodeListsByBlockHash) { [self.masternodeListsByBlockHash removeAllObjects]; } @@ -358,8 +358,8 @@ - (void)removeOldMasternodeLists:(uint32_t)lastBlockHeight { NSArray *masternodeListEntities = [DSMasternodeListEntity objectsInContext:self.managedObjectContext matching:@"block.height < %@ && block.blockHash IN %@ && (block.usedByQuorums.@count == 0)", @(lastBlockHeight - 50), masternodeListBlockHashes]; BOOL removedItems = !!masternodeListEntities.count; for (DSMasternodeListEntity *masternodeListEntity in [masternodeListEntities copy]) { - DSLog(@"Removing masternodeList at height %u", masternodeListEntity.block.height); - DSLog(@"quorums are %@", masternodeListEntity.block.usedByQuorums); + DSLog(@"[%@] Removing masternodeList at height %u", self.chain.name, masternodeListEntity.block.height); + DSLog(@"[%@] quorums are %@", self.chain.name, masternodeListEntity.block.usedByQuorums); //A quorum is on a block that can only have one masternode list. //A block can have one quorum of each type. //A quorum references the masternode list by it's block @@ -399,7 +399,7 @@ - (void)removeOldSimplifiedMasternodeEntries { BOOL deletedSomething = FALSE; NSUInteger deletionCount = 0; for (DSSimplifiedMasternodeEntryEntity *simplifiedMasternodeEntryEntity in [simplifiedMasternodeEntryEntities copy]) { - DSLog(@"removeOldSimplifiedMasternodeEntries: %@", simplifiedMasternodeEntryEntity.providerRegistrationTransactionHash.hexString); + DSLog(@"[%@] removeOldSimplifiedMasternodeEntries: %@", self.chain.name, simplifiedMasternodeEntryEntity.providerRegistrationTransactionHash.hexString); [self.managedObjectContext deleteObject:simplifiedMasternodeEntryEntity]; deletedSomething = TRUE; deletionCount++; @@ -456,14 +456,13 @@ - (void)saveMasternodeList:(DSMasternodeList *)masternodeList addedMasternodes:( self.masternodeListCurrentlyBeingSavedCount--; dispatch_group_leave(self.savingGroup); if (error) { - DSLog(@"Finished saving MNL at height %u with error: %@", [self heightForBlockHash:masternodeList.blockHash], error.description); + DSLog(@"[%@] Finished saving MNL at height %u with error: %@", self.chain.name, [self heightForBlockHash:masternodeList.blockHash], error.description); } completion(error); }]; } - (void)saveQuorumSnapshot:(DSQuorumSnapshot *)quorumSnapshot - toChain:(DSChain *)chain completion:(void (^)(NSError *error))completion { if (!quorumSnapshot) { return; @@ -474,17 +473,17 @@ - (void)saveQuorumSnapshot:(DSQuorumSnapshot *)quorumSnapshot if ([self.cachedQuorumSnapshots objectForKey:blockHashData]) { return; } - DSLog(@"Queued saving Quorum Snapshot for: %u: %@", blockHeight, uint256_hex(blockHash)); + DSLog(@"[%@] Queued saving Quorum Snapshot for: %u: %@", self.chain.name, blockHeight, uint256_hex(blockHash)); [self.cachedQuorumSnapshots setObject:quorumSnapshot forKey:blockHashData]; dispatch_group_enter(self.savingGroup); NSManagedObjectContext *context = self.managedObjectContext; [context performBlockAndWait:^{ @autoreleasepool { - BOOL createUnknownBlocks = chain.allowInsightBlocksForVerification; - DSChainEntity *chainEntity = [chain chainEntityInContext:context]; + BOOL createUnknownBlocks = self.chain.allowInsightBlocksForVerification; + DSChainEntity *chainEntity = [self.chain chainEntityInContext:context]; DSMerkleBlockEntity *merkleBlockEntity = [DSMerkleBlockEntity merkleBlockEntityForBlockHash:blockHash inContext:context]; if (!merkleBlockEntity) { - merkleBlockEntity = [DSMerkleBlockEntity merkleBlockEntityForBlockHashFromCheckpoint:blockHash chain:chain inContext:context]; + merkleBlockEntity = [DSMerkleBlockEntity merkleBlockEntityForBlockHashFromCheckpoint:blockHash chain:self.chain inContext:context]; } //NSAssert(!merkleBlockEntity || !merkleBlockEntity.quorumSnapshot, @"Merkle block should not have a quorum snapshot already"); NSError *error = nil; @@ -492,11 +491,11 @@ - (void)saveQuorumSnapshot:(DSQuorumSnapshot *)quorumSnapshot if (createUnknownBlocks) { merkleBlockEntity = [DSMerkleBlockEntity createMerkleBlockEntityForBlockHash:blockHash blockHeight:blockHeight chainEntity:chainEntity inContext:context]; } else { - DSLog(@"Merkle block should exist for block hash %@", blockHashData.hexString); + DSLog(@"[%@] Merkle block should exist for block hash %@", self.chain.name, blockHashData.hexString); error = [NSError errorWithCode:600 localizedDescriptionKey:@"Merkle block should exist"]; } } else if (merkleBlockEntity.quorumSnapshot) { - DSLog(@"Merkle block already have quorum snapshot for %@", blockHashData.hexString); + DSLog(@"[%@] Merkle block already have quorum snapshot for %@", self.chain.name, blockHashData.hexString); error = [NSError errorWithCode:600 localizedDescriptionKey:@"Merkle block should not have a quorum snapshot already"]; // DGaF // skip we're just processing saved snapshot //[merkleBlockEntity.quorumSnapshot updateAttributesFromPotentialQuorumSnapshot:quorumSnapshot onBlock:merkleBlockEntity] @@ -506,7 +505,7 @@ - (void)saveQuorumSnapshot:(DSQuorumSnapshot *)quorumSnapshot } else { DSQuorumSnapshotEntity *quorumSnapshotEntity = [DSQuorumSnapshotEntity managedObjectInBlockedContext:context]; [quorumSnapshotEntity updateAttributesFromPotentialQuorumSnapshot:quorumSnapshot onBlock:merkleBlockEntity]; - DSLog(@"Finished saving Quorum Snapshot at height %u: %@", blockHeight, uint256_hex(blockHash)); + DSLog(@"[%@] Finished saving Quorum Snapshot at height %u: %@", self.chain.name, blockHeight, uint256_hex(blockHash)); } error = [context ds_save]; if (completion) { @@ -523,7 +522,7 @@ + (void)saveMasternodeList:(DSMasternodeList *)masternodeList createUnknownBlocks:(BOOL)createUnknownBlocks inContext:(NSManagedObjectContext *)context completion:(void (^)(NSError *error))completion { - DSLog(@"Queued saving MNL at height %u: %@", masternodeList.height, uint256_hex(masternodeList.blockHash)); + DSLog(@"[%@] Queued saving MNL at height %u: %@", chain.name, masternodeList.height, uint256_hex(masternodeList.blockHash)); [context performBlockAndWait:^{ //masternodes @autoreleasepool { @@ -542,7 +541,7 @@ + (void)saveMasternodeList:(DSMasternodeList *)masternodeList if (createUnknownBlocks) { merkleBlockEntity = [DSMerkleBlockEntity createMerkleBlockEntityForBlockHash:mnlBlockHash blockHeight:mnlHeight chainEntity:chainEntity inContext:context]; } else { - DSLog(@"Merkle block should exist for block hash %@", mnlBlockHashData); + DSLog(@"[%@] Merkle block should exist for block hash %@", chain.name, mnlBlockHashData); error = [NSError errorWithCode:600 localizedDescriptionKey:@"Merkle block should exist"]; } } else if (merkleBlockEntity.masternodeList) { @@ -606,7 +605,7 @@ + (void)saveMasternodeList:(DSMasternodeList *)masternodeList } } chainEntity.baseBlockHash = mnlBlockHashData; - DSLog(@"Finished merging MNL at height %u: %@", mnlHeight, mnlBlockHashData.hexString); + DSLog(@"[%@] Finished merging MNL at height %u: %@", chain.name, mnlHeight, mnlBlockHashData.hexString); } else if (!error) { DSMasternodeListEntity *masternodeListEntity = [DSMasternodeListEntity managedObjectInBlockedContext:context]; @@ -665,7 +664,7 @@ + (void)saveMasternodeList:(DSMasternodeList *)masternodeList } } chainEntity.baseBlockHash = mnlBlockHashData; - DSLog(@"Finished saving MNL at height %u", mnlHeight); + DSLog(@"[%@] Finished saving MNL at height %u", chain.name, mnlHeight); } else { chainEntity.baseBlockHash = uint256_data(chain.genesisHash); [DSLocalMasternodeEntity deleteAllOnChainEntity:chainEntity]; @@ -702,11 +701,11 @@ - (DSQuorumEntry *)quorumEntryForPlatformHavingQuorumHash:(UInt256)quorumHash fo masternodeList = [self masternodeListBeforeBlockHash:block.blockHash]; } if (!masternodeList) { - DSLog(@"No masternode list found yet"); + DSLog(@"[%@] No masternode list found yet", self.chain.name); return nil; } if (block.height - masternodeList.height > 32) { - DSLog(@"Masternode list is too old"); + DSLog(@"[%@] Masternode list is too old", self.chain.name); return nil; } DSQuorumEntry *quorumEntry = [masternodeList quorumEntryForPlatformWithQuorumHash:quorumHash]; @@ -730,11 +729,11 @@ - (DSQuorumEntry *)quorumEntryForLockRequestID:(UInt256)requestID } DSMasternodeList *masternodeList = [self masternodeListBeforeBlockHash:blockHash]; if (!masternodeList) { - DSLog(@"No masternode list found yet"); + DSLog(@"[%@] No masternode list found yet", self.chain.name); return nil; } if (merkleBlock.height - masternodeList.height > offset) { - DSLog(@"Masternode list for is too old (age: %d masternodeList height %d merkle block height %d)", + DSLog(@"[%@] Masternode list for is too old (age: %d masternodeList height %d merkle block height %d)", self.chain.name, merkleBlock.height - masternodeList.height, masternodeList.height, merkleBlock.height); return nil; } @@ -761,7 +760,7 @@ - (BOOL)addBlockToValidationQueue:(DSMerkleBlock *)merkleBlock { //DSLog(@"addBlockToValidationQueue: %u:%@", merkleBlock.height, uint256_hex(merkleBlockHash)); NSData *merkleBlockHashData = uint256_data(merkleBlockHash); if ([self hasMasternodeListAt:merkleBlockHashData]) { - DSLog(@"Already have that masternode list (or in stub) %u", merkleBlock.height); + DSLog(@"[%@] Already have that masternode list (or in stub) %u", self.chain.name, merkleBlock.height); return NO; } self.lastQueriedBlockHash = merkleBlockHash; diff --git a/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.m b/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.m index 7e3ddd912..60b2d443e 100644 --- a/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.m +++ b/DashSync/shared/Models/Masternode/DSMnDiffProcessingResult.m @@ -31,7 +31,7 @@ + (instancetype)processingResultWith:(MNListDiffResult *)result onChain:(DSChain return processingResult; } if (result->masternode_list == NULL) { - NSLog(@"DSQRInfoProcessingResult.error.unknown"); + DSLog(@"[%@] DSQRInfoProcessingResult.error.unknown", chain.name); processingResult.errorStatus = ProcessingError_ParseError; return processingResult; } diff --git a/DashSync/shared/Models/Masternode/DSQRInfoProcessingResult.m b/DashSync/shared/Models/Masternode/DSQRInfoProcessingResult.m index d71aa59e6..b96d5d120 100644 --- a/DashSync/shared/Models/Masternode/DSQRInfoProcessingResult.m +++ b/DashSync/shared/Models/Masternode/DSQRInfoProcessingResult.m @@ -24,11 +24,11 @@ + (instancetype)processingResultWith:(QRInfoResult *)result onChain:(DSChain *)c uint8_t errorStatus = result->error_status; processingResult.errorStatus = errorStatus; if (errorStatus > 0) { - NSLog(@"DSQRInfoProcessingResult.error %ul", errorStatus); + DSLog(@"[%@] DSQRInfoProcessingResult.error %ul", chain.name, errorStatus); return processingResult; } if (result->result_at_tip == NULL) { - NSLog(@"DSQRInfoProcessingResult.error.unknown"); + DSLog(@"[%@] DSQRInfoProcessingResult.error.unknown", chain.name); processingResult.errorStatus = ProcessingError_ParseError; return processingResult; } diff --git a/DashSync/shared/Models/Masternode/DSQuorumEntry.m b/DashSync/shared/Models/Masternode/DSQuorumEntry.m index f47957964..903df11e7 100644 --- a/DashSync/shared/Models/Masternode/DSQuorumEntry.m +++ b/DashSync/shared/Models/Masternode/DSQuorumEntry.m @@ -192,7 +192,7 @@ - (BOOL)validateWithMasternodeList:(DSMasternodeList *)masternodeList { blockHeightLookup:^uint32_t(UInt256 blockHash) { DSMerkleBlock *block = [self.chain blockForBlockHash:blockHash]; if (!block) { - DSLog(@"Unknown block %@", uint256_reverse_hex(blockHash)); + DSLog(@"[%@] Unknown block %@", self.chain.name, uint256_reverse_hex(blockHash)); NSAssert(block, @"block should be known"); } return block.height; @@ -201,7 +201,7 @@ - (BOOL)validateWithMasternodeList:(DSMasternodeList *)masternodeList { - (BOOL)validateWithMasternodeList:(DSMasternodeList *)masternodeList blockHeightLookup:(BlockHeightFinder)blockHeightLookup { if (!masternodeList) { - DSLog(@"Trying to validate a quorum without a masternode list"); + DSLog(@"[%@] Trying to validate a quorum without a masternode list", self.chain.name); return NO; } MasternodeList *list = [masternodeList ffi_malloc]; diff --git a/DashSync/shared/Models/Masternode/DSQuorumRotationService.m b/DashSync/shared/Models/Masternode/DSQuorumRotationService.m index cf0196604..dcfb6a254 100644 --- a/DashSync/shared/Models/Masternode/DSQuorumRotationService.m +++ b/DashSync/shared/Models/Masternode/DSQuorumRotationService.m @@ -37,7 +37,7 @@ - (void)composeMasternodeListRequest:(NSOrderedSet *)list { NSAssert(([self.store heightForBlockHash:previousBlockHash] != UINT32_MAX) || uint256_is_zero(previousBlockHash), @"This block height should be known"); [self requestQuorumRotationInfo:previousBlockHash forBlockHash:blockHash]; } else { - DSLog(@"Missing block (%@)", blockHashData.hexString); + DSLog(@"[%@] Missing block (%@)", self.chain.name, blockHashData.hexString); [self removeFromRetrievalQueue:blockHashData]; } /* @@ -72,7 +72,7 @@ - (void)getRecentMasternodeList { DSMerkleBlock *merkleBlock = [self.chain blockFromChainTip:0]; if (!merkleBlock) { // sometimes it happens while rescan - DSLog(@"getRecentMasternodeList: (no block exist) for tip"); + DSLog(@"[%@] getRecentMasternodeList: (no block exist) for tip", self.chain.name); return; } UInt256 merkleBlockHash = merkleBlock.blockHash; @@ -87,7 +87,7 @@ - (void)getRecentMasternodeList { BOOL needUpdate = !self.masternodeListAtH || [self.masternodeListAtH hasUnverifiedRotatedQuorums] || (lastHeight % updateInterval == rotationOffset && lastHeight >= [self.store heightForBlockHash:self.masternodeListAtH.blockHash] + rotationOffset); if (needUpdate && [self.store addBlockToValidationQueue:merkleBlock]) { - DSLog(@"QuorumRotationService.Getting masternode list %u", merkleBlock.height); + DSLog(@"[%@] QuorumRotationService.Getting masternode list %u", self.chain.name, merkleBlock.height); NSData *merkleBlockHashData = uint256_data(merkleBlockHash); BOOL emptyRequestQueue = ![self retrievalQueueCount]; [self addToRetrievalQueue:merkleBlockHashData]; @@ -103,12 +103,12 @@ - (void)requestQuorumRotationInfo:(UInt256)previousBlockHash forBlockHash:(UInt2 // blockHeight % dkgInterval == activeSigningQuorumsCount + 11 + 8 DSMasternodeListRequest *matchedRequest = [self requestInRetrievalFor:previousBlockHash blockHash:blockHash]; if (matchedRequest) { - DSLog(@"•••• qrinfo request with such a range already in retrieval: %@ .. %@", uint256_hex(previousBlockHash), uint256_hex(blockHash)); + DSLog(@"[%@] •••• qrinfo request with such a range already in retrieval: %@ .. %@", self.chain.name, uint256_hex(previousBlockHash), uint256_hex(blockHash)); return; } NSArray *baseBlockHashes = @[[NSData dataWithUInt256:previousBlockHash]]; DSGetQRInfoRequest *request = [DSGetQRInfoRequest requestWithBaseBlockHashes:baseBlockHashes blockHash:blockHash extraShare:YES]; - DSLog(@"•••• requestQuorumRotationInfo: %@ .. %@", uint256_hex(previousBlockHash), uint256_hex(blockHash)); + DSLog(@"[%@] •••• requestQuorumRotationInfo: %@ .. %@", self.chain.name, uint256_hex(previousBlockHash), uint256_hex(blockHash)); [self sendMasternodeListRequest:request]; } diff --git a/DashSync/shared/Models/Masternode/DSSimplifiedMasternodeEntry.m b/DashSync/shared/Models/Masternode/DSSimplifiedMasternodeEntry.m index 24426bc62..201bc2bde 100644 --- a/DashSync/shared/Models/Masternode/DSSimplifiedMasternodeEntry.m +++ b/DashSync/shared/Models/Masternode/DSSimplifiedMasternodeEntry.m @@ -195,7 +195,7 @@ - (UInt256)simplifiedMasternodeEntryHashAtBlockHeight:(uint32_t)blockHeight { uint32_t distance = prevHeight - blockHeight; if (distance < minDistance) { minDistance = distance; - NSLog(@"SME Hash for proTxHash %@ : Using %@ instead of %@ for list at block height %u", uint256_hex(self.providerRegistrationTransactionHash), uint256_hex(*(UInt256 *)(blockInfo.u8)), uint256_hex(usedSimplifiedMasternodeEntryHash), blockHeight); + DSLog(@"[%@] SME Hash for proTxHash %@ : Using %@ instead of %@ for list at block height %u", self.chain.name, uint256_hex(self.providerRegistrationTransactionHash), uint256_hex(*(UInt256 *)(blockInfo.u8)), uint256_hex(usedSimplifiedMasternodeEntryHash), blockHeight); usedSimplifiedMasternodeEntryHash = previousSimplifiedMasternodeEntryHashes[previousBlock].UInt256; } } diff --git a/DashSync/shared/Models/Network/DSPeer.m b/DashSync/shared/Models/Network/DSPeer.m index bf64ecdfb..6458092f5 100644 --- a/DashSync/shared/Models/Network/DSPeer.m +++ b/DashSync/shared/Models/Network/DSPeer.m @@ -223,7 +223,7 @@ - (void)connect { if (!self.reachability) self.reachability = [DSReachabilityManager sharedManager]; if (self.reachability.networkReachabilityStatus == DSReachabilityStatusNotReachable) { // delay connect until network is reachable - DSLog(@"%@:%u not reachable, waiting...", self.host, self.port); + DSLog(@"[%@: %@:%d] not reachable, waiting...", self.chain.name, self.host, self.port); dispatch_async(dispatch_get_main_queue(), ^{ if (!self.reachabilityObserver) { self.reachabilityObserver = @@ -282,7 +282,7 @@ - (void)connect { CFReadStreamRef readStream = NULL; CFWriteStreamRef writeStream = NULL; - DSLog(@"%@:%u connecting", self.host, self.port); + DSLog(@"[%@: %@:%d] connecting", self.chain.name, self.host, self.port); CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)self.host, self.port, &readStream, &writeStream); self.inputStream = CFBridgingRelease(readStream); self.outputStream = CFBridgingRelease(writeStream); @@ -311,9 +311,9 @@ - (void)disconnectWithError:(NSError *)error { if (_status == DSPeerStatus_Disconnected) return; if (!error) { - DSLog(@"Disconnected from peer %@ (%@ protocol %d) with no error", self.host, self.useragent, self.version); + DSLog(@"[%@: %@:%d] Disconnected from peer (%@ protocol %d) with no error", self.chain.name, self.host, self.port, self.useragent, self.version); } else { - DSLog(@"Disconnected from peer %@ (%@ protocol %d) with error %@", self.host, self.useragent, self.version, error); + DSLog(@"[%@: %@:%d] Disconnected from peer (%@ protocol %d) with error %@", self.chain.name, self.host, self.port, self.useragent, self.version, error); } [NSObject cancelPreviousPerformRequestsWithTarget:self]; // cancel connect timeout @@ -353,7 +353,7 @@ - (void)error:(NSString *)message, ... NS_FORMAT_FUNCTION(1, 2) { - (void)didConnect { if (self.status != DSPeerStatus_Connecting || !self.sentVerack || !self.gotVerack) return; - DSLog(@"%@:%u handshake completed %@", self.host, self.port, (self.peerDelegate.downloadPeer == self) ? @"(download peer)" : @""); + DSLog(@"[%@: %@:%d] handshake completed %@", self.chain.name, self.host, self.port, (self.peerDelegate.downloadPeer == self) ? @"(download peer)" : @""); [NSObject cancelPreviousPerformRequestsWithTarget:self]; // cancel pending handshake timeout _status = DSPeerStatus_Connected; @@ -380,7 +380,7 @@ - (void)sendRequest:(DSMessageRequest *)request { - (void)sendMessage:(NSData *)message type:(NSString *)type { if (message.length > MAX_MSG_LENGTH) { - DSLog(@"%@:%u failed to send %@, length %u is too long", self.host, self.port, type, (int)message.length); + DSLog(@"[%@: %@:%d] failed to send %@, length %u is too long", self.chain.name, self.host, self.port, type, (int)message.length); #if DEBUG abort(); #endif @@ -390,22 +390,22 @@ - (void)sendMessage:(NSData *)message type:(NSString *)type { CFRunLoopPerformBlock([self.runLoop getCFRunLoop], kCFRunLoopCommonModes, ^{ #if MESSAGE_LOGGING if (![type isEqualToString:MSG_GETDATA] && ![type isEqualToString:MSG_VERSION] && ![type isEqualToString:MSG_GETBLOCKS]) { //we log this somewhere else for better accuracy of what data is being got - DSLog(@"%@:%u %@sending %@", self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", type); + DSLog(@"[%@: %@:%d] %@sending %@", self.chain.name, self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", type); #if MESSAGE_IN_DEPTH_TX_LOGGING if ([type isEqualToString:@"ix"] || [type isEqualToString:@"tx"]) { DSTransaction *transactionBeingSent = [DSTransaction transactionWithMessage:message onChain:self.chain]; #if DEBUG - DSLogPrivate(@"%@:%u transaction %@", self.host, self.port, transactionBeingSent.longDescription); + DSLogPrivate(@"[%@: %@:%d] transaction %@", self.chain.name, self.host, self.port, transactionBeingSent.longDescription); #else - DSLog(@"%@:%u transaction %@", self.host, self.port, @""); + DSLog(@"[%@: %@:%d] transaction %@", self.chain.name, self.host, self.port, @""); #endif } #endif #if MESSAGE_CONTENT_LOGGING #if DEBUG - DSLogPrivate(@"%@:%u sending data (%lu bytes) %@", self.host, self.port, (unsigned long)message.length, message.hexString); + DSLogPrivate(@"[%@: %@:%d] sending data (%lu bytes) %@", self.chain.name, self.host, self.port, (unsigned long)message.length, message.hexString); #else - DSLog(@"%@:%u sending data (%lu bytes) %@", self.host, self.port, (unsigned long)message.length, @""); + DSLog(@"[%@: %@:%d] sending data (%lu bytes) %@", self.chain.name, self.host, self.port, (unsigned long)message.length, @""); #endif #endif } @@ -445,7 +445,7 @@ - (void)sendVersionMessage { self.pingStartTime = [NSDate timeIntervalSince1970]; #if MESSAGE_LOGGING - DSLog(@"%@:%u %@sending version with protocol version %d user agent %@", self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", self.chain.protocolVersion, agent); + DSLog(@"[%@: %@:%d] %@sending version with protocol version %d user agent %@", self.chain.name, self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", self.chain.protocolVersion, agent); #endif [self sendRequest:request]; } @@ -461,15 +461,15 @@ - (void)sendFilterloadMessage:(NSData *)filter { self.sentFilter = YES; } #if DEBUG - DSLogPrivate(@"Sending filter with fingerprint %@ to node %@ %@", [NSData dataWithUInt256:filter.SHA256].shortHexString, self.host, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @""); + DSLogPrivate(@"[%@: %@:%d] Sending filter with fingerprint %@ to node %@", self.chain.name, self.host, self.port, [NSData dataWithUInt256:filter.SHA256].shortHexString, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @""); #else - DSLog(@"Sending filter with fingerprint %@ to node %@ %@", @"", self.host, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @""); + DSLog(@"[%@: %@:%d] Sending filter with fingerprint %@ to node %@", @"", self.chain.name, self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @""); #endif [self sendRequest:[DSFilterLoadRequest requestWithBloomFilterData:filter]]; } - (void)mempoolTimeout { - DSLog(@"[DSPeer] mempool time out %@", self.host); + DSLog(@"[%@: %@:%d] [DSPeer] mempool time out", self.chain.name, self.host, self.port); __block MempoolCompletionBlock completion = self.mempoolTransactionCompletion; [self sendPingMessageWithPongHandler:^(BOOL success) { if (completion) { @@ -481,9 +481,9 @@ - (void)mempoolTimeout { - (void)sendMempoolMessage:(NSArray *)publishedTxHashes completion:(MempoolCompletionBlock)completion { #if DEBUG - DSLogPrivate(@"%@:%u sendMempoolMessage %@", self.host, self.port, publishedTxHashes); + DSLogPrivate(@"[%@: %@:%d] sendMempoolMessage %@", self.chain.name, self.host, self.port, publishedTxHashes); #else - DSLog(@"%@:%u sendMempoolMessage %@", self.host, self.port, @""); + DSLog(@"[%@: %@:%d] sendMempoolMessage %@", self.chain.name, self.host, self.port, @""); #endif @synchronized (self.knownTxHashes) { [self.knownTxHashes addObjectsFromArray:publishedTxHashes]; @@ -558,9 +558,9 @@ - (void)sendGetblocksMessageWithLocators:(NSArray *)locators andHashStop:(UInt25 } }]; #if DEBUG - DSLogPrivate(@"%@:%u %@sending getblocks with locators %@", self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", locatorHexes); + DSLogPrivate(@"[%@: %@:%d] %@sending getblocks with locators %@", self.chain.name, self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", locatorHexes); #else - DSLog(@"%@:%u %@sending getblocks with locators %@", self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", @""); + DSLog(@"[%@: %@:%d] %@sending getblocks with locators %@", self.chain.name, self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", @""); #endif //#if MESSAGE_CONTENT_LOGGING //#if DEBUG @@ -575,7 +575,7 @@ - (void)sendGetblocksMessageWithLocators:(NSArray *)locators andHashStop:(UInt25 } - (void)sendInvMessageForHashes:(NSArray *)invHashes ofType:(DSInvType)invType { - DSLogPrivate(@"%@:%u sending inv message of type %@ hashes count %lu", self.host, self.port, [self nameOfInvMessage:invType], (unsigned long)invHashes.count); + DSLogPrivate(@"[%@: %@:%d] sending inv message of type %@ hashes count %lu", self.chain.name, self.host, self.port, [self nameOfInvMessage:invType], (unsigned long)invHashes.count); NSMutableOrderedSet *hashes = [NSMutableOrderedSet orderedSetWithArray:invHashes]; @synchronized (self.knownTxHashes) { [hashes minusOrderedSet:self.knownTxHashes]; @@ -628,9 +628,9 @@ - (void)sendGetdataMessageForTxHash:(UInt256)txHash { DSGetDataForTransactionHashRequest *request = [DSGetDataForTransactionHashRequest requestForTransactionHash:txHash]; #if MESSAGE_LOGGING #if DEBUG - DSLogPrivate(@"%@:%u sending getdata for transaction %@", self.host, self.port, uint256_hex(txHash)); + DSLogPrivate(@"[%@: %@:%d] sending getdata for transaction %@", self.chain.name, self.host, self.port, uint256_hex(txHash)); #else - DSLog(@"%@:%u sending getdata for transaction %@", self.host, self.port, @""); + DSLog(@"[%@: %@:%d] sending getdata for transaction %@", self.chain.name, self.host, self.port, @""); #endif #endif [self sendRequest:request]; @@ -639,7 +639,7 @@ - (void)sendGetdataMessageForTxHash:(UInt256)txHash { - (void)sendGetdataMessageWithTxHashes:(NSArray *)txHashes instantSendLockHashes:(NSArray *)instantSendLockHashes instantSendLockDHashes:(NSArray *)instantSendLockDHashes blockHashes:(NSArray *)blockHashes chainLockHashes:(NSArray *)chainLockHashes { if (!([[DSOptionsManager sharedInstance] syncType] & DSSyncType_GetsNewBlocks)) return; if (txHashes.count + instantSendLockHashes.count + instantSendLockDHashes.count + blockHashes.count + chainLockHashes.count > MAX_GETDATA_HASHES) { // limit total hash count to MAX_GETDATA_HASHES - DSLog(@"%@:%u couldn't send getdata, %u is too many items, max is %u", self.host, self.port, + DSLog(@"[%@: %@:%d] couldn't send getdata, %u is too many items, max is %u", self.chain.name, self.host, self.port, (int)txHashes.count + (int)instantSendLockHashes.count + (int)instantSendLockDHashes.count + (int)blockHashes.count + (int)chainLockHashes.count, MAX_GETDATA_HASHES); return; } else if (txHashes.count + instantSendLockHashes.count + instantSendLockDHashes.count + blockHashes.count + chainLockHashes.count == 0) @@ -652,23 +652,23 @@ - (void)sendGetdataMessageWithTxHashes:(NSArray *)txHashes instantSendLockHashes chainLockHashes:chainLockHashes]; self.sentGetdataTxBlocks = YES; #if MESSAGE_LOGGING - DSLog(@"%@:%u sending getdata (transactions and blocks)", self.host, self.port); + DSLog(@"[%@: %@:%d] sending getdata (transactions and blocks)", self.chain.name, self.host, self.port); #endif [self sendRequest:request]; } - (void)sendGovernanceRequest:(DSGovernanceHashesRequest *)request { if (request.hashes.count > MAX_GETDATA_HASHES) { // limit total hash count to MAX_GETDATA_HASHES - DSLog(@"%@:%u couldn't send governance votes getdata, %u is too many items, max is %u", self.host, self.port, + DSLog(@"[%@: %@:%d] couldn't send governance votes getdata, %u is too many items, max is %u", self.chain.name, self.host, self.port, (int)request.hashes.count, MAX_GETDATA_HASHES); return; } else if (request.hashes.count == 0) { - DSLog(@"%@:%u couldn't send governance getdata, there is no items", self.host, self.port); + DSLog(@"[%@: %@:%d] couldn't send governance getdata, there is no items", self.chain.name, self.host, self.port); return; } #if MESSAGE_LOGGING - DSLog(@"%@:%u sending getdata (%@)", self.host, self.port, request.description); + DSLog(@"[%@: %@:%d] sending getdata (%@)", self.chain.name, self.host, self.port, request.description); #endif // Not used @@ -687,7 +687,7 @@ - (void)sendPingMessageWithPongHandler:(void (^)(BOOL success))pongHandler { self.pingStartTime = [NSDate timeIntervalSince1970]; #if MESSAGE_LOGGING - DSLog(@"%@:%u sending ping", self.host, self.port); + DSLog(@"[%@: %@:%d] sending ping", self.chain.name, self.host, self.port); #endif [self dispatchAsyncInDelegateQueue:^{ [self sendRequest:[DSPingRequest requestWithLocalNonce:localNonce]]; @@ -700,7 +700,7 @@ - (void)rerequestBlocksFrom:(UInt256)blockHash { if (i != NSNotFound) { [self.knownBlockHashes removeObjectsInRange:NSMakeRange(0, i)]; - DSLog(@"%@:%u re-requesting %u blocks", self.host, self.port, (int)self.knownBlockHashes.count); + DSLog(@"[%@: %@:%d] re-requesting %u blocks", self.chain.name, self.host, self.port, (int)self.knownBlockHashes.count); [self sendGetdataMessageWithTxHashes:nil instantSendLockHashes:nil instantSendLockDHashes:nil blockHashes:self.knownBlockHashes.array chainLockHashes:nil]; } } @@ -716,13 +716,13 @@ - (void)sendGetSporks { // Governance Synchronization for Votes and Objects - (void)sendGovernanceSyncRequest:(DSGovernanceSyncRequest *)request { // Make sure we aren't in a governance sync process - DSLog(@"%@:%u Requesting Governance Object Vote Hashes", self.host, self.port); + DSLog(@"[%@: %@:%d] Requesting Governance Object Vote Hashes", self.chain.name, self.host, self.port); if (self.governanceRequestState != DSGovernanceRequestState_None) { - DSLog(@"%@:%u Requesting Governance Object Hashes out of resting state", self.host, self.port); + DSLog(@"[%@: %@:%d] Requesting Governance Object Hashes out of resting state", self.chain.name, self.host, self.port); return; } - DSLog(@"%@:%u Requesting %@", self.host, self.port, request.description); + DSLog(@"[%@: %@:%d] Requesting %@", self.chain.name, self.host, self.port, request.description); self.governanceRequestState = request.state; [self sendRequest:request]; @@ -731,7 +731,7 @@ - (void)sendGovernanceSyncRequest:(DSGovernanceSyncRequest *)request { //we aren't afraid of coming back here within 5 seconds because a peer can only sendGovSync once every 3 hours dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ if (self.governanceRequestState == DSGovernanceRequestState_GovernanceObjectHashes) { - DSLog(@"%@:%u Peer ignored request for governance object hashes", self.host, self.port); + DSLog(@"[%@: %@:%d] Peer ignored request for governance object hashes", self.chain.name, self.host, self.port); [self.governanceDelegate peer:self ignoredGovernanceSync:DSGovernanceRequestState_GovernanceObjectHashes]; } }); @@ -752,7 +752,7 @@ - (void)sendGovObject:(DSGovernanceObject *)governanceObject { - (void)acceptMessage:(NSData *)message type:(NSString *)type { #if MESSAGE_LOGGING if (![type isEqualToString:MSG_INV] && ![type isEqualToString:MSG_GOVOBJVOTE] && ![type isEqualToString:MSG_MERKLEBLOCK]) { - DSLog(@"%@:%u accept message %@", self.host, self.port, type); + DSLog(@"[%@: %@:%d] accept message %@", self.chain.name, self.host, self.port, type); } #endif if (self.currentBlock && (!([MSG_TX isEqual:type] || [MSG_IX isEqual:type] || [MSG_ISLOCK isEqual:type]))) { @@ -839,7 +839,7 @@ - (void)acceptMessage:(NSData *)message type:(NSString *)type { [self acceptDarksendTransactionMessage:message]; #if DROP_MESSAGE_LOGGING else { - DSLog(@"%@:%u dropping %@, len:%u, not implemented", self.host, self.port, type, (int)message.length); + DSLog(@"[%@: %@:%d] dropping %@, len:%u, not implemented", self.chain.name, self.host, self.port, type, (int)message.length); } #endif } @@ -862,13 +862,13 @@ - (void)acceptVersionMessage:(NSData *)message { if (self.version < self.chain.minProtocolVersion || self.version > self.chain.protocolVersion) { #if MESSAGE_LOGGING - DSLog(@"%@:%u protocol version %u not supported, valid versions are: [%u, %u], useragent:\"%@\", ", self.host, self.port, self.version, self.chain.minProtocolVersion, self.chain.protocolVersion, self.useragent); + DSLog(@"[%@: %@:%d] protocol version %u not supported, valid versions are: [%u, %u], useragent:\"%@\", ", self.chain.name, self.host, self.port, self.version, self.chain.minProtocolVersion, self.chain.protocolVersion, self.useragent); #endif [self error:@"protocol version %u not supported", self.version]; return; } else { #if MESSAGE_LOGGING - DSLog(@"%@:%u got version %u, useragent:\"%@\"", self.host, self.port, self.version, self.useragent); + DSLog(@"[%@: %@:%d] got version %u, useragent:\"%@\"", self.chain.name, self.host, self.port, self.version, self.useragent); #endif } [self sendVerackMessage]; @@ -876,14 +876,14 @@ - (void)acceptVersionMessage:(NSData *)message { - (void)acceptVerackMessage:(NSData *)message { if (self.gotVerack) { - DSLog(@"%@:%u got unexpected verack", self.host, self.port); + DSLog(@"[%@: %@:%d] got unexpected verack", self.chain.name, self.host, self.port); return; } _pingTime = [NSDate timeIntervalSince1970] - self.pingStartTime; // use verack time as initial ping time self.pingStartTime = 0; #if MESSAGE_LOGGING - DSLog(@"%@:%u got verack in %fs", self.host, self.port, self.pingTime); + DSLog(@"[%@: %@:%d] got verack in %fs", self.chain.name, self.host, self.port, self.pingTime); #endif self.gotVerack = YES; [self didConnect]; @@ -892,7 +892,7 @@ - (void)acceptVerackMessage:(NSData *)message { // TODO: relay addresses - (void)acceptAddrMessage:(NSData *)message { if (message.length > 0 && [message UInt8AtOffset:0] == 0) { - DSLog(@"%@:%u got addr with 0 addresses", self.host, self.port); + DSLog(@"[%@: %@:%d] got addr with 0 addresses", self.chain.name, self.host, self.port); return; } else if (message.length < 5) { [self error:@"malformed addr message, length %u is too short", (int)message.length]; @@ -906,14 +906,14 @@ - (void)acceptAddrMessage:(NSData *)message { NSMutableArray *peers = [NSMutableArray array]; if (count > 1000) { - DSLog(@"%@:%u dropping addr message, %u is too many addresses (max 1000)", self.host, self.port, (int)count); + DSLog(@"[%@: %@:%d] dropping addr message, %u is too many addresses (max 1000)", self.chain.name, self.host, self.port, (int)count); return; } else if (message.length < l.unsignedIntegerValue + count * 30) { [self error:@"malformed addr message, length is %u, should be %u for %u addresses", (int)message.length, (int)(l.unsignedIntegerValue + count * 30), (int)count]; return; } else - DSLog(@"%@:%u got addr with %u addresses", self.host, self.port, (int)count); + DSLog(@"[%@: %@:%d] got addr with %u addresses", self.chain.name, self.host, self.port, (int)count); for (NSUInteger off = l.unsignedIntegerValue; off < l.unsignedIntegerValue + 30 * count; off += 30) { NSTimeInterval timestamp = [message UInt32AtOffset:off]; @@ -942,7 +942,7 @@ - (void)acceptAddrMessage:(NSData *)message { } - (void)acceptAddrV2Message:(NSData *)message { - DSLog(@"%@:%u sendaddrv2, len:%u, (not implemented)", self.host, self.port, (int)message.length); + DSLog(@"[%@: %@:%d] sendaddrv2, len:%u, (not implemented)", self.chain.name, self.host, self.port, (int)message.length); } - (NSString *)nameOfInvMessage:(DSInvType)type { @@ -1015,16 +1015,16 @@ - (void)acceptInvMessage:(NSData *)message { (int)(((l.unsignedIntegerValue == 0) ? 1 : l.unsignedIntegerValue) + count * 36), (int)count]; return; } else if (count > MAX_GETDATA_HASHES) { - DSLog(@"%@:%u dropping inv message, %u is too many items, max is %u", self.host, self.port, (int)count, + DSLog(@"[%@: %@:%d] dropping inv message, %u is too many items, max is %u", self.chain.name, self.host, self.port, (int)count, MAX_GETDATA_HASHES); return; } #if MESSAGE_LOGGING if (count == 0) { - DSLog(@"Got empty Inv message"); + DSLog(@"[%@: %@:%d] Got empty Inv message", self.chain.name, self.host, self.port); } if (count > 0 && ([message UInt32AtOffset:l.unsignedIntegerValue] != DSInvType_MasternodePing) && ([message UInt32AtOffset:l.unsignedIntegerValue] != DSInvType_MasternodePaymentVote) && ([message UInt32AtOffset:l.unsignedIntegerValue] != DSInvType_MasternodeVerify) && ([message UInt32AtOffset:l.unsignedIntegerValue] != DSInvType_GovernanceObjectVote) && ([message UInt32AtOffset:l.unsignedIntegerValue] != DSInvType_DSTx)) { - DSLog(@"%@:%u got inv with %u item%@ (first item %@ with hash %@/%@)", self.host, self.port, (int)count, count == 1 ? @"" : @"s", [self nameOfInvMessage:[message UInt32AtOffset:l.unsignedIntegerValue]], [NSData dataWithUInt256:[message UInt256AtOffset:l.unsignedIntegerValue + sizeof(uint32_t)]].hexString, [NSData dataWithUInt256:[message UInt256AtOffset:l.unsignedIntegerValue + sizeof(uint32_t)]].reverse.hexString); + DSLog(@"[%@: %@:%d] got inv with %u item%@ (first item %@ with hash %@/%@)", self.chain.name, self.host, self.port, (int)count, count == 1 ? @"" : @"s", [self nameOfInvMessage:[message UInt32AtOffset:l.unsignedIntegerValue]], [NSData dataWithUInt256:[message UInt256AtOffset:l.unsignedIntegerValue + sizeof(uint32_t)]].hexString, [NSData dataWithUInt256:[message UInt256AtOffset:l.unsignedIntegerValue + sizeof(uint32_t)]].reverse.hexString); } #endif BOOL onlyPrivateSendTransactions = NO; @@ -1065,7 +1065,7 @@ - (void)acceptInvMessage:(NSData *)message { case DSInvType_CompactBlock: break; case DSInvType_ChainLockSignature: [chainLockHashes addObject:uint256_obj(hash)]; break; case DSInvType_QuorumPrematureCommitment: - NSLog(@"Send premature commitment containing the quorum public key (intra-quorum communication)"); + DSLog(@"[%@: %@:%d] Send premature commitment containing the quorum public key (intra-quorum communication)", self.chain.name, self.host, self.port); break; default: { NSString *desc = [NSString stringWithFormat:@"inventory type not dealt with: %u", type]; @@ -1085,7 +1085,7 @@ - (void)acceptInvMessage:(NSData *)message { [self error:@"got tx inv message before loading a filter"]; return; } else if (txHashes.count + instantSendLockHashes.count + instantSendLockDHashes.count > 10000) { // this was happening on testnet, some sort of DOS/spam attack? - DSLog(@"%@:%u too many transactions, disconnecting", self.host, self.port); + DSLog(@"[%@: %@:%d] too many transactions, disconnecting", self.chain.name, self.host, self.port); [self disconnect]; // disconnecting seems to be the easiest way to mitigate it return; } else if (currentHeight > 0 && blockHashes.count > 2 && blockHashes.count < 500 && @@ -1220,7 +1220,7 @@ - (void)acceptInvMessage:(NSData *)message { if (self.mempoolTransactionCompletion && (txHashes.count + governanceObjectHashes.count + sporkHashes.count > 0)) { self.mempoolRequestTime = [NSDate timeIntervalSince1970]; // this will cancel the mempool timeout - DSLog(@"[DSPeer] got mempool tx inv messages %@", self.host); + DSLog(@"[%@: %@:%d] [DSPeer] got mempool tx inv messages", self.chain.name, self.host, self.port); __block MempoolCompletionBlock completion = self.mempoolTransactionCompletion; [self sendPingMessageWithPongHandler:^(BOOL success) { if (completion) { @@ -1259,15 +1259,15 @@ - (void)acceptTxMessage:(NSData *)message { }]; #if LOG_FULL_TX_MESSAGE #if DEBUG - DSLogPrivate(@"%@:%u got tx %@ %@", self.host, self.port, uint256_obj(tx.txHash), message.hexString); + DSLogPrivate(@"[%@: %@:%d] got tx %@ %@", self.chain.name, self.host, self.port, uint256_obj(tx.txHash), message.hexString); #else - DSLog(@"%@:%u got tx %@ %@", self.host, self.port, @"", @""); + DSLog(@"[%@: %@:%d] got tx %@ %@", self.chain.name, self.host, self.port, @"", @""); #endif #else #if DEBUG - DSLogPrivate(@"%@:%u got tx (%hu): %@", self.host, self.port, tx.type, uint256_obj(tx.txHash)); + DSLogPrivate(@"[%@: %@:%d] got tx (%hu): %@", self.chain.name, self.host, self.port, tx.type, uint256_obj(tx.txHash)); #else - DSLog(@"%@:%u got tx (%lu): %@", self.host, self.port, tx.type, @""); + DSLog(@"[%@: %@:%d] got tx (%lu): %@", self.chain.name, self.host, self.port, tx.type, @""); #endif #endif } @@ -1279,16 +1279,16 @@ - (void)acceptTxMessage:(NSData *)message { [self.currentBlockTxHashes removeObject:uint256_obj(txHash)]; } else { #if DEBUG - DSLogPrivate(@"%@:%u current block does not contain transaction %@ (contains %@)", self.host, self.port, uint256_hex(txHash), self.currentBlockTxHashes); + DSLogPrivate(@"[%@: %@:%d] current block does not contain transaction %@ (contains %@)", self.chain.name, self.host, self.port, uint256_hex(txHash), self.currentBlockTxHashes); #else - DSLog(@"%@:%u current block does not contain transaction %@ (contains %@)", self.host, self.port, @"", @""); + DSLog(@"[%@: %@:%d] current block does not contain transaction %@ (contains %@)", self.chain.name, self.host, self.port, @"", @""); #endif } if (self.currentBlockTxHashes.count == 0) { // we received the entire block including all matched tx DSMerkleBlock *block = self.currentBlock; - DSLog(@"%@:%u clearing current block", self.host, self.port); + DSLog(@"[%@: %@:%d] clearing current block", self.chain.name, self.host, self.port); self.currentBlock = nil; self.currentBlockTxHashes = nil; @@ -1298,21 +1298,21 @@ - (void)acceptTxMessage:(NSData *)message { }); } } else { - DSLog(@"%@:%u no current block", self.host, self.port); + DSLog(@"[%@: %@:%d] no current block", self.chain.name, self.host, self.port); } } - (void)acceptIslockMessage:(NSData *)message { #if LOG_TX_LOCK_VOTES - DSLog(@"peer relayed islock message: %@", message.hexString); + DSLog(@"[%@: %@:%d] peer relayed islock message: %@", self.chain.name, self.host, self.port, message.hexString); #endif if (![self.chain.chainManager.sporkManager deterministicMasternodeListEnabled]) { - DSLog(@"returned instant send lock message when DML not enabled: %@", message); //no error here + DSLog(@"[%@: %@:%d] returned instant send lock message when DML not enabled: %@", self.chain.name, self.host, self.port, message); //no error here return; } if (![self.chain.chainManager.sporkManager llmqInstantSendEnabled]) { - DSLog(@"returned instant send lock message when llmq instant send is not enabled: %@", message); //no error here + DSLog(@"[%@: %@:%d] returned instant send lock message when llmq instant send is not enabled: %@", self.chain.name, self.host, self.port, message); //no error here return; } DSInstantSendTransactionLock *instantSendTransactionLock = [DSInstantSendTransactionLock instantSendTransactionLockWithNonDeterministicMessage:message onChain:self.chain]; @@ -1331,14 +1331,14 @@ - (void)acceptIslockMessage:(NSData *)message { - (void)acceptIsdlockMessage:(NSData *)message { #if LOG_TX_LOCK_VOTES - DSLog(@"peer relayed isdlock message: %@", message.hexString); + DSLog(@"[%@: %@:%d] peer relayed isdlock message: %@", self.chain.name, self.host, self.port, message.hexString); #endif if (![self.chain.chainManager.sporkManager deterministicMasternodeListEnabled]) { - DSLog(@"returned instant send lock message when DML not enabled: %@", message); //no error here + DSLog(@"[%@: %@:%d] returned instant send lock message when DML not enabled: %@", self.chain.name, self.host, self.port, message); //no error here return; } if (![self.chain.chainManager.sporkManager llmqInstantSendEnabled]) { - DSLog(@"returned instant send lock message when llmq instant send is not enabled: %@", message); //no error here + DSLog(@"[%@: %@:%d] returned instant send lock message when llmq instant send is not enabled: %@", self.chain.name, self.host, self.port, message); //no error here return; } DSInstantSendTransactionLock *instantSendTransactionLock = [DSInstantSendTransactionLock instantSendTransactionLockWithDeterministicMessage:message onChain:self.chain]; @@ -1383,12 +1383,12 @@ - (void)acceptHeadersMessage:(NSData *)message { } if (count == 0) { #if DEBUG - DSLogPrivate(@"%@:%u got 0 headers (%@)", self.host, self.port, message.hexString); + DSLogPrivate(@"[%@: %@:%d] got 0 headers (%@)", self.chain.name, self.host, self.port, message.hexString); #else - DSLog(@"%@:%u got 0 headers (%@)", self.host, self.port, @""); + DSLog(@"[%@: %@:%d] got 0 headers (%@)", self.chain.name, self.host, self.port, @""); #endif } else { - DSLog(@"%@:%u got %u headers", self.host, self.port, (int)count); + DSLog(@"[%@: %@:%d] got %u headers", self.chain.name, self.host, self.port, (int)count); } #if LOG_ALL_HEADERS_IN_ACCEPT_HEADERS @@ -1425,7 +1425,7 @@ - (void)acceptHeadersMessage:(NSData *)message { NSTimeInterval firstTimestamp = [message UInt32AtOffset:l + 81 + 68]; if (!self.chain.needsInitialTerminalHeadersSync && (firstTimestamp + DAY_TIME_INTERVAL * 2 >= self.earliestKeyTime) && [self.chain.chainManager shouldRequestMerkleBlocksForZoneAfterHeight:self.chain.lastSyncBlockHeight + 1]) { //this is a rare scenario where we called getheaders but the first header returned was actually past the cuttoff, but the previous header was before the cuttoff - DSLog(@"%@:%u calling getblocks with locators: %@", self.host, self.port, [self.chain chainSyncBlockLocatorArray]); + DSLog(@"[%@: %@:%d] calling getblocks with locators: %@", self.chain.name, self.host, self.port, [self.chain chainSyncBlockLocatorArray]); [self sendGetblocksMessageWithLocators:self.chain.chainSyncBlockLocatorArray andHashStop:UINT256_ZERO]; return; } @@ -1445,11 +1445,11 @@ - (void)acceptHeadersMessage:(NSData *)message { } lastBlockHash = [DSKeyManager x11:[message subdataWithRange:NSMakeRange(off, 80)]]; lastHashData = uint256_data(lastBlockHash); - DSLog(@"%@:%u calling getblocks with locators: [%@, %@]", self.host, self.port, lastHashData.reverse.hexString, firstHashData.reverse.hexString); + DSLog(@"[%@: %@:%d] calling getblocks with locators: [%@, %@]", self.chain.name, self.host, self.port, lastHashData.reverse.hexString, firstHashData.reverse.hexString); [self sendGetblocksMessageWithLocators:@[lastHashData, firstHashData] andHashStop:UINT256_ZERO]; } else { - DSLog(@"%@:%u calling getheaders with locators: [%@, %@]", self.host, self.port, lastHashData.reverse.hexString, firstHashData.reverse.hexString); + DSLog(@"[%@: %@:%d] calling getheaders with locators: [%@, %@]", self.chain.name, self.host, self.port, lastHashData.reverse.hexString, firstHashData.reverse.hexString); [self sendGetheadersMessageWithLocators:@[lastHashData, firstHashData] andHashStop:UINT256_ZERO]; } } @@ -1466,7 +1466,7 @@ - (void)acceptHeadersMessage:(NSData *)message { } - (void)acceptGetaddrMessage:(NSData *)message { - DSLog(@"%@:%u got getaddr", self.host, self.port); + DSLog(@"[%@: %@:%d] got getaddr", self.chain.name, self.host, self.port); [self sendRequest:[DSAddrRequest request]]; } @@ -1480,12 +1480,12 @@ - (void)acceptGetdataMessage:(NSData *)message { (int)(((l == 0) ? 1 : l) + count * 36), (int)count]; return; } else if (count > MAX_GETDATA_HASHES) { - DSLog(@"%@:%u dropping getdata message, %u is too many items, max is %u", self.host, self.port, (int)count, + DSLog(@"[%@: %@:%d] dropping getdata message, %u is too many items, max is %u", self.chain.name, self.host, self.port, (int)count, MAX_GETDATA_HASHES); return; } - DSLog(@"%@:%u %@got getdata for %u item%@", self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer)" : @"", (int)count, count == 1 ? @"" : @"s"); + DSLog(@"[%@: %@:%d] %@got getdata for %u item%@", self.chain.name, self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer)" : @"", (int)count, count == 1 ? @"" : @"s"); [self dispatchAsyncInDelegateQueue:^{ NSMutableData *notfound = [NSMutableData data]; @@ -1506,9 +1506,9 @@ - (void)acceptGetdataMessage:(NSData *)message { break; } else { #if DEBUG - DSLogPrivate(@"peer %@ requested transaction was not found with hash %@ reversed %@", self.host, [NSData dataWithUInt256:hash].hexString, [NSData dataWithUInt256:hash].reverse.hexString); + DSLogPrivate(@"[%@: %@:%d] peer requested transaction was not found with hash %@ reversed %@", self.chain.name, self.host, self.port, [NSData dataWithUInt256:hash].hexString, [NSData dataWithUInt256:hash].reverse.hexString); #else - DSLog(@"peer %@ requested transaction was not found with hash %@ reversed %@", self.host, @"", @""); + DSLog(@"[%@: %@:%d] peer requested transaction was not found with hash %@ reversed %@", self.chain.name, self.host, self.port, @"", @""); #endif [notfound appendUInt32:type]; [notfound appendBytes:&hash length:sizeof(hash)]; @@ -1563,7 +1563,7 @@ - (void)acceptNotfoundMessage:(NSData *)message { return; } - DSLog(@"%@:%u got notfound with %u item%@ (first item %@)", self.host, self.port, (int)count, count == 1 ? @"" : @"s", [self nameOfInvMessage:[message UInt32AtOffset:l]]); + DSLog(@"[%@: %@:%d] got notfound with %u item%@ (first item %@)", self.chain.name, self.host, self.port, (int)count, count == 1 ? @"" : @"s", [self nameOfInvMessage:[message UInt32AtOffset:l]]); for (NSUInteger off = l; off < l + 36 * count; off += 36) { if ([message UInt32AtOffset:off] == DSInvType_Tx) { @@ -1585,7 +1585,7 @@ - (void)acceptPingMessage:(NSData *)message { return; } #if MESSAGE_LOGGING - DSLog(@"%@:%u got ping", self.host, self.port); + DSLog(@"[%@: %@:%d] got ping", self.chain.name, self.host, self.port); #endif [self sendMessage:message type:MSG_PONG]; } @@ -1600,7 +1600,7 @@ - (void)acceptPongMessage:(NSData *)message { } else { __block BOOL hasNoHandlers = ![self.pongHandlers count]; if (hasNoHandlers) { - DSLog(@"%@:%u got unexpected pong", self.host, self.port); + DSLog(@"[%@: %@:%d] got unexpected pong", self.chain.name, self.host, self.port); return; } } @@ -1614,7 +1614,7 @@ - (void)acceptPongMessage:(NSData *)message { } #if MESSAGE_LOGGING - DSLog(@"%@:%u got pong in %fs", self.host, self.port, self.pingTime); + DSLog(@"[%@: %@:%d] got pong in %fs", self.chain.name, self.host, self.port, self.pingTime); #endif if (self->_status == DSPeerStatus_Connected && self.pongHandlers.count) { void (^handler)(BOOL) = [self.pongHandlers objectAtIndex:0]; @@ -1640,7 +1640,7 @@ - (void)acceptMerkleblockMessage:(NSData *)message { [self error:@"got merkleblock message before loading a filter"]; return; } - //else DSLog(@"%@:%u got merkleblock %@", self.host, self.port, uint256_hex(block.blockHash)); + //else DSLog(@"[%@: %@:%d] got merkleblock %@", self.chain.name, self.host, self.port, uint256_hex(block.blockHash)); NSMutableOrderedSet *txHashes = [NSMutableOrderedSet orderedSetWithArray:block.transactionHashes]; @synchronized (self.knownTxHashes) { @@ -1665,9 +1665,9 @@ - (void)acceptMerkleblockMessage:(NSData *)message { - (void)acceptChainLockMessage:(NSData *)message { if (![self.chain.chainManager.sporkManager chainLocksEnabled]) { #if DEBUG - DSLogPrivate(@"returned chain lock message when chain locks are not enabled: %@", message); //no error here + DSLogPrivate(@"[%@: %@:%d] returned chain lock message when chain locks are not enabled: %@", self.chain.name, self.host, self.port, message); //no error here #else - DSLog(@"returned chain lock message when chain locks are not enabled: %@", @""); //no error here + DSLog(@"[%@: %@:%d] returned chain lock message when chain locks are not enabled: %@", self.chain.name, self.host, self.port, @""); //no error here #endif return; } @@ -1697,10 +1697,10 @@ - (void)acceptRejectMessage:(NSData *)message { UInt256 txHash = ([MSG_TX isEqual:type] || [MSG_IX isEqual:type]) ? [message UInt256AtOffset:off + l] : UINT256_ZERO; #if DEBUG - DSLogPrivate(@"%@:%u rejected %@ code: 0x%x reason: \"%@\"%@%@", self.host, self.port, type, code, reason, + DSLogPrivate(@"[%@: %@:%d] rejected %@ code: 0x%x reason: \"%@\"%@%@", self.chain.name, self.host, self.port, type, code, reason, (uint256_is_zero(txHash) ? @"" : @" txid: "), (uint256_is_zero(txHash) ? @"" : uint256_obj(txHash))); #else - DSLog(@"%@:%u rejected %@ code: 0x%x reason: \"%@\"%@%@", self.host, self.port, type, code, reason, + DSLog(@"[%@: %@:%d] rejected %@ code: 0x%x reason: \"%@\"%@%@", self.chain.name, self.host, self.port, type, code, reason, (uint256_is_zero(txHash) ? @"" : @" txid: "), (uint256_is_zero(txHash) ? @"" : @"")); #endif reason = nil; // fixes an unused variable warning for non-debug builds @@ -1720,7 +1720,7 @@ - (void)acceptFeeFilterMessage:(NSData *)message { } _feePerByte = ceilf((float)[message UInt64AtOffset:0] / 1000.0f); - DSLog(@"%@:%u got feefilter with rate %llu per Byte", self.host, self.port, self.feePerByte); + DSLog(@"[%@: %@:%d] got feefilter with rate %llu per Byte", self.chain.name, self.host, self.port, self.feePerByte); [self dispatchAsyncInDelegateQueue:^{ [self.transactionDelegate peer:self setFeePerByte:self.feePerByte]; }]; @@ -1737,7 +1737,7 @@ - (void)acceptSporkMessage:(NSData *)message { - (void)acceptSSCMessage:(NSData *)message { DSSyncCountInfo syncCountInfo = [message UInt32AtOffset:0]; uint32_t count = [message UInt32AtOffset:4]; - DSLog(@"received ssc message %d %d", syncCountInfo, count); + DSLog(@"[%@: %@:%d] received ssc message %d %d", self.chain.name, self.host, self.port, syncCountInfo, count); switch (syncCountInfo) { case DSSyncCountInfo_GovernanceObject: if (self.governanceRequestState == DSGovernanceRequestState_GovernanceObjectHashes) { @@ -1795,7 +1795,7 @@ - (void)acceptGovObjectVoteMessage:(NSData *)message { } - (void)acceptGovObjectSyncMessage:(NSData *)message { - DSLog(@"Gov Object Sync"); + DSLog(@"[%@: %@:%d] Gov Object Sync", self.chain.name, self.host, self.port); } // MARK: - Accept Dark send @@ -1926,7 +1926,7 @@ - (NSError *)connectionTimeoutError { - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { switch (eventCode) { //!OCLINT case NSStreamEventOpenCompleted: - DSLog(@"%@:%u %@ stream connected in %fs", self.host, self.port, + DSLog(@"[%@: %@:%d] %@ stream connected in %fs", self.chain.name, self.host, self.port, (aStream == self.inputStream) ? @"input" : (aStream == self.outputStream ? @"output" : @"unknown"), [NSDate timeIntervalSince1970] - self.pingStartTime); @@ -1970,7 +1970,7 @@ - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { maxLength:self.msgHeader.length - headerLen]; if (l < 0) { - DSLog(@"%@:%u error reading message", self.host, self.port); + DSLog(@"[%@: %@:%d] error reading message", self.chain.name, self.host, self.port); goto reset; //!OCLINT } @@ -2010,7 +2010,7 @@ - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { maxLength:self.msgPayload.length - payloadLen]; if (l < 0) { - DSLog(@"%@:%u error reading %@", self.host, self.port, type); + DSLog(@"[%@: %@:%d] error reading %@", self.chain.name, self.host, self.port, type); goto reset; //!OCLINT } @@ -2038,17 +2038,17 @@ - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { break; case NSStreamEventErrorOccurred: - DSLog(@"%@:%u error connecting, %@", self.host, self.port, aStream.streamError); + DSLog(@"[%@: %@:%d] error connecting, %@", self.chain.name, self.host, self.port, aStream.streamError); [self disconnectWithError:aStream.streamError]; break; case NSStreamEventEndEncountered: - DSLog(@"%@:%u connection closed", self.host, self.port); + DSLog(@"[%@: %@:%d] connection closed", self.chain.name, self.host, self.port); [self disconnectWithError:nil]; break; default: - DSLog(@"%@:%u unknown network stream eventCode:%u", self.host, self.port, (int)eventCode); + DSLog(@"[%@: %@:%d] unknown network stream eventCode:%u", self.chain.name, self.host, self.port, (int)eventCode); } } diff --git a/DashSync/shared/Models/Transactions/Base/DSInstantSendTransactionLock.m b/DashSync/shared/Models/Transactions/Base/DSInstantSendTransactionLock.m index a97a9d392..5a2fb3cfd 100644 --- a/DashSync/shared/Models/Transactions/Base/DSInstantSendTransactionLock.m +++ b/DashSync/shared/Models/Transactions/Base/DSInstantSendTransactionLock.m @@ -166,7 +166,7 @@ - (UInt256)requestID { [data appendData:input]; } _requestID = [data SHA256_2]; - DSLogPrivate(@"the request ID is %@", uint256_hex(_requestID)); + DSLogPrivate(@"[%@] the request ID is %@", self.chain.name, uint256_hex(_requestID)); return _requestID; } @@ -206,28 +206,28 @@ - (BOOL)verifySignatureWithQuorumOffset:(uint32_t)offset { if (quorumEntry && quorumEntry.verified) { self.signatureVerified = [self verifySignatureAgainstQuorum:quorumEntry]; if (!self.signatureVerified) { - DSLog(@"unable to verify IS signature with offset %d", offset); + DSLog(@"[%@] unable to verify IS signature with offset %d", self.chain.name, offset); } else { - DSLog(@"IS signature verified with offset %d", offset); + DSLog(@"[%@] IS signature verified with offset %d", self.chain.name, offset); } } else if (quorumEntry) { - DSLog(@"quorum entry %@ found but is not yet verified", uint256_hex(quorumEntry.quorumHash)); + DSLog(@"[%@] quorum entry %@ found but is not yet verified", self.chain.name, uint256_hex(quorumEntry.quorumHash)); } else { - DSLog(@"no quorum entry found"); + DSLog(@"[%@] no quorum entry found", self.chain.name); } if (self.signatureVerified) { self.intendedQuorum = quorumEntry; } else if (quorumEntry.verified && offset == 8) { //try again a few blocks more in the past - DSLog(@"trying with offset 0"); + DSLog(@"[%@] trying with offset 0", self.chain.name); return [self verifySignatureWithQuorumOffset:0]; } else if (quorumEntry.verified && offset == 0) { //try again a few blocks more in the future - DSLog(@"trying with offset 16"); + DSLog(@"[%@] trying with offset 16", self.chain.name); return [self verifySignatureWithQuorumOffset:16]; } - DSLog(@"returning signature verified %d with offset %d", self.signatureVerified, offset); + DSLog(@"[%@] returning signature verified %d with offset %d", self.chain.name, self.signatureVerified, offset); return self.signatureVerified; } diff --git a/DashSync/shared/Models/Transactions/Base/DSTransaction.m b/DashSync/shared/Models/Transactions/Base/DSTransaction.m index 485880905..f6f0e1f9f 100644 --- a/DashSync/shared/Models/Transactions/Base/DSTransaction.m +++ b/DashSync/shared/Models/Transactions/Base/DSTransaction.m @@ -864,7 +864,7 @@ - (BOOL)saveInitialInContext:(NSManagedObjectContext *)context { if (![context ds_save]) { self.persistenceStatus = DSTransactionPersistenceStatus_Saved; } else { - DSLog(@"There was an error saving the transaction"); + DSLog(@"[%@] There was an error saving the transaction", self.chain.name); self.persistenceStatus = DSTransactionPersistenceStatus_NotSaved; } } else { diff --git a/DashSync/shared/Models/Transactions/Provider/DSProviderRegistrationTransaction.m b/DashSync/shared/Models/Transactions/Provider/DSProviderRegistrationTransaction.m index 4ca170d6d..b49269d17 100644 --- a/DashSync/shared/Models/Transactions/Provider/DSProviderRegistrationTransaction.m +++ b/DashSync/shared/Models/Transactions/Provider/DSProviderRegistrationTransaction.m @@ -133,7 +133,7 @@ - (instancetype)initWithProviderRegistrationTransactionVersion:(uint16_t)version self.platformNodeID = platformNodeID; self.operatorReward = operatorReward; self.scriptPayout = scriptPayout; - DSLogPrivate(@"Creating provider (masternode) with ownerKeyHash %@", uint160_data(ownerKeyHash)); + DSLogPrivate(@"[%@] Creating provider (masternode) with ownerKeyHash %@", chain.name, uint160_data(ownerKeyHash)); return self; } @@ -164,7 +164,7 @@ - (instancetype)initWithInputHashes:(NSArray *)hashes inputIndexes:(NSArray *)in self.scriptPayout = scriptPayout; [self hasSetInputsAndOutputs]; - DSLogPrivate(@"Creating provider (masternode) with ownerKeyHash %@", uint160_data(ownerKeyHash)); + DSLogPrivate(@"[%@] Creating provider (masternode) with ownerKeyHash %@", chain.name, uint160_data(ownerKeyHash)); return self; } diff --git a/DashSync/shared/Models/Wallet/DSAccount.m b/DashSync/shared/Models/Wallet/DSAccount.m index cba8e612d..b0a9fe375 100644 --- a/DashSync/shared/Models/Wallet/DSAccount.m +++ b/DashSync/shared/Models/Wallet/DSAccount.m @@ -225,7 +225,7 @@ - (void)loadTransactions { NSArray *transactions = [DSTransactionEntity objectsInContext:self.managedObjectContext matching:@"transactionHash.chain == %@", [self.wallet.chain chainEntityInContext:self.managedObjectContext]]; for (DSTransactionEntity *entity in transactions) { DSTransaction *transaction = [entity transactionForChain:self.wallet.chain]; - DSLogPrivate(@"Transaction %@", [transaction longDescription]); + DSLogPrivate(@"[%@] Transaction %@", _wallet.chain.name, [transaction longDescription]); } #endif @@ -1079,7 +1079,7 @@ - (DSTransaction *)updateTransaction:(DSTransaction *)transaction // check for sufficient total funds before building a smaller transaction if (self.balance < amount + [self.wallet.chain feeForTxSize:txSize + cpfpSize]) { - DSLog(@"Insufficient funds. %llu is less than transaction amount:%llu", self.balance, + DSLog(@"[%@] Insufficient funds. %llu is less than transaction amount:%llu", self.wallet.chain.name, self.balance, amount + [self.wallet.chain feeForTxSize:txSize + cpfpSize]); return nil; } @@ -1118,7 +1118,7 @@ - (DSTransaction *)updateTransaction:(DSTransaction *)transaction } if (balance < amount + feeAmount) { // insufficient funds - DSLog(@"Insufficient funds. %llu is less than transaction amount:%llu", balance, amount + feeAmount); + DSLog(@"[%@] Insufficient funds. %llu is less than transaction amount:%llu", self.wallet.chain.name, balance, amount + feeAmount); return nil; } @@ -1164,9 +1164,9 @@ - (NSArray *)setBlockHeight:(int32_t)height andTimestamp:(NSTimeInterval)timesta if (!tx || (tx.blockHeight == height && tx.timestamp == timestamp)) continue; #if DEBUG - DSLogPrivate(@"Setting account tx %@ height to %d", tx, height); + DSLogPrivate(@"[%@] Setting account tx %@ height to %d", self.wallet.chain.name, tx, height); #else - DSLogPrivate(@"Setting account tx %@ height to %d", @"", height); + DSLogPrivate(@"[%@] Setting account tx %@ height to %d", self.wallet.chain.name, @"", height); #endif tx.blockHeight = height; if (tx.timestamp == UINT32_MAX || tx.timestamp == 0) { @@ -1406,9 +1406,9 @@ - (void)signTransactions:(NSArray *)transactions withPrompt:(NS - (BOOL)registerTransaction:(DSTransaction *)transaction saveImmediately:(BOOL)saveImmediately { NSParameterAssert(transaction); #if DEBUG - DSLogPrivate(@"[DSAccount] registering transaction %@", transaction); + DSLogPrivate(@"[%@] [DSAccount] registering transaction %@", self.wallet.chain.name, transaction); #else - DSLog(@"[DSAccount] registering transaction %@", @""); + DSLog(@"[%@] [DSAccount] registering transaction %@", self.wallet.chain.name, @""); #endif @synchronized (self) { UInt256 txHash = transaction.txHash; @@ -1424,17 +1424,17 @@ - (BOOL)registerTransaction:(DSTransaction *)transaction saveImmediately:(BOOL)s } if (self.allTx[hash] != nil) { #if DEBUG - DSLogPrivate(@"[DSAccount] transaction already registered %@", transaction); + DSLogPrivate(@"[%@] [DSAccount] transaction already registered %@", self.wallet.chain.name, transaction); #else - DSLog(@"[DSAccount] transaction already registered %@", @""); + DSLog(@"[%@] [DSAccount] transaction already registered %@", self.wallet.chain.name, @""); #endif return YES; } //TODO: handle tx replacement with input sequence numbers (now replacements appear invalid until confirmation) #if DEBUG - DSLogPrivate(@"[DSAccount] received unseen transaction %@", transaction); + DSLogPrivate(@"[%@] [DSAccount] received unseen transaction %@", self.wallet.chain.name, transaction); #else - DSLog(@"[DSAccount] received unseen transaction %@", @""); + DSLog(@"[%@] [DSAccount] received unseen transaction %@", self.wallet.chain.name, @""); #endif if ([self checkIsFirstTransaction:transaction]) _firstTransactionHash = txHash; //it's okay if this isn't really the first, as it will be close enough (500 blocks close) self.allTx[hash] = transaction; diff --git a/DashSync/shared/Models/Wallet/DSSpecialTransactionsWalletHolder.m b/DashSync/shared/Models/Wallet/DSSpecialTransactionsWalletHolder.m index 1f003d11a..60509ae7d 100644 --- a/DashSync/shared/Models/Wallet/DSSpecialTransactionsWalletHolder.m +++ b/DashSync/shared/Models/Wallet/DSSpecialTransactionsWalletHolder.m @@ -365,9 +365,9 @@ - (NSArray *)setBlockHeight:(int32_t)height andTimestamp:(NSTimeInterval)timesta if (!tx || (tx.blockHeight == height && tx.timestamp == timestamp)) continue; #if DEBUG - DSLogPrivate(@"Setting special tx %@ height to %d", tx, height); + DSLogPrivate(@"[%@] Setting special tx %@ height to %d", self.wallet.chain.name, tx, height); #else - DSLog(@"Setting special tx %@ height to %d", @"", height); + DSLog(@"[%@] Setting special tx %@ height to %d", self.wallet.chain.name, @"", height); #endif tx.blockHeight = height; if (tx.timestamp == UINT32_MAX || tx.timestamp == 0) { diff --git a/DashSync/shared/Models/Wallet/DSWallet.m b/DashSync/shared/Models/Wallet/DSWallet.m index 7e450641e..9eee22251 100644 --- a/DashSync/shared/Models/Wallet/DSWallet.m +++ b/DashSync/shared/Models/Wallet/DSWallet.m @@ -561,9 +561,9 @@ - (void)migrateWalletCreationTime { if (realWalletCreationTime && (realWalletCreationTime != REFERENCE_DATE_2001)) { _walletCreationTime = MAX(realWalletCreationTime, BIP39_CREATION_TIME); //safeguard #if DEBUG - DSLogPrivate(@"real wallet creation set to %@", realWalletCreationDate); + DSLogPrivate(@"[%@] real wallet creation set to %@", self.chain.name, realWalletCreationDate); #else - DSLog(@"real wallet creation set to %@", @""); + DSLog(@"[%@] real wallet creation set to %@", self.chain.name, @""); #endif setKeychainData([NSData dataWithBytes:&realWalletCreationTime length:sizeof(realWalletCreationTime)], self.creationTimeUniqueID, NO); } else if (realWalletCreationTime == REFERENCE_DATE_2001) { @@ -1324,7 +1324,7 @@ - (NSMutableDictionary *)blockchainIdentities { [context performBlockAndWait:^{ NSUInteger blockchainIdentityEntitiesCount = [DSBlockchainIdentityEntity countObjectsInContext:context matching:@"chain == %@ && isLocal == TRUE", [self.chain chainEntityInContext:context]]; if (blockchainIdentityEntitiesCount != keyChainDictionary.count) { - DSLog(@"Unmatching blockchain entities count"); + DSLog(@"[%@] Unmatching blockchain entities count", self.chain.name); } DSBlockchainIdentityEntity *blockchainIdentityEntity = [DSBlockchainIdentityEntity anyObjectInContext:context matching:@"uniqueID == %@", uniqueIdData]; DSBlockchainIdentity *blockchainIdentity = nil; @@ -1443,7 +1443,7 @@ - (NSMutableDictionary *)blockchainInvitations { [context performBlockAndWait:^{ NSUInteger blockchainInvitationEntitiesCount = [DSBlockchainInvitationEntity countObjectsInContext:context matching:@"chain == %@", [self.chain chainEntityInContext:context]]; if (blockchainInvitationEntitiesCount != keyChainDictionary.count) { - DSLog(@"Unmatching blockchain invitations count"); + DSLog(@"[%@] Unmatching blockchain invitations count", self.chain.name); } DSBlockchainInvitationEntity *blockchainInvitationEntity = [DSBlockchainInvitationEntity anyObjectInContext:context matching:@"blockchainIdentity.uniqueID == %@", uint256_data([dsutxo_data(blockchainInvitationLockedOutpoint) SHA256_2])]; DSBlockchainInvitation *blockchainInvitation = nil; From 26f18c8b7e3b452998bde7f9cb4f2f180f18085a Mon Sep 17 00:00:00 2001 From: pankcuf Date: Fri, 17 Nov 2023 19:37:52 +0700 Subject: [PATCH 31/32] fix: cleanup callbacks when stopping chain --- .../Managers/Chain Managers/DSChainManager.m | 2 + .../Chain Managers/DSMasternodeManager.h | 1 + .../Chain Managers/DSMasternodeManager.m | 68 +++-- .../Managers/Chain Managers/DSPeerManager.m | 13 +- .../Masternode/DSMasternodeListService.h | 1 + .../Masternode/DSMasternodeListService.m | 89 +++--- DashSync/shared/Models/Network/DSPeer.m | 280 ++++++++++-------- Example/Podfile.lock | 4 +- 8 files changed, 263 insertions(+), 195 deletions(-) diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m index bec1e9000..18830a575 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSChainManager.m @@ -474,6 +474,8 @@ - (void)startSync { } - (void)stopSync { + DSLog(@"[%@] stopSync (chain switch)", self.chain.name); + [self.masternodeManager stopSync]; [self.peerManager disconnect:DSDisconnectReason_ChainSwitch]; self.syncPhase = DSChainSyncPhase_Offline; } diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.h b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.h index 6f931d3c0..0af7fe899 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.h +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.h @@ -91,6 +91,7 @@ NS_ASSUME_NONNULL_BEGIN - (BOOL)saveCLSignature:(NSData *)blockHashData signatureData:(NSData *)signatureData; - (void)startSync; +- (void)stopSync; - (BOOL)requestMasternodeListForBlockHeight:(uint32_t)blockHeight error:(NSError *_Nullable *_Nullable)error; - (BOOL)requestMasternodeListForBlockHash:(UInt256)blockHash; diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m index 363b6b350..dca4860ca 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSMasternodeManager.m @@ -64,7 +64,8 @@ @interface DSMasternodeManager () @property (nonatomic, assign) uint32_t rotatedQuorumsActivationHeight; @property (nonatomic, strong) dispatch_group_t processingGroup; @property (nonatomic, strong) dispatch_queue_t processingQueue; - +@property (nonatomic, strong) dispatch_source_t masternodeListTimer; +@property (nonatomic) BOOL isSyncing; @end @@ -348,9 +349,21 @@ - (DSMasternodeList *)masternodeListBeforeBlockHash:(UInt256)blockHash { // MARK: - Requesting Masternode List - (void)startSync { + DSLog(@"[%@] [DSMasternodeManager] startSync", self.chain.name); + self.isSyncing = YES; [self getRecentMasternodeList]; } +- (void)stopSync { + DSLog(@"[%@] [DSMasternodeManager] stopSync", self.chain.name); + self.isSyncing = NO; + [self cancelMasternodeListTimer]; + if (self.chain.isRotatedQuorumsPresented) { + [self.quorumRotationService stop]; + } + [self.masternodeListDiffService stop]; +} + - (void)getRecentMasternodeList { DSLog(@"[%@] getRecentMasternodeList at tip", self.chain.name); [self.masternodeListDiffService getRecentMasternodeList]; @@ -363,14 +376,29 @@ - (void)getRecentMasternodeList { // the safety delay checks to see if this was called in the last n seconds. - (void)getCurrentMasternodeListWithSafetyDelay:(uint32_t)safetyDelay { self.timeIntervalForMasternodeRetrievalSafetyDelay = [[NSDate date] timeIntervalSince1970]; - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(safetyDelay * NSEC_PER_SEC)), self.chain.networkingQueue, ^{ - NSTimeInterval timeElapsed = [[NSDate date] timeIntervalSince1970] - self.timeIntervalForMasternodeRetrievalSafetyDelay; - if (timeElapsed > safetyDelay) { - [self getRecentMasternodeList]; + [self cancelMasternodeListTimer]; + @synchronized (self) { + self.masternodeListTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.chain.networkingQueue); + if (self.masternodeListTimer) { + dispatch_source_set_timer(self.masternodeListTimer, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(safetyDelay * NSEC_PER_SEC)), DISPATCH_TIME_FOREVER, 1ull * NSEC_PER_SEC); + dispatch_source_set_event_handler(self.masternodeListTimer, ^{ + NSTimeInterval timeElapsed = [[NSDate date] timeIntervalSince1970] - self.timeIntervalForMasternodeRetrievalSafetyDelay; + if (timeElapsed > safetyDelay) { + [self getRecentMasternodeList]; + } + }); + dispatch_resume(self.masternodeListTimer); } - }); + } +} +- (void)cancelMasternodeListTimer { + @synchronized (self) { + if (self.masternodeListTimer) { + dispatch_source_cancel(self.masternodeListTimer); + self.masternodeListTimer = nil; + } + } } - - (void)getMasternodeListsForBlockHashes:(NSOrderedSet *)blockHashes { [self.masternodeListDiffService populateRetrievalQueueWithBlockHashes:blockHashes]; } @@ -554,10 +582,13 @@ - (void)processMasternodeListDiffResult:(DSMnDiffProcessingResult *)result forPe DSLog(@"[%@] •••• processMasternodeListDiffResult: rotated quorums are presented at height %u: %@, so we'll switch into consuming qrinfo", self.chain.name, masternodeListBlockHeight, uint256_hex(masternodeListBlockHash)); self.chain.isRotatedQuorumsPresented = YES; self.rotatedQuorumsActivationHeight = masternodeListBlockHeight; - [self.quorumRotationService addToRetrievalQueue:masternodeListBlockHashData]; - [self.quorumRotationService dequeueMasternodeListRequest]; + if (self.isSyncing) { + [self.quorumRotationService addToRetrievalQueue:masternodeListBlockHashData]; + [self.quorumRotationService dequeueMasternodeListRequest]; + } } - [self.masternodeListDiffService updateAfterProcessingMasternodeListWithBlockHash:masternodeListBlockHashData fromPeer:peer]; + if (self.isSyncing) + [self.masternodeListDiffService updateAfterProcessingMasternodeListWithBlockHash:masternodeListBlockHashData fromPeer:peer]; completion(); }]; } @@ -623,31 +654,26 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH4C skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH4C count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH4C]) { -// DSLog(@"••• updateStoreWithMasternodeList (h-4c): %u: %@ (%@)", masternodeListAtH4C.height, uint256_hex(blockHashAtH4C), uint256_reverse_hex(blockHashAtH4C)); [self updateStoreWithProcessingResult:masternodeListAtH4C result:mnListDiffResultAtH4C completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH3C skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH3C count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH3C]) { -// DSLog(@"••• updateStoreWithMasternodeList (h-3c): %u: %@ (%@)", masternodeListAtH3C.height, uint256_hex(blockHashAtH3C), uint256_reverse_hex(blockHashAtH3C)); [self updateStoreWithProcessingResult:masternodeListAtH3C result:mnListDiffResultAtH3C completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH2C skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH2C count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH2C]) { -// DSLog(@"••• updateStoreWithMasternodeList (h-2c): %u: %@ (%@)", masternodeListAtH2C.height, uint256_hex(blockHashAtH2C), uint256_reverse_hex(blockHashAtH2C)); [self updateStoreWithProcessingResult:masternodeListAtH2C result:mnListDiffResultAtH2C completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtHC skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtHC count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtHC]) { -// DSLog(@"••• updateStoreWithMasternodeList (h-c): %u: %@ (%@)", masternodeListAtHC.height, uint256_hex(blockHashAtHC), uint256_reverse_hex(blockHashAtHC)); [self updateStoreWithProcessingResult:masternodeListAtHC result:mnListDiffResultAtHC completion:^(NSError *error) {}]; } if (![self.quorumRotationService shouldProcessDiffResult:mnListDiffResultAtH skipPresenceInRetrieval:YES]) { [self.quorumRotationService issueWithMasternodeListFromPeer:peer]; } else if (![missingMasternodeListsAtH count] || ![masternodeListQueriesNeedingQuorumsValidated containsObject:blockHashDataAtH]) { -// DSLog(@"••• updateStoreWithMasternodeList (h): %u: %@ (%@)", masternodeListAtH.height, uint256_hex(blockHashAtH), uint256_reverse_hex(blockHashAtH)); [self updateStoreWithProcessingResult:masternodeListAtH result:mnListDiffResultAtH completion:^(NSError *error) {}]; } @@ -664,7 +690,6 @@ - (void)processQRInfoResult:(DSQRInfoProcessingResult *)result forPeer:(DSPeer * [self.store.masternodeListQueriesNeedingQuorumsValidated removeObject:blockHashDataAtTip]; } } -// DSLog(@"••• updateStoreWithMasternodeList (tip): %u: %@ (%@)", masternodeListAtTip.height, uint256_hex(blockHashAtTip), uint256_reverse_hex(blockHashAtTip)); [self updateStoreWithProcessingResult:masternodeListAtTip result:mnListDiffResultAtTip completion:^(NSError *error) {}]; [self.quorumRotationService updateAfterProcessingMasternodeListWithBlockHash:blockHashDataAtTip fromPeer:peer]; } @@ -698,7 +723,8 @@ - (void)processMissingMasternodeLists:(NSOrderedSet *)neededMissingMasternodeLis self.store.masternodeListAwaitingQuorumValidation = masternodeList; NSMutableOrderedSet *neededMasternodeLists = [neededMissingMasternodeLists mutableCopy]; [neededMasternodeLists addObject:masternodeListBlockHashData]; //also get the current one again - [self getMasternodeListsForBlockHashes:neededMasternodeLists]; + if (self.isSyncing) + [self getMasternodeListsForBlockHashes:neededMasternodeLists]; } - (void)updateStoreWithProcessingResult:(DSMasternodeList *)masternodeList result:(DSMnDiffProcessingResult *)result completion:(void (^)(NSError *error))completion { if (uint256_eq(self.store.masternodeListAwaitingQuorumValidation.blockHash, masternodeList.blockHash)) { @@ -714,9 +740,11 @@ - (void)updateStoreWithProcessingResult:(DSMasternodeList *)masternodeList resul return; } [self wipeMasternodeInfo]; - dispatch_async(self.chain.networkingQueue, ^{ - [self getRecentMasternodeList]; - }); + if (self.isSyncing) { + dispatch_async(self.chain.networkingQueue, ^{ + [self getRecentMasternodeList]; + }); + } }]; } diff --git a/DashSync/shared/Models/Managers/Chain Managers/DSPeerManager.m b/DashSync/shared/Models/Managers/Chain Managers/DSPeerManager.m index 7b54d5808..1a8a53a8c 100644 --- a/DashSync/shared/Models/Managers/Chain Managers/DSPeerManager.m +++ b/DashSync/shared/Models/Managers/Chain Managers/DSPeerManager.m @@ -1012,15 +1012,16 @@ - (void)peer:(DSPeer *)peer disconnectedWithError:(NSError *)error { [self.managedObjectContext deleteObject:obj]; } }]; - DSLog(@"[%@: %@:%d] [DSPeerManager] disconnectedWithError: max connect failures exceeded", self.chain.name, peer.host, peer.port); @synchronized(self) { _peers = nil; } - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:DSChainManagerSyncFailedNotification - object:nil - userInfo:(error) ? @{@"error": error, DSChainManagerNotificationChainKey: self.chain} : @{DSChainManagerNotificationChainKey: self.chain}]; - }); + if (_desiredState != DSPeerManagerDesiredState_Disconnected) + DSLog(@"[%@: %@:%d] [DSPeerManager] disconnectedWithError: max connect failures exceeded", self.chain.name, peer.host, peer.port); + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:DSChainManagerSyncFailedNotification + object:nil + userInfo:(error) ? @{@"error": error, DSChainManagerNotificationChainKey: self.chain} : @{DSChainManagerNotificationChainKey: self.chain}]; + }); } else if (self.connectFailures < MAX_CONNECT_FAILURES) { dispatch_async(dispatch_get_main_queue(), ^{ #if TARGET_OS_IOS diff --git a/DashSync/shared/Models/Masternode/DSMasternodeListService.h b/DashSync/shared/Models/Masternode/DSMasternodeListService.h index 2e5d56a9d..ae1c225f8 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeListService.h +++ b/DashSync/shared/Models/Masternode/DSMasternodeListService.h @@ -64,6 +64,7 @@ typedef NS_ENUM(NSUInteger, DSMasternodeListRequestMode) { - (void)populateRetrievalQueueWithBlockHashes:(NSOrderedSet *)blockHashes; - (void)getRecentMasternodeList; - (void)dequeueMasternodeListRequest; +- (void)stop; - (void)addToRetrievalQueue:(NSData *)masternodeBlockHashData; - (void)addToRetrievalQueueArray:(NSArray *)masternodeBlockHashDataArray; diff --git a/DashSync/shared/Models/Masternode/DSMasternodeListService.m b/DashSync/shared/Models/Masternode/DSMasternodeListService.m index 70dfa6cd2..ef62bf210 100644 --- a/DashSync/shared/Models/Masternode/DSMasternodeListService.m +++ b/DashSync/shared/Models/Masternode/DSMasternodeListService.m @@ -37,6 +37,7 @@ @interface DSMasternodeListService () @property (nonatomic, assign) NSUInteger retrievalQueueMaxAmount; // List: list of block ranges baseBlockHash + blockHash @property (nonatomic, strong) NSMutableSet *requestsInRetrieval; +@property (nonatomic, strong) dispatch_source_t timeoutTimer; @end @@ -56,39 +57,49 @@ - (instancetype)initWithChain:(DSChain *)chain store:(DSMasternodeListStore *)st } - (void)startTimeOutObserver { - __block NSSet *requestsInRetrieval; - __block NSUInteger masternodeListCount; - __block uint16_t timeOutObserverTry; - dispatch_time_t timeout; + [self cancelTimeOutObserver]; @synchronized (self) { - requestsInRetrieval = [self.requestsInRetrieval copy]; - masternodeListCount = [self.store knownMasternodeListsCount]; + NSSet *requestsInRetrieval = [self.requestsInRetrieval copy]; + NSUInteger masternodeListCount = [self.store knownMasternodeListsCount]; self.timeOutObserverTry++; - timeOutObserverTry = self.timeOutObserverTry; - timeout = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * (self.timedOutAttempt + 1) * NSEC_PER_SEC)); + uint16_t timeOutObserverTry = self.timeOutObserverTry; + dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * (self.timedOutAttempt + 1) * NSEC_PER_SEC)); + self.timeoutTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.chain.networkingQueue); + if (self.timeoutTimer) { + dispatch_source_set_timer(self.timeoutTimer, timeout, DISPATCH_TIME_FOREVER, 1ull * NSEC_PER_SEC); + dispatch_source_set_event_handler(self.timeoutTimer, ^{ + @synchronized (self) { + if (!self.retrievalQueueMaxAmount || self.timeOutObserverTry != timeOutObserverTry) { + return; + } + NSSet *requestsInRetrieval2 = [self.requestsInRetrieval copy]; + NSMutableSet *leftToGet = [requestsInRetrieval mutableCopy]; + [leftToGet intersectSet:requestsInRetrieval2]; + if ((masternodeListCount == [self.store knownMasternodeListsCount]) && [requestsInRetrieval isEqualToSet:leftToGet]) { + DSLog(@"[%@] %@ TimedOut", self.chain.name, self); + self.timedOutAttempt++; + [self disconnectFromDownloadPeer]; + [self cleanRequestsInRetrieval]; + [self dequeueMasternodeListRequest]; + } else { + [self startTimeOutObserver]; + } + } + }); + dispatch_resume(self.timeoutTimer); + } } - dispatch_after(timeout, self.chain.networkingQueue, ^{ - __block NSSet *requestsInRetrieval2; - @synchronized (self) { - if (!self.retrievalQueueMaxAmount || self.timeOutObserverTry != timeOutObserverTry) { - return; - } - requestsInRetrieval2 = [self.requestsInRetrieval copy]; - // Removes from the receiving set each object that isn’t a member of another given set. - NSMutableSet *leftToGet = [requestsInRetrieval mutableCopy]; - [leftToGet intersectSet:requestsInRetrieval2]; - if ((masternodeListCount == [self.store knownMasternodeListsCount]) && [requestsInRetrieval isEqualToSet:leftToGet]) { - DSLog(@"[%@] TimedOut", self.chain.name); - self.timedOutAttempt++; - [self disconnectFromDownloadPeer]; - [self cleanRequestsInRetrieval]; - [self dequeueMasternodeListRequest]; - } else { - [self startTimeOutObserver]; - } +} + +- (void)cancelTimeOutObserver { + @synchronized (self) { + if (self.timeoutTimer) { + dispatch_source_cancel(self.timeoutTimer); + self.timeoutTimer = nil; } - }); + } } + - (NSString *)logListSet:(NSOrderedSet *)list { NSString *str = @"\n"; for (NSData *blockHashData in list) { @@ -115,6 +126,11 @@ - (void)dequeueMasternodeListRequest { }]; } +- (void)stop { + [self cancelTimeOutObserver]; + [self cleanAllLists]; +} + - (void)getRecentMasternodeList { @synchronized(self.retrievalQueue) { DSMerkleBlock *merkleBlock = [self.chain blockFromChainTip:0]; @@ -207,7 +223,7 @@ - (BOOL)shouldProcessDiffResult:(DSMnDiffProcessingResult *)diffResult skipPrese } BOOL isValid = [diffResult isTotallyValid]; if (!isValid) { - DSLog(@"[%@] ••• Invalid result: %@", self.chain.name, diffResult.debugDescription); + DSLog(@"[%@] Invalid diff result: %@", self.chain.name, diffResult.debugDescription); } return isValid; @@ -243,7 +259,6 @@ - (void)removeFromRetrievalQueue:(NSData *)masternodeBlockHashData { } - (void)cleanRequestsInRetrieval { - DSLog(@"[%@] •••• cleanRequestsInRetrieval: %@", self.chain.name, self); [self.requestsInRetrieval removeAllObjects]; } @@ -319,13 +334,13 @@ - (BOOL)removeRequestInRetrievalForBaseBlockHash:(UInt256)baseBlockHash blockHas @synchronized (self.requestsInRetrieval) { requestsInRetrieval = [self.requestsInRetrieval copy]; } - NSMutableArray *requestsInRetrievalStrings = [NSMutableArray array]; - for (DSMasternodeListRequest *requestInRetrieval in requestsInRetrieval) { - [requestsInRetrievalStrings addObject:[requestInRetrieval logWithBlockHeightLookup:^uint32_t(UInt256 blockHash) { - return [self.store heightForBlockHash:blockHash]; - }]]; - } - DSLog(@"[%@] •••• A masternode list (%@ .. %@) was received that is not set to be retrieved (%@)", self.chain.name, uint256_hex(baseBlockHash), uint256_hex(blockHash), [requestsInRetrievalStrings componentsJoinedByString:@", "]); + NSMutableArray *requestsInRetrievalStrings = [NSMutableArray array]; + for (DSMasternodeListRequest *requestInRetrieval in requestsInRetrieval) { + [requestsInRetrievalStrings addObject:[requestInRetrieval logWithBlockHeightLookup:^uint32_t(UInt256 blockHash) { + return [self.store heightForBlockHash:blockHash]; + }]]; + } + DSLog(@"[%@] A masternode list (%@ .. %@) was received that is not set to be retrieved (%@)", self.chain.name, uint256_hex(baseBlockHash), uint256_hex(blockHash), [requestsInRetrievalStrings componentsJoinedByString:@", "]); #endif /* DEBUG */ return NO; } diff --git a/DashSync/shared/Models/Network/DSPeer.m b/DashSync/shared/Models/Network/DSPeer.m index 6458092f5..1f7f9ee61 100644 --- a/DashSync/shared/Models/Network/DSPeer.m +++ b/DashSync/shared/Models/Network/DSPeer.m @@ -81,17 +81,19 @@ #endif #define MESSAGE_LOGGING (1 & DEBUG) -#define MESSAGE_CONTENT_LOGGING (1 & DEBUG) -#define MESSAGE_IN_DEPTH_TX_LOGGING (1 & DEBUG) +#define MESSAGE_CONTENT_LOGGING (0 & DEBUG) +#define MESSAGE_IN_DEPTH_TX_LOGGING (0 & DEBUG) #define HEADER_LENGTH 24 #define MAX_MSG_LENGTH 0x02000000 #define CONNECT_TIMEOUT 3.0 -#define MEMPOOL_TIMEOUT 2.0 +#define MEMPOOL_TIMEOUT 3.0 #define LOCK(lock) dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); #define UNLOCK(lock) dispatch_semaphore_signal(lock); +#define DSLogWithLocation(obj, fmt, ...) DSLog(@"%@ " fmt, [obj debugLocation], ##__VA_ARGS__) +#define DSLogPrivateWithLocation(obj, fmt, ...) DSLogPrivate(@"%@ " fmt, [obj debugLocation], ##__VA_ARGS__) @interface DSPeer () @@ -124,6 +126,7 @@ @interface DSPeer () @property (nonatomic, assign) uint64_t receivedOrphanCount; @property (nonatomic, assign) NSTimeInterval mempoolRequestTime; @property (nonatomic, strong) dispatch_semaphore_t outputBufferSemaphore; +@property (strong, nonatomic) dispatch_source_t mempoolTimer; @end @@ -207,6 +210,10 @@ - (NSString *)location { return [NSString stringWithFormat:@"%@:%d", self.host, self.port]; } +- (NSString *)debugLocation { + return [NSString stringWithFormat:@"[%@: %@]", self.chain.name, self.location]; +} + - (NSString *)host { char s[INET6_ADDRSTRLEN]; @@ -223,7 +230,7 @@ - (void)connect { if (!self.reachability) self.reachability = [DSReachabilityManager sharedManager]; if (self.reachability.networkReachabilityStatus == DSReachabilityStatusNotReachable) { // delay connect until network is reachable - DSLog(@"[%@: %@:%d] not reachable, waiting...", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"not reachable, waiting..."); dispatch_async(dispatch_get_main_queue(), ^{ if (!self.reachabilityObserver) { self.reachabilityObserver = @@ -281,8 +288,7 @@ - (void)connect { dispatch_async(dispatch_queue_create(label.UTF8String, NULL), ^{ CFReadStreamRef readStream = NULL; CFWriteStreamRef writeStream = NULL; - - DSLog(@"[%@: %@:%d] connecting", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"connecting"); CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)self.host, self.port, &readStream, &writeStream); self.inputStream = CFBridgingRelease(readStream); self.outputStream = CFBridgingRelease(writeStream); @@ -308,13 +314,8 @@ - (void)disconnect { } - (void)disconnectWithError:(NSError *)error { - if (_status == DSPeerStatus_Disconnected) return; - if (!error) { - DSLog(@"[%@: %@:%d] Disconnected from peer (%@ protocol %d) with no error", self.chain.name, self.host, self.port, self.useragent, self.version); - } else { - DSLog(@"[%@: %@:%d] Disconnected from peer (%@ protocol %d) with error %@", self.chain.name, self.host, self.port, self.useragent, self.version, error); - } + DSLogWithLocation(self, @"Disconnected from peer (%@ protocol %d) with error: %@", self.useragent, self.version, error ? error : @"(None)"); [NSObject cancelPreviousPerformRequestsWithTarget:self]; // cancel connect timeout _status = DSPeerStatus_Disconnected; @@ -335,7 +336,8 @@ - (void)disconnectWithError:(NSError *)error { ((void (^)(BOOL))self.pongHandlers[0])(NO); [self.pongHandlers removeObjectAtIndex:0]; } - if (self.mempoolTransactionCompletion) self.mempoolTransactionCompletion(NO, YES, YES); + if (self.mempoolTransactionCompletion) + self.mempoolTransactionCompletion(NO, YES, YES); self.mempoolTransactionCompletion = nil; [self dispatchAsyncInDelegateQueue:^{ [self.peerDelegate peer:self disconnectedWithError:error]; @@ -353,7 +355,7 @@ - (void)error:(NSString *)message, ... NS_FORMAT_FUNCTION(1, 2) { - (void)didConnect { if (self.status != DSPeerStatus_Connecting || !self.sentVerack || !self.gotVerack) return; - DSLog(@"[%@: %@:%d] handshake completed %@", self.chain.name, self.host, self.port, (self.peerDelegate.downloadPeer == self) ? @"(download peer)" : @""); + DSLogWithLocation(self, @"handshake completed %@", (self.peerDelegate.downloadPeer == self) ? @"(download peer)" : @""); [NSObject cancelPreviousPerformRequestsWithTarget:self]; // cancel pending handshake timeout _status = DSPeerStatus_Connected; @@ -380,7 +382,7 @@ - (void)sendRequest:(DSMessageRequest *)request { - (void)sendMessage:(NSData *)message type:(NSString *)type { if (message.length > MAX_MSG_LENGTH) { - DSLog(@"[%@: %@:%d] failed to send %@, length %u is too long", self.chain.name, self.host, self.port, type, (int)message.length); + DSLogWithLocation(self, @"failed to send %@, length %u is too long", type, (int)message.length); #if DEBUG abort(); #endif @@ -390,22 +392,22 @@ - (void)sendMessage:(NSData *)message type:(NSString *)type { CFRunLoopPerformBlock([self.runLoop getCFRunLoop], kCFRunLoopCommonModes, ^{ #if MESSAGE_LOGGING if (![type isEqualToString:MSG_GETDATA] && ![type isEqualToString:MSG_VERSION] && ![type isEqualToString:MSG_GETBLOCKS]) { //we log this somewhere else for better accuracy of what data is being got - DSLog(@"[%@: %@:%d] %@sending %@", self.chain.name, self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", type); + DSLogWithLocation(self, @"%@sending %@", self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", type); #if MESSAGE_IN_DEPTH_TX_LOGGING if ([type isEqualToString:@"ix"] || [type isEqualToString:@"tx"]) { DSTransaction *transactionBeingSent = [DSTransaction transactionWithMessage:message onChain:self.chain]; #if DEBUG - DSLogPrivate(@"[%@: %@:%d] transaction %@", self.chain.name, self.host, self.port, transactionBeingSent.longDescription); + DSLogPrivateWithLocation(self, @"transaction %@", transactionBeingSent.longDescription); #else - DSLog(@"[%@: %@:%d] transaction %@", self.chain.name, self.host, self.port, @""); + DSLogWithLocation(self, @"transaction %@", @""); #endif } #endif #if MESSAGE_CONTENT_LOGGING #if DEBUG - DSLogPrivate(@"[%@: %@:%d] sending data (%lu bytes) %@", self.chain.name, self.host, self.port, (unsigned long)message.length, message.hexString); + DSLogPrivateWithLocation(self, @"sending data (%lu bytes) %@", (unsigned long)message.length, message.hexString); #else - DSLog(@"[%@: %@:%d] sending data (%lu bytes) %@", self.chain.name, self.host, self.port, (unsigned long)message.length, @""); + DSLogWithLocation(self, @"sending data (%lu bytes) %@", (unsigned long)message.length, @""); #endif #endif } @@ -445,7 +447,7 @@ - (void)sendVersionMessage { self.pingStartTime = [NSDate timeIntervalSince1970]; #if MESSAGE_LOGGING - DSLog(@"[%@: %@:%d] %@sending version with protocol version %d user agent %@", self.chain.name, self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", self.chain.protocolVersion, agent); + DSLogWithLocation(self, @"%@sending version with protocol version %d user agent %@", self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", self.chain.protocolVersion, agent); #endif [self sendRequest:request]; } @@ -461,53 +463,76 @@ - (void)sendFilterloadMessage:(NSData *)filter { self.sentFilter = YES; } #if DEBUG - DSLogPrivate(@"[%@: %@:%d] Sending filter with fingerprint %@ to node %@", self.chain.name, self.host, self.port, [NSData dataWithUInt256:filter.SHA256].shortHexString, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @""); + DSLogPrivateWithLocation(self, @"Sending filter with fingerprint %@ to node %@", [NSData dataWithUInt256:filter.SHA256].shortHexString, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @""); #else - DSLog(@"[%@: %@:%d] Sending filter with fingerprint %@ to node %@", @"", self.chain.name, self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @""); + DSLogWithLocation(self, @"Sending filter with fingerprint %@ to node %@", @"", self.peerDelegate.downloadPeer == self ? @"(download peer) " : @""); #endif [self sendRequest:[DSFilterLoadRequest requestWithBloomFilterData:filter]]; } -- (void)mempoolTimeout { - DSLog(@"[%@: %@:%d] [DSPeer] mempool time out", self.chain.name, self.host, self.port); - __block MempoolCompletionBlock completion = self.mempoolTransactionCompletion; - [self sendPingMessageWithPongHandler:^(BOOL success) { - if (completion) { - completion(success, YES, NO); - } - }]; - self.mempoolTransactionCompletion = nil; -} +/** + This method sends a mempool message to the connected peer for information about transactions in the memory pool of a peer. + It is used to synchronize the local view of the peer's memory pool with the transactions known locally. + @param publishedTxHashes An array of transaction hashes that the client has knowledge of. These are used to update the internal list of known transaction hashes. + @param completion A completion block that is called when the mempool message processing is complete. This block is provided with three boolean arguments indicating various states of the transaction processing (e.g., if it was added, already known, or rejected). +*/ - (void)sendMempoolMessage:(NSArray *)publishedTxHashes completion:(MempoolCompletionBlock)completion { #if DEBUG - DSLogPrivate(@"[%@: %@:%d] sendMempoolMessage %@", self.chain.name, self.host, self.port, publishedTxHashes); + DSLogPrivateWithLocation(self, @"sendMempoolMessage %@", publishedTxHashes); #else - DSLog(@"[%@: %@:%d] sendMempoolMessage %@", self.chain.name, self.host, self.port, @""); + DSLogWithLocation(self, @"sendMempoolMessage %@", @""); #endif @synchronized (self.knownTxHashes) { [self.knownTxHashes addObjectsFromArray:publishedTxHashes]; } self.sentMempool = YES; - - if (completion) { - if (self.mempoolTransactionCompletion) { - [self dispatchAsyncInDelegateQueue:^{ - if (self->_status == DSPeerStatus_Connected) completion(NO, NO, NO); - }]; - } else { - self.mempoolTransactionCompletion = completion; - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MEMPOOL_TIMEOUT * NSEC_PER_SEC)), self.delegateQueue, ^{ - if ([NSDate timeIntervalSince1970] - self.mempoolRequestTime >= MEMPOOL_TIMEOUT) { - [self mempoolTimeout]; + [self cancelMempoolTimer]; + @synchronized (self) { + if (completion) { + if (self.mempoolTransactionCompletion) { + [self dispatchAsyncInDelegateQueue:^{ + if (self->_status == DSPeerStatus_Connected) completion(NO, NO, NO); + }]; + } else { + self.mempoolTransactionCompletion = completion; + self.mempoolTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.delegateQueue); + if (self.mempoolTimer) { + dispatch_source_set_timer(self.mempoolTimer, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MEMPOOL_TIMEOUT * NSEC_PER_SEC)), DISPATCH_TIME_FOREVER, 1ull * NSEC_PER_SEC); + dispatch_source_set_event_handler(self.mempoolTimer, ^{ + if ([NSDate timeIntervalSince1970] - self.mempoolRequestTime >= MEMPOOL_TIMEOUT) { + [self mempoolTimeout]; + } + }); + dispatch_resume(self.mempoolTimer); } - }); + } } } + self.mempoolRequestTime = [NSDate timeIntervalSince1970]; [self sendRequest:[DSMessageRequest requestWithType:MSG_MEMPOOL]]; } +- (void)cancelMempoolTimer { + @synchronized (self) { + if (self.mempoolTimer) { + dispatch_source_cancel(self.mempoolTimer); + self.mempoolTimer = nil; + } + } +} +- (void)mempoolTimeout { + DSLogWithLocation(self, @"[DSPeer] mempool time out"); + __block MempoolCompletionBlock completion = self.mempoolTransactionCompletion; + [self sendPingMessageWithPongHandler:^(BOOL success) { + if (completion) { + completion(success, YES, NO); + } + }]; + self.mempoolTransactionCompletion = nil; +} + // the standard blockchain download protocol works as follows (for SPV mode): // - local peer sends getblocks // - remote peer reponds with inv containing up to 500 block hashes @@ -551,16 +576,14 @@ - (void)sendGetblocksMessageWithLocators:(NSArray *)locators andHashStop:(UInt25 NSMutableArray *locatorHexes = [NSMutableArray arrayWithCapacity:[locators count]]; [locators enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { uint32_t knownHeight = [self.chain quickHeightForBlockHash:((NSData *)obj).UInt256]; - if (knownHeight == UINT32_MAX) { - [locatorHexes addObject:[NSString stringWithFormat:@"%@ (block height unknown)", ((NSData *)obj).reverse.hexString]]; - } else { - [locatorHexes addObject:[NSString stringWithFormat:@"%@ (block %d)", ((NSData *)obj).reverse.hexString, knownHeight]]; - } + [locatorHexes addObject:[NSString stringWithFormat:@"%@ (block height %@)", + ((NSData *)obj).reverse.hexString, + knownHeight == UINT32_MAX ? @"unknown" : @"%d", knownHeight]]; }]; #if DEBUG - DSLogPrivate(@"[%@: %@:%d] %@sending getblocks with locators %@", self.chain.name, self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", locatorHexes); + DSLogPrivateWithLocation(self, @"%@sending getblocks with locators %@", self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", locatorHexes); #else - DSLog(@"[%@: %@:%d] %@sending getblocks with locators %@", self.chain.name, self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", @""); + DSLogWithLocation(self, @"%@sending getblocks with locators %@", self.peerDelegate.downloadPeer == self ? @"(download peer) " : @"", @""); #endif //#if MESSAGE_CONTENT_LOGGING //#if DEBUG @@ -575,7 +598,7 @@ - (void)sendGetblocksMessageWithLocators:(NSArray *)locators andHashStop:(UInt25 } - (void)sendInvMessageForHashes:(NSArray *)invHashes ofType:(DSInvType)invType { - DSLogPrivate(@"[%@: %@:%d] sending inv message of type %@ hashes count %lu", self.chain.name, self.host, self.port, [self nameOfInvMessage:invType], (unsigned long)invHashes.count); + DSLogPrivateWithLocation(self, @"sending inv message of type %@ hashes count %lu", [self nameOfInvMessage:invType], invHashes.count); NSMutableOrderedSet *hashes = [NSMutableOrderedSet orderedSetWithArray:invHashes]; @synchronized (self.knownTxHashes) { [hashes minusOrderedSet:self.knownTxHashes]; @@ -628,9 +651,9 @@ - (void)sendGetdataMessageForTxHash:(UInt256)txHash { DSGetDataForTransactionHashRequest *request = [DSGetDataForTransactionHashRequest requestForTransactionHash:txHash]; #if MESSAGE_LOGGING #if DEBUG - DSLogPrivate(@"[%@: %@:%d] sending getdata for transaction %@", self.chain.name, self.host, self.port, uint256_hex(txHash)); + DSLogPrivateWithLocation(self, @"sending getdata for transaction %@", uint256_hex(txHash)); #else - DSLog(@"[%@: %@:%d] sending getdata for transaction %@", self.chain.name, self.host, self.port, @""); + DSLogWithLocation(self, @"sending getdata for transaction %@", @""); #endif #endif [self sendRequest:request]; @@ -638,11 +661,11 @@ - (void)sendGetdataMessageForTxHash:(UInt256)txHash { - (void)sendGetdataMessageWithTxHashes:(NSArray *)txHashes instantSendLockHashes:(NSArray *)instantSendLockHashes instantSendLockDHashes:(NSArray *)instantSendLockDHashes blockHashes:(NSArray *)blockHashes chainLockHashes:(NSArray *)chainLockHashes { if (!([[DSOptionsManager sharedInstance] syncType] & DSSyncType_GetsNewBlocks)) return; - if (txHashes.count + instantSendLockHashes.count + instantSendLockDHashes.count + blockHashes.count + chainLockHashes.count > MAX_GETDATA_HASHES) { // limit total hash count to MAX_GETDATA_HASHES - DSLog(@"[%@: %@:%d] couldn't send getdata, %u is too many items, max is %u", self.chain.name, self.host, self.port, - (int)txHashes.count + (int)instantSendLockHashes.count + (int)instantSendLockDHashes.count + (int)blockHashes.count + (int)chainLockHashes.count, MAX_GETDATA_HASHES); + NSUInteger totalCount = txHashes.count + instantSendLockHashes.count + instantSendLockDHashes.count + blockHashes.count + chainLockHashes.count; + if (totalCount > MAX_GETDATA_HASHES) { // limit total hash count to MAX_GETDATA_HASHES + DSLogWithLocation(self, @"couldn't send getdata, %u is too many items, max is %u", totalCount, MAX_GETDATA_HASHES); return; - } else if (txHashes.count + instantSendLockHashes.count + instantSendLockDHashes.count + blockHashes.count + chainLockHashes.count == 0) + } else if (totalCount == 0) return; DSGetDataForTransactionHashesRequest *request = [DSGetDataForTransactionHashesRequest requestForTransactionHashes:txHashes @@ -652,23 +675,22 @@ - (void)sendGetdataMessageWithTxHashes:(NSArray *)txHashes instantSendLockHashes chainLockHashes:chainLockHashes]; self.sentGetdataTxBlocks = YES; #if MESSAGE_LOGGING - DSLog(@"[%@: %@:%d] sending getdata (transactions and blocks)", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"sending getdata (transactions and blocks)"); #endif [self sendRequest:request]; } - (void)sendGovernanceRequest:(DSGovernanceHashesRequest *)request { if (request.hashes.count > MAX_GETDATA_HASHES) { // limit total hash count to MAX_GETDATA_HASHES - DSLog(@"[%@: %@:%d] couldn't send governance votes getdata, %u is too many items, max is %u", self.chain.name, self.host, self.port, - (int)request.hashes.count, MAX_GETDATA_HASHES); + DSLogWithLocation(self, @"couldn't send governance votes getdata, %u is too many items, max is %u", request.hashes.count, MAX_GETDATA_HASHES); return; } else if (request.hashes.count == 0) { - DSLog(@"[%@: %@:%d] couldn't send governance getdata, there is no items", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"couldn't send governance getdata, there is no items"); return; } #if MESSAGE_LOGGING - DSLog(@"[%@: %@:%d] sending getdata (%@)", self.chain.name, self.host, self.port, request.description); + DSLogWithLocation(self, @"sending getdata (%@)", request.description); #endif // Not used @@ -687,7 +709,7 @@ - (void)sendPingMessageWithPongHandler:(void (^)(BOOL success))pongHandler { self.pingStartTime = [NSDate timeIntervalSince1970]; #if MESSAGE_LOGGING - DSLog(@"[%@: %@:%d] sending ping", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"sending ping"); #endif [self dispatchAsyncInDelegateQueue:^{ [self sendRequest:[DSPingRequest requestWithLocalNonce:localNonce]]; @@ -700,7 +722,7 @@ - (void)rerequestBlocksFrom:(UInt256)blockHash { if (i != NSNotFound) { [self.knownBlockHashes removeObjectsInRange:NSMakeRange(0, i)]; - DSLog(@"[%@: %@:%d] re-requesting %u blocks", self.chain.name, self.host, self.port, (int)self.knownBlockHashes.count); + DSLogWithLocation(self, @"re-requesting %u blocks", self.knownBlockHashes.count); [self sendGetdataMessageWithTxHashes:nil instantSendLockHashes:nil instantSendLockDHashes:nil blockHashes:self.knownBlockHashes.array chainLockHashes:nil]; } } @@ -716,13 +738,13 @@ - (void)sendGetSporks { // Governance Synchronization for Votes and Objects - (void)sendGovernanceSyncRequest:(DSGovernanceSyncRequest *)request { // Make sure we aren't in a governance sync process - DSLog(@"[%@: %@:%d] Requesting Governance Object Vote Hashes", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"Requesting Governance Object Vote Hashes"); if (self.governanceRequestState != DSGovernanceRequestState_None) { DSLog(@"[%@: %@:%d] Requesting Governance Object Hashes out of resting state", self.chain.name, self.host, self.port); return; } - DSLog(@"[%@: %@:%d] Requesting %@", self.chain.name, self.host, self.port, request.description); + DSLogWithLocation(self, @"Requesting %@", request.description); self.governanceRequestState = request.state; [self sendRequest:request]; @@ -731,7 +753,7 @@ - (void)sendGovernanceSyncRequest:(DSGovernanceSyncRequest *)request { //we aren't afraid of coming back here within 5 seconds because a peer can only sendGovSync once every 3 hours dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ if (self.governanceRequestState == DSGovernanceRequestState_GovernanceObjectHashes) { - DSLog(@"[%@: %@:%d] Peer ignored request for governance object hashes", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"Peer ignored request for governance object hashes"); [self.governanceDelegate peer:self ignoredGovernanceSync:DSGovernanceRequestState_GovernanceObjectHashes]; } }); @@ -752,7 +774,7 @@ - (void)sendGovObject:(DSGovernanceObject *)governanceObject { - (void)acceptMessage:(NSData *)message type:(NSString *)type { #if MESSAGE_LOGGING if (![type isEqualToString:MSG_INV] && ![type isEqualToString:MSG_GOVOBJVOTE] && ![type isEqualToString:MSG_MERKLEBLOCK]) { - DSLog(@"[%@: %@:%d] accept message %@", self.chain.name, self.host, self.port, type); + DSLogWithLocation(self, @"accept message %@", type); } #endif if (self.currentBlock && (!([MSG_TX isEqual:type] || [MSG_IX isEqual:type] || [MSG_ISLOCK isEqual:type]))) { @@ -839,7 +861,7 @@ - (void)acceptMessage:(NSData *)message type:(NSString *)type { [self acceptDarksendTransactionMessage:message]; #if DROP_MESSAGE_LOGGING else { - DSLog(@"[%@: %@:%d] dropping %@, len:%u, not implemented", self.chain.name, self.host, self.port, type, (int)message.length); + DSLogWithLocation(self, @"dropping %@, len:%u, not implemented", type, message.length); } #endif } @@ -862,13 +884,13 @@ - (void)acceptVersionMessage:(NSData *)message { if (self.version < self.chain.minProtocolVersion || self.version > self.chain.protocolVersion) { #if MESSAGE_LOGGING - DSLog(@"[%@: %@:%d] protocol version %u not supported, valid versions are: [%u, %u], useragent:\"%@\", ", self.chain.name, self.host, self.port, self.version, self.chain.minProtocolVersion, self.chain.protocolVersion, self.useragent); + DSLogWithLocation(self, @"protocol version %u not supported, valid versions are: [%u, %u], useragent:\"%@\", ", self.version, self.chain.minProtocolVersion, self.chain.protocolVersion, self.useragent); #endif [self error:@"protocol version %u not supported", self.version]; return; } else { #if MESSAGE_LOGGING - DSLog(@"[%@: %@:%d] got version %u, useragent:\"%@\"", self.chain.name, self.host, self.port, self.version, self.useragent); + DSLogWithLocation(self, @"got version %u, useragent:\"%@\"", self.version, self.useragent); #endif } [self sendVerackMessage]; @@ -876,14 +898,14 @@ - (void)acceptVersionMessage:(NSData *)message { - (void)acceptVerackMessage:(NSData *)message { if (self.gotVerack) { - DSLog(@"[%@: %@:%d] got unexpected verack", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"got unexpected verack"); return; } _pingTime = [NSDate timeIntervalSince1970] - self.pingStartTime; // use verack time as initial ping time self.pingStartTime = 0; #if MESSAGE_LOGGING - DSLog(@"[%@: %@:%d] got verack in %fs", self.chain.name, self.host, self.port, self.pingTime); + DSLogWithLocation(self, @"got verack in %fs", self.pingTime); #endif self.gotVerack = YES; [self didConnect]; @@ -892,7 +914,7 @@ - (void)acceptVerackMessage:(NSData *)message { // TODO: relay addresses - (void)acceptAddrMessage:(NSData *)message { if (message.length > 0 && [message UInt8AtOffset:0] == 0) { - DSLog(@"[%@: %@:%d] got addr with 0 addresses", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"got addr with 0 addresses"); return; } else if (message.length < 5) { [self error:@"malformed addr message, length %u is too short", (int)message.length]; @@ -906,14 +928,14 @@ - (void)acceptAddrMessage:(NSData *)message { NSMutableArray *peers = [NSMutableArray array]; if (count > 1000) { - DSLog(@"[%@: %@:%d] dropping addr message, %u is too many addresses (max 1000)", self.chain.name, self.host, self.port, (int)count); + DSLogWithLocation(self, @"dropping addr message, %u is too many addresses (max 1000)", count); return; } else if (message.length < l.unsignedIntegerValue + count * 30) { [self error:@"malformed addr message, length is %u, should be %u for %u addresses", (int)message.length, (int)(l.unsignedIntegerValue + count * 30), (int)count]; return; } else - DSLog(@"[%@: %@:%d] got addr with %u addresses", self.chain.name, self.host, self.port, (int)count); + DSLogWithLocation(self, @"got addr with %u addresses", count); for (NSUInteger off = l.unsignedIntegerValue; off < l.unsignedIntegerValue + 30 * count; off += 30) { NSTimeInterval timestamp = [message UInt32AtOffset:off]; @@ -942,7 +964,7 @@ - (void)acceptAddrMessage:(NSData *)message { } - (void)acceptAddrV2Message:(NSData *)message { - DSLog(@"[%@: %@:%d] sendaddrv2, len:%u, (not implemented)", self.chain.name, self.host, self.port, (int)message.length); + DSLogWithLocation(self, @"sendaddrv2, len:%u, (not implemented)", message.length); } - (NSString *)nameOfInvMessage:(DSInvType)type { @@ -1015,16 +1037,15 @@ - (void)acceptInvMessage:(NSData *)message { (int)(((l.unsignedIntegerValue == 0) ? 1 : l.unsignedIntegerValue) + count * 36), (int)count]; return; } else if (count > MAX_GETDATA_HASHES) { - DSLog(@"[%@: %@:%d] dropping inv message, %u is too many items, max is %u", self.chain.name, self.host, self.port, (int)count, - MAX_GETDATA_HASHES); + DSLogWithLocation(self, @"dropping inv message, %u is too many items, max is %u", count, MAX_GETDATA_HASHES); return; } #if MESSAGE_LOGGING if (count == 0) { - DSLog(@"[%@: %@:%d] Got empty Inv message", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"Got empty Inv message"); } if (count > 0 && ([message UInt32AtOffset:l.unsignedIntegerValue] != DSInvType_MasternodePing) && ([message UInt32AtOffset:l.unsignedIntegerValue] != DSInvType_MasternodePaymentVote) && ([message UInt32AtOffset:l.unsignedIntegerValue] != DSInvType_MasternodeVerify) && ([message UInt32AtOffset:l.unsignedIntegerValue] != DSInvType_GovernanceObjectVote) && ([message UInt32AtOffset:l.unsignedIntegerValue] != DSInvType_DSTx)) { - DSLog(@"[%@: %@:%d] got inv with %u item%@ (first item %@ with hash %@/%@)", self.chain.name, self.host, self.port, (int)count, count == 1 ? @"" : @"s", [self nameOfInvMessage:[message UInt32AtOffset:l.unsignedIntegerValue]], [NSData dataWithUInt256:[message UInt256AtOffset:l.unsignedIntegerValue + sizeof(uint32_t)]].hexString, [NSData dataWithUInt256:[message UInt256AtOffset:l.unsignedIntegerValue + sizeof(uint32_t)]].reverse.hexString); + DSLogWithLocation(self, @"got inv with %u item%@ (first item %@ with hash %@/%@)", (int)count, count == 1 ? @"" : @"s", [self nameOfInvMessage:[message UInt32AtOffset:l.unsignedIntegerValue]], [NSData dataWithUInt256:[message UInt256AtOffset:l.unsignedIntegerValue + sizeof(uint32_t)]].hexString, [NSData dataWithUInt256:[message UInt256AtOffset:l.unsignedIntegerValue + sizeof(uint32_t)]].reverse.hexString); } #endif BOOL onlyPrivateSendTransactions = NO; @@ -1085,7 +1106,7 @@ - (void)acceptInvMessage:(NSData *)message { [self error:@"got tx inv message before loading a filter"]; return; } else if (txHashes.count + instantSendLockHashes.count + instantSendLockDHashes.count > 10000) { // this was happening on testnet, some sort of DOS/spam attack? - DSLog(@"[%@: %@:%d] too many transactions, disconnecting", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"too many transactions, disconnecting"); [self disconnect]; // disconnecting seems to be the easiest way to mitigate it return; } else if (currentHeight > 0 && blockHashes.count > 2 && blockHashes.count < 500 && @@ -1220,7 +1241,7 @@ - (void)acceptInvMessage:(NSData *)message { if (self.mempoolTransactionCompletion && (txHashes.count + governanceObjectHashes.count + sporkHashes.count > 0)) { self.mempoolRequestTime = [NSDate timeIntervalSince1970]; // this will cancel the mempool timeout - DSLog(@"[%@: %@:%d] [DSPeer] got mempool tx inv messages", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"[DSPeer] got mempool tx inv messages"); __block MempoolCompletionBlock completion = self.mempoolTransactionCompletion; [self sendPingMessageWithPongHandler:^(BOOL success) { if (completion) { @@ -1259,15 +1280,15 @@ - (void)acceptTxMessage:(NSData *)message { }]; #if LOG_FULL_TX_MESSAGE #if DEBUG - DSLogPrivate(@"[%@: %@:%d] got tx %@ %@", self.chain.name, self.host, self.port, uint256_obj(tx.txHash), message.hexString); + DSLogPrivateWithLocation(self, @"got tx %@ %@", uint256_obj(tx.txHash), message.hexString); #else - DSLog(@"[%@: %@:%d] got tx %@ %@", self.chain.name, self.host, self.port, @"", @""); + DSLogWithLocation(self, @"got tx %@ %@", @"", @""); #endif #else #if DEBUG - DSLogPrivate(@"[%@: %@:%d] got tx (%hu): %@", self.chain.name, self.host, self.port, tx.type, uint256_obj(tx.txHash)); + DSLogPrivateWithLocation(self, @"got tx (%hu): %@", tx.type, uint256_obj(tx.txHash)); #else - DSLog(@"[%@: %@:%d] got tx (%lu): %@", self.chain.name, self.host, self.port, tx.type, @""); + DSLogWithLocation(self, @"got tx (%lu): %@", tx.type, @""); #endif #endif } @@ -1279,16 +1300,16 @@ - (void)acceptTxMessage:(NSData *)message { [self.currentBlockTxHashes removeObject:uint256_obj(txHash)]; } else { #if DEBUG - DSLogPrivate(@"[%@: %@:%d] current block does not contain transaction %@ (contains %@)", self.chain.name, self.host, self.port, uint256_hex(txHash), self.currentBlockTxHashes); + DSLogPrivateWithLocation(self, @"current block does not contain transaction %@ (contains %@)", uint256_hex(txHash), self.currentBlockTxHashes); #else - DSLog(@"[%@: %@:%d] current block does not contain transaction %@ (contains %@)", self.chain.name, self.host, self.port, @"", @""); + DSLogWithLocation(self, @"current block does not contain transaction %@ (contains %@)", @"", @""); #endif } if (self.currentBlockTxHashes.count == 0) { // we received the entire block including all matched tx DSMerkleBlock *block = self.currentBlock; - DSLog(@"[%@: %@:%d] clearing current block", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"clearing current block"); self.currentBlock = nil; self.currentBlockTxHashes = nil; @@ -1298,21 +1319,21 @@ - (void)acceptTxMessage:(NSData *)message { }); } } else { - DSLog(@"[%@: %@:%d] no current block", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"no current block"); } } - (void)acceptIslockMessage:(NSData *)message { #if LOG_TX_LOCK_VOTES - DSLog(@"[%@: %@:%d] peer relayed islock message: %@", self.chain.name, self.host, self.port, message.hexString); + DSLogWithLocation(self, @"peer relayed islock message: %@", message.hexString); #endif if (![self.chain.chainManager.sporkManager deterministicMasternodeListEnabled]) { - DSLog(@"[%@: %@:%d] returned instant send lock message when DML not enabled: %@", self.chain.name, self.host, self.port, message); //no error here + DSLogWithLocation(self, @"returned instant send lock message when DML not enabled: %@", message); //no error here return; } if (![self.chain.chainManager.sporkManager llmqInstantSendEnabled]) { - DSLog(@"[%@: %@:%d] returned instant send lock message when llmq instant send is not enabled: %@", self.chain.name, self.host, self.port, message); //no error here + DSLogWithLocation(self, @"returned instant send lock message when llmq instant send is not enabled: %@", message); //no error here return; } DSInstantSendTransactionLock *instantSendTransactionLock = [DSInstantSendTransactionLock instantSendTransactionLockWithNonDeterministicMessage:message onChain:self.chain]; @@ -1331,14 +1352,14 @@ - (void)acceptIslockMessage:(NSData *)message { - (void)acceptIsdlockMessage:(NSData *)message { #if LOG_TX_LOCK_VOTES - DSLog(@"[%@: %@:%d] peer relayed isdlock message: %@", self.chain.name, self.host, self.port, message.hexString); + DSLogWithLocation(self, @"peer relayed isdlock message: %@", message.hexString); #endif if (![self.chain.chainManager.sporkManager deterministicMasternodeListEnabled]) { - DSLog(@"[%@: %@:%d] returned instant send lock message when DML not enabled: %@", self.chain.name, self.host, self.port, message); //no error here + DSLogWithLocation(self, @"returned instant send lock message when DML not enabled: %@", message); //no error here return; } if (![self.chain.chainManager.sporkManager llmqInstantSendEnabled]) { - DSLog(@"[%@: %@:%d] returned instant send lock message when llmq instant send is not enabled: %@", self.chain.name, self.host, self.port, message); //no error here + DSLogWithLocation(self, @"returned instant send lock message when llmq instant send is not enabled: %@", message); //no error here return; } DSInstantSendTransactionLock *instantSendTransactionLock = [DSInstantSendTransactionLock instantSendTransactionLockWithDeterministicMessage:message onChain:self.chain]; @@ -1383,12 +1404,12 @@ - (void)acceptHeadersMessage:(NSData *)message { } if (count == 0) { #if DEBUG - DSLogPrivate(@"[%@: %@:%d] got 0 headers (%@)", self.chain.name, self.host, self.port, message.hexString); + DSLogPrivateWithLocation(self, @"got 0 headers (%@)", message.hexString); #else - DSLog(@"[%@: %@:%d] got 0 headers (%@)", self.chain.name, self.host, self.port, @""); + DSLogWithLocation(self, @"got 0 headers (%@)", @""); #endif } else { - DSLog(@"[%@: %@:%d] got %u headers", self.chain.name, self.host, self.port, (int)count); + DSLogWithLocation(self, @"got %u headers", count); } #if LOG_ALL_HEADERS_IN_ACCEPT_HEADERS @@ -1425,7 +1446,7 @@ - (void)acceptHeadersMessage:(NSData *)message { NSTimeInterval firstTimestamp = [message UInt32AtOffset:l + 81 + 68]; if (!self.chain.needsInitialTerminalHeadersSync && (firstTimestamp + DAY_TIME_INTERVAL * 2 >= self.earliestKeyTime) && [self.chain.chainManager shouldRequestMerkleBlocksForZoneAfterHeight:self.chain.lastSyncBlockHeight + 1]) { //this is a rare scenario where we called getheaders but the first header returned was actually past the cuttoff, but the previous header was before the cuttoff - DSLog(@"[%@: %@:%d] calling getblocks with locators: %@", self.chain.name, self.host, self.port, [self.chain chainSyncBlockLocatorArray]); + DSLogWithLocation(self, @"calling getblocks with locators: %@", [self.chain chainSyncBlockLocatorArray]); [self sendGetblocksMessageWithLocators:self.chain.chainSyncBlockLocatorArray andHashStop:UINT256_ZERO]; return; } @@ -1445,11 +1466,11 @@ - (void)acceptHeadersMessage:(NSData *)message { } lastBlockHash = [DSKeyManager x11:[message subdataWithRange:NSMakeRange(off, 80)]]; lastHashData = uint256_data(lastBlockHash); - DSLog(@"[%@: %@:%d] calling getblocks with locators: [%@, %@]", self.chain.name, self.host, self.port, lastHashData.reverse.hexString, firstHashData.reverse.hexString); + DSLogWithLocation(self, @"calling getblocks with locators: [%@, %@]", lastHashData.reverse.hexString, firstHashData.reverse.hexString); [self sendGetblocksMessageWithLocators:@[lastHashData, firstHashData] andHashStop:UINT256_ZERO]; } else { - DSLog(@"[%@: %@:%d] calling getheaders with locators: [%@, %@]", self.chain.name, self.host, self.port, lastHashData.reverse.hexString, firstHashData.reverse.hexString); + DSLogWithLocation(self, @"calling getheaders with locators: [%@, %@]", lastHashData.reverse.hexString, firstHashData.reverse.hexString); [self sendGetheadersMessageWithLocators:@[lastHashData, firstHashData] andHashStop:UINT256_ZERO]; } } @@ -1466,7 +1487,7 @@ - (void)acceptHeadersMessage:(NSData *)message { } - (void)acceptGetaddrMessage:(NSData *)message { - DSLog(@"[%@: %@:%d] got getaddr", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"got getaddr"); [self sendRequest:[DSAddrRequest request]]; } @@ -1480,12 +1501,11 @@ - (void)acceptGetdataMessage:(NSData *)message { (int)(((l == 0) ? 1 : l) + count * 36), (int)count]; return; } else if (count > MAX_GETDATA_HASHES) { - DSLog(@"[%@: %@:%d] dropping getdata message, %u is too many items, max is %u", self.chain.name, self.host, self.port, (int)count, - MAX_GETDATA_HASHES); + DSLogWithLocation(self, @"dropping getdata message, %u is too many items, max is %u", count, MAX_GETDATA_HASHES); return; } - DSLog(@"[%@: %@:%d] %@got getdata for %u item%@", self.chain.name, self.host, self.port, self.peerDelegate.downloadPeer == self ? @"(download peer)" : @"", (int)count, count == 1 ? @"" : @"s"); + DSLogWithLocation(self, @"%@got getdata for %u item%@", self.peerDelegate.downloadPeer == self ? @"(download peer)" : @"", count, count == 1 ? @"" : @"s"); [self dispatchAsyncInDelegateQueue:^{ NSMutableData *notfound = [NSMutableData data]; @@ -1506,9 +1526,9 @@ - (void)acceptGetdataMessage:(NSData *)message { break; } else { #if DEBUG - DSLogPrivate(@"[%@: %@:%d] peer requested transaction was not found with hash %@ reversed %@", self.chain.name, self.host, self.port, [NSData dataWithUInt256:hash].hexString, [NSData dataWithUInt256:hash].reverse.hexString); + DSLogPrivateWithLocation(self, @"peer requested transaction was not found with hash %@ reversed %@", [NSData dataWithUInt256:hash].hexString, [NSData dataWithUInt256:hash].reverse.hexString); #else - DSLog(@"[%@: %@:%d] peer requested transaction was not found with hash %@ reversed %@", self.chain.name, self.host, self.port, @"", @""); + DSLogWithLocation(self, @"peer requested transaction was not found with hash %@ reversed %@", @"", @""); #endif [notfound appendUInt32:type]; [notfound appendBytes:&hash length:sizeof(hash)]; @@ -1563,7 +1583,7 @@ - (void)acceptNotfoundMessage:(NSData *)message { return; } - DSLog(@"[%@: %@:%d] got notfound with %u item%@ (first item %@)", self.chain.name, self.host, self.port, (int)count, count == 1 ? @"" : @"s", [self nameOfInvMessage:[message UInt32AtOffset:l]]); + DSLogWithLocation(self, @"got notfound with %u item%@ (first item %@)", count, count == 1 ? @"" : @"s", [self nameOfInvMessage:[message UInt32AtOffset:l]]); for (NSUInteger off = l; off < l + 36 * count; off += 36) { if ([message UInt32AtOffset:off] == DSInvType_Tx) { @@ -1585,7 +1605,7 @@ - (void)acceptPingMessage:(NSData *)message { return; } #if MESSAGE_LOGGING - DSLog(@"[%@: %@:%d] got ping", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"got ping"); #endif [self sendMessage:message type:MSG_PONG]; } @@ -1600,7 +1620,7 @@ - (void)acceptPongMessage:(NSData *)message { } else { __block BOOL hasNoHandlers = ![self.pongHandlers count]; if (hasNoHandlers) { - DSLog(@"[%@: %@:%d] got unexpected pong", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"got unexpected pong"); return; } } @@ -1614,7 +1634,7 @@ - (void)acceptPongMessage:(NSData *)message { } #if MESSAGE_LOGGING - DSLog(@"[%@: %@:%d] got pong in %fs", self.chain.name, self.host, self.port, self.pingTime); + DSLogWithLocation(self, @"got pong in %fs", self.pingTime); #endif if (self->_status == DSPeerStatus_Connected && self.pongHandlers.count) { void (^handler)(BOOL) = [self.pongHandlers objectAtIndex:0]; @@ -1665,9 +1685,9 @@ - (void)acceptMerkleblockMessage:(NSData *)message { - (void)acceptChainLockMessage:(NSData *)message { if (![self.chain.chainManager.sporkManager chainLocksEnabled]) { #if DEBUG - DSLogPrivate(@"[%@: %@:%d] returned chain lock message when chain locks are not enabled: %@", self.chain.name, self.host, self.port, message); //no error here + DSLogPrivateWithLocation(self, @"returned chain lock message when chain locks are not enabled: %@", message); //no error here #else - DSLog(@"[%@: %@:%d] returned chain lock message when chain locks are not enabled: %@", self.chain.name, self.host, self.port, @""); //no error here + DSLogWithLocation(self, @"returned chain lock message when chain locks are not enabled: %@", @""); //no error here #endif return; } @@ -1697,10 +1717,10 @@ - (void)acceptRejectMessage:(NSData *)message { UInt256 txHash = ([MSG_TX isEqual:type] || [MSG_IX isEqual:type]) ? [message UInt256AtOffset:off + l] : UINT256_ZERO; #if DEBUG - DSLogPrivate(@"[%@: %@:%d] rejected %@ code: 0x%x reason: \"%@\"%@%@", self.chain.name, self.host, self.port, type, code, reason, + DSLogPrivateWithLocation(self, @"rejected %@ code: 0x%x reason: \"%@\"%@%@", type, code, reason, (uint256_is_zero(txHash) ? @"" : @" txid: "), (uint256_is_zero(txHash) ? @"" : uint256_obj(txHash))); #else - DSLog(@"[%@: %@:%d] rejected %@ code: 0x%x reason: \"%@\"%@%@", self.chain.name, self.host, self.port, type, code, reason, + DSLogWithLocation(self, @"rejected %@ code: 0x%x reason: \"%@\"%@%@", type, code, reason, (uint256_is_zero(txHash) ? @"" : @" txid: "), (uint256_is_zero(txHash) ? @"" : @"")); #endif reason = nil; // fixes an unused variable warning for non-debug builds @@ -1720,7 +1740,7 @@ - (void)acceptFeeFilterMessage:(NSData *)message { } _feePerByte = ceilf((float)[message UInt64AtOffset:0] / 1000.0f); - DSLog(@"[%@: %@:%d] got feefilter with rate %llu per Byte", self.chain.name, self.host, self.port, self.feePerByte); + DSLogWithLocation(self, @"got feefilter with rate %llu per Byte", self.feePerByte); [self dispatchAsyncInDelegateQueue:^{ [self.transactionDelegate peer:self setFeePerByte:self.feePerByte]; }]; @@ -1737,7 +1757,7 @@ - (void)acceptSporkMessage:(NSData *)message { - (void)acceptSSCMessage:(NSData *)message { DSSyncCountInfo syncCountInfo = [message UInt32AtOffset:0]; uint32_t count = [message UInt32AtOffset:4]; - DSLog(@"[%@: %@:%d] received ssc message %d %d", self.chain.name, self.host, self.port, syncCountInfo, count); + DSLogWithLocation(self, @"received ssc message %d %d", syncCountInfo, count); switch (syncCountInfo) { case DSSyncCountInfo_GovernanceObject: if (self.governanceRequestState == DSGovernanceRequestState_GovernanceObjectHashes) { @@ -1795,7 +1815,7 @@ - (void)acceptGovObjectVoteMessage:(NSData *)message { } - (void)acceptGovObjectSyncMessage:(NSData *)message { - DSLog(@"[%@: %@:%d] Gov Object Sync", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"Gov Object Sync"); } // MARK: - Accept Dark send @@ -1926,7 +1946,7 @@ - (NSError *)connectionTimeoutError { - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { switch (eventCode) { //!OCLINT case NSStreamEventOpenCompleted: - DSLog(@"[%@: %@:%d] %@ stream connected in %fs", self.chain.name, self.host, self.port, + DSLogWithLocation(self, @"%@ stream connected in %fs", (aStream == self.inputStream) ? @"input" : (aStream == self.outputStream ? @"output" : @"unknown"), [NSDate timeIntervalSince1970] - self.pingStartTime); @@ -1970,7 +1990,7 @@ - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { maxLength:self.msgHeader.length - headerLen]; if (l < 0) { - DSLog(@"[%@: %@:%d] error reading message", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"error reading message"); goto reset; //!OCLINT } @@ -2010,7 +2030,7 @@ - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { maxLength:self.msgPayload.length - payloadLen]; if (l < 0) { - DSLog(@"[%@: %@:%d] error reading %@", self.chain.name, self.host, self.port, type); + DSLogWithLocation(self, @"error reading %@", type); goto reset; //!OCLINT } @@ -2038,17 +2058,17 @@ - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { break; case NSStreamEventErrorOccurred: - DSLog(@"[%@: %@:%d] error connecting, %@", self.chain.name, self.host, self.port, aStream.streamError); + DSLogWithLocation(self, @"error connecting, %@", aStream.streamError); [self disconnectWithError:aStream.streamError]; break; case NSStreamEventEndEncountered: - DSLog(@"[%@: %@:%d] connection closed", self.chain.name, self.host, self.port); + DSLogWithLocation(self, @"connection closed"); [self disconnectWithError:nil]; break; default: - DSLog(@"[%@: %@:%d] unknown network stream eventCode:%u", self.chain.name, self.host, self.port, (int)eventCode); + DSLogWithLocation(self, @"unknown network stream eventCode:%u", eventCode); } } diff --git a/Example/Podfile.lock b/Example/Podfile.lock index 2429e3887..35763ade7 100644 --- a/Example/Podfile.lock +++ b/Example/Podfile.lock @@ -657,7 +657,7 @@ PODS: - gRPC/Interface-Legacy (1.49.0): - gRPC-RxLibrary/Interface (= 1.49.0) - KVO-MVVM (0.5.1) - - Protobuf (3.25.0) + - Protobuf (3.25.1) - SDWebImage (5.14.3): - SDWebImage/Core (= 5.14.3) - SDWebImage/Core (5.14.3) @@ -721,7 +721,7 @@ SPEC CHECKSUMS: gRPC-ProtoRPC: 1c223e0f1732bb8d0b9e9e0ea60cc0fe995b8e2d gRPC-RxLibrary: 92327f150e11cf3b1c0f52e083944fd9f5cb5d1e KVO-MVVM: 4df3afd1f7ebcb69735458b85db59c4271ada7c6 - Protobuf: 6a4183ec1d51649eb2be7b86ccc286e5c539219c + Protobuf: d94761c33f1239c0a43a0817ca1a5f7f7c900241 SDWebImage: 9c36e66c8ce4620b41a7407698dda44211a96764 tinycbor: d4d71dddda1f8392fbb4249f63faf8552f327590 TinyCborObjc: 5204540fb90ff0c40fb22d408fa51bab79d78a80 From 9a4011d265b487ce3d9486d762f0d2897372e943 Mon Sep 17 00:00:00 2001 From: pankcuf Date: Fri, 17 Nov 2023 19:40:16 +0700 Subject: [PATCH 32/32] chore: bump up protocol version for mainnet (70230) --- DashSync/shared/Models/Chain/DSChainConstants.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DashSync/shared/Models/Chain/DSChainConstants.h b/DashSync/shared/Models/Chain/DSChainConstants.h index 7776a9e2a..56ce05e87 100644 --- a/DashSync/shared/Models/Chain/DSChainConstants.h +++ b/DashSync/shared/Models/Chain/DSChainConstants.h @@ -31,7 +31,7 @@ #define TESTNET_DAPI_GRPC_STANDARD_PORT 3010 #define DEVNET_DAPI_GRPC_STANDARD_PORT 3010 -#define PROTOCOL_VERSION_MAINNET 70228 +#define PROTOCOL_VERSION_MAINNET 70230 #define DEFAULT_MIN_PROTOCOL_VERSION_MAINNET 70228 #define PROTOCOL_VERSION_TESTNET 70230