text: //
  //  BRPeerManager.h
  //
  //  Created by Aaron Voisine on 9/2/15.
  //  Copyright (c) 2015 breadwallet LLC.
  //
  //  Permission is hereby granted, free of charge, to any person obtaining a copy
  //  of this software and associated documentation files (the "Software"), to deal
  //  in the Software without restriction, including without limitation the rights
  //  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  //  copies of the Software, and to permit persons to whom the Software is
  //  furnished to do so, subject to the following conditions:
  //
  //  The above copyright notice and this permission notice shall be included in
  //  all copies or substantial portions of the Software.
  //
  //  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  //  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  //  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  //  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  //  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  //  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  //  THE SOFTWARE.
  
  #ifndef BRPeerManager_h
  #define BRPeerManager_h
  
  #include "BRPeer.h"
  #include "BRMerkleBlock.h"
  #include "BRTransaction.h"
  #include "BRWallet.h"
  #include "BRChainParams.h"
  #include <stddef.h>
  #include <inttypes.h>
  
  #ifdef __cplusplus
  extern "C" {
  #endif
  
  #define PEER_MAX_CONNECTIONS 3
  
  /* defines, how many blocks to be held in sqlite DB */
  #define SAVE_BLOCK_COUNT 300
  #define SAVE_BLOCK_INTERVAL 4000
      
  /* OPTIONS FOR CLEARING MEMORY */
  /*
  Remarks:
      The authors of the original breadwallet core ensure that the application
      contains at least 2016 blocks, until a difficulty transition block gets relayed.
      Since Digibyte makes use of DigiShield (or more specifically MultiShield), on each and
      every block there occurs a difficulty transition.
      We need to keep some blocks in memory in case of forks, to walk the chain backwards.
      To clear memory we have introduced a trigger value: CLEAR_MEM_BLOCKS_COUNT_TRIGGER.
      If the BRPeerManager instance contains more than CLEAR_MEM_BLOCKS_COUNT_TRIGGER blocks in 'blocks',
      we trigger the memory cleanup. The first CLEAR_MEM_BLOCKS_COUNT_TAIL_LEN blocks will be freed up.
      Note that we have to remove the tail, that is, we have to walk back the chain, until we reach the tail,
      then free up the remaining blocks.
   
      CLEAR_MEM_BLOCKS_COUNT_TAIL_LEN is at least the SAVE_BLOCK_COUNT
          plus a reserve of CLEAR_MEM_BLOCKS_RESERVE_COUNT blocks.
  */
  #define CLEAR_MEM_BLOCKS_COUNT_TRIGGER 5000
  #define CLEAR_MEM_BLOCKS_RESERVE_COUNT 500
  #define CLEAR_MEM_BLOCKS_COUNT_TAIL_LEN (CLEAR_MEM_BLOCKS_COUNT_TRIGGER - SAVE_BLOCK_COUNT - CLEAR_MEM_BLOCKS_RESERVE_COUNT)
      
  /* Readability constants */
  #define ADD_TO_SAVED_BLOCKS 0
  #define REPLACE_SAVED_BLOCKS 1
  
  typedef struct BRPeerManagerStruct BRPeerManager;
  
  // returns a newly allocated BRPeerManager struct that must be freed by calling BRPeerManagerFree()
  BRPeerManager* BRPeerManagerNew(const BRChainParams* params, BRWallet* wallet, uint32_t earliestKeyTime,
                                  BRMerkleBlock* blocks[], size_t blocksCount, const BRPeer peers[], size_t peersCount);
  
  // Extension of the above. Accepts a custom initial block
  BRPeerManager* BRPeerManagerNewEx(const BRChainParams* params, BRWallet* wallet, uint32_t earliestKeyTime,
                                    BRMerkleBlock* blocks[], size_t blocksCount, const BRPeer peers[], size_t peersCount, BRMerkleBlock* startSyncFrom);
      
  // not thread-safe, set callbacks once before calling BRPeerManagerConnect()
  // info is a void pointer that will be passed along with each callback call
  // void syncStarted(void *) - called when blockchain syncing starts
  // void syncStopped(void *, int) - called when blockchain syncing stops, error is an errno.h code
  // void txStatusUpdate(void *) - called when transaction status may have changed such as when a new block arrives
  // void saveBlocks(void *, int, BRMerkleBlock *[], size_t) - called when blocks should be saved to the persistent store
  // - if replace is true, remove any previously saved blocks first
  // void savePeers(void *, int, const BRPeer[], size_t) - called when peers should be saved to the persistent store
  // - if replace is true, remove any previously saved peers first
  // int networkIsReachable(void *) - must return true when networking is available, false otherwise
  // void threadCleanup(void *) - called before a thread terminates to faciliate any needed cleanup
  void BRPeerManagerSetCallbacks(BRPeerManager *manager, void *info,
                                 void (*syncStarted)(void *info),
                                 void (*syncStopped)(void *info, int error),
                                 void (*txStatusUpdate)(void *info),
                                 void (*saveBlocks)(void *info, int replace, BRMerkleBlock *blocks[], size_t blocksCount, uint64_t* memIntegrityCheck),
                                 void (*savePeers)(void *info, int replace, const BRPeer peers[], size_t peersCount),
                                 int (*networkIsReachable)(void *info),
                                 void (*threadCleanup)(void *info));
  
  // specifies a single fixed peer to use when connecting to the bitcoin network
  // set address to UINT128_ZERO to revert to default behavior
  void BRPeerManagerSetFixedPeer(BRPeerManager *manager, UInt128 address, uint16_t port);
  
  // sets a custom start block
  void BRPeerManagerSetStartBlock(BRPeerManager* manager, BRMerkleBlock* start);
      
  // current connect status
  BRPeerStatus BRPeerManagerConnectStatus(BRPeerManager *manager);
  
  // connect to bitcoin peer-to-peer network (also call this whenever networkIsReachable() status changes)
  void BRPeerManagerConnect(BRPeerManager *manager);
  
  // disconnect from bitcoin peer-to-peer network (may cause syncFailed(), saveBlocks() or savePeers() callbacks to fire)
  void BRPeerManagerDisconnect(BRPeerManager *manager);
  
  // rescans blocks and transactions after earliestKeyTime (a new random download peer is also selected due to the
  // possibility that a malicious node might lie by omitting transactions that match the bloom filter)
  void BRPeerManagerRescan(BRPeerManager *manager);
  
  // the (unverified) best block height reported by connected peers
  uint32_t BRPeerManagerEstimatedBlockHeight(BRPeerManager *manager);
  
  // current proof-of-work verified best block height
  uint32_t BRPeerManagerLastBlockHeight(BRPeerManager *manager);
  
  // current proof-of-work verified best block timestamp (time interval since unix epoch)
  uint32_t BRPeerManagerLastBlockTimestamp(BRPeerManager *manager);
  
  // current network sync progress from 0 to 1
  // startHeight is the block height of the most recent fully completed sync
  double BRPeerManagerSyncProgress(BRPeerManager *manager, uint32_t startHeight);
  
  // returns the number of currently connected peers
  size_t BRPeerManagerPeerCount(BRPeerManager *manager);
  
  // description of the peer most recently used to sync blockchain data
  const char *BRPeerManagerDownloadPeerName(BRPeerManager *manager);
  
  // publishes tx to bitcoin network (do not call BRTransactionFree() on tx afterward)
  void BRPeerManagerPublishTx(BRPeerManager *manager, BRTransaction *tx, void *info,
                              void (*callback)(void *info, int error));
  
  // number of connected peers that have relayed the given unconfirmed transaction
  size_t BRPeerManagerRelayCount(BRPeerManager *manager, UInt256 txHash);
  
  // frees memory allocated for manager (call BRPeerManagerDisconnect() first if connected)
  void BRPeerManagerFree(BRPeerManager *manager);
  	
  /*
   * The following two methods sync the blockchain beginning from startBlock.
   *
   * Usage: Create a custom merkle block and pass it to BPPeerManagerMainNetNewEx()
   *     BRMerkleBlock* test = BRMerkleBlockNew();
   *     test->blockHash = UInt256Reverse(uint256("7497ea1b465eb39f1c8f507bc877078fe016d6fcb6dfad3a64c98dcc6e1e8496"));
   *     test->height = 0;
   *     test->timestamp = 1389388394;
   *     test->target = 0x1e0ffff0;
   */
  
  BRPeerManager* BPPeerManagerMainNetNewEx(BRWallet *wallet, uint32_t earliestKeyTime, BRMerkleBlock *blocks[], size_t blocksCount, const BRPeer peers[], size_t peersCount, BRMerkleBlock* startBlock);
  
  BRPeerManager* BPPeerManagerTestNetNewEx(BRWallet *wallet, uint32_t earliestKeyTime, BRMerkleBlock *blocks[], size_t blocksCount, const BRPeer peers[], size_t peersCount, BRMerkleBlock* startBlock);
      
  // function to create Peermanager under for the mainnet directly
  BRPeerManager *BPPeerManagerMainNetNew(BRWallet *wallet, uint32_t earliestKeyTime,
  									   BRMerkleBlock *blocks[], size_t blocksCount, const BRPeer peers[], size_t peersCount);
  
  // function to create Peermanager under for the testnet directly
  BRPeerManager *BPPeerManagerTestNetNew(BRWallet *wallet, uint32_t earliestKeyTime,
  									   BRMerkleBlock *blocks[], size_t blocksCount, const BRPeer peers[], size_t peersCount);
  
  
  #ifdef __cplusplus
  }
  #endif
  
  #endif // BRPeerManager_h
  