Merge pull request #38 from jl777/dPoW

DPoW
This commit is contained in:
jl777
2016-10-24 06:09:11 -03:00
committed by GitHub
19 changed files with 606 additions and 142 deletions

View File

@@ -7,7 +7,7 @@ komodo_gtest_SOURCES = \
gtest/test_checktransaction.cpp \
gtest/json_test_vectors.cpp \
gtest/json_test_vectors.h \
gtest/test_foundersreward.cpp \
# gtest/test_foundersreward.cpp \
gtest/test_wallet_zkeys.cpp \
gtest/test_jsonspirit.cpp \
gtest/test_tautology.cpp \

View File

@@ -23,6 +23,8 @@
using namespace std;
#include "komodo_interest.h"
static bool fCreateBlank;
static map<string,UniValue> registers;
@@ -322,6 +324,7 @@ vector<unsigned char> ParseHexUO(map<string,UniValue>& o, string strKey)
return ParseHexUV(o[strKey], strKey);
}
static void MutateTxSign(CMutableTransaction& tx, const string& flagStr)
{
int nHashType = SIGHASH_ALL;

View File

@@ -383,18 +383,24 @@ const CScript &CCoinsViewCache::GetSpendFor(const CTxIn& input) const
return coins->vout[input.prevout.n].scriptPubKey;
}
uint32_t komodo_txtime(uint256 hash);
uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime);
CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const
CAmount CCoinsViewCache::GetValueIn(int32_t nHeight,int64_t *interestp,const CTransaction& tx,uint32_t tiptime) const
{
if (tx.IsCoinBase())
uint32_t timestamp,minutes; int64_t interest;
*interestp = 0;
if ( tx.IsCoinBase() != 0 )
return 0;
CAmount nResult = 0;
CAmount value,nResult = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
//fprintf(stderr,"i.%d time.%u\n",i,komodo_txtime(tx.vin[i].prevout.hash));
nResult += GetOutputFor(tx.vin[i]).nValue;
value = GetOutputFor(tx.vin[i]).nValue;
nResult += value;
interest = komodo_interest(nHeight,value,tx.nLockTime,tiptime);
#ifdef KOMODO_ENABLE_INTEREST
nResult += interest;
#endif
(*interestp) += interest;
}
nResult += tx.GetJoinSplitValueIn();

View File

@@ -85,12 +85,14 @@ public:
//! version of the CTransaction; accesses to this value should probably check for nHeight as well,
//! as new tx version will probably only be introduced at certain heights
int nVersion;
uint32_t nLockTime;
void FromTx(const CTransaction &tx, int nHeightIn) {
fCoinBase = tx.IsCoinBase();
vout = tx.vout;
nHeight = nHeightIn;
nVersion = tx.nVersion;
nLockTime = tx.nLockTime;
ClearUnspendable();
}
@@ -510,7 +512,7 @@ public:
* @param[in] tx transaction for which we are checking input total
* @return Sum of value of all inputs (scriptSigs)
*/
CAmount GetValueIn(const CTransaction& tx) const;
CAmount GetValueIn(int32_t nHeight,int64_t *interestp,const CTransaction& tx,uint32_t prevblocktime) const;
//! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
bool HaveInputs(const CTransaction& tx) const;

View File

@@ -14,6 +14,7 @@
#include <boost/filesystem.hpp>
#include "util.h"
#ifndef disable_founders
// To run tests:
// ./zcash-gtest --gtest_filter="founders_reward_test.*"
@@ -178,3 +179,4 @@ TEST(founders_reward_test, per_address_reward_testnet) {
SelectParams(CBaseChainParams::TESTNET);
verifyNumberOfRewards();
}
#endif

View File

@@ -19,29 +19,62 @@
#include <stdint.h>
#include <stdio.h>
#include <pthread.h>
#include <ctype.h>
#include "uthash.h"
#include "komodo_interest.h"
#define KOMODO_TESTNET_EXPIRATION 60000
#define KOMODO_ELECTION_GAP 1000
#define KOMODO_PUBKEYS_HEIGHT(height) ((int32_t)(((((height)+KOMODO_ELECTION_GAP*.5)/KOMODO_ELECTION_GAP) + 1) * KOMODO_ELECTION_GAP))
int32_t IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,NOTARIZED_HEIGHT,Num_nutxos,KOMODO_NUMNOTARIES = 64;
int32_t NUM_PRICES,IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,NOTARIZED_HEIGHT,Num_nutxos,KOMODO_NUMNOTARIES = 64;
std::string NOTARY_PUBKEY;
uint8_t NOTARY_PUBKEY33[33];
uint256 NOTARIZED_HASH,NOTARIZED_BTCTXID;
pthread_mutex_t komodo_mutex;
uint32_t *PVALS;
struct nutxo_entry { UT_hash_handle hh; uint256 txhash; uint64_t voutmask; int32_t notaryid,height; } *NUTXOS;
struct knotary_entry { UT_hash_handle hh; uint8_t pubkey[33],notaryid; };
struct knotaries_entry { int32_t height,numnotaries; struct knotary_entry *Notaries; } Pubkeys[10000];
struct notarized_checkpoint { uint256 notarized_hash,notarized_btctxid; int32_t nHeight,notarized_height; } *NPOINTS; int32_t NUM_NPOINTS;
int32_t komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotaries,uint8_t notaryid,uint256 txhash,uint64_t voutmask,uint8_t numvouts);
int32_t komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotaries,uint8_t notaryid,uint256 txhash,uint64_t voutmask,uint8_t numvouts,uint32_t *pvals,uint8_t numpvals);
// add opreturn funcid
// pricefeeds
#define CRYPTO777_PUBSECPSTR "020e46e79a2a8d12b9b5d12c7a91adb4e454edfae43c0a0cb805427d2ac7613fd9"
#define MAX_CURRENCIES 32
char CURRENCIES[][8] = { "USD", "EUR", "JPY", "GBP", "AUD", "CAD", "CHF", "NZD", // major currencies
"CNY", "RUB", "MXN", "BRL", "INR", "HKD", "TRY", "ZAR", "PLN", "NOK", "SEK", "DKK", "CZK", "HUF", "ILS", "KRW", "MYR", "PHP", "RON", "SGD", "THB", "BGN", "IDR", "HRK",
"KMD" };
uint32_t MINDENOMS[] = { 1000, 1000, 100000, 1000, 1000, 1000, 1000, 1000, // major currencies
10000, 100000, 10000, 1000, 100000, 10000, 1000, 10000, 1000, 10000, 10000, 10000, 10000, 100000, 1000, 1000000, 1000, 10000, 1000, 1000, 10000, 1000, 10000000, 10000, // end of currencies
};
/*uint32_t PAX_val32(double val)
{
uint32_t val32 = 0; struct price_resolution price;
if ( (price.Pval= val*1000000000) != 0 )
{
if ( price.Pval > 0xffffffff )
printf("Pval overflow error %lld\n",(long long)price.Pval);
else val32 = (uint32_t)price.Pval;
}
return(val32);
}*/
double PAX_val(uint32_t pval,int32_t baseid)
{
//printf("PAX_val baseid.%d pval.%u\n",baseid,pval);
if ( baseid >= 0 && baseid < MAX_CURRENCIES )
return(((double)pval / 1000000000.) / MINDENOMS[baseid]);
return(0.);
}
const char *Notaries[][2] =
{
{ "jl777_testA", "03b7621b44118017a16043f19b30cc8a4cfe068ac4e42417bae16ba460c80f3828" },
@@ -81,37 +114,63 @@ const char *Notaries[][2] =
{ "titomane_SH", "035f49d7a308dd9a209e894321f010d21b7793461b0c89d6d9231a3fe5f68d9960" },
};
uint64_t komodo_accrued_interest(int32_t height,int64_t paidinterest)
{
static uint64_t *interests; static int32_t maxheight;
int32_t ind,incr = 100000;
if ( height >= maxheight )
{
interests = (uint64_t *)realloc(interests,(maxheight + incr) * sizeof(*interests) * 2);
memset(&interests[maxheight << 1],0,incr * sizeof(*interests) * 2);
maxheight += incr;
}
ind = (height << 1);
if ( paidinterest < 0 ) // request
return(interests[ind]);
else
{
if ( interests[ind + 1] != paidinterest )
{
interests[ind + 1] = paidinterest;
if ( height == 0 )
height++;
for (; height<maxheight; height++,ind+=2)
interests[ind] = interests[ind - 2] + interests[ind + 1];
}
}
}
static const uint32_t crc32_tab[] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
uint64_t komodo_moneysupply(int32_t height)
uint32_t calc_crc32(uint32_t crc,const void *buf,size_t size)
{
if ( height <= 1 )
return(0);
else return(COIN * 100000000 + (height-1) * 3 + komodo_accrued_interest(height,-1));
const uint8_t *p;
p = (const uint8_t *)buf;
crc = crc ^ ~0U;
while (size--)
crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
return crc ^ ~0U;
}
int32_t iguana_rwnum(int32_t rwflag,uint8_t *serialized,int32_t len,void *endianedp)
@@ -165,6 +224,29 @@ int32_t iguana_rwbignum(int32_t rwflag,uint8_t *serialized,int32_t len,uint8_t *
return(len);
}
int32_t dpow_readprices(uint8_t *data,uint32_t *timestampp,double *KMDBTCp,double *BTCUSDp,double *CNYUSDp,uint32_t *pvals)
{
uint32_t kmdbtc,btcusd,cnyusd; int32_t i,n,len = 0;
len += iguana_rwnum(0,&data[len],sizeof(uint32_t),(void *)timestampp);
len += iguana_rwnum(0,&data[len],sizeof(uint32_t),(void *)&n);
len += iguana_rwnum(0,&data[len],sizeof(uint32_t),(void *)&kmdbtc); // /= 1000
len += iguana_rwnum(0,&data[len],sizeof(uint32_t),(void *)&btcusd); // *= 1000
len += iguana_rwnum(0,&data[len],sizeof(uint32_t),(void *)&cnyusd);
*KMDBTCp = ((double)kmdbtc / (1000000000. * 1000.));
*BTCUSDp = ((double)btcusd / (1000000000. / 1000.));
*CNYUSDp = ((double)cnyusd / 1000000000.);
for (i=0; i<n-3; i++)
{
len += iguana_rwnum(0,&data[len],sizeof(uint32_t),(void *)&pvals[i]);
//printf("%u ",pvals[i]);
}
pvals[i++] = kmdbtc;
pvals[i++] = btcusd;
pvals[i++] = cnyusd;
//printf("OP_RETURN prices\n");
return(n);
}
int32_t _unhex(char c)
{
if ( c >= '0' && c <= '9' )
@@ -241,7 +323,7 @@ int32_t komodo_threshold(int32_t height,uint64_t signedmask)
for (i=0; i<numnotaries; i++)
if ( ((1LL << i) & signedmask) != 0 )
wt++;
if ( wt > (numnotaries >> 1) || (wt > numnotaries/5 && (signedmask & 3) != 0) )
if ( wt > (numnotaries >> 1) || (wt > 7 && (signedmask & 3) != 0) )
return(1); // N/2+1 || N/3 + devsig
else return(0);
}
@@ -253,19 +335,8 @@ uint32_t komodo_txtime(uint256 hash)
if (!GetTransaction(hash, tx, hashBlock, true))
{
//printf("null GetTransaction\n");
return(0);
return(tx.nLockTime);
}
if (!hashBlock.IsNull()) {
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex))
return(pindex->GetBlockTime());
}
//printf("cant find in iterator\n");
}
//printf("null hashBlock\n");
return(0);
}
@@ -283,7 +354,7 @@ void komodo_nutxoadd(int32_t addflag,int32_t height,int32_t notaryid,uint256 txh
HASH_ADD_KEYPTR(hh,NUTXOS,&np->txhash,sizeof(np->txhash),np);
printf("Add NUTXO[%d] <- %s notaryid.%d t%u %s %llx\n",Num_nutxos,Notaries[notaryid][0],notaryid,komodo_txtime(txhash),txhash.ToString().c_str(),(long long)voutmask);
if ( addflag != 0 )
komodo_stateupdate(height,0,0,notaryid,txhash,voutmask,numvouts);
komodo_stateupdate(height,0,0,notaryid,txhash,voutmask,numvouts,0,0);
Num_nutxos++;
pthread_mutex_unlock(&komodo_mutex);
}
@@ -353,6 +424,11 @@ int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33)
void komodo_notarized_update(int32_t nHeight,int32_t notarized_height,uint256 notarized_hash,uint256 notarized_btctxid)
{
struct notarized_checkpoint *np;
if ( notarized_height > nHeight )
{
printf("komodo_notarized_update REJECT notarized_height %d > %d nHeight\n",notarized_height,nHeight);
return;
}
NPOINTS = (struct notarized_checkpoint *)realloc(NPOINTS,(NUM_NPOINTS+1) * sizeof(*NPOINTS));
np = &NPOINTS[NUM_NPOINTS++];
memset(np,0,sizeof(*np));
@@ -379,14 +455,97 @@ int32_t komodo_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *n
*notarized_hashp = np->notarized_hash;
*notarized_btctxidp = np->notarized_btctxid;
return(np->notarized_height);
}
}
memset(notarized_hashp,0,sizeof(*notarized_hashp));
return(0);
}
void komodo_pvals(int32_t height,uint32_t *pvals,uint8_t numpvals)
{
int32_t i,nonz; double KMDBTC,BTCUSD,CNYUSD; uint32_t kmdbtc,btcusd,cnyusd;
if ( numpvals >= 35 )
{
for (nonz=i=0; i<32; i++)
{
if ( pvals[i] != 0 )
nonz++;
printf("%u ",pvals[i]);
}
if ( nonz == 32 )
{
kmdbtc = pvals[i++];
btcusd = pvals[i++];
cnyusd = pvals[i++];
KMDBTC = ((double)kmdbtc / (1000000000. * 1000.));
BTCUSD = ((double)btcusd / (1000000000. / 1000.));
CNYUSD = ((double)cnyusd / 1000000000.);
PVALS = (uint32_t *)realloc(PVALS,(NUM_PRICES+1) * sizeof(*PVALS) * 36);
PVALS[36 * NUM_PRICES] = height;
memcpy(&PVALS[36 * NUM_PRICES + 1],pvals,sizeof(*pvals) * 35);
NUM_PRICES++;
printf("OP_RETURN.%d KMD %.8f BTC %.6f CNY %.6f NUM_PRICES.%d\n",height,KMDBTC,BTCUSD,CNYUSD,NUM_PRICES);
}
}
}
int32_t komodo_baseid(char *origbase)
{
int32_t i; char base[64];
for (i=0; origbase[i]!=0&&i<sizeof(base); i++)
base[i] = toupper((int32_t)(origbase[i] & 0xff));
base[i] = 0;
for (i=0; i<=MAX_CURRENCIES; i++)
if ( strcmp(CURRENCIES[i],base) == 0 )
return(i);
printf("illegal base.(%s) %s\n",origbase,base);
return(-1);
}
int32_t komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotaries,uint8_t notaryid,uint256 txhash,uint64_t voutmask,uint8_t numvouts)
#define USD 0
uint64_t komodo_paxprice(int32_t height,char *base,char *rel,uint64_t volume)
{
static FILE *fp; static int32_t errs,didinit; char fname[512]; int32_t ht,k,func; uint8_t num,pubkeys[64][33];
int32_t baseid=-1,relid=-1,i,ht; uint32_t kmdbtc,btcusd,pvalb,pvalr,*ptr; double usdval,baseval,relval,KMDBTC,BTCUSD,KMDUSD;
if ( (baseid= komodo_baseid(base)) >= 0 && (relid= komodo_baseid(rel)) >= 0 )
{
for (i=NUM_PRICES-1; i>=0; i--)
{
ptr = &PVALS[36 * i];
if ( *ptr < height )
{
if ( (pvalb= ptr[1 + baseid]) != 0 )
{
baseval = PAX_val(pvalb,baseid);
if ( relid == MAX_CURRENCIES )
{
kmdbtc = ptr[1 + MAX_CURRENCIES];
btcusd = ptr[1 + MAX_CURRENCIES + 1];
if ( ptr[1 + USD] != 0 && kmdbtc != 0 && btcusd != 0 )
{
usdval = PAX_val(ptr[1 + USD],USD);
KMDBTC = ((double)kmdbtc / (1000000000. * 1000.));
BTCUSD = ((double)btcusd / (1000000000. / 1000.));
KMDUSD = (KMDBTC * BTCUSD);
printf("base -> USD %f, BTC %f KMDUSD %f\n",baseval/usdval,BTCUSD,KMDUSD);
return(volume * (baseval / usdval) / KMDUSD);
}
}
else if ( (pvalr= ptr[1 + relid]) != 0 )
{
relval = PAX_val(pvalr,relid);
printf("ht.%d [%d] base.(%u %f) rel.(%u %f) -> %llu\n",height,*ptr,pvalb,baseval,pvalr,relval,(long long)(COIN * (baseval / relval)));
return(volume * (baseval / relval));
}
}
return(0);
}
}
} else printf("paxprice invalid base.%s %d, rel.%s %d\n",base,baseid,rel,relid);
return(0);
}
int32_t komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotaries,uint8_t notaryid,uint256 txhash,uint64_t voutmask,uint8_t numvouts,uint32_t *pvals,uint8_t numpvals)
{
static FILE *fp; static int32_t errs,didinit; char fname[512]; int32_t ht,k,i,func; uint8_t num,pubkeys[64][33];
#ifdef WIN32
sprintf(fname,"%s\\%s",GetDataDir(false).string().c_str(),(char *)"komodostate");
#else
@@ -442,6 +601,16 @@ int32_t komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numno
{
//printf("D[%d]\n",ht);
}
else if ( func == 'V' )
{
int32_t numpvals; uint32_t pvals[128];
numpvals = fgetc(fp);
if ( numpvals*sizeof(uint32_t) <= sizeof(pvals) && fread(pvals,sizeof(uint32_t),numpvals,fp) == numpvals )
{
komodo_pvals(ht,pvals,numpvals);
printf("load pvals ht.%d numpvals.%d\n",ht,numpvals);
} else printf("error loading pvals[%d]\n",numpvals);
}
else printf("illegal func.(%d %c)\n",func,func);
}
} else fp = fopen(fname,"wb+");
@@ -480,6 +649,17 @@ int32_t komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numno
if ( fwrite(&txhash,1,sizeof(txhash),fp) != sizeof(txhash) )
errs++;
}
else if ( pvals != 0 && numpvals > 0 )
{
fputc('V',fp);
if ( fwrite(&height,1,sizeof(height),fp) != sizeof(height) )
errs++;
fputc(numpvals,fp);
if ( fwrite(pvals,sizeof(uint32_t),numpvals,fp) != numpvals )
errs++;
komodo_pvals(height,pvals,numpvals);
printf("save pvals height.%d numpvals.%d\n",height,numpvals);
}
else if ( height != 0 )
{
//printf("func N ht.%d errs.%d\n",NOTARIZED_HEIGHT,errs);
@@ -515,13 +695,13 @@ void komodo_init()
}
komodo_notarysinit(0,pubkeys,KOMODO_NUMNOTARIES);
memset(&zero,0,sizeof(zero));
komodo_stateupdate(0,0,0,0,zero,0,0);
komodo_stateupdate(0,0,0,0,zero,0,0,0,0);
}
}
int32_t komodo_voutupdate(int32_t notaryid,uint8_t *scriptbuf,int32_t scriptlen,int32_t height,uint256 txhash,int32_t i,int32_t j,uint64_t *voutmaskp,int32_t *specialtxp,int32_t *notarizedheightp)
{
int32_t k,opretlen,nid,len = 0; uint256 kmdtxid,btctxid; uint8_t crypto777[33];
static uint256 zero; int32_t k,opretlen,nid,len = 0; uint256 kmdtxid,btctxid; uint8_t crypto777[33];
if ( scriptlen == 35 && scriptbuf[0] == 33 && scriptbuf[34] == 0xac )
{
decode_hex(crypto777,33,(char *)CRYPTO777_PUBSECPSTR);
@@ -565,7 +745,7 @@ int32_t komodo_voutupdate(int32_t notaryid,uint8_t *scriptbuf,int32_t scriptlen,
opretlen = scriptbuf[len++];
opretlen = (opretlen << 8) + scriptbuf[len++];
}
if ( opretlen >= 32*2+4 )
if ( opretlen >= 32*2+4 && strcmp("KMD",(char *)&scriptbuf[len+32*2+4]) == 0 )
{
len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&kmdtxid);
len += iguana_rwnum(0,&scriptbuf[len],4,(uint8_t *)notarizedheightp);
@@ -573,15 +753,21 @@ int32_t komodo_voutupdate(int32_t notaryid,uint8_t *scriptbuf,int32_t scriptlen,
//for (k=0; k<scriptlen; k++)
// printf("%02x",scriptbuf[k]);
//printf(" <- script ht.%d i.%d j.%d\n",height,i,j);
printf("ht.%d NOTARIZED.%d KMD.%s BTCTXID.%s\n",height,*notarizedheightp,kmdtxid.ToString().c_str(),btctxid.ToString().c_str());
if ( *notarizedheightp > NOTARIZED_HEIGHT )
if ( *notarizedheightp > NOTARIZED_HEIGHT && *notarizedheightp < height )
{
static uint256 zero;
printf("ht.%d NOTARIZED.%d KMD.%s BTCTXID.%s (%s)\n",height,*notarizedheightp,kmdtxid.ToString().c_str(),btctxid.ToString().c_str(),(char *)&scriptbuf[len]);
NOTARIZED_HEIGHT = *notarizedheightp;
NOTARIZED_HASH = kmdtxid;
NOTARIZED_BTCTXID = btctxid;
komodo_stateupdate(height,0,0,0,zero,0,0);
}
komodo_stateupdate(height,0,0,0,zero,0,0,0,0);
} else printf("reject ht.%d NOTARIZED.%d KMD.%s BTCTXID.%s (%s)\n",height,*notarizedheightp,kmdtxid.ToString().c_str(),btctxid.ToString().c_str(),(char *)&scriptbuf[len]);
}
else if ( i == 0 && scriptbuf[len] == 'P' )
{
double KMDBTC,BTCUSD,CNYUSD; uint32_t numpvals,timestamp,pvals[128];
numpvals = dpow_readprices(&scriptbuf[++len],&timestamp,&KMDBTC,&BTCUSD,&CNYUSD,pvals);
komodo_stateupdate(height,0,0,0,zero,0,0,pvals,numpvals);
printf("vout OP_RETURN.%d prices numpvals.%d opretlen.%d\n",height,numpvals,opretlen);
}
}
return(notaryid);
@@ -655,7 +841,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block)
if ( numvalid > 13 )
{
memset(&txhash,0,sizeof(txhash));
komodo_stateupdate(height,pubkeys,numvalid,0,txhash,0,0);
komodo_stateupdate(height,pubkeys,numvalid,0,txhash,0,0,0,0);
}
printf("new notaries.%d newheight.%d from height.%d\n",numvouts-1,KOMODO_PUBKEYS_HEIGHT(height),height);
}
@@ -670,7 +856,7 @@ void komodo_disconnect(CBlockIndex *pindex,CBlock& block)
//uint256 zero;
//printf("disconnect ht.%d\n",pindex->nHeight);
//memset(&zero,0,sizeof(zero));
//komodo_stateupdate(-pindex->nHeight,0,0,0,zero,0,0);
//komodo_stateupdate(-pindex->nHeight,0,0,0,zero,0,0,0,0);
}
int32_t komodo_block2height(CBlock *block)
@@ -719,4 +905,77 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height)
}
}
int32_t komodo_opreturnscript(uint8_t *script,uint8_t type,uint8_t *opret,int32_t opretlen)
{
int32_t offset = 0;
script[offset++] = 0x6a;
opretlen++;
if ( opretlen >= 0x4c )
{
if ( opretlen > 0xff )
{
script[offset++] = 0x4d;
script[offset++] = opretlen & 0xff;
script[offset++] = (opretlen >> 8) & 0xff;
}
else
{
script[offset++] = 0x4c;
script[offset++] = opretlen;
}
} else script[offset++] = opretlen;
script[offset++] = type;
memcpy(&script[offset],opret,opretlen);
return(opretlen + offset);
}
int32_t komodo_opreturn(uint8_t *opret,int32_t maxsize)
{
static uint32_t lastcrc;
FILE *fp; char fname[512]; uint32_t crc32,check,timestamp; int32_t i,n,retval,fsize,len=0; uint8_t data[8192];
#ifdef WIN32
sprintf(fname,"%s\\%s",GetDataDir(false).string().c_str(),(char *)"komodofeed");
#else
sprintf(fname,"%s/%s",GetDataDir(false).string().c_str(),(char *)"komodofeed");
#endif
if ( (fp= fopen(fname,"rb")) != 0 )
{
fseek(fp,0,SEEK_END);
fsize = (int32_t)ftell(fp);
rewind(fp);
if ( fsize <= maxsize-4 && fsize <= sizeof(data) && fsize > sizeof(crc32) )
{
if ( (retval= (int32_t)fread(data,1,fsize,fp)) == fsize )
{
len = iguana_rwnum(0,data,sizeof(crc32),(void *)&crc32);
check = calc_crc32(0,data+sizeof(crc32),(int32_t)(fsize-sizeof(crc32)));
if ( check == crc32 )
{
double KMDBTC,BTCUSD,CNYUSD; uint32_t pvals[128];
dpow_readprices(&data[len],&timestamp,&KMDBTC,&BTCUSD,&CNYUSD,pvals);
if ( 0 && lastcrc != crc32 )
{
for (i=0; i<32; i++)
printf("%u ",pvals[i]);
printf("t%u n.%d KMD %f BTC %f CNY %f (%f)\n",timestamp,n,KMDBTC,BTCUSD,CNYUSD,CNYUSD!=0?1./CNYUSD:0);
}
if ( timestamp > time(NULL)-600 )
{
n = komodo_opreturnscript(opret,'P',data+sizeof(crc32),(int32_t)(fsize-sizeof(crc32)));
if ( 0 && lastcrc != crc32 )
{
for (i=0; i<n; i++)
printf("%02x",opret[i]);
printf(" coinbase opret[%d] crc32.%u:%u\n",n,crc32,check);
}
} else printf("t%u too old for %u\n",timestamp,(uint32_t)time(NULL));
lastcrc = crc32;
} else printf("crc32 %u mismatch %u\n",crc32,check);
} else printf("fread.%d error != fsize.%d\n",retval,fsize);
} else printf("fsize.%d > maxsize.%d or data[%d]\n",fsize,maxsize,(int32_t)sizeof(data));
fclose(fp);
}
return(n);
}
#endif

62
src/komodo_interest.h Normal file
View File

@@ -0,0 +1,62 @@
//#define KOMODO_ENABLE_INTEREST
#define KOMODO_INTEREST ((uint64_t)(0.05 * COIN))
#define dstr(x) ((double)(x)/COIN)
uint64_t komodo_accrued_interest(int32_t height,int64_t paidinterest)
{
static uint64_t *interests; static int32_t maxheight;
uint64_t total; int32_t ind,incr = 100000;
if ( height >= maxheight )
{
interests = (uint64_t *)realloc(interests,(maxheight + incr) * sizeof(*interests) * 2);
memset(&interests[maxheight << 1],0,incr * sizeof(*interests) * 2);
maxheight += incr;
}
ind = (height << 1);
if ( paidinterest < 0 ) // request
return(interests[ind]);
else
{
if ( interests[ind + 1] != paidinterest )
{
interests[ind + 1] = paidinterest;
if ( height == 0 )
interests[ind] = interests[ind + 1];
else interests[ind] = interests[ind - 2] + interests[ind + 1];
total = interests[ind];
for (++height; height<maxheight; height++)
{
ind = (height << 1);
interests[ind] = total;
interests[ind + 1] = 0;
}
}
}
}
uint64_t komodo_moneysupply(int32_t height)
{
if ( height <= 1 )
return(0);
else return(COIN * 100000000 + (height-1) * 3 + komodo_accrued_interest(height,-1));
}
uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime)
{
int32_t minutes; uint64_t numerator,denominator,interest = 0;
if ( komodo_moneysupply(txheight) < MAX_MONEY && nLockTime >= LOCKTIME_THRESHOLD && tiptime != 0 && nLockTime < tiptime && nValue >= COIN )
{
if ( (minutes= (tiptime - nLockTime) / 60) > 60 )
{
numerator = (nValue * KOMODO_INTEREST);
denominator = (((uint64_t)365 * 24 * 60) / minutes);
if ( denominator == 0 )
denominator = 1; // max KOMODO_INTEREST per transfer, do it at least annually!
interest = (numerator / denominator) / COIN;
fprintf(stderr,"komodo_interest %lld %.8f nLockTime.%u tiptime.%u minutes.%d interest %lld %.8f (%llu / %llu)\n",(long long)nValue,dstr(nValue),nLockTime,tiptime,minutes,(long long)interest,dstr(interest),(long long)numerator,(long long)denominator);
}
}
return(interest);
}

View File

@@ -699,9 +699,23 @@ bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
return true;
if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
return true;
if ( (int64_t)tx.nLockTime >= LOCKTIME_THRESHOLD && (int64_t)tx.nLockTime < nBlockTime-3600 )
{
fprintf(stderr,"IsFinalTx reject locktime %u vs nBlockTime %u\n",tx.nLockTime,(uint32_t)nBlockTime);
return(false); // need to prevent pastdating tx
}
BOOST_FOREACH(const CTxIn& txin, tx.vin)
if (!txin.IsFinal())
{
if ( txin.nSequence == 0xfffffffe && (int64_t)tx.nLockTime >= LOCKTIME_THRESHOLD && (int64_t)tx.nLockTime > nBlockTime )
{
}
else if (!txin.IsFinal())
{
printf("non-final txin seq.%x\n",txin.nSequence);
return false;
}
}
return true;
}
@@ -1037,38 +1051,44 @@ CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowF
}
bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
bool* pfMissingInputs, bool fRejectAbsurdFee)
bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,bool* pfMissingInputs, bool fRejectAbsurdFee)
{
AssertLockHeld(cs_main);
if (pfMissingInputs)
*pfMissingInputs = false;
if (!CheckTransaction(tx, state))
{
fprintf(stderr,"AcceptToMemoryPool CheckTransaction failed\n");
return error("AcceptToMemoryPool: CheckTransaction failed");
}
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
REJECT_INVALID, "coinbase");
{
fprintf(stderr,"AcceptToMemoryPool coinbase as individual tx\n");
return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),REJECT_INVALID, "coinbase");
}
// Rather not work on nonstandard transactions (unless -testnet/-regtest)
string reason;
if (Params().RequireStandard() && !IsStandardTx(tx, reason))
return state.DoS(0,
error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
REJECT_NONSTANDARD, reason);
{
fprintf(stderr,"AcceptToMemoryPool nonstandard transaction: %s\n",reason.c_str());
return state.DoS(0,error("AcceptToMemoryPool: nonstandard transaction: %s", reason),REJECT_NONSTANDARD, reason);
}
// Only accept nLockTime-using transactions that can be mined in the next
// block; we don't want our mempool filled up with transactions that can't
// be mined yet.
if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
{
fprintf(stderr,"AcceptToMemoryPool non-final\n");
return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
// is it already in the memory pool?
}
// is it already in the memory pool?
uint256 hash = tx.GetHash();
if (pool.exists(hash))
{
fprintf(stderr,"already in mempool\n");
return false;
}
// Check for conflicts with in-memory transactions
{
@@ -1079,6 +1099,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
if (pool.mapNextTx.count(outpoint))
{
// Disable replacement feature for now
fprintf(stderr,"Disable replacement feature for now\n");
return false;
}
}
@@ -1086,6 +1107,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) {
if (pool.mapNullifiers.count(nf))
{
fprintf(stderr,"pool.mapNullifiers.count\n");
return false;
}
}
@@ -1095,7 +1117,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
{
CCoinsView dummy;
CCoinsViewCache view(&dummy);
int64_t interest;
CAmount nValueIn = 0;
{
LOCK(pool.cs);
@@ -1104,7 +1126,10 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
// do we already have it?
if (view.HaveCoins(hash))
{
fprintf(stderr,"view.HaveCoins(hash) error\n");
return false;
}
// do all inputs exist?
// Note that this does not check for the presence of actual outputs (see the next check for that),
@@ -1113,6 +1138,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
if (!view.HaveCoins(txin.prevout.hash)) {
if (pfMissingInputs)
*pfMissingInputs = true;
fprintf(stderr,"do all inputs exist?\n");
return false;
}
}
@@ -1130,7 +1156,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
// Bring the best block into scope
view.GetBestBlock();
nValueIn = view.GetValueIn(tx);
nValueIn = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime);
// we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
view.SetBackend(dummy);
@@ -1148,8 +1174,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
unsigned int nSigOps = GetLegacySigOpCount(tx);
nSigOps += GetP2SHSigOpCount(tx, view);
if (nSigOps > MAX_STANDARD_TX_SIGOPS)
return state.DoS(0,
error("AcceptToMemoryPool: too many sigops %s, %d > %d",
return state.DoS(0, error("AcceptToMemoryPool: too many sigops %s, %d > %d",
hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
@@ -1190,16 +1215,14 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
REJECT_INSUFFICIENTFEE, "rate limited free transaction");
return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"), REJECT_INSUFFICIENTFEE, "rate limited free transaction");
LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
hash.ToString(),
nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
hash.ToString(), nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
@@ -2098,6 +2121,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
int64_t nTimeStart = GetTimeMicros();
CAmount nFees = 0;
int nInputs = 0;
int64_t interest,sum = 0;
unsigned int nSigOps = 0;
CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
std::vector<std::pair<uint256, CDiskTxPos> > vPos;
@@ -2131,7 +2155,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
if (nSigOps > MAX_BLOCK_SIGOPS)
return state.DoS(100, error("ConnectBlock(): too many sigops"),
REJECT_INVALID, "bad-blk-sigops");
//fprintf(stderr,"ht.%d vout0 t%u\n",pindex->nHeight,tx.nLockTime);
if (!tx.IsCoinBase())
{
if (!view.HaveInputs(tx))
@@ -2151,14 +2175,14 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin
return state.DoS(100, error("ConnectBlock(): too many sigops"),
REJECT_INVALID, "bad-blk-sigops");
nFees += view.GetValueIn(tx)-tx.GetValueOut();
nFees += view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime) - tx.GetValueOut();
sum += interest;
std::vector<CScriptCheck> vChecks;
if (!ContextualCheckInputs(tx, state, view, fScriptChecks, flags, false, chainparams.GetConsensus(), nScriptCheckThreads ? &vChecks : NULL))
return false;
control.Add(vChecks);
}
komodo_accrued_interest(pindex->nHeight,sum);
CTxUndo undoDummy;
if (i > 0) {
blockundo.vtxundo.push_back(CTxUndo());
@@ -3076,19 +3100,26 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta
return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d) vs %d", __func__, nHeight,pcheckpoint->nHeight));
else
{
int32_t notarized_height; uint256 notarized_hash,notarized_btctxid;
int32_t notarized_height; uint256 notarized_hash,notarized_btctxid; CBlockIndex *notary;
notarized_height = komodo_notarizeddata(chainActive.Tip()->nHeight,&notarized_hash,&notarized_btctxid);
//printf("nHeight.%d -> (%d %s)\n",chainActive.Tip()->nHeight,notarized_height,notarized_hash.ToString().c_str());
if ( nHeight < notarized_height )
if ( (notary= mapBlockIndex[notarized_hash]) != 0 )
{
fprintf(stderr,"nHeight.%d < NOTARIZED_HEIGHT.%d\n",nHeight,notarized_height);
return state.DoS(100, error("%s: forked chain older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height));
}
else if ( nHeight == notarized_height && memcmp(&hash,&notarized_hash,sizeof(hash)) != 0 )
{
fprintf(stderr,"nHeight.%d == NOTARIZED_HEIGHT.%d, diff hash\n",nHeight,notarized_height);
return state.DoS(100, error("%s: forked chain at notarized (height %d) with different hash", __func__, notarized_height));
}
//printf("nHeight.%d -> (%d %s)\n",chainActive.Tip()->nHeight,notarized_height,notarized_hash.ToString().c_str());
if ( notary->nHeight == notarized_height ) // if notarized_hash not in chain, reorg
{
if ( nHeight < notarized_height )
{
fprintf(stderr,"nHeight.%d < NOTARIZED_HEIGHT.%d\n",nHeight,notarized_height);
return state.DoS(100, error("%s: forked chain older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height));
}
else if ( nHeight == notarized_height && memcmp(&hash,&notarized_hash,sizeof(hash)) != 0 )
{
fprintf(stderr,"nHeight.%d == NOTARIZED_HEIGHT.%d, diff hash\n",nHeight,notarized_height);
return state.DoS(100, error("%s: forked chain at notarized (height %d) with different hash", __func__, notarized_height));
}
} else fprintf(stderr,"notary_hash %s ht.%d at ht.%d\n",notarized_hash.ToString().c_str(),notarized_height,notary->nHeight);
} else if ( notarized_height > 0 )
fprintf(stderr,"couldnt find notary_hash %s ht.%d\n",notarized_hash.ToString().c_str(),notarized_height);
}
}

View File

@@ -96,6 +96,8 @@ void UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams,
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);
}
int32_t komodo_opreturn(uint8_t *opret,int32_t maxsize);
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
{
const CChainParams& chainparams = Params();
@@ -228,6 +230,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
// Collect transactions into block
uint64_t nBlockSize = 1000;
uint64_t nBlockTx = 0;
int64_t interest;
int nBlockSigOps = 100;
bool fSortedByFee = (nBlockPrioritySize <= 0);
@@ -275,7 +278,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
if (!view.HaveInputs(tx))
continue;
CAmount nTxFees = view.GetValueIn(tx)-tx.GetValueOut();
CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut();
nTxSigOps += GetP2SHSigOpCount(tx, view);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
@@ -329,13 +332,25 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
// Create coinbase tx
CMutableTransaction txNew;
//txNew.nLockTime = (uint32_t)time(NULL) - 60;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
int32_t i,opretlen; uint8_t opret[8192],*ptr;
if ( (opretlen= komodo_opreturn(opret,sizeof(opret))) > 0 )
{
txNew.vout.resize(2);
txNew.vout[1].scriptPubKey.resize(opretlen);
ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data();
for (i=0; i<opretlen; i++)
ptr[i] = opret[i];
txNew.vout[1].nValue = 0;
//fprintf(stderr,"opretlen.%d\n",opretlen);
} else txNew.vout.resize(1);
txNew.vout[0].scriptPubKey = scriptPubKeyIn;
txNew.vout[0].nValue = GetBlockSubsidy(nHeight, chainparams.GetConsensus());
// Add fees
txNew.vout[0].nValue += nFees;
txNew.vin[0].scriptSig = CScript() << nHeight << OP_0;
pblock->vtx[0] = txNew;
@@ -488,6 +503,7 @@ void static BitcoinMiner(CWallet *pwallet)
//
// Create new block
//
uint32_t starttime = (uint32_t)time(NULL);
unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrev = chainActive.Tip();
@@ -499,17 +515,17 @@ void static BitcoinMiner(CWallet *pwallet)
}
CBlock *pblock = &pblocktemplate->block;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
LogPrintf("Running ZcashMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(),
::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
//
// Search
//
int32_t notaryid;
int64_t nStart = GetTime();
int32_t notaryid; uint32_t savebits; int64_t nStart = GetTime();
savebits = pblock->nBits;
if ( komodo_chosennotary(&notaryid,pindexPrev->nHeight+1,NOTARY_PUBKEY33) > 0 )
{
pblock->nBits = KOMODO_MINDIFF_NBITS;
//fprintf(stderr,"I am the chosen one for ht.%d\n",pindexPrev->nHeight+1);
}
arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
@@ -549,11 +565,14 @@ void static BitcoinMiner(CWallet *pwallet)
if (UintToArith256(pblock->GetHash()) > hashTarget) {
return false;
}
/* if ( pblock->nBits == KOMODO_MINDIFF_NBITS && time(NULL) < starttime+50 )
sleep(starttime+50-time(NULL));*/
// Found a solution
SetThreadPriority(THREAD_PRIORITY_NORMAL);
LogPrintf("ZcashMiner:\n");
LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), hashTarget.GetHex());
if (ProcessBlockFound(pblock, *pwallet, reservekey)) {
// Ignore chain updates caused by us
std::lock_guard<std::mutex> lock{m_cs};
@@ -595,6 +614,7 @@ void static BitcoinMiner(CWallet *pwallet)
// Update nNonce and nTime
pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1);
pblock->nBits = savebits;
UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);
if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks)
{

View File

@@ -267,8 +267,7 @@ public:
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
return (a.nValue == b.nValue && a.scriptPubKey == b.scriptPubKey);
}
friend bool operator!=(const CTxOut& a, const CTxOut& b)

View File

@@ -506,6 +506,7 @@ static bool rest_getutxos(AcceptedConnection* conn,
utxo.push_back(Pair("txvers", (int32_t)coin.nTxVer));
utxo.push_back(Pair("height", (int32_t)coin.nHeight));
utxo.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
//utxo.push_back(Pair("interest", ValueFromAmount(komodo_interest(coin.out.nValue,coin.nLockTime,chainActive.Tip()->nTime))));
// include the script in a json output
Object o;

View File

@@ -380,6 +380,35 @@ Value gettxoutsetinfo(const Array& params, bool fHelp)
return ret;
}
uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime);
uint32_t komodo_txtime(uint256 hash);
uint64_t komodo_paxprice(int32_t height,char *base,char *rel,uint64_t basevolume);
Value paxprice(const Array& params, bool fHelp)
{
if ( fHelp || params.size() < 3 || params.size() > 4 )
throw runtime_error("paxprice \"base\" \"rel\" height\n");
LOCK(cs_main);
Object ret; uint64_t pricetoshis,basevolume=0,relvolume;
std::string base = params[0].get_str();
std::string rel = params[1].get_str();
int32_t height = atoi(params[2].get_str().c_str());
if ( params.size() == 4 )
basevolume = AmountFromValue(params[3]);
if ( basevolume == 0 )
basevolume = COIN;
relvolume = komodo_paxprice(height,(char *)base.c_str(),(char *)rel.c_str(),basevolume);
ret.push_back(Pair("base", base));
ret.push_back(Pair("rel", rel));
ret.push_back(Pair("height", height));
if ( basevolume != 0 )
{
ret.push_back(Pair("price",((double)relvolume / (double)basevolume)));
ret.push_back(Pair("relvolume", ValueFromAmount(relvolume)));
}
return ret;
}
Value gettxout(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
@@ -448,9 +477,17 @@ Value gettxout(const Array& params, bool fHelp)
ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT)
ret.push_back(Pair("confirmations", 0));
else
ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1));
else ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1));
ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue)));
CBlockIndex *pblockindex = chainActive[coins.nHeight];
uint64_t interest; uint32_t timestamp=0;
if ( pblockindex != 0 )
timestamp = pblockindex->nTime; // this is approx, but cant figure out how to get tx here
interest = komodo_interest(coins.nHeight,coins.vout[n].nValue,timestamp,pindex->nTime);
//fprintf(stderr,"nValue %llu lock.%u:%u nTime.%u -> %llu\n",(long long)coins.vout[n].nValue,coins.nLockTime,timestamp,pindex->nTime,(long long)interest);
ret.push_back(Pair("interest", ValueFromAmount(interest)));
Object o;
ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true);
ret.push_back(Pair("scriptPubKey", o));

View File

@@ -105,7 +105,8 @@ static const CRPCConvertParam vRPCConvertParams[] =
{ "z_sendmany", 2},
{ "z_getoperationstatus", 0},
{ "z_getoperationresult", 0},
{ "z_importkey", 1 }
{ "z_importkey", 1 },
{ "paxprice", 3 },
};
class CRPCConvertTable

View File

@@ -96,6 +96,8 @@ Array TxJoinSplitToJSON(const CTransaction& tx) {
return vjoinsplit;
}
uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime);
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
@@ -119,10 +121,19 @@ void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
}
entry.push_back(Pair("vin", vin));
Array vout;
BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
CBlockIndex *pindex = it->second;
uint64_t interest;
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
if ( pindex != 0 && tx.nLockTime != 0 )
{
interest = komodo_interest(pindex->nHeight,txout.nValue,tx.nLockTime,pindex->nTime);
fprintf(stderr,"TxtoJSON interest %llu %.8f\n",(long long)interest,(double)interest/COIN);
out.push_back(Pair("interest", ValueFromAmount(interest)));
}
out.push_back(Pair("n", (int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);

View File

@@ -300,6 +300,7 @@ static const CRPCCommand vRPCCommands[] =
{ "blockchain", "verifytxoutproof", &verifytxoutproof, true },
{ "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true },
{ "blockchain", "verifychain", &verifychain, true },
{ "blockchain", "paxprice", &paxprice, true },
/* Mining */
{ "mining", "getblocktemplate", &getblocktemplate, true },

View File

@@ -243,6 +243,7 @@ extern json_spirit::Value getblockhash(const json_spirit::Array& params, bool fH
extern json_spirit::Value getblock(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value gettxoutsetinfo(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value gettxout(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value paxprice(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value verifychain(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getchaintips(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value invalidateblock(const json_spirit::Array& params, bool fHelp);

View File

@@ -520,9 +520,9 @@ BOOST_AUTO_TEST_CASE(test_Get)
t1.vout.resize(2);
t1.vout[0].nValue = 90*CENT;
t1.vout[0].scriptPubKey << OP_1;
int64_t interest;
BOOST_CHECK(AreInputsStandard(t1, coins));
BOOST_CHECK_EQUAL(coins.GetValueIn(t1), (50+21+22)*CENT);
BOOST_CHECK_EQUAL(coins.GetValueIn(0,&interest,t1,0), (50+21+22)*CENT);
// Adding extra junk to the scriptSig should make it non-standard:
t1.vin[0].scriptSig << OP_11;

View File

@@ -610,7 +610,7 @@ Value getreceivedbyaddress(const Array& params, bool fHelp)
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
nAmount += txout.nValue; // komodo_interest?
}
return ValueFromAmount(nAmount);
@@ -666,7 +666,7 @@ Value getreceivedbyaccount(const Array& params, bool fHelp)
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
nAmount += txout.nValue; // komodo_interest?
}
}
@@ -1140,7 +1140,7 @@ Value ListReceived(const Array& params, bool fByAccounts)
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nAmount += txout.nValue; // komodo_interest?
item.nConf = min(item.nConf, nDepth);
item.txids.push_back(wtx.GetHash());
if (mine & ISMINE_WATCH_ONLY)
@@ -2259,6 +2259,8 @@ Value resendwallettransactions(const Array& params, bool fHelp)
return result;
}
uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime);
Value listunspent(const Array& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
@@ -2363,6 +2365,17 @@ Value listunspent(const Array& params, bool fHelp)
}
}
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
if ( out.tx->nLockTime != 0 )
{
BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
CBlockIndex *pindex = it->second;
uint64_t interest;
if ( pindex != 0 )
{
interest = komodo_interest(pindex->nHeight,nValue,out.tx->nLockTime,pindex->nTime);
entry.push_back(Pair("interest",ValueFromAmount(interest)));
}
}
entry.push_back(Pair("confirmations",out.nDepth));
entry.push_back(Pair("spendable", out.fSpendable));
results.push_back(entry);
@@ -2880,7 +2893,7 @@ CAmount getBalanceTaddr(std::string transparentAddress, int minDepth=1) {
}
}
CAmount nValue = out.tx->vout[out.i].nValue;
CAmount nValue = out.tx->vout[out.i].nValue; // komodo_interest
balance += nValue;
}
return balance;

View File

@@ -1312,7 +1312,7 @@ CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
if (IsMine(prev.vout[txin.prevout.n]) & filter)
return prev.vout[txin.prevout.n].nValue;
return prev.vout[txin.prevout.n].nValue; // komodo_interest?
}
}
return 0;
@@ -2333,6 +2333,8 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int
return true;
}
uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime);
bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool& fOnlyCoinbaseCoinsRet, bool& fNeedCoinbaseCoinsRet, const CCoinControl* coinControl) const
{
// Output parameter fOnlyCoinbaseCoinsRet is set to true when the only available coins are coinbase utxos.
@@ -2369,11 +2371,17 @@ bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*
// coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
if (coinControl && coinControl->HasSelected())
{
uint64_t interest;
BOOST_FOREACH(const COutput& out, vCoins)
{
if(!out.fSpendable)
continue;
nValueRet += out.tx->vout[out.i].nValue;
interest = komodo_interest(chainActive.Tip()->nHeight,out.tx->vout[out.i].nValue,out.tx->nLockTime,chainActive.Tip()->nTime);
#ifdef KOMODO_ENABLE_INTEREST
nValueRet += interest;
#endif
fprintf(stderr,"interest %llu from %llu lock.%u tip.%u\n",(long long)interest,(long long)out.tx->vout[out.i].nValue,out.tx->nLockTime,chainActive.Tip()->nTime);
setCoinsRet.insert(make_pair(out.tx, out.i));
}
return (nValueRet >= nTargetValue);
@@ -2411,27 +2419,34 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend,
wtxNew.BindWallet(this);
CMutableTransaction txNew;
// Discourage fee sniping.
//
// However because of a off-by-one-error in previous versions we need to
// neuter it by setting nLockTime to at least one less than nBestHeight.
// Secondly currently propagation of transactions created for block heights
// corresponding to blocks that were just mined may be iffy - transactions
// aren't re-accepted into the mempool - we additionally neuter the code by
// going ten blocks back. Doesn't yet do anything for sniping, but does act
// to shake out wallet bugs like not showing nLockTime'd transactions at
// all.
txNew.nLockTime = std::max(0, chainActive.Height() - 10);
// Secondly occasionally randomly pick a nLockTime even further back, so
// that transactions that are delayed after signing for whatever reason,
// e.g. high-latency mix networks and some CoinJoin implementations, have
// better privacy.
if (GetRandInt(10) == 0)
txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
if ( 0 )
{
// Discourage fee sniping.
//
// However because of a off-by-one-error in previous versions we need to
// neuter it by setting nLockTime to at least one less than nBestHeight.
// Secondly currently propagation of transactions created for block heights
// corresponding to blocks that were just mined may be iffy - transactions
// aren't re-accepted into the mempool - we additionally neuter the code by
// going ten blocks back. Doesn't yet do anything for sniping, but does act
// to shake out wallet bugs like not showing nLockTime'd transactions at
// all.
txNew.nLockTime = std::max(0, chainActive.Height() - 10);
// Secondly occasionally randomly pick a nLockTime even further back, so
// that transactions that are delayed after signing for whatever reason,
// e.g. high-latency mix networks and some CoinJoin implementations, have
// better privacy.
if (GetRandInt(10) == 0)
txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
}
else
{
txNew.nLockTime = (uint32_t)chainActive.Tip()->nTime + 1; // set to a time close to now
}
{
LOCK2(cs_main, cs_wallet);