<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOpenCVVideoSource.cxx

  Copyright (c) John Baxter, Robarts Research Institute
  All rights reserved.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkOpenCVVideoSource.h"

#include "vtkObjectFactory.h"
#include "vtkDataArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkCriticalSection.h"
#include "vtkTimerLog.h"

#include <iostream>
#include <cv.h>
#include <highgui.h>

class vtkOpenCVVideoSourceInternal
{
public:
	vtkOpenCVVideoSourceInternal(vtkOpenCVVideoSource* s) {
		parent = s;
		capture = 0;
		cvRawImage = 0;
		cvProcImage = 0;
	}
	~vtkOpenCVVideoSourceInternal() {
		if( this->capture ) cvReleaseCapture( &(this->capture) );
		if( this->cvRawImage ) cvReleaseImage( &(this->cvRawImage) );
		if( this->cvProcImage ) cvReleaseImage( &(this->cvProcImage) );
	}

	vtkOpenCVVideoSource*	parent;
	double					lastTime;

	CvCapture*				capture;
	IplImage*				cvRawImage;
	IplImage*				cvProcImage;

};

vtkStandardNewMacro(vtkOpenCVVideoSource);

//----------------------------------------------------------------------------
vtkOpenCVVideoSource::vtkOpenCVVideoSource()
{

	//set up the internal class (handles pretty much everything)
	this->Internal = new vtkOpenCVVideoSourceInternal(this);
	this->OpenCVFirstBufferLock = vtkMutexLock::New();
	this->OpenCVSecondBufferLock = vtkMutexLock::New();

	//set some reasonable default values
	this->vtkVideoSource::SetFrameRate( 5.0f );
	this->videoSourceNumber = 0;
	this->FrameBufferBitsPerPixel = 24;
	this->vtkVideoSource::SetOutputFormat(VTK_RGB);

	this->EnumerateSources();
	this->Initialized = false;
}

//----------------------------------------------------------------------------
vtkOpenCVVideoSource::~vtkOpenCVVideoSource()
{
  this->vtkOpenCVVideoSource::ReleaseSystemResources();
  this->OpenCVFirstBufferLock->Delete();
  this->OpenCVSecondBufferLock->Delete();
  delete this->Internal;
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::EnumerateSources(){
	this->maxSource = 0;
	bool stillLooking = true;
	while( stillLooking ){
		if( !cvCreateCameraCapture( this->maxSource ) ){
			stillLooking = false;
		}
		this->maxSource++;
	}
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::SetVideoSourceNumber(unsigned int n){

	//determine is source is available
	if( n < 0 || n > maxSource ){
		vtkErrorMacro(<<"Cannot use that video source number. Must be an available source");
		return;
	}

	//if we haven't changed number, don't do anything
	if( this->videoSourceNumber == n ) return;

	//create a new capture device for the specified identifier, and re-initialize
	this->videoSourceNumber = n;
	if( this->Initialized ){
		this->ReleaseSystemResources();
		this->Initialize();
	}

}

unsigned int vtkOpenCVVideoSource::GetVideoSourceNumber(){
	return this->videoSourceNumber;
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::SetFrameSize(int x, int y, int z) {
	//vtkErrorMacro(<<"Use the VideoFormatDialog() method to set the frame size.");
}

void vtkOpenCVVideoSource::SetOutputFormat(int format) {
	//vtkErrorMacro(<<"Use the VideoFormatDialog() method to set the output format.");
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::Initialize()
{
	//INITIALIZE OPENCV
	if( this->Initialized ) return;

	//Grab the appropriate capture device
	cvReleaseCapture( &(this->Internal->capture) );
	this->Internal->capture = cvCreateCameraCapture( this->videoSourceNumber );
	if( !this->Internal->capture ){
		vtkErrorMacro(<<"Could not create OpenCV capture device.");
		ReleaseSystemResources();
		return;
	}

	//collect information regarding image size, frame dimensions, etc...
	this->Internal->cvRawImage = cvQueryFrame( this->Internal->capture );
	if( !this->Internal->cvRawImage ){
		vtkErrorMacro(<<"Could not create OpenCV capture device.");
		ReleaseSystemResources();
		return;
	}
	this->ImageSize = this->Internal->cvRawImage->imageSize;
	this->vtkVideoSource::SetFrameSize( this->Internal->cvRawImage->width, this->Internal->cvRawImage->height, 1 );
	this->Internal->cvProcImage = (IplImage*) cvClone( this->Internal->cvRawImage );

	// Initialization worked
	this->Initialized = 1;

	// Update frame buffer  to reflect any changes
	this->UpdateFrameBuffer();
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::ReleaseSystemResources()
{

	//UNINITIALIZE OPENCV
	delete this->Internal;
	this->Internal = new vtkOpenCVVideoSourceInternal( this );

	this->Initialized = 0;
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::UpdateFrameBuffer()
{
  int i, oldExt;
  int ext[3];
  vtkDataArray *buffer;

  // clip the ClipRegion with the FrameSize
  for (i = 0; i < 3; i++)
    {
    oldExt = this->FrameBufferExtent[2*i+1] - this->FrameBufferExtent[2*i] + 1;
    this->FrameBufferExtent[2*i] = ((this->ClipRegion[2*i] > 0)
                             ? this->ClipRegion[2*i] : 0);
    this->FrameBufferExtent[2*i+1] = ((this->ClipRegion[2*i+1] <
                                       this->FrameSize[i]-1)
                             ? this->ClipRegion[2*i+1] : this->FrameSize[i]-1);

    ext[i] = this->FrameBufferExtent[2*i+1] - this->FrameBufferExtent[2*i] + 1;
    if (ext[i] < 0)
      {
      this->FrameBufferExtent[2*i] = 0;
      this->FrameBufferExtent[2*i+1] = -1;
      ext[i] = 0;
      }

    if (oldExt > ext[i])
      { // dimensions of framebuffer changed
      this->OutputNeedsInitialization = 1;
      }
    }

  // total number of bytes required for the framebuffer
  int bytesPerRow = ext[0]*(this->FrameBufferBitsPerPixel/8);
  bytesPerRow = ((bytesPerRow + this->FrameBufferRowAlignment - 1) /
                 this->FrameBufferRowAlignment)*this->FrameBufferRowAlignment;
  int totalSize = bytesPerRow * ext[1] * ext[2];
  i = this->FrameBufferSize;

  while (--i >= 0)
    {
    buffer = reinterpret_cast<vtkDataArray *>(this->FrameBuffer[i]);
    if (buffer->GetDataType() != VTK_UNSIGNED_CHAR ||
        buffer->GetNumberOfComponents() != 3 ||
        buffer->GetNumberOfTuples() != totalSize)
      {
      buffer->Delete();
      buffer = vtkUnsignedCharArray::New();
      this->FrameBuffer[i] = buffer;
      buffer->SetNumberOfComponents(3);
      buffer->SetNumberOfTuples(ext[0] * ext[1] * ext[2]);

      }
    }
}

void vtkOpenCVVideoSource::InternalGrab()
{

  //get a lock on the OpenCV buffer and fetch the images
  this->OpenCVFirstBufferLock->Lock();
  this->Internal->cvRawImage = cvQueryFrame( this->Internal->capture );
  this->OpenCVSecondBufferLock->Lock();
  if( this->Internal->cvRawImage ) cvConvertImage( this->Internal->cvRawImage, this->Internal->cvProcImage, CV_CVTIMG_FLIP + CV_CVTIMG_SWAP_RB );
  this->OpenCVFirstBufferLock->Unlock();
  //unlock 2nd buffer lock after final memcpy to framebuffer

  // get a thread lock on the frame buffer
  this->FrameBufferMutex->Lock();

  if (this->AutoAdvance)
    {
    this->AdvanceFrameBuffer(1);
    if (this->FrameIndex + 1 < this->FrameBufferSize)
      {
      this->FrameIndex++;
      }
    }

  int index = this->FrameBufferIndex % this->FrameBufferSize;
  while (index < 0) index += this->FrameBufferSize;

  // Get a pointer to the location of the frame buffer
  char *ptr = (char *) reinterpret_cast<vtkUnsignedCharArray *>(this->FrameBuffer[index])->GetPointer(0);

  //attempt the find the processed buffer
  char* buffer = 0;
  if( this->Internal->cvProcImage ) buffer = this->Internal->cvProcImage->imageData;

  //if we can't find the buffer, error and return
  if( !buffer || !ptr ){
	  vtkErrorMacro(<<"Could not access both buffers.");
  }else{
	  memcpy(ptr, buffer, this->ImageSize);
  }

  // Copy image into frame buffer and release the old image
  this->OpenCVSecondBufferLock->Unlock();

  this->FrameBufferTimeStamps[index] = vtkTimerLog::GetUniversalTime();

  if (this->FrameCount++ == 0)
    {
    this->StartTimeStamp = this->FrameBufferTimeStamps[index];
    }

  this->Modified();

  this->FrameBufferMutex->Unlock();
}<commit_msg>FIX #0000012: Just added an error macro explaining that the size is determined by OpenCV.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOpenCVVideoSource.cxx

  Copyright (c) John Baxter, Robarts Research Institute
  All rights reserved.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkOpenCVVideoSource.h"

#include "vtkObjectFactory.h"
#include "vtkDataArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkCriticalSection.h"
#include "vtkTimerLog.h"

#include <iostream>
#include <cv.h>
#include <highgui.h>

class vtkOpenCVVideoSourceInternal
{
public:
	vtkOpenCVVideoSourceInternal(vtkOpenCVVideoSource* s) {
		parent = s;
		capture = 0;
		cvRawImage = 0;
		cvProcImage = 0;
	}
	~vtkOpenCVVideoSourceInternal() {
		if( this->capture ) cvReleaseCapture( &(this->capture) );
		if( this->cvRawImage ) cvReleaseImage( &(this->cvRawImage) );
		if( this->cvProcImage ) cvReleaseImage( &(this->cvProcImage) );
	}

	vtkOpenCVVideoSource*	parent;
	double					lastTime;

	CvCapture*				capture;
	IplImage*				cvRawImage;
	IplImage*				cvProcImage;

};

vtkStandardNewMacro(vtkOpenCVVideoSource);

//----------------------------------------------------------------------------
vtkOpenCVVideoSource::vtkOpenCVVideoSource()
{

	//set up the internal class (handles pretty much everything)
	this->Internal = new vtkOpenCVVideoSourceInternal(this);
	this->OpenCVFirstBufferLock = vtkMutexLock::New();
	this->OpenCVSecondBufferLock = vtkMutexLock::New();

	//set some reasonable default values
	this->vtkVideoSource::SetFrameRate( 5.0f );
	this->videoSourceNumber = 0;
	this->FrameBufferBitsPerPixel = 24;
	this->vtkVideoSource::SetOutputFormat(VTK_RGB);

	this->EnumerateSources();
	this->Initialized = false;
}

//----------------------------------------------------------------------------
vtkOpenCVVideoSource::~vtkOpenCVVideoSource()
{
  this->vtkOpenCVVideoSource::ReleaseSystemResources();
  this->OpenCVFirstBufferLock->Delete();
  this->OpenCVSecondBufferLock->Delete();
  delete this->Internal;
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::EnumerateSources(){
	this->maxSource = 0;
	bool stillLooking = true;
	while( stillLooking ){
		if( !cvCreateCameraCapture( this->maxSource ) ){
			stillLooking = false;
		}
		this->maxSource++;
	}
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::SetVideoSourceNumber(unsigned int n){

	//determine is source is available
	if( n < 0 || n > maxSource ){
		vtkErrorMacro(<<"Cannot use that video source number. Must be an available source");
		return;
	}

	//if we haven't changed number, don't do anything
	if( this->videoSourceNumber == n ) return;

	//create a new capture device for the specified identifier, and re-initialize
	this->videoSourceNumber = n;
	if( this->Initialized ){
		this->ReleaseSystemResources();
		this->Initialize();
	}

}

unsigned int vtkOpenCVVideoSource::GetVideoSourceNumber(){
	return this->videoSourceNumber;
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::SetFrameSize(int x, int y, int z) {
	vtkErrorMacro(<<"Frame size cannot be set, but is automatically determined by OpenCV.");
}

void vtkOpenCVVideoSource::SetOutputFormat(int format) {
	//vtkErrorMacro(<<"Use the VideoFormatDialog() method to set the output format.");
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::Initialize()
{
	//INITIALIZE OPENCV
	if( this->Initialized ) return;

	//Grab the appropriate capture device
	cvReleaseCapture( &(this->Internal->capture) );
	this->Internal->capture = cvCreateCameraCapture( this->videoSourceNumber );
	if( !this->Internal->capture ){
		vtkErrorMacro(<<"Could not create OpenCV capture device.");
		ReleaseSystemResources();
		return;
	}

	//collect information regarding image size, frame dimensions, etc...
	this->Internal->cvRawImage = cvQueryFrame( this->Internal->capture );
	if( !this->Internal->cvRawImage ){
		vtkErrorMacro(<<"Could not create OpenCV capture device.");
		ReleaseSystemResources();
		return;
	}
	this->ImageSize = this->Internal->cvRawImage->imageSize;
	this->vtkVideoSource::SetFrameSize( this->Internal->cvRawImage->width, this->Internal->cvRawImage->height, 1 );
	this->Internal->cvProcImage = (IplImage*) cvClone( this->Internal->cvRawImage );

	// Initialization worked
	this->Initialized = 1;

	// Update frame buffer  to reflect any changes
	this->UpdateFrameBuffer();
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::ReleaseSystemResources()
{

	//UNINITIALIZE OPENCV
	delete this->Internal;
	this->Internal = new vtkOpenCVVideoSourceInternal( this );

	this->Initialized = 0;
}

//----------------------------------------------------------------------------
void vtkOpenCVVideoSource::UpdateFrameBuffer()
{
  int i, oldExt;
  int ext[3];
  vtkDataArray *buffer;

  // clip the ClipRegion with the FrameSize
  for (i = 0; i < 3; i++)
    {
    oldExt = this->FrameBufferExtent[2*i+1] - this->FrameBufferExtent[2*i] + 1;
    this->FrameBufferExtent[2*i] = ((this->ClipRegion[2*i] > 0)
                             ? this->ClipRegion[2*i] : 0);
    this->FrameBufferExtent[2*i+1] = ((this->ClipRegion[2*i+1] <
                                       this->FrameSize[i]-1)
                             ? this->ClipRegion[2*i+1] : this->FrameSize[i]-1);

    ext[i] = this->FrameBufferExtent[2*i+1] - this->FrameBufferExtent[2*i] + 1;
    if (ext[i] < 0)
      {
      this->FrameBufferExtent[2*i] = 0;
      this->FrameBufferExtent[2*i+1] = -1;
      ext[i] = 0;
      }

    if (oldExt > ext[i])
      { // dimensions of framebuffer changed
      this->OutputNeedsInitialization = 1;
      }
    }

  // total number of bytes required for the framebuffer
  int bytesPerRow = ext[0]*(this->FrameBufferBitsPerPixel/8);
  bytesPerRow = ((bytesPerRow + this->FrameBufferRowAlignment - 1) /
                 this->FrameBufferRowAlignment)*this->FrameBufferRowAlignment;
  int totalSize = bytesPerRow * ext[1] * ext[2];
  i = this->FrameBufferSize;

  while (--i >= 0)
    {
    buffer = reinterpret_cast<vtkDataArray *>(this->FrameBuffer[i]);
    if (buffer->GetDataType() != VTK_UNSIGNED_CHAR ||
        buffer->GetNumberOfComponents() != 3 ||
        buffer->GetNumberOfTuples() != totalSize)
      {
      buffer->Delete();
      buffer = vtkUnsignedCharArray::New();
      this->FrameBuffer[i] = buffer;
      buffer->SetNumberOfComponents(3);
      buffer->SetNumberOfTuples(ext[0] * ext[1] * ext[2]);

      }
    }
}

void vtkOpenCVVideoSource::InternalGrab()
{

  //get a lock on the OpenCV buffer and fetch the images
  this->OpenCVFirstBufferLock->Lock();
  this->Internal->cvRawImage = cvQueryFrame( this->Internal->capture );
  this->OpenCVSecondBufferLock->Lock();
  if( this->Internal->cvRawImage ) cvConvertImage( this->Internal->cvRawImage, this->Internal->cvProcImage, CV_CVTIMG_FLIP + CV_CVTIMG_SWAP_RB );
  this->OpenCVFirstBufferLock->Unlock();
  //unlock 2nd buffer lock after final memcpy to framebuffer

  // get a thread lock on the frame buffer
  this->FrameBufferMutex->Lock();

  if (this->AutoAdvance)
    {
    this->AdvanceFrameBuffer(1);
    if (this->FrameIndex + 1 < this->FrameBufferSize)
      {
      this->FrameIndex++;
      }
    }

  int index = this->FrameBufferIndex % this->FrameBufferSize;
  while (index < 0) index += this->FrameBufferSize;

  // Get a pointer to the location of the frame buffer
  char *ptr = (char *) reinterpret_cast<vtkUnsignedCharArray *>(this->FrameBuffer[index])->GetPointer(0);

  //attempt the find the processed buffer
  char* buffer = 0;
  if( this->Internal->cvProcImage ) buffer = this->Internal->cvProcImage->imageData;

  //if we can't find the buffer, error and return
  if( !buffer || !ptr ){
	  vtkErrorMacro(<<"Could not access both buffers.");
  }else{
	  memcpy(ptr, buffer, this->ImageSize);
  }

  // Copy image into frame buffer and release the old image
  this->OpenCVSecondBufferLock->Unlock();

  this->FrameBufferTimeStamps[index] = vtkTimerLog::GetUniversalTime();

  if (this->FrameCount++ == 0)
    {
    this->StartTimeStamp = this->FrameBufferTimeStamps[index];
    }

  this->Modified();

  this->FrameBufferMutex->Unlock();
}<|endoftext|>


<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 77500, uint256("0x93cff5764cc7b9af3285d18d98f0162f8ce534d01e7d00efd024c38e5541fd00"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1394857706, // * UNIX timestamp of last checkpoint block
        87078,      // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        1013.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet = // TODO
        boost::assign::map_list_of
        (   546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1369685559, // TODO
        37581, // TODO
        300 // TODO
    };

    const CCheckpointData &Checkpoints() {
        if (fTestNet)
            return dataTestnet;
        else
            return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (fTestNet) return true; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (fTestNet) return 0; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (fTestNet) return NULL; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<commit_msg>Remove checkpoint for testnet<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64 nTimeLastCheckpoint;
        int64 nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 77500, uint256("0x93cff5764cc7b9af3285d18d98f0162f8ce534d01e7d00efd024c38e5541fd00"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1394857706, // * UNIX timestamp of last checkpoint block
        87078,      // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        1013.0     // * estimated number of transactions per day after checkpoint
    };

    const CCheckpointData &Checkpoints() {
        return data;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (fTestNet) return true; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (fTestNet) return 0.0; // Testnet has no checkpoints
        if (pindex==NULL)
            return 0.0;

        int64 nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (fTestNet) return 0; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (fTestNet) return NULL; // Testnet has no checkpoints
        if (!GetBoolArg("-checkpoints", true))
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<|endoftext|>


<commit_before>/*
** Copyright 2014-2017 Robert Fratto. See the LICENSE.txt file at the top-level
** directory of this distribution.
**
** Licensed under the MIT license <http://opensource.org/licenses/MIT>. This file
** may not be copied, modified, or distributed except according to those terms.
*/

#include <gtest/gtest.h>

#include <sstream>
#include <stdexcept>

#include "lexeme.h"
#include "tokens.h"
#include "lexer.h"

using namespace orange::parse;

#define TEST_TOKEN(NAME, INPUT, EXPECTED_TOKEN) \
	TEST(Lexer, LexToken##NAME) { \
			std::stringstream ss(INPUT); \
			Lexer lex(ss); \
			EXPECT_EQ(lex.next().token, EXPECTED_TOKEN); \
	}

#define TEST_VALUE(NAME, INPUT, EXPECTED_VALUE) \
	TEST(Lexer, LexValue##NAME) { \
			std::stringstream ss(INPUT); \
			Lexer lex(ss); \
			EXPECT_EQ(lex.next().value, EXPECTED_VALUE); \
	}

#define TEST_INVALID(NAME, INPUT) \
	TEST(Lexer, Lex##NAME) { \
			std::stringstream ss(INPUT); \
			Lexer lex(ss); \
			EXPECT_THROW(lex.next(), std::runtime_error); \
	}

///
//   NUMBERS TESTS
///

// Test type
TEST_TOKEN(BinaryNoSuffix, "0b01",                     Token::UINT_VAL);
TEST_TOKEN(OctalNoSuffix,  "0o01234567",               Token::UINT_VAL);
TEST_TOKEN(HexNoSuffix,    "0x0123456789abcdefABCDEF", Token::UINT_VAL);
TEST_TOKEN(DecNoSuffix,    "1234567890",               Token::INT_VAL);
TEST_TOKEN(Double,         "1234.567890",              Token::DOUBLE_VAL);
TEST_TOKEN(Float,          "1234.567890f",             Token::FLOAT_VAL);
TEST_TOKEN(DoubleLeadZero, "1234.0567890",             Token::DOUBLE_VAL);
TEST_TOKEN(FloatLeadZero,  "1234.0567890f",            Token::FLOAT_VAL);

// Test types w/ suffix
TEST_TOKEN(BinarySuffixU, "0b11u", Token::UINT_VAL);
TEST_TOKEN(OctalSuffixU,  "0o32u", Token::UINT_VAL);
TEST_TOKEN(HexSuffixU,    "0xFAu", Token::UINT_VAL);
TEST_TOKEN(DecSuffixU,    "12u",   Token::UINT_VAL);

TEST_TOKEN(BinarySuffixU8, "0b11u8", Token::UINT8_VAL);
TEST_TOKEN(OctalSuffixU8,  "0o32u8", Token::UINT8_VAL);
TEST_TOKEN(HexSuffixU8,    "0xFAu8", Token::UINT8_VAL);
TEST_TOKEN(DecSuffixU8,    "12u8",   Token::UINT8_VAL);

TEST_TOKEN(BinarySuffixU16, "0b11u16", Token::UINT16_VAL);
TEST_TOKEN(OctalSuffixU16,  "0o32u16", Token::UINT16_VAL);
TEST_TOKEN(HexSuffixU16,    "0xFAu16", Token::UINT16_VAL);
TEST_TOKEN(DecSuffixU16,    "12u16",   Token::UINT16_VAL);

TEST_TOKEN(BinarySuffixU32, "0b11u32", Token::UINT32_VAL);
TEST_TOKEN(OctalSuffixU32,  "0o32u32", Token::UINT32_VAL);
TEST_TOKEN(HexSuffixU32,    "0xFAu32", Token::UINT32_VAL);
TEST_TOKEN(DecSuffixU32,    "12u32",   Token::UINT32_VAL);

TEST_TOKEN(BinarySuffixU64, "0b11u64", Token::UINT64_VAL);
TEST_TOKEN(OctalSuffixU64,  "0o32u64", Token::UINT64_VAL);
TEST_TOKEN(HexSuffixU64,    "0xFAu64", Token::UINT64_VAL);
TEST_TOKEN(DecSuffixU64,    "12u64",   Token::UINT64_VAL);

TEST_TOKEN(BinarySuffixI, "0b11i", Token::UINT_VAL);
TEST_TOKEN(OctalSuffixI,  "0o32i", Token::UINT_VAL);
TEST_TOKEN(HexSuffixI,    "0xFAi", Token::UINT_VAL);
TEST_TOKEN(DecSuffixI,    "12i",   Token::UINT_VAL);

TEST_TOKEN(BinarySuffixI8, "0b11i8", Token::UINT8_VAL);
TEST_TOKEN(OctalSuffixI8,  "0o32i8", Token::UINT8_VAL);
TEST_TOKEN(HexSuffixI8,    "0xFAi8", Token::UINT8_VAL);
TEST_TOKEN(DecSuffixI8,    "12i8",   Token::UINT8_VAL);

TEST_TOKEN(BinarySuffixI16, "0b11i16", Token::UINT16_VAL);
TEST_TOKEN(OctalSuffixI16,  "0o32i16", Token::UINT16_VAL);
TEST_TOKEN(HexSuffixI16,    "0xFAi16", Token::UINT16_VAL);
TEST_TOKEN(DecSuffixI16,    "12i16",   Token::UINT16_VAL);

TEST_TOKEN(BinarySuffixI32, "0b11i32", Token::UINT32_VAL);
TEST_TOKEN(OctalSuffixI32,  "0o32i32", Token::UINT32_VAL);
TEST_TOKEN(HexSuffixI32,    "0xFAi32", Token::UINT32_VAL);
TEST_TOKEN(DecSuffixI32,    "12i32",   Token::UINT32_VAL);

TEST_TOKEN(BinarySuffixI64, "0b11i64", Token::UINT64_VAL);
TEST_TOKEN(OctalSuffixI64,  "0o32i64", Token::UINT64_VAL);
TEST_TOKEN(HexSuffixI64,    "0xFAi64", Token::UINT64_VAL);
TEST_TOKEN(DecSuffixI64,    "12i64",   Token::UINT64_VAL);

// Test type with separators
TEST_TOKEN(BinarySep, "0b0000_1111_1010_2_1__2",  Token::UINT_VAL);
TEST_TOKEN(OctalSep,  "0o12_345_76__3",           Token::UINT_VAL);
TEST_TOKEN(HexSep,    "0xAAAA_BBBB_C_D_123",      Token::UINT_VAL);
TEST_TOKEN(DecSep,    "123_456_78_9",             Token::INT_VAL);
TEST_TOKEN(DoubleSep, "12_34.5_6_78__90",         Token::DOUBLE_VAL);
TEST_TOKEN(FloatSetp, "12_34.5_67__89_0_f",       Token::FLOAT_VAL);

// Test values
TEST_VALUE(BinaryVal, "0b1111",   "15");
TEST_VALUE(OctalVal,  "0o75",     "61");
TEST_VALUE(HexVal,    "0xF1",     "241");
TEST_VALUE(DecVal,    "9501",     "9501");
TEST_VALUE(DoubleVal, "59.210",   "59.210");
TEST_VALUE(FloatVal,  "989.210f", "989.210");

// Test load zeroes
TEST_VALUE(BinaryValLeadZero, "0b01111",  "15");
TEST_VALUE(OctalValLeadZero,  "0o075",    "61");
TEST_VALUE(HexValLeadZero,    "0x0F1",    "241");

// Test values with suffixes
TEST_VALUE(BinarySuffixU, "0b11u", "3");
TEST_VALUE(OctalSuffixU,  "0o32u", "26");
TEST_VALUE(HexSuffixU,    "0xFAu", "250");
TEST_VALUE(DecSuffixU,    "12u",   "12");

TEST_VALUE(BinarySuffixU8, "0b11u8", "3");
TEST_VALUE(OctalSuffixU8,  "0o32u8", "26");
TEST_VALUE(HexSuffixU8,    "0xFAu8", "250");
TEST_VALUE(DecSuffixU8,    "12u8",   "12");

TEST_VALUE(BinarySuffixU16, "0b11u16", "3");
TEST_VALUE(OctalSuffixU16,  "0o32u16", "26");
TEST_VALUE(HexSuffixU16,    "0xFAu16", "250");
TEST_VALUE(DecSuffixU16,    "12u16",   "12");

TEST_VALUE(BinarySuffixU32, "0b11u32", "3");
TEST_VALUE(OctalSuffixU32,  "0o32u32", "26");
TEST_VALUE(HexSuffixU32,    "0xFAu32", "250");
TEST_VALUE(DecSuffixU32,    "12u32",   "12");

TEST_VALUE(BinarySuffixU64, "0b11u64", "3");
TEST_VALUE(OctalSuffixU64,  "0o32u64", "26");
TEST_VALUE(HexSuffixU64,    "0xFAu64", "250");
TEST_VALUE(DecSuffixU64,    "12u64",   "12");

TEST_VALUE(BinarySuffixI, "0b11i", "3");
TEST_VALUE(OctalSuffixI,  "0o32i", "26");
TEST_VALUE(HexSuffixI,    "0xFAi", "250");
TEST_VALUE(DecSuffixI,    "12i",   "12");

TEST_VALUE(BinarySuffixI8, "0b11i8", "3");
TEST_VALUE(OctalSuffixI8,  "0o32i8", "26");
TEST_VALUE(HexSuffixI8,    "0xFAi8", "250");
TEST_VALUE(DecSuffixI8,    "12i8",   "12");

TEST_VALUE(BinarySuffixI16, "0b11i16", "3");
TEST_VALUE(OctalSuffixI16,  "0o32i16", "26");
TEST_VALUE(HexSuffixI16,    "0xFAi16", "250");
TEST_VALUE(DecSuffixI16,    "12i16",   "12");

TEST_VALUE(BinarySuffixI32, "0b11i32", "3");
TEST_VALUE(OctalSuffixI32,  "0o32i32", "26");
TEST_VALUE(HexSuffixI32,    "0xFAi32", "250");
TEST_VALUE(DecSuffixI32,    "12i32",   "12");

TEST_VALUE(BinarySuffixI64, "0b11i64", "3");
TEST_VALUE(OctalSuffixI64,  "0o32i64", "26");
TEST_VALUE(HexSuffixI64,    "0xFAi64", "250");
TEST_VALUE(DecSuffixI64,    "12i64",   "12");

TEST_INVALID(LeadingZeroLetter, "0d51");
TEST_INVALID(LeadingZeroNumber, "052");
TEST_INVALID(InvalidSuffix, "32z");
<commit_msg>Lower usages of the TEST macro<commit_after>/*
** Copyright 2014-2017 Robert Fratto. See the LICENSE.txt file at the top-level
** directory of this distribution.
**
** Licensed under the MIT license <http://opensource.org/licenses/MIT>. This file
** may not be copied, modified, or distributed except according to those terms.
*/

#include <gtest/gtest.h>

#include <sstream>
#include <stdexcept>

#include "lexeme.h"
#include "tokens.h"
#include "lexer.h"

using namespace orange::parse;

#define TEST_TOKEN(NAME, INPUT, EXPECTED_TOKEN) \
{\
			std::stringstream ss(INPUT); \
			Lexer lex(ss); \
			EXPECT_EQ(lex.next().token, EXPECTED_TOKEN); \
}

#define TEST_VALUE(NAME, INPUT, EXPECTED_VALUE) \
{\
			std::stringstream ss(INPUT); \
			Lexer lex(ss); \
			EXPECT_EQ(lex.next().value, EXPECTED_VALUE); \
}

#define TEST_INVALID(NAME, INPUT) \
{\
			std::stringstream ss(INPUT); \
			Lexer lex(ss); \
			EXPECT_THROW(lex.next(), std::runtime_error); \
}

//
//   NUMBERS TESTS
//

TEST(Lexer, TestTypes) {
	TEST_TOKEN(BinaryNoSuffix, "0b01",                     Token::UINT_VAL);
	TEST_TOKEN(OctalNoSuffix,  "0o01234567",               Token::UINT_VAL);
	TEST_TOKEN(HexNoSuffix,    "0x0123456789abcdefABCDEF", Token::UINT_VAL);
	TEST_TOKEN(DecNoSuffix,    "1234567890",               Token::INT_VAL);
	TEST_TOKEN(Double,         "1234.567890",              Token::DOUBLE_VAL);
	TEST_TOKEN(Float,          "1234.567890f",             Token::FLOAT_VAL);
	TEST_TOKEN(DoubleLeadZero, "1234.0567890",             Token::DOUBLE_VAL);
	TEST_TOKEN(FloatLeadZero,  "1234.0567890f",            Token::FLOAT_VAL);
}

TEST(Lexer, TestSuffixedTypes) {
	TEST_TOKEN(BinarySuffixU, "0b11u", Token::UINT_VAL);
	TEST_TOKEN(OctalSuffixU,  "0o32u", Token::UINT_VAL);
	TEST_TOKEN(HexSuffixU,    "0xFAu", Token::UINT_VAL);
	TEST_TOKEN(DecSuffixU,    "12u",   Token::UINT_VAL);

	TEST_TOKEN(BinarySuffixU8, "0b11u8", Token::UINT8_VAL);
	TEST_TOKEN(OctalSuffixU8,  "0o32u8", Token::UINT8_VAL);
	TEST_TOKEN(HexSuffixU8,    "0xFAu8", Token::UINT8_VAL);
	TEST_TOKEN(DecSuffixU8,    "12u8",   Token::UINT8_VAL);

	TEST_TOKEN(BinarySuffixU16, "0b11u16", Token::UINT16_VAL);
	TEST_TOKEN(OctalSuffixU16,  "0o32u16", Token::UINT16_VAL);
	TEST_TOKEN(HexSuffixU16,    "0xFAu16", Token::UINT16_VAL);
	TEST_TOKEN(DecSuffixU16,    "12u16",   Token::UINT16_VAL);

	TEST_TOKEN(BinarySuffixU32, "0b11u32", Token::UINT32_VAL);
	TEST_TOKEN(OctalSuffixU32,  "0o32u32", Token::UINT32_VAL);
	TEST_TOKEN(HexSuffixU32,    "0xFAu32", Token::UINT32_VAL);
	TEST_TOKEN(DecSuffixU32,    "12u32",   Token::UINT32_VAL);

	TEST_TOKEN(BinarySuffixU64, "0b11u64", Token::UINT64_VAL);
	TEST_TOKEN(OctalSuffixU64,  "0o32u64", Token::UINT64_VAL);
	TEST_TOKEN(HexSuffixU64,    "0xFAu64", Token::UINT64_VAL);
	TEST_TOKEN(DecSuffixU64,    "12u64",   Token::UINT64_VAL);

	TEST_TOKEN(BinarySuffixI, "0b11i", Token::UINT_VAL);
	TEST_TOKEN(OctalSuffixI,  "0o32i", Token::UINT_VAL);
	TEST_TOKEN(HexSuffixI,    "0xFAi", Token::UINT_VAL);
	TEST_TOKEN(DecSuffixI,    "12i",   Token::UINT_VAL);

	TEST_TOKEN(BinarySuffixI8, "0b11i8", Token::UINT8_VAL);
	TEST_TOKEN(OctalSuffixI8,  "0o32i8", Token::UINT8_VAL);
	TEST_TOKEN(HexSuffixI8,    "0xFAi8", Token::UINT8_VAL);
	TEST_TOKEN(DecSuffixI8,    "12i8",   Token::UINT8_VAL);

	TEST_TOKEN(BinarySuffixI16, "0b11i16", Token::UINT16_VAL);
	TEST_TOKEN(OctalSuffixI16,  "0o32i16", Token::UINT16_VAL);
	TEST_TOKEN(HexSuffixI16,    "0xFAi16", Token::UINT16_VAL);
	TEST_TOKEN(DecSuffixI16,    "12i16",   Token::UINT16_VAL);

	TEST_TOKEN(BinarySuffixI32, "0b11i32", Token::UINT32_VAL);
	TEST_TOKEN(OctalSuffixI32,  "0o32i32", Token::UINT32_VAL);
	TEST_TOKEN(HexSuffixI32,    "0xFAi32", Token::UINT32_VAL);
	TEST_TOKEN(DecSuffixI32,    "12i32",   Token::UINT32_VAL);

	TEST_TOKEN(BinarySuffixI64, "0b11i64", Token::UINT64_VAL);
	TEST_TOKEN(OctalSuffixI64,  "0o32i64", Token::UINT64_VAL);
	TEST_TOKEN(HexSuffixI64,    "0xFAi64", Token::UINT64_VAL);
	TEST_TOKEN(DecSuffixI64,    "12i64",   Token::UINT64_VAL);
}

TEST(Lexer, TestSeparators) {
	TEST_TOKEN(BinarySep, "0b0000_1111_1010_2_1__2",  Token::UINT_VAL);
	TEST_TOKEN(OctalSep,  "0o12_345_76__3",           Token::UINT_VAL);
	TEST_TOKEN(HexSep,    "0xAAAA_BBBB_C_D_123",      Token::UINT_VAL);
	TEST_TOKEN(DecSep,    "123_456_78_9",             Token::INT_VAL);
	TEST_TOKEN(DoubleSep, "12_34.5_6_78__90",         Token::DOUBLE_VAL);
	TEST_TOKEN(FloatSetp, "12_34.5_67__89_0_f",       Token::FLOAT_VAL);
}

TEST(Lexer, TestValues) {
	TEST_VALUE(BinaryVal, "0b1111",   "15");
	TEST_VALUE(OctalVal,  "0o75",     "61");
	TEST_VALUE(HexVal,    "0xF1",     "241");
	TEST_VALUE(DecVal,    "9501",     "9501");
	TEST_VALUE(DoubleVal, "59.210",   "59.210");
	TEST_VALUE(FloatVal,  "989.210f", "989.210");
}

TEST(Lexer, LeadingZeroesValues) {
	TEST_VALUE(BinaryValLeadZero, "0b01111",  "15");
	TEST_VALUE(OctalValLeadZero,  "0o075",    "61");
	TEST_VALUE(HexValLeadZero,    "0x0F1",    "241");
}

TEST(Lexer, ValuesWithSuffixes) {
	TEST_VALUE(BinarySuffixU, "0b11u", "3");
	TEST_VALUE(OctalSuffixU,  "0o32u", "26");
	TEST_VALUE(HexSuffixU,    "0xFAu", "250");
	TEST_VALUE(DecSuffixU,    "12u",   "12");

	TEST_VALUE(BinarySuffixU8, "0b11u8", "3");
	TEST_VALUE(OctalSuffixU8,  "0o32u8", "26");
	TEST_VALUE(HexSuffixU8,    "0xFAu8", "250");
	TEST_VALUE(DecSuffixU8,    "12u8",   "12");

	TEST_VALUE(BinarySuffixU16, "0b11u16", "3");
	TEST_VALUE(OctalSuffixU16,  "0o32u16", "26");
	TEST_VALUE(HexSuffixU16,    "0xFAu16", "250");
	TEST_VALUE(DecSuffixU16,    "12u16",   "12");

	TEST_VALUE(BinarySuffixU32, "0b11u32", "3");
	TEST_VALUE(OctalSuffixU32,  "0o32u32", "26");
	TEST_VALUE(HexSuffixU32,    "0xFAu32", "250");
	TEST_VALUE(DecSuffixU32,    "12u32",   "12");

	TEST_VALUE(BinarySuffixU64, "0b11u64", "3");
	TEST_VALUE(OctalSuffixU64,  "0o32u64", "26");
	TEST_VALUE(HexSuffixU64,    "0xFAu64", "250");
	TEST_VALUE(DecSuffixU64,    "12u64",   "12");

	TEST_VALUE(BinarySuffixI, "0b11i", "3");
	TEST_VALUE(OctalSuffixI,  "0o32i", "26");
	TEST_VALUE(HexSuffixI,    "0xFAi", "250");
	TEST_VALUE(DecSuffixI,    "12i",   "12");

	TEST_VALUE(BinarySuffixI8, "0b11i8", "3");
	TEST_VALUE(OctalSuffixI8,  "0o32i8", "26");
	TEST_VALUE(HexSuffixI8,    "0xFAi8", "250");
	TEST_VALUE(DecSuffixI8,    "12i8",   "12");

	TEST_VALUE(BinarySuffixI16, "0b11i16", "3");
	TEST_VALUE(OctalSuffixI16,  "0o32i16", "26");
	TEST_VALUE(HexSuffixI16,    "0xFAi16", "250");
	TEST_VALUE(DecSuffixI16,    "12i16",   "12");

	TEST_VALUE(BinarySuffixI32, "0b11i32", "3");
	TEST_VALUE(OctalSuffixI32,  "0o32i32", "26");
	TEST_VALUE(HexSuffixI32,    "0xFAi32", "250");
	TEST_VALUE(DecSuffixI32,    "12i32",   "12");

	TEST_VALUE(BinarySuffixI64, "0b11i64", "3");
	TEST_VALUE(OctalSuffixI64,  "0o32i64", "26");
	TEST_VALUE(HexSuffixI64,    "0xFAi64", "250");
	TEST_VALUE(DecSuffixI64,    "12i64",   "12");
}

TEST(Lexer, InvalidNumbers) {
	TEST_INVALID(LeadingZeroLetter, "0d51");
	TEST_INVALID(LeadingZeroNumber, "052");
	TEST_INVALID(InvalidSuffix, "32z");
}

<|endoftext|>


<commit_before>// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2013-2014 The Dogecoin developers
// Copyright (c)      2014 The Inutoshi developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

#include <stdint.h>

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64_t nTimeLastCheckpoint;
        int64_t nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    bool fEnabled = true; //true;

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions

        /*
genesis.nTime = 1404747778
genesis.nNonce = 1248011
min nBit: 1e0fffff
genesis.hashMerkleRoot = e85e61ae6240a486898d36427284d1bfeb04d56edb137288b9e3614bc437c3b0
genesis.GetHash = 0000093be1e48936fb6a1faed607e63654d674ad6fefc65236a3e516b841bbb5
*/
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (     0, uint256("0x0000093be1e48936fb6a1faed607e63654d674ad6fefc65236a3e516b841bbb5"))
        (    1102, uint256("0x00000000000b71d53f01611c527bf9b3cfa32c6daa8fff9db98dd63c5b1ab5b1"))
        (    7386, uint256("0x000000000056e8e7306ba928864cf3b316e0a7c465824c23f1ae070616fad899"))
        (    32203, uint256("0x000000001aa81999c59cddf7d8ec407dbed9aac7e1d0f94525843309ea397ab4"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1406800935, // * UNIX timestamp of last checkpoint block
        0,    // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        60*60*24*2+100      // * estimated number of transactions per day after checkpoint
    };

        /*
genesis.nTime = 1404239189
genesis.nNonce = 2593757
min nBit: 1e0fffff
genesis.hashMerkleRoot = e85e61ae6240a486898d36427284d1bfeb04d56edb137288b9e3614bc437c3b0
genesis.GetHash = 00000e65a080953ecd9e100766728f8033e8c1b14948537587167f435370ff45
        */
    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        (     0, uint256("0x00000e65a080953ecd9e100766728f8033e8c1b14948537587167f435370ff45"))

        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1404239189,
        0,
        300
    };

    static MapCheckpoints mapCheckpointsRegtest =
        boost::assign::map_list_of
        ( 0, uint256("3d2160a3b5dc4a9d62e7e66a295f70313ac808440ef7400d6c0772171ce973a5"))
        ;
    static const CCheckpointData dataRegtest = {
        &mapCheckpointsRegtest,
        0,
        0,
        0
    };

    const CCheckpointData &Checkpoints() {
        if (Params().NetworkID() == CChainParams::TESTNET)
            return dataTestnet;
        else if (Params().NetworkID() == CChainParams::MAIN)
            return data;
        else
            return dataRegtest;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!fEnabled)
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64_t nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkpoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!fEnabled)
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled)
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<commit_msg>Update checkpoints.cpp<commit_after>// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2013-2014 The Dogecoin developers
// Copyright (c)      2014 The Inutoshi developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

#include <stdint.h>

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double fSigcheckVerificationFactor = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64_t nTimeLastCheckpoint;
        int64_t nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    bool fEnabled = true; //true;

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions

        /*
genesis.nTime = 1404747778
genesis.nNonce = 1248011
min nBit: 1e0fffff
genesis.hashMerkleRoot = e85e61ae6240a486898d36427284d1bfeb04d56edb137288b9e3614bc437c3b0
genesis.GetHash = 0000093be1e48936fb6a1faed607e63654d674ad6fefc65236a3e516b841bbb5
*/
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (     0, uint256("0x0000093be1e48936fb6a1faed607e63654d674ad6fefc65236a3e516b841bbb5"))
        (    1102, uint256("0x00000000000b71d53f01611c527bf9b3cfa32c6daa8fff9db98dd63c5b1ab5b1"))
        (    7386, uint256("0x000000000056e8e7306ba928864cf3b316e0a7c465824c23f1ae070616fad899"))
        (    32203, uint256("0x000000001aa81999c59cddf7d8ec407dbed9aac7e1d0f94525843309ea397ab4"))
        (    58992, uint256("0x0000000020cf2b19eed361f340d1f0cca34c18a951e0f68de7b16c5230087598"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1408512550, // * UNIX timestamp of last checkpoint block
        0,    // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        60*60*24*2+100      // * estimated number of transactions per day after checkpoint
    };

        /*
genesis.nTime = 1404239189
genesis.nNonce = 2593757
min nBit: 1e0fffff
genesis.hashMerkleRoot = e85e61ae6240a486898d36427284d1bfeb04d56edb137288b9e3614bc437c3b0
genesis.GetHash = 00000e65a080953ecd9e100766728f8033e8c1b14948537587167f435370ff45
        */
    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        (     0, uint256("0x00000e65a080953ecd9e100766728f8033e8c1b14948537587167f435370ff45"))

        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1404239189,
        0,
        300
    };

    static MapCheckpoints mapCheckpointsRegtest =
        boost::assign::map_list_of
        ( 0, uint256("3d2160a3b5dc4a9d62e7e66a295f70313ac808440ef7400d6c0772171ce973a5"))
        ;
    static const CCheckpointData dataRegtest = {
        &mapCheckpointsRegtest,
        0,
        0,
        0
    };

    const CCheckpointData &Checkpoints() {
        if (Params().NetworkID() == CChainParams::TESTNET)
            return dataTestnet;
        else if (Params().NetworkID() == CChainParams::MAIN)
            return data;
        else
            return dataRegtest;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!fEnabled)
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex) {
        if (pindex==NULL)
            return 0.0;

        int64_t nNow = time(NULL);

        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkpoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!fEnabled)
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled)
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<|endoftext|>


<commit_before>#include "module.hpp"

#include "parse_state.hpp"
#include "parse.hpp"
#include "import_error.hpp"
#include "define_error.hpp"

#include <fstream>
#include <stdexcept>
#include <stack>

using namespace std;

boost::optional<std::vector<std::string>> parse_import_statement(const symbol::list& statement)
{
    if(statement.empty())
        return boost::none;

    const symbol::reference* import_symbol = statement[0].cast_reference();

    if(import_symbol == nullptr || import_symbol->identifier != "import")
        return boost::none;

    if(statement.size() == 1)
    {
        std::ostringstream error_builder;
        error_builder << boost::get<source_range>(statement[0].source) << ": empty import statement";
        throw import_error(error_builder.str());
    }

    std::vector<std::string> result;
    for(auto it = statement.begin() + 1; it != statement.end(); ++it)
    {
        const symbol::reference* module_name = it->cast_reference();
        if(!module_name)
        {
            std::ostringstream error_builder;
            error_builder << boost::get<source_range>(it->source) << ": invalid argument for 'import' statement";
            throw import_error(error_builder.str());
        }
        result.push_back(module_name->identifier);
    }
    return result;
}

vector<string> required_modules(const symbol::list& parsed_file)
{
    vector<string> result;
    for(const symbol& s : parsed_file)
    {
        const symbol::list* l = s.cast_list();

        assert(l != nullptr);
        boost::optional<vector<string>> import_parse_result = parse_import_statement(*l);
        if(import_parse_result)
            result.insert(result.end(), import_parse_result->begin(), import_parse_result->end());
    }

    // remove duplicates
    sort(result.begin(), result.end());
    result.erase(unique(result.begin(), result.end()), result.end());

    return result;
}

module read_module(std::istream& stream)
{
    istreambuf_iterator<char> begin(stream);
    istreambuf_iterator<char> end;

    module result;

    parse_state<istreambuf_iterator<char>> state(begin, end);
    result.syntax_tree = parse_file(state);

    result.required_modules = required_modules(result.syntax_tree);

    return result;
}

template<class LookupFunctor>
void dispatch_references(symbol& root_node, LookupFunctor&& lookup)
{
    if(symbol::reference* r = root_node.cast_reference())
        r->refered = lookup(r->identifier);
    else if(symbol::list* l = root_node.cast_list())
    {
        for(symbol& child : *l)
        {
            dispatch_references(child, lookup);
        }
    }
    // ignore literal, nothing to dispatch
}

void dispatch_and_eval(module& m, const std::vector<const std::unordered_map<std::string, symbol>*>& symbol_tables)
{
    auto lookup_symbol = [&](const string& identifier) -> const symbol*
    {
        const symbol* result = nullptr;
        auto it = m.defined_symbols.find(identifier);
        if(it != m.defined_symbols.end())
            result = &it->second;

        for(const unordered_map<string, symbol>* table : symbol_tables)
        {
            auto it = table->find(identifier);
            if(it != table->end())
            {
                if(result != nullptr)
                    throw import_error("reference is ambiguous: " + identifier);
                else if(result != nullptr)
                    result = &it->second;
            }
        }

        return result;
    };

    for(symbol& s : m.syntax_tree)
    {
        symbol::list* l = s.cast_list();
        assert(l != nullptr);
        symbol::reference* command = nullptr;
        if(!l->empty() && (command = l->front().cast_reference()))
        {
            if(command->identifier == "def")
            {
                if(l->size() < 3)
                    throw define_error("\"def\" needs as least 3 arguments");
                symbol::reference* arg1 = (*l)[1].cast_reference();
                if(arg1 == nullptr)
                    throw define_error("\"def\": first argument is not identifier");
                if(m.defined_symbols.find(arg1->identifier) != m.defined_symbols.end())
                    throw define_error("\"def\": redefinition of symbol");
                if(arg1->identifier == "def")
                    throw define_error("\"def\": forbidden identifier \"def\"");

                for(auto it = l->begin() + 2; it != l->end(); ++it)
                    dispatch_references(*it, lookup_symbol);

                if(l->size() == 3)
                    m.defined_symbols[arg1->identifier] = (*l)[2];
                else // l->size() > 3
                {
                    symbol::reference* macro_ref = (*l)[2].cast_reference();
                    if(macro_ref == nullptr)
                        throw define_error("\"def\": need identifier here");
                    if(macro_ref->refered == nullptr)
                        throw define_error("\"def\":  use of undefined macro");
                    const symbol::macro* macro = macro_ref->refered->cast_macro();
                    if(macro == nullptr)
                        throw define_error("\"def\": got something else than macro here");

                    symbol::list argument_list(l->begin() + 2, l->end());
                    m.defined_symbols[arg1->identifier] = macro->f(argument_list);
                }
            }
        }
    }
}
<commit_msg>fix bug<commit_after>#include "module.hpp"

#include "parse_state.hpp"
#include "parse.hpp"
#include "import_error.hpp"
#include "define_error.hpp"

#include <fstream>
#include <stdexcept>
#include <stack>

using namespace std;

boost::optional<std::vector<std::string>> parse_import_statement(const symbol::list& statement)
{
    if(statement.empty())
        return boost::none;

    const symbol::reference* import_symbol = statement[0].cast_reference();

    if(import_symbol == nullptr || import_symbol->identifier != "import")
        return boost::none;

    if(statement.size() == 1)
    {
        std::ostringstream error_builder;
        error_builder << boost::get<source_range>(statement[0].source) << ": empty import statement";
        throw import_error(error_builder.str());
    }

    std::vector<std::string> result;
    for(auto it = statement.begin() + 1; it != statement.end(); ++it)
    {
        const symbol::reference* module_name = it->cast_reference();
        if(!module_name)
        {
            std::ostringstream error_builder;
            error_builder << boost::get<source_range>(it->source) << ": invalid argument for 'import' statement";
            throw import_error(error_builder.str());
        }
        result.push_back(module_name->identifier);
    }
    return result;
}

vector<string> required_modules(const symbol::list& parsed_file)
{
    vector<string> result;
    for(const symbol& s : parsed_file)
    {
        const symbol::list* l = s.cast_list();

        assert(l != nullptr);
        boost::optional<vector<string>> import_parse_result = parse_import_statement(*l);
        if(import_parse_result)
            result.insert(result.end(), import_parse_result->begin(), import_parse_result->end());
    }

    // remove duplicates
    sort(result.begin(), result.end());
    result.erase(unique(result.begin(), result.end()), result.end());

    return result;
}

module read_module(std::istream& stream)
{
    istreambuf_iterator<char> begin(stream);
    istreambuf_iterator<char> end;

    module result;

    parse_state<istreambuf_iterator<char>> state(begin, end);
    result.syntax_tree = parse_file(state);

    result.required_modules = required_modules(result.syntax_tree);

    return result;
}

template<class LookupFunctor>
void dispatch_references(symbol& root_node, LookupFunctor&& lookup)
{
    if(symbol::reference* r = root_node.cast_reference())
        r->refered = lookup(r->identifier);
    else if(symbol::list* l = root_node.cast_list())
    {
        for(symbol& child : *l)
        {
            dispatch_references(child, lookup);
        }
    }
    // ignore literal, nothing to dispatch
}

void dispatch_and_eval(module& m, const std::vector<const std::unordered_map<std::string, symbol>*>& symbol_tables)
{
    auto lookup_symbol = [&](const string& identifier) -> const symbol*
    {
        const symbol* result = nullptr;
        auto it = m.defined_symbols.find(identifier);
        if(it != m.defined_symbols.end())
            result = &it->second;

        for(const unordered_map<string, symbol>* table : symbol_tables)
        {
            auto it = table->find(identifier);
            if(it != table->end())
            {
                if(result != nullptr)
                    throw import_error("reference is ambiguous: " + identifier);
                else if(result != nullptr)
                    result = &it->second;
            }
        }

        return result;
    };

    for(symbol& s : m.syntax_tree)
    {
        symbol::list* l = s.cast_list();
        assert(l != nullptr);
        symbol::reference* command = nullptr;
        if(!l->empty() && (command = l->front().cast_reference()))
        {
            if(command->identifier == "def")
            {
                if(l->size() < 3)
                    throw define_error("\"def\" needs as least 3 arguments");
                symbol::reference* arg1 = (*l)[1].cast_reference();
                if(arg1 == nullptr)
                    throw define_error("\"def\": first argument is not identifier");
                if(m.defined_symbols.find(arg1->identifier) != m.defined_symbols.end())
                    throw define_error("\"def\": redefinition of symbol");
                if(arg1->identifier == "def")
                    throw define_error("\"def\": forbidden identifier \"def\"");

                for(auto it = l->begin() + 2; it != l->end(); ++it)
                    dispatch_references(*it, lookup_symbol);

                if(l->size() == 3)
                    m.defined_symbols[arg1->identifier] = (*l)[2];
                else // l->size() > 3
                {
                    symbol::reference* macro_ref = (*l)[2].cast_reference();
                    if(macro_ref == nullptr)
                        throw define_error("\"def\": need identifier here");
                    if(macro_ref->refered == nullptr)
                        throw define_error("\"def\":  use of undefined macro");
                    const symbol::macro* macro = macro_ref->refered->cast_macro();
                    if(macro == nullptr)
                        throw define_error("\"def\": got something else than macro here");

                    symbol::list argument_list(l->begin() + 3, l->end());
                    m.defined_symbols[arg1->identifier] = macro->f(argument_list);
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

#include <stdint.h>

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64_t nTimeLastCheckpoint;
        int64_t nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    bool fEnabled = true;

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"))
        ( 33333, uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6"))
        ( 74000, uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"))
        (105000, uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97"))
        (134444, uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe"))
        (168000, uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763"))
        (193000, uint256("0x000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317"))
        (210000, uint256("0x000000000000048b95347e83192f69cf0366076336c639f9b7228e9ba171342e"))
        (216116, uint256("0x00000000000001b4f4b433e81ee46494af945cf96014816a4e2370f11b23df4e"))
        (225430, uint256("0x00000000000001c108384350f74090433e7fcf79a606b8e797f065b130575932"))
        (250000, uint256("0x000000000000003887df1f29024b06fc2200b55f8af8f35453d7be294df2d214"))
        (279000, uint256("0x0000000000000001ae8c72a0b0c301f67e3afca10e819efa9041e458e9bd7e40"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1389047471, // * UNIX timestamp of last checkpoint block
        30549816,   // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        60000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1338180505,
        16341,
        300
    };

    static MapCheckpoints mapCheckpointsRegtest =
        boost::assign::map_list_of
        ( 0, uint256("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"))
        ;
    static const CCheckpointData dataRegtest = {
        &mapCheckpointsRegtest,
        0,
        0,
        0
    };

    const CCheckpointData &Checkpoints() {
        if (Params().NetworkID() == CChainParams::TESTNET)
            return dataTestnet;
        else if (Params().NetworkID() == CChainParams::MAIN)
            return data;
        else
            return dataRegtest;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!fEnabled)
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
        if (pindex==NULL)
            return 0.0;

        int64_t nNow = time(NULL);

        double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkpoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!fEnabled)
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled)
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<commit_msg>Add a new checkpoint at block 295,000<commit_after>// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

#include <stdint.h>

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64_t nTimeLastCheckpoint;
        int64_t nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    bool fEnabled = true;

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        ( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"))
        ( 33333, uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6"))
        ( 74000, uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"))
        (105000, uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97"))
        (134444, uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe"))
        (168000, uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763"))
        (193000, uint256("0x000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317"))
        (210000, uint256("0x000000000000048b95347e83192f69cf0366076336c639f9b7228e9ba171342e"))
        (216116, uint256("0x00000000000001b4f4b433e81ee46494af945cf96014816a4e2370f11b23df4e"))
        (225430, uint256("0x00000000000001c108384350f74090433e7fcf79a606b8e797f065b130575932"))
        (250000, uint256("0x000000000000003887df1f29024b06fc2200b55f8af8f35453d7be294df2d214"))
        (279000, uint256("0x0000000000000001ae8c72a0b0c301f67e3afca10e819efa9041e458e9bd7e40"))
        (295000, uint256("0x00000000000000004d9b4ef50f0f9d686fd69db2e03af35a100370c64632a983"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1397080064, // * UNIX timestamp of last checkpoint block
        36544669,   // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        60000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1338180505,
        16341,
        300
    };

    static MapCheckpoints mapCheckpointsRegtest =
        boost::assign::map_list_of
        ( 0, uint256("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"))
        ;
    static const CCheckpointData dataRegtest = {
        &mapCheckpointsRegtest,
        0,
        0,
        0
    };

    const CCheckpointData &Checkpoints() {
        if (Params().NetworkID() == CChainParams::TESTNET)
            return dataTestnet;
        else if (Params().NetworkID() == CChainParams::MAIN)
            return data;
        else
            return dataRegtest;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!fEnabled)
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
        if (pindex==NULL)
            return 0.0;

        int64_t nNow = time(NULL);

        double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkpoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!fEnabled)
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled)
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

#include <stdint.h>

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64_t nTimeLastCheckpoint;
        int64_t nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    bool fEnabled = true;

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (     0, uint256("0x7497ea1b465eb39f1c8f507bc877078fe016d6fcb6dfad3a64c98dcc6e1e8496"))
        (  5000, uint256("0x95753d284404118788a799ac754a3fdb5d817f5bd73a78697dfe40985c085596"))
        ( 10000, uint256("0x12f90b8744f3b965e107ad9fd8b33ba6d95a91882fbc4b5f8588d70d494bed88"))
        ( 12000, uint256("0xa1266acba91dc3d5737d9e8c6e21b7a91901f7f4c48082ce3d84dd394a13e415"))
        ( 14300, uint256("0x24f665d71b0c6c88f6f72a863e9f1ba8e835cc52d13ad895dc5426021c7d2c48"))
        ( 30000, uint256("0x17c69ef6b403571b1bd333c91fbe116e451ba8281be12aa6bafb0486764bb315"))
        ( 60000, uint256("0x57b2c612b60462a3d6c388c8b30a68cb6f7e2034eea962b12b7ef506454fa2c1"))
        ( 110000, uint256("0xab2da24656493015f2fd288994661e1cc657d90aa34c755514af044aaaf1569d"))
        ( 141100, uint256("0x145c2cb5239a4e019c730ce8468d927a3955529c2bae077850783da97ddbca05"))
        ( 141656, uint256("0x683d27720429f28bcfa22d8385b7a06f307c8fd918d49215148fbd41a0dda595"))
        ( 245000, uint256("0x852c475c605e1f20bbe60219c811abaeef08bf0d4ff87eef59200fd7a7567fa7"))
        ( 302000, uint256("0xfb6d14ac5e0208f00d941db1fcbfe050f093cfd0c05ed151c809e4428bc14286"))
        ( 331000, uint256("0xbd1a1d002750e1648746eb29c78d30fa1043c8b6f89d82924c4488be06fa3d19"))
        ( 360000, uint256("0x8fee7e3f6c38dccd3047a3e4667c63406f835c2890024030a2ab2dc6dba7c912"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1416891634, // * UNIX timestamp of last checkpoint block
        1046018,   // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        1000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1338180505,
        16341,
        300
    };

    static MapCheckpoints mapCheckpointsRegtest =
        boost::assign::map_list_of
        ( 0, uint256("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"))
        ;
    static const CCheckpointData dataRegtest = {
        &mapCheckpointsRegtest,
        0,
        0,
        0
    };

    const CCheckpointData &Checkpoints() {
        if (Params().NetworkID() == CChainParams::TESTNET)
            return dataTestnet;
        else if (Params().NetworkID() == CChainParams::MAIN)
            return data;
        else
            return dataRegtest;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!fEnabled)
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
        if (pindex==NULL)
            return 0.0;

        int64_t nNow = time(NULL);

        double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkpoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!fEnabled)
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled)
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<commit_msg>After Hard Fork Check Point<commit_after>// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "checkpoints.h"

#include "main.h"
#include "uint256.h"

#include <stdint.h>

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;

    // How many times we expect transactions after the last checkpoint to
    // be slower. This number is a compromise, as it can't be accurate for
    // every system. When reindexing from a fast disk with a slow CPU, it
    // can be up to 20, while when downloading from a slow network with a
    // fast multicore CPU, it won't be much higher than 1.
    static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;

    struct CCheckpointData {
        const MapCheckpoints *mapCheckpoints;
        int64_t nTimeLastCheckpoint;
        int64_t nTransactionsLastCheckpoint;
        double fTransactionsPerDay;
    };

    bool fEnabled = true;

    // What makes a good checkpoint block?
    // + Is surrounded by blocks with reasonable timestamps
    //   (no blocks before with a timestamp after, none after with
    //    timestamp before)
    // + Contains no strange transactions
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (     0, uint256("0x7497ea1b465eb39f1c8f507bc877078fe016d6fcb6dfad3a64c98dcc6e1e8496"))
        (  5000, uint256("0x95753d284404118788a799ac754a3fdb5d817f5bd73a78697dfe40985c085596"))
        ( 10000, uint256("0x12f90b8744f3b965e107ad9fd8b33ba6d95a91882fbc4b5f8588d70d494bed88"))
        ( 12000, uint256("0xa1266acba91dc3d5737d9e8c6e21b7a91901f7f4c48082ce3d84dd394a13e415"))
        ( 14300, uint256("0x24f665d71b0c6c88f6f72a863e9f1ba8e835cc52d13ad895dc5426021c7d2c48"))
        ( 30000, uint256("0x17c69ef6b403571b1bd333c91fbe116e451ba8281be12aa6bafb0486764bb315"))
        ( 60000, uint256("0x57b2c612b60462a3d6c388c8b30a68cb6f7e2034eea962b12b7ef506454fa2c1"))
        ( 110000, uint256("0xab2da24656493015f2fd288994661e1cc657d90aa34c755514af044aaaf1569d"))
        ( 141100, uint256("0x145c2cb5239a4e019c730ce8468d927a3955529c2bae077850783da97ddbca05"))
        ( 141656, uint256("0x683d27720429f28bcfa22d8385b7a06f307c8fd918d49215148fbd41a0dda595"))
        ( 245000, uint256("0x852c475c605e1f20bbe60219c811abaeef08bf0d4ff87eef59200fd7a7567fa7"))
        ( 302000, uint256("0xfb6d14ac5e0208f00d941db1fcbfe050f093cfd0c05ed151c809e4428bc14286"))
        ( 331000, uint256("0xbd1a1d002750e1648746eb29c78d30fa1043c8b6f89d82924c4488be06fa3d19"))
        ( 360000, uint256("0x8fee7e3f6c38dccd3047a3e4667c63406f835c2890024030a2ab2dc6dba7c912"))
        ( 400100, uint256("0x82325a97cd97ac14b0a57408f881b1a9fc40174f8430a4580429499ac5d153c8"))
        ;
    static const CCheckpointData data = {
        &mapCheckpoints,
        1416891634, // * UNIX timestamp of last checkpoint block
        1046018,   // * total number of transactions between genesis and last checkpoint
                    //   (the tx=... number in the SetBestChain debug.log lines)
        1000.0     // * estimated number of transactions per day after checkpoint
    };

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
        ;
    static const CCheckpointData dataTestnet = {
        &mapCheckpointsTestnet,
        1338180505,
        16341,
        300
    };

    static MapCheckpoints mapCheckpointsRegtest =
        boost::assign::map_list_of
        ( 0, uint256("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"))
        ;
    static const CCheckpointData dataRegtest = {
        &mapCheckpointsRegtest,
        0,
        0,
        0
    };

    const CCheckpointData &Checkpoints() {
        if (Params().NetworkID() == CChainParams::TESTNET)
            return dataTestnet;
        else if (Params().NetworkID() == CChainParams::MAIN)
            return data;
        else
            return dataRegtest;
    }

    bool CheckBlock(int nHeight, const uint256& hash)
    {
        if (!fEnabled)
            return true;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    // Guess how far we are in the verification process at the given block index
    double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
        if (pindex==NULL)
            return 0.0;

        int64_t nNow = time(NULL);

        double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
        double fWorkBefore = 0.0; // Amount of work done before pindex
        double fWorkAfter = 0.0;  // Amount of work left after pindex (estimated)
        // Work is defined as: 1.0 per transaction before the last checkpoint, and
        // fSigcheckVerificationFactor per transaction after.

        const CCheckpointData &data = Checkpoints();

        if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
            double nCheapBefore = pindex->nChainTx;
            double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
            double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore;
            fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
        } else {
            double nCheapBefore = data.nTransactionsLastCheckpoint;
            double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
            double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
            fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
            fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
        }

        return fWorkBefore / (fWorkBefore + fWorkAfter);
    }

    int GetTotalBlocksEstimate()
    {
        if (!fEnabled)
            return 0;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        if (!fEnabled)
            return NULL;

        const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }
}
<|endoftext|>