Ejemplo n.º 1
0
bool ProcessBlockMsg(BTCMessage &msg)
{
	if (!msg.VerifyChecksum() || msg.vPayload.size()<=80)	// something wrong with checksum or length, can't process it
		return false;

	// calculate hash of this block
	uint256 curBlockHash = Hash(msg.vPayload.begin(), msg.vPayload.begin()+80);

	mysqlpp::Connection *my_conn = mydb.GrabConnection();	// get a database connection
	if (mydb.IsBlockHashKnown(my_conn, &curBlockHash)) {
		mydb.ReleaseConnection(my_conn);
		return true;			// nothing to do, as we got already this block somehow (from previous download or unsollicited message)
	}
	// now do the real stuff: block is not known yet
	ChainBlocks newBlock(0);	// create new block to add, we don't know ID yet
	newBlock.hash.assign((char *)curBlockHash.begin(), 32);
	newBlock.prevhash.assign((char *)&msg.vPayload[4], 32);	// first 4 bytes are version number, not checked for now
	newBlock.height=-2;			// height not yet known

	// --> see if prevBlockHash exists in existing blocks in ChainBlocks
	int iPrevHeight = mydb.GetBlockHeightFromHash(my_conn, newBlock.prevhash);
	if (iPrevHeight>=-1) {					// this new block has a previous hash of a temporary block with known height
		newBlock.height=iPrevHeight+1;		// so height of this block is known
		int iBestHeight=mydb.GetBestHeightKnown(my_conn);
		if (newBlock.height<=iBestHeight) {	// height of new block is less or equal then best known temporary --> discard all temp blocks with this height and above
			for (iPrevHeight=iBestHeight; iPrevHeight>=newBlock.height; iPrevHeight--)
				mydb.DeleteBlockDataOfHeight(my_conn, iPrevHeight);
		}
	}
	else {									// this new block has unknown height
		if (BTCnode.GetNodeStatus()>4) {				// we have an up-to-date block chain, so this is unusual, probably a block fork happened
			int iSafeHeight = mydb.GetSafeHeight(my_conn);
			if (iSafeHeight>0) {
				uint256 hash_start;
				if (mydb.GetBlockHashFromHeight(my_conn, iSafeHeight, hash_start)) {
					if (BTCnode.SendMsg_GetBlocks(hash_start, uint256(0))) {
						BTCnode.Peer_AskedBlockHeight = iSafeHeight + 500;  // we asked up to 500 new blocks
					}
				}
			}
		}
	}
	newBlock.status = (newBlock.height>=0)? 1 : 0;

	// --> add it to ChainBlocks
	if (mydb.AddBlockToChain(my_conn, newBlock)) {	// block added successfully
		// --> add tx's to ChainTxIns and ChainTxOuts
		std::vector<unsigned char>::iterator itTxBegin;
		std::vector<unsigned char>::iterator it=msg.vPayload.begin()+80;	// we start at 80 offset with TX data
		int iNrTransactions = (int)msg.GetVarInt(it);						// retrieve the varint indicating number of transactions
		int iEachTx;
		mysqlpp::Transaction myTrans(*my_conn);
		for (iEachTx=0; iEachTx < iNrTransactions; iEachTx++) {		// loop through each transaction
			itTxBegin = it;											// remember where current transaction starts for hash calculation later on
			ChainTxs newTx(newBlock.ID, iEachTx);					// insert incomplete Tx as we need referencial integrity on depending TxIns and TxOuts
			if (mydb.InsertChainTx(my_conn, newTx)) {
				it +=4;		// skip version number
				int iNrTxIO = (int)msg.GetVarInt(it);				// number of input transactions
				int iEachTxIO;
				for (iEachTxIO=0; iEachTxIO < iNrTxIO; iEachTxIO++) {
					// loop through each "in" transaction
					// we retain only the "OutPoint" Structure, we expect signature to be valid (otherwise it wouldn't be in a block)
					ChainTxIns newTxIn(newBlock.ID, iEachTx, iEachTxIO);		// create record data variable
					newTxIn.opHash.assign((char *)&it[0],32);	// OutPoint hash
					memcpy(&newTxIn.opN, &it[32], 4);			// OutPoint index number
					it+=36;		// skip OutPoint
					int iVI = (int)msg.GetVarInt(it);			// length of script
					it+=iVI;	// skip script
					it+=4;		// skip sequence
					mydb.InsertChainTxIn(my_conn, newTxIn);
				}
				iNrTxIO = (int)msg.GetVarInt(it);				// number of output transactions
				for (iEachTxIO=0; iEachTxIO < iNrTxIO; iEachTxIO++) {
					// loop through each "out" transaction
					// we examine the script and extract: value, type and hash(es)
					ChainTxOuts newTxOut(newBlock.ID, iEachTx, iEachTxIO);		// create record data variable
					memcpy(&newTxOut.value, &it[0], 8);			// value of output
					it+=8;		// skip the value
					newTxOut.txType=0;
					int iVI = (int)msg.GetVarInt(it);			// length of script
					// examine script to find out the type of transactions
					if (it[0]<OP_PUSHDATA1) {	// script starts with immediate data
						if (it[0]==65 && it[66]==OP_CHECKSIG) {		// transaction is "Transaction to IP address/ Generation"
							vector<unsigned char> vPubKey(it+1, it+66);	// extract Public Key from Msg
							uint160 uKeyHash = Hash160(vPubKey);
							newTxOut.smartID.assign((const char *)&uKeyHash, 20);		// copy it into record
							newTxOut.smartIDAdr = Hash160ToAddress(uKeyHash);			// store base58 address too
							newTxOut.storeID.it_is_null();								// storeID is not used
							newTxOut.txType=2;
						}
					}
					else {
						if (it[0]==OP_DUP && it[1]==OP_HASH160 && it[2]==20 && it[23]==OP_EQUALVERIFY) { // transaction start = std Tx to BitcoinAddress
							if (it[24]==OP_CHECKSIG) {	// it is standard transaction
								vector<unsigned char> vKeyHash(it+3, it+23);			// extract hash from Msg
								newTxOut.smartID.assign((const char *)&it[3], 20);		// extract hash from Msg
								newTxOut.smartIDAdr = Hash160ToAddress( uint160(vKeyHash) );
								newTxOut.storeID.it_is_null();
								newTxOut.txType=1;
							}
							else
								if (1==0) {	// our new type of transaction
									newTxOut.txType=3;
								}
						}
					}
					it+=iVI;	// skip script
					if (newTxOut.txType!=0)
						mydb.InsertChainTxOut(my_conn, newTxOut);
				} // END for each TxOut
				it+=4;		// skip lock time
			} // END if insert chain ok
			// iterator it points now to the end of the transaction, now we can calculate the hash of it
			curBlockHash = Hash(itTxBegin, it);						// calculate it
			newTx.txHash.assign((const char *)&curBlockHash, 32);	// transfer to record
			mydb.UpdateChainTx(my_conn, newTx);						// update the already inserted record
			mydb.TxUnconfirmedDies(my_conn, newTx.txHash);			// set life=0 for this unconfirmed tx
		} // END loop Tx
		myTrans.commit();
	} // END add block
	mydb.TxUnconfirmedAges(my_conn);
	mydb.ReleaseConnection(my_conn);
	return true;
}
Ejemplo n.º 2
0
uint256 CCoinsViewCache::GetBestBlock() const {
    if (hashBlock == uint256(0))
        hashBlock = base->GetBestBlock();
    return hashBlock;
}
Ejemplo n.º 3
0
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0x06;
        pchMessageStart[1] = 0x03;
        pchMessageStart[2] = 0x04;
        pchMessageStart[3] = 0x01;
        nDefaultPort = 2222; //Ring was forged in the second age
        nRPCPort = 2223; //Ring was forged in the second age.
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
        nSubsidyHalvingInterval = 500000;

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
  
        const char* pszTimestamp = "Sauron says hello.";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 1 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1386541846;
        genesis.nBits    = 0x1e0fffff;
        genesis.nNonce   = 0;
        
        //// debug print
        hashGenesisBlock = genesis.GetHash();
        while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
            if (++genesis.nNonce==0) break;
            hashGenesisBlock = genesis.GetHash();
        }

        printf("%s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("%x\n", bnProofOfWorkLimit.GetCompact());
        genesis.print();
        
        
        assert(hashGenesisBlock == uint256("0x"));
        assert(genesis.hashMerkleRoot == uint256("0x"));

        vSeeds.push_back(CDNSSeedData("someaddress.com or IP addy", "someaddress.com"));


        base58Prefixes[PUBKEY_ADDRESS] = 63;
        base58Prefixes[SCRIPT_ADDRESS] = 30;
        base58Prefixes[SECRET_KEY] = 224;

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            // It'll only connect to one or two seed nodes because once it connects,
            // it'll get a pile of addresses with newer timestamps.
            // Seed nodes are given a random 'last seen time' 
            const int64 nTwoDays = 2 * 24 * 60 * 60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
            vFixedSeeds.push_back(addr);
        }
    }
Ejemplo n.º 4
0
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0xf8;
        pchMessageStart[1] = 0xb5;
        pchMessageStart[2] = 0x03;
        pchMessageStart[3] = 0xdf;
        vAlertPubKey = ParseHex("04f09702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284");
        nDefaultPort = 12835;
        nRPCPort = 12832;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
        nSubsidyHalvingInterval = 950000;

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.

        const char* pszTimestamp = "February 5, 2014: The Black Hills are not for sale - 1868 Is The LAW!";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 5000 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1390747675;
        genesis.nBits    = 0x1e0ffff0;
        genesis.nNonce   = 2091390249;

        //// debug print
        hashGenesisBlock = genesis.GetHash();
        //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
        //   if (++genesis.nNonce==0) break;
        //    hashGenesisBlock = genesis.GetHash();
        //}

        //printf("%s\n", hashGenesisBlock.ToString().c_str());
        //printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        //printf("%x\n", bnProofOfWorkLimit.GetCompact());
        //genesis.print();


        assert(hashGenesisBlock == uint256("0x00000c7c73d8ce604178dae13f0fc6ec0be3275614366d44b1b4b5c6e238c60c"));
        assert(genesis.hashMerkleRoot == uint256("0x62d496378e5834989dd9594cfc168dbb76f84a39bbda18286cddc7d1d1589f4f"));

        vSeeds.push_back(CDNSSeedData("node.Maza.org", "node.Maza.org"));
        vSeeds.push_back(CDNSSeedData("node.Maza.cf", "node.Maza.cf"));
        vSeeds.push_back(CDNSSeedData("Maza.no-ip.org", "Maza.no-ip.org"));

        base58Prefixes[PUBKEY_ADDRESS] = 50;
        base58Prefixes[SCRIPT_ADDRESS] = 9;
        base58Prefixes[SECRET_KEY] = 224;

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            // It'll only connect to one or two seed nodes because once it connects,
            // it'll get a pile of addresses with newer timestamps.
            // Seed nodes are given a random 'last seen time'
            const int64 nTwoDays = 2 * 24 * 60 * 60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
            vFixedSeeds.push_back(addr);
        }
    }
Ejemplo n.º 5
0
        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,
Ejemplo n.º 6
0
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0x09;
        pchMessageStart[1] = 0x04;
        pchMessageStart[2] = 0x04;
        pchMessageStart[3] = 0x05;
        nDefaultPort = 7777;
        nRPCPort = 7070;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
        nSubsidyHalvingInterval = 250000;

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.

        const char* pszTimestamp = "Pump dump sell buy hold but when you hear the thunder be ready bc it will be showtimeee";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 1 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1387754247;
        genesis.nBits    = 0x1e0fffff;
        genesis.nNonce   = 416023;

        //// debug print
        hashGenesisBlock = genesis.GetHash();
        while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
            if (++genesis.nNonce==0) break;
            hashGenesisBlock = genesis.GetHash();
        }

        printf("%s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("%x\n", bnProofOfWorkLimit.GetCompact());
        genesis.print();


        assert(hashGenesisBlock == uint256("0x00000a26ae3a3e42c19266cdcb6c1705c644f6e12eff14ed69384ae9415f555d"));
        assert(genesis.hashMerkleRoot == uint256("0xcbe518469ca4a98504a704913d2e3b4c0a131c8734a21aa8e56f879071e5c3fc"));

        vSeeds.push_back(CDNSSeedData("70.193.4.56", "70.193.4.56"));


        base58Prefixes[PUBKEY_ADDRESS] = 127;
        base58Prefixes[SCRIPT_ADDRESS] = 30;
        base58Prefixes[SECRET_KEY] = 224;

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            // It'll only connect to one or two seed nodes because once it connects,
            // it'll get a pile of addresses with newer timestamps.
            // Seed nodes are given a random 'last seen time'
            const int64 nTwoDays = 2 * 24 * 60 * 60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
            vFixedSeeds.push_back(addr);
        }
    }
Ejemplo n.º 7
0
    void run ()
    {
        testcase ("add/traverse");

        beast::Journal const j;                            // debug journal
        
        tests::TestFamily f(j);

        // h3 and h4 differ only in the leaf, same terminal node (level 19)
        uint256 h1, h2, h3, h4, h5;
        h1.SetHex ("092891fe4ef6cee585fdc6fda0e09eb4d386363158ec3321b8123e5a772c6ca7");
        h2.SetHex ("436ccbac3347baa1f1e53baeef1f43334da88f1f6d70d963b833afd6dfa289fe");
        h3.SetHex ("b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8");
        h4.SetHex ("b92891fe4ef6cee585fdc6fda2e09eb4d386363158ec3321b8123e5a772c6ca8");
        h5.SetHex ("a92891fe4ef6cee585fdc6fda0e09eb4d386363158ec3321b8123e5a772c6ca7");

        SHAMap sMap (SHAMapType::FREE, f, beast::Journal());
        SHAMapItem i1 (h1, IntToVUC (1)), i2 (h2, IntToVUC (2)), i3 (h3, IntToVUC (3)), i4 (h4, IntToVUC (4)), i5 (h5, IntToVUC (5));
        unexpected (!sMap.addItem (i2, true, false), "no add");
        unexpected (!sMap.addItem (i1, true, false), "no add");

        std::shared_ptr<SHAMapItem const> i;
        i = sMap.peekFirstItem ();
        unexpected (!i || (*i != i1), "bad traverse");
        i = sMap.peekNextItem (i->key());
        unexpected (!i || (*i != i2), "bad traverse");
        i = sMap.peekNextItem (i->key());
        unexpected (i, "bad traverse");
        sMap.addItem (i4, true, false);
        sMap.delItem (i2.key());
        sMap.addItem (i3, true, false);
        i = sMap.peekFirstItem ();
        unexpected (!i || (*i != i1), "bad traverse");
        i = sMap.peekNextItem (i->key());
        unexpected (!i || (*i != i3), "bad traverse");
        i = sMap.peekNextItem (i->key());
        unexpected (!i || (*i != i4), "bad traverse");
        i = sMap.peekNextItem (i->key());
        unexpected (i, "bad traverse");

        testcase ("snapshot");
        uint256 mapHash = sMap.getHash ();
        std::shared_ptr<SHAMap> map2 = sMap.snapShot (false);
        unexpected (sMap.getHash () != mapHash, "bad snapshot");
        unexpected (map2->getHash () != mapHash, "bad snapshot");
        unexpected (!sMap.delItem (sMap.peekFirstItem ()->key()), "bad mod");
        unexpected (sMap.getHash () == mapHash, "bad snapshot");
        unexpected (map2->getHash () != mapHash, "bad snapshot");

        testcase ("build/tear");
        {
            std::vector<uint256> keys(8);
            keys[0].SetHex ("b92891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8");
            keys[1].SetHex ("b92881fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8");
            keys[2].SetHex ("b92691fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8");
            keys[3].SetHex ("b92791fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8");
            keys[4].SetHex ("b91891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8");
            keys[5].SetHex ("b99891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8");
            keys[6].SetHex ("f22891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8");
            keys[7].SetHex ("292891fe4ef6cee585fdc6fda1e09eb4d386363158ec3321b8123e5a772c6ca8");

            std::vector<uint256> hashes(8);
            hashes[0].SetHex ("B7387CFEA0465759ADC718E8C42B52D2309D179B326E239EB5075C64B6281F7F");
            hashes[1].SetHex ("FBC195A9592A54AB44010274163CB6BA95F497EC5BA0A8831845467FB2ECE266");
            hashes[2].SetHex ("4E7D2684B65DFD48937FFB775E20175C43AF0C94066F7D5679F51AE756795B75");
            hashes[3].SetHex ("7A2F312EB203695FFD164E038E281839EEF06A1B99BFC263F3CECC6C74F93E07");
            hashes[4].SetHex ("395A6691A372387A703FB0F2C6D2C405DAF307D0817F8F0E207596462B0E3A3E");
            hashes[5].SetHex ("D044C0A696DE3169CC70AE216A1564D69DE96582865796142CE7D98A84D9DDE4");
            hashes[6].SetHex ("76DCC77C4027309B5A91AD164083264D70B77B5E43E08AEDA5EBF94361143615");
            hashes[7].SetHex ("DF4220E93ADC6F5569063A01B4DC79F8DB9553B6A3222ADE23DEA02BBE7230E5");

            SHAMap map (SHAMapType::FREE, f, beast::Journal());

            expect (map.getHash() == uint256(), "bad initial empty map hash");
            for (int i = 0; i < keys.size(); ++i)
            {
                SHAMapItem item (keys[i], IntToVUC (i));
                map.addItem (item, true, false);
                expect (map.getHash() == hashes[i], "bad buildup map hash");
            }
            for (int i = keys.size() - 1; i >= 0; --i)
            {
                expect (map.getHash() == hashes[i], "bad teardown hash");
                map.delItem (keys[i]);
            }
            expect (map.getHash() == uint256(), "bad final empty map hash");
        }
    }
Ejemplo n.º 8
0
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0x02;
        pchMessageStart[1] = 0x03;
        pchMessageStart[2] = 0x04;
        pchMessageStart[3] = 0x05;
        nDefaultPort = 25535;
        nRPCPort = 25536;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
        nSubsidyHalvingInterval = 86400;

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
  
        const char* pszTimestamp = "Lumberjacks and Maple Trees in the Great White North";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 1 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1390857400;
        genesis.nBits    = 0x1e0fffff;
        genesis.nNonce   = 102200;
        
        //// debug print
        hashGenesisBlock = genesis.GetHash();
        while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
            if (++genesis.nNonce==0) break;
            hashGenesisBlock = genesis.GetHash();
        }

        printf("%s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("%x\n", bnProofOfWorkLimit.GetCompact());
        genesis.print();
        
        
        assert(hashGenesisBlock == uint256("0x00000567bbebf0cde56b9d36d3476eb1ea5c5060a45006e3523e5eaab5e5e212"));
        assert(genesis.hashMerkleRoot == uint256("0xb929ecd9c646676b88098ad7a1031e0ab2baf390901083e3f22292b26d8c50b4"));

        vSeeds.push_back(CDNSSeedData("andarazoroflove.org", "andarazoroflove.org"));


        base58Prefixes[PUBKEY_ADDRESS] = 28;
        base58Prefixes[SCRIPT_ADDRESS] = 28;
        base58Prefixes[SECRET_KEY] = 224;

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            // It'll only connect to one or two seed nodes because once it connects,
            // it'll get a pile of addresses with newer timestamps.
            // Seed nodes are given a random 'last seen time' 
            const int64 nTwoDays = 2 * 24 * 60 * 60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
            vFixedSeeds.push_back(addr);
        }
    }
Ejemplo n.º 9
0
bool CGovernanceObject::IsCollateralValid(std::string& strError, bool& fMissingConfirmations) const
{
    strError = "";
    fMissingConfirmations = false;
    CAmount nMinFee = GetMinCollateralFee();
    uint256 nExpectedHash = GetHash();

    CTransactionRef txCollateral;
    uint256 nBlockHash;

    // RETRIEVE TRANSACTION IN QUESTION

    if (!GetTransaction(nCollateralHash, txCollateral, Params().GetConsensus(), nBlockHash, true)) {
        strError = strprintf("Can't find collateral tx %s", nCollateralHash.ToString());
        LogPrintf("CGovernanceObject::IsCollateralValid -- %s\n", strError);
        return false;
    }

    if (nBlockHash == uint256()) {
        strError = strprintf("Collateral tx %s is not mined yet", txCollateral->ToString());
        LogPrintf("CGovernanceObject::IsCollateralValid -- %s\n", strError);
        return false;
    }

    if (txCollateral->vout.size() < 1) {
        strError = strprintf("tx vout size less than 1 | %d", txCollateral->vout.size());
        LogPrintf("CGovernanceObject::IsCollateralValid -- %s\n", strError);
        return false;
    }

    // LOOK FOR SPECIALIZED GOVERNANCE SCRIPT (PROOF OF BURN)

    CScript findScript;
    findScript << OP_RETURN << ToByteVector(nExpectedHash);

    LogPrint("gobject", "CGovernanceObject::IsCollateralValid -- txCollateral->vout.size() = %s, findScript = %s, nMinFee = %lld\n",
                txCollateral->vout.size(), ScriptToAsmStr(findScript, false), nMinFee);

    bool foundOpReturn = false;
    for (const auto& output : txCollateral->vout) {
        LogPrint("gobject", "CGovernanceObject::IsCollateralValid -- txout = %s, output.nValue = %lld, output.scriptPubKey = %s\n",
                    output.ToString(), output.nValue, ScriptToAsmStr(output.scriptPubKey, false));
        if (!output.scriptPubKey.IsPayToPublicKeyHash() && !output.scriptPubKey.IsUnspendable()) {
            strError = strprintf("Invalid Script %s", txCollateral->ToString());
            LogPrintf("CGovernanceObject::IsCollateralValid -- %s\n", strError);
            return false;
        }
        if (output.scriptPubKey == findScript && output.nValue >= nMinFee) {
            foundOpReturn = true;
        }
    }

    if (!foundOpReturn) {
        strError = strprintf("Couldn't find opReturn %s in %s", nExpectedHash.ToString(), txCollateral->ToString());
        LogPrintf("CGovernanceObject::IsCollateralValid -- %s\n", strError);
        return false;
    }

    // GET CONFIRMATIONS FOR TRANSACTION

    AssertLockHeld(cs_main);
    int nConfirmationsIn = 0;
    if (nBlockHash != uint256()) {
        BlockMap::iterator mi = mapBlockIndex.find(nBlockHash);
        if (mi != mapBlockIndex.end() && (*mi).second) {
            CBlockIndex* pindex = (*mi).second;
            if (chainActive.Contains(pindex)) {
                nConfirmationsIn += chainActive.Height() - pindex->nHeight + 1;
            }
        }
    }

    if ((nConfirmationsIn < GOVERNANCE_FEE_CONFIRMATIONS) &&
        (!instantsend.IsLockedInstantSendTransaction(nCollateralHash) || llmq::quorumInstantSendManager->IsLocked(nCollateralHash))) {
        strError = strprintf("Collateral requires at least %d confirmations to be relayed throughout the network (it has only %d)", GOVERNANCE_FEE_CONFIRMATIONS, nConfirmationsIn);
        if (nConfirmationsIn >= GOVERNANCE_MIN_RELAY_FEE_CONFIRMATIONS) {
            fMissingConfirmations = true;
            strError += ", pre-accepted -- waiting for required confirmations";
        } else {
            strError += ", rejected -- try again later";
        }
        LogPrintf("CGovernanceObject::IsCollateralValid -- %s\n", strError);

        return false;
    }

    strError = "valid";
    return true;
}
Ejemplo n.º 10
0
uint256 ParseHashUO(std::map<std::string,UniValue>& o, std::string strKey)
{
    if (!o.count(strKey))
        return uint256();
    return ParseHashUV(o[strKey], strKey);
}
Ejemplo n.º 11
0
unsigned int KimotoGravityWell(const CBlockIndex* pindexLast, int algo) {
	
	unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit(algo).GetCompact();
	if (fDebug){
    LogPrintf("Proof Of Work Limit For Algo %i, is % i\n", algo, nProofOfWorkLimit);
    }
    // Genesis block
    if (pindexLast == NULL){
		LogPrintf("Genesis Block Difficulty");
        return nProofOfWorkLimit;
	}
	const CBlockIndex* pindexPrevAlgo = GetLastBlockIndexForAlgo(pindexLast, algo);
    if (pindexPrevAlgo == NULL){
		LogPrintf("pindexPrevAlgo == NULL for Algo %i, is % i\n", algo, nProofOfWorkLimit);
        return nProofOfWorkLimit;
	}
    /* Franko Multi Algo Gravity Well */
    const CBlockIndex   *BlockLastSolved                 = pindexPrevAlgo;
    const CBlockIndex   *BlockReading                    = pindexPrevAlgo;

	unsigned int		 AlgoCounter					 = 0;
    uint64_t             PastBlocksMass                  = 0;
    int64_t              PastRateActualSeconds           = 0;
    int64_t              PastRateTargetSeconds           = 0;
    double               PastRateAdjustmentRatio         = double(1);
    uint256              PastDifficultyAverage;
    uint256              PastDifficultyAveragePrev;
    uint256              BlockReadingDifficulty;
    double               EventHorizonDeviation;
    double               EventHorizonDeviationFast;
    double               EventHorizonDeviationSlow;

    static const int64_t TargetBlockSpacing              = 60; // == 1 minute
    unsigned int         TimeDaySeconds                  = 60 * 60 * 24;
    int64_t              PastSecondsMin                  = TimeDaySeconds * 0.25; // == 6300 Seconds
    int64_t              PastSecondsMax                  = TimeDaySeconds * 7; // == 604800 Seconds
    uint64_t             PastBlocksMin                   = PastSecondsMin / TargetBlockSpacing; // == 360 blocks
    uint64_t             PastBlocksMax                   = PastSecondsMax / TargetBlockSpacing; // == 10080 blocks

	//loop through and count the blocks found by the algo
	for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
        if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
		// Makes sure we are only calculating blocks from the specified algo
		if (BlockReading->GetAlgo() != algo){ BlockReading = BlockReading->pprev; continue; }
		AlgoCounter++;
		BlockReading = BlockReading->pprev;
	}

    if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 ||
        (uint64_t)BlockLastSolved->nHeight < PastBlocksMin ||
			AlgoCounter < PastBlocksMin) {
        return Params().ProofOfWorkLimit(algo).GetCompact();
    }
    
    int64_t LatestBlockTime = BlockLastSolved->GetBlockTime();


    BlockReading = pindexPrevAlgo;
    for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
        if (PastBlocksMax > 0 && i > AlgoCounter) { break; }
		// Makes sure we are only calculating blocks from the specified algo
		if (BlockReading->GetAlgo() != algo){ BlockReading = BlockReading->pprev; continue; }

        PastBlocksMass++;

        if (i == 1) {
            PastDifficultyAverage.SetCompact(BlockReading->nBits);
        } else {
            BlockReadingDifficulty.SetCompact(BlockReading->nBits);
            if (BlockReadingDifficulty > PastDifficultyAveragePrev) {
                PastDifficultyAverage = PastDifficultyAveragePrev + ((BlockReadingDifficulty - PastDifficultyAveragePrev) / i);
            } else {
                PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - BlockReadingDifficulty) / i);
            }
        }
        PastDifficultyAveragePrev = PastDifficultyAverage;

        if (LatestBlockTime < BlockReading->GetBlockTime()) {
                LatestBlockTime = BlockReading->GetBlockTime();
        }
        PastRateActualSeconds = LatestBlockTime - BlockReading->GetBlockTime();
        PastRateTargetSeconds = TargetBlockSpacing * PastBlocksMass;
        PastRateAdjustmentRatio = double(1);
        
        if (PastRateActualSeconds < 1) { PastRateActualSeconds = 1; }
        
        if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
            PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds);
        }
        EventHorizonDeviation                   = 1 + (0.7084 * pow((double(PastBlocksMass)/double(144)), -1.228));
        EventHorizonDeviationFast               = EventHorizonDeviation;
        EventHorizonDeviationSlow               = 1 / EventHorizonDeviation;

        if (PastBlocksMass >= PastBlocksMin) {
            if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) ||
                (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) {
                assert(BlockReading);
                break;
            }
        }
        if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
        BlockReading = BlockReading->pprev;
    }

    uint256 bnNew(PastDifficultyAverage);
    if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
        bnNew *= PastRateActualSeconds;
        bnNew /= PastRateTargetSeconds;
    }
    if (bnNew > Params().ProofOfWorkLimit(algo)) { bnNew = Params().ProofOfWorkLimit(algo); }

    // debug print
       if (fDebug){
        LogPrintf("Franko Multi Algo Gravity Well\n");
    
    LogPrintf("PastRateAdjustmentRatio =  %g    PastRateTargetSeconds = %d    PastRateActualSeconds = %d\n",
               PastRateAdjustmentRatio, PastRateTargetSeconds, PastRateActualSeconds);
    LogPrintf("Before: %08x  %s\n", BlockLastSolved->nBits, uint256().SetCompact(BlockLastSolved->nBits).ToString());
    LogPrintf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.ToString());
    }
    return bnNew.GetCompact();
}
Ejemplo n.º 12
0
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0x05;
        pchMessageStart[1] = 0x05;
        pchMessageStart[2] = 0xb5;
        pchMessageStart[3] = 0x05;
        nDefaultPort = 5530;
        nRPCPort = 5531;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
        nSubsidyHalvingInterval = 100000;

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
  
        const char* pszTimestamp = "vcoin sn";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 1 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1431517588;
        genesis.nBits    = 0x1e0fffff;
        genesis.nNonce   = 1486592;
        
        //// debug print
        hashGenesisBlock = genesis.GetHash();
        while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
            if (++genesis.nNonce==0) break;
            hashGenesisBlock = genesis.GetHash();
        }

        printf("%s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("%x\n", bnProofOfWorkLimit.GetCompact());
        genesis.print();
        
        
        assert(hashGenesisBlock == uint256("0x00000b7e804f0de87e7752550ff04d7686a4599509897feefd7f03904eb45633"));
        assert(genesis.hashMerkleRoot == uint256("0x1576ef41775095b26a8f8f2bb65b693ec12230608a425aa84ee462381cae00e6"));

        vSeeds.push_back(CDNSSeedData("1", "108.61.10.90"));
        vSeeds.push_back(CDNSSeedData("2", "185.92.222.31"));


        base58Prefixes[PUBKEY_ADDRESS] = 70;
        base58Prefixes[SCRIPT_ADDRESS] = 30;
        base58Prefixes[SECRET_KEY] = 224;

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            // It'll only connect to one or two seed nodes because once it connects,
            // it'll get a pile of addresses with newer timestamps.
            // Seed nodes are given a random 'last seen time' 
            const int64 nTwoDays = 2 * 24 * 60 * 60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
            vFixedSeeds.push_back(addr);
        }
    }
Ejemplo n.º 13
0
bool shamap::compare (shamap::ref othermap, delta& differences, int maxcount)
{
    // compare two hash trees, add up to maxcount differences to the difference table
    // return value: true=complete table of differences given, false=too many differences
    // throws on corrupt tables or missing nodes
    // caution: othermap is not locked and must be immutable

    assert (isvalid () && othermap && othermap->isvalid ());

    using stackentry = std::pair <shamaptreenode*, shamaptreenode*>;
    std::stack <stackentry, std::vector<stackentry>> nodestack; // track nodes we've pushed

    if (gethash () == othermap->gethash ())
        return true;

    nodestack.push ({root.get(), othermap->root.get()});
    while (!nodestack.empty ())
    {
        shamaptreenode* ournode = nodestack.top().first;
        shamaptreenode* othernode = nodestack.top().second;
        nodestack.pop ();

        if (!ournode || !othernode)
        {
            assert (false);
            throw shamapmissingnode (mtype, uint256 ());
        }

        if (ournode->isleaf () && othernode->isleaf ())
        {
            // two leaves
            if (ournode->gettag () == othernode->gettag ())
            {
                if (ournode->peekdata () != othernode->peekdata ())
                {
                    differences.insert (std::make_pair (ournode->gettag (),
                                                 deltaref (ournode->peekitem (),
                                                 othernode->peekitem ())));
                    if (--maxcount <= 0)
                        return false;
                }
            }
            else
            {
                differences.insert (std::make_pair(ournode->gettag (),
                                                   deltaref(ournode->peekitem(),
                                                   shamapitem::pointer ())));
                if (--maxcount <= 0)
                    return false;

                differences.insert(std::make_pair(othernode->gettag (),
                                                  deltaref(shamapitem::pointer(),
                                                  othernode->peekitem ())));
                if (--maxcount <= 0)
                    return false;
            }
        }
        else if (ournode->isinner () && othernode->isleaf ())
        {
            if (!walkbranch (ournode, othernode->peekitem (),
                    true, differences, maxcount))
                return false;
        }
        else if (ournode->isleaf () && othernode->isinner ())
        {
            if (!othermap->walkbranch (othernode, ournode->peekitem (),
                                       false, differences, maxcount))
                return false;
        }
        else if (ournode->isinner () && othernode->isinner ())
        {
            for (int i = 0; i < 16; ++i)
                if (ournode->getchildhash (i) != othernode->getchildhash (i))
                {
                    if (othernode->isemptybranch (i))
                    {
                        // we have a branch, the other tree does not
                        shamaptreenode* inode = descendthrow (ournode, i);
                        if (!walkbranch (inode,
                                         shamapitem::pointer (), true,
                                         differences, maxcount))
                            return false;
                    }
                    else if (ournode->isemptybranch (i))
                    {
                        // the other tree has a branch, we do not
                        shamaptreenode* inode =
                            othermap->descendthrow(othernode, i);
                        if (!othermap->walkbranch (inode,
                                                   shamapitem::pointer(),
                                                   false, differences, maxcount))
                            return false;
                    }
                    else // the two trees have different non-empty branches
                        nodestack.push ({descendthrow (ournode, i),
                                        othermap->descendthrow (othernode, i)});
                }
        }
        else
            assert (false);
    }

    return true;
}
Ejemplo n.º 14
0
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0x12;
        pchMessageStart[1] = 0x0c;
        pchMessageStart[2] = 0x07;
        pchMessageStart[3] = 0xdd;
        nDefaultPort = 18123;
        nRPCPort = 18124;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
        //nSubsidyHalvingInterval = 100000;

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
  
        const char* pszTimestamp = "LeaCoin - for Lea, my little sweetie. :-)";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 1 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1387357200;
        genesis.nBits    = 0x1e0fffff;
        genesis.nNonce   = 647623;
        
        //// debug print
        hashGenesisBlock = genesis.GetHash();
        //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
        //    if (++genesis.nNonce==0) break;
        //    hashGenesisBlock = genesis.GetHash();
        //}

        printf("%s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("%x\n", bnProofOfWorkLimit.GetCompact());
        genesis.print();
        
        
        assert(hashGenesisBlock == uint256("0x00000a33e2728123ae58837d86248e19c3530a603aa9b59228fc9954ef2c93e0"));
        assert(genesis.hashMerkleRoot == uint256("0x448cd8630d0904ac9bb61d6fb51a0c3b25b707913b3f5a91af4e2220934690da"));

        vSeeds.push_back(CDNSSeedData("leacoin.org", "dnsseed.leacoin.org"));


        base58Prefixes[PUBKEY_ADDRESS] = 48;
        base58Prefixes[SCRIPT_ADDRESS] = 30;
        base58Prefixes[SECRET_KEY] = 224;

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            // It'll only connect to one or two seed nodes because once it connects,
            // it'll get a pile of addresses with newer timestamps.
            // Seed nodes are given a random 'last seen time' 
            const int64 nTwoDays = 2 * 24 * 60 * 60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
            vFixedSeeds.push_back(addr);
        }
    }
Ejemplo n.º 15
0
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0x66;
        pchMessageStart[1] = 0x66;
        pchMessageStart[2] = 0x66;
        pchMessageStart[3] = 0x66;
        nDefaultPort = 24242;
        nRPCPort = 24243;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
        nSubsidyHalvingInterval = 35040000;

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
  
        const char* pszTimestamp = "Release the Kraken - www.krakencoin.com";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 1 * COIN;
        txNewvout1nValue = 5;
        txNewvout2nValue = 450000 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1394270601;
        genesis.nBits    = 0x1e0fffff;
        genesis.nNonce   = 943874;
        
        //// debug print
        hashGenesisBlock = genesis.GetHash();
        //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
          //  if (++genesis.nNonce==0) break;
            //hashGenesisBlock = genesis.GetHash();
        //}

        printf("%s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("%x\n", bnProofOfWorkLimit.GetCompact());
        genesis.print();
        
        
        assert(hashGenesisBlock == uint256("0x00000e9d058285796d9d49c3110a98c9367d25b7ab82cab06088f29ff4160b2a"));
        assert(genesis.hashMerkleRoot == uint256("0x67cf79c130dc3b7f3a164ffde6d4ff3b30fb3847e649e5ab8c889cbcba8db40d"));

        vSeeds.push_back(CDNSSeedData("162.243.90.199", "162.243.90.199"));


        base58Prefixes[PUBKEY_ADDRESS] = 45;
        base58Prefixes[SCRIPT_ADDRESS] = 30;
        base58Prefixes[SECRET_KEY] = 224;

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            // It'll only connect to one or two seed nodes because once it connects,
            // it'll get a pile of addresses with newer timestamps.
            // Seed nodes are given a random 'last seen time' 
            const int64 nTwoDays = 2 * 24 * 60 * 60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
            vFixedSeeds.push_back(addr);
        }
    }
Ejemplo n.º 16
0
// AntiGravityWave by reorder, derived from code by Evan Duffield - [email protected]
unsigned int static AntiGravityWave(const CBlockIndex* pindexLast, const CBlockHeader *pblock, int64_t version)
{
    const CBlockIndex *BlockLastSolved = pindexLast;
    const CBlockIndex *BlockReading = pindexLast;
    int64_t nActualTimespan = 0;
    int64_t LastBlockTime = 0;
    int64_t PastBlocksMin = 24;
    int64_t PastBlocksMax = 24;

    if (version == 1) {
        PastBlocksMin = 24;
        PastBlocksMax = 24;
    } else if (version == 2) {
        PastBlocksMin = 72;
        PastBlocksMax = 72;
    }

    int64_t CountBlocks = 0;
    uint256 PastDifficultyAverage;
    uint256 PastDifficultyAveragePrev;

    if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) {
        return Params().ProofOfWorkLimit().GetCompact();
    }

    for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
        if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
            CountBlocks++;

        if (CountBlocks <= PastBlocksMin) {
            if (CountBlocks == 1)
                PastDifficultyAverage.SetCompact(BlockReading->nBits);
            else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks)+(uint256().SetCompact(BlockReading->nBits))) / (CountBlocks+1); }
                PastDifficultyAveragePrev = PastDifficultyAverage;
        }

        if (LastBlockTime > 0) {
            int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime());
            nActualTimespan += Diff;
        }
        LastBlockTime = BlockReading->GetBlockTime();

        if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
            BlockReading = BlockReading->pprev;
    }

    uint256 bnNew(PastDifficultyAverage);

    if (version == 2)
        --CountBlocks;

    int64_t nTargetTimespan = CountBlocks*Params().TargetSpacing();

    int64_t div = 3;
    if (version == 1)
        div = 3;
    else if (version == 2)
        div = 2;

    if (nActualTimespan < nTargetTimespan/div)
        nActualTimespan = nTargetTimespan/div;
    if (nActualTimespan > nTargetTimespan*div)
        nActualTimespan = nTargetTimespan*div;

    // Retarget
    bnNew *= nActualTimespan;
    bnNew /= nTargetTimespan;

    if (bnNew > Params().ProofOfWorkLimit()) {
        bnNew = Params().ProofOfWorkLimit();
    }

    return bnNew.GetCompact();
}
Ejemplo n.º 17
0
uint256 CCoinsView::GetBestBlock() { return uint256(0); }
Ejemplo n.º 18
0
        item.nTime = nTime;

        return item;
    }

    //
    // 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, initCheckpoint(hashGenesisBlock, 1386695449) )
        (14500, initCheckpoint(uint256("0x0000000dca006b6ddd1faff9606bd6f5d80bdfc4a872e8375fe3e941aad30e74"), 1388554748) )     
        (77500, initCheckpoint(uint256("0x0000000a792af4c7c8cd7535b9f2bd2a366c8bb7ef9582b90acedb0e0cba6269"), 1392475713) )
        (149825, initCheckpoint(uint256("0x00000034d18a80debe54b395ac5069571d1c7fc325c7e372c519aaa5c1f4380f"), 1397134677) )
     ;


    // TestNet has no checkpoints
    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 0, initCheckpoint(hashGenesisBlockTestNet, 1360105017) )
        ;

    bool CheckHardened(int nHeight, const uint256& hash)
    {
        MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
void RemoteMinerThreadGPU::Run(void *arg)
{
	threaddata *td=(threaddata *)arg;
	int64 currentblockid=-1;

	static const unsigned int SHA256InitState[8] ={0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
	uint256 tempbuff[4];
	uint256 &temphash=*alignup<16>(tempbuff);
	uint256 hashbuff[4];
	uint256 &hash=*alignup<16>(hashbuff);
	uint256 currenttarget;
	gpurunnertype gpu;

	unsigned char currentmidbuff[256];
	unsigned char currentblockbuff[256];
	unsigned char *midbuffptr;
	unsigned char *blockbuffptr;
	unsigned int *nonce;
	midbuffptr=alignup<16>(currentmidbuff);
	blockbuffptr=alignup<16>(currentblockbuff);
	nonce=(unsigned int *)(blockbuffptr+12);

	uint256 besthash=~(uint256(0));
	unsigned int besthashnonce=0;

	unsigned char *metahash=0;
	unsigned int metahashsize=td->m_metahashsize;
	unsigned int metahashpos=0;
	unsigned int metahashstartnonce=0;

	SetThreadPriority(THREAD_PRIORITY_LOWEST);

	FormatHashBlocks(&temphash,sizeof(temphash));
	for(int i=0; i<64/4; i++)
	{
		((unsigned int*)&temphash)[i] = CryptoPP::ByteReverse(((unsigned int*)&temphash)[i]);
	}

	gpu.FindBestConfiguration();

	while(td->m_generate)
	{
		if(td->m_havework)
		{
			if(metahashstartnonce==0)
			{
				CRITICAL_BLOCK(td->m_cs);
				if(currentblockid!=td->m_nextblock.m_blockid)
				{
					currenttarget=td->m_nextblock.m_target;
					currentblockid=td->m_nextblock.m_blockid;
					::memcpy(midbuffptr,&td->m_nextblock.m_midstate[0],32);
					::memcpy(blockbuffptr,&td->m_nextblock.m_block[0],64);
					metahashpos=0;
					metahashstartnonce=0;
					(*nonce)=0;
					besthash=~(uint256(0));
					besthashnonce=0;
					if(metahash==0 || td->m_metahashsize!=metahashsize)
					{
						metahashsize=td->m_metahashsize;
						if(metahash)
						{
							delete [] metahash;
						}
						metahash=new unsigned char[metahashsize];
					}

					for(int i=0; i<8; i++)
					{
						gpu.GetIn()->m_AH[i]=((unsigned int *)midbuffptr)[i];
					}
					gpu.GetIn()->m_merkle=((unsigned int *)blockbuffptr)[0];
					gpu.GetIn()->m_ntime=((unsigned int *)blockbuffptr)[1];
					gpu.GetIn()->m_nbits=((unsigned int *)blockbuffptr)[2];
				}
			}

			gpu.GetIn()->m_nonce=(*nonce);

			gpu.RunStep();

			for(int i=0; i<gpu.GetNumThreads()*gpu.GetNumBlocks(); i++)
			{
				memcpy(&hash,&(gpu.GetOut()[i].m_bestAH[0]),32);

				if(gpu.GetOut()[i].m_bestnonce!=0 && hash!=0 && hash<=currenttarget)
				{
					CRITICAL_BLOCK(td->m_cs);
					td->m_foundhashes.push_back(foundhash(currentblockid,gpu.GetOut()[i].m_bestnonce));
				}

				if(gpu.GetOut()[i].m_bestnonce!=0 && hash!=0 && hash<besthash && gpu.GetOut()[i].m_bestnonce<metahashstartnonce+metahashsize)
				{
					besthash=hash;
					besthashnonce=gpu.GetOut()[i].m_bestnonce;
				}

				for(int j=0; j<gpu.GetStepIterations(); j++)
				{
					(*nonce)++;
					metahash[metahashpos++]=gpu.GetMetaHash()[(i*gpu.GetStepIterations())+j];

					if(metahashpos>=metahashsize)
					{

						{
							CRITICAL_BLOCK(td->m_cs);
							td->m_hashresults.push_back(hashresult(currentblockid,besthash,besthashnonce,metahash,metahashstartnonce));

							if(td->m_metahashptrs.size()>0)
							{
								metahash=td->m_metahashptrs[td->m_metahashptrs.size()-1];
								td->m_metahashptrs.erase(td->m_metahashptrs.end()-1);
							}
							else
							{
								metahash=new unsigned char[metahashsize];
							}
						}

						metahashpos=0;
						metahashstartnonce=(*nonce);
						besthash=~(uint256(0));
						besthashnonce=0;

						{
							CRITICAL_BLOCK(td->m_cs);
							if(currentblockid!=td->m_nextblock.m_blockid)
							{
								currenttarget=td->m_nextblock.m_target;
								currentblockid=td->m_nextblock.m_blockid;
								::memcpy(midbuffptr,&td->m_nextblock.m_midstate[0],32);
								::memcpy(blockbuffptr,&td->m_nextblock.m_block[0],64);
								metahashpos=0;
								metahashstartnonce=0;
								(*nonce)=0;
								for(int i=0; i<8; i++)
								{
									gpu.GetIn()->m_AH[i]=((unsigned int *)midbuffptr)[i];
								}
								gpu.GetIn()->m_merkle=((unsigned int *)blockbuffptr)[0];
								gpu.GetIn()->m_ntime=((unsigned int *)blockbuffptr)[1];
								gpu.GetIn()->m_nbits=((unsigned int *)blockbuffptr)[2];
							}
						}

					}
				}	// j

			}

		}
		else
		{
			Sleep(100);
		}

	}

	{
		CRITICAL_BLOCK(td->m_cs);
		td->m_done=true;
	}

}
Ejemplo n.º 20
0
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0xfd;
        pchMessageStart[1] = 0xa4;
        pchMessageStart[2] = 0xdc;
        pchMessageStart[3] = 0x6c;
        vAlertPubKey = ParseHex("04d1832d7d0c59634d67d3023379403014c2878d0c2372d175219063a48fa06e6d429e09f36d3196ec544c2cfdd12d6fe510a399595f75ebb6da238eb5f70f2072");
        nDefaultPort = 12340;
        nRPCPort = 12341;

        bnProofOfWorkLimit[ALGO_SHA256D] = CBigNum(~uint256(0) >> 20); // 1.00000000
        bnProofOfWorkLimit[ALGO_SCRYPT]  = CBigNum(~uint256(0) >> 20);
        bnProofOfWorkLimit[ALGO_GROESTL] = CBigNum(~uint256(0) >> 20); // 0.00195311
        bnProofOfWorkLimit[ALGO_SKEIN]   = CBigNum(~uint256(0) >> 20); // 0.00195311
        bnProofOfWorkLimit[ALGO_QUBIT]   = CBigNum(~uint256(0) >> 20); // 0.00097655

        // Build the genesis block.
        const char* pszTimestamp = "Visir 10. oktober 2008 Gjaldeyrishoft sett a Islendinga";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 1 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("04a5814813115273a109cff99907ba4a05d951873dae7acb6c973d0c9e7c88911a3dbc9aa600deac241b91707e7b4ffb30ad91c8e56e695a1ddf318592988afe0a") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1390598806;
        genesis.nBits    = Params().ProofOfWorkLimit(ALGO_SCRYPT).GetCompact();
        //genesis.nBits = 0x1e0fffff;
        genesis.nNonce   = 538548;

        hashGenesisBlock = genesis.GetHash();

        assert(hashGenesisBlock == uint256("0x2a8e100939494904af825b488596ddd536b3a96226ad02e0f7ab7ae472b27a8e"));
        assert(genesis.hashMerkleRoot == uint256("0x8957e5e8d2f0e90c42e739ec62fcc5dd21064852da64b6528ebd46567f222169"));

        vSeeds.push_back(CDNSSeedData("luxembourgh", "s1.auroraseed.net"));
        vSeeds.push_back(CDNSSeedData("united-states-west", "aurseed1.criptoe.com"));
        vSeeds.push_back(CDNSSeedData("united-states-east", "s1.auroraseed.com"));
        vSeeds.push_back(CDNSSeedData("iceland", "s1.auroraseed.org"));
        vSeeds.push_back(CDNSSeedData("the-netherlands", "s1.auroraseed.eu"));
        vSeeds.push_back(CDNSSeedData("electrum2", "electrum2.aurorcoin.is"));
        vSeeds.push_back(CDNSSeedData("electrum3", "electrum3.auroracoin.is"));
        vSeeds.push_back(CDNSSeedData("electrum4", "electrum4.auroracoin.is"));

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,23);
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5);
        base58Prefixes[SECRET_KEY]     = std::vector<unsigned char>(1,176);
        base58Prefixes[SECRET_KEY_OLD] = std::vector<unsigned char>(1,151);
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            const int64_t nOneWeek = 7*24*60*60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
            vFixedSeeds.push_back(addr);
        }
    }
Ejemplo n.º 21
0
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0x55;
        pchMessageStart[1] = 0x42;
        pchMessageStart[2] = 0x4B;
        pchMessageStart[3] = 0x45;
        nDefaultPort = 11066;
        nRPCPort = 11067;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
        nSubsidyHalvingInterval = 100000;

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
  
        const char* pszTimestamp = "Viking Era";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 0.001 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1400630400; //nTime
        genesis.nBits    = 0x1e0fffff;
        genesis.nNonce   = 2016973;
        
        hashGenesisBlock = genesis.GetHash();
        // while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
        //     if (++genesis.nNonce==0) break;
        //     hashGenesisBlock = genesis.GetHash();
        //}


        printf("%s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("%x\n", bnProofOfWorkLimit.GetCompact());
        genesis.print();
        
        
        assert(hashGenesisBlock == uint256("0x00000c07c30a4f74683e64ed156668e3f8d2e71bb4efcdcc44c248708d1cabf2"));
        assert(genesis.hashMerkleRoot == uint256("0xb8b26c88ea01ea6cbbd9fd39158f1e6cae130cc2cd5950b78727d83aa71c056d"));

        vSeeds.push_back(CDNSSeedData("198.46.134.15", "192.3.10.93"));
		vSeeds.push_back(CDNSSeedData("95.85.46.218", "81.11.246.44"));
        vSeeds.push_back(CDNSSeedData("108.61.10.90", "192.241.199.243"));
   

        base58Prefixes[PUBKEY_ADDRESS] = 70;
        base58Prefixes[SCRIPT_ADDRESS] = 132;
        base58Prefixes[SECRET_KEY] = 86;

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            // It'll only connect to one or two seed nodes because once it connects,
            // it'll get a pile of addresses with newer timestamps.
            // Seed nodes are given a random 'last seen time' 
            const int64 nTwoDays = 2 * 24 * 60 * 60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
            vFixedSeeds.push_back(addr);
        }
    }
CMessage::CMessage()
	: m_header( (int)CPayloadKind::Uninitiated, std::vector<unsigned char>(), 0, CPubKey(), uint256(), uint256() )
{
}
Ejemplo n.º 23
0
/// Convert vector to arith_uint256, via uint256 blob
inline arith_uint256 arith_uint256V(const std::vector<unsigned char>& vch)
{
    return UintToArith256(uint256(vch));
}
Ejemplo n.º 24
0
    void testSerialization ()
    {
        testcase ("serialization");

        unexpected (sfGeneric.isUseful (), "sfGeneric must not be useful");

        SField const& sfTestVL = SField::getField (STI_VL, 255);
        SField const& sfTestH256 = SField::getField (STI_HASH256, 255);
        SField const& sfTestU32 = SField::getField (STI_UINT32, 255);
        SField const& sfTestObject = SField::getField (STI_OBJECT, 255);

        SOTemplate elements;
        elements.push_back (SOElement (sfFlags, SOE_REQUIRED));
        elements.push_back (SOElement (sfTestVL, SOE_REQUIRED));
        elements.push_back (SOElement (sfTestH256, SOE_OPTIONAL));
        elements.push_back (SOElement (sfTestU32, SOE_REQUIRED));

        STObject object1 (elements, sfTestObject);
        STObject object2 (object1);

        unexpected (object1.getSerializer () != object2.getSerializer (),
            "STObject error 1");

        unexpected (object1.isFieldPresent (sfTestH256) ||
            !object1.isFieldPresent (sfTestVL), "STObject error");

        object1.makeFieldPresent (sfTestH256);

        unexpected (!object1.isFieldPresent (sfTestH256), "STObject Error 2");

        unexpected (object1.getFieldH256 (sfTestH256) != uint256 (),
            "STObject error 3");

        if (object1.getSerializer () == object2.getSerializer ())
        {
            WriteLog (lsINFO, STObject) << "O1: " << object1.getJson (0);
            WriteLog (lsINFO, STObject) << "O2: " << object2.getJson (0);
            fail ("STObject error 4");
        }
        else
        {
            pass ();
        }

        object1.makeFieldAbsent (sfTestH256);

        unexpected (object1.isFieldPresent (sfTestH256), "STObject error 5");

        unexpected (object1.getFlags () != 0, "STObject error 6");

        unexpected (object1.getSerializer () != object2.getSerializer (),
            "STObject error 7");

        STObject copy (object1);

        unexpected (object1.isFieldPresent (sfTestH256), "STObject error 8");

        unexpected (copy.isFieldPresent (sfTestH256), "STObject error 9");

        unexpected (object1.getSerializer () != copy.getSerializer (),
            "STObject error 10");

        copy.setFieldU32 (sfTestU32, 1);

        unexpected (object1.getSerializer () == copy.getSerializer (),
            "STObject error 11");

        for (int i = 0; i < 1000; i++)
        {
            Blob j (i, 2);

            object1.setFieldVL (sfTestVL, j);

            Serializer s;
            object1.add (s);
            SerialIter it (s.slice());

            STObject object3 (elements, it, sfTestObject);

            unexpected (object1.getFieldVL (sfTestVL) != j, "STObject error");

            unexpected (object3.getFieldVL (sfTestVL) != j, "STObject error");
        }
    }
/* This implements a constant-space merkle root/path calculator, limited to 2^32
 * leaves. */
static void MerkleComputation(const std::vector<uint256> &leaves,
                              uint256 *proot, bool *pmutated,
                              uint32_t branchpos,
                              std::vector<uint256> *pbranch) {
    if (pbranch) pbranch->clear();
    if (leaves.size() == 0) {
        if (pmutated) *pmutated = false;
        if (proot) *proot = uint256();
        return;
    }
    bool mutated = false;
    // count is the number of leaves processed so far.
    uint32_t count = 0;
    // inner is an array of eagerly computed subtree hashes, indexed by tree
    // level (0 being the leaves).
    // For example, when count is 25 (11001 in binary), inner[4] is the hash of
    // the first 16 leaves, inner[3] of the next 8 leaves, and inner[0] equal to
    // the last leaf. The other inner entries are undefined.
    uint256 inner[32];
    // Which position in inner is a hash that depends on the matching leaf.
    int matchlevel = -1;
    // First process all leaves into 'inner' values.
    while (count < leaves.size()) {
        uint256 h = leaves[count];
        bool matchh = count == branchpos;
        count++;
        int level;
        // For each of the lower bits in count that are 0, do 1 step. Each
        // corresponds to an inner value that existed before processing the
        // current leaf, and each needs a hash to combine it.
        for (level = 0; !(count & (((uint32_t)1) << level)); level++) {
            if (pbranch) {
                if (matchh) {
                    pbranch->push_back(inner[level]);
                } else if (matchlevel == level) {
                    pbranch->push_back(h);
                    matchh = true;
                }
            }
            mutated |= (inner[level] == h);
            CHash256()
                .Write(inner[level].begin(), 32)
                .Write(h.begin(), 32)
                .Finalize(h.begin());
        }
        // Store the resulting hash at inner position level.
        inner[level] = h;
        if (matchh) {
            matchlevel = level;
        }
    }
    // Do a final 'sweep' over the rightmost branch of the tree to process
    // odd levels, and reduce everything to a single top value.
    // Level is the level (counted from the bottom) up to which we've sweeped.
    int level = 0;
    // As long as bit number level in count is zero, skip it. It means there
    // is nothing left at this level.
    while (!(count & (((uint32_t)1) << level))) {
        level++;
    }
    uint256 h = inner[level];
    bool matchh = matchlevel == level;
    while (count != (((uint32_t)1) << level)) {
        // If we reach this point, h is an inner value that is not the top.
        // We combine it with itself (Commercium's special rule for odd levels in
        // the tree) to produce a higher level one.
        if (pbranch && matchh) {
            pbranch->push_back(h);
        }
        CHash256()
            .Write(h.begin(), 32)
            .Write(h.begin(), 32)
            .Finalize(h.begin());
        // Increment count to the value it would have if two entries at this
        // level had existed.
        count += (((uint32_t)1) << level);
        level++;
        // And propagate the result upwards accordingly.
        while (!(count & (((uint32_t)1) << level))) {
            if (pbranch) {
                if (matchh) {
                    pbranch->push_back(inner[level]);
                } else if (matchlevel == level) {
                    pbranch->push_back(h);
                    matchh = true;
                }
            }
            CHash256()
                .Write(inner[level].begin(), 32)
                .Write(h.begin(), 32)
                .Finalize(h.begin());
            level++;
        }
    }
    // Return result.
    if (pmutated) *pmutated = mutated;
    if (proot) *proot = h;
}
Ejemplo n.º 26
0
uint256 CBlock::BuildMerkleTree(bool* fMutated) const
{
    /* WARNING! If you're reading this because you're learning about crypto
       and/or designing a new system that will use merkle trees, keep in mind
       that the following merkle tree algorithm has a serious flaw related to
       duplicate txids, resulting in a vulnerability (CVE-2012-2459).

       The reason is that if the number of hashes in the list at a given time
       is odd, the last one is duplicated before computing the next level (which
       is unusual in Merkle trees). This results in certain sequences of
       transactions leading to the same merkle root. For example, these two
       trees:

                    A               A
                  /  \            /   \
                B     C         B       C
               / \    |        / \     / \
              D   E   F       D   E   F   F
             / \ / \ / \     / \ / \ / \ / \
             1 2 3 4 5 6     1 2 3 4 5 6 5 6

       for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
       6 are repeated) result in the same root hash A (because the hash of both
       of (F) and (F,F) is C).

       The vulnerability results from being able to send a block with such a
       transaction list, with the same merkle root, and the same block hash as
       the original without duplication, resulting in failed validation. If the
       receiving node proceeds to mark that block as permanently invalid
       however, it will fail to accept further unmodified (and thus potentially
       valid) versions of the same block. We defend against this by detecting
       the case where we would hash two identical hashes at the end of the list
       together, and treating that identically to the block having an invalid
       merkle root. Assuming no double-SHA256 collisions, this will detect all
       known ways of changing the transactions without affecting the merkle
       root.
    */
    vMerkleTree.clear();
    vMerkleTree.reserve(vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.
    for (std::vector<CTransaction>::const_iterator it(vtx.begin()); it != vtx.end(); ++it)
        vMerkleTree.push_back(it->GetHash());
    int j = 0;
    bool mutated = false;
    for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
    {
        for (int i = 0; i < nSize; i += 2)
        {
            int i2 = std::min(i+1, nSize-1);
            if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) {
                // Two identical hashes at the end of the list at a particular level.
                mutated = true;
            }
            vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
                                       BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
        }
        j += nSize;
    }
    if (fMutated) {
        *fMutated = mutated;
    }
    return (vMerkleTree.empty() ? uint256() : vMerkleTree.back());
}
Ejemplo n.º 27
0
#include <boost/test/unit_test.hpp>
#include <stdint.h>
#include <sstream>
#include <iomanip>
#include <limits>
#include <cmath>
#include <string>
#include <stdio.h>

BOOST_FIXTURE_TEST_SUITE(uint256_tests, BasicTestingSetup)

const unsigned char R1Array[] =
    "\x9c\x52\x4a\xdb\xcf\x56\x11\x12\x2b\x29\x12\x5e\x5d\x35\xd2\xd2"
    "\x22\x81\xaa\xb5\x33\xf0\x08\x32\xd5\x56\xb1\xf9\xea\xe5\x1d\x7d";
const char R1ArrayHex[] = "7D1DE5EAF9B156D53208F033B5AA8122D2d2355d5e12292b121156cfdb4a529c";
const uint256 R1L = uint256(std::vector<unsigned char>(R1Array,R1Array+32));
const uint160 R1S = uint160(std::vector<unsigned char>(R1Array,R1Array+20));

const unsigned char R2Array[] =
    "\x70\x32\x1d\x7c\x47\xa5\x6b\x40\x26\x7e\x0a\xc3\xa6\x9c\xb6\xbf"
    "\x13\x30\x47\xa3\x19\x2d\xda\x71\x49\x13\x72\xf0\xb4\xca\x81\xd7";
const uint256 R2L = uint256(std::vector<unsigned char>(R2Array,R2Array+32));
const uint160 R2S = uint160(std::vector<unsigned char>(R2Array,R2Array+20));

const unsigned char ZeroArray[] =
    "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
    "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
const uint256 ZeroL = uint256(std::vector<unsigned char>(ZeroArray,ZeroArray+32));
const uint160 ZeroS = uint160(std::vector<unsigned char>(ZeroArray,ZeroArray+20));

const unsigned char OneArray[] =
Ejemplo n.º 28
0
    bool doapplyvoting(ledger::ref lastclosedledger, shamap::ref initialposition) override
    {
        uint32_t dividendledger = lastclosedledger->getdividendbaseledger();
        
        int weight = 0;
        std::map<uint256, int> votes;
        
        // get validations for validation ledger
        validationset const set = getapp().getvalidations ().getvalidations (lastclosedledger->gethash ());
        for (auto const& e : set)
        {
            stvalidation const& val = *e.second;
            
            if (val.istrusted ())
            {
                if (val.isfieldpresent (sfdividendledger) &&
                    val.isfieldpresent (sfdividendresulthash))
                {
                    uint32_t ledgerseq = val.getfieldu32 (sfdividendledger);
                    if (ledgerseq != dividendledger)
                        continue;
                    const uint256 & dividendhash = val.getfieldh256 (sfdividendresulthash);
                    ++votes[dividendhash];
//                    if (ledgerseq != dividendledger || dividendhash != dividendresulthash) {
                    if (m_journal.debug)
                        m_journal.debug << "recv dividend apply vote based " << ledgerseq << " hash " << dividendhash << " from validator " << val.getnodeid() << " in " << lastclosedledger->gethash();
//                        continue;
//                    }
//                    ++weight;
                }
            }
        }
        
        uint256 dividendresulthash;
        for (auto const& v : votes)
        {
            if (v.second > weight)
            {
                dividendresulthash = v.first;
                weight = v.second;
            }
        }
        
        dividendmaster::pointer dividendmaster = getapp().getops().getdividendmaster();
        if (!dividendmaster->trylock())
        {
            if (weight >=getapp().getledgermaster().getminvalidations())
                return false;
            else
                return true;
        }
        
        if (!dividendmaster->isready() ||
            dividendledger != dividendmaster->getledgerseq() ||
            dividendresulthash != dividendmaster->getresulthash())
        {
            if (dividendmaster->isready())
                m_journal.warning << "we got mismatch dividend apply based " << dividendledger << " hash " << dividendresulthash << " ours " << dividendmaster->getresulthash() << " based " << dividendmaster->getledgerseq() << " in " << lastclosedledger->gethash();
            dividendmaster->unlock();
            if (weight >=getapp().getledgermaster().getminvalidations())
                return false;
            else
                return true;
        }
        
        if (weight >= getapp().getledgermaster().getminvalidations())
        {
            m_journal.warning << "we are voting for a dividend apply based " << dividendledger << " hash " << dividendresulthash << " with " << weight << " same votes in " << lastclosedledger->gethash();
            dividendmaster->filldivresult(initialposition);
            dividendmaster->filldivready(initialposition);
            dividendmaster->setready(false);
        }
        else
        {
            m_journal.warning << "we are cancelling a dividend apply with only " << weight << " same votes in " << lastclosedledger->gethash();
            dividendmaster->settotaldividend(0);
            dividendmaster->settotaldividendvbc(0);
            dividendmaster->setsumvrank(0);
            dividendmaster->setsumvspd(0);
            dividendmaster->setresulthash(uint256());
            dividendmaster->filldivready(initialposition);
            dividendmaster->setready(false);
        }
        
        dividendmaster->unlock();
        
        return true;
    }
Ejemplo n.º 29
0
uint256 CCoinsView::GetBestBlock() const { return uint256(); }
Ejemplo n.º 30
0
    CRegTestParams() {
        strNetworkID = "regtest";
        consensus.nSubsidyHalvingInterval = 150;
        consensus.nMasternodePaymentsStartBlock = 240;
        consensus.nMasternodePaymentsIncreaseBlock = 350;
        consensus.nMasternodePaymentsIncreasePeriod = 10;
        consensus.nInstantSendConfirmationsRequired = 2;
        consensus.nInstantSendKeepLock = 6;
        consensus.nBudgetPaymentsStartBlock = 1000;
        consensus.nBudgetPaymentsCycleBlocks = 50;
        consensus.nBudgetPaymentsWindowBlocks = 10;
        consensus.nSuperblockStartBlock = 1500;
        consensus.nSuperblockStartHash = uint256(); // do not check this on regtest
        consensus.nSuperblockCycle = 10;
        consensus.nGovernanceMinQuorum = 1;
        consensus.nGovernanceFilterElements = 100;
        consensus.nMasternodeMinimumConfirmations = 1;
        consensus.BIP34Height = 100000000; // BIP34 has not activated on regtest (far in the future so block v1 are not rejected in tests)
        consensus.BIP34Hash = uint256();
        consensus.BIP65Height = 1351; // BIP65 activated on regtest (Used in rpc activation tests)
        consensus.BIP66Height = 1251; // BIP66 activated on regtest (Used in rpc activation tests)
        consensus.DIP0001Height = 2000;
        consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); // ~uint256(0) >> 1
        consensus.nPowTargetTimespan = 24 * 60 * 60; // Dash: 1 day
        consensus.nPowTargetSpacing = 2.5 * 60; // Dash: 2.5 minutes
        consensus.fPowAllowMinDifficultyBlocks = true;
        consensus.fPowNoRetargeting = true;
        consensus.nPowKGWHeight = 15200; // same as mainnet
        consensus.nPowDGWHeight = 34140; // same as mainnet
        consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains
        consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016)
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL;
        consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].bit = 1;
        consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nStartTime = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_DIP0001].nTimeout = 999999999999ULL;
        consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].bit = 2;
        consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nStartTime = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_BIP147].nTimeout = 999999999999ULL;
        consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].bit = 3;
        consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nStartTime = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_DIP0003].nTimeout = 999999999999ULL;

        // The best chain should have at least this much work.
        consensus.nMinimumChainWork = uint256S("0x00");

        // By default assume that the signatures in ancestors of this block are valid.
        consensus.defaultAssumeValid = uint256S("0x00");

        pchMessageStart[0] = 0xfc;
        pchMessageStart[1] = 0xc1;
        pchMessageStart[2] = 0xb7;
        pchMessageStart[3] = 0xdc;
        nDefaultPort = 19994;
        nPruneAfterHeight = 1000;

        genesis = CreateGenesisBlock(1417713337, 1096447, 0x207fffff, 1, 50 * COIN);
        consensus.hashGenesisBlock = genesis.GetHash();
        assert(consensus.hashGenesisBlock == uint256S("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e"));
        assert(genesis.hashMerkleRoot == uint256S("0xe0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7"));

        vFixedSeeds.clear(); //!< Regtest mode doesn't have any fixed seeds.
        vSeeds.clear();      //!< Regtest mode doesn't have any DNS seeds.

        fMiningRequiresPeers = false;
        fDefaultConsistencyChecks = true;
        fRequireStandard = false;
        fRequireRoutableExternalIP = false;
        fMineBlocksOnDemand = true;
        fAllowMultipleAddressesFromGroup = true;
        fAllowMultiplePorts = true;

        nFulfilledRequestExpireTime = 5*60; // fulfilled requests expire in 5 minutes

        // privKey: cP4EKFyJsHT39LDqgdcB43Y3YXjNyjb5Fuas1GQSeAtjnZWmZEQK
        vSporkAddresses = {"yj949n1UH6fDhw6HtVE5VMj2iSTaSWBMcW"};
        nMinSporkKeys = 1;
        // regtest usually has no masternodes in most tests, so don't check for upgraged MNs
        fBIP9CheckMasternodesUpgraded = false;
        consensus.fLLMQAllowDummyCommitments = true;

        checkpointData = (CCheckpointData){
            boost::assign::map_list_of
            ( 0, uint256S("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e"))
        };

        chainTxData = ChainTxData{
            0,
            0,
            0
        };

        // Regtest Dash addresses start with 'y'
        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,140);
        // Regtest Dash script addresses start with '8' or '9'
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,19);
        // Regtest private keys start with '9' or 'c' (Bitcoin defaults)
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,239);
        // Regtest Dash BIP32 pubkeys start with 'tpub' (Bitcoin defaults)
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
        // Regtest Dash BIP32 prvkeys start with 'tprv' (Bitcoin defaults)
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();

        // Regtest Dash BIP44 coin type is '1' (All coin's testnet default)
        nExtCoinType = 1;

        // long living quorum params
        consensus.llmqs[Consensus::LLMQ_10_60] = llmq10_60;
        consensus.llmqs[Consensus::LLMQ_50_60] = llmq50_60;
    }