From 713c2a947a5726d25aa860b9a82af547567256ae Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 18:31:50 +0300 Subject: [PATCH 001/507] Initial ccdata for notarization --- src/komodo.h | 47 ++++++++++++++++++++++++++++++++++++----- src/komodo_bitcoind.h | 2 +- src/komodo_cJSON.c | 2 +- src/komodo_ccdata.h | 46 ++++++++++++++++++++++++++++++++++++++++ src/komodo_curve25519.h | 2 +- src/komodo_events.h | 2 +- src/komodo_gateway.h | 2 +- src/komodo_globals.h | 5 +++-- src/komodo_interest.h | 2 +- src/komodo_jumblr.h | 2 +- src/komodo_kv.h | 2 +- src/komodo_notary.h | 2 +- src/komodo_pax.h | 2 +- src/komodo_structs.h | 12 ++++++++++- src/komodo_utils.h | 6 +++--- src/script/cc.h | 2 +- 16 files changed, 116 insertions(+), 22 deletions(-) create mode 100644 src/komodo_ccdata.h diff --git a/src/komodo.h b/src/komodo.h index 32fcce047..6f366a39a 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * @@ -54,6 +54,7 @@ int32_t komodo_parsestatefile(struct komodo_state *sp,FILE *fp,char *symbol,char #include "komodo_jumblr.h" #include "komodo_gateway.h" #include "komodo_events.h" +#include "komodo_ccdata.h" void komodo_currentheight_set(int32_t height) { @@ -595,16 +596,49 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } else validated = 1; if ( notarized != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height && validated != 0 ) { - int32_t nameoffset = (int32_t)strlen(ASSETCHAINS_SYMBOL) + 1; + struct komodo_ccdata ccdata; int32_t nameoffset = (int32_t)strlen(ASSETCHAINS_SYMBOL) + 1; + memset(&ccdata,0,sizeof(ccdata)); sp->NOTARIZED_HEIGHT = *notarizedheightp; sp->NOTARIZED_HASH = srchash; sp->NOTARIZED_DESTTXID = desttxid; memset(&sp->MoM,0,sizeof(sp->MoM)); sp->MoMdepth = 0; + len += nameoffset; + strncpy(ccdata.symbol,(char *)&scriptbuf[len+32*2+4],sizeof(ccdata.symbol)); + ccdata.notarized_height = *notarizedheightp; + ccdata.MoM = sp->MoM; + ccdata.height = height; + ccdata.txi = txi; if ( len+36 <= opretlen ) { - len += iguana_rwbignum(0,&scriptbuf[len+nameoffset],32,(uint8_t *)&sp->MoM); - len += iguana_rwnum(0,&scriptbuf[len+nameoffset],sizeof(sp->MoMdepth),(uint8_t *)&sp->MoMdepth); + len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&sp->MoM); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(sp->MoMdepth),(uint8_t *)&sp->MoMdepth); + if ( len+sizeof(ccdata.CCid) <= opretlen ) + { + len += iguana_rwnum(0,&scriptbuf[len],sizeof(ccdata.CCid),(uint8_t *)&ccdata.CCid); + ccdata.len = sizeof(ccdata.CCid); + if ( ASSETCHAINS_SYMBOL[0] != 0 ) + { + // MoMoM, depth, numpairs, (notarization ht, MoMoM offset) + if ( len+40 <= opretlen && strcmp(ccdata.symbol,ASSETCHAINS_SYMBOL) == 0 ) + { + len += iguana_rwbignum(0,&scriptbuf[len],sizeof(ccdata.MoMoM),(uint8_t *)&ccdata.MoMoM); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(ccdata.MoMoMdepth),(uint8_t *)&ccdata.MoMoMdepth); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(ccdata.numpairs),(uint8_t *)&ccdata.numpairs); + ccdata.len += sizeof(ccdata.MoMoM) + sizeof(ccdata.MoMoMdepth) + sizeof(ccdata.numpairs); + if ( len+ccdata.numpairs*8 == opretlen ) + { + ccdata.pairs = calloc(ccdata.numpairs,sizeof(*cc.pairs)); + for (k=0; kMoM == zero || sp->MoMdepth > 1440 || sp->MoMdepth < 0 ) { memset(&sp->MoM,0,sizeof(sp->MoM)); @@ -612,11 +646,14 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } else { + komodo_rwccdata(1,&ccdata); //printf("VALID %s MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,sp->MoM.ToString().c_str(),sp->MoMdepth); } + if ( ccdata.pairs != 0 ) + free(ccdata.pairs); + memset(&ccdata,0,sizeof(ccdata)); } komodo_stateupdate(height,0,0,0,zero,0,0,0,0,0,0,0,0,0,0,sp->MoM,sp->MoMdepth); - len += nameoffset; if ( ASSETCHAINS_SYMBOL[0] != 0 ) printf("[%s] ht.%d NOTARIZED.%d %s.%s %sTXID.%s lens.(%d %d) MoM.%s %d\n",ASSETCHAINS_SYMBOL,height,*notarizedheightp,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),ASSETCHAINS_SYMBOL[0]==0?"BTC":"KMD",desttxid.ToString().c_str(),opretlen,len,sp->MoM.ToString().c_str(),sp->MoMdepth); if ( ASSETCHAINS_SYMBOL[0] == 0 ) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 6ffa4022c..1b5e9ad64 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * diff --git a/src/komodo_cJSON.c b/src/komodo_cJSON.c index ca2c6517c..8569b7802 100755 --- a/src/komodo_cJSON.c +++ b/src/komodo_cJSON.c @@ -56,7 +56,7 @@ static int32_t cJSON_strcasecmp(const char *s1,const char *s2) // the following written by jl777 /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h new file mode 100644 index 000000000..b61e35658 --- /dev/null +++ b/src/komodo_ccdata.h @@ -0,0 +1,46 @@ +/****************************************************************************** + * Copyright © 2014-2018 The SuperNET Developers. * + * * + * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * + * the top-level directory of this distribution for the individual copyright * + * holder information and the developer policies on copyright and licensing. * + * * + * Unless otherwise agreed in a custom licensing agreement, no part of the * + * SuperNET software, including this file may be copied, modified, propagated * + * or distributed except according to the terms contained in the LICENSE file * + * * + * Removal or modification of this copyright notice is prohibited. * + * * + ******************************************************************************/ + +#ifndef H_KOMODOCCDATA_H +#define H_KOMODOCCDATA_H + + +/*struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; +struct komodo_ccdata +{ + uint32_t CCid; + bits256 MoMoM,MoM; + int32_t MoMoMdepth,numpairs,notarized_height,height,txi; + struct ccdatapair *pairs; + char symbol[65]; +}; +*/ + +int32_t komodo_rwccdata(int32_t rwflag,struct komodo_ccdata *ccdata) +{ + if ( rwflag == 0 ) + { + + } + fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d numpairs.%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->notarized_height,bits256_str(str,ccdata->MoM),cddata->height,ccdata->txi,ccdata->numpairs); + if ( ASSETCHAINS_SYMBOL[0] == 0 ) + { + } + else + { + } +} + +#endif diff --git a/src/komodo_curve25519.h b/src/komodo_curve25519.h index a7283e265..90d9a7e00 100644 --- a/src/komodo_curve25519.h +++ b/src/komodo_curve25519.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * diff --git a/src/komodo_events.h b/src/komodo_events.h index 4d9ff87dc..ef09c4bbf 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 72f36a21c..8a3477b92 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * diff --git a/src/komodo_globals.h b/src/komodo_globals.h index cb8f61988..1f4872d51 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * @@ -46,7 +46,8 @@ struct komodo_state KOMODO_STATES[34]; int COINBASE_MATURITY = _COINBASE_MATURITY;//100; int32_t IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAINS_SEED,KOMODO_ON_DEMAND,KOMODO_EXTERNAL_NOTARIES,KOMODO_PASSPORT_INITDONE,KOMODO_PAX,KOMODO_EXCHANGEWALLET,KOMODO_REWIND; -int32_t KOMODO_LASTMINED,prevKOMODO_LASTMINED,JUMBLR_PAUSE,ASSETCHAINS_CC; +int32_t KOMODO_LASTMINED,prevKOMODO_LASTMINED,JUMBLR_PAUSE; +uint32_t ASSETCHAINS_CC; std::string NOTARY_PUBKEY,ASSETCHAINS_NOTARIES,ASSETCHAINS_OVERRIDE_PUBKEY; uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33]; diff --git a/src/komodo_interest.h b/src/komodo_interest.h index 07b12cfe1..23ed985ca 100644 --- a/src/komodo_interest.h +++ b/src/komodo_interest.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * diff --git a/src/komodo_jumblr.h b/src/komodo_jumblr.h index 951ed9de0..e033306b4 100755 --- a/src/komodo_jumblr.h +++ b/src/komodo_jumblr.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * diff --git a/src/komodo_kv.h b/src/komodo_kv.h index 7c20becb1..58d550414 100644 --- a/src/komodo_kv.h +++ b/src/komodo_kv.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * diff --git a/src/komodo_notary.h b/src/komodo_notary.h index f46681718..59c53ecf6 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * diff --git a/src/komodo_pax.h b/src/komodo_pax.h index 2c048bac9..d0bad0e14 100644 --- a/src/komodo_pax.h +++ b/src/komodo_pax.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * diff --git a/src/komodo_structs.h b/src/komodo_structs.h index 38a2b3138..984138cc2 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * @@ -89,6 +89,16 @@ struct notarized_checkpoint int32_t nHeight,notarized_height,MoMdepth; }; +struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; +struct komodo_ccdata +{ + uint32_t CCid; + bits256 MoMoM,MoM; + int32_t MoMoMdepth,numpairs,notarized_height,height,txi; + struct ccdatapair *pairs; + char symbol[65]; +}; + struct komodo_state { uint256 NOTARIZED_HASH,NOTARIZED_DESTTXID,MoM; diff --git a/src/komodo_utils.h b/src/komodo_utils.h index 3059ebf64..6fb4eb596 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * @@ -1528,7 +1528,7 @@ void komodo_args(char *argv0) } } } - ASSETCHAINS_CC = GetArg("-ac_cc",0); // keep it outside the assetchains hashing so KMD can do it and we dont have two identical chains other than -ac_cc + ASSETCHAINS_CC = GetArg("-ac_cc",0); if ( (KOMODO_REWIND= GetArg("-rewind",0)) != 0 ) { printf("KOMODO_REWIND %d\n",KOMODO_REWIND); @@ -1575,7 +1575,7 @@ void komodo_args(char *argv0) extralen += iguana_rwnum(1,&extraptr[extralen],sizeof(ASSETCHAINS_REWARD),(void *)&ASSETCHAINS_REWARD); extralen += iguana_rwnum(1,&extraptr[extralen],sizeof(ASSETCHAINS_HALVING),(void *)&ASSETCHAINS_HALVING); extralen += iguana_rwnum(1,&extraptr[extralen],sizeof(ASSETCHAINS_DECAY),(void *)&ASSETCHAINS_DECAY); - val = ASSETCHAINS_COMMISSION | ((ASSETCHAINS_STAKED & 0xff) << 32); + val = ASSETCHAINS_COMMISSION | (((uint64_t)ASSETCHAINS_STAKED & 0xff) << 32) | (((uint64_t)ASSETCHAINS_CC & 0xffffff) << 40); extralen += iguana_rwnum(1,&extraptr[extralen],sizeof(val),(void *)&val); } addn = GetArg("-seednode",""); diff --git a/src/script/cc.h b/src/script/cc.h index ad1666b86..dc019beba 100644 --- a/src/script/cc.h +++ b/src/script/cc.h @@ -6,7 +6,7 @@ #include "cryptoconditions/include/cryptoconditions.h" -extern int32_t ASSETCHAINS_CC; +extern uint32_t ASSETCHAINS_CC; bool IsCryptoConditionsEnabled(); // Limit acceptable condition types From 2fb22ef82d2185dbf9dc1a1c3d07e7e557c0f679 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 18:37:04 +0300 Subject: [PATCH 002/507] Test --- src/miner.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index f95933117..e59d6502e 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -401,16 +401,16 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked)); nFees += txfees; pblock->nTime = blocktime; - if ( GetAdjustedTime()+30 < pblock->nTime ) + if ( GetAdjustedTime() < pblock->nTime ) { - //printf("need to wait %d seconds to submit: ",(int32_t)(pblock->nTime - GetAdjustedTime())); - /*while ( GetAdjustedTime()+30 < pblock->nTime ) + printf("need to wait %d seconds to submit: ",(int32_t)(pblock->nTime - GetAdjustedTime())); + while ( GetAdjustedTime() < pblock->nTime ) { sleep(30); fprintf(stderr,"%d ",(int32_t)(pblock->nTime - GetAdjustedTime())); - }*/ - //fprintf(stderr,"finished waiting\n"); - sleep(30); + } + fprintf(stderr,"finished waiting\n"); + //sleep(pblock->nTime - GetAdjustedTime()); } } else fprintf(stderr,"no utxos eligible for staking\n"); From 5c739676bf774eab74a419009c8e4e4d97cf122b Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 18:40:48 +0300 Subject: [PATCH 003/507] Test --- src/komodo_structs.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_structs.h b/src/komodo_structs.h index 984138cc2..d266d0d15 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -94,8 +94,8 @@ struct komodo_ccdata { uint32_t CCid; bits256 MoMoM,MoM; - int32_t MoMoMdepth,numpairs,notarized_height,height,txi; - struct ccdatapair *pairs; + int32_t MoMoMdepth,numpairs,notarized_height,height,txi,len; + struct komodo_ccdatapair *pairs; char symbol[65]; }; From 26c0ce948baae94bde7c5b1f30e6bfe743c699e8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 18:42:04 +0300 Subject: [PATCH 004/507] Test --- src/komodo.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 6f366a39a..363f9106a 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -608,7 +608,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr ccdata.notarized_height = *notarizedheightp; ccdata.MoM = sp->MoM; ccdata.height = height; - ccdata.txi = txi; + ccdata.txi = i; if ( len+36 <= opretlen ) { len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&sp->MoM); @@ -628,7 +628,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr ccdata.len += sizeof(ccdata.MoMoM) + sizeof(ccdata.MoMoMdepth) + sizeof(ccdata.numpairs); if ( len+ccdata.numpairs*8 == opretlen ) { - ccdata.pairs = calloc(ccdata.numpairs,sizeof(*cc.pairs)); + ccdata.pairs = calloc(ccdata.numpairs,sizeof(*ccdata.pairs)); for (k=0; k Date: Wed, 11 Apr 2018 18:43:34 +0300 Subject: [PATCH 005/507] Test --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 363f9106a..9c0b64d45 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -628,7 +628,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr ccdata.len += sizeof(ccdata.MoMoM) + sizeof(ccdata.MoMoMdepth) + sizeof(ccdata.numpairs); if ( len+ccdata.numpairs*8 == opretlen ) { - ccdata.pairs = calloc(ccdata.numpairs,sizeof(*ccdata.pairs)); + ccdata.pairs = (struct komodo_ccdatapair *)calloc(ccdata.numpairs,sizeof(*ccdata.pairs)); for (k=0; k Date: Wed, 11 Apr 2018 18:44:51 +0300 Subject: [PATCH 006/507] Test --- src/komodo_structs.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_structs.h b/src/komodo_structs.h index d266d0d15..ff7b7c27a 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -93,7 +93,7 @@ struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; struct komodo_ccdata { uint32_t CCid; - bits256 MoMoM,MoM; + uint256 MoMoM,MoM; int32_t MoMoMdepth,numpairs,notarized_height,height,txi,len; struct komodo_ccdatapair *pairs; char symbol[65]; From 013622e89b98c9052888c2bd0365ed27be42df5c Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 18:46:15 +0300 Subject: [PATCH 007/507] Test --- src/komodo_ccdata.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index b61e35658..805f18e14 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -34,7 +34,7 @@ int32_t komodo_rwccdata(int32_t rwflag,struct komodo_ccdata *ccdata) { } - fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d numpairs.%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->notarized_height,bits256_str(str,ccdata->MoM),cddata->height,ccdata->txi,ccdata->numpairs); + char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d numpairs.%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->notarized_height,bits256_str(str,(bits256)ccdata->MoM),ccdata->height,ccdata->txi,ccdata->numpairs); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { } From 9c525cd4358899533b5eeab3ef50c3462fba1035 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 18:47:12 +0300 Subject: [PATCH 008/507] Test --- src/komodo_ccdata.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 805f18e14..e5ba9d107 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -34,7 +34,7 @@ int32_t komodo_rwccdata(int32_t rwflag,struct komodo_ccdata *ccdata) { } - char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d numpairs.%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->notarized_height,bits256_str(str,(bits256)ccdata->MoM),ccdata->height,ccdata->txi,ccdata->numpairs); + char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d numpairs.%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->notarized_height,bits256_str(str,(bits256 *)&ccdata->MoM),ccdata->height,ccdata->txi,ccdata->numpairs); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { } From fff8f48a35f110c78ba77450f2f8f7bff4ee34be Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 18:48:12 +0300 Subject: [PATCH 009/507] Test --- src/komodo_ccdata.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index e5ba9d107..d56c09e81 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -34,7 +34,7 @@ int32_t komodo_rwccdata(int32_t rwflag,struct komodo_ccdata *ccdata) { } - char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d numpairs.%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->notarized_height,bits256_str(str,(bits256 *)&ccdata->MoM),ccdata->height,ccdata->txi,ccdata->numpairs); + char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d numpairs.%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->notarized_height,bits256_str(str,*(bits256 *)&ccdata->MoM),ccdata->height,ccdata->txi,ccdata->numpairs); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { } From da6e99a0cb48d933e9304e873a42910e6949612f Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 19:08:06 +0300 Subject: [PATCH 010/507] Test --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index e59d6502e..c13d5030c 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -404,7 +404,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) if ( GetAdjustedTime() < pblock->nTime ) { printf("need to wait %d seconds to submit: ",(int32_t)(pblock->nTime - GetAdjustedTime())); - while ( GetAdjustedTime() < pblock->nTime ) + while ( GetAdjustedTime()+30 < pblock->nTime ) { sleep(30); fprintf(stderr,"%d ",(int32_t)(pblock->nTime - GetAdjustedTime())); From 22d20d89137dccad7bbc40b97185c9304ea3fbd8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 19:38:36 +0300 Subject: [PATCH 011/507] Test --- src/komodo.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 9c0b64d45..e78463643 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -647,14 +647,14 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr else { komodo_rwccdata(1,&ccdata); - //printf("VALID %s MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,sp->MoM.ToString().c_str(),sp->MoMdepth); + printf("VALID %s MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,sp->MoM.ToString().c_str(),sp->MoMdepth); } if ( ccdata.pairs != 0 ) free(ccdata.pairs); memset(&ccdata,0,sizeof(ccdata)); } komodo_stateupdate(height,0,0,0,zero,0,0,0,0,0,0,0,0,0,0,sp->MoM,sp->MoMdepth); - if ( ASSETCHAINS_SYMBOL[0] != 0 ) + //if ( ASSETCHAINS_SYMBOL[0] != 0 ) printf("[%s] ht.%d NOTARIZED.%d %s.%s %sTXID.%s lens.(%d %d) MoM.%s %d\n",ASSETCHAINS_SYMBOL,height,*notarizedheightp,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),ASSETCHAINS_SYMBOL[0]==0?"BTC":"KMD",desttxid.ToString().c_str(),opretlen,len,sp->MoM.ToString().c_str(),sp->MoMdepth); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { From 195c2e167eb7e3648ba502037b8061d7d5dba56a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 20:07:37 +0300 Subject: [PATCH 012/507] Test --- src/komodo.h | 88 +++++++++++++++++++++++++++++----------------------- 1 file changed, 49 insertions(+), 39 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index e78463643..8794e8758 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -509,7 +509,7 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar int32_t komodo_voutupdate(int32_t *isratificationp,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,uint64_t value,int32_t notarized,uint64_t signedmask,uint32_t timestamp) { static uint256 zero; static FILE *signedfp; - int32_t opretlen,nid,k,len = 0; uint256 srchash,desttxid; uint8_t crypto777[33]; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; + int32_t opretlen,nid,k,MoMdepth,matched,len = 0; uint256 MoM,srchash,desttxid; uint8_t crypto777[33]; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; if ( (sp= komodo_stateptr(symbol,dest)) == 0 ) return(-1); if ( scriptlen == 35 && scriptbuf[0] == 33 && scriptbuf[34] == 0xac ) @@ -565,19 +565,20 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) printf("[%s] notarized.%d notarizedht.%d sp.Nht %d sp.ht %d opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,notarized,*notarizedheightp,sp->NOTARIZED_HEIGHT,sp->CURRENT_HEIGHT,opretlen,scriptbuf[len+32*2+4],scriptbuf[len+32*2+4+1],scriptbuf[len+32*2+4+2]); - if ( j == 1 && opretlen >= 32*2+4 && strcmp(ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,(char *)&scriptbuf[len+32*2+4]) == 0 ) + matched = (strcmp(ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,(char *)&scriptbuf[len+32*2+4]) == 0); + if ( j == 1 && opretlen >= 32*2+4 ) { len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&srchash); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); - if ( strcmp("PIZZA",ASSETCHAINS_SYMBOL) == 0 && opretlen == 110 ) + if ( strcmp("PIZZA",ASSETCHAINS_SYMBOL) == 0 && opretlen >= 110 ) { notarized = 1; } static int32_t last_rewind; int32_t rewindtarget,validated = 0; CBlockIndex *pindex;// - if ( IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != *notarizedheightp) ) + if ( matched != 0 && IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != *notarizedheightp) ) { if ( sp->NOTARIZED_HEIGHT > 0 && sp->NOTARIZED_HEIGHT < *notarizedheightp ) rewindtarget = sp->NOTARIZED_HEIGHT - 1; @@ -598,21 +599,22 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr { struct komodo_ccdata ccdata; int32_t nameoffset = (int32_t)strlen(ASSETCHAINS_SYMBOL) + 1; memset(&ccdata,0,sizeof(ccdata)); - sp->NOTARIZED_HEIGHT = *notarizedheightp; - sp->NOTARIZED_HASH = srchash; - sp->NOTARIZED_DESTTXID = desttxid; - memset(&sp->MoM,0,sizeof(sp->MoM)); - sp->MoMdepth = 0; + //sp->NOTARIZED_HEIGHT = *notarizedheightp; + //sp->NOTARIZED_HASH = srchash; + //sp->NOTARIZED_DESTTXID = desttxid; + memset(&MoM,0,sizeof(MoM)); + MoMdepth = 0; len += nameoffset; strncpy(ccdata.symbol,(char *)&scriptbuf[len+32*2+4],sizeof(ccdata.symbol)); ccdata.notarized_height = *notarizedheightp; - ccdata.MoM = sp->MoM; ccdata.height = height; ccdata.txi = i; if ( len+36 <= opretlen ) { - len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&sp->MoM); - len += iguana_rwnum(0,&scriptbuf[len],sizeof(sp->MoMdepth),(uint8_t *)&sp->MoMdepth); + len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&MoM); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(MoMdepth),(uint8_t *)&MoMdepth); + ccdata.MoM = MoM; + ccdata.MoMdepth = MoMdepth; if ( len+sizeof(ccdata.CCid) <= opretlen ) { len += iguana_rwnum(0,&scriptbuf[len],sizeof(ccdata.CCid),(uint8_t *)&ccdata.CCid); @@ -639,45 +641,53 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } else ccdata.len = 0; } } - if ( sp->MoM == zero || sp->MoMdepth > 1440 || sp->MoMdepth < 0 ) + if ( MoM == zero || MoMdepth > 1440 || MoMdepth < 0 ) { - memset(&sp->MoM,0,sizeof(sp->MoM)); - sp->MoMdepth = 0; + memset(&MoM,0,sizeof(MoM)); + MoMdepth = 0; } else { komodo_rwccdata(1,&ccdata); - printf("VALID %s MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,sp->MoM.ToString().c_str(),sp->MoMdepth); + printf("VALID %s MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,MoM.ToString().c_str(),MoMdepth); } if ( ccdata.pairs != 0 ) free(ccdata.pairs); memset(&ccdata,0,sizeof(ccdata)); } - komodo_stateupdate(height,0,0,0,zero,0,0,0,0,0,0,0,0,0,0,sp->MoM,sp->MoMdepth); - //if ( ASSETCHAINS_SYMBOL[0] != 0 ) - printf("[%s] ht.%d NOTARIZED.%d %s.%s %sTXID.%s lens.(%d %d) MoM.%s %d\n",ASSETCHAINS_SYMBOL,height,*notarizedheightp,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),ASSETCHAINS_SYMBOL[0]==0?"BTC":"KMD",desttxid.ToString().c_str(),opretlen,len,sp->MoM.ToString().c_str(),sp->MoMdepth); - if ( ASSETCHAINS_SYMBOL[0] == 0 ) + if ( matched != 0 ) { - if ( signedfp == 0 ) + sp->NOTARIZED_HEIGHT = *notarizedheightp; + sp->NOTARIZED_HASH = srchash; + sp->NOTARIZED_DESTTXID = desttxid; + sp->MoM = MoM; + sp->MoMdepth = MoMdepth; + komodo_stateupdate(height,0,0,0,zero,0,0,0,0,0,0,0,0,0,0,sp->MoM,sp->MoMdepth); + if ( ASSETCHAINS_SYMBOL[0] != 0 ) + printf("[%s] ht.%d NOTARIZED.%d %s.%s %sTXID.%s lens.(%d %d) MoM.%s %d\n",ASSETCHAINS_SYMBOL,height,*notarizedheightp,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),ASSETCHAINS_SYMBOL[0]==0?"BTC":"KMD",desttxid.ToString().c_str(),opretlen,len,sp->MoM.ToString().c_str(),sp->MoMdepth); + if ( ASSETCHAINS_SYMBOL[0] == 0 ) { - char fname[512]; - komodo_statefname(fname,ASSETCHAINS_SYMBOL,(char *)"signedmasks"); - if ( (signedfp= fopen(fname,"rb+")) == 0 ) - signedfp = fopen(fname,"wb"); - else fseek(signedfp,0,SEEK_END); - } - if ( signedfp != 0 ) - { - fwrite(&height,1,sizeof(height),signedfp); - fwrite(&signedmask,1,sizeof(signedmask),signedfp); - fflush(signedfp); - } - if ( opretlen > len && scriptbuf[len] == 'A' ) - { - //for (i=0; i len && scriptbuf[len] == 'A' ) + { + //for (i=0; iNOTARIZED_HEIGHT ) From ee4d1d4cc043290287371a06a36b8cf503c77ede Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 20:15:09 +0300 Subject: [PATCH 013/507] Test --- src/komodo.h | 14 ++++++++------ src/komodo_structs.h | 2 +- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 8794e8758..95b643822 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -595,7 +595,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr last_rewind = rewindtarget; } } else validated = 1; - if ( notarized != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height && validated != 0 ) + if ( notarized != 0 && validated != 0 && (matched == 0 || (*notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height)) ) { struct komodo_ccdata ccdata; int32_t nameoffset = (int32_t)strlen(ASSETCHAINS_SYMBOL) + 1; memset(&ccdata,0,sizeof(ccdata)); @@ -622,12 +622,14 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr if ( ASSETCHAINS_SYMBOL[0] != 0 ) { // MoMoM, depth, numpairs, (notarization ht, MoMoM offset) - if ( len+40 <= opretlen && strcmp(ccdata.symbol,ASSETCHAINS_SYMBOL) == 0 ) + if ( len+48 <= opretlen && strcmp(ccdata.symbol,ASSETCHAINS_SYMBOL) == 0 ) { + len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&ccdata.MoMoMstart); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&ccdata.MoMoMend); len += iguana_rwbignum(0,&scriptbuf[len],sizeof(ccdata.MoMoM),(uint8_t *)&ccdata.MoMoM); - len += iguana_rwnum(0,&scriptbuf[len],sizeof(ccdata.MoMoMdepth),(uint8_t *)&ccdata.MoMoMdepth); - len += iguana_rwnum(0,&scriptbuf[len],sizeof(ccdata.numpairs),(uint8_t *)&ccdata.numpairs); - ccdata.len += sizeof(ccdata.MoMoM) + sizeof(ccdata.MoMoMdepth) + sizeof(ccdata.numpairs); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&ccdata.MoMoMdepth); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&ccdata.numpairs); + ccdata.len += sizeof(ccdata.MoMoM) + sizeof(uint32_t)*4; if ( len+ccdata.numpairs*8 == opretlen ) { ccdata.pairs = (struct komodo_ccdatapair *)calloc(ccdata.numpairs,sizeof(*ccdata.pairs)); @@ -649,7 +651,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr else { komodo_rwccdata(1,&ccdata); - printf("VALID %s MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,MoM.ToString().c_str(),MoMdepth); + printf("[%s] matched.%d VALID (%s) MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,matched,ccdata.symbol,MoM.ToString().c_str(),MoMdepth); } if ( ccdata.pairs != 0 ) free(ccdata.pairs); diff --git a/src/komodo_structs.h b/src/komodo_structs.h index ff7b7c27a..c620da392 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -94,7 +94,7 @@ struct komodo_ccdata { uint32_t CCid; uint256 MoMoM,MoM; - int32_t MoMoMdepth,numpairs,notarized_height,height,txi,len; + int32_t MoMoMstart,MoMoMend,MoMoMdepth,numpairs,notarized_height,height,txi,len,MoMdepth; struct komodo_ccdatapair *pairs; char symbol[65]; }; From 0d826729be8d3bfbbc08ca605349a6da93118e0c Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 20:39:24 +0300 Subject: [PATCH 014/507] Test --- src/komodo.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 95b643822..475fc4d2d 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -595,7 +595,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr last_rewind = rewindtarget; } } else validated = 1; - if ( notarized != 0 && validated != 0 && (matched == 0 || (*notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height)) ) + if ( notarized != 0 && (matched == 0 || (validated != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height)) ) { struct komodo_ccdata ccdata; int32_t nameoffset = (int32_t)strlen(ASSETCHAINS_SYMBOL) + 1; memset(&ccdata,0,sizeof(ccdata)); @@ -692,8 +692,8 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } } } - } else if ( *notarizedheightp != sp->NOTARIZED_HEIGHT ) - printf("validated.%d notarized.%d %llx reject ht.%d NOTARIZED.%d prev.%d %s.%s DESTTXID.%s (%s) len.%d opretlen.%d\n",validated,notarized,(long long)signedmask,height,*notarizedheightp,sp->NOTARIZED_HEIGHT,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),desttxid.ToString().c_str(),(char *)&scriptbuf[len],len,opretlen); + } else if ( matched != 0 && *notarizedheightp != sp->NOTARIZED_HEIGHT ) + printf("validated.%d notarized.%d %llx reject ht.%d NOTARIZED.%d prev.%d %s.%s DESTTXID.%s len.%d opretlen.%d\n",validated,notarized,(long long)signedmask,height,*notarizedheightp,sp->NOTARIZED_HEIGHT,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),desttxid.ToString().c_str(),len,opretlen); } else if ( i == 0 && j == 1 && opretlen == 149 ) { From 8e21f6b5cc38630dca0ccf6f79f82089798329d8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 20:49:53 +0300 Subject: [PATCH 015/507] Test --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 475fc4d2d..55628f7c5 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -563,7 +563,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr opretlen = scriptbuf[len++]; opretlen += (scriptbuf[len++] << 8); } - if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) + //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) printf("[%s] notarized.%d notarizedht.%d sp.Nht %d sp.ht %d opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,notarized,*notarizedheightp,sp->NOTARIZED_HEIGHT,sp->CURRENT_HEIGHT,opretlen,scriptbuf[len+32*2+4],scriptbuf[len+32*2+4+1],scriptbuf[len+32*2+4+2]); matched = (strcmp(ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,(char *)&scriptbuf[len+32*2+4]) == 0); if ( j == 1 && opretlen >= 32*2+4 ) From e6d3e5c89e2829ed594f908d0f3f365f51ba85cb Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 20:53:50 +0300 Subject: [PATCH 016/507] Test --- src/komodo.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 55628f7c5..1de71d47e 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -563,11 +563,10 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr opretlen = scriptbuf[len++]; opretlen += (scriptbuf[len++] << 8); } - //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) - printf("[%s] notarized.%d notarizedht.%d sp.Nht %d sp.ht %d opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,notarized,*notarizedheightp,sp->NOTARIZED_HEIGHT,sp->CURRENT_HEIGHT,opretlen,scriptbuf[len+32*2+4],scriptbuf[len+32*2+4+1],scriptbuf[len+32*2+4+2]); matched = (strcmp(ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,(char *)&scriptbuf[len+32*2+4]) == 0); if ( j == 1 && opretlen >= 32*2+4 ) { + printf("[%s] matched.%d i.%d j.%d notarized.%d notarizedht.%d sp.Nht %d sp.ht %d opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,matched,i,j,notarized,*notarizedheightp,sp->NOTARIZED_HEIGHT,sp->CURRENT_HEIGHT,opretlen,scriptbuf[len+32*2+4],scriptbuf[len+32*2+4+1],scriptbuf[len+32*2+4+2]); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&srchash); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); From 1bbbf487f86ef900033d339dc220895127fd197f Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 21:16:11 +0300 Subject: [PATCH 017/507] Test --- src/komodo.h | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 1de71d47e..c0c83477e 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -509,7 +509,7 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar int32_t komodo_voutupdate(int32_t *isratificationp,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,uint64_t value,int32_t notarized,uint64_t signedmask,uint32_t timestamp) { static uint256 zero; static FILE *signedfp; - int32_t opretlen,nid,k,MoMdepth,matched,len = 0; uint256 MoM,srchash,desttxid; uint8_t crypto777[33]; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; + int32_t opretlen,nid,offset,k,MoMdepth,matched,len = 0; uint256 MoM,srchash,desttxid; uint8_t crypto777[33]; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; if ( (sp= komodo_stateptr(symbol,dest)) == 0 ) return(-1); if ( scriptlen == 35 && scriptbuf[0] == 33 && scriptbuf[34] == 0xac ) @@ -564,12 +564,14 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr opretlen += (scriptbuf[len++] << 8); } matched = (strcmp(ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,(char *)&scriptbuf[len+32*2+4]) == 0); - if ( j == 1 && opretlen >= 32*2+4 ) + offset = 32 * (1 + matched) + 4; + if ( j == 1 && opretlen >= offset ) { - printf("[%s] matched.%d i.%d j.%d notarized.%d notarizedht.%d sp.Nht %d sp.ht %d opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,matched,i,j,notarized,*notarizedheightp,sp->NOTARIZED_HEIGHT,sp->CURRENT_HEIGHT,opretlen,scriptbuf[len+32*2+4],scriptbuf[len+32*2+4+1],scriptbuf[len+32*2+4+2]); + printf("[%s] matched.%d i.%d j.%d notarized.%d notarizedht.%d sp.Nht %d sp.ht %d opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,matched,i,j,notarized,*notarizedheightp,sp->NOTARIZED_HEIGHT,sp->CURRENT_HEIGHT,opretlen,scriptbuf[len+offset],scriptbuf[len+offset+1],scriptbuf[len+offset+2]); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&srchash); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); - len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); + if ( matched != 0 ) + len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); if ( strcmp("PIZZA",ASSETCHAINS_SYMBOL) == 0 && opretlen >= 110 ) { notarized = 1; @@ -604,7 +606,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr memset(&MoM,0,sizeof(MoM)); MoMdepth = 0; len += nameoffset; - strncpy(ccdata.symbol,(char *)&scriptbuf[len+32*2+4],sizeof(ccdata.symbol)); + strncpy(ccdata.symbol,(char *)&scriptbuf[len+offset],sizeof(ccdata.symbol)); ccdata.notarized_height = *notarizedheightp; ccdata.height = height; ccdata.txi = i; @@ -664,7 +666,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr sp->MoM = MoM; sp->MoMdepth = MoMdepth; komodo_stateupdate(height,0,0,0,zero,0,0,0,0,0,0,0,0,0,0,sp->MoM,sp->MoMdepth); - if ( ASSETCHAINS_SYMBOL[0] != 0 ) + //if ( ASSETCHAINS_SYMBOL[0] != 0 ) printf("[%s] ht.%d NOTARIZED.%d %s.%s %sTXID.%s lens.(%d %d) MoM.%s %d\n",ASSETCHAINS_SYMBOL,height,*notarizedheightp,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),ASSETCHAINS_SYMBOL[0]==0?"BTC":"KMD",desttxid.ToString().c_str(),opretlen,len,sp->MoM.ToString().c_str(),sp->MoMdepth); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { @@ -694,12 +696,12 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } else if ( matched != 0 && *notarizedheightp != sp->NOTARIZED_HEIGHT ) printf("validated.%d notarized.%d %llx reject ht.%d NOTARIZED.%d prev.%d %s.%s DESTTXID.%s len.%d opretlen.%d\n",validated,notarized,(long long)signedmask,height,*notarizedheightp,sp->NOTARIZED_HEIGHT,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),desttxid.ToString().c_str(),len,opretlen); } - else if ( i == 0 && j == 1 && opretlen == 149 ) + else if ( matched != 0 && i == 0 && j == 1 && opretlen == 149 ) { if ( notaryid >= 0 && notaryid < 64 ) komodo_paxpricefeed(height,&scriptbuf[len],opretlen); } - else + else if ( matched != 0 ) { //int32_t k; for (k=0; k Date: Wed, 11 Apr 2018 21:23:39 +0300 Subject: [PATCH 018/507] Test --- src/komodo.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index c0c83477e..c82e37d23 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -567,7 +567,10 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr offset = 32 * (1 + matched) + 4; if ( j == 1 && opretlen >= offset ) { - printf("[%s] matched.%d i.%d j.%d notarized.%d notarizedht.%d sp.Nht %d sp.ht %d opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,matched,i,j,notarized,*notarizedheightp,sp->NOTARIZED_HEIGHT,sp->CURRENT_HEIGHT,opretlen,scriptbuf[len+offset],scriptbuf[len+offset+1],scriptbuf[len+offset+2]); + if ( matched == 0 && bitweight(signedmask) >= KOMODO_MINRATIFY ) + notarized = 1; + if ( opretlen != 149 ) + printf("[%s] matched.%d i.%d j.%d notarized.%d %llx opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,matched,i,j,notarized,(long long)signedmask,opretlen,scriptbuf[len+offset],scriptbuf[len+offset+1],scriptbuf[len+offset+2]); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&srchash); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); if ( matched != 0 ) From a490f90524f248a0d63ba00fda2afd8a3a0a9c6f Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 21:43:11 +0300 Subject: [PATCH 019/507] Test --- src/komodo.h | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index c82e37d23..3bb633999 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -556,6 +556,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } if ( scriptbuf[len++] == 0x6a ) { + int32_t nameoffset; if ( (opretlen= scriptbuf[len++]) == 0x4c ) opretlen = scriptbuf[len++]; else if ( opretlen == 0x4d ) @@ -563,22 +564,35 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr opretlen = scriptbuf[len++]; opretlen += (scriptbuf[len++] << 8); } - matched = (strcmp(ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,(char *)&scriptbuf[len+32*2+4]) == 0); - offset = 32 * (1 + matched) + 4; - if ( j == 1 && opretlen >= offset ) + matched = 0; + if ( ASSETCHAINS_SYMBOL[0] == 0 ) { + nameoffset = (int32_t)strlen("KMD") + 1; + if ( strcmp("KMD",(char *)&scriptbuf[len+offset]) == 0 ) + matched = 1; + } + else + { + nameoffset = (int32_t)strlen(ASSETCHAINS_SYMBOL) + 1; + if ( strcmp(ASSETCHAINS_SYMBOL,(char *)&scriptbuf[len+offset]) == 0 ) + matched = 1; + } + offset = 32 * (1 + matched) + 4; + if ( j == 1 && opretlen >= len+offset ) + { + struct komodo_ccdata ccdata; + memset(&ccdata,0,sizeof(ccdata)); + strncpy(ccdata.symbol,(char *)&scriptbuf[len+offset],sizeof(ccdata.symbol)); if ( matched == 0 && bitweight(signedmask) >= KOMODO_MINRATIFY ) notarized = 1; + if ( strcmp("PIZZA",(char *)&scriptbuf[len+offset]) == 0 && opretlen >= 110 ) + notarized = 1; if ( opretlen != 149 ) - printf("[%s] matched.%d i.%d j.%d notarized.%d %llx opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,matched,i,j,notarized,(long long)signedmask,opretlen,scriptbuf[len+offset],scriptbuf[len+offset+1],scriptbuf[len+offset+2]); + printf("[%s] (%s) matched.%d i.%d j.%d notarized.%d %llx opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,ccdata.symbol,matched,i,j,notarized,(long long)signedmask,opretlen,scriptbuf[len+offset],scriptbuf[len+offset+1],scriptbuf[len+offset+2]); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&srchash); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); if ( matched != 0 ) len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); - if ( strcmp("PIZZA",ASSETCHAINS_SYMBOL) == 0 && opretlen >= 110 ) - { - notarized = 1; - } static int32_t last_rewind; int32_t rewindtarget,validated = 0; CBlockIndex *pindex;// @@ -601,18 +615,16 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } else validated = 1; if ( notarized != 0 && (matched == 0 || (validated != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height)) ) { - struct komodo_ccdata ccdata; int32_t nameoffset = (int32_t)strlen(ASSETCHAINS_SYMBOL) + 1; - memset(&ccdata,0,sizeof(ccdata)); //sp->NOTARIZED_HEIGHT = *notarizedheightp; //sp->NOTARIZED_HASH = srchash; //sp->NOTARIZED_DESTTXID = desttxid; memset(&MoM,0,sizeof(MoM)); MoMdepth = 0; len += nameoffset; - strncpy(ccdata.symbol,(char *)&scriptbuf[len+offset],sizeof(ccdata.symbol)); ccdata.notarized_height = *notarizedheightp; ccdata.height = height; ccdata.txi = i; + printf("len.%d + 36 %d vs opretlen.%d\n",len,len+36,opretlen); if ( len+36 <= opretlen ) { len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&MoM); From e621c0a30235ac25c6532bfe84940512d86b0f47 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 21:49:53 +0300 Subject: [PATCH 020/507] Test --- src/komodo.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 3bb633999..48d53e0a0 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -568,7 +568,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr if ( ASSETCHAINS_SYMBOL[0] == 0 ) { nameoffset = (int32_t)strlen("KMD") + 1; - if ( strcmp("KMD",(char *)&scriptbuf[len+offset]) == 0 ) + if ( strcmp("KMD",(char *)&scriptbuf[len+32 * 2 + 4]) == 0 ) matched = 1; } else @@ -588,7 +588,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr if ( strcmp("PIZZA",(char *)&scriptbuf[len+offset]) == 0 && opretlen >= 110 ) notarized = 1; if ( opretlen != 149 ) - printf("[%s] (%s) matched.%d i.%d j.%d notarized.%d %llx opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,ccdata.symbol,matched,i,j,notarized,(long long)signedmask,opretlen,scriptbuf[len+offset],scriptbuf[len+offset+1],scriptbuf[len+offset+2]); + printf("[%s].%d (%s) matched.%d i.%d j.%d notarized.%d %llx opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,height,ccdata.symbol,matched,i,j,notarized,(long long)signedmask,opretlen,scriptbuf[len+offset],scriptbuf[len+offset+1],scriptbuf[len+offset+2]); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&srchash); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); if ( matched != 0 ) From 90b5b4fdc8be68da9708825b60bdeb600719ff50 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 22:02:53 +0300 Subject: [PATCH 021/507] Test --- src/komodo.h | 4 +++- src/komodo_ccdata.h | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 48d53e0a0..55eaddaf0 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -666,13 +666,15 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } else { - komodo_rwccdata(1,&ccdata); + komodo_rwccdata(ASSETCHAINS_SYMBOL,1,&ccdata); printf("[%s] matched.%d VALID (%s) MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,matched,ccdata.symbol,MoM.ToString().c_str(),MoMdepth); } if ( ccdata.pairs != 0 ) free(ccdata.pairs); memset(&ccdata,0,sizeof(ccdata)); } + else if ( ASSETCHAINS_SYMBOL[0] == 0 && matched != 0 && notarized != 0 && validated != 0 ) + komodo_rwccdata("KMD",1,&ccdata); if ( matched != 0 ) { sp->NOTARIZED_HEIGHT = *notarizedheightp; diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index d56c09e81..d8c68422a 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -28,7 +28,7 @@ struct komodo_ccdata }; */ -int32_t komodo_rwccdata(int32_t rwflag,struct komodo_ccdata *ccdata) +int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccdata) { if ( rwflag == 0 ) { From b6c1a2c30b4e3d23a0d2b46cb136f6b976f1ba20 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 22:07:40 +0300 Subject: [PATCH 022/507] Test --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 55eaddaf0..5cc987695 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -585,7 +585,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr strncpy(ccdata.symbol,(char *)&scriptbuf[len+offset],sizeof(ccdata.symbol)); if ( matched == 0 && bitweight(signedmask) >= KOMODO_MINRATIFY ) notarized = 1; - if ( strcmp("PIZZA",(char *)&scriptbuf[len+offset]) == 0 && opretlen >= 110 ) + if ( strcmp("PIZZA",ccdata.symbol) == 0 ) notarized = 1; if ( opretlen != 149 ) printf("[%s].%d (%s) matched.%d i.%d j.%d notarized.%d %llx opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,height,ccdata.symbol,matched,i,j,notarized,(long long)signedmask,opretlen,scriptbuf[len+offset],scriptbuf[len+offset+1],scriptbuf[len+offset+2]); From 06575b0a5463bd2d6122e12e00625100c724260e Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 22:17:31 +0300 Subject: [PATCH 023/507] Test --- src/komodo.h | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 5cc987695..9ddae2e11 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -567,19 +567,19 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr matched = 0; if ( ASSETCHAINS_SYMBOL[0] == 0 ) { - nameoffset = (int32_t)strlen("KMD") + 1; if ( strcmp("KMD",(char *)&scriptbuf[len+32 * 2 + 4]) == 0 ) matched = 1; } else { - nameoffset = (int32_t)strlen(ASSETCHAINS_SYMBOL) + 1; if ( strcmp(ASSETCHAINS_SYMBOL,(char *)&scriptbuf[len+offset]) == 0 ) matched = 1; } offset = 32 * (1 + matched) + 4; + nameoffset = (int32_t)strlen((char *)&scriptbuf[len+offset]) + 1; if ( j == 1 && opretlen >= len+offset ) { + static int32_t last_rewind; int32_t rewindtarget,validated = 0; CBlockIndex *pindex;// struct komodo_ccdata ccdata; memset(&ccdata,0,sizeof(ccdata)); strncpy(ccdata.symbol,(char *)&scriptbuf[len+offset],sizeof(ccdata.symbol)); @@ -593,9 +593,6 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); if ( matched != 0 ) len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); - static int32_t last_rewind; - int32_t rewindtarget,validated = 0; - CBlockIndex *pindex;// if ( matched != 0 && IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != *notarizedheightp) ) { if ( sp->NOTARIZED_HEIGHT > 0 && sp->NOTARIZED_HEIGHT < *notarizedheightp ) @@ -624,7 +621,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr ccdata.notarized_height = *notarizedheightp; ccdata.height = height; ccdata.txi = i; - printf("len.%d + 36 %d vs opretlen.%d\n",len,len+36,opretlen); + printf("nameoffset.%d len.%d + 36 %d vs opretlen.%d\n",nameoffset,len,len+36,opretlen); if ( len+36 <= opretlen ) { len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&MoM); From eea78002cf74297ab2dcf7560e78efe2de784cdd Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 22:19:16 +0300 Subject: [PATCH 024/507] Test --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 9ddae2e11..8955d39fd 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -671,7 +671,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr memset(&ccdata,0,sizeof(ccdata)); } else if ( ASSETCHAINS_SYMBOL[0] == 0 && matched != 0 && notarized != 0 && validated != 0 ) - komodo_rwccdata("KMD",1,&ccdata); + komodo_rwccdata((char *)"KMD",1,&ccdata); if ( matched != 0 ) { sp->NOTARIZED_HEIGHT = *notarizedheightp; From d24efb035d2ec0278349ab1ef6efb6c257ec213a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 22:37:28 +0300 Subject: [PATCH 025/507] Test --- src/komodo.h | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 8955d39fd..67e0bb34d 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -576,7 +576,10 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr matched = 1; } offset = 32 * (1 + matched) + 4; - nameoffset = (int32_t)strlen((char *)&scriptbuf[len+offset]) + 1; + nameoffset = (int32_t)strlen((char *)&scriptbuf[len+offset]); + if ( nameoffset == 2 ) + nameoffset += 2; + else nameoffset++; if ( j == 1 && opretlen >= len+offset ) { static int32_t last_rewind; int32_t rewindtarget,validated = 0; CBlockIndex *pindex;// @@ -588,7 +591,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr if ( strcmp("PIZZA",ccdata.symbol) == 0 ) notarized = 1; if ( opretlen != 149 ) - printf("[%s].%d (%s) matched.%d i.%d j.%d notarized.%d %llx opretlen.%d (%c %c %c)\n",ASSETCHAINS_SYMBOL,height,ccdata.symbol,matched,i,j,notarized,(long long)signedmask,opretlen,scriptbuf[len+offset],scriptbuf[len+offset+1],scriptbuf[len+offset+2]); + printf("[%s].%d (%s) matched.%d i.%d j.%d notarized.%d %llx opretlen.%d len.%d offset.%d\n",ASSETCHAINS_SYMBOL,height,ccdata.symbol,matched,i,j,notarized,(long long)signedmask,opretlen,len,offset); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&srchash); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); if ( matched != 0 ) @@ -622,6 +625,8 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr ccdata.height = height; ccdata.txi = i; printf("nameoffset.%d len.%d + 36 %d vs opretlen.%d\n",nameoffset,len,len+36,opretlen); + //nameoffset.4 len.43 + 36 79 vs opretlen.76 + //[].783861 (BOTS) matched.0 i.7 j.1 notarized.1 40001f140380 opretlen.77 (B O T) if ( len+36 <= opretlen ) { len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&MoM); From ab3db75bebccf035cea5f7ce24ae4e164d885a8d Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 22:44:40 +0300 Subject: [PATCH 026/507] Test --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 67e0bb34d..9240fe517 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -627,7 +627,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr printf("nameoffset.%d len.%d + 36 %d vs opretlen.%d\n",nameoffset,len,len+36,opretlen); //nameoffset.4 len.43 + 36 79 vs opretlen.76 //[].783861 (BOTS) matched.0 i.7 j.1 notarized.1 40001f140380 opretlen.77 (B O T) - if ( len+36 <= opretlen ) + if ( len+33 <= opretlen ) { len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&MoM); len += iguana_rwnum(0,&scriptbuf[len],sizeof(MoMdepth),(uint8_t *)&MoMdepth); From a730ab12ef6ff5ee7f220e9a0c8c58f909c9e98f Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 23:04:25 +0300 Subject: [PATCH 027/507] Test --- src/komodo.h | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 9240fe517..486db241c 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -556,7 +556,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } if ( scriptbuf[len++] == 0x6a ) { - int32_t nameoffset; + int32_t nameoffset,opoffset = 0; if ( (opretlen= scriptbuf[len++]) == 0x4c ) opretlen = scriptbuf[len++]; else if ( opretlen == 0x4d ) @@ -564,6 +564,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr opretlen = scriptbuf[len++]; opretlen += (scriptbuf[len++] << 8); } + opoffset = len; matched = 0; if ( ASSETCHAINS_SYMBOL[0] == 0 ) { @@ -580,7 +581,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr if ( nameoffset == 2 ) nameoffset += 2; else nameoffset++; - if ( j == 1 && opretlen >= len+offset ) + if ( j == 1 && opretlen >= len+offset-opoffset ) { static int32_t last_rewind; int32_t rewindtarget,validated = 0; CBlockIndex *pindex;// struct komodo_ccdata ccdata; @@ -591,7 +592,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr if ( strcmp("PIZZA",ccdata.symbol) == 0 ) notarized = 1; if ( opretlen != 149 ) - printf("[%s].%d (%s) matched.%d i.%d j.%d notarized.%d %llx opretlen.%d len.%d offset.%d\n",ASSETCHAINS_SYMBOL,height,ccdata.symbol,matched,i,j,notarized,(long long)signedmask,opretlen,len,offset); + printf("[%s].%d (%s) matched.%d i.%d j.%d notarized.%d %llx opretlen.%d len.%d offset.%d opoffset.%d\n",ASSETCHAINS_SYMBOL,height,ccdata.symbol,matched,i,j,notarized,(long long)signedmask,opretlen,len,offset,opoffset); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&srchash); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); if ( matched != 0 ) @@ -627,7 +628,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr printf("nameoffset.%d len.%d + 36 %d vs opretlen.%d\n",nameoffset,len,len+36,opretlen); //nameoffset.4 len.43 + 36 79 vs opretlen.76 //[].783861 (BOTS) matched.0 i.7 j.1 notarized.1 40001f140380 opretlen.77 (B O T) - if ( len+33 <= opretlen ) + if ( len+36-opoffset <= opretlen ) { len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&MoM); len += iguana_rwnum(0,&scriptbuf[len],sizeof(MoMdepth),(uint8_t *)&MoMdepth); @@ -640,7 +641,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr if ( ASSETCHAINS_SYMBOL[0] != 0 ) { // MoMoM, depth, numpairs, (notarization ht, MoMoM offset) - if ( len+48 <= opretlen && strcmp(ccdata.symbol,ASSETCHAINS_SYMBOL) == 0 ) + if ( len+48-opoffset <= opretlen && strcmp(ccdata.symbol,ASSETCHAINS_SYMBOL) == 0 ) { len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&ccdata.MoMoMstart); len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&ccdata.MoMoMend); From 5c8889053942490a9fb8dc26e656a68515476d86 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 23:24:58 +0300 Subject: [PATCH 028/507] Test --- src/komodo.h | 12 +++++------- src/komodo_ccdata.h | 5 ++++- src/main.cpp | 2 +- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 486db241c..340ccc093 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -591,7 +591,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr notarized = 1; if ( strcmp("PIZZA",ccdata.symbol) == 0 ) notarized = 1; - if ( opretlen != 149 ) + if ( 0 && opretlen != 149 ) printf("[%s].%d (%s) matched.%d i.%d j.%d notarized.%d %llx opretlen.%d len.%d offset.%d opoffset.%d\n",ASSETCHAINS_SYMBOL,height,ccdata.symbol,matched,i,j,notarized,(long long)signedmask,opretlen,len,offset,opoffset); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&srchash); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); @@ -625,9 +625,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr ccdata.notarized_height = *notarizedheightp; ccdata.height = height; ccdata.txi = i; - printf("nameoffset.%d len.%d + 36 %d vs opretlen.%d\n",nameoffset,len,len+36,opretlen); - //nameoffset.4 len.43 + 36 79 vs opretlen.76 - //[].783861 (BOTS) matched.0 i.7 j.1 notarized.1 40001f140380 opretlen.77 (B O T) + //printf("nameoffset.%d len.%d + 36 %d vs opretlen.%d\n",nameoffset,len,len+36,opretlen); if ( len+36-opoffset <= opretlen ) { len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&MoM); @@ -670,7 +668,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr else { komodo_rwccdata(ASSETCHAINS_SYMBOL,1,&ccdata); - printf("[%s] matched.%d VALID (%s) MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,matched,ccdata.symbol,MoM.ToString().c_str(),MoMdepth); + //printf("[%s] matched.%d VALID (%s) MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,matched,ccdata.symbol,MoM.ToString().c_str(),MoMdepth); } if ( ccdata.pairs != 0 ) free(ccdata.pairs); @@ -686,7 +684,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr sp->MoM = MoM; sp->MoMdepth = MoMdepth; komodo_stateupdate(height,0,0,0,zero,0,0,0,0,0,0,0,0,0,0,sp->MoM,sp->MoMdepth); - //if ( ASSETCHAINS_SYMBOL[0] != 0 ) + if ( ASSETCHAINS_SYMBOL[0] != 0 ) printf("[%s] ht.%d NOTARIZED.%d %s.%s %sTXID.%s lens.(%d %d) MoM.%s %d\n",ASSETCHAINS_SYMBOL,height,*notarizedheightp,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),ASSETCHAINS_SYMBOL[0]==0?"BTC":"KMD",desttxid.ToString().c_str(),opretlen,len,sp->MoM.ToString().c_str(),sp->MoMdepth); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { @@ -713,7 +711,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } } } - } else if ( matched != 0 && *notarizedheightp != sp->NOTARIZED_HEIGHT ) + } else //if ( matched != 0 && *notarizedheightp != sp->NOTARIZED_HEIGHT ) printf("validated.%d notarized.%d %llx reject ht.%d NOTARIZED.%d prev.%d %s.%s DESTTXID.%s len.%d opretlen.%d\n",validated,notarized,(long long)signedmask,height,*notarizedheightp,sp->NOTARIZED_HEIGHT,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),desttxid.ToString().c_str(),len,opretlen); } else if ( matched != 0 && i == 0 && j == 1 && opretlen == 149 ) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index d8c68422a..a45931a6f 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -30,11 +30,14 @@ struct komodo_ccdata int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccdata) { + bits256 hash; int32_t i; if ( rwflag == 0 ) { } - char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d numpairs.%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->notarized_height,bits256_str(str,*(bits256 *)&ccdata->MoM),ccdata->height,ccdata->txi,ccdata->numpairs); + for (i=0; i<32; i++) + hash[i] = ((uint8_t *)&ccdata->MoM)[31-i]; + char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d numpairs.%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->notarized_height,bits256_str(str,hash),ccdata->height,ccdata->txi,ccdata->numpairs); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { } diff --git a/src/main.cpp b/src/main.cpp index fb833bff5..6eff7c921 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3090,7 +3090,7 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo } } fprintf(stderr,"reached rewind.%d, best to do: ./komodo-cli -ac_name=%s stop\n",KOMODO_REWIND,ASSETCHAINS_SYMBOL); - sleep(60); + sleep(20); fprintf(stderr,"resuming normal operations\n"); KOMODO_REWIND = 0; return(true); From b007d0b00ab2d4ca83c1a96adce07d6f22f8f103 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 23:28:59 +0300 Subject: [PATCH 029/507] Test --- src/komodo_ccdata.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index a45931a6f..c5689fb79 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -36,7 +36,7 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd } for (i=0; i<32; i++) - hash[i] = ((uint8_t *)&ccdata->MoM)[31-i]; + hash.bytes[i] = ((uint8_t *)&ccdata->MoM)[31-i]; char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d numpairs.%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->notarized_height,bits256_str(str,hash),ccdata->height,ccdata->txi,ccdata->numpairs); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { From ae9fc2a33282c8d6fc0b10d2af2066fa15547b65 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 11 Apr 2018 23:41:52 +0300 Subject: [PATCH 030/507] Test --- src/komodo.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 340ccc093..b15d08498 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -614,7 +614,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr last_rewind = rewindtarget; } } else validated = 1; - if ( notarized != 0 && (matched == 0 || (validated != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height)) ) + if ( notarized != 0 && validated != 0 ) { //sp->NOTARIZED_HEIGHT = *notarizedheightp; //sp->NOTARIZED_HASH = srchash; @@ -676,7 +676,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } else if ( ASSETCHAINS_SYMBOL[0] == 0 && matched != 0 && notarized != 0 && validated != 0 ) komodo_rwccdata((char *)"KMD",1,&ccdata); - if ( matched != 0 ) + if ( matched != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height ) { sp->NOTARIZED_HEIGHT = *notarizedheightp; sp->NOTARIZED_HASH = srchash; From d269d79ecc245048af16c4aa18db1c73fa9f1e45 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 00:37:37 +0300 Subject: [PATCH 031/507] Test --- src/komodo.h | 45 ++++++++++++++++++++++---------------------- src/komodo_ccdata.h | 15 +++++++++------ src/komodo_structs.h | 17 +++++++++++++---- 3 files changed, 45 insertions(+), 32 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index b15d08498..527402020 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -584,8 +584,9 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr if ( j == 1 && opretlen >= len+offset-opoffset ) { static int32_t last_rewind; int32_t rewindtarget,validated = 0; CBlockIndex *pindex;// - struct komodo_ccdata ccdata; + struct komodo_ccdata ccdata; struct komodo_ccdataMoMoM MoMoMdata; memset(&ccdata,0,sizeof(ccdata)); + memset(&MoMoMdata,0,sizeof(MoMoMdata)); strncpy(ccdata.symbol,(char *)&scriptbuf[len+offset],sizeof(ccdata.symbol)); if ( matched == 0 && bitweight(signedmask) >= KOMODO_MINRATIFY ) notarized = 1; @@ -622,16 +623,16 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr memset(&MoM,0,sizeof(MoM)); MoMdepth = 0; len += nameoffset; - ccdata.notarized_height = *notarizedheightp; - ccdata.height = height; - ccdata.txi = i; + ccdata.MoMdata.notarized_height = *notarizedheightp; + ccdata.MoMdata.height = height; + ccdata.MoMdata.txi = i; //printf("nameoffset.%d len.%d + 36 %d vs opretlen.%d\n",nameoffset,len,len+36,opretlen); if ( len+36-opoffset <= opretlen ) { len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&MoM); len += iguana_rwnum(0,&scriptbuf[len],sizeof(MoMdepth),(uint8_t *)&MoMdepth); - ccdata.MoM = MoM; - ccdata.MoMdepth = MoMdepth; + ccdata.MoMdata.MoM = MoM; + ccdata.MoMdata.MoMdepth = MoMdepth; if ( len+sizeof(ccdata.CCid) <= opretlen ) { len += iguana_rwnum(0,&scriptbuf[len],sizeof(ccdata.CCid),(uint8_t *)&ccdata.CCid); @@ -641,23 +642,23 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr // MoMoM, depth, numpairs, (notarization ht, MoMoM offset) if ( len+48-opoffset <= opretlen && strcmp(ccdata.symbol,ASSETCHAINS_SYMBOL) == 0 ) { - len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&ccdata.MoMoMstart); - len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&ccdata.MoMoMend); - len += iguana_rwbignum(0,&scriptbuf[len],sizeof(ccdata.MoMoM),(uint8_t *)&ccdata.MoMoM); - len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&ccdata.MoMoMdepth); - len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&ccdata.numpairs); - ccdata.len += sizeof(ccdata.MoMoM) + sizeof(uint32_t)*4; - if ( len+ccdata.numpairs*8 == opretlen ) + len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMstart); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMend); + len += iguana_rwbignum(0,&scriptbuf[len],sizeof(ccdata.MoMoM),(uint8_t *)&MoMoMdata.MoMoM); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMdepth); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.numpairs); + MoMoMdata.len += sizeof(MoMoMdata.MoMoM) + sizeof(uint32_t)*4; + if ( len+MoMoMdata.numpairs*8-opoffset == opretlen ) { - ccdata.pairs = (struct komodo_ccdatapair *)calloc(ccdata.numpairs,sizeof(*ccdata.pairs)); - for (k=0; k 1440 || MoMdepth < 0 ) @@ -667,7 +668,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } else { - komodo_rwccdata(ASSETCHAINS_SYMBOL,1,&ccdata); + komodo_rwccdata(ASSETCHAINS_SYMBOL,1,&ccdata,&MoMoMdata); //printf("[%s] matched.%d VALID (%s) MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,matched,ccdata.symbol,MoM.ToString().c_str(),MoMdepth); } if ( ccdata.pairs != 0 ) @@ -675,7 +676,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr memset(&ccdata,0,sizeof(ccdata)); } else if ( ASSETCHAINS_SYMBOL[0] == 0 && matched != 0 && notarized != 0 && validated != 0 ) - komodo_rwccdata((char *)"KMD",1,&ccdata); + komodo_rwccdata((char *)"KMD",1,&ccdata,0); if ( matched != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height ) { sp->NOTARIZED_HEIGHT = *notarizedheightp; diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index c5689fb79..532569c6b 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -21,14 +21,14 @@ struct komodo_ccdata { uint32_t CCid; - bits256 MoMoM,MoM; - int32_t MoMoMdepth,numpairs,notarized_height,height,txi; - struct ccdatapair *pairs; + uint256 MoMoM,MoM; + int32_t MoMoMstart,MoMoMend,MoMoMdepth,numpairs,notarized_height,height,txi,len,MoMdepth; + struct komodo_ccdatapair *pairs; char symbol[65]; }; */ -int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccdata) +int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccdata,struct komodo_ccdataMoMoM *MoMoMdata) { bits256 hash; int32_t i; if ( rwflag == 0 ) @@ -36,10 +36,13 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd } for (i=0; i<32; i++) - hash.bytes[i] = ((uint8_t *)&ccdata->MoM)[31-i]; - char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d numpairs.%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->notarized_height,bits256_str(str,hash),ccdata->height,ccdata->txi,ccdata->numpairs); + hash.bytes[i] = ((uint8_t *)&ccdata->MoMdata.MoM)[31-i]; + char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->MoMdata.notarized_height,bits256_str(str,hash),ccdata->MoMdata.height,ccdata->MoMdata.txi); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { + // find/create entry for CCid + // if KMD, for all CCids, get range and calc MoMoM for RPC retrieval + // given MoM height for CCid chain, find the offset and MoMoM } else { diff --git a/src/komodo_structs.h b/src/komodo_structs.h index c620da392..003cd13f6 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -89,13 +89,22 @@ struct notarized_checkpoint int32_t nHeight,notarized_height,MoMdepth; }; +struct komodo_ccdataMoM +{ + uint256 MoM; + int32_t MoMdepth,notarized_height,height,txi; +}; +struct komodo_ccdataMoMoM +{ + uint256 MoMoM; + int32_t MoMoMstart,MoMoMend,MoMoMdepth,numpairs; + struct komodo_ccdatapair *pairs; +}; struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; struct komodo_ccdata { - uint32_t CCid; - uint256 MoMoM,MoM; - int32_t MoMoMstart,MoMoMend,MoMoMdepth,numpairs,notarized_height,height,txi,len,MoMdepth; - struct komodo_ccdatapair *pairs; + struct komodo_ccdataMoM MoMdata; + uint32_t CCid,len; char symbol[65]; }; From 00c6ec9d3f2545b6a8e79ee725add02ca29829c3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 00:39:14 +0300 Subject: [PATCH 032/507] Test --- src/komodo_structs.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/komodo_structs.h b/src/komodo_structs.h index 003cd13f6..8784ef26f 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -94,13 +94,16 @@ struct komodo_ccdataMoM uint256 MoM; int32_t MoMdepth,notarized_height,height,txi; }; + +struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; + struct komodo_ccdataMoMoM { uint256 MoMoM; int32_t MoMoMstart,MoMoMend,MoMoMdepth,numpairs; struct komodo_ccdatapair *pairs; }; -struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; + struct komodo_ccdata { struct komodo_ccdataMoM MoMdata; From c0d01b7da469e626333d344e33941ef06bedb6d3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 00:40:23 +0300 Subject: [PATCH 033/507] Test --- src/komodo.h | 5 +++-- src/komodo_structs.h | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 527402020..e2767a04b 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -671,9 +671,10 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr komodo_rwccdata(ASSETCHAINS_SYMBOL,1,&ccdata,&MoMoMdata); //printf("[%s] matched.%d VALID (%s) MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,matched,ccdata.symbol,MoM.ToString().c_str(),MoMdepth); } - if ( ccdata.pairs != 0 ) - free(ccdata.pairs); + if ( MoMoMdata.pairs != 0 ) + free(MoMoMdata.pairs); memset(&ccdata,0,sizeof(ccdata)); + memset(&MoMoMdata,0,sizeof(MoMoMdata)); } else if ( ASSETCHAINS_SYMBOL[0] == 0 && matched != 0 && notarized != 0 && validated != 0 ) komodo_rwccdata((char *)"KMD",1,&ccdata,0); diff --git a/src/komodo_structs.h b/src/komodo_structs.h index 8784ef26f..6527bebb7 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -100,7 +100,7 @@ struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; struct komodo_ccdataMoMoM { uint256 MoMoM; - int32_t MoMoMstart,MoMoMend,MoMoMdepth,numpairs; + int32_t MoMoMstart,MoMoMend,MoMoMdepth,numpairs,len; struct komodo_ccdatapair *pairs; }; From 090b1c9fac9150712029599e0cadb9b219471075 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 00:41:38 +0300 Subject: [PATCH 034/507] Test --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index e2767a04b..059fb3da6 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -644,7 +644,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr { len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMstart); len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMend); - len += iguana_rwbignum(0,&scriptbuf[len],sizeof(ccdata.MoMoM),(uint8_t *)&MoMoMdata.MoMoM); + len += iguana_rwbignum(0,&scriptbuf[len],sizeof(MoMoMdata.MoMoM),(uint8_t *)&MoMoMdata.MoMoM); len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMdepth); len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.numpairs); MoMoMdata.len += sizeof(MoMoMdata.MoMoM) + sizeof(uint32_t)*4; From fb9c36521831a04ae94689923cab752c3d2f598a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 11:44:28 +0300 Subject: [PATCH 035/507] Calculate MoMoM --- src/komodo.h | 6 +-- src/komodo_ccdata.h | 108 ++++++++++++++++++++++++++++++++++++++---- src/komodo_globals.h | 2 +- src/komodo_structs.h | 5 +- src/rpcblockchain.cpp | 13 +++++ src/rpcclient.cpp | 1 + src/rpcserver.cpp | 1 + src/rpcserver.h | 1 + 8 files changed, 122 insertions(+), 15 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 059fb3da6..a261cf0db 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -357,6 +357,7 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar if ( didinit == 0 ) { portable_mutex_init(&KOMODO_KV_mutex); + portable_mutex_init(&KOMODO_CC_mutex); didinit = 1; } if ( (sp= komodo_stateptr(symbol,dest)) == 0 ) @@ -640,14 +641,13 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr if ( ASSETCHAINS_SYMBOL[0] != 0 ) { // MoMoM, depth, numpairs, (notarization ht, MoMoM offset) - if ( len+48-opoffset <= opretlen && strcmp(ccdata.symbol,ASSETCHAINS_SYMBOL) == 0 ) + if ( len+44-opoffset <= opretlen && strcmp(ccdata.symbol,ASSETCHAINS_SYMBOL) == 0 ) { len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMstart); len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMend); len += iguana_rwbignum(0,&scriptbuf[len],sizeof(MoMoMdata.MoMoM),(uint8_t *)&MoMoMdata.MoMoM); - len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMdepth); len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.numpairs); - MoMoMdata.len += sizeof(MoMoMdata.MoMoM) + sizeof(uint32_t)*4; + MoMoMdata.len += sizeof(MoMoMdata.MoMoM) + sizeof(uint32_t)*3; if ( len+MoMoMdata.numpairs*8-opoffset == opretlen ) { MoMoMdata.pairs = (struct komodo_ccdatapair *)calloc(MoMoMdata.numpairs,sizeof(*MoMoMdata.pairs)); diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 532569c6b..fc746bcf2 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -16,21 +16,109 @@ #ifndef H_KOMODOCCDATA_H #define H_KOMODOCCDATA_H +/* +struct komodo_ccdataMoM +{ + uint256 MoM; + int32_t MoMdepth,notarized_height,height,txi; +}; + +struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; + +struct komodo_ccdataMoMoM +{ + uint256 MoMoM; + int32_t MoMoMstarti,MoMoMendi,numpairs,len; + struct komodo_ccdatapair *pairs; +}; -/*struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; struct komodo_ccdata { - uint32_t CCid; - uint256 MoMoM,MoM; - int32_t MoMoMstart,MoMoMend,MoMoMdepth,numpairs,notarized_height,height,txi,len,MoMdepth; - struct komodo_ccdatapair *pairs; + struct komodo_ccdataMoM MoMdata; + uint32_t CCid,len,inMoMoM; char symbol[65]; }; */ +struct komodo_ccdata *CC_data; + +bits256 iguana_merkle(bits256 *tree,int32_t txn_count) +{ + int32_t i,n=0,prev; uint8_t serialized[sizeof(bits256) * 2]; + if ( txn_count == 1 ) + return(tree[0]); + prev = 0; + while ( txn_count > 1 ) + { + if ( (txn_count & 1) != 0 ) + tree[prev + txn_count] = tree[prev + txn_count-1], txn_count++; + n += txn_count; + for (i=0; i> 1)] = bits256_doublesha256(0,serialized,sizeof(serialized)); + } + prev = n; + txn_count >>= 1; + } + return(tree[n]); +} + +char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) +{ + cJSON *retjson,*pairs,*item; struct komodo_ccdata *ccdata,*tmp; int32_t max,offset,starti,endi,kmdstarti=0; bits256 *tree,MoMoM; + starti = endi = offset = max = 0; + pairs = cJSON_CreateArray(); + portable_mutex_lock(&KOMODO_CC_mutex); + DL_FOREACH_SAFE(CC_data,ccdata,tmp) + { + if ( ccdata->MoMdata.height < kmdheight ) + { + if ( endi == 0 ) + endi = ccdata->MoMdata.height; + if ( strcmp(ccdata->symbol,symbol) == 0 ) + { + if (ccdata->MoMdata.notarized_height <= notarized_height ) + { + starti = ccdata->MoMdata.height + 1; + break; + } + item = cJSON_CreateArray(); + jaddinum(item,ccdata->MoMdata.notarized_height); + jaddinum(item,offset); + jaddi(pairs,item); + } + if ( offset >= max ) + { + max += 100; + tree = realloc(sizeof(*tree),max); + } + memcpy(&tree[offset++],&ccdata->MoMdata.MoM,sizeof(bits256)); + starti = ccdata->MoMdata.height; + } + } + portable_mutex_unlock(&KOMODO_CC_mutex); + retjson = cJSON_CreateObject(); + jaddnum(retjson,"kmdstarti",starti); + jaddnum(retjson,"kmdendi",endi); + if ( starti != 0 && endi != 0 && endi >= starti ) + { + if ( tree != 0 && offset > 0 ) + { + MoMoM = iguana_merkle(tree,offset); + jaddbits256(retjson,"MoMoM",MoMoM); + } + } + if ( tree != 0 ) + free(tree); + jadd(retjson,"offsets",pairs); + return(jprint(retjson,1)); +} + int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccdata,struct komodo_ccdataMoMoM *MoMoMdata) { - bits256 hash; int32_t i; + bits256 hash; int32_t i; struct komodo_ccdata *ptr; if ( rwflag == 0 ) { @@ -40,9 +128,11 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->MoMdata.notarized_height,bits256_str(str,hash),ccdata->MoMdata.height,ccdata->MoMdata.txi); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { - // find/create entry for CCid - // if KMD, for all CCids, get range and calc MoMoM for RPC retrieval - // given MoM height for CCid chain, find the offset and MoMoM + ptr = calloc(1,sizeof(*ptr)); + *ptr = *ccdata; + portable_mutex_lock(&KOMODO_CC_mutex); + DL_PREPEND(CC_data,ptr); + portable_mutex_unlock(&KOMODO_CC_mutex); } else { diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 1f4872d51..4d9d53f07 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -62,4 +62,4 @@ char KMDUSERPASS[4096],BTCUSERPASS[4096]; uint16_t KMD_PORT = 7771,BITCOIND_PORT uint64_t PENDING_KOMODO_TX; struct komodo_kv *KOMODO_KV; -pthread_mutex_t KOMODO_KV_mutex; +pthread_mutex_t KOMODO_KV_mutex,KOMODO_CC_mutex; diff --git a/src/komodo_structs.h b/src/komodo_structs.h index 6527bebb7..caf6aeae1 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -100,14 +100,15 @@ struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; struct komodo_ccdataMoMoM { uint256 MoMoM; - int32_t MoMoMstart,MoMoMend,MoMoMdepth,numpairs,len; + int32_t MoMoMstarti,MoMoMendi,numpairs,len; struct komodo_ccdatapair *pairs; }; struct komodo_ccdata { + struct komodo_ccdata *next,*prev; struct komodo_ccdataMoM MoMdata; - uint32_t CCid,len; + uint32_t CCid,inMoMoM,len; char symbol[65]; }; diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 010fb051c..5ddeaabf5 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -553,6 +553,7 @@ char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160, int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width); int32_t komodo_kvsearch(uint256 *refpubkeyp,int32_t current_height,uint32_t *flagsp,int32_t *heightp,uint8_t value[IGUANA_MAXSCRIPTSIZE],uint8_t *key,int32_t keylen); int32_t komodo_MoM(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight); +char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height); UniValue kvsearch(const UniValue& params, bool fHelp) { @@ -589,6 +590,18 @@ UniValue kvsearch(const UniValue& params, bool fHelp) return ret; } +UniValue MoMoMdata(const UniValue& params, bool fHelp) +{ + char *symbol; int32_t kmdheight; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); + if ( fHelp || params.size() != 3 ) + throw runtime_error("height_MoM needs symbol kmdheight notarized_height\n"); + LOCK(cs_main); + symbol = (char *)params[0].get_str().c_str(); + kmdheight = atoi(params[1].get_str().c_str()); + notarized_height = atoi(params[2].get_str().c_str()); + return((UniValue)komodo_MoMoMdata(symbol,kmdheight,notarized_height)); +} + UniValue height_MoM(const UniValue& params, bool fHelp) { int32_t height,depth,notarized_height; uint256 MoM,kmdtxid; uint32_t timestamp = 0; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); diff --git a/src/rpcclient.cpp b/src/rpcclient.cpp index 6a83e8c19..475a8bf69 100644 --- a/src/rpcclient.cpp +++ b/src/rpcclient.cpp @@ -126,6 +126,7 @@ static const CRPCConvertParam vRPCConvertParams[] = { "paxpending", 0 }, { "notaries", 2 }, { "height_MoM", 1 }, + { "MoMoMdata", 3 }, { "txMoMproof", 1 }, { "minerids", 1 }, { "kvsearch", 1 }, diff --git a/src/rpcserver.cpp b/src/rpcserver.cpp index 5d573f62b..dffe2d4d9 100644 --- a/src/rpcserver.cpp +++ b/src/rpcserver.cpp @@ -296,6 +296,7 @@ static const CRPCCommand vRPCCommands[] = { "blockchain", "paxpending", &paxpending, true }, { "blockchain", "paxprices", &paxprices, true }, { "blockchain", "notaries", ¬aries, true }, + { "blockchain", "MoMoMdata", &MoMoMdata, true }, { "blockchain", "height_MoM", &height_MoM, true }, { "blockchain", "txMoMproof", &txMoMproof, true }, { "blockchain", "minerids", &minerids, true }, diff --git a/src/rpcserver.h b/src/rpcserver.h index b4e6ed8fc..f3e0d5d89 100644 --- a/src/rpcserver.h +++ b/src/rpcserver.h @@ -304,6 +304,7 @@ extern UniValue z_validateaddress(const UniValue& params, bool fHelp); // in rpc extern UniValue z_getpaymentdisclosure(const UniValue& params, bool fHelp); // in rpcdisclosure.cpp extern UniValue z_validatepaymentdisclosure(const UniValue ¶ms, bool fHelp); // in rpcdisclosure.cpp +extern UniValue MoMoMdata(const UniValue& params, bool fHelp); extern UniValue height_MoM(const UniValue& params, bool fHelp); extern UniValue txMoMproof(const UniValue& params, bool fHelp); extern UniValue notaries(const UniValue& params, bool fHelp); From acee891f561446e67c11f743d92f3d8768903cdb Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 11:47:23 +0300 Subject: [PATCH 036/507] Test --- src/komodo.h | 4 ++-- src/komodo_ccdata.h | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index a261cf0db..03e6dc1f6 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -643,8 +643,8 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr // MoMoM, depth, numpairs, (notarization ht, MoMoM offset) if ( len+44-opoffset <= opretlen && strcmp(ccdata.symbol,ASSETCHAINS_SYMBOL) == 0 ) { - len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMstart); - len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMend); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMstarti); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMendi); len += iguana_rwbignum(0,&scriptbuf[len],sizeof(MoMoMdata.MoMoM),(uint8_t *)&MoMoMdata.MoMoM); len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.numpairs); MoMoMdata.len += sizeof(MoMoMdata.MoMoM) + sizeof(uint32_t)*3; diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index fc746bcf2..c5fa401f6 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -92,7 +92,7 @@ char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) if ( offset >= max ) { max += 100; - tree = realloc(sizeof(*tree),max); + tree = (bits256 *)realloc(sizeof(*tree),max); } memcpy(&tree[offset++],&ccdata->MoMdata.MoM,sizeof(bits256)); starti = ccdata->MoMdata.height; @@ -100,19 +100,19 @@ char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) } portable_mutex_unlock(&KOMODO_CC_mutex); retjson = cJSON_CreateObject(); - jaddnum(retjson,"kmdstarti",starti); - jaddnum(retjson,"kmdendi",endi); + jaddnum(retjson,(char *)"kmdstarti",starti); + jaddnum(retjson,(char *)"kmdendi",endi); if ( starti != 0 && endi != 0 && endi >= starti ) { if ( tree != 0 && offset > 0 ) { MoMoM = iguana_merkle(tree,offset); - jaddbits256(retjson,"MoMoM",MoMoM); + jaddbits256(retjson,(char *)"MoMoM",MoMoM); } } if ( tree != 0 ) free(tree); - jadd(retjson,"offsets",pairs); + jadd(retjson,(char *)"offsets",pairs); return(jprint(retjson,1)); } From b71e57a4827aa12459683ee281752ec855e701ed Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 11:49:33 +0300 Subject: [PATCH 037/507] Fix --- src/komodo_ccdata.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index c5fa401f6..15b1086ca 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -92,7 +92,7 @@ char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) if ( offset >= max ) { max += 100; - tree = (bits256 *)realloc(sizeof(*tree),max); + tree = (bits256 *)realloc(tree,sizeof(*tree)*max); } memcpy(&tree[offset++],&ccdata->MoMdata.MoM,sizeof(bits256)); starti = ccdata->MoMdata.height; @@ -128,7 +128,7 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->MoMdata.notarized_height,bits256_str(str,hash),ccdata->MoMdata.height,ccdata->MoMdata.txi); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { - ptr = calloc(1,sizeof(*ptr)); + ptr = (struct komodo_ccdata *)calloc(1,sizeof(*ptr)); *ptr = *ccdata; portable_mutex_lock(&KOMODO_CC_mutex); DL_PREPEND(CC_data,ptr); From 847f8d4639d73fa50d8774fc378959e1af236105 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 11:52:39 +0300 Subject: [PATCH 038/507] Test --- src/rpcblockchain.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 5ddeaabf5..108efdd03 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -592,7 +592,7 @@ UniValue kvsearch(const UniValue& params, bool fHelp) UniValue MoMoMdata(const UniValue& params, bool fHelp) { - char *symbol; int32_t kmdheight; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); + char *symbol; int32_t kmdheight,notarized_height; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); if ( fHelp || params.size() != 3 ) throw runtime_error("height_MoM needs symbol kmdheight notarized_height\n"); LOCK(cs_main); From b11b2845266a998b4cf8aea96f14a9b5a6ebf541 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 12:03:29 +0300 Subject: [PATCH 039/507] +print --- src/komodo_ccdata.h | 1 + src/rpcblockchain.cpp | 15 +++++++++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 15b1086ca..c3978414b 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -113,6 +113,7 @@ char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) if ( tree != 0 ) free(tree); jadd(retjson,(char *)"offsets",pairs); + fprintf(stderr,"%s\n",jprint(retjson,0)); return(jprint(retjson,1)); } diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 108efdd03..4581424c1 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -592,21 +592,28 @@ UniValue kvsearch(const UniValue& params, bool fHelp) UniValue MoMoMdata(const UniValue& params, bool fHelp) { - char *symbol; int32_t kmdheight,notarized_height; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); + char *symbol,*retstr; int32_t kmdheight,notarized_height; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); if ( fHelp || params.size() != 3 ) - throw runtime_error("height_MoM needs symbol kmdheight notarized_height\n"); + throw runtime_error("MoMoMdata symbol kmdheight notarized_height\n"); LOCK(cs_main); symbol = (char *)params[0].get_str().c_str(); kmdheight = atoi(params[1].get_str().c_str()); notarized_height = atoi(params[2].get_str().c_str()); - return((UniValue)komodo_MoMoMdata(symbol,kmdheight,notarized_height)); + if ( (retstr= komodo_MoMoMdata(symbol,kmdheight,notarized_height)) != 0 ) + { + ret.push_back(Pair("coin",symbol)); + ret.push_back(Pair("kmdheight",kmdheight)); + ret.push_back(Pair("notarized_height",notarized_height)); + free(retstr); + } + return(ret); } UniValue height_MoM(const UniValue& params, bool fHelp) { int32_t height,depth,notarized_height; uint256 MoM,kmdtxid; uint32_t timestamp = 0; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); if ( fHelp || params.size() != 1 ) - throw runtime_error("height_MoM needs height\n"); + throw runtime_error("height_MoM height\n"); LOCK(cs_main); height = atoi(params[0].get_str().c_str()); if ( height <= 0 ) From 1f21e3a31ff07c5315a8decf327ae787ed719fdb Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 12:12:02 +0300 Subject: [PATCH 040/507] Test --- src/komodo_ccdata.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index c3978414b..baf7385f6 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -67,7 +67,7 @@ bits256 iguana_merkle(bits256 *tree,int32_t txn_count) char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) { - cJSON *retjson,*pairs,*item; struct komodo_ccdata *ccdata,*tmp; int32_t max,offset,starti,endi,kmdstarti=0; bits256 *tree,MoMoM; + cJSON *retjson,*pairs,*item; struct komodo_ccdata *ccdata,*tmp; int32_t max,offset,starti,endi,kmdstarti=0; bits256 *tree=0,MoMoM; starti = endi = offset = max = 0; pairs = cJSON_CreateArray(); portable_mutex_lock(&KOMODO_CC_mutex); @@ -75,10 +75,10 @@ char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) { if ( ccdata->MoMdata.height < kmdheight ) { - if ( endi == 0 ) - endi = ccdata->MoMdata.height; if ( strcmp(ccdata->symbol,symbol) == 0 ) { + if ( endi == 0 ) + endi = ccdata->MoMdata.height; if (ccdata->MoMdata.notarized_height <= notarized_height ) { starti = ccdata->MoMdata.height + 1; From d1fb566733a5b868a427fe96d6d52eab3b0971ec Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 12:12:53 +0300 Subject: [PATCH 041/507] Prints --- src/komodo_ccdata.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index baf7385f6..ee0bb1608 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -93,6 +93,7 @@ char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) { max += 100; tree = (bits256 *)realloc(tree,sizeof(*tree)*max); + fprintf(stderr,"tree reallocated to %p max.%d\n",tree,max); } memcpy(&tree[offset++],&ccdata->MoMdata.MoM,sizeof(bits256)); starti = ccdata->MoMdata.height; @@ -111,7 +112,10 @@ char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) } } if ( tree != 0 ) + { + fprintf(stderr,"free tree.%p\n",tree); free(tree); + } jadd(retjson,(char *)"offsets",pairs); fprintf(stderr,"%s\n",jprint(retjson,0)); return(jprint(retjson,1)); From 9973e12ebbfa68cfad2b5e3402bf1025f82b6301 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 12:18:06 +0300 Subject: [PATCH 042/507] Test --- src/komodo_ccdata.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index ee0bb1608..d10c701bf 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -75,6 +75,7 @@ char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) { if ( ccdata->MoMdata.height < kmdheight ) { + fprintf(stderr,"%s notarized.%d kmd.%d\n",ccdata->symbol,ccdata->MoMdata.notarized_height,ccdata->MoMdata.height); if ( strcmp(ccdata->symbol,symbol) == 0 ) { if ( endi == 0 ) From 51dab1491448a2541016fa8c48c2f537155bdd3f Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 14:41:39 +0300 Subject: [PATCH 043/507] MoMoM code complete --- src/komodo.h | 9 +-- src/komodo_bitcoind.h | 4 +- src/komodo_ccdata.h | 128 +++++++++++++++++++++++++++++------------- src/komodo_globals.h | 2 +- src/komodo_notary.h | 34 +++++++---- src/komodo_structs.h | 8 +-- src/rpcblockchain.cpp | 54 +++++++++++++----- 7 files changed, 163 insertions(+), 76 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 03e6dc1f6..52daaae0e 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -641,13 +641,14 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr if ( ASSETCHAINS_SYMBOL[0] != 0 ) { // MoMoM, depth, numpairs, (notarization ht, MoMoM offset) - if ( len+44-opoffset <= opretlen && strcmp(ccdata.symbol,ASSETCHAINS_SYMBOL) == 0 ) + if ( len+48-opoffset <= opretlen && strcmp(ccdata.symbol,ASSETCHAINS_SYMBOL) == 0 ) { - len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMstarti); - len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMendi); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.kmdstarti); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.kmdendi); len += iguana_rwbignum(0,&scriptbuf[len],sizeof(MoMoMdata.MoMoM),(uint8_t *)&MoMoMdata.MoMoM); + len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.MoMoMdepth); len += iguana_rwnum(0,&scriptbuf[len],sizeof(uint32_t),(uint8_t *)&MoMoMdata.numpairs); - MoMoMdata.len += sizeof(MoMoMdata.MoMoM) + sizeof(uint32_t)*3; + MoMoMdata.len += sizeof(MoMoMdata.MoMoM) + sizeof(uint32_t)*4; if ( len+MoMoMdata.numpairs*8-opoffset == opretlen ) { MoMoMdata.pairs = (struct komodo_ccdatapair *)calloc(MoMoMdata.numpairs,sizeof(*MoMoMdata.pairs)); diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 1b5e9ad64..4ba908f8b 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -869,10 +869,10 @@ int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33],uint32_t timestamp return(0); } -int32_t komodo_MoM(int32_t *notarized_heightp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight) +int32_t komodo_MoM(int32_t *notarized_heightp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip) { int32_t depth,notarized_ht; uint256 MoM,kmdtxid; - depth = komodo_MoMdata(¬arized_ht,&MoM,&kmdtxid,nHeight); + depth = komodo_MoMdata(¬arized_ht,&MoM,&kmdtxid,nHeight,MoMoMp,MoMoMoffsetp,MoMoMdepthp,kmdstartip,kmdendip); memset(MoMp,0,sizeof(*MoMp)); memset(kmdtxidp,0,sizeof(*kmdtxidp)); *notarized_heightp = 0; diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index d10c701bf..3761e406b 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -16,31 +16,8 @@ #ifndef H_KOMODOCCDATA_H #define H_KOMODOCCDATA_H -/* -struct komodo_ccdataMoM -{ - uint256 MoM; - int32_t MoMdepth,notarized_height,height,txi; -}; - -struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; - -struct komodo_ccdataMoMoM -{ - uint256 MoMoM; - int32_t MoMoMstarti,MoMoMendi,numpairs,len; - struct komodo_ccdatapair *pairs; -}; - -struct komodo_ccdata -{ - struct komodo_ccdataMoM MoMdata; - uint32_t CCid,len,inMoMoM; - char symbol[65]; -}; -*/ - struct komodo_ccdata *CC_data; +int32_t CC_firstheight; bits256 iguana_merkle(bits256 *tree,int32_t txn_count) { @@ -65,11 +42,18 @@ bits256 iguana_merkle(bits256 *tree,int32_t txn_count) return(tree[n]); } -char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) +int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM *mdata,char *symbol,int32_t kmdheight,int32_t notarized_height) { - cJSON *retjson,*pairs,*item; struct komodo_ccdata *ccdata,*tmp; int32_t max,offset,starti,endi,kmdstarti=0; bits256 *tree=0,MoMoM; - starti = endi = offset = max = 0; + cJSON *retjson,*pairs,*item; uint8_t hexdata[8192]; struct komodo_ccdata *ccdata,*tmp; int32_t len,i,retval=-1,max,offset,starti,endi,kmdstarti=0; bits256 *tree=0,MoMoM; + starti = endi = offset = max = len = 0; + hexstr[0] = 0; + if ( sizeof(hexdata)*2+1 > hexsize ) + { + fprintf(stderr,"hexsize.%d too small for %d\n",hexsize,(int32_t)sizeof(hexdata)); + return(-1); + } pairs = cJSON_CreateArray(); + memset(mdata,0,sizeof(*mdata)); portable_mutex_lock(&KOMODO_CC_mutex); DL_FOREACH_SAFE(CC_data,ccdata,tmp) { @@ -79,8 +63,11 @@ char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) if ( strcmp(ccdata->symbol,symbol) == 0 ) { if ( endi == 0 ) + { + len += iguana_rwnum(1,&hexdata[len],sizeof(ccdata->CCid),(uint8_t *)&ccdata->CCid); endi = ccdata->MoMdata.height; - if (ccdata->MoMdata.notarized_height <= notarized_height ) + } + if ( (mdata.numpairs == 1 && notarized_height == 0) || ccdata->MoMdata.notarized_height <= notarized_height ) { starti = ccdata->MoMdata.height + 1; break; @@ -89,12 +76,13 @@ char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) jaddinum(item,ccdata->MoMdata.notarized_height); jaddinum(item,offset); jaddi(pairs,item); + mdata.numpairs++; } if ( offset >= max ) { max += 100; tree = (bits256 *)realloc(tree,sizeof(*tree)*max); - fprintf(stderr,"tree reallocated to %p max.%d\n",tree,max); + //fprintf(stderr,"tree reallocated to %p max.%d\n",tree,max); } memcpy(&tree[offset++],&ccdata->MoMdata.MoM,sizeof(bits256)); starti = ccdata->MoMdata.height; @@ -110,38 +98,98 @@ char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height) { MoMoM = iguana_merkle(tree,offset); jaddbits256(retjson,(char *)"MoMoM",MoMoM); + jaddnum(retjson,(char *)"MoMoMdepth",offset); + if ( mdata.numpairs > 0 && mdata.numpairs == cJSON_GetArraySize(pairs) ) + { + len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->kmdstarti); + len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->kmdendi); + len += iguana_rwbignum(1,&hexdata[len],sizeof(mdata->MoMoM),(uint8_t *)&mdata->MoMoM); + len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->MoMoMdepth); + len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->numpairs); + mdata.pairs = (struct komodo_ccdatapair *)calloc(mdata.numpairs,sizeof(*mdata.pairs)); + for (i=0; i sizeof(hexdata) ) + { + fprintf(stderr,"%s %d %d i.%d of %d exceeds hexdata.%d\n",symbol,kmdheight,notarized_height,i,mdata.numpairs,(int32_t)sizeof(hexdata)); + break; + } + item = jitem(pairs,i); + mdata.pairs[i].notarization_height = juint(0,jitem(item,0)); + mdata.pairs[i].MoMoMoffset = juint(0,jitem(item,1)); + len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata.pairs[i].notarization_height); + len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata.pairs[i].MoMoMoffset); + } + if ( i == mdata.numpairs && len*2+1 < hexsize ) + { + init_hexbyte_noT(hexstr,hexdata,len); + retval = 0; + } else fprintf(stderr,"%s %d %d too much hexdata[%d] for hexstr[%d]\n",symbol,kmdheight,notarized_height,len,hexsize); + } } } if ( tree != 0 ) - { - fprintf(stderr,"free tree.%p\n",tree); free(tree); - } jadd(retjson,(char *)"offsets",pairs); fprintf(stderr,"%s\n",jprint(retjson,0)); - return(jprint(retjson,1)); + return(retval); } int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccdata,struct komodo_ccdataMoMoM *MoMoMdata) { - bits256 hash; int32_t i; struct komodo_ccdata *ptr; + bits256 hash; int32_t i; struct komodo_ccdata *ptr; struct notarized_checkpoint *np; if ( rwflag == 0 ) { - + // load from disk } + else + { + // write to disk + } + if ( ccdata->MoMdata.height > 0 && (CC_firstheight == 0 || ccdata->MoMdata.height < CC_firstheight) ) + CC_firstheight = ccdata->MoMdata.height; for (i=0; i<32; i++) hash.bytes[i] = ((uint8_t *)&ccdata->MoMdata.MoM)[31-i]; char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->MoMdata.notarized_height,bits256_str(str,hash),ccdata->MoMdata.height,ccdata->MoMdata.txi); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { - ptr = (struct komodo_ccdata *)calloc(1,sizeof(*ptr)); - *ptr = *ccdata; - portable_mutex_lock(&KOMODO_CC_mutex); - DL_PREPEND(CC_data,ptr); - portable_mutex_unlock(&KOMODO_CC_mutex); + if ( CC_data != 0 && (CC_data->MoMdata.height > ccdata->MoMdata.height || (CC_data->MoMdata.height == ccdata->MoMdata.height && CC_data->MoMdata.txi >= ccdata->MoMdata.txi)) ) + { + printf("out of order detected? SKIP CC_data ht.%d/txi.%d vs ht.%d/txi.%d\n",CC_data->MoMdata.height,CC_data->MoMdata.txi,ccdata->MoMdata.height,ccdata->MoMdata.txi); + } + else + { + ptr = (struct komodo_ccdata *)calloc(1,sizeof(*ptr)); + *ptr = *ccdata; + portable_mutex_lock(&KOMODO_CC_mutex); + DL_PREPEND(CC_data,ptr); + portable_mutex_unlock(&KOMODO_CC_mutex); + } } else { + if ( MoMoMdata != 0 && MoMoMdata->pairs != 0 ) + { + for (i=0; inumpairs; i++) + { + if ( (np= komodo_npptr(MoMoMdata->pairs[i].notarized_height)) != 0 ) + { + if ( bits256_nonz(np->MoMoM) == 0 ) + { + np->MoMoM = MoMoMdata->MoMoM; + np->MoMoMdepth = MoMoMdata->MoMoMdepth; + np->MoMoMoffset = MoMoMdata->MoMoMoffset; + np->kmdstarti = MoMoMdata->kmdstarti; + np->kmdendi = MoMoMdata->kmdendi; + } + else if ( bits256_cmp(np->MoMoM,MoMoMdata->MoMoM) != 0 || np->MoMoMdepth != MoMoMdata->MoMoMdepth || np->MoMoMoffset != MoMoMdata->MoMoMoffset || np->kmdstarti != MoMoMdata->kmdstarti || np->kmdendi != MoMoMdata->kmdendi ) + { + char str[65],str2[65]; + fprintf(stderr,"preexisting MoMoM mismatch: %s (%d %d %d %d) vs %s (%d %d %d %d)\n",bits256_str(str,np->MoMoM),np->MoMoMdepth,np->MoMoMoffset,np->kmdstarti,np->kmdendi,bits256_str(str2,MoMoMdata->MoMoM),,MoMoMdata->MoMoMdepth,MoMoMdata->MoMoMoffset,MoMoMdata->kmdstarti,MoMoMdata->kmdendi); + } + } + } + } } } diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 4d9d53f07..919ee97dd 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -18,7 +18,7 @@ uint32_t komodo_heightstamp(int32_t height); void 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,int32_t kheight,uint32_t ktime,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout,uint256 MoM,int32_t MoMdepth); void komodo_init(int32_t height); -int32_t komodo_MoMdata(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight); +int32_t komodo_MoMdata(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip); int32_t komodo_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *notarized_desttxidp); char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port); void komodo_init(int32_t height); diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 59c53ecf6..1c5b6c855 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -396,27 +396,39 @@ int32_t komodo_notarized_height(uint256 *hashp,uint256 *txidp) } } - -int32_t komodo_MoMdata(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t height) +struct notarized_checkpoint *komodo_npptr(int32_t height) { - int32_t i; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; struct komodo_state *sp; struct notarized_checkpoint *np = 0; - np = 0; + char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; int32_t i; struct komodo_state *sp; struct notarized_checkpoint *np = 0; if ( (sp= komodo_stateptr(symbol,dest)) != 0 ) { for (i=sp->NUM_NPOINTS-1; i>=0; i--) { np = &sp->NPOINTS[i]; if ( np->MoMdepth > 0 && height > np->notarized_height-np->MoMdepth && height <= np->notarized_height ) - { - *notarized_htp = np->notarized_height; - *MoMp = np->MoM; - *kmdtxidp = np->notarized_desttxid; - return(np->MoMdepth); - } + return(np); } } - *notarized_htp = 0; + return(0); +} + +int32_t komodo_MoMdata(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t height,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip) +{ + struct notarized_checkpoint *np = 0; + if ( (np= komodo_npptr(height)) != 0 ) + { + *notarized_htp = np->notarized_height; + *MoMp = np->MoM; + *kmdtxidp = np->notarized_desttxid; + *MoMoMp = np->MoMoM; + *MoMoMoffsetp = np->MoMoMoffset; + *MoMoMdepthp = np->MoMoMdepth; + *kmdstartip = np->kmdstarti; + *kmdendip = np->kmdendip; + return(np->MoMdepth); + } + *notarized_htp = *MoMoMoffsetp = *MoMoMdepthp = *kmdstartip = *kmdendip = 0; memset(MoMp,0,sizeof(*MoMp)); + memset(MoMoMp,0,sizeof(*MoMoMp)); memset(kmdtxidp,0,sizeof(*kmdtxidp)); return(0); } diff --git a/src/komodo_structs.h b/src/komodo_structs.h index caf6aeae1..32a630950 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -85,8 +85,8 @@ struct knotary_entry { UT_hash_handle hh; uint8_t pubkey[33],notaryid; }; struct knotaries_entry { int32_t height,numnotaries; struct knotary_entry *Notaries; }; struct notarized_checkpoint { - uint256 notarized_hash,notarized_desttxid,MoM; - int32_t nHeight,notarized_height,MoMdepth; + uint256 notarized_hash,notarized_desttxid,MoM,MoMoM; + int32_t nHeight,notarized_height,MoMdepth,MoMoMdepth,MoMoMoffset,kmdstarti,kmdendi; }; struct komodo_ccdataMoM @@ -100,7 +100,7 @@ struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; struct komodo_ccdataMoMoM { uint256 MoMoM; - int32_t MoMoMstarti,MoMoMendi,numpairs,len; + int32_t kmdstarti,kmdendi,MoMoMdepth,numpairs,len; struct komodo_ccdatapair *pairs; }; @@ -108,7 +108,7 @@ struct komodo_ccdata { struct komodo_ccdata *next,*prev; struct komodo_ccdataMoM MoMdata; - uint32_t CCid,inMoMoM,len; + uint32_t CCid,len; char symbol[65]; }; diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 4581424c1..a003b2c7a 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -539,6 +539,7 @@ UniValue gettxoutsetinfo(const UniValue& params, bool fHelp) } #include "komodo_defs.h" +#include "komodo_structs.h" #define IGUANA_MAXSCRIPTSIZE 10001 #define KOMODO_KVDURATION 1440 @@ -552,8 +553,8 @@ char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160, //uint32_t komodo_interest_args(int32_t *txheightp,uint32_t *tiptimep,uint64_t *valuep,uint256 hash,int32_t n); int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width); int32_t komodo_kvsearch(uint256 *refpubkeyp,int32_t current_height,uint32_t *flagsp,int32_t *heightp,uint8_t value[IGUANA_MAXSCRIPTSIZE],uint8_t *key,int32_t keylen); -int32_t komodo_MoM(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight); -char *komodo_MoMoMdata(char *symbol,int32_t kmdheight,int32_t notarized_height); +int32_t komodo_MoM(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip); +int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM *mdata,char *symbol,int32_t kmdheight,int32_t notarized_height); UniValue kvsearch(const UniValue& params, bool fHelp) { @@ -592,26 +593,43 @@ UniValue kvsearch(const UniValue& params, bool fHelp) UniValue MoMoMdata(const UniValue& params, bool fHelp) { - char *symbol,*retstr; int32_t kmdheight,notarized_height; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); + char *symbol,hexstr[16384+1]; struct komodo_MoMoMdata mdata; int32_t kmdheight,notarized_height; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); if ( fHelp || params.size() != 3 ) throw runtime_error("MoMoMdata symbol kmdheight notarized_height\n"); LOCK(cs_main); symbol = (char *)params[0].get_str().c_str(); kmdheight = atoi(params[1].get_str().c_str()); notarized_height = atoi(params[2].get_str().c_str()); - if ( (retstr= komodo_MoMoMdata(symbol,kmdheight,notarized_height)) != 0 ) + ret.push_back(Pair("coin",symbol)); + ret.push_back(Pair("kmdheight",kmdheight)); + ret.push_back(Pair("notarized_height",notarized_height)); + if ( komodo_MoMoMdata(hexstr,sizeof(hexstr),&mdata,symbol,kmdheight,notarized_height) == 0 ) { - ret.push_back(Pair("coin",symbol)); - ret.push_back(Pair("kmdheight",kmdheight)); - ret.push_back(Pair("notarized_height",notarized_height)); - free(retstr); - } + ret.push_back(Pair("kmdstarti",mdata.kmdstarti)); + ret.push_back(Pair("kmdendi",mdata.kmdendi)); + ret.push_back(Pair("MoMoM",mdata.MoMoM.ToString())); + ret.push_back(Pair("MoMoMdepth",mdata.MoMoMdepth)); + ret.push_back(Pair("numnotarizations",mdata.numpairs)); + if ( mdata.pairs != 0 ) + { + for (i=0; inHeight; } //fprintf(stderr,"height_MoM height.%d\n",height); - depth = komodo_MoM(¬arized_height,&MoM,&kmdtxid,height); + depth = komodo_MoM(¬arized_height,&MoM,&kmdtxid,height,&MoMoM,&MoMoMoffset,&MoMoMdepth,&kmdstarti,&kmdendi); ret.push_back(Pair("coin",(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "KMD" : ASSETCHAINS_SYMBOL))); ret.push_back(Pair("height",height)); ret.push_back(Pair("timestamp",(uint64_t)timestamp)); @@ -636,6 +654,14 @@ UniValue height_MoM(const UniValue& params, bool fHelp) ret.push_back(Pair("notarized_height",notarized_height)); ret.push_back(Pair("MoM",MoM.GetHex())); ret.push_back(Pair("kmdtxid",kmdtxid.GetHex())); + if ( ASSETCHAINS_SYMBOL[0] != 0 ) + { + ret.push_back(Pair("MoMoM",MoMoM.GetHex())); + ret.push_back(Pair("MoMoMoffset",MoMoMoffset)); + ret.push_back(Pair("MoMoMdepth",MoMoMdepth)); + ret.push_back(Pair("kmdstarti",kmdstarti)); + ret.push_back(Pair("kmdendi",kmdendi)); + } } else ret.push_back(Pair("error",(char *)"no MoM for height")); return ret; @@ -643,11 +669,11 @@ UniValue height_MoM(const UniValue& params, bool fHelp) UniValue txMoMproof(const UniValue& params, bool fHelp) { - uint256 hash, notarisationHash, MoM; + uint256 hash, notarisationHash, MoM,MoMoM; int32_t notarisedHeight, depth; CBlockIndex* blockIndex; std::vector branch; - int nIndex; + int nIndex,MoMoMdepth,MoMoMoffset,kmdstarti,kmdendi; // parse params and get notarisation data for tx { @@ -663,7 +689,7 @@ UniValue txMoMproof(const UniValue& params, bool fHelp) blockIndex = mapBlockIndex[blockHash]; - depth = komodo_MoM(¬arisedHeight, &MoM, ¬arisationHash, blockIndex->nHeight); + depth = komodo_MoM(¬arisedHeight, &MoM, ¬arisationHash, blockIndex->nHeight,&MoMoM,&MoMoMoffset,&MoMoMdepth,&kmdstarti,&kmdendi); if (!depth) throw runtime_error("notarisation not found"); From 1b491957e4badfdae0c579f807a42370d913dd10 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 16:35:37 +0300 Subject: [PATCH 044/507] Fix syntax errors because I don't know C++ well enough to type 1000 lines of code without syntax errors --- src/komodo_ccdata.h | 42 +++++++++++++++++++++--------------------- src/komodo_notary.h | 2 +- src/komodo_structs.h | 2 +- 3 files changed, 23 insertions(+), 23 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 3761e406b..162c4b202 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -59,7 +59,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM { if ( ccdata->MoMdata.height < kmdheight ) { - fprintf(stderr,"%s notarized.%d kmd.%d\n",ccdata->symbol,ccdata->MoMdata.notarized_height,ccdata->MoMdata.height); + fprintf(stderr,"%s notarized.%d kmd.%d\n",ccdata->symbol,ccdata->MoMdata.notarization_height,ccdata->MoMdata.height); if ( strcmp(ccdata->symbol,symbol) == 0 ) { if ( endi == 0 ) @@ -67,16 +67,16 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM len += iguana_rwnum(1,&hexdata[len],sizeof(ccdata->CCid),(uint8_t *)&ccdata->CCid); endi = ccdata->MoMdata.height; } - if ( (mdata.numpairs == 1 && notarized_height == 0) || ccdata->MoMdata.notarized_height <= notarized_height ) + if ( (mdata->numpairs == 1 && notarized_height == 0) || ccdata->MoMdata.notarization_height <= notarized_height ) { starti = ccdata->MoMdata.height + 1; break; } item = cJSON_CreateArray(); - jaddinum(item,ccdata->MoMdata.notarized_height); + jaddinum(item,ccdata->MoMdata.notarization_height); jaddinum(item,offset); jaddi(pairs,item); - mdata.numpairs++; + mdata->numpairs++; } if ( offset >= max ) { @@ -99,30 +99,30 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM MoMoM = iguana_merkle(tree,offset); jaddbits256(retjson,(char *)"MoMoM",MoMoM); jaddnum(retjson,(char *)"MoMoMdepth",offset); - if ( mdata.numpairs > 0 && mdata.numpairs == cJSON_GetArraySize(pairs) ) + if ( mdata->numpairs > 0 && mdata.numpairs == cJSON_GetArraySize(pairs) ) { len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->kmdstarti); len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->kmdendi); len += iguana_rwbignum(1,&hexdata[len],sizeof(mdata->MoMoM),(uint8_t *)&mdata->MoMoM); len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->MoMoMdepth); len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->numpairs); - mdata.pairs = (struct komodo_ccdatapair *)calloc(mdata.numpairs,sizeof(*mdata.pairs)); - for (i=0; ipairs = (struct komodo_ccdatapair *)calloc(mdata->numpairs,sizeof(*mdata->pairs)); + for (i=0; inumpairs; i++) { if ( len + sizeof(uint32_t)*2 > sizeof(hexdata) ) { - fprintf(stderr,"%s %d %d i.%d of %d exceeds hexdata.%d\n",symbol,kmdheight,notarized_height,i,mdata.numpairs,(int32_t)sizeof(hexdata)); + fprintf(stderr,"%s %d %d i.%d of %d exceeds hexdata.%d\n",symbol,kmdheight,notarized_height,i,mdata->numpairs,(int32_t)sizeof(hexdata)); break; } item = jitem(pairs,i); - mdata.pairs[i].notarization_height = juint(0,jitem(item,0)); - mdata.pairs[i].MoMoMoffset = juint(0,jitem(item,1)); - len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata.pairs[i].notarization_height); - len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata.pairs[i].MoMoMoffset); + mdata->pairs[i].notarization_height = juint(0,jitem(item,0)); + mdata->pairs[i].MoMoMoffset = juint(0,jitem(item,1)); + len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->pairs[i].notarization_height); + len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->pairs[i].MoMoMoffset); } - if ( i == mdata.numpairs && len*2+1 < hexsize ) + if ( i == mdata->numpairs && len*2+1 < hexsize ) { - init_hexbyte_noT(hexstr,hexdata,len); + init_hexbytes_noT(hexstr,hexdata,len); retval = 0; } else fprintf(stderr,"%s %d %d too much hexdata[%d] for hexstr[%d]\n",symbol,kmdheight,notarized_height,len,hexsize); } @@ -137,7 +137,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccdata,struct komodo_ccdataMoMoM *MoMoMdata) { - bits256 hash; int32_t i; struct komodo_ccdata *ptr; struct notarized_checkpoint *np; + bits256 hash,zero; int32_t i; struct komodo_ccdata *ptr; struct notarized_checkpoint *np; if ( rwflag == 0 ) { // load from disk @@ -150,7 +150,7 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd CC_firstheight = ccdata->MoMdata.height; for (i=0; i<32; i++) hash.bytes[i] = ((uint8_t *)&ccdata->MoMdata.MoM)[31-i]; - char str[65]; fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->MoMdata.notarized_height,bits256_str(str,hash),ccdata->MoMdata.height,ccdata->MoMdata.txi); + fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->MoMdata.notarization_height,hash.ToString().c_str(),ccdata->MoMdata.height,ccdata->MoMdata.txi); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { if ( CC_data != 0 && (CC_data->MoMdata.height > ccdata->MoMdata.height || (CC_data->MoMdata.height == ccdata->MoMdata.height && CC_data->MoMdata.txi >= ccdata->MoMdata.txi)) ) @@ -172,9 +172,10 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd { for (i=0; inumpairs; i++) { - if ( (np= komodo_npptr(MoMoMdata->pairs[i].notarized_height)) != 0 ) + if ( (np= komodo_npptr(MoMoMdata->pairs[i].notarization_height)) != 0 ) { - if ( bits256_nonz(np->MoMoM) == 0 ) + memset(&zero,0,sizeof(zero)); + if ( np->MoMoM == zero ) { np->MoMoM = MoMoMdata->MoMoM; np->MoMoMdepth = MoMoMdata->MoMoMdepth; @@ -182,10 +183,9 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd np->kmdstarti = MoMoMdata->kmdstarti; np->kmdendi = MoMoMdata->kmdendi; } - else if ( bits256_cmp(np->MoMoM,MoMoMdata->MoMoM) != 0 || np->MoMoMdepth != MoMoMdata->MoMoMdepth || np->MoMoMoffset != MoMoMdata->MoMoMoffset || np->kmdstarti != MoMoMdata->kmdstarti || np->kmdendi != MoMoMdata->kmdendi ) + else if ( np->MoMoM != MoMoMdata->MoMoM || np->MoMoMdepth != MoMoMdata->MoMoMdepth || np->MoMoMoffset != MoMoMdata->MoMoMoffset || np->kmdstarti != MoMoMdata->kmdstarti || np->kmdendi != MoMoMdata->kmdendi ) { - char str[65],str2[65]; - fprintf(stderr,"preexisting MoMoM mismatch: %s (%d %d %d %d) vs %s (%d %d %d %d)\n",bits256_str(str,np->MoMoM),np->MoMoMdepth,np->MoMoMoffset,np->kmdstarti,np->kmdendi,bits256_str(str2,MoMoMdata->MoMoM),,MoMoMdata->MoMoMdepth,MoMoMdata->MoMoMoffset,MoMoMdata->kmdstarti,MoMoMdata->kmdendi); + fprintf(stderr,"preexisting MoMoM mismatch: %s (%d %d %d %d) vs %s (%d %d %d %d)\n",np->MoMoM.ToString().c_str(),np->MoMoMdepth,np->MoMoMoffset,np->kmdstarti,np->kmdendi,MoMoMdata->MoMoM.ToString().c_str(),,MoMoMdata->MoMoMdepth,MoMoMdata->MoMoMoffset,MoMoMdata->kmdstarti,MoMoMdata->kmdendi); } } } diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 1c5b6c855..29b8809da 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -423,7 +423,7 @@ int32_t komodo_MoMdata(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,in *MoMoMoffsetp = np->MoMoMoffset; *MoMoMdepthp = np->MoMoMdepth; *kmdstartip = np->kmdstarti; - *kmdendip = np->kmdendip; + *kmdendip = np->kmdendi; return(np->MoMdepth); } *notarized_htp = *MoMoMoffsetp = *MoMoMdepthp = *kmdstartip = *kmdendip = 0; diff --git a/src/komodo_structs.h b/src/komodo_structs.h index 32a630950..23f8752e8 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -100,7 +100,7 @@ struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; struct komodo_ccdataMoMoM { uint256 MoMoM; - int32_t kmdstarti,kmdendi,MoMoMdepth,numpairs,len; + int32_t kmdstarti,kmdendi,MoMoMoffset,MoMoMdepth,numpairs,len; struct komodo_ccdatapair *pairs; }; From 3c302435c9e4e0746e53ec9dd1a637aa1fd29db3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 16:39:28 +0300 Subject: [PATCH 045/507] Fix... --- src/komodo_ccdata.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 162c4b202..b311cd14d 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -175,7 +175,7 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd if ( (np= komodo_npptr(MoMoMdata->pairs[i].notarization_height)) != 0 ) { memset(&zero,0,sizeof(zero)); - if ( np->MoMoM == zero ) + if ( memcmp(&np->MoMoM,&zero,sizeof(np->MoMoM)) == 0 ) { np->MoMoM = MoMoMdata->MoMoM; np->MoMoMdepth = MoMoMdata->MoMoMdepth; @@ -183,7 +183,7 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd np->kmdstarti = MoMoMdata->kmdstarti; np->kmdendi = MoMoMdata->kmdendi; } - else if ( np->MoMoM != MoMoMdata->MoMoM || np->MoMoMdepth != MoMoMdata->MoMoMdepth || np->MoMoMoffset != MoMoMdata->MoMoMoffset || np->kmdstarti != MoMoMdata->kmdstarti || np->kmdendi != MoMoMdata->kmdendi ) + else if ( memcmp(&np->MoMoM,&MoMoMdata->MoMoM,sizeof(np->MoMoM)) != 0 || np->MoMoMdepth != MoMoMdata->MoMoMdepth || np->MoMoMoffset != MoMoMdata->MoMoMoffset || np->kmdstarti != MoMoMdata->kmdstarti || np->kmdendi != MoMoMdata->kmdendi ) { fprintf(stderr,"preexisting MoMoM mismatch: %s (%d %d %d %d) vs %s (%d %d %d %d)\n",np->MoMoM.ToString().c_str(),np->MoMoMdepth,np->MoMoMoffset,np->kmdstarti,np->kmdendi,MoMoMdata->MoMoM.ToString().c_str(),,MoMoMdata->MoMoMdepth,MoMoMdata->MoMoMoffset,MoMoMdata->kmdstarti,MoMoMdata->kmdendi); } From 208608d2f39930f7e2a407488de5141a6c8746df Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 16:40:48 +0300 Subject: [PATCH 046/507] Test --- src/komodo_ccdata.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index b311cd14d..f6b8eb6b3 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -44,7 +44,7 @@ bits256 iguana_merkle(bits256 *tree,int32_t txn_count) int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM *mdata,char *symbol,int32_t kmdheight,int32_t notarized_height) { - cJSON *retjson,*pairs,*item; uint8_t hexdata[8192]; struct komodo_ccdata *ccdata,*tmp; int32_t len,i,retval=-1,max,offset,starti,endi,kmdstarti=0; bits256 *tree=0,MoMoM; + cJSON *retjson,*pairs,*item; uint8_t hexdata[8192]; struct komodo_ccdata *ccdata,*tmp; int32_t len,i,retval=-1,max,offset,starti,endi,kmdstarti=0; bits256 *tree=0; uint256 MoMoM; starti = endi = offset = max = len = 0; hexstr[0] = 0; if ( sizeof(hexdata)*2+1 > hexsize ) @@ -137,7 +137,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccdata,struct komodo_ccdataMoMoM *MoMoMdata) { - bits256 hash,zero; int32_t i; struct komodo_ccdata *ptr; struct notarized_checkpoint *np; + uint256 hash,zero; int32_t i; struct komodo_ccdata *ptr; struct notarized_checkpoint *np; if ( rwflag == 0 ) { // load from disk From d67bdfe9368ce57026c030c5e960ed47d27bb71d Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 16:45:10 +0300 Subject: [PATCH 047/507] fix... --- src/komodo.h | 2 +- src/komodo_ccdata.h | 18 +++++++++--------- src/komodo_structs.h | 2 +- src/rpcblockchain.cpp | 2 +- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 52daaae0e..33ef5c19f 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -654,7 +654,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr MoMoMdata.pairs = (struct komodo_ccdatapair *)calloc(MoMoMdata.numpairs,sizeof(*MoMoMdata.pairs)); for (k=0; kMoMdata.height < kmdheight ) { - fprintf(stderr,"%s notarized.%d kmd.%d\n",ccdata->symbol,ccdata->MoMdata.notarization_height,ccdata->MoMdata.height); + fprintf(stderr,"%s notarized.%d kmd.%d\n",ccdata->symbol,ccdata->MoMdata.notarized_height,ccdata->MoMdata.height); if ( strcmp(ccdata->symbol,symbol) == 0 ) { if ( endi == 0 ) @@ -67,13 +67,13 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM len += iguana_rwnum(1,&hexdata[len],sizeof(ccdata->CCid),(uint8_t *)&ccdata->CCid); endi = ccdata->MoMdata.height; } - if ( (mdata->numpairs == 1 && notarized_height == 0) || ccdata->MoMdata.notarization_height <= notarized_height ) + if ( (mdata->numpairs == 1 && notarized_height == 0) || ccdata->MoMdata.notarized_height <= notarized_height ) { starti = ccdata->MoMdata.height + 1; break; } item = cJSON_CreateArray(); - jaddinum(item,ccdata->MoMdata.notarization_height); + jaddinum(item,ccdata->MoMdata.notarized_height); jaddinum(item,offset); jaddi(pairs,item); mdata->numpairs++; @@ -99,7 +99,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM MoMoM = iguana_merkle(tree,offset); jaddbits256(retjson,(char *)"MoMoM",MoMoM); jaddnum(retjson,(char *)"MoMoMdepth",offset); - if ( mdata->numpairs > 0 && mdata.numpairs == cJSON_GetArraySize(pairs) ) + if ( mdata->numpairs > 0 && mdata->numpairs == cJSON_GetArraySize(pairs) ) { len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->kmdstarti); len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->kmdendi); @@ -115,9 +115,9 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM break; } item = jitem(pairs,i); - mdata->pairs[i].notarization_height = juint(0,jitem(item,0)); - mdata->pairs[i].MoMoMoffset = juint(0,jitem(item,1)); - len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->pairs[i].notarization_height); + mdata->pairs[i].notarized_height = juint(jitem(item,0),0); + mdata->pairs[i].MoMoMoffset = juint(jitem(item,1),0); + len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->pairs[i].notarized_height); len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->pairs[i].MoMoMoffset); } if ( i == mdata->numpairs && len*2+1 < hexsize ) @@ -150,7 +150,7 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd CC_firstheight = ccdata->MoMdata.height; for (i=0; i<32; i++) hash.bytes[i] = ((uint8_t *)&ccdata->MoMdata.MoM)[31-i]; - fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->MoMdata.notarization_height,hash.ToString().c_str(),ccdata->MoMdata.height,ccdata->MoMdata.txi); + fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->MoMdata.notarized_height,hash.ToString().c_str(),ccdata->MoMdata.height,ccdata->MoMdata.txi); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { if ( CC_data != 0 && (CC_data->MoMdata.height > ccdata->MoMdata.height || (CC_data->MoMdata.height == ccdata->MoMdata.height && CC_data->MoMdata.txi >= ccdata->MoMdata.txi)) ) @@ -172,7 +172,7 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd { for (i=0; inumpairs; i++) { - if ( (np= komodo_npptr(MoMoMdata->pairs[i].notarization_height)) != 0 ) + if ( (np= komodo_npptr(MoMoMdata->pairs[i].notarized_height)) != 0 ) { memset(&zero,0,sizeof(zero)); if ( memcmp(&np->MoMoM,&zero,sizeof(np->MoMoM)) == 0 ) diff --git a/src/komodo_structs.h b/src/komodo_structs.h index 23f8752e8..df9cd2154 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -95,7 +95,7 @@ struct komodo_ccdataMoM int32_t MoMdepth,notarized_height,height,txi; }; -struct komodo_ccdatapair { int32_t notarization_height; uint32_t MoMoMoffset; }; +struct komodo_ccdatapair { int32_t notarized_height; uint32_t MoMoMoffset; }; struct komodo_ccdataMoMoM { diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index a003b2c7a..37fbe755e 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -615,7 +615,7 @@ UniValue MoMoMdata(const UniValue& params, bool fHelp) for (i=0; i Date: Thu, 12 Apr 2018 16:47:32 +0300 Subject: [PATCH 048/507] fix... --- src/komodo_ccdata.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index a2267e6de..fa8634f32 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -96,8 +96,9 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM { if ( tree != 0 && offset > 0 ) { - MoMoM = iguana_merkle(tree,offset); - jaddbits256(retjson,(char *)"MoMoM",MoMoM); + tmp = iguana_merkle(tree,offset); + memcpy(&MoMoM,&tmp,sizeof(MoMoM)); + jaddbits256(retjson,(char *)"MoMoM",tmp); jaddnum(retjson,(char *)"MoMoMdepth",offset); if ( mdata->numpairs > 0 && mdata->numpairs == cJSON_GetArraySize(pairs) ) { From 69145d33279c2fcc61fb733b195d1c21144ef018 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 16:48:36 +0300 Subject: [PATCH 049/507] Fix --- src/komodo_ccdata.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index fa8634f32..3f62ab75e 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -186,7 +186,7 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd } else if ( memcmp(&np->MoMoM,&MoMoMdata->MoMoM,sizeof(np->MoMoM)) != 0 || np->MoMoMdepth != MoMoMdata->MoMoMdepth || np->MoMoMoffset != MoMoMdata->MoMoMoffset || np->kmdstarti != MoMoMdata->kmdstarti || np->kmdendi != MoMoMdata->kmdendi ) { - fprintf(stderr,"preexisting MoMoM mismatch: %s (%d %d %d %d) vs %s (%d %d %d %d)\n",np->MoMoM.ToString().c_str(),np->MoMoMdepth,np->MoMoMoffset,np->kmdstarti,np->kmdendi,MoMoMdata->MoMoM.ToString().c_str(),,MoMoMdata->MoMoMdepth,MoMoMdata->MoMoMoffset,MoMoMdata->kmdstarti,MoMoMdata->kmdendi); + fprintf(stderr,"preexisting MoMoM mismatch: %s (%d %d %d %d) vs %s (%d %d %d %d)\n",np->MoMoM.ToString().c_str(),np->MoMoMdepth,np->MoMoMoffset,np->kmdstarti,np->kmdendi,MoMoMdata->MoMoM.ToString().c_str(),MoMoMdata->MoMoMdepth,MoMoMdata->MoMoMoffset,MoMoMdata->kmdstarti,MoMoMdata->kmdendi); } } } From b54773f0d7e0b94ade16c28048c2e2ccd1ba764f Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 16:50:49 +0300 Subject: [PATCH 050/507] fix... --- src/komodo_ccdata.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 3f62ab75e..5a32fb346 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -138,7 +138,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccdata,struct komodo_ccdataMoMoM *MoMoMdata) { - uint256 hash,zero; int32_t i; struct komodo_ccdata *ptr; struct notarized_checkpoint *np; + uint256 hash,zero; bits256 tmp; int32_t i; struct komodo_ccdata *ptr; struct notarized_checkpoint *np; if ( rwflag == 0 ) { // load from disk @@ -150,7 +150,8 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd if ( ccdata->MoMdata.height > 0 && (CC_firstheight == 0 || ccdata->MoMdata.height < CC_firstheight) ) CC_firstheight = ccdata->MoMdata.height; for (i=0; i<32; i++) - hash.bytes[i] = ((uint8_t *)&ccdata->MoMdata.MoM)[31-i]; + tmp.bytes[i] = ((uint8_t *)&ccdata->MoMdata.MoM)[31-i]; + memcpy(&hash,&tmp,sizeof(hash)); fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->MoMdata.notarized_height,hash.ToString().c_str(),ccdata->MoMdata.height,ccdata->MoMdata.txi); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { From 0ecf0707161d41720d6432539f708bdd6e99cf2a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 16:52:21 +0300 Subject: [PATCH 051/507] Fix --- src/komodo_ccdata.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 5a32fb346..a512ed6ff 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -44,7 +44,7 @@ bits256 iguana_merkle(bits256 *tree,int32_t txn_count) int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM *mdata,char *symbol,int32_t kmdheight,int32_t notarized_height) { - cJSON *retjson,*pairs,*item; uint8_t hexdata[8192]; struct komodo_ccdata *ccdata,*tmp; int32_t len,i,retval=-1,max,offset,starti,endi,kmdstarti=0; bits256 *tree=0; uint256 MoMoM; + cJSON *retjson,*pairs,*item; uint8_t hexdata[8192]; struct komodo_ccdata *ccdata,*tmpptr; int32_t len,i,retval=-1,max,offset,starti,endi,kmdstarti=0; bits256 *tree=0,tmp; uint256 MoMoM; starti = endi = offset = max = len = 0; hexstr[0] = 0; if ( sizeof(hexdata)*2+1 > hexsize ) @@ -55,7 +55,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM pairs = cJSON_CreateArray(); memset(mdata,0,sizeof(*mdata)); portable_mutex_lock(&KOMODO_CC_mutex); - DL_FOREACH_SAFE(CC_data,ccdata,tmp) + DL_FOREACH_SAFE(CC_data,ccdata,tmpptr) { if ( ccdata->MoMdata.height < kmdheight ) { From 28d820d72fdcafcf90d8aecf6ea948d46581c3f5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 16:56:12 +0300 Subject: [PATCH 052/507] fix... --- src/rpcblockchain.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 37fbe755e..b0d734ea7 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -593,7 +593,7 @@ UniValue kvsearch(const UniValue& params, bool fHelp) UniValue MoMoMdata(const UniValue& params, bool fHelp) { - char *symbol,hexstr[16384+1]; struct komodo_MoMoMdata mdata; int32_t kmdheight,notarized_height; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); + char *symbol,hexstr[16384+1]; struct komodo_ccdataMoMoM mdata; int32_t i,kmdheight,notarized_height; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); if ( fHelp || params.size() != 3 ) throw runtime_error("MoMoMdata symbol kmdheight notarized_height\n"); LOCK(cs_main); From 602c7d4649e1eed09ee9eb4e55b191d4515e1724 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 17:00:39 +0300 Subject: [PATCH 053/507] fix --- src/rpcblockchain.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index b0d734ea7..b3cce892f 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -615,13 +615,13 @@ UniValue MoMoMdata(const UniValue& params, bool fHelp) for (i=0; i Date: Thu, 12 Apr 2018 17:01:34 +0300 Subject: [PATCH 054/507] Fix --- src/rpcblockchain.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index b3cce892f..b965b8138 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -614,7 +614,7 @@ UniValue MoMoMdata(const UniValue& params, bool fHelp) { for (i=0; i Date: Thu, 12 Apr 2018 17:02:33 +0300 Subject: [PATCH 055/507] Fix --- src/rpcblockchain.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index b965b8138..90838c4a9 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -615,8 +615,8 @@ UniValue MoMoMdata(const UniValue& params, bool fHelp) for (i=0; i Date: Thu, 12 Apr 2018 17:03:07 +0300 Subject: [PATCH 056/507] ) --- src/rpcblockchain.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 90838c4a9..0115c8c22 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -616,7 +616,7 @@ UniValue MoMoMdata(const UniValue& params, bool fHelp) { UniValue item(UniValue::VOBJ); item.push_back(Pair("height",(int)mdata.pairs[i].notarized_height)); - item.push_back(Pair("MoMoMoffset",(int)mdata.pairs[i].MoMoMoffset); + item.push_back(Pair("MoMoMoffset",(int)mdata.pairs[i].MoMoMoffset)); a.push_back(item); } free(mdata.pairs); From 9a92a030d627b579799a5298e56df683d5b8503f Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 17:11:32 +0300 Subject: [PATCH 057/507] Debug --- src/komodo_ccdata.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index a512ed6ff..6c746c21e 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -132,7 +132,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM if ( tree != 0 ) free(tree); jadd(retjson,(char *)"offsets",pairs); - fprintf(stderr,"%s\n",jprint(retjson,0)); + fprintf(stderr,"%s\n",jprint(retjson,1)); return(retval); } From 0a1455d21da64aac01925ab367e513c74a08dfd4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 17:20:53 +0300 Subject: [PATCH 058/507] Debug --- src/komodo_ccdata.h | 2 ++ src/rpcblockchain.cpp | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 6c746c21e..11ba2b347 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -108,6 +108,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->MoMoMdepth); len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->numpairs); mdata->pairs = (struct komodo_ccdatapair *)calloc(mdata->numpairs,sizeof(*mdata->pairs)); + fprintf(stderr,"pairs allocated to %p num.%d\n",mdata->pairs,mdata->numpairs); for (i=0; inumpairs; i++) { if ( len + sizeof(uint32_t)*2 > sizeof(hexdata) ) @@ -124,6 +125,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM if ( i == mdata->numpairs && len*2+1 < hexsize ) { init_hexbytes_noT(hexstr,hexdata,len); + jadd(retjson,(char *)"data",hexstr); retval = 0; } else fprintf(stderr,"%s %d %d too much hexdata[%d] for hexstr[%d]\n",symbol,kmdheight,notarized_height,len,hexsize); } diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 0115c8c22..8b296a66b 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -603,6 +603,7 @@ UniValue MoMoMdata(const UniValue& params, bool fHelp) ret.push_back(Pair("coin",symbol)); ret.push_back(Pair("kmdheight",kmdheight)); ret.push_back(Pair("notarized_height",notarized_height)); + memset(&mdata,0,sizeof(mdata)); if ( komodo_MoMoMdata(hexstr,sizeof(hexstr),&mdata,symbol,kmdheight,notarized_height) == 0 ) { ret.push_back(Pair("kmdstarti",mdata.kmdstarti)); @@ -612,6 +613,7 @@ UniValue MoMoMdata(const UniValue& params, bool fHelp) ret.push_back(Pair("numnotarizations",mdata.numpairs)); if ( mdata.pairs != 0 ) { + fprintf(stderr,"mdata.pairs free %p, numpairs.%d\n",mdata.pairs,mdata.numpairs); for (i=0; i Date: Thu, 12 Apr 2018 17:52:30 +0300 Subject: [PATCH 059/507] Test --- src/komodo_ccdata.h | 35 +++++++++++++++-------------------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 11ba2b347..78568732e 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -44,15 +44,14 @@ bits256 iguana_merkle(bits256 *tree,int32_t txn_count) int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM *mdata,char *symbol,int32_t kmdheight,int32_t notarized_height) { - cJSON *retjson,*pairs,*item; uint8_t hexdata[8192]; struct komodo_ccdata *ccdata,*tmpptr; int32_t len,i,retval=-1,max,offset,starti,endi,kmdstarti=0; bits256 *tree=0,tmp; uint256 MoMoM; - starti = endi = offset = max = len = 0; + uint8_t hexdata[8192]; struct komodo_ccdata *ccdata,*tmpptr; int32_t len,maxpairs,i,retval=-1,max,offset,starti,endi; bits256 *tree=0,tmp; uint256 MoMoM; + starti = endi = offset = max = len = maxpairs = 0; hexstr[0] = 0; if ( sizeof(hexdata)*2+1 > hexsize ) { fprintf(stderr,"hexsize.%d too small for %d\n",hexsize,(int32_t)sizeof(hexdata)); return(-1); } - pairs = cJSON_CreateArray(); memset(mdata,0,sizeof(*mdata)); portable_mutex_lock(&KOMODO_CC_mutex); DL_FOREACH_SAFE(CC_data,ccdata,tmpptr) @@ -72,10 +71,14 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM starti = ccdata->MoMdata.height + 1; break; } - item = cJSON_CreateArray(); - jaddinum(item,ccdata->MoMdata.notarized_height); - jaddinum(item,offset); - jaddi(pairs,item); + if ( mdata->numpairs >= maxpairs ) + { + maxpairs += 100; + mdata->pairs = (struct komodo_ccdatapair *)realloc(mdata->pairs,sizeof(*mdata->pairs)*maxpairs); + fprintf(stderr,"pairs reallocated to %p num.%d\n",mdata->pairs,mdata->numpairs); + } + mdata->pairs[mdata->numpairs].notarized_height = ccdata->MoMdata.notarized_height; + mdata->pairs[mdata->numpairs].MoMoMoffset = offset; mdata->numpairs++; } if ( offset >= max ) @@ -89,17 +92,16 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM } } portable_mutex_unlock(&KOMODO_CC_mutex); - retjson = cJSON_CreateObject(); - jaddnum(retjson,(char *)"kmdstarti",starti); - jaddnum(retjson,(char *)"kmdendi",endi); + mdata->kmdstarti = starti; + mdata->kmdendi = endi; if ( starti != 0 && endi != 0 && endi >= starti ) { if ( tree != 0 && offset > 0 ) { tmp = iguana_merkle(tree,offset); memcpy(&MoMoM,&tmp,sizeof(MoMoM)); - jaddbits256(retjson,(char *)"MoMoM",tmp); - jaddnum(retjson,(char *)"MoMoMdepth",offset); + mdata->MoMoM = MoMoM; + mdata->MoMoMdepth = offset; if ( mdata->numpairs > 0 && mdata->numpairs == cJSON_GetArraySize(pairs) ) { len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->kmdstarti); @@ -107,8 +109,6 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM len += iguana_rwbignum(1,&hexdata[len],sizeof(mdata->MoMoM),(uint8_t *)&mdata->MoMoM); len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->MoMoMdepth); len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->numpairs); - mdata->pairs = (struct komodo_ccdatapair *)calloc(mdata->numpairs,sizeof(*mdata->pairs)); - fprintf(stderr,"pairs allocated to %p num.%d\n",mdata->pairs,mdata->numpairs); for (i=0; inumpairs; i++) { if ( len + sizeof(uint32_t)*2 > sizeof(hexdata) ) @@ -116,16 +116,13 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM fprintf(stderr,"%s %d %d i.%d of %d exceeds hexdata.%d\n",symbol,kmdheight,notarized_height,i,mdata->numpairs,(int32_t)sizeof(hexdata)); break; } - item = jitem(pairs,i); - mdata->pairs[i].notarized_height = juint(jitem(item,0),0); - mdata->pairs[i].MoMoMoffset = juint(jitem(item,1),0); len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->pairs[i].notarized_height); len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->pairs[i].MoMoMoffset); } if ( i == mdata->numpairs && len*2+1 < hexsize ) { init_hexbytes_noT(hexstr,hexdata,len); - jadd(retjson,(char *)"data",hexstr); + fprintf(stderr,"hexstr.(%s)\n",hexstr); retval = 0; } else fprintf(stderr,"%s %d %d too much hexdata[%d] for hexstr[%d]\n",symbol,kmdheight,notarized_height,len,hexsize); } @@ -133,8 +130,6 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM } if ( tree != 0 ) free(tree); - jadd(retjson,(char *)"offsets",pairs); - fprintf(stderr,"%s\n",jprint(retjson,1)); return(retval); } From becfd453e97ec038141d58e2ecf7fc3357461b37 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 17:53:20 +0300 Subject: [PATCH 060/507] Test --- src/komodo_ccdata.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 78568732e..e749fd308 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -102,7 +102,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM memcpy(&MoMoM,&tmp,sizeof(MoMoM)); mdata->MoMoM = MoMoM; mdata->MoMoMdepth = offset; - if ( mdata->numpairs > 0 && mdata->numpairs == cJSON_GetArraySize(pairs) ) + if ( mdata->numpairs > 0 ) { len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->kmdstarti); len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->kmdendi); From 5877c76ea2eab4081d3d525f6bcbccb81a579e7a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 18:02:32 +0300 Subject: [PATCH 061/507] Test --- src/komodo_ccdata.h | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index e749fd308..68a45e3d8 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -85,9 +85,10 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM { max += 100; tree = (bits256 *)realloc(tree,sizeof(*tree)*max); - //fprintf(stderr,"tree reallocated to %p max.%d\n",tree,max); + fprintf(stderr,"tree reallocated to %p max.%d\n",tree,max); } - memcpy(&tree[offset++],&ccdata->MoMdata.MoM,sizeof(bits256)); + memcpy(&tree[offset],&ccdata->MoMdata.MoM,sizeof(bits256)); + offset++; starti = ccdata->MoMdata.height; } } @@ -98,6 +99,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM { if ( tree != 0 && offset > 0 ) { + tree = (bits256 *)realloc(tree,sizeof(*tree)*(offset * 3)); tmp = iguana_merkle(tree,offset); memcpy(&MoMoM,&tmp,sizeof(MoMoM)); mdata->MoMoM = MoMoM; @@ -129,7 +131,10 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM } } if ( tree != 0 ) + { + fprintf(stderr,"free tree.%p\n",tree); free(tree); + } return(retval); } From 5740b2aa6b81fa2341adb092b00605e9f25270aa Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 18:45:25 +0300 Subject: [PATCH 062/507] Add allMoMs --- src/komodo_ccdata.h | 48 +++++++++++++++++++++++++++++++++++++++---- src/komodo_structs.h | 3 ++- src/rpcblockchain.cpp | 33 ++++++++++++++++++++++++++++- src/rpcclient.cpp | 1 + src/rpcserver.cpp | 1 + src/rpcserver.h | 1 + 6 files changed, 81 insertions(+), 6 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 68a45e3d8..f08a13a71 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -42,6 +42,44 @@ bits256 iguana_merkle(bits256 *tree,int32_t txn_count) return(tree[n]); } +struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t *MoMoMdepthp,int32_t kmdstarti,int32_t kmdendi) +{ + struct komodo_ccdata_entry *allMoMs=0; bits256 *tree,tmp; struct komodo_ccdata *ccdata,*tmpptr; int32_t i,num,max; + num = max = 0; + portable_mutex_lock(&KOMODO_CC_mutex); + DL_FOREACH_SAFE(CC_data,ccdata,tmpptr) + { + if ( ccdata->MoMdata.height <= kmdendi && ccdata->MoMdata.height >= kmdstarti ) + { + if ( num >= max ) + { + max += 100; + allMoMs = (struct komodo_ccdata_entry *)realloc(allMoMs,max * sizeof(*allMoMs)); + } + allMoMs[num].MoM = ccdata->MoMdata.MoM; + allMoMs[num].notarized_height = ccdata->MoMdata.notarized_height; + allMoMs[num].height = ccdata->MoMdata.height; + allMoMs[num].txi = ccdata->MoMdata.txi; + strcpy(allMoMs[num].symbol,ccdata->symbol); + num++; + } + } + if ( (*nump= num) > 0 ) + { + tree = (bits256 *)calloc(sizeof(bits256),num*3); + for (i=0; inumpairs == 1 && notarized_height == 0) || ccdata->MoMdata.notarized_height <= notarized_height ) { starti = ccdata->MoMdata.height + 1; + if ( notarized_height == 0 ) + notarized_height = ccdata->MoMdata.notarized_height; break; } if ( mdata->numpairs >= maxpairs ) { maxpairs += 100; mdata->pairs = (struct komodo_ccdatapair *)realloc(mdata->pairs,sizeof(*mdata->pairs)*maxpairs); - fprintf(stderr,"pairs reallocated to %p num.%d\n",mdata->pairs,mdata->numpairs); + //fprintf(stderr,"pairs reallocated to %p num.%d\n",mdata->pairs,mdata->numpairs); } mdata->pairs[mdata->numpairs].notarized_height = ccdata->MoMdata.notarized_height; mdata->pairs[mdata->numpairs].MoMoMoffset = offset; @@ -85,7 +125,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM { max += 100; tree = (bits256 *)realloc(tree,sizeof(*tree)*max); - fprintf(stderr,"tree reallocated to %p max.%d\n",tree,max); + //fprintf(stderr,"tree reallocated to %p max.%d\n",tree,max); } memcpy(&tree[offset],&ccdata->MoMdata.MoM,sizeof(bits256)); offset++; @@ -124,7 +164,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM if ( i == mdata->numpairs && len*2+1 < hexsize ) { init_hexbytes_noT(hexstr,hexdata,len); - fprintf(stderr,"hexstr.(%s)\n",hexstr); + //fprintf(stderr,"hexstr.(%s)\n",hexstr); retval = 0; } else fprintf(stderr,"%s %d %d too much hexdata[%d] for hexstr[%d]\n",symbol,kmdheight,notarized_height,len,hexsize); } @@ -132,7 +172,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM } if ( tree != 0 ) { - fprintf(stderr,"free tree.%p\n",tree); + //fprintf(stderr,"free tree.%p\n",tree); free(tree); } return(retval); diff --git a/src/komodo_structs.h b/src/komodo_structs.h index df9cd2154..634edf74c 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -95,7 +95,8 @@ struct komodo_ccdataMoM int32_t MoMdepth,notarized_height,height,txi; }; -struct komodo_ccdatapair { int32_t notarized_height; uint32_t MoMoMoffset; }; +struct komodo_ccdata_entry { uint256 MoM; int32_t notarized_height,height,txi; char symbol[65]; }; +struct komodo_ccdatapair { int32_t notarized_height,MoMoMoffset; }; struct komodo_ccdataMoMoM { diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 8b296a66b..770feb4e7 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -555,6 +555,7 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width); int32_t komodo_kvsearch(uint256 *refpubkeyp,int32_t current_height,uint32_t *flagsp,int32_t *heightp,uint8_t value[IGUANA_MAXSCRIPTSIZE],uint8_t *key,int32_t keylen); int32_t komodo_MoM(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip); int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM *mdata,char *symbol,int32_t kmdheight,int32_t notarized_height); +struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,int32_t kmdstarti,int32_t kmdendi); UniValue kvsearch(const UniValue& params, bool fHelp) { @@ -591,6 +592,36 @@ UniValue kvsearch(const UniValue& params, bool fHelp) return ret; } +struct komodo_ccdata_entry { uint256 MoM; int32_t notarized_height,height,txi; char symbol[65]; }; + +UniValue allMoMs(const UniValue& params, bool fHelp) +{ + struct komodo_ccdata_entry *allMoMs; uint256 MoMoM; int32_t num,i,kmdstarti,kmdendi; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); + if ( fHelp || params.size() != 2 ) + throw runtime_error("allMoMs kmdstarti kmdendi\n"); + LOCK(cs_main); + kmdstarti = atoi(params[0].get_str().c_str()); + kmdendi = atoi(params[1].get_str().c_str()); + ret.push_back(Pair("kmdstarti",kmdstarti)); + ret.push_back(Pair("kmdendi",kmdendi)); + if ( (allMoMs= komodo_allMoMs(&num,&MoMoM,&MoMoMdepth,kmdstarti,kmdendi)) != 0 ) + { + for (i=0; i Date: Thu, 12 Apr 2018 18:50:03 +0300 Subject: [PATCH 063/507] Test --- src/komodo_ccdata.h | 2 +- src/rpcblockchain.cpp | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index f08a13a71..8572e8aa5 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -42,7 +42,7 @@ bits256 iguana_merkle(bits256 *tree,int32_t txn_count) return(tree[n]); } -struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t *MoMoMdepthp,int32_t kmdstarti,int32_t kmdendi) +struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t kmdstarti,int32_t kmdendi) { struct komodo_ccdata_entry *allMoMs=0; bits256 *tree,tmp; struct komodo_ccdata *ccdata,*tmpptr; int32_t i,num,max; num = max = 0; diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 770feb4e7..816e32096 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -592,8 +592,6 @@ UniValue kvsearch(const UniValue& params, bool fHelp) return ret; } -struct komodo_ccdata_entry { uint256 MoM; int32_t notarized_height,height,txi; char symbol[65]; }; - UniValue allMoMs(const UniValue& params, bool fHelp) { struct komodo_ccdata_entry *allMoMs; uint256 MoMoM; int32_t num,i,kmdstarti,kmdendi; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); @@ -604,19 +602,21 @@ UniValue allMoMs(const UniValue& params, bool fHelp) kmdendi = atoi(params[1].get_str().c_str()); ret.push_back(Pair("kmdstarti",kmdstarti)); ret.push_back(Pair("kmdendi",kmdendi)); - if ( (allMoMs= komodo_allMoMs(&num,&MoMoM,&MoMoMdepth,kmdstarti,kmdendi)) != 0 ) + if ( (allMoMs= komodo_allMoMs(&num,&MoMoM,kmdstarti,kmdendi)) != 0 ) { for (i=0; i Date: Thu, 12 Apr 2018 18:52:16 +0300 Subject: [PATCH 064/507] Test --- src/komodo_ccdata.h | 2 +- src/komodo_structs.h | 2 +- src/rpcblockchain.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 8572e8aa5..30bd858a0 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -58,7 +58,7 @@ struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t } allMoMs[num].MoM = ccdata->MoMdata.MoM; allMoMs[num].notarized_height = ccdata->MoMdata.notarized_height; - allMoMs[num].height = ccdata->MoMdata.height; + allMoMs[num].kmdheight = ccdata->MoMdata.height; allMoMs[num].txi = ccdata->MoMdata.txi; strcpy(allMoMs[num].symbol,ccdata->symbol); num++; diff --git a/src/komodo_structs.h b/src/komodo_structs.h index 634edf74c..383d2fa9c 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -92,7 +92,7 @@ struct notarized_checkpoint struct komodo_ccdataMoM { uint256 MoM; - int32_t MoMdepth,notarized_height,height,txi; + int32_t MoMdepth,notarized_height,kmdheight,txi; }; struct komodo_ccdata_entry { uint256 MoM; int32_t notarized_height,height,txi; char symbol[65]; }; diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 816e32096..d49068295 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -555,7 +555,7 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width); int32_t komodo_kvsearch(uint256 *refpubkeyp,int32_t current_height,uint32_t *flagsp,int32_t *heightp,uint8_t value[IGUANA_MAXSCRIPTSIZE],uint8_t *key,int32_t keylen); int32_t komodo_MoM(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip); int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM *mdata,char *symbol,int32_t kmdheight,int32_t notarized_height); -struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,int32_t kmdstarti,int32_t kmdendi); +struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t kmdstarti,int32_t kmdendi); UniValue kvsearch(const UniValue& params, bool fHelp) { From 623d2effad0bbc63358bcf29fa946b066528fa70 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 18:53:33 +0300 Subject: [PATCH 065/507] Test --- src/komodo_structs.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_structs.h b/src/komodo_structs.h index 383d2fa9c..3d8f50718 100644 --- a/src/komodo_structs.h +++ b/src/komodo_structs.h @@ -92,10 +92,10 @@ struct notarized_checkpoint struct komodo_ccdataMoM { uint256 MoM; - int32_t MoMdepth,notarized_height,kmdheight,txi; + int32_t MoMdepth,notarized_height,height,txi; }; -struct komodo_ccdata_entry { uint256 MoM; int32_t notarized_height,height,txi; char symbol[65]; }; +struct komodo_ccdata_entry { uint256 MoM; int32_t notarized_height,kmdheight,txi; char symbol[65]; }; struct komodo_ccdatapair { int32_t notarized_height,MoMoMoffset; }; struct komodo_ccdataMoMoM From 0fc422817520f19494e42e617327c9f69e25530e Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 19:33:36 +0300 Subject: [PATCH 066/507] Have MoMoMdata use allMoMs --- src/komodo_ccdata.h | 59 +++++++++++++++++++++------------------------ 1 file changed, 28 insertions(+), 31 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 30bd858a0..3a4bbbda1 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -63,6 +63,8 @@ struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t strcpy(allMoMs[num].symbol,ccdata->symbol); num++; } + if ( ccdata->MoMdata.height < kmdstarti ) + break; } if ( (*nump= num) > 0 ) { @@ -80,10 +82,23 @@ struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t return(allMoMs); } +int32_t komodo_addpair(struct komodo_ccdataMoMoM *mdata,int32_t notarized_height,int32_t offset,int32_t maxpairs) +{ + if ( mdata->numpairs >= maxpairs ) + { + maxpairs += 100; + mdata->pairs = (struct komodo_ccdatapair *)realloc(mdata->pairs,sizeof(*mdata->pairs)*maxpairs); + //fprintf(stderr,"pairs reallocated to %p num.%d\n",mdata->pairs,mdata->numpairs); + } + mdata->pairs[mdata->numpairs].notarized_height = notarized_height; + mdata->pairs[mdata->numpairs].MoMoMoffset = offset; + mdata->numpairs++; +} + int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM *mdata,char *symbol,int32_t kmdheight,int32_t notarized_height) { - uint8_t hexdata[8192]; struct komodo_ccdata *ccdata,*tmpptr; int32_t len,maxpairs,i,retval=-1,max,offset,starti,endi; bits256 *tree=0,tmp; uint256 MoMoM; - starti = endi = offset = max = len = maxpairs = 0; + uint8_t hexdata[8192]; struct komodo_ccdata *ccdata,*tmpptr; int32_t len,maxpairs,i,retval=-1,depth,starti,endi,CCid=0; struct komodo_ccdata_entry *allMoMs; + starti = endi = depth = len = maxpairs = 0; hexstr[0] = 0; if ( sizeof(hexdata)*2+1 > hexsize ) { @@ -96,13 +111,13 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM { if ( ccdata->MoMdata.height < kmdheight ) { - fprintf(stderr,"%s notarized.%d kmd.%d\n",ccdata->symbol,ccdata->MoMdata.notarized_height,ccdata->MoMdata.height); + //fprintf(stderr,"%s notarized.%d kmd.%d\n",ccdata->symbol,ccdata->MoMdata.notarized_height,ccdata->MoMdata.height); if ( strcmp(ccdata->symbol,symbol) == 0 ) { if ( endi == 0 ) { - len += iguana_rwnum(1,&hexdata[len],sizeof(ccdata->CCid),(uint8_t *)&ccdata->CCid); endi = ccdata->MoMdata.height; + CCid = ccdata->CCid; } if ( (mdata->numpairs == 1 && notarized_height == 0) || ccdata->MoMdata.notarized_height <= notarized_height ) { @@ -111,24 +126,7 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM notarized_height = ccdata->MoMdata.notarized_height; break; } - if ( mdata->numpairs >= maxpairs ) - { - maxpairs += 100; - mdata->pairs = (struct komodo_ccdatapair *)realloc(mdata->pairs,sizeof(*mdata->pairs)*maxpairs); - //fprintf(stderr,"pairs reallocated to %p num.%d\n",mdata->pairs,mdata->numpairs); - } - mdata->pairs[mdata->numpairs].notarized_height = ccdata->MoMdata.notarized_height; - mdata->pairs[mdata->numpairs].MoMoMoffset = offset; - mdata->numpairs++; } - if ( offset >= max ) - { - max += 100; - tree = (bits256 *)realloc(tree,sizeof(*tree)*max); - //fprintf(stderr,"tree reallocated to %p max.%d\n",tree,max); - } - memcpy(&tree[offset],&ccdata->MoMdata.MoM,sizeof(bits256)); - offset++; starti = ccdata->MoMdata.height; } } @@ -137,15 +135,18 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM mdata->kmdendi = endi; if ( starti != 0 && endi != 0 && endi >= starti ) { - if ( tree != 0 && offset > 0 ) + if ( (allMoMs= komodo_allMoMs(&depth,MoMoMp,starti,endi)) != 0 ) { - tree = (bits256 *)realloc(tree,sizeof(*tree)*(offset * 3)); - tmp = iguana_merkle(tree,offset); - memcpy(&MoMoM,&tmp,sizeof(MoMoM)); mdata->MoMoM = MoMoM; - mdata->MoMoMdepth = offset; + mdata->MoMoMdepth = depth; + for (i=0; inumpairs > 0 ) { + len += iguana_rwnum(1,&hexdata[len],sizeof(CCid),(uint8_t *)&CCid); len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->kmdstarti); len += iguana_rwnum(1,&hexdata[len],sizeof(uint32_t),(uint8_t *)&mdata->kmdendi); len += iguana_rwbignum(1,&hexdata[len],sizeof(mdata->MoMoM),(uint8_t *)&mdata->MoMoM); @@ -168,13 +169,9 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM retval = 0; } else fprintf(stderr,"%s %d %d too much hexdata[%d] for hexstr[%d]\n",symbol,kmdheight,notarized_height,len,hexsize); } + free(allMoMs); } } - if ( tree != 0 ) - { - //fprintf(stderr,"free tree.%p\n",tree); - free(tree); - } return(retval); } From e7c626c2729b1b17988b13fddcf9fc2c266265de Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 19:34:46 +0300 Subject: [PATCH 067/507] Test --- src/komodo_ccdata.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 3a4bbbda1..dfa800c53 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -135,9 +135,8 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM mdata->kmdendi = endi; if ( starti != 0 && endi != 0 && endi >= starti ) { - if ( (allMoMs= komodo_allMoMs(&depth,MoMoMp,starti,endi)) != 0 ) + if ( (allMoMs= komodo_allMoMs(&depth,&mdata->MoMoM,starti,endi)) != 0 ) { - mdata->MoMoM = MoMoM; mdata->MoMoMdepth = depth; for (i=0; i Date: Thu, 12 Apr 2018 19:42:47 +0300 Subject: [PATCH 068/507] Test --- src/komodo_ccdata.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index dfa800c53..84f9c65d1 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -66,6 +66,7 @@ struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t if ( ccdata->MoMdata.height < kmdstarti ) break; } + portable_mutex_unlock(&KOMODO_CC_mutex); if ( (*nump= num) > 0 ) { tree = (bits256 *)calloc(sizeof(bits256),num*3); From 816d95d586a0feb6fcf38744e793e208c8194f34 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 20:01:50 +0300 Subject: [PATCH 069/507] Test --- src/komodo_events.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/komodo_events.h b/src/komodo_events.h index ef09c4bbf..3d60e4074 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -171,6 +171,7 @@ void komodo_eventadd_kmdheight(struct komodo_state *sp,char *symbol,int32_t heig } else { + fprintf(stderr,"REWIND kmdheight.%d\n",kmdheight); kmdheight = -kmdheight; komodo_eventadd(sp,height,symbol,KOMODO_EVENT_REWIND,(uint8_t *)&height,sizeof(height)); if ( sp != 0 ) From dfd07d78784f842862864979eed84869aa0ffeea Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 20:13:36 +0300 Subject: [PATCH 070/507] Reorg ccdata --- src/komodo.h | 4 ++++ src/komodo_ccdata.h | 23 +++++++++++++++++++++++ src/komodo_events.h | 2 +- 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 33ef5c19f..c6060568c 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -797,7 +797,11 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block) else { if ( pindex->nHeight != hwmheight ) + { printf("%s hwmheight.%d vs pindex->nHeight.%d t.%u reorg.%d\n",ASSETCHAINS_SYMBOL,hwmheight,pindex->nHeight,(uint32_t)pindex->nTime,hwmheight-pindex->nHeight); + komodo_purge_ccdata((int32_t)pindex->nHeight); + hwmheight = pindex->nHeight; + } komodo_event_rewind(sp,symbol,pindex->nHeight); komodo_stateupdate(pindex->nHeight,0,0,0,zero,0,0,0,0,-pindex->nHeight,pindex->nTime,0,0,0,0,zero,0); } diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 84f9c65d1..2692923b9 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -175,6 +175,29 @@ int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM return(retval); } +void komodo_purge_ccdata(int32_t height) +{ + struct komodo_ccdata *ccdata,*tmpptr; + if ( ASSETCHAINS_SYMBOL[0] == 0 ) + { + portable_mutex_lock(&KOMODO_CC_mutex); + DL_FOREACH_SAFE(CC_data,ccdata,tmpptr) + { + if ( ccdata->MoMdata.height >= height ) + { + printf("PURGE %s notarized.%d\n",ccdata->MoMdata.symbol,ccdata->MoMdata.notarized_height); + DL_DELETE(ccdata); + free(ccdata); + } + } + portable_mutex_unlock(&KOMODO_CC_mutex); + } + else + { + // purge notarized data + } +} + int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccdata,struct komodo_ccdataMoMoM *MoMoMdata) { uint256 hash,zero; bits256 tmp; int32_t i; struct komodo_ccdata *ptr; struct notarized_checkpoint *np; diff --git a/src/komodo_events.h b/src/komodo_events.h index 3d60e4074..0ced206ac 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -171,7 +171,7 @@ void komodo_eventadd_kmdheight(struct komodo_state *sp,char *symbol,int32_t heig } else { - fprintf(stderr,"REWIND kmdheight.%d\n",kmdheight); + //fprintf(stderr,"REWIND kmdheight.%d\n",kmdheight); kmdheight = -kmdheight; komodo_eventadd(sp,height,symbol,KOMODO_EVENT_REWIND,(uint8_t *)&height,sizeof(height)); if ( sp != 0 ) From e2563215782ef0fcd740cf16a71ddd54c9e5ff8a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 20:15:42 +0300 Subject: [PATCH 071/507] Test --- src/komodo_ccdata.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 2692923b9..cb9739945 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -186,7 +186,7 @@ void komodo_purge_ccdata(int32_t height) if ( ccdata->MoMdata.height >= height ) { printf("PURGE %s notarized.%d\n",ccdata->MoMdata.symbol,ccdata->MoMdata.notarized_height); - DL_DELETE(ccdata); + DL_DELETE(CC_data,ccdata); free(ccdata); } } From 20eaf8aaf3e94a9f88d3b1241cb64860c1b68c98 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 20:25:23 +0300 Subject: [PATCH 072/507] Test --- src/komodo_ccdata.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index cb9739945..8e233797f 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -185,7 +185,7 @@ void komodo_purge_ccdata(int32_t height) { if ( ccdata->MoMdata.height >= height ) { - printf("PURGE %s notarized.%d\n",ccdata->MoMdata.symbol,ccdata->MoMdata.notarized_height); + printf("PURGE %s notarized.%d\n",ccdata->symbol,ccdata->MoMdata.notarized_height); DL_DELETE(CC_data,ccdata); free(ccdata); } From 667a4eb3fa1d789137667a3b9e9833c664e0feb8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 20:35:36 +0300 Subject: [PATCH 073/507] Test --- src/komodo_ccdata.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 8e233797f..1c324e4ea 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -188,7 +188,7 @@ void komodo_purge_ccdata(int32_t height) printf("PURGE %s notarized.%d\n",ccdata->symbol,ccdata->MoMdata.notarized_height); DL_DELETE(CC_data,ccdata); free(ccdata); - } + } else break; } portable_mutex_unlock(&KOMODO_CC_mutex); } From 835c1c0256720192e1f128a51614c54f1bead45a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 20:47:56 +0300 Subject: [PATCH 074/507] Test --- src/komodo.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index c6060568c..1076674dc 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -574,7 +574,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } else { - if ( strcmp(ASSETCHAINS_SYMBOL,(char *)&scriptbuf[len+offset]) == 0 ) + if ( strcmp(ASSETCHAINS_SYMBOL,(char *)&scriptbuf[len+32*2+4]) == 0 ) matched = 1; } offset = 32 * (1 + matched) + 4; @@ -593,7 +593,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr notarized = 1; if ( strcmp("PIZZA",ccdata.symbol) == 0 ) notarized = 1; - if ( 0 && opretlen != 149 ) + //if ( 0 && opretlen != 149 ) printf("[%s].%d (%s) matched.%d i.%d j.%d notarized.%d %llx opretlen.%d len.%d offset.%d opoffset.%d\n",ASSETCHAINS_SYMBOL,height,ccdata.symbol,matched,i,j,notarized,(long long)signedmask,opretlen,len,offset,opoffset); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&srchash); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); @@ -634,7 +634,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr len += iguana_rwnum(0,&scriptbuf[len],sizeof(MoMdepth),(uint8_t *)&MoMdepth); ccdata.MoMdata.MoM = MoM; ccdata.MoMdata.MoMdepth = MoMdepth; - if ( len+sizeof(ccdata.CCid) <= opretlen ) + if ( len+sizeof(ccdata.CCid)-opoffset <= opretlen ) { len += iguana_rwnum(0,&scriptbuf[len],sizeof(ccdata.CCid),(uint8_t *)&ccdata.CCid); ccdata.len = sizeof(ccdata.CCid); From 874106bf7567bef1f06710ec666818e764da3982 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 20:51:43 +0300 Subject: [PATCH 075/507] Test --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 1076674dc..9ec296937 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -593,7 +593,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr notarized = 1; if ( strcmp("PIZZA",ccdata.symbol) == 0 ) notarized = 1; - //if ( 0 && opretlen != 149 ) + if ( 0 && opretlen != 149 ) printf("[%s].%d (%s) matched.%d i.%d j.%d notarized.%d %llx opretlen.%d len.%d offset.%d opoffset.%d\n",ASSETCHAINS_SYMBOL,height,ccdata.symbol,matched,i,j,notarized,(long long)signedmask,opretlen,len,offset,opoffset); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&srchash); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); From fce64b22d624d286130cd2faebccde15ab9fc964 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 21:04:01 +0300 Subject: [PATCH 076/507] Print --- src/univalue/lib/univalue.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/univalue/lib/univalue.cpp b/src/univalue/lib/univalue.cpp index 14f4c3c4f..446d2cabd 100644 --- a/src/univalue/lib/univalue.cpp +++ b/src/univalue/lib/univalue.cpp @@ -309,7 +309,10 @@ bool UniValue::get_bool() const const std::string& UniValue::get_str() const { if (typ != VSTR) + { + fprintf(stderr,"typ.%d VSTR %d\n",(int32_t)typ,(int32_t)VSTR); throw std::runtime_error("JSON value is not a string as expected"); + } return getValStr(); } From e0196ded31ea0fd94ea37aed110e973828e091db Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 21:06:11 +0300 Subject: [PATCH 077/507] Test --- src/univalue/lib/univalue.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/univalue/lib/univalue.cpp b/src/univalue/lib/univalue.cpp index 446d2cabd..bfb4a7d63 100644 --- a/src/univalue/lib/univalue.cpp +++ b/src/univalue/lib/univalue.cpp @@ -310,7 +310,7 @@ const std::string& UniValue::get_str() const { if (typ != VSTR) { - fprintf(stderr,"typ.%d VSTR %d\n",(int32_t)typ,(int32_t)VSTR); + //fprintf(stderr,"typ.%d VSTR %d\n",(int32_t)typ,(int32_t)VSTR); throw std::runtime_error("JSON value is not a string as expected"); } return getValStr(); From f0a71becef38cbb1a9f0aaeb0f0dda6283db0986 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 21:09:23 +0300 Subject: [PATCH 078/507] Test --- src/univalue/lib/univalue.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/univalue/lib/univalue.cpp b/src/univalue/lib/univalue.cpp index bfb4a7d63..105614568 100644 --- a/src/univalue/lib/univalue.cpp +++ b/src/univalue/lib/univalue.cpp @@ -13,11 +13,13 @@ #include #include "univalue.h" +#include namespace { static bool ParsePrechecks(const std::string& str) { + fprintf(stderr,"Parse.(%s)\n",str.c_str()); if (str.empty()) // No empty string allowed return false; if (str.size() >= 1 && (json_isspace(str[0]) || json_isspace(str[str.size()-1]))) // No padding allowed From 4e13218a0e3def14a3988093360b2e24a7635068 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 21:13:16 +0300 Subject: [PATCH 079/507] Test --- src/univalue/lib/univalue.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/univalue/lib/univalue.cpp b/src/univalue/lib/univalue.cpp index 105614568..0e8005f23 100644 --- a/src/univalue/lib/univalue.cpp +++ b/src/univalue/lib/univalue.cpp @@ -19,7 +19,7 @@ namespace { static bool ParsePrechecks(const std::string& str) { - fprintf(stderr,"Parse.(%s)\n",str.c_str()); + //fprintf(stderr,"Parse.(%s)\n",str.c_str()); if (str.empty()) // No empty string allowed return false; if (str.size() >= 1 && (json_isspace(str[0]) || json_isspace(str[str.size()-1]))) // No padding allowed From cf54fc3881f2bf904eb033cc86849d856ea181af Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 12 Apr 2018 22:03:52 +0300 Subject: [PATCH 080/507] Test --- src/rpcclient.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rpcclient.cpp b/src/rpcclient.cpp index 4b44a8f59..3ff7bc8a0 100644 --- a/src/rpcclient.cpp +++ b/src/rpcclient.cpp @@ -126,7 +126,7 @@ static const CRPCConvertParam vRPCConvertParams[] = { "paxpending", 0 }, { "notaries", 2 }, { "height_MoM", 1 }, - { "MoMoMdata", 3 }, + //{ "MoMoMdata", 3 }, { "allMoMs", 2 }, { "txMoMproof", 1 }, { "minerids", 1 }, From f2173f8cf97ed28ee83fde28d787f737d9092313 Mon Sep 17 00:00:00 2001 From: "Jonathan \"Duke\" Leto" Date: Thu, 12 Apr 2018 14:24:21 -0700 Subject: [PATCH 081/507] Prevent core dumps from invalid maxpairs --- src/komodo_ccdata.h | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 1c324e4ea..adfc965ee 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -85,11 +85,16 @@ struct komodo_ccdata_entry *komodo_allMoMs(int32_t *nump,uint256 *MoMoMp,int32_t int32_t komodo_addpair(struct komodo_ccdataMoMoM *mdata,int32_t notarized_height,int32_t offset,int32_t maxpairs) { - if ( mdata->numpairs >= maxpairs ) - { - maxpairs += 100; - mdata->pairs = (struct komodo_ccdatapair *)realloc(mdata->pairs,sizeof(*mdata->pairs)*maxpairs); - //fprintf(stderr,"pairs reallocated to %p num.%d\n",mdata->pairs,mdata->numpairs); + if ( maxpairs >= 0) { + if ( mdata->numpairs >= maxpairs ) + { + maxpairs += 100; + mdata->pairs = (struct komodo_ccdatapair *)realloc(mdata->pairs,sizeof(*mdata->pairs)*maxpairs); + //fprintf(stderr,"pairs reallocated to %p num.%d\n",mdata->pairs,mdata->numpairs); + } + } else { + fprintf(stderr,"komodo_addpair.maxpairs %d must be >= 0\n",maxpairs,(int32_t)maxpairs); + return(-1); } mdata->pairs[mdata->numpairs].notarized_height = notarized_height; mdata->pairs[mdata->numpairs].MoMoMoffset = offset; From 622c9e4eef318039be7e500e84813a8f868e8735 Mon Sep 17 00:00:00 2001 From: "Jonathan \"Duke\" Leto" Date: Thu, 12 Apr 2018 14:52:33 -0700 Subject: [PATCH 082/507] fix --- src/komodo_ccdata.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index adfc965ee..746a94216 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -93,7 +93,7 @@ int32_t komodo_addpair(struct komodo_ccdataMoMoM *mdata,int32_t notarized_height //fprintf(stderr,"pairs reallocated to %p num.%d\n",mdata->pairs,mdata->numpairs); } } else { - fprintf(stderr,"komodo_addpair.maxpairs %d must be >= 0\n",maxpairs,(int32_t)maxpairs); + fprintf(stderr,"komodo_addpair.maxpairs %d must be >= 0\n",(int32_t)maxpairs); return(-1); } mdata->pairs[mdata->numpairs].notarized_height = notarized_height; From 30d10c2daafdb70c33af82e278750c94eeef60d1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 10:29:40 +0300 Subject: [PATCH 083/507] Fix maxpairs return --- src/komodo_ccdata.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 746a94216..fa0464bd4 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -99,6 +99,7 @@ int32_t komodo_addpair(struct komodo_ccdataMoMoM *mdata,int32_t notarized_height mdata->pairs[mdata->numpairs].notarized_height = notarized_height; mdata->pairs[mdata->numpairs].MoMoMoffset = offset; mdata->numpairs++; + return(maxpairs); } int32_t komodo_MoMoMdata(char *hexstr,int32_t hexsize,struct komodo_ccdataMoMoM *mdata,char *symbol,int32_t kmdheight,int32_t notarized_height) From 742aca3b449d3417c7813622ae8fef9d9315434c Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:00:11 +0300 Subject: [PATCH 084/507] Test --- src/komodo_bitcoind.h | 4 ++-- src/komodo_notary.h | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 4ba908f8b..2ef38f0dd 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -857,13 +857,13 @@ int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33],uint32_t timestamp komodo_chosennotary(&nid,height-i,pubkey33,timestamp); if ( nid == notaryid ) { - if ( (0) && notaryid > 0 ) + //if ( (0) && notaryid > 0 ) fprintf(stderr,"ht.%d notaryid.%d already mined -i.%d nid.%d\n",height,notaryid,i,nid); if ( height > 225000 ) return(-1); } } - //fprintf(stderr,"special notaryid.%d ht.%d limit.%d\n",notaryid,height,limit); + fprintf(stderr,"special notaryid.%d ht.%d limit.%d\n",notaryid,height,limit); return(1); } return(0); diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 29b8809da..1a75caafc 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -203,6 +203,8 @@ int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestam int32_t i,htind,n; uint64_t mask = 0; struct knotary_entry *kp,*tmp; if ( timestamp == 0 && ASSETCHAINS_SYMBOL[0] != 0 ) timestamp = komodo_heightstamp(height); + else if ( ASSETCHAINS_SYMBOL[0] == 0 ) + timestamp = 0; if ( height >= KOMODO_NOTARIES_HARDCODED || ASSETCHAINS_SYMBOL[0] != 0 ) { if ( (timestamp != 0 && timestamp <= KOMODO_NOTARIES_TIMESTAMP1) || (ASSETCHAINS_SYMBOL[0] == 0 && height <= KOMODO_NOTARIES_HEIGHT1) ) From 87150126413e6d1a161d997460cd947986de6890 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:06:24 +0300 Subject: [PATCH 085/507] Test --- src/pow.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index 93ef9ab11..9271eaae4 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -142,10 +142,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in height = komodo_currentheight() + 1; special = komodo_chosennotary(¬aryid,height,pubkey33,timestamp); flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); - /*if ( ASSETCHAINS_STAKED != 0 ) - bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); - else*/ - if ( height > 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary + if ( height > 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary { for (i=0; i<33; i++) { @@ -153,8 +150,12 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in nonz++; } if ( nonz == 0 ) + { + fprintf(stderr,"ht.%d null pubkey checkproof return\n",height); return(true); // will come back via different path with pubkey set + } special2 = komodo_is_special(height,pubkey33,timestamp); + fprintf(stderr,"ht.%d special.%d flag.%d special2.%d\n",height,special,flag,special2); if ( notaryid >= 0 ) { if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) From 5fb970e7dcc2cf666d599b8c40811261178d46b5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:20:52 +0300 Subject: [PATCH 086/507] Hot fix 790833 --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index cbee3f6a6..2bf0795a6 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -158,7 +158,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - if ( flag != 0 ) + if ( flag != 0 || height == 790833 ) bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); } } From 3ac2d1266a7dbc1943c6b3977a47f42b05f5dbb3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:30:20 +0300 Subject: [PATCH 087/507] Test --- src/pow.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 9271eaae4..510ed59de 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -164,7 +164,9 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - if ( flag != 0 ) + else if ( special2 < 0 ) + flag = 0; + if ( flag != 0 )//|| height == 790833 ) bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); } } From 48d8c6d3330894b29feb59d72e6b5e3ec9bb5823 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:33:11 +0300 Subject: [PATCH 088/507] Test --- src/pow.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index 510ed59de..434cf6d0b 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -164,9 +164,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - else if ( special2 < 0 ) - flag = 0; - if ( flag != 0 )//|| height == 790833 ) + if ( flag != 0 && special2 >= 0 )//|| height == 790833 ) bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); } } From f443a449ccdcd18f8471cb3ce5bd8784888e6c45 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:36:51 +0300 Subject: [PATCH 089/507] Test --- src/komodo_bitcoind.h | 4 ++-- src/pow.cpp | 9 +++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 2ef38f0dd..4ba908f8b 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -857,13 +857,13 @@ int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33],uint32_t timestamp komodo_chosennotary(&nid,height-i,pubkey33,timestamp); if ( nid == notaryid ) { - //if ( (0) && notaryid > 0 ) + if ( (0) && notaryid > 0 ) fprintf(stderr,"ht.%d notaryid.%d already mined -i.%d nid.%d\n",height,notaryid,i,nid); if ( height > 225000 ) return(-1); } } - fprintf(stderr,"special notaryid.%d ht.%d limit.%d\n",notaryid,height,limit); + //fprintf(stderr,"special notaryid.%d ht.%d limit.%d\n",notaryid,height,limit); return(1); } return(0); diff --git a/src/pow.cpp b/src/pow.cpp index 434cf6d0b..032d41461 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -151,11 +151,13 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } if ( nonz == 0 ) { - fprintf(stderr,"ht.%d null pubkey checkproof return\n",height); + //fprintf(stderr,"ht.%d null pubkey checkproof return\n",height); return(true); // will come back via different path with pubkey set } special2 = komodo_is_special(height,pubkey33,timestamp); - fprintf(stderr,"ht.%d special.%d flag.%d special2.%d\n",height,special,flag,special2); + ht.790833 notaryid.50 already mined -i.1 nid.50 + ht.790833 special.0 flag.1 special2.-1 + fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); if ( notaryid >= 0 ) { if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) @@ -165,7 +167,10 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); if ( flag != 0 && special2 >= 0 )//|| height == 790833 ) + { + fprintf(stderr,"EASY MINING\n"); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); + } } } if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) From 6e5a61d180c10713c318933329e4566581b964bc Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:38:07 +0300 Subject: [PATCH 090/507] Test --- src/pow.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index 032d41461..40fb0ebf8 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -155,8 +155,6 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in return(true); // will come back via different path with pubkey set } special2 = komodo_is_special(height,pubkey33,timestamp); - ht.790833 notaryid.50 already mined -i.1 nid.50 - ht.790833 special.0 flag.1 special2.-1 fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); if ( notaryid >= 0 ) { From 7a20bd76f64c7e0d610a3b0e3e26a9220141abc4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:42:26 +0300 Subject: [PATCH 091/507] Test --- src/pow.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 40fb0ebf8..b69be1ac4 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -166,7 +166,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); if ( flag != 0 && special2 >= 0 )//|| height == 790833 ) { - fprintf(stderr,"EASY MINING\n"); + fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); } } @@ -197,6 +197,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in return error("CheckProofOfWork(): hash doesn't match nBits"); } else fprintf(stderr,"skip return error height.%d loading.%d\n",height,KOMODO_LOADINGBLOCKS); } //else fprintf(stderr,"skip height.%d loading.%d\n",height,KOMODO_LOADINGBLOCKS); + return false; } return true; } From 5f4b743e5336c2fcbdd6f46816dbff54d4aba6b8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:44:04 +0300 Subject: [PATCH 092/507] test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index b69be1ac4..96dfc5038 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -164,7 +164,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - if ( flag != 0 && special2 >= 0 )//|| height == 790833 ) + if ( flag != 0 )//&& special2 >= 0 )//|| height == 790833 ) { fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); From 0cb5e31015dfe3696c394509e43ff8526ee6ced2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:45:52 +0300 Subject: [PATCH 093/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 96dfc5038..126f6a97b 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -164,7 +164,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - if ( flag != 0 )//&& special2 >= 0 )//|| height == 790833 ) + if ( flag != 0 || special2 >= 0 )//|| height == 790833 ) { fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); From 7dfae517cb1154cd157e5d79e43b52b6939a54a2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:47:32 +0300 Subject: [PATCH 094/507] test --- src/pow.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 126f6a97b..f6a5fb046 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -164,7 +164,10 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - if ( flag != 0 || special2 >= 0 )//|| height == 790833 ) + else if ( special2 < 0 ) + flag = 0; + //ht.702630 notaryid.-1 special.-1 flag.1 special2.0 + if ( flag != 0 || height == 702630 ) { fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); From f94969e1e388d3cfa51a65dc188b5a4a25920ab0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:49:23 +0300 Subject: [PATCH 095/507] Test --- src/pow.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index f6a5fb046..cc4376e16 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -164,10 +164,9 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - else if ( special2 < 0 ) + else if ( height > 780000 && special2 < 0 ) flag = 0; - //ht.702630 notaryid.-1 special.-1 flag.1 special2.0 - if ( flag != 0 || height == 702630 ) + if ( flag != 0 ) { fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); From d49c0532a51b1264b7406d017581e0e8db99faf6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:51:08 +0300 Subject: [PATCH 096/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index cc4376e16..f530b2f13 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -164,7 +164,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - else if ( height > 780000 && special2 < 0 ) + else if ( height > 790900 && special2 < 0 ) flag = 0; if ( flag != 0 ) { From e2cf1dcbf3bd4153a5e587b6e120d13f63ffc241 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:54:18 +0300 Subject: [PATCH 097/507] Test --- src/pow.cpp | 34 +++++++--------------------------- 1 file changed, 7 insertions(+), 27 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index f530b2f13..5f27b6500 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -139,11 +139,14 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in timestamp = komodo_chainactive_timestamp(); bnTarget.SetCompact(nBits, &fNegative, &fOverflow); if ( height == 0 ) + { height = komodo_currentheight() + 1; - special = komodo_chosennotary(¬aryid,height,pubkey33,timestamp); - flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); + fprintf(stderr,"set height to %d\n",height); + } if ( height > 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary { + special = komodo_chosennotary(¬aryid,height,pubkey33,timestamp); + flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); for (i=0; i<33; i++) { if ( pubkey33[i] != 0 ) @@ -164,8 +167,8 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - else if ( height > 790900 && special2 < 0 ) - flag = 0; + //else if ( height > 790900 && special2 < 0 ) + // flag = 0; if ( flag != 0 ) { fprintf(stderr,"EASY MINING ht.%d\n",height); @@ -177,30 +180,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in return error("CheckProofOfWork(): nBits below minimum work"); // Check proof of work matches claimed amount if ( UintToArith256(hash) > bnTarget ) - { - if ( 0 && (height < 235300 || height >= 236000) && KOMODO_LOADINGBLOCKS == 0 && height > 188000 ) - //&& )//186269, 182507&& komodo_chainactive(height) != 0 && nonzpkeys > 0 - { - for (i=31; i>=0; i--) - printf("%02x",((uint8_t *)&hash)[i]); - printf(" hash vs "); - for (i=31; i>=0; i--) - printf("%02x",((uint8_t *)&bnTarget)[i]); - printf(" ht.%d special.%d notaryid.%d ht.%d mod.%d error\n",height,special,notaryid,height,(height % 35)); - for (i=0; i<33; i++) - printf("%02x",pubkey33[i]); - printf(" <- pubkey\n"); - for (i=0; i<66; i++) - printf("%d ",mids[i]); - printf(" minerids from ht.%d\n",height); - if ( KOMODO_REWIND == 0 && (notaryid >= 0 || height > 225000) ) - { - fprintf(stderr,"pow error height.%d loading.%d notaryid.%d\n",height,KOMODO_LOADINGBLOCKS,notaryid); - return error("CheckProofOfWork(): hash doesn't match nBits"); - } else fprintf(stderr,"skip return error height.%d loading.%d\n",height,KOMODO_LOADINGBLOCKS); - } //else fprintf(stderr,"skip height.%d loading.%d\n",height,KOMODO_LOADINGBLOCKS); return false; - } return true; } From a67ac4a963db29fa775575452195e05751f908d1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:56:13 +0300 Subject: [PATCH 098/507] Test --- src/pow.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index 5f27b6500..9c8f57e46 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -169,11 +169,11 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); //else if ( height > 790900 && special2 < 0 ) // flag = 0; - if ( flag != 0 ) - { - fprintf(stderr,"EASY MINING ht.%d\n",height); - bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); - } + } + if ( flag != 0 ) + { + fprintf(stderr,"EASY MINING ht.%d\n",height); + bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); } } if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) From 49a472b53b5f4a8da3be8a3982194390f467d365 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:57:05 +0300 Subject: [PATCH 099/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 9c8f57e46..d1d0a6ab6 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -170,7 +170,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in //else if ( height > 790900 && special2 < 0 ) // flag = 0; } - if ( flag != 0 ) + if ( flag != 0 || special2 > 0 ) { fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); From 47cc7f6cb3c7460ff9ac78dcf260b03b46d45202 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 12:59:06 +0300 Subject: [PATCH 100/507] Test --- src/pow.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index d1d0a6ab6..c2242f4c2 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -167,8 +167,8 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - //else if ( height > 790900 && special2 < 0 ) - // flag = 0; + else if ( height == 790833 ) + flag = 1; } if ( flag != 0 || special2 > 0 ) { From 346d0b0d78fa8ee29030d0d84c529ef917b882ba Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 13:10:29 +0300 Subject: [PATCH 101/507] Test --- src/pow.cpp | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index c2242f4c2..555be1f5d 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -146,7 +146,6 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in if ( height > 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary { special = komodo_chosennotary(¬aryid,height,pubkey33,timestamp); - flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); for (i=0; i<33; i++) { if ( pubkey33[i] != 0 ) @@ -157,18 +156,33 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in //fprintf(stderr,"ht.%d null pubkey checkproof return\n",height); return(true); // will come back via different path with pubkey set } - special2 = komodo_is_special(height,pubkey33,timestamp); - fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); - if ( notaryid >= 0 ) + flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); + if ( 0 ) { - if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) - flag = 1; - else if ( height >= 80000 && height < 108000 && special2 > 0 ) - flag = 1; - else if ( height >= 108000 && special2 > 0 ) - flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - else if ( height == 790833 ) + special2 = komodo_is_special(height,pubkey33,timestamp); + fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); + if ( notaryid >= 0 ) + { + if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) + flag = 1; + else if ( height >= 80000 && height < 108000 && special2 > 0 ) + flag = 1; + else if ( height >= 108000 && special2 > 0 ) + flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); + else if ( height == 790833 ) + flag = 1; + } + } + else if ( notaryid >= 0 ) + { + for (i=0; i<65; i++) + if ( notaryid == mids[i] ) + break; + if ( i == 65 ) flag = 1; + else flag = 0; + if ( (height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0 ) + flag = 0; } if ( flag != 0 || special2 > 0 ) { From 7003739a596d4542aa34ca888d8c73493b66c10a Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 13:14:23 +0300 Subject: [PATCH 102/507] Test --- src/pow.cpp | 34 ++++++++++------------------------ 1 file changed, 10 insertions(+), 24 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index 555be1f5d..38ec0ce36 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -157,32 +157,18 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in return(true); // will come back via different path with pubkey set } flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); - if ( 0 ) + special2 = komodo_is_special(height,pubkey33,timestamp); + fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); + if ( notaryid >= 0 ) { - special2 = komodo_is_special(height,pubkey33,timestamp); - fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); - if ( notaryid >= 0 ) - { - if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) - flag = 1; - else if ( height >= 80000 && height < 108000 && special2 > 0 ) - flag = 1; - else if ( height >= 108000 && special2 > 0 ) - flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - else if ( height == 790833 ) - flag = 1; - } - } - else if ( notaryid >= 0 ) - { - for (i=0; i<65; i++) - if ( notaryid == mids[i] ) - break; - if ( i == 65 ) + if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) + flag = 1; + else if ( height >= 80000 && height < 108000 && special2 > 0 ) + flag = 1; + else if ( height >= 108000 && special2 > 0 ) + flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); + else if ( height == 790833 ) flag = 1; - else flag = 0; - if ( (height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0 ) - flag = 0; } if ( flag != 0 || special2 > 0 ) { From 0ede506158bb0df0df55b75411f6ced3c368e827 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 13:19:11 +0300 Subject: [PATCH 103/507] Test --- src/pow.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/pow.cpp b/src/pow.cpp index 38ec0ce36..ad9bd14ac 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -169,6 +169,8 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); else if ( height == 790833 ) flag = 1; + else if ( special2 < 0 ) + flag = 0; } if ( flag != 0 || special2 > 0 ) { From fed9d98845aef9fc96bfbf49c2947ad2235b8953 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 13:20:30 +0300 Subject: [PATCH 104/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index ad9bd14ac..49762fb5d 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -169,7 +169,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); else if ( height == 790833 ) flag = 1; - else if ( special2 < 0 ) + else if ( special2 < 0 && height > 700000 ) flag = 0; } if ( flag != 0 || special2 > 0 ) From 416a1de39145cffe5082d3bf6e9a50c72e5ad95c Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 13:21:21 +0300 Subject: [PATCH 105/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 49762fb5d..d2069d34f 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -167,7 +167,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - else if ( height == 790833 ) + else if ( height == 790833 || height == 741551 ) flag = 1; else if ( special2 < 0 && height > 700000 ) flag = 0; From 7e10c8a601df071b8ad8b0d1dbd4f67c5a9ce4c6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 13:23:03 +0300 Subject: [PATCH 106/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index d2069d34f..326764bcf 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -167,7 +167,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - else if ( height == 790833 || height == 741551 ) + else if ( height == 790833 || height == 741551 || height == 768413 ) flag = 1; else if ( special2 < 0 && height > 700000 ) flag = 0; From 2c34965a5173d86cc05314819be848b71f235d04 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 13:24:11 +0300 Subject: [PATCH 107/507] Test --- src/pow.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index 326764bcf..617161aff 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -167,9 +167,9 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - else if ( height == 790833 || height == 741551 || height == 768413 ) + else if ( height == 790833 ) flag = 1; - else if ( special2 < 0 && height > 700000 ) + else if ( special2 < 0 && height > 790833 ) flag = 0; } if ( flag != 0 || special2 > 0 ) From c8f73c1d211a6777999e83c9116c910374713bde Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 13:34:51 +0300 Subject: [PATCH 108/507] Test --- src/komodo_bitcoind.h | 2 +- src/pow.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 4ba908f8b..359a417d8 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -857,7 +857,7 @@ int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33],uint32_t timestamp komodo_chosennotary(&nid,height-i,pubkey33,timestamp); if ( nid == notaryid ) { - if ( (0) && notaryid > 0 ) + //if ( (0) && notaryid > 0 ) fprintf(stderr,"ht.%d notaryid.%d already mined -i.%d nid.%d\n",height,notaryid,i,nid); if ( height > 225000 ) return(-1); diff --git a/src/pow.cpp b/src/pow.cpp index 617161aff..6f20ebc2f 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -141,7 +141,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in if ( height == 0 ) { height = komodo_currentheight() + 1; - fprintf(stderr,"set height to %d\n",height); + //fprintf(stderr,"set height to %d\n",height); } if ( height > 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary { @@ -158,7 +158,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); special2 = komodo_is_special(height,pubkey33,timestamp); - fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); + //fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); if ( notaryid >= 0 ) { if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) @@ -174,7 +174,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } if ( flag != 0 || special2 > 0 ) { - fprintf(stderr,"EASY MINING ht.%d\n",height); + //fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); } } From 82f82d3f08fbd890e03c3a6827e8d424dcc6884b Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 13:44:33 +0300 Subject: [PATCH 109/507] Test --- src/komodo_bitcoind.h | 20 +++++++++++++++++--- src/pow.cpp | 4 ++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 359a417d8..fc58131b6 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -840,12 +840,26 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre return(-1); } -int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33],uint32_t timestamp) +int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) { int32_t i,notaryid=0,minerid,limit,nid; //uint8_t _pubkey33[33]; if ( height >= 225000 ) komodo_chosennotary(¬aryid,height,pubkey33,timestamp); - if ( height >= 34000 && notaryid >= 0 ) + if ( height >= 700000 ) + { + if ( mids[0] >= 0 ) + { + for (i=1; i<66; i++) + { + if ( mids[i] == mids[0] ) + { + fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,mids[0],i); + return(-1); + } + } + } else return(0); + } + else if ( height >= 34000 && notaryid >= 0 ) { if ( height < 79693 ) limit = 64; @@ -857,7 +871,7 @@ int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33],uint32_t timestamp komodo_chosennotary(&nid,height-i,pubkey33,timestamp); if ( nid == notaryid ) { - //if ( (0) && notaryid > 0 ) + if ( (0) && notaryid > 0 ) fprintf(stderr,"ht.%d notaryid.%d already mined -i.%d nid.%d\n",height,notaryid,i,nid); if ( height > 225000 ) return(-1); diff --git a/src/pow.cpp b/src/pow.cpp index 6f20ebc2f..a93a6cc95 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -117,7 +117,7 @@ bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams& param } int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); -int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33],uint32_t timestamp); +int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp); int32_t komodo_currentheight(); CBlockIndex *komodo_chainactive(int32_t height); void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height); @@ -157,7 +157,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in return(true); // will come back via different path with pubkey set } flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); - special2 = komodo_is_special(height,pubkey33,timestamp); + special2 = komodo_is_special(pubkeys,mids,height,pubkey33,timestamp); //fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); if ( notaryid >= 0 ) { From 428a3934ab23fbf408d4a98bc0e2ae4655f017f2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 13:49:53 +0300 Subject: [PATCH 110/507] Test --- src/komodo_bitcoind.h | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index fc58131b6..c1d9bd0d8 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -844,8 +844,6 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh { int32_t i,notaryid=0,minerid,limit,nid; //uint8_t _pubkey33[33]; if ( height >= 225000 ) - komodo_chosennotary(¬aryid,height,pubkey33,timestamp); - if ( height >= 700000 ) { if ( mids[0] >= 0 ) { @@ -859,26 +857,31 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh } } else return(0); } - else if ( height >= 34000 && notaryid >= 0 ) + else { - if ( height < 79693 ) - limit = 64; - else if ( height < 82000 ) - limit = 8; - else limit = 66; - for (i=1; i= 225000 ) + komodo_chosennotary(¬aryid,height,pubkey33,timestamp); + if ( height >= 34000 && notaryid >= 0 ) { - komodo_chosennotary(&nid,height-i,pubkey33,timestamp); - if ( nid == notaryid ) + if ( height < 79693 ) + limit = 64; + else if ( height < 82000 ) + limit = 8; + else limit = 66; + for (i=1; i 0 ) - fprintf(stderr,"ht.%d notaryid.%d already mined -i.%d nid.%d\n",height,notaryid,i,nid); - if ( height > 225000 ) - return(-1); + komodo_chosennotary(&nid,height-i,pubkey33,timestamp); + if ( nid == notaryid ) + { + if ( (0) && notaryid > 0 ) + fprintf(stderr,"ht.%d notaryid.%d already mined -i.%d nid.%d\n",height,notaryid,i,nid); + if ( height > 225000 ) + return(-1); + } } + //fprintf(stderr,"special notaryid.%d ht.%d limit.%d\n",notaryid,height,limit); + return(1); } - //fprintf(stderr,"special notaryid.%d ht.%d limit.%d\n",notaryid,height,limit); - return(1); } return(0); } From 3e790b0a15239b788a0a8ef3c56555e442e12ef1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 13:50:33 +0300 Subject: [PATCH 111/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index c1d9bd0d8..ac9be7555 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -843,7 +843,7 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) { int32_t i,notaryid=0,minerid,limit,nid; //uint8_t _pubkey33[33]; - if ( height >= 225000 ) + if ( height >= 82000 ) { if ( mids[0] >= 0 ) { From c85ac67275bc004995718a3424616b2803a01141 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 13:52:39 +0300 Subject: [PATCH 112/507] Test --- src/komodo_bitcoind.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index ac9be7555..f5dc561dc 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -855,6 +855,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh return(-1); } } + return(1); } else return(0); } else From 80573e47c25c2f197c95e45d18dfd7cbf8ba2bbd Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 13:54:05 +0300 Subject: [PATCH 113/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index f5dc561dc..5e87c9b11 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -843,7 +843,7 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) { int32_t i,notaryid=0,minerid,limit,nid; //uint8_t _pubkey33[33]; - if ( height >= 82000 ) + if ( height >= 225000 ) { if ( mids[0] >= 0 ) { From 861119a1c15206833d659ccb16f923c24ccb10b3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 14:00:37 +0300 Subject: [PATCH 114/507] Test --- src/komodo_bitcoind.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 5e87c9b11..abd979d5d 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -852,7 +852,9 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh if ( mids[i] == mids[0] ) { fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,mids[0],i); - return(-1); + if ( height > 790000 ) + return(-1); + else break; } } return(1); From 3db54b5b1b6787e91e3e3f918594cef5a774bb29 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 14:09:48 +0300 Subject: [PATCH 115/507] Test --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 9ec296937..ef36e8405 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -714,7 +714,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } } } - } else //if ( matched != 0 && *notarizedheightp != sp->NOTARIZED_HEIGHT ) + } else if ( height > 600000 )//if ( matched != 0 && *notarizedheightp != sp->NOTARIZED_HEIGHT ) printf("validated.%d notarized.%d %llx reject ht.%d NOTARIZED.%d prev.%d %s.%s DESTTXID.%s len.%d opretlen.%d\n",validated,notarized,(long long)signedmask,height,*notarizedheightp,sp->NOTARIZED_HEIGHT,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),desttxid.ToString().c_str(),len,opretlen); } else if ( matched != 0 && i == 0 && j == 1 && opretlen == 149 ) From 0a245d0afddc2d8c6706a7dda4fc626d1b30b173 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 14:13:39 +0300 Subject: [PATCH 116/507] Future activation --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index a93a6cc95..3b208bdf4 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -169,7 +169,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); else if ( height == 790833 ) flag = 1; - else if ( special2 < 0 && height > 790833 ) + else if ( special2 < 0 && height > 800000 ) flag = 0; } if ( flag != 0 || special2 > 0 ) From 3bc02cffdad925864655a677721c67ee974fe312 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 14:25:36 +0300 Subject: [PATCH 117/507] Test --- src/pow.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index 3b208bdf4..91ff89b5c 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -134,8 +134,8 @@ extern std::string NOTARY_PUBKEY; bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned int nBits, const Consensus::Params& params) { extern int32_t KOMODO_REWIND; - bool fNegative,fOverflow; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,duplicate,flag = 0, mids[66]; uint32_t timestamp = 0; - arith_uint256 bnTarget; CBlockIndex *pindex; uint8_t pubkeys[66][33]; + bool fNegative,fOverflow; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t timestamp = 0; + arith_uint256 bnTarget; uint8_t pubkeys[66][33]; timestamp = komodo_chainactive_timestamp(); bnTarget.SetCompact(nBits, &fNegative, &fOverflow); if ( height == 0 ) From eedb0249719245fda6ac71cc96a161c060040b69 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 14:44:49 +0300 Subject: [PATCH 118/507] Only display error for same coin --- src/komodo.h | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index ef36e8405..e388e03b0 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -557,7 +557,8 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } if ( scriptbuf[len++] == 0x6a ) { - int32_t nameoffset,opoffset = 0; + static int32_t last_rewind; int32_t rewindtarget,validated = 0,nameoffset,opoffset = 0; CBlockIndex *pindex;// + struct komodo_ccdata ccdata; struct komodo_ccdataMoMoM MoMoMdata; if ( (opretlen= scriptbuf[len++]) == 0x4c ) opretlen = scriptbuf[len++]; else if ( opretlen == 0x4d ) @@ -582,13 +583,11 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr if ( nameoffset == 2 ) nameoffset += 2; else nameoffset++; + memset(&ccdata,0,sizeof(ccdata)); + strncpy(ccdata.symbol,(char *)&scriptbuf[len+offset],sizeof(ccdata.symbol)); if ( j == 1 && opretlen >= len+offset-opoffset ) { - static int32_t last_rewind; int32_t rewindtarget,validated = 0; CBlockIndex *pindex;// - struct komodo_ccdata ccdata; struct komodo_ccdataMoMoM MoMoMdata; - memset(&ccdata,0,sizeof(ccdata)); memset(&MoMoMdata,0,sizeof(MoMoMdata)); - strncpy(ccdata.symbol,(char *)&scriptbuf[len+offset],sizeof(ccdata.symbol)); if ( matched == 0 && bitweight(signedmask) >= KOMODO_MINRATIFY ) notarized = 1; if ( strcmp("PIZZA",ccdata.symbol) == 0 ) @@ -714,8 +713,8 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } } } - } else if ( height > 600000 )//if ( matched != 0 && *notarizedheightp != sp->NOTARIZED_HEIGHT ) - printf("validated.%d notarized.%d %llx reject ht.%d NOTARIZED.%d prev.%d %s.%s DESTTXID.%s len.%d opretlen.%d\n",validated,notarized,(long long)signedmask,height,*notarizedheightp,sp->NOTARIZED_HEIGHT,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),desttxid.ToString().c_str(),len,opretlen); + } else if ( opretlen != 149 && height > 600000 && strcmp(ccdata.symbol,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL) == 0 )//if ( matched != 0 && *notarizedheightp != sp->NOTARIZED_HEIGHT ) + printf("%s validated.%d notarized.%d %llx reject ht.%d NOTARIZED.%d prev.%d %s.%s DESTTXID.%s len.%d opretlen.%d\n",ccdata.symbol,validated,notarized,(long long)signedmask,height,*notarizedheightp,sp->NOTARIZED_HEIGHT,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),desttxid.ToString().c_str(),len,opretlen); } else if ( matched != 0 && i == 0 && j == 1 && opretlen == 149 ) { From 3e34f0a6e0841523e470e50a683e79bc36af0dc4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 14:48:32 +0300 Subject: [PATCH 119/507] Test --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index e388e03b0..f422a639d 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -713,7 +713,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } } } - } else if ( opretlen != 149 && height > 600000 && strcmp(ccdata.symbol,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL) == 0 )//if ( matched != 0 && *notarizedheightp != sp->NOTARIZED_HEIGHT ) + } else if ( opretlen != 149 && height > 600000 && matched != 0 ) printf("%s validated.%d notarized.%d %llx reject ht.%d NOTARIZED.%d prev.%d %s.%s DESTTXID.%s len.%d opretlen.%d\n",ccdata.symbol,validated,notarized,(long long)signedmask,height,*notarizedheightp,sp->NOTARIZED_HEIGHT,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),desttxid.ToString().c_str(),len,opretlen); } else if ( matched != 0 && i == 0 && j == 1 && opretlen == 149 ) From 07d48b0d702e0477df1d7a0c9d48a3a1baeffd64 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 15:21:09 +0300 Subject: [PATCH 120/507] Test --- src/pow.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index 91ff89b5c..401d2f0a6 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -169,13 +169,13 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); else if ( height == 790833 ) flag = 1; - else if ( special2 < 0 && height > 800000 ) + else if ( special2 < 0 && height > 792000 ) flag = 0; - } - if ( flag != 0 || special2 > 0 ) - { - //fprintf(stderr,"EASY MINING ht.%d\n",height); - bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); + if ( flag != 0 || special2 > 0 ) + { + //fprintf(stderr,"EASY MINING ht.%d\n",height); + bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); + } } } if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) From 0d260372bae086e700b05aba667e8d34138646a7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 15:24:43 +0300 Subject: [PATCH 121/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index abd979d5d..4895a7ddf 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -843,7 +843,7 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) { int32_t i,notaryid=0,minerid,limit,nid; //uint8_t _pubkey33[33]; - if ( height >= 225000 ) + if ( height >= 790000 ) { if ( mids[0] >= 0 ) { From 90f6612b04ab5daa2beb6479fb17091f567673cc Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 15:28:32 +0300 Subject: [PATCH 122/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 401d2f0a6..7b3b47dc1 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -158,7 +158,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); special2 = komodo_is_special(pubkeys,mids,height,pubkey33,timestamp); - //fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); + fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); if ( notaryid >= 0 ) { if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) From f54b8ecc93c29f22632bba10c3e58b699ae66b8d Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 15:32:50 +0300 Subject: [PATCH 123/507] Test --- src/komodo_bitcoind.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 4895a7ddf..78cf301c8 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -753,12 +753,12 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) } } } else pindex->notaryid = -1; - } + } fprintf(stderr,"error loading block.%d\n",pindex->height); } else { // height -> pubkey33 - //printf("extending chaintip komodo_index2pubkey33 height.%d need to get pubkey33\n",height); + fprintf(stderr,"extending chaintip komodo_index2pubkey33 height.%d need to get pubkey33\n",height); } } From 77f144cdc4471ec0bb906cac932698daf0ca0a3a Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 15:33:54 +0300 Subject: [PATCH 124/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 78cf301c8..47a26473a 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -753,7 +753,7 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) } } } else pindex->notaryid = -1; - } fprintf(stderr,"error loading block.%d\n",pindex->height); + } fprintf(stderr,"error loading block.%d\n",pindex->nHeight); } else { From f785b4d7a5bd72b04427ef4022d59f04182cffb5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 15:35:55 +0300 Subject: [PATCH 125/507] Test --- src/komodo_bitcoind.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 47a26473a..ba6c2e19b 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -727,7 +727,7 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) CBlock block; int32_t num,i; uint8_t pubkeys[64][33]; //komodo_init(height); memset(pubkey33,0,33); - if ( pindex != 0 ) + if ( pindex != 0 && pindex->nHeight == height ) { if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) { @@ -758,7 +758,7 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) else { // height -> pubkey33 - fprintf(stderr,"extending chaintip komodo_index2pubkey33 height.%d need to get pubkey33\n",height); + fprintf(stderr,"extending chaintip komodo_index2pubkey33 height.%d pindex.%d need to get pubkey33\n",height,pindex!=0?pindex->nHeight:-1); } } From 4188bbb680b8088eeef9c5048ca7c6e8a0abfc6b Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 15:37:51 +0300 Subject: [PATCH 126/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index ba6c2e19b..f075c95c3 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -753,7 +753,7 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) } } } else pindex->notaryid = -1; - } fprintf(stderr,"error loading block.%d\n",pindex->nHeight); + } fprintf(stderr,"error loading height.%d block.%d notaryid.%d\n",height,pindex->nHeight,pindex->notaryid); } else { From 6a963f8680e25cc8da66484f83b082ff231e6670 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 15:40:54 +0300 Subject: [PATCH 127/507] Test --- src/komodo_bitcoind.h | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index f075c95c3..1909bd3f2 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -752,8 +752,15 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) } } } - } else pindex->notaryid = -1; - } fprintf(stderr,"error loading height.%d block.%d notaryid.%d\n",height,pindex->nHeight,pindex->notaryid); + } + else + { + for (i=0; i<33; i++) + fprintf(stderr,"%02x",pindex->pubkey33[i]); + pindex->notaryid = -1; + fprintf(stderr," error loading height.%d block.%d notaryid.%d\n",height,pindex->nHeight,pindex->notaryid); + } + } fprintf(stderr," error loading height.%d block.%d notaryid.%d\n",height,pindex->nHeight,pindex->notaryid); } else { From 19cf4b9e30eb3a5eff83bc304e806071d9666f03 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 15:44:35 +0300 Subject: [PATCH 128/507] Test --- src/komodo_bitcoind.h | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 1909bd3f2..a6da32540 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -732,6 +732,18 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) { memcpy(pubkey33,pindex->pubkey33,33); + if ( (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) + { + pindex->notaryid = -1; + for (i=0; inotaryid = i; + break; + } + } + } return; } if ( komodo_blockload(block,pindex) == 0 ) From 05d4bcecd630dab433a2db8f4ccce4e71a7c6d93 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 15:46:56 +0300 Subject: [PATCH 129/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index a6da32540..9599300c0 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -862,7 +862,7 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) { int32_t i,notaryid=0,minerid,limit,nid; //uint8_t _pubkey33[33]; - if ( height >= 790000 ) + if ( height >= 700000 ) { if ( mids[0] >= 0 ) { From ce363f878ed590287850c9a6af9b8936849e2907 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 15:49:27 +0300 Subject: [PATCH 130/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 6eff7c921..cb4ffed18 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1613,7 +1613,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()))) { int32_t i; for (i=0; i<33; i++) - printf("%02x",pubkey33[i]); + fprintf(stderr,"%02x",pubkey33[i]); fprintf(stderr," warning unexpected diff at ht.%d\n",height); return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString()); From 141950a496a77f15434d3f02402b9acf051f8cc7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 16:03:45 +0300 Subject: [PATCH 131/507] Test --- src/komodo_bitcoind.h | 51 ++++++++++++++++++++++++++++--------------- src/main.cpp | 5 +++++ 2 files changed, 39 insertions(+), 17 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 9599300c0..eae27956b 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -722,9 +722,35 @@ uint32_t komodo_heightstamp(int32_t height) return(0); } +void komodo_pindex_init(CBlockIndex *pindex) +{ + int32_t i,num; uint8_t pubkeys[64][33]; + pindex->notaryid = -1; + memset(pindex->pubkey33,0,33); + if ( pindex->vtx[0].vout.size() > 0 ) + { + uint8_t *ptr = (uint8_t *)pindex->vtx[0].vout[0].scriptPubKey.data(); + n = pindex->vtx[0].vout[0].scriptPubKey.size(); + if ( n == 35 ) + memcpy(pindex->pubkey33,ptr+1,33); + } + if ( (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) + { + pindex->notaryid = -1; + for (i=0; ipubkey33,33) == 0 ) + { + pindex->notaryid = i; + break; + } + } + } +} + void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) { - CBlock block; int32_t num,i; uint8_t pubkeys[64][33]; + CBlock block; int32_t num,i; //komodo_init(height); memset(pubkey33,0,33); if ( pindex != 0 && pindex->nHeight == height ) @@ -732,23 +758,15 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) { memcpy(pubkey33,pindex->pubkey33,33); - if ( (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) - { - pindex->notaryid = -1; - for (i=0; inotaryid = i; - break; - } - } - } + if ( pindex->notaryid < 0 ) + komodo_pindex_init(pindex); return; } if ( komodo_blockload(block,pindex) == 0 ) { - komodo_block2pubkey33(pubkey33,block); + komodo_pindex_init(pindex); + memcpy(pubkey33,pindex->pubkey33,33); + /*komodo_block2pubkey33(pubkey33,block); if ( (pubkey33[0] == 2 || pubkey33[0] == 3) ) { memcpy(pindex->pubkey33,pubkey33,33); @@ -765,13 +783,12 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) } } } - else + if ( pindex->notaryid < 0 ) { for (i=0; i<33; i++) fprintf(stderr,"%02x",pindex->pubkey33[i]); - pindex->notaryid = -1; fprintf(stderr," error loading height.%d block.%d notaryid.%d\n",height,pindex->nHeight,pindex->notaryid); - } + }*/ } fprintf(stderr," error loading height.%d block.%d notaryid.%d\n",height,pindex->nHeight,pindex->notaryid); } else diff --git a/src/main.cpp b/src/main.cpp index cb4ffed18..a31f04380 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4091,6 +4091,8 @@ CBlockIndex * InsertBlockIndex(uint256 hash) return pindexNew; } +void komodo_pindex_init(CBlockIndex *pindex); + bool static LoadBlockIndexDB() { const CChainParams& chainparams = Params(); @@ -4106,6 +4108,9 @@ bool static LoadBlockIndexDB() { CBlockIndex* pindex = item.second; vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); + if ( pindex->nHeight >= 0 ) + komodo_pindex_init(pindex); + else pindex->notaryid = -1; } sort(vSortedByHeight.begin(), vSortedByHeight.end()); BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) From 010f741c1fe7f24ab39efb54150400ecf5dc7f05 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 16:11:11 +0300 Subject: [PATCH 132/507] Test --- src/komodo_bitcoind.h | 61 +++++++++---------------------------------- 1 file changed, 12 insertions(+), 49 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index eae27956b..3fb51a0ad 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -727,22 +727,19 @@ void komodo_pindex_init(CBlockIndex *pindex) int32_t i,num; uint8_t pubkeys[64][33]; pindex->notaryid = -1; memset(pindex->pubkey33,0,33); - if ( pindex->vtx[0].vout.size() > 0 ) + if ( komodo_blockload(block,pindex) == 0 ) { - uint8_t *ptr = (uint8_t *)pindex->vtx[0].vout[0].scriptPubKey.data(); - n = pindex->vtx[0].vout[0].scriptPubKey.size(); - if ( n == 35 ) - memcpy(pindex->pubkey33,ptr+1,33); - } - if ( (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) - { - pindex->notaryid = -1; - for (i=0; ipubkey33,block); + if ( (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) { - if ( memcmp(pubkeys[i],pindex->pubkey33,33) == 0 ) + pindex->notaryid = -1; + for (i=0; inotaryid = i; - break; + if ( memcmp(pubkeys[i],pindex->pubkey33,33) == 0 ) + { + pindex->notaryid = i; + break; + } } } } @@ -751,50 +748,16 @@ void komodo_pindex_init(CBlockIndex *pindex) void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) { CBlock block; int32_t num,i; - //komodo_init(height); memset(pubkey33,0,33); if ( pindex != 0 && pindex->nHeight == height ) { if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) { memcpy(pubkey33,pindex->pubkey33,33); - if ( pindex->notaryid < 0 ) - komodo_pindex_init(pindex); return; } - if ( komodo_blockload(block,pindex) == 0 ) - { - komodo_pindex_init(pindex); - memcpy(pubkey33,pindex->pubkey33,33); - /*komodo_block2pubkey33(pubkey33,block); - if ( (pubkey33[0] == 2 || pubkey33[0] == 3) ) - { - memcpy(pindex->pubkey33,pubkey33,33); - if ( (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) - { - pindex->notaryid = -1; - for (i=0; inotaryid = i; - break; - } - } - } - } - if ( pindex->notaryid < 0 ) - { - for (i=0; i<33; i++) - fprintf(stderr,"%02x",pindex->pubkey33[i]); - fprintf(stderr," error loading height.%d block.%d notaryid.%d\n",height,pindex->nHeight,pindex->notaryid); - }*/ - } fprintf(stderr," error loading height.%d block.%d notaryid.%d\n",height,pindex->nHeight,pindex->notaryid); - } - else - { - // height -> pubkey33 - fprintf(stderr,"extending chaintip komodo_index2pubkey33 height.%d pindex.%d need to get pubkey33\n",height,pindex!=0?pindex->nHeight:-1); + komodo_pindex_init(pindex); + memcpy(pubkey33,pindex->pubkey33,33); } } From 5368f298cdeac49824563fc39f6b751b162ab816 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 16:12:19 +0300 Subject: [PATCH 133/507] Test --- src/komodo_bitcoind.h | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 3fb51a0ad..8c6a9c058 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -724,7 +724,7 @@ uint32_t komodo_heightstamp(int32_t height) void komodo_pindex_init(CBlockIndex *pindex) { - int32_t i,num; uint8_t pubkeys[64][33]; + int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; pindex->notaryid = -1; memset(pindex->pubkey33,0,33); if ( komodo_blockload(block,pindex) == 0 ) @@ -761,14 +761,6 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) } } -/*void komodo_connectpindex(CBlockIndex *pindex) -{ - CBlock block; - if ( komodo_blockload(block,pindex) == 0 ) - komodo_connectblock(pindex,block); -}*/ - - int8_t komodo_minerid(int32_t height,uint8_t *pubkey33) { int32_t num,i,numnotaries; CBlockIndex *pindex; uint32_t timestamp=0; uint8_t _pubkey33[33],pubkeys[64][33]; From 071f1be1f6f8534870b64b93e92af23ae53b4d7a Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 16:16:46 +0300 Subject: [PATCH 134/507] Test --- src/komodo_bitcoind.h | 10 +++++----- src/main.cpp | 6 ++---- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 8c6a9c058..63b594343 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -722,7 +722,7 @@ uint32_t komodo_heightstamp(int32_t height) return(0); } -void komodo_pindex_init(CBlockIndex *pindex) +void komodo_pindex_init(CBlockIndex *pindex,int32_t height) { int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; pindex->notaryid = -1; @@ -730,9 +730,8 @@ void komodo_pindex_init(CBlockIndex *pindex) if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pindex->pubkey33,block); - if ( (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) + if ( (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) { - pindex->notaryid = -1; for (i=0; ipubkey33,33) == 0 ) @@ -742,6 +741,7 @@ void komodo_pindex_init(CBlockIndex *pindex) } } } + printf("pindex.%d initialized notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); } } @@ -749,14 +749,14 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) { CBlock block; int32_t num,i; memset(pubkey33,0,33); - if ( pindex != 0 && pindex->nHeight == height ) + if ( pindex != 0 ) { if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) { memcpy(pubkey33,pindex->pubkey33,33); return; } - komodo_pindex_init(pindex); + komodo_pindex_init(pindex,height); memcpy(pubkey33,pindex->pubkey33,33); } } diff --git a/src/main.cpp b/src/main.cpp index a31f04380..fd56bf052 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4091,7 +4091,7 @@ CBlockIndex * InsertBlockIndex(uint256 hash) return pindexNew; } -void komodo_pindex_init(CBlockIndex *pindex); +void komodo_pindex_init(CBlockIndex *pindex,int32_t height); bool static LoadBlockIndexDB() { @@ -4108,9 +4108,7 @@ bool static LoadBlockIndexDB() { CBlockIndex* pindex = item.second; vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); - if ( pindex->nHeight >= 0 ) - komodo_pindex_init(pindex); - else pindex->notaryid = -1; + komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } sort(vSortedByHeight.begin(), vSortedByHeight.end()); BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) From 2b00bd236c328d299dd53890eca9d211b84f3f22 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 16:22:27 +0300 Subject: [PATCH 135/507] Test --- src/komodo_bitcoind.h | 25 ++++++++++++++----------- src/main.cpp | 3 +++ 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 63b594343..3bc68471a 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -725,23 +725,26 @@ uint32_t komodo_heightstamp(int32_t height) void komodo_pindex_init(CBlockIndex *pindex,int32_t height) { int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; + printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); + if ( pindex->notaryid >= 0 ) + return; pindex->notaryid = -1; - memset(pindex->pubkey33,0,33); - if ( komodo_blockload(block,pindex) == 0 ) + if ( pindex->pubkey33[0] != 2 && pindex->pubkey33[0] != 3 ) { - komodo_block2pubkey33(pindex->pubkey33,block); - if ( (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) + memset(pindex->pubkey33,0,33); + if ( komodo_blockload(block,pindex) == 0 ) + komodo_block2pubkey33(pindex->pubkey33,block); + } + if ( (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) + { + for (i=0; ipubkey33,33) == 0 ) { - if ( memcmp(pubkeys[i],pindex->pubkey33,33) == 0 ) - { - pindex->notaryid = i; - break; - } + pindex->notaryid = i; + break; } } - printf("pindex.%d initialized notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); } } diff --git a/src/main.cpp b/src/main.cpp index fd56bf052..7880373ec 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4157,6 +4157,7 @@ bool static LoadBlockIndexDB() pindex->BuildSkip(); if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex))) pindexBestHeader = pindex; + komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } // Load block file info @@ -4185,6 +4186,7 @@ bool static LoadBlockIndexDB() if (pindex->nStatus & BLOCK_HAVE_DATA) { setBlkDataFiles.insert(pindex->nFile); } + komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } for (std::set::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) { @@ -4220,6 +4222,7 @@ bool static LoadBlockIndexDB() if (pindex->pprev) { pindex->pprev->hashAnchorEnd = pindex->hashAnchor; } + komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } // Load pointer to end of best chain From 7680b77f61cbfe3abb33fa7fed2c08fdb3f6b877 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 16:27:17 +0300 Subject: [PATCH 136/507] Test --- src/pow.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/pow.cpp b/src/pow.cpp index 7b3b47dc1..408892579 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -182,7 +182,21 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in return error("CheckProofOfWork(): nBits below minimum work"); // Check proof of work matches claimed amount if ( UintToArith256(hash) > bnTarget ) + { + for (i=31; i>=0; i--) + printf("%02x",((uint8_t *)&hash)[i]); + printf(" hash vs "); + for (i=31; i>=0; i--) + printf("%02x",((uint8_t *)&bnTarget)[i]); + printf(" ht.%d special.%d notaryid.%d ht.%d mod.%d error\n",height,special,notaryid,height,(height % 35)); + for (i=0; i<33; i++) + printf("%02x",pubkey33[i]); + printf(" <- pubkey\n"); + for (i=0; i<66; i++) + printf("%d ",mids[i]); + printf(" minerids from ht.%d\n",height); return false; + } return true; } From 65e4a4cc80f0336837176d80f8b49f0c3dfd4e96 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 16:29:07 +0300 Subject: [PATCH 137/507] Test --- src/pow.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 408892579..f5cbc3c96 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -195,7 +195,8 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in for (i=0; i<66; i++) printf("%d ",mids[i]); printf(" minerids from ht.%d\n",height); - return false; + if ( KOMODO_LOADINGBLOCKS == 0 ) + return false; } return true; } From ace61bc19aa807a7037d55a89186acb296587033 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 16:33:27 +0300 Subject: [PATCH 138/507] Test --- src/komodo_bitcoind.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 3bc68471a..93c0306d1 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -733,7 +733,12 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) { memset(pindex->pubkey33,0,33); if ( komodo_blockload(block,pindex) == 0 ) + { komodo_block2pubkey33(pindex->pubkey33,block); + for (i=0; i<33; i++) + fprintf(stderr,"%02x",pindex->pubkey33[i]); + fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); + } } if ( (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) { @@ -745,6 +750,12 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) break; } } + if ( i == num ) + { + for (i=0; i<33; i++) + fprintf(stderr,"%02x",pindex->pubkey33[i]); + fprintf(stderr," unmatched pubkey at height %d/%d\n",pindex->nHeight,height); + } } } From 8c8dce0870184d49fbbd5cf4d7377a26f9f69e4a Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 16:36:17 +0300 Subject: [PATCH 139/507] Test --- src/komodo_bitcoind.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 93c0306d1..25646a438 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -726,7 +726,7 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) { int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); - if ( pindex->notaryid >= 0 ) + if ( pindex->notaryid >= 0 && (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) ) return; pindex->notaryid = -1; if ( pindex->pubkey33[0] != 2 && pindex->pubkey33[0] != 3 ) @@ -848,6 +848,8 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) { int32_t i,notaryid=0,minerid,limit,nid; //uint8_t _pubkey33[33]; + if ( height >= 225000 ) + komodo_chosennotary(¬aryid,height,pubkey33,timestamp); if ( height >= 700000 ) { if ( mids[0] >= 0 ) @@ -867,8 +869,6 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh } else { - if ( height >= 225000 ) - komodo_chosennotary(¬aryid,height,pubkey33,timestamp); if ( height >= 34000 && notaryid >= 0 ) { if ( height < 79693 ) From 26190fd177d54bb9176a18eb7ac59f9376bd8855 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 16:43:06 +0300 Subject: [PATCH 140/507] Test --- src/komodo_bitcoind.h | 5 +++-- src/pow.cpp | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 25646a438..cf591d0c7 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -815,8 +815,9 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non } else { - komodo_index2pubkey33(pubkey33,pindex,height-i); - memcpy(pubkeys[i],pubkey33,33); + pindex_komodo_init(pindex,height-i); + //komodo_index2pubkey33(pubkey33,pindex,height-i); + memcpy(pubkeys[i],pindex->pubkey33,33); if ( (mids[i]= komodo_minerid(height-i,pubkey33)) >= 0 ) { //mids[i] = *(int32_t *)pubkey33; diff --git a/src/pow.cpp b/src/pow.cpp index f5cbc3c96..5c38ac994 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -134,7 +134,7 @@ extern std::string NOTARY_PUBKEY; bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned int nBits, const Consensus::Params& params) { extern int32_t KOMODO_REWIND; - bool fNegative,fOverflow; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t timestamp = 0; + bool fNegative,fOverflow; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t timestamp = 0; CBlockIndex *pindex; arith_uint256 bnTarget; uint8_t pubkeys[66][33]; timestamp = komodo_chainactive_timestamp(); bnTarget.SetCompact(nBits, &fNegative, &fOverflow); @@ -195,7 +195,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in for (i=0; i<66; i++) printf("%d ",mids[i]); printf(" minerids from ht.%d\n",height); - if ( KOMODO_LOADINGBLOCKS == 0 ) + //if ( KOMODO_LOADINGBLOCKS == 0 ) return false; } return true; From 81323657a25fdb45c53f90c9fb21444a1e6501cd Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 16:51:40 +0300 Subject: [PATCH 141/507] Test --- src/komodo_bitcoind.h | 6 +++--- src/main.cpp | 10 +++++----- src/pow.cpp | 2 ++ 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index cf591d0c7..428233a1b 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -725,13 +725,13 @@ uint32_t komodo_heightstamp(int32_t height) void komodo_pindex_init(CBlockIndex *pindex,int32_t height) { int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; - printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); if ( pindex->notaryid >= 0 && (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) ) return; + printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); pindex->notaryid = -1; - if ( pindex->pubkey33[0] != 2 && pindex->pubkey33[0] != 3 ) + if ( pindex->pubkey33[0] != 2 && pindex->pubkey33[0] != 3 && pindex->pubkey33[0] != 0xff ) { - memset(pindex->pubkey33,0,33); + memset(pindex->pubkey33,0xff,33); if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pindex->pubkey33,block); diff --git a/src/main.cpp b/src/main.cpp index 7880373ec..83c320ccb 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4091,7 +4091,7 @@ CBlockIndex * InsertBlockIndex(uint256 hash) return pindexNew; } -void komodo_pindex_init(CBlockIndex *pindex,int32_t height); +//void komodo_pindex_init(CBlockIndex *pindex,int32_t height); bool static LoadBlockIndexDB() { @@ -4108,7 +4108,7 @@ bool static LoadBlockIndexDB() { CBlockIndex* pindex = item.second; vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); - komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } sort(vSortedByHeight.begin(), vSortedByHeight.end()); BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) @@ -4157,7 +4157,7 @@ bool static LoadBlockIndexDB() pindex->BuildSkip(); if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex))) pindexBestHeader = pindex; - komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } // Load block file info @@ -4186,7 +4186,7 @@ bool static LoadBlockIndexDB() if (pindex->nStatus & BLOCK_HAVE_DATA) { setBlkDataFiles.insert(pindex->nFile); } - komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } for (std::set::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) { @@ -4222,7 +4222,7 @@ bool static LoadBlockIndexDB() if (pindex->pprev) { pindex->pprev->hashAnchorEnd = pindex->hashAnchor; } - komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } // Load pointer to end of best chain diff --git a/src/pow.cpp b/src/pow.cpp index 5c38ac994..2882360d0 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -145,6 +145,8 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } if ( height > 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary { + if ( (pindex= komodo_chainactive(height)) != 0 ) + komodo_pindex_init(pindex,height); special = komodo_chosennotary(¬aryid,height,pubkey33,timestamp); for (i=0; i<33; i++) { From 63745869e49df5d9151daedbeb9f8844b2eb3d50 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:04:23 +0300 Subject: [PATCH 142/507] Test --- src/komodo_bitcoind.h | 7 ++++--- src/main.cpp | 2 +- src/pow.cpp | 3 +++ 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 428233a1b..52d09cb20 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -765,7 +765,7 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) memset(pubkey33,0,33); if ( pindex != 0 ) { - if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) + if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 || pindex->pubkey33[0] == 0xff ) { memcpy(pubkey33,pindex->pubkey33,33); return; @@ -780,7 +780,7 @@ int8_t komodo_minerid(int32_t height,uint8_t *pubkey33) int32_t num,i,numnotaries; CBlockIndex *pindex; uint32_t timestamp=0; uint8_t _pubkey33[33],pubkeys[64][33]; if ( (pindex= chainActive[height]) != 0 ) { - if ( (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) ) + if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 || pindex->pubkey33[0] == 0xff ) { if ( pubkey33 != 0 ) memcpy(pubkey33,pindex->pubkey33,33); @@ -807,7 +807,7 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non { if ( (pindex= komodo_chainactive(height-i)) != 0 ) { - if ( pindex->notaryid >= 0 && (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) ) + if ( pindex->notaryid >= 0 && (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 || pindex->pubkey33[0] == 0xff) ) { memcpy(pubkeys[i],pindex->pubkey33,33); mids[i] = pindex->notaryid; @@ -843,6 +843,7 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre minerids[i] = komodo_minerid(height - i,0); } return(n);*/ + fprintf(stderr,"komodo_minerids is deprecated\n"); return(-1); } diff --git a/src/main.cpp b/src/main.cpp index 83c320ccb..884112cde 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3507,7 +3507,7 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); // Check proof of work matches claimed amount - komodo_index2pubkey33(pubkey33,pindex,height); + //komodo_index2pubkey33(pubkey33,pindex,height); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) ) return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash"); return true; diff --git a/src/pow.cpp b/src/pow.cpp index 2882360d0..dac141c64 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -146,7 +146,10 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in if ( height > 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary { if ( (pindex= komodo_chainactive(height)) != 0 ) + { komodo_pindex_init(pindex,height); + memcpy(pubkey33,pindex->pubkey33,33); + } special = komodo_chosennotary(¬aryid,height,pubkey33,timestamp); for (i=0; i<33; i++) { From 221ff50675a9644a6bee9a00f270f78fc9854ee2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:05:50 +0300 Subject: [PATCH 143/507] Test --- src/komodo_globals.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 919ee97dd..bee78dcb2 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -16,6 +16,7 @@ #include "komodo_defs.h" uint32_t komodo_heightstamp(int32_t height); +void komodo_pindex_init(CBlockIndex *pindex,int32_t height); void 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,int32_t kheight,uint32_t ktime,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout,uint256 MoM,int32_t MoMdepth); void komodo_init(int32_t height); int32_t komodo_MoMdata(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip); From 9e6d49e91390b5963f6980673bc957cfd60da023 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:13:17 +0300 Subject: [PATCH 144/507] Test --- src/komodo_bitcoind.h | 4 ++-- src/pow.cpp | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 52d09cb20..bbc45807b 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -725,7 +725,7 @@ uint32_t komodo_heightstamp(int32_t height) void komodo_pindex_init(CBlockIndex *pindex,int32_t height) { int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; - if ( pindex->notaryid >= 0 && (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) ) + if ( pindex->notaryid >= 0 && (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 || pindex->pubkey33[0] == 0xff) ) return; printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); pindex->notaryid = -1; @@ -815,7 +815,7 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non } else { - pindex_komodo_init(pindex,height-i); + komodo_pindex_init(pindex,height-i); //komodo_index2pubkey33(pubkey33,pindex,height-i); memcpy(pubkeys[i],pindex->pubkey33,33); if ( (mids[i]= komodo_minerid(height-i,pubkey33)) >= 0 ) diff --git a/src/pow.cpp b/src/pow.cpp index dac141c64..39a082bac 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -194,12 +194,17 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in for (i=31; i>=0; i--) printf("%02x",((uint8_t *)&bnTarget)[i]); printf(" ht.%d special.%d notaryid.%d ht.%d mod.%d error\n",height,special,notaryid,height,(height % 35)); + if ( pindex != 0 ) + { + pindex->notaryid = -1; + komodo_pindex_init(pindex,height); + } for (i=0; i<33; i++) printf("%02x",pubkey33[i]); printf(" <- pubkey\n"); for (i=0; i<66; i++) printf("%d ",mids[i]); - printf(" minerids from ht.%d\n",height); + printf(" minerids from ht.%d pindex.%p\n",height,pindex); //if ( KOMODO_LOADINGBLOCKS == 0 ) return false; } From 70a47bd3d64d243f50be1ea0b22a8797467930d7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:14:51 +0300 Subject: [PATCH 145/507] Test --- src/pow.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/pow.cpp b/src/pow.cpp index 39a082bac..5b022b644 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -116,6 +116,7 @@ bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams& param return true; } +void komodo_pindex_init(CBlockIndex *pindex,int32_t height); int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp); int32_t komodo_currentheight(); From 143d63a20b5d6b2dd6fb303ad1d37dc9c51b8183 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:17:07 +0300 Subject: [PATCH 146/507] Test --- src/komodo_globals.h | 1 - 1 file changed, 1 deletion(-) diff --git a/src/komodo_globals.h b/src/komodo_globals.h index bee78dcb2..919ee97dd 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -16,7 +16,6 @@ #include "komodo_defs.h" uint32_t komodo_heightstamp(int32_t height); -void komodo_pindex_init(CBlockIndex *pindex,int32_t height); void 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,int32_t kheight,uint32_t ktime,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout,uint256 MoM,int32_t MoMdepth); void komodo_init(int32_t height); int32_t komodo_MoMdata(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip); From 1f333439ff9dbdba2e73cf349fc7d9a6e4fb090c Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:19:23 +0300 Subject: [PATCH 147/507] Test --- src/komodo_bitcoind.h | 4 +++- src/pow.cpp | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index bbc45807b..55d8a9357 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -731,7 +731,9 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) pindex->notaryid = -1; if ( pindex->pubkey33[0] != 2 && pindex->pubkey33[0] != 3 && pindex->pubkey33[0] != 0xff ) { - memset(pindex->pubkey33,0xff,33); + if ( KOMODO_LOADINGBLOCKS == 0 ) + memset(pindex->pubkey33,0xff,33); + else memset(pindex->pubkey33,0,33); if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pindex->pubkey33,block); diff --git a/src/pow.cpp b/src/pow.cpp index 5b022b644..b6c7d2b31 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -206,7 +206,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in for (i=0; i<66; i++) printf("%d ",mids[i]); printf(" minerids from ht.%d pindex.%p\n",height,pindex); - //if ( KOMODO_LOADINGBLOCKS == 0 ) + if ( KOMODO_LOADINGBLOCKS == 0 ) return false; } return true; From a080f9fcfe4598c114cdb71b56533e38e209341e Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:20:58 +0300 Subject: [PATCH 148/507] Test --- src/komodo_bitcoind.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 55d8a9357..135526a96 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -722,6 +722,7 @@ uint32_t komodo_heightstamp(int32_t height) return(0); } +extern int32_t KOMODO_LOADINGBLOCKS; void komodo_pindex_init(CBlockIndex *pindex,int32_t height) { int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; From 65116260153921ec8b95852fd157d513ebefdf17 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:25:51 +0300 Subject: [PATCH 149/507] Test --- src/komodo_bitcoind.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 135526a96..f1d207943 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -728,7 +728,7 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; if ( pindex->notaryid >= 0 && (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 || pindex->pubkey33[0] == 0xff) ) return; - printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); + //printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); pindex->notaryid = -1; if ( pindex->pubkey33[0] != 2 && pindex->pubkey33[0] != 3 && pindex->pubkey33[0] != 0xff ) { @@ -740,7 +740,7 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) komodo_block2pubkey33(pindex->pubkey33,block); for (i=0; i<33; i++) fprintf(stderr,"%02x",pindex->pubkey33[i]); - fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); + fprintf(stderr," set pubkey at height %d/%d tip.%d\n",pindex->nHeight,height,chainActive.Tip()->nHeight); } } if ( (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) From bab2f263a2f526f7891566e3e3384f0364eb570a Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:28:49 +0300 Subject: [PATCH 150/507] Test --- src/komodo_bitcoind.h | 2 +- src/pow.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index f1d207943..d88c7ddad 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -740,7 +740,7 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) komodo_block2pubkey33(pindex->pubkey33,block); for (i=0; i<33; i++) fprintf(stderr,"%02x",pindex->pubkey33[i]); - fprintf(stderr," set pubkey at height %d/%d tip.%d\n",pindex->nHeight,height,chainActive.Tip()->nHeight); + fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); } } if ( (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) diff --git a/src/pow.cpp b/src/pow.cpp index b6c7d2b31..8abe12ce0 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -205,7 +205,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in printf(" <- pubkey\n"); for (i=0; i<66; i++) printf("%d ",mids[i]); - printf(" minerids from ht.%d pindex.%p\n",height,pindex); + printf(" minerids from ht.%d pindex.%p %d\n",height,pindex,chainActive.Tip()!=0?chainActive.Tip()->nHeight:-1); if ( KOMODO_LOADINGBLOCKS == 0 ) return false; } From 2366096c6532a286e8e07e16eedeff982dea1ff7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:29:58 +0300 Subject: [PATCH 151/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 8abe12ce0..dda4a9ec5 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -205,7 +205,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in printf(" <- pubkey\n"); for (i=0; i<66; i++) printf("%d ",mids[i]); - printf(" minerids from ht.%d pindex.%p %d\n",height,pindex,chainActive.Tip()!=0?chainActive.Tip()->nHeight:-1); + printf(" minerids from ht.%d pindex.%p %d\n",height,pindex); if ( KOMODO_LOADINGBLOCKS == 0 ) return false; } From 6a98bf0618987b64663eedd5ad852eab5c663794 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:30:42 +0300 Subject: [PATCH 152/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index dda4a9ec5..b6c7d2b31 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -205,7 +205,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in printf(" <- pubkey\n"); for (i=0; i<66; i++) printf("%d ",mids[i]); - printf(" minerids from ht.%d pindex.%p %d\n",height,pindex); + printf(" minerids from ht.%d pindex.%p\n",height,pindex); if ( KOMODO_LOADINGBLOCKS == 0 ) return false; } From f527fcdb9723e59e45f4f8094b06a0fb8a4ae219 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:46:08 +0300 Subject: [PATCH 153/507] Test --- src/komodo_bitcoind.h | 6 +++--- src/main.cpp | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index d88c7ddad..f5e8a6707 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -662,7 +662,7 @@ int32_t komodo_block2height(CBlock *block) void komodo_block2pubkey33(uint8_t *pubkey33,CBlock& block) { int32_t n; - memset(pubkey33,0,33); + memset(pubkey33,0xff,33); if ( block.vtx[0].vout.size() > 0 ) { #ifdef KOMODO_ZCASH @@ -732,9 +732,9 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) pindex->notaryid = -1; if ( pindex->pubkey33[0] != 2 && pindex->pubkey33[0] != 3 && pindex->pubkey33[0] != 0xff ) { - if ( KOMODO_LOADINGBLOCKS == 0 ) + //if ( KOMODO_LOADINGBLOCKS == 0 ) memset(pindex->pubkey33,0xff,33); - else memset(pindex->pubkey33,0,33); + //else memset(pindex->pubkey33,0,33); if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pindex->pubkey33,block); diff --git a/src/main.cpp b/src/main.cpp index 884112cde..85066fd9f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4037,6 +4037,7 @@ bool CheckDiskSpace(uint64_t nAdditionalBytes) FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) { + int32_t incr; if (pos.IsNull()) return NULL; boost::filesystem::path path = GetBlockPosFilename(pos, prefix); @@ -4048,6 +4049,26 @@ FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) LogPrintf("Unable to open file %s\n", path.string()); return NULL; } + if ( strcmp(prefix,(char *)"blk") == 0 ) + { + long fsize,fpos; int32_t incr = 16*1024*1024; + fpos = ftell(file); + fseek(file,0,SEEK_END); + fsize = ftell(file); + if ( fsize > incr ) + { + char *ignore = malloc(incr); + if ( ignore != 0 ) + { + rewind(file); + while ( fread(ignore,1,incr,file) == incr ) + fprintf(stderr,"."); + free(ignore); + fprintf(stderr,"loaded %ld bytes set fpos.%ld\n",(long)ftell(file),(long)fpos); + } + } + fseek(file,fpos,SEEK_SET); + } if (pos.nPos) { if (fseek(file, pos.nPos, SEEK_SET)) { LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string()); From e477852b1abfccda9d640949b2c52bcaeb5b1be1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:47:12 +0300 Subject: [PATCH 154/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 85066fd9f..8ebf364ab 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4057,7 +4057,7 @@ FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) fsize = ftell(file); if ( fsize > incr ) { - char *ignore = malloc(incr); + char *ignore = (char *)malloc(incr); if ( ignore != 0 ) { rewind(file); From 913339f11813f8aa48d9c6cb622f5d93ac3a0cc0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:50:25 +0300 Subject: [PATCH 155/507] Test --- src/main.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 8ebf364ab..1fb70bafc 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4037,7 +4037,7 @@ bool CheckDiskSpace(uint64_t nAdditionalBytes) FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) { - int32_t incr; + static int32_t didinit; long fsize,fpos; int32_t incr = 16*1024*1024; if (pos.IsNull()) return NULL; boost::filesystem::path path = GetBlockPosFilename(pos, prefix); @@ -4049,9 +4049,8 @@ FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) LogPrintf("Unable to open file %s\n", path.string()); return NULL; } - if ( strcmp(prefix,(char *)"blk") == 0 ) + if ( didinit == 0 && strcmp(prefix,(char *)"blk") == 0 ) { - long fsize,fpos; int32_t incr = 16*1024*1024; fpos = ftell(file); fseek(file,0,SEEK_END); fsize = ftell(file); @@ -4068,6 +4067,7 @@ FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) } } fseek(file,fpos,SEEK_SET); + didinit = 1; } if (pos.nPos) { if (fseek(file, pos.nPos, SEEK_SET)) { From 0690e63e4ad40d59dda9e108a6d14960e3337862 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:55:04 +0300 Subject: [PATCH 156/507] Test --- src/komodo_bitcoind.h | 8 +++++--- src/pow.cpp | 5 +++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index f5e8a6707..2e6776bfb 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -662,7 +662,9 @@ int32_t komodo_block2height(CBlock *block) void komodo_block2pubkey33(uint8_t *pubkey33,CBlock& block) { int32_t n; - memset(pubkey33,0xff,33); + if ( KOMODO_LOADINGBLOCKS == 0 ) + memset(pubkey33,0xff,33); + else memset(pubkey33,0,33); if ( block.vtx[0].vout.size() > 0 ) { #ifdef KOMODO_ZCASH @@ -732,9 +734,9 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) pindex->notaryid = -1; if ( pindex->pubkey33[0] != 2 && pindex->pubkey33[0] != 3 && pindex->pubkey33[0] != 0xff ) { - //if ( KOMODO_LOADINGBLOCKS == 0 ) + if ( KOMODO_LOADINGBLOCKS == 0 ) memset(pindex->pubkey33,0xff,33); - //else memset(pindex->pubkey33,0,33); + else memset(pindex->pubkey33,0,33); if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pindex->pubkey33,block); diff --git a/src/pow.cpp b/src/pow.cpp index b6c7d2b31..1984c33a7 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -146,6 +146,8 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } if ( height > 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary { + if ( KOMODO_LOADINGBLOCKS == 0 ) + return(true); if ( (pindex= komodo_chainactive(height)) != 0 ) { komodo_pindex_init(pindex,height); @@ -206,8 +208,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in for (i=0; i<66; i++) printf("%d ",mids[i]); printf(" minerids from ht.%d pindex.%p\n",height,pindex); - if ( KOMODO_LOADINGBLOCKS == 0 ) - return false; + return false; } return true; } From e28e0df9be57e978033567bb86cfff0f517a6358 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 17:56:44 +0300 Subject: [PATCH 157/507] Test --- src/komodo_bitcoind.h | 1 - src/komodo_globals.h | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 2e6776bfb..7cd05cccd 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -724,7 +724,6 @@ uint32_t komodo_heightstamp(int32_t height) return(0); } -extern int32_t KOMODO_LOADINGBLOCKS; void komodo_pindex_init(CBlockIndex *pindex,int32_t height) { int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 919ee97dd..0bfc3a06e 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -60,6 +60,7 @@ uint64_t ASSETCHAINS_ENDSUBSIDY,ASSETCHAINS_REWARD,ASSETCHAINS_HALVING,ASSETCHAI uint32_t KOMODO_INITDONE; char KMDUSERPASS[4096],BTCUSERPASS[4096]; uint16_t KMD_PORT = 7771,BITCOIND_PORT = 7771; uint64_t PENDING_KOMODO_TX; +extern int32_t KOMODO_LOADINGBLOCKS; struct komodo_kv *KOMODO_KV; pthread_mutex_t KOMODO_KV_mutex,KOMODO_CC_mutex; From 48fec2e7712d0457f1caa0f10b9b9edf758002cc Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 18:00:34 +0300 Subject: [PATCH 158/507] Test --- src/pow.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/pow.cpp b/src/pow.cpp index 1984c33a7..a3cd4872b 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -200,6 +200,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in if ( pindex != 0 ) { pindex->notaryid = -1; + memset(pindex->pubkey33,0,33); komodo_pindex_init(pindex,height); } for (i=0; i<33; i++) From 065505b79540bb560a2814c6679905bfd0592f15 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 18:06:44 +0300 Subject: [PATCH 159/507] Test --- src/chain.h | 2 +- src/komodo_bitcoind.h | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/chain.h b/src/chain.h index d3c46f9d6..3b8bbd9bd 100644 --- a/src/chain.h +++ b/src/chain.h @@ -177,7 +177,7 @@ public: //! (memory only) Sequential id assigned to distinguish order in which blocks are received. uint32_t nSequenceId; - int8_t notaryid; uint8_t pubkey33[33]; + int8_t notaryid; uint8_t pubkey33[33],didinit; void SetNull() { diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 7cd05cccd..d7b507290 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -727,11 +727,11 @@ uint32_t komodo_heightstamp(int32_t height) void komodo_pindex_init(CBlockIndex *pindex,int32_t height) { int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; - if ( pindex->notaryid >= 0 && (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 || pindex->pubkey33[0] == 0xff) ) + if ( pindex->notaryid >= 0 ) return; - //printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); + printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); pindex->notaryid = -1; - if ( pindex->pubkey33[0] != 2 && pindex->pubkey33[0] != 3 && pindex->pubkey33[0] != 0xff ) + if ( pindex->didinit == 0 ) { if ( KOMODO_LOADINGBLOCKS == 0 ) memset(pindex->pubkey33,0xff,33); @@ -742,9 +742,10 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) for (i=0; i<33; i++) fprintf(stderr,"%02x",pindex->pubkey33[i]); fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); - } + pindex->didinit = 1; + } else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); } - if ( (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3) && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) + if ( pindex->didinit != 0 && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) { for (i=0; i Date: Fri, 13 Apr 2018 18:13:20 +0300 Subject: [PATCH 160/507] Test --- src/komodo_bitcoind.h | 6 +++--- src/pow.cpp | 3 +-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index d7b507290..e9b3a7def 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -770,7 +770,7 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) memset(pubkey33,0,33); if ( pindex != 0 ) { - if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 || pindex->pubkey33[0] == 0xff ) + if ( pindex->didinit != 0 ) { memcpy(pubkey33,pindex->pubkey33,33); return; @@ -785,7 +785,7 @@ int8_t komodo_minerid(int32_t height,uint8_t *pubkey33) int32_t num,i,numnotaries; CBlockIndex *pindex; uint32_t timestamp=0; uint8_t _pubkey33[33],pubkeys[64][33]; if ( (pindex= chainActive[height]) != 0 ) { - if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 || pindex->pubkey33[0] == 0xff ) + if ( pindex->didinit != 0 ) { if ( pubkey33 != 0 ) memcpy(pubkey33,pindex->pubkey33,33); @@ -812,7 +812,7 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non { if ( (pindex= komodo_chainactive(height-i)) != 0 ) { - if ( pindex->notaryid >= 0 && (pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 || pindex->pubkey33[0] == 0xff) ) + if ( pindex->notaryid >= 0 && pindex->didinit != 0 ) { memcpy(pubkeys[i],pindex->pubkey33,33); mids[i] = pindex->notaryid; diff --git a/src/pow.cpp b/src/pow.cpp index a3cd4872b..423341d0f 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -199,8 +199,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in printf(" ht.%d special.%d notaryid.%d ht.%d mod.%d error\n",height,special,notaryid,height,(height % 35)); if ( pindex != 0 ) { - pindex->notaryid = -1; - memset(pindex->pubkey33,0,33); + pindex->didinit = 0; komodo_pindex_init(pindex,height); } for (i=0; i<33; i++) From d47abc0486d7fd2dff8891963e601e3ae1f4742f Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 18:15:38 +0300 Subject: [PATCH 161/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index e9b3a7def..ec15cb45b 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -742,7 +742,7 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) for (i=0; i<33; i++) fprintf(stderr,"%02x",pindex->pubkey33[i]); fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); - pindex->didinit = 1; + pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); } else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); } if ( pindex->didinit != 0 && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) From 52985d544d7c928358c059d25a7297d6fdc28c42 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 18:19:28 +0300 Subject: [PATCH 162/507] Test --- src/main.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 1fb70bafc..849ca3b85 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -53,6 +53,7 @@ using namespace std; CCriticalSection cs_main; extern uint8_t NOTARY_PUBKEY33[33]; +extern int32_t KOMODO_LOADINGBLOCKS; BlockMap mapBlockIndex; CChain chainActive; @@ -2426,6 +2427,8 @@ static int64_t nTimeTotal = 0; bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck) { const CChainParams& chainparams = Params(); + KOMODO_LOADINGBLOCKS = 0; + //fprintf(stderr,"connectblock ht.%d\n",(int32_t)pindex->nHeight); AssertLockHeld(cs_main); bool fExpensiveChecks = true; @@ -4518,7 +4521,6 @@ void UnloadBlockIndex() bool LoadBlockIndex() { - extern int32_t KOMODO_LOADINGBLOCKS; // Load block index from databases KOMODO_LOADINGBLOCKS = 1; if (!fReindex && !LoadBlockIndexDB()) @@ -4526,7 +4528,6 @@ bool LoadBlockIndex() KOMODO_LOADINGBLOCKS = 0; return false; } - KOMODO_LOADINGBLOCKS = 0; fprintf(stderr,"finished loading blocks %s\n",ASSETCHAINS_SYMBOL); return true; } From ba88a1dad97d249add6dce1f701051dc583634b6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 18:20:53 +0300 Subject: [PATCH 163/507] Test --- src/main.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 849ca3b85..1cf8884cf 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4115,7 +4115,7 @@ CBlockIndex * InsertBlockIndex(uint256 hash) return pindexNew; } -//void komodo_pindex_init(CBlockIndex *pindex,int32_t height); +void komodo_pindex_init(CBlockIndex *pindex,int32_t height); bool static LoadBlockIndexDB() { @@ -4132,7 +4132,7 @@ bool static LoadBlockIndexDB() { CBlockIndex* pindex = item.second; vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); - //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } sort(vSortedByHeight.begin(), vSortedByHeight.end()); BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) @@ -4181,7 +4181,7 @@ bool static LoadBlockIndexDB() pindex->BuildSkip(); if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex))) pindexBestHeader = pindex; - //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } // Load block file info @@ -4210,7 +4210,7 @@ bool static LoadBlockIndexDB() if (pindex->nStatus & BLOCK_HAVE_DATA) { setBlkDataFiles.insert(pindex->nFile); } - //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } for (std::set::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) { @@ -4246,7 +4246,7 @@ bool static LoadBlockIndexDB() if (pindex->pprev) { pindex->pprev->hashAnchorEnd = pindex->hashAnchor; } - //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } // Load pointer to end of best chain From 326ddd8684c11052fc675f71c7bb69dbe91ab0bb Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 18:22:46 +0300 Subject: [PATCH 164/507] Test --- src/komodo_bitcoind.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index ec15cb45b..32b2a3218 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -727,12 +727,12 @@ uint32_t komodo_heightstamp(int32_t height) void komodo_pindex_init(CBlockIndex *pindex,int32_t height) { int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; - if ( pindex->notaryid >= 0 ) + if ( pindex->didinit != 0 && pindex->notaryid >= 0 ) return; printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); - pindex->notaryid = -1; if ( pindex->didinit == 0 ) { + pindex->notaryid = -1; if ( KOMODO_LOADINGBLOCKS == 0 ) memset(pindex->pubkey33,0xff,33); else memset(pindex->pubkey33,0,33); From 61e49b141bd60ed142c2d5218706b16c64b5e102 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 18:25:50 +0300 Subject: [PATCH 165/507] Test --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 1cf8884cf..32a8eaf65 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2427,7 +2427,6 @@ static int64_t nTimeTotal = 0; bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck) { const CChainParams& chainparams = Params(); - KOMODO_LOADINGBLOCKS = 0; //fprintf(stderr,"connectblock ht.%d\n",(int32_t)pindex->nHeight); AssertLockHeld(cs_main); @@ -4066,10 +4065,11 @@ FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) while ( fread(ignore,1,incr,file) == incr ) fprintf(stderr,"."); free(ignore); - fprintf(stderr,"loaded %ld bytes set fpos.%ld\n",(long)ftell(file),(long)fpos); + fprintf(stderr,"loaded %ld bytes set fpos.%ld loading.%d\n",(long)ftell(file),(long)fpos,KOMODO_LOADINGBLOCKS); } } fseek(file,fpos,SEEK_SET); + KOMODO_LOADINGBLOCKS = 0; didinit = 1; } if (pos.nPos) { From 102cc989d772f938e1393d198ef66296ace678ad Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 18:30:19 +0300 Subject: [PATCH 166/507] Test --- src/main.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 32a8eaf65..50b84b91b 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4115,7 +4115,7 @@ CBlockIndex * InsertBlockIndex(uint256 hash) return pindexNew; } -void komodo_pindex_init(CBlockIndex *pindex,int32_t height); +//void komodo_pindex_init(CBlockIndex *pindex,int32_t height); bool static LoadBlockIndexDB() { @@ -4132,7 +4132,7 @@ bool static LoadBlockIndexDB() { CBlockIndex* pindex = item.second; vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); - komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } sort(vSortedByHeight.begin(), vSortedByHeight.end()); BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) @@ -4181,7 +4181,7 @@ bool static LoadBlockIndexDB() pindex->BuildSkip(); if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex))) pindexBestHeader = pindex; - komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } // Load block file info @@ -4210,7 +4210,7 @@ bool static LoadBlockIndexDB() if (pindex->nStatus & BLOCK_HAVE_DATA) { setBlkDataFiles.insert(pindex->nFile); } - komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } for (std::set::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) { @@ -4246,7 +4246,7 @@ bool static LoadBlockIndexDB() if (pindex->pprev) { pindex->pprev->hashAnchorEnd = pindex->hashAnchor; } - komodo_pindex_init(pindex,(int32_t)pindex->nHeight); + //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } // Load pointer to end of best chain From 5920762d60b81e50c2c82d8184667599af531fb7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 18:31:10 +0300 Subject: [PATCH 167/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 32b2a3218..d2b310ef5 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -727,7 +727,7 @@ uint32_t komodo_heightstamp(int32_t height) void komodo_pindex_init(CBlockIndex *pindex,int32_t height) { int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; - if ( pindex->didinit != 0 && pindex->notaryid >= 0 ) + if ( pindex->didinit != 0 ) return; printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); if ( pindex->didinit == 0 ) From 524e02801894a41dc82c734ef2eeaa51d02eb668 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 18:38:55 +0300 Subject: [PATCH 168/507] Test --- src/komodo_bitcoind.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index d2b310ef5..bf5088024 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -729,7 +729,7 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; if ( pindex->didinit != 0 ) return; - printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); + //printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); if ( pindex->didinit == 0 ) { pindex->notaryid = -1; @@ -739,11 +739,11 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pindex->pubkey33,block); - for (i=0; i<33; i++) - fprintf(stderr,"%02x",pindex->pubkey33[i]); - fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); + //for (i=0; i<33; i++) + // fprintf(stderr,"%02x",pindex->pubkey33[i]); + //fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); - } else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); + } // else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); } if ( pindex->didinit != 0 && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) { @@ -755,7 +755,7 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) break; } } - if ( i == num ) + if ( 0 && i == num ) { for (i=0; i<33; i++) fprintf(stderr,"%02x",pindex->pubkey33[i]); From 5500c8bae129cc574967fcc65cfa21b978e69ca3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 19:02:20 +0300 Subject: [PATCH 169/507] Test --- src/komodo_ccdata.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index fa0464bd4..5dfc364c7 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -219,6 +219,8 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd CC_firstheight = ccdata->MoMdata.height; for (i=0; i<32; i++) tmp.bytes[i] = ((uint8_t *)&ccdata->MoMdata.MoM)[31-i]; + if ( bits256_nonz(tmp) == 0 ) + return(0); memcpy(&hash,&tmp,sizeof(hash)); fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->MoMdata.notarized_height,hash.ToString().c_str(),ccdata->MoMdata.height,ccdata->MoMdata.txi); if ( ASSETCHAINS_SYMBOL[0] == 0 ) @@ -261,6 +263,7 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd } } } + return(1); } #endif From c9cfa52798d6443b2a13074241f658a986288c82 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 19:07:41 +0300 Subject: [PATCH 170/507] Test --- src/komodo_ccdata.h | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index 5dfc364c7..ab3ea04b0 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -206,7 +206,7 @@ void komodo_purge_ccdata(int32_t height) int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccdata,struct komodo_ccdataMoMoM *MoMoMdata) { - uint256 hash,zero; bits256 tmp; int32_t i; struct komodo_ccdata *ptr; struct notarized_checkpoint *np; + uint256 hash,zero; bits256 tmp; int32_t i,nonz; struct komodo_ccdata *ptr; struct notarized_checkpoint *np; if ( rwflag == 0 ) { // load from disk @@ -217,9 +217,12 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd } if ( ccdata->MoMdata.height > 0 && (CC_firstheight == 0 || ccdata->MoMdata.height < CC_firstheight) ) CC_firstheight = ccdata->MoMdata.height; - for (i=0; i<32; i++) - tmp.bytes[i] = ((uint8_t *)&ccdata->MoMdata.MoM)[31-i]; - if ( bits256_nonz(tmp) == 0 ) + for (nonz=i=0; i<32; i++) + { + if ( (tmp.bytes[i]= ((uint8_t *)&ccdata->MoMdata.MoM)[31-i]) != 0 ) + nonz++; + } + if ( nonz == 0 ) return(0); memcpy(&hash,&tmp,sizeof(hash)); fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->MoMdata.notarized_height,hash.ToString().c_str(),ccdata->MoMdata.height,ccdata->MoMdata.txi); From 008f47c204f96c8101580a9226f4b9d3403bb529 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 19:13:46 +0300 Subject: [PATCH 171/507] Test --- src/komodo_bitcoind.h | 6 +++--- src/pow.cpp | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index bf5088024..f7b7f15b7 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -854,9 +854,7 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) { - int32_t i,notaryid=0,minerid,limit,nid; //uint8_t _pubkey33[33]; - if ( height >= 225000 ) - komodo_chosennotary(¬aryid,height,pubkey33,timestamp); + int32_t i,notaryid=0,minerid,limit,nid; if ( height >= 700000 ) { if ( mids[0] >= 0 ) @@ -878,6 +876,8 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh { if ( height >= 34000 && notaryid >= 0 ) { + if ( height >= 225000 ) + komodo_chosennotary(¬aryid,height,pubkey33,timestamp); if ( height < 79693 ) limit = 64; else if ( height < 82000 ) diff --git a/src/pow.cpp b/src/pow.cpp index 423341d0f..09b5a531c 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -146,7 +146,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } if ( height > 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary { - if ( KOMODO_LOADINGBLOCKS == 0 ) + if ( KOMODO_LOADINGBLOCKS != 0 ) return(true); if ( (pindex= komodo_chainactive(height)) != 0 ) { From f875a5dd0967b19f9d642c8280620b9918a4946e Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 19:17:28 +0300 Subject: [PATCH 172/507] Test --- src/rpcblockchain.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index d49068295..425472758 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -702,9 +702,7 @@ UniValue height_MoM(const UniValue& params, bool fHelp) UniValue txMoMproof(const UniValue& params, bool fHelp) { - uint256 hash, notarisationHash, MoM,MoMoM; - int32_t notarisedHeight, depth; - CBlockIndex* blockIndex; + uint256 hash, notarisationHash, MoM,MoMoM; int32_t notarisedHeight, depth; CBlockIndex* blockIndex; std::vector branch; int nIndex,MoMoMdepth,MoMoMoffset,kmdstarti,kmdendi; From 1a6080508c57a6d942f8a7d05ff2544058a209ce Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 19:29:09 +0300 Subject: [PATCH 173/507] Test --- src/init.cpp | 5 ++++- src/main.cpp | 10 +++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index 3bacc7087..f47b1ee13 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -69,6 +69,7 @@ using namespace std; extern void ThreadSendAlert(); +extern int32_t KOMODO_LOADINGBLOCKS; ZCJoinSplit* pzcashParams = NULL; @@ -625,6 +626,7 @@ void ThreadImport(std::vector vImportFiles) LogPrintf("Reindexing finished\n"); // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): InitBlockIndex(); + KOMODO_LOADINGBLOCKS = 0; } // hardcoded $DATADIR/bootstrap.dat @@ -1421,7 +1423,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) strLoadError = _("Error initializing block database"); break; } - + KOMODO_LOADINGBLOCKS = 0; // Check for changed -txindex state if (fTxIndex != GetBoolArg("-txindex", true)) { strLoadError = _("You need to rebuild the database using -reindex to change -txindex"); @@ -1483,6 +1485,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) } } } + KOMODO_LOADINGBLOCKS = 0; // As LoadBlockIndex can take several minutes, it's possible the user // requested to kill the GUI during the last operation. If so, exit. diff --git a/src/main.cpp b/src/main.cpp index 50b84b91b..bde26c086 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4037,9 +4037,10 @@ bool CheckDiskSpace(uint64_t nAdditionalBytes) return true; } + FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) { - static int32_t didinit; long fsize,fpos; int32_t incr = 16*1024*1024; + static int32_t didinit[1000]; long fsize,fpos; int32_t incr = 16*1024*1024; if (pos.IsNull()) return NULL; boost::filesystem::path path = GetBlockPosFilename(pos, prefix); @@ -4051,7 +4052,7 @@ FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) LogPrintf("Unable to open file %s\n", path.string()); return NULL; } - if ( didinit == 0 && strcmp(prefix,(char *)"blk") == 0 ) + if ( pos.nFile < sizeof(didinit)/sizeof(*didinit) && didinit[pos.nFile] == 0 && strcmp(prefix,(char *)"blk") == 0 ) { fpos = ftell(file); fseek(file,0,SEEK_END); @@ -4065,12 +4066,11 @@ FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) while ( fread(ignore,1,incr,file) == incr ) fprintf(stderr,"."); free(ignore); - fprintf(stderr,"loaded %ld bytes set fpos.%ld loading.%d\n",(long)ftell(file),(long)fpos,KOMODO_LOADINGBLOCKS); + fprintf(stderr,"blk.%d loaded %ld bytes set fpos.%ld loading.%d\n",(int)pos.nFile,(long)ftell(file),(long)fpos,KOMODO_LOADINGBLOCKS); } } fseek(file,fpos,SEEK_SET); - KOMODO_LOADINGBLOCKS = 0; - didinit = 1; + didinit[pos.nFile] = 1; } if (pos.nPos) { if (fseek(file, pos.nPos, SEEK_SET)) { From 9f7555d9ef19806cb7ebad66d4fbe52b4d3fe092 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 19:33:11 +0300 Subject: [PATCH 174/507] test --- src/init.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/init.cpp b/src/init.cpp index f47b1ee13..49c109829 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -627,6 +627,7 @@ void ThreadImport(std::vector vImportFiles) // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): InitBlockIndex(); KOMODO_LOADINGBLOCKS = 0; + fprintf(stderr,"KOMODO_LOADINGBLOCKS finished\n"); } // hardcoded $DATADIR/bootstrap.dat @@ -1424,6 +1425,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) break; } KOMODO_LOADINGBLOCKS = 0; + fprintf(stderr,"KOMODO_LOADINGBLOCKS finished\n"); // Check for changed -txindex state if (fTxIndex != GetBoolArg("-txindex", true)) { strLoadError = _("You need to rebuild the database using -reindex to change -txindex"); @@ -1486,6 +1488,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) } } KOMODO_LOADINGBLOCKS = 0; + fprintf(stderr,"KOMODO_LOADINGBLOCKS finished\n"); // As LoadBlockIndex can take several minutes, it's possible the user // requested to kill the GUI during the last operation. If so, exit. From 5f0ff2d5fd9ec8dc2b69a9e5f9aad95dacb9861a Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 19:34:53 +0300 Subject: [PATCH 175/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 09b5a531c..f0d83c214 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -128,7 +128,7 @@ extern char ASSETCHAINS_SYMBOL[]; #define KOMODO_ELECTION_GAP 2000 int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height); -int32_t KOMODO_LOADINGBLOCKS; +int32_t KOMODO_LOADINGBLOCKS = 1; extern std::string NOTARY_PUBKEY; From 33e92db91bcd2d8a0ada4bb86a47d7a6a7782d83 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 19:41:57 +0300 Subject: [PATCH 176/507] Test --- src/komodo_bitcoind.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index f7b7f15b7..f9d3508db 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -812,6 +812,13 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non { if ( (pindex= komodo_chainactive(height-i)) != 0 ) { + if ( pindex->notaryid >= 64 || pindex->notaryid < -1 ) + { + fprintf(stderr,"unexpected notaryid.%d at ht.%d\n",pindex->notaryid,height-i); + pindex->notaryid = -1; + memset(pindex->pubkey33,0,33); + pindex->didinit = 0; + } if ( pindex->notaryid >= 0 && pindex->didinit != 0 ) { memcpy(pubkeys[i],pindex->pubkey33,33); From d45545dc198d0edee666b98ab30d17b987e37bec Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 19:49:30 +0300 Subject: [PATCH 177/507] Test --- src/pow.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index f0d83c214..a3a0e7260 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -135,7 +135,7 @@ extern std::string NOTARY_PUBKEY; bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned int nBits, const Consensus::Params& params) { extern int32_t KOMODO_REWIND; - bool fNegative,fOverflow; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t timestamp = 0; CBlockIndex *pindex; + bool fNegative,fOverflow; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t timestamp = 0; CBlockIndex *pindex=0; arith_uint256 bnTarget; uint8_t pubkeys[66][33]; timestamp = komodo_chainactive_timestamp(); bnTarget.SetCompact(nBits, &fNegative, &fOverflow); @@ -146,8 +146,6 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } if ( height > 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary { - if ( KOMODO_LOADINGBLOCKS != 0 ) - return(true); if ( (pindex= komodo_chainactive(height)) != 0 ) { komodo_pindex_init(pindex,height); @@ -208,7 +206,8 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in for (i=0; i<66; i++) printf("%d ",mids[i]); printf(" minerids from ht.%d pindex.%p\n",height,pindex); - return false; + if ( KOMODO_LOADINGBLOCKS == 0 ) + return false; } return true; } From 91e508ec62c524f2a33c35c6033382fc2c0b6be9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 19:52:06 +0300 Subject: [PATCH 178/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index f9d3508db..9e7849a68 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -742,7 +742,7 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) //for (i=0; i<33; i++) // fprintf(stderr,"%02x",pindex->pubkey33[i]); //fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); - pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); + //pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); } // else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); } if ( pindex->didinit != 0 && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) From 0bf061757789ed86e2e77116bf66ffb4aab1616e Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 19:55:31 +0300 Subject: [PATCH 179/507] Test --- src/komodo_bitcoind.h | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 9e7849a68..ef99aec75 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -739,9 +739,9 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pindex->pubkey33,block); - //for (i=0; i<33; i++) - // fprintf(stderr,"%02x",pindex->pubkey33[i]); - //fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); + for (i=0; i<33; i++) + fprintf(stderr,"%02x",pindex->pubkey33[i]); + fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); //pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); } // else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); } @@ -770,6 +770,11 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) memset(pubkey33,0,33); if ( pindex != 0 ) { + if ( komodo_blockload(block,pindex) == 0 ) + { + komodo_block2pubkey33(pindex->pubkey33,block); + return; + } if ( pindex->didinit != 0 ) { memcpy(pubkey33,pindex->pubkey33,33); From 079c2dce7e360bd7d64b2e80dfffbcc1d06eb750 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:00:35 +0300 Subject: [PATCH 180/507] Test --- src/komodo_bitcoind.h | 2 +- src/main.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index ef99aec75..2593d6cff 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -742,7 +742,7 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) for (i=0; i<33; i++) fprintf(stderr,"%02x",pindex->pubkey33[i]); fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); - //pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); + pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); } // else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); } if ( pindex->didinit != 0 && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) diff --git a/src/main.cpp b/src/main.cpp index bde26c086..ea0f8de08 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1610,7 +1610,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString()); } // Check the header - komodo_block2pubkey33(pubkey33,block); + //komodo_block2pubkey33(pubkey33,block); if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()))) { int32_t i; for (i=0; i<33; i++) From 3884efe71d200210bb9485e9163784c433190150 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:03:13 +0300 Subject: [PATCH 181/507] Test --- src/komodo_bitcoind.h | 6 +++--- src/pow.cpp | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 2593d6cff..60ca7f24d 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -739,9 +739,9 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pindex->pubkey33,block); - for (i=0; i<33; i++) - fprintf(stderr,"%02x",pindex->pubkey33[i]); - fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); + //for (i=0; i<33; i++) + // fprintf(stderr,"%02x",pindex->pubkey33[i]); + //fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); } // else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); } diff --git a/src/pow.cpp b/src/pow.cpp index a3a0e7260..a5813a7af 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -189,6 +189,8 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in // Check proof of work matches claimed amount if ( UintToArith256(hash) > bnTarget ) { + if ( KOMODO_LOADINGBLOCKS == 0 ) + return false; for (i=31; i>=0; i--) printf("%02x",((uint8_t *)&hash)[i]); printf(" hash vs "); @@ -206,8 +208,6 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in for (i=0; i<66; i++) printf("%d ",mids[i]); printf(" minerids from ht.%d pindex.%p\n",height,pindex); - if ( KOMODO_LOADINGBLOCKS == 0 ) - return false; } return true; } From fcc5eb9aa2ff8f6d1d0809d2c3615b5c76d3bd73 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:05:00 +0300 Subject: [PATCH 182/507] Test --- src/pow.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index a5813a7af..15cec3e35 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -164,7 +164,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); special2 = komodo_is_special(pubkeys,mids,height,pubkey33,timestamp); - fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); + //fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); if ( notaryid >= 0 ) { if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) @@ -189,7 +189,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in // Check proof of work matches claimed amount if ( UintToArith256(hash) > bnTarget ) { - if ( KOMODO_LOADINGBLOCKS == 0 ) + if ( KOMODO_LOADINGBLOCKS != 0 ) return false; for (i=31; i>=0; i--) printf("%02x",((uint8_t *)&hash)[i]); From e3a0c010841c2d8f3401019b0866d49369e8fce3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:06:19 +0300 Subject: [PATCH 183/507] Test --- src/pow.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 15cec3e35..a6b5f7a45 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -190,7 +190,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in if ( UintToArith256(hash) > bnTarget ) { if ( KOMODO_LOADINGBLOCKS != 0 ) - return false; + return true; for (i=31; i>=0; i--) printf("%02x",((uint8_t *)&hash)[i]); printf(" hash vs "); @@ -208,6 +208,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in for (i=0; i<66; i++) printf("%d ",mids[i]); printf(" minerids from ht.%d pindex.%p\n",height,pindex); + return false; } return true; } From 3c89a0234ce8493ec78959147d11f40ee4eeed47 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:08:01 +0300 Subject: [PATCH 184/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 60ca7f24d..24c3358c2 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -876,7 +876,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh if ( mids[i] == mids[0] ) { fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,mids[0],i); - if ( height > 790000 ) + if ( height > 792000 ) return(-1); else break; } From 6def1dd580fe434231f3b03ef354c2899e49f698 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:08:52 +0300 Subject: [PATCH 185/507] Test --- src/komodo_bitcoind.h | 4 ++-- src/main.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 24c3358c2..e19a1126c 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -770,11 +770,11 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) memset(pubkey33,0,33); if ( pindex != 0 ) { - if ( komodo_blockload(block,pindex) == 0 ) + /*if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pindex->pubkey33,block); return; - } + }*/ if ( pindex->didinit != 0 ) { memcpy(pubkey33,pindex->pubkey33,33); diff --git a/src/main.cpp b/src/main.cpp index ea0f8de08..6bfe65a28 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3509,7 +3509,7 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); // Check proof of work matches claimed amount - //komodo_index2pubkey33(pubkey33,pindex,height); + komodo_index2pubkey33(pubkey33,pindex,height); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) ) return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash"); return true; From 0fba8caa9d80be367c6bf038038c4659e4bb0956 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:13:38 +0300 Subject: [PATCH 186/507] Test --- src/komodo_bitcoind.h | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index e19a1126c..3dd01b2a9 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -770,11 +770,11 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) memset(pubkey33,0,33); if ( pindex != 0 ) { - /*if ( komodo_blockload(block,pindex) == 0 ) + if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pindex->pubkey33,block); return; - }*/ + } if ( pindex->didinit != 0 ) { memcpy(pubkey33,pindex->pubkey33,33); @@ -811,7 +811,7 @@ int8_t komodo_minerid(int32_t height,uint8_t *pubkey33) int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height) { - int32_t i,j,duplicate; CBlockIndex *pindex; uint8_t pubkey33[33]; + int32_t i,j,duplicate; CBlock block; CBlockIndex *pindex; uint8_t pubkey33[33]; memset(mids,-1,sizeof(*mids)*66); for (i=duplicate=0; i<66; i++) { @@ -823,6 +823,8 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non pindex->notaryid = -1; memset(pindex->pubkey33,0,33); pindex->didinit = 0; + if ( komodo_blockload(block,pindex) == 0 ) + komodo_block2pubkey33(pindex->pubkey33,block); } if ( pindex->notaryid >= 0 && pindex->didinit != 0 ) { From 84dbfee79a078ab4f0d9ff7c1300eb5b8c9f5f08 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:18:33 +0300 Subject: [PATCH 187/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index a6b5f7a45..7fcc3241a 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -200,7 +200,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in if ( pindex != 0 ) { pindex->didinit = 0; - komodo_pindex_init(pindex,height); + komodo_index2pubkey33(pubkey33,pindex,height); } for (i=0; i<33; i++) printf("%02x",pubkey33[i]); From 819d14c85d0120bbda8f29c8b1d559016f776e96 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:20:23 +0300 Subject: [PATCH 188/507] Test --- src/komodo_bitcoind.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 3dd01b2a9..d69ddef44 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -817,9 +817,9 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non { if ( (pindex= komodo_chainactive(height-i)) != 0 ) { - if ( pindex->notaryid >= 64 || pindex->notaryid < -1 ) + if ( pindex->didinit != 0 && (pindex->notaryid >= 64 || pindex->notaryid < -1) ) { - fprintf(stderr,"unexpected notaryid.%d at ht.%d\n",pindex->notaryid,height-i); + //fprintf(stderr,"unexpected notaryid.%d at ht.%d\n",pindex->notaryid,height-i); pindex->notaryid = -1; memset(pindex->pubkey33,0,33); pindex->didinit = 0; From d0dc7ea822701dfbef4a641a0fba10f57a14c281 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:23:03 +0300 Subject: [PATCH 189/507] Test --- src/pow.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index 7fcc3241a..48bb63763 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -164,7 +164,6 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); special2 = komodo_is_special(pubkeys,mids,height,pubkey33,timestamp); - //fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); if ( notaryid >= 0 ) { if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) @@ -175,8 +174,12 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); else if ( height == 790833 ) flag = 1; - else if ( special2 < 0 && height > 792000 ) - flag = 0; + else if ( special2 < 0 ) + { + if ( height > 792000 ) + flag = 0; + else fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); + } if ( flag != 0 || special2 > 0 ) { //fprintf(stderr,"EASY MINING ht.%d\n",height); @@ -208,7 +211,8 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in for (i=0; i<66; i++) printf("%d ",mids[i]); printf(" minerids from ht.%d pindex.%p\n",height,pindex); - return false; + if ( height > 792000 ) + return false; } return true; } From 3a6c498b7a25dd12e3d5c9b32f236eb9b3bbd813 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:29:02 +0300 Subject: [PATCH 190/507] Test --- src/komodo_bitcoind.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index d69ddef44..58249bcd3 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -742,7 +742,8 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) //for (i=0; i<33; i++) // fprintf(stderr,"%02x",pindex->pubkey33[i]); //fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); - pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); + if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) + pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); } // else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); } if ( pindex->didinit != 0 && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) From 702f7543d5dfd973e03d1d0ed7040f88be4d1838 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:33:12 +0300 Subject: [PATCH 191/507] Test --- src/komodo_bitcoind.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 58249bcd3..8eeff0e33 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -742,8 +742,8 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) //for (i=0; i<33; i++) // fprintf(stderr,"%02x",pindex->pubkey33[i]); //fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); - if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) - pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); + //if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) + // pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); } // else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); } if ( pindex->didinit != 0 && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) From 7db2c2f3dd3f4807f158a500546ef6642972a80e Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:36:15 +0300 Subject: [PATCH 192/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 8eeff0e33..32187da35 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -838,7 +838,7 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non komodo_pindex_init(pindex,height-i); //komodo_index2pubkey33(pubkey33,pindex,height-i); memcpy(pubkeys[i],pindex->pubkey33,33); - if ( (mids[i]= komodo_minerid(height-i,pubkey33)) >= 0 ) + if ( (mids[i]= komodo_minerid(height-i,pindex->pubkey33)) >= 0 ) { //mids[i] = *(int32_t *)pubkey33; (*nonzpkeysp)++; From e3b9257b2e509f3dc9ab366f10790f6d79bab54d Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:48:31 +0300 Subject: [PATCH 193/507] Test --- src/komodo_bitcoind.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 32187da35..b8d268406 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -870,7 +870,7 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) { int32_t i,notaryid=0,minerid,limit,nid; - if ( height >= 700000 ) + /*if ( height >= 700000 ) { if ( mids[0] >= 0 ) { @@ -887,7 +887,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh return(1); } else return(0); } - else + else*/ { if ( height >= 34000 && notaryid >= 0 ) { @@ -903,8 +903,8 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh komodo_chosennotary(&nid,height-i,pubkey33,timestamp); if ( nid == notaryid ) { - if ( (0) && notaryid > 0 ) - fprintf(stderr,"ht.%d notaryid.%d already mined -i.%d nid.%d\n",height,notaryid,i,nid); + //if ( (0) && notaryid > 0 ) + fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,mids[0],i); if ( height > 225000 ) return(-1); } From b05f9bfa940370db4295fe19374ae92fe8dc135d Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:54:09 +0300 Subject: [PATCH 194/507] Test --- src/komodo_bitcoind.h | 2 +- src/pow.cpp | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index b8d268406..e347a7025 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -904,7 +904,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh if ( nid == notaryid ) { //if ( (0) && notaryid > 0 ) - fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,mids[0],i); + fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d] nid.%d notaryid.%d\n",height,mids[0],i,nid,notaryid); if ( height > 225000 ) return(-1); } diff --git a/src/pow.cpp b/src/pow.cpp index 48bb63763..5958b47dd 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -146,11 +146,11 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } if ( height > 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary { - if ( (pindex= komodo_chainactive(height)) != 0 ) + /*if ( (pindex= komodo_chainactive(height)) != 0 ) { komodo_pindex_init(pindex,height); memcpy(pubkey33,pindex->pubkey33,33); - } + }*/ special = komodo_chosennotary(¬aryid,height,pubkey33,timestamp); for (i=0; i<33; i++) { @@ -200,11 +200,11 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in for (i=31; i>=0; i--) printf("%02x",((uint8_t *)&bnTarget)[i]); printf(" ht.%d special.%d notaryid.%d ht.%d mod.%d error\n",height,special,notaryid,height,(height % 35)); - if ( pindex != 0 ) + /*if ( pindex != 0 ) { pindex->didinit = 0; komodo_index2pubkey33(pubkey33,pindex,height); - } + }*/ for (i=0; i<33; i++) printf("%02x",pubkey33[i]); printf(" <- pubkey\n"); From 56f088747a96a9784e46d8e470ac04631806aa91 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 20:56:02 +0300 Subject: [PATCH 195/507] Test --- src/komodo_bitcoind.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index e347a7025..923243aa6 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -889,10 +889,10 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh } else*/ { + if ( height >= 225000 ) + komodo_chosennotary(¬aryid,height,pubkey33,timestamp); if ( height >= 34000 && notaryid >= 0 ) { - if ( height >= 225000 ) - komodo_chosennotary(¬aryid,height,pubkey33,timestamp); if ( height < 79693 ) limit = 64; else if ( height < 82000 ) From fd002038624e9211f02db99a235e2837b5bb6f72 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:00:27 +0300 Subject: [PATCH 196/507] Test --- src/pow.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 5958b47dd..ec297a559 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -135,8 +135,9 @@ extern std::string NOTARY_PUBKEY; bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned int nBits, const Consensus::Params& params) { extern int32_t KOMODO_REWIND; - bool fNegative,fOverflow; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t timestamp = 0; CBlockIndex *pindex=0; + bool fNegative,fOverflow; uint8_t origpubkey33[33]; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t timestamp = 0; CBlockIndex *pindex=0; arith_uint256 bnTarget; uint8_t pubkeys[66][33]; + memcpy(origpubkey33,pubkey33,33); timestamp = komodo_chainactive_timestamp(); bnTarget.SetCompact(nBits, &fNegative, &fOverflow); if ( height == 0 ) @@ -208,6 +209,9 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in for (i=0; i<33; i++) printf("%02x",pubkey33[i]); printf(" <- pubkey\n"); + for (i=0; i<33; i++) + printf("%02x",origpubkey33[i]); + printf(" <- origpubkey\n"); for (i=0; i<66; i++) printf("%d ",mids[i]); printf(" minerids from ht.%d pindex.%p\n",height,pindex); From ec06a2e311483381022ce44ec89ed3bbaa53af30 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:06:06 +0300 Subject: [PATCH 197/507] Test --- src/main.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 6bfe65a28..73137e6ec 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3476,7 +3476,6 @@ bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigne bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& blockhdr, CValidationState& state, bool fCheckPOW) { - uint8_t pubkey33[33]; // Check timestamp if ( 0 ) { @@ -3509,9 +3508,9 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); // Check proof of work matches claimed amount - komodo_index2pubkey33(pubkey33,pindex,height); + /*komodo_index2pubkey33(pubkey33,pindex,height); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) ) - return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash"); + return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash");*/ return true; } @@ -3521,12 +3520,16 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat libzcash::ProofVerifier& verifier, bool fCheckPOW, bool fCheckMerkleRoot) { - // These are checks that are independent of context. + uint8_t pubkey33[33]; + // These are checks that are independent of context. // Check that the header is valid (particularly PoW). This is mostly // redundant with the call in AcceptBlockHeader. if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW)) return false; + komodo_index2pubkey33(pubkey33,pindex,height); + if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), block.nBits, Params().GetConsensus()) ) + return state.DoS(50, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); // Check the merkle root. if (fCheckMerkleRoot) { From bff564101aef223e56f73df279d582976b808f6a Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:09:18 +0300 Subject: [PATCH 198/507] Test --- src/main.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 73137e6ec..38534524b 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -54,6 +54,7 @@ using namespace std; CCriticalSection cs_main; extern uint8_t NOTARY_PUBKEY33[33]; extern int32_t KOMODO_LOADINGBLOCKS; +void komodo_block2pubkey33(uint8_t *pubkey33,CBlock& block); BlockMap mapBlockIndex; CChain chainActive; @@ -1610,7 +1611,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString()); } // Check the header - //komodo_block2pubkey33(pubkey33,block); + komodo_block2pubkey33(pubkey33,block); if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()))) { int32_t i; for (i=0; i<33; i++) @@ -3527,8 +3528,9 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat // redundant with the call in AcceptBlockHeader. if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW)) return false; - komodo_index2pubkey33(pubkey33,pindex,height); - if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), block.nBits, Params().GetConsensus()) ) + //komodo_index2pubkey33(pubkey33,pindex,height); + komodo_block2pubkey33(pubkey33,block); + if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) return state.DoS(50, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); // Check the merkle root. From 392abce3276c4d45115d469b8858e794dd4413c4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:10:39 +0300 Subject: [PATCH 199/507] Test --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 38534524b..fba85dbe7 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1611,7 +1611,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString()); } // Check the header - komodo_block2pubkey33(pubkey33,block); + komodo_block2pubkey33(pubkey33,(CBlock *)block); if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()))) { int32_t i; for (i=0; i<33; i++) @@ -3529,7 +3529,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW)) return false; //komodo_index2pubkey33(pubkey33,pindex,height); - komodo_block2pubkey33(pubkey33,block); + komodo_block2pubkey33(pubkey33,(CBlock *)block); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) return state.DoS(50, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); From 6f88f5413b005c374b3603b5f84468998282b4d1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:12:07 +0300 Subject: [PATCH 200/507] Test --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index fba85dbe7..c721790b3 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1611,7 +1611,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString()); } // Check the header - komodo_block2pubkey33(pubkey33,(CBlock *)block); + komodo_block2pubkey33(pubkey33,(CBlock)block); if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()))) { int32_t i; for (i=0; i<33; i++) @@ -3529,7 +3529,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW)) return false; //komodo_index2pubkey33(pubkey33,pindex,height); - komodo_block2pubkey33(pubkey33,(CBlock *)block); + komodo_block2pubkey33(pubkey33,(CBlock)block); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) return state.DoS(50, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); From 198481557bf9a6a6a9301a298ff5887b7448d7ae Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:13:56 +0300 Subject: [PATCH 201/507] Test --- src/komodo_bitcoind.h | 16 ++++++++-------- src/main.cpp | 6 +++--- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 923243aa6..86989799d 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -659,21 +659,21 @@ int32_t komodo_block2height(CBlock *block) return(height); } -void komodo_block2pubkey33(uint8_t *pubkey33,CBlock& block) +void komodo_block2pubkey33(uint8_t *pubkey33,CBlock *block) { int32_t n; if ( KOMODO_LOADINGBLOCKS == 0 ) memset(pubkey33,0xff,33); else memset(pubkey33,0,33); - if ( block.vtx[0].vout.size() > 0 ) + if ( block->vtx[0].vout.size() > 0 ) { #ifdef KOMODO_ZCASH - uint8_t *ptr = (uint8_t *)block.vtx[0].vout[0].scriptPubKey.data(); + uint8_t *ptr = (uint8_t *)block->vtx[0].vout[0].scriptPubKey.data(); #else - uint8_t *ptr = (uint8_t *)&block.vtx[0].vout[0].scriptPubKey[0]; + uint8_t *ptr = (uint8_t *)&block->vtx[0].vout[0].scriptPubKey[0]; #endif //komodo_init(0); - n = block.vtx[0].vout[0].scriptPubKey.size(); + n = block->vtx[0].vout[0].scriptPubKey.size(); if ( n == 35 ) memcpy(pubkey33,ptr+1,33); } @@ -738,7 +738,7 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) else memset(pindex->pubkey33,0,33); if ( komodo_blockload(block,pindex) == 0 ) { - komodo_block2pubkey33(pindex->pubkey33,block); + komodo_block2pubkey33(pindex->pubkey33,&block); //for (i=0; i<33; i++) // fprintf(stderr,"%02x",pindex->pubkey33[i]); //fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); @@ -773,7 +773,7 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) { if ( komodo_blockload(block,pindex) == 0 ) { - komodo_block2pubkey33(pindex->pubkey33,block); + komodo_block2pubkey33(pindex->pubkey33,&block); return; } if ( pindex->didinit != 0 ) @@ -825,7 +825,7 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non memset(pindex->pubkey33,0,33); pindex->didinit = 0; if ( komodo_blockload(block,pindex) == 0 ) - komodo_block2pubkey33(pindex->pubkey33,block); + komodo_block2pubkey33(pindex->pubkey33,&block); } if ( pindex->notaryid >= 0 && pindex->didinit != 0 ) { diff --git a/src/main.cpp b/src/main.cpp index c721790b3..cf854dbf1 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -54,7 +54,7 @@ using namespace std; CCriticalSection cs_main; extern uint8_t NOTARY_PUBKEY33[33]; extern int32_t KOMODO_LOADINGBLOCKS; -void komodo_block2pubkey33(uint8_t *pubkey33,CBlock& block); +void komodo_block2pubkey33(uint8_t *pubkey33,CBlock *block); BlockMap mapBlockIndex; CChain chainActive; @@ -1611,7 +1611,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString()); } // Check the header - komodo_block2pubkey33(pubkey33,(CBlock)block); + komodo_block2pubkey33(pubkey33,(CBlock *)&block); if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()))) { int32_t i; for (i=0; i<33; i++) @@ -3529,7 +3529,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW)) return false; //komodo_index2pubkey33(pubkey33,pindex,height); - komodo_block2pubkey33(pubkey33,(CBlock)block); + komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) return state.DoS(50, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); From 149a4d640cd83c1a2654c423693a440be87c1194 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:21:53 +0300 Subject: [PATCH 202/507] Test --- src/komodo_bitcoind.h | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 86989799d..a7e4d0560 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -786,19 +786,22 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) } } -int8_t komodo_minerid(int32_t height,uint8_t *pubkey33) +int8_t komodo_minerid(int32_t height,uint8_t *destpubkey33) { - int32_t num,i,numnotaries; CBlockIndex *pindex; uint32_t timestamp=0; uint8_t _pubkey33[33],pubkeys[64][33]; + int32_t num,i,numnotaries; CBlockIndex *pindex; uint32_t timestamp=0; uint8_t pubkey33[33],pubkeys[64][33]; if ( (pindex= chainActive[height]) != 0 ) { if ( pindex->didinit != 0 ) { - if ( pubkey33 != 0 ) - memcpy(pubkey33,pindex->pubkey33,33); + if ( destpubkey33 != 0 ) + memcpy(destpubkey33,pindex->pubkey33,33); return(pindex->notaryid); } - if ( pubkey33 != 0 ) - komodo_index2pubkey33(pubkey33,pindex,height); + komodo_index2pubkey33(pubkey33,pindex,height); + if ( destpubkey33 != 0 ) + memcpy(destpubkey33,pindex->pubkey33,33); + if ( pindex->didinit != 0 ) + return(pindex->notaryid); timestamp = pindex->GetBlockTime(); if ( (num= komodo_notaries(pubkeys,height,timestamp)) > 0 ) { @@ -838,7 +841,7 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non komodo_pindex_init(pindex,height-i); //komodo_index2pubkey33(pubkey33,pindex,height-i); memcpy(pubkeys[i],pindex->pubkey33,33); - if ( (mids[i]= komodo_minerid(height-i,pindex->pubkey33)) >= 0 ) + if ( (mids[i]= komodo_minerid(height-i,0)) >= 0 ) { //mids[i] = *(int32_t *)pubkey33; (*nonzpkeysp)++; From 4c2cffc4c710f25e712267c8a90d2b8753d46b05 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:26:06 +0300 Subject: [PATCH 203/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index a7e4d0560..7ccbf3b37 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -743,7 +743,7 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) // fprintf(stderr,"%02x",pindex->pubkey33[i]); //fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); //if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) - // pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); + pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); } // else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); } if ( pindex->didinit != 0 && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) From 30cc22823ac09be84c269abf755d95a53eda70bb Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:30:00 +0300 Subject: [PATCH 204/507] Test --- src/komodo_bitcoind.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 7ccbf3b37..1f03fabc7 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -873,7 +873,7 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) { int32_t i,notaryid=0,minerid,limit,nid; - /*if ( height >= 700000 ) + if ( height >= 700000 ) { if ( mids[0] >= 0 ) { @@ -890,7 +890,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh return(1); } else return(0); } - else*/ + else { if ( height >= 225000 ) komodo_chosennotary(¬aryid,height,pubkey33,timestamp); From ef0de476a5209186b460a54436a9e03e6a10a58b Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:37:42 +0300 Subject: [PATCH 205/507] Test --- src/komodo_bitcoind.h | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 1f03fabc7..b72814a2a 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -767,15 +767,15 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) { - CBlock block; int32_t num,i; + int32_t num,i; //CBlock block; memset(pubkey33,0,33); if ( pindex != 0 ) { - if ( komodo_blockload(block,pindex) == 0 ) + /*if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pindex->pubkey33,&block); return; - } + }*/ if ( pindex->didinit != 0 ) { memcpy(pubkey33,pindex->pubkey33,33); @@ -810,6 +810,7 @@ int8_t komodo_minerid(int32_t height,uint8_t *destpubkey33) return(i); } } + fprintf(stderr,"komodo_minerid height.%d null pindex\n"); return(komodo_electednotary(&numnotaries,pubkey33,height,timestamp)); } @@ -823,12 +824,11 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non { if ( pindex->didinit != 0 && (pindex->notaryid >= 64 || pindex->notaryid < -1) ) { - //fprintf(stderr,"unexpected notaryid.%d at ht.%d\n",pindex->notaryid,height-i); + fprintf(stderr,"unexpected notaryid.%d at ht.%d\n",pindex->notaryid,height-i); pindex->notaryid = -1; memset(pindex->pubkey33,0,33); pindex->didinit = 0; - if ( komodo_blockload(block,pindex) == 0 ) - komodo_block2pubkey33(pindex->pubkey33,&block); + komodo_pindex_init(pindex,height); } if ( pindex->notaryid >= 0 && pindex->didinit != 0 ) { @@ -839,8 +839,11 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non else { komodo_pindex_init(pindex,height-i); - //komodo_index2pubkey33(pubkey33,pindex,height-i); - memcpy(pubkeys[i],pindex->pubkey33,33); + if ( pindex->didinit == 0 ) + { + if ( komodo_blockload(block,pindex) == 0 ) + komodo_block2pubkey33(pubkeys[i],&block); + } else memcpy(pubkeys[i],pindex->pubkey33,33); if ( (mids[i]= komodo_minerid(height-i,0)) >= 0 ) { //mids[i] = *(int32_t *)pubkey33; From 0f29cbd6607f2f013dd8a740503662aa567e6072 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:38:42 +0300 Subject: [PATCH 206/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index b72814a2a..1950c5ae7 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -810,7 +810,7 @@ int8_t komodo_minerid(int32_t height,uint8_t *destpubkey33) return(i); } } - fprintf(stderr,"komodo_minerid height.%d null pindex\n"); + fprintf(stderr,"komodo_minerid height.%d null pindex\n",height); return(komodo_electednotary(&numnotaries,pubkey33,height,timestamp)); } From da9fce3e92fb2ff60c333320cf68fb4048a39d44 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:48:36 +0300 Subject: [PATCH 207/507] Test --- src/komodo_bitcoind.h | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 1950c5ae7..cc95c6536 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -786,7 +786,7 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) } } -int8_t komodo_minerid(int32_t height,uint8_t *destpubkey33) +/*int8_t komodo_minerid(int32_t height,uint8_t *destpubkey33) { int32_t num,i,numnotaries; CBlockIndex *pindex; uint32_t timestamp=0; uint8_t pubkey33[33],pubkeys[64][33]; if ( (pindex= chainActive[height]) != 0 ) @@ -812,17 +812,31 @@ int8_t komodo_minerid(int32_t height,uint8_t *destpubkey33) } fprintf(stderr,"komodo_minerid height.%d null pindex\n",height); return(komodo_electednotary(&numnotaries,pubkey33,height,timestamp)); -} +}*/ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height) { - int32_t i,j,duplicate; CBlock block; CBlockIndex *pindex; uint8_t pubkey33[33]; + int32_t i,j,n,duplicate; CBlock block; CBlockIndex *pindex; uint8_t pubkey33[33],notarypubs[64][33]; memset(mids,-1,sizeof(*mids)*66); + n = komodo_notaries(notarypubs,height,0); for (i=duplicate=0; i<66; i++) { if ( (pindex= komodo_chainactive(height-i)) != 0 ) { - if ( pindex->didinit != 0 && (pindex->notaryid >= 64 || pindex->notaryid < -1) ) + if ( komodo_blockload(block,pindex) == 0 ) + { + komodo_block2pubkey33(pubkeys[i],&block); + for (j=0; jdidinit != 0 && (pindex->notaryid >= 64 || pindex->notaryid < -1) ) { fprintf(stderr,"unexpected notaryid.%d at ht.%d\n",pindex->notaryid,height-i); pindex->notaryid = -1; @@ -849,7 +863,7 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non //mids[i] = *(int32_t *)pubkey33; (*nonzpkeysp)++; } - } + }*/ if ( mids[0] >= 0 && i > 0 && mids[i] == mids[0] ) duplicate++; } From c352ebb88cf243f3f51b7e328e5b2644587279aa Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:52:16 +0300 Subject: [PATCH 208/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index cc95c6536..c65d69364 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -909,7 +909,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh } else { - if ( height >= 225000 ) + //if ( height >= 225000 ) komodo_chosennotary(¬aryid,height,pubkey33,timestamp); if ( height >= 34000 && notaryid >= 0 ) { From 178618db31059e10d9184adb3e6b418fdd7fb0da Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:54:33 +0300 Subject: [PATCH 209/507] Test --- src/komodo_bitcoind.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index c65d69364..1d4da35f4 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -816,7 +816,7 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height) { - int32_t i,j,n,duplicate; CBlock block; CBlockIndex *pindex; uint8_t pubkey33[33],notarypubs[64][33]; + int32_t i,j,n,duplicate; CBlock block; CBlockIndex *pindex; uint8_t notarypubs33[64][33]; memset(mids,-1,sizeof(*mids)*66); n = komodo_notaries(notarypubs,height,0); for (i=duplicate=0; i<66; i++) @@ -828,14 +828,14 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non komodo_block2pubkey33(pubkeys[i],&block); for (j=0; jdidinit != 0 && (pindex->notaryid >= 64 || pindex->notaryid < -1) ) { fprintf(stderr,"unexpected notaryid.%d at ht.%d\n",pindex->notaryid,height-i); From 1481a43ddb76a6ce83e683f354e071f33ad91de1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 21:55:26 +0300 Subject: [PATCH 210/507] Test --- src/komodo_bitcoind.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 1d4da35f4..505569cb4 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -818,7 +818,7 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non { int32_t i,j,n,duplicate; CBlock block; CBlockIndex *pindex; uint8_t notarypubs33[64][33]; memset(mids,-1,sizeof(*mids)*66); - n = komodo_notaries(notarypubs,height,0); + n = komodo_notaries(notarypubs33,height,0); for (i=duplicate=0; i<66; i++) { if ( (pindex= komodo_chainactive(height-i)) != 0 ) @@ -835,7 +835,7 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non break; } } - } else fprintf("couldnt load block.%d\n",height); + } else fprintf(stderr,"couldnt load block.%d\n",height); /*if ( pindex->didinit != 0 && (pindex->notaryid >= 64 || pindex->notaryid < -1) ) { fprintf(stderr,"unexpected notaryid.%d at ht.%d\n",pindex->notaryid,height-i); From cd897e2b88e4e8c0ef95f4d30b6dde619ec09f62 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 22:01:02 +0300 Subject: [PATCH 211/507] Test --- src/komodo_bitcoind.h | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 505569cb4..9cc063155 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -767,15 +767,10 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) { - int32_t num,i; //CBlock block; + int32_t num,i; memset(pubkey33,0,33); if ( pindex != 0 ) { - /*if ( komodo_blockload(block,pindex) == 0 ) - { - komodo_block2pubkey33(pindex->pubkey33,&block); - return; - }*/ if ( pindex->didinit != 0 ) { memcpy(pubkey33,pindex->pubkey33,33); @@ -890,7 +885,7 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) { int32_t i,notaryid=0,minerid,limit,nid; - if ( height >= 700000 ) + /*if ( height >= 700000 ) { if ( mids[0] >= 0 ) { @@ -907,7 +902,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh return(1); } else return(0); } - else + else*/ { //if ( height >= 225000 ) komodo_chosennotary(¬aryid,height,pubkey33,timestamp); @@ -924,7 +919,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh if ( nid == notaryid ) { //if ( (0) && notaryid > 0 ) - fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d] nid.%d notaryid.%d\n",height,mids[0],i,nid,notaryid); + fprintf(stderr,"ht.%d repeat mids0.%d in mids[%d] nid.%d notaryid.%d\n",height,mids[0],i,nid,notaryid); if ( height > 225000 ) return(-1); } From 73709f319c3bd6021fd76228ea4984263f249e09 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 22:07:58 +0300 Subject: [PATCH 212/507] Test --- src/komodo_bitcoind.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 9cc063155..0dbf23e47 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -919,7 +919,9 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh if ( nid == notaryid ) { //if ( (0) && notaryid > 0 ) - fprintf(stderr,"ht.%d repeat mids0.%d in mids[%d] nid.%d notaryid.%d\n",height,mids[0],i,nid,notaryid); + for (j=0; j<66; j++) + printf("%d ",mids[j]); + fprintf(stderr,"ht.%d repeat mids[%d] nid.%d notaryid.%d\n",height-i,i,nid,notaryid); if ( height > 225000 ) return(-1); } From 442215b4019379fe89f48d60cb3439806367ad9c Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 22:18:11 +0300 Subject: [PATCH 213/507] Test --- src/komodo_bitcoind.h | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 0dbf23e47..4524af806 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -884,16 +884,20 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) { - int32_t i,notaryid=0,minerid,limit,nid; - /*if ( height >= 700000 ) + int32_t i,j,notaryid=0,minerid,limit,nid; uint8_t destpubkey33[33]; + //if ( height >= 225000 ) + komodo_chosennotary(¬aryid,height,pubkey33,timestamp); + if ( height >= 700000 ) { - if ( mids[0] >= 0 ) + if ( notaryid >= 0 ) { for (i=1; i<66; i++) { - if ( mids[i] == mids[0] ) + if ( mids[i] == notaryid ) { - fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,mids[0],i); + for (j=0; j<66; j++) + printf("%d ",mids[j]); + fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,notaryid,i); if ( height > 792000 ) return(-1); else break; @@ -902,10 +906,8 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh return(1); } else return(0); } - else*/ + else { - //if ( height >= 225000 ) - komodo_chosennotary(¬aryid,height,pubkey33,timestamp); if ( height >= 34000 && notaryid >= 0 ) { if ( height < 79693 ) @@ -918,7 +920,6 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh komodo_chosennotary(&nid,height-i,pubkey33,timestamp); if ( nid == notaryid ) { - //if ( (0) && notaryid > 0 ) for (j=0; j<66; j++) printf("%d ",mids[j]); fprintf(stderr,"ht.%d repeat mids[%d] nid.%d notaryid.%d\n",height-i,i,nid,notaryid); From cb19d181a576c13e01e82dd76d2f9ce764ecbeb7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 22:24:51 +0300 Subject: [PATCH 214/507] Test --- src/komodo_bitcoind.h | 7 +++---- src/pow.cpp | 6 ++++++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 4524af806..2547d7388 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -885,9 +885,8 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) { int32_t i,j,notaryid=0,minerid,limit,nid; uint8_t destpubkey33[33]; - //if ( height >= 225000 ) komodo_chosennotary(¬aryid,height,pubkey33,timestamp); - if ( height >= 700000 ) + if ( height >= 82000 ) { if ( notaryid >= 0 ) { @@ -896,7 +895,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh if ( mids[i] == notaryid ) { for (j=0; j<66; j++) - printf("%d ",mids[j]); + fprintf(stderr,"%d ",mids[j]); fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,notaryid,i); if ( height > 792000 ) return(-1); @@ -921,7 +920,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh if ( nid == notaryid ) { for (j=0; j<66; j++) - printf("%d ",mids[j]); + fprintf(stderr,"%d ",mids[j]); fprintf(stderr,"ht.%d repeat mids[%d] nid.%d notaryid.%d\n",height-i,i,nid,notaryid); if ( height > 225000 ) return(-1); diff --git a/src/pow.cpp b/src/pow.cpp index ec297a559..4141664c0 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -218,6 +218,12 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in if ( height > 792000 ) return false; } + if ( KOMODO_LOADINGBLOCKS == 0 ) + { + for (i=0; i<66; i++) + fprintf(stderr,"%d ",mids[i]); + fprintf(stderr,"mids ht.%d\n",height); + } return true; } From 79fb8179037a4ac5b3ad2ede33fb641b2a7c5399 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 22:31:09 +0300 Subject: [PATCH 215/507] Test --- src/komodo_bitcoind.h | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 2547d7388..cf26fcb8b 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -818,6 +818,15 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non { if ( (pindex= komodo_chainactive(height-i)) != 0 ) { + if ( pindex->didinit != 0 ) + { + memcpy(pubkeys[i],pindex->pubkey33,33); + if ( (mids[i]= pindex->notaryid) >= 0 ) + (*nonzpkeysp)++; + if ( mids[0] >= 0 && i > 0 && mids[i] == mids[0] ) + duplicate++; + continue; + } if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pubkeys[i],&block); @@ -919,9 +928,9 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh komodo_chosennotary(&nid,height-i,pubkey33,timestamp); if ( nid == notaryid ) { - for (j=0; j<66; j++) - fprintf(stderr,"%d ",mids[j]); - fprintf(stderr,"ht.%d repeat mids[%d] nid.%d notaryid.%d\n",height-i,i,nid,notaryid); + //for (j=0; j<66; j++) + // fprintf(stderr,"%d ",mids[j]); + //fprintf(stderr,"ht.%d repeat mids[%d] nid.%d notaryid.%d\n",height-i,i,nid,notaryid); if ( height > 225000 ) return(-1); } From 232506f7aeaa09839f1e2f55b461a28e066d667d Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 22:35:46 +0300 Subject: [PATCH 216/507] Test --- src/komodo_bitcoind.h | 54 +++++-------------------------------------- src/pow.cpp | 5 ---- 2 files changed, 6 insertions(+), 53 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index cf26fcb8b..dd95bbef0 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -724,7 +724,7 @@ uint32_t komodo_heightstamp(int32_t height) return(0); } -void komodo_pindex_init(CBlockIndex *pindex,int32_t height) +/*void komodo_pindex_init(CBlockIndex *pindex,int32_t height) gets data corrupted { int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; if ( pindex->didinit != 0 ) @@ -743,7 +743,7 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) // fprintf(stderr,"%02x",pindex->pubkey33[i]); //fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); //if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) - pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); + // pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); } // else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); } if ( pindex->didinit != 0 && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) @@ -763,21 +763,16 @@ void komodo_pindex_init(CBlockIndex *pindex,int32_t height) fprintf(stderr," unmatched pubkey at height %d/%d\n",pindex->nHeight,height); } } -} +}*/ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) { - int32_t num,i; + int32_t num,i; CBlock block; memset(pubkey33,0,33); if ( pindex != 0 ) { - if ( pindex->didinit != 0 ) - { - memcpy(pubkey33,pindex->pubkey33,33); - return; - } - komodo_pindex_init(pindex,height); - memcpy(pubkey33,pindex->pubkey33,33); + if ( komodo_blockload(block,pindex) == 0 ) + komodo_block2pubkey33(pubkey33,&block); } } @@ -818,15 +813,6 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non { if ( (pindex= komodo_chainactive(height-i)) != 0 ) { - if ( pindex->didinit != 0 ) - { - memcpy(pubkeys[i],pindex->pubkey33,33); - if ( (mids[i]= pindex->notaryid) >= 0 ) - (*nonzpkeysp)++; - if ( mids[0] >= 0 && i > 0 && mids[i] == mids[0] ) - duplicate++; - continue; - } if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pubkeys[i],&block); @@ -840,34 +826,6 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non } } } else fprintf(stderr,"couldnt load block.%d\n",height); - /*if ( pindex->didinit != 0 && (pindex->notaryid >= 64 || pindex->notaryid < -1) ) - { - fprintf(stderr,"unexpected notaryid.%d at ht.%d\n",pindex->notaryid,height-i); - pindex->notaryid = -1; - memset(pindex->pubkey33,0,33); - pindex->didinit = 0; - komodo_pindex_init(pindex,height); - } - if ( pindex->notaryid >= 0 && pindex->didinit != 0 ) - { - memcpy(pubkeys[i],pindex->pubkey33,33); - mids[i] = pindex->notaryid; - (*nonzpkeysp)++; - } - else - { - komodo_pindex_init(pindex,height-i); - if ( pindex->didinit == 0 ) - { - if ( komodo_blockload(block,pindex) == 0 ) - komodo_block2pubkey33(pubkeys[i],&block); - } else memcpy(pubkeys[i],pindex->pubkey33,33); - if ( (mids[i]= komodo_minerid(height-i,0)) >= 0 ) - { - //mids[i] = *(int32_t *)pubkey33; - (*nonzpkeysp)++; - } - }*/ if ( mids[0] >= 0 && i > 0 && mids[i] == mids[0] ) duplicate++; } diff --git a/src/pow.cpp b/src/pow.cpp index 4141664c0..aa08d5396 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -147,11 +147,6 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } if ( height > 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary { - /*if ( (pindex= komodo_chainactive(height)) != 0 ) - { - komodo_pindex_init(pindex,height); - memcpy(pubkey33,pindex->pubkey33,33); - }*/ special = komodo_chosennotary(¬aryid,height,pubkey33,timestamp); for (i=0; i<33; i++) { From ca619b923cf3d2e88767c76a21c2a52010353cb4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 22:43:46 +0300 Subject: [PATCH 217/507] Test --- src/pow.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index aa08d5396..9c1cb9810 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -116,7 +116,6 @@ bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams& param return true; } -void komodo_pindex_init(CBlockIndex *pindex,int32_t height); int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp); int32_t komodo_currentheight(); @@ -216,7 +215,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in if ( KOMODO_LOADINGBLOCKS == 0 ) { for (i=0; i<66; i++) - fprintf(stderr,"%d ",mids[i]); + fprintf(stderr,"%d ",i==0?notaryid:mids[i]); fprintf(stderr,"mids ht.%d\n",height); } return true; From f31232d8d0a2711d92fb7406a941ed27dc815061 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 22:45:26 +0300 Subject: [PATCH 218/507] Test --- src/chain.h | 1 - 1 file changed, 1 deletion(-) diff --git a/src/chain.h b/src/chain.h index 3b8bbd9bd..a28e4e44a 100644 --- a/src/chain.h +++ b/src/chain.h @@ -177,7 +177,6 @@ public: //! (memory only) Sequential id assigned to distinguish order in which blocks are received. uint32_t nSequenceId; - int8_t notaryid; uint8_t pubkey33[33],didinit; void SetNull() { From dd5ed83468f3e7fbb0d9504ff1d98663aedfeb35 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 22:46:21 +0300 Subject: [PATCH 219/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 9c1cb9810..61c50469f 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -212,7 +212,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in if ( height > 792000 ) return false; } - if ( KOMODO_LOADINGBLOCKS == 0 ) + if ( KOMODO_LOADINGBLOCKS == 0 && height > 34000 ) { for (i=0; i<66; i++) fprintf(stderr,"%d ",i==0?notaryid:mids[i]); From e0848449e332d427eccb2dc3d0115487120ac096 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 13 Apr 2018 23:04:06 +0300 Subject: [PATCH 220/507] New notaries --- src/komodo_notary.h | 132 ++++++++++++++++++++++---------------------- 1 file changed, 66 insertions(+), 66 deletions(-) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 1a75caafc..82ec4c002 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -126,75 +126,75 @@ const char *Notaries_elected0[][2] = { "xxspot2_XX", "03d85b221ea72ebcd25373e7961f4983d12add66a92f899deaf07bab1d8b6f5573" } }; -#define KOMODO_NOTARIES_TIMESTAMP1 1530921600 // 7/7/2017 -#define KOMODO_NOTARIES_HEIGHT1 ((900000 / KOMODO_ELECTION_GAP) * KOMODO_ELECTION_GAP) +#define KOMODO_NOTARIES_TIMESTAMP1 1525132800 // May 1st 2018 1530921600 // 7/7/2017 +#define KOMODO_NOTARIES_HEIGHT1 ((820000 / KOMODO_ELECTION_GAP) * KOMODO_ELECTION_GAP) const char *Notaries_elected1[][2] = { - { "0_jl777_testA", "03b7621b44118017a16043f19b30cc8a4cfe068ac4e42417bae16ba460c80f3828" }, - { "0_jl777_testB", "02ebfc784a4ba768aad88d44d1045d240d47b26e248cafaf1c5169a42d7a61d344" }, - { "0_kolo_testA", "0287aa4b73988ba26cf6565d815786caf0d2c4af704d7883d163ee89cd9977edec" }, - { "artik_AR", "029acf1dcd9f5ff9c455f8bb717d4ae0c703e089d16cf8424619c491dff5994c90" }, - { "artik_EU", "03f54b2c24f82632e3cdebe4568ba0acf487a80f8a89779173cdb78f74514847ce" }, - { "artik_NA", "0224e31f93eff0cc30eaf0b2389fbc591085c0e122c4d11862c1729d090106c842" }, - { "artik_SH", "02bdd8840a34486f38305f311c0e2ae73e84046f6e9c3dd3571e32e58339d20937" }, - { "badass_EU", "0209d48554768dd8dada988b98aca23405057ac4b5b46838a9378b95c3e79b9b9e" }, - { "badass_NA", "02afa1a9f948e1634a29dc718d218e9d150c531cfa852843a1643a02184a63c1a7" }, - { "badass_SH", "026b49dd3923b78a592c1b475f208e23698d3f085c4c3b4906a59faf659fd9530b" }, - { "crackers_EU", "03bc819982d3c6feb801ec3b720425b017d9b6ee9a40746b84422cbbf929dc73c3" }, // 10 - { "crackers_NA", "03205049103113d48c7c7af811b4c8f194dafc43a50d5313e61a22900fc1805b45" }, - { "crackers_SH", "02be28310e6312d1dd44651fd96f6a44ccc269a321f907502aae81d246fabdb03e" }, - { "durerus_EU", "02bcbd287670bdca2c31e5d50130adb5dea1b53198f18abeec7211825f47485d57" }, - { "etszombi_AR", "031c79168d15edabf17d9ec99531ea9baa20039d0cdc14d9525863b83341b210e9" }, - { "etszombi_EU", "0281b1ad28d238a2b217e0af123ce020b79e91b9b10ad65a7917216eda6fe64bf7" }, // 15 - { "etszombi_SH", "025d7a193c0757f7437fad3431f027e7b5ed6c925b77daba52a8755d24bf682dde" }, - { "farl4web_EU", "0300ecf9121cccf14cf9423e2adb5d98ce0c4e251721fa345dec2e03abeffbab3f" }, - { "farl4web_SH", "0396bb5ed3c57aa1221d7775ae0ff751e4c7dc9be220d0917fa8bbdf670586c030" }, - { "fullmoon_AR", "0254b1d64840ce9ff6bec9dd10e33beb92af5f7cee628f999cb6bc0fea833347cc" }, - { "fullmoon_NA", "031fb362323b06e165231c887836a8faadb96eda88a79ca434e28b3520b47d235b" }, // 20 - { "fullmoon_SH", "030e12b42ec33a80e12e570b6c8274ce664565b5c3da106859e96a7208b93afd0d" }, - { "grewal_NA", "03adc0834c203d172bce814df7c7a5e13dc603105e6b0adabc942d0421aefd2132" }, - { "grewal_SH", "03212a73f5d38a675ee3cdc6e82542a96c38c3d1c79d25a1ed2e42fcf6a8be4e68" }, - { "indenodes_AR", "02ec0fa5a40f47fd4a38ea5c89e375ad0b6ddf4807c99733c9c3dc15fb978ee147" }, - { "indenodes_EU", "0221387ff95c44cb52b86552e3ec118a3c311ca65b75bf807c6c07eaeb1be8303c" }, - { "indenodes_NA", "02698c6f1c9e43b66e82dbb163e8df0e5a2f62f3a7a882ca387d82f86e0b3fa988" }, - { "indenodes_SH", "0334e6e1ec8285c4b85bd6dae67e17d67d1f20e7328efad17ce6fd24ae97cdd65e" }, - { "jeezy_EU", "023cb3e593fb85c5659688528e9a4f1c4c7f19206edc7e517d20f794ba686fd6d6" }, - { "jsgalt_NA", "027b3fb6fede798cd17c30dbfb7baf9332b3f8b1c7c513f443070874c410232446" }, - { "karasugoi_NA", "02a348b03b9c1a8eac1b56f85c402b041c9bce918833f2ea16d13452309052a982" }, // 30 - { "kashifali_EU", "033777c52a0190f261c6f66bd0e2bb299d30f012dcb8bfff384103211edb8bb207" }, - { "kolo_AR", "03016d19344c45341e023b72f9fb6e6152fdcfe105f3b4f50b82a4790ff54e9dc6" }, - { "kolo_SH", "02aa24064500756d9b0959b44d5325f2391d8e95c6127e109184937152c384e185" }, - { "metaphilibert_AR", "02adad675fae12b25fdd0f57250b0caf7f795c43f346153a31fe3e72e7db1d6ac6" }, - { "movecrypto_AR", "022783d94518e4dc77cbdf1a97915b29f427d7bc15ea867900a76665d3112be6f3" }, - { "movecrypto_EU", "021ab53bc6cf2c46b8a5456759f9d608966eff87384c2b52c0ac4cc8dd51e9cc42" }, - { "movecrypto_NA", "02efb12f4d78f44b0542d1c60146738e4d5506d27ec98a469142c5c84b29de0a80" }, - { "movecrypto_SH", "031f9739a3ebd6037a967ce1582cde66e79ea9a0551c54731c59c6b80f635bc859" }, - { "muros_AR", "022d77402fd7179335da39479c829be73428b0ef33fb360a4de6890f37c2aa005e" }, - { "noashh_AR", "029d93ef78197dc93892d2a30e5a54865f41e0ca3ab7eb8e3dcbc59c8756b6e355" }, // 40 - { "noashh_EU", "02061c6278b91fd4ac5cab4401100ffa3b2d5a277e8f71db23401cc071b3665546" }, - { "noashh_NA", "033c073366152b6b01535e15dd966a3a8039169584d06e27d92a69889b720d44e1" }, - { "nxtswe_EU", "032fb104e5eaa704a38a52c126af8f67e870d70f82977e5b2f093d5c1c21ae5899" }, - { "polycryptoblog_NA", "02708dcda7c45fb54b78469673c2587bfdd126e381654819c4c23df0e00b679622" }, - { "pondsea_AR", "032e1c213787312099158f2d74a89e8240a991d162d4ce8017d8504d1d7004f735" }, - { "pondsea_EU", "0225aa6f6f19e543180b31153d9e6d55d41bc7ec2ba191fd29f19a2f973544e29d" }, - { "pondsea_NA", "031bcfdbb62268e2ff8dfffeb9ddff7fe95fca46778c77eebff9c3829dfa1bb411" }, - { "pondsea_SH", "02209073bc0943451498de57f802650311b1f12aa6deffcd893da198a544c04f36" }, - { "popcornbag_AR", "02761f106fb34fbfc5ddcc0c0aa831ed98e462a908550b280a1f7bd32c060c6fa3" }, - { "popcornbag_NA", "03c6085c7fdfff70988fda9b197371f1caf8397f1729a844790e421ee07b3a93e8" }, // 50 - { "ptytrader_NA", "0328c61467148b207400b23875234f8a825cce65b9c4c9b664f47410b8b8e3c222" }, - { "ptytrader_SH", "0250c93c492d8d5a6b565b90c22bee07c2d8701d6118c6267e99a4efd3c7748fa4" }, - { "rnr_AR", "029bdb08f931c0e98c2c4ba4ef45c8e33a34168cb2e6bf953cef335c359d77bfcd" }, - { "rnr_EU", "03f5c08dadffa0ffcafb8dd7ffc38c22887bd02702a6c9ac3440deddcf2837692b" }, - { "rnr_NA", "02e17c5f8c3c80f584ed343b8dcfa6d710dfef0889ec1e7728ce45ce559347c58c" }, - { "rnr_SH", "037536fb9bdfed10251f71543fb42679e7c52308bcd12146b2568b9a818d8b8377" }, - { "titomane_AR", "03cda6ca5c2d02db201488a54a548dbfc10533bdc275d5ea11928e8d6ab33c2185" }, - { "titomane_EU", "02e41feded94f0cc59f55f82f3c2c005d41da024e9a805b41105207ef89aa4bfbd" }, - { "titomane_SH", "035f49d7a308dd9a209e894321f010d21b7793461b0c89d6d9231a3fe5f68d9960" }, - { "vanbreuk_EU", "024f3cad7601d2399c131fd070e797d9cd8533868685ddbe515daa53c2e26004c3" }, // 60 - { "xrobesx_NA", "03f0cc6d142d14a40937f12dbd99dbd9021328f45759e26f1877f2a838876709e1" }, - { "xxspot1_XX", "02ef445a392fcaf3ad4176a5da7f43580e8056594e003eba6559a713711a27f955" }, - { "xxspot2_XX", "03d85b221ea72ebcd25373e7961f4983d12add66a92f899deaf07bab1d8b6f5573" } + {"0dev1_jl777", "03b7621b44118017a16043f19b30cc8a4cfe068ac4e42417bae16ba460c80f3828" }, + {"0dev2_kolo", "030f34af4b908fb8eb2099accb56b8d157d49f6cfb691baa80fdd34f385efed961" }, + {"0dev3_kolo", "025af9d2b2a05338478159e9ac84543968fd18c45fd9307866b56f33898653b014" }, + {"0dev4_decker", "028eea44a09674dda00d88ffd199a09c9b75ba9782382cc8f1e97c0fd565fe5707" }, + {"a-team_SH", "03b59ad322b17cb94080dc8e6dc10a0a865de6d47c16fb5b1a0b5f77f9507f3cce" }, + {"artik_AR", "029acf1dcd9f5ff9c455f8bb717d4ae0c703e089d16cf8424619c491dff5994c90" }, + {"artik_EU", "03f54b2c24f82632e3cdebe4568ba0acf487a80f8a89779173cdb78f74514847ce" }, + {"artik_NA", "0224e31f93eff0cc30eaf0b2389fbc591085c0e122c4d11862c1729d090106c842" }, + {"artik_SH", "02bdd8840a34486f38305f311c0e2ae73e84046f6e9c3dd3571e32e58339d20937" }, + {"badass_EU", "0209d48554768dd8dada988b98aca23405057ac4b5b46838a9378b95c3e79b9b9e" }, + {"badass_NA", "02afa1a9f948e1634a29dc718d218e9d150c531cfa852843a1643a02184a63c1a7" }, + {"batman_AR", "033ecb640ec5852f42be24c3bf33ca123fb32ced134bed6aa2ba249cf31b0f2563" }, + {"batman_SH", "02ca5898931181d0b8aafc75ef56fce9c43656c0b6c9f64306e7c8542f6207018c" }, + {"ca333_EU", "03fc87b8c804f12a6bd18efd43b0ba2828e4e38834f6b44c0bfee19f966a12ba99" }, + {"chainmakers_EU", "02f3b08938a7f8d2609d567aebc4989eeded6e2e880c058fdf092c5da82c3bc5ee" }, + {"chainmakers_NA", "0276c6d1c65abc64c8559710b8aff4b9e33787072d3dda4ec9a47b30da0725f57a" }, + {"chainstrike_SH", "0370bcf10575d8fb0291afad7bf3a76929734f888228bc49e35c5c49b336002153" }, + {"cipi_AR", "02c4f89a5b382750836cb787880d30e23502265054e1c327a5bfce67116d757ce8" }, + {"cipi_NA", "02858904a2a1a0b44df4c937b65ee1f5b66186ab87a751858cf270dee1d5031f18" }, + {"crackers_EU", "03bc819982d3c6feb801ec3b720425b017d9b6ee9a40746b84422cbbf929dc73c3" }, + {"crackers_NA", "03205049103113d48c7c7af811b4c8f194dafc43a50d5313e61a22900fc1805b45" }, + {"dwy_EU", "0259c646288580221fdf0e92dbeecaee214504fdc8bbdf4a3019d6ec18b7540424" }, + {"emmanux_SH", "033f316114d950497fc1d9348f03770cd420f14f662ab2db6172df44c389a2667a" }, + {"etszombi_EU", "0281b1ad28d238a2b217e0af123ce020b79e91b9b10ad65a7917216eda6fe64bf7" }, + {"fullmoon_AR", "03380314c4f42fa854df8c471618751879f9e8f0ff5dbabda2bd77d0f96cb35676" }, + {"fullmoon_NA", "030216211d8e2a48bae9e5d7eb3a42ca2b7aae8770979a791f883869aea2fa6eef" }, + {"fullmoon_SH", "03f34282fa57ecc7aba8afaf66c30099b5601e98dcbfd0d8a58c86c20d8b692c64" }, + {"goldenman_EU", "02d6f13a8f745921cdb811e32237bb98950af1a5952be7b3d429abd9152f8e388d" }, + {"indenodes_AR", "02ec0fa5a40f47fd4a38ea5c89e375ad0b6ddf4807c99733c9c3dc15fb978ee147" }, + {"indenodes_EU", "0221387ff95c44cb52b86552e3ec118a3c311ca65b75bf807c6c07eaeb1be8303c" }, + {"indenodes_NA", "02698c6f1c9e43b66e82dbb163e8df0e5a2f62f3a7a882ca387d82f86e0b3fa988" }, + {"indenodes_SH", "0334e6e1ec8285c4b85bd6dae67e17d67d1f20e7328efad17ce6fd24ae97cdd65e" }, + {"jackson_AR", "038ff7cfe34cb13b524e0941d5cf710beca2ffb7e05ddf15ced7d4f14fbb0a6f69" }, + {"jeezy_EU", "023cb3e593fb85c5659688528e9a4f1c4c7f19206edc7e517d20f794ba686fd6d6" }, + {"karasugoi_NA", "02a348b03b9c1a8eac1b56f85c402b041c9bce918833f2ea16d13452309052a982" }, + {"komodoninja_EU", "038e567b99806b200b267b27bbca2abf6a3e8576406df5f872e3b38d30843cd5ba" }, + {"komodoninja_SH", "033178586896915e8456ebf407b1915351a617f46984001790f0cce3d6f3ada5c2" }, + {"komodopioneers_SH", "033ace50aedf8df70035b962a805431363a61cc4e69d99d90726a2d48fb195f68c" }, + {"libscott_SH", "03301a8248d41bc5dc926088a8cf31b65e2daf49eed7eb26af4fb03aae19682b95" }, + {"lukechilds_AR", "031aa66313ee024bbee8c17915cf7d105656d0ace5b4a43a3ab5eae1e14ec02696" }, + {"madmax_AR", "03891555b4a4393d655bf76f0ad0fb74e5159a615b6925907678edc2aac5e06a75" }, + {"meshbits_AR", "02957fd48ae6cb361b8a28cdb1b8ccf5067ff68eb1f90cba7df5f7934ed8eb4b2c" }, + {"meshbits_SH", "025c6e94877515dfd7b05682b9cc2fe4a49e076efe291e54fcec3add78183c1edb" }, + {"metaphilibert_AR", "02adad675fae12b25fdd0f57250b0caf7f795c43f346153a31fe3e72e7db1d6ac6" }, + {"metaphilibert_SH", "0284af1a5ef01503e6316a2ca4abf8423a794e9fc17ac6846f042b6f4adedc3309" }, + {"patchkez_SH", "0296270f394140640f8fa15684fc11255371abb6b9f253416ea2734e34607799c4" }, + {"pbca26_NA", "0276aca53a058556c485bbb60bdc54b600efe402a8b97f0341a7c04803ce204cb5" }, + {"peer2cloud_AR", "034e5563cb885999ae1530bd66fab728e580016629e8377579493b386bf6cebb15" }, + {"peer2cloud_SH", "03396ac453b3f23e20f30d4793c5b8ab6ded6993242df4f09fd91eb9a4f8aede84" }, + {"polycryptoblog_NA", "02708dcda7c45fb54b78469673c2587bfdd126e381654819c4c23df0e00b679622" }, + {"hyper_AR", "020f2f984d522051bd5247b61b080b4374a7ab389d959408313e8062acad3266b4" }, + {"hyper_EU", "03d00cf9ceace209c59fb013e112a786ad583d7de5ca45b1e0df3b4023bb14bf51" }, + {"hyper_SH", "0383d0b37f59f4ee5e3e98a47e461c861d49d0d90c80e9e16f7e63686a2dc071f3" }, + {"hyper_NA", "03d91c43230336c0d4b769c9c940145a8c53168bf62e34d1bccd7f6cfc7e5592de" }, + {"popcornbag_AR", "02761f106fb34fbfc5ddcc0c0aa831ed98e462a908550b280a1f7bd32c060c6fa3" }, + {"popcornbag_NA", "03c6085c7fdfff70988fda9b197371f1caf8397f1729a844790e421ee07b3a93e8" }, + {"alien_AR", "0348d9b1fc6acf81290405580f525ee49b4749ed4637b51a28b18caa26543b20f0" }, + {"alien_EU", "020aab8308d4df375a846a9e3b1c7e99597b90497efa021d50bcf1bbba23246527" }, + {"thegaltmines_NA", "031bea28bec98b6380958a493a703ddc3353d7b05eb452109a773eefd15a32e421" }, + {"titomane_AR", "029d19215440d8cb9cc6c6b7a4744ae7fb9fb18d986e371b06aeb34b64845f9325" }, + {"titomane_EU", "0360b4805d885ff596f94312eed3e4e17cb56aa8077c6dd78d905f8de89da9499f" }, + {"titomane_SH", "03573713c5b20c1e682a2e8c0f8437625b3530f278e705af9b6614de29277a435b" }, + {"webworker01_NA", "03bb7d005e052779b1586f071834c5facbb83470094cff5112f0072b64989f97d7" }, + {"xrobesx_NA", "03f0cc6d142d14a40937f12dbd99dbd9021328f45759e26f1877f2a838876709e1" }, }; int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) From 54c737f0971dc0392a40d2965cb9b6751505cf7a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 00:02:56 +0300 Subject: [PATCH 221/507] Test --- src/komodo_notary.h | 46 --------------------------------------------- 1 file changed, 46 deletions(-) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 82ec4c002..cce57596b 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -540,50 +540,4 @@ void komodo_init(int32_t height) didinit = 1; komodo_stateupdate(0,0,0,0,zero,0,0,0,0,0,0,0,0,0,0,zero,0); } - /*else if ( 0 && height == KOMODO_MAINNET_START ) - { - n = (int32_t)(sizeof(Notaries_elected)/sizeof(*Notaries_elected)); - for (k=0; k 0 ) - { - for (i=0; i Date: Sat, 14 Apr 2018 00:10:36 +0300 Subject: [PATCH 222/507] Test --- src/pow.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index 61c50469f..d9cab230b 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -212,12 +212,6 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in if ( height > 792000 ) return false; } - if ( KOMODO_LOADINGBLOCKS == 0 && height > 34000 ) - { - for (i=0; i<66; i++) - fprintf(stderr,"%d ",i==0?notaryid:mids[i]); - fprintf(stderr,"mids ht.%d\n",height); - } return true; } From 5c7c4cc92bcb231cd1ca665e2fa4be74dacb9f12 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 00:19:07 +0300 Subject: [PATCH 223/507] Test --- src/pow.cpp | 43 ++++++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index d9cab230b..a973f24a3 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -189,28 +189,29 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in { if ( KOMODO_LOADINGBLOCKS != 0 ) return true; - for (i=31; i>=0; i--) - printf("%02x",((uint8_t *)&hash)[i]); - printf(" hash vs "); - for (i=31; i>=0; i--) - printf("%02x",((uint8_t *)&bnTarget)[i]); - printf(" ht.%d special.%d notaryid.%d ht.%d mod.%d error\n",height,special,notaryid,height,(height % 35)); - /*if ( pindex != 0 ) + if ( ASSETCHAINS_SYMBOL[0] == 0 ) { - pindex->didinit = 0; - komodo_index2pubkey33(pubkey33,pindex,height); - }*/ - for (i=0; i<33; i++) - printf("%02x",pubkey33[i]); - printf(" <- pubkey\n"); - for (i=0; i<33; i++) - printf("%02x",origpubkey33[i]); - printf(" <- origpubkey\n"); - for (i=0; i<66; i++) - printf("%d ",mids[i]); - printf(" minerids from ht.%d pindex.%p\n",height,pindex); - if ( height > 792000 ) - return false; + if ( height > 790000 ) + { + for (i=31; i>=0; i--) + printf("%02x",((uint8_t *)&hash)[i]); + printf(" hash vs "); + for (i=31; i>=0; i--) + printf("%02x",((uint8_t *)&bnTarget)[i]); + printf(" ht.%d special.%d notaryid.%d ht.%d mod.%d error\n",height,special,notaryid,height,(height % 35)); + for (i=0; i<33; i++) + printf("%02x",pubkey33[i]); + printf(" <- pubkey\n"); + for (i=0; i<33; i++) + printf("%02x",origpubkey33[i]); + printf(" <- origpubkey\n"); + for (i=0; i<66; i++) + printf("%d ",mids[i]); + printf(" minerids from ht.%d pindex.%p\n",height,pindex); + } + if ( height > 792000 ) + return false; + } else return false; } return true; } From 092896124f54410caa11d8fa1497d26437a273f9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 00:21:12 +0300 Subject: [PATCH 224/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 009297242..b7b945353 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -189,7 +189,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in { if ( KOMODO_LOADINGBLOCKS != 0 ) return true; - if ( height > 792000 ) + if ( ASSETCHAINS_SYMBOL[0] != 0 || height > 792000 ) return false; } return true; From 83cabb7d1b969cf3b69502f5654957dae52ab227 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 00:25:02 +0300 Subject: [PATCH 225/507] Test --- src/komodo_bitcoind.h | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index dd95bbef0..95ec0f095 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -861,9 +861,12 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh { if ( mids[i] == notaryid ) { - for (j=0; j<66; j++) - fprintf(stderr,"%d ",mids[j]); - fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,notaryid,i); + if ( height > 700000 ) + { + for (j=0; j<66; j++) + fprintf(stderr,"%d ",mids[j]); + fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,notaryid,i); + } if ( height > 792000 ) return(-1); else break; From 20dfaa77f51ef809e689a6d5e955d4e4e358aee0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 01:30:23 +0300 Subject: [PATCH 226/507] New notaries activate height 820000 Bugfix for 790833 bug Performance improvements If your node crashed, you should be able to just pull and rebuild and it should startup. We are not seeing the need to resync on most nodes. If you are mining, this is a must update right away --- src/init.cpp | 4 + src/komodo.h | 8 +- src/komodo_bitcoind.h | 465 +++++++++++++++++++++++++++--------------- src/komodo_globals.h | 2 +- src/komodo_notary.h | 338 +++++++++++++++++++----------- src/komodo_utils.h | 4 +- src/main.cpp | 74 +++++-- src/miner.cpp | 4 +- src/pow.cpp | 84 ++++---- src/rpcblockchain.cpp | 96 +++++---- src/rpcmisc.cpp | 4 +- 11 files changed, 680 insertions(+), 403 deletions(-) diff --git a/src/init.cpp b/src/init.cpp index fe10401a8..79552a76f 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -62,6 +62,7 @@ using namespace std; extern void ThreadSendAlert(); +extern int32_t KOMODO_LOADINGBLOCKS; ZCJoinSplit* pzcashParams = NULL; @@ -596,6 +597,7 @@ void ThreadImport(std::vector vImportFiles) LogPrintf("Reindexing finished\n"); // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): InitBlockIndex(); + KOMODO_LOADINGBLOCKS = 0; } // hardcoded $DATADIR/bootstrap.dat @@ -1335,6 +1337,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) strLoadError = _("Error initializing block database"); break; } + KOMODO_LOADINGBLOCKS = 0; // Check for changed -txindex state if (fTxIndex != GetBoolArg("-txindex", true)) { @@ -1389,6 +1392,7 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) } } } + KOMODO_LOADINGBLOCKS = 0; // As LoadBlockIndex can take several minutes, it's possible the user // requested to kill the GUI during the last operation. If so, exit. diff --git a/src/komodo.h b/src/komodo.h index c6467d957..129ea3b5f 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -473,7 +473,7 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar } } -int32_t komodo_voutupdate(int32_t *isratificationp,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,uint64_t value,int32_t notarized,uint64_t signedmask) +int32_t komodo_voutupdate(int32_t *isratificationp,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,uint64_t value,int32_t notarized,uint64_t signedmask,uint32_t timestamp) { static uint256 zero; static FILE *signedfp; int32_t opretlen,nid,k,len = 0; uint256 kmdtxid,desttxid; uint8_t crypto777[33]; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; @@ -499,7 +499,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr *specialtxp = 1; //printf(">>>>>>>> "); } - else if ( komodo_chosennotary(&nid,height,scriptbuf + 1) >= 0 ) + else if ( komodo_chosennotary(&nid,height,scriptbuf + 1,timestamp) >= 0 ) { //printf("found notary.k%d\n",k); if ( notaryid < 64 ) @@ -646,7 +646,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block) return; } //fprintf(stderr,"%s connect.%d\n",ASSETCHAINS_SYMBOL,pindex->nHeight); - numnotaries = komodo_notaries(pubkeys,pindex->nHeight); + numnotaries = komodo_notaries(pubkeys,pindex->nHeight,pindex->GetBlockTime()); calc_rmd160_sha256(rmd160,pubkeys[0],33); if ( pindex->nHeight > hwmheight ) hwmheight = pindex->nHeight; @@ -741,7 +741,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block) #else memcpy(scriptbuf,(uint8_t *)&block.vtx[i].vout[j].scriptPubKey[0],len); #endif - notaryid = komodo_voutupdate(&isratification,notaryid,scriptbuf,len,height,txhash,i,j,&voutmask,&specialtx,¬arizedheight,(uint64_t)block.vtx[i].vout[j].nValue,notarized,signedmask); + notaryid = komodo_voutupdate(&isratification,notaryid,scriptbuf,len,height,txhash,i,j,&voutmask,&specialtx,¬arizedheight,(uint64_t)block.vtx[i].vout[j].nValue,notarized,signedmask,(uint32_t)chainActive.Tip()->GetBlockTime()); if ( 0 && i > 0 ) { for (k=0; k> 1; decode_hex(script,len,hexstr); + if ( script[1] == 0x4c ) + { + script++; + len--; + } + else if ( script[1] == 0x4d ) + { + script += 2; + len -= 2; + } retval = komodo_verifynotarizedscript(height,script,len,NOTARIZED_HASH); } } @@ -486,54 +500,54 @@ int32_t komodo_verifynotarization(char *symbol,char *dest,int32_t height,int32_t } /*uint256 komodo_getblockhash(int32_t height) -{ - uint256 hash; char params[128],*hexstr,*jsonstr; cJSON *result; int32_t i; uint8_t revbuf[32]; - memset(&hash,0,sizeof(hash)); - sprintf(params,"[%d]",height); - if ( (jsonstr= komodo_issuemethod(KMDUSERPASS,(char *)"getblockhash",params,BITCOIND_PORT)) != 0 ) - { - if ( (result= cJSON_Parse(jsonstr)) != 0 ) - { - if ( (hexstr= jstr(result,(char *)"result")) != 0 ) - { - if ( is_hexstr(hexstr,0) == 64 ) - { - decode_hex(revbuf,32,hexstr); - for (i=0; i<32; i++) - ((uint8_t *)&hash)[i] = revbuf[31-i]; - } - } - free_json(result); - } - printf("KMD hash.%d (%s) %x\n",height,jsonstr,*(uint32_t *)&hash); - free(jsonstr); - } - return(hash); -} - -uint256 _komodo_getblockhash(int32_t height);*/ + { + uint256 hash; char params[128],*hexstr,*jsonstr; cJSON *result; int32_t i; uint8_t revbuf[32]; + memset(&hash,0,sizeof(hash)); + sprintf(params,"[%d]",height); + if ( (jsonstr= komodo_issuemethod(KMDUSERPASS,(char *)"getblockhash",params,BITCOIND_PORT)) != 0 ) + { + if ( (result= cJSON_Parse(jsonstr)) != 0 ) + { + if ( (hexstr= jstr(result,(char *)"result")) != 0 ) + { + if ( is_hexstr(hexstr,0) == 64 ) + { + decode_hex(revbuf,32,hexstr); + for (i=0; i<32; i++) + ((uint8_t *)&hash)[i] = revbuf[31-i]; + } + } + free_json(result); + } + printf("KMD hash.%d (%s) %x\n",height,jsonstr,*(uint32_t *)&hash); + free(jsonstr); + } + return(hash); + } + + uint256 _komodo_getblockhash(int32_t height);*/ uint64_t komodo_seed(int32_t height) { uint64_t seed = 0; /*if ( 0 ) // problem during init time, seeds are needed for loading blockindex, so null seeds... - { - uint256 hash,zero; CBlockIndex *pindex; - memset(&hash,0,sizeof(hash)); - memset(&zero,0,sizeof(zero)); - if ( height > 10 ) - height -= 10; - if ( ASSETCHAINS_SYMBOL[0] == 0 ) - hash = _komodo_getblockhash(height); - if ( memcmp(&hash,&zero,sizeof(hash)) == 0 ) - hash = komodo_getblockhash(height); - int32_t i; - for (i=0; i<32; i++) - printf("%02x",((uint8_t *)&hash)[i]); - printf(" seed.%d\n",height); - seed = arith_uint256(hash.GetHex()).GetLow64(); - } - else*/ + { + uint256 hash,zero; CBlockIndex *pindex; + memset(&hash,0,sizeof(hash)); + memset(&zero,0,sizeof(zero)); + if ( height > 10 ) + height -= 10; + if ( ASSETCHAINS_SYMBOL[0] == 0 ) + hash = _komodo_getblockhash(height); + if ( memcmp(&hash,&zero,sizeof(hash)) == 0 ) + hash = komodo_getblockhash(height); + int32_t i; + for (i=0; i<32; i++) + printf("%02x",((uint8_t *)&hash)[i]); + printf(" seed.%d\n",height); + seed = arith_uint256(hash.GetHex()).GetLow64(); + } + else*/ { seed = (height << 13) ^ (height << 2); seed <<= 21; @@ -543,20 +557,27 @@ uint64_t komodo_seed(int32_t height) return(seed); } -uint32_t komodo_txtime(uint256 hash) +uint32_t komodo_txtime(uint64_t *valuep,uint256 hash,int32_t n,char *destaddr) { - CTransaction tx; - uint256 hashBlock; + CTxDestination address; CTransaction tx; uint256 hashBlock; + *valuep = 0; if (!GetTransaction(hash, tx, #ifndef KOMODO_ZCASH Params().GetConsensus(), #endif hashBlock, true)) { - //printf("null GetTransaction\n"); - return(tx.nLockTime); + fprintf(stderr,"ERROR: %s/v%d locktime.%u\n",hash.ToString().c_str(),n,(uint32_t)tx.nLockTime); + return(0); } - return(0); + //fprintf(stderr,"%s/v%d locktime.%u\n",hash.ToString().c_str(),n,(uint32_t)tx.nLockTime); + if ( n < tx.vout.size() ) + { + *valuep = tx.vout[n].nValue; + if (ExtractDestination(tx.vout[n].scriptPubKey, address)) + strcpy(destaddr,CBitcoinAddress(address).ToString().c_str()); + } + return(tx.nLockTime); } void komodo_disconnect(CBlockIndex *pindex,CBlock& block) @@ -574,7 +595,7 @@ void komodo_disconnect(CBlockIndex *pindex,CBlock& block) int32_t komodo_is_notarytx(const CTransaction& tx) { - uint8_t *ptr,crypto777[33]; + uint8_t *ptr; static uint8_t crypto777[33]; if ( tx.vout.size() > 0 ) { #ifdef KOMODO_ZCASH @@ -584,7 +605,8 @@ int32_t komodo_is_notarytx(const CTransaction& tx) #endif if ( ptr != 0 ) { - decode_hex(crypto777,33,(char *)CRYPTO777_PUBSECPSTR); + if ( crypto777[0] == 0 ) + decode_hex(crypto777,33,(char *)CRYPTO777_PUBSECPSTR); if ( memcmp(ptr+1,crypto777,33) == 0 ) { //printf("found notarytx\n"); @@ -597,7 +619,14 @@ int32_t komodo_is_notarytx(const CTransaction& tx) int32_t komodo_block2height(CBlock *block) { - int32_t i,n,height = 0; uint8_t *ptr; + static uint32_t match,mismatch; + int32_t i,n,height2=-1,height = 0; uint8_t *ptr; CBlockIndex *pindex; + if ( (pindex= mapBlockIndex[block->GetHash()]) != 0 ) + { + height2 = (int32_t)pindex->nHeight; + if ( height2 >= 0 ) + return(height2); + } if ( block->vtx[0].vin.size() > 0 ) { #ifdef KOMODO_ZCASH @@ -610,7 +639,7 @@ int32_t komodo_block2height(CBlock *block) //for (i=0; i<6; i++) // printf("%02x",ptr[i]); n = ptr[0]; - for (i=0; i= 0 ) + height = height2; + } else match++; return(height); } -void komodo_block2pubkey33(uint8_t *pubkey33,CBlock& block) +void komodo_block2pubkey33(uint8_t *pubkey33,CBlock *block) { int32_t n; - memset(pubkey33,0,33); - if ( block.vtx[0].vout.size() > 0 ) + if ( KOMODO_LOADINGBLOCKS == 0 ) + memset(pubkey33,0xff,33); + else memset(pubkey33,0,33); + if ( block->vtx[0].vout.size() > 0 ) { #ifdef KOMODO_ZCASH - uint8_t *ptr = (uint8_t *)block.vtx[0].vout[0].scriptPubKey.data(); + uint8_t *ptr = (uint8_t *)block->vtx[0].vout[0].scriptPubKey.data(); #else - uint8_t *ptr = (uint8_t *)&block.vtx[0].vout[0].scriptPubKey[0]; + uint8_t *ptr = (uint8_t *)&block->vtx[0].vout[0].scriptPubKey[0]; #endif //komodo_init(0); - n = block.vtx[0].vout[0].scriptPubKey.size(); + n = block->vtx[0].vout[0].scriptPubKey.size(); if ( n == 35 ) memcpy(pubkey33,ptr+1,33); } @@ -658,6 +696,13 @@ int32_t komodo_blockload(CBlock& block,CBlockIndex *pindex) return(0); } +uint32_t komodo_chainactive_timestamp() +{ + if ( chainActive.Tip() != 0 ) + return((uint32_t)chainActive.Tip()->GetBlockTime()); + else return(0); +} + CBlockIndex *komodo_chainactive(int32_t height) { if ( chainActive.Tip() != 0 ) @@ -675,73 +720,112 @@ uint32_t komodo_heightstamp(int32_t height) CBlockIndex *ptr; if ( height > 0 && (ptr= komodo_chainactive(height)) != 0 ) return(ptr->nTime); - else fprintf(stderr,"komodo_heightstamp null ptr for block.%d\n",height); + //else fprintf(stderr,"komodo_heightstamp null ptr for block.%d\n",height); return(0); } +/*void komodo_pindex_init(CBlockIndex *pindex,int32_t height) gets data corrupted + { + int32_t i,num; uint8_t pubkeys[64][33]; CBlock block; + if ( pindex->didinit != 0 ) + return; + //printf("pindex.%d komodo_pindex_init notary.%d from height.%d\n",pindex->nHeight,pindex->notaryid,height); + if ( pindex->didinit == 0 ) + { + pindex->notaryid = -1; + if ( KOMODO_LOADINGBLOCKS == 0 ) + memset(pindex->pubkey33,0xff,33); + else memset(pindex->pubkey33,0,33); + if ( komodo_blockload(block,pindex) == 0 ) + { + komodo_block2pubkey33(pindex->pubkey33,&block); + //for (i=0; i<33; i++) + // fprintf(stderr,"%02x",pindex->pubkey33[i]); + //fprintf(stderr," set pubkey at height %d/%d\n",pindex->nHeight,height); + //if ( pindex->pubkey33[0] == 2 || pindex->pubkey33[0] == 3 ) + // pindex->didinit = (KOMODO_LOADINGBLOCKS == 0); + } // else fprintf(stderr,"error loading block at %d/%d",pindex->nHeight,height); + } + if ( pindex->didinit != 0 && pindex->nHeight >= 0 && (num= komodo_notaries(pubkeys,(int32_t)pindex->nHeight,(uint32_t)pindex->nTime)) > 0 ) + { + for (i=0; ipubkey33,33) == 0 ) + { + pindex->notaryid = i; + break; + } + } + if ( 0 && i == num ) + { + for (i=0; i<33; i++) + fprintf(stderr,"%02x",pindex->pubkey33[i]); + fprintf(stderr," unmatched pubkey at height %d/%d\n",pindex->nHeight,height); + } + } + }*/ + void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) { - CBlock block; - //komodo_init(height); + int32_t num,i; CBlock block; memset(pubkey33,0,33); if ( pindex != 0 ) { if ( komodo_blockload(block,pindex) == 0 ) - komodo_block2pubkey33(pubkey33,block); - } - else - { - // height -> pubkey33 - //printf("extending chaintip komodo_index2pubkey33 height.%d need to get pubkey33\n",height); + komodo_block2pubkey33(pubkey33,&block); } } -void komodo_connectpindex(CBlockIndex *pindex) -{ - CBlock block; - if ( komodo_blockload(block,pindex) == 0 ) - komodo_connectblock(pindex,block); -} - -int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height); -int32_t komodo_electednotary(uint8_t *pubkey33,int32_t height); - -int8_t komodo_minerid(int32_t height,uint8_t *pubkey33) -{ - int32_t num,i; CBlockIndex *pindex; uint8_t _pubkey33[33],pubkeys[64][33]; - if ( pubkey33 == 0 && (pindex= chainActive[height]) != 0 ) - { - if ( pubkey33 == 0 ) - { - pubkey33 = _pubkey33; - komodo_index2pubkey33(pubkey33,pindex,height); - } - if ( (num= komodo_notaries(pubkeys,height)) > 0 ) - { - for (i=0; ididinit != 0 ) + { + if ( destpubkey33 != 0 ) + memcpy(destpubkey33,pindex->pubkey33,33); + return(pindex->notaryid); + } + komodo_index2pubkey33(pubkey33,pindex,height); + if ( destpubkey33 != 0 ) + memcpy(destpubkey33,pindex->pubkey33,33); + if ( pindex->didinit != 0 ) + return(pindex->notaryid); + timestamp = pindex->GetBlockTime(); + if ( (num= komodo_notaries(pubkeys,height,timestamp)) > 0 ) + { + for (i=0; i= 0 ) + if ( komodo_blockload(block,pindex) == 0 ) { - //mids[i] = *(int32_t *)pubkey33; - (*nonzpkeysp)++; - } + komodo_block2pubkey33(pubkeys[i],&block); + for (j=0; j= 0 && i > 0 && mids[i] == mids[0] ) duplicate++; } @@ -751,50 +835,90 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non else return(0); } -int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) +int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // deprecate { - int32_t i,n=0; - for (i=0; i= 225000 ) - komodo_chosennotary(¬aryid,height,_pubkey33); - if ( height >= 34000 && notaryid >= 0 ) + int32_t i,j,notaryid=0,minerid,limit,nid; uint8_t destpubkey33[33]; + komodo_chosennotary(¬aryid,height,pubkey33,timestamp); + if ( height >= 82000 ) { - if ( height < 79693 ) - limit = 64; - else if ( height < 82000 ) - limit = 8; - else limit = 66; - for (i=1; i= 0 ) { - komodo_chosennotary(&nid,height-i,_pubkey33); - if ( nid == notaryid ) //komodo_minerid(height-i,_pubkey33) + for (i=1; i<66; i++) { - if ( (0) && notaryid > 0 ) - fprintf(stderr,"ht.%d notaryid.%d already mined -i.%d nid.%d\n",height,notaryid,i,nid); - if ( height > 225000 ) - return(-1); + if ( mids[i] == notaryid ) + { + //for (j=0; j<66; j++) + // fprintf(stderr,"%d ",mids[j]); + //fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,notaryid,i); + if ( height > 792000 ) + return(-1); + else break; + } } + return(1); + } else return(0); + } + else + { + if ( height >= 34000 && notaryid >= 0 ) + { + if ( height < 79693 ) + limit = 64; + else if ( height < 82000 ) + limit = 8; + else limit = 66; + for (i=1; i 225000 ) + return(-1); + } + } + //fprintf(stderr,"special notaryid.%d ht.%d limit.%d\n",notaryid,height,limit); + return(1); } - //fprintf(stderr,"special notaryid.%d ht.%d limit.%d\n",notaryid,height,limit); - return(1); } return(0); } +/*int32_t komodo_MoM(int32_t *notarized_heightp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip) +{ + int32_t depth,notarized_ht; uint256 MoM,kmdtxid; + depth = komodo_MoMdata(¬arized_ht,&MoM,&kmdtxid,nHeight,MoMoMp,MoMoMoffsetp,MoMoMdepthp,kmdstartip,kmdendip); + memset(MoMp,0,sizeof(*MoMp)); + memset(kmdtxidp,0,sizeof(*kmdtxidp)); + *notarized_heightp = 0; + if ( depth > 0 && notarized_ht > 0 && nHeight > notarized_ht-depth && nHeight <= notarized_ht ) + { + *MoMp = MoM; + *notarized_heightp = notarized_ht; + *kmdtxidp = kmdtxid; + } + return(depth); +}*/ + int32_t komodo_checkpoint(int32_t *notarized_heightp,int32_t nHeight,uint256 hash) { - int32_t notarized_height; uint256 notarized_hash,notarized_desttxid; CBlockIndex *notary; CBlockIndex *pindex; + int32_t notarized_height,MoMdepth; uint256 MoM,notarized_hash,notarized_desttxid; CBlockIndex *notary,*pindex; if ( (pindex= chainActive.Tip()) == 0 ) return(-1); notarized_height = komodo_notarizeddata(pindex->nHeight,¬arized_hash,¬arized_desttxid); @@ -806,17 +930,18 @@ int32_t komodo_checkpoint(int32_t *notarized_heightp,int32_t nHeight,uint256 has { if ( nHeight < notarized_height ) { - fprintf(stderr,"nHeight.%d < NOTARIZED_HEIGHT.%d\n",nHeight,notarized_height); + //fprintf(stderr,"[%s] nHeight.%d < NOTARIZED_HEIGHT.%d\n",ASSETCHAINS_SYMBOL,nHeight,notarized_height); return(-1); } else if ( nHeight == notarized_height && memcmp(&hash,¬arized_hash,sizeof(hash)) != 0 ) { - fprintf(stderr,"nHeight.%d == NOTARIZED_HEIGHT.%d, diff hash\n",nHeight,notarized_height); + fprintf(stderr,"[%s] nHeight.%d == NOTARIZED_HEIGHT.%d, diff hash\n",ASSETCHAINS_SYMBOL,nHeight,notarized_height); return(-1); } - } else fprintf(stderr,"unexpected error notary_hash %s ht.%d at ht.%d\n",notarized_hash.ToString().c_str(),notarized_height,notary->nHeight); - } else if ( notarized_height > 0 && notarized_height != 73880 && notarized_height >= 170000 ) - fprintf(stderr,"[%s] couldnt find notarized.(%s %d) ht.%d\n",ASSETCHAINS_SYMBOL,notarized_hash.ToString().c_str(),notarized_height,pindex->nHeight); + } else fprintf(stderr,"[%s] unexpected error notary_hash %s ht.%d at ht.%d\n",ASSETCHAINS_SYMBOL,notarized_hash.ToString().c_str(),notarized_height,notary->nHeight); + } + //else if ( notarized_height > 0 && notarized_height != 73880 && notarized_height >= 170000 ) + // fprintf(stderr,"[%s] couldnt find notarized.(%s %d) ht.%d\n",ASSETCHAINS_SYMBOL,notarized_hash.ToString().c_str(),notarized_height,pindex->nHeight); return(0); } @@ -831,12 +956,13 @@ uint32_t komodo_interest_args(uint32_t *txheighttimep,int32_t *txheightp,uint32_ uint32_t locktime = 0; if ( n < tx.vout.size() ) { - if ( (pindex= mapBlockIndex[hashBlock]) != 0 && (tipindex= chainActive.Tip()) != 0 ) + if ( (pindex= mapBlockIndex[hashBlock]) != 0 ) { *valuep = tx.vout[n].nValue; *txheightp = pindex->nHeight; *txheighttimep = pindex->nTime; - *tiptimep = tipindex->nTime; + if ( *tiptimep == 0 && (tipindex= chainActive.Tip()) != 0 ) + *tiptimep = (uint32_t)tipindex->nTime; locktime = tx.nLockTime; //fprintf(stderr,"tx locktime.%u %.8f height.%d | tiptime.%u\n",locktime,(double)*valuep/COIN,*txheightp,*tiptimep); } @@ -845,9 +971,13 @@ uint32_t komodo_interest_args(uint32_t *txheighttimep,int32_t *txheightp,uint32_ } uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime); -uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue) + +uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue,int32_t tipheight) { - uint64_t value; uint32_t tiptime,txheighttimep; + uint64_t value; uint32_t tiptime=0,txheighttimep; CBlockIndex *pindex; + if ( (pindex= chainActive[tipheight]) != 0 ) + tiptime = (uint32_t)pindex->nTime; + else fprintf(stderr,"cant find height[%d]\n",tipheight); if ( (*locktimep= komodo_interest_args(&txheighttimep,txheightp,&tiptime,&value,hash,n)) != 0 ) { if ( (checkvalue == 0 || value == checkvalue) && (checkheight == 0 || *txheightp == checkheight) ) @@ -882,7 +1012,7 @@ int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_ { if ( tx.nLockTime != 1477258935 || dispflag != 0 ) { - //fprintf(stderr,"komodo_validate_interest.%d reject.%d [%d] locktime %u cmp2.%u\n",dispflag,txheight,(int32_t)(tx.nLockTime - (cmptime-3600)),(uint32_t)tx.nLockTime,cmptime); + fprintf(stderr,"komodo_validate_interest.%d reject.%d [%d] locktime %u cmp2.%u\n",dispflag,txheight,(int32_t)(tx.nLockTime - (cmptime-3600)),(uint32_t)tx.nLockTime,cmptime); } return(-1); } @@ -892,3 +1022,4 @@ int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_ } return(0); } + diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 144064d7a..904b57344 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -21,7 +21,7 @@ int32_t komodo_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *n char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port); void komodo_init(int32_t height); void komodo_assetchain_pubkeys(char *jsonstr); -int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33); +int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); int32_t komodo_isrealtime(int32_t *kmdheightp); uint64_t komodo_paxtotal(); int32_t komodo_longestchain(); diff --git a/src/komodo_notary.h b/src/komodo_notary.h index a306f848f..f5c65dac3 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -13,6 +13,7 @@ * * ******************************************************************************/ + #include "komodo_defs.h" #include "komodo_cJSON.h" @@ -58,7 +59,7 @@ const char *Notaries_genesis[][2] = { "titomane_SH", "035f49d7a308dd9a209e894321f010d21b7793461b0c89d6d9231a3fe5f68d9960" }, }; -const char *Notaries_elected[][2] = +const char *Notaries_elected0[][2] = { { "0_jl777_testA", "03b7621b44118017a16043f19b30cc8a4cfe068ac4e42417bae16ba460c80f3828" }, { "0_jl777_testB", "02ebfc784a4ba768aad88d44d1045d240d47b26e248cafaf1c5169a42d7a61d344" }, @@ -126,64 +127,127 @@ const char *Notaries_elected[][2] = { "xxspot2_XX", "03d85b221ea72ebcd25373e7961f4983d12add66a92f899deaf07bab1d8b6f5573" } }; -int32_t komodo_electednotary(uint8_t *pubkey33,int32_t height) -{ - char pubkeystr[67]; int32_t i; uint8_t legacy33[33]; - for (i=0; i<33; i++) - sprintf(&pubkeystr[i*2],"%02x",pubkey33[i]); - pubkeystr[66] = 0; - //printf("%s vs\n",pubkeystr); - for (i=0; i elected %s\n",i,(char *)Notaries_elected[i][1]); - return(i); - } - } - /*if ( height < 300000 ) - { - for (i=0; i elected %s\n",i,(char *)Notaries_elected[i][1]); - return(i+64); - } - } - decode_hex(legacy33,33,(char *)"0252b6185bf8ea7efe8bbc345ddc8da87329149f30233088387abd716d4aa9e974"); - if ( memcmp(pubkey33,legacy33,33) == 0 ) - return(128); - }*/ - return(-1); -} +#define KOMODO_NOTARIES_TIMESTAMP1 1525132800 // May 1st 2018 1530921600 // 7/7/2017 +#define KOMODO_NOTARIES_HEIGHT1 ((820000 / KOMODO_ELECTION_GAP) * KOMODO_ELECTION_GAP) -int32_t komodo_ratify_threshold(int32_t height,uint64_t signedmask) +const char *Notaries_elected1[][2] = { - int32_t htind,numnotaries,i,wt = 0; - htind = height / KOMODO_ELECTION_GAP; - numnotaries = Pubkeys[htind].numnotaries; - for (i=0; i (numnotaries >> 1) || (wt > 7 && (signedmask & 1) != 0) ) - return(1); - else return(0); -} + {"0dev1_jl777", "03b7621b44118017a16043f19b30cc8a4cfe068ac4e42417bae16ba460c80f3828" }, + {"0dev2_kolo", "030f34af4b908fb8eb2099accb56b8d157d49f6cfb691baa80fdd34f385efed961" }, + {"0dev3_kolo", "025af9d2b2a05338478159e9ac84543968fd18c45fd9307866b56f33898653b014" }, + {"0dev4_decker", "028eea44a09674dda00d88ffd199a09c9b75ba9782382cc8f1e97c0fd565fe5707" }, + {"a-team_SH", "03b59ad322b17cb94080dc8e6dc10a0a865de6d47c16fb5b1a0b5f77f9507f3cce" }, + {"artik_AR", "029acf1dcd9f5ff9c455f8bb717d4ae0c703e089d16cf8424619c491dff5994c90" }, + {"artik_EU", "03f54b2c24f82632e3cdebe4568ba0acf487a80f8a89779173cdb78f74514847ce" }, + {"artik_NA", "0224e31f93eff0cc30eaf0b2389fbc591085c0e122c4d11862c1729d090106c842" }, + {"artik_SH", "02bdd8840a34486f38305f311c0e2ae73e84046f6e9c3dd3571e32e58339d20937" }, + {"badass_EU", "0209d48554768dd8dada988b98aca23405057ac4b5b46838a9378b95c3e79b9b9e" }, + {"badass_NA", "02afa1a9f948e1634a29dc718d218e9d150c531cfa852843a1643a02184a63c1a7" }, + {"batman_AR", "033ecb640ec5852f42be24c3bf33ca123fb32ced134bed6aa2ba249cf31b0f2563" }, + {"batman_SH", "02ca5898931181d0b8aafc75ef56fce9c43656c0b6c9f64306e7c8542f6207018c" }, + {"ca333_EU", "03fc87b8c804f12a6bd18efd43b0ba2828e4e38834f6b44c0bfee19f966a12ba99" }, + {"chainmakers_EU", "02f3b08938a7f8d2609d567aebc4989eeded6e2e880c058fdf092c5da82c3bc5ee" }, + {"chainmakers_NA", "0276c6d1c65abc64c8559710b8aff4b9e33787072d3dda4ec9a47b30da0725f57a" }, + {"chainstrike_SH", "0370bcf10575d8fb0291afad7bf3a76929734f888228bc49e35c5c49b336002153" }, + {"cipi_AR", "02c4f89a5b382750836cb787880d30e23502265054e1c327a5bfce67116d757ce8" }, + {"cipi_NA", "02858904a2a1a0b44df4c937b65ee1f5b66186ab87a751858cf270dee1d5031f18" }, + {"crackers_EU", "03bc819982d3c6feb801ec3b720425b017d9b6ee9a40746b84422cbbf929dc73c3" }, + {"crackers_NA", "03205049103113d48c7c7af811b4c8f194dafc43a50d5313e61a22900fc1805b45" }, + {"dwy_EU", "0259c646288580221fdf0e92dbeecaee214504fdc8bbdf4a3019d6ec18b7540424" }, + {"emmanux_SH", "033f316114d950497fc1d9348f03770cd420f14f662ab2db6172df44c389a2667a" }, + {"etszombi_EU", "0281b1ad28d238a2b217e0af123ce020b79e91b9b10ad65a7917216eda6fe64bf7" }, + {"fullmoon_AR", "03380314c4f42fa854df8c471618751879f9e8f0ff5dbabda2bd77d0f96cb35676" }, + {"fullmoon_NA", "030216211d8e2a48bae9e5d7eb3a42ca2b7aae8770979a791f883869aea2fa6eef" }, + {"fullmoon_SH", "03f34282fa57ecc7aba8afaf66c30099b5601e98dcbfd0d8a58c86c20d8b692c64" }, + {"goldenman_EU", "02d6f13a8f745921cdb811e32237bb98950af1a5952be7b3d429abd9152f8e388d" }, + {"indenodes_AR", "02ec0fa5a40f47fd4a38ea5c89e375ad0b6ddf4807c99733c9c3dc15fb978ee147" }, + {"indenodes_EU", "0221387ff95c44cb52b86552e3ec118a3c311ca65b75bf807c6c07eaeb1be8303c" }, + {"indenodes_NA", "02698c6f1c9e43b66e82dbb163e8df0e5a2f62f3a7a882ca387d82f86e0b3fa988" }, + {"indenodes_SH", "0334e6e1ec8285c4b85bd6dae67e17d67d1f20e7328efad17ce6fd24ae97cdd65e" }, + {"jackson_AR", "038ff7cfe34cb13b524e0941d5cf710beca2ffb7e05ddf15ced7d4f14fbb0a6f69" }, + {"jeezy_EU", "023cb3e593fb85c5659688528e9a4f1c4c7f19206edc7e517d20f794ba686fd6d6" }, + {"karasugoi_NA", "02a348b03b9c1a8eac1b56f85c402b041c9bce918833f2ea16d13452309052a982" }, + {"komodoninja_EU", "038e567b99806b200b267b27bbca2abf6a3e8576406df5f872e3b38d30843cd5ba" }, + {"komodoninja_SH", "033178586896915e8456ebf407b1915351a617f46984001790f0cce3d6f3ada5c2" }, + {"komodopioneers_SH", "033ace50aedf8df70035b962a805431363a61cc4e69d99d90726a2d48fb195f68c" }, + {"libscott_SH", "03301a8248d41bc5dc926088a8cf31b65e2daf49eed7eb26af4fb03aae19682b95" }, + {"lukechilds_AR", "031aa66313ee024bbee8c17915cf7d105656d0ace5b4a43a3ab5eae1e14ec02696" }, + {"madmax_AR", "03891555b4a4393d655bf76f0ad0fb74e5159a615b6925907678edc2aac5e06a75" }, + {"meshbits_AR", "02957fd48ae6cb361b8a28cdb1b8ccf5067ff68eb1f90cba7df5f7934ed8eb4b2c" }, + {"meshbits_SH", "025c6e94877515dfd7b05682b9cc2fe4a49e076efe291e54fcec3add78183c1edb" }, + {"metaphilibert_AR", "02adad675fae12b25fdd0f57250b0caf7f795c43f346153a31fe3e72e7db1d6ac6" }, + {"metaphilibert_SH", "0284af1a5ef01503e6316a2ca4abf8423a794e9fc17ac6846f042b6f4adedc3309" }, + {"patchkez_SH", "0296270f394140640f8fa15684fc11255371abb6b9f253416ea2734e34607799c4" }, + {"pbca26_NA", "0276aca53a058556c485bbb60bdc54b600efe402a8b97f0341a7c04803ce204cb5" }, + {"peer2cloud_AR", "034e5563cb885999ae1530bd66fab728e580016629e8377579493b386bf6cebb15" }, + {"peer2cloud_SH", "03396ac453b3f23e20f30d4793c5b8ab6ded6993242df4f09fd91eb9a4f8aede84" }, + {"polycryptoblog_NA", "02708dcda7c45fb54b78469673c2587bfdd126e381654819c4c23df0e00b679622" }, + {"hyper_AR", "020f2f984d522051bd5247b61b080b4374a7ab389d959408313e8062acad3266b4" }, + {"hyper_EU", "03d00cf9ceace209c59fb013e112a786ad583d7de5ca45b1e0df3b4023bb14bf51" }, + {"hyper_SH", "0383d0b37f59f4ee5e3e98a47e461c861d49d0d90c80e9e16f7e63686a2dc071f3" }, + {"hyper_NA", "03d91c43230336c0d4b769c9c940145a8c53168bf62e34d1bccd7f6cfc7e5592de" }, + {"popcornbag_AR", "02761f106fb34fbfc5ddcc0c0aa831ed98e462a908550b280a1f7bd32c060c6fa3" }, + {"popcornbag_NA", "03c6085c7fdfff70988fda9b197371f1caf8397f1729a844790e421ee07b3a93e8" }, + {"alien_AR", "0348d9b1fc6acf81290405580f525ee49b4749ed4637b51a28b18caa26543b20f0" }, + {"alien_EU", "020aab8308d4df375a846a9e3b1c7e99597b90497efa021d50bcf1bbba23246527" }, + {"thegaltmines_NA", "031bea28bec98b6380958a493a703ddc3353d7b05eb452109a773eefd15a32e421" }, + {"titomane_AR", "029d19215440d8cb9cc6c6b7a4744ae7fb9fb18d986e371b06aeb34b64845f9325" }, + {"titomane_EU", "0360b4805d885ff596f94312eed3e4e17cb56aa8077c6dd78d905f8de89da9499f" }, + {"titomane_SH", "03573713c5b20c1e682a2e8c0f8437625b3530f278e705af9b6614de29277a435b" }, + {"webworker01_NA", "03bb7d005e052779b1586f071834c5facbb83470094cff5112f0072b64989f97d7" }, + {"xrobesx_NA", "03f0cc6d142d14a40937f12dbd99dbd9021328f45759e26f1877f2a838876709e1" }, +}; -int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height) +int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) { + static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1; int32_t i,htind,n; uint64_t mask = 0; struct knotary_entry *kp,*tmp; - if ( height >= 180000 || ASSETCHAINS_SYMBOL[0] != 0 ) + if ( timestamp == 0 && ASSETCHAINS_SYMBOL[0] != 0 ) + timestamp = komodo_heightstamp(height); + else if ( ASSETCHAINS_SYMBOL[0] == 0 ) + timestamp = 0; + if ( height >= KOMODO_NOTARIES_HARDCODED || ASSETCHAINS_SYMBOL[0] != 0 ) { - n = (int32_t)(sizeof(Notaries_elected)/sizeof(*Notaries_elected)); - for (i=0; i= KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP ) + htind = (KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP) - 1; + if ( Pubkeys == 0 ) + { + komodo_init(height); + //printf("Pubkeys.%p htind.%d vs max.%d\n",Pubkeys,htind,KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP); + } pthread_mutex_lock(&komodo_mutex); n = Pubkeys[htind].numnotaries; + if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) + fprintf(stderr,"%s height.%d t.%u genesis.%d\n",ASSETCHAINS_SYMBOL,height,timestamp,n); HASH_ITER(hh,Pubkeys[htind].Notaries,kp,tmp) { if ( kp->notaryid < n ) @@ -199,12 +263,40 @@ int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height) return(-1); } +int32_t komodo_electednotary(int32_t *numnotariesp,uint8_t *pubkey33,int32_t height,uint32_t timestamp) +{ + int32_t i,n; uint8_t pubkeys[64][33]; + n = komodo_notaries(pubkeys,height,timestamp); + *numnotariesp = n; + for (i=0; i= KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP ) + htind = (KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP) - 1; + numnotaries = Pubkeys[htind].numnotaries; + for (i=0; i (numnotaries >> 1) || (wt > 7 && (signedmask & 1) != 0) ) + return(1); + else return(0); +} + void komodo_notarysinit(int32_t origheight,uint8_t pubkeys[64][33],int32_t num) { static int32_t hwmheight; int32_t k,i,htind,height; struct knotary_entry *kp; struct knotaries_entry N; if ( Pubkeys == 0 ) - Pubkeys = (struct knotaries_entry *)calloc(KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP,sizeof(*Pubkeys)); + Pubkeys = (struct knotaries_entry *)calloc(1 + (KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP),sizeof(*Pubkeys)); memset(&N,0,sizeof(N)); if ( origheight > 0 ) { @@ -212,6 +304,8 @@ void komodo_notarysinit(int32_t origheight,uint8_t pubkeys[64][33],int32_t num) height /= KOMODO_ELECTION_GAP; height = ((height + 1) * KOMODO_ELECTION_GAP); htind = (height / KOMODO_ELECTION_GAP); + if ( htind >= KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP ) + htind = (KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP) - 1; //printf("htind.%d activation %d from %d vs %d | hwmheight.%d %s\n",htind,height,origheight,(((origheight+KOMODO_ELECTION_GAP/2)/KOMODO_ELECTION_GAP)+1)*KOMODO_ELECTION_GAP,hwmheight,ASSETCHAINS_SYMBOL); } else htind = 0; pthread_mutex_lock(&komodo_mutex); @@ -244,29 +338,31 @@ void komodo_notarysinit(int32_t origheight,uint8_t pubkeys[64][33],int32_t num) hwmheight = origheight; } -int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33) +int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp) { // -1 if not notary, 0 if notary, 1 if special notary struct knotary_entry *kp; int32_t numnotaries=0,htind,modval = -1; - komodo_init(0); *notaryidp = -1; - if ( height < 0 || height >= KOMODO_MAXBLOCKS ) + if ( height < 0 )//|| height >= KOMODO_MAXBLOCKS ) { printf("komodo_chosennotary ht.%d illegal\n",height); return(-1); } - if ( height >= 180000 ) + if ( height >= KOMODO_NOTARIES_HARDCODED || ASSETCHAINS_SYMBOL[0] != 0 ) { - if ( (*notaryidp= komodo_electednotary(pubkey33,height)) >= 0 ) + if ( (*notaryidp= komodo_electednotary(&numnotaries,pubkey33,height,timestamp)) >= 0 && numnotaries != 0 ) { - numnotaries = (int32_t)(sizeof(Notaries_elected)/sizeof(*Notaries_elected)); modval = ((height % numnotaries) == *notaryidp); return(modval); } } - if ( height >= 250000 )//300000 ) + if ( height >= 250000 ) return(-1); + if ( Pubkeys == 0 ) + komodo_init(0); htind = height / KOMODO_ELECTION_GAP; + if ( htind >= KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP ) + htind = (KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP) - 1; pthread_mutex_lock(&komodo_mutex); HASH_FIND(hh,Pubkeys[htind].Notaries,pubkey33,33,kp); pthread_mutex_unlock(&komodo_mutex); @@ -285,27 +381,6 @@ int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33) return(modval); } -void komodo_notarized_update(struct komodo_state *sp,int32_t nHeight,int32_t notarized_height,uint256 notarized_hash,uint256 notarized_desttxid) -{ - struct notarized_checkpoint *np; - if ( notarized_height > nHeight ) - { - printf("komodo_notarized_update REJECT notarized_height %d > %d nHeight\n",notarized_height,nHeight); - return; - } - if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) - printf("[%s] komodo_notarized_update nHeight.%d notarized_height.%d\n",ASSETCHAINS_SYMBOL,nHeight,notarized_height); - portable_mutex_lock(&komodo_mutex); - sp->NPOINTS = (struct notarized_checkpoint *)realloc(sp->NPOINTS,(sp->NUM_NPOINTS+1) * sizeof(*sp->NPOINTS)); - np = &sp->NPOINTS[sp->NUM_NPOINTS++]; - memset(np,0,sizeof(*np)); - np->nHeight = nHeight; - sp->NOTARIZED_HEIGHT = np->notarized_height = notarized_height; - sp->NOTARIZED_HASH = np->notarized_hash = notarized_hash; - sp->NOTARIZED_DESTTXID = np->notarized_desttxid = notarized_desttxid; - portable_mutex_unlock(&komodo_mutex); -} - //struct komodo_state *komodo_stateptr(char *symbol,char *dest); int32_t komodo_notarized_height(uint256 *hashp,uint256 *txidp) { @@ -324,6 +399,43 @@ int32_t komodo_notarized_height(uint256 *hashp,uint256 *txidp) } } +/*struct notarized_checkpoint *komodo_npptr(int32_t height) +{ + char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; int32_t i; struct komodo_state *sp; struct notarized_checkpoint *np = 0; + if ( (sp= komodo_stateptr(symbol,dest)) != 0 ) + { + for (i=sp->NUM_NPOINTS-1; i>=0; i--) + { + np = &sp->NPOINTS[i]; + if ( np->MoMdepth > 0 && height > np->notarized_height-np->MoMdepth && height <= np->notarized_height ) + return(np); + } + } + return(0); +} + +int32_t komodo_MoMdata(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t height,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip) +{ + struct notarized_checkpoint *np = 0; + if ( (np= komodo_npptr(height)) != 0 ) + { + *notarized_htp = np->notarized_height; + *MoMp = np->MoM; + *kmdtxidp = np->notarized_desttxid; + *MoMoMp = np->MoMoM; + *MoMoMoffsetp = np->MoMoMoffset; + *MoMoMdepthp = np->MoMoMdepth; + *kmdstartip = np->kmdstarti; + *kmdendip = np->kmdendi; + return(np->MoMdepth); + } + *notarized_htp = *MoMoMoffsetp = *MoMoMdepthp = *kmdstartip = *kmdendip = 0; + memset(MoMp,0,sizeof(*MoMp)); + memset(MoMoMp,0,sizeof(*MoMoMp)); + memset(kmdtxidp,0,sizeof(*kmdtxidp)); + return(0); +}*/ + int32_t komodo_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *notarized_desttxidp) { struct notarized_checkpoint *np = 0; int32_t i=0,flag = 0; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; struct komodo_state *sp; @@ -380,11 +492,35 @@ int32_t komodo_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *n return(0); } +void komodo_notarized_update(struct komodo_state *sp,int32_t nHeight,int32_t notarized_height,uint256 notarized_hash,uint256 notarized_desttxid,uint256 MoM,int32_t MoMdepth) +{ + struct notarized_checkpoint *np; + if ( notarized_height >= nHeight ) + { + fprintf(stderr,"komodo_notarized_update REJECT notarized_height %d > %d nHeight\n",notarized_height,nHeight); + return; + } + if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) + fprintf(stderr,"[%s] komodo_notarized_update nHeight.%d notarized_height.%d\n",ASSETCHAINS_SYMBOL,nHeight,notarized_height); + portable_mutex_lock(&komodo_mutex); + sp->NPOINTS = (struct notarized_checkpoint *)realloc(sp->NPOINTS,(sp->NUM_NPOINTS+1) * sizeof(*sp->NPOINTS)); + np = &sp->NPOINTS[sp->NUM_NPOINTS++]; + memset(np,0,sizeof(*np)); + np->nHeight = nHeight; + sp->NOTARIZED_HEIGHT = np->notarized_height = notarized_height; + sp->NOTARIZED_HASH = np->notarized_hash = notarized_hash; + sp->NOTARIZED_DESTTXID = np->notarized_desttxid = notarized_desttxid; + sp->MoM = np->MoM = MoM; + sp->MoMdepth = np->MoMdepth = MoMdepth; + portable_mutex_unlock(&komodo_mutex); +} + void komodo_init(int32_t height) { static int didinit; uint256 zero; int32_t k,n; uint8_t pubkeys[64][33]; if ( 0 && height != 0 ) printf("komodo_init ht.%d didinit.%d\n",height,didinit); + memset(&zero,0,sizeof(zero)); if ( didinit == 0 ) { pthread_mutex_init(&komodo_mutex,NULL); @@ -400,56 +536,10 @@ void komodo_init(int32_t height) } komodo_notarysinit(0,pubkeys,k); } - memset(&zero,0,sizeof(zero)); //for (i=0; i 0 ) - { - for (i=0; iGetBlockHash() == hash ) + { + //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); + return true; + } return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),REJECT_CHECKPOINT, "checkpoint mismatch"); + } // Don't accept any forks from the main chain prior to last checkpoint CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints()); int32_t notarized_height; - if (pcheckpoint && (nHeight < pcheckpoint->nHeight || nHeight == 1 && chainActive.Tip() != 0 && chainActive.Tip()->nHeight > 1) ) + if (pcheckpoint && nHeight > 1 && nHeight < pcheckpoint->nHeight ) return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d) vs %d", __func__, nHeight,pcheckpoint->nHeight)); else if ( komodo_checkpoint(¬arized_height,nHeight,hash) < 0 ) - return state.DoS(100, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height)); + { + CBlockIndex *heightblock = chainActive[nHeight]; + if ( heightblock != 0 && heightblock->GetBlockHash() == hash ) + { + //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); + return true; + } else return state.DoS(100, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height)); + } } // Reject block.nVersion < 4 blocks if (block.nVersion < 4) @@ -3391,7 +3407,40 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc *ppindex = pindex; if (pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK) return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); - return true; + if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 + { + if (!CheckBlockHeader(pindex->nHeight,pindex, block, state)) + { + pindex->nStatus |= BLOCK_FAILED_MASK; + fprintf(stderr,"known block failing CheckBlockHeader %d\n",(int32_t)pindex->nHeight); + return false; + } + CBlockIndex* pindexPrev = NULL; + if (hash != chainparams.GetConsensus().hashGenesisBlock) + { + BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); + if (mi == mapBlockIndex.end()) + { + pindex->nStatus |= BLOCK_FAILED_MASK; + fprintf(stderr,"known block.%d failing to find prevblock\n",(int32_t)pindex->nHeight); + return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk"); + } + pindexPrev = (*mi).second; + if (pindexPrev == 0 || (pindexPrev->nStatus & BLOCK_FAILED_MASK) ) + { + pindex->nStatus |= BLOCK_FAILED_MASK; + fprintf(stderr,"known block.%d found invalid prevblock\n",(int32_t)pindex->nHeight); + return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk"); + } + } + if (!ContextualCheckBlockHeader(block, state, pindexPrev)) + { + pindex->nStatus |= BLOCK_FAILED_MASK; + fprintf(stderr,"known block.%d failing ContextualCheckBlockHeader\n",(int32_t)pindex->nHeight); + return false; + } + } + return true; } if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state)) @@ -3995,7 +4044,6 @@ void UnloadBlockIndex() bool LoadBlockIndex() { - extern int32_t KOMODO_LOADINGBLOCKS; // Load block index from databases KOMODO_LOADINGBLOCKS = 1; if (!fReindex && !LoadBlockIndexDB()) @@ -4003,7 +4051,7 @@ bool LoadBlockIndex() KOMODO_LOADINGBLOCKS = 0; return false; } - KOMODO_LOADINGBLOCKS = 0; + //KOMODO_LOADINGBLOCKS = 0; fprintf(stderr,"finished loading blocks %s\n",ASSETCHAINS_SYMBOL); return true; } diff --git a/src/miner.cpp b/src/miner.cpp index d7fc3a94d..7c44915d2 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -113,7 +113,7 @@ extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; extern std::string NOTARY_PUBKEY; extern uint8_t NOTARY_PUBKEY33[33]; uint32_t Mining_start,Mining_height; -int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33); +int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33]); int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize); uint64_t komodo_paxtotal(); @@ -648,7 +648,7 @@ void static BitcoinMiner() break; } //sleep(60); - komodo_chosennotary(¬aryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33); + komodo_chosennotary(¬aryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime()); std::string solver; //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 ) diff --git a/src/pow.cpp b/src/pow.cpp index 2bf0795a6..081cceb5e 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -115,41 +115,49 @@ bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams& param return true; } -int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33); -int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33]); +int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); +int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp); int32_t komodo_currentheight(); CBlockIndex *komodo_chainactive(int32_t height); -int8_t komodo_minerid(int32_t height,uint8_t *pubkey33); void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height); extern int32_t KOMODO_CHOSEN_ONE; +extern uint64_t ASSETCHAINS_STAKED; +extern char ASSETCHAINS_SYMBOL[]; #define KOMODO_ELECTION_GAP 2000 - + int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height); -int32_t KOMODO_LOADINGBLOCKS; +int32_t KOMODO_LOADINGBLOCKS = 1; extern std::string NOTARY_PUBKEY; bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned int nBits, const Consensus::Params& params) { extern int32_t KOMODO_REWIND; - bool fNegative,fOverflow; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,duplicate,flag = 0, mids[66]; - arith_uint256 bnTarget; CBlockIndex *pindex; uint8_t pubkeys[66][33]; - + bool fNegative,fOverflow; uint8_t origpubkey33[33]; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t timestamp = 0; CBlockIndex *pindex=0; + arith_uint256 bnTarget; uint8_t pubkeys[66][33]; + memcpy(origpubkey33,pubkey33,33); + timestamp = komodo_chainactive_timestamp(); bnTarget.SetCompact(nBits, &fNegative, &fOverflow); if ( height == 0 ) - height = komodo_currentheight() + 1; - special = komodo_chosennotary(¬aryid,height,pubkey33); - flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); - if ( height > 34000 ) // 0 -> non-special notary { + height = komodo_currentheight() + 1; + //fprintf(stderr,"set height to %d\n",height); + } + if ( height > 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary + { + special = komodo_chosennotary(¬aryid,height,pubkey33,timestamp); for (i=0; i<33; i++) { if ( pubkey33[i] != 0 ) nonz++; } if ( nonz == 0 ) + { + //fprintf(stderr,"ht.%d null pubkey checkproof return\n",height); return(true); // will come back via different path with pubkey set - special2 = komodo_is_special(height,pubkey33); + } + flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); + special2 = komodo_is_special(pubkeys,mids,height,pubkey33,timestamp); if ( notaryid >= 0 ) { if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) @@ -158,8 +166,19 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 1; else if ( height >= 108000 && special2 > 0 ) flag = ((height % KOMODO_ELECTION_GAP) > 64 || (height % KOMODO_ELECTION_GAP) == 0); - if ( flag != 0 || height == 790833 ) + else if ( height == 790833 ) + flag = 1; + else if ( special2 < 0 ) + { + if ( height > 792000 ) + flag = 0; + else fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); + } + if ( flag != 0 || special2 > 0 ) + { + //fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); + } } } if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) @@ -167,39 +186,10 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in // Check proof of work matches claimed amount if ( UintToArith256(hash) > bnTarget ) { - if ( (height < 235300 || height >= 236000) && KOMODO_LOADINGBLOCKS == 0 && height > 188000 ) - //&& )//186269, 182507&& komodo_chainactive(height) != 0 && nonzpkeys > 0 - { - for (i=31; i>=0; i--) - printf("%02x",((uint8_t *)&hash)[i]); - printf(" hash vs "); - for (i=31; i>=0; i--) - printf("%02x",((uint8_t *)&bnTarget)[i]); - printf(" ht.%d special.%d notaryid.%d ht.%d mod.%d error\n",height,special,notaryid,height,(height % 35)); - for (i=0; i<33; i++) - printf("%02x",pubkey33[i]); - printf(" <- pubkey\n"); - for (i=0; i<66; i++) - printf("%d ",mids[i]); - printf(" minerids from ht.%d\n",height); - if ( KOMODO_REWIND == 0 && (notaryid >= 0 || height > 225000) ) - { - fprintf(stderr,"pow error height.%d loading.%d notaryid.%d\n",height,KOMODO_LOADINGBLOCKS,notaryid); - return error("CheckProofOfWork(): hash doesn't match nBits"); - } else fprintf(stderr,"skip return error height.%d loading.%d\n",height,KOMODO_LOADINGBLOCKS); - } //else fprintf(stderr,"skip height.%d loading.%d\n",height,KOMODO_LOADINGBLOCKS); - } - if ( 0 && height > 248000 ) - { - for (i=31; i>=0; i--) - fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); - fprintf(stderr," hash vs "); - for (i=31; i>=0; i--) - fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); - fprintf(stderr," POW ok for ht.%d notaryid.%d: ",height,notaryid); - for (i=0; i<33; i++) - fprintf(stderr,"%02x",pubkey33[i]); - fprintf(stderr,"\n"); + if ( KOMODO_LOADINGBLOCKS != 0 ) + return true; + if ( ASSETCHAINS_SYMBOL[0] != 0 || height > 792000 ) + return false; } return true; } diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 10f617765..3947b65e3 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -519,10 +519,10 @@ UniValue gettxoutsetinfo(const UniValue& params, bool fHelp) #define KOMODO_KVBINARY 2 extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime); -uint32_t komodo_txtime(uint256 hash); +//uint32_t komodo_txtime(uint256 hash); uint64_t komodo_paxprice(uint64_t *seedp,int32_t height,char *base,char *rel,uint64_t basevolume); int32_t komodo_paxprices(int32_t *heights,uint64_t *prices,int32_t max,char *base,char *rel); -int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height); +int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp); char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160,int32_t len); //uint32_t komodo_interest_args(int32_t *txheightp,uint32_t *tiptimep,uint64_t *valuep,uint256 hash,int32_t n); int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width); @@ -581,13 +581,19 @@ UniValue kvsearch(const UniValue& params, bool fHelp) UniValue minerids(const UniValue& params, bool fHelp) { - UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); uint8_t minerids[2000],pubkeys[65][33]; int32_t i,j,n,numnotaries,tally[129]; + uint32_t timestamp = 0; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); uint8_t minerids[2000],pubkeys[65][33]; int32_t i,j,n,numnotaries,tally[129]; if ( fHelp || params.size() != 1 ) throw runtime_error("minerids needs height\n"); LOCK(cs_main); int32_t height = atoi(params[0].get_str().c_str()); if ( height <= 0 ) height = chainActive.Tip()->nHeight; + else + { + CBlockIndex *pblockindex = chainActive[height]; + if ( pblockindex != 0 ) + timestamp = pblockindex->GetBlockTime(); + } if ( (n= komodo_minerids(minerids,height,(int32_t)(sizeof(minerids)/sizeof(*minerids)))) > 0 ) { memset(tally,0,sizeof(tally)); @@ -632,49 +638,57 @@ UniValue minerids(const UniValue& params, bool fHelp) UniValue notaries(const UniValue& params, bool fHelp) { - UniValue a(UniValue::VARR); UniValue ret(UniValue::VOBJ); int32_t i,j,n,m; char *hexstr; uint8_t pubkeys[64][33]; char btcaddr[64],kmdaddr[64],*ptr; - if ( fHelp || params.size() != 1 ) - throw runtime_error("notaries height\n"); + UniValue a(UniValue::VARR); uint32_t timestamp=0; UniValue ret(UniValue::VOBJ); int32_t i,j,n,m; char *hexstr; uint8_t pubkeys[64][33]; char btcaddr[64],kmdaddr[64],*ptr; + if ( fHelp || (params.size() != 1 && params.size() != 2) ) + throw runtime_error("notaries height timestamp\n"); LOCK(cs_main); int32_t height = atoi(params[0].get_str().c_str()); + if ( params.size() == 2 ) + timestamp = (uint32_t)atol(params[1].get_str().c_str()); + else timestamp = (uint32_t)time(NULL); if ( height < 0 ) - height = chainActive.Tip()->nHeight; - //fprintf(stderr,"notaries as of height.%d\n",height); - //if ( height > chainActive.Height()+20000 ) - // throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); - //else { - if ( (n= komodo_notaries(pubkeys,height)) > 0 ) - { - for (i=0; inHeight; + timestamp = chainActive.Tip()->GetBlockTime(); } + else if ( params.size() < 2 ) + { + CBlockIndex *pblockindex = chainActive[height]; + if ( pblockindex != 0 ) + timestamp = pblockindex->GetBlockTime(); + } + if ( (n= komodo_notaries(pubkeys,height,timestamp)) > 0 ) + { + for (i=0; inHeight)) >= 0 ) + if ( (notaryid= komodo_whoami(pubkeystr,(int32_t)chainActive.Tip()->nHeight,komodo_chainactive_timestamp())) >= 0 ) { obj.push_back(Pair("notaryid", notaryid)); obj.push_back(Pair("pubkey", pubkeystr)); From 49311c0553a496109b5e66c236ef1151bb6a064b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 01:46:51 +0300 Subject: [PATCH 227/507] Syntax fixes --- src/coins.cpp | 4 ++-- src/komodo-tx.cpp | 2 +- src/komodo_notary.h | 8 ++++---- src/komodo_structs.h | 1 + src/main.cpp | 2 +- src/pow.cpp | 1 + src/rpcblockchain.cpp | 4 ++-- src/rpcmisc.cpp | 1 + src/wallet/rpcwallet.cpp | 4 ++-- src/wallet/wallet.cpp | 4 ++-- 10 files changed, 17 insertions(+), 14 deletions(-) diff --git a/src/coins.cpp b/src/coins.cpp index 37d969010..272beb3d1 100644 --- a/src/coins.cpp +++ b/src/coins.cpp @@ -387,7 +387,7 @@ const CScript &CCoinsViewCache::GetSpendFor(const CTxIn& input) const } //uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime); -uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue); +uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue,int32_t tipheight); extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; CAmount CCoinsViewCache::GetValueIn(int32_t nHeight,int64_t *interestp,const CTransaction& tx,uint32_t tiptime) const @@ -407,7 +407,7 @@ CAmount CCoinsViewCache::GetValueIn(int32_t nHeight,int64_t *interestp,const CTr if ( value >= 10*COIN ) { int64_t interest; int32_t txheight; uint32_t locktime; - interest = komodo_accrued_interest(&txheight,&locktime,tx.vin[i].prevout.hash,tx.vin[i].prevout.n,0,value); + interest = komodo_accrued_interest(&txheight,&locktime,tx.vin[i].prevout.hash,tx.vin[i].prevout.n,0,value,(int32_t)nHeight); //printf("nResult %.8f += val %.8f interest %.8f ht.%d lock.%u tip.%u\n",(double)nResult/COIN,(double)value/COIN,(double)interest/COIN,txheight,locktime,tiptime); //fprintf(stderr,"nResult %.8f += val %.8f interest %.8f ht.%d lock.%u tip.%u\n",(double)nResult/COIN,(double)value/COIN,(double)interest/COIN,txheight,locktime,tiptime); nResult += interest; diff --git a/src/komodo-tx.cpp b/src/komodo-tx.cpp index 645bc30a2..bce749d7f 100644 --- a/src/komodo-tx.cpp +++ b/src/komodo-tx.cpp @@ -31,7 +31,7 @@ using namespace std; #include "komodo_interest.h" -uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue) +uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue,int32_t tipheight) { return(0); } diff --git a/src/komodo_notary.h b/src/komodo_notary.h index f5c65dac3..38eced369 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -492,7 +492,7 @@ int32_t komodo_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *n return(0); } -void komodo_notarized_update(struct komodo_state *sp,int32_t nHeight,int32_t notarized_height,uint256 notarized_hash,uint256 notarized_desttxid,uint256 MoM,int32_t MoMdepth) +void komodo_notarized_update(struct komodo_state *sp,int32_t nHeight,int32_t notarized_height,uint256 notarized_hash,uint256 notarized_desttxid)//,uint256 MoM,int32_t MoMdepth) { struct notarized_checkpoint *np; if ( notarized_height >= nHeight ) @@ -510,8 +510,8 @@ void komodo_notarized_update(struct komodo_state *sp,int32_t nHeight,int32_t not sp->NOTARIZED_HEIGHT = np->notarized_height = notarized_height; sp->NOTARIZED_HASH = np->notarized_hash = notarized_hash; sp->NOTARIZED_DESTTXID = np->notarized_desttxid = notarized_desttxid; - sp->MoM = np->MoM = MoM; - sp->MoMdepth = np->MoMdepth = MoMdepth; + //sp->MoM = np->MoM = MoM; + //sp->MoMdepth = np->MoMdepth = MoMdepth; portable_mutex_unlock(&komodo_mutex); } @@ -539,7 +539,7 @@ void komodo_init(int32_t height) //for (i=0; ivout[prevout.n].nValue >= 10*COIN ) { int64_t interest; int32_t txheight; uint32_t locktime; - if ( (interest= komodo_accrued_interest(&txheight,&locktime,prevout.hash,prevout.n,0,coins->vout[prevout.n].nValue)) != 0 ) + if ( (interest= komodo_accrued_interest(&txheight,&locktime,prevout.hash,prevout.n,0,coins->vout[prevout.n].nValue,(int32_t)nSpendHeight-1)) != 0 ) { //fprintf(stderr,"checkResult %.8f += val %.8f interest %.8f ht.%d lock.%u tip.%u\n",(double)nValueIn/COIN,(double)coins->vout[prevout.n].nValue/COIN,(double)interest/COIN,txheight,locktime,chainActive.Tip()->nTime); nValueIn += interest; diff --git a/src/pow.cpp b/src/pow.cpp index 081cceb5e..ce82a4e1b 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -115,6 +115,7 @@ bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams& param return true; } +uint32_t komodo_chainactive_timestamp(); int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp); int32_t komodo_currentheight(); diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 3947b65e3..caecbc5e1 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -801,7 +801,7 @@ UniValue paxprices(const UniValue& params, bool fHelp) return ret; } -uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue); +uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue,int32_t tipheight); UniValue gettxout(const UniValue& params, bool fHelp) { @@ -874,7 +874,7 @@ UniValue gettxout(const UniValue& params, bool fHelp) else ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); uint64_t interest; int32_t txheight; uint32_t locktime; - if ( (interest= komodo_accrued_interest(&txheight,&locktime,hash,n,coins.nHeight,coins.vout[n].nValue)) != 0 ) + if ( (interest= komodo_accrued_interest(&txheight,&locktime,hash,n,coins.nHeight,coins.vout[n].nValue,(int32_t)pindex->nHeight)) != 0 ) ret.push_back(Pair("interest", ValueFromAmount(interest))); UniValue o(UniValue::VOBJ); ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true); diff --git a/src/rpcmisc.cpp b/src/rpcmisc.cpp index 2ef749049..e17285630 100644 --- a/src/rpcmisc.cpp +++ b/src/rpcmisc.cpp @@ -51,6 +51,7 @@ extern int32_t KOMODO_LASTMINED,JUMBLR_PAUSE; extern char ASSETCHAINS_SYMBOL[]; int32_t notarizedtxid_height(char *dest,char *txidstr,int32_t *kmdnotarized_heightp); #define KOMODO_VERSION "0.1.1" +uint32_t komodo_chainactive_timestamp(); UniValue getinfo(const UniValue& params, bool fHelp) { diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index ccf4fc34a..c407b0174 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -72,7 +72,7 @@ void EnsureWalletIsUnlocked() throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); } -uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue); +uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue,int32_t tipheight); uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime); void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry) @@ -2668,9 +2668,9 @@ UniValue listunspent(const UniValue& params, bool fHelp) BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); CBlockIndex *tipindex,*pindex = it->second; uint64_t interest; uint32_t locktime; int32_t txheight; - komodo_accrued_interest(&txheight,&locktime,out.tx->GetHash(),out.i,0,nValue); if ( pindex != 0 && (tipindex= chainActive.Tip()) != 0 ) { + komodo_accrued_interest(&txheight,&locktime,out.tx->GetHash(),out.i,0,nValue,(int32_t)tipindex->nHeight); interest = komodo_interest(txheight,nValue,out.tx->nLockTime,tipindex->nTime); entry.push_back(Pair("interest",ValueFromAmount(interest))); } diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 9dc96f10c..0532f99d8 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -2205,7 +2205,7 @@ CAmount CWallet::GetImmatureWatchOnlyBalance() const * populate vCoins with vector of available COutputs. */ uint64_t komodo_interestnew(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime); -uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue); +uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 hash,int32_t n,int32_t checkheight,uint64_t checkvalue,int32_t tipheight); void CWallet::AvailableCoins(vector& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue, bool fIncludeCoinBase) const { @@ -2249,9 +2249,9 @@ void CWallet::AvailableCoins(vector& vCoins, bool fOnlyConfirmed, const { if ( pcoin->vout[i].nValue >= 10*COIN ) { - komodo_accrued_interest(&txheight,&locktime,wtxid,i,0,pcoin->vout[i].nValue); if ( (tipindex= chainActive.Tip()) != 0 ) { + komodo_accrued_interest(&txheight,&locktime,wtxid,i,0,pcoin->vout[i].nValue,(int32_t)tipindex->nHeight); interest = komodo_interestnew(txheight,pcoin->vout[i].nValue,locktime,tipindex->nTime); } else interest = 0; //interest = komodo_interestnew(chainActive.Tip()->nHeight+1,pcoin->vout[i].nValue,pcoin->nLockTime,chainActive.Tip()->nTime); From aeabfddd56b293d83460c3411e1eb1b2c7e501a7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 01:48:36 +0300 Subject: [PATCH 228/507] syntax --- src/komodo_notary.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 38eced369..5fcc15312 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -539,7 +539,7 @@ void komodo_init(int32_t height) //for (i=0; i Date: Sat, 14 Apr 2018 01:49:59 +0300 Subject: [PATCH 229/507] Add timestamp --- src/rpcblockchain.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index caecbc5e1..9919d161d 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -597,7 +597,7 @@ UniValue minerids(const UniValue& params, bool fHelp) if ( (n= komodo_minerids(minerids,height,(int32_t)(sizeof(minerids)/sizeof(*minerids)))) > 0 ) { memset(tally,0,sizeof(tally)); - numnotaries = komodo_notaries(pubkeys,height); + numnotaries = komodo_notaries(pubkeys,height,timestamp); if ( numnotaries > 0 ) { for (i=0; i Date: Sat, 14 Apr 2018 01:55:51 +0300 Subject: [PATCH 230/507] -assetchain_pubkeys --- src/komodo_globals.h | 2 +- src/komodo_utils.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 904b57344..7acdb9ccc 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -20,7 +20,7 @@ void komodo_init(int32_t height); int32_t komodo_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *notarized_desttxidp); char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port); void komodo_init(int32_t height); -void komodo_assetchain_pubkeys(char *jsonstr); +//void komodo_assetchain_pubkeys(char *jsonstr); int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); int32_t komodo_isrealtime(int32_t *kmdheightp); uint64_t komodo_paxtotal(); diff --git a/src/komodo_utils.h b/src/komodo_utils.h index 995f81002..8b724c40b 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1564,8 +1564,8 @@ void komodo_args(char *argv0) COINBASE_MATURITY = 1; LogPrintf("ASSETCHAINS_PORT %s %u\n",ASSETCHAINS_SYMBOL,ASSETCHAINS_PORT); } - ASSETCHAINS_NOTARIES = GetArg("-ac_notaries",""); - komodo_assetchain_pubkeys((char *)ASSETCHAINS_NOTARIES.c_str()); + //ASSETCHAINS_NOTARIES = GetArg("-ac_notaries",""); + //komodo_assetchain_pubkeys((char *)ASSETCHAINS_NOTARIES.c_str()); iguana_rwnum(1,magic,sizeof(ASSETCHAINS_MAGIC),(void *)&ASSETCHAINS_MAGIC); for (i=0; i<4; i++) sprintf(&magicstr[i<<1],"%02x",magic[i]); From 92833827400ed1347842485184ae32985a9dd432 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 01:57:38 +0300 Subject: [PATCH 231/507] +komodo_heightstamp --- src/komodo_globals.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 7acdb9ccc..2a7cdaf3d 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -15,6 +15,7 @@ #include "komodo_defs.h" +uint32_t komodo_heightstamp(int32_t height); void 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,int32_t kheight,uint32_t ktime,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout); void komodo_init(int32_t height); int32_t komodo_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *notarized_desttxidp); From 616b8051f4b44736fca1465f00a9bd480436362f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 01:59:06 +0300 Subject: [PATCH 232/507] +heightstamp --- src/komodo_notary.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 5fcc15312..e7ae7d738 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -198,6 +198,8 @@ const char *Notaries_elected1[][2] = {"xrobesx_NA", "03f0cc6d142d14a40937f12dbd99dbd9021328f45759e26f1877f2a838876709e1" }, }; +uint32_t komodo_heightstamp(int32_t height); + int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) { static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1; From 7cc106cc871a7bbf9fb94e285813923eadd9c428 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 02:01:56 +0300 Subject: [PATCH 233/507] Add stub --- src/bitcoin-cli.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp index cac650a00..6e116adf2 100644 --- a/src/bitcoin-cli.cpp +++ b/src/bitcoin-cli.cpp @@ -75,6 +75,11 @@ public: #include "komodo_cJSON.c" #include "komodo_notary.h" +uint32_t komodo_heightstamp(int32_t height) +{ + return(0); +} + void 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,int32_t KMDheight,uint32_t KMDtimestamp,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout) { From e70b1af226e48e2e1f0b314dca2fd4a7f16455f6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 03:03:38 +0300 Subject: [PATCH 234/507] Dont deprecate assetchains --- src/deprecation.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/deprecation.cpp b/src/deprecation.cpp index 9f394e720..8898e049a 100644 --- a/src/deprecation.cpp +++ b/src/deprecation.cpp @@ -11,12 +11,13 @@ #include "chainparams.h" static const std::string CLIENT_VERSION_STR = FormatVersion(CLIENT_VERSION); +extern char ASSETCHAINS_SYMBOL[]; void EnforceNodeDeprecation(int nHeight, bool forceLogging) { // Do not enforce deprecation in regtest or on testnet std::string networkID = Params().NetworkIDString(); - if (networkID != "main") return; + if (networkID != "main" || ASSETCHAINS_SYMBOL[0] != 0 ) return; int blocksToDeprecation = DEPRECATION_HEIGHT - nHeight; bool disableDeprecation = (GetArg("-disabledeprecation", "") == CLIENT_VERSION_STR); @@ -58,4 +59,4 @@ void EnforceNodeDeprecation(int nHeight, bool forceLogging) { LogPrintf("*** %s\n", msg); uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_WARNING); } -} \ No newline at end of file +} From cfaa7d06c6a4df0b8394f83093174e54ebf045f0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 03:12:27 +0300 Subject: [PATCH 235/507] Change print --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index a973f24a3..84acedd1f 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -191,7 +191,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in return true; if ( ASSETCHAINS_SYMBOL[0] == 0 ) { - if ( height > 790000 ) + if ( height > 792000 ) { for (i=31; i>=0; i--) printf("%02x",((uint8_t *)&hash)[i]); From b3b20b8b25d65da7de11f87926214933f6508f06 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 03:14:07 +0300 Subject: [PATCH 236/507] -print --- src/arith_uint256.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/arith_uint256.cpp b/src/arith_uint256.cpp index a1865b649..c9074fe91 100644 --- a/src/arith_uint256.cpp +++ b/src/arith_uint256.cpp @@ -111,7 +111,7 @@ int base_uint::CompareTo(const base_uint& b) const { if ( (uint64_t)pn < 0x1000 || (uint64_t)b.pn <= 0x1000 ) { - fprintf(stderr,"CompareTo null %p or %p\n",pn,b.pn); + //fprintf(stderr,"CompareTo null %p or %p\n",pn,b.pn); return(0); } for (int i = WIDTH - 1; i >= 0; i--) { From b3119d36ca6163ae9f570e27c063833fa551745d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 14:33:49 +0300 Subject: [PATCH 237/507] Increase rpcworkqueue to 256 --- src/komodo_utils.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_utils.h b/src/komodo_utils.h index 6fb4eb596..417ecfb52 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1365,7 +1365,7 @@ void komodo_configfile(char *symbol,uint16_t port) #ifndef FROM_CLI if ( (fp= fopen(fname,"wb")) != 0 ) { - fprintf(fp,"rpcuser=user%u\nrpcpassword=pass%s\nrpcport=%u\nserver=1\ntxindex=1\nrpcworkqueue=64\nrpcallowip=127.0.0.1\n",crc,password,port); + fprintf(fp,"rpcuser=user%u\nrpcpassword=pass%s\nrpcport=%u\nserver=1\ntxindex=1\nrpcworkqueue=256\nrpcallowip=127.0.0.1\n",crc,password,port); fclose(fp); printf("Created (%s)\n",fname); } else printf("Couldnt create (%s)\n",fname); From 457b455787f4bf4ea4b37ebba0b5155541be5aec Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 15:10:47 +0300 Subject: [PATCH 238/507] Fix buffer overflow and reduce KMD men usage --- src/komodo_events.h | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/komodo_events.h b/src/komodo_events.h index 0ced206ac..db309d09b 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -20,7 +20,7 @@ struct komodo_event *komodo_eventadd(struct komodo_state *sp,int32_t height,char *symbol,uint8_t type,uint8_t *data,uint16_t datalen) { struct komodo_event *ep=0; uint16_t len = (uint16_t)(sizeof(*ep) + datalen); - if ( sp != 0 ) + if ( sp != 0 && ASSETCHAINS_SYMBOL[0] != 0 ) { portable_mutex_lock(&komodo_mutex); ep = (struct komodo_event *)calloc(1,len); @@ -55,7 +55,7 @@ void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t heig N.notarizedheight = notarizedheight; N.MoM = MoM; N.MoMdepth = MoMdepth; - strcpy(N.dest,dest); + strncpy(N.dest,dest,sizeof(N.dest)-1); komodo_eventadd(sp,height,symbol,KOMODO_EVENT_NOTARIZED,(uint8_t *)&N,sizeof(N)); if ( sp != 0 ) komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid,MoM,MoMdepth); @@ -77,18 +77,21 @@ void komodo_eventadd_pubkeys(struct komodo_state *sp,char *symbol,int32_t height void komodo_eventadd_pricefeed(struct komodo_state *sp,char *symbol,int32_t height,uint32_t *prices,uint8_t num) { struct komodo_event_pricefeed F; - memset(&F,0,sizeof(F)); - F.num = num; - memcpy(F.prices,prices,sizeof(*F.prices) * num); - komodo_eventadd(sp,height,symbol,KOMODO_EVENT_PRICEFEED,(uint8_t *)&F,(int32_t)(sizeof(F.num) + sizeof(*F.prices) * num)); - if ( sp != 0 ) - komodo_pvals(height,prices,num); + if ( num == sizeof(F.prices)/sizeof(*F.prices) ) + { + memset(&F,0,sizeof(F)); + F.num = num; + memcpy(F.prices,prices,sizeof(*F.prices) * num); + komodo_eventadd(sp,height,symbol,KOMODO_EVENT_PRICEFEED,(uint8_t *)&F,(int32_t)(sizeof(F.num) + sizeof(*F.prices) * num)); + if ( sp != 0 ) + komodo_pvals(height,prices,num); + } else fprintf(stderr,"skip pricefeed[%d]\n",num); } void komodo_eventadd_opreturn(struct komodo_state *sp,char *symbol,int32_t height,uint256 txid,uint64_t value,uint16_t vout,uint8_t *buf,uint16_t opretlen) { - struct komodo_event_opreturn O; uint8_t opret[16384]; - memset(&O,0,sizeof(O)); + struct komodo_event_opreturn O; uint8_t *opret; + opretlen = (uint8_t *)calloc(1,sizeof(*O) + opretlen + 16); O.txid = txid; O.value = value; O.vout = vout; @@ -96,6 +99,7 @@ void komodo_eventadd_opreturn(struct komodo_state *sp,char *symbol,int32_t heigh memcpy(&opret[sizeof(O)],buf,opretlen); O.oplen = (int32_t)(opretlen + sizeof(O)); komodo_eventadd(sp,height,symbol,KOMODO_EVENT_OPRETURN,opret,O.oplen); + free(opret); if ( sp != 0 ) komodo_opreturn(height,value,buf,opretlen,txid,vout,symbol); } From 774680ba81cd0c28c489f682dc9a356c13c7d7ca Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 15:13:39 +0300 Subject: [PATCH 239/507] Test --- src/komodo_events.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_events.h b/src/komodo_events.h index db309d09b..360603804 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -91,7 +91,7 @@ void komodo_eventadd_pricefeed(struct komodo_state *sp,char *symbol,int32_t heig void komodo_eventadd_opreturn(struct komodo_state *sp,char *symbol,int32_t height,uint256 txid,uint64_t value,uint16_t vout,uint8_t *buf,uint16_t opretlen) { struct komodo_event_opreturn O; uint8_t *opret; - opretlen = (uint8_t *)calloc(1,sizeof(*O) + opretlen + 16); + opretlen = (uint8_t *)calloc(1,sizeof(O) + opretlen + 16); O.txid = txid; O.value = value; O.vout = vout; From 46b94f6348160165454982414199572140acda69 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 15:15:03 +0300 Subject: [PATCH 240/507] Test --- src/komodo_events.h | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/komodo_events.h b/src/komodo_events.h index 360603804..5cd29ce72 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -91,17 +91,20 @@ void komodo_eventadd_pricefeed(struct komodo_state *sp,char *symbol,int32_t heig void komodo_eventadd_opreturn(struct komodo_state *sp,char *symbol,int32_t height,uint256 txid,uint64_t value,uint16_t vout,uint8_t *buf,uint16_t opretlen) { struct komodo_event_opreturn O; uint8_t *opret; - opretlen = (uint8_t *)calloc(1,sizeof(O) + opretlen + 16); - O.txid = txid; - O.value = value; - O.vout = vout; - memcpy(opret,&O,sizeof(O)); - memcpy(&opret[sizeof(O)],buf,opretlen); - O.oplen = (int32_t)(opretlen + sizeof(O)); - komodo_eventadd(sp,height,symbol,KOMODO_EVENT_OPRETURN,opret,O.oplen); - free(opret); - if ( sp != 0 ) - komodo_opreturn(height,value,buf,opretlen,txid,vout,symbol); + if ( ASSETCHAINS_SYMBOL[0] != 0 ) + { + opret = (uint8_t *)calloc(1,sizeof(O) + opretlen + 16); + O.txid = txid; + O.value = value; + O.vout = vout; + memcpy(opret,&O,sizeof(O)); + memcpy(&opret[sizeof(O)],buf,opretlen); + O.oplen = (int32_t)(opretlen + sizeof(O)); + komodo_eventadd(sp,height,symbol,KOMODO_EVENT_OPRETURN,opret,O.oplen); + free(opret); + if ( sp != 0 ) + komodo_opreturn(height,value,buf,opretlen,txid,vout,symbol); + } } void komodo_event_undo(struct komodo_state *sp,struct komodo_event *ep) From 28616d3592fa82d114372b8823896655fa91fe26 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 15:56:31 +0300 Subject: [PATCH 241/507] Fix possible buffer overflow and reduce KMD memory usage --- src/komodo_events.h | 102 ++++++++++++++++++++++++-------------------- 1 file changed, 56 insertions(+), 46 deletions(-) diff --git a/src/komodo_events.h b/src/komodo_events.h index ff054c3bb..c64ccbaa2 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * @@ -20,7 +20,7 @@ struct komodo_event *komodo_eventadd(struct komodo_state *sp,int32_t height,char *symbol,uint8_t type,uint8_t *data,uint16_t datalen) { struct komodo_event *ep=0; uint16_t len = (uint16_t)(sizeof(*ep) + datalen); - if ( sp != 0 ) + if ( sp != 0 && ASSETCHAINS_SYMBOL[0] != 0 ) { portable_mutex_lock(&komodo_mutex); ep = (struct komodo_event *)calloc(1,len); @@ -37,10 +37,10 @@ struct komodo_event *komodo_eventadd(struct komodo_state *sp,int32_t height,char return(ep); } -void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t height,char *dest,uint256 notarized_hash,uint256 notarized_desttxid,int32_t notarizedheight) +void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t height,char *dest,uint256 notarized_hash,uint256 notarized_desttxid,int32_t notarizedheight,uint256 MoM,int32_t MoMdepth) { struct komodo_event_notarized N; - if ( komodo_verifynotarization(symbol,dest,height,notarizedheight,notarized_hash,notarized_desttxid) != 0 ) + if ( NOTARY_PUBKEY33[0] != 0 && komodo_verifynotarization(symbol,dest,height,notarizedheight,notarized_hash,notarized_desttxid) != 0 ) { if ( height > 50000 || ASSETCHAINS_SYMBOL[0] != 0 ) printf("[%s] error validating notarization ht.%d notarized_height.%d, if on a pruned %s node this can be ignored\n",ASSETCHAINS_SYMBOL,height,notarizedheight,dest); @@ -53,10 +53,12 @@ void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t heig N.blockhash = notarized_hash; N.desttxid = notarized_desttxid; N.notarizedheight = notarizedheight; - strcpy(N.dest,dest); + N.MoM = MoM; + N.MoMdepth = MoMdepth; + strncpy(N.dest,dest,sizeof(N.dest)-1); komodo_eventadd(sp,height,symbol,KOMODO_EVENT_NOTARIZED,(uint8_t *)&N,sizeof(N)); if ( sp != 0 ) - komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid); + komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid,MoM,MoMdepth); } } @@ -75,27 +77,34 @@ void komodo_eventadd_pubkeys(struct komodo_state *sp,char *symbol,int32_t height void komodo_eventadd_pricefeed(struct komodo_state *sp,char *symbol,int32_t height,uint32_t *prices,uint8_t num) { struct komodo_event_pricefeed F; - memset(&F,0,sizeof(F)); - F.num = num; - memcpy(F.prices,prices,sizeof(*F.prices) * num); - komodo_eventadd(sp,height,symbol,KOMODO_EVENT_PRICEFEED,(uint8_t *)&F,(int32_t)(sizeof(F.num) + sizeof(*F.prices) * num)); - if ( sp != 0 ) - komodo_pvals(height,prices,num); + if ( num == sizeof(F.prices)/sizeof(*F.prices) ) + { + memset(&F,0,sizeof(F)); + F.num = num; + memcpy(F.prices,prices,sizeof(*F.prices) * num); + komodo_eventadd(sp,height,symbol,KOMODO_EVENT_PRICEFEED,(uint8_t *)&F,(int32_t)(sizeof(F.num) + sizeof(*F.prices) * num)); + if ( sp != 0 ) + komodo_pvals(height,prices,num); + } //else fprintf(stderr,"skip pricefeed[%d]\n",num); } void komodo_eventadd_opreturn(struct komodo_state *sp,char *symbol,int32_t height,uint256 txid,uint64_t value,uint16_t vout,uint8_t *buf,uint16_t opretlen) { - struct komodo_event_opreturn O; uint8_t opret[16384]; - memset(&O,0,sizeof(O)); - O.txid = txid; - O.value = value; - O.vout = vout; - memcpy(opret,&O,sizeof(O)); - memcpy(&opret[sizeof(O)],buf,opretlen); - O.oplen = (int32_t)(opretlen + sizeof(O)); - komodo_eventadd(sp,height,symbol,KOMODO_EVENT_OPRETURN,opret,O.oplen); - if ( sp != 0 ) - komodo_opreturn(height,value,buf,opretlen,txid,vout,symbol); + struct komodo_event_opreturn O; uint8_t *opret; + if ( ASSETCHAINS_SYMBOL[0] != 0 ) + { + opret = (uint8_t *)calloc(1,sizeof(O) + opretlen + 16); + O.txid = txid; + O.value = value; + O.vout = vout; + memcpy(opret,&O,sizeof(O)); + memcpy(&opret[sizeof(O)],buf,opretlen); + O.oplen = (int32_t)(opretlen + sizeof(O)); + komodo_eventadd(sp,height,symbol,KOMODO_EVENT_OPRETURN,opret,O.oplen); + free(opret); + if ( sp != 0 ) + komodo_opreturn(height,value,buf,opretlen,txid,vout,symbol); + } } void komodo_event_undo(struct komodo_state *sp,struct komodo_event *ep) @@ -169,6 +178,7 @@ void komodo_eventadd_kmdheight(struct komodo_state *sp,char *symbol,int32_t heig } else { + //fprintf(stderr,"REWIND kmdheight.%d\n",kmdheight); kmdheight = -kmdheight; komodo_eventadd(sp,height,symbol,KOMODO_EVENT_REWIND,(uint8_t *)&height,sizeof(height)); if ( sp != 0 ) @@ -178,30 +188,30 @@ void komodo_eventadd_kmdheight(struct komodo_state *sp,char *symbol,int32_t heig /*void komodo_eventadd_deposit(int32_t actionflag,char *symbol,int32_t height,uint64_t komodoshis,char *fiat,uint64_t fiatoshis,uint8_t rmd160[20],bits256 kmdtxid,uint16_t kmdvout,uint64_t price) -{ - uint8_t opret[512]; uint16_t opretlen; - komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_DEPOSIT,kmdtxid,komodoshis,kmdvout,opret,opretlen); -} - -void komodo_eventadd_issued(int32_t actionflag,char *symbol,int32_t height,int32_t fiatheight,bits256 fiattxid,uint16_t fiatvout,bits256 kmdtxid,uint16_t kmdvout,uint64_t fiatoshis) -{ - uint8_t opret[512]; uint16_t opretlen; - komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_ISSUED,fiattxid,fiatoshis,fiatvout,opret,opretlen); -} - -void komodo_eventadd_withdraw(int32_t actionflag,char *symbol,int32_t height,uint64_t komodoshis,char *fiat,uint64_t fiatoshis,uint8_t rmd160[20],bits256 fiattxid,int32_t fiatvout,uint64_t price) -{ - uint8_t opret[512]; uint16_t opretlen; - komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_WITHDRAW,fiattxid,fiatoshis,fiatvout,opret,opretlen); -} - -void komodo_eventadd_redeemed(int32_t actionflag,char *symbol,int32_t height,bits256 kmdtxid,uint16_t kmdvout,int32_t fiatheight,bits256 fiattxid,uint16_t fiatvout,uint64_t komodoshis) -{ - uint8_t opret[512]; uint16_t opretlen; - komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_REDEEMED,kmdtxid,komodoshis,kmdvout,opret,opretlen); -}*/ + { + uint8_t opret[512]; uint16_t opretlen; + komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_DEPOSIT,kmdtxid,komodoshis,kmdvout,opret,opretlen); + } + + void komodo_eventadd_issued(int32_t actionflag,char *symbol,int32_t height,int32_t fiatheight,bits256 fiattxid,uint16_t fiatvout,bits256 kmdtxid,uint16_t kmdvout,uint64_t fiatoshis) + { + uint8_t opret[512]; uint16_t opretlen; + komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_ISSUED,fiattxid,fiatoshis,fiatvout,opret,opretlen); + } + + void komodo_eventadd_withdraw(int32_t actionflag,char *symbol,int32_t height,uint64_t komodoshis,char *fiat,uint64_t fiatoshis,uint8_t rmd160[20],bits256 fiattxid,int32_t fiatvout,uint64_t price) + { + uint8_t opret[512]; uint16_t opretlen; + komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_WITHDRAW,fiattxid,fiatoshis,fiatvout,opret,opretlen); + } + + void komodo_eventadd_redeemed(int32_t actionflag,char *symbol,int32_t height,bits256 kmdtxid,uint16_t kmdvout,int32_t fiatheight,bits256 fiattxid,uint16_t fiatvout,uint64_t komodoshis) + { + uint8_t opret[512]; uint16_t opretlen; + komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_REDEEMED,kmdtxid,komodoshis,kmdvout,opret,opretlen); + }*/ // process events -// +// #endif From ff89a2e7d692aa5d00b97291063472ca7614f667 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 15:58:34 +0300 Subject: [PATCH 242/507] Fix syntax --- src/komodo_events.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/komodo_events.h b/src/komodo_events.h index c64ccbaa2..30e745051 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -37,7 +37,7 @@ struct komodo_event *komodo_eventadd(struct komodo_state *sp,int32_t height,char return(ep); } -void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t height,char *dest,uint256 notarized_hash,uint256 notarized_desttxid,int32_t notarizedheight,uint256 MoM,int32_t MoMdepth) +void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t height,char *dest,uint256 notarized_hash,uint256 notarized_desttxid,int32_t notarizedheight)//,uint256 MoM,int32_t MoMdepth) { struct komodo_event_notarized N; if ( NOTARY_PUBKEY33[0] != 0 && komodo_verifynotarization(symbol,dest,height,notarizedheight,notarized_hash,notarized_desttxid) != 0 ) @@ -53,12 +53,12 @@ void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t heig N.blockhash = notarized_hash; N.desttxid = notarized_desttxid; N.notarizedheight = notarizedheight; - N.MoM = MoM; - N.MoMdepth = MoMdepth; + //N.MoM = MoM; + //N.MoMdepth = MoMdepth; strncpy(N.dest,dest,sizeof(N.dest)-1); komodo_eventadd(sp,height,symbol,KOMODO_EVENT_NOTARIZED,(uint8_t *)&N,sizeof(N)); if ( sp != 0 ) - komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid,MoM,MoMdepth); + komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid)//,MoM,MoMdepth); } } From c3e2036428ce80e7dc567384b80302174d718f9d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 15:59:28 +0300 Subject: [PATCH 243/507] ; minor bug fix update --- src/komodo_events.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_events.h b/src/komodo_events.h index 30e745051..219d6e479 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -58,7 +58,7 @@ void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t heig strncpy(N.dest,dest,sizeof(N.dest)-1); komodo_eventadd(sp,height,symbol,KOMODO_EVENT_NOTARIZED,(uint8_t *)&N,sizeof(N)); if ( sp != 0 ) - komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid)//,MoM,MoMdepth); + komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid);//,MoM,MoMdepth); } } From 98dc898d4011f0ddbdce431c44bc9558b58e5bb5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 16:02:09 +0300 Subject: [PATCH 244/507] Remove printouts --- src/komodo.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 129ea3b5f..aba93c9e4 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -189,7 +189,7 @@ int32_t komodo_parsestatefile(struct komodo_state *sp,FILE *fp,char *symbol,char //printf("load pvals ht.%d numpvals.%d\n",ht,numpvals); } else printf("error loading pvals[%d]\n",numpvals); } - else printf("[%s] %s illegal func.(%d %c)\n",ASSETCHAINS_SYMBOL,symbol,func,func); + // else printf("[%s] %s illegal func.(%d %c)\n",ASSETCHAINS_SYMBOL,symbol,func,func); return(func); } else return(-1); } @@ -319,7 +319,7 @@ int32_t komodo_parsestatefiledata(struct komodo_state *sp,uint8_t *filedata,long //printf("load pvals ht.%d numpvals.%d\n",ht,numpvals); } else printf("error loading pvals[%d]\n",numpvals); } - else printf("[%s] %s illegal func.(%d %c)\n",ASSETCHAINS_SYMBOL,symbol,func,func); + // else printf("[%s] %s illegal func.(%d %c)\n",ASSETCHAINS_SYMBOL,symbol,func,func); *fposp = fpos; return(func); } From 8dc1322c41999b6d7975bbfb21d9d72cc030fd0a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 16:02:46 +0300 Subject: [PATCH 245/507] -printf --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 7061fa4eb..48324ca42 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3436,7 +3436,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc if (!ContextualCheckBlockHeader(block, state, pindexPrev)) { pindex->nStatus |= BLOCK_FAILED_MASK; - fprintf(stderr,"known block.%d failing ContextualCheckBlockHeader\n",(int32_t)pindex->nHeight); + //fprintf(stderr,"known block.%d failing ContextualCheckBlockHeader\n",(int32_t)pindex->nHeight); return false; } } From f73e64e0f5a848b0e49cec6d576711b85041b5d1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 14 Apr 2018 16:16:49 +0300 Subject: [PATCH 246/507] Prints --- src/komodo_bitcoind.h | 2 +- src/main.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 95ec0f095..cd65ab9dd 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -651,7 +651,7 @@ int32_t komodo_block2height(CBlock *block) } if ( height != height2 ) { - fprintf(stderr,"block2height height.%d vs height2.%d, match.%d mismatch.%d\n",height,height2,match,mismatch); + //fprintf(stderr,"block2height height.%d vs height2.%d, match.%d mismatch.%d\n",height,height2,match,mismatch); mismatch++; if ( height2 >= 0 ) height = height2; diff --git a/src/main.cpp b/src/main.cpp index cf854dbf1..cf5674958 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3778,7 +3778,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, return false; if ( pindex == 0 ) { - fprintf(stderr,"AcceptBlock error null pindex\n"); + //fprintf(stderr,"AcceptBlock error null pindex\n"); return false; } // Try to process all requested blocks that we don't have, but only From f5befabb97eac9ac762c07886884455f6b4ca1f8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 12:45:59 +0300 Subject: [PATCH 247/507] Sync dpowassets --- src/dpowassets | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/dpowassets b/src/dpowassets index bd970c357..14bb39912 100755 --- a/src/dpowassets +++ b/src/dpowassets @@ -26,11 +26,10 @@ curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dp curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"AXO\",\"pubkey\":\"$pubkey\"}" curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"ETOMIC\",\"pubkey\":\"$pubkey\"}" curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"BTCH\",\"pubkey\":\"$pubkey\"}" -#curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"CHAIN\",\"pubkey\":\"$pubkey\"}" +curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"CHAIN\",\"pubkey\":\"$pubkey\"}" curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"VOTE2018\",\"pubkey\":\"$pubkey\"}" curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"NINJA\",\"pubkey\":\"$pubkey\"}" curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"OOT\",\"pubkey\":\"$pubkey\"}" -#curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"BNTN\",\"pubkey\":\"$pubkey\"}" +curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"BNTN\",\"pubkey\":\"$pubkey\"}" +curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"PRLPAY\",\"pubkey\":\"$pubkey\"}" -#curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"USD\",\"pubkey\":\"$pubkey\"}" -#curl --url "http://127.0.0.1:7776" --data "{\"agent\":\"iguana\",\"method\":\"dpow\",\"symbol\":\"EUR\",\"pubkey\":\"$pubkey\"}" From ff5cd12f702d231d6eecc1edb7aa50cc6550dcf5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 12:54:47 +0300 Subject: [PATCH 248/507] Add realtime fork detection --- src/komodo.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index aba93c9e4..502e09d66 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -476,7 +476,7 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar int32_t komodo_voutupdate(int32_t *isratificationp,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,uint64_t value,int32_t notarized,uint64_t signedmask,uint32_t timestamp) { static uint256 zero; static FILE *signedfp; - int32_t opretlen,nid,k,len = 0; uint256 kmdtxid,desttxid; uint8_t crypto777[33]; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; + CBlockIndex *pindex; int32_t opretlen,nid,k,len = 0; uint256 kmdtxid,desttxid; uint8_t crypto777[33]; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; if ( (sp= komodo_stateptr(symbol,dest)) == 0 ) return(-1); if ( scriptlen == 35 && scriptbuf[0] == 33 && scriptbuf[34] == 0xac ) @@ -537,6 +537,11 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&kmdtxid); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); + if ( notarized != 0 && IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != *notarizedheightp) ) + { + fprintf(stderr,"%s possible FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,*notarizedheightp,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,rewindtarget); + notarized = 0; + } if ( notarized != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height && (height < sp->CURRENT_HEIGHT-1000 || komodo_verifynotarization(ASSETCHAINS_SYMBOL[0]==0?(char *)"KMD":ASSETCHAINS_SYMBOL,(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "BTC" : "KMD"),height,*notarizedheightp,kmdtxid,desttxid) == 0) ) { sp->NOTARIZED_HEIGHT = *notarizedheightp; From 9504daf6ef98afed029aabbeafcd176635d24550 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 12:56:05 +0300 Subject: [PATCH 249/507] Sp->NOTARIZED_HEIGHT --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 502e09d66..bcf5be91c 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -539,7 +539,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); if ( notarized != 0 && IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != *notarizedheightp) ) { - fprintf(stderr,"%s possible FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,*notarizedheightp,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,rewindtarget); + fprintf(stderr,"%s possible FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,*notarizedheightp,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,sp->NOTARIZED_HEIGHT); notarized = 0; } if ( notarized != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height && (height < sp->CURRENT_HEIGHT-1000 || komodo_verifynotarization(ASSETCHAINS_SYMBOL[0]==0?(char *)"KMD":ASSETCHAINS_SYMBOL,(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "BTC" : "KMD"),height,*notarizedheightp,kmdtxid,desttxid) == 0) ) From 52ec573ade7224f84e965f3138b1e23ec0b4b24a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 12:57:19 +0300 Subject: [PATCH 250/507] Use kmdtxid --- src/komodo.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index bcf5be91c..63569e60d 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -537,9 +537,9 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&kmdtxid); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); - if ( notarized != 0 && IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != *notarizedheightp) ) + if ( notarized != 0 && IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[kmdtxid]) == 0 || pindex->nHeight != *notarizedheightp) ) { - fprintf(stderr,"%s possible FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,*notarizedheightp,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,sp->NOTARIZED_HEIGHT); + fprintf(stderr,"%s possible FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,*notarizedheightp,kmdtxid.ToString().c_str(),sp->NOTARIZED_HEIGHT,sp->NOTARIZED_HEIGHT); notarized = 0; } if ( notarized != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height && (height < sp->CURRENT_HEIGHT-1000 || komodo_verifynotarization(ASSETCHAINS_SYMBOL[0]==0?(char *)"KMD":ASSETCHAINS_SYMBOL,(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "BTC" : "KMD"),height,*notarizedheightp,kmdtxid,desttxid) == 0) ) From 56bd32aee3766ef13005c2ff1e72248501eb72c2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 15:57:22 +0300 Subject: [PATCH 251/507] -printf only --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index bc7ec2bd5..e9ddd4fc0 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -651,7 +651,7 @@ int32_t komodo_block2height(CBlock *block) } if ( height != height2 ) { - fprintf(stderr,"block2height height.%d vs height2.%d, match.%d mismatch.%d\n",height,height2,match,mismatch); + //fprintf(stderr,"block2height height.%d vs height2.%d, match.%d mismatch.%d\n",height,height2,match,mismatch); mismatch++; if ( height2 >= 0 ) height = height2; From c7a1d2340895a9110bc54461986bd363c8835ec6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 17:28:37 +0300 Subject: [PATCH 252/507] Lenient banscore --- src/komodo.h | 47 ++++++++++++++++++++++++++----------------- src/main.cpp | 14 +++++++++---- src/miner.cpp | 2 +- src/rpcblockchain.cpp | 2 +- 4 files changed, 41 insertions(+), 24 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index f422a639d..fa5d1044f 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -507,6 +507,31 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar } } +int32_t komodo_validate_chain(uint256 srchash,int32_t notarized_height) +{ + static int32_t last_rewind; int32_t rewindtarget; CBlockIndex *pblock; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; + if ( (sp= komodo_stateptr(symbol,dest)) == 0 ) + return(0); + if ( IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != notarizedheight) ) + { + if ( sp->NOTARIZED_HEIGHT > 0 && sp->NOTARIZED_HEIGHT < notarizedheight ) + rewindtarget = sp->NOTARIZED_HEIGHT - 1; + else if ( *notarizedheightp > 101 ) + rewindtarget = notarizedheight - 101; + else rewindtarget = 0; + if ( rewindtarget != 0 && rewindtarget > KOMODO_REWIND && rewindtarget > last_rewind ) + { + if ( last_rewind != 0 ) + { + KOMODO_REWIND = rewindtarget; + fprintf(stderr,"%s FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,notarizedheight,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,rewindtarget); + } + last_rewind = rewindtarget; + } + return(0); + } else return(1); +} + int32_t komodo_voutupdate(int32_t *isratificationp,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,uint64_t value,int32_t notarized,uint64_t signedmask,uint32_t timestamp) { static uint256 zero; static FILE *signedfp; @@ -557,8 +582,8 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } if ( scriptbuf[len++] == 0x6a ) { - static int32_t last_rewind; int32_t rewindtarget,validated = 0,nameoffset,opoffset = 0; CBlockIndex *pindex;// struct komodo_ccdata ccdata; struct komodo_ccdataMoMoM MoMoMdata; + int32_t validated = 0,nameoffset,opoffset = 0; if ( (opretlen= scriptbuf[len++]) == 0x4c ) opretlen = scriptbuf[len++]; else if ( opretlen == 0x4d ) @@ -598,23 +623,9 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); if ( matched != 0 ) len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); - if ( matched != 0 && IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != *notarizedheightp) ) - { - if ( sp->NOTARIZED_HEIGHT > 0 && sp->NOTARIZED_HEIGHT < *notarizedheightp ) - rewindtarget = sp->NOTARIZED_HEIGHT - 1; - else if ( *notarizedheightp > 101 ) - rewindtarget = *notarizedheightp - 101; - else rewindtarget = 0; - if ( rewindtarget != 0 && rewindtarget > KOMODO_REWIND && rewindtarget > last_rewind ) - { - if ( last_rewind != 0 ) - { - KOMODO_REWIND = rewindtarget; - fprintf(stderr,"%s FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,*notarizedheightp,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,rewindtarget); - } - last_rewind = rewindtarget; - } - } else validated = 1; + if ( matched != 0 ) + validated = komodo_validate_chain(srchash,*notarizedheightp); + else validated = 1; if ( notarized != 0 && validated != 0 ) { //sp->NOTARIZED_HEIGHT = *notarizedheightp; diff --git a/src/main.cpp b/src/main.cpp index cf5674958..9d7bceded 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1242,11 +1242,14 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa return error("AcceptToMemoryPool: komodo_validate_interest failed"); } if (!CheckTransaction(tx, state, verifier)) + { + return error("AcceptToMemoryPool: CheckTransaction failed"); - + } // DoS level set to 10 to be more forgiving. // Check transaction contextually against the set of consensus rules which apply in the next block to be mined. - if (!ContextualCheckTransaction(tx, state, nextBlockHeight, 10)) { + if (!ContextualCheckTransaction(tx, state, nextBlockHeight, 10)) + { return error("AcceptToMemoryPool: ContextualCheckTransaction failed"); } @@ -1850,7 +1853,7 @@ void Misbehaving(NodeId pnode, int howmuch) return; state->nMisbehavior += howmuch; - int banscore = GetArg("-banscore", 100); + int banscore = GetArg("-banscore", 5000); if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore) { LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior); @@ -3865,9 +3868,12 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc LOCK(cs_main); bool fRequested = MarkBlockAsReceived(pblock->GetHash()); fRequested |= fForceProcessing; - if (!checked) { + if (!checked) + { if ( pfrom != 0 ) + { Misbehaving(pfrom->GetId(), 1); + } return error("%s: CheckBlock FAILED", __func__); } diff --git a/src/miner.cpp b/src/miner.cpp index c13d5030c..fc5bcfb12 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -212,7 +212,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight)) continue; - if ( komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,2) < 0 ) + if ( komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 ) { fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure\n"); continue; diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 425472758..f1fefcf96 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -803,7 +803,7 @@ UniValue minerids(const UniValue& params, bool fHelp) if ( pblockindex != 0 ) timestamp = pblockindex->GetBlockTime(); } - if ( 0 && (n= komodo_minerids(minerids,height,(int32_t)(sizeof(minerids)/sizeof(*minerids)))) > 0 ) + if ( (n= komodo_minerids(minerids,height,(int32_t)(sizeof(minerids)/sizeof(*minerids)))) > 0 ) { memset(tally,0,sizeof(tally)); numnotaries = komodo_notaries(pubkeys,height,timestamp); From 76140489aaa97f5d6be4fe3b46684fcc866fa4c8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 17:30:40 +0300 Subject: [PATCH 253/507] Fix notarizedheight --- src/komodo.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index fa5d1044f..8fcfe30a0 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -512,19 +512,19 @@ int32_t komodo_validate_chain(uint256 srchash,int32_t notarized_height) static int32_t last_rewind; int32_t rewindtarget; CBlockIndex *pblock; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; if ( (sp= komodo_stateptr(symbol,dest)) == 0 ) return(0); - if ( IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != notarizedheight) ) + if ( IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != notarized_height) ) { - if ( sp->NOTARIZED_HEIGHT > 0 && sp->NOTARIZED_HEIGHT < notarizedheight ) + if ( sp->NOTARIZED_HEIGHT > 0 && sp->NOTARIZED_HEIGHT < notarized_height ) rewindtarget = sp->NOTARIZED_HEIGHT - 1; - else if ( *notarizedheightp > 101 ) - rewindtarget = notarizedheight - 101; + else if ( notarized_height > 101 ) + rewindtarget = notarized_height - 101; else rewindtarget = 0; if ( rewindtarget != 0 && rewindtarget > KOMODO_REWIND && rewindtarget > last_rewind ) { if ( last_rewind != 0 ) { KOMODO_REWIND = rewindtarget; - fprintf(stderr,"%s FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,notarizedheight,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,rewindtarget); + fprintf(stderr,"%s FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,notarized_height,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,rewindtarget); } last_rewind = rewindtarget; } From cd29c830885ebf5db35823acd501b665fae40aab Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 17:31:46 +0300 Subject: [PATCH 254/507] +pindex --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 8fcfe30a0..ad99a4387 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -509,7 +509,7 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar int32_t komodo_validate_chain(uint256 srchash,int32_t notarized_height) { - static int32_t last_rewind; int32_t rewindtarget; CBlockIndex *pblock; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; + static int32_t last_rewind; int32_t rewindtarget; CBlockIndex *pindex; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; if ( (sp= komodo_stateptr(symbol,dest)) == 0 ) return(0); if ( IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != notarized_height) ) From 42bdb117c671ecff9d2d9b654e5dffa1be39b429 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 17:51:49 +0300 Subject: [PATCH 255/507] Test --- src/main.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 9d7bceded..72ca12c2f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1853,7 +1853,7 @@ void Misbehaving(NodeId pnode, int howmuch) return; state->nMisbehavior += howmuch; - int banscore = GetArg("-banscore", 5000); + int banscore = GetArg("-banscore", 101); if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore) { LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior); @@ -3524,7 +3524,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat libzcash::ProofVerifier& verifier, bool fCheckPOW, bool fCheckMerkleRoot) { - uint8_t pubkey33[33]; + uint8_t pubkey33[33]; CBlockIndex *tipindex; // These are checks that are independent of context. // Check that the header is valid (particularly PoW). This is mostly @@ -3534,8 +3534,13 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat //komodo_index2pubkey33(pubkey33,pindex,height); komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) - return state.DoS(50, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); - + { + if ( (tipindex= chainActive.Tip()) != 0 && height >= tipindex->nHeight && IsInitialBlockDownload() == 0 && komodo_longestchain() > tipindex->nHeight+100 ) + { + fprintf(stderr,"tip.%d longest.%d newblock.%d/%d\n",tipindex->nHeight,komodo_longestchain(),height,pindex->nHeight); + } + return state.DoS(33, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); + } // Check the merkle root. if (fCheckMerkleRoot) { bool mutated; From ad4ca5c5052fdd2ca77e943a679f5897c9c6e1fd Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 17:58:29 +0300 Subject: [PATCH 256/507] Test --- src/main.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 72ca12c2f..530ae2b62 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1412,7 +1412,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa CAmount txMinFee = GetMinRelayFee(tx, nSize, true); if (fLimitFree && nFees < txMinFee) { - fprintf(stderr,"accept failure.5\n"); + //fprintf(stderr,"accept failure.5\n"); return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",hash.ToString(), nFees, txMinFee),REJECT_INSUFFICIENTFEE, "insufficient fee"); } } @@ -3535,9 +3535,13 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) { - if ( (tipindex= chainActive.Tip()) != 0 && height >= tipindex->nHeight && IsInitialBlockDownload() == 0 && komodo_longestchain() > tipindex->nHeight+100 ) + if ( (tipindex= chainActive.Tip()) != 0 && height >= tipindex->nHeight && IsInitialBlockDownload() == 0 ) { - fprintf(stderr,"tip.%d longest.%d newblock.%d/%d\n",tipindex->nHeight,komodo_longestchain(),height,pindex->nHeight); + fprintf(stderr,"check longest chain\n"); + if ( komodo_longestchain() > tipindex->nHeight+100 ) + { + fprintf(stderr,"tip.%d longest.%d newblock.%d/%d\n",tipindex->nHeight,komodo_longestchain(),height,pindex->nHeight); + } } return state.DoS(33, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); } From d085cf67abcb23fabf01ffc3282c7f70b357e470 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 18:02:58 +0300 Subject: [PATCH 257/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 530ae2b62..5f4f6c3e4 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3540,7 +3540,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat fprintf(stderr,"check longest chain\n"); if ( komodo_longestchain() > tipindex->nHeight+100 ) { - fprintf(stderr,"tip.%d longest.%d newblock.%d/%d\n",tipindex->nHeight,komodo_longestchain(),height,pindex->nHeight); + fprintf(stderr,"tip.%d longest.%d newblock.%d\n",tipindex->nHeight,komodo_longestchain(),height); } } return state.DoS(33, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); From 78c23c84c7d502474b442fdf68e8c4ecdf700e28 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 18:10:28 +0300 Subject: [PATCH 258/507] Test --- src/rpcnet.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/rpcnet.cpp b/src/rpcnet.cpp index d2798f10c..13accb4c3 100644 --- a/src/rpcnet.cpp +++ b/src/rpcnet.cpp @@ -168,11 +168,13 @@ UniValue getpeerinfo(const UniValue& params, bool fHelp) int32_t komodo_longestchain() { int32_t ht,n=0,num=0,maxheight=0,height = 0; - LOCK(cs_main); + //LOCK(cs_main); + fprintf(stderr,"komodo_longestchain\n"); vector vstats; CopyNodeStats(vstats); BOOST_FOREACH(const CNodeStats& stats, vstats) { + fprintf(stderr,"komodo_longestchain iter.%d\n",n); CNodeStateStats statestats; bool fStateStats = GetNodeStateStats(stats.nodeid,statestats); ht = 0; From 6477ad07af42e75becac4069967e968197337cb4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 18:19:20 +0300 Subject: [PATCH 259/507] Test --- src/main.cpp | 29 ++++++++++++++++------------- src/rpcnet.cpp | 12 ++++++++---- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 5f4f6c3e4..0957930d6 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -53,7 +53,7 @@ using namespace std; CCriticalSection cs_main; extern uint8_t NOTARY_PUBKEY33[33]; -extern int32_t KOMODO_LOADINGBLOCKS; +extern int32_t KOMODO_LOADINGBLOCKS,KOMODO_LONGESTCHAIN; void komodo_block2pubkey33(uint8_t *pubkey33,CBlock *block); BlockMap mapBlockIndex; @@ -3524,7 +3524,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat libzcash::ProofVerifier& verifier, bool fCheckPOW, bool fCheckMerkleRoot) { - uint8_t pubkey33[33]; CBlockIndex *tipindex; + uint8_t pubkey33[33]; // These are checks that are independent of context. // Check that the header is valid (particularly PoW). This is mostly @@ -3535,14 +3535,6 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) { - if ( (tipindex= chainActive.Tip()) != 0 && height >= tipindex->nHeight && IsInitialBlockDownload() == 0 ) - { - fprintf(stderr,"check longest chain\n"); - if ( komodo_longestchain() > tipindex->nHeight+100 ) - { - fprintf(stderr,"tip.%d longest.%d newblock.%d\n",tipindex->nHeight,komodo_longestchain(),height); - } - } return state.DoS(33, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); } // Check the merkle root. @@ -3711,14 +3703,24 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc // Check for duplicate uint256 hash = block.GetHash(); BlockMap::iterator miSelf = mapBlockIndex.find(hash); - CBlockIndex *pindex = NULL; + CBlockIndex *tipindex,*pindex = NULL; if (miSelf != mapBlockIndex.end()) { // Block header is already known. pindex = miSelf->second; if (ppindex) *ppindex = pindex; - if (pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK) + if ( pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK ) + { + if ( (tipindex= chainActive.Tip()) != 0 && pindex->nHeight >= tipindex->nHeight && IsInitialBlockDownload() == 0 ) + { + fprintf(stderr,"check longest chain.%d\n",KOMODO_LONGESTCHAIN); + if ( KOMODO_LONGESTCHAIN > tipindex->nHeight+100 ) + { + fprintf(stderr,"tip.%d longest.%d newblock.%d\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,pindex->nHeight); + } + } return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); + } if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 debug test { if (!CheckBlockHeader(pindex->nHeight,pindex, block, state)) @@ -5723,7 +5725,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } if (!AcceptBlockHeader(header, state, &pindexLast)) { int nDoS; - if (state.IsInvalid(nDoS)) { + if (state.IsInvalid(nDoS)) + { if (nDoS > 0) Misbehaving(pfrom->GetId(), nDoS/nDoS); return error("invalid header received"); diff --git a/src/rpcnet.cpp b/src/rpcnet.cpp index 13accb4c3..1d492f35a 100644 --- a/src/rpcnet.cpp +++ b/src/rpcnet.cpp @@ -165,16 +165,16 @@ UniValue getpeerinfo(const UniValue& params, bool fHelp) return ret; } +int32_t KOMODO_LONGESTCHAIN; int32_t komodo_longestchain() { int32_t ht,n=0,num=0,maxheight=0,height = 0; - //LOCK(cs_main); - fprintf(stderr,"komodo_longestchain\n"); + LOCK(cs_main); vector vstats; CopyNodeStats(vstats); BOOST_FOREACH(const CNodeStats& stats, vstats) { - fprintf(stderr,"komodo_longestchain iter.%d\n",n); + //fprintf(stderr,"komodo_longestchain iter.%d\n",n); CNodeStateStats statestats; bool fStateStats = GetNodeStateStats(stats.nodeid,statestats); ht = 0; @@ -193,8 +193,12 @@ int32_t komodo_longestchain() height = ht; } if ( num > (n >> 1) ) + { + KOMODO_LONGESTCHAIN = height; return(height); - else return(0); + } + KOMODO_LONGESTCHAIN = 0; + return(0); } UniValue addnode(const UniValue& params, bool fHelp) From 1486af0a9fc2e46794998303a52204e7fe5c2e9b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 18:38:06 +0300 Subject: [PATCH 260/507] Test --- src/main.cpp | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 0957930d6..234241b2d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3520,6 +3520,20 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtime); +int32_t komodo_reverify_blockcheck(int32_t height,CBlockIndex *pindex) +{ + CBlockIndex *tipindex; + if ( (tipindex= chainActive.Tip()) != 0 && height >= tipindex->nHeight && IsInitialBlockDownload() == 0 ) + { + fprintf(stderr,"check longest chain.%d\n",KOMODO_LONGESTCHAIN); + if ( KOMODO_LONGESTCHAIN > height+100 ) + { + fprintf(stderr,"tip.%d longest.%d newblock.%d\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height); + } + } + return(0); +} + bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidationState& state, libzcash::ProofVerifier& verifier, bool fCheckPOW, bool fCheckMerkleRoot) @@ -3535,6 +3549,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) { + komodo_reverify_blockcheck(height,pindex); return state.DoS(33, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); } // Check the merkle root. @@ -3703,7 +3718,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc // Check for duplicate uint256 hash = block.GetHash(); BlockMap::iterator miSelf = mapBlockIndex.find(hash); - CBlockIndex *tipindex,*pindex = NULL; + CBlockIndex *pindex = NULL; if (miSelf != mapBlockIndex.end()) { // Block header is already known. pindex = miSelf->second; @@ -3711,14 +3726,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc *ppindex = pindex; if ( pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK ) { - if ( (tipindex= chainActive.Tip()) != 0 && pindex->nHeight >= tipindex->nHeight && IsInitialBlockDownload() == 0 ) - { - fprintf(stderr,"check longest chain.%d\n",KOMODO_LONGESTCHAIN); - if ( KOMODO_LONGESTCHAIN > tipindex->nHeight+100 ) - { - fprintf(stderr,"tip.%d longest.%d newblock.%d\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,pindex->nHeight); - } - } + komodo_reverify_blockcheck(pindex->nHeight,pindex); return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); } if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 debug test From cef5ad03abc54ed77c7ddadcb580619388e685fe Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 18:59:20 +0300 Subject: [PATCH 261/507] Test --- src/main.cpp | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 234241b2d..20ca78e7c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3088,6 +3088,7 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo fprintf(stderr,">>>>>>>>>>> rewind start ht.%d -> KOMODO_REWIND.%d\n",chainActive.Tip()->nHeight,KOMODO_REWIND); while ( KOMODO_REWIND > 0 && chainActive.Tip()->nHeight > KOMODO_REWIND ) { + fBlocksDisconnected = true; fprintf(stderr,"%d ",(int32_t)chainActive.Tip()->nHeight); if ( !DisconnectTip(state) ) { @@ -3099,7 +3100,7 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo sleep(20); fprintf(stderr,"resuming normal operations\n"); KOMODO_REWIND = 0; - return(true); + //return(true); } // Build list of new blocks to connect. std::vector vpindexToConnect; @@ -3522,13 +3523,13 @@ int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtim int32_t komodo_reverify_blockcheck(int32_t height,CBlockIndex *pindex) { - CBlockIndex *tipindex; + CBlockIndex *tipindex; CBlock _block; if ( (tipindex= chainActive.Tip()) != 0 && height >= tipindex->nHeight && IsInitialBlockDownload() == 0 ) { - fprintf(stderr,"check longest chain.%d\n",KOMODO_LONGESTCHAIN); - if ( KOMODO_LONGESTCHAIN > height+100 ) + if ( KOMODO_LONGESTCHAIN > height+100 || GetAdjustedTime() > tipindex->nTime+3600 ) { - fprintf(stderr,"tip.%d longest.%d newblock.%d\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height); + fprintf(stderr,"tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),block->nTime); + KOMODO_REWIND = tipindex->nHeight - 11; } } return(0); @@ -4492,6 +4493,12 @@ bool RewindBlockIndex(const CChainParams& params) pindexIter->nSequenceId = 0; // Make sure it gets written setDirtyBlockIndex.insert(pindexIter); + if (pindexIter == pindexBestInvalid) + { + fprintf(stderr,"Reset invalid block marker if it was pointing to this block\n"); + pindexBestInvalid = NULL; + } + // Update indices setBlockIndexCandidates.erase(pindexIter); auto ret = mapBlocksUnlinked.equal_range(pindexIter->pprev); From 9de605d185eedcbf074ab9f806af60ad6b52631f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 19:00:53 +0300 Subject: [PATCH 262/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 20ca78e7c..4da0dfadb 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3528,7 +3528,7 @@ int32_t komodo_reverify_blockcheck(int32_t height,CBlockIndex *pindex) { if ( KOMODO_LONGESTCHAIN > height+100 || GetAdjustedTime() > tipindex->nTime+3600 ) { - fprintf(stderr,"tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),block->nTime); + fprintf(stderr,"tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),tipindex->nTime); KOMODO_REWIND = tipindex->nHeight - 11; } } From c031c2c759507bea01044661b7eb4fa13ba161a5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 19:01:39 +0300 Subject: [PATCH 263/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 4da0dfadb..b06fb875d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3526,7 +3526,7 @@ int32_t komodo_reverify_blockcheck(int32_t height,CBlockIndex *pindex) CBlockIndex *tipindex; CBlock _block; if ( (tipindex= chainActive.Tip()) != 0 && height >= tipindex->nHeight && IsInitialBlockDownload() == 0 ) { - if ( KOMODO_LONGESTCHAIN > height+100 || GetAdjustedTime() > tipindex->nTime+3600 ) + if ( KOMODO_LONGESTCHAIN > height+100 && GetAdjustedTime() > tipindex->nTime+3600 ) { fprintf(stderr,"tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),tipindex->nTime); KOMODO_REWIND = tipindex->nHeight - 11; From 15c97e2950ef91000d0be017d5afecd5d97958fb Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 19:09:53 +0300 Subject: [PATCH 264/507] Test --- src/main.cpp | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index b06fb875d..6b16f5982 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3521,15 +3521,26 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtime); -int32_t komodo_reverify_blockcheck(int32_t height,CBlockIndex *pindex) +int32_t komodo_reverify_blockcheck(CValidationState& state,int32_t height,CBlockIndex *pindex) { - CBlockIndex *tipindex; CBlock _block; + CBlockIndex *tipindex; int32_t rewindtarget; if ( (tipindex= chainActive.Tip()) != 0 && height >= tipindex->nHeight && IsInitialBlockDownload() == 0 ) { if ( KOMODO_LONGESTCHAIN > height+100 && GetAdjustedTime() > tipindex->nTime+3600 ) { fprintf(stderr,"tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),tipindex->nTime); - KOMODO_REWIND = tipindex->nHeight - 11; + rewindtarget = tipindex->nHeight - 11; + while ( rewindtarget > 0 && (tipindex= chainActive.Tip()) != 0 && tipindex->nHeight > rewindtarget ) + { + fprintf(stderr,"%d ",(int32_t)tipindex->nHeight); + if ( !DisconnectTip(state) ) + { + //InvalidateBlock(state,chainActive.Tip()); + break; + } + } + tipindex = chainActive.Tip(); + fprintf(stderr,"rewind done to %d\n",tipindex!=0?tipindex->nHeight:-1); } } return(0); @@ -3550,7 +3561,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) { - komodo_reverify_blockcheck(height,pindex); + komodo_reverify_blockcheck(state,height,pindex); return state.DoS(33, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); } // Check the merkle root. @@ -3727,7 +3738,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc *ppindex = pindex; if ( pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK ) { - komodo_reverify_blockcheck(pindex->nHeight,pindex); + komodo_reverify_blockcheck(state,pindex->nHeight,pindex); return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); } if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 debug test From 2cbb8be26b5023795751ba2c23126e654bb50b10 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 19:10:20 +0300 Subject: [PATCH 265/507] Test --- src/main.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main.cpp b/src/main.cpp index 6b16f5982..26df11cac 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3530,6 +3530,7 @@ int32_t komodo_reverify_blockcheck(CValidationState& state,int32_t height,CBlock { fprintf(stderr,"tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),tipindex->nTime); rewindtarget = tipindex->nHeight - 11; + fprintf(stderr,"rewindtarget <- %d\n",rewindtarget); while ( rewindtarget > 0 && (tipindex= chainActive.Tip()) != 0 && tipindex->nHeight > rewindtarget ) { fprintf(stderr,"%d ",(int32_t)tipindex->nHeight); From a9855467e28a2c8f935972fe9286e2f551ebad89 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 19:14:57 +0300 Subject: [PATCH 266/507] Test --- src/main.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 26df11cac..12b47f26c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3534,11 +3534,9 @@ int32_t komodo_reverify_blockcheck(CValidationState& state,int32_t height,CBlock while ( rewindtarget > 0 && (tipindex= chainActive.Tip()) != 0 && tipindex->nHeight > rewindtarget ) { fprintf(stderr,"%d ",(int32_t)tipindex->nHeight); + InvalidateBlock(state,tipindex); if ( !DisconnectTip(state) ) - { - //InvalidateBlock(state,chainActive.Tip()); break; - } } tipindex = chainActive.Tip(); fprintf(stderr,"rewind done to %d\n",tipindex!=0?tipindex->nHeight:-1); From 2ca62c8784f0647d4e3e7a5c15ce8598e73c7c1b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 19:32:01 +0300 Subject: [PATCH 267/507] Test --- src/main.cpp | 40 +++++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 12b47f26c..5f221d581 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3085,16 +3085,15 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo } if ( KOMODO_REWIND != 0 ) { + CBlockIndex *tipindex; fprintf(stderr,">>>>>>>>>>> rewind start ht.%d -> KOMODO_REWIND.%d\n",chainActive.Tip()->nHeight,KOMODO_REWIND); - while ( KOMODO_REWIND > 0 && chainActive.Tip()->nHeight > KOMODO_REWIND ) + while ( KOMODO_REWIND > 0 && (tipindex= chainActive.Tip()) != 0 && tipindex->nHeight > KOMODO_REWIND ) { fBlocksDisconnected = true; - fprintf(stderr,"%d ",(int32_t)chainActive.Tip()->nHeight); + fprintf(stderr,"%d ",(int32_t)tipindex->nHeight); + InvalidateBlock(state,tipindex); if ( !DisconnectTip(state) ) - { - InvalidateBlock(state,chainActive.Tip()); break; - } } fprintf(stderr,"reached rewind.%d, best to do: ./komodo-cli -ac_name=%s stop\n",KOMODO_REWIND,ASSETCHAINS_SYMBOL); sleep(20); @@ -3524,22 +3523,26 @@ int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtim int32_t komodo_reverify_blockcheck(CValidationState& state,int32_t height,CBlockIndex *pindex) { CBlockIndex *tipindex; int32_t rewindtarget; - if ( (tipindex= chainActive.Tip()) != 0 && height >= tipindex->nHeight && IsInitialBlockDownload() == 0 ) + if ( IsInitialBlockDownload() == 0 && (tipindex= chainActive.Tip()) != 0 && height >= tipindex->nHeight-10 ) { - if ( KOMODO_LONGESTCHAIN > height+100 && GetAdjustedTime() > tipindex->nTime+3600 ) + // if 200 blocks behind longestchain and no blocks for 2 hours + if ( KOMODO_LONGESTCHAIN > height+200 ) { - fprintf(stderr,"tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),tipindex->nTime); - rewindtarget = tipindex->nHeight - 11; - fprintf(stderr,"rewindtarget <- %d\n",rewindtarget); - while ( rewindtarget > 0 && (tipindex= chainActive.Tip()) != 0 && tipindex->nHeight > rewindtarget ) + if ( GetAdjustedTime() > tipindex->nTime+3600*2 ) { - fprintf(stderr,"%d ",(int32_t)tipindex->nHeight); - InvalidateBlock(state,tipindex); - if ( !DisconnectTip(state) ) - break; + fprintf(stderr,"tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),tipindex->nTime); + rewindtarget = tipindex->nHeight - 11; + fprintf(stderr,"rewindtarget <- %d\n",rewindtarget); + while ( rewindtarget > 0 && (tipindex= chainActive.Tip()) != 0 && tipindex->nHeight > rewindtarget ) + { + fprintf(stderr,"%d ",(int32_t)tipindex->nHeight); + InvalidateBlock(state,tipindex); + if ( !DisconnectTip(state) ) + break; + } + tipindex = chainActive.Tip(); + fprintf(stderr,"rewind done to %d\n",tipindex!=0?tipindex->nHeight:-1); } - tipindex = chainActive.Tip(); - fprintf(stderr,"rewind done to %d\n",tipindex!=0?tipindex->nHeight:-1); } } return(0); @@ -3769,11 +3772,10 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc if (!ContextualCheckBlockHeader(block, state, pindexPrev)) { pindex->nStatus |= BLOCK_FAILED_MASK; - fprintf(stderr,"known block.%d failing ContextualCheckBlockHeader\n",(int32_t)pindex->nHeight); + //fprintf(stderr,"known block.%d failing ContextualCheckBlockHeader\n",(int32_t)pindex->nHeight); return false; } } - return true; } From 412bb6a82402d5008126ee857e985857031b5e72 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 19:32:35 +0300 Subject: [PATCH 268/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 5f221d581..4c4038516 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3523,7 +3523,7 @@ int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtim int32_t komodo_reverify_blockcheck(CValidationState& state,int32_t height,CBlockIndex *pindex) { CBlockIndex *tipindex; int32_t rewindtarget; - if ( IsInitialBlockDownload() == 0 && (tipindex= chainActive.Tip()) != 0 && height >= tipindex->nHeight-10 ) + if ( IsInitialBlockDownload() == 0 && (tipindex= chainActive.Tip()) != 0 ) { // if 200 blocks behind longestchain and no blocks for 2 hours if ( KOMODO_LONGESTCHAIN > height+200 ) From 2c8d6b22461fda9b4de1f7f1f05a968a713e5c9e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 20:06:30 +0300 Subject: [PATCH 269/507] One shot rewind --- src/main.cpp | 4 +++- src/version.h | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 4c4038516..c7f500fa1 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3522,8 +3522,9 @@ int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtim int32_t komodo_reverify_blockcheck(CValidationState& state,int32_t height,CBlockIndex *pindex) { + static int32_t oneshot; CBlockIndex *tipindex; int32_t rewindtarget; - if ( IsInitialBlockDownload() == 0 && (tipindex= chainActive.Tip()) != 0 ) + if ( oneshot == 0 && IsInitialBlockDownload() == 0 && (tipindex= chainActive.Tip()) != 0 ) { // if 200 blocks behind longestchain and no blocks for 2 hours if ( KOMODO_LONGESTCHAIN > height+200 ) @@ -3533,6 +3534,7 @@ int32_t komodo_reverify_blockcheck(CValidationState& state,int32_t height,CBlock fprintf(stderr,"tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),tipindex->nTime); rewindtarget = tipindex->nHeight - 11; fprintf(stderr,"rewindtarget <- %d\n",rewindtarget); + oneshot = 1; while ( rewindtarget > 0 && (tipindex= chainActive.Tip()) != 0 && tipindex->nHeight > rewindtarget ) { fprintf(stderr,"%d ",(int32_t)tipindex->nHeight); diff --git a/src/version.h b/src/version.h index 25527895d..0a12fe8cb 100644 --- a/src/version.h +++ b/src/version.h @@ -31,3 +31,5 @@ static const int BIP0031_VERSION = 60000; static const int MEMPOOL_GD_VERSION = 60002; #endif // BITCOIN_VERSION_H + + From edf503844186a8e3ffa30c0efa9b5b46c50d8a51 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 20:07:56 +0300 Subject: [PATCH 270/507] -newlines --- src/version.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/version.h b/src/version.h index 0a12fe8cb..25527895d 100644 --- a/src/version.h +++ b/src/version.h @@ -31,5 +31,3 @@ static const int BIP0031_VERSION = 60000; static const int MEMPOOL_GD_VERSION = 60002; #endif // BITCOIN_VERSION_H - - From 8d65568383772c2b0d409bc6ba3d5373e272a01c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 21:15:20 +0300 Subject: [PATCH 271/507] main.cpp from dev --- src/main.cpp | 2273 +++++++++++++++++++++++++------------------------- 1 file changed, 1140 insertions(+), 1133 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index c7f500fa1..fa66fdb12 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -106,30 +106,30 @@ const string strMessageMagic = "Komodo Signed Message:\n"; // Internal stuff namespace { - + struct CBlockIndexWorkComparator { bool operator()(CBlockIndex *pa, CBlockIndex *pb) const { // First sort by most total work, ... if (pa->nChainWork > pb->nChainWork) return false; if (pa->nChainWork < pb->nChainWork) return true; - + // ... then by earliest time received, ... if (pa->nSequenceId < pb->nSequenceId) return false; if (pa->nSequenceId > pb->nSequenceId) return true; - + // Use pointer address as tie breaker (should only happen with blocks // loaded from disk, as those all have id 0). if (pa < pb) return false; if (pa > pb) return true; - + // Identical blocks. return false; } }; - + CBlockIndex *pindexBestInvalid; - + /** * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be @@ -139,10 +139,10 @@ namespace { /** Number of nodes with fSyncStarted. */ int nSyncStarted = 0; /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions. - * Pruned nodes may have entries where B is missing data. - */ + * Pruned nodes may have entries where B is missing data. + */ multimap mapBlocksUnlinked; - + CCriticalSection cs_LastBlockFile; std::vector vinfoBlockFile; int nLastBlockFile = 0; @@ -151,7 +151,7 @@ namespace { * or if we allocate more file space when we're in prune mode */ bool fCheckForPruning = false; - + /** * Every received block is assigned a unique and increasing identifier, so we * know which one to give priority in case of a fork. @@ -159,14 +159,14 @@ namespace { CCriticalSection cs_nBlockSequenceId; /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */ uint32_t nBlockSequenceId = 1; - + /** * Sources of received blocks, saved to be able to send them reject * messages or ban them when processing happens afterwards. Protected by * cs_main. */ map mapBlockSource; - + /** * Filter for transactions that were recently rejected by * AcceptToMemoryPool. These are not rerequested until the chain tip @@ -189,7 +189,7 @@ namespace { */ boost::scoped_ptr recentRejects; uint256 hashRecentRejectsChainTip; - + /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */ struct QueuedBlock { uint256 hash; @@ -199,16 +199,16 @@ namespace { int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer) }; map::iterator> > mapBlocksInFlight; - + /** Number of blocks in flight with validated headers. */ int nQueuedValidatedHeaders = 0; - + /** Number of preferable block download peers. */ int nPreferredDownload = 0; - + /** Dirty block index entries. */ set setDirtyBlockIndex; - + /** Dirty block file entries. */ set setDirtyFileInfo; } // anon namespace @@ -219,306 +219,306 @@ namespace { // namespace { - -struct CBlockReject { - unsigned char chRejectCode; - string strRejectReason; - uint256 hashBlock; -}; - -/** - * Maintain validation-specific state about nodes, protected by cs_main, instead - * by CNode's own locks. This simplifies asynchronous operation, where - * processing of incoming data is done after the ProcessMessage call returns, - * and we're no longer holding the node's locks. - */ -struct CNodeState { - //! The peer's address - CService address; - //! Whether we have a fully established connection. - bool fCurrentlyConnected; - //! Accumulated misbehaviour score for this peer. - int nMisbehavior; - //! Whether this peer should be disconnected and banned (unless whitelisted). - bool fShouldBan; - //! String name of this peer (debugging/logging purposes). - std::string name; - //! List of asynchronously-determined block rejections to notify this peer about. - std::vector rejects; - //! The best known block we know this peer has announced. - CBlockIndex *pindexBestKnownBlock; - //! The hash of the last unknown block this peer has announced. - uint256 hashLastUnknownBlock; - //! The last full block we both have. - CBlockIndex *pindexLastCommonBlock; - //! Whether we've started headers synchronization with this peer. - bool fSyncStarted; - //! Since when we're stalling block download progress (in microseconds), or 0. - int64_t nStallingSince; - list vBlocksInFlight; - int nBlocksInFlight; - int nBlocksInFlightValidHeaders; - //! Whether we consider this a preferred download peer. - bool fPreferredDownload; - - CNodeState() { - fCurrentlyConnected = false; - nMisbehavior = 0; - fShouldBan = false; - pindexBestKnownBlock = NULL; - hashLastUnknownBlock.SetNull(); - pindexLastCommonBlock = NULL; - fSyncStarted = false; - nStallingSince = 0; - nBlocksInFlight = 0; - nBlocksInFlightValidHeaders = 0; - fPreferredDownload = false; - } -}; - -/** Map maintaining per-node state. Requires cs_main. */ -map mapNodeState; - -// Requires cs_main. -CNodeState *State(NodeId pnode) { - map::iterator it = mapNodeState.find(pnode); - if (it == mapNodeState.end()) - return NULL; - return &it->second; -} - -int GetHeight() -{ - LOCK(cs_main); - return chainActive.Height(); -} - -void UpdatePreferredDownload(CNode* node, CNodeState* state) -{ - nPreferredDownload -= state->fPreferredDownload; - - // Whether this node should be marked as a preferred download node. - state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient; - - nPreferredDownload += state->fPreferredDownload; -} - -// Returns time at which to timeout block request (nTime in microseconds) -int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams) -{ - return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore); -} - -void InitializeNode(NodeId nodeid, const CNode *pnode) { - LOCK(cs_main); - CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second; - state.name = pnode->addrName; - state.address = pnode->addr; -} - -void FinalizeNode(NodeId nodeid) { - LOCK(cs_main); - CNodeState *state = State(nodeid); - - if (state->fSyncStarted) - nSyncStarted--; - - if (state->nMisbehavior == 0 && state->fCurrentlyConnected) { - AddressCurrentlyConnected(state->address); - } - - BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight) - mapBlocksInFlight.erase(entry.hash); - EraseOrphansFor(nodeid); - nPreferredDownload -= state->fPreferredDownload; - - mapNodeState.erase(nodeid); -} -void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) -{ -/* int expired = pool.Expire(GetTime() - age); - if (expired != 0) - LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired); + struct CBlockReject { + unsigned char chRejectCode; + string strRejectReason; + uint256 hashBlock; + }; - std::vector vNoSpendsRemaining; - pool.TrimToSize(limit, &vNoSpendsRemaining); - BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining) - pcoinsTip->Uncache(removed);*/ -} - -// Requires cs_main. -// Returns a bool indicating whether we requested this block. -bool MarkBlockAsReceived(const uint256& hash) { - map::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); - if (itInFlight != mapBlocksInFlight.end()) { - CNodeState *state = State(itInFlight->second.first); - nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders; - state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders; - state->vBlocksInFlight.erase(itInFlight->second.second); - state->nBlocksInFlight--; - state->nStallingSince = 0; - mapBlocksInFlight.erase(itInFlight); - return true; - } - return false; -} - -// Requires cs_main. -void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) { - CNodeState *state = State(nodeid); - assert(state != NULL); - - // Make sure it's not listed somewhere already. - MarkBlockAsReceived(hash); - - int64_t nNow = GetTimeMicros(); - QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)}; - nQueuedValidatedHeaders += newentry.fValidatedHeaders; - list::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry); - state->nBlocksInFlight++; - state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders; - mapBlocksInFlight[hash] = std::make_pair(nodeid, it); -} - -/** Check whether the last unknown block a peer advertized is not yet known. */ -void ProcessBlockAvailability(NodeId nodeid) { - CNodeState *state = State(nodeid); - assert(state != NULL); - - if (!state->hashLastUnknownBlock.IsNull()) { - BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock); - if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) - { - if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) - state->pindexBestKnownBlock = itOld->second; - state->hashLastUnknownBlock.SetNull(); + /** + * Maintain validation-specific state about nodes, protected by cs_main, instead + * by CNode's own locks. This simplifies asynchronous operation, where + * processing of incoming data is done after the ProcessMessage call returns, + * and we're no longer holding the node's locks. + */ + struct CNodeState { + //! The peer's address + CService address; + //! Whether we have a fully established connection. + bool fCurrentlyConnected; + //! Accumulated misbehaviour score for this peer. + int nMisbehavior; + //! Whether this peer should be disconnected and banned (unless whitelisted). + bool fShouldBan; + //! String name of this peer (debugging/logging purposes). + std::string name; + //! List of asynchronously-determined block rejections to notify this peer about. + std::vector rejects; + //! The best known block we know this peer has announced. + CBlockIndex *pindexBestKnownBlock; + //! The hash of the last unknown block this peer has announced. + uint256 hashLastUnknownBlock; + //! The last full block we both have. + CBlockIndex *pindexLastCommonBlock; + //! Whether we've started headers synchronization with this peer. + bool fSyncStarted; + //! Since when we're stalling block download progress (in microseconds), or 0. + int64_t nStallingSince; + list vBlocksInFlight; + int nBlocksInFlight; + int nBlocksInFlightValidHeaders; + //! Whether we consider this a preferred download peer. + bool fPreferredDownload; + + CNodeState() { + fCurrentlyConnected = false; + nMisbehavior = 0; + fShouldBan = false; + pindexBestKnownBlock = NULL; + hashLastUnknownBlock.SetNull(); + pindexLastCommonBlock = NULL; + fSyncStarted = false; + nStallingSince = 0; + nBlocksInFlight = 0; + nBlocksInFlightValidHeaders = 0; + fPreferredDownload = false; } + }; + + /** Map maintaining per-node state. Requires cs_main. */ + map mapNodeState; + + // Requires cs_main. + CNodeState *State(NodeId pnode) { + map::iterator it = mapNodeState.find(pnode); + if (it == mapNodeState.end()) + return NULL; + return &it->second; } -} - -/** Update tracking information about which blocks a peer is assumed to have. */ -void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) { - CNodeState *state = State(nodeid); - assert(state != NULL); - - /*ProcessBlockAvailability(nodeid); - - BlockMap::iterator it = mapBlockIndex.find(hash); - if (it != mapBlockIndex.end() && it->second->nChainWork > 0) { - // An actually better block was announced. - if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) - state->pindexBestKnownBlock = it->second; - } else*/ + + int GetHeight() { - // An unknown block was announced; just assume that the latest one is the best one. - state->hashLastUnknownBlock = hash; + LOCK(cs_main); + return chainActive.Height(); } -} - -/** Find the last common ancestor two blocks have. - * Both pa and pb must be non-NULL. */ -CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) { - if (pa->nHeight > pb->nHeight) { - pa = pa->GetAncestor(pb->nHeight); - } else if (pb->nHeight > pa->nHeight) { - pb = pb->GetAncestor(pa->nHeight); + + void UpdatePreferredDownload(CNode* node, CNodeState* state) + { + nPreferredDownload -= state->fPreferredDownload; + + // Whether this node should be marked as a preferred download node. + state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient; + + nPreferredDownload += state->fPreferredDownload; } - - while (pa != pb && pa && pb) { - pa = pa->pprev; - pb = pb->pprev; + + // Returns time at which to timeout block request (nTime in microseconds) + int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams) + { + return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore); } - - // Eventually all chain branches meet at the genesis block. - assert(pa == pb); - return pa; -} - -/** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has - * at most count entries. */ -void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector& vBlocks, NodeId& nodeStaller) { - if (count == 0) - return; - - vBlocks.reserve(vBlocks.size() + count); - CNodeState *state = State(nodeid); - assert(state != NULL); - - // Make sure pindexBestKnownBlock is up to date, we'll need it. - ProcessBlockAvailability(nodeid); - - if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) { - // This peer has nothing interesting. - return; + + void InitializeNode(NodeId nodeid, const CNode *pnode) { + LOCK(cs_main); + CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second; + state.name = pnode->addrName; + state.address = pnode->addr; } - - if (state->pindexLastCommonBlock == NULL) { - // Bootstrap quickly by guessing a parent of our best tip is the forking point. - // Guessing wrong in either direction is not a problem. - state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())]; - } - - // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor - // of its current tip anymore. Go back enough to fix that. - state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock); - if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) - return; - - std::vector vToFetch; - CBlockIndex *pindexWalk = state->pindexLastCommonBlock; - // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last - // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to - // download that next block if the window were 1 larger. - int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW; - int nMaxHeight = std::min(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1); - NodeId waitingfor = -1; - while (pindexWalk->nHeight < nMaxHeight) { - // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards - // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive - // as iterating over ~100 CBlockIndex* entries anyway. - int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max(count - vBlocks.size(), 128)); - vToFetch.resize(nToFetch); - pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch); - vToFetch[nToFetch - 1] = pindexWalk; - for (unsigned int i = nToFetch - 1; i > 0; i--) { - vToFetch[i - 1] = vToFetch[i]->pprev; + + void FinalizeNode(NodeId nodeid) { + LOCK(cs_main); + CNodeState *state = State(nodeid); + + if (state->fSyncStarted) + nSyncStarted--; + + if (state->nMisbehavior == 0 && state->fCurrentlyConnected) { + AddressCurrentlyConnected(state->address); } - - // Iterate over those blocks in vToFetch (in forward direction), adding the ones that - // are not yet downloaded and not in flight to vBlocks. In the meantime, update - // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's - // already part of our chain (and therefore don't need it even if pruned). - BOOST_FOREACH(CBlockIndex* pindex, vToFetch) { - if (!pindex->IsValid(BLOCK_VALID_TREE)) { - // We consider the chain that this peer is on invalid. - return; + + BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight) + mapBlocksInFlight.erase(entry.hash); + EraseOrphansFor(nodeid); + nPreferredDownload -= state->fPreferredDownload; + + mapNodeState.erase(nodeid); + } + + void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) + { + /* int expired = pool.Expire(GetTime() - age); + if (expired != 0) + LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired); + + std::vector vNoSpendsRemaining; + pool.TrimToSize(limit, &vNoSpendsRemaining); + BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining) + pcoinsTip->Uncache(removed);*/ + } + + // Requires cs_main. + // Returns a bool indicating whether we requested this block. + bool MarkBlockAsReceived(const uint256& hash) { + map::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); + if (itInFlight != mapBlocksInFlight.end()) { + CNodeState *state = State(itInFlight->second.first); + nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders; + state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders; + state->vBlocksInFlight.erase(itInFlight->second.second); + state->nBlocksInFlight--; + state->nStallingSince = 0; + mapBlocksInFlight.erase(itInFlight); + return true; + } + return false; + } + + // Requires cs_main. + void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) { + CNodeState *state = State(nodeid); + assert(state != NULL); + + // Make sure it's not listed somewhere already. + MarkBlockAsReceived(hash); + + int64_t nNow = GetTimeMicros(); + QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)}; + nQueuedValidatedHeaders += newentry.fValidatedHeaders; + list::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry); + state->nBlocksInFlight++; + state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders; + mapBlocksInFlight[hash] = std::make_pair(nodeid, it); + } + + /** Check whether the last unknown block a peer advertized is not yet known. */ + void ProcessBlockAvailability(NodeId nodeid) { + CNodeState *state = State(nodeid); + assert(state != NULL); + + if (!state->hashLastUnknownBlock.IsNull()) { + BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock); + if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) + { + if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) + state->pindexBestKnownBlock = itOld->second; + state->hashLastUnknownBlock.SetNull(); } - if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) { - if (pindex->nChainTx) - state->pindexLastCommonBlock = pindex; - } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) { - // The block is not already downloaded, and not yet in flight. - if (pindex->nHeight > nWindowEnd) { - // We reached the end of the window. - if (vBlocks.size() == 0 && waitingfor != nodeid) { - // We aren't able to fetch anything, but we would be if the download window was one larger. - nodeStaller = waitingfor; + } + } + + /** Update tracking information about which blocks a peer is assumed to have. */ + void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) { + CNodeState *state = State(nodeid); + assert(state != NULL); + + /*ProcessBlockAvailability(nodeid); + + BlockMap::iterator it = mapBlockIndex.find(hash); + if (it != mapBlockIndex.end() && it->second->nChainWork > 0) { + // An actually better block was announced. + if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) + state->pindexBestKnownBlock = it->second; + } else*/ + { + // An unknown block was announced; just assume that the latest one is the best one. + state->hashLastUnknownBlock = hash; + } + } + + /** Find the last common ancestor two blocks have. + * Both pa and pb must be non-NULL. */ + CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) { + if (pa->nHeight > pb->nHeight) { + pa = pa->GetAncestor(pb->nHeight); + } else if (pb->nHeight > pa->nHeight) { + pb = pb->GetAncestor(pa->nHeight); + } + + while (pa != pb && pa && pb) { + pa = pa->pprev; + pb = pb->pprev; + } + + // Eventually all chain branches meet at the genesis block. + assert(pa == pb); + return pa; + } + + /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has + * at most count entries. */ + void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector& vBlocks, NodeId& nodeStaller) { + if (count == 0) + return; + + vBlocks.reserve(vBlocks.size() + count); + CNodeState *state = State(nodeid); + assert(state != NULL); + + // Make sure pindexBestKnownBlock is up to date, we'll need it. + ProcessBlockAvailability(nodeid); + + if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) { + // This peer has nothing interesting. + return; + } + + if (state->pindexLastCommonBlock == NULL) { + // Bootstrap quickly by guessing a parent of our best tip is the forking point. + // Guessing wrong in either direction is not a problem. + state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())]; + } + + // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor + // of its current tip anymore. Go back enough to fix that. + state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock); + if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) + return; + + std::vector vToFetch; + CBlockIndex *pindexWalk = state->pindexLastCommonBlock; + // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last + // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to + // download that next block if the window were 1 larger. + int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW; + int nMaxHeight = std::min(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1); + NodeId waitingfor = -1; + while (pindexWalk->nHeight < nMaxHeight) { + // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards + // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive + // as iterating over ~100 CBlockIndex* entries anyway. + int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max(count - vBlocks.size(), 128)); + vToFetch.resize(nToFetch); + pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch); + vToFetch[nToFetch - 1] = pindexWalk; + for (unsigned int i = nToFetch - 1; i > 0; i--) { + vToFetch[i - 1] = vToFetch[i]->pprev; + } + + // Iterate over those blocks in vToFetch (in forward direction), adding the ones that + // are not yet downloaded and not in flight to vBlocks. In the meantime, update + // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's + // already part of our chain (and therefore don't need it even if pruned). + BOOST_FOREACH(CBlockIndex* pindex, vToFetch) { + if (!pindex->IsValid(BLOCK_VALID_TREE)) { + // We consider the chain that this peer is on invalid. + return; + } + if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) { + if (pindex->nChainTx) + state->pindexLastCommonBlock = pindex; + } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) { + // The block is not already downloaded, and not yet in flight. + if (pindex->nHeight > nWindowEnd) { + // We reached the end of the window. + if (vBlocks.size() == 0 && waitingfor != nodeid) { + // We aren't able to fetch anything, but we would be if the download window was one larger. + nodeStaller = waitingfor; + } + return; } - return; + vBlocks.push_back(pindex); + if (vBlocks.size() == count) { + return; + } + } else if (waitingfor == -1) { + // This is the first already-in-flight block. + waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first; } - vBlocks.push_back(pindex); - if (vBlocks.size() == count) { - return; - } - } else if (waitingfor == -1) { - // This is the first already-in-flight block. - waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first; } } } -} - + } // anon namespace bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) { @@ -590,7 +590,7 @@ bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(c uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; - + // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume @@ -604,12 +604,12 @@ bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(c LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString()); return false; } - + mapOrphanTransactions[hash].tx = tx; mapOrphanTransactions[hash].fromPeer = peer; BOOST_FOREACH(const CTxIn& txin, tx.vin) - mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash); - + mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash); + LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(), mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size()); return true; @@ -659,8 +659,8 @@ unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRE map::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); - EraseOrphanTx(it->first); - ++nEvicted; + EraseOrphanTx(it->first); + ++nEvicted; } return nEvicted; } @@ -669,7 +669,7 @@ unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRE bool IsStandardTx(const CTransaction& tx, string& reason, const int nHeight) { bool isOverwinter = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER); - + if (isOverwinter) { // Overwinter standard rules apply if (tx.nVersion > CTransaction::OVERWINTER_MAX_CURRENT_VERSION || tx.nVersion < CTransaction::OVERWINTER_MIN_CURRENT_VERSION) { @@ -683,7 +683,7 @@ bool IsStandardTx(const CTransaction& tx, string& reason, const int nHeight) return false; } } - + BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed @@ -702,7 +702,7 @@ bool IsStandardTx(const CTransaction& tx, string& reason, const int nHeight) return false; } } - + unsigned int v=0,nDataOut = 0; txnouttype whichType; BOOST_FOREACH(const CTxOut& txout, tx.vout) @@ -728,13 +728,13 @@ bool IsStandardTx(const CTransaction& tx, string& reason, const int nHeight) } v++; } - + // only one OP_RETURN txout is permitted if (nDataOut > 1) { reason = "multi-op-return"; return false; } - + return true; } @@ -771,7 +771,7 @@ bool IsExpiredTx(const CTransaction &tx, int nBlockHeight) bool CheckFinalTx(const CTransaction &tx, int flags) { AssertLockHeld(cs_main); - + // By convention a negative value for flags indicates that the // current network-enforced consensus rules should be used. In // a future soft-fork scenario that would mean checking which @@ -779,7 +779,7 @@ bool CheckFinalTx(const CTransaction &tx, int flags) // appropriate flags. At the present time no soft-forks are // scheduled, so no flags are set. flags = std::max(flags, 0); - + // CheckFinalTx() uses chainActive.Height()+1 to evaluate // nLockTime because when IsFinalTx() is called within // CBlock::AcceptBlock(), the height of the block *being* @@ -787,15 +787,15 @@ bool CheckFinalTx(const CTransaction &tx, int flags) // transaction can be part of the *next* block, we need to call // IsFinalTx() with one more than chainActive.Height(). const int nBlockHeight = chainActive.Height() + 1; - + // Timestamps on the other hand don't get any special treatment, // because we can't know what timestamp the next block will have, // and there aren't timestamp applications where it matters. // However this changes once median past time-locks are enforced: const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST) - ? chainActive.Tip()->GetMedianTimePast() - : GetAdjustedTime(); - + ? chainActive.Tip()->GetMedianTimePast() + : GetAdjustedTime(); + return IsFinalTx(tx, nBlockHeight, nBlockTime); } @@ -812,11 +812,11 @@ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, { if (tx.IsCoinBase()) return true; // Coinbases don't use vin normally - + for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]); - + vector > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: @@ -826,7 +826,7 @@ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; - + // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations @@ -836,7 +836,7 @@ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, vector > stack; if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), consensusBranchId)) return false; - + if (whichType == TX_SCRIPTHASH) { if (stack.empty()) @@ -859,11 +859,11 @@ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, return (sigops <= MAX_P2SH_SIGOPS); } } - + if (stack.size() != (unsigned int)nArgsExpected) return false; } - + return true; } @@ -885,7 +885,7 @@ unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& in { if (tx.IsCoinBase()) return 0; - + unsigned int nSigOps = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) { @@ -898,7 +898,7 @@ unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& in /** * Check a transaction contextually against a set of consensus rules valid at a given block height. - * + * * Notes: * 1. AcceptToMemoryPool calls CheckTransaction and this function. * 2. ProcessNewBlock calls AcceptBlock, which calls CheckBlock (which calls CheckTransaction) @@ -908,39 +908,39 @@ bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, { bool isOverwinter = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER); bool isSprout = !isOverwinter; - + // If Sprout rules apply, reject transactions which are intended for Overwinter and beyond if (isSprout && tx.fOverwintered) { return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwinter is not active yet"), REJECT_INVALID, "tx-overwinter-not-active"); } - + // If Overwinter rules apply: if (isOverwinter) { // Reject transactions with valid version but missing overwinter flag if (tx.nVersion >= OVERWINTER_MIN_TX_VERSION && !tx.fOverwintered) { return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwinter flag must be set"), - REJECT_INVALID, "tx-overwinter-flag-not-set"); + REJECT_INVALID, "tx-overwinter-flag-not-set"); } - + // Reject transactions with invalid version if (tx.fOverwintered && tx.nVersion > OVERWINTER_MAX_TX_VERSION ) { return state.DoS(100, error("CheckTransaction(): overwinter version too high"), - REJECT_INVALID, "bad-tx-overwinter-version-too-high"); + REJECT_INVALID, "bad-tx-overwinter-version-too-high"); } - + // Reject transactions intended for Sprout if (!tx.fOverwintered) { return state.DoS(dosLevel, error("ContextualCheckTransaction: overwinter is active"), - REJECT_INVALID, "tx-overwinter-active"); + REJECT_INVALID, "tx-overwinter-active"); } - + // Check that all transactions are unexpired if (IsExpiredTx(tx, nHeight)) { return state.DoS(dosLevel, error("ContextualCheckTransaction(): transaction is expired"), REJECT_INVALID, "tx-overwinter-expired"); } } - + if (!(tx.IsCoinBase() || tx.vjoinsplit.empty())) { auto consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus()); // Empty output script. @@ -950,11 +950,11 @@ bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL, 0, consensusBranchId); } catch (std::logic_error ex) { return state.DoS(100, error("CheckTransaction(): error computing signature hash"), - REJECT_INVALID, "error-computing-signature-hash"); + REJECT_INVALID, "error-computing-signature-hash"); } - + BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32); - + // We rely on libsodium to check that the signature is canonical. // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0 if (crypto_sign_verify_detached(&tx.joinSplitSig[0], @@ -962,7 +962,7 @@ bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, tx.joinSplitPubKey.begin() ) != 0) { return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"), - REJECT_INVALID, "bad-txns-invalid-joinsplit-signature"); + REJECT_INVALID, "bad-txns-invalid-joinsplit-signature"); } } return true; @@ -988,11 +988,11 @@ bool CheckTransaction(const CTransaction& tx, CValidationState &state, } } } - // Don't count coinbase transactions because mining skews the count + // Don't count coinbase transactions because mining skews the count if (!tx.IsCoinBase()) { transactionsValidated.increment(); } - + if (!CheckTransactionWithoutProofVerification(tx, state)) { return false; } else { @@ -1000,7 +1000,7 @@ bool CheckTransaction(const CTransaction& tx, CValidationState &state, BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) { if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) { return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"), - REJECT_INVALID, "bad-txns-joinsplit-verification-failed"); + REJECT_INVALID, "bad-txns-joinsplit-verification-failed"); } } return true; @@ -1010,7 +1010,7 @@ bool CheckTransaction(const CTransaction& tx, CValidationState &state, bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state) { // Basic checks that don't depend on any context - + /** * Previously: * 1. The consensus rule below was: @@ -1040,18 +1040,18 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio else if (tx.fOverwintered) { if (tx.nVersion < OVERWINTER_MIN_TX_VERSION) { return state.DoS(100, error("CheckTransaction(): overwinter version too low"), - REJECT_INVALID, "bad-tx-overwinter-version-too-low"); + REJECT_INVALID, "bad-tx-overwinter-version-too-low"); } if (tx.nVersionGroupId != OVERWINTER_VERSION_GROUP_ID) { return state.DoS(100, error("CheckTransaction(): unknown tx version group id"), - REJECT_INVALID, "bad-tx-version-group-id"); + REJECT_INVALID, "bad-tx-version-group-id"); } if (tx.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD) { return state.DoS(100, error("CheckTransaction(): expiry height is too high"), - REJECT_INVALID, "bad-tx-expiry-height-too-high"); + REJECT_INVALID, "bad-tx-expiry-height-too-high"); } } - + // Transactions can contain empty `vin` and `vout` so long as // `vjoinsplit` is non-empty. if (tx.vin.empty() && tx.vjoinsplit.empty()) @@ -1060,13 +1060,13 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio if (tx.vout.empty() && tx.vjoinsplit.empty()) return state.DoS(10, error("CheckTransaction(): vout empty"), REJECT_INVALID, "bad-txns-vout-empty"); - + // Size limits BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE) return state.DoS(100, error("CheckTransaction(): size limits failed"), REJECT_INVALID, "bad-txns-oversize"); - + // Check for negative or overflow output values CAmount nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, tx.vout) @@ -1084,7 +1084,7 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio return state.DoS(100, error("CheckTransaction(): txout total out of range"), REJECT_INVALID, "bad-txns-txouttotal-toolarge"); } - + // Ensure that joinsplit values are well-formed BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit) { @@ -1092,34 +1092,34 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"), REJECT_INVALID, "bad-txns-vpub_old-negative"); } - + if (joinsplit.vpub_new < 0) { return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"), REJECT_INVALID, "bad-txns-vpub_new-negative"); } - + if (joinsplit.vpub_old > MAX_MONEY) { return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"), REJECT_INVALID, "bad-txns-vpub_old-toolarge"); } - + if (joinsplit.vpub_new > MAX_MONEY) { return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"), REJECT_INVALID, "bad-txns-vpub_new-toolarge"); } - + if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) { return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"), REJECT_INVALID, "bad-txns-vpubs-both-nonzero"); } - + nValueOut += joinsplit.vpub_old; if (!MoneyRange(nValueOut)) { return state.DoS(100, error("CheckTransaction(): txout total out of range"), REJECT_INVALID, "bad-txns-txouttotal-toolarge"); } } - + // Ensure input values do not exceed MAX_MONEY // We have not resolved the txin values at this stage, // but we do know what the joinsplits claim to add @@ -1129,15 +1129,15 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio for (std::vector::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it) { nValueIn += it->vpub_new; - + if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) { return state.DoS(100, error("CheckTransaction(): txin total out of range"), REJECT_INVALID, "bad-txns-txintotal-toolarge"); } } } - - + + // Check for duplicate inputs set vInOutPoints; BOOST_FOREACH(const CTxIn& txin, tx.vin) @@ -1147,7 +1147,7 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio REJECT_INVALID, "bad-txns-inputs-duplicate"); vInOutPoints.insert(txin.prevout); } - + // Check for duplicate joinsplit nullifiers in this transaction set vJoinSplitNullifiers; BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit) @@ -1156,19 +1156,19 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio { if (vJoinSplitNullifiers.count(nf)) return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"), - REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate"); - + REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate"); + vJoinSplitNullifiers.insert(nf); } } - + if (tx.IsCoinBase()) { // There should be no joinsplits in a coinbase transaction if (tx.vjoinsplit.size() > 0) return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"), REJECT_INVALID, "bad-cb-has-joinsplits"); - + if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100) return state.DoS(100, error("CheckTransaction(): coinbase script size"), REJECT_INVALID, "bad-cb-length"); @@ -1176,11 +1176,11 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio else { BOOST_FOREACH(const CTxIn& txin, tx.vin) - if (txin.prevout.IsNull()) - return state.DoS(10, error("CheckTransaction(): prevout is null"), - REJECT_INVALID, "bad-txns-prevout-null"); + if (txin.prevout.IsNull()) + return state.DoS(10, error("CheckTransaction(): prevout is null"), + REJECT_INVALID, "bad-txns-prevout-null"); } - + return true; } @@ -1196,9 +1196,9 @@ CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowF if (dPriorityDelta > 0 || nFeeDelta > 0) return 0; } - + CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes); - + if (fAllowFree) { // There is a free transaction area in blocks created by most miners, @@ -1208,7 +1208,7 @@ CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowF if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000)) nMinFee = 0; } - + if (!MoneyRange(nMinFee)) nMinFee = MAX_MONEY; return nMinFee; @@ -1309,7 +1309,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa } } } - + { CCoinsView dummy; CCoinsViewCache view(&dummy); @@ -1380,7 +1380,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa fprintf(stderr,"accept failure.4\n"); 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"); } - + CAmount nValueOut = tx.GetValueOut(); CAmount nFees = nValueIn-nValueOut; double dPriority = view.GetPriority(tx, chainActive.Height()); @@ -1494,14 +1494,14 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow) { CBlockIndex *pindexSlow = NULL; - + LOCK(cs_main); - + if (mempool.lookup(hash, txOut)) { return true; } - + if (fTxIndex) { CDiskTxPos postx; if (pblocktree->ReadTxIndex(hash, postx)) { @@ -1522,7 +1522,7 @@ bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock return true; } } - + if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it int nHeight = -1; { @@ -1534,7 +1534,7 @@ bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock if (nHeight > 0) pindexSlow = chainActive[nHeight]; } - + if (pindexSlow) { CBlock block; if (ReadBlockFromDisk(block, pindexSlow)) { @@ -1547,23 +1547,23 @@ bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock } } } - + return false; } /*char *komodo_getspendscript(uint256 hash,int32_t n) -{ - CTransaction tx; uint256 hashBlock; - if ( !GetTransaction(hash,tx,hashBlock,true) ) - { - printf("null GetTransaction\n"); - return(0); - } - if ( n >= 0 && n < tx.vout.size() ) - return((char *)tx.vout[n].scriptPubKey.ToString().c_str()); - else printf("getspendscript illegal n.%d\n",n); - return(0); -}*/ + { + CTransaction tx; uint256 hashBlock; + if ( !GetTransaction(hash,tx,hashBlock,true) ) + { + printf("null GetTransaction\n"); + return(0); + } + if ( n >= 0 && n < tx.vout.size() ) + return((char *)tx.vout[n].scriptPubKey.ToString().c_str()); + else printf("getspendscript illegal n.%d\n",n); + return(0); + }*/ ////////////////////////////////////////////////////////////////////////////// @@ -1577,18 +1577,18 @@ bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::M CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("WriteBlockToDisk: OpenBlockFile failed"); - + // Write index header unsigned int nSize = fileout.GetSerializeSize(block); fileout << FLATDATA(messageStart) << nSize; - + // Write block long fileOutPos = ftell(fileout.Get()); if (fileOutPos < 0) return error("WriteBlockToDisk: ftell failed"); pos.nPos = (unsigned int)fileOutPos; fileout << block; - + return true; } @@ -1596,7 +1596,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) { uint8_t pubkey33[33]; block.SetNull(); - + // Open history file to read CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION); if (filein.IsNull()) @@ -1604,7 +1604,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) //fprintf(stderr,"readblockfromdisk err A\n"); return false;//error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString()); } - + // Read block try { filein >> block; @@ -1634,7 +1634,7 @@ bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex) return false; if (block.GetHash() != pindex->GetBlockHash()) return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s", - pindex->ToString(), pindex->GetBlockPos().ToString()); + pindex->ToString(), pindex->GetBlockPos().ToString()); return true; } @@ -1699,27 +1699,27 @@ CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams) return(nSubsidy); } else return(0); } -/* - // Mining slow start - // The subsidy is ramped up linearly, skipping the middle payout of - // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start. - if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) { - nSubsidy /= consensusParams.nSubsidySlowStartInterval; - nSubsidy *= nHeight; - return nSubsidy; - } else if (nHeight < consensusParams.nSubsidySlowStartInterval) { - nSubsidy /= consensusParams.nSubsidySlowStartInterval; - nSubsidy *= (nHeight+1); - return nSubsidy; - } - - assert(nHeight > consensusParams.SubsidySlowStartShift()); - int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;*/ + /* + // Mining slow start + // The subsidy is ramped up linearly, skipping the middle payout of + // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start. + if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) { + nSubsidy /= consensusParams.nSubsidySlowStartInterval; + nSubsidy *= nHeight; + return nSubsidy; + } else if (nHeight < consensusParams.nSubsidySlowStartInterval) { + nSubsidy /= consensusParams.nSubsidySlowStartInterval; + nSubsidy *= (nHeight+1); + return nSubsidy; + } + + assert(nHeight > consensusParams.SubsidySlowStartShift()); + int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;*/ // Force block reward to zero when right shift is undefined. //int halvings = nHeight / consensusParams.nSubsidyHalvingInterval; //if (halvings >= 64) // return 0; - + // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years. //nSubsidy >>= halvings; return nSubsidy; @@ -1751,8 +1751,8 @@ bool IsInitialBlockDownload() else if ( pindexBestHeader != 0 && pindexBestHeader->nHeight > ptr->nHeight ) ptr = pindexBestHeader; //if ( ASSETCHAINS_SYMBOL[0] == 0 ) - state = ((chainActive.Height() < ptr->nHeight - 24*60) || - ptr->GetBlockTime() < (GetTime() - chainParams.MaxTipAge())); + state = ((chainActive.Height() < ptr->nHeight - 24*60) || + ptr->GetBlockTime() < (GetTime() - chainParams.MaxTipAge())); //else state = (chainActive.Height() < ptr->nHeight - 24*60); //fprintf(stderr,"state.%d ht.%d vs %d, t.%u %u\n",state,(int32_t)chainActive.Height(),(uint32_t)ptr->nHeight,(int32_t)ptr->GetBlockTime(),(uint32_t)(GetTime() - chainParams.MaxTipAge())); if (!state) @@ -1773,25 +1773,25 @@ void CheckForkWarningConditions() // (we assume we don't get stuck on a fork before the last checkpoint) if (IsInitialBlockDownload()) return; - + // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it) // of our head, drop it if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288) pindexBestForkTip = NULL; - + if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6))) { if (!fLargeWorkForkFound && pindexBestForkBase) { std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") + - pindexBestForkBase->phashBlock->ToString() + std::string("'"); + pindexBestForkBase->phashBlock->ToString() + std::string("'"); CAlert::Notify(warning, true); } if (pindexBestForkTip && pindexBestForkBase) { LogPrintf("%s: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n", __func__, - pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(), - pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString()); + pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(), + pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString()); fLargeWorkForkFound = true; } else @@ -1823,7 +1823,7 @@ void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip) break; pfork = pfork->pprev; } - + // We define a condition where we should warn the user about as a fork of at least 7 blocks // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network @@ -1832,13 +1832,13 @@ void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip) // We define it this way because it allows us to only store the highest fork tip (+ base) which meets // the 7-block condition and from this always have the most-likely-to-cause-warning fork if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) && - pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) && - chainActive.Height() - pindexNewForkTip->nHeight < 72) + pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) && + chainActive.Height() - pindexNewForkTip->nHeight < 72) { pindexBestForkTip = pindexNewForkTip; pindexBestForkBase = pfork; } - + CheckForkWarningConditions(); } @@ -1847,11 +1847,11 @@ void Misbehaving(NodeId pnode, int howmuch) { if (howmuch == 0) return; - + CNodeState *state = State(pnode); if (state == NULL) return; - + state->nMisbehavior += howmuch; int banscore = GetArg("-banscore", 101); if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore) @@ -1866,16 +1866,16 @@ void static InvalidChainFound(CBlockIndex* pindexNew) { if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork) pindexBestInvalid = pindexNew; - + LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__, - pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, - log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", - pindexNew->GetBlockTime())); + pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, + log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", + pindexNew->GetBlockTime())); CBlockIndex *tip = chainActive.Tip(); assert (tip); LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__, - tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0), - DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime())); + tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0), + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime())); CheckForkWarningConditions(); } @@ -1906,7 +1906,7 @@ void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txund BOOST_FOREACH(const CTxIn &txin, tx.vin) { CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash); unsigned nPos = txin.prevout.n; - + if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull()) assert(false); // mark an outpoint spent, and construct undo information @@ -1950,17 +1950,17 @@ int GetSpendHeight(const CCoinsViewCache& inputs) } namespace Consensus { -bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams) -{ + bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams) + { // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!inputs.HaveInputs(tx)) return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString())); - + // are the JoinSplit's requirements met? if (!inputs.HaveJoinSplitRequirements(tx)) return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString())); - + CAmount nValueIn = 0; CAmount nFees = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) @@ -1968,26 +1968,26 @@ bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoins const COutPoint &prevout = tx.vin[i].prevout; const CCoins *coins = inputs.AccessCoins(prevout.hash); assert(coins); - + if (coins->IsCoinBase()) { // Ensure that coinbases are matured if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) { return state.Invalid( - error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight), - REJECT_INVALID, "bad-txns-premature-spend-of-coinbase"); + error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight), + REJECT_INVALID, "bad-txns-premature-spend-of-coinbase"); } - + // Ensure that coinbases cannot be spent to transparent outputs // Disabled on regtest if (fCoinbaseEnforcedProtectionEnabled && consensusParams.fCoinbaseMustBeProtected && !tx.vout.empty()) { return state.Invalid( - error("CheckInputs(): tried to spend coinbase with transparent outputs"), - REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs"); + error("CheckInputs(): tried to spend coinbase with transparent outputs"), + REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs"); } } - + // Check for negative or overflow input values nValueIn += coins->vout[prevout.n].nValue; #ifdef KOMODO_ENABLE_INTEREST @@ -1998,7 +1998,7 @@ bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoins int64_t interest; int32_t txheight; uint32_t locktime; if ( (interest= komodo_accrued_interest(&txheight,&locktime,prevout.hash,prevout.n,0,coins->vout[prevout.n].nValue,(int32_t)nSpendHeight-1)) != 0 ) { -//fprintf(stderr,"checkResult %.8f += val %.8f interest %.8f ht.%d lock.%u tip.%u\n",(double)nValueIn/COIN,(double)coins->vout[prevout.n].nValue/COIN,(double)interest/COIN,txheight,locktime,chainActive.Tip()->nTime); + //fprintf(stderr,"checkResult %.8f += val %.8f interest %.8f ht.%d lock.%u tip.%u\n",(double)nValueIn/COIN,(double)coins->vout[prevout.n].nValue/COIN,(double)interest/COIN,txheight,locktime,chainActive.Tip()->nTime); nValueIn += interest; } } @@ -2007,14 +2007,14 @@ bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoins if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return state.DoS(100, error("CheckInputs(): txin values out of range"), REJECT_INVALID, "bad-txns-inputvalues-outofrange"); - + } - + nValueIn += tx.GetJoinSplitValueIn(); if (!MoneyRange(nValueIn)) return state.DoS(100, error("CheckInputs(): vpub_old values out of range"), REJECT_INVALID, "bad-txns-inputvalues-outofrange"); - + if (nValueIn < tx.GetValueOut()) { fprintf(stderr,"spentheight.%d valuein %s vs %s error\n",nSpendHeight,FormatMoney(nValueIn).c_str(), FormatMoney(tx.GetValueOut()).c_str()); @@ -2030,35 +2030,35 @@ bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoins if (!MoneyRange(nFees)) return state.DoS(100, error("CheckInputs(): nFees out of range"), REJECT_INVALID, "bad-txns-fee-outofrange"); - return true; -} + return true; + } }// namespace Consensus bool ContextualCheckInputs( - const CTransaction& tx, - CValidationState &state, - const CCoinsViewCache &inputs, - bool fScriptChecks, - unsigned int flags, - bool cacheStore, - PrecomputedTransactionData& txdata, - const Consensus::Params& consensusParams, - uint32_t consensusBranchId, - std::vector *pvChecks) + const CTransaction& tx, + CValidationState &state, + const CCoinsViewCache &inputs, + bool fScriptChecks, + unsigned int flags, + bool cacheStore, + PrecomputedTransactionData& txdata, + const Consensus::Params& consensusParams, + uint32_t consensusBranchId, + std::vector *pvChecks) { if (!tx.IsCoinBase()) { if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams)) { return false; } - + if (pvChecks) pvChecks->reserve(tx.vin.size()); - + // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. - + // Skip ECDSA signature verification when connecting blocks // before the last block chain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. @@ -2067,7 +2067,7 @@ bool ContextualCheckInputs( const COutPoint &prevout = tx.vin[i].prevout; const CCoins* coins = inputs.AccessCoins(prevout.hash); assert(coins); - + // Verify signature CScriptCheck check(*coins, tx, i, flags, cacheStore, consensusBranchId, &txdata); if (pvChecks) { @@ -2082,7 +2082,7 @@ bool ContextualCheckInputs( // avoid splitting the network between upgraded and // non-upgraded nodes. CScriptCheck check2(*coins, tx, i, - flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, consensusBranchId, &txdata); + flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, consensusBranchId, &txdata); if (check2()) return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError()))); } @@ -2098,123 +2098,123 @@ bool ContextualCheckInputs( } } } - + return true; } /*bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, const Consensus::Params& consensusParams, std::vector *pvChecks) -{ - if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) { - fprintf(stderr,"ContextualCheckInputs failure.0\n"); - return false; - } - - if (!tx.IsCoinBase()) - { - // While checking, GetBestBlock() refers to the parent block. - // This is also true for mempool checks. - CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second; - int nSpendHeight = pindexPrev->nHeight + 1; - for (unsigned int i = 0; i < tx.vin.size(); i++) - { - const COutPoint &prevout = tx.vin[i].prevout; - const CCoins *coins = inputs.AccessCoins(prevout.hash); - // Assertion is okay because NonContextualCheckInputs ensures the inputs - // are available. - assert(coins); - - // If prev is coinbase, check that it's matured - if (coins->IsCoinBase()) { - if ( ASSETCHAINS_SYMBOL[0] == 0 ) - COINBASE_MATURITY = _COINBASE_MATURITY; - if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) { - fprintf(stderr,"ContextualCheckInputs failure.1 i.%d of %d\n",i,(int32_t)tx.vin.size()); - - return state.Invalid( - error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),REJECT_INVALID, "bad-txns-premature-spend-of-coinbase"); - } - } - } - } - - return true; -}*/ + { + if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) { + fprintf(stderr,"ContextualCheckInputs failure.0\n"); + return false; + } + + if (!tx.IsCoinBase()) + { + // While checking, GetBestBlock() refers to the parent block. + // This is also true for mempool checks. + CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second; + int nSpendHeight = pindexPrev->nHeight + 1; + for (unsigned int i = 0; i < tx.vin.size(); i++) + { + const COutPoint &prevout = tx.vin[i].prevout; + const CCoins *coins = inputs.AccessCoins(prevout.hash); + // Assertion is okay because NonContextualCheckInputs ensures the inputs + // are available. + assert(coins); + + // If prev is coinbase, check that it's matured + if (coins->IsCoinBase()) { + if ( ASSETCHAINS_SYMBOL[0] == 0 ) + COINBASE_MATURITY = _COINBASE_MATURITY; + if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) { + fprintf(stderr,"ContextualCheckInputs failure.1 i.%d of %d\n",i,(int32_t)tx.vin.size()); + + return state.Invalid( + error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),REJECT_INVALID, "bad-txns-premature-spend-of-coinbase"); + } + } + } + } + + return true; + }*/ namespace { - -bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart) -{ - // Open history file to append - CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION); - if (fileout.IsNull()) - return error("%s: OpenUndoFile failed", __func__); - - // Write index header - unsigned int nSize = fileout.GetSerializeSize(blockundo); - fileout << FLATDATA(messageStart) << nSize; - - // Write undo data - long fileOutPos = ftell(fileout.Get()); - if (fileOutPos < 0) - return error("%s: ftell failed", __func__); - pos.nPos = (unsigned int)fileOutPos; - fileout << blockundo; - - // calculate & write checksum - CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); - hasher << hashBlock; - hasher << blockundo; - fileout << hasher.GetHash(); - - return true; -} - -bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock) -{ - // Open history file to read - CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION); - if (filein.IsNull()) - return error("%s: OpenBlockFile failed", __func__); - - // Read block - uint256 hashChecksum; - try { - filein >> blockundo; - filein >> hashChecksum; + + bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart) + { + // Open history file to append + CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION); + if (fileout.IsNull()) + return error("%s: OpenUndoFile failed", __func__); + + // Write index header + unsigned int nSize = fileout.GetSerializeSize(blockundo); + fileout << FLATDATA(messageStart) << nSize; + + // Write undo data + long fileOutPos = ftell(fileout.Get()); + if (fileOutPos < 0) + return error("%s: ftell failed", __func__); + pos.nPos = (unsigned int)fileOutPos; + fileout << blockundo; + + // calculate & write checksum + CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); + hasher << hashBlock; + hasher << blockundo; + fileout << hasher.GetHash(); + + return true; } - catch (const std::exception& e) { - return error("%s: Deserialize or I/O error - %s", __func__, e.what()); + + bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock) + { + // Open history file to read + CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION); + if (filein.IsNull()) + return error("%s: OpenBlockFile failed", __func__); + + // Read block + uint256 hashChecksum; + try { + filein >> blockundo; + filein >> hashChecksum; + } + catch (const std::exception& e) { + return error("%s: Deserialize or I/O error - %s", __func__, e.what()); + } + + // Verify checksum + CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); + hasher << hashBlock; + hasher << blockundo; + if (hashChecksum != hasher.GetHash()) + return error("%s: Checksum mismatch", __func__); + + return true; } - - // Verify checksum - CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); - hasher << hashBlock; - hasher << blockundo; - if (hashChecksum != hasher.GetHash()) - return error("%s: Checksum mismatch", __func__); - - return true; -} - -/** Abort with a message */ -bool AbortNode(const std::string& strMessage, const std::string& userMessage="") -{ - strMiscWarning = strMessage; - LogPrintf("*** %s\n", strMessage); - uiInterface.ThreadSafeMessageBox( - userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage, - "", CClientUIInterface::MSG_ERROR); - StartShutdown(); - return false; -} - -bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="") -{ - AbortNode(strMessage, userMessage); - return state.Error(strMessage); -} - + + /** Abort with a message */ + bool AbortNode(const std::string& strMessage, const std::string& userMessage="") + { + strMiscWarning = strMessage; + LogPrintf("*** %s\n", strMessage); + uiInterface.ThreadSafeMessageBox( + userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage, + "", CClientUIInterface::MSG_ERROR); + StartShutdown(); + return false; + } + + bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="") + { + AbortNode(strMessage, userMessage); + return state.Error(strMessage); + } + } // anon namespace /** @@ -2227,7 +2227,7 @@ bool AbortNode(CValidationState& state, const std::string& strMessage, const std static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out) { bool fClean = true; - + CCoinsModifier coins = view.ModifyCoins(out.hash); if (undo.nHeight != 0) { // undo data contains height: this is the last output of the prevout tx being spent @@ -2246,17 +2246,17 @@ static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const CO if (coins->vout.size() < out.n+1) coins->vout.resize(out.n+1); coins->vout[out.n] = undo.txout; - + return fClean; } bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean) { assert(pindex->GetBlockHash() == view.GetBestBlock()); - + if (pfClean) *pfClean = false; - + bool fClean = true; komodo_disconnect(pindex,block); CBlockUndo blockUndo; @@ -2265,41 +2265,41 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex return error("DisconnectBlock(): no undo data available"); if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) return error("DisconnectBlock(): failure reading undo data"); - + if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) return error("DisconnectBlock(): block and undo data inconsistent"); - + // undo transactions in reverse order for (int i = block.vtx.size() - 1; i >= 0; i--) { const CTransaction &tx = block.vtx[i]; uint256 hash = tx.GetHash(); - + // Check that all outputs are available and match the outputs in the block itself // exactly. { - CCoinsModifier outs = view.ModifyCoins(hash); - outs->ClearUnspendable(); - - CCoins outsBlock(tx, pindex->nHeight); - // The CCoins serialization does not serialize negative numbers. - // No network rules currently depend on the version here, so an inconsistency is harmless - // but it must be corrected before txout nversion ever influences a network rule. - if (outsBlock.nVersion < 0) - outs->nVersion = outsBlock.nVersion; - if (*outs != outsBlock) - fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted"); - - // remove outputs - outs->Clear(); + CCoinsModifier outs = view.ModifyCoins(hash); + outs->ClearUnspendable(); + + CCoins outsBlock(tx, pindex->nHeight); + // The CCoins serialization does not serialize negative numbers. + // No network rules currently depend on the version here, so an inconsistency is harmless + // but it must be corrected before txout nversion ever influences a network rule. + if (outsBlock.nVersion < 0) + outs->nVersion = outsBlock.nVersion; + if (*outs != outsBlock) + fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted"); + + // remove outputs + outs->Clear(); } - + // unspend nullifiers BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) { BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) { view.SetNullifier(nf, false); } } - + // restore inputs if (i > 0) { // not coinbases const CTxUndo &txundo = blockUndo.vtxundo[i-1]; @@ -2313,27 +2313,27 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex } } } - + // set the old best anchor back view.PopAnchor(blockUndo.old_tree_root); - + // move best block pointer to prevout block view.SetBestBlock(pindex->pprev->GetBlockHash()); - + if (pfClean) { *pfClean = fClean; return true; } - + return fClean; } void static FlushBlockFile(bool fFinalize = false) { LOCK(cs_LastBlockFile); - + CDiskBlockPos posOld(nLastBlockFile, 0); - + FILE *fileOld = OpenBlockFile(posOld); if (fileOld) { if (fFinalize) @@ -2341,7 +2341,7 @@ void static FlushBlockFile(bool fFinalize = false) FileCommit(fileOld); fclose(fileOld); } - + fileOld = OpenUndoFile(posOld); if (fileOld) { if (fFinalize) @@ -2369,20 +2369,20 @@ void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const int64_t nPowTargetSpacing) { if (bestHeader == NULL || initialDownloadCheck()) return; - + static int64_t lastAlertTime = 0; int64_t now = GetAdjustedTime(); if (lastAlertTime > now-60*60*24) return; // Alert at most once per day - + const int SPAN_HOURS=4; const int SPAN_SECONDS=SPAN_HOURS*60*60; int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing; - + boost::math::poisson_distribution poisson(BLOCKS_EXPECTED); - + std::string strWarning; int64_t startTime = GetAdjustedTime()-SPAN_SECONDS; - + LOCK(cs); const CBlockIndex* i = bestHeader; int nBlocks = 0; @@ -2391,17 +2391,17 @@ void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const i = i->pprev; if (i == NULL) return; // Ran out of chain, we must not be fully synced } - + // How likely is it to find that many by chance? double p = boost::math::pdf(poisson, nBlocks); - + LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS); LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p); - + // Aim for one false-positive about every fifty years of normal running: const int FIFTY_YEARS = 50*365*24*60*60; double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS); - + if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED) { // Many fewer blocks than expected: alert! @@ -2431,7 +2431,7 @@ static int64_t nTimeTotal = 0; bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck) { const CChainParams& chainparams = Params(); - + //fprintf(stderr,"connectblock ht.%d\n",(int32_t)pindex->nHeight); AssertLockHeld(cs_main); bool fExpensiveChecks = true; @@ -2444,15 +2444,15 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin } auto verifier = libzcash::ProofVerifier::Strict(); auto disabledVerifier = libzcash::ProofVerifier::Disabled(); - + // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in if (!CheckBlock(pindex->nHeight,pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck)) return false; - + // verify that the view's current state corresponds to the previous block uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash(); assert(hashPrevBlock == view.GetBestBlock()); - + // Special case for the genesis block, skipping connection of its transactions // (its coinbase is unspendable) if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) { @@ -2466,7 +2466,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin } return true; } - + bool fScriptChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints())); //if ( KOMODO_TESTNET_EXPIRATION != 0 && pindex->nHeight > KOMODO_TESTNET_EXPIRATION ) // "testnet" // return(false); @@ -2478,15 +2478,15 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"), REJECT_INVALID, "bad-txns-BIP30"); } - + unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY; - + // DERSIG (BIP66) is also always enforced, but does not have a flag. - + CBlockUndo blockundo; - + CCheckQueueControl control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL); - + int64_t nTimeStart = GetTimeMicros(); CAmount nFees = 0; int nInputs = 0; @@ -2496,7 +2496,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin std::vector > vPos; vPos.reserve(block.vtx.size()); blockundo.vtxundo.reserve(block.vtx.size() - 1); - + // Construct the incremental merkle tree at the current // block position, auto old_tree_root = view.GetBestAnchor(); @@ -2508,16 +2508,16 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin // This should never fail: we should always be able to get the root // that is on the tip of our chain assert(view.GetAnchorAt(old_tree_root, tree)); - + { // Consistency check: the root of the tree we're given should // match what we asked for. assert(tree.root() == old_tree_root); } - + // Grab the consensus branch ID for the block's height auto consensusBranchId = CurrentEpochBranchId(pindex->nHeight, Params().GetConsensus()); - + std::vector txdata; txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated for (unsigned int i = 0; i < block.vtx.size(); i++) @@ -2528,18 +2528,18 @@ 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); + //fprintf(stderr,"ht.%d vout0 t%u\n",pindex->nHeight,tx.nLockTime); if (!tx.IsCoinBase()) { if (!view.HaveInputs(tx)) return state.DoS(100, error("ConnectBlock(): inputs missing/spent"), REJECT_INVALID, "bad-txns-inputs-missingorspent"); - + // are the JoinSplit's requirements met? if (!view.HaveJoinSplitRequirements(tx)) return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"), REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met"); - + // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. @@ -2548,14 +2548,14 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin return state.DoS(100, error("ConnectBlock(): too many sigops"), REJECT_INVALID, "bad-blk-sigops"); } - + txdata.emplace_back(tx); - + if (!tx.IsCoinBase()) { nFees += view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime) - tx.GetValueOut(); sum += interest; - + std::vector vChecks; if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, txdata[i], chainparams.GetConsensus(), consensusBranchId, nScriptCheckThreads ? &vChecks : NULL)) return false; @@ -2568,28 +2568,28 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin blockundo.vtxundo.push_back(CTxUndo()); } UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight); - + BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) { BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) { // Insert the note commitments into our temporary tree. - + tree.append(note_commitment); } } - + vPos.push_back(std::make_pair(tx.GetHash(), pos)); pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); } - + view.PushAnchor(tree); if (!fJustCheck) { pindex->hashAnchorEnd = tree.root(); } blockundo.old_tree_root = old_tree_root; - + int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart; LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs-1), nTimeConnect * 0.000001); - + CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus()) + sum; if ( ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && block.vtx[0].vout.size() > 1 ) { @@ -2606,9 +2606,9 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin if ( ASSETCHAINS_SYMBOL[0] != 0 || pindex->nHeight >= KOMODO_NOTARIES_HEIGHT1 || block.vtx[0].vout[0].nValue > blockReward ) { return state.DoS(100, - error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)", - block.vtx[0].GetValueOut(), blockReward), - REJECT_INVALID, "bad-cb-amount"); + error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)", + block.vtx[0].GetValueOut(), blockReward), + REJECT_INVALID, "bad-cb-amount"); } else if ( NOTARY_PUBKEY33[0] != 0 ) fprintf(stderr,"allow nHeight.%d coinbase %.8f vs %.8f interest %.8f\n",(int32_t)pindex->nHeight,dstr(block.vtx[0].GetValueOut()),dstr(blockReward),dstr(sum)); } @@ -2616,10 +2616,10 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin return state.DoS(100, false); int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart; LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs-1), nTimeVerify * 0.000001); - + if (fJustCheck) return true; - + // Write undo information to disk if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS)) { @@ -2629,42 +2629,42 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin return error("ConnectBlock(): FindUndoPos failed"); if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart())) return AbortNode(state, "Failed to write undo data"); - + // update nUndoPos in block index pindex->nUndoPos = pos.nPos; pindex->nStatus |= BLOCK_HAVE_UNDO; } - + // Now that all consensus rules have been validated, set nCachedBranchId. // Move this if BLOCK_VALID_CONSENSUS is ever altered. static_assert(BLOCK_VALID_CONSENSUS == BLOCK_VALID_SCRIPTS, - "nCachedBranchId must be set after all consensus rules have been validated."); + "nCachedBranchId must be set after all consensus rules have been validated."); if (IsActivationHeightForAnyUpgrade(pindex->nHeight, Params().GetConsensus())) { pindex->nStatus |= BLOCK_ACTIVATES_UPGRADE; pindex->nCachedBranchId = CurrentEpochBranchId(pindex->nHeight, chainparams.GetConsensus()); } else if (pindex->pprev) { pindex->nCachedBranchId = pindex->pprev->nCachedBranchId; } - + pindex->RaiseValidity(BLOCK_VALID_SCRIPTS); setDirtyBlockIndex.insert(pindex); } - + if (fTxIndex) if (!pblocktree->WriteTxIndex(vPos)) return AbortNode(state, "Failed to write transaction index"); - + // add this block to the view's block chain view.SetBestBlock(pindex->GetBlockHash()); - + int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2; LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001); - + // Watch for changes to the previous coinbase transaction. static uint256 hashPrevBestCoinBase; GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = block.vtx[0].GetHash(); - + int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3; LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001); @@ -2694,88 +2694,88 @@ bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) { std::set setFilesToPrune; bool fFlushForPrune = false; try { - if (fPruneMode && fCheckForPruning && !fReindex) { - FindFilesToPrune(setFilesToPrune); - fCheckForPruning = false; - if (!setFilesToPrune.empty()) { - fFlushForPrune = true; - if (!fHavePruned) { - pblocktree->WriteFlag("prunedblockfiles", true); - fHavePruned = true; + if (fPruneMode && fCheckForPruning && !fReindex) { + FindFilesToPrune(setFilesToPrune); + fCheckForPruning = false; + if (!setFilesToPrune.empty()) { + fFlushForPrune = true; + if (!fHavePruned) { + pblocktree->WriteFlag("prunedblockfiles", true); + fHavePruned = true; + } } } - } - int64_t nNow = GetTimeMicros(); - // Avoid writing/flushing immediately after startup. - if (nLastWrite == 0) { - nLastWrite = nNow; - } - if (nLastFlush == 0) { - nLastFlush = nNow; - } - if (nLastSetChain == 0) { - nLastSetChain = nNow; - } - size_t cacheSize = pcoinsTip->DynamicMemoryUsage(); - // The cache is large and close to the limit, but we have time now (not in the middle of a block processing). - bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage; - // The cache is over the limit, we have to write now. - bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage; - // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash. - bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000; - // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage. - bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000; - // Combine all conditions that result in a full cache flush. - bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune; - // Write blocks and block index to disk. - if (fDoFullFlush || fPeriodicWrite) { - // Depend on nMinDiskSpace to ensure we can write block index - if (!CheckDiskSpace(0)) - return state.Error("out of disk space"); - // First make sure all block and undo data is flushed to disk. - FlushBlockFile(); - // Then update all block file information (which may refer to block and undo files). - { - std::vector > vFiles; - vFiles.reserve(setDirtyFileInfo.size()); - for (set::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) { - vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it])); - setDirtyFileInfo.erase(it++); - } - std::vector vBlocks; - vBlocks.reserve(setDirtyBlockIndex.size()); - for (set::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) { - vBlocks.push_back(*it); - setDirtyBlockIndex.erase(it++); - } - if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) { - return AbortNode(state, "Files to write to block index database"); - } + int64_t nNow = GetTimeMicros(); + // Avoid writing/flushing immediately after startup. + if (nLastWrite == 0) { + nLastWrite = nNow; + } + if (nLastFlush == 0) { + nLastFlush = nNow; + } + if (nLastSetChain == 0) { + nLastSetChain = nNow; + } + size_t cacheSize = pcoinsTip->DynamicMemoryUsage(); + // The cache is large and close to the limit, but we have time now (not in the middle of a block processing). + bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage; + // The cache is over the limit, we have to write now. + bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage; + // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash. + bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000; + // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage. + bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000; + // Combine all conditions that result in a full cache flush. + bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune; + // Write blocks and block index to disk. + if (fDoFullFlush || fPeriodicWrite) { + // Depend on nMinDiskSpace to ensure we can write block index + if (!CheckDiskSpace(0)) + return state.Error("out of disk space"); + // First make sure all block and undo data is flushed to disk. + FlushBlockFile(); + // Then update all block file information (which may refer to block and undo files). + { + std::vector > vFiles; + vFiles.reserve(setDirtyFileInfo.size()); + for (set::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) { + vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it])); + setDirtyFileInfo.erase(it++); + } + std::vector vBlocks; + vBlocks.reserve(setDirtyBlockIndex.size()); + for (set::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) { + vBlocks.push_back(*it); + setDirtyBlockIndex.erase(it++); + } + if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) { + return AbortNode(state, "Files to write to block index database"); + } + } + // Finally remove any pruned files + if (fFlushForPrune) + UnlinkPrunedFiles(setFilesToPrune); + nLastWrite = nNow; + } + // Flush best chain related state. This can only be done if the blocks / block index write was also done. + if (fDoFullFlush) { + // Typical CCoins structures on disk are around 128 bytes in size. + // Pushing a new one to the database can cause it to be written + // twice (once in the log, and once in the tables). This is already + // an overestimation, as most will delete an existing entry or + // overwrite one. Still, use a conservative safety factor of 2. + if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize())) + return state.Error("out of disk space"); + // Flush the chainstate (which may refer to block index entries). + if (!pcoinsTip->Flush()) + return AbortNode(state, "Failed to write to coin database"); + nLastFlush = nNow; + } + if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) { + // Update best block in wallet (so we can detect restored wallets). + GetMainSignals().SetBestChain(chainActive.GetLocator()); + nLastSetChain = nNow; } - // Finally remove any pruned files - if (fFlushForPrune) - UnlinkPrunedFiles(setFilesToPrune); - nLastWrite = nNow; - } - // Flush best chain related state. This can only be done if the blocks / block index write was also done. - if (fDoFullFlush) { - // Typical CCoins structures on disk are around 128 bytes in size. - // Pushing a new one to the database can cause it to be written - // twice (once in the log, and once in the tables). This is already - // an overestimation, as most will delete an existing entry or - // overwrite one. Still, use a conservative safety factor of 2. - if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize())) - return state.Error("out of disk space"); - // Flush the chainstate (which may refer to block index entries). - if (!pcoinsTip->Flush()) - return AbortNode(state, "Failed to write to coin database"); - nLastFlush = nNow; - } - if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) { - // Update best block in wallet (so we can detect restored wallets). - GetMainSignals().SetBestChain(chainActive.GetLocator()); - nLastSetChain = nNow; - } } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error while flushing: ") + e.what()); } @@ -2797,18 +2797,18 @@ void PruneAndFlush() { void static UpdateTip(CBlockIndex *pindexNew) { const CChainParams& chainParams = Params(); chainActive.SetTip(pindexNew); - + // New best block nTimeBestReceived = GetTime(); mempool.AddTransactionsUpdated(1); - + LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__, - chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx, - DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), - Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize()); - + chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx, + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), + Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize()); + cvBlockChange.notify_all(); - + // Check the version of the last 100 blocks to see if we need to upgrade: static bool fWarned = false; if (!IsInitialBlockDownload() && !fWarned) @@ -2858,7 +2858,7 @@ bool static DisconnectTip(CValidationState &state, bool fBare = false) { // Write the chain state to disk, if necessary. if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED)) return false; - + if (!fBare) { // Resurrect mempool transactions from the disconnected block. BOOST_FOREACH(const CTransaction &tx, block.vtx) { @@ -2874,7 +2874,7 @@ bool static DisconnectTip(CValidationState &state, bool fBare = false) { mempool.removeWithAnchor(anchorBeforeDisconnect); } } - + // Update chainActive and related variables. UpdateTip(pindexDelete->pprev); // Get the current commitment tree @@ -2944,10 +2944,10 @@ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock * // Remove conflicting transactions from the mempool. list txConflicted; mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload()); - + // Remove transactions that expire at new block height from mempool mempool.removeExpired(pindexNew->nHeight); - + // Update chainActive & related variables. UpdateTip(pindexNew); // Tell wallet about transactions that went from mempool @@ -2962,9 +2962,9 @@ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock * // Update cached incremental witnesses //fprintf(stderr,"chaintip true\n"); GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true); - + EnforceNodeDeprecation(pindexNew->nHeight); - + int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1; LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001); LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001); @@ -2978,7 +2978,7 @@ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock * static CBlockIndex* FindMostWorkChain() { do { CBlockIndex *pindexNew = NULL; - + // Find the best candidate header. { std::set::reverse_iterator it = setBlockIndexCandidates.rbegin(); @@ -2986,14 +2986,14 @@ static CBlockIndex* FindMostWorkChain() { return NULL; pindexNew = *it; } - + // Check whether all blocks on the path between the currently active chain and the candidate are valid. // Just going until the active chain is an optimization, as we know all blocks in it are valid already. CBlockIndex *pindexTest = pindexNew; bool fInvalidAncestor = false; while (pindexTest && !chainActive.Contains(pindexTest)) { assert(pindexTest->nChainTx || pindexTest->nHeight == 0); - + // Pruned nodes may have entries in setBlockIndexCandidates for // which block files have been deleted. Remove those as candidates // for the most work chain if we come across them; we can't switch @@ -3050,7 +3050,7 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo bool fInvalidFound = false; const CBlockIndex *pindexOldTip = chainActive.Tip(); const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork); - + // - On ChainDB initialization, pindexOldTip will be null, so there are no removable blocks. // - If pindexMostWork is in a chain that doesn't have the same genesis block as our chain, // then pindexFork will be null, and we would need to remove the entire chain including @@ -3059,23 +3059,23 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo static_assert(MAX_REORG_LENGTH > 0, "We must be able to reorg some distance"); if (reorgLength > MAX_REORG_LENGTH) { auto msg = strprintf(_( - "A block chain reorganization has been detected that would roll back %d blocks! " - "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety." - ), reorgLength, MAX_REORG_LENGTH) + "\n\n" + - _("Reorganization details") + ":\n" + - "- " + strprintf(_("Current tip: %s, height %d, work %s"), - pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight, pindexOldTip->nChainWork.GetHex()) + "\n" + - "- " + strprintf(_("New tip: %s, height %d, work %s"), - pindexMostWork->phashBlock->GetHex(), pindexMostWork->nHeight, pindexMostWork->nChainWork.GetHex()) + "\n" + - "- " + strprintf(_("Fork point: %s, height %d"), - pindexFork->phashBlock->GetHex(), pindexFork->nHeight) + "\n\n" + - _("Please help, human!"); + "A block chain reorganization has been detected that would roll back %d blocks! " + "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety." + ), reorgLength, MAX_REORG_LENGTH) + "\n\n" + + _("Reorganization details") + ":\n" + + "- " + strprintf(_("Current tip: %s, height %d, work %s"), + pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight, pindexOldTip->nChainWork.GetHex()) + "\n" + + "- " + strprintf(_("New tip: %s, height %d, work %s"), + pindexMostWork->phashBlock->GetHex(), pindexMostWork->nHeight, pindexMostWork->nChainWork.GetHex()) + "\n" + + "- " + strprintf(_("Fork point: %s, height %d"), + pindexFork->phashBlock->GetHex(), pindexFork->nHeight) + "\n\n" + + _("Please help, human!"); LogPrintf("*** %s\n", msg); uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return false; } - + // Disconnect active blocks which are no longer in the best chain. bool fBlocksDisconnected = false; while (chainActive.Tip() && chainActive.Tip() != pindexFork) { @@ -3117,7 +3117,7 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo pindexIter = pindexIter->pprev; } nHeight = nTargetHeight; - + // Connect new blocks. BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) { if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) { @@ -3143,20 +3143,20 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo } } } - + if (fBlocksDisconnected) { mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); } mempool.removeWithoutBranchId( - CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus())); + CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus())); mempool.check(pcoinsTip); - + // Callbacks/notifications for a new best chain. if (fInvalidFound) CheckForkWarningConditionsOnNewFork(vpindexToConnect.back()); else CheckForkWarningConditions(); - + return true; } @@ -3171,23 +3171,23 @@ bool ActivateBestChain(CValidationState &state, CBlock *pblock) { const CChainParams& chainParams = Params(); do { boost::this_thread::interruption_point(); - + bool fInitialDownload; { LOCK(cs_main); pindexMostWork = FindMostWorkChain(); - + // Whether we have anything to do at all. if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip()) return true; - + if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL)) return false; pindexNewTip = chainActive.Tip(); fInitialDownload = IsInitialBlockDownload(); } // When we reach this point, we switched to a new tip (stored in pindexNewTip). - + // Notifications/callbacks that can run without cs_main if (!fInitialDownload) { uint256 hashNewTip = pindexNewTip->GetBlockHash(); @@ -3200,8 +3200,8 @@ bool ActivateBestChain(CValidationState &state, CBlock *pblock) { if (nLocalServices & NODE_NETWORK) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) - if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) - pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip)); + if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) + pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip)); } // Notify external listeners about the new tip. GetMainSignals().UpdatedBlockTip(pindexNewTip); @@ -3209,23 +3209,23 @@ bool ActivateBestChain(CValidationState &state, CBlock *pblock) { } //else fprintf(stderr,"initial download skips propagation\n"); } while(pindexMostWork != chainActive.Tip()); CheckBlockIndex(); - + // Write changes periodically to disk, after relay. if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) { return false; } - + return true; } bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) { AssertLockHeld(cs_main); - + // Mark the block itself as invalid. pindex->nStatus |= BLOCK_FAILED_VALID; setDirtyBlockIndex.insert(pindex); setBlockIndexCandidates.erase(pindex); - + while (chainActive.Contains(pindex)) { CBlockIndex *pindexWalk = chainActive.Tip(); pindexWalk->nStatus |= BLOCK_FAILED_CHILD; @@ -3236,12 +3236,12 @@ bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) { if (!DisconnectTip(state)) { mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); mempool.removeWithoutBranchId( - CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus())); + CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus())); return false; } } //LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60); - + // The resulting new best tip may not be in setBlockIndexCandidates anymore, so // add it again. BlockMap::iterator it = mapBlockIndex.begin(); @@ -3251,19 +3251,19 @@ bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) { } it++; } - + InvalidChainFound(pindex); mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); mempool.removeWithoutBranchId( - CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus())); + CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus())); return true; } bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) { AssertLockHeld(cs_main); - + int nHeight = pindex->nHeight; - + // Remove the invalidity flag from this block and all its descendants. BlockMap::iterator it = mapBlockIndex.begin(); while (it != mapBlockIndex.end()) { @@ -3280,7 +3280,7 @@ bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) { } it++; } - + // Remove the invalidity flag from all ancestors too. while (pindex != NULL) { if (pindex->nStatus & BLOCK_FAILED_MASK) { @@ -3299,7 +3299,7 @@ CBlockIndex* AddToBlockIndex(const CBlockHeader& block) BlockMap::iterator it = mapBlockIndex.find(hash); if (it != mapBlockIndex.end()) return it->second; - + // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(block); assert(pindexNew); @@ -3320,9 +3320,9 @@ CBlockIndex* AddToBlockIndex(const CBlockHeader& block) pindexNew->RaiseValidity(BLOCK_VALID_TREE); if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork) pindexBestHeader = pindexNew; - + setDirtyBlockIndex.insert(pindexNew); - + return pindexNew; } @@ -3346,12 +3346,12 @@ bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBl pindexNew->nStatus |= BLOCK_HAVE_DATA; pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS); setDirtyBlockIndex.insert(pindexNew); - + if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) { // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS. deque queue; queue.push_back(pindexNew); - + // Recursively process any descendant blocks that now may be eligible to be connected. while (!queue.empty()) { CBlockIndex *pindex = queue.front(); @@ -3386,19 +3386,19 @@ bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBl mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew)); } } - + return true; } bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false) { LOCK(cs_LastBlockFile); - + unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile; if (vinfoBlockFile.size() <= nFile) { vinfoBlockFile.resize(nFile + 1); } - + if (!fKnown) { while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) { nFile++; @@ -3409,7 +3409,7 @@ bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAdd pos.nFile = nFile; pos.nPos = vinfoBlockFile[nFile].nSize; } - + if (nFile != nLastBlockFile) { if (!fKnown) { LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString()); @@ -3417,13 +3417,13 @@ bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAdd FlushBlockFile(!fKnown); nLastBlockFile = nFile; } - + vinfoBlockFile[nFile].AddBlock(nHeight, nTime); if (fKnown) vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize); else vinfoBlockFile[nFile].nSize += nAddSize; - + if (!fKnown) { unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; @@ -3442,7 +3442,7 @@ bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAdd return state.Error("out of disk space"); } } - + setDirtyFileInfo.insert(nFile); return true; } @@ -3450,14 +3450,14 @@ bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAdd bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize) { pos.nFile = nFile; - + LOCK(cs_LastBlockFile); - + unsigned int nNewSize; pos.nPos = vinfoBlockFile[nFile].nUndoSize; nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize; setDirtyFileInfo.insert(nFile); - + unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; if (nNewChunks > nOldChunks) { @@ -3474,7 +3474,7 @@ bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigne else return state.Error("out of disk space"); } - + return true; } @@ -3506,15 +3506,15 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl // Check block version //if (block.nVersion < MIN_BLOCK_VERSION) // return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low"); - + // Check Equihash solution is valid if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) ) return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); // Check proof of work matches claimed amount /*komodo_index2pubkey33(pubkey33,pindex,height); - if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) ) - return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash");*/ + if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) ) + return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash");*/ return true; } @@ -3524,6 +3524,8 @@ int32_t komodo_reverify_blockcheck(CValidationState& state,int32_t height,CBlock { static int32_t oneshot; CBlockIndex *tipindex; int32_t rewindtarget; + if ( KOMODO_REWIND != 0 ) + oneshot = KOMODO_REWIND; if ( oneshot == 0 && IsInitialBlockDownload() == 0 && (tipindex= chainActive.Tip()) != 0 ) { // if 200 blocks behind longestchain and no blocks for 2 hours @@ -3555,8 +3557,8 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat bool fCheckPOW, bool fCheckMerkleRoot) { uint8_t pubkey33[33]; - // These are checks that are independent of context. - + // These are checks that are independent of context. + // Check that the header is valid (particularly PoW). This is mostly // redundant with the call in AcceptBlockHeader. if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW)) @@ -3575,7 +3577,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if (block.hashMerkleRoot != hashMerkleRoot2) return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"), REJECT_INVALID, "bad-txnmrklroot", true); - + // Check for merkle tree malleability (CVE-2012-2459): repeating sequences // of transactions in a block without affecting the merkle root of a block, // while still invalidating it. @@ -3583,16 +3585,16 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat return state.DoS(100, error("CheckBlock(): duplicate transaction"), REJECT_INVALID, "bad-txns-duplicate", true); } - + // All potential-corruption validation must be done before we do any // transaction validation, as otherwise we may mark the header as invalid // because we receive the wrong transactions for it. - + // Size limits if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return state.DoS(100, error("CheckBlock(): size limits failed"), REJECT_INVALID, "bad-blk-length"); - + // First transaction must be coinbase, the rest must not be if (block.vtx.empty() || !block.vtx[0].IsCoinBase()) return state.DoS(100, error("CheckBlock(): first tx is not coinbase"), @@ -3601,12 +3603,12 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if (block.vtx[i].IsCoinBase()) return state.DoS(100, error("CheckBlock(): more than one coinbase"), REJECT_INVALID, "bad-cb-multiple"); - + // Check transactions BOOST_FOREACH(const CTransaction& tx, block.vtx) { if ( komodo_validate_interest(tx,height == 0 ? komodo_block2height((CBlock *)&block) : height,block.nTime,1) < 0 ) - return error("CheckBlock: komodo_validate_interest failed"); + return error("CheckBlock: komodo_validate_interest failed"); if (!CheckTransaction(tx, state, verifier)) return error("CheckBlock(): CheckTransaction failed"); } @@ -3619,7 +3621,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"), REJECT_INVALID, "bad-blk-sigops", true); if ( komodo_check_deposit(height,block,(pindex==0||pindex->pprev==0)?0:pindex->pprev->nTime) < 0 ) - //if ( komodo_check_deposit(ASSETCHAINS_SYMBOL[0] == 0 ? height : pindex != 0 ? (int32_t)pindex->nHeight : chainActive.Tip()->nHeight+1,block,pindex==0||pindex->pprev==0?0:pindex->pprev->nTime) < 0 ) + //if ( komodo_check_deposit(ASSETCHAINS_SYMBOL[0] == 0 ? height : pindex != 0 ? (int32_t)pindex->nHeight : chainActive.Tip()->nHeight+1,block,pindex==0||pindex->pprev==0?0:pindex->pprev->nTime) < 0 ) { static uint32_t counter; if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) @@ -3636,11 +3638,11 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta uint256 hash = block.GetHash(); if (hash == consensusParams.hashGenesisBlock) return true; - + assert(pindexPrev); - + int nHeight = pindexPrev->nHeight+1; - + // Check proof of work if ( (nHeight < 235300 || nHeight > 236000) && block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams)) { @@ -3648,12 +3650,12 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta return state.DoS(100, error("%s: incorrect proof of work", __func__), REJECT_INVALID, "bad-diffbits"); } - + // Check timestamp against prev if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast()) return state.Invalid(error("%s: block's timestamp is too early", __func__), REJECT_INVALID, "time-too-old"); - + if (fCheckpointsEnabled) { // Check that the block chain matches the known block chain up to a checkpoint @@ -3685,7 +3687,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta if (block.nVersion < 4) return state.Invalid(error("%s : rejected nVersion<4 block", __func__), REJECT_OBSOLETE, "bad-version"); - + return true; } @@ -3693,24 +3695,24 @@ bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIn { const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1; const Consensus::Params& consensusParams = Params().GetConsensus(); - + // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, block.vtx) { - + // Check transaction contextually against consensus rules at block height if (!ContextualCheckTransaction(tx, state, nHeight, 100)) { return false; // Failure reason has been set in validation state object } - + int nLockTimeFlags = 0; int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST) - ? pindexPrev->GetMedianTimePast() - : block.GetBlockTime(); + ? pindexPrev->GetMedianTimePast() + : block.GetBlockTime(); if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) { return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal"); } } - + // Enforce BIP 34 rule that the coinbase starts with serialized block height. // In Zcash this has been enforced since launch, except that the genesis // block didn't include the height in the coinbase (see Zcash protocol spec @@ -3723,7 +3725,7 @@ bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIn return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height"); } } - + return true; } @@ -3743,7 +3745,12 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc if ( pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK ) { komodo_reverify_blockcheck(state,pindex->nHeight,pindex); - return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); + if ( KOMODO_LONGESTCHAIN != 0 && pindex->nHeight > KOMODO_LONGESTCHAIN-100 ) + return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); + else + { + pindex->nStatus &= ~BLOCK_FAILED_MASK; + } } if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 debug test { @@ -3780,10 +3787,10 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc } return true; } - + if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state)) return false; - + // Get prev block index CBlockIndex* pindexPrev = NULL; if (hash != chainparams.GetConsensus().hashGenesisBlock) { @@ -3809,7 +3816,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, { const CChainParams& chainparams = Params(); AssertLockHeld(cs_main); - + CBlockIndex *&pindex = *ppindex; if (!AcceptBlockHeader(block, state, &pindex)) return false; @@ -3829,7 +3836,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, // regardless of whether pruning is enabled; it should generally be safe to // not process unrequested blocks. bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP)); - + // TODO: deal better with return value and error conditions for duplicate // and unrequested blocks. if (fAlreadyHave) return true; @@ -3838,7 +3845,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, if (!fHasMoreWork) return true; // Don't process less-work chains if (fTooFarAhead) return true; // Block height is too high } - + // See method docstring for why this is always disabled auto verifier = libzcash::ProofVerifier::Disabled(); if ((!CheckBlock(pindex->nHeight,pindex,block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) { @@ -3848,9 +3855,9 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, } return false; } - + int nHeight = pindex->nHeight; - + // Write block to history file try { unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); @@ -3867,10 +3874,10 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error: ") + e.what()); } - + if (fCheckForPruning) FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files - + return true; } @@ -3910,7 +3917,7 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc } return error("%s: CheckBlock FAILED", __func__); } - + // Store to disk CBlockIndex *pindex = NULL; bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp); @@ -3921,10 +3928,10 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc if (!ret) return error("%s: AcceptBlock FAILED", __func__); } - + if (!ActivateBestChain(state, pblock)) return error("%s: ActivateBestChain failed", __func__); - + return true; } @@ -3932,14 +3939,14 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex { AssertLockHeld(cs_main); assert(pindexPrev == chainActive.Tip()); - + CCoinsViewCache viewNew(pcoinsTip); CBlockIndex indexDummy(block); indexDummy.pprev = pindexPrev; indexDummy.nHeight = pindexPrev->nHeight + 1; // JoinSplit proofs are verified in ConnectBlock auto verifier = libzcash::ProofVerifier::Disabled(); - + // NOTE: CheckBlockHeader is called by CheckBlock if (!ContextualCheckBlockHeader(block, state, pindexPrev)) { @@ -3962,7 +3969,7 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex return false; } assert(state.IsValid()); - + return true; } @@ -3992,7 +3999,7 @@ void PruneOneBlockFile(const int fileNumber) pindex->nDataPos = 0; pindex->nUndoPos = 0; setDirtyBlockIndex.insert(pindex); - + // Prune from mapBlocksUnlinked -- any block we prune would have // to be downloaded again in order to consider its chain, at which // point it would be considered as a candidate for @@ -4007,7 +4014,7 @@ void PruneOneBlockFile(const int fileNumber) } } } - + vinfoBlockFile[fileNumber].SetNull(); setDirtyFileInfo.insert(fileNumber); } @@ -4033,7 +4040,7 @@ void FindFilesToPrune(std::set& setFilesToPrune) if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) { return; } - + unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP; uint64_t nCurrentUsage = CalculateCurrentUsage(); // We don't check to prune until after we've allocated new space for files @@ -4042,21 +4049,21 @@ void FindFilesToPrune(std::set& setFilesToPrune) uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE; uint64_t nBytesToPrune; int count=0; - + if (nCurrentUsage + nBuffer >= nPruneTarget) { for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) { nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize; - + if (vinfoBlockFile[fileNumber].nSize == 0) continue; - + if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target? break; - + // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) continue; - + PruneOneBlockFile(fileNumber); // Queue up the files for removal setFilesToPrune.insert(fileNumber); @@ -4064,21 +4071,21 @@ void FindFilesToPrune(std::set& setFilesToPrune) count++; } } - + LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n", - nPruneTarget/1024/1024, nCurrentUsage/1024/1024, - ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024, - nLastBlockWeCanPrune, count); + nPruneTarget/1024/1024, nCurrentUsage/1024/1024, + ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024, + nLastBlockWeCanPrune, count); } bool CheckDiskSpace(uint64_t nAdditionalBytes) { uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available; - + // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) return AbortNode("Disk space is low!", _("Error: Disk space is low!")); - + return true; } @@ -4144,19 +4151,19 @@ CBlockIndex * InsertBlockIndex(uint256 hash) { if (hash.IsNull()) return NULL; - + // Return existing BlockMap::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) return (*mi).second; - + // Create new CBlockIndex* pindexNew = new CBlockIndex(); if (!pindexNew) throw runtime_error("LoadBlockIndex(): new CBlockIndex failed"); mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); - + return pindexNew; } @@ -4167,9 +4174,9 @@ bool static LoadBlockIndexDB() const CChainParams& chainparams = Params(); if (!pblocktree->LoadBlockIndexGuts()) return false; - + boost::this_thread::interruption_point(); - + // Calculate nChainWork vector > vSortedByHeight; vSortedByHeight.reserve(mapBlockIndex.size()); @@ -4228,7 +4235,7 @@ bool static LoadBlockIndexDB() pindexBestHeader = pindex; //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } - + // Load block file info pblocktree->ReadLastBlockFile(nLastBlockFile); vinfoBlockFile.resize(nLastBlockFile + 1); @@ -4245,7 +4252,7 @@ bool static LoadBlockIndexDB() break; } } - + // Check presence of blk files LogPrintf("Checking all blk files are present...\n"); set setBlkDataFiles; @@ -4264,21 +4271,21 @@ bool static LoadBlockIndexDB() return false; } } - + // Check whether we have ever pruned block & undo files pblocktree->ReadFlag("prunedblockfiles", fHavePruned); if (fHavePruned) LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n"); - + // Check whether we need to continue reindexing bool fReindexing = false; pblocktree->ReadReindexing(fReindexing); fReindex |= fReindexing; - + // Check whether we have a transaction index pblocktree->ReadFlag("txindex", fTxIndex); LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled"); - + // Fill in-memory data BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex) { @@ -4293,7 +4300,7 @@ bool static LoadBlockIndexDB() } //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } - + // Load pointer to end of best chain BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); if (it == mapBlockIndex.end()) @@ -4301,16 +4308,16 @@ bool static LoadBlockIndexDB() chainActive.SetTip(it->second); // Set hashAnchorEnd for the end of best chain it->second->hashAnchorEnd = pcoinsTip->GetBestAnchor(); - + PruneBlockIndexCandidates(); - + LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__, - chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), - DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), - Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip())); - + chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), + Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip())); + EnforceNodeDeprecation(chainActive.Height(), true); - + return true; } @@ -4329,7 +4336,7 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth LOCK(cs_main); if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL) return true; - + // Verify blocks in the best chain if (nCheckDepth <= 0) nCheckDepth = 1000000000; // suffices until the year 19000 @@ -4383,7 +4390,7 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth } if (pindexFailure) return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions); - + // check level 4: try reconnecting blocks if (nCheckLevel >= 4) { CBlockIndex *pindex = pindexState; @@ -4398,16 +4405,16 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); } } - + LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions); - + return true; } bool RewindBlockIndex(const CChainParams& params) { LOCK(cs_main); - + // RewindBlockIndex is called after LoadBlockIndex, so at this point every block // index will have nCachedBranchId set based on the values previously persisted // to disk. By definition, a set nCachedBranchId means that the block was @@ -4422,10 +4429,10 @@ bool RewindBlockIndex(const CChainParams& params) bool fFlagSet = pindex->nStatus & BLOCK_ACTIVATES_UPGRADE; bool fFlagExpected = IsActivationHeightForAnyUpgrade(pindex->nHeight, consensus); return fFlagSet == fFlagExpected && - pindex->nCachedBranchId && - *pindex->nCachedBranchId == CurrentEpochBranchId(pindex->nHeight, consensus); + pindex->nCachedBranchId && + *pindex->nCachedBranchId == CurrentEpochBranchId(pindex->nHeight, consensus); }; - + int nHeight = 1; while (nHeight <= chainActive.Height()) { if (!sufficientlyValidated(chainActive[nHeight])) { @@ -4433,28 +4440,28 @@ bool RewindBlockIndex(const CChainParams& params) } nHeight++; } - + // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1 auto rewindLength = chainActive.Height() - nHeight; if (rewindLength > 0 && rewindLength > MAX_REORG_LENGTH) { auto pindexOldTip = chainActive.Tip(); auto pindexRewind = chainActive[nHeight - 1]; auto msg = strprintf(_( - "A block chain rewind has been detected that would roll back %d blocks! " - "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety." - ), rewindLength, MAX_REORG_LENGTH) + "\n\n" + - _("Rewind details") + ":\n" + - "- " + strprintf(_("Current tip: %s, height %d"), - pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight) + "\n" + - "- " + strprintf(_("Rewinding to: %s, height %d"), - pindexRewind->phashBlock->GetHex(), pindexRewind->nHeight) + "\n\n" + - _("Please help, human!"); + "A block chain rewind has been detected that would roll back %d blocks! " + "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety." + ), rewindLength, MAX_REORG_LENGTH) + "\n\n" + + _("Rewind details") + ":\n" + + "- " + strprintf(_("Current tip: %s, height %d"), + pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight) + "\n" + + "- " + strprintf(_("Rewinding to: %s, height %d"), + pindexRewind->phashBlock->GetHex(), pindexRewind->nHeight) + "\n\n" + + _("Please help, human!"); LogPrintf("*** %s\n", msg); uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return false; } - + CValidationState state; CBlockIndex* pindex = chainActive.Tip(); while (chainActive.Height() >= nHeight) { @@ -4473,13 +4480,13 @@ bool RewindBlockIndex(const CChainParams& params) if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) return false; } - + // Reduce validity flag and have-data flags. // We do this after actual disconnecting, otherwise we'll end up writing the lack of data // to disk before writing the chainstate, resulting in a failure to continue if interrupted. for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) { CBlockIndex* pindexIter = it->second; - + // Note: If we encounter an insufficiently validated block that // is on chainActive, it must be because we are a pruning node, and // this block or some successor doesn't HAVE_DATA, so we were unable to @@ -4488,8 +4495,8 @@ bool RewindBlockIndex(const CChainParams& params) if (!sufficientlyValidated(pindexIter) && !chainActive.Contains(pindexIter)) { // Reduce validity pindexIter->nStatus = - std::min(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | - (pindexIter->nStatus & ~BLOCK_VALID_MASK); + std::min(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | + (pindexIter->nStatus & ~BLOCK_VALID_MASK); // Remove have-data flags pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO); // Remove branch ID @@ -4527,15 +4534,15 @@ bool RewindBlockIndex(const CChainParams& params) setBlockIndexCandidates.insert(pindexIter); } } - + PruneBlockIndexCandidates(); - + CheckBlockIndex(); - + if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) { return false; } - + return true; } @@ -4562,7 +4569,7 @@ void UnloadBlockIndex() setDirtyFileInfo.clear(); mapNodeState.clear(); recentRejects.reset(NULL); - + BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) { delete entry.second; } @@ -4587,19 +4594,19 @@ bool LoadBlockIndex() bool InitBlockIndex() { const CChainParams& chainparams = Params(); LOCK(cs_main); - + // Initialize global variables that cannot be constructed at startup. recentRejects.reset(new CRollingBloomFilter(120000, 0.000001)); - + // Check whether we're already initialized if (chainActive.Genesis() != NULL) return true; - + // Use the provided setting for -txindex in the new database fTxIndex = GetBoolArg("-txindex", true); pblocktree->WriteFlag("txindex", fTxIndex); LogPrintf("Initializing databases...\n"); - + // Only add the genesis block if not reindexing (in which case we reuse the one already on disk) if (!fReindex) { try { @@ -4625,7 +4632,7 @@ bool InitBlockIndex() { return error("LoadBlockIndex(): failed to initialize block database: %s", e.what()); } } - + return true; } @@ -4637,7 +4644,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) // Map of disk positions for blocks with unknown parent (only used for reindex) static std::multimap mapBlocksUnknownParent; int64_t nStart = GetTimeMillis(); - + int nLoaded = 0; try { // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor @@ -4645,7 +4652,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) uint64_t nRewind = blkdat.GetPos(); while (!blkdat.eof()) { boost::this_thread::interruption_point(); - + blkdat.SetPos(nRewind); nRewind++; // start one byte further next time, in case of failure blkdat.SetLimit(); // remove former limit @@ -4676,17 +4683,17 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) CBlock block; blkdat >> block; nRewind = blkdat.GetPos(); - + // detect out of order blocks, and store them for later uint256 hash = block.GetHash(); if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) { LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(), - block.hashPrevBlock.ToString()); + block.hashPrevBlock.ToString()); if (dbp) mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp)); continue; } - + // process in case the block isn't known yet if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) { CValidationState state; @@ -4697,7 +4704,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) { LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight); } - + // Recursively process earlier encountered successors of this block deque queue; queue.push_back(hash); @@ -4710,7 +4717,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) if (ReadBlockFromDisk(mapBlockIndex[hash]!=0?mapBlockIndex[hash]->nHeight:0,block, it->second)) { LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(), - head.ToString()); + head.ToString()); CValidationState dummy; if (ProcessNewBlock(0,dummy, NULL, &block, true, &it->second)) { @@ -4740,9 +4747,9 @@ void static CheckBlockIndex() if (!fCheckBlockIndex) { return; } - + LOCK(cs_main); - + // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain, // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when // iterating the block tree require that chainActive has been initialized.) @@ -4750,20 +4757,20 @@ void static CheckBlockIndex() assert(mapBlockIndex.size() <= 1); return; } - + // Build forward-pointing map of the entire block tree. std::multimap forward; for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) { - forward.insert(std::make_pair(it->second->pprev, it->second)); + forward.insert(std::make_pair(it->second->pprev, it->second)); } - + assert(forward.size() == mapBlockIndex.size()); - + std::pair::iterator,std::multimap::iterator> rangeGenesis = forward.equal_range(NULL); CBlockIndex *pindex = rangeGenesis.first->second; rangeGenesis.first++; assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL. - + // Iterate over the entire block tree, using depth-first search. // Along the way, remember whether there are blocks on the path from genesis // block being explored which are the first to have certain properties. @@ -4785,7 +4792,7 @@ void static CheckBlockIndex() if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex; if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex; if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex; - + // Begin: actual consistency checks. if (pindex->pprev == NULL) { // Genesis block checks. @@ -4871,7 +4878,7 @@ void static CheckBlockIndex() } // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow // End: actual consistency checks. - + // Try descending into the first subnode. std::pair::iterator,std::multimap::iterator> range = forward.equal_range(pindex); if (range.first != range.second) { @@ -4914,7 +4921,7 @@ void static CheckBlockIndex() } } } - + // Check that we actually traversed the entire map. assert(nNodes == forward.size()); } @@ -4929,20 +4936,20 @@ std::string GetWarnings(const std::string& strFor) int nPriority = 0; string strStatusBar; string strRPC; - + if (!CLIENT_VERSION_IS_RELEASE) strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications"); - + if (GetBoolArg("-testsafemode", false)) strStatusBar = strRPC = "testsafemode enabled"; - + // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } - + if (fLargeWorkForkFound) { nPriority = 2000; @@ -4953,7 +4960,7 @@ std::string GetWarnings(const std::string& strFor) nPriority = 2000; strStatusBar = strRPC = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade."); } - + // Alerts { LOCK(cs_mapAlerts); @@ -4970,7 +4977,7 @@ std::string GetWarnings(const std::string& strFor) } } } - + if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") @@ -4996,7 +5003,7 @@ bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { switch (inv.type) { - case MSG_TX: + case MSG_TX: { assert(recentRejects); if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip) @@ -5008,14 +5015,14 @@ bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash(); recentRejects->reset(); } - + return recentRejects->contains(inv.hash) || - mempool.exists(inv.hash) || - mapOrphanTransactions.count(inv.hash) || - pcoinsTip->HaveCoins(inv.hash); + mempool.exists(inv.hash) || + mapOrphanTransactions.count(inv.hash) || + pcoinsTip->HaveCoins(inv.hash); } - case MSG_BLOCK: - return mapBlockIndex.count(inv.hash); + case MSG_BLOCK: + return mapBlockIndex.count(inv.hash); } // Don't know what it is, just say we already got one return true; @@ -5024,21 +5031,21 @@ bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) void static ProcessGetData(CNode* pfrom) { std::deque::iterator it = pfrom->vRecvGetData.begin(); - + vector vNotFound; - + LOCK(cs_main); - + while (it != pfrom->vRecvGetData.end()) { // Don't bother if send buffer is too full to respond anyway if (pfrom->nSendSize >= SendBufferSize()) break; - + const CInv &inv = *it; { boost::this_thread::interruption_point(); it++; - + if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) { bool send = false; @@ -5053,8 +5060,8 @@ void static ProcessGetData(CNode* pfrom) // chain if they are valid, and no more than a month older (both in time, and in // best equivalent proof of work) than the best header chain we know about. send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) && - (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) && - (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth); + (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) && + (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth); if (!send) { LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId()); } @@ -5142,17 +5149,17 @@ void static ProcessGetData(CNode* pfrom) vNotFound.push_back(inv); } } - + // Track requests for our stuff. GetMainSignals().Inventory(inv.hash); - + if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) break; } } - + pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it); - + if (!vNotFound.empty()) { // Let the peer know that we didn't find what it asked for, so it doesn't // have to wait around forever. Currently only SPV clients actually care @@ -5175,10 +5182,10 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } - - - - + + + + if (strCommand == "version") { // Each connection can only send one version message @@ -5188,7 +5195,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, Misbehaving(pfrom->GetId(), 1); return false; } - + int64_t nTime; CAddress addrMe; CAddress addrFrom; @@ -5203,7 +5210,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->fDisconnect = true; return false; } - + // When Overwinter is active, reject incoming connections from non-Overwinter nodes const Consensus::Params& params = Params().GetConsensus(); if (NetworkUpgradeActive(GetHeight(), params, Consensus::UPGRADE_OVERWINTER) @@ -5211,12 +5218,12 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, { LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion); pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE, - strprintf("Version must be %d or greater", - params.vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion)); + strprintf("Version must be %d or greater", + params.vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion)); pfrom->fDisconnect = true; return false; } - + if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) @@ -5231,7 +5238,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message else pfrom->fRelayTxes = true; - + // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { @@ -5239,26 +5246,26 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->fDisconnect = true; return true; } - + pfrom->addrLocal = addrMe; if (pfrom->fInbound && addrMe.IsRoutable()) { SeenLocal(addrMe); } - + // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); - + pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); - + // Potentially mark this peer as a preferred download peer. UpdatePreferredDownload(pfrom, State(pfrom->GetId())); - + // Change version pfrom->PushMessage("verack"); pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); - + if (!pfrom->fInbound) { // Advertise our address @@ -5275,7 +5282,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->PushAddress(addr); } } - + // Get recent addresses if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { @@ -5290,72 +5297,72 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, addrman.Good(addrFrom); } } - + // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) - item.second.RelayTo(pfrom); + item.second.RelayTo(pfrom); } - + pfrom->fSuccessfullyConnected = true; - + string remoteAddr; if (fLogIPs) remoteAddr = ", peeraddr=" + pfrom->addr.ToString(); - + LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n", pfrom->cleanSubVer, pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString(), pfrom->id, remoteAddr); - + int64_t nTimeOffset = nTime - GetTime(); pfrom->nTimeOffset = nTimeOffset; AddTimeData(pfrom->addr, nTimeOffset); } - - + + else if (pfrom->nVersion == 0) { // Must have a version message before anything else Misbehaving(pfrom->GetId(), 1); return false; } - - + + else if (strCommand == "verack") { pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); - + // Mark this node as currently connected, so we update its timestamp later. if (pfrom->fNetworkNode) { LOCK(cs_main); State(pfrom->GetId())->fCurrentlyConnected = true; } } - - + + // Disconnect existing peer connection when: // 1. The version message has been received // 2. Overwinter is active // 3. Peer version is pre-Overwinter else if (NetworkUpgradeActive(GetHeight(), chainparams.GetConsensus(), Consensus::UPGRADE_OVERWINTER) - && (pfrom->nVersion < chainparams.GetConsensus().vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion)) + && (pfrom->nVersion < chainparams.GetConsensus().vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion)) { LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion); pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE, - strprintf("Version must be %d or greater", - chainparams.GetConsensus().vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion)); + strprintf("Version must be %d or greater", + chainparams.GetConsensus().vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion)); pfrom->fDisconnect = true; return false; } - - + + else if (strCommand == "addr") { vector vAddr; vRecv >> vAddr; - + // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; @@ -5364,7 +5371,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, Misbehaving(pfrom->GetId(), 20); return error("message addr size() = %u", vAddr.size()); } - + // Store the new addresses vector vAddrOk; int64_t nNow = GetAdjustedTime(); @@ -5372,7 +5379,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, BOOST_FOREACH(CAddress& addr, vAddr) { boost::this_thread::interruption_point(); - + if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); @@ -5416,8 +5423,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, if (pfrom->fOneShot) pfrom->fDisconnect = true; } - - + + else if (strCommand == "inv") { vector vInv; @@ -5427,24 +5434,24 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, Misbehaving(pfrom->GetId(), 20); return error("message inv size() = %u", vInv.size()); } - + LOCK(cs_main); - + std::vector vToFetch; - + for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; - + boost::this_thread::interruption_point(); pfrom->AddInventoryKnown(inv); - + bool fAlreadyHave = AlreadyHave(inv); LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id); - + if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK) pfrom->AskFor(inv); - + if (inv.type == MSG_BLOCK) { UpdateBlockAvailability(pfrom->GetId(), inv.hash); if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) { @@ -5468,21 +5475,21 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id); } } - + // Track requests for our stuff GetMainSignals().Inventory(inv.hash); - + if (pfrom->nSendSize > (SendBufferSize() * 2)) { Misbehaving(pfrom->GetId(), 50); return error("send buffer size() = %u", pfrom->nSendSize); } } - + if (!vToFetch.empty()) pfrom->PushMessage("getdata", vToFetch); } - - + + else if (strCommand == "getdata") { vector vInv; @@ -5492,29 +5499,29 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, Misbehaving(pfrom->GetId(), 20); return error("message getdata size() = %u", vInv.size()); } - + if (fDebug || (vInv.size() != 1)) LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id); - + if ((fDebug && vInv.size() > 0) || (vInv.size() == 1)) LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id); - + pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end()); ProcessGetData(pfrom); } - - + + else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; - + LOCK(cs_main); - + // Find the last block the caller has in the main chain CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator); - + // Send the rest of the chain if (pindex) pindex = chainActive.Next(pindex); @@ -5538,19 +5545,19 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } } } - - + + else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; - + LOCK(cs_main); - + if (IsInitialBlockDownload()) return true; - + CBlockIndex* pindex = NULL; if (locator.IsNull()) { @@ -5567,7 +5574,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, if (pindex) pindex = chainActive.Next(pindex); } - + // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end vector vHeaders; int nLimit = MAX_HEADERS_RESULTS; @@ -5590,37 +5597,37 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, fprintf(stderr,"you can ignore redundant getheaders from peer.%d %d prev.%d\n",(int32_t)pfrom->id,(int32_t)(pindex ? pindex->nHeight : -1),pfrom->lasthdrsreq); } } - - + + else if (strCommand == "tx") { vector vWorkQueue; vector vEraseQueue; CTransaction tx; vRecv >> tx; - + CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); - + LOCK(cs_main); - + bool fMissingInputs = false; CValidationState state; - + pfrom->setAskFor.erase(inv.hash); mapAlreadyAskedFor.erase(inv); - + if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs)) { mempool.check(pcoinsTip); RelayTransaction(tx); vWorkQueue.push_back(inv.hash); - + LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n", - pfrom->id, pfrom->cleanSubVer, - tx.GetHash().ToString(), - mempool.mapTx.size()); - + pfrom->id, pfrom->cleanSubVer, + tx.GetHash().ToString(), + mempool.mapTx.size()); + // Recursively process any orphan transactions that depended on this one set setMisbehaving; for (unsigned int i = 0; i < vWorkQueue.size(); i++) @@ -5640,8 +5647,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get // anyone relaying LegitTxX banned) CValidationState stateDummy; - - + + if (setMisbehaving.count(fromPeer)) continue; if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2)) @@ -5671,15 +5678,15 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, mempool.check(pcoinsTip); } } - + BOOST_FOREACH(uint256 hash, vEraseQueue) - EraseOrphanTx(hash); + EraseOrphanTx(hash); } // TODO: currently, prohibit joinsplits from entering mapOrphans else if (fMissingInputs && tx.vjoinsplit.size() == 0) { AddOrphanTx(tx, pfrom->GetId()); - + // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS)); unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx); @@ -5688,7 +5695,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } else { assert(recentRejects); recentRejects->insert(tx.GetHash()); - + if (pfrom->fWhitelisted) { // Always relay transactions received from whitelisted peers, even // if they were already in the mempool or rejected from it due @@ -5704,7 +5711,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, RelayTransaction(tx); } else { LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n", - tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode()); + tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode()); } } } @@ -5712,20 +5719,20 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, if (state.IsInvalid(nDoS)) { LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(), - pfrom->id, pfrom->cleanSubVer, - state.GetRejectReason()); + pfrom->id, pfrom->cleanSubVer, + state.GetRejectReason()); pfrom->PushMessage("reject", strCommand, state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash); if (nDoS > 0) Misbehaving(pfrom->GetId(), nDoS); } } - - + + else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing { std::vector headers; - + // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks. unsigned int nCount = ReadCompactSize(vRecv); if (nCount > MAX_HEADERS_RESULTS) { @@ -5737,14 +5744,14 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, vRecv >> headers[n]; ReadCompactSize(vRecv); // ignore tx count; assume it is 0. } - + LOCK(cs_main); - + if (nCount == 0) { // Nothing interesting. Stop asking this peers for more headers. return true; } - + CBlockIndex *pindexLast = NULL; BOOST_FOREACH(const CBlockHeader& header, headers) { CValidationState state; @@ -5762,10 +5769,10 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } } } - + if (pindexLast) UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash()); - + if (nCount == MAX_HEADERS_RESULTS && pindexLast) { // Headers message had its maximum size; the peer may have more headers. // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue @@ -5777,20 +5784,20 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256()); } } - + CheckBlockIndex(); } - + else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing { CBlock block; vRecv >> block; - + CInv inv(MSG_BLOCK, block.GetHash()); LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id); - + pfrom->AddInventoryKnown(inv); - + CValidationState state; // Process all blocks from whitelisted peers, even if not requested, // unless we're still syncing with the network. @@ -5807,10 +5814,10 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, Misbehaving(pfrom->GetId(), nDoS); } } - + } - - + + // This asymmetric behavior for inbound and outbound connections was introduced // to prevent a fingerprinting attack: an attacker can send specific fake addresses // to users' AddrMan and later request them by sending getaddr messages. @@ -5825,18 +5832,18 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, return true; } pfrom->fSentAddr = true; - + pfrom->vAddrToSend.clear(); vector vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) - pfrom->PushAddress(addr); + pfrom->PushAddress(addr); } - - + + else if (strCommand == "mempool") { LOCK2(cs_main, pfrom->cs_filter); - + std::vector vtxid; mempool.queryHashes(vtxid); vector vInv; @@ -5846,7 +5853,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, bool fInMemPool = mempool.lookup(hash, tx); if (!fInMemPool) continue; // another thread removed since queryHashes, maybe... if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) || - (!pfrom->pfilter)) + (!pfrom->pfilter)) vInv.push_back(inv); if (vInv.size() == MAX_INV_SZ) { pfrom->PushMessage("inv", vInv); @@ -5856,8 +5863,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, if (vInv.size() > 0) pfrom->PushMessage("inv", vInv); } - - + + else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) @@ -5878,8 +5885,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->PushMessage("pong", nonce); } } - - + + else if (strCommand == "pong") { int64_t pingUsecEnd = nTimeReceived; @@ -5887,10 +5894,10 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, size_t nAvail = vRecv.in_avail(); bool bPingFinished = false; std::string sProblem; - + if (nAvail >= sizeof(nonce)) { vRecv >> nonce; - + // Only process pong message if there is an outstanding ping (old ping without nonce should never pong) if (pfrom->nPingNonceSent != 0) { if (nonce == pfrom->nPingNonceSent) { @@ -5922,27 +5929,27 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, bPingFinished = true; sProblem = "Short payload"; } - + if (!(sProblem.empty())) { LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n", - pfrom->id, - pfrom->cleanSubVer, - sProblem, - pfrom->nPingNonceSent, - nonce, - nAvail); + pfrom->id, + pfrom->cleanSubVer, + sProblem, + pfrom->nPingNonceSent, + nonce, + nAvail); } if (bPingFinished) { pfrom->nPingNonceSent = 0; } } - - + + else if (fAlerts && strCommand == "alert") { CAlert alert; vRecv >> alert; - + uint256 alertHash = alert.GetHash(); if (pfrom->setKnown.count(alertHash) == 0) { @@ -5953,7 +5960,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) - alert.RelayTo(pnode); + alert.RelayTo(pnode); } } else { @@ -5967,13 +5974,13 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } } } - - + + else if (strCommand == "filterload") { CBloomFilter filter; vRecv >> filter; - + if (!filter.IsWithinSizeConstraints()) // There is no excuse for sending a too-large filter Misbehaving(pfrom->GetId(), 100); @@ -5986,13 +5993,13 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } pfrom->fRelayTxes = true; } - - + + else if (strCommand == "filteradd") { vector vData; vRecv >> vData; - + // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object, // and thus, the maximum size any matched object can have) in a filteradd message if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) @@ -6006,8 +6013,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, Misbehaving(pfrom->GetId(), 100); } } - - + + else if (strCommand == "filterclear") { LOCK(pfrom->cs_filter); @@ -6015,18 +6022,18 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->pfilter = new CBloomFilter(); pfrom->fRelayTxes = true; } - - + + else if (strCommand == "reject") { if (fDebug) { try { string strMsg; unsigned char ccode; string strReason; vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH); - + ostringstream ss; ss << strMsg << " code " << itostr(ccode) << ": " << strReason; - + if (strMsg == "block" || strMsg == "tx") { uint256 hash; @@ -6044,14 +6051,14 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, // We do not care about the NOTFOUND message, but logging an Unknown Command // message would be undesirable as we transmit it ourselves. } - + else { // Ignore unknown commands for extensibility LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id); } - - - + + + return true; } @@ -6060,7 +6067,7 @@ bool ProcessMessages(CNode* pfrom) { //if (fDebug) // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size()); - + // // Message format // (4) message start @@ -6070,41 +6077,41 @@ bool ProcessMessages(CNode* pfrom) // (x) data // bool fOk = true; - + if (!pfrom->vRecvGetData.empty()) ProcessGetData(pfrom); - + // this maintains the order of responses if (!pfrom->vRecvGetData.empty()) return fOk; - + std::deque::iterator it = pfrom->vRecvMsg.begin(); while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) { // Don't bother if send buffer is too full to respond anyway if (pfrom->nSendSize >= SendBufferSize()) break; - + // get next message CNetMessage& msg = *it; - + //if (fDebug) // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__, // msg.hdr.nMessageSize, msg.vRecv.size(), // msg.complete() ? "Y" : "N"); - + // end, if an incomplete message is found if (!msg.complete()) break; - + // at this point, any failure means we can delete the current message it++; - + // Scan for message start if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) { LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id); fOk = false; break; } - + // Read header CMessageHeader& hdr = msg.hdr; if (!hdr.IsValid(Params().MessageStart())) @@ -6113,10 +6120,10 @@ bool ProcessMessages(CNode* pfrom) continue; } string strCommand = hdr.GetCommand(); - + // Message size unsigned int nMessageSize = hdr.nMessageSize; - + // Checksum CDataStream& vRecv = msg.vRecv; uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); @@ -6124,10 +6131,10 @@ bool ProcessMessages(CNode* pfrom) if (nChecksum != hdr.nChecksum) { LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__, - SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum); + SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum); continue; } - + // Process message bool fRet = false; try @@ -6161,17 +6168,17 @@ bool ProcessMessages(CNode* pfrom) } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } - + if (!fRet) LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id); - + break; } - + // In case the connection got shut down, its receive buffer was wiped if (!pfrom->fDisconnect) pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it); - + return fOk; } @@ -6183,7 +6190,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) // Don't send anything until we get its version message if (pto->nVersion == 0) return true; - + // // Message: ping // @@ -6212,11 +6219,11 @@ bool SendMessages(CNode* pto, bool fSendTrickle) pto->PushMessage("ping"); } } - + TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState() if (!lockMain) return true; - + // Address refresh broadcast static int64_t nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) @@ -6227,14 +6234,14 @@ bool SendMessages(CNode* pto, bool fSendTrickle) // Periodically clear addrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->addrKnown.reset(); - + // Rebroadcast our address AdvertizeLocal(pnode); } if (!vNodes.empty()) nLastRebroadcast = GetTime(); } - + // // Message: addr // @@ -6260,7 +6267,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } - + CNodeState &state = *State(pto->GetId()); if (state.fShouldBan) { if (pto->fWhitelisted) @@ -6276,11 +6283,11 @@ bool SendMessages(CNode* pto, bool fSendTrickle) } state.fShouldBan = false; } - + BOOST_FOREACH(const CBlockReject& reject, state.rejects) - pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock); + pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock); state.rejects.clear(); - + // Start block sync if (pindexBestHeader == NULL) pindexBestHeader = chainActive.Tip(); @@ -6295,7 +6302,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256()); } } - + // Resend wallet transactions that haven't gotten in a block yet // Except during reindex, importing and IBD, when old wallet // transactions become unconfirmed and spams other nodes. @@ -6303,7 +6310,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) { GetMainSignals().Broadcast(nTimeBestReceived); } - + // // Message: inventory // @@ -6317,7 +6324,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) { if (pto->setInventoryKnown.count(inv)) continue; - + // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { @@ -6328,14 +6335,14 @@ bool SendMessages(CNode* pto, bool fSendTrickle) uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0); - + if (fTrickleWait) { vInvWait.push_back(inv); continue; } } - + // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { @@ -6351,7 +6358,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) } if (!vInv.empty()) pto->PushMessage("inv", vInv); - + // Detect whether we're stalling int64_t nNow = GetTimeMicros(); if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) { @@ -6383,7 +6390,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) pto->fDisconnect = true; } } - + // // Message: getdata (blocks) // @@ -6396,7 +6403,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash())); MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex); LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(), - pindex->nHeight, pto->id); + pindex->nHeight, pto->id); } if (state.nBlocksInFlight == 0 && staller != -1) { if (State(staller)->nStallingSince == 0) { @@ -6405,7 +6412,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) } } } - + // // Message: getdata (non-blocks) // @@ -6430,14 +6437,14 @@ bool SendMessages(CNode* pto, bool fSendTrickle) } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); - + } return true; } - std::string CBlockFileInfo::ToString() const { - return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast)); - } +std::string CBlockFileInfo::ToString() const { + return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast)); +} @@ -6451,7 +6458,7 @@ public: for (; it1 != mapBlockIndex.end(); it1++) delete (*it1).second; mapBlockIndex.clear(); - + // orphan transactions mapOrphanTransactions.clear(); mapOrphanTransactionsByPrev.clear(); @@ -6460,7 +6467,7 @@ public: extern "C" const char* getDataDir() { - return GetDataDir().string().c_str(); + return GetDataDir().string().c_str(); } @@ -6468,14 +6475,14 @@ extern "C" const char* getDataDir() CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight) { CMutableTransaction mtx; - + bool isOverwintered = NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_OVERWINTER); if (isOverwintered) { mtx.fOverwintered = true; mtx.nVersionGroupId = OVERWINTER_VERSION_GROUP_ID; mtx.nVersion = 3; // Expiry height is not set. Only fields required for a parser to treat as a valid Overwinter V3 tx. - + // TODO: In future, when moving from Overwinter to Sapling, it will be useful // to set the expiry height to: min(activation_height - 1, default_expiry_height) } From 88169fac222932ab2e189028038f301c20bc57c1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 21:36:16 +0300 Subject: [PATCH 272/507] Add debug prints --- src/main.cpp | 17 +++++++++-------- src/miner.cpp | 5 +++-- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 48324ca42..a8f5d80be 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2234,11 +2234,6 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin const CChainParams& chainparams = Params(); //fprintf(stderr,"connectblock ht.%d\n",(int32_t)pindex->nHeight); AssertLockHeld(cs_main); -/*<<<<<<< HEA - // Check it again in case a previous version let a bad block in - bool fExpensiveChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints())); -======= -*/ bool fExpensiveChecks = true; if (fCheckpointsEnabled) { CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints()); @@ -3332,7 +3327,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta CBlockIndex *heightblock = chainActive[nHeight]; if ( heightblock != 0 && heightblock->GetBlockHash() == hash ) { - //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); + fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); return true; } return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),REJECT_CHECKPOINT, "checkpoint mismatch"); } @@ -3346,7 +3341,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta CBlockIndex *heightblock = chainActive[nHeight]; if ( heightblock != 0 && heightblock->GetBlockHash() == hash ) { - //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); + fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); return true; } else return state.DoS(100, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height)); } @@ -3436,7 +3431,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc if (!ContextualCheckBlockHeader(block, state, pindexPrev)) { pindex->nStatus |= BLOCK_FAILED_MASK; - //fprintf(stderr,"known block.%d failing ContextualCheckBlockHeader\n",(int32_t)pindex->nHeight); + fprintf(stderr,"known block.%d failing ContextualCheckBlockHeader\n",(int32_t)pindex->nHeight); return false; } } @@ -3444,7 +3439,10 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc } if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state)) + { + fprintf(stderr,"AcceptBlock CheckBlockHeader failed\n"); return false; + } // Get prev block index CBlockIndex* pindexPrev = NULL; @@ -3457,7 +3455,10 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk"); } if (!ContextualCheckBlockHeader(block, state, pindexPrev)) + { + fprintf(stderr,"AcceptBlock ContextualCheckBlockHeader failed\n"); return false; + } if (pindex == NULL) pindex = AddToBlockIndex(block); if (ppindex) diff --git a/src/miner.cpp b/src/miner.cpp index 7c44915d2..692d984ba 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -396,6 +396,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) // Add fees txNew.vout[0].nValue += nFees; txNew.vin[0].scriptSig = CScript() << nHeight << OP_0; +#ifdef nomore if ( ASSETCHAINS_SYMBOL[0] == 0 ) { /*int32_t i,opretlen; uint8_t opret[256],*ptr; @@ -419,7 +420,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) if ( txNew.vout.size() > 1 ) fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size()); } - +#endif pblock->vtx[0] = txNew; pblocktemplate->vTxFees[0] = -nFees; // Randomise nonce @@ -441,7 +442,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) { static uint32_t counter; - if ( counter++ < 100 ) + //if ( counter++ < 100 ) fprintf(stderr,"warning: testblockvalidity failed\n"); return(0); } From f56990f6f7c1742c93fc71867312d645a5246ba3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 21:57:24 +0300 Subject: [PATCH 273/507] Test --- src/main.cpp | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index a8f5d80be..1f4d00cf5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3021,8 +3021,12 @@ CBlockIndex* AddToBlockIndex(const CBlockHeader& block) // Check for duplicate uint256 hash = block.GetHash(); BlockMap::iterator it = mapBlockIndex.find(hash); - if (it != mapBlockIndex.end()) - return it->second; + if (it != mapBlockIndex.end() ) + { + if ( it->second != 0 ) + return it->second; + else fprintf(stderr,"AddToBlockIndex unexpected null it->second\n"); + } // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(block); @@ -3327,7 +3331,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta CBlockIndex *heightblock = chainActive[nHeight]; if ( heightblock != 0 && heightblock->GetBlockHash() == hash ) { - fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); + //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); return true; } return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),REJECT_CHECKPOINT, "checkpoint mismatch"); } @@ -3435,7 +3439,8 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return false; } } - return true; + fprintf(stderr,"return true pindex.%p %ppindex.%p\n",pindex,*ppindex); + return true; } if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state)) @@ -3460,7 +3465,10 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return false; } if (pindex == NULL) - pindex = AddToBlockIndex(block); + { + if ( (pindex= AddToBlockIndex(block)) == 0 ) + fprintf(stderr,"AcceptBlockHeader couldnt create pindex\n"); + } if (ppindex) *ppindex = pindex; return true; From ee8a0545c0a5d56b43c2d728c5cb2e6ce70261ad Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 21:59:12 +0300 Subject: [PATCH 274/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 1f4d00cf5..66f9ddf33 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3439,7 +3439,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return false; } } - fprintf(stderr,"return true pindex.%p %ppindex.%p\n",pindex,*ppindex); + fprintf(stderr,"return true pindex.%p ppindex.%p\n",pindex,*ppindex); return true; } From fc99365175a909dd45001ba1ba72be46b06754eb Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 22:05:04 +0300 Subject: [PATCH 275/507] Test --- src/main.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 66f9ddf33..884fcdf36 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3439,7 +3439,8 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return false; } } - fprintf(stderr,"return true pindex.%p ppindex.%p\n",pindex,*ppindex); + if ( pindex != *ppindex ) + fprintf(stderr,"return true ht.%d pindex.%p ppindex.%p\n",pindex->nHeight,pindex,*ppindex); return true; } From 4751ae3e8f96c6baa0bdf697f45a65db7a8420db Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 22:10:48 +0300 Subject: [PATCH 276/507] Test --- src/komodo_notary.h | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index e7ae7d738..ccb4ef859 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -202,8 +202,8 @@ uint32_t komodo_heightstamp(int32_t height); int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) { - static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1; - int32_t i,htind,n; uint64_t mask = 0; struct knotary_entry *kp,*tmp; + static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1,n0,n1; + int32_t i,htind; uint64_t mask = 0; struct knotary_entry *kp,*tmp; if ( timestamp == 0 && ASSETCHAINS_SYMBOL[0] != 0 ) timestamp = komodo_heightstamp(height); else if ( ASSETCHAINS_SYMBOL[0] == 0 ) @@ -214,27 +214,27 @@ int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestam { if ( did0 == 0 ) { - n = (int32_t)(sizeof(Notaries_elected0)/sizeof(*Notaries_elected0)); - for (i=0; i Date: Sun, 15 Apr 2018 22:23:00 +0300 Subject: [PATCH 277/507] N -> static n0/n1 --- src/komodo_notary.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index ccb4ef859..0de2a2c22 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -203,7 +203,7 @@ uint32_t komodo_heightstamp(int32_t height); int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) { static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1,n0,n1; - int32_t i,htind; uint64_t mask = 0; struct knotary_entry *kp,*tmp; + int32_t i,htind,n; uint64_t mask = 0; struct knotary_entry *kp,*tmp; if ( timestamp == 0 && ASSETCHAINS_SYMBOL[0] != 0 ) timestamp = komodo_heightstamp(height); else if ( ASSETCHAINS_SYMBOL[0] == 0 ) @@ -222,6 +222,7 @@ int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestam memcpy(pubkeys,elected_pubkeys0,n0 * 33); //if ( ASSETCHAINS_SYMBOL[0] != 0 ) //fprintf(stderr,"%s height.%d t.%u elected.%d notaries\n",ASSETCHAINS_SYMBOL,height,timestamp,n0); + return(n0); } else //if ( (timestamp != 0 && timestamp <= KOMODO_NOTARIES_TIMESTAMP2) || height <= KOMODO_NOTARIES_HEIGHT2 ) { @@ -235,8 +236,8 @@ int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestam did1 = 1; } memcpy(pubkeys,elected_pubkeys1,n1 * 33); + return(n1); } - return(n); } htind = height / KOMODO_ELECTION_GAP; if ( htind >= KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP ) From 14c144030af73a5315a6da9fc211d689abd24c13 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 22:33:44 +0300 Subject: [PATCH 278/507] Fix non-static n -> n0/n1 --- src/komodo_notary.h | 21 +++++++++++---------- src/miner.cpp | 1 - 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index cce57596b..3c2819df5 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -199,7 +199,7 @@ const char *Notaries_elected1[][2] = int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) { - static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1; + static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1; static int32_t n0,n1; int32_t i,htind,n; uint64_t mask = 0; struct knotary_entry *kp,*tmp; if ( timestamp == 0 && ASSETCHAINS_SYMBOL[0] != 0 ) timestamp = komodo_heightstamp(height); @@ -211,29 +211,30 @@ int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestam { if ( did0 == 0 ) { - n = (int32_t)(sizeof(Notaries_elected0)/sizeof(*Notaries_elected0)); - for (i=0; i= KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP ) diff --git a/src/miner.cpp b/src/miner.cpp index fc5bcfb12..a732aa56b 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -689,7 +689,6 @@ void static BitcoinMiner() if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) break; } - //sleep(60); komodo_chosennotary(¬aryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime()); std::string solver; From 2233e3dc3c062b0324b380470b19543867ed3e71 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 22:39:57 +0300 Subject: [PATCH 279/507] -print --- src/komodo_notary.h | 2 +- src/main.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 0de2a2c22..2a6c729b4 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -202,7 +202,7 @@ uint32_t komodo_heightstamp(int32_t height); int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) { - static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1,n0,n1; + static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1; static in32_t n0,n1; int32_t i,htind,n; uint64_t mask = 0; struct knotary_entry *kp,*tmp; if ( timestamp == 0 && ASSETCHAINS_SYMBOL[0] != 0 ) timestamp = komodo_heightstamp(height); diff --git a/src/main.cpp b/src/main.cpp index 884fcdf36..9bcab1b17 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3345,7 +3345,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta CBlockIndex *heightblock = chainActive[nHeight]; if ( heightblock != 0 && heightblock->GetBlockHash() == hash ) { - fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); + //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); return true; } else return state.DoS(100, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height)); } From d8b4fa6d74e627273797c2f652f3675f7af7a468 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 22:42:01 +0300 Subject: [PATCH 280/507] syntax --- src/komodo_notary.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 2a6c729b4..0f9779129 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -202,7 +202,7 @@ uint32_t komodo_heightstamp(int32_t height); int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) { - static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1; static in32_t n0,n1; + static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1; static int32_t n0,n1; int32_t i,htind,n; uint64_t mask = 0; struct knotary_entry *kp,*tmp; if ( timestamp == 0 && ASSETCHAINS_SYMBOL[0] != 0 ) timestamp = komodo_heightstamp(height); From 63d286cd0ebd8705e3107e9a4699644080a646fa Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 22:59:05 +0300 Subject: [PATCH 281/507] Test --- src/main.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main.cpp b/src/main.cpp index 9bcab1b17..80bf7ea52 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3406,6 +3406,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc *ppindex = pindex; if (pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK) return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); +#ifdef notnow if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 { if (!CheckBlockHeader(pindex->nHeight,pindex, block, state)) @@ -3441,6 +3442,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc } if ( pindex != *ppindex ) fprintf(stderr,"return true ht.%d pindex.%p ppindex.%p\n",pindex->nHeight,pindex,*ppindex); +#endif return true; } From 03e2210d24eec049b967a699527370d39d8e9355 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:22:22 +0300 Subject: [PATCH 282/507] Test --- src/main.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index fa66fdb12..8f3ea6108 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -54,6 +54,7 @@ using namespace std; CCriticalSection cs_main; extern uint8_t NOTARY_PUBKEY33[33]; extern int32_t KOMODO_LOADINGBLOCKS,KOMODO_LONGESTCHAIN; +int32_t KOMODO_NEWBLOCKS; void komodo_block2pubkey33(uint8_t *pubkey33,CBlock *block); BlockMap mapBlockIndex; @@ -2801,7 +2802,7 @@ void static UpdateTip(CBlockIndex *pindexNew) { // New best block nTimeBestReceived = GetTime(); mempool.AddTransactionsUpdated(1); - + KOMODO_NEWBLOCKS++; LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__, chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), @@ -3529,11 +3530,13 @@ int32_t komodo_reverify_blockcheck(CValidationState& state,int32_t height,CBlock if ( oneshot == 0 && IsInitialBlockDownload() == 0 && (tipindex= chainActive.Tip()) != 0 ) { // if 200 blocks behind longestchain and no blocks for 2 hours - if ( KOMODO_LONGESTCHAIN > height+200 ) + if ( KOMODO_LONGESTCHAIN > height+200 && KOMODO_NEWBLOCKS == 0 ) { if ( GetAdjustedTime() > tipindex->nTime+3600*2 ) { fprintf(stderr,"tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),tipindex->nTime); + KOMODO_REWIND = tipindex->nHeight - 11; + /* rewindtarget = tipindex->nHeight - 11; fprintf(stderr,"rewindtarget <- %d\n",rewindtarget); oneshot = 1; @@ -3545,7 +3548,7 @@ int32_t komodo_reverify_blockcheck(CValidationState& state,int32_t height,CBlock break; } tipindex = chainActive.Tip(); - fprintf(stderr,"rewind done to %d\n",tipindex!=0?tipindex->nHeight:-1); + fprintf(stderr,"rewind done to %d\n",tipindex!=0?tipindex->nHeight:-1);*/ } } } From a2c379fbcba6259132e03fa19476416e870e145c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:29:28 +0300 Subject: [PATCH 283/507] Test --- src/miner.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 692d984ba..4e8f5dd0b 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -774,13 +774,13 @@ void static BitcoinMiner() if ( i == 33 ) externalflag = 1; else externalflag = 0; - if ( NOTARY_PUBKEY33[0] != 0 && (notaryid < 3 || notaryid == 34 || notaryid == 51 || notaryid == 52) ) + if ( NOTARY_PUBKEY33[0] != 0 && notaryid < 3 ) { for (i=1; i<66; i++) if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 ) break; - if ( externalflag == 0 && i != 66 ) - printf("VIOLATION at %d\n",i); + if ( externalflag == 0 && i != 66 && mids[0] >= 0 ) + printf("VIOLATION at %d mids[0] %d vs mids[%d] %d\n",i,mids[0],i,mids[i]); for (i=0; i<66; i++) { break; for (j=0; j<33; j++) From 3b380b6b0a5991b3220323ddd7b71e3be97c75a6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:29:52 +0300 Subject: [PATCH 284/507] Revert "Test" This reverts commit a2c379fbcba6259132e03fa19476416e870e145c. --- src/miner.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 4e8f5dd0b..692d984ba 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -774,13 +774,13 @@ void static BitcoinMiner() if ( i == 33 ) externalflag = 1; else externalflag = 0; - if ( NOTARY_PUBKEY33[0] != 0 && notaryid < 3 ) + if ( NOTARY_PUBKEY33[0] != 0 && (notaryid < 3 || notaryid == 34 || notaryid == 51 || notaryid == 52) ) { for (i=1; i<66; i++) if ( memcmp(pubkeys[i],pubkeys[0],33) == 0 ) break; - if ( externalflag == 0 && i != 66 && mids[0] >= 0 ) - printf("VIOLATION at %d mids[0] %d vs mids[%d] %d\n",i,mids[0],i,mids[i]); + if ( externalflag == 0 && i != 66 ) + printf("VIOLATION at %d\n",i); for (i=0; i<66; i++) { break; for (j=0; j<33; j++) From 15e0680bd272059dbf92523423116dd7c1a38b19 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:29:58 +0300 Subject: [PATCH 285/507] Revert "Test" This reverts commit 63d286cd0ebd8705e3107e9a4699644080a646fa. --- src/main.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 80bf7ea52..9bcab1b17 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3406,7 +3406,6 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc *ppindex = pindex; if (pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK) return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); -#ifdef notnow if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 { if (!CheckBlockHeader(pindex->nHeight,pindex, block, state)) @@ -3442,7 +3441,6 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc } if ( pindex != *ppindex ) fprintf(stderr,"return true ht.%d pindex.%p ppindex.%p\n",pindex->nHeight,pindex,*ppindex); -#endif return true; } From 0370d2edd684180e5835fbd5f17f9f4ccb9bea1a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:30:07 +0300 Subject: [PATCH 286/507] Revert "syntax" This reverts commit d8b4fa6d74e627273797c2f652f3675f7af7a468. --- src/komodo_notary.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 0f9779129..2a6c729b4 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -202,7 +202,7 @@ uint32_t komodo_heightstamp(int32_t height); int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) { - static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1; static int32_t n0,n1; + static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1; static in32_t n0,n1; int32_t i,htind,n; uint64_t mask = 0; struct knotary_entry *kp,*tmp; if ( timestamp == 0 && ASSETCHAINS_SYMBOL[0] != 0 ) timestamp = komodo_heightstamp(height); From 523276e6c6b8b1341e556f09bd93ae880ba1f372 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:30:12 +0300 Subject: [PATCH 287/507] Revert "-print" This reverts commit 2233e3dc3c062b0324b380470b19543867ed3e71. --- src/komodo_notary.h | 2 +- src/main.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 2a6c729b4..0de2a2c22 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -202,7 +202,7 @@ uint32_t komodo_heightstamp(int32_t height); int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) { - static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1; static in32_t n0,n1; + static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1,n0,n1; int32_t i,htind,n; uint64_t mask = 0; struct knotary_entry *kp,*tmp; if ( timestamp == 0 && ASSETCHAINS_SYMBOL[0] != 0 ) timestamp = komodo_heightstamp(height); diff --git a/src/main.cpp b/src/main.cpp index 9bcab1b17..884fcdf36 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3345,7 +3345,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta CBlockIndex *heightblock = chainActive[nHeight]; if ( heightblock != 0 && heightblock->GetBlockHash() == hash ) { - //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); + fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); return true; } else return state.DoS(100, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height)); } From ec50c8817ac0a16478eab6804f7958f373db09a8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:30:42 +0300 Subject: [PATCH 288/507] Revert "N -> static n0/n1" This reverts commit da58058de8823ec251d0a1b373bf4cfc8da8f953. --- src/komodo_notary.h | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 0de2a2c22..ccb4ef859 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -203,7 +203,7 @@ uint32_t komodo_heightstamp(int32_t height); int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) { static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1,n0,n1; - int32_t i,htind,n; uint64_t mask = 0; struct knotary_entry *kp,*tmp; + int32_t i,htind; uint64_t mask = 0; struct knotary_entry *kp,*tmp; if ( timestamp == 0 && ASSETCHAINS_SYMBOL[0] != 0 ) timestamp = komodo_heightstamp(height); else if ( ASSETCHAINS_SYMBOL[0] == 0 ) @@ -222,7 +222,6 @@ int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestam memcpy(pubkeys,elected_pubkeys0,n0 * 33); //if ( ASSETCHAINS_SYMBOL[0] != 0 ) //fprintf(stderr,"%s height.%d t.%u elected.%d notaries\n",ASSETCHAINS_SYMBOL,height,timestamp,n0); - return(n0); } else //if ( (timestamp != 0 && timestamp <= KOMODO_NOTARIES_TIMESTAMP2) || height <= KOMODO_NOTARIES_HEIGHT2 ) { @@ -236,8 +235,8 @@ int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestam did1 = 1; } memcpy(pubkeys,elected_pubkeys1,n1 * 33); - return(n1); } + return(n); } htind = height / KOMODO_ELECTION_GAP; if ( htind >= KOMODO_MAXBLOCKS / KOMODO_ELECTION_GAP ) From 598c8173df3ce6ad57b43510f7c22a03946ef6ea Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:30:47 +0300 Subject: [PATCH 289/507] Revert "Test" This reverts commit 4751ae3e8f96c6baa0bdf697f45a65db7a8420db. --- src/komodo_notary.h | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index ccb4ef859..e7ae7d738 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -202,8 +202,8 @@ uint32_t komodo_heightstamp(int32_t height); int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestamp) { - static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1,n0,n1; - int32_t i,htind; uint64_t mask = 0; struct knotary_entry *kp,*tmp; + static uint8_t elected_pubkeys0[64][33],elected_pubkeys1[64][33],did0,did1; + int32_t i,htind,n; uint64_t mask = 0; struct knotary_entry *kp,*tmp; if ( timestamp == 0 && ASSETCHAINS_SYMBOL[0] != 0 ) timestamp = komodo_heightstamp(height); else if ( ASSETCHAINS_SYMBOL[0] == 0 ) @@ -214,27 +214,27 @@ int32_t komodo_notaries(uint8_t pubkeys[64][33],int32_t height,uint32_t timestam { if ( did0 == 0 ) { - n0 = (int32_t)(sizeof(Notaries_elected0)/sizeof(*Notaries_elected0)); - for (i=0; i Date: Sun, 15 Apr 2018 23:30:52 +0300 Subject: [PATCH 290/507] Revert "Test" This reverts commit fc99365175a909dd45001ba1ba72be46b06754eb. --- src/main.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 884fcdf36..66f9ddf33 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3439,8 +3439,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return false; } } - if ( pindex != *ppindex ) - fprintf(stderr,"return true ht.%d pindex.%p ppindex.%p\n",pindex->nHeight,pindex,*ppindex); + fprintf(stderr,"return true pindex.%p ppindex.%p\n",pindex,*ppindex); return true; } From 397094b904495c8039f88e47f8f1bf63a5f50895 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:30:57 +0300 Subject: [PATCH 291/507] Revert "Test" This reverts commit ee8a0545c0a5d56b43c2d728c5cb2e6ce70261ad. --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 66f9ddf33..1f4d00cf5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3439,7 +3439,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return false; } } - fprintf(stderr,"return true pindex.%p ppindex.%p\n",pindex,*ppindex); + fprintf(stderr,"return true pindex.%p %ppindex.%p\n",pindex,*ppindex); return true; } From dbd87e657cfe6437333c3957a9fdae7d00e94f42 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:31:01 +0300 Subject: [PATCH 292/507] Revert "Test" This reverts commit f56990f6f7c1742c93fc71867312d645a5246ba3. --- src/main.cpp | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 1f4d00cf5..a8f5d80be 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3021,12 +3021,8 @@ CBlockIndex* AddToBlockIndex(const CBlockHeader& block) // Check for duplicate uint256 hash = block.GetHash(); BlockMap::iterator it = mapBlockIndex.find(hash); - if (it != mapBlockIndex.end() ) - { - if ( it->second != 0 ) - return it->second; - else fprintf(stderr,"AddToBlockIndex unexpected null it->second\n"); - } + if (it != mapBlockIndex.end()) + return it->second; // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(block); @@ -3331,7 +3327,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta CBlockIndex *heightblock = chainActive[nHeight]; if ( heightblock != 0 && heightblock->GetBlockHash() == hash ) { - //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); + fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); return true; } return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),REJECT_CHECKPOINT, "checkpoint mismatch"); } @@ -3439,8 +3435,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return false; } } - fprintf(stderr,"return true pindex.%p %ppindex.%p\n",pindex,*ppindex); - return true; + return true; } if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state)) @@ -3465,10 +3460,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return false; } if (pindex == NULL) - { - if ( (pindex= AddToBlockIndex(block)) == 0 ) - fprintf(stderr,"AcceptBlockHeader couldnt create pindex\n"); - } + pindex = AddToBlockIndex(block); if (ppindex) *ppindex = pindex; return true; From 828ceb32932809e530162fc412ef672b7dc6af75 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:31:05 +0300 Subject: [PATCH 293/507] Revert "Add debug prints" This reverts commit 88169fac222932ab2e189028038f301c20bc57c1. --- src/main.cpp | 17 ++++++++--------- src/miner.cpp | 5 ++--- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index a8f5d80be..48324ca42 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2234,6 +2234,11 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin const CChainParams& chainparams = Params(); //fprintf(stderr,"connectblock ht.%d\n",(int32_t)pindex->nHeight); AssertLockHeld(cs_main); +/*<<<<<<< HEA + // Check it again in case a previous version let a bad block in + bool fExpensiveChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints())); +======= +*/ bool fExpensiveChecks = true; if (fCheckpointsEnabled) { CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints()); @@ -3327,7 +3332,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta CBlockIndex *heightblock = chainActive[nHeight]; if ( heightblock != 0 && heightblock->GetBlockHash() == hash ) { - fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); + //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); return true; } return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),REJECT_CHECKPOINT, "checkpoint mismatch"); } @@ -3341,7 +3346,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta CBlockIndex *heightblock = chainActive[nHeight]; if ( heightblock != 0 && heightblock->GetBlockHash() == hash ) { - fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); + //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); return true; } else return state.DoS(100, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height)); } @@ -3431,7 +3436,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc if (!ContextualCheckBlockHeader(block, state, pindexPrev)) { pindex->nStatus |= BLOCK_FAILED_MASK; - fprintf(stderr,"known block.%d failing ContextualCheckBlockHeader\n",(int32_t)pindex->nHeight); + //fprintf(stderr,"known block.%d failing ContextualCheckBlockHeader\n",(int32_t)pindex->nHeight); return false; } } @@ -3439,10 +3444,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc } if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state)) - { - fprintf(stderr,"AcceptBlock CheckBlockHeader failed\n"); return false; - } // Get prev block index CBlockIndex* pindexPrev = NULL; @@ -3455,10 +3457,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk"); } if (!ContextualCheckBlockHeader(block, state, pindexPrev)) - { - fprintf(stderr,"AcceptBlock ContextualCheckBlockHeader failed\n"); return false; - } if (pindex == NULL) pindex = AddToBlockIndex(block); if (ppindex) diff --git a/src/miner.cpp b/src/miner.cpp index 692d984ba..7c44915d2 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -396,7 +396,6 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) // Add fees txNew.vout[0].nValue += nFees; txNew.vin[0].scriptSig = CScript() << nHeight << OP_0; -#ifdef nomore if ( ASSETCHAINS_SYMBOL[0] == 0 ) { /*int32_t i,opretlen; uint8_t opret[256],*ptr; @@ -420,7 +419,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) if ( txNew.vout.size() > 1 ) fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size()); } -#endif + pblock->vtx[0] = txNew; pblocktemplate->vTxFees[0] = -nFees; // Randomise nonce @@ -442,7 +441,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) { static uint32_t counter; - //if ( counter++ < 100 ) + if ( counter++ < 100 ) fprintf(stderr,"warning: testblockvalidity failed\n"); return(0); } From 30d7d83a11345789d4873c66369a4834050181e9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:31:11 +0300 Subject: [PATCH 294/507] Revert "-printf only" This reverts commit 56bd32aee3766ef13005c2ff1e72248501eb72c2. --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index e9ddd4fc0..bc7ec2bd5 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -651,7 +651,7 @@ int32_t komodo_block2height(CBlock *block) } if ( height != height2 ) { - //fprintf(stderr,"block2height height.%d vs height2.%d, match.%d mismatch.%d\n",height,height2,match,mismatch); + fprintf(stderr,"block2height height.%d vs height2.%d, match.%d mismatch.%d\n",height,height2,match,mismatch); mismatch++; if ( height2 >= 0 ) height = height2; From ecc47f43df56d38ebfc0da2b1f87057c535ccc45 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:31:18 +0300 Subject: [PATCH 295/507] Revert "Use kmdtxid" This reverts commit 52ec573ade7224f84e965f3138b1e23ec0b4b24a. --- src/komodo.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 63569e60d..bcf5be91c 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -537,9 +537,9 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&kmdtxid); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); - if ( notarized != 0 && IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[kmdtxid]) == 0 || pindex->nHeight != *notarizedheightp) ) + if ( notarized != 0 && IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != *notarizedheightp) ) { - fprintf(stderr,"%s possible FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,*notarizedheightp,kmdtxid.ToString().c_str(),sp->NOTARIZED_HEIGHT,sp->NOTARIZED_HEIGHT); + fprintf(stderr,"%s possible FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,*notarizedheightp,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,sp->NOTARIZED_HEIGHT); notarized = 0; } if ( notarized != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height && (height < sp->CURRENT_HEIGHT-1000 || komodo_verifynotarization(ASSETCHAINS_SYMBOL[0]==0?(char *)"KMD":ASSETCHAINS_SYMBOL,(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "BTC" : "KMD"),height,*notarizedheightp,kmdtxid,desttxid) == 0) ) From ad26fa2dab8d29ddf511c936bffe2dd53764bcd2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:31:23 +0300 Subject: [PATCH 296/507] Revert "Sp->NOTARIZED_HEIGHT" This reverts commit 9504daf6ef98afed029aabbeafcd176635d24550. --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index bcf5be91c..502e09d66 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -539,7 +539,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); if ( notarized != 0 && IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != *notarizedheightp) ) { - fprintf(stderr,"%s possible FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,*notarizedheightp,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,sp->NOTARIZED_HEIGHT); + fprintf(stderr,"%s possible FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,*notarizedheightp,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,rewindtarget); notarized = 0; } if ( notarized != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height && (height < sp->CURRENT_HEIGHT-1000 || komodo_verifynotarization(ASSETCHAINS_SYMBOL[0]==0?(char *)"KMD":ASSETCHAINS_SYMBOL,(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "BTC" : "KMD"),height,*notarizedheightp,kmdtxid,desttxid) == 0) ) From d3d5be30e02c613b892532eef0030dfdf846e5ba Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:31:28 +0300 Subject: [PATCH 297/507] Revert "Add realtime fork detection" This reverts commit ff5cd12f702d231d6eecc1edb7aa50cc6550dcf5. --- src/komodo.h | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 502e09d66..aba93c9e4 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -476,7 +476,7 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar int32_t komodo_voutupdate(int32_t *isratificationp,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,uint64_t value,int32_t notarized,uint64_t signedmask,uint32_t timestamp) { static uint256 zero; static FILE *signedfp; - CBlockIndex *pindex; int32_t opretlen,nid,k,len = 0; uint256 kmdtxid,desttxid; uint8_t crypto777[33]; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; + int32_t opretlen,nid,k,len = 0; uint256 kmdtxid,desttxid; uint8_t crypto777[33]; struct komodo_state *sp; char symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; if ( (sp= komodo_stateptr(symbol,dest)) == 0 ) return(-1); if ( scriptlen == 35 && scriptbuf[0] == 33 && scriptbuf[34] == 0xac ) @@ -537,11 +537,6 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&kmdtxid); len += iguana_rwnum(0,&scriptbuf[len],sizeof(*notarizedheightp),(uint8_t *)notarizedheightp); len += iguana_rwbignum(0,&scriptbuf[len],32,(uint8_t *)&desttxid); - if ( notarized != 0 && IsInitialBlockDownload() == 0 && ((pindex= mapBlockIndex[srchash]) == 0 || pindex->nHeight != *notarizedheightp) ) - { - fprintf(stderr,"%s possible FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,*notarizedheightp,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,rewindtarget); - notarized = 0; - } if ( notarized != 0 && *notarizedheightp > sp->NOTARIZED_HEIGHT && *notarizedheightp < height && (height < sp->CURRENT_HEIGHT-1000 || komodo_verifynotarization(ASSETCHAINS_SYMBOL[0]==0?(char *)"KMD":ASSETCHAINS_SYMBOL,(char *)(ASSETCHAINS_SYMBOL[0] == 0 ? "BTC" : "KMD"),height,*notarizedheightp,kmdtxid,desttxid) == 0) ) { sp->NOTARIZED_HEIGHT = *notarizedheightp; From 62c7b320ff8f0bac9aba015bfce52d904369be9c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:31:47 +0300 Subject: [PATCH 298/507] Revert "Remove printouts" This reverts commit 98dc898d4011f0ddbdce431c44bc9558b58e5bb5. --- src/komodo.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index aba93c9e4..129ea3b5f 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -189,7 +189,7 @@ int32_t komodo_parsestatefile(struct komodo_state *sp,FILE *fp,char *symbol,char //printf("load pvals ht.%d numpvals.%d\n",ht,numpvals); } else printf("error loading pvals[%d]\n",numpvals); } - // else printf("[%s] %s illegal func.(%d %c)\n",ASSETCHAINS_SYMBOL,symbol,func,func); + else printf("[%s] %s illegal func.(%d %c)\n",ASSETCHAINS_SYMBOL,symbol,func,func); return(func); } else return(-1); } @@ -319,7 +319,7 @@ int32_t komodo_parsestatefiledata(struct komodo_state *sp,uint8_t *filedata,long //printf("load pvals ht.%d numpvals.%d\n",ht,numpvals); } else printf("error loading pvals[%d]\n",numpvals); } - // else printf("[%s] %s illegal func.(%d %c)\n",ASSETCHAINS_SYMBOL,symbol,func,func); + else printf("[%s] %s illegal func.(%d %c)\n",ASSETCHAINS_SYMBOL,symbol,func,func); *fposp = fpos; return(func); } From edc77fe31f0a6173e3659315cce61faa2843950e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:31:51 +0300 Subject: [PATCH 299/507] Revert ";" This reverts commit c3e2036428ce80e7dc567384b80302174d718f9d. --- src/komodo_events.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_events.h b/src/komodo_events.h index 219d6e479..30e745051 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -58,7 +58,7 @@ void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t heig strncpy(N.dest,dest,sizeof(N.dest)-1); komodo_eventadd(sp,height,symbol,KOMODO_EVENT_NOTARIZED,(uint8_t *)&N,sizeof(N)); if ( sp != 0 ) - komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid);//,MoM,MoMdepth); + komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid)//,MoM,MoMdepth); } } From 14c6a62f7a294f3ad596d7f389c30f47702c600c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:31:55 +0300 Subject: [PATCH 300/507] Revert "Fix syntax" This reverts commit ff89a2e7d692aa5d00b97291063472ca7614f667. --- src/komodo_events.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/komodo_events.h b/src/komodo_events.h index 30e745051..c64ccbaa2 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -37,7 +37,7 @@ struct komodo_event *komodo_eventadd(struct komodo_state *sp,int32_t height,char return(ep); } -void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t height,char *dest,uint256 notarized_hash,uint256 notarized_desttxid,int32_t notarizedheight)//,uint256 MoM,int32_t MoMdepth) +void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t height,char *dest,uint256 notarized_hash,uint256 notarized_desttxid,int32_t notarizedheight,uint256 MoM,int32_t MoMdepth) { struct komodo_event_notarized N; if ( NOTARY_PUBKEY33[0] != 0 && komodo_verifynotarization(symbol,dest,height,notarizedheight,notarized_hash,notarized_desttxid) != 0 ) @@ -53,12 +53,12 @@ void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t heig N.blockhash = notarized_hash; N.desttxid = notarized_desttxid; N.notarizedheight = notarizedheight; - //N.MoM = MoM; - //N.MoMdepth = MoMdepth; + N.MoM = MoM; + N.MoMdepth = MoMdepth; strncpy(N.dest,dest,sizeof(N.dest)-1); komodo_eventadd(sp,height,symbol,KOMODO_EVENT_NOTARIZED,(uint8_t *)&N,sizeof(N)); if ( sp != 0 ) - komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid)//,MoM,MoMdepth); + komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid,MoM,MoMdepth); } } From 3b6dda83b15ee0e7bce601d8fc53e07b6649d065 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:32:11 +0300 Subject: [PATCH 301/507] Revert "Fix possible buffer overflow and reduce KMD memory usage" This reverts commit 28616d3592fa82d114372b8823896655fa91fe26. --- src/komodo_events.h | 102 ++++++++++++++++++++------------------------ 1 file changed, 46 insertions(+), 56 deletions(-) diff --git a/src/komodo_events.h b/src/komodo_events.h index c64ccbaa2..ff054c3bb 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2018 The SuperNET Developers. * + * Copyright © 2014-2017 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * @@ -20,7 +20,7 @@ struct komodo_event *komodo_eventadd(struct komodo_state *sp,int32_t height,char *symbol,uint8_t type,uint8_t *data,uint16_t datalen) { struct komodo_event *ep=0; uint16_t len = (uint16_t)(sizeof(*ep) + datalen); - if ( sp != 0 && ASSETCHAINS_SYMBOL[0] != 0 ) + if ( sp != 0 ) { portable_mutex_lock(&komodo_mutex); ep = (struct komodo_event *)calloc(1,len); @@ -37,10 +37,10 @@ struct komodo_event *komodo_eventadd(struct komodo_state *sp,int32_t height,char return(ep); } -void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t height,char *dest,uint256 notarized_hash,uint256 notarized_desttxid,int32_t notarizedheight,uint256 MoM,int32_t MoMdepth) +void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t height,char *dest,uint256 notarized_hash,uint256 notarized_desttxid,int32_t notarizedheight) { struct komodo_event_notarized N; - if ( NOTARY_PUBKEY33[0] != 0 && komodo_verifynotarization(symbol,dest,height,notarizedheight,notarized_hash,notarized_desttxid) != 0 ) + if ( komodo_verifynotarization(symbol,dest,height,notarizedheight,notarized_hash,notarized_desttxid) != 0 ) { if ( height > 50000 || ASSETCHAINS_SYMBOL[0] != 0 ) printf("[%s] error validating notarization ht.%d notarized_height.%d, if on a pruned %s node this can be ignored\n",ASSETCHAINS_SYMBOL,height,notarizedheight,dest); @@ -53,12 +53,10 @@ void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t heig N.blockhash = notarized_hash; N.desttxid = notarized_desttxid; N.notarizedheight = notarizedheight; - N.MoM = MoM; - N.MoMdepth = MoMdepth; - strncpy(N.dest,dest,sizeof(N.dest)-1); + strcpy(N.dest,dest); komodo_eventadd(sp,height,symbol,KOMODO_EVENT_NOTARIZED,(uint8_t *)&N,sizeof(N)); if ( sp != 0 ) - komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid,MoM,MoMdepth); + komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid); } } @@ -77,34 +75,27 @@ void komodo_eventadd_pubkeys(struct komodo_state *sp,char *symbol,int32_t height void komodo_eventadd_pricefeed(struct komodo_state *sp,char *symbol,int32_t height,uint32_t *prices,uint8_t num) { struct komodo_event_pricefeed F; - if ( num == sizeof(F.prices)/sizeof(*F.prices) ) - { - memset(&F,0,sizeof(F)); - F.num = num; - memcpy(F.prices,prices,sizeof(*F.prices) * num); - komodo_eventadd(sp,height,symbol,KOMODO_EVENT_PRICEFEED,(uint8_t *)&F,(int32_t)(sizeof(F.num) + sizeof(*F.prices) * num)); - if ( sp != 0 ) - komodo_pvals(height,prices,num); - } //else fprintf(stderr,"skip pricefeed[%d]\n",num); + memset(&F,0,sizeof(F)); + F.num = num; + memcpy(F.prices,prices,sizeof(*F.prices) * num); + komodo_eventadd(sp,height,symbol,KOMODO_EVENT_PRICEFEED,(uint8_t *)&F,(int32_t)(sizeof(F.num) + sizeof(*F.prices) * num)); + if ( sp != 0 ) + komodo_pvals(height,prices,num); } void komodo_eventadd_opreturn(struct komodo_state *sp,char *symbol,int32_t height,uint256 txid,uint64_t value,uint16_t vout,uint8_t *buf,uint16_t opretlen) { - struct komodo_event_opreturn O; uint8_t *opret; - if ( ASSETCHAINS_SYMBOL[0] != 0 ) - { - opret = (uint8_t *)calloc(1,sizeof(O) + opretlen + 16); - O.txid = txid; - O.value = value; - O.vout = vout; - memcpy(opret,&O,sizeof(O)); - memcpy(&opret[sizeof(O)],buf,opretlen); - O.oplen = (int32_t)(opretlen + sizeof(O)); - komodo_eventadd(sp,height,symbol,KOMODO_EVENT_OPRETURN,opret,O.oplen); - free(opret); - if ( sp != 0 ) - komodo_opreturn(height,value,buf,opretlen,txid,vout,symbol); - } + struct komodo_event_opreturn O; uint8_t opret[16384]; + memset(&O,0,sizeof(O)); + O.txid = txid; + O.value = value; + O.vout = vout; + memcpy(opret,&O,sizeof(O)); + memcpy(&opret[sizeof(O)],buf,opretlen); + O.oplen = (int32_t)(opretlen + sizeof(O)); + komodo_eventadd(sp,height,symbol,KOMODO_EVENT_OPRETURN,opret,O.oplen); + if ( sp != 0 ) + komodo_opreturn(height,value,buf,opretlen,txid,vout,symbol); } void komodo_event_undo(struct komodo_state *sp,struct komodo_event *ep) @@ -178,7 +169,6 @@ void komodo_eventadd_kmdheight(struct komodo_state *sp,char *symbol,int32_t heig } else { - //fprintf(stderr,"REWIND kmdheight.%d\n",kmdheight); kmdheight = -kmdheight; komodo_eventadd(sp,height,symbol,KOMODO_EVENT_REWIND,(uint8_t *)&height,sizeof(height)); if ( sp != 0 ) @@ -188,30 +178,30 @@ void komodo_eventadd_kmdheight(struct komodo_state *sp,char *symbol,int32_t heig /*void komodo_eventadd_deposit(int32_t actionflag,char *symbol,int32_t height,uint64_t komodoshis,char *fiat,uint64_t fiatoshis,uint8_t rmd160[20],bits256 kmdtxid,uint16_t kmdvout,uint64_t price) - { - uint8_t opret[512]; uint16_t opretlen; - komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_DEPOSIT,kmdtxid,komodoshis,kmdvout,opret,opretlen); - } - - void komodo_eventadd_issued(int32_t actionflag,char *symbol,int32_t height,int32_t fiatheight,bits256 fiattxid,uint16_t fiatvout,bits256 kmdtxid,uint16_t kmdvout,uint64_t fiatoshis) - { - uint8_t opret[512]; uint16_t opretlen; - komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_ISSUED,fiattxid,fiatoshis,fiatvout,opret,opretlen); - } - - void komodo_eventadd_withdraw(int32_t actionflag,char *symbol,int32_t height,uint64_t komodoshis,char *fiat,uint64_t fiatoshis,uint8_t rmd160[20],bits256 fiattxid,int32_t fiatvout,uint64_t price) - { - uint8_t opret[512]; uint16_t opretlen; - komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_WITHDRAW,fiattxid,fiatoshis,fiatvout,opret,opretlen); - } - - void komodo_eventadd_redeemed(int32_t actionflag,char *symbol,int32_t height,bits256 kmdtxid,uint16_t kmdvout,int32_t fiatheight,bits256 fiattxid,uint16_t fiatvout,uint64_t komodoshis) - { - uint8_t opret[512]; uint16_t opretlen; - komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_REDEEMED,kmdtxid,komodoshis,kmdvout,opret,opretlen); - }*/ +{ + uint8_t opret[512]; uint16_t opretlen; + komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_DEPOSIT,kmdtxid,komodoshis,kmdvout,opret,opretlen); +} + +void komodo_eventadd_issued(int32_t actionflag,char *symbol,int32_t height,int32_t fiatheight,bits256 fiattxid,uint16_t fiatvout,bits256 kmdtxid,uint16_t kmdvout,uint64_t fiatoshis) +{ + uint8_t opret[512]; uint16_t opretlen; + komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_ISSUED,fiattxid,fiatoshis,fiatvout,opret,opretlen); +} + +void komodo_eventadd_withdraw(int32_t actionflag,char *symbol,int32_t height,uint64_t komodoshis,char *fiat,uint64_t fiatoshis,uint8_t rmd160[20],bits256 fiattxid,int32_t fiatvout,uint64_t price) +{ + uint8_t opret[512]; uint16_t opretlen; + komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_WITHDRAW,fiattxid,fiatoshis,fiatvout,opret,opretlen); +} + +void komodo_eventadd_redeemed(int32_t actionflag,char *symbol,int32_t height,bits256 kmdtxid,uint16_t kmdvout,int32_t fiatheight,bits256 fiattxid,uint16_t fiatvout,uint64_t komodoshis) +{ + uint8_t opret[512]; uint16_t opretlen; + komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_REDEEMED,kmdtxid,komodoshis,kmdvout,opret,opretlen); +}*/ // process events -// +// #endif From dbed0ea52fe34d9da78fe5861a42472babc53031 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:38:48 +0300 Subject: [PATCH 302/507] Add back events overflow protection --- src/komodo_events.h | 102 ++++++++++++++++++++++++-------------------- 1 file changed, 56 insertions(+), 46 deletions(-) diff --git a/src/komodo_events.h b/src/komodo_events.h index ff054c3bb..0196f1646 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -1,5 +1,5 @@ /****************************************************************************** - * Copyright © 2014-2017 The SuperNET Developers. * + * Copyright © 2014-2018 The SuperNET Developers. * * * * See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at * * the top-level directory of this distribution for the individual copyright * @@ -20,7 +20,7 @@ struct komodo_event *komodo_eventadd(struct komodo_state *sp,int32_t height,char *symbol,uint8_t type,uint8_t *data,uint16_t datalen) { struct komodo_event *ep=0; uint16_t len = (uint16_t)(sizeof(*ep) + datalen); - if ( sp != 0 ) + if ( sp != 0 && ASSETCHAINS_SYMBOL[0] != 0 ) { portable_mutex_lock(&komodo_mutex); ep = (struct komodo_event *)calloc(1,len); @@ -37,10 +37,10 @@ struct komodo_event *komodo_eventadd(struct komodo_state *sp,int32_t height,char return(ep); } -void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t height,char *dest,uint256 notarized_hash,uint256 notarized_desttxid,int32_t notarizedheight) +void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t height,char *dest,uint256 notarized_hash,uint256 notarized_desttxid,int32_t notarizedheight)//,uint256 MoM,int32_t MoMdepth) { struct komodo_event_notarized N; - if ( komodo_verifynotarization(symbol,dest,height,notarizedheight,notarized_hash,notarized_desttxid) != 0 ) + if ( NOTARY_PUBKEY33[0] != 0 && komodo_verifynotarization(symbol,dest,height,notarizedheight,notarized_hash,notarized_desttxid) != 0 ) { if ( height > 50000 || ASSETCHAINS_SYMBOL[0] != 0 ) printf("[%s] error validating notarization ht.%d notarized_height.%d, if on a pruned %s node this can be ignored\n",ASSETCHAINS_SYMBOL,height,notarizedheight,dest); @@ -53,10 +53,12 @@ void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t heig N.blockhash = notarized_hash; N.desttxid = notarized_desttxid; N.notarizedheight = notarizedheight; - strcpy(N.dest,dest); + //N.MoM = MoM; + //N.MoMdepth = MoMdepth; + strncpy(N.dest,dest,sizeof(N.dest)-1); komodo_eventadd(sp,height,symbol,KOMODO_EVENT_NOTARIZED,(uint8_t *)&N,sizeof(N)); if ( sp != 0 ) - komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid); + komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid)//,MoM,MoMdepth); } } @@ -75,27 +77,34 @@ void komodo_eventadd_pubkeys(struct komodo_state *sp,char *symbol,int32_t height void komodo_eventadd_pricefeed(struct komodo_state *sp,char *symbol,int32_t height,uint32_t *prices,uint8_t num) { struct komodo_event_pricefeed F; - memset(&F,0,sizeof(F)); - F.num = num; - memcpy(F.prices,prices,sizeof(*F.prices) * num); - komodo_eventadd(sp,height,symbol,KOMODO_EVENT_PRICEFEED,(uint8_t *)&F,(int32_t)(sizeof(F.num) + sizeof(*F.prices) * num)); - if ( sp != 0 ) - komodo_pvals(height,prices,num); + if ( num == sizeof(F.prices)/sizeof(*F.prices) ) + { + memset(&F,0,sizeof(F)); + F.num = num; + memcpy(F.prices,prices,sizeof(*F.prices) * num); + komodo_eventadd(sp,height,symbol,KOMODO_EVENT_PRICEFEED,(uint8_t *)&F,(int32_t)(sizeof(F.num) + sizeof(*F.prices) * num)); + if ( sp != 0 ) + komodo_pvals(height,prices,num); + } else fprintf(stderr,"skip pricefeed[%d]\n",num); } void komodo_eventadd_opreturn(struct komodo_state *sp,char *symbol,int32_t height,uint256 txid,uint64_t value,uint16_t vout,uint8_t *buf,uint16_t opretlen) { - struct komodo_event_opreturn O; uint8_t opret[16384]; - memset(&O,0,sizeof(O)); - O.txid = txid; - O.value = value; - O.vout = vout; - memcpy(opret,&O,sizeof(O)); - memcpy(&opret[sizeof(O)],buf,opretlen); - O.oplen = (int32_t)(opretlen + sizeof(O)); - komodo_eventadd(sp,height,symbol,KOMODO_EVENT_OPRETURN,opret,O.oplen); - if ( sp != 0 ) - komodo_opreturn(height,value,buf,opretlen,txid,vout,symbol); + struct komodo_event_opreturn O; uint8_t *opret; + if ( ASSETCHAINS_SYMBOL[0] != 0 ) + { + opret = (uint8_t *)calloc(1,sizeof(O) + opretlen + 16); + O.txid = txid; + O.value = value; + O.vout = vout; + memcpy(opret,&O,sizeof(O)); + memcpy(&opret[sizeof(O)],buf,opretlen); + O.oplen = (int32_t)(opretlen + sizeof(O)); + komodo_eventadd(sp,height,symbol,KOMODO_EVENT_OPRETURN,opret,O.oplen); + free(opret); + if ( sp != 0 ) + komodo_opreturn(height,value,buf,opretlen,txid,vout,symbol); + } } void komodo_event_undo(struct komodo_state *sp,struct komodo_event *ep) @@ -169,6 +178,7 @@ void komodo_eventadd_kmdheight(struct komodo_state *sp,char *symbol,int32_t heig } else { + //fprintf(stderr,"REWIND kmdheight.%d\n",kmdheight); kmdheight = -kmdheight; komodo_eventadd(sp,height,symbol,KOMODO_EVENT_REWIND,(uint8_t *)&height,sizeof(height)); if ( sp != 0 ) @@ -178,30 +188,30 @@ void komodo_eventadd_kmdheight(struct komodo_state *sp,char *symbol,int32_t heig /*void komodo_eventadd_deposit(int32_t actionflag,char *symbol,int32_t height,uint64_t komodoshis,char *fiat,uint64_t fiatoshis,uint8_t rmd160[20],bits256 kmdtxid,uint16_t kmdvout,uint64_t price) -{ - uint8_t opret[512]; uint16_t opretlen; - komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_DEPOSIT,kmdtxid,komodoshis,kmdvout,opret,opretlen); -} - -void komodo_eventadd_issued(int32_t actionflag,char *symbol,int32_t height,int32_t fiatheight,bits256 fiattxid,uint16_t fiatvout,bits256 kmdtxid,uint16_t kmdvout,uint64_t fiatoshis) -{ - uint8_t opret[512]; uint16_t opretlen; - komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_ISSUED,fiattxid,fiatoshis,fiatvout,opret,opretlen); -} - -void komodo_eventadd_withdraw(int32_t actionflag,char *symbol,int32_t height,uint64_t komodoshis,char *fiat,uint64_t fiatoshis,uint8_t rmd160[20],bits256 fiattxid,int32_t fiatvout,uint64_t price) -{ - uint8_t opret[512]; uint16_t opretlen; - komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_WITHDRAW,fiattxid,fiatoshis,fiatvout,opret,opretlen); -} - -void komodo_eventadd_redeemed(int32_t actionflag,char *symbol,int32_t height,bits256 kmdtxid,uint16_t kmdvout,int32_t fiatheight,bits256 fiattxid,uint16_t fiatvout,uint64_t komodoshis) -{ - uint8_t opret[512]; uint16_t opretlen; - komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_REDEEMED,kmdtxid,komodoshis,kmdvout,opret,opretlen); -}*/ + { + uint8_t opret[512]; uint16_t opretlen; + komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_DEPOSIT,kmdtxid,komodoshis,kmdvout,opret,opretlen); + } + + void komodo_eventadd_issued(int32_t actionflag,char *symbol,int32_t height,int32_t fiatheight,bits256 fiattxid,uint16_t fiatvout,bits256 kmdtxid,uint16_t kmdvout,uint64_t fiatoshis) + { + uint8_t opret[512]; uint16_t opretlen; + komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_ISSUED,fiattxid,fiatoshis,fiatvout,opret,opretlen); + } + + void komodo_eventadd_withdraw(int32_t actionflag,char *symbol,int32_t height,uint64_t komodoshis,char *fiat,uint64_t fiatoshis,uint8_t rmd160[20],bits256 fiattxid,int32_t fiatvout,uint64_t price) + { + uint8_t opret[512]; uint16_t opretlen; + komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_WITHDRAW,fiattxid,fiatoshis,fiatvout,opret,opretlen); + } + + void komodo_eventadd_redeemed(int32_t actionflag,char *symbol,int32_t height,bits256 kmdtxid,uint16_t kmdvout,int32_t fiatheight,bits256 fiattxid,uint16_t fiatvout,uint64_t komodoshis) + { + uint8_t opret[512]; uint16_t opretlen; + komodo_eventadd_opreturn(symbol,height,KOMODO_OPRETURN_REDEEMED,kmdtxid,komodoshis,kmdvout,opret,opretlen); + }*/ // process events -// +// #endif From 0972d75b3a2ee2e426ef0e4b2608c892d984944f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 15 Apr 2018 23:41:34 +0300 Subject: [PATCH 303/507] ; --- src/komodo_events.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_events.h b/src/komodo_events.h index 0196f1646..f44d2c6e9 100644 --- a/src/komodo_events.h +++ b/src/komodo_events.h @@ -58,7 +58,7 @@ void komodo_eventadd_notarized(struct komodo_state *sp,char *symbol,int32_t heig strncpy(N.dest,dest,sizeof(N.dest)-1); komodo_eventadd(sp,height,symbol,KOMODO_EVENT_NOTARIZED,(uint8_t *)&N,sizeof(N)); if ( sp != 0 ) - komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid)//,MoM,MoMdepth); + komodo_notarized_update(sp,height,notarizedheight,notarized_hash,notarized_desttxid);//,MoM,MoMdepth); } } From 7466a33007679ec514e185e7a1e5528e137dc3ac Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 00:03:29 +0300 Subject: [PATCH 304/507] Test --- src/main.cpp | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 8f3ea6108..4fb86a671 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3747,13 +3747,13 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc *ppindex = pindex; if ( pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK ) { - komodo_reverify_blockcheck(state,pindex->nHeight,pindex); - if ( KOMODO_LONGESTCHAIN != 0 && pindex->nHeight > KOMODO_LONGESTCHAIN-100 ) + //komodo_reverify_blockcheck(state,pindex->nHeight,pindex); + //if ( KOMODO_LONGESTCHAIN != 0 && pindex->nHeight > KOMODO_LONGESTCHAIN-100 ) return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); - else - { - pindex->nStatus &= ~BLOCK_FAILED_MASK; - } + //else + //{ + // pindex->nStatus &= ~BLOCK_FAILED_MASK; + //} } if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 debug test { @@ -3788,6 +3788,8 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return false; } } + if ( *ppindex == 0 ) + fprintf(stderr,"unexpected null *ppindex\n"); return true; } @@ -3809,7 +3811,10 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc if (!ContextualCheckBlockHeader(block, state, pindexPrev)) return false; if (pindex == NULL) - pindex = AddToBlockIndex(block); + { + if ( (pindex= AddToBlockIndex(block)) == 0 ) + fprintf(stderr,"couldnt add to block index\n"); + } if (ppindex) *ppindex = pindex; return true; @@ -3825,7 +3830,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, return false; if ( pindex == 0 ) { - //fprintf(stderr,"AcceptBlock error null pindex\n"); + fprintf(stderr,"unexpected AcceptBlock error null pindex\n"); return false; } // Try to process all requested blocks that we don't have, but only From d828f57946bab5a5f2a0214f95b35ea9608033b9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 00:22:22 +0300 Subject: [PATCH 305/507] Test --- src/main.cpp | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 4fb86a671..fa79c73c5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3746,15 +3746,8 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc if (ppindex) *ppindex = pindex; if ( pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK ) - { - //komodo_reverify_blockcheck(state,pindex->nHeight,pindex); - //if ( KOMODO_LONGESTCHAIN != 0 && pindex->nHeight > KOMODO_LONGESTCHAIN-100 ) - return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); - //else - //{ - // pindex->nStatus &= ~BLOCK_FAILED_MASK; - //} - } + return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); +#ifdef DEXcode if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 debug test { if (!CheckBlockHeader(pindex->nHeight,pindex, block, state)) @@ -3790,6 +3783,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc } if ( *ppindex == 0 ) fprintf(stderr,"unexpected null *ppindex\n"); +#endif return true; } From 49601901de303a7ca6c5b39ac95abf6706f2ba54 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 01:04:37 +0300 Subject: [PATCH 306/507] Test --- src/main.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index fa79c73c5..58ff820f5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3664,12 +3664,13 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta // Check that the block chain matches the known block chain up to a checkpoint if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash)) { - CBlockIndex *heightblock = chainActive[nHeight]; + /*CBlockIndex *heightblock = chainActive[nHeight]; if ( heightblock != 0 && heightblock->GetBlockHash() == hash ) { //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); return true; - } return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),REJECT_CHECKPOINT, "checkpoint mismatch"); + }*/ + return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),REJECT_CHECKPOINT, "checkpoint mismatch"); } // Don't accept any forks from the main chain prior to last checkpoint CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints()); From 876e74e980b746ec7383231f52573d2988b5a93c Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 01:09:02 +0300 Subject: [PATCH 307/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 58ff820f5..cae2c73a7 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3916,7 +3916,7 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc { if ( pfrom != 0 ) { - Misbehaving(pfrom->GetId(), 1); + //Misbehaving(pfrom->GetId(), 1); } return error("%s: CheckBlock FAILED", __func__); } From 176eeb772df6c048988476ec2add9eeed8f73fa5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 01:15:30 +0300 Subject: [PATCH 308/507] Test --- src/main.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index cae2c73a7..6b24d28f6 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3571,7 +3571,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) { komodo_reverify_blockcheck(state,height,pindex); - return state.DoS(33, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); + return state.DoS(1, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); } // Check the merkle root. if (fCheckMerkleRoot) { @@ -3676,7 +3676,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(chainParams.Checkpoints()); int32_t notarized_height; if (pcheckpoint && nHeight > 1 && nHeight < pcheckpoint->nHeight ) - return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d) vs %d", __func__, nHeight,pcheckpoint->nHeight)); + return state.DoS(1, error("%s: forked chain older than last checkpoint (height %d) vs %d", __func__, nHeight,pcheckpoint->nHeight)); else if ( komodo_checkpoint(¬arized_height,nHeight,hash) < 0 ) { CBlockIndex *heightblock = chainActive[nHeight]; @@ -3684,7 +3684,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta { //fprintf(stderr,"got a pre notarization block that matches height.%d\n",(int32_t)nHeight); return true; - } else return state.DoS(100, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height)); + } else return state.DoS(1, error("%s: forked chain %d older than last notarized (height %d) vs %d", __func__,nHeight, notarized_height)); } } // Reject block.nVersion < 4 blocks From 71564078257b6e6c87f7bb16d9d0c7ecb41f4255 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 01:16:16 +0300 Subject: [PATCH 309/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 6b24d28f6..a21dc5d48 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3571,7 +3571,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) { komodo_reverify_blockcheck(state,height,pindex); - return state.DoS(1, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); + return false; // happens if on a fork state.DoS(1, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); } // Check the merkle root. if (fCheckMerkleRoot) { From 9142a36868ed8f069436cf9f22985b3dae46fa2b Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 01:17:20 +0300 Subject: [PATCH 310/507] Test --- src/komodo_bitcoind.h | 2 +- src/pow.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index cd65ab9dd..40308096c 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -861,7 +861,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh { if ( mids[i] == notaryid ) { - if ( height > 700000 ) + if ( 0 && height > 700000 ) { for (j=0; j<66; j++) fprintf(stderr,"%d ",mids[j]); diff --git a/src/pow.cpp b/src/pow.cpp index 84acedd1f..92f1da3ce 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -191,7 +191,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in return true; if ( ASSETCHAINS_SYMBOL[0] == 0 ) { - if ( height > 792000 ) + if ( 0 && height > 792000 ) { for (i=31; i>=0; i--) printf("%02x",((uint8_t *)&hash)[i]); From 04a1f0bbc3e31d2182cc504e20a40366cb791ba1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 01:24:58 +0300 Subject: [PATCH 311/507] Test --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index a21dc5d48..12c7c3666 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3916,9 +3916,9 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc { if ( pfrom != 0 ) { - //Misbehaving(pfrom->GetId(), 1); + Misbehaving(pfrom->GetId(), 1); } - return error("%s: CheckBlock FAILED", __func__); + return false; // prevent flooding debug.log error("%s: CheckBlock FAILED", __func__); } // Store to disk From 872cf91b4453df3385b7678f6f231fa699cde49b Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 01:35:35 +0300 Subject: [PATCH 312/507] Test accepting failed check block --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 12c7c3666..77a87ad00 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3912,13 +3912,13 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc LOCK(cs_main); bool fRequested = MarkBlockAsReceived(pblock->GetHash()); fRequested |= fForceProcessing; - if (!checked) + if (!checked && 0) // bypass test { if ( pfrom != 0 ) { Misbehaving(pfrom->GetId(), 1); } - return false; // prevent flooding debug.log error("%s: CheckBlock FAILED", __func__); + return error("%s: CheckBlock FAILED", __func__); } // Store to disk From 58ce89f01b75a0dc2b3147cab2d96eebbbc5cc7a Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 01:51:23 +0300 Subject: [PATCH 313/507] Disable PoW outside of connect --- src/main.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 77a87ad00..38958a884 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2447,7 +2447,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin auto disabledVerifier = libzcash::ProofVerifier::Disabled(); // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in - if (!CheckBlock(pindex->nHeight,pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck)) + if (!CheckBlock(pindex->nHeight,pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, 1, !fJustCheck)) //!fJustCheck, !fJustCheck)) return false; // verify that the view's current state corresponds to the previous block @@ -3912,7 +3912,7 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc LOCK(cs_main); bool fRequested = MarkBlockAsReceived(pblock->GetHash()); fRequested |= fForceProcessing; - if (!checked && 0) // bypass test + if (!checked) { if ( pfrom != 0 ) { @@ -4365,7 +4365,7 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth if (!ReadBlockFromDisk(block, pindex)) return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); // check level 1: verify block validity - if (nCheckLevel >= 1 && !CheckBlock(pindex->nHeight,pindex,block, state, verifier)) + if (nCheckLevel >= 1 && !CheckBlock(pindex->nHeight,pindex,block, state, verifier,0)) return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); // check level 2: verify undo validity if (nCheckLevel >= 2 && pindex) { From 073cf3b29d0585ded6fec1afd7322a55207d7314 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 01:54:44 +0300 Subject: [PATCH 314/507] Test --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 38958a884..74fcf9b98 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3906,8 +3906,8 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc if ( chainActive.Tip() != 0 ) komodo_currentheight_set(chainActive.Tip()->nHeight); if ( ASSETCHAINS_SYMBOL[0] == 0 ) - checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier); - else checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier); + checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier,0); + else checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier,0); { LOCK(cs_main); bool fRequested = MarkBlockAsReceived(pblock->GetHash()); From 0edbd23e8cdc49236d0c4a65bfe7a69aae156ca5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 01:59:38 +0300 Subject: [PATCH 315/507] Test --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 74fcf9b98..53c056b5d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3751,7 +3751,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc #ifdef DEXcode if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 debug test { - if (!CheckBlockHeader(pindex->nHeight,pindex, block, state)) + if (!CheckBlockHeader(pindex->nHeight,pindex, block, state,0)) { pindex->nStatus |= BLOCK_FAILED_MASK; fprintf(stderr,"known block failing CheckBlockHeader %d\n",(int32_t)pindex->nHeight); @@ -3788,7 +3788,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return true; } - if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state)) + if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state,0)) return false; // Get prev block index From 44c0859ffbdfc1e273dfc831c8c1828827803fb9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 02:07:45 +0300 Subject: [PATCH 316/507] Test --- src/main.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 53c056b5d..32fc4dfe9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3534,9 +3534,8 @@ int32_t komodo_reverify_blockcheck(CValidationState& state,int32_t height,CBlock { if ( GetAdjustedTime() > tipindex->nTime+3600*2 ) { - fprintf(stderr,"tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),tipindex->nTime); - KOMODO_REWIND = tipindex->nHeight - 11; - /* + fprintf(stderr,"possible fork: tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),tipindex->nTime); + /*KOMODO_REWIND = tipindex->nHeight - 11; rewindtarget = tipindex->nHeight - 11; fprintf(stderr,"rewindtarget <- %d\n",rewindtarget); oneshot = 1; @@ -3789,8 +3788,10 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc } if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state,0)) + { + fprintf(stderr,"CheckBlockHeader failed\n"); return false; - + } // Get prev block index CBlockIndex* pindexPrev = NULL; if (hash != chainparams.GetConsensus().hashGenesisBlock) { @@ -3804,7 +3805,10 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk"); } if (!ContextualCheckBlockHeader(block, state, pindexPrev)) + { + fprintf(stderr,"ContextualCheckBlockHeader failed\n"); return false; + } if (pindex == NULL) { if ( (pindex= AddToBlockIndex(block)) == 0 ) From bd8997bfa7045930af6f7dcaeabf8a748e27a6d1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 02:11:53 +0300 Subject: [PATCH 317/507] Test --- src/main.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 32fc4dfe9..9be386e25 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3826,7 +3826,10 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CBlockIndex *&pindex = *ppindex; if (!AcceptBlockHeader(block, state, &pindex)) + { + fprintf(stderr,"AcceptBlockHeader rejected\n"); return false; + } if ( pindex == 0 ) { fprintf(stderr,"unexpected AcceptBlock error null pindex\n"); @@ -3855,7 +3858,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, // See method docstring for why this is always disabled auto verifier = libzcash::ProofVerifier::Disabled(); - if ((!CheckBlock(pindex->nHeight,pindex,block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) { + if ((!CheckBlock(pindex->nHeight,pindex,block, state, verifier,0)) || !ContextualCheckBlock(block, state, pindex->pprev)) { if (state.IsInvalid() && !state.CorruptionPossible()) { pindex->nStatus |= BLOCK_FAILED_VALID; setDirtyBlockIndex.insert(pindex); From 07359935ebc4efe4239cdcb8e5dbac0bfbf29eb8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 02:15:18 +0300 Subject: [PATCH 318/507] Test --- src/main.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 9be386e25..bed13eb46 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3835,6 +3835,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, fprintf(stderr,"unexpected AcceptBlock error null pindex\n"); return false; } + fprintf(stderr,"acceptblockheader passed\n"); // Try to process all requested blocks that we don't have, but only // process an unrequested block if it's new and has enough work to // advance our tip, and isn't too many blocks ahead. @@ -3858,11 +3859,13 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, // See method docstring for why this is always disabled auto verifier = libzcash::ProofVerifier::Disabled(); - if ((!CheckBlock(pindex->nHeight,pindex,block, state, verifier,0)) || !ContextualCheckBlock(block, state, pindex->pprev)) { + if ((!CheckBlock(pindex->nHeight,pindex,block, state, verifier,0)) || !ContextualCheckBlock(block, state, pindex->pprev)) + { if (state.IsInvalid() && !state.CorruptionPossible()) { pindex->nStatus |= BLOCK_FAILED_VALID; setDirtyBlockIndex.insert(pindex); } + fprintf(stderr,"CheckBlock or ContextualCheckBlock failed\n"); return false; } From f6cad5cc70a501b1739f41c250cfffbb6821f294 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 02:21:05 +0300 Subject: [PATCH 319/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index bed13eb46..2101efe61 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3938,7 +3938,7 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId(); } CheckBlockIndex(); - if (!ret) + if (!ret && 0) return error("%s: AcceptBlock FAILED", __func__); } From b6aa98f662fffa1520c25b6062414115b3c78f7e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 02:24:40 +0300 Subject: [PATCH 320/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 2101efe61..bed13eb46 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3938,7 +3938,7 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId(); } CheckBlockIndex(); - if (!ret && 0) + if (!ret) return error("%s: AcceptBlock FAILED", __func__); } From da4020cb6162e529fff373b59e0a5fbf0d505a84 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 02:35:19 +0300 Subject: [PATCH 321/507] Test --- src/komodo_bitcoind.h | 2 +- src/main.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 40308096c..cd65ab9dd 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -861,7 +861,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh { if ( mids[i] == notaryid ) { - if ( 0 && height > 700000 ) + if ( height > 700000 ) { for (j=0; j<66; j++) fprintf(stderr,"%d ",mids[j]); diff --git a/src/main.cpp b/src/main.cpp index bed13eb46..79ac0cafe 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3835,7 +3835,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, fprintf(stderr,"unexpected AcceptBlock error null pindex\n"); return false; } - fprintf(stderr,"acceptblockheader passed\n"); + //fprintf(stderr,"acceptblockheader passed\n"); // Try to process all requested blocks that we don't have, but only // process an unrequested block if it's new and has enough work to // advance our tip, and isn't too many blocks ahead. From 3d3f275f1479cb3500073ecc837da947414ff50a Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 02:45:36 +0300 Subject: [PATCH 322/507] +prints --- src/main.cpp | 2 +- src/pow.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 79ac0cafe..a7e3a3aab 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4529,7 +4529,7 @@ bool RewindBlockIndex(const CChainParams& params) setDirtyBlockIndex.insert(pindexIter); if (pindexIter == pindexBestInvalid) { - fprintf(stderr,"Reset invalid block marker if it was pointing to this block\n"); + //fprintf(stderr,"Reset invalid block marker if it was pointing to this block\n"); pindexBestInvalid = NULL; } diff --git a/src/pow.cpp b/src/pow.cpp index 92f1da3ce..b118b94d9 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -177,7 +177,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } if ( flag != 0 || special2 > 0 ) { - //fprintf(stderr,"EASY MINING ht.%d\n",height); + fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); } } @@ -191,7 +191,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in return true; if ( ASSETCHAINS_SYMBOL[0] == 0 ) { - if ( 0 && height > 792000 ) + if ( 1 && height > 792000 ) { for (i=31; i>=0; i--) printf("%02x",((uint8_t *)&hash)[i]); From 8bb84dabc429d90efb1a85552bc95bfd934f0987 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 02:47:29 +0300 Subject: [PATCH 323/507] -print --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index b118b94d9..65c907230 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -177,7 +177,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in } if ( flag != 0 || special2 > 0 ) { - fprintf(stderr,"EASY MINING ht.%d\n",height); + //fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); } } From d2e27d3fd455f3f6bbbde244d9d40a56be8e3e8f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 02:56:44 +0300 Subject: [PATCH 324/507] Sync with latest main.cpp --- src/main.cpp | 3160 ++++++++++++++++++++++++++++++-------------------- 1 file changed, 1875 insertions(+), 1285 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 48324ca42..3255c3380 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -13,7 +13,9 @@ #include "chainparams.h" #include "checkpoints.h" #include "checkqueue.h" +#include "consensus/upgrades.h" #include "consensus/validation.h" +#include "deprecation.h" #include "init.h" #include "merkleblock.h" #include "metrics.h" @@ -27,6 +29,7 @@ #include "utilmoneystr.h" #include "validationinterface.h" #include "wallet/asyncrpcoperation_sendmany.h" +#include "wallet/asyncrpcoperation_shieldcoinbase.h" #include @@ -50,7 +53,9 @@ using namespace std; CCriticalSection cs_main; extern uint8_t NOTARY_PUBKEY33[33]; -extern int32_t KOMODO_LOADINGBLOCKS; +extern int32_t KOMODO_LOADINGBLOCKS,KOMODO_LONGESTCHAIN; +int32_t KOMODO_NEWBLOCKS; +void komodo_block2pubkey33(uint8_t *pubkey33,CBlock *block); BlockMap mapBlockIndex; CChain chainActive; @@ -73,6 +78,8 @@ size_t nCoinCacheUsage = 5000 * 300; uint64_t nPruneTarget = 0; bool fAlerts = DEFAULT_ALERTS; +unsigned int expiryDelta = DEFAULT_TX_EXPIRY_DELTA; + /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */ CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE); @@ -100,30 +107,30 @@ const string strMessageMagic = "Komodo Signed Message:\n"; // Internal stuff namespace { - + struct CBlockIndexWorkComparator { bool operator()(CBlockIndex *pa, CBlockIndex *pb) const { // First sort by most total work, ... if (pa->nChainWork > pb->nChainWork) return false; if (pa->nChainWork < pb->nChainWork) return true; - + // ... then by earliest time received, ... if (pa->nSequenceId < pb->nSequenceId) return false; if (pa->nSequenceId > pb->nSequenceId) return true; - + // Use pointer address as tie breaker (should only happen with blocks // loaded from disk, as those all have id 0). if (pa < pb) return false; if (pa > pb) return true; - + // Identical blocks. return false; } }; - + CBlockIndex *pindexBestInvalid; - + /** * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be @@ -133,10 +140,10 @@ namespace { /** Number of nodes with fSyncStarted. */ int nSyncStarted = 0; /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions. - * Pruned nodes may have entries where B is missing data. - */ + * Pruned nodes may have entries where B is missing data. + */ multimap mapBlocksUnlinked; - + CCriticalSection cs_LastBlockFile; std::vector vinfoBlockFile; int nLastBlockFile = 0; @@ -145,7 +152,7 @@ namespace { * or if we allocate more file space when we're in prune mode */ bool fCheckForPruning = false; - + /** * Every received block is assigned a unique and increasing identifier, so we * know which one to give priority in case of a fork. @@ -153,14 +160,14 @@ namespace { CCriticalSection cs_nBlockSequenceId; /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */ uint32_t nBlockSequenceId = 1; - + /** * Sources of received blocks, saved to be able to send them reject * messages or ban them when processing happens afterwards. Protected by * cs_main. */ map mapBlockSource; - + /** * Filter for transactions that were recently rejected by * AcceptToMemoryPool. These are not rerequested until the chain tip @@ -183,7 +190,7 @@ namespace { */ boost::scoped_ptr recentRejects; uint256 hashRecentRejectsChainTip; - + /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */ struct QueuedBlock { uint256 hash; @@ -193,16 +200,16 @@ namespace { int64_t nTimeDisconnect; //! The timeout for this block request (for disconnecting a slow peer) }; map::iterator> > mapBlocksInFlight; - + /** Number of blocks in flight with validated headers. */ int nQueuedValidatedHeaders = 0; - + /** Number of preferable block download peers. */ int nPreferredDownload = 0; - + /** Dirty block index entries. */ set setDirtyBlockIndex; - + /** Dirty block file entries. */ set setDirtyFileInfo; } // anon namespace @@ -213,306 +220,306 @@ namespace { // namespace { - -struct CBlockReject { - unsigned char chRejectCode; - string strRejectReason; - uint256 hashBlock; -}; - -/** - * Maintain validation-specific state about nodes, protected by cs_main, instead - * by CNode's own locks. This simplifies asynchronous operation, where - * processing of incoming data is done after the ProcessMessage call returns, - * and we're no longer holding the node's locks. - */ -struct CNodeState { - //! The peer's address - CService address; - //! Whether we have a fully established connection. - bool fCurrentlyConnected; - //! Accumulated misbehaviour score for this peer. - int nMisbehavior; - //! Whether this peer should be disconnected and banned (unless whitelisted). - bool fShouldBan; - //! String name of this peer (debugging/logging purposes). - std::string name; - //! List of asynchronously-determined block rejections to notify this peer about. - std::vector rejects; - //! The best known block we know this peer has announced. - CBlockIndex *pindexBestKnownBlock; - //! The hash of the last unknown block this peer has announced. - uint256 hashLastUnknownBlock; - //! The last full block we both have. - CBlockIndex *pindexLastCommonBlock; - //! Whether we've started headers synchronization with this peer. - bool fSyncStarted; - //! Since when we're stalling block download progress (in microseconds), or 0. - int64_t nStallingSince; - list vBlocksInFlight; - int nBlocksInFlight; - int nBlocksInFlightValidHeaders; - //! Whether we consider this a preferred download peer. - bool fPreferredDownload; - - CNodeState() { - fCurrentlyConnected = false; - nMisbehavior = 0; - fShouldBan = false; - pindexBestKnownBlock = NULL; - hashLastUnknownBlock.SetNull(); - pindexLastCommonBlock = NULL; - fSyncStarted = false; - nStallingSince = 0; - nBlocksInFlight = 0; - nBlocksInFlightValidHeaders = 0; - fPreferredDownload = false; - } -}; - -/** Map maintaining per-node state. Requires cs_main. */ -map mapNodeState; - -// Requires cs_main. -CNodeState *State(NodeId pnode) { - map::iterator it = mapNodeState.find(pnode); - if (it == mapNodeState.end()) - return NULL; - return &it->second; -} - -int GetHeight() -{ - LOCK(cs_main); - return chainActive.Height(); -} - -void UpdatePreferredDownload(CNode* node, CNodeState* state) -{ - nPreferredDownload -= state->fPreferredDownload; - - // Whether this node should be marked as a preferred download node. - state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient; - - nPreferredDownload += state->fPreferredDownload; -} - -// Returns time at which to timeout block request (nTime in microseconds) -int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams) -{ - return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore); -} - -void InitializeNode(NodeId nodeid, const CNode *pnode) { - LOCK(cs_main); - CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second; - state.name = pnode->addrName; - state.address = pnode->addr; -} - -void FinalizeNode(NodeId nodeid) { - LOCK(cs_main); - CNodeState *state = State(nodeid); - - if (state->fSyncStarted) - nSyncStarted--; - - if (state->nMisbehavior == 0 && state->fCurrentlyConnected) { - AddressCurrentlyConnected(state->address); - } - - BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight) - mapBlocksInFlight.erase(entry.hash); - EraseOrphansFor(nodeid); - nPreferredDownload -= state->fPreferredDownload; - - mapNodeState.erase(nodeid); -} -void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) -{ -/* int expired = pool.Expire(GetTime() - age); - if (expired != 0) - LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired); + struct CBlockReject { + unsigned char chRejectCode; + string strRejectReason; + uint256 hashBlock; + }; - std::vector vNoSpendsRemaining; - pool.TrimToSize(limit, &vNoSpendsRemaining); - BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining) - pcoinsTip->Uncache(removed);*/ -} - -// Requires cs_main. -// Returns a bool indicating whether we requested this block. -bool MarkBlockAsReceived(const uint256& hash) { - map::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); - if (itInFlight != mapBlocksInFlight.end()) { - CNodeState *state = State(itInFlight->second.first); - nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders; - state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders; - state->vBlocksInFlight.erase(itInFlight->second.second); - state->nBlocksInFlight--; - state->nStallingSince = 0; - mapBlocksInFlight.erase(itInFlight); - return true; - } - return false; -} - -// Requires cs_main. -void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) { - CNodeState *state = State(nodeid); - assert(state != NULL); - - // Make sure it's not listed somewhere already. - MarkBlockAsReceived(hash); - - int64_t nNow = GetTimeMicros(); - QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)}; - nQueuedValidatedHeaders += newentry.fValidatedHeaders; - list::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry); - state->nBlocksInFlight++; - state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders; - mapBlocksInFlight[hash] = std::make_pair(nodeid, it); -} - -/** Check whether the last unknown block a peer advertized is not yet known. */ -void ProcessBlockAvailability(NodeId nodeid) { - CNodeState *state = State(nodeid); - assert(state != NULL); - - if (!state->hashLastUnknownBlock.IsNull()) { - BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock); - if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) - { - if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) - state->pindexBestKnownBlock = itOld->second; - state->hashLastUnknownBlock.SetNull(); + /** + * Maintain validation-specific state about nodes, protected by cs_main, instead + * by CNode's own locks. This simplifies asynchronous operation, where + * processing of incoming data is done after the ProcessMessage call returns, + * and we're no longer holding the node's locks. + */ + struct CNodeState { + //! The peer's address + CService address; + //! Whether we have a fully established connection. + bool fCurrentlyConnected; + //! Accumulated misbehaviour score for this peer. + int nMisbehavior; + //! Whether this peer should be disconnected and banned (unless whitelisted). + bool fShouldBan; + //! String name of this peer (debugging/logging purposes). + std::string name; + //! List of asynchronously-determined block rejections to notify this peer about. + std::vector rejects; + //! The best known block we know this peer has announced. + CBlockIndex *pindexBestKnownBlock; + //! The hash of the last unknown block this peer has announced. + uint256 hashLastUnknownBlock; + //! The last full block we both have. + CBlockIndex *pindexLastCommonBlock; + //! Whether we've started headers synchronization with this peer. + bool fSyncStarted; + //! Since when we're stalling block download progress (in microseconds), or 0. + int64_t nStallingSince; + list vBlocksInFlight; + int nBlocksInFlight; + int nBlocksInFlightValidHeaders; + //! Whether we consider this a preferred download peer. + bool fPreferredDownload; + + CNodeState() { + fCurrentlyConnected = false; + nMisbehavior = 0; + fShouldBan = false; + pindexBestKnownBlock = NULL; + hashLastUnknownBlock.SetNull(); + pindexLastCommonBlock = NULL; + fSyncStarted = false; + nStallingSince = 0; + nBlocksInFlight = 0; + nBlocksInFlightValidHeaders = 0; + fPreferredDownload = false; } + }; + + /** Map maintaining per-node state. Requires cs_main. */ + map mapNodeState; + + // Requires cs_main. + CNodeState *State(NodeId pnode) { + map::iterator it = mapNodeState.find(pnode); + if (it == mapNodeState.end()) + return NULL; + return &it->second; } -} - -/** Update tracking information about which blocks a peer is assumed to have. */ -void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) { - CNodeState *state = State(nodeid); - assert(state != NULL); - - /*ProcessBlockAvailability(nodeid); - - BlockMap::iterator it = mapBlockIndex.find(hash); - if (it != mapBlockIndex.end() && it->second->nChainWork > 0) { - // An actually better block was announced. - if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) - state->pindexBestKnownBlock = it->second; - } else*/ + + int GetHeight() { - // An unknown block was announced; just assume that the latest one is the best one. - state->hashLastUnknownBlock = hash; + LOCK(cs_main); + return chainActive.Height(); } -} - -/** Find the last common ancestor two blocks have. - * Both pa and pb must be non-NULL. */ -CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) { - if (pa->nHeight > pb->nHeight) { - pa = pa->GetAncestor(pb->nHeight); - } else if (pb->nHeight > pa->nHeight) { - pb = pb->GetAncestor(pa->nHeight); + + void UpdatePreferredDownload(CNode* node, CNodeState* state) + { + nPreferredDownload -= state->fPreferredDownload; + + // Whether this node should be marked as a preferred download node. + state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient; + + nPreferredDownload += state->fPreferredDownload; } - - while (pa != pb && pa && pb) { - pa = pa->pprev; - pb = pb->pprev; + + // Returns time at which to timeout block request (nTime in microseconds) + int64_t GetBlockTimeout(int64_t nTime, int nValidatedQueuedBefore, const Consensus::Params &consensusParams) + { + return nTime + 500000 * consensusParams.nPowTargetSpacing * (4 + nValidatedQueuedBefore); } - - // Eventually all chain branches meet at the genesis block. - assert(pa == pb); - return pa; -} - -/** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has - * at most count entries. */ -void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector& vBlocks, NodeId& nodeStaller) { - if (count == 0) - return; - - vBlocks.reserve(vBlocks.size() + count); - CNodeState *state = State(nodeid); - assert(state != NULL); - - // Make sure pindexBestKnownBlock is up to date, we'll need it. - ProcessBlockAvailability(nodeid); - - if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) { - // This peer has nothing interesting. - return; + + void InitializeNode(NodeId nodeid, const CNode *pnode) { + LOCK(cs_main); + CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second; + state.name = pnode->addrName; + state.address = pnode->addr; } - - if (state->pindexLastCommonBlock == NULL) { - // Bootstrap quickly by guessing a parent of our best tip is the forking point. - // Guessing wrong in either direction is not a problem. - state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())]; - } - - // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor - // of its current tip anymore. Go back enough to fix that. - state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock); - if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) - return; - - std::vector vToFetch; - CBlockIndex *pindexWalk = state->pindexLastCommonBlock; - // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last - // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to - // download that next block if the window were 1 larger. - int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW; - int nMaxHeight = std::min(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1); - NodeId waitingfor = -1; - while (pindexWalk->nHeight < nMaxHeight) { - // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards - // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive - // as iterating over ~100 CBlockIndex* entries anyway. - int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max(count - vBlocks.size(), 128)); - vToFetch.resize(nToFetch); - pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch); - vToFetch[nToFetch - 1] = pindexWalk; - for (unsigned int i = nToFetch - 1; i > 0; i--) { - vToFetch[i - 1] = vToFetch[i]->pprev; + + void FinalizeNode(NodeId nodeid) { + LOCK(cs_main); + CNodeState *state = State(nodeid); + + if (state->fSyncStarted) + nSyncStarted--; + + if (state->nMisbehavior == 0 && state->fCurrentlyConnected) { + AddressCurrentlyConnected(state->address); } - - // Iterate over those blocks in vToFetch (in forward direction), adding the ones that - // are not yet downloaded and not in flight to vBlocks. In the mean time, update - // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's - // already part of our chain (and therefore don't need it even if pruned). - BOOST_FOREACH(CBlockIndex* pindex, vToFetch) { - if (!pindex->IsValid(BLOCK_VALID_TREE)) { - // We consider the chain that this peer is on invalid. - return; + + BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight) + mapBlocksInFlight.erase(entry.hash); + EraseOrphansFor(nodeid); + nPreferredDownload -= state->fPreferredDownload; + + mapNodeState.erase(nodeid); + } + + void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) + { + /* int expired = pool.Expire(GetTime() - age); + if (expired != 0) + LogPrint("mempool", "Expired %i transactions from the memory pool\n", expired); + + std::vector vNoSpendsRemaining; + pool.TrimToSize(limit, &vNoSpendsRemaining); + BOOST_FOREACH(const uint256& removed, vNoSpendsRemaining) + pcoinsTip->Uncache(removed);*/ + } + + // Requires cs_main. + // Returns a bool indicating whether we requested this block. + bool MarkBlockAsReceived(const uint256& hash) { + map::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); + if (itInFlight != mapBlocksInFlight.end()) { + CNodeState *state = State(itInFlight->second.first); + nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders; + state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders; + state->vBlocksInFlight.erase(itInFlight->second.second); + state->nBlocksInFlight--; + state->nStallingSince = 0; + mapBlocksInFlight.erase(itInFlight); + return true; + } + return false; + } + + // Requires cs_main. + void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, CBlockIndex *pindex = NULL) { + CNodeState *state = State(nodeid); + assert(state != NULL); + + // Make sure it's not listed somewhere already. + MarkBlockAsReceived(hash); + + int64_t nNow = GetTimeMicros(); + QueuedBlock newentry = {hash, pindex, nNow, pindex != NULL, GetBlockTimeout(nNow, nQueuedValidatedHeaders, consensusParams)}; + nQueuedValidatedHeaders += newentry.fValidatedHeaders; + list::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry); + state->nBlocksInFlight++; + state->nBlocksInFlightValidHeaders += newentry.fValidatedHeaders; + mapBlocksInFlight[hash] = std::make_pair(nodeid, it); + } + + /** Check whether the last unknown block a peer advertized is not yet known. */ + void ProcessBlockAvailability(NodeId nodeid) { + CNodeState *state = State(nodeid); + assert(state != NULL); + + if (!state->hashLastUnknownBlock.IsNull()) { + BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock); + if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) + { + if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) + state->pindexBestKnownBlock = itOld->second; + state->hashLastUnknownBlock.SetNull(); } - if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) { - if (pindex->nChainTx) - state->pindexLastCommonBlock = pindex; - } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) { - // The block is not already downloaded, and not yet in flight. - if (pindex->nHeight > nWindowEnd) { - // We reached the end of the window. - if (vBlocks.size() == 0 && waitingfor != nodeid) { - // We aren't able to fetch anything, but we would be if the download window was one larger. - nodeStaller = waitingfor; + } + } + + /** Update tracking information about which blocks a peer is assumed to have. */ + void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) { + CNodeState *state = State(nodeid); + assert(state != NULL); + + /*ProcessBlockAvailability(nodeid); + + BlockMap::iterator it = mapBlockIndex.find(hash); + if (it != mapBlockIndex.end() && it->second->nChainWork > 0) { + // An actually better block was announced. + if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) + state->pindexBestKnownBlock = it->second; + } else*/ + { + // An unknown block was announced; just assume that the latest one is the best one. + state->hashLastUnknownBlock = hash; + } + } + + /** Find the last common ancestor two blocks have. + * Both pa and pb must be non-NULL. */ + CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) { + if (pa->nHeight > pb->nHeight) { + pa = pa->GetAncestor(pb->nHeight); + } else if (pb->nHeight > pa->nHeight) { + pb = pb->GetAncestor(pa->nHeight); + } + + while (pa != pb && pa && pb) { + pa = pa->pprev; + pb = pb->pprev; + } + + // Eventually all chain branches meet at the genesis block. + assert(pa == pb); + return pa; + } + + /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has + * at most count entries. */ + void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector& vBlocks, NodeId& nodeStaller) { + if (count == 0) + return; + + vBlocks.reserve(vBlocks.size() + count); + CNodeState *state = State(nodeid); + assert(state != NULL); + + // Make sure pindexBestKnownBlock is up to date, we'll need it. + ProcessBlockAvailability(nodeid); + + if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) { + // This peer has nothing interesting. + return; + } + + if (state->pindexLastCommonBlock == NULL) { + // Bootstrap quickly by guessing a parent of our best tip is the forking point. + // Guessing wrong in either direction is not a problem. + state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())]; + } + + // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor + // of its current tip anymore. Go back enough to fix that. + state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock); + if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) + return; + + std::vector vToFetch; + CBlockIndex *pindexWalk = state->pindexLastCommonBlock; + // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last + // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to + // download that next block if the window were 1 larger. + int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW; + int nMaxHeight = std::min(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1); + NodeId waitingfor = -1; + while (pindexWalk->nHeight < nMaxHeight) { + // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards + // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive + // as iterating over ~100 CBlockIndex* entries anyway. + int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max(count - vBlocks.size(), 128)); + vToFetch.resize(nToFetch); + pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch); + vToFetch[nToFetch - 1] = pindexWalk; + for (unsigned int i = nToFetch - 1; i > 0; i--) { + vToFetch[i - 1] = vToFetch[i]->pprev; + } + + // Iterate over those blocks in vToFetch (in forward direction), adding the ones that + // are not yet downloaded and not in flight to vBlocks. In the meantime, update + // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's + // already part of our chain (and therefore don't need it even if pruned). + BOOST_FOREACH(CBlockIndex* pindex, vToFetch) { + if (!pindex->IsValid(BLOCK_VALID_TREE)) { + // We consider the chain that this peer is on invalid. + return; + } + if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) { + if (pindex->nChainTx) + state->pindexLastCommonBlock = pindex; + } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) { + // The block is not already downloaded, and not yet in flight. + if (pindex->nHeight > nWindowEnd) { + // We reached the end of the window. + if (vBlocks.size() == 0 && waitingfor != nodeid) { + // We aren't able to fetch anything, but we would be if the download window was one larger. + nodeStaller = waitingfor; + } + return; } - return; + vBlocks.push_back(pindex); + if (vBlocks.size() == count) { + return; + } + } else if (waitingfor == -1) { + // This is the first already-in-flight block. + waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first; } - vBlocks.push_back(pindex); - if (vBlocks.size() == count) { - return; - } - } else if (waitingfor == -1) { - // This is the first already-in-flight block. - waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first; } } } -} - + } // anon namespace bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) { @@ -558,6 +565,9 @@ CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& loc CBlockIndex* pindex = (*mi).second; if (pindex != 0 && chain.Contains(pindex)) return pindex; + if (pindex != 0 && pindex->GetAncestor(chain.Height()) == chain.Tip()) { + return chain.Tip(); + } } } return chain.Genesis(); @@ -581,7 +591,7 @@ bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(c uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; - + // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume @@ -595,12 +605,12 @@ bool AddOrphanTx(const CTransaction& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(c LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString()); return false; } - + mapOrphanTransactions[hash].tx = tx; mapOrphanTransactions[hash].fromPeer = peer; BOOST_FOREACH(const CTxIn& txin, tx.vin) - mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash); - + mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash); + LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(), mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size()); return true; @@ -650,25 +660,31 @@ unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRE map::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); - EraseOrphanTx(it->first); - ++nEvicted; + EraseOrphanTx(it->first); + ++nEvicted; } return nEvicted; } - - - - - -bool IsStandardTx(const CTransaction& tx, string& reason) +bool IsStandardTx(const CTransaction& tx, string& reason, const int nHeight) { - if (tx.nVersion > CTransaction::MAX_CURRENT_VERSION || tx.nVersion < CTransaction::MIN_CURRENT_VERSION) { - reason = "version"; - return false; + bool isOverwinter = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER); + + if (isOverwinter) { + // Overwinter standard rules apply + if (tx.nVersion > CTransaction::OVERWINTER_MAX_CURRENT_VERSION || tx.nVersion < CTransaction::OVERWINTER_MIN_CURRENT_VERSION) { + reason = "overwinter-version"; + return false; + } + } else { + // Sprout standard rules apply + if (tx.nVersion > CTransaction::SPROUT_MAX_CURRENT_VERSION || tx.nVersion < CTransaction::SPROUT_MIN_CURRENT_VERSION) { + reason = "version"; + return false; + } } - + BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed @@ -687,7 +703,7 @@ bool IsStandardTx(const CTransaction& tx, string& reason) return false; } } - + unsigned int v=0,nDataOut = 0; txnouttype whichType; BOOST_FOREACH(const CTxOut& txout, tx.vout) @@ -713,13 +729,13 @@ bool IsStandardTx(const CTransaction& tx, string& reason) } v++; } - + // only one OP_RETURN txout is permitted if (nDataOut > 1) { reason = "multi-op-return"; return false; } - + return true; } @@ -738,17 +754,25 @@ bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime) } else if (!txin.IsFinal()) { - printf("non-final txin seq.%x locktime.%u vs nTime.%u\n",txin.nSequence,(uint32_t)tx.nLockTime,(uint32_t)nBlockTime); + //printf("non-final txin seq.%x locktime.%u vs nTime.%u\n",txin.nSequence,(uint32_t)tx.nLockTime,(uint32_t)nBlockTime); return false; } } return true; } +bool IsExpiredTx(const CTransaction &tx, int nBlockHeight) +{ + if (tx.nExpiryHeight == 0 || tx.IsCoinBase()) { + return false; + } + return static_cast(nBlockHeight) > tx.nExpiryHeight; +} + bool CheckFinalTx(const CTransaction &tx, int flags) { AssertLockHeld(cs_main); - + // By convention a negative value for flags indicates that the // current network-enforced consensus rules should be used. In // a future soft-fork scenario that would mean checking which @@ -756,7 +780,7 @@ bool CheckFinalTx(const CTransaction &tx, int flags) // appropriate flags. At the present time no soft-forks are // scheduled, so no flags are set. flags = std::max(flags, 0); - + // CheckFinalTx() uses chainActive.Height()+1 to evaluate // nLockTime because when IsFinalTx() is called within // CBlock::AcceptBlock(), the height of the block *being* @@ -764,15 +788,15 @@ bool CheckFinalTx(const CTransaction &tx, int flags) // transaction can be part of the *next* block, we need to call // IsFinalTx() with one more than chainActive.Height(). const int nBlockHeight = chainActive.Height() + 1; - + // Timestamps on the other hand don't get any special treatment, // because we can't know what timestamp the next block will have, // and there aren't timestamp applications where it matters. // However this changes once median past time-locks are enforced: const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST) - ? chainActive.Tip()->GetMedianTimePast() - : GetAdjustedTime(); - + ? chainActive.Tip()->GetMedianTimePast() + : GetAdjustedTime(); + return IsFinalTx(tx, nBlockHeight, nBlockTime); } @@ -785,15 +809,15 @@ bool CheckFinalTx(const CTransaction &tx, int flags) * 2. P2SH scripts with a crazy number of expensive * CHECKSIG/CHECKMULTISIG operations */ -bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) +bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, uint32_t consensusBranchId) { if (tx.IsCoinBase()) return true; // Coinbases don't use vin normally - + for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]); - + vector > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: @@ -803,7 +827,7 @@ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; - + // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations @@ -811,9 +835,9 @@ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) // IsStandardTx() will have already returned false // and this method isn't called. vector > stack; - if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker())) + if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker(), consensusBranchId)) return false; - + if (whichType == TX_SCRIPTHASH) { if (stack.empty()) @@ -836,11 +860,11 @@ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) return (sigops <= MAX_P2SH_SIGOPS); } } - + if (stack.size() != (unsigned int)nArgsExpected) return false; } - + return true; } @@ -862,7 +886,7 @@ unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& in { if (tx.IsCoinBase()) return 0; - + unsigned int nSigOps = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) { @@ -873,7 +897,80 @@ unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& in return nSigOps; } -bool CheckTransaction(const CTransaction& tx, CValidationState &state,libzcash::ProofVerifier& verifier) +/** + * Check a transaction contextually against a set of consensus rules valid at a given block height. + * + * Notes: + * 1. AcceptToMemoryPool calls CheckTransaction and this function. + * 2. ProcessNewBlock calls AcceptBlock, which calls CheckBlock (which calls CheckTransaction) + * and ContextualCheckBlock (which calls this function). + */ +bool ContextualCheckTransaction(const CTransaction& tx, CValidationState &state, const int nHeight, const int dosLevel) +{ + bool isOverwinter = NetworkUpgradeActive(nHeight, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER); + bool isSprout = !isOverwinter; + + // If Sprout rules apply, reject transactions which are intended for Overwinter and beyond + if (isSprout && tx.fOverwintered) { + return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwinter is not active yet"), + REJECT_INVALID, "tx-overwinter-not-active"); + } + + // If Overwinter rules apply: + if (isOverwinter) { + // Reject transactions with valid version but missing overwinter flag + if (tx.nVersion >= OVERWINTER_MIN_TX_VERSION && !tx.fOverwintered) { + return state.DoS(dosLevel, error("ContextualCheckTransaction(): overwinter flag must be set"), + REJECT_INVALID, "tx-overwinter-flag-not-set"); + } + + // Reject transactions with invalid version + if (tx.fOverwintered && tx.nVersion > OVERWINTER_MAX_TX_VERSION ) { + return state.DoS(100, error("CheckTransaction(): overwinter version too high"), + REJECT_INVALID, "bad-tx-overwinter-version-too-high"); + } + + // Reject transactions intended for Sprout + if (!tx.fOverwintered) { + return state.DoS(dosLevel, error("ContextualCheckTransaction: overwinter is active"), + REJECT_INVALID, "tx-overwinter-active"); + } + + // Check that all transactions are unexpired + if (IsExpiredTx(tx, nHeight)) { + return state.DoS(dosLevel, error("ContextualCheckTransaction(): transaction is expired"), REJECT_INVALID, "tx-overwinter-expired"); + } + } + + if (!(tx.IsCoinBase() || tx.vjoinsplit.empty())) { + auto consensusBranchId = CurrentEpochBranchId(nHeight, Params().GetConsensus()); + // Empty output script. + CScript scriptCode; + uint256 dataToBeSigned; + try { + dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL, 0, consensusBranchId); + } catch (std::logic_error ex) { + return state.DoS(100, error("CheckTransaction(): error computing signature hash"), + REJECT_INVALID, "error-computing-signature-hash"); + } + + BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32); + + // We rely on libsodium to check that the signature is canonical. + // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0 + if (crypto_sign_verify_detached(&tx.joinSplitSig[0], + dataToBeSigned.begin(), 32, + tx.joinSplitPubKey.begin() + ) != 0) { + return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"), + REJECT_INVALID, "bad-txns-invalid-joinsplit-signature"); + } + } + return true; +} + +bool CheckTransaction(const CTransaction& tx, CValidationState &state, + libzcash::ProofVerifier& verifier) { static uint256 array[64]; static int32_t numbanned,indallvouts; int32_t j,k,n; if ( *(int32_t *)&array[0] == 0 ) @@ -892,11 +989,11 @@ bool CheckTransaction(const CTransaction& tx, CValidationState &state,libzcash:: } } } - // Don't count coinbase transactions because mining skews the count + // Don't count coinbase transactions because mining skews the count if (!tx.IsCoinBase()) { transactionsValidated.increment(); } - + if (!CheckTransactionWithoutProofVerification(tx, state)) { return false; } else { @@ -904,7 +1001,7 @@ bool CheckTransaction(const CTransaction& tx, CValidationState &state,libzcash:: BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) { if (!joinsplit.Verify(*pzcashParams, verifier, tx.joinSplitPubKey)) { return state.DoS(100, error("CheckTransaction(): joinsplit does not verify"), - REJECT_INVALID, "bad-txns-joinsplit-verification-failed"); + REJECT_INVALID, "bad-txns-joinsplit-verification-failed"); } } return true; @@ -914,13 +1011,48 @@ bool CheckTransaction(const CTransaction& tx, CValidationState &state,libzcash:: bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidationState &state) { // Basic checks that don't depend on any context - - // Check transaction version - if (tx.nVersion < MIN_TX_VERSION) { + + /** + * Previously: + * 1. The consensus rule below was: + * if (tx.nVersion < SPROUT_MIN_TX_VERSION) { ... } + * which checked if tx.nVersion fell within the range: + * INT32_MIN <= tx.nVersion < SPROUT_MIN_TX_VERSION + * 2. The parser allowed tx.nVersion to be negative + * + * Now: + * 1. The consensus rule checks to see if tx.Version falls within the range: + * 0 <= tx.nVersion < SPROUT_MIN_TX_VERSION + * 2. The previous consensus rule checked for negative values within the range: + * INT32_MIN <= tx.nVersion < 0 + * This is unnecessary for Overwinter transactions since the parser now + * interprets the sign bit as fOverwintered, so tx.nVersion is always >=0, + * and when Overwinter is not active ContextualCheckTransaction rejects + * transactions with fOverwintered set. When fOverwintered is set, + * this function and ContextualCheckTransaction will together check to + * ensure tx.nVersion avoids the following ranges: + * 0 <= tx.nVersion < OVERWINTER_MIN_TX_VERSION + * OVERWINTER_MAX_TX_VERSION < tx.nVersion <= INT32_MAX + */ + if (!tx.fOverwintered && tx.nVersion < SPROUT_MIN_TX_VERSION) { return state.DoS(100, error("CheckTransaction(): version too low"), REJECT_INVALID, "bad-txns-version-too-low"); } - + else if (tx.fOverwintered) { + if (tx.nVersion < OVERWINTER_MIN_TX_VERSION) { + return state.DoS(100, error("CheckTransaction(): overwinter version too low"), + REJECT_INVALID, "bad-tx-overwinter-version-too-low"); + } + if (tx.nVersionGroupId != OVERWINTER_VERSION_GROUP_ID) { + return state.DoS(100, error("CheckTransaction(): unknown tx version group id"), + REJECT_INVALID, "bad-tx-version-group-id"); + } + if (tx.nExpiryHeight >= TX_EXPIRY_HEIGHT_THRESHOLD) { + return state.DoS(100, error("CheckTransaction(): expiry height is too high"), + REJECT_INVALID, "bad-tx-expiry-height-too-high"); + } + } + // Transactions can contain empty `vin` and `vout` so long as // `vjoinsplit` is non-empty. if (tx.vin.empty() && tx.vjoinsplit.empty()) @@ -929,13 +1061,13 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio if (tx.vout.empty() && tx.vjoinsplit.empty()) return state.DoS(10, error("CheckTransaction(): vout empty"), REJECT_INVALID, "bad-txns-vout-empty"); - + // Size limits BOOST_STATIC_ASSERT(MAX_BLOCK_SIZE > MAX_TX_SIZE); // sanity if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_TX_SIZE) return state.DoS(100, error("CheckTransaction(): size limits failed"), REJECT_INVALID, "bad-txns-oversize"); - + // Check for negative or overflow output values CAmount nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, tx.vout) @@ -953,7 +1085,7 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio return state.DoS(100, error("CheckTransaction(): txout total out of range"), REJECT_INVALID, "bad-txns-txouttotal-toolarge"); } - + // Ensure that joinsplit values are well-formed BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit) { @@ -961,34 +1093,34 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old negative"), REJECT_INVALID, "bad-txns-vpub_old-negative"); } - + if (joinsplit.vpub_new < 0) { return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new negative"), REJECT_INVALID, "bad-txns-vpub_new-negative"); } - + if (joinsplit.vpub_old > MAX_MONEY) { return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_old too high"), REJECT_INVALID, "bad-txns-vpub_old-toolarge"); } - + if (joinsplit.vpub_new > MAX_MONEY) { return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new too high"), REJECT_INVALID, "bad-txns-vpub_new-toolarge"); } - + if (joinsplit.vpub_new != 0 && joinsplit.vpub_old != 0) { return state.DoS(100, error("CheckTransaction(): joinsplit.vpub_new and joinsplit.vpub_old both nonzero"), REJECT_INVALID, "bad-txns-vpubs-both-nonzero"); } - + nValueOut += joinsplit.vpub_old; if (!MoneyRange(nValueOut)) { return state.DoS(100, error("CheckTransaction(): txout total out of range"), REJECT_INVALID, "bad-txns-txouttotal-toolarge"); } } - + // Ensure input values do not exceed MAX_MONEY // We have not resolved the txin values at this stage, // but we do know what the joinsplits claim to add @@ -998,15 +1130,15 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio for (std::vector::const_iterator it(tx.vjoinsplit.begin()); it != tx.vjoinsplit.end(); ++it) { nValueIn += it->vpub_new; - + if (!MoneyRange(it->vpub_new) || !MoneyRange(nValueIn)) { return state.DoS(100, error("CheckTransaction(): txin total out of range"), REJECT_INVALID, "bad-txns-txintotal-toolarge"); } } } - - + + // Check for duplicate inputs set vInOutPoints; BOOST_FOREACH(const CTxIn& txin, tx.vin) @@ -1016,7 +1148,7 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio REJECT_INVALID, "bad-txns-inputs-duplicate"); vInOutPoints.insert(txin.prevout); } - + // Check for duplicate joinsplit nullifiers in this transaction set vJoinSplitNullifiers; BOOST_FOREACH(const JSDescription& joinsplit, tx.vjoinsplit) @@ -1025,19 +1157,19 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio { if (vJoinSplitNullifiers.count(nf)) return state.DoS(100, error("CheckTransaction(): duplicate nullifiers"), - REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate"); - + REJECT_INVALID, "bad-joinsplits-nullifiers-duplicate"); + vJoinSplitNullifiers.insert(nf); } } - + if (tx.IsCoinBase()) { // There should be no joinsplits in a coinbase transaction if (tx.vjoinsplit.size() > 0) return state.DoS(100, error("CheckTransaction(): coinbase has joinsplits"), REJECT_INVALID, "bad-cb-has-joinsplits"); - + if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100) return state.DoS(100, error("CheckTransaction(): coinbase script size"), REJECT_INVALID, "bad-cb-length"); @@ -1045,35 +1177,11 @@ bool CheckTransactionWithoutProofVerification(const CTransaction& tx, CValidatio else { BOOST_FOREACH(const CTxIn& txin, tx.vin) - if (txin.prevout.IsNull()) - return state.DoS(10, error("CheckTransaction(): prevout is null"), - REJECT_INVALID, "bad-txns-prevout-null"); - - if (tx.vjoinsplit.size() > 0) { - // Empty output script. - CScript scriptCode; - uint256 dataToBeSigned; - try { - dataToBeSigned = SignatureHash(scriptCode, tx, NOT_AN_INPUT, SIGHASH_ALL); - } catch (std::logic_error ex) { - return state.DoS(100, error("CheckTransaction(): error computing signature hash"), - REJECT_INVALID, "error-computing-signature-hash"); - } - - BOOST_STATIC_ASSERT(crypto_sign_PUBLICKEYBYTES == 32); - - // We rely on libsodium to check that the signature is canonical. - // https://github.com/jedisct1/libsodium/commit/62911edb7ff2275cccd74bf1c8aefcc4d76924e0 - if (crypto_sign_verify_detached(&tx.joinSplitSig[0], - dataToBeSigned.begin(), 32, - tx.joinSplitPubKey.begin() - ) != 0) { - return state.DoS(100, error("CheckTransaction(): invalid joinsplit signature"), - REJECT_INVALID, "bad-txns-invalid-joinsplit-signature"); - } - } + if (txin.prevout.IsNull()) + return state.DoS(10, error("CheckTransaction(): prevout is null"), + REJECT_INVALID, "bad-txns-prevout-null"); } - + return true; } @@ -1089,9 +1197,9 @@ CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowF if (dPriorityDelta > 0 || nFeeDelta > 0) return 0; } - + CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes); - + if (fAllowFree) { // There is a free transaction area in blocks created by most miners, @@ -1101,7 +1209,7 @@ CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowF if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000)) nMinFee = 0; } - + if (!MoneyRange(nMinFee)) nMinFee = MAX_MONEY; return nMinFee; @@ -1113,6 +1221,21 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa AssertLockHeld(cs_main); if (pfMissingInputs) *pfMissingInputs = false; + + int nextBlockHeight = chainActive.Height() + 1; + auto consensusBranchId = CurrentEpochBranchId(nextBlockHeight, Params().GetConsensus()); + + // Node operator can choose to reject tx by number of transparent inputs + static_assert(std::numeric_limits::max() >= std::numeric_limits::max(), "size_t too small"); + size_t limit = (size_t) GetArg("-mempooltxinputlimit", 0); + if (limit > 0) { + size_t n = tx.vin.size(); + if (n > limit) { + LogPrint("mempool", "Dropping txid %s : too many transparent inputs %zu > limit %zu\n", tx.GetHash().ToString(), n, limit ); + return false; + } + } + auto verifier = libzcash::ProofVerifier::Strict(); if ( komodo_validate_interest(tx,chainActive.Tip()->nHeight+1,chainActive.Tip()->GetMedianTimePast() + 777,0) < 0 ) { @@ -1121,9 +1244,16 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa } if (!CheckTransaction(tx, state, verifier)) { - fprintf(stderr,"accept failure.0\n"); + return error("AcceptToMemoryPool: CheckTransaction failed"); } + // DoS level set to 10 to be more forgiving. + // Check transaction contextually against the set of consensus rules which apply in the next block to be mined. + if (!ContextualCheckTransaction(tx, state, nextBlockHeight, 10)) + { + return error("AcceptToMemoryPool: ContextualCheckTransaction failed"); + } + // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) { @@ -1132,9 +1262,9 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa } // Rather not work on nonstandard transactions (unless -testnet/-regtest) string reason; - if (Params().RequireStandard() && !IsStandardTx(tx, reason)) + if (Params().RequireStandard() && !IsStandardTx(tx, reason, nextBlockHeight)) { - fprintf(stderr,"AcceptToMemoryPool nonstandard transaction: %s\n",reason.c_str()); + fprintf(stderr,"AcceptToMemoryPool reject 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 @@ -1145,99 +1275,100 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa //fprintf(stderr,"AcceptToMemoryPool reject 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 { - LOCK(pool.cs); // protect pool.mapNextTx - for (unsigned int i = 0; i < tx.vin.size(); i++) - { - COutPoint outpoint = tx.vin[i].prevout; - if (pool.mapNextTx.count(outpoint)) + LOCK(pool.cs); // protect pool.mapNextTx + for (unsigned int i = 0; i < tx.vin.size(); i++) { - static uint32_t counter; - // Disable replacement feature for now - //if ( counter++ < 100 ) - fprintf(stderr,"Disable replacement feature for now\n"); - return false; - } - } - BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) { - BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) { - if (pool.mapNullifiers.count(nf)) + COutPoint outpoint = tx.vin[i].prevout; + if (pool.mapNextTx.count(outpoint)) { - fprintf(stderr,"pool.mapNullifiers.count\n"); + static uint32_t counter; + // Disable replacement feature for now + //if ( counter++ < 100 ) + fprintf(stderr,"Disable replacement feature for now\n"); return false; } } + BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) + { + BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) + { + if (pool.mapNullifiers.count(nf)) + { + fprintf(stderr,"pool.mapNullifiers.count\n"); + return false; + } + } + } } - } - + { CCoinsView dummy; CCoinsViewCache view(&dummy); int64_t interest; CAmount nValueIn = 0; { - LOCK(pool.cs); - CCoinsViewMemPool viewMemPool(pcoinsTip, pool); - view.SetBackend(viewMemPool); - - // 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), - // and only helps with filling in pfMissingInputs (to determine missing vs spent). - BOOST_FOREACH(const CTxIn txin, tx.vin) { - if (!view.HaveCoins(txin.prevout.hash)) { - if (pfMissingInputs) - *pfMissingInputs = true; - //fprintf(stderr,"missing inputs\n"); + LOCK(pool.cs); + CCoinsViewMemPool viewMemPool(pcoinsTip, pool); + view.SetBackend(viewMemPool); + + // do we already have it? + if (view.HaveCoins(hash)) + { + fprintf(stderr,"view.HaveCoins(hash) error\n"); return false; } - } - - // are the actual inputs available? - if (!view.HaveInputs(tx)) - { - //fprintf(stderr,"accept failure.1\n"); - return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),REJECT_DUPLICATE, "bad-txns-inputs-spent"); - } - // are the joinsplit's requirements met? - if (!view.HaveJoinSplitRequirements(tx)) - { - fprintf(stderr,"accept failure.2\n"); - return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met"); - } - - // Bring the best block into scope - view.GetBestBlock(); - - nValueIn = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime); + + // do all inputs exist? + // Note that this does not check for the presence of actual outputs (see the next check for that), + // and only helps with filling in pfMissingInputs (to determine missing vs spent). + BOOST_FOREACH(const CTxIn txin, tx.vin) + { + if (!view.HaveCoins(txin.prevout.hash)) + { + if (pfMissingInputs) + *pfMissingInputs = true; + //fprintf(stderr,"missing inputs\n"); + return false; + } + } + + // are the actual inputs available? + if (!view.HaveInputs(tx)) + { + //fprintf(stderr,"accept failure.1\n"); + return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),REJECT_DUPLICATE, "bad-txns-inputs-spent"); + } + // are the joinsplit's requirements met? + if (!view.HaveJoinSplitRequirements(tx)) + { + //fprintf(stderr,"accept failure.2\n"); + return state.Invalid(error("AcceptToMemoryPool: joinsplit requirements not met"),REJECT_DUPLICATE, "bad-txns-joinsplit-requirements-not-met"); + } + + // Bring the best block into scope + view.GetBestBlock(); + + nValueIn = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime); if ( 0 && interest != 0 ) fprintf(stderr,"add interest %.8f\n",(double)interest/COIN); - // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool - view.SetBackend(dummy); + // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool + view.SetBackend(dummy); } - + // Check for non-standard pay-to-script-hash in inputs - if (Params().RequireStandard() && !AreInputsStandard(tx, view)) - { - fprintf(stderr,"accept failure.3\n"); - return error("AcceptToMemoryPool: nonstandard transaction input"); - } - + if (Params().RequireStandard() && !AreInputsStandard(tx, view, consensusBranchId)) + return error("AcceptToMemoryPool: reject nonstandard transaction input"); + // Check that the transaction doesn't have an excessive number of // sigops, making it impossible to mine. Since the coinbase transaction // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than @@ -1250,14 +1381,30 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa fprintf(stderr,"accept failure.4\n"); 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"); } - + CAmount nValueOut = tx.GetValueOut(); CAmount nFees = nValueIn-nValueOut; double dPriority = view.GetPriority(tx, chainActive.Height()); - - CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx)); + + // Keep track of transactions that spend a coinbase, which we re-scan + // during reorgs to ensure COINBASE_MATURITY is still met. + bool fSpendsCoinbase = false; + BOOST_FOREACH(const CTxIn &txin, tx.vin) { + const CCoins *coins = view.AccessCoins(txin.prevout.hash); + if (coins->IsCoinBase()) { + fSpendsCoinbase = true; + break; + } + } + + // Grab the branch ID we expect this transaction to commit to. We don't + // yet know if it does, but if the entry gets added to the mempool, then + // it has passed ContextualCheckInputs and therefore this is correct. + auto consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus()); + + CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height(), mempool.HasNoInputsOf(tx), fSpendsCoinbase, consensusBranchId); unsigned int nSize = entry.GetTxSize(); - + // Accept a tx if it contains joinsplits and has at least the default fee specified by z_sendmany. if (tx.vjoinsplit.size() > 0 && nFees >= ASYNC_RPC_OPERATION_DEFAULT_MINERS_FEE) { // In future we will we have more accurate and dynamic computation of fees for tx with joinsplits. @@ -1266,17 +1413,17 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa CAmount txMinFee = GetMinRelayFee(tx, nSize, true); if (fLimitFree && nFees < txMinFee) { - fprintf(stderr,"accept failure.5\n"); + //fprintf(stderr,"accept failure.5\n"); return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",hash.ToString(), nFees, txMinFee),REJECT_INSUFFICIENTFEE, "insufficient fee"); } } - + // Require that free transactions have sufficient priority to be mined in the next block. if (GetBoolArg("-relaypriority", false) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) { fprintf(stderr,"accept failure.6\n"); return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority"); } - + // Continuously rate-limit free (really, very-low-fee) transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make others' transactions take longer to confirm. @@ -1286,9 +1433,9 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa static double dFreeCount; static int64_t nLastTime; int64_t nNow = GetTime(); - + LOCK(csFreeLimiter); - + // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; @@ -1302,21 +1449,22 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } - + if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000 && nFees > nValueOut/19 ) { fprintf(stderr,"accept failure.8\n"); return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",hash.ToString(), nFees, ::minRelayTxFee.GetFee(nSize) * 10000); } - + // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. - if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus())) + PrecomputedTransactionData txdata(tx); + if (!ContextualCheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId)) { - fprintf(stderr,"accept failure.9\n"); + //fprintf(stderr,"accept failure.9\n"); return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString()); } - + // Check again against just the consensus-critical mandatory script // verification flags, in case of bugs in the standard flags that cause // transactions to pass as valid when they're actually invalid. For @@ -1326,20 +1474,20 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa // There is a similar check in CreateNewBlock() to prevent creating // invalid blocks, however allowing such transactions into the mempool // can be exploited as a DoS attack. - if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, Params().GetConsensus())) + if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId)) { fprintf(stderr,"accept failure.10\n"); return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString()); } - + // Store transaction in memory if ( komodo_is_notarytx(tx) == 0 ) KOMODO_ON_DEMAND++; pool.addUnchecked(hash, entry, !IsInitialBlockDownload()); } - + SyncWithWallets(tx, NULL); - + return true; } @@ -1347,14 +1495,14 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow) { CBlockIndex *pindexSlow = NULL; - + LOCK(cs_main); - + if (mempool.lookup(hash, txOut)) { return true; } - + if (fTxIndex) { CDiskTxPos postx; if (pblocktree->ReadTxIndex(hash, postx)) { @@ -1375,7 +1523,7 @@ bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock return true; } } - + if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it int nHeight = -1; { @@ -1387,7 +1535,7 @@ bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock if (nHeight > 0) pindexSlow = chainActive[nHeight]; } - + if (pindexSlow) { CBlock block; if (ReadBlockFromDisk(block, pindexSlow)) { @@ -1400,23 +1548,23 @@ bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock } } } - + return false; } /*char *komodo_getspendscript(uint256 hash,int32_t n) -{ - CTransaction tx; uint256 hashBlock; - if ( !GetTransaction(hash,tx,hashBlock,true) ) - { - printf("null GetTransaction\n"); - return(0); - } - if ( n >= 0 && n < tx.vout.size() ) - return((char *)tx.vout[n].scriptPubKey.ToString().c_str()); - else printf("getspendscript illegal n.%d\n",n); - return(0); -}*/ + { + CTransaction tx; uint256 hashBlock; + if ( !GetTransaction(hash,tx,hashBlock,true) ) + { + printf("null GetTransaction\n"); + return(0); + } + if ( n >= 0 && n < tx.vout.size() ) + return((char *)tx.vout[n].scriptPubKey.ToString().c_str()); + else printf("getspendscript illegal n.%d\n",n); + return(0); + }*/ ////////////////////////////////////////////////////////////////////////////// @@ -1430,18 +1578,18 @@ bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::M CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("WriteBlockToDisk: OpenBlockFile failed"); - + // Write index header unsigned int nSize = fileout.GetSerializeSize(block); fileout << FLATDATA(messageStart) << nSize; - + // Write block long fileOutPos = ftell(fileout.Get()); if (fileOutPos < 0) return error("WriteBlockToDisk: ftell failed"); pos.nPos = (unsigned int)fileOutPos; fileout << block; - + return true; } @@ -1449,7 +1597,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) { uint8_t pubkey33[33]; block.SetNull(); - + // Open history file to read CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION); if (filein.IsNull()) @@ -1457,7 +1605,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) //fprintf(stderr,"readblockfromdisk err A\n"); return false;//error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString()); } - + // Read block try { filein >> block; @@ -1471,7 +1619,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()))) { int32_t i; for (i=0; i<33; i++) - printf("%02x",pubkey33[i]); + fprintf(stderr,"%02x",pubkey33[i]); fprintf(stderr," warning unexpected diff at ht.%d\n",height); return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString()); @@ -1487,18 +1635,19 @@ bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex) return false; if (block.GetHash() != pindex->GetBlockHash()) return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s", - pindex->ToString(), pindex->GetBlockPos().ToString()); + pindex->ToString(), pindex->GetBlockPos().ToString()); return true; } //uint64_t komodo_moneysupply(int32_t height); extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; extern uint32_t ASSETCHAINS_MAGIC; -extern uint64_t ASSETCHAINS_SUPPLY; +extern uint64_t ASSETCHAINS_STAKED,ASSETCHAINS_ENDSUBSIDY,ASSETCHAINS_REWARD,ASSETCHAINS_HALVING,ASSETCHAINS_LINEAR,ASSETCHAINS_COMMISSION,ASSETCHAINS_SUPPLY; CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams) { - CAmount nSubsidy = 3 * COIN; + static uint64_t cached_subsidy; static int32_t cached_numhalvings; + int32_t numhalvings,i; uint64_t numerator; CAmount nSubsidy = 3 * COIN; if ( ASSETCHAINS_SYMBOL[0] == 0 ) { if ( nHeight == 1 ) @@ -1511,29 +1660,67 @@ CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams) { if ( nHeight == 1 ) return(ASSETCHAINS_SUPPLY * COIN + (ASSETCHAINS_MAGIC & 0xffffff)); - else return(10000); + else if ( ASSETCHAINS_ENDSUBSIDY == 0 || nHeight < ASSETCHAINS_ENDSUBSIDY ) + { + if ( ASSETCHAINS_REWARD == 0 ) + return(10000); + else if ( ASSETCHAINS_ENDSUBSIDY != 0 && nHeight >= ASSETCHAINS_ENDSUBSIDY ) + return(0); + else + { + nSubsidy = ASSETCHAINS_REWARD; + if ( ASSETCHAINS_HALVING != 0 ) + { + if ( (numhalvings= (nHeight / ASSETCHAINS_HALVING)) > 0 ) + { + if ( numhalvings >= 64 && ASSETCHAINS_DECAY == 0 ) + return(0); + if ( ASSETCHAINS_DECAY == 0 ) + nSubsidy >>= numhalvings; + else if ( ASSETCHAINS_DECAY == 100000000 && ASSETCHAINS_ENDSUBSIDY != 0 ) + { + numerator = (ASSETCHAINS_ENDSUBSIDY - nHeight); + nSubsidy = (nSubsidy * numerator) / ASSETCHAINS_ENDSUBSIDY; + } + else + { + if ( cached_subsidy > 0 && cached_numhalvings == numhalvings ) + nSubsidy = cached_subsidy; + else + { + for (i=0; i consensusParams.SubsidySlowStartShift()); - int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;*/ + /* + // Mining slow start + // The subsidy is ramped up linearly, skipping the middle payout of + // MAX_SUBSIDY/2 to keep the monetary curve consistent with no slow start. + if (nHeight < consensusParams.nSubsidySlowStartInterval / 2) { + nSubsidy /= consensusParams.nSubsidySlowStartInterval; + nSubsidy *= nHeight; + return nSubsidy; + } else if (nHeight < consensusParams.nSubsidySlowStartInterval) { + nSubsidy /= consensusParams.nSubsidySlowStartInterval; + nSubsidy *= (nHeight+1); + return nSubsidy; + } + + assert(nHeight > consensusParams.SubsidySlowStartShift()); + int halvings = (nHeight - consensusParams.SubsidySlowStartShift()) / consensusParams.nSubsidyHalvingInterval;*/ // Force block reward to zero when right shift is undefined. //int halvings = nHeight / consensusParams.nSubsidyHalvingInterval; //if (halvings >= 64) // return 0; - + // Subsidy is cut in half every 840,000 blocks which will occur approximately every 4 years. //nSubsidy >>= halvings; return nSubsidy; @@ -1564,10 +1751,10 @@ bool IsInitialBlockDownload() ptr = pindexBestHeader; else if ( pindexBestHeader != 0 && pindexBestHeader->nHeight > ptr->nHeight ) ptr = pindexBestHeader; - if ( ASSETCHAINS_SYMBOL[0] == 0 ) - state = ((chainActive.Height() < ptr->nHeight - 24*60) || - ptr->GetBlockTime() < (GetTime() - chainParams.MaxTipAge())); - else state = (chainActive.Height() < ptr->nHeight - 10); + //if ( ASSETCHAINS_SYMBOL[0] == 0 ) + state = ((chainActive.Height() < ptr->nHeight - 24*60) || + ptr->GetBlockTime() < (GetTime() - chainParams.MaxTipAge())); + //else state = (chainActive.Height() < ptr->nHeight - 24*60); //fprintf(stderr,"state.%d ht.%d vs %d, t.%u %u\n",state,(int32_t)chainActive.Height(),(uint32_t)ptr->nHeight,(int32_t)ptr->GetBlockTime(),(uint32_t)(GetTime() - chainParams.MaxTipAge())); if (!state) { @@ -1587,25 +1774,25 @@ void CheckForkWarningConditions() // (we assume we don't get stuck on a fork before the last checkpoint) if (IsInitialBlockDownload()) return; - + // If our best fork is no longer within 288 blocks (+/- 12 hours if no one mines it) // of our head, drop it if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 288) pindexBestForkTip = NULL; - + if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6))) { if (!fLargeWorkForkFound && pindexBestForkBase) { std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") + - pindexBestForkBase->phashBlock->ToString() + std::string("'"); + pindexBestForkBase->phashBlock->ToString() + std::string("'"); CAlert::Notify(warning, true); } if (pindexBestForkTip && pindexBestForkBase) { LogPrintf("%s: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n", __func__, - pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(), - pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString()); + pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(), + pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString()); fLargeWorkForkFound = true; } else @@ -1637,7 +1824,7 @@ void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip) break; pfork = pfork->pprev; } - + // We define a condition where we should warn the user about as a fork of at least 7 blocks // with a tip within 72 blocks (+/- 3 hours if no one mines it) of ours // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network @@ -1646,13 +1833,13 @@ void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip) // We define it this way because it allows us to only store the highest fork tip (+ base) which meets // the 7-block condition and from this always have the most-likely-to-cause-warning fork if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) && - pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) && - chainActive.Height() - pindexNewForkTip->nHeight < 72) + pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) && + chainActive.Height() - pindexNewForkTip->nHeight < 72) { pindexBestForkTip = pindexNewForkTip; pindexBestForkBase = pfork; } - + CheckForkWarningConditions(); } @@ -1661,13 +1848,13 @@ void Misbehaving(NodeId pnode, int howmuch) { if (howmuch == 0) return; - + CNodeState *state = State(pnode); if (state == NULL) return; - + state->nMisbehavior += howmuch; - int banscore = GetArg("-banscore", 100); + int banscore = GetArg("-banscore", 101); if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore) { LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior); @@ -1680,16 +1867,16 @@ void static InvalidChainFound(CBlockIndex* pindexNew) { if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork) pindexBestInvalid = pindexNew; - + LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__, - pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, - log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", - pindexNew->GetBlockTime())); + pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, + log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", + pindexNew->GetBlockTime())); CBlockIndex *tip = chainActive.Tip(); assert (tip); LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__, - tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0), - DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime())); + tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0), + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime())); CheckForkWarningConditions(); } @@ -1712,7 +1899,7 @@ void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state } } -void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight) +void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight) { if (!tx.IsCoinBase()) // mark inputs spent { @@ -1720,7 +1907,7 @@ void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCach BOOST_FOREACH(const CTxIn &txin, tx.vin) { CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash); unsigned nPos = txin.prevout.n; - + if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull()) assert(false); // mark an outpoint spent, and construct undo information @@ -1742,15 +1929,15 @@ void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCach inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight); // add outputs } -void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight) +void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight) { CTxUndo txundo; - UpdateCoins(tx, state, inputs, txundo, nHeight); + UpdateCoins(tx, inputs, txundo, nHeight); } bool CScriptCheck::operator()() { const CScript &scriptSig = ptxTo->vin[nIn].scriptSig; - if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) { + if (!VerifyScript(scriptSig, scriptPubKey, nFlags, ServerTransactionSignatureChecker(ptxTo, nIn, amount, cacheStore, *txdata), consensusBranchId, &error)) { return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error)); } return true; @@ -1764,17 +1951,17 @@ int GetSpendHeight(const CCoinsViewCache& inputs) } namespace Consensus { -bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams) -{ + bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, const Consensus::Params& consensusParams) + { // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!inputs.HaveInputs(tx)) return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString())); - + // are the JoinSplit's requirements met? if (!inputs.HaveJoinSplitRequirements(tx)) return state.Invalid(error("CheckInputs(): %s JoinSplit requirements not met", tx.GetHash().ToString())); - + CAmount nValueIn = 0; CAmount nFees = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) @@ -1782,30 +1969,30 @@ bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoins const COutPoint &prevout = tx.vin[i].prevout; const CCoins *coins = inputs.AccessCoins(prevout.hash); assert(coins); - + if (coins->IsCoinBase()) { // Ensure that coinbases are matured if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) { return state.Invalid( - error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight), - REJECT_INVALID, "bad-txns-premature-spend-of-coinbase"); + error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight), + REJECT_INVALID, "bad-txns-premature-spend-of-coinbase"); } - + // Ensure that coinbases cannot be spent to transparent outputs // Disabled on regtest if (fCoinbaseEnforcedProtectionEnabled && consensusParams.fCoinbaseMustBeProtected && !tx.vout.empty()) { return state.Invalid( - error("CheckInputs(): tried to spend coinbase with transparent outputs"), - REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs"); + error("CheckInputs(): tried to spend coinbase with transparent outputs"), + REJECT_INVALID, "bad-txns-coinbase-spend-has-transparent-outputs"); } } - + // Check for negative or overflow input values nValueIn += coins->vout[prevout.n].nValue; #ifdef KOMODO_ENABLE_INTEREST - if ( ASSETCHAINS_SYMBOL[0] == 0 && chainActive.Tip() != 0 && chainActive.Tip()->nHeight >= 60000 ) + if ( ASSETCHAINS_SYMBOL[0] == 0 && nSpendHeight > 60000 )//chainActive.Tip() != 0 && chainActive.Tip()->nHeight >= 60000 ) { if ( coins->vout[prevout.n].nValue >= 10*COIN ) { @@ -1821,18 +2008,20 @@ bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoins if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return state.DoS(100, error("CheckInputs(): txin values out of range"), REJECT_INVALID, "bad-txns-inputvalues-outofrange"); - + } - + nValueIn += tx.GetJoinSplitValueIn(); if (!MoneyRange(nValueIn)) return state.DoS(100, error("CheckInputs(): vpub_old values out of range"), REJECT_INVALID, "bad-txns-inputvalues-outofrange"); - + if (nValueIn < tx.GetValueOut()) + { + fprintf(stderr,"spentheight.%d valuein %s vs %s error\n",nSpendHeight,FormatMoney(nValueIn).c_str(), FormatMoney(tx.GetValueOut()).c_str()); return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s) diff %.8f", tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut()),((double)nValueIn - tx.GetValueOut())/COIN),REJECT_INVALID, "bad-txns-in-belowout"); - + } // Tally transaction fees CAmount nTxFee = nValueIn - tx.GetValueOut(); if (nTxFee < 0) @@ -1842,24 +2031,35 @@ bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoins if (!MoneyRange(nFees)) return state.DoS(100, error("CheckInputs(): nFees out of range"), REJECT_INVALID, "bad-txns-fee-outofrange"); - return true; -} + return true; + } }// namespace Consensus -bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, const Consensus::Params& consensusParams, std::vector *pvChecks) +bool ContextualCheckInputs( + const CTransaction& tx, + CValidationState &state, + const CCoinsViewCache &inputs, + bool fScriptChecks, + unsigned int flags, + bool cacheStore, + PrecomputedTransactionData& txdata, + const Consensus::Params& consensusParams, + uint32_t consensusBranchId, + std::vector *pvChecks) { - if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams)) - return false; - if (!tx.IsCoinBase()) { + if (!Consensus::CheckTxInputs(tx, state, inputs, GetSpendHeight(inputs), consensusParams)) { + return false; + } + if (pvChecks) pvChecks->reserve(tx.vin.size()); - + // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. - + // Skip ECDSA signature verification when connecting blocks // before the last block chain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. @@ -1868,9 +2068,9 @@ bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, cons const COutPoint &prevout = tx.vin[i].prevout; const CCoins* coins = inputs.AccessCoins(prevout.hash); assert(coins); - + // Verify signature - CScriptCheck check(*coins, tx, i, flags, cacheStore); + CScriptCheck check(*coins, tx, i, flags, cacheStore, consensusBranchId, &txdata); if (pvChecks) { pvChecks->push_back(CScriptCheck()); check.swap(pvChecks->back()); @@ -1882,9 +2082,9 @@ bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, cons // arguments; if so, don't trigger DoS protection to // avoid splitting the network between upgraded and // non-upgraded nodes. - CScriptCheck check(*coins, tx, i, - flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore); - if (check()) + CScriptCheck check2(*coins, tx, i, + flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore, consensusBranchId, &txdata); + if (check2()) return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError()))); } // Failures of other flags indicate a transaction that is @@ -1899,123 +2099,123 @@ bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, cons } } } - + return true; } /*bool ContextualCheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, const Consensus::Params& consensusParams, std::vector *pvChecks) -{ - if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) { - fprintf(stderr,"ContextualCheckInputs failure.0\n"); - return false; - } - - if (!tx.IsCoinBase()) - { - // While checking, GetBestBlock() refers to the parent block. - // This is also true for mempool checks. - CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second; - int nSpendHeight = pindexPrev->nHeight + 1; - for (unsigned int i = 0; i < tx.vin.size(); i++) - { - const COutPoint &prevout = tx.vin[i].prevout; - const CCoins *coins = inputs.AccessCoins(prevout.hash); - // Assertion is okay because NonContextualCheckInputs ensures the inputs - // are available. - assert(coins); - - // If prev is coinbase, check that it's matured - if (coins->IsCoinBase()) { - if ( ASSETCHAINS_SYMBOL[0] == 0 ) - COINBASE_MATURITY = _COINBASE_MATURITY; - if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) { - fprintf(stderr,"ContextualCheckInputs failure.1 i.%d of %d\n",i,(int32_t)tx.vin.size()); - - return state.Invalid( - error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),REJECT_INVALID, "bad-txns-premature-spend-of-coinbase"); - } - } - } - } - - return true; -}*/ + { + if (!NonContextualCheckInputs(tx, state, inputs, fScriptChecks, flags, cacheStore, consensusParams, pvChecks)) { + fprintf(stderr,"ContextualCheckInputs failure.0\n"); + return false; + } + + if (!tx.IsCoinBase()) + { + // While checking, GetBestBlock() refers to the parent block. + // This is also true for mempool checks. + CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second; + int nSpendHeight = pindexPrev->nHeight + 1; + for (unsigned int i = 0; i < tx.vin.size(); i++) + { + const COutPoint &prevout = tx.vin[i].prevout; + const CCoins *coins = inputs.AccessCoins(prevout.hash); + // Assertion is okay because NonContextualCheckInputs ensures the inputs + // are available. + assert(coins); + + // If prev is coinbase, check that it's matured + if (coins->IsCoinBase()) { + if ( ASSETCHAINS_SYMBOL[0] == 0 ) + COINBASE_MATURITY = _COINBASE_MATURITY; + if (nSpendHeight - coins->nHeight < COINBASE_MATURITY) { + fprintf(stderr,"ContextualCheckInputs failure.1 i.%d of %d\n",i,(int32_t)tx.vin.size()); + + return state.Invalid( + error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),REJECT_INVALID, "bad-txns-premature-spend-of-coinbase"); + } + } + } + } + + return true; + }*/ namespace { - -bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart) -{ - // Open history file to append - CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION); - if (fileout.IsNull()) - return error("%s: OpenUndoFile failed", __func__); - - // Write index header - unsigned int nSize = fileout.GetSerializeSize(blockundo); - fileout << FLATDATA(messageStart) << nSize; - - // Write undo data - long fileOutPos = ftell(fileout.Get()); - if (fileOutPos < 0) - return error("%s: ftell failed", __func__); - pos.nPos = (unsigned int)fileOutPos; - fileout << blockundo; - - // calculate & write checksum - CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); - hasher << hashBlock; - hasher << blockundo; - fileout << hasher.GetHash(); - - return true; -} - -bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock) -{ - // Open history file to read - CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION); - if (filein.IsNull()) - return error("%s: OpenBlockFile failed", __func__); - - // Read block - uint256 hashChecksum; - try { - filein >> blockundo; - filein >> hashChecksum; + + bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart) + { + // Open history file to append + CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION); + if (fileout.IsNull()) + return error("%s: OpenUndoFile failed", __func__); + + // Write index header + unsigned int nSize = fileout.GetSerializeSize(blockundo); + fileout << FLATDATA(messageStart) << nSize; + + // Write undo data + long fileOutPos = ftell(fileout.Get()); + if (fileOutPos < 0) + return error("%s: ftell failed", __func__); + pos.nPos = (unsigned int)fileOutPos; + fileout << blockundo; + + // calculate & write checksum + CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); + hasher << hashBlock; + hasher << blockundo; + fileout << hasher.GetHash(); + + return true; } - catch (const std::exception& e) { - return error("%s: Deserialize or I/O error - %s", __func__, e.what()); + + bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock) + { + // Open history file to read + CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION); + if (filein.IsNull()) + return error("%s: OpenBlockFile failed", __func__); + + // Read block + uint256 hashChecksum; + try { + filein >> blockundo; + filein >> hashChecksum; + } + catch (const std::exception& e) { + return error("%s: Deserialize or I/O error - %s", __func__, e.what()); + } + + // Verify checksum + CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); + hasher << hashBlock; + hasher << blockundo; + if (hashChecksum != hasher.GetHash()) + return error("%s: Checksum mismatch", __func__); + + return true; } - - // Verify checksum - CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); - hasher << hashBlock; - hasher << blockundo; - if (hashChecksum != hasher.GetHash()) - return error("%s: Checksum mismatch", __func__); - - return true; -} - -/** Abort with a message */ -bool AbortNode(const std::string& strMessage, const std::string& userMessage="") -{ - strMiscWarning = strMessage; - LogPrintf("*** %s\n", strMessage); - uiInterface.ThreadSafeMessageBox( - userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage, - "", CClientUIInterface::MSG_ERROR); - StartShutdown(); - return false; -} - -bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="") -{ - AbortNode(strMessage, userMessage); - return state.Error(strMessage); -} - + + /** Abort with a message */ + bool AbortNode(const std::string& strMessage, const std::string& userMessage="") + { + strMiscWarning = strMessage; + LogPrintf("*** %s\n", strMessage); + uiInterface.ThreadSafeMessageBox( + userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage, + "", CClientUIInterface::MSG_ERROR); + StartShutdown(); + return false; + } + + bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="") + { + AbortNode(strMessage, userMessage); + return state.Error(strMessage); + } + } // anon namespace /** @@ -2028,7 +2228,7 @@ bool AbortNode(CValidationState& state, const std::string& strMessage, const std static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out) { bool fClean = true; - + CCoinsModifier coins = view.ModifyCoins(out.hash); if (undo.nHeight != 0) { // undo data contains height: this is the last output of the prevout tx being spent @@ -2047,17 +2247,17 @@ static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const CO if (coins->vout.size() < out.n+1) coins->vout.resize(out.n+1); coins->vout[out.n] = undo.txout; - + return fClean; } bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean) { assert(pindex->GetBlockHash() == view.GetBestBlock()); - + if (pfClean) *pfClean = false; - + bool fClean = true; komodo_disconnect(pindex,block); CBlockUndo blockUndo; @@ -2066,41 +2266,41 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex return error("DisconnectBlock(): no undo data available"); if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash())) return error("DisconnectBlock(): failure reading undo data"); - + if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) return error("DisconnectBlock(): block and undo data inconsistent"); - + // undo transactions in reverse order for (int i = block.vtx.size() - 1; i >= 0; i--) { const CTransaction &tx = block.vtx[i]; uint256 hash = tx.GetHash(); - + // Check that all outputs are available and match the outputs in the block itself // exactly. { - CCoinsModifier outs = view.ModifyCoins(hash); - outs->ClearUnspendable(); - - CCoins outsBlock(tx, pindex->nHeight); - // The CCoins serialization does not serialize negative numbers. - // No network rules currently depend on the version here, so an inconsistency is harmless - // but it must be corrected before txout nversion ever influences a network rule. - if (outsBlock.nVersion < 0) - outs->nVersion = outsBlock.nVersion; - if (*outs != outsBlock) - fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted"); - - // remove outputs - outs->Clear(); + CCoinsModifier outs = view.ModifyCoins(hash); + outs->ClearUnspendable(); + + CCoins outsBlock(tx, pindex->nHeight); + // The CCoins serialization does not serialize negative numbers. + // No network rules currently depend on the version here, so an inconsistency is harmless + // but it must be corrected before txout nversion ever influences a network rule. + if (outsBlock.nVersion < 0) + outs->nVersion = outsBlock.nVersion; + if (*outs != outsBlock) + fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted"); + + // remove outputs + outs->Clear(); } - + // unspend nullifiers BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) { BOOST_FOREACH(const uint256 &nf, joinsplit.nullifiers) { view.SetNullifier(nf, false); } } - + // restore inputs if (i > 0) { // not coinbases const CTxUndo &txundo = blockUndo.vtxundo[i-1]; @@ -2114,27 +2314,27 @@ bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex } } } - + // set the old best anchor back view.PopAnchor(blockUndo.old_tree_root); - + // move best block pointer to prevout block view.SetBestBlock(pindex->pprev->GetBlockHash()); - + if (pfClean) { *pfClean = fClean; return true; } - + return fClean; } void static FlushBlockFile(bool fFinalize = false) { LOCK(cs_LastBlockFile); - + CDiskBlockPos posOld(nLastBlockFile, 0); - + FILE *fileOld = OpenBlockFile(posOld); if (fileOld) { if (fFinalize) @@ -2142,7 +2342,7 @@ void static FlushBlockFile(bool fFinalize = false) FileCommit(fileOld); fclose(fileOld); } - + fileOld = OpenUndoFile(posOld); if (fileOld) { if (fFinalize) @@ -2170,39 +2370,39 @@ void PartitionCheck(bool (*initialDownloadCheck)(), CCriticalSection& cs, const int64_t nPowTargetSpacing) { if (bestHeader == NULL || initialDownloadCheck()) return; - + static int64_t lastAlertTime = 0; int64_t now = GetAdjustedTime(); if (lastAlertTime > now-60*60*24) return; // Alert at most once per day - + const int SPAN_HOURS=4; const int SPAN_SECONDS=SPAN_HOURS*60*60; int BLOCKS_EXPECTED = SPAN_SECONDS / nPowTargetSpacing; - + boost::math::poisson_distribution poisson(BLOCKS_EXPECTED); - + std::string strWarning; int64_t startTime = GetAdjustedTime()-SPAN_SECONDS; - + LOCK(cs); const CBlockIndex* i = bestHeader; int nBlocks = 0; while (i->GetBlockTime() >= startTime) { ++nBlocks; i = i->pprev; - if (i == NULL) return; // Ran out of chain, we must not be fully sync'ed + if (i == NULL) return; // Ran out of chain, we must not be fully synced } - + // How likely is it to find that many by chance? double p = boost::math::pdf(poisson, nBlocks); - + LogPrint("partitioncheck", "%s : Found %d blocks in the last %d hours\n", __func__, nBlocks, SPAN_HOURS); LogPrint("partitioncheck", "%s : likelihood: %g\n", __func__, p); - + // Aim for one false-positive about every fifty years of normal running: const int FIFTY_YEARS = 50*365*24*60*60; double alertThreshold = 1.0 / (FIFTY_YEARS / SPAN_SECONDS); - + if (p <= alertThreshold && nBlocks < BLOCKS_EXPECTED) { // Many fewer blocks than expected: alert! @@ -2232,13 +2432,9 @@ static int64_t nTimeTotal = 0; bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck) { const CChainParams& chainparams = Params(); + //fprintf(stderr,"connectblock ht.%d\n",(int32_t)pindex->nHeight); AssertLockHeld(cs_main); -/*<<<<<<< HEA - // Check it again in case a previous version let a bad block in - bool fExpensiveChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints())); -======= -*/ bool fExpensiveChecks = true; if (fCheckpointsEnabled) { CBlockIndex *pindexLastCheckpoint = Checkpoints::GetLastCheckpoint(chainparams.Checkpoints()); @@ -2247,18 +2443,17 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin fExpensiveChecks = false; } } -//>>>>>>> zcash/master auto verifier = libzcash::ProofVerifier::Strict(); auto disabledVerifier = libzcash::ProofVerifier::Disabled(); - + // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in if (!CheckBlock(pindex->nHeight,pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, !fJustCheck, !fJustCheck)) return false; - + // verify that the view's current state corresponds to the previous block uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash(); assert(hashPrevBlock == view.GetBestBlock()); - + // Special case for the genesis block, skipping connection of its transactions // (its coinbase is unspendable) if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) { @@ -2272,7 +2467,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin } return true; } - + bool fScriptChecks = (!fCheckpointsEnabled || pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(chainparams.Checkpoints())); //if ( KOMODO_TESTNET_EXPIRATION != 0 && pindex->nHeight > KOMODO_TESTNET_EXPIRATION ) // "testnet" // return(false); @@ -2284,25 +2479,15 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"), REJECT_INVALID, "bad-txns-BIP30"); } - - unsigned int flags = SCRIPT_VERIFY_P2SH; - - // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks, - // when 75% of the network has upgraded: - if (block.nVersion >= 3) { - flags |= SCRIPT_VERIFY_DERSIG; - } - - // Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4 - // blocks, when 75% of the network has upgraded: - if (block.nVersion >= 4) { - flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY; - } - + + unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY; + + // DERSIG (BIP66) is also always enforced, but does not have a flag. + CBlockUndo blockundo; - + CCheckQueueControl control(fExpensiveChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL); - + int64_t nTimeStart = GetTimeMicros(); CAmount nFees = 0; int nInputs = 0; @@ -2312,7 +2497,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin std::vector > vPos; vPos.reserve(block.vtx.size()); blockundo.vtxundo.reserve(block.vtx.size() - 1); - + // Construct the incremental merkle tree at the current // block position, auto old_tree_root = view.GetBestAnchor(); @@ -2324,13 +2509,18 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin // This should never fail: we should always be able to get the root // that is on the tip of our chain assert(view.GetAnchorAt(old_tree_root, tree)); - + { // Consistency check: the root of the tree we're given should // match what we asked for. assert(tree.root() == old_tree_root); } - + + // Grab the consensus branch ID for the block's height + auto consensusBranchId = CurrentEpochBranchId(pindex->nHeight, Params().GetConsensus()); + + std::vector txdata; + txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated for (unsigned int i = 0; i < block.vtx.size(); i++) { const CTransaction &tx = block.vtx[i]; @@ -2339,18 +2529,18 @@ 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); + //fprintf(stderr,"ht.%d vout0 t%u\n",pindex->nHeight,tx.nLockTime); if (!tx.IsCoinBase()) { if (!view.HaveInputs(tx)) return state.DoS(100, error("ConnectBlock(): inputs missing/spent"), REJECT_INVALID, "bad-txns-inputs-missingorspent"); - + // are the JoinSplit's requirements met? if (!view.HaveJoinSplitRequirements(tx)) return state.DoS(100, error("ConnectBlock(): JoinSplit requirements not met"), REJECT_INVALID, "bad-txns-joinsplit-requirements-not-met"); - + // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. @@ -2358,11 +2548,17 @@ 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"); - + } + + txdata.emplace_back(tx); + + if (!tx.IsCoinBase()) + { nFees += view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime) - tx.GetValueOut(); sum += interest; + std::vector vChecks; - if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, chainparams.GetConsensus(), nScriptCheckThreads ? &vChecks : NULL)) + if (!ContextualCheckInputs(tx, state, view, fExpensiveChecks, flags, false, txdata[i], chainparams.GetConsensus(), consensusBranchId, nScriptCheckThreads ? &vChecks : NULL)) return false; control.Add(vChecks); } @@ -2372,45 +2568,59 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin if (i > 0) { blockundo.vtxundo.push_back(CTxUndo()); } - UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight); - + UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight); + BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit) { BOOST_FOREACH(const uint256 ¬e_commitment, joinsplit.commitments) { // Insert the note commitments into our temporary tree. - + tree.append(note_commitment); } } - + vPos.push_back(std::make_pair(tx.GetHash(), pos)); pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); } - + view.PushAnchor(tree); if (!fJustCheck) { pindex->hashAnchorEnd = tree.root(); } blockundo.old_tree_root = old_tree_root; - + int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart; LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs-1), nTimeConnect * 0.000001); - - CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus()); - if (block.vtx[0].vout[0].nValue > blockReward) - //if (block.vtx[0].GetValueOut() > blockReward) - return state.DoS(100, - error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)", - block.vtx[0].GetValueOut(), blockReward), - REJECT_INVALID, "bad-cb-amount"); - + + CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus()) + sum; + if ( ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && block.vtx[0].vout.size() > 1 ) + { + uint64_t checktoshis; + if ( (checktoshis = komodo_commission(block)) != 0 ) + { + if ( block.vtx[0].vout.size() == 2 && block.vtx[0].vout[1].nValue == checktoshis ) + blockReward += checktoshis; + else fprintf(stderr,"checktoshis %.8f vs actual vout[1] %.8f\n",dstr(checktoshis),dstr(block.vtx[0].vout[1].nValue)); + } + } + if ( block.vtx[0].GetValueOut() > blockReward+1 ) + { + if ( ASSETCHAINS_SYMBOL[0] != 0 || pindex->nHeight >= KOMODO_NOTARIES_HEIGHT1 || block.vtx[0].vout[0].nValue > blockReward ) + { + return state.DoS(100, + error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)", + block.vtx[0].GetValueOut(), blockReward), + REJECT_INVALID, "bad-cb-amount"); + } else if ( NOTARY_PUBKEY33[0] != 0 ) + fprintf(stderr,"allow nHeight.%d coinbase %.8f vs %.8f interest %.8f\n",(int32_t)pindex->nHeight,dstr(block.vtx[0].GetValueOut()),dstr(blockReward),dstr(sum)); + } if (!control.Wait()) return state.DoS(100, false); int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart; LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs-1), nTimeVerify * 0.000001); - + if (fJustCheck) return true; - + // Write undo information to disk if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS)) { @@ -2420,31 +2630,42 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin return error("ConnectBlock(): FindUndoPos failed"); if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart())) return AbortNode(state, "Failed to write undo data"); - + // update nUndoPos in block index pindex->nUndoPos = pos.nPos; pindex->nStatus |= BLOCK_HAVE_UNDO; } - + + // Now that all consensus rules have been validated, set nCachedBranchId. + // Move this if BLOCK_VALID_CONSENSUS is ever altered. + static_assert(BLOCK_VALID_CONSENSUS == BLOCK_VALID_SCRIPTS, + "nCachedBranchId must be set after all consensus rules have been validated."); + if (IsActivationHeightForAnyUpgrade(pindex->nHeight, Params().GetConsensus())) { + pindex->nStatus |= BLOCK_ACTIVATES_UPGRADE; + pindex->nCachedBranchId = CurrentEpochBranchId(pindex->nHeight, chainparams.GetConsensus()); + } else if (pindex->pprev) { + pindex->nCachedBranchId = pindex->pprev->nCachedBranchId; + } + pindex->RaiseValidity(BLOCK_VALID_SCRIPTS); setDirtyBlockIndex.insert(pindex); } - + if (fTxIndex) if (!pblocktree->WriteTxIndex(vPos)) return AbortNode(state, "Failed to write transaction index"); - + // add this block to the view's block chain view.SetBestBlock(pindex->GetBlockHash()); - + int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2; LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001); - + // Watch for changes to the previous coinbase transaction. static uint256 hashPrevBestCoinBase; GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = block.vtx[0].GetHash(); - + int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3; LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001); @@ -2474,88 +2695,88 @@ bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) { std::set setFilesToPrune; bool fFlushForPrune = false; try { - if (fPruneMode && fCheckForPruning && !fReindex) { - FindFilesToPrune(setFilesToPrune); - fCheckForPruning = false; - if (!setFilesToPrune.empty()) { - fFlushForPrune = true; - if (!fHavePruned) { - pblocktree->WriteFlag("prunedblockfiles", true); - fHavePruned = true; + if (fPruneMode && fCheckForPruning && !fReindex) { + FindFilesToPrune(setFilesToPrune); + fCheckForPruning = false; + if (!setFilesToPrune.empty()) { + fFlushForPrune = true; + if (!fHavePruned) { + pblocktree->WriteFlag("prunedblockfiles", true); + fHavePruned = true; + } } } - } - int64_t nNow = GetTimeMicros(); - // Avoid writing/flushing immediately after startup. - if (nLastWrite == 0) { - nLastWrite = nNow; - } - if (nLastFlush == 0) { - nLastFlush = nNow; - } - if (nLastSetChain == 0) { - nLastSetChain = nNow; - } - size_t cacheSize = pcoinsTip->DynamicMemoryUsage(); - // The cache is large and close to the limit, but we have time now (not in the middle of a block processing). - bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage; - // The cache is over the limit, we have to write now. - bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage; - // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash. - bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000; - // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage. - bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000; - // Combine all conditions that result in a full cache flush. - bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune; - // Write blocks and block index to disk. - if (fDoFullFlush || fPeriodicWrite) { - // Depend on nMinDiskSpace to ensure we can write block index - if (!CheckDiskSpace(0)) - return state.Error("out of disk space"); - // First make sure all block and undo data is flushed to disk. - FlushBlockFile(); - // Then update all block file information (which may refer to block and undo files). - { - std::vector > vFiles; - vFiles.reserve(setDirtyFileInfo.size()); - for (set::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) { - vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it])); - setDirtyFileInfo.erase(it++); - } - std::vector vBlocks; - vBlocks.reserve(setDirtyBlockIndex.size()); - for (set::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) { - vBlocks.push_back(*it); - setDirtyBlockIndex.erase(it++); - } - if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) { - return AbortNode(state, "Files to write to block index database"); - } + int64_t nNow = GetTimeMicros(); + // Avoid writing/flushing immediately after startup. + if (nLastWrite == 0) { + nLastWrite = nNow; + } + if (nLastFlush == 0) { + nLastFlush = nNow; + } + if (nLastSetChain == 0) { + nLastSetChain = nNow; + } + size_t cacheSize = pcoinsTip->DynamicMemoryUsage(); + // The cache is large and close to the limit, but we have time now (not in the middle of a block processing). + bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize * (10.0/9) > nCoinCacheUsage; + // The cache is over the limit, we have to write now. + bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nCoinCacheUsage; + // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash. + bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000; + // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage. + bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000; + // Combine all conditions that result in a full cache flush. + bool fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune; + // Write blocks and block index to disk. + if (fDoFullFlush || fPeriodicWrite) { + // Depend on nMinDiskSpace to ensure we can write block index + if (!CheckDiskSpace(0)) + return state.Error("out of disk space"); + // First make sure all block and undo data is flushed to disk. + FlushBlockFile(); + // Then update all block file information (which may refer to block and undo files). + { + std::vector > vFiles; + vFiles.reserve(setDirtyFileInfo.size()); + for (set::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) { + vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it])); + setDirtyFileInfo.erase(it++); + } + std::vector vBlocks; + vBlocks.reserve(setDirtyBlockIndex.size()); + for (set::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) { + vBlocks.push_back(*it); + setDirtyBlockIndex.erase(it++); + } + if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) { + return AbortNode(state, "Files to write to block index database"); + } + } + // Finally remove any pruned files + if (fFlushForPrune) + UnlinkPrunedFiles(setFilesToPrune); + nLastWrite = nNow; + } + // Flush best chain related state. This can only be done if the blocks / block index write was also done. + if (fDoFullFlush) { + // Typical CCoins structures on disk are around 128 bytes in size. + // Pushing a new one to the database can cause it to be written + // twice (once in the log, and once in the tables). This is already + // an overestimation, as most will delete an existing entry or + // overwrite one. Still, use a conservative safety factor of 2. + if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize())) + return state.Error("out of disk space"); + // Flush the chainstate (which may refer to block index entries). + if (!pcoinsTip->Flush()) + return AbortNode(state, "Failed to write to coin database"); + nLastFlush = nNow; + } + if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) { + // Update best block in wallet (so we can detect restored wallets). + GetMainSignals().SetBestChain(chainActive.GetLocator()); + nLastSetChain = nNow; } - // Finally remove any pruned files - if (fFlushForPrune) - UnlinkPrunedFiles(setFilesToPrune); - nLastWrite = nNow; - } - // Flush best chain related state. This can only be done if the blocks / block index write was also done. - if (fDoFullFlush) { - // Typical CCoins structures on disk are around 128 bytes in size. - // Pushing a new one to the database can cause it to be written - // twice (once in the log, and once in the tables). This is already - // an overestimation, as most will delete an existing entry or - // overwrite one. Still, use a conservative safety factor of 2. - if (!CheckDiskSpace(128 * 2 * 2 * pcoinsTip->GetCacheSize())) - return state.Error("out of disk space"); - // Flush the chainstate (which may refer to block index entries). - if (!pcoinsTip->Flush()) - return AbortNode(state, "Failed to write to coin database"); - nLastFlush = nNow; - } - if ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000) { - // Update best block in wallet (so we can detect restored wallets). - GetMainSignals().SetBestChain(chainActive.GetLocator()); - nLastSetChain = nNow; - } } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error while flushing: ") + e.what()); } @@ -2577,18 +2798,18 @@ void PruneAndFlush() { void static UpdateTip(CBlockIndex *pindexNew) { const CChainParams& chainParams = Params(); chainActive.SetTip(pindexNew); - + // New best block nTimeBestReceived = GetTime(); mempool.AddTransactionsUpdated(1); - + KOMODO_NEWBLOCKS++; LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%.1fMiB(%utx)\n", __func__, - chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx, - DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), - Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize()); - + chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx, + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), + Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip()), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize()); + cvBlockChange.notify_all(); - + // Check the version of the last 100 blocks to see if we need to upgrade: static bool fWarned = false; if (!IsInitialBlockDownload() && !fWarned) @@ -2613,11 +2834,13 @@ void static UpdateTip(CBlockIndex *pindexNew) { } } -/** Disconnect chainActive's tip. */ -bool static DisconnectTip(CValidationState &state) { +/** + * Disconnect chainActive's tip. You probably want to call mempool.removeForReorg and + * mempool.removeWithoutBranchId after this, with cs_main held. + */ +bool static DisconnectTip(CValidationState &state, bool fBare = false) { CBlockIndex *pindexDelete = chainActive.Tip(); assert(pindexDelete); - mempool.check(pcoinsTip); // Read block from disk. CBlock block; if (!ReadBlockFromDisk(block, pindexDelete)) @@ -2636,21 +2859,23 @@ bool static DisconnectTip(CValidationState &state) { // Write the chain state to disk, if necessary. if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED)) return false; - // Resurrect mempool transactions from the disconnected block. - BOOST_FOREACH(const CTransaction &tx, block.vtx) { - // ignore validation errors in resurrected transactions - list removed; - CValidationState stateDummy; - if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL)) - mempool.remove(tx, removed, true); + + if (!fBare) { + // Resurrect mempool transactions from the disconnected block. + BOOST_FOREACH(const CTransaction &tx, block.vtx) { + // ignore validation errors in resurrected transactions + list removed; + CValidationState stateDummy; + if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL)) + mempool.remove(tx, removed, true); + } + if (anchorBeforeDisconnect != anchorAfterDisconnect) { + // The anchor may not change between block disconnects, + // in which case we don't want to evict from the mempool yet! + mempool.removeWithAnchor(anchorBeforeDisconnect); + } } - if (anchorBeforeDisconnect != anchorAfterDisconnect) { - // The anchor may not change between block disconnects, - // in which case we don't want to evict from the mempool yet! - mempool.removeWithAnchor(anchorBeforeDisconnect); - } - mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight); - mempool.check(pcoinsTip); + // Update chainActive and related variables. UpdateTip(pindexDelete->pprev); // Get the current commitment tree @@ -2676,11 +2901,11 @@ static int64_t nTimePostConnect = 0; /** * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock * corresponding to pindexNew, to bypass loading it again from disk. + * You probably want to call mempool.removeWithoutBranchId after this, with cs_main held. */ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) { assert(pindexNew->pprev == chainActive.Tip()); - mempool.check(pcoinsTip); // Read block from disk. int64_t nTime1 = GetTimeMicros(); CBlock block; @@ -2720,7 +2945,10 @@ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock * // Remove conflicting transactions from the mempool. list txConflicted; mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted, !IsInitialBlockDownload()); - mempool.check(pcoinsTip); + + // Remove transactions that expire at new block height from mempool + mempool.removeExpired(pindexNew->nHeight); + // Update chainActive & related variables. UpdateTip(pindexNew); // Tell wallet about transactions that went from mempool @@ -2735,7 +2963,9 @@ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock * // Update cached incremental witnesses //fprintf(stderr,"chaintip true\n"); GetMainSignals().ChainTip(pindexNew, pblock, oldTree, true); - + + EnforceNodeDeprecation(pindexNew->nHeight); + int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1; LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001); LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001); @@ -2749,7 +2979,7 @@ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock * static CBlockIndex* FindMostWorkChain() { do { CBlockIndex *pindexNew = NULL; - + // Find the best candidate header. { std::set::reverse_iterator it = setBlockIndexCandidates.rbegin(); @@ -2757,14 +2987,14 @@ static CBlockIndex* FindMostWorkChain() { return NULL; pindexNew = *it; } - + // Check whether all blocks on the path between the currently active chain and the candidate are valid. // Just going until the active chain is an optimization, as we know all blocks in it are valid already. CBlockIndex *pindexTest = pindexNew; bool fInvalidAncestor = false; while (pindexTest && !chainActive.Contains(pindexTest)) { assert(pindexTest->nChainTx || pindexTest->nHeight == 0); - + // Pruned nodes may have entries in setBlockIndexCandidates for // which block files have been deleted. Remove those as candidates // for the most work chain if we come across them; we can't switch @@ -2821,77 +3051,113 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo bool fInvalidFound = false; const CBlockIndex *pindexOldTip = chainActive.Tip(); const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork); - + + // - On ChainDB initialization, pindexOldTip will be null, so there are no removable blocks. + // - If pindexMostWork is in a chain that doesn't have the same genesis block as our chain, + // then pindexFork will be null, and we would need to remove the entire chain including + // our genesis block. In practice this (probably) won't happen because of checks elsewhere. + auto reorgLength = pindexOldTip ? pindexOldTip->nHeight - (pindexFork ? pindexFork->nHeight : -1) : 0; + static_assert(MAX_REORG_LENGTH > 0, "We must be able to reorg some distance"); + if (reorgLength > MAX_REORG_LENGTH) { + auto msg = strprintf(_( + "A block chain reorganization has been detected that would roll back %d blocks! " + "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety." + ), reorgLength, MAX_REORG_LENGTH) + "\n\n" + + _("Reorganization details") + ":\n" + + "- " + strprintf(_("Current tip: %s, height %d, work %s"), + pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight, pindexOldTip->nChainWork.GetHex()) + "\n" + + "- " + strprintf(_("New tip: %s, height %d, work %s"), + pindexMostWork->phashBlock->GetHex(), pindexMostWork->nHeight, pindexMostWork->nChainWork.GetHex()) + "\n" + + "- " + strprintf(_("Fork point: %s, height %d"), + pindexFork->phashBlock->GetHex(), pindexFork->nHeight) + "\n\n" + + _("Please help, human!"); + LogPrintf("*** %s\n", msg); + uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR); + StartShutdown(); + return false; + } + // Disconnect active blocks which are no longer in the best chain. + bool fBlocksDisconnected = false; while (chainActive.Tip() && chainActive.Tip() != pindexFork) { if (!DisconnectTip(state)) return false; + fBlocksDisconnected = true; } if ( KOMODO_REWIND != 0 ) { - fprintf(stderr,"rewind start ht.%d\n",chainActive.Tip()->nHeight); - while ( KOMODO_REWIND > 0 && chainActive.Tip()->nHeight > KOMODO_REWIND ) + CBlockIndex *tipindex; + fprintf(stderr,">>>>>>>>>>> rewind start ht.%d -> KOMODO_REWIND.%d\n",chainActive.Tip()->nHeight,KOMODO_REWIND); + while ( KOMODO_REWIND > 0 && (tipindex= chainActive.Tip()) != 0 && tipindex->nHeight > KOMODO_REWIND ) { + fBlocksDisconnected = true; + fprintf(stderr,"%d ",(int32_t)tipindex->nHeight); + InvalidateBlock(state,tipindex); if ( !DisconnectTip(state) ) - { - InvalidateBlock(state,chainActive.Tip()); break; - } } - fprintf(stderr,"reached rewind.%d, best to do: ./komodo-cli stop\n",KOMODO_REWIND); - sleep(60); + fprintf(stderr,"reached rewind.%d, best to do: ./komodo-cli -ac_name=%s stop\n",KOMODO_REWIND,ASSETCHAINS_SYMBOL); + sleep(20); + fprintf(stderr,"resuming normal operations\n"); KOMODO_REWIND = 0; - return(true); + //return(true); } // Build list of new blocks to connect. std::vector vpindexToConnect; bool fContinue = true; int nHeight = pindexFork ? pindexFork->nHeight : -1; while (fContinue && nHeight != pindexMostWork->nHeight) { - // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need - // a few blocks along the way. - int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight); - vpindexToConnect.clear(); - vpindexToConnect.reserve(nTargetHeight - nHeight); - CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight); - while (pindexIter && pindexIter->nHeight != nHeight) { - vpindexToConnect.push_back(pindexIter); - pindexIter = pindexIter->pprev; - } - nHeight = nTargetHeight; - - // Connect new blocks. - BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) { - if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) { - if (state.IsInvalid()) { - // The block violates a consensus rule. - if (!state.CorruptionPossible()) - InvalidChainFound(vpindexToConnect.back()); - state = CValidationState(); - fInvalidFound = true; - fContinue = false; - break; + // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need + // a few blocks along the way. + int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight); + vpindexToConnect.clear(); + vpindexToConnect.reserve(nTargetHeight - nHeight); + CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight); + while (pindexIter && pindexIter->nHeight != nHeight) { + vpindexToConnect.push_back(pindexIter); + pindexIter = pindexIter->pprev; + } + nHeight = nTargetHeight; + + // Connect new blocks. + BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) { + if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) { + if (state.IsInvalid()) { + // The block violates a consensus rule. + if (!state.CorruptionPossible()) + InvalidChainFound(vpindexToConnect.back()); + state = CValidationState(); + fInvalidFound = true; + fContinue = false; + break; + } else { + // A system error occurred (disk space, database error, ...). + return false; + } } else { - // A system error occurred (disk space, database error, ...). - return false; - } - } else { - PruneBlockIndexCandidates(); - if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) { - // We're in a better position than we were. Return temporarily to release the lock. - fContinue = false; - break; + PruneBlockIndexCandidates(); + if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) { + // We're in a better position than we were. Return temporarily to release the lock. + fContinue = false; + break; + } } } } + + if (fBlocksDisconnected) { + mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); } - + mempool.removeWithoutBranchId( + CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus())); + mempool.check(pcoinsTip); + // Callbacks/notifications for a new best chain. if (fInvalidFound) CheckForkWarningConditionsOnNewFork(vpindexToConnect.back()); else CheckForkWarningConditions(); - + return true; } @@ -2906,23 +3172,23 @@ bool ActivateBestChain(CValidationState &state, CBlock *pblock) { const CChainParams& chainParams = Params(); do { boost::this_thread::interruption_point(); - + bool fInitialDownload; { LOCK(cs_main); pindexMostWork = FindMostWorkChain(); - + // Whether we have anything to do at all. if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip()) return true; - + if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL)) return false; pindexNewTip = chainActive.Tip(); fInitialDownload = IsInitialBlockDownload(); } // When we reach this point, we switched to a new tip (stored in pindexNewTip). - + // Notifications/callbacks that can run without cs_main if (!fInitialDownload) { uint256 hashNewTip = pindexNewTip->GetBlockHash(); @@ -2935,8 +3201,8 @@ bool ActivateBestChain(CValidationState &state, CBlock *pblock) { if (nLocalServices & NODE_NETWORK) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) - if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) - pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip)); + if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) + pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip)); } // Notify external listeners about the new tip. GetMainSignals().UpdatedBlockTip(pindexNewTip); @@ -2944,23 +3210,23 @@ bool ActivateBestChain(CValidationState &state, CBlock *pblock) { } //else fprintf(stderr,"initial download skips propagation\n"); } while(pindexMostWork != chainActive.Tip()); CheckBlockIndex(); - + // Write changes periodically to disk, after relay. if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) { return false; } - + return true; } bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) { AssertLockHeld(cs_main); - + // Mark the block itself as invalid. pindex->nStatus |= BLOCK_FAILED_VALID; setDirtyBlockIndex.insert(pindex); setBlockIndexCandidates.erase(pindex); - + while (chainActive.Contains(pindex)) { CBlockIndex *pindexWalk = chainActive.Tip(); pindexWalk->nStatus |= BLOCK_FAILED_CHILD; @@ -2969,11 +3235,14 @@ bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) { // ActivateBestChain considers blocks already in chainActive // unconditionally valid already, so force disconnect away from it. if (!DisconnectTip(state)) { + mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); + mempool.removeWithoutBranchId( + CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus())); return false; } } //LimitMempoolSize(mempool, GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60); - + // The resulting new best tip may not be in setBlockIndexCandidates anymore, so // add it again. BlockMap::iterator it = mapBlockIndex.begin(); @@ -2983,16 +3252,19 @@ bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) { } it++; } - + InvalidChainFound(pindex); + mempool.removeForReorg(pcoinsTip, chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); + mempool.removeWithoutBranchId( + CurrentEpochBranchId(chainActive.Tip()->nHeight + 1, Params().GetConsensus())); return true; } bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) { AssertLockHeld(cs_main); - + int nHeight = pindex->nHeight; - + // Remove the invalidity flag from this block and all its descendants. BlockMap::iterator it = mapBlockIndex.begin(); while (it != mapBlockIndex.end()) { @@ -3009,7 +3281,7 @@ bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) { } it++; } - + // Remove the invalidity flag from all ancestors too. while (pindex != NULL) { if (pindex->nStatus & BLOCK_FAILED_MASK) { @@ -3028,7 +3300,7 @@ CBlockIndex* AddToBlockIndex(const CBlockHeader& block) BlockMap::iterator it = mapBlockIndex.find(hash); if (it != mapBlockIndex.end()) return it->second; - + // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(block); assert(pindexNew); @@ -3049,9 +3321,9 @@ CBlockIndex* AddToBlockIndex(const CBlockHeader& block) pindexNew->RaiseValidity(BLOCK_VALID_TREE); if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork) pindexBestHeader = pindexNew; - + setDirtyBlockIndex.insert(pindexNew); - + return pindexNew; } @@ -3060,23 +3332,41 @@ bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBl { pindexNew->nTx = block.vtx.size(); pindexNew->nChainTx = 0; + CAmount sproutValue = 0; + for (auto tx : block.vtx) { + for (auto js : tx.vjoinsplit) { + sproutValue += js.vpub_old; + sproutValue -= js.vpub_new; + } + } + pindexNew->nSproutValue = sproutValue; + pindexNew->nChainSproutValue = boost::none; pindexNew->nFile = pos.nFile; pindexNew->nDataPos = pos.nPos; pindexNew->nUndoPos = 0; pindexNew->nStatus |= BLOCK_HAVE_DATA; pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS); setDirtyBlockIndex.insert(pindexNew); - + if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) { // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS. deque queue; queue.push_back(pindexNew); - + // Recursively process any descendant blocks that now may be eligible to be connected. while (!queue.empty()) { CBlockIndex *pindex = queue.front(); queue.pop_front(); pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx; + if (pindex->pprev) { + if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) { + pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue; + } else { + pindex->nChainSproutValue = boost::none; + } + } else { + pindex->nChainSproutValue = pindex->nSproutValue; + } { LOCK(cs_nBlockSequenceId); pindex->nSequenceId = nBlockSequenceId++; @@ -3097,19 +3387,19 @@ bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBl mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew)); } } - + return true; } bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false) { LOCK(cs_LastBlockFile); - + unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile; if (vinfoBlockFile.size() <= nFile) { vinfoBlockFile.resize(nFile + 1); } - + if (!fKnown) { while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) { nFile++; @@ -3120,7 +3410,7 @@ bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAdd pos.nFile = nFile; pos.nPos = vinfoBlockFile[nFile].nSize; } - + if (nFile != nLastBlockFile) { if (!fKnown) { LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString()); @@ -3128,13 +3418,13 @@ bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAdd FlushBlockFile(!fKnown); nLastBlockFile = nFile; } - + vinfoBlockFile[nFile].AddBlock(nHeight, nTime); if (fKnown) vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize); else vinfoBlockFile[nFile].nSize += nAddSize; - + if (!fKnown) { unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; @@ -3153,7 +3443,7 @@ bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAdd return state.Error("out of disk space"); } } - + setDirtyFileInfo.insert(nFile); return true; } @@ -3161,14 +3451,14 @@ bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAdd bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize) { pos.nFile = nFile; - + LOCK(cs_LastBlockFile); - + unsigned int nNewSize; pos.nPos = vinfoBlockFile[nFile].nUndoSize; nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize; setDirtyFileInfo.insert(nFile); - + unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; if (nNewChunks > nOldChunks) { @@ -3185,7 +3475,7 @@ bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigne else return state.Error("out of disk space"); } - + return true; } @@ -3209,37 +3499,80 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl } if (blockhdr.GetBlockTime() > GetAdjustedTime() + 60) return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),REJECT_INVALID, "time-too-new"); + else if ( ASSETCHAINS_STAKED != 0 && pindex != 0 && pindex->pprev != 0 && pindex->nTime <= pindex->pprev->nTime ) + { + fprintf(stderr,"ht.%d %u vs ht.%d %u, is not monotonic\n",pindex->nHeight,pindex->nTime,pindex->pprev->nHeight,pindex->pprev->nTime); + return state.Invalid(error("CheckBlockHeader(): block timestamp needs to always increase"),REJECT_INVALID, "time-too-new"); + } // Check block version //if (block.nVersion < MIN_BLOCK_VERSION) // return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low"); - + // Check Equihash solution is valid if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) ) return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); // Check proof of work matches claimed amount /*komodo_index2pubkey33(pubkey33,pindex,height); - if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) ) - return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash");*/ + if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) ) + return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash");*/ return true; } -int32_t komodo_check_deposit(int32_t height,const CBlock& block); +int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtime); + +int32_t komodo_reverify_blockcheck(CValidationState& state,int32_t height,CBlockIndex *pindex) +{ + static int32_t oneshot; + CBlockIndex *tipindex; int32_t rewindtarget; + if ( KOMODO_REWIND != 0 ) + oneshot = KOMODO_REWIND; + if ( oneshot == 0 && IsInitialBlockDownload() == 0 && (tipindex= chainActive.Tip()) != 0 ) + { + // if 200 blocks behind longestchain and no blocks for 2 hours + if ( KOMODO_LONGESTCHAIN > height+200 && KOMODO_NEWBLOCKS == 0 ) + { + if ( GetAdjustedTime() > tipindex->nTime+3600*2 ) + { + fprintf(stderr,"tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),tipindex->nTime); + KOMODO_REWIND = tipindex->nHeight - 11; + /* + rewindtarget = tipindex->nHeight - 11; + fprintf(stderr,"rewindtarget <- %d\n",rewindtarget); + oneshot = 1; + while ( rewindtarget > 0 && (tipindex= chainActive.Tip()) != 0 && tipindex->nHeight > rewindtarget ) + { + fprintf(stderr,"%d ",(int32_t)tipindex->nHeight); + InvalidateBlock(state,tipindex); + if ( !DisconnectTip(state) ) + break; + } + tipindex = chainActive.Tip(); + fprintf(stderr,"rewind done to %d\n",tipindex!=0?tipindex->nHeight:-1);*/ + } + } + } + return(0); +} + bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidationState& state, libzcash::ProofVerifier& verifier, bool fCheckPOW, bool fCheckMerkleRoot) { uint8_t pubkey33[33]; - // These are checks that are independent of context. - + // These are checks that are independent of context. + // Check that the header is valid (particularly PoW). This is mostly // redundant with the call in AcceptBlockHeader. if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW)) return false; + //komodo_index2pubkey33(pubkey33,pindex,height); komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) - return state.DoS(50, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); - + { + komodo_reverify_blockcheck(state,height,pindex); + return state.DoS(33, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); + } // Check the merkle root. if (fCheckMerkleRoot) { bool mutated; @@ -3247,7 +3580,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if (block.hashMerkleRoot != hashMerkleRoot2) return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"), REJECT_INVALID, "bad-txnmrklroot", true); - + // Check for merkle tree malleability (CVE-2012-2459): repeating sequences // of transactions in a block without affecting the merkle root of a block, // while still invalidating it. @@ -3255,16 +3588,16 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat return state.DoS(100, error("CheckBlock(): duplicate transaction"), REJECT_INVALID, "bad-txns-duplicate", true); } - + // All potential-corruption validation must be done before we do any // transaction validation, as otherwise we may mark the header as invalid // because we receive the wrong transactions for it. - + // Size limits if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return state.DoS(100, error("CheckBlock(): size limits failed"), REJECT_INVALID, "bad-blk-length"); - + // First transaction must be coinbase, the rest must not be if (block.vtx.empty() || !block.vtx[0].IsCoinBase()) return state.DoS(100, error("CheckBlock(): first tx is not coinbase"), @@ -3273,12 +3606,12 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if (block.vtx[i].IsCoinBase()) return state.DoS(100, error("CheckBlock(): more than one coinbase"), REJECT_INVALID, "bad-cb-multiple"); - + // Check transactions BOOST_FOREACH(const CTransaction& tx, block.vtx) { - if ( komodo_validate_interest(tx,komodo_block2height((CBlock *)&block),block.nTime,1) < 0 ) - return error("CheckBlock: komodo_validate_interest failed"); + if ( komodo_validate_interest(tx,height == 0 ? komodo_block2height((CBlock *)&block) : height,block.nTime,1) < 0 ) + return error("CheckBlock: komodo_validate_interest failed"); if (!CheckTransaction(tx, state, verifier)) return error("CheckBlock(): CheckTransaction failed"); } @@ -3290,10 +3623,11 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if (nSigOps > MAX_BLOCK_SIGOPS) return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"), REJECT_INVALID, "bad-blk-sigops", true); - if ( komodo_check_deposit(ASSETCHAINS_SYMBOL[0] == 0 ? height : pindex != 0 ? (int32_t)pindex->nHeight : chainActive.Tip()->nHeight+1,block) < 0 ) + if ( komodo_check_deposit(height,block,(pindex==0||pindex->pprev==0)?0:pindex->pprev->nTime) < 0 ) + //if ( komodo_check_deposit(ASSETCHAINS_SYMBOL[0] == 0 ? height : pindex != 0 ? (int32_t)pindex->nHeight : chainActive.Tip()->nHeight+1,block,pindex==0||pindex->pprev==0?0:pindex->pprev->nTime) < 0 ) { static uint32_t counter; - if ( counter++ < 100 ) + if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) fprintf(stderr,"check deposit rejection\n"); return(false); } @@ -3307,11 +3641,11 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta uint256 hash = block.GetHash(); if (hash == consensusParams.hashGenesisBlock) return true; - + assert(pindexPrev); - + int nHeight = pindexPrev->nHeight+1; - + // Check proof of work if ( (nHeight < 235300 || nHeight > 236000) && block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams)) { @@ -3319,14 +3653,15 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta return state.DoS(100, error("%s: incorrect proof of work", __func__), REJECT_INVALID, "bad-diffbits"); } - + // Check timestamp against prev if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast()) return state.Invalid(error("%s: block's timestamp is too early", __func__), REJECT_INVALID, "time-too-old"); - + if (fCheckpointsEnabled) { + // Check that the block chain matches the known block chain up to a checkpoint if (!Checkpoints::CheckBlock(chainParams.Checkpoints(), nHeight, hash)) { CBlockIndex *heightblock = chainActive[nHeight]; @@ -3355,7 +3690,7 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta if (block.nVersion < 4) return state.Invalid(error("%s : rejected nVersion<4 block", __func__), REJECT_OBSOLETE, "bad-version"); - + return true; } @@ -3363,23 +3698,28 @@ bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIn { const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1; const Consensus::Params& consensusParams = Params().GetConsensus(); - + // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, block.vtx) { + + // Check transaction contextually against consensus rules at block height + if (!ContextualCheckTransaction(tx, state, nHeight, 100)) { + return false; // Failure reason has been set in validation state object + } + int nLockTimeFlags = 0; int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST) - ? pindexPrev->GetMedianTimePast() - : block.GetBlockTime(); + ? pindexPrev->GetMedianTimePast() + : block.GetBlockTime(); if (!IsFinalTx(tx, nHeight, nLockTimeCutoff)) { return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal"); } } - - // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height - // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet): - // Since MIN_BLOCK_VERSION = 4 all blocks with nHeight > 0 should satisfy this. - // This rule is not applied to the genesis block, which didn't include the height - // in the coinbase. + + // Enforce BIP 34 rule that the coinbase starts with serialized block height. + // In Zcash this has been enforced since launch, except that the genesis + // block didn't include the height in the coinbase (see Zcash protocol spec + // section '6.8 Bitcoin Improvement Proposals'). if (nHeight > 0) { CScript expect = CScript() << nHeight; @@ -3388,7 +3728,7 @@ bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIn return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height"); } } - + return true; } @@ -3405,9 +3745,17 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc pindex = miSelf->second; if (ppindex) *ppindex = pindex; - if (pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK) - return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); - if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 + if ( pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK ) + { + komodo_reverify_blockcheck(state,pindex->nHeight,pindex); + if ( KOMODO_LONGESTCHAIN != 0 && pindex->nHeight > KOMODO_LONGESTCHAIN-100 ) + return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); + else + { + pindex->nStatus &= ~BLOCK_FAILED_MASK; + } + } + if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 debug test { if (!CheckBlockHeader(pindex->nHeight,pindex, block, state)) { @@ -3440,18 +3788,20 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc return false; } } - return true; + return true; } - + if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state)) return false; - + // Get prev block index CBlockIndex* pindexPrev = NULL; if (hash != chainparams.GetConsensus().hashGenesisBlock) { BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); if (mi == mapBlockIndex.end()) + { return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk"); + } pindexPrev = (*mi).second; if (pindexPrev == 0 || (pindexPrev->nStatus & BLOCK_FAILED_MASK) ) return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk"); @@ -3459,7 +3809,10 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc if (!ContextualCheckBlockHeader(block, state, pindexPrev)) return false; if (pindex == NULL) - pindex = AddToBlockIndex(block); + { + if ( (pindex= AddToBlockIndex(block)) == 0 ) + fprintf(stderr,"couldnt add to block index\n"); + } if (ppindex) *ppindex = pindex; return true; @@ -3469,7 +3822,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, { const CChainParams& chainparams = Params(); AssertLockHeld(cs_main); - + CBlockIndex *&pindex = *ppindex; if (!AcceptBlockHeader(block, state, &pindex)) return false; @@ -3489,7 +3842,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, // regardless of whether pruning is enabled; it should generally be safe to // not process unrequested blocks. bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP)); - + // TODO: deal better with return value and error conditions for duplicate // and unrequested blocks. if (fAlreadyHave) return true; @@ -3498,7 +3851,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, if (!fHasMoreWork) return true; // Don't process less-work chains if (fTooFarAhead) return true; // Block height is too high } - + // See method docstring for why this is always disabled auto verifier = libzcash::ProofVerifier::Disabled(); if ((!CheckBlock(pindex->nHeight,pindex,block, state, verifier)) || !ContextualCheckBlock(block, state, pindex->pprev)) { @@ -3508,9 +3861,9 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, } return false; } - + int nHeight = pindex->nHeight; - + // Write block to history file try { unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); @@ -3527,10 +3880,10 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error: ") + e.what()); } - + if (fCheckForPruning) FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files - + return true; } @@ -3562,12 +3915,15 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc LOCK(cs_main); bool fRequested = MarkBlockAsReceived(pblock->GetHash()); fRequested |= fForceProcessing; - if (!checked) { + if (!checked) + { if ( pfrom != 0 ) + { Misbehaving(pfrom->GetId(), 1); + } return error("%s: CheckBlock FAILED", __func__); } - + // Store to disk CBlockIndex *pindex = NULL; bool ret = AcceptBlock(*pblock, state, &pindex, fRequested, dbp); @@ -3578,10 +3934,10 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc if (!ret) return error("%s: AcceptBlock FAILED", __func__); } - + if (!ActivateBestChain(state, pblock)) return error("%s: ActivateBestChain failed", __func__); - + return true; } @@ -3589,14 +3945,14 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex { AssertLockHeld(cs_main); assert(pindexPrev == chainActive.Tip()); - + CCoinsViewCache viewNew(pcoinsTip); CBlockIndex indexDummy(block); indexDummy.pprev = pindexPrev; indexDummy.nHeight = pindexPrev->nHeight + 1; // JoinSplit proofs are verified in ConnectBlock auto verifier = libzcash::ProofVerifier::Disabled(); - + // NOTE: CheckBlockHeader is called by CheckBlock if (!ContextualCheckBlockHeader(block, state, pindexPrev)) { @@ -3619,7 +3975,7 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex return false; } assert(state.IsValid()); - + return true; } @@ -3649,7 +4005,7 @@ void PruneOneBlockFile(const int fileNumber) pindex->nDataPos = 0; pindex->nUndoPos = 0; setDirtyBlockIndex.insert(pindex); - + // Prune from mapBlocksUnlinked -- any block we prune would have // to be downloaded again in order to consider its chain, at which // point it would be considered as a candidate for @@ -3664,7 +4020,7 @@ void PruneOneBlockFile(const int fileNumber) } } } - + vinfoBlockFile[fileNumber].SetNull(); setDirtyFileInfo.insert(fileNumber); } @@ -3690,7 +4046,7 @@ void FindFilesToPrune(std::set& setFilesToPrune) if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) { return; } - + unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP; uint64_t nCurrentUsage = CalculateCurrentUsage(); // We don't check to prune until after we've allocated new space for files @@ -3699,21 +4055,21 @@ void FindFilesToPrune(std::set& setFilesToPrune) uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE; uint64_t nBytesToPrune; int count=0; - + if (nCurrentUsage + nBuffer >= nPruneTarget) { for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) { nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize; - + if (vinfoBlockFile[fileNumber].nSize == 0) continue; - + if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target? break; - + // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) continue; - + PruneOneBlockFile(fileNumber); // Queue up the files for removal setFilesToPrune.insert(fileNumber); @@ -3721,26 +4077,28 @@ void FindFilesToPrune(std::set& setFilesToPrune) count++; } } - + LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n", - nPruneTarget/1024/1024, nCurrentUsage/1024/1024, - ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024, - nLastBlockWeCanPrune, count); + nPruneTarget/1024/1024, nCurrentUsage/1024/1024, + ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024, + nLastBlockWeCanPrune, count); } bool CheckDiskSpace(uint64_t nAdditionalBytes) { uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available; - + // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) return AbortNode("Disk space is low!", _("Error: Disk space is low!")); - + return true; } + FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) { + static int32_t didinit[1000]; long fsize,fpos; int32_t incr = 16*1024*1024; if (pos.IsNull()) return NULL; boost::filesystem::path path = GetBlockPosFilename(pos, prefix); @@ -3752,6 +4110,26 @@ FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) LogPrintf("Unable to open file %s\n", path.string()); return NULL; } + if ( pos.nFile < sizeof(didinit)/sizeof(*didinit) && didinit[pos.nFile] == 0 && strcmp(prefix,(char *)"blk") == 0 ) + { + fpos = ftell(file); + fseek(file,0,SEEK_END); + fsize = ftell(file); + if ( fsize > incr ) + { + char *ignore = (char *)malloc(incr); + if ( ignore != 0 ) + { + rewind(file); + while ( fread(ignore,1,incr,file) == incr ) + fprintf(stderr,"."); + free(ignore); + fprintf(stderr,"blk.%d loaded %ld bytes set fpos.%ld loading.%d\n",(int)pos.nFile,(long)ftell(file),(long)fpos,KOMODO_LOADINGBLOCKS); + } + } + fseek(file,fpos,SEEK_SET); + didinit[pos.nFile] = 1; + } if (pos.nPos) { if (fseek(file, pos.nPos, SEEK_SET)) { LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string()); @@ -3779,30 +4157,32 @@ CBlockIndex * InsertBlockIndex(uint256 hash) { if (hash.IsNull()) return NULL; - + // Return existing BlockMap::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) return (*mi).second; - + // Create new CBlockIndex* pindexNew = new CBlockIndex(); if (!pindexNew) throw runtime_error("LoadBlockIndex(): new CBlockIndex failed"); mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); - + return pindexNew; } +//void komodo_pindex_init(CBlockIndex *pindex,int32_t height); + bool static LoadBlockIndexDB() { const CChainParams& chainparams = Params(); if (!pblocktree->LoadBlockIndexGuts()) return false; - + boost::this_thread::interruption_point(); - + // Calculate nChainWork vector > vSortedByHeight; vSortedByHeight.reserve(mapBlockIndex.size()); @@ -3810,6 +4190,7 @@ bool static LoadBlockIndexDB() { CBlockIndex* pindex = item.second; vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); + //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } sort(vSortedByHeight.begin(), vSortedByHeight.end()); BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) @@ -3822,14 +4203,34 @@ bool static LoadBlockIndexDB() if (pindex->pprev) { if (pindex->pprev->nChainTx) { pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx; + if (pindex->pprev->nChainSproutValue && pindex->nSproutValue) { + pindex->nChainSproutValue = *pindex->pprev->nChainSproutValue + *pindex->nSproutValue; + } else { + pindex->nChainSproutValue = boost::none; + } } else { pindex->nChainTx = 0; + pindex->nChainSproutValue = boost::none; mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex)); } } else { pindex->nChainTx = pindex->nTx; + pindex->nChainSproutValue = pindex->nSproutValue; } } + // Construct in-memory chain of branch IDs. + // Relies on invariant: a block that does not activate a network upgrade + // will always be valid under the same consensus rules as its parent. + // Genesis block has a branch ID of zero by definition, but has no + // validity status because it is side-loaded into a fresh chain. + // Activation blocks will have branch IDs set (read from disk). + if (pindex->pprev) { + if (pindex->IsValid(BLOCK_VALID_CONSENSUS) && !pindex->nCachedBranchId) { + pindex->nCachedBranchId = pindex->pprev->nCachedBranchId; + } + } else { + pindex->nCachedBranchId = SPROUT_BRANCH_ID; + } if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL)) setBlockIndexCandidates.insert(pindex); if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork)) @@ -3838,8 +4239,9 @@ bool static LoadBlockIndexDB() pindex->BuildSkip(); if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex))) pindexBestHeader = pindex; + //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } - + // Load block file info pblocktree->ReadLastBlockFile(nLastBlockFile); vinfoBlockFile.resize(nLastBlockFile + 1); @@ -3856,7 +4258,7 @@ bool static LoadBlockIndexDB() break; } } - + // Check presence of blk files LogPrintf("Checking all blk files are present...\n"); set setBlkDataFiles; @@ -3866,6 +4268,7 @@ bool static LoadBlockIndexDB() if (pindex->nStatus & BLOCK_HAVE_DATA) { setBlkDataFiles.insert(pindex->nFile); } + //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } for (std::set::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) { @@ -3874,21 +4277,21 @@ bool static LoadBlockIndexDB() return false; } } - + // Check whether we have ever pruned block & undo files pblocktree->ReadFlag("prunedblockfiles", fHavePruned); if (fHavePruned) LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n"); - + // Check whether we need to continue reindexing bool fReindexing = false; pblocktree->ReadReindexing(fReindexing); fReindex |= fReindexing; - + // Check whether we have a transaction index pblocktree->ReadFlag("txindex", fTxIndex); LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled"); - + // Fill in-memory data BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex) { @@ -3901,8 +4304,9 @@ bool static LoadBlockIndexDB() if (pindex->pprev) { pindex->pprev->hashAnchorEnd = pindex->hashAnchor; } + //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } - + // Load pointer to end of best chain BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); if (it == mapBlockIndex.end()) @@ -3910,14 +4314,16 @@ bool static LoadBlockIndexDB() chainActive.SetTip(it->second); // Set hashAnchorEnd for the end of best chain it->second->hashAnchorEnd = pcoinsTip->GetBestAnchor(); - + PruneBlockIndexCandidates(); - + LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__, - chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), - DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), - Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip())); - + chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), + DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), + Checkpoints::GuessVerificationProgress(chainparams.Checkpoints(), chainActive.Tip())); + + EnforceNodeDeprecation(chainActive.Height(), true); + return true; } @@ -3936,7 +4342,7 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth LOCK(cs_main); if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL) return true; - + // Verify blocks in the best chain if (nCheckDepth <= 0) nCheckDepth = 1000000000; // suffices until the year 19000 @@ -3990,7 +4396,7 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth } if (pindexFailure) return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions); - + // check level 4: try reconnecting blocks if (nCheckLevel >= 4) { CBlockIndex *pindex = pindexState; @@ -4005,9 +4411,144 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); } } - + LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions); + + return true; +} +bool RewindBlockIndex(const CChainParams& params) +{ + LOCK(cs_main); + + // RewindBlockIndex is called after LoadBlockIndex, so at this point every block + // index will have nCachedBranchId set based on the values previously persisted + // to disk. By definition, a set nCachedBranchId means that the block was + // fully-validated under the corresponding consensus rules. Thus we can quickly + // identify whether the current active chain matches our expected sequence of + // consensus rule changes, with two checks: + // + // - BLOCK_ACTIVATES_UPGRADE is set only on blocks that activate upgrades. + // - nCachedBranchId for each block matches what we expect. + auto sufficientlyValidated = [¶ms](const CBlockIndex* pindex) { + auto consensus = params.GetConsensus(); + bool fFlagSet = pindex->nStatus & BLOCK_ACTIVATES_UPGRADE; + bool fFlagExpected = IsActivationHeightForAnyUpgrade(pindex->nHeight, consensus); + return fFlagSet == fFlagExpected && + pindex->nCachedBranchId && + *pindex->nCachedBranchId == CurrentEpochBranchId(pindex->nHeight, consensus); + }; + + int nHeight = 1; + while (nHeight <= chainActive.Height()) { + if (!sufficientlyValidated(chainActive[nHeight])) { + break; + } + nHeight++; + } + + // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1 + auto rewindLength = chainActive.Height() - nHeight; + if (rewindLength > 0 && rewindLength > MAX_REORG_LENGTH) { + auto pindexOldTip = chainActive.Tip(); + auto pindexRewind = chainActive[nHeight - 1]; + auto msg = strprintf(_( + "A block chain rewind has been detected that would roll back %d blocks! " + "This is larger than the maximum of %d blocks, and so the node is shutting down for your safety." + ), rewindLength, MAX_REORG_LENGTH) + "\n\n" + + _("Rewind details") + ":\n" + + "- " + strprintf(_("Current tip: %s, height %d"), + pindexOldTip->phashBlock->GetHex(), pindexOldTip->nHeight) + "\n" + + "- " + strprintf(_("Rewinding to: %s, height %d"), + pindexRewind->phashBlock->GetHex(), pindexRewind->nHeight) + "\n\n" + + _("Please help, human!"); + LogPrintf("*** %s\n", msg); + uiInterface.ThreadSafeMessageBox(msg, "", CClientUIInterface::MSG_ERROR); + StartShutdown(); + return false; + } + + CValidationState state; + CBlockIndex* pindex = chainActive.Tip(); + while (chainActive.Height() >= nHeight) { + if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) { + // If pruning, don't try rewinding past the HAVE_DATA point; + // since older blocks can't be served anyway, there's + // no need to walk further, and trying to DisconnectTip() + // will fail (and require a needless reindex/redownload + // of the blockchain). + break; + } + if (!DisconnectTip(state, true)) { + return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight); + } + // Occasionally flush state to disk. + if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) + return false; + } + + // Reduce validity flag and have-data flags. + // We do this after actual disconnecting, otherwise we'll end up writing the lack of data + // to disk before writing the chainstate, resulting in a failure to continue if interrupted. + for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) { + CBlockIndex* pindexIter = it->second; + + // Note: If we encounter an insufficiently validated block that + // is on chainActive, it must be because we are a pruning node, and + // this block or some successor doesn't HAVE_DATA, so we were unable to + // rewind all the way. Blocks remaining on chainActive at this point + // must not have their validity reduced. + if (!sufficientlyValidated(pindexIter) && !chainActive.Contains(pindexIter)) { + // Reduce validity + pindexIter->nStatus = + std::min(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | + (pindexIter->nStatus & ~BLOCK_VALID_MASK); + // Remove have-data flags + pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO); + // Remove branch ID + pindexIter->nStatus &= ~BLOCK_ACTIVATES_UPGRADE; + pindexIter->nCachedBranchId = boost::none; + // Remove storage location + pindexIter->nFile = 0; + pindexIter->nDataPos = 0; + pindexIter->nUndoPos = 0; + // Remove various other things + pindexIter->nTx = 0; + pindexIter->nChainTx = 0; + pindexIter->nSproutValue = boost::none; + pindexIter->nChainSproutValue = boost::none; + pindexIter->nSequenceId = 0; + // Make sure it gets written + setDirtyBlockIndex.insert(pindexIter); + if (pindexIter == pindexBestInvalid) + { + fprintf(stderr,"Reset invalid block marker if it was pointing to this block\n"); + pindexBestInvalid = NULL; + } + + // Update indices + setBlockIndexCandidates.erase(pindexIter); + auto ret = mapBlocksUnlinked.equal_range(pindexIter->pprev); + while (ret.first != ret.second) { + if (ret.first->second == pindexIter) { + mapBlocksUnlinked.erase(ret.first++); + } else { + ++ret.first; + } + } + } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) { + setBlockIndexCandidates.insert(pindexIter); + } + } + + PruneBlockIndexCandidates(); + + CheckBlockIndex(); + + if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) { + return false; + } + return true; } @@ -4034,7 +4575,7 @@ void UnloadBlockIndex() setDirtyFileInfo.clear(); mapNodeState.clear(); recentRejects.reset(NULL); - + BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) { delete entry.second; } @@ -4051,7 +4592,6 @@ bool LoadBlockIndex() KOMODO_LOADINGBLOCKS = 0; return false; } - //KOMODO_LOADINGBLOCKS = 0; fprintf(stderr,"finished loading blocks %s\n",ASSETCHAINS_SYMBOL); return true; } @@ -4060,19 +4600,19 @@ bool LoadBlockIndex() bool InitBlockIndex() { const CChainParams& chainparams = Params(); LOCK(cs_main); - + // Initialize global variables that cannot be constructed at startup. recentRejects.reset(new CRollingBloomFilter(120000, 0.000001)); - + // Check whether we're already initialized if (chainActive.Genesis() != NULL) return true; - + // Use the provided setting for -txindex in the new database fTxIndex = GetBoolArg("-txindex", true); pblocktree->WriteFlag("txindex", fTxIndex); LogPrintf("Initializing databases...\n"); - + // Only add the genesis block if not reindexing (in which case we reuse the one already on disk) if (!fReindex) { try { @@ -4086,6 +4626,8 @@ bool InitBlockIndex() { if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) return error("LoadBlockIndex(): writing genesis block to disk failed"); CBlockIndex *pindex = AddToBlockIndex(block); + if ( pindex == 0 ) + return error("LoadBlockIndex(): couldnt add to block index"); if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) return error("LoadBlockIndex(): genesis block not accepted"); if (!ActivateBestChain(state, &block)) @@ -4096,7 +4638,7 @@ bool InitBlockIndex() { return error("LoadBlockIndex(): failed to initialize block database: %s", e.what()); } } - + return true; } @@ -4108,7 +4650,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) // Map of disk positions for blocks with unknown parent (only used for reindex) static std::multimap mapBlocksUnknownParent; int64_t nStart = GetTimeMillis(); - + int nLoaded = 0; try { // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor @@ -4116,7 +4658,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) uint64_t nRewind = blkdat.GetPos(); while (!blkdat.eof()) { boost::this_thread::interruption_point(); - + blkdat.SetPos(nRewind); nRewind++; // start one byte further next time, in case of failure blkdat.SetLimit(); // remove former limit @@ -4147,17 +4689,17 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) CBlock block; blkdat >> block; nRewind = blkdat.GetPos(); - + // detect out of order blocks, and store them for later uint256 hash = block.GetHash(); if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) { LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(), - block.hashPrevBlock.ToString()); + block.hashPrevBlock.ToString()); if (dbp) mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp)); continue; } - + // process in case the block isn't known yet if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) { CValidationState state; @@ -4168,7 +4710,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) { LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight); } - + // Recursively process earlier encountered successors of this block deque queue; queue.push_back(hash); @@ -4181,7 +4723,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) if (ReadBlockFromDisk(mapBlockIndex[hash]!=0?mapBlockIndex[hash]->nHeight:0,block, it->second)) { LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(), - head.ToString()); + head.ToString()); CValidationState dummy; if (ProcessNewBlock(0,dummy, NULL, &block, true, &it->second)) { @@ -4211,9 +4753,9 @@ void static CheckBlockIndex() if (!fCheckBlockIndex) { return; } - + LOCK(cs_main); - + // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain, // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when // iterating the block tree require that chainActive has been initialized.) @@ -4221,20 +4763,20 @@ void static CheckBlockIndex() assert(mapBlockIndex.size() <= 1); return; } - + // Build forward-pointing map of the entire block tree. std::multimap forward; for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) { forward.insert(std::make_pair(it->second->pprev, it->second)); } - + assert(forward.size() == mapBlockIndex.size()); - + std::pair::iterator,std::multimap::iterator> rangeGenesis = forward.equal_range(NULL); CBlockIndex *pindex = rangeGenesis.first->second; rangeGenesis.first++; assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL. - + // Iterate over the entire block tree, using depth-first search. // Along the way, remember whether there are blocks on the path from genesis // block being explored which are the first to have certain properties. @@ -4256,7 +4798,7 @@ void static CheckBlockIndex() if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex; if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex; if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex; - + // Begin: actual consistency checks. if (pindex->pprev == NULL) { // Genesis block checks. @@ -4342,7 +4884,7 @@ void static CheckBlockIndex() } // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow // End: actual consistency checks. - + // Try descending into the first subnode. std::pair::iterator,std::multimap::iterator> range = forward.equal_range(pindex); if (range.first != range.second) { @@ -4385,7 +4927,7 @@ void static CheckBlockIndex() } } } - + // Check that we actually traversed the entire map. assert(nNodes == forward.size()); } @@ -4400,20 +4942,20 @@ std::string GetWarnings(const std::string& strFor) int nPriority = 0; string strStatusBar; string strRPC; - + if (!CLIENT_VERSION_IS_RELEASE) strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications"); - + if (GetBoolArg("-testsafemode", false)) strStatusBar = strRPC = "testsafemode enabled"; - + // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } - + if (fLargeWorkForkFound) { nPriority = 2000; @@ -4424,7 +4966,7 @@ std::string GetWarnings(const std::string& strFor) nPriority = 2000; strStatusBar = strRPC = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade."); } - + // Alerts { LOCK(cs_mapAlerts); @@ -4441,7 +4983,7 @@ std::string GetWarnings(const std::string& strFor) } } } - + if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") @@ -4467,7 +5009,7 @@ bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { switch (inv.type) { - case MSG_TX: + case MSG_TX: { assert(recentRejects); if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip) @@ -4479,14 +5021,14 @@ bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash(); recentRejects->reset(); } - + return recentRejects->contains(inv.hash) || - mempool.exists(inv.hash) || - mapOrphanTransactions.count(inv.hash) || - pcoinsTip->HaveCoins(inv.hash); + mempool.exists(inv.hash) || + mapOrphanTransactions.count(inv.hash) || + pcoinsTip->HaveCoins(inv.hash); } - case MSG_BLOCK: - return mapBlockIndex.count(inv.hash); + case MSG_BLOCK: + return mapBlockIndex.count(inv.hash); } // Don't know what it is, just say we already got one return true; @@ -4495,21 +5037,21 @@ bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) void static ProcessGetData(CNode* pfrom) { std::deque::iterator it = pfrom->vRecvGetData.begin(); - + vector vNotFound; - + LOCK(cs_main); - + while (it != pfrom->vRecvGetData.end()) { // Don't bother if send buffer is too full to respond anyway if (pfrom->nSendSize >= SendBufferSize()) break; - + const CInv &inv = *it; { boost::this_thread::interruption_point(); it++; - + if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) { bool send = false; @@ -4524,8 +5066,8 @@ void static ProcessGetData(CNode* pfrom) // chain if they are valid, and no more than a month older (both in time, and in // best equivalent proof of work) than the best header chain we know about. send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) && - (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) && - (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth); + (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) && + (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, Params().GetConsensus()) < nOneMonth); if (!send) { LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId()); } @@ -4613,17 +5155,17 @@ void static ProcessGetData(CNode* pfrom) vNotFound.push_back(inv); } } - + // Track requests for our stuff. GetMainSignals().Inventory(inv.hash); - + if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) break; } } - + pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it); - + if (!vNotFound.empty()) { // Let the peer know that we didn't find what it asked for, so it doesn't // have to wait around forever. Currently only SPV clients actually care @@ -4646,10 +5188,10 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } - - - - + + + + if (strCommand == "version") { // Each connection can only send one version message @@ -4659,7 +5201,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, Misbehaving(pfrom->GetId(), 1); return false; } - + int64_t nTime; CAddress addrMe; CAddress addrFrom; @@ -4674,7 +5216,20 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->fDisconnect = true; return false; } - + + // When Overwinter is active, reject incoming connections from non-Overwinter nodes + const Consensus::Params& params = Params().GetConsensus(); + if (NetworkUpgradeActive(GetHeight(), params, Consensus::UPGRADE_OVERWINTER) + && pfrom->nVersion < params.vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion) + { + LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion); + pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE, + strprintf("Version must be %d or greater", + params.vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion)); + pfrom->fDisconnect = true; + return false; + } + if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) @@ -4689,7 +5244,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message else pfrom->fRelayTxes = true; - + // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { @@ -4697,26 +5252,26 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->fDisconnect = true; return true; } - + pfrom->addrLocal = addrMe; if (pfrom->fInbound && addrMe.IsRoutable()) { SeenLocal(addrMe); } - + // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); - + pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); - + // Potentially mark this peer as a preferred download peer. UpdatePreferredDownload(pfrom, State(pfrom->GetId())); - + // Change version pfrom->PushMessage("verack"); pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); - + if (!pfrom->fInbound) { // Advertise our address @@ -4733,7 +5288,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->PushAddress(addr); } } - + // Get recent addresses if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { @@ -4748,56 +5303,72 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, addrman.Good(addrFrom); } } - + // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) - item.second.RelayTo(pfrom); + item.second.RelayTo(pfrom); } - + pfrom->fSuccessfullyConnected = true; - + string remoteAddr; if (fLogIPs) remoteAddr = ", peeraddr=" + pfrom->addr.ToString(); - + LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n", pfrom->cleanSubVer, pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString(), pfrom->id, remoteAddr); - + int64_t nTimeOffset = nTime - GetTime(); pfrom->nTimeOffset = nTimeOffset; AddTimeData(pfrom->addr, nTimeOffset); } - - + + else if (pfrom->nVersion == 0) { // Must have a version message before anything else Misbehaving(pfrom->GetId(), 1); return false; } - - + + else if (strCommand == "verack") { pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); - + // Mark this node as currently connected, so we update its timestamp later. if (pfrom->fNetworkNode) { LOCK(cs_main); State(pfrom->GetId())->fCurrentlyConnected = true; } } - - + + + // Disconnect existing peer connection when: + // 1. The version message has been received + // 2. Overwinter is active + // 3. Peer version is pre-Overwinter + else if (NetworkUpgradeActive(GetHeight(), chainparams.GetConsensus(), Consensus::UPGRADE_OVERWINTER) + && (pfrom->nVersion < chainparams.GetConsensus().vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion)) + { + LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion); + pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE, + strprintf("Version must be %d or greater", + chainparams.GetConsensus().vUpgrades[Consensus::UPGRADE_OVERWINTER].nProtocolVersion)); + pfrom->fDisconnect = true; + return false; + } + + else if (strCommand == "addr") { vector vAddr; vRecv >> vAddr; - + // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; @@ -4806,7 +5377,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, Misbehaving(pfrom->GetId(), 20); return error("message addr size() = %u", vAddr.size()); } - + // Store the new addresses vector vAddrOk; int64_t nNow = GetAdjustedTime(); @@ -4814,7 +5385,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, BOOST_FOREACH(CAddress& addr, vAddr) { boost::this_thread::interruption_point(); - + if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); @@ -4858,8 +5429,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, if (pfrom->fOneShot) pfrom->fDisconnect = true; } - - + + else if (strCommand == "inv") { vector vInv; @@ -4869,24 +5440,24 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, Misbehaving(pfrom->GetId(), 20); return error("message inv size() = %u", vInv.size()); } - + LOCK(cs_main); - + std::vector vToFetch; - + for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; - + boost::this_thread::interruption_point(); pfrom->AddInventoryKnown(inv); - + bool fAlreadyHave = AlreadyHave(inv); LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id); - + if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK) pfrom->AskFor(inv); - + if (inv.type == MSG_BLOCK) { UpdateBlockAvailability(pfrom->GetId(), inv.hash); if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) { @@ -4910,21 +5481,21 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id); } } - + // Track requests for our stuff GetMainSignals().Inventory(inv.hash); - + if (pfrom->nSendSize > (SendBufferSize() * 2)) { Misbehaving(pfrom->GetId(), 50); return error("send buffer size() = %u", pfrom->nSendSize); } } - + if (!vToFetch.empty()) pfrom->PushMessage("getdata", vToFetch); } - - + + else if (strCommand == "getdata") { vector vInv; @@ -4934,29 +5505,29 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, Misbehaving(pfrom->GetId(), 20); return error("message getdata size() = %u", vInv.size()); } - + if (fDebug || (vInv.size() != 1)) LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id); - + if ((fDebug && vInv.size() > 0) || (vInv.size() == 1)) LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id); - + pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end()); ProcessGetData(pfrom); } - - + + else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; - + LOCK(cs_main); - + // Find the last block the caller has in the main chain CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator); - + // Send the rest of the chain if (pindex) pindex = chainActive.Next(pindex); @@ -4980,19 +5551,19 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } } } - - + + else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; - + LOCK(cs_main); - + if (IsInitialBlockDownload()) return true; - + CBlockIndex* pindex = NULL; if (locator.IsNull()) { @@ -5009,7 +5580,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, if (pindex) pindex = chainActive.Next(pindex); } - + // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end vector vHeaders; int nLimit = MAX_HEADERS_RESULTS; @@ -5032,37 +5603,37 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, fprintf(stderr,"you can ignore redundant getheaders from peer.%d %d prev.%d\n",(int32_t)pfrom->id,(int32_t)(pindex ? pindex->nHeight : -1),pfrom->lasthdrsreq); } } - - + + else if (strCommand == "tx") { vector vWorkQueue; vector vEraseQueue; CTransaction tx; vRecv >> tx; - + CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); - + LOCK(cs_main); - + bool fMissingInputs = false; CValidationState state; - + pfrom->setAskFor.erase(inv.hash); mapAlreadyAskedFor.erase(inv); - + if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs)) { mempool.check(pcoinsTip); RelayTransaction(tx); vWorkQueue.push_back(inv.hash); - + LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n", - pfrom->id, pfrom->cleanSubVer, - tx.GetHash().ToString(), - mempool.mapTx.size()); - + pfrom->id, pfrom->cleanSubVer, + tx.GetHash().ToString(), + mempool.mapTx.size()); + // Recursively process any orphan transactions that depended on this one set setMisbehaving; for (unsigned int i = 0; i < vWorkQueue.size(); i++) @@ -5082,8 +5653,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get // anyone relaying LegitTxX banned) CValidationState stateDummy; - - + + if (setMisbehaving.count(fromPeer)) continue; if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2)) @@ -5113,15 +5684,15 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, mempool.check(pcoinsTip); } } - + BOOST_FOREACH(uint256 hash, vEraseQueue) - EraseOrphanTx(hash); + EraseOrphanTx(hash); } // TODO: currently, prohibit joinsplits from entering mapOrphans else if (fMissingInputs && tx.vjoinsplit.size() == 0) { AddOrphanTx(tx, pfrom->GetId()); - + // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS)); unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx); @@ -5130,7 +5701,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } else { assert(recentRejects); recentRejects->insert(tx.GetHash()); - + if (pfrom->fWhitelisted) { // Always relay transactions received from whitelisted peers, even // if they were already in the mempool or rejected from it due @@ -5146,7 +5717,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, RelayTransaction(tx); } else { LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s (code %d))\n", - tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode()); + tx.GetHash().ToString(), pfrom->id, state.GetRejectReason(), state.GetRejectCode()); } } } @@ -5154,20 +5725,20 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, if (state.IsInvalid(nDoS)) { LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(), - pfrom->id, pfrom->cleanSubVer, - state.GetRejectReason()); + pfrom->id, pfrom->cleanSubVer, + state.GetRejectReason()); pfrom->PushMessage("reject", strCommand, state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash); if (nDoS > 0) Misbehaving(pfrom->GetId(), nDoS); } } - - + + else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing { std::vector headers; - + // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks. unsigned int nCount = ReadCompactSize(vRecv); if (nCount > MAX_HEADERS_RESULTS) { @@ -5179,14 +5750,14 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, vRecv >> headers[n]; ReadCompactSize(vRecv); // ignore tx count; assume it is 0. } - + LOCK(cs_main); - + if (nCount == 0) { // Nothing interesting. Stop asking this peers for more headers. return true; } - + CBlockIndex *pindexLast = NULL; BOOST_FOREACH(const CBlockHeader& header, headers) { CValidationState state; @@ -5196,17 +5767,18 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } if (!AcceptBlockHeader(header, state, &pindexLast)) { int nDoS; - if (state.IsInvalid(nDoS)) { + if (state.IsInvalid(nDoS)) + { if (nDoS > 0) Misbehaving(pfrom->GetId(), nDoS/nDoS); return error("invalid header received"); } } } - + if (pindexLast) UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash()); - + if (nCount == MAX_HEADERS_RESULTS && pindexLast) { // Headers message had its maximum size; the peer may have more headers. // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue @@ -5218,20 +5790,20 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256()); } } - + CheckBlockIndex(); } - + else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing { CBlock block; vRecv >> block; - + CInv inv(MSG_BLOCK, block.GetHash()); LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id); - + pfrom->AddInventoryKnown(inv); - + CValidationState state; // Process all blocks from whitelisted peers, even if not requested, // unless we're still syncing with the network. @@ -5248,10 +5820,10 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, Misbehaving(pfrom->GetId(), nDoS); } } - + } - - + + // This asymmetric behavior for inbound and outbound connections was introduced // to prevent a fingerprinting attack: an attacker can send specific fake addresses // to users' AddrMan and later request them by sending getaddr messages. @@ -5266,18 +5838,18 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, return true; } pfrom->fSentAddr = true; - + pfrom->vAddrToSend.clear(); vector vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) - pfrom->PushAddress(addr); + pfrom->PushAddress(addr); } - - + + else if (strCommand == "mempool") { LOCK2(cs_main, pfrom->cs_filter); - + std::vector vtxid; mempool.queryHashes(vtxid); vector vInv; @@ -5287,7 +5859,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, bool fInMemPool = mempool.lookup(hash, tx); if (!fInMemPool) continue; // another thread removed since queryHashes, maybe... if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) || - (!pfrom->pfilter)) + (!pfrom->pfilter)) vInv.push_back(inv); if (vInv.size() == MAX_INV_SZ) { pfrom->PushMessage("inv", vInv); @@ -5297,8 +5869,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, if (vInv.size() > 0) pfrom->PushMessage("inv", vInv); } - - + + else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) @@ -5319,8 +5891,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->PushMessage("pong", nonce); } } - - + + else if (strCommand == "pong") { int64_t pingUsecEnd = nTimeReceived; @@ -5328,10 +5900,10 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, size_t nAvail = vRecv.in_avail(); bool bPingFinished = false; std::string sProblem; - + if (nAvail >= sizeof(nonce)) { vRecv >> nonce; - + // Only process pong message if there is an outstanding ping (old ping without nonce should never pong) if (pfrom->nPingNonceSent != 0) { if (nonce == pfrom->nPingNonceSent) { @@ -5363,27 +5935,27 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, bPingFinished = true; sProblem = "Short payload"; } - + if (!(sProblem.empty())) { LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n", - pfrom->id, - pfrom->cleanSubVer, - sProblem, - pfrom->nPingNonceSent, - nonce, - nAvail); + pfrom->id, + pfrom->cleanSubVer, + sProblem, + pfrom->nPingNonceSent, + nonce, + nAvail); } if (bPingFinished) { pfrom->nPingNonceSent = 0; } } - - + + else if (fAlerts && strCommand == "alert") { CAlert alert; vRecv >> alert; - + uint256 alertHash = alert.GetHash(); if (pfrom->setKnown.count(alertHash) == 0) { @@ -5394,7 +5966,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) - alert.RelayTo(pnode); + alert.RelayTo(pnode); } } else { @@ -5408,13 +5980,13 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } } } - - + + else if (strCommand == "filterload") { CBloomFilter filter; vRecv >> filter; - + if (!filter.IsWithinSizeConstraints()) // There is no excuse for sending a too-large filter Misbehaving(pfrom->GetId(), 100); @@ -5427,13 +5999,13 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, } pfrom->fRelayTxes = true; } - - + + else if (strCommand == "filteradd") { vector vData; vRecv >> vData; - + // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object, // and thus, the maximum size any matched object can have) in a filteradd message if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) @@ -5447,8 +6019,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, Misbehaving(pfrom->GetId(), 100); } } - - + + else if (strCommand == "filterclear") { LOCK(pfrom->cs_filter); @@ -5456,18 +6028,18 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->pfilter = new CBloomFilter(); pfrom->fRelayTxes = true; } - - + + else if (strCommand == "reject") { if (fDebug) { try { string strMsg; unsigned char ccode; string strReason; vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH); - + ostringstream ss; ss << strMsg << " code " << itostr(ccode) << ": " << strReason; - + if (strMsg == "block" || strMsg == "tx") { uint256 hash; @@ -5485,14 +6057,14 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, // We do not care about the NOTFOUND message, but logging an Unknown Command // message would be undesirable as we transmit it ourselves. } - + else { // Ignore unknown commands for extensibility LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id); } - - - + + + return true; } @@ -5501,7 +6073,7 @@ bool ProcessMessages(CNode* pfrom) { //if (fDebug) // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size()); - + // // Message format // (4) message start @@ -5511,41 +6083,41 @@ bool ProcessMessages(CNode* pfrom) // (x) data // bool fOk = true; - + if (!pfrom->vRecvGetData.empty()) ProcessGetData(pfrom); - + // this maintains the order of responses if (!pfrom->vRecvGetData.empty()) return fOk; - + std::deque::iterator it = pfrom->vRecvMsg.begin(); while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) { // Don't bother if send buffer is too full to respond anyway if (pfrom->nSendSize >= SendBufferSize()) break; - + // get next message CNetMessage& msg = *it; - + //if (fDebug) // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__, // msg.hdr.nMessageSize, msg.vRecv.size(), // msg.complete() ? "Y" : "N"); - + // end, if an incomplete message is found if (!msg.complete()) break; - + // at this point, any failure means we can delete the current message it++; - + // Scan for message start if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) { LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id); fOk = false; break; } - + // Read header CMessageHeader& hdr = msg.hdr; if (!hdr.IsValid(Params().MessageStart())) @@ -5554,10 +6126,10 @@ bool ProcessMessages(CNode* pfrom) continue; } string strCommand = hdr.GetCommand(); - + // Message size unsigned int nMessageSize = hdr.nMessageSize; - + // Checksum CDataStream& vRecv = msg.vRecv; uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); @@ -5565,10 +6137,10 @@ bool ProcessMessages(CNode* pfrom) if (nChecksum != hdr.nChecksum) { LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__, - SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum); + SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum); continue; } - + // Process message bool fRet = false; try @@ -5602,17 +6174,17 @@ bool ProcessMessages(CNode* pfrom) } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } - + if (!fRet) LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id); - + break; } - + // In case the connection got shut down, its receive buffer was wiped if (!pfrom->fDisconnect) pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it); - + return fOk; } @@ -5624,7 +6196,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) // Don't send anything until we get its version message if (pto->nVersion == 0) return true; - + // // Message: ping // @@ -5653,11 +6225,11 @@ bool SendMessages(CNode* pto, bool fSendTrickle) pto->PushMessage("ping"); } } - + TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState() if (!lockMain) return true; - + // Address refresh broadcast static int64_t nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) @@ -5668,14 +6240,14 @@ bool SendMessages(CNode* pto, bool fSendTrickle) // Periodically clear addrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->addrKnown.reset(); - + // Rebroadcast our address AdvertizeLocal(pnode); } if (!vNodes.empty()) nLastRebroadcast = GetTime(); } - + // // Message: addr // @@ -5701,7 +6273,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } - + CNodeState &state = *State(pto->GetId()); if (state.fShouldBan) { if (pto->fWhitelisted) @@ -5717,11 +6289,11 @@ bool SendMessages(CNode* pto, bool fSendTrickle) } state.fShouldBan = false; } - + BOOST_FOREACH(const CBlockReject& reject, state.rejects) - pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock); + pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock); state.rejects.clear(); - + // Start block sync if (pindexBestHeader == NULL) pindexBestHeader = chainActive.Tip(); @@ -5736,7 +6308,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256()); } } - + // Resend wallet transactions that haven't gotten in a block yet // Except during reindex, importing and IBD, when old wallet // transactions become unconfirmed and spams other nodes. @@ -5744,7 +6316,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) { GetMainSignals().Broadcast(nTimeBestReceived); } - + // // Message: inventory // @@ -5758,7 +6330,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) { if (pto->setInventoryKnown.count(inv)) continue; - + // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { @@ -5769,14 +6341,14 @@ bool SendMessages(CNode* pto, bool fSendTrickle) uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0); - + if (fTrickleWait) { vInvWait.push_back(inv); continue; } } - + // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { @@ -5792,7 +6364,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) } if (!vInv.empty()) pto->PushMessage("inv", vInv); - + // Detect whether we're stalling int64_t nNow = GetTimeMicros(); if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) { @@ -5824,7 +6396,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) pto->fDisconnect = true; } } - + // // Message: getdata (blocks) // @@ -5837,7 +6409,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash())); MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex); LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(), - pindex->nHeight, pto->id); + pindex->nHeight, pto->id); } if (state.nBlocksInFlight == 0 && staller != -1) { if (State(staller)->nStallingSince == 0) { @@ -5846,7 +6418,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle) } } } - + // // Message: getdata (non-blocks) // @@ -5871,14 +6443,14 @@ bool SendMessages(CNode* pto, bool fSendTrickle) } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); - + } return true; } - std::string CBlockFileInfo::ToString() const { - return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast)); - } +std::string CBlockFileInfo::ToString() const { + return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast)); +} @@ -5892,7 +6464,7 @@ public: for (; it1 != mapBlockIndex.end(); it1++) delete (*it1).second; mapBlockIndex.clear(); - + // orphan transactions mapOrphanTransactions.clear(); mapOrphanTransactionsByPrev.clear(); @@ -5901,6 +6473,24 @@ public: extern "C" const char* getDataDir() { - return GetDataDir().string().c_str(); + return GetDataDir().string().c_str(); } + +// Set default values of new CMutableTransaction based on consensus rules at given height. +CMutableTransaction CreateNewContextualCMutableTransaction(const Consensus::Params& consensusParams, int nHeight) +{ + CMutableTransaction mtx; + + bool isOverwintered = NetworkUpgradeActive(nHeight, consensusParams, Consensus::UPGRADE_OVERWINTER); + if (isOverwintered) { + mtx.fOverwintered = true; + mtx.nVersionGroupId = OVERWINTER_VERSION_GROUP_ID; + mtx.nVersion = 3; + // Expiry height is not set. Only fields required for a parser to treat as a valid Overwinter V3 tx. + + // TODO: In future, when moving from Overwinter to Sapling, it will be useful + // to set the expiry height to: min(activation_height - 1, default_expiry_height) + } + return mtx; +} From 6107175727017775e1b7cbb40e62b7c61a077b7d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 02:59:11 +0300 Subject: [PATCH 325/507] -includes --- src/main.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 3255c3380..c2d360a9d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -13,9 +13,9 @@ #include "chainparams.h" #include "checkpoints.h" #include "checkqueue.h" -#include "consensus/upgrades.h" +//#include "consensus/upgrades.h" #include "consensus/validation.h" -#include "deprecation.h" +//#include "deprecation.h" #include "init.h" #include "merkleblock.h" #include "metrics.h" @@ -29,7 +29,7 @@ #include "utilmoneystr.h" #include "validationinterface.h" #include "wallet/asyncrpcoperation_sendmany.h" -#include "wallet/asyncrpcoperation_shieldcoinbase.h" +//#include "wallet/asyncrpcoperation_shieldcoinbase.h" #include From c51be288c513e2e3a9504d1e96c2e1472c6ef364 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 03:39:37 +0300 Subject: [PATCH 326/507] +error return --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index a7e3a3aab..1e3e12463 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3570,7 +3570,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) { komodo_reverify_blockcheck(state,height,pindex); - return false; // happens if on a fork state.DoS(1, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); + return state.DoS(1, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); } // Check the merkle root. if (fCheckMerkleRoot) { From e7b497fd2230a4e92da3f9e1b1ca1ee3c3964d02 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 03:45:05 +0300 Subject: [PATCH 327/507] Restore fixes --- src/komodo.h | 6 +++--- src/komodo_pax.h | 2 +- src/main.cpp | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 32fcce047..d74760147 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -120,7 +120,7 @@ int32_t komodo_parsestatefile(struct komodo_state *sp,FILE *fp,char *symbol,char MoMdepth = 0; } //if ( matched != 0 ) global independent states -> inside *sp - komodo_eventadd_notarized(sp,symbol,ht,dest,notarized_hash,notarized_desttxid,notarized_height,MoM,MoMdepth); + komodo_eventadd_notarized(sp,symbol,ht,dest,notarized_hash,notarized_desttxid,notarized_height);//,MoM,MoMdepth); } else if ( func == 'U' ) // deprecated { @@ -265,7 +265,7 @@ int32_t komodo_parsestatefiledata(struct komodo_state *sp,uint8_t *filedata,long memset(&MoM,0,sizeof(MoM)); MoMdepth = 0; } - komodo_eventadd_notarized(sp,symbol,ht,dest,notarized_hash,notarized_desttxid,notarized_height,MoM,MoMdepth); + komodo_eventadd_notarized(sp,symbol,ht,dest,notarized_hash,notarized_desttxid,notarized_height);//,MoM,MoMdepth); } else if ( func == 'U' ) // deprecated { @@ -498,7 +498,7 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar if ( fwrite(&sp->MoMdepth,1,sizeof(sp->MoMdepth),fp) != sizeof(sp->MoMdepth) ) errs++; } - komodo_eventadd_notarized(sp,symbol,height,dest,sp->NOTARIZED_HASH,sp->NOTARIZED_DESTTXID,sp->NOTARIZED_HEIGHT,sp->MoM,sp->MoMdepth); + komodo_eventadd_notarized(sp,symbol,height,dest,sp->NOTARIZED_HASH,sp->NOTARIZED_DESTTXID,sp->NOTARIZED_HEIGHT);//,sp->MoM,sp->MoMdepth); } } fflush(fp); diff --git a/src/komodo_pax.h b/src/komodo_pax.h index 2c048bac9..bcf6fa5d7 100644 --- a/src/komodo_pax.h +++ b/src/komodo_pax.h @@ -709,7 +709,7 @@ void komodo_paxpricefeed(int32_t height,uint8_t *pricefeed,int32_t opretlen) double KMDBTC,BTCUSD,CNYUSD; uint32_t numpvals,timestamp,pvals[128]; uint256 zero; numpvals = dpow_readprices(height,pricefeed,×tamp,&KMDBTC,&BTCUSD,&CNYUSD,pvals); memset(&zero,0,sizeof(zero)); - komodo_stateupdate(height,0,0,0,zero,0,0,pvals,numpvals,0,0,0,0,0,0,zero,0); + komodo_stateupdate(height,0,0,0,zero,0,0,pvals,numpvals,0,0,0,0,0,0); if ( 0 ) { int32_t i; diff --git a/src/main.cpp b/src/main.cpp index cadcf1039..3a8859851 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -13,9 +13,9 @@ #include "chainparams.h" #include "checkpoints.h" #include "checkqueue.h" -//#include "consensus/upgrades.h" +#include "consensus/upgrades.h" #include "consensus/validation.h" -//#include "deprecation.h" +#include "deprecation.h" #include "init.h" #include "merkleblock.h" #include "metrics.h" @@ -29,7 +29,7 @@ #include "utilmoneystr.h" #include "validationinterface.h" #include "wallet/asyncrpcoperation_sendmany.h" -//#include "wallet/asyncrpcoperation_shieldcoinbase.h" +#include "wallet/asyncrpcoperation_shieldcoinbase.h" #include From b96da7c76b69b101a15e94c860916814dab4963d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 03:51:58 +0300 Subject: [PATCH 328/507] Syntax --- src/komodo.h | 23 ++++++++++++----------- src/rpcblockchain.cpp | 2 ++ src/rpcclient.cpp | 4 ++-- src/rpcserver.cpp | 4 ++-- src/rpcserver.h | 4 ++-- 5 files changed, 20 insertions(+), 17 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index d74760147..f0cb249c1 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -349,7 +349,7 @@ int32_t komodo_parsestatefiledata(struct komodo_state *sp,uint8_t *filedata,long return(-1); } -void 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,int32_t KMDheight,uint32_t KMDtimestamp,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout,uint256 MoM,int32_t MoMdepth) +void 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,int32_t KMDheight,uint32_t KMDtimestamp,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout)//,uint256 MoM,int32_t MoMdepth) { static FILE *fp; static int32_t errs,didinit; static uint256 zero; struct komodo_state *sp; char fname[512],symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; int32_t retval,ht,func; uint8_t num,pubkeys[64][33]; @@ -480,9 +480,10 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar //printf("ht.%d func N ht.%d errs.%d\n",height,NOTARIZED_HEIGHT,errs); if ( sp != 0 ) { - if ( sp->MoMdepth > 0 && sp->MoM != zero ) - fputc('M',fp); - else fputc('N',fp); + //if ( sp->MoMdepth > 0 && sp->MoM != zero ) + // fputc('M',fp); + //else + fputc('N',fp); if ( fwrite(&height,1,sizeof(height),fp) != sizeof(height) ) errs++; if ( fwrite(&sp->NOTARIZED_HEIGHT,1,sizeof(sp->NOTARIZED_HEIGHT),fp) != sizeof(sp->NOTARIZED_HEIGHT) ) @@ -491,13 +492,13 @@ void komodo_stateupdate(int32_t height,uint8_t notarypubs[][33],uint8_t numnotar errs++; if ( fwrite(&sp->NOTARIZED_DESTTXID,1,sizeof(sp->NOTARIZED_DESTTXID),fp) != sizeof(sp->NOTARIZED_DESTTXID) ) errs++; - if ( sp->MoMdepth > 0 && sp->MoM != zero ) + /*if ( sp->MoMdepth > 0 && sp->MoM != zero ) { if ( fwrite(&sp->MoM,1,sizeof(sp->MoM),fp) != sizeof(sp->MoM) ) errs++; if ( fwrite(&sp->MoMdepth,1,sizeof(sp->MoMdepth),fp) != sizeof(sp->MoMdepth) ) errs++; - } + }*/ komodo_eventadd_notarized(sp,symbol,height,dest,sp->NOTARIZED_HASH,sp->NOTARIZED_DESTTXID,sp->NOTARIZED_HEIGHT);//,sp->MoM,sp->MoMdepth); } } @@ -599,7 +600,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr sp->NOTARIZED_HEIGHT = *notarizedheightp; sp->NOTARIZED_HASH = srchash; sp->NOTARIZED_DESTTXID = desttxid; - memset(&sp->MoM,0,sizeof(sp->MoM)); + /*memset(&sp->MoM,0,sizeof(sp->MoM)); sp->MoMdepth = 0; if ( len+36 <= opretlen ) { @@ -614,11 +615,11 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr { //printf("VALID %s MoM.%s [%d]\n",ASSETCHAINS_SYMBOL,sp->MoM.ToString().c_str(),sp->MoMdepth); } - } - komodo_stateupdate(height,0,0,0,zero,0,0,0,0,0,0,0,0,0,0,sp->MoM,sp->MoMdepth); + }*/ + komodo_stateupdate(height,0,0,0,zero,0,0,0,0,0,0,0,0,0,0);//,sp->MoM,sp->MoMdepth); len += nameoffset; - if ( ASSETCHAINS_SYMBOL[0] != 0 ) - printf("[%s] ht.%d NOTARIZED.%d %s.%s %sTXID.%s lens.(%d %d) MoM.%s %d\n",ASSETCHAINS_SYMBOL,height,*notarizedheightp,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),ASSETCHAINS_SYMBOL[0]==0?"BTC":"KMD",desttxid.ToString().c_str(),opretlen,len,sp->MoM.ToString().c_str(),sp->MoMdepth); + //if ( ASSETCHAINS_SYMBOL[0] != 0 ) + // printf("[%s] ht.%d NOTARIZED.%d %s.%s %sTXID.%s lens.(%d %d) MoM.%s %d\n",ASSETCHAINS_SYMBOL,height,*notarizedheightp,ASSETCHAINS_SYMBOL[0]==0?"KMD":ASSETCHAINS_SYMBOL,srchash.ToString().c_str(),ASSETCHAINS_SYMBOL[0]==0?"BTC":"KMD",desttxid.ToString().c_str(),opretlen,len,sp->MoM.ToString().c_str(),sp->MoMdepth); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { if ( signedfp == 0 ) diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index d34c41bd4..1877c1d34 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -589,6 +589,7 @@ UniValue kvsearch(const UniValue& params, bool fHelp) return ret; } +/* UniValue height_MoM(const UniValue& params, bool fHelp) { int32_t height,depth,notarized_height,MoMoMdepth,MoMoMoffset,kmdstarti,kmdendi; uint256 MoM,MoMoM,kmdtxid; uint32_t timestamp = 0; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); @@ -716,6 +717,7 @@ UniValue txMoMproof(const UniValue& params, bool fHelp) ssProof << MoMProof(nIndex, branch, notarisationHash); return HexStr(ssProof.begin(), ssProof.end()); } +*/ UniValue minerids(const UniValue& params, bool fHelp) { diff --git a/src/rpcclient.cpp b/src/rpcclient.cpp index 6a83e8c19..799dca34f 100644 --- a/src/rpcclient.cpp +++ b/src/rpcclient.cpp @@ -125,8 +125,8 @@ static const CRPCConvertParam vRPCConvertParams[] = { "paxprices", 3 }, { "paxpending", 0 }, { "notaries", 2 }, - { "height_MoM", 1 }, - { "txMoMproof", 1 }, + //{ "height_MoM", 1 }, + //{ "txMoMproof", 1 }, { "minerids", 1 }, { "kvsearch", 1 }, { "kvupdate", 4 }, diff --git a/src/rpcserver.cpp b/src/rpcserver.cpp index 5d573f62b..ba55be91a 100644 --- a/src/rpcserver.cpp +++ b/src/rpcserver.cpp @@ -296,8 +296,8 @@ static const CRPCCommand vRPCCommands[] = { "blockchain", "paxpending", &paxpending, true }, { "blockchain", "paxprices", &paxprices, true }, { "blockchain", "notaries", ¬aries, true }, - { "blockchain", "height_MoM", &height_MoM, true }, - { "blockchain", "txMoMproof", &txMoMproof, true }, + //{ "blockchain", "height_MoM", &height_MoM, true }, + //{ "blockchain", "txMoMproof", &txMoMproof, true }, { "blockchain", "minerids", &minerids, true }, { "blockchain", "kvsearch", &kvsearch, true }, { "blockchain", "kvupdate", &kvupdate, true }, diff --git a/src/rpcserver.h b/src/rpcserver.h index b4e6ed8fc..c4e0a6d1d 100644 --- a/src/rpcserver.h +++ b/src/rpcserver.h @@ -304,8 +304,8 @@ extern UniValue z_validateaddress(const UniValue& params, bool fHelp); // in rpc extern UniValue z_getpaymentdisclosure(const UniValue& params, bool fHelp); // in rpcdisclosure.cpp extern UniValue z_validatepaymentdisclosure(const UniValue ¶ms, bool fHelp); // in rpcdisclosure.cpp -extern UniValue height_MoM(const UniValue& params, bool fHelp); -extern UniValue txMoMproof(const UniValue& params, bool fHelp); +//extern UniValue height_MoM(const UniValue& params, bool fHelp); +//extern UniValue txMoMproof(const UniValue& params, bool fHelp); extern UniValue notaries(const UniValue& params, bool fHelp); extern UniValue minerids(const UniValue& params, bool fHelp); extern UniValue kvsearch(const UniValue& params, bool fHelp); From 3c966993da49290706aea38ee372098c3c79ebef Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 03:54:13 +0300 Subject: [PATCH 329/507] -args --- src/komodo.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index f0cb249c1..c266c85f0 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -641,7 +641,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr //for (i=0; iNOTARIZED_HEIGHT ) @@ -670,7 +670,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } if ( *isratificationp == 0 && (signedmask != 0 || (scriptbuf[len] != 'X' && scriptbuf[len] != 'A')) ) // && scriptbuf[len] != 'I') - komodo_stateupdate(height,0,0,0,txhash,0,0,0,0,0,0,value,&scriptbuf[len],opretlen,j,zero,0); + komodo_stateupdate(height,0,0,0,txhash,0,0,0,0,0,0,value,&scriptbuf[len],opretlen,j);//,zero,0); } } return(notaryid); @@ -729,7 +729,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block) if ( pindex->nHeight != hwmheight ) printf("%s hwmheight.%d vs pindex->nHeight.%d t.%u reorg.%d\n",ASSETCHAINS_SYMBOL,hwmheight,pindex->nHeight,(uint32_t)pindex->nTime,hwmheight-pindex->nHeight); komodo_event_rewind(sp,symbol,pindex->nHeight); - komodo_stateupdate(pindex->nHeight,0,0,0,zero,0,0,0,0,-pindex->nHeight,pindex->nTime,0,0,0,0,zero,0); + komodo_stateupdate(pindex->nHeight,0,0,0,zero,0,0,0,0,-pindex->nHeight,pindex->nTime,0,0,0,0);//,zero,0); } komodo_currentheight_set(chainActive.Tip()->nHeight); if ( pindex != 0 ) @@ -861,7 +861,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block) if ( ((signedmask & 1) != 0 && numvalid >= KOMODO_MINRATIFY) || bitweight(signedmask) > (numnotaries/3) ) { memset(&txhash,0,sizeof(txhash)); - komodo_stateupdate(height,pubkeys,numvalid,0,txhash,0,0,0,0,0,0,0,0,0,0,zero,0); + komodo_stateupdate(height,pubkeys,numvalid,0,txhash,0,0,0,0,0,0,0,0,0,0);//,zero,0); printf("RATIFIED! >>>>>>>>>> new notaries.%d newheight.%d from height.%d\n",numvalid,(((height+KOMODO_ELECTION_GAP/2)/KOMODO_ELECTION_GAP)+1)*KOMODO_ELECTION_GAP,height); } else printf("signedmask.%llx numvalid.%d wt.%d numnotaries.%d\n",(long long)signedmask,numvalid,bitweight(signedmask),numnotaries); } From 220736b6c7ad38f1b104ce36c3d114f1fbe36ef3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 03:55:47 +0300 Subject: [PATCH 330/507] Again --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index c266c85f0..2732c530f 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -870,7 +870,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block) if ( NOTARY_PUBKEY33[0] != 0 && ASSETCHAINS_SYMBOL[0] == 0 ) printf("%s ht.%d\n",ASSETCHAINS_SYMBOL[0] == 0 ? "KMD" : ASSETCHAINS_SYMBOL,height); if ( pindex->nHeight == hwmheight ) - komodo_stateupdate(height,0,0,0,zero,0,0,0,0,height,(uint32_t)pindex->nTime,0,0,0,0,zero,0); + komodo_stateupdate(height,0,0,0,zero,0,0,0,0,height,(uint32_t)pindex->nTime,0,0,0,0);//,zero,0); } else fprintf(stderr,"komodo_connectblock: unexpected null pindex\n"); //KOMODO_INITDONE = (uint32_t)time(NULL); //fprintf(stderr,"%s end connect.%d\n",ASSETCHAINS_SYMBOL,pindex->nHeight); From ba6c9a5a479ce6a6bdc32a74c4ff2c2350a27c6f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 04:18:35 +0300 Subject: [PATCH 331/507] Move equihash to check block --- src/main.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 1e3e12463..b3b5760d5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3509,8 +3509,8 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl // return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low"); // Check Equihash solution is valid - if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) ) - return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); + /*if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) ) + return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution");*/ // Check proof of work matches claimed amount /*komodo_index2pubkey33(pubkey33,pindex,height); @@ -3565,11 +3565,12 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat // redundant with the call in AcceptBlockHeader. if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW)) return false; - //komodo_index2pubkey33(pubkey33,pindex,height); + if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) ) + return state.DoS(100, error("CheckBlock(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) { - komodo_reverify_blockcheck(state,height,pindex); + //komodo_reverify_blockcheck(state,height,pindex); return state.DoS(1, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); } // Check the merkle root. From f8ba64736f46ebf5ed6859bcc272bcf72d96aa04 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 04:21:30 +0300 Subject: [PATCH 332/507] Test miner --- src/miner.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index a732aa56b..afaf52ee1 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -931,9 +931,9 @@ void static BitcoinMiner() else { CValidationState state; - if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), false, false)) + if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), true, false)) { - //fprintf(stderr,"Invalid block mined, try again\n"); + fprintf(stderr,"Invalid block mined, try again\n"); return(false); } if ( NOTARY_PUBKEY33[0] != 0 ) From d4ae49affd3f835fd9138926c9150db8db2ddd47 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 04:33:31 +0300 Subject: [PATCH 333/507] Syntax --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index b3b5760d5..69b5cb875 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3565,7 +3565,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat // redundant with the call in AcceptBlockHeader. if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW)) return false; - if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) ) + if ( fCheckPOW && !CheckEquihashSolution(&block, Params()) ) return state.DoS(100, error("CheckBlock(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) @@ -3979,7 +3979,7 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex } if (!ConnectBlock(block, state, &indexDummy, viewNew, true)) { - fprintf(stderr,"TestBlockValidity failure D\n"); + //fprintf(stderr,"TestBlockValidity failure D\n"); return false; } assert(state.IsValid()); From ff84ea53014cb131d7deac28a6ad333cef99d840 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 07:00:56 +0300 Subject: [PATCH 334/507] -wallet utility --- Makefile.am | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Makefile.am b/Makefile.am index d0c289ee1..d3171b206 100644 --- a/Makefile.am +++ b/Makefile.am @@ -15,7 +15,7 @@ endif BITCOIND_BIN=$(top_builddir)/src/zcashd$(EXEEXT) BITCOIN_CLI_BIN=$(top_builddir)/src/zcash-cli$(EXEEXT) -WALLET_UTILITY_BIN=$(top_builddir)/src/wallet-utility$(EXEEXT) +#WALLET_UTILITY_BIN=$(top_builddir)/src/wallet-utility$(EXEEXT) BITCOIN_WIN_INSTALLER=$(PACKAGE)-$(PACKAGE_VERSION)-win$(WINDOWS_BITS)-setup$(EXEEXT) if TARGET_DARWIN @@ -156,8 +156,8 @@ $(BITCOIND_BIN): FORCE $(BITCOIN_CLI_BIN): FORCE $(MAKE) -C src $(@F) -$(WALLET_UTILITY_BIN): FORCE - $(MAKE) -C src $(@F) +#$(WALLET_UTILITY_BIN): FORCE +# $(MAKE) -C src $(@F) if USE_LCOV From c29e5dd7043eb0eb774ff81280ad12685afcf801 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 07:15:11 +0300 Subject: [PATCH 335/507] -libsnark/gtests.cpp --- src/snark/libsnark/gtests.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/snark/libsnark/gtests.cpp b/src/snark/libsnark/gtests.cpp index 74c66bdad..7d6308f89 100644 --- a/src/snark/libsnark/gtests.cpp +++ b/src/snark/libsnark/gtests.cpp @@ -3,10 +3,11 @@ #include "common/profiling.hpp" int main(int argc, char **argv) { - libsnark::inhibit_profiling_info = true; + /*libsnark::inhibit_profiling_info = true; libsnark::inhibit_profiling_counters = true; testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); + return RUN_ALL_TESTS();*/ + return(0); } From f64557f7e04ed3566341287a9a5b94bf37e25d11 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 07:19:36 +0300 Subject: [PATCH 336/507] Test --- src/Makefile.am | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index c51489565..328b3e269 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -100,9 +100,9 @@ bin_PROGRAMS = noinst_PROGRAMS = TESTS = -if BUILD_BITCOIND +#if BUILD_BITCOIND bin_PROGRAMS += komodod -endif +#endif if BUILD_BITCOIN_UTILS bin_PROGRAMS += komodo-cli komodo-tx From 455ba304112ee24ff54ec56c2e3b1d6938263d10 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 07:41:57 +0300 Subject: [PATCH 337/507] Fix getblocktemplate --- src/main.cpp | 6 +++--- src/main.h | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 69b5cb875..7febd5192 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2923,7 +2923,7 @@ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock * LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001); { CCoinsViewCache view(pcoinsTip); - bool rv = ConnectBlock(*pblock, state, pindexNew, view); + bool rv = ConnectBlock(*pblock, state, pindexNew, view,false,true); GetMainSignals().BlockChecked(*pblock, state); if (!rv) { if (state.IsInvalid()) @@ -3977,7 +3977,7 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex fprintf(stderr,"TestBlockValidity failure C\n"); return false; } - if (!ConnectBlock(block, state, &indexDummy, viewNew, true)) + if (!ConnectBlock(block, state, &indexDummy, viewNew, true,fCheckPOW)) { //fprintf(stderr,"TestBlockValidity failure D\n"); return false; @@ -4415,7 +4415,7 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth CBlock block; if (!ReadBlockFromDisk(block, pindex)) return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); - if (!ConnectBlock(block, state, pindex, coins)) + if (!ConnectBlock(block, state, pindex, coins,false,true)) return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); } } diff --git a/src/main.h b/src/main.h index 1c864de20..cb10e0168 100644 --- a/src/main.h +++ b/src/main.h @@ -447,7 +447,7 @@ bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex); bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL); /** Apply the effects of this block (with given index) on the UTXO set represented by coins */ -bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false); +bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false,bool fCheckPOW = false); /** Context-independent validity checks */ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex,const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true); From c01b993644bf4d6891a76b6ad1a58372f2729ddf Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 07:45:26 +0300 Subject: [PATCH 338/507] Test --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 7febd5192..abfa40aa6 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2429,7 +2429,7 @@ static int64_t nTimeIndex = 0; static int64_t nTimeCallbacks = 0; static int64_t nTimeTotal = 0; -bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck) +bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck, bool fCheckPOW) { const CChainParams& chainparams = Params(); @@ -2447,7 +2447,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin auto disabledVerifier = libzcash::ProofVerifier::Disabled(); // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in - if (!CheckBlock(pindex->nHeight,pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, 1, !fJustCheck)) //!fJustCheck, !fJustCheck)) + if (!CheckBlock(pindex->nHeight,pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, fCheckPOW, !fJustCheck)) //!fJustCheck, !fJustCheck)) return false; // verify that the view's current state corresponds to the previous block From 9dd93da4743aced049b078c5fbbe750cc6111f89 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 08:23:29 +0300 Subject: [PATCH 339/507] Test validity in mined block path --- src/miner.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index e571f3617..176fb83a7 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -917,6 +917,12 @@ void static BitcoinMiner() // fprintf(stderr," missed target\n"); return false; } + CValidationState state; + if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), true, false)) + { + fprintf(stderr,"Invalid block mined, try again\n"); + return(false); + } if ( ASSETCHAINS_STAKED == 0 ) { if ( Mining_start != 0 && time(NULL) < Mining_start+roundrobin_delay ) @@ -934,12 +940,6 @@ void static BitcoinMiner() } else { - CValidationState state; - if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), true, false)) - { - fprintf(stderr,"Invalid block mined, try again\n"); - return(false); - } if ( NOTARY_PUBKEY33[0] != 0 ) { printf("need to wait %d seconds to submit\n",(int32_t)(pblock->nTime - GetAdjustedTime())); From bdeeaa4978d7394cbfbdda3ee0c6fb6e21bd73be Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 08:29:21 +0300 Subject: [PATCH 340/507] Test --- src/komodo_globals.h | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/komodo_globals.h b/src/komodo_globals.h index d3a95c6cc..865f377e2 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -47,10 +47,6 @@ int COINBASE_MATURITY = _COINBASE_MATURITY;//100; int32_t IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAINS_SEED,KOMODO_ON_DEMAND,KOMODO_EXTERNAL_NOTARIES,KOMODO_PASSPORT_INITDONE,KOMODO_PAX,KOMODO_EXCHANGEWALLET,KOMODO_REWIND; int32_t KOMODO_LASTMINED,prevKOMODO_LASTMINED,JUMBLR_PAUSE; -<<<<<<< HEAD -uint32_t ASSETCHAINS_CC; -======= ->>>>>>> dev std::string NOTARY_PUBKEY,ASSETCHAINS_NOTARIES,ASSETCHAINS_OVERRIDE_PUBKEY; uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33]; From 4d9b5edbcf7600dabbac589d1e6d0df40ba2db2e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 08:35:52 +0300 Subject: [PATCH 341/507] Test --- src/Makefile.am | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index 4fd1f5f0a..f60f60a7c 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -111,6 +111,7 @@ if ENABLE_WALLET bin_PROGRAMS += wallet-utility endif + LIBZCASH_H = \ zcash/IncrementalMerkleTree.hpp \ zcash/NoteEncryption.hpp \ @@ -527,7 +528,8 @@ wallet_utility_LDADD = \ $(CRYPTO_LIBS) \ $(LIBZCASH) \ $(LIBSNARK) \ - $(LIBZCASH_LIBS) + $(LIBZCASH_LIBS)\ + $(LIBCRYPTOCONDITIONS) endif # zcash-tx binary # From 1d9d9b4f809a62cb817e6baedd7d92c34f1d2ec3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 08:41:04 +0300 Subject: [PATCH 342/507] Devmerged --- src/main.cpp | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 67748e698..4a3e5c3ea 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2564,11 +2564,7 @@ static int64_t nTimeIndex = 0; static int64_t nTimeCallbacks = 0; static int64_t nTimeTotal = 0; -<<<<<<< HEAD -bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck, bool fCheckPOW) -======= bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck,bool fCheckPOW) ->>>>>>> devmerge { const CChainParams& chainparams = Params(); @@ -3164,11 +3160,7 @@ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock * LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001); { CCoinsViewCache view(pcoinsTip); -<<<<<<< HEAD - bool rv = ConnectBlock(*pblock, state, pindexNew, view,false,true); -======= bool rv = ConnectBlock(*pblock, state, pindexNew, view, false, true); ->>>>>>> devmerge GetMainSignals().BlockChecked(*pblock, state); if (!rv) { if (state.IsInvalid()) @@ -4671,11 +4663,7 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth CBlock block; if (!ReadBlockFromDisk(block, pindex)) return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); -<<<<<<< HEAD - if (!ConnectBlock(block, state, pindex, coins,false,true)) -======= if (!ConnectBlock(block, state, pindex, coins,false, true)) ->>>>>>> devmerge return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); } } From b95368bf871537fd660be79c2087c8813bb390d3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 08:56:27 +0300 Subject: [PATCH 343/507] Mining fix --- src/main.cpp | 7 +++---- src/miner.cpp | 12 ++++++------ 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 83026de4b..fdac8db95 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3509,7 +3509,7 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl // return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low"); // Check Equihash solution is valid - if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) ) + /*if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) ) return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); // Check proof of work matches claimed amount @@ -3568,12 +3568,11 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat fprintf(stderr,"checkblockheader error PoW.%d\n",fCheckPOW); return false; } + if ( fCheckPOW && !CheckEquihashSolution(&block, Params()) ) + return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) - { - //komodo_reverify_blockcheck(state,height,pindex); return state.DoS(1, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); - } // Check the merkle root. if (fCheckMerkleRoot) { bool mutated; diff --git a/src/miner.cpp b/src/miner.cpp index 60140b0af..93f19818f 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -918,6 +918,12 @@ void static BitcoinMiner() // fprintf(stderr," missed target\n"); return false; } + CValidationState state; + if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), true, false)) + { + fprintf(stderr,"Invalid block mined, try again\n"); + return(false); + } if ( ASSETCHAINS_STAKED == 0 ) { if ( Mining_start != 0 && time(NULL) < Mining_start+roundrobin_delay ) @@ -935,12 +941,6 @@ void static BitcoinMiner() } else { - CValidationState state; - if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), true, false)) - { - fprintf(stderr,"Invalid block mined, try again\n"); - return(false); - } if ( NOTARY_PUBKEY33[0] != 0 ) { printf("need to wait %d seconds to submit\n",(int32_t)(pblock->nTime - GetAdjustedTime())); From 7a1b1fc4ff1b3c63f4aababd9f82e289580cf227 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 11:30:11 +0300 Subject: [PATCH 344/507] if ( pindex != 0 ) --- src/main.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index fdac8db95..61954f439 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3785,7 +3785,8 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc if ( *ppindex == 0 ) fprintf(stderr,"unexpected null *ppindex\n"); #endif - return true; + if ( pindex != 0 ) + return true; } if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state,0)) @@ -3807,7 +3808,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc } if (!ContextualCheckBlockHeader(block, state, pindexPrev)) { - fprintf(stderr,"ContextualCheckBlockHeader failed\n"); + //fprintf(stderr,"ContextualCheckBlockHeader failed\n"); return false; } if (pindex == NULL) From 54bf05383c504ec8b0deacefff5d5aca26099ae3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 11:31:34 +0300 Subject: [PATCH 345/507] if ( pindex != 0 ) --- src/main.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 4a3e5c3ea..3e1063471 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4022,7 +4022,8 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc if ( *ppindex == 0 ) fprintf(stderr,"unexpected null *ppindex\n"); #endif - return true; + if ( pindex != 0 ) + return true; } if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state,0)) @@ -4044,7 +4045,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc } if (!ContextualCheckBlockHeader(block, state, pindexPrev)) { - fprintf(stderr,"ContextualCheckBlockHeader failed\n"); + //fprintf(stderr,"ContextualCheckBlockHeader failed\n"); return false; } if (pindex == NULL) From 5215d24e8188258bee76e3b1d4b6af418bc806dc Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 12:19:54 +0300 Subject: [PATCH 346/507] Test another chance --- src/main.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 3e1063471..345a6d880 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3977,14 +3977,21 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc // Check for duplicate uint256 hash = block.GetHash(); BlockMap::iterator miSelf = mapBlockIndex.find(hash); - CBlockIndex *pindex = NULL; - if (miSelf != mapBlockIndex.end()) { + CBlockIndex *tipindex,*pindex = NULL; + if (miSelf != mapBlockIndex.end()) + { // Block header is already known. pindex = miSelf->second; if (ppindex) *ppindex = pindex; if ( pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK ) - return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); + { + if ( IsInitialBlockDownload() == 0 && (tipindex= chainActive.Tip()) != 0 &&KOMODO_LONGESTCHAIN > height+200 && KOMODO_NEWBLOCKS == 0 ) + { + pindex->nStatus &= ~(BLOCK_FAILED_MASK); + fprintf(stderr,"give ht.%d another chance\n",pindex->nHeight); + } else return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); + } #ifdef DEXcode if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 debug test { From 68cf8a7e66abc57b9ddb0270738e83c2ba11c84e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 12:21:46 +0300 Subject: [PATCH 347/507] Fix --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 345a6d880..f44e12d88 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3986,7 +3986,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc *ppindex = pindex; if ( pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK ) { - if ( IsInitialBlockDownload() == 0 && (tipindex= chainActive.Tip()) != 0 &&KOMODO_LONGESTCHAIN > height+200 && KOMODO_NEWBLOCKS == 0 ) + if ( IsInitialBlockDownload() == 0 && (tipindex= chainActive.Tip()) != 0 &&KOMODO_LONGESTCHAIN > pindex->nHeight+200 && KOMODO_NEWBLOCKS == 0 ) { pindex->nStatus &= ~(BLOCK_FAILED_MASK); fprintf(stderr,"give ht.%d another chance\n",pindex->nHeight); From b8dd52900a2a82cf372fc6887d68f2c7ecce65a4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 13:02:38 +0300 Subject: [PATCH 348/507] Disable auto rewind --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index ad99a4387..1b557d08b 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -523,7 +523,7 @@ int32_t komodo_validate_chain(uint256 srchash,int32_t notarized_height) { if ( last_rewind != 0 ) { - KOMODO_REWIND = rewindtarget; + //KOMODO_REWIND = rewindtarget; fprintf(stderr,"%s FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,notarized_height,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,rewindtarget); } last_rewind = rewindtarget; From 7db1433a02e7fb2313ccefffa66bf5f82a70657e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 13:05:13 +0300 Subject: [PATCH 349/507] Disable auto rewind --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 2732c530f..859e3db9d 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -588,7 +588,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr { if ( last_rewind != 0 ) { - KOMODO_REWIND = rewindtarget; + //KOMODO_REWIND = rewindtarget; fprintf(stderr,"%s FORK detected. notarized.%d %s not in this chain! last notarization %d -> rewindtarget.%d\n",ASSETCHAINS_SYMBOL,*notarizedheightp,srchash.ToString().c_str(),sp->NOTARIZED_HEIGHT,rewindtarget); } last_rewind = rewindtarget; From 3378ff4491ffe41380b09fb87543479e396326d5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 16:47:03 +0300 Subject: [PATCH 350/507] Allow genesis, must update --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 61954f439..a06244393 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3505,8 +3505,8 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl return state.Invalid(error("CheckBlockHeader(): block timestamp needs to always increase"),REJECT_INVALID, "time-too-new"); } // Check block version - //if (block.nVersion < MIN_BLOCK_VERSION) - // return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low"); + if (height > 0 && block.nVersion < MIN_BLOCK_VERSION) + return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low"); // Check Equihash solution is valid /*if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) ) From edddf5f020d72a066ba3bdc248565a48edf656c9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 16:47:47 +0300 Subject: [PATCH 351/507] Allow genesis: must update --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index f44e12d88..756908702 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3742,8 +3742,8 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl return state.Invalid(error("CheckBlockHeader(): block timestamp needs to always increase"),REJECT_INVALID, "time-too-new"); } // Check block version - //if (block.nVersion < MIN_BLOCK_VERSION) - // return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low"); + if (height > 0 && block.nVersion < MIN_BLOCK_VERSION) + return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low"); // Check Equihash solution is valid /*if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) ) From 5d173d2a9a2b40739f7f97151aaec8b73fcbc4c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 17:11:14 +0300 Subject: [PATCH 352/507] Blockader --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 756908702..75c544e9d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3742,7 +3742,7 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl return state.Invalid(error("CheckBlockHeader(): block timestamp needs to always increase"),REJECT_INVALID, "time-too-new"); } // Check block version - if (height > 0 && block.nVersion < MIN_BLOCK_VERSION) + if (height > 0 && blockhdr.nVersion < MIN_BLOCK_VERSION) return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low"); // Check Equihash solution is valid From c47cc02f431ea201e7d321fa260097d0fd2dbefd Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 17:12:25 +0300 Subject: [PATCH 353/507] Blockader --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index a06244393..e1c36c802 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3505,7 +3505,7 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl return state.Invalid(error("CheckBlockHeader(): block timestamp needs to always increase"),REJECT_INVALID, "time-too-new"); } // Check block version - if (height > 0 && block.nVersion < MIN_BLOCK_VERSION) + if (height > 0 && blockhdr.nVersion < MIN_BLOCK_VERSION) return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low"); // Check Equihash solution is valid From 3ad8d2478ff256e4e8add215768fd4da2ded4185 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 19:46:37 +0300 Subject: [PATCH 354/507] Test --- src/komodo_bitcoind.h | 13 +++++++++---- src/main.cpp | 6 +++--- src/pow.cpp | 16 +++++++++------- src/pow.h | 2 +- src/rpcmining.cpp | 2 +- src/txdb.cpp | 2 +- 6 files changed, 24 insertions(+), 17 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index ba5e8d255..fcdfe5a74 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -849,10 +849,10 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre return(-1); } -int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) +int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t tiptime,uint32_t blocktime) { int32_t i,j,notaryid=0,minerid,limit,nid; uint8_t destpubkey33[33]; - komodo_chosennotary(¬aryid,height,pubkey33,timestamp); + komodo_chosennotary(¬aryid,height,pubkey33,tiptime); if ( height >= 82000 ) { if ( notaryid >= 0 ) @@ -869,7 +869,12 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh else break; } } - return(1); + if ( blocktime < tiptime+60 ) + { + fprintf(stderr,"n.%d l.%d\n",notaryid,blocktime-tiptime); + if ( height > 807000 ) + return(-2); + } else return(1); } else return(0); } else @@ -883,7 +888,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh else limit = 66; for (i=1; i 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary { - special = komodo_chosennotary(¬aryid,height,pubkey33,timestamp); + special = komodo_chosennotary(¬aryid,height,pubkey33,tiptime); for (i=0; i<33; i++) { if ( pubkey33[i] != 0 ) @@ -158,7 +160,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in return(true); // will come back via different path with pubkey set } flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); - special2 = komodo_is_special(pubkeys,mids,height,pubkey33,timestamp); + special2 = komodo_is_special(pubkeys,mids,height,pubkey33,tiptime,blocktime); if ( notaryid >= 0 ) { if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) @@ -175,7 +177,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 0; else fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); } - if ( flag != 0 || special2 > 0 ) + if ( (flag != 0 || special2 > 0) && special2 != -2 ) { //fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); diff --git a/src/pow.h b/src/pow.h index 3edec74ac..213fe228d 100644 --- a/src/pow.h +++ b/src/pow.h @@ -25,7 +25,7 @@ unsigned int CalculateNextWorkRequired(arith_uint256 bnAvg, bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams&); /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */ -bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned int nBits, const Consensus::Params&); +bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned int nBits, const Consensus::Params&,uint32_t blocktime); arith_uint256 GetBlockProof(const CBlockIndex& block); /** Return the time it would take to redo the work difference between from and to, assuming the current hashrate corresponds to the difficulty at tip, in seconds. */ diff --git a/src/rpcmining.cpp b/src/rpcmining.cpp index da1d5207f..d141c42c4 100644 --- a/src/rpcmining.cpp +++ b/src/rpcmining.cpp @@ -257,7 +257,7 @@ UniValue generate(const UniValue& params, bool fHelp) LOCK(cs_main); pblock->nSolution = soln; solutionTargetChecks.increment(); - return CheckProofOfWork(chainActive.Height(),NOTARY_PUBKEY33,pblock->GetHash(), pblock->nBits, Params().GetConsensus()); + return CheckProofOfWork(chainActive.Height(),NOTARY_PUBKEY33,pblock->GetHash(), pblock->nBits, Params().GetConsensus(),pblock->nTime); }; bool found = EhBasicSolveUncancellable(n, k, curr_state, validBlock); ehSolverRuns.increment(); diff --git a/src/txdb.cpp b/src/txdb.cpp index f37f66daf..c33816952 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -530,7 +530,7 @@ bool CBlockTreeDB::LoadBlockIndexGuts() diskindex.ToString(), pindexNew->ToString()); uint8_t pubkey33[33]; komodo_index2pubkey33(pubkey33,pindexNew,pindexNew->nHeight); - if (!CheckProofOfWork(pindexNew->nHeight,pubkey33,pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus())) + if (!CheckProofOfWork(pindexNew->nHeight,pubkey33,pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus(),pindexNew->nTime)) return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString()); pcursor->Next(); } else { From e284540042c46ffd6645af8baedc354d5fa41b5d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 20:01:00 +0300 Subject: [PATCH 355/507] Test --- src/komodo_bitcoind.h | 4 +--- src/main.cpp | 8 ++++---- src/pow.cpp | 4 ++-- src/pow.h | 2 +- src/rpcmining.cpp | 2 +- src/txdb.cpp | 2 +- 6 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index fcdfe5a74..2bc831e1f 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -871,9 +871,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh } if ( blocktime < tiptime+60 ) { - fprintf(stderr,"n.%d l.%d\n",notaryid,blocktime-tiptime); - if ( height > 807000 ) - return(-2); + fprintf(stderr,"ht.%d n.%d l.%d\n",height,notaryid,blocktime-tiptime); } else return(1); } else return(0); } diff --git a/src/main.cpp b/src/main.cpp index f3719374c..0057dfb07 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1655,7 +1655,7 @@ bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::M return true; } -bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) +bool ReadBlockFromDisk(CBlockIndex *pprev,int32_t height,CBlock& block, const CDiskBlockPos& pos) { uint8_t pubkey33[33]; block.SetNull(); @@ -1678,7 +1678,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) } // Check the header komodo_block2pubkey33(pubkey33,(CBlock *)&block); - if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus(),block.nTime))) + if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus(),block.nTime,pprev!=0?pprev->nTime:0))) { int32_t i; for (i=0; i<33; i++) fprintf(stderr,"%02x",pubkey33[i]); @@ -1693,7 +1693,7 @@ bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex) { if ( pindex == 0 ) return false; - if (!ReadBlockFromDisk(pindex->nHeight,block, pindex->GetBlockPos())) + if (!ReadBlockFromDisk(pindex->pprev,pindex->nHeight,block, pindex->GetBlockPos())) return false; if (block.GetHash() != pindex->GetBlockHash()) return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s", @@ -3808,7 +3808,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if ( fCheckPOW && !CheckEquihashSolution(&block, Params()) ) return state.DoS(100, error("CheckBlock(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); komodo_block2pubkey33(pubkey33,(CBlock *)&block); - if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus(),block.nTime) ) + if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus(),block.nTime,pindex->pprev!=0?pindex->pprev->nTime:0) ) return state.DoS(1, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); // Check the merkle root. if (fCheckMerkleRoot) { diff --git a/src/pow.cpp b/src/pow.cpp index 7c1ae8b7f..8bda92e45 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -131,13 +131,13 @@ int32_t KOMODO_LOADINGBLOCKS = 1; extern std::string NOTARY_PUBKEY; -bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int nBits,const Consensus::Params& params,uint32_t blocktime) +bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int nBits,const Consensus::Params& params,uint32_t blocktime,uint32_t tiptime) { extern int32_t KOMODO_REWIND; bool fNegative,fOverflow; uint8_t origpubkey33[33]; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t tiptime = 0; arith_uint256 bnTarget; uint8_t pubkeys[66][33]; memcpy(origpubkey33,pubkey33,33); - tiptime = komodo_chainactive_timestamp(); + //tiptime = komodo_chainactive_timestamp(); bnTarget.SetCompact(nBits, &fNegative, &fOverflow); if ( blocktime == 0 || tiptime == 0 ) fprintf(stderr,"nul blocktime.%u or tiptime.%u\n",blocktime,tiptime); diff --git a/src/pow.h b/src/pow.h index 213fe228d..f546318e9 100644 --- a/src/pow.h +++ b/src/pow.h @@ -25,7 +25,7 @@ unsigned int CalculateNextWorkRequired(arith_uint256 bnAvg, bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams&); /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */ -bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned int nBits, const Consensus::Params&,uint32_t blocktime); +bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned int nBits, const Consensus::Params&,uint32_t blocktime,uint32_t tiptime); arith_uint256 GetBlockProof(const CBlockIndex& block); /** Return the time it would take to redo the work difference between from and to, assuming the current hashrate corresponds to the difficulty at tip, in seconds. */ diff --git a/src/rpcmining.cpp b/src/rpcmining.cpp index d141c42c4..d423fc70f 100644 --- a/src/rpcmining.cpp +++ b/src/rpcmining.cpp @@ -257,7 +257,7 @@ UniValue generate(const UniValue& params, bool fHelp) LOCK(cs_main); pblock->nSolution = soln; solutionTargetChecks.increment(); - return CheckProofOfWork(chainActive.Height(),NOTARY_PUBKEY33,pblock->GetHash(), pblock->nBits, Params().GetConsensus(),pblock->nTime); + return CheckProofOfWork(chainActive.Height(),NOTARY_PUBKEY33,pblock->GetHash(), pblock->nBits, Params().GetConsensus(),pblock->nTime,chainActive.Tip()->nTime); }; bool found = EhBasicSolveUncancellable(n, k, curr_state, validBlock); ehSolverRuns.increment(); diff --git a/src/txdb.cpp b/src/txdb.cpp index c33816952..7415c75ad 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -530,7 +530,7 @@ bool CBlockTreeDB::LoadBlockIndexGuts() diskindex.ToString(), pindexNew->ToString()); uint8_t pubkey33[33]; komodo_index2pubkey33(pubkey33,pindexNew,pindexNew->nHeight); - if (!CheckProofOfWork(pindexNew->nHeight,pubkey33,pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus(),pindexNew->nTime)) + if (!CheckProofOfWork(pindexNew->nHeight,pubkey33,pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus(),pindexNew->nTime,pindexNew->pprev!=0?pindexNew->pprev->nTime:0)) return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString()); pcursor->Next(); } else { From a30dd993bfe64e2926741da0a68678242fa1c64b Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 20:16:28 +0300 Subject: [PATCH 356/507] Test --- src/komodo_bitcoind.h | 9 +++++---- src/komodo_notary.h | 2 +- src/main.cpp | 8 ++++---- src/miner.cpp | 6 +++--- src/pow.cpp | 16 +++++++--------- src/pow.h | 2 +- src/rpcmining.cpp | 2 +- src/txdb.cpp | 2 +- 8 files changed, 23 insertions(+), 24 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 2bc831e1f..6af72e298 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -804,7 +804,7 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) return(komodo_electednotary(&numnotaries,pubkey33,height,timestamp)); }*/ -int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height) +int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t blocktimes[66],int32_t *nonzpkeysp,int32_t height) { int32_t i,j,n,duplicate; CBlock block; CBlockIndex *pindex; uint8_t notarypubs33[64][33]; memset(mids,-1,sizeof(*mids)*66); @@ -813,6 +813,7 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non { if ( (pindex= komodo_chainactive(height-i)) != 0 ) { + blocktimes[i] = pindex->nTime; if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pubkeys[i],&block); @@ -849,7 +850,7 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre return(-1); } -int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t tiptime,uint32_t blocktime) +int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t blocktimes[66],int32_t height,uint8_t pubkey33[33],uint32_t tiptime,uint32_t blocktime) { int32_t i,j,notaryid=0,minerid,limit,nid; uint8_t destpubkey33[33]; komodo_chosennotary(¬aryid,height,pubkey33,tiptime); @@ -869,9 +870,9 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh else break; } } - if ( blocktime < tiptime+60 ) + if ( blocktime < blocktimes[1]+60 ) { - fprintf(stderr,"ht.%d n.%d l.%d\n",height,notaryid,blocktime-tiptime); + fprintf(stderr,"ht.%d n.%d blocktimes[%u vs %u %u]\n",height,notaryid,blocktime,blocktimes[0],blocktimes[1]); } else return(1); } else return(0); } diff --git a/src/komodo_notary.h b/src/komodo_notary.h index b770a6514..c2c8d09ef 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -127,7 +127,7 @@ const char *Notaries_elected0[][2] = }; #define KOMODO_NOTARIES_TIMESTAMP1 1525132800 // May 1st 2018 1530921600 // 7/7/2017 -#define KOMODO_NOTARIES_HEIGHT1 ((820000 / KOMODO_ELECTION_GAP) * KOMODO_ELECTION_GAP) +#define KOMODO_NOTARIES_HEIGHT1 ((814000 / KOMODO_ELECTION_GAP) * KOMODO_ELECTION_GAP) const char *Notaries_elected1[][2] = { diff --git a/src/main.cpp b/src/main.cpp index 0057dfb07..f3719374c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1655,7 +1655,7 @@ bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::M return true; } -bool ReadBlockFromDisk(CBlockIndex *pprev,int32_t height,CBlock& block, const CDiskBlockPos& pos) +bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) { uint8_t pubkey33[33]; block.SetNull(); @@ -1678,7 +1678,7 @@ bool ReadBlockFromDisk(CBlockIndex *pprev,int32_t height,CBlock& block, const CD } // Check the header komodo_block2pubkey33(pubkey33,(CBlock *)&block); - if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus(),block.nTime,pprev!=0?pprev->nTime:0))) + if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus(),block.nTime))) { int32_t i; for (i=0; i<33; i++) fprintf(stderr,"%02x",pubkey33[i]); @@ -1693,7 +1693,7 @@ bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex) { if ( pindex == 0 ) return false; - if (!ReadBlockFromDisk(pindex->pprev,pindex->nHeight,block, pindex->GetBlockPos())) + if (!ReadBlockFromDisk(pindex->nHeight,block, pindex->GetBlockPos())) return false; if (block.GetHash() != pindex->GetBlockHash()) return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s", @@ -3808,7 +3808,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if ( fCheckPOW && !CheckEquihashSolution(&block, Params()) ) return state.DoS(100, error("CheckBlock(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); komodo_block2pubkey33(pubkey33,(CBlock *)&block); - if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus(),block.nTime,pindex->pprev!=0?pindex->pprev->nTime:0) ) + if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus(),block.nTime) ) return state.DoS(1, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); // Check the merkle root. if (fCheckMerkleRoot) { diff --git a/src/miner.cpp b/src/miner.cpp index 45a405d08..9a8a75411 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -657,7 +657,7 @@ static bool ProcessBlockFound(CBlock* pblock) } int32_t komodo_baseid(char *origbase); -int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height); +int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height); arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc); int32_t FOUND_BLOCK,KOMODO_MAYBEMINED; extern int32_t KOMODO_LASTMINED; @@ -802,7 +802,7 @@ void static BitcoinMiner() // // Search // - uint8_t pubkeys[66][33]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime(); + uint8_t pubkeys[66][33]; uint32_t blocktimes[66]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime(); savebits = pblock->nBits; HASHTarget = arith_uint256().SetCompact(pblock->nBits); roundrobin_delay = ROUNDROBIN_DELAY; @@ -811,7 +811,7 @@ void static BitcoinMiner() j = 65; if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 ) { - komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,pindexPrev->nHeight); + komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->nHeight); if ( nonzpkeys > 0 ) { for (i=0; i<33; i++) diff --git a/src/pow.cpp b/src/pow.cpp index 8bda92e45..ed1f4ee08 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -117,7 +117,7 @@ bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams& param } int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); -int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t tiptime,uint32_t blocktime); +int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t blocktimes[66],int32_t height,uint8_t pubkey33[33],uint32_t tiptime,uint32_t blocktime); int32_t komodo_currentheight(); CBlockIndex *komodo_chainactive(int32_t height); void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height); @@ -126,21 +126,19 @@ extern uint64_t ASSETCHAINS_STAKED; extern char ASSETCHAINS_SYMBOL[]; #define KOMODO_ELECTION_GAP 2000 -int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height); +int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t blocktimes[66],int32_t *nonzpkeysp,int32_t height); int32_t KOMODO_LOADINGBLOCKS = 1; extern std::string NOTARY_PUBKEY; -bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int nBits,const Consensus::Params& params,uint32_t blocktime,uint32_t tiptime) +bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int nBits,const Consensus::Params& params,uint32_t blocktime) { extern int32_t KOMODO_REWIND; - bool fNegative,fOverflow; uint8_t origpubkey33[33]; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t tiptime = 0; + bool fNegative,fOverflow; uint8_t origpubkey33[33]; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t tiptime,blocktimes[66] = 0; arith_uint256 bnTarget; uint8_t pubkeys[66][33]; memcpy(origpubkey33,pubkey33,33); - //tiptime = komodo_chainactive_timestamp(); + tiptime = komodo_chainactive_timestamp(); bnTarget.SetCompact(nBits, &fNegative, &fOverflow); - if ( blocktime == 0 || tiptime == 0 ) - fprintf(stderr,"nul blocktime.%u or tiptime.%u\n",blocktime,tiptime); if ( height == 0 ) { height = komodo_currentheight() + 1; @@ -159,8 +157,8 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int //fprintf(stderr,"ht.%d null pubkey checkproof return\n",height); return(true); // will come back via different path with pubkey set } - flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); - special2 = komodo_is_special(pubkeys,mids,height,pubkey33,tiptime,blocktime); + flag = komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,height); + special2 = komodo_is_special(pubkeys,mids,blocktimes,height,pubkey33,tiptime,blocktime); if ( notaryid >= 0 ) { if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) diff --git a/src/pow.h b/src/pow.h index f546318e9..213fe228d 100644 --- a/src/pow.h +++ b/src/pow.h @@ -25,7 +25,7 @@ unsigned int CalculateNextWorkRequired(arith_uint256 bnAvg, bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams&); /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */ -bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned int nBits, const Consensus::Params&,uint32_t blocktime,uint32_t tiptime); +bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned int nBits, const Consensus::Params&,uint32_t blocktime); arith_uint256 GetBlockProof(const CBlockIndex& block); /** Return the time it would take to redo the work difference between from and to, assuming the current hashrate corresponds to the difficulty at tip, in seconds. */ diff --git a/src/rpcmining.cpp b/src/rpcmining.cpp index d423fc70f..d141c42c4 100644 --- a/src/rpcmining.cpp +++ b/src/rpcmining.cpp @@ -257,7 +257,7 @@ UniValue generate(const UniValue& params, bool fHelp) LOCK(cs_main); pblock->nSolution = soln; solutionTargetChecks.increment(); - return CheckProofOfWork(chainActive.Height(),NOTARY_PUBKEY33,pblock->GetHash(), pblock->nBits, Params().GetConsensus(),pblock->nTime,chainActive.Tip()->nTime); + return CheckProofOfWork(chainActive.Height(),NOTARY_PUBKEY33,pblock->GetHash(), pblock->nBits, Params().GetConsensus(),pblock->nTime); }; bool found = EhBasicSolveUncancellable(n, k, curr_state, validBlock); ehSolverRuns.increment(); diff --git a/src/txdb.cpp b/src/txdb.cpp index 7415c75ad..c33816952 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -530,7 +530,7 @@ bool CBlockTreeDB::LoadBlockIndexGuts() diskindex.ToString(), pindexNew->ToString()); uint8_t pubkey33[33]; komodo_index2pubkey33(pubkey33,pindexNew,pindexNew->nHeight); - if (!CheckProofOfWork(pindexNew->nHeight,pubkey33,pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus(),pindexNew->nTime,pindexNew->pprev!=0?pindexNew->pprev->nTime:0)) + if (!CheckProofOfWork(pindexNew->nHeight,pubkey33,pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus(),pindexNew->nTime)) return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString()); pcursor->Next(); } else { From b2e33f78fe701d217ffec71fc654e5a2d7100c60 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 20:17:53 +0300 Subject: [PATCH 357/507] Test --- src/pow.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index ed1f4ee08..1bb07680f 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -134,9 +134,10 @@ extern std::string NOTARY_PUBKEY; bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int nBits,const Consensus::Params& params,uint32_t blocktime) { extern int32_t KOMODO_REWIND; - bool fNegative,fOverflow; uint8_t origpubkey33[33]; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t tiptime,blocktimes[66] = 0; + bool fNegative,fOverflow; uint8_t origpubkey33[33]; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t tiptime,blocktimes[66]; arith_uint256 bnTarget; uint8_t pubkeys[66][33]; memcpy(origpubkey33,pubkey33,33); + memset(blocktimes,0,sizeof(blocktimes)); tiptime = komodo_chainactive_timestamp(); bnTarget.SetCompact(nBits, &fNegative, &fOverflow); if ( height == 0 ) From 8960e442e215fb28ee99c09424dbb8070543bd36 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 20:20:20 +0300 Subject: [PATCH 358/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 6af72e298..8f207da4a 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -872,7 +872,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t bloc } if ( blocktime < blocktimes[1]+60 ) { - fprintf(stderr,"ht.%d n.%d blocktimes[%u vs %u %u]\n",height,notaryid,blocktime,blocktimes[0],blocktimes[1]); + fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); } else return(1); } else return(0); } From dac3c30c1af5e1f877d29b678721ef6b19dd689f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 20:31:42 +0300 Subject: [PATCH 359/507] Test --- src/komodo_bitcoind.h | 6 +++--- src/pow.cpp | 9 +++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 8f207da4a..d7d0df1d0 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -850,10 +850,10 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre return(-1); } -int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t blocktimes[66],int32_t height,uint8_t pubkey33[33],uint32_t tiptime,uint32_t blocktime) +int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t blocktimes[66],int32_t height,uint8_t pubkey33[33],uint32_t blocktime) { int32_t i,j,notaryid=0,minerid,limit,nid; uint8_t destpubkey33[33]; - komodo_chosennotary(¬aryid,height,pubkey33,tiptime); + komodo_chosennotary(¬aryid,height,pubkey33,blocktimes[0]); if ( height >= 82000 ) { if ( notaryid >= 0 ) @@ -870,7 +870,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t bloc else break; } } - if ( blocktime < blocktimes[1]+60 ) + if ( blocktime < blocktimes[1]+57 ) { fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); } else return(1); diff --git a/src/pow.cpp b/src/pow.cpp index 1bb07680f..d35d5a53c 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -117,7 +117,7 @@ bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams& param } int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); -int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t blocktimes[66],int32_t height,uint8_t pubkey33[33],uint32_t tiptime,uint32_t blocktime); +int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t blocktimes[66],int32_t height,uint8_t pubkey33[33],uint32_t blocktime); int32_t komodo_currentheight(); CBlockIndex *komodo_chainactive(int32_t height); void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height); @@ -155,11 +155,11 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int } if ( nonz == 0 ) { - //fprintf(stderr,"ht.%d null pubkey checkproof return\n",height); + fprintf(stderr,"ht.%d null pubkey checkproof return\n",height); return(true); // will come back via different path with pubkey set } flag = komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,height); - special2 = komodo_is_special(pubkeys,mids,blocktimes,height,pubkey33,tiptime,blocktime); + special2 = komodo_is_special(pubkeys,mids,blocktimes,height,pubkey33,blocktime); if ( notaryid >= 0 ) { if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) @@ -178,7 +178,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int } if ( (flag != 0 || special2 > 0) && special2 != -2 ) { - //fprintf(stderr,"EASY MINING ht.%d\n",height); + fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); } } @@ -216,6 +216,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int if ( ASSETCHAINS_SYMBOL[0] != 0 || height > 792000 ) return false; } + fprintf(stderr,"height.%d notaryid.%d PoW valid\n",height,notaryid); return true; } From 70ebf02a21a2039909b91b39e25db7019ba441c8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 20:46:10 +0300 Subject: [PATCH 360/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index d7d0df1d0..74c341511 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -887,7 +887,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t bloc else limit = 66; for (i=1; i Date: Mon, 16 Apr 2018 20:49:11 +0300 Subject: [PATCH 361/507] Test --- src/pow.cpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/pow.cpp b/src/pow.cpp index d35d5a53c..2e92931ae 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -190,7 +190,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int { if ( KOMODO_LOADINGBLOCKS != 0 ) return true; -/* if ( ASSETCHAINS_SYMBOL[0] == 0 ) + if ( ASSETCHAINS_SYMBOL[0] != 0 || height > 792000 ) { if ( 1 && height > 792000 ) { @@ -208,13 +208,10 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int printf(" <- origpubkey\n"); for (i=0; i<66; i++) printf("%d ",mids[i]); - printf(" minerids from ht.%d pindex.%p\n",height,pindex); + printf(" minerids from ht.%d\n",height); } - if ( height > 792000 ) - return false; - } else return false;*/ - if ( ASSETCHAINS_SYMBOL[0] != 0 || height > 792000 ) return false; + } } fprintf(stderr,"height.%d notaryid.%d PoW valid\n",height,notaryid); return true; From 973793f7572c4ef8b268035291d64d88d6e5d34a Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 20:50:13 +0300 Subject: [PATCH 362/507] Test --- src/pow.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 2e92931ae..9bdd90cb1 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -213,7 +213,12 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int return false; } } - fprintf(stderr,"height.%d notaryid.%d PoW valid\n",height,notaryid); + for (i=31; i>=0; i--) + fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); + fprintf(stderr," hash vs "); + for (i=31; i>=0; i--) + fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); + fprintf(stderr," height.%d notaryid.%d PoW valid\n",height,notaryid); return true; } From a8854ddf143e8d43ce25a86b5e45b861ad298a1d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 20:51:08 +0300 Subject: [PATCH 363/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 74c341511..ac1568913 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -870,9 +870,9 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t bloc else break; } } + fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); if ( blocktime < blocktimes[1]+57 ) { - fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); } else return(1); } else return(0); } From 0f5e787bbcbfc0a6dd3a28a2991dd1071c9f05ef Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 20:57:44 +0300 Subject: [PATCH 364/507] Test --- src/komodo_bitcoind.h | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index ac1568913..05db31fa9 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -856,21 +856,22 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t bloc komodo_chosennotary(¬aryid,height,pubkey33,blocktimes[0]); if ( height >= 82000 ) { + fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); if ( notaryid >= 0 ) { for (i=1; i<66; i++) { if ( mids[i] == notaryid ) { - //for (j=0; j<66; j++) - // fprintf(stderr,"%d ",mids[j]); - //fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,notaryid,i); if ( height > 792000 ) + { + for (j=0; j<66; j++) + fprintf(stderr,"%d ",mids[j]); + fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,notaryid,i); return(-1); - else break; + } else break; } } - fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); if ( blocktime < blocktimes[1]+57 ) { } else return(1); From a658d9269f09b03ade72596558ccb14cb745bdfc Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 21:08:20 +0300 Subject: [PATCH 365/507] Test --- src/komodo_bitcoind.h | 6 ++++-- src/pow.cpp | 6 +++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 05db31fa9..46a6349e3 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -856,7 +856,6 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t bloc komodo_chosennotary(¬aryid,height,pubkey33,blocktimes[0]); if ( height >= 82000 ) { - fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); if ( notaryid >= 0 ) { for (i=1; i<66; i++) @@ -872,8 +871,11 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t bloc } else break; } } - if ( blocktime < blocktimes[1]+57 ) + if ( blocktime != 0 && blocktimes[1] != 0 && blocktime < blocktimes[1]+57 ) { + fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); + if ( height > 780000 ) + return(-2); } else return(1); } else return(0); } diff --git a/src/pow.cpp b/src/pow.cpp index 9bdd90cb1..01b4b6851 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -178,7 +178,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int } if ( (flag != 0 || special2 > 0) && special2 != -2 ) { - fprintf(stderr,"EASY MINING ht.%d\n",height); + //fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); } } @@ -213,12 +213,12 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int return false; } } - for (i=31; i>=0; i--) + /*for (i=31; i>=0; i--) fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); fprintf(stderr," hash vs "); for (i=31; i>=0; i--) fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); - fprintf(stderr," height.%d notaryid.%d PoW valid\n",height,notaryid); + fprintf(stderr," height.%d notaryid.%d PoW valid\n",height,notaryid);*/ return true; } From 26d9f4c3479b0e7789e7ed34c9896b068ed7bb4d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 21:11:35 +0300 Subject: [PATCH 366/507] Test --- src/komodo_bitcoind.h | 2 +- src/pow.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 46a6349e3..114213dbd 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -874,7 +874,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t bloc if ( blocktime != 0 && blocktimes[1] != 0 && blocktime < blocktimes[1]+57 ) { fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); - if ( height > 780000 ) + if ( height > 807000 ) return(-2); } else return(1); } else return(0); diff --git a/src/pow.cpp b/src/pow.cpp index 01b4b6851..83f9cb18d 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -155,7 +155,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int } if ( nonz == 0 ) { - fprintf(stderr,"ht.%d null pubkey checkproof return\n",height); + //fprintf(stderr,"ht.%d null pubkey checkproof return\n",height); return(true); // will come back via different path with pubkey set } flag = komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,height); From fb64a588cfafd7364496927e594bd8926374c613 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 21:44:12 +0300 Subject: [PATCH 367/507] Test --- src/komodo_bitcoind.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 114213dbd..072020c03 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -876,7 +876,8 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t bloc fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); if ( height > 807000 ) return(-2); - } else return(1); + } + return(1); } else return(0); } else From 68e4ccfbb1ed95557d6c9b39d7c6f684667bfb93 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 21:45:49 +0300 Subject: [PATCH 368/507] Test --- src/komodo_bitcoind.h | 28 +++++++++++++++++--------- src/pow.cpp | 47 ++++++++++++++++++++++++++++++++++--------- 2 files changed, 55 insertions(+), 20 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 6cc32fe5d..89b9e0aab 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -651,6 +651,7 @@ int32_t komodo_block2height(CBlock *block) } if ( height != height2 ) { + //fprintf(stderr,"block2height height.%d vs height2.%d, match.%d mismatch.%d\n",height,height2,match,mismatch); mismatch++; if ( height2 >= 0 ) height = height2; @@ -803,7 +804,7 @@ void komodo_index2pubkey33(uint8_t *pubkey33,CBlockIndex *pindex,int32_t height) return(komodo_electednotary(&numnotaries,pubkey33,height,timestamp)); }*/ -int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height) +int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t blocktimes[66],int32_t *nonzpkeysp,int32_t height) { int32_t i,j,n,duplicate; CBlock block; CBlockIndex *pindex; uint8_t notarypubs33[64][33]; memset(mids,-1,sizeof(*mids)*66); @@ -812,6 +813,7 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *non { if ( (pindex= komodo_chainactive(height-i)) != 0 ) { + blocktimes[i] = pindex->nTime; if ( komodo_blockload(block,pindex) == 0 ) { komodo_block2pubkey33(pubkeys[i],&block); @@ -848,10 +850,10 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // depre return(-1); } -int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t height,uint8_t pubkey33[33],uint32_t timestamp) +int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t blocktimes[66],int32_t height,uint8_t pubkey33[33],uint32_t blocktime) { int32_t i,j,notaryid=0,minerid,limit,nid; uint8_t destpubkey33[33]; - komodo_chosennotary(¬aryid,height,pubkey33,timestamp); + komodo_chosennotary(¬aryid,height,pubkey33,blocktimes[0]); if ( height >= 82000 ) { if ( notaryid >= 0 ) @@ -860,14 +862,21 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh { if ( mids[i] == notaryid ) { - //for (j=0; j<66; j++) - // fprintf(stderr,"%d ",mids[j]); - //fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,notaryid,i); if ( height > 792000 ) + { + for (j=0; j<66; j++) + fprintf(stderr,"%d ",mids[j]); + fprintf(stderr,"ht.%d repeat notaryid.%d in mids[%d]\n",height,notaryid,i); return(-1); - else break; + } else break; } } + if ( blocktime != 0 && blocktimes[1] != 0 && blocktime < blocktimes[1]+57 ) + { + fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); + if ( height > 807000 ) + return(-2); + } return(1); } else return(0); } @@ -882,7 +891,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],int32_t heigh else limit = 66; for (i=1; i 34000 && ASSETCHAINS_SYMBOL[0] == 0 ) // 0 -> non-special notary { - special = komodo_chosennotary(¬aryid,height,pubkey33,timestamp); + special = komodo_chosennotary(¬aryid,height,pubkey33,tiptime); for (i=0; i<33; i++) { if ( pubkey33[i] != 0 ) @@ -158,8 +158,8 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in //fprintf(stderr,"ht.%d null pubkey checkproof return\n",height); return(true); // will come back via different path with pubkey set } - flag = komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,height); - special2 = komodo_is_special(pubkeys,mids,height,pubkey33,timestamp); + flag = komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,height); + special2 = komodo_is_special(pubkeys,mids,blocktimes,height,pubkey33,blocktime); if ( notaryid >= 0 ) { if ( height > 10000 && height < 80000 && (special != 0 || special2 > 0) ) @@ -176,7 +176,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in flag = 0; else fprintf(stderr,"ht.%d notaryid.%d special.%d flag.%d special2.%d\n",height,notaryid,special,flag,special2); } - if ( flag != 0 || special2 > 0 ) + if ( (flag != 0 || special2 > 0) && special2 != -2 ) { //fprintf(stderr,"EASY MINING ht.%d\n",height); bnTarget.SetCompact(KOMODO_MINDIFF_NBITS,&fNegative,&fOverflow); @@ -191,11 +191,38 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned in if ( KOMODO_LOADINGBLOCKS != 0 ) return true; if ( ASSETCHAINS_SYMBOL[0] != 0 || height > 792000 ) + { + if ( 1 && height > 792000 ) + { + for (i=31; i>=0; i--) + printf("%02x",((uint8_t *)&hash)[i]); + printf(" hash vs "); + for (i=31; i>=0; i--) + printf("%02x",((uint8_t *)&bnTarget)[i]); + printf(" ht.%d special.%d notaryid.%d ht.%d mod.%d error\n",height,special,notaryid,height,(height % 35)); + for (i=0; i<33; i++) + printf("%02x",pubkey33[i]); + printf(" <- pubkey\n"); + for (i=0; i<33; i++) + printf("%02x",origpubkey33[i]); + printf(" <- origpubkey\n"); + for (i=0; i<66; i++) + printf("%d ",mids[i]); + printf(" minerids from ht.%d\n",height); + } return false; + } } + /*for (i=31; i>=0; i--) + fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); + fprintf(stderr," hash vs "); + for (i=31; i>=0; i--) + fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); + fprintf(stderr," height.%d notaryid.%d PoW valid\n",height,notaryid);*/ return true; } + arith_uint256 GetBlockProof(const CBlockIndex& block) { arith_uint256 bnTarget; From 4263420bc8826f5b5cee820f9ca4c5f65ee0a8af Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 21:47:52 +0300 Subject: [PATCH 369/507] Test --- src/main.cpp | 6 +++--- src/miner.cpp | 4 ++-- src/pow.h | 2 +- src/rpcmining.cpp | 2 +- src/txdb.cpp | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index e1c36c802..028b72623 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1616,7 +1616,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) } // Check the header komodo_block2pubkey33(pubkey33,(CBlock *)&block); - if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()))) + if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus(),block.nTime))) { int32_t i; for (i=0; i<33; i++) fprintf(stderr,"%02x",pubkey33[i]); @@ -3514,7 +3514,7 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl // Check proof of work matches claimed amount /*komodo_index2pubkey33(pubkey33,pindex,height); - if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus()) ) + if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus(),blockhdr.nTime) ) return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),REJECT_INVALID, "high-hash");*/ return true; } @@ -3571,7 +3571,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if ( fCheckPOW && !CheckEquihashSolution(&block, Params()) ) return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); komodo_block2pubkey33(pubkey33,(CBlock *)&block); - if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus()) ) + if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus(),block.nTime) ) return state.DoS(1, error("CheckBlock(): proof of work failed"),REJECT_INVALID, "high-hash"); // Check the merkle root. if (fCheckMerkleRoot) { diff --git a/src/miner.cpp b/src/miner.cpp index 93f19818f..d60dea6a7 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -804,7 +804,7 @@ void static BitcoinMiner() // // Search // - uint8_t pubkeys[66][33]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime(); + uint8_t pubkeys[66][33]; uint32_t blocktimes[66];int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime(); savebits = pblock->nBits; HASHTarget = arith_uint256().SetCompact(pblock->nBits); roundrobin_delay = ROUNDROBIN_DELAY; @@ -813,7 +813,7 @@ void static BitcoinMiner() j = 65; if ( (Mining_height >= 235300 && Mining_height < 236000) || (Mining_height % KOMODO_ELECTION_GAP) > 64 || (Mining_height % KOMODO_ELECTION_GAP) == 0 ) { - komodo_eligiblenotary(pubkeys,mids,&nonzpkeys,pindexPrev->nHeight); + komodo_eligiblenotary(pubkeys,mids,blocktimes,&nonzpkeys,pindexPrev->nHeight); if ( nonzpkeys > 0 ) { for (i=0; i<33; i++) diff --git a/src/pow.h b/src/pow.h index 3edec74ac..213fe228d 100644 --- a/src/pow.h +++ b/src/pow.h @@ -25,7 +25,7 @@ unsigned int CalculateNextWorkRequired(arith_uint256 bnAvg, bool CheckEquihashSolution(const CBlockHeader *pblock, const CChainParams&); /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */ -bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned int nBits, const Consensus::Params&); +bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash, unsigned int nBits, const Consensus::Params&,uint32_t blocktime); arith_uint256 GetBlockProof(const CBlockIndex& block); /** Return the time it would take to redo the work difference between from and to, assuming the current hashrate corresponds to the difficulty at tip, in seconds. */ diff --git a/src/rpcmining.cpp b/src/rpcmining.cpp index da1d5207f..d141c42c4 100644 --- a/src/rpcmining.cpp +++ b/src/rpcmining.cpp @@ -257,7 +257,7 @@ UniValue generate(const UniValue& params, bool fHelp) LOCK(cs_main); pblock->nSolution = soln; solutionTargetChecks.increment(); - return CheckProofOfWork(chainActive.Height(),NOTARY_PUBKEY33,pblock->GetHash(), pblock->nBits, Params().GetConsensus()); + return CheckProofOfWork(chainActive.Height(),NOTARY_PUBKEY33,pblock->GetHash(), pblock->nBits, Params().GetConsensus(),pblock->nTime); }; bool found = EhBasicSolveUncancellable(n, k, curr_state, validBlock); ehSolverRuns.increment(); diff --git a/src/txdb.cpp b/src/txdb.cpp index f1adb11be..73109881f 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -324,7 +324,7 @@ bool CBlockTreeDB::LoadBlockIndexGuts() diskindex.ToString(), pindexNew->ToString()); uint8_t pubkey33[33]; komodo_index2pubkey33(pubkey33,pindexNew,pindexNew->nHeight); - if (!CheckProofOfWork(pindexNew->nHeight,pubkey33,pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus())) + if (!CheckProofOfWork(pindexNew->nHeight,pubkey33,pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus(),pindexNew->nTime)) return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString()); pcursor->Next(); } else { From 5c000d526f8ccb3d38996238a9c4568eec48eb8f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 21:51:07 +0300 Subject: [PATCH 370/507] test --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index d60dea6a7..bb07b5ebb 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -658,7 +658,7 @@ static bool ProcessBlockFound(CBlock* pblock) } int32_t komodo_baseid(char *origbase); -int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,int32_t *nonzpkeysp,int32_t height); +int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t blocktimes[66],int32_t *nonzpkeysp,int32_t height); arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc); int32_t FOUND_BLOCK,KOMODO_MAYBEMINED; extern int32_t KOMODO_LASTMINED; From 9c0b0da4ba754a59a3e8366fc93b0b8a586df8b6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 21:57:29 +0300 Subject: [PATCH 371/507] Test --- src/komodo_bitcoind.h | 4 ++-- src/rpcblockchain.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 89b9e0aab..ab4927079 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -908,7 +908,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t bloc return(0); } -int32_t komodo_MoM(int32_t *notarized_heightp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip) +/*int32_t komodo_MoM(int32_t *notarized_heightp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip) { int32_t depth,notarized_ht; uint256 MoM,kmdtxid; depth = komodo_MoMdata(¬arized_ht,&MoM,&kmdtxid,nHeight,MoMoMp,MoMoMoffsetp,MoMoMdepthp,kmdstartip,kmdendip); @@ -922,7 +922,7 @@ int32_t komodo_MoM(int32_t *notarized_heightp,uint256 *MoMp,uint256 *kmdtxidp,in *kmdtxidp = kmdtxid; } return(depth); -} +}*/ int32_t komodo_checkpoint(int32_t *notarized_heightp,int32_t nHeight,uint256 hash) { diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 1877c1d34..de3f55077 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -552,7 +552,7 @@ char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160, //uint32_t komodo_interest_args(int32_t *txheightp,uint32_t *tiptimep,uint64_t *valuep,uint256 hash,int32_t n); int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width); int32_t komodo_kvsearch(uint256 *refpubkeyp,int32_t current_height,uint32_t *flagsp,int32_t *heightp,uint8_t value[IGUANA_MAXSCRIPTSIZE],uint8_t *key,int32_t keylen); -int32_t komodo_MoM(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip); +//int32_t komodo_MoM(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip); UniValue kvsearch(const UniValue& params, bool fHelp) { From c77a5f86da7ebda373308e24643aab2340d87f58 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 22:30:18 +0300 Subject: [PATCH 372/507] Test --- src/miner.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/miner.cpp b/src/miner.cpp index 9a8a75411..a19003358 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -484,6 +484,8 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) UpdateTime(pblock, Params().GetConsensus(), pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); } + if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 && pblock->nTime < pindexPrev->nTime+60 ) + pblock->nTime = pindexPrev->nTime + 60; pblock->nSolution.clear(); pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); From 0f88fb0c7be0c082b43ea45ae382474b8b0248d2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 22:42:15 +0300 Subject: [PATCH 373/507] Test --- src/miner.cpp | 602 +++++++++++++++++++++++++------------------------- 1 file changed, 301 insertions(+), 301 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index bb07b5ebb..062156822 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -63,7 +63,7 @@ public: set setDependsOn; CFeeRate feeRate; double dPriority; - + COrphan(const CTransaction* ptxIn) : ptx(ptxIn), feeRate(0), dPriority(0) { } @@ -77,10 +77,10 @@ typedef boost::tuple TxPriority; class TxPriorityCompare { bool byFee; - + public: TxPriorityCompare(bool _byFee) : byFee(_byFee) { } - + bool operator()(const TxPriority& a, const TxPriority& b) { if (byFee) @@ -112,7 +112,6 @@ extern std::string NOTARY_PUBKEY; extern uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33]; uint32_t Mining_start,Mining_height; int32_t komodo_chosennotary(int32_t *notaryidp,int32_t height,uint8_t *pubkey33,uint32_t timestamp); -int32_t komodo_is_special(int32_t height,uint8_t pubkey33[33]); int32_t komodo_pax_opreturn(int32_t height,uint8_t *opret,int32_t maxsize); uint64_t komodo_paxtotal(); int32_t komodo_baseid(char *origbase); @@ -160,30 +159,30 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) // -blockversion=N to test forking scenarios if (Params().MineBlocksOnDemand()) pblock->nVersion = GetArg("-blockversion", pblock->nVersion); - + // Add dummy coinbase tx as first transaction pblock->vtx.push_back(CTransaction()); pblocktemplate->vTxFees.push_back(-1); // updated at end pblocktemplate->vTxSigOps.push_back(-1); // updated at end - + // Largest block you're willing to create: unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE); // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity: nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize)); - + // How much of the block should be dedicated to high-priority transactions, // included regardless of the fees they pay unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE); nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize); - + // Minimum block size you want to create; block will be filled with free transactions // until there are no more or the block reaches this size: unsigned int nBlockMinSize = GetArg("-blockminsize", DEFAULT_BLOCK_MIN_SIZE); nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize); - + // Collect memory pool transactions into the block CAmount nFees = 0; - + { LOCK2(cs_main, mempool.cs); CBlockIndex* pindexPrev = chainActive.Tip(); @@ -198,7 +197,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) list vOrphan; // list memory doesn't move map > mapDependers; bool fPrintPriority = GetBoolArg("-printpriority", false); - + // This vector will be sorted into a priority queue: vector vecPriority; vecPriority.reserve(mempool.mapTx.size()); @@ -206,14 +205,14 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) mi != mempool.mapTx.end(); ++mi) { const CTransaction& tx = mi->GetTx(); - + int64_t nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) - ? nMedianTimePast - : pblock->GetBlockTime(); - + ? nMedianTimePast + : pblock->GetBlockTime(); + if (tx.IsCoinBase() || !IsFinalTx(tx, nHeight, nLockTimeCutoff) || IsExpiredTx(tx, nHeight)) continue; - if ( komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,2) < 0 ) + if ( komodo_validate_interest(tx,nHeight,(uint32_t)pblock->nTime,0) < 0 ) { fprintf(stderr,"CreateNewBlock: komodo_validate_interest failure\n"); continue; @@ -239,7 +238,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) vOrphan.pop_back(); break; } - + // Has to wait for dependencies if (!porphan) { @@ -254,27 +253,27 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) } const CCoins* coins = view.AccessCoins(txin.prevout.hash); assert(coins); - + CAmount nValueIn = coins->vout[txin.prevout.n].nValue; nTotalIn += nValueIn; - + int nConf = nHeight - coins->nHeight; - + dPriority += (double)nValueIn * nConf; } nTotalIn += tx.GetJoinSplitValueIn(); - + if (fMissingInputs) continue; - + // Priority is sum(valuein * age) / modified_txsize unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); dPriority = tx.ComputePriority(dPriority, nTxSize); - + uint256 hash = tx.GetHash(); mempool.ApplyDeltas(hash, dPriority, nTotalIn); - + CFeeRate feeRate(nTotalIn-tx.GetValueOut(), nTxSize); - + if (porphan) { porphan->dPriority = dPriority; @@ -283,37 +282,37 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) else vecPriority.push_back(TxPriority(dPriority, feeRate, &(mi->GetTx()))); } - + // Collect transactions into block uint64_t nBlockSize = 1000; uint64_t nBlockTx = 0; int64_t interest; int nBlockSigOps = 100; bool fSortedByFee = (nBlockPrioritySize <= 0); - + TxPriorityCompare comparer(fSortedByFee); std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); - + while (!vecPriority.empty()) { // Take highest priority transaction off the priority queue: double dPriority = vecPriority.front().get<0>(); CFeeRate feeRate = vecPriority.front().get<1>(); const CTransaction& tx = *(vecPriority.front().get<2>()); - + std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer); vecPriority.pop_back(); - + // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= nBlockMaxSize) continue; - + // Legacy limits on sigOps: unsigned int nTxSigOps = GetLegacySigOpCount(tx); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1) continue; - + // Skip free transactions if we're past the minimum block size: const uint256& hash = tx.GetHash(); double dPriorityDelta = 0; @@ -321,7 +320,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta); if (fSortedByFee && (dPriorityDelta <= 0) && (nFeeDelta <= 0) && (feeRate < ::minRelayTxFee) && (nBlockSize + nTxSize >= nBlockMinSize)) continue; - + // Prioritise by fee once past the priority size or we run out of high-priority // transactions: if (!fSortedByFee && @@ -331,16 +330,16 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) comparer = TxPriorityCompare(fSortedByFee); std::make_heap(vecPriority.begin(), vecPriority.end(), comparer); } - + if (!view.HaveInputs(tx)) continue; - + CAmount nTxFees = view.GetValueIn(chainActive.Tip()->nHeight,&interest,tx,chainActive.Tip()->nTime)-tx.GetValueOut(); - + nTxSigOps += GetP2SHSigOpCount(tx, view); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS-1) continue; - + // Note that flags: we don't want to set mempool/IsStandard() // policy here, but we still have to ensure that the block we // create only contains transactions that are valid in new blocks. @@ -348,9 +347,9 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) PrecomputedTransactionData txdata(tx); if (!ContextualCheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, txdata, Params().GetConsensus(), consensusBranchId)) continue; - + UpdateCoins(tx, view, nHeight); - + // Added pblock->vtx.push_back(tx); pblocktemplate->vTxFees.push_back(nTxFees); @@ -359,12 +358,12 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; - + if (fPrintPriority) { LogPrintf("priority %.1f fee %s txid %s\n",dPriority, feeRate.ToString(), tx.GetHash().ToString()); } - + // Add transactions that depend on this one to the priority queue if (mapDependers.count(hash)) { @@ -382,7 +381,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) } } } - + nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; blocktime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); @@ -402,21 +401,21 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) pblocktemplate->vTxSigOps.push_back(GetLegacySigOpCount(txStaked)); nFees += txfees; pblock->nTime = blocktime; - if ( GetAdjustedTime()+30 < pblock->nTime ) + if ( GetAdjustedTime() < pblock->nTime ) { - //printf("need to wait %d seconds to submit: ",(int32_t)(pblock->nTime - GetAdjustedTime())); - /*while ( GetAdjustedTime()+30 < pblock->nTime ) + printf("need to wait %d seconds to submit: ",(int32_t)(pblock->nTime - GetAdjustedTime())); + while ( GetAdjustedTime()+30 < pblock->nTime ) { sleep(30); fprintf(stderr,"%d ",(int32_t)(pblock->nTime - GetAdjustedTime())); - }*/ - //fprintf(stderr,"finished waiting\n"); - sleep(30); + } + fprintf(stderr,"finished waiting\n"); + //sleep(pblock->nTime - GetAdjustedTime()); } - + } else fprintf(stderr,"no utxos eligible for staking\n"); } - + // Create coinbase tx CMutableTransaction txNew = CreateNewContextualCMutableTransaction(chainparams.GetConsensus(), nHeight); txNew.vin.resize(1); @@ -429,30 +428,30 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) // Add fees txNew.vout[0].nValue += nFees; txNew.vin[0].scriptSig = CScript() << nHeight << OP_0; - + /*if ( ASSETCHAINS_SYMBOL[0] == 0 ) - { - int32_t i,opretlen; uint8_t opret[256],*ptr; - if ( (nHeight % 60) == 0 || komodo_gateway_deposits(&txNew,(char *)"KMD",1) == 0 ) - { - if ( (opretlen= komodo_pax_opreturn((int32_t)nHeight,opret,sizeof(opret))) > 0 ) // have pricefeed - { - txNew.vout.resize(2); - txNew.vout[1].scriptPubKey.resize(opretlen); - ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data(); - for (i=0; i 1 ) - fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size()); - }*/ + { + int32_t i,opretlen; uint8_t opret[256],*ptr; + if ( (nHeight % 60) == 0 || komodo_gateway_deposits(&txNew,(char *)"KMD",1) == 0 ) + { + if ( (opretlen= komodo_pax_opreturn((int32_t)nHeight,opret,sizeof(opret))) > 0 ) // have pricefeed + { + txNew.vout.resize(2); + txNew.vout[1].scriptPubKey.resize(opretlen); + ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data(); + for (i=0; i 1 ) + fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size()); + }*/ pblock->vtx[0] = txNew; if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission(pblocktemplate->block)) != 0 ) @@ -476,7 +475,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) nonce <<= 32; nonce >>= 16; pblock->nNonce = ArithToUint256(nonce); - + // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); pblock->hashReserved = uint256(); @@ -485,64 +484,66 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) UpdateTime(pblock, Params().GetConsensus(), pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); } + if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 && pblock->nTime < pindexPrev->nTime+60 ) + pblock->nTime = pindexPrev->nTime + 60; pblock->nSolution.clear(); pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); - + CValidationState state; if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) { static uint32_t counter; //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) - fprintf(stderr,"warning: miner testblockvalidity failed\n"); + fprintf(stderr,"warning: miner testblockvalidity failed\n"); return(0); } } - + return pblocktemplate.release(); } /* -#ifdef ENABLE_WALLET -boost::optional GetMinerScriptPubKey(CReserveKey& reservekey) -#else -boost::optional GetMinerScriptPubKey() -#endif -{ - CKeyID keyID; - CBitcoinAddress addr; - if (addr.SetString(GetArg("-mineraddress", ""))) { - addr.GetKeyID(keyID); - } else { -#ifdef ENABLE_WALLET - CPubKey pubkey; - if (!reservekey.GetReservedKey(pubkey)) { - return boost::optional(); - } - keyID = pubkey.GetID(); -#else - return boost::optional(); -#endif - } - - CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; - return scriptPubKey; -} - -#ifdef ENABLE_WALLET -CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey) -{ - boost::optional scriptPubKey = GetMinerScriptPubKey(reservekey); -#else -CBlockTemplate* CreateNewBlockWithKey() -{ - boost::optional scriptPubKey = GetMinerScriptPubKey(); -#endif - - if (!scriptPubKey) { - return NULL; - } - return CreateNewBlock(*scriptPubKey); -}*/ + #ifdef ENABLE_WALLET + boost::optional GetMinerScriptPubKey(CReserveKey& reservekey) + #else + boost::optional GetMinerScriptPubKey() + #endif + { + CKeyID keyID; + CBitcoinAddress addr; + if (addr.SetString(GetArg("-mineraddress", ""))) { + addr.GetKeyID(keyID); + } else { + #ifdef ENABLE_WALLET + CPubKey pubkey; + if (!reservekey.GetReservedKey(pubkey)) { + return boost::optional(); + } + keyID = pubkey.GetID(); + #else + return boost::optional(); + #endif + } + + CScript scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ToByteVector(keyID) << OP_EQUALVERIFY << OP_CHECKSIG; + return scriptPubKey; + } + + #ifdef ENABLE_WALLET + CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey) + { + boost::optional scriptPubKey = GetMinerScriptPubKey(reservekey); + #else + CBlockTemplate* CreateNewBlockWithKey() + { + boost::optional scriptPubKey = GetMinerScriptPubKey(); + #endif + + if (!scriptPubKey) { + return NULL; + } + return CreateNewBlock(*scriptPubKey); + }*/ ////////////////////////////////////////////////////////////////////////////// // @@ -565,7 +566,7 @@ void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& CMutableTransaction txCoinbase(pblock->vtx[0]); txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; assert(txCoinbase.vin[0].scriptSig.size() <= 100); - + pblock->vtx[0] = txCoinbase; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); } @@ -610,7 +611,7 @@ static bool ProcessBlockFound(CBlock* pblock) { LogPrintf("%s\n", pblock->ToString()); LogPrintf("generated %s height.%d\n", FormatMoney(pblock->vtx[0].vout[0].nValue),chainActive.Tip()->nHeight+1); - + // Found a solution { LOCK(cs_main); @@ -625,11 +626,11 @@ static bool ProcessBlockFound(CBlock* pblock) for (i=31; i>=0; i--) fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); fprintf(stderr," <- chainTip (stale)\n"); - + return error("KomodoMiner: generated block is stale"); } } - + #ifdef ENABLE_WALLET // Remove key from key pool if ( IS_KOMODO_NOTARY == 0 ) @@ -646,19 +647,19 @@ static bool ProcessBlockFound(CBlock* pblock) wallet.mapRequestCount[pblock->GetHash()] = 0; } #endif - + // Process this block the same as if we had received it from another node CValidationState state; if (!ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL)) return error("KomodoMiner: ProcessNewBlock, block not accepted"); - + TrackMinedBlock(pblock->GetHash()); - + return true; } int32_t komodo_baseid(char *origbase); -int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t blocktimes[66],int32_t *nonzpkeysp,int32_t height); +int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t *blocktimes,int32_t *nonzpkeysp,int32_t height); arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc); int32_t FOUND_BLOCK,KOMODO_MAYBEMINED; extern int32_t KOMODO_LASTMINED; @@ -675,15 +676,15 @@ void static BitcoinMiner() SetThreadPriority(THREAD_PRIORITY_LOWEST); RenameThread("komodo-miner"); const CChainParams& chainparams = Params(); - + #ifdef ENABLE_WALLET // Each thread has its own key CReserveKey reservekey(pwallet); #endif - + // Each thread has its own counter unsigned int nExtraNonce = 0; - + unsigned int n = chainparams.EquihashN(); unsigned int k = chainparams.EquihashK(); uint8_t *script; uint64_t total,checktoshis; int32_t i,j,notaryid = -1; @@ -693,12 +694,11 @@ void static BitcoinMiner() if ( komodo_baseid(ASSETCHAINS_SYMBOL) < 0 ) break; } - //sleep(60); komodo_chosennotary(¬aryid,chainActive.Tip()->nHeight,NOTARY_PUBKEY33,(uint32_t)chainActive.Tip()->GetBlockTime()); - + std::string solver; //if ( notaryid >= 0 || ASSETCHAINS_SYMBOL[0] != 0 ) - solver = "tromp"; + solver = "tromp"; //else solver = "default"; assert(solver == "tromp" || solver == "default"); LogPrint("pow", "Using Equihash solver \"%s\" with n = %u, k = %u\n", solver, n, k); @@ -707,13 +707,13 @@ void static BitcoinMiner() std::mutex m_cs; bool cancelSolver = false; boost::signals2::connection c = uiInterface.NotifyBlockTip.connect( - [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable { - std::lock_guard lock{m_cs}; - cancelSolver = true; - } - ); + [&m_cs, &cancelSolver](const uint256& hashNewTip) mutable { + std::lock_guard lock{m_cs}; + cancelSolver = true; + } + ); miningTimer.start(); - + try { if ( ASSETCHAINS_SYMBOL[0] != 0 ) fprintf(stderr,"try %s Mining with %s\n",ASSETCHAINS_SYMBOL,solver.c_str()); @@ -736,16 +736,16 @@ void static BitcoinMiner() break; MilliSleep(5000); //fprintf(stderr,"fvNodesEmpty %d IsInitialBlockDownload(%s) %d\n",(int32_t)fvNodesEmpty,ASSETCHAINS_SYMBOL,(int32_t)IsInitialBlockDownload()); - + } while (true); //fprintf(stderr,"%s Found peers\n",ASSETCHAINS_SYMBOL); miningTimer.start(); } /*while ( ASSETCHAINS_SYMBOL[0] != 0 && chainActive.Tip()->nHeight < ASSETCHAINS_MINHEIGHT ) - { - fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight); - sleep(3); - }*/ + { + fprintf(stderr,"%s waiting for block 100, ht.%d\n",ASSETCHAINS_SYMBOL,chainActive.Tip()->nHeight); + sleep(3); + }*/ // // Create new block // @@ -804,7 +804,7 @@ void static BitcoinMiner() // // Search // - uint8_t pubkeys[66][33]; uint32_t blocktimes[66];int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime(); + uint8_t pubkeys[66][33]; uint32_t blocktimes[66]; int mids[256],gpucount,nonzpkeys,i,j,externalflag; uint32_t savebits; int64_t nStart = GetTime(); savebits = pblock->nBits; HASHTarget = arith_uint256().SetCompact(pblock->nBits); roundrobin_delay = ROUNDROBIN_DELAY; @@ -878,11 +878,11 @@ void static BitcoinMiner() while (true) { /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt - { - fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); - sleep(10); - break; - }*/ + { + fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); + sleep(10); + break; + }*/ // Hash state KOMODO_CHOSEN_ONE = 0; crypto_generichash_blake2b_state state; @@ -903,11 +903,11 @@ void static BitcoinMiner() //fprintf(stderr,"running solver\n"); std::function)> validBlock = #ifdef ENABLE_WALLET - [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams] + [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams] #else - [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams] + [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams] #endif - (std::vector soln) { + (std::vector soln) { // Write the solution to the hash and compute the result. LogPrint("pow", "- Checking solution against target\n"); pblock->nSolution = soln; @@ -963,178 +963,178 @@ void static BitcoinMiner() #ifdef ENABLE_WALLET if (ProcessBlockFound(pblock, *pwallet, reservekey)) { #else - if (ProcessBlockFound(pblock)) { + if (ProcessBlockFound(pblock)) { #endif - // Ignore chain updates caused by us + // Ignore chain updates caused by us + std::lock_guard lock{m_cs}; + cancelSolver = false; + } + KOMODO_CHOSEN_ONE = 0; + SetThreadPriority(THREAD_PRIORITY_LOWEST); + // In regression test mode, stop mining after a block is found. + if (chainparams.MineBlocksOnDemand()) { + // Increment here because throwing skips the call below + ehSolverRuns.increment(); + throw boost::thread_interrupted(); + } + //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 ) + // sleep(1800); + return true; + }; + std::function cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) { std::lock_guard lock{m_cs}; - cancelSolver = false; - } - KOMODO_CHOSEN_ONE = 0; - SetThreadPriority(THREAD_PRIORITY_LOWEST); - // In regression test mode, stop mining after a block is found. - if (chainparams.MineBlocksOnDemand()) { - // Increment here because throwing skips the call below - ehSolverRuns.increment(); - throw boost::thread_interrupted(); - } - //if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 ) - // sleep(1800); - return true; - }; - std::function cancelled = [&m_cs, &cancelSolver](EhSolverCancelCheck pos) { - std::lock_guard lock{m_cs}; - return cancelSolver; - }; - - // TODO: factor this out into a function with the same API for each solver. - if (solver == "tromp" ) { //&& notaryid >= 0 ) { - // Create solver and initialize it. - equi eq(1); - eq.setstate(&curr_state); - - // Initialization done, start algo driver. - eq.digit0(0); - eq.xfull = eq.bfull = eq.hfull = 0; - eq.showbsizes(0); - for (u32 r = 1; r < WK; r++) { - (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0); + return cancelSolver; + }; + + // TODO: factor this out into a function with the same API for each solver. + if (solver == "tromp" ) { //&& notaryid >= 0 ) { + // Create solver and initialize it. + equi eq(1); + eq.setstate(&curr_state); + + // Initialization done, start algo driver. + eq.digit0(0); eq.xfull = eq.bfull = eq.hfull = 0; - eq.showbsizes(r); - } - eq.digitK(0); - ehSolverRuns.increment(); - - // Convert solution indices to byte array (decompress) and pass it to validBlock method. - for (size_t s = 0; s < eq.nsols; s++) { - LogPrint("pow", "Checking solution %d\n", s+1); - std::vector index_vector(PROOFSIZE); - for (size_t i = 0; i < PROOFSIZE; i++) { - index_vector[i] = eq.sols[s][i]; + eq.showbsizes(0); + for (u32 r = 1; r < WK; r++) { + (r&1) ? eq.digitodd(r, 0) : eq.digiteven(r, 0); + eq.xfull = eq.bfull = eq.hfull = 0; + eq.showbsizes(r); } - std::vector sol_char = GetMinimalFromIndices(index_vector, DIGITBITS); - - if (validBlock(sol_char)) { - // If we find a POW solution, do not try other solutions - // because they become invalid as we created a new block in blockchain. - break; - } - } - } else { - try { - // If we find a valid block, we rebuild - bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled); + eq.digitK(0); ehSolverRuns.increment(); - if (found) { - int32_t i; uint256 hash = pblock->GetHash(); - for (i=0; i<32; i++) - fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); - fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height); - FOUND_BLOCK = 1; - KOMODO_MAYBEMINED = Mining_height; + + // Convert solution indices to byte array (decompress) and pass it to validBlock method. + for (size_t s = 0; s < eq.nsols; s++) { + LogPrint("pow", "Checking solution %d\n", s+1); + std::vector index_vector(PROOFSIZE); + for (size_t i = 0; i < PROOFSIZE; i++) { + index_vector[i] = eq.sols[s][i]; + } + std::vector sol_char = GetMinimalFromIndices(index_vector, DIGITBITS); + + if (validBlock(sol_char)) { + // If we find a POW solution, do not try other solutions + // because they become invalid as we created a new block in blockchain. + break; + } + } + } else { + try { + // If we find a valid block, we rebuild + bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled); + ehSolverRuns.increment(); + if (found) { + int32_t i; uint256 hash = pblock->GetHash(); + for (i=0; i<32; i++) + fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); + fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height); + FOUND_BLOCK = 1; + KOMODO_MAYBEMINED = Mining_height; + break; + } + } catch (EhSolverCancelledException&) { + LogPrint("pow", "Equihash solver cancelled\n"); + std::lock_guard lock{m_cs}; + cancelSolver = false; + } + } + + // Check for stop or if block needs to be rebuilt + boost::this_thread::interruption_point(); + // Regtest mode doesn't require peers + if ( FOUND_BLOCK != 0 ) + { + FOUND_BLOCK = 0; + fprintf(stderr,"FOUND_BLOCK!\n"); + //sleep(2000); + } + if (vNodes.empty() && chainparams.MiningRequiresPeers()) + { + if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT ) + { + fprintf(stderr,"no nodes, break\n"); break; } - } catch (EhSolverCancelledException&) { - LogPrint("pow", "Equihash solver cancelled\n"); - std::lock_guard lock{m_cs}; - cancelSolver = false; } - } - - // Check for stop or if block needs to be rebuilt - boost::this_thread::interruption_point(); - // Regtest mode doesn't require peers - if ( FOUND_BLOCK != 0 ) - { - FOUND_BLOCK = 0; - fprintf(stderr,"FOUND_BLOCK!\n"); - //sleep(2000); - } - if (vNodes.empty() && chainparams.MiningRequiresPeers()) - { - if ( ASSETCHAINS_SYMBOL[0] == 0 || Mining_height > ASSETCHAINS_MINHEIGHT ) + if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff) { - fprintf(stderr,"no nodes, break\n"); + //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) + fprintf(stderr,"0xffff, break\n"); break; } - } - if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff) - { - //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) - fprintf(stderr,"0xffff, break\n"); - break; - } - if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) - { - if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) - fprintf(stderr,"timeout, break\n"); - break; - } - if ( pindexPrev != chainActive.Tip() ) - { - if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) - fprintf(stderr,"Tip advanced, break\n"); - break; - } - // Update nNonce and nTime - pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); - pblock->nBits = savebits; - if ( ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 ) - UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); - if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks) - { - // Changing pblock->nTime can change work required on testnet: - HASHTarget.SetCompact(pblock->nBits); + if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) + { + if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) + fprintf(stderr,"timeout, break\n"); + break; + } + if ( pindexPrev != chainActive.Tip() ) + { + if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) + fprintf(stderr,"Tip advanced, break\n"); + break; + } + // Update nNonce and nTime + pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); + pblock->nBits = savebits; + if ( ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 ) + UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); + if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks) + { + // Changing pblock->nTime can change work required on testnet: + HASHTarget.SetCompact(pblock->nBits); + } } } } - } - catch (const boost::thread_interrupted&) - { + catch (const boost::thread_interrupted&) + { + miningTimer.stop(); + c.disconnect(); + LogPrintf("KomodoMiner terminated\n"); + throw; + } + catch (const std::runtime_error &e) + { + miningTimer.stop(); + c.disconnect(); + LogPrintf("KomodoMiner runtime error: %s\n", e.what()); + return; + } miningTimer.stop(); c.disconnect(); - LogPrintf("KomodoMiner terminated\n"); - throw; } - catch (const std::runtime_error &e) - { - miningTimer.stop(); - c.disconnect(); - LogPrintf("KomodoMiner runtime error: %s\n", e.what()); - return; - } - miningTimer.stop(); - c.disconnect(); -} - + #ifdef ENABLE_WALLET -void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads) + void GenerateBitcoins(bool fGenerate, CWallet* pwallet, int nThreads) #else -void GenerateBitcoins(bool fGenerate, int nThreads) + void GenerateBitcoins(bool fGenerate, int nThreads) #endif -{ - static boost::thread_group* minerThreads = NULL; - - if (nThreads < 0) - nThreads = GetNumCores(); - - if (minerThreads != NULL) { - minerThreads->interrupt_all(); - delete minerThreads; - minerThreads = NULL; - } - - if (nThreads == 0 || !fGenerate) - return; - - minerThreads = new boost::thread_group(); - for (int i = 0; i < nThreads; i++) { + static boost::thread_group* minerThreads = NULL; + + if (nThreads < 0) + nThreads = GetNumCores(); + + if (minerThreads != NULL) + { + minerThreads->interrupt_all(); + delete minerThreads; + minerThreads = NULL; + } + + if (nThreads == 0 || !fGenerate) + return; + + minerThreads = new boost::thread_group(); + for (int i = 0; i < nThreads; i++) { #ifdef ENABLE_WALLET - minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet)); + minerThreads->create_thread(boost::bind(&BitcoinMiner, pwallet)); #else - minerThreads->create_thread(&BitcoinMiner); + minerThreads->create_thread(&BitcoinMiner); #endif + } } -} - + #endif // ENABLE_MINING From 0c8ffe59fd013ef60cc40b483491e73631be77e9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 22:52:58 +0300 Subject: [PATCH 374/507] Test --- src/main.cpp | 4 ++-- src/miner.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 028b72623..d8874b1c8 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3565,7 +3565,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat // redundant with the call in AcceptBlockHeader. if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW)) { - fprintf(stderr,"checkblockheader error PoW.%d\n",fCheckPOW); + //fprintf(stderr,"checkblockheader error PoW.%d\n",fCheckPOW); return false; } if ( fCheckPOW && !CheckEquihashSolution(&block, Params()) ) @@ -3970,7 +3970,7 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex } if (!CheckBlock(indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot)) { - fprintf(stderr,"TestBlockValidity failure B\n"); + //fprintf(stderr,"TestBlockValidity failure B\n"); return false; } if (!ContextualCheckBlock(block, state, pindexPrev)) diff --git a/src/miner.cpp b/src/miner.cpp index 062156822..df75ba6dc 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -492,9 +492,9 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) CValidationState state; if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) { - static uint32_t counter; + //static uint32_t counter; //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) - fprintf(stderr,"warning: miner testblockvalidity failed\n"); + //fprintf(stderr,"warning: miner testblockvalidity failed\n"); return(0); } } From 404721449e9e685b19a89aa23acf7ab13e0838e5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 22:54:24 +0300 Subject: [PATCH 375/507] Test --- src/main.cpp | 4 ++-- src/miner.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index f3719374c..d7e7b2148 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3802,7 +3802,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat // redundant with the call in AcceptBlockHeader. if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW)) { - fprintf(stderr,"checkblockheader error PoW.%d\n",fCheckPOW); + //fprintf(stderr,"checkblockheader error PoW.%d\n",fCheckPOW); return false; } if ( fCheckPOW && !CheckEquihashSolution(&block, Params()) ) @@ -4214,7 +4214,7 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex } if (!CheckBlock(indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot)) { - fprintf(stderr,"TestBlockValidity failure B\n"); + //fprintf(stderr,"TestBlockValidity failure B\n"); return false; } if (!ContextualCheckBlock(block, state, pindexPrev)) diff --git a/src/miner.cpp b/src/miner.cpp index a19003358..fc7bc1de7 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -492,9 +492,9 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) CValidationState state; if ( !TestBlockValidity(state, *pblock, pindexPrev, false, false)) { - static uint32_t counter; + //static uint32_t counter; //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) - fprintf(stderr,"warning: miner testblockvalidity failed\n"); + // fprintf(stderr,"warning: miner testblockvalidity failed\n"); return(0); } } From 707b061c254fc96319bbf5d1b244cefacd0256c3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 23:03:05 +0300 Subject: [PATCH 376/507] Test --- src/komodo_bitcoind.h | 3 ++- src/miner.cpp | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 072020c03..2b4848004 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -873,7 +873,8 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t bloc } if ( blocktime != 0 && blocktimes[1] != 0 && blocktime < blocktimes[1]+57 ) { - fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); + if ( height > 790000 ) + fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); if ( height > 807000 ) return(-2); } diff --git a/src/miner.cpp b/src/miner.cpp index fc7bc1de7..3a181e64b 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -485,7 +485,12 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); } if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 && pblock->nTime < pindexPrev->nTime+60 ) + { pblock->nTime = pindexPrev->nTime + 60; + fprintf(stderr,"block.nTime %u vs prev.%u, gettime.%u vs adjusted.%u\n",pblock->nTime,pindexPrev->nTime + 60,pblock->GetBlockTime(),GetAdjustedTime() + 60); + while ( pblock->GetBlockTime() > GetAdjustedTime() + 60 ) + sleep(1); + } pblock->nSolution.clear(); pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); From 79d6d16cfcaa9fd14dd3593cf23ff3da09034023 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 23:06:03 +0300 Subject: [PATCH 377/507] Test --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index 3a181e64b..18e75f22a 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -487,7 +487,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 && pblock->nTime < pindexPrev->nTime+60 ) { pblock->nTime = pindexPrev->nTime + 60; - fprintf(stderr,"block.nTime %u vs prev.%u, gettime.%u vs adjusted.%u\n",pblock->nTime,pindexPrev->nTime + 60,pblock->GetBlockTime(),GetAdjustedTime() + 60); + fprintf(stderr,"block.nTime %u vs prev.%u, gettime.%u vs adjusted.%u\n",(uint32_t)pblock->nTime,(uint32_t)(pindexPrev->nTime + 60),(uint32_t)pblock->GetBlockTime(),(uint32_t)(GetAdjustedTime() + 60)); while ( pblock->GetBlockTime() > GetAdjustedTime() + 60 ) sleep(1); } From f7ce3004cd39bec78167f117801ba477306a58c8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 23:15:02 +0300 Subject: [PATCH 378/507] Test --- src/komodo_bitcoind.h | 4 ++-- src/main.cpp | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 2b4848004..2679917a5 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -873,8 +873,8 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t bloc } if ( blocktime != 0 && blocktimes[1] != 0 && blocktime < blocktimes[1]+57 ) { - if ( height > 790000 ) - fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); + //if ( height > 790000 ) + // fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); if ( height > 807000 ) return(-2); } diff --git a/src/main.cpp b/src/main.cpp index d7e7b2148..760127993 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4058,7 +4058,9 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc if (pindex == NULL) { if ( (pindex= AddToBlockIndex(block)) == 0 ) - fprintf(stderr,"couldnt add to block index\n"); + { + //fprintf(stderr,"couldnt add to block index\n"); + } } if (ppindex) *ppindex = pindex; From 2814a36378206862411b671a83bdb16c66fee046 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 23:16:57 +0300 Subject: [PATCH 379/507] Test --- src/komodo_bitcoind.h | 2 +- src/main.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index ab4927079..3d569577f 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -873,7 +873,7 @@ int32_t komodo_is_special(uint8_t pubkeys[66][33],int32_t mids[66],uint32_t bloc } if ( blocktime != 0 && blocktimes[1] != 0 && blocktime < blocktimes[1]+57 ) { - fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); + //fprintf(stderr,"lag.%d ht.%d n.%d blocktimes[%u vs %u %u]\n",blocktime-blocktimes[1],height,notaryid,blocktime,blocktimes[0],blocktimes[1]); if ( height > 807000 ) return(-2); } diff --git a/src/main.cpp b/src/main.cpp index d8874b1c8..029429cb8 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3829,7 +3829,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CBlockIndex *&pindex = *ppindex; if (!AcceptBlockHeader(block, state, &pindex)) { - fprintf(stderr,"AcceptBlockHeader rejected\n"); + //fprintf(stderr,"AcceptBlockHeader rejected\n"); return false; } if ( pindex == 0 ) From 0b2881023755afe34971655e68a3585c4ceaf300 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 23:21:24 +0300 Subject: [PATCH 380/507] Test --- src/miner.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/miner.cpp b/src/miner.cpp index df75ba6dc..84194f5ba 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -485,7 +485,12 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); } if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 && pblock->nTime < pindexPrev->nTime+60 ) + { pblock->nTime = pindexPrev->nTime + 60; + fprintf(stderr,"block.nTime %u vs prev.%u, gettime.%u vs adjusted.%u\n",(uint32_t)pblock->nTime,(uint32_t)(pindexPrev->nTime + 60),(uint32_t)pblock->GetBlockTime(),(uint32_t)(GetAdjustedTime() + 60)); + while ( pblock->GetBlockTime() > GetAdjustedTime() + 60 ) + sleep(1); + } pblock->nSolution.clear(); pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); From 5afd0f5da35bf7baf0ee7d054fad36a44804878c Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 23:26:51 +0300 Subject: [PATCH 381/507] Test --- src/main.cpp | 2 +- src/miner.cpp | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 760127993..3c46997c4 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4075,7 +4075,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CBlockIndex *&pindex = *ppindex; if (!AcceptBlockHeader(block, state, &pindex)) { - fprintf(stderr,"AcceptBlockHeader rejected\n"); + //fprintf(stderr,"AcceptBlockHeader rejected\n"); return false; } if ( pindex == 0 ) diff --git a/src/miner.cpp b/src/miner.cpp index 18e75f22a..56d9324f7 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -487,9 +487,9 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) if ( ASSETCHAINS_SYMBOL[0] == 0 && NOTARY_PUBKEY33[0] != 0 && pblock->nTime < pindexPrev->nTime+60 ) { pblock->nTime = pindexPrev->nTime + 60; - fprintf(stderr,"block.nTime %u vs prev.%u, gettime.%u vs adjusted.%u\n",(uint32_t)pblock->nTime,(uint32_t)(pindexPrev->nTime + 60),(uint32_t)pblock->GetBlockTime(),(uint32_t)(GetAdjustedTime() + 60)); while ( pblock->GetBlockTime() > GetAdjustedTime() + 60 ) sleep(1); + fprintf(stderr,"block.nTime %u vs prev.%u, gettime.%u vs adjusted.%u\n",(uint32_t)pblock->nTime,(uint32_t)(pindexPrev->nTime + 60),(uint32_t)pblock->GetBlockTime(),(uint32_t)(GetAdjustedTime() + 60)); } pblock->nSolution.clear(); pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); @@ -934,9 +934,9 @@ void static BitcoinMiner() if ( Mining_start != 0 && time(NULL) < Mining_start+roundrobin_delay ) { //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+roundrobin_delay-time(NULL))); - int32_t nseconds = Mining_start+roundrobin_delay-time(NULL); - if ( nseconds > 0 ) - sleep(nseconds); + //int32_t nseconds = Mining_start+roundrobin_delay-time(NULL); + //if ( nseconds > 0 ) + // sleep(nseconds); MilliSleep((rand() % 1700) + 1); } else if ( ASSETCHAINS_SYMBOL[0] != 0 ) From f78ecb0abaa6d7feb1f99fad68cdc12cb78a320a Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 16 Apr 2018 23:35:38 +0300 Subject: [PATCH 382/507] Test --- src/miner.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 84194f5ba..01817c759 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -934,9 +934,9 @@ void static BitcoinMiner() if ( Mining_start != 0 && time(NULL) < Mining_start+roundrobin_delay ) { //printf("Round robin diff sleep %d\n",(int32_t)(Mining_start+roundrobin_delay-time(NULL))); - int32_t nseconds = Mining_start+roundrobin_delay-time(NULL); - if ( nseconds > 0 ) - sleep(nseconds); + //int32_t nseconds = Mining_start+roundrobin_delay-time(NULL); + //if ( nseconds > 0 ) + // sleep(nseconds); MilliSleep((rand() % 1700) + 1); } else if ( ASSETCHAINS_SYMBOL[0] != 0 ) From cb0e43a8a97b81e2eca3eff491b607952cad0b86 Mon Sep 17 00:00:00 2001 From: "Jonathan \"Duke\" Leto" Date: Mon, 16 Apr 2018 17:17:36 -0700 Subject: [PATCH 383/507] Script to stop all asset chains --- src/assetchains_stop | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/assetchains_stop diff --git a/src/assetchains_stop b/src/assetchains_stop new file mode 100644 index 000000000..29e1ab325 --- /dev/null +++ b/src/assetchains_stop @@ -0,0 +1,40 @@ +#!/bin/bash +args=("$@") +komodo_cli='./komodo-cli' +delay=20 + +function komodo_stop () +{ + $komodo_cli --ac_name=$1 stop +} + +#set -x + +komodo_stop REVS +komodo_stop SUPERNET +komodo_stop DEX +komodo_stop PANGEA +komodo_stop JUMBLR +komodo_stop BET +komodo_stop CRYPTO +komodo_stop HODL +komodo_stop MSHARK +komodo_stop BOTS +komodo_stop MGW +komodo_stop COQUI +komodo_stop WLC +komodo_stop KV +komodo_stop CEAL +komodo_stop MESH +komodo_stop MNZ +komodo_stop AXO +komodo_stop ETOMIC +komodo_stop BTCH +komodo_stop VOTE2018 +komodo_stop PIZZA +komodo_stop BEER +komodo_stop NINJA +komodo_stop OOT +komodo_stop BNTN +komodo_stop CHAIN +komodo_stop PRLPAY From 32b915c93d951d4c3b39438195f87eb6de22af95 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 10:24:56 +0300 Subject: [PATCH 384/507] test --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index 56d9324f7..ef67ad84c 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -506,7 +506,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) return pblocktemplate.release(); } - + /* #ifdef ENABLE_WALLET boost::optional GetMinerScriptPubKey(CReserveKey& reservekey) From 7eac8c6bc20c26e32c14ece783b0a74e79bcee81 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 10:37:47 +0300 Subject: [PATCH 385/507] New notaries activate 814000 --- src/main.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 029429cb8..ccd8bbd19 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4055,7 +4055,6 @@ void FindFilesToPrune(std::set& setFilesToPrune) if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) { return; } - unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP; uint64_t nCurrentUsage = CalculateCurrentUsage(); // We don't check to prune until after we've allocated new space for files From cfea8d0ff5fb404f56cfb48eefcced8758dc53bf Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 10:39:11 +0300 Subject: [PATCH 386/507] New notaries activate 814000 --- src/main.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 3c46997c4..7b690cb32 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4032,7 +4032,6 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc if ( pindex != 0 ) return true; } - if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state,0)) { fprintf(stderr,"CheckBlockHeader failed\n"); From 47a4812f1736fc8d929af624fb2d7e1a7df0094a Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 10:40:05 +0300 Subject: [PATCH 387/507] 814000 change --- src/komodo_notary.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 411914f3a..127a56329 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -128,7 +128,7 @@ const char *Notaries_elected0[][2] = }; #define KOMODO_NOTARIES_TIMESTAMP1 1525132800 // May 1st 2018 1530921600 // 7/7/2017 -#define KOMODO_NOTARIES_HEIGHT1 ((820000 / KOMODO_ELECTION_GAP) * KOMODO_ELECTION_GAP) +#define KOMODO_NOTARIES_HEIGHT1 ((814000 / KOMODO_ELECTION_GAP) * KOMODO_ELECTION_GAP) const char *Notaries_elected1[][2] = { From dc4124de8ef3f859b7c58ce10f5edc97ae933606 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 11:52:33 +0300 Subject: [PATCH 388/507] Revert special case --- src/main.cpp | 94 +++++----------------------------------------------- 1 file changed, 8 insertions(+), 86 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 7b690cb32..516a01f0c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3746,8 +3746,10 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl return state.DoS(100, error("CheckBlockHeader(): block version too low"),REJECT_INVALID, "version-too-low"); // Check Equihash solution is valid - /*if ( fCheckPOW && !CheckEquihashSolution(&blockhdr, Params()) ) - return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution");*/ + if ( fCheckPOW ) + { + if ( !CheckEquihashSolution(&blockhdr, Params()) ) + return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); // Check proof of work matches claimed amount /*komodo_index2pubkey33(pubkey33,pindex,height); @@ -3758,39 +3760,6 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtime); -int32_t komodo_reverify_blockcheck(CValidationState& state,int32_t height,CBlockIndex *pindex) -{ - static int32_t oneshot; - CBlockIndex *tipindex; int32_t rewindtarget; - if ( KOMODO_REWIND != 0 ) - oneshot = KOMODO_REWIND; - if ( oneshot == 0 && IsInitialBlockDownload() == 0 && (tipindex= chainActive.Tip()) != 0 ) - { - // if 200 blocks behind longestchain and no blocks for 2 hours - if ( KOMODO_LONGESTCHAIN > height+200 && KOMODO_NEWBLOCKS == 0 ) - { - if ( GetAdjustedTime() > tipindex->nTime+3600*2 ) - { - fprintf(stderr,"possible fork: tip.%d longest.%d newblock.%d lag.%d blocktime.%u\n",tipindex->nHeight,KOMODO_LONGESTCHAIN,height,(int32_t)(GetAdjustedTime() - tipindex->nTime),tipindex->nTime); - /*KOMODO_REWIND = tipindex->nHeight - 11; - rewindtarget = tipindex->nHeight - 11; - fprintf(stderr,"rewindtarget <- %d\n",rewindtarget); - oneshot = 1; - while ( rewindtarget > 0 && (tipindex= chainActive.Tip()) != 0 && tipindex->nHeight > rewindtarget ) - { - fprintf(stderr,"%d ",(int32_t)tipindex->nHeight); - InvalidateBlock(state,tipindex); - if ( !DisconnectTip(state) ) - break; - } - tipindex = chainActive.Tip(); - fprintf(stderr,"rewind done to %d\n",tipindex!=0?tipindex->nHeight:-1);*/ - } - } - } - return(0); -} - bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidationState& state, libzcash::ProofVerifier& verifier, bool fCheckPOW, bool fCheckMerkleRoot) @@ -3861,10 +3830,9 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"), REJECT_INVALID, "bad-blk-sigops", true); if ( komodo_check_deposit(height,block,(pindex==0||pindex->pprev==0)?0:pindex->pprev->nTime) < 0 ) - //if ( komodo_check_deposit(ASSETCHAINS_SYMBOL[0] == 0 ? height : pindex != 0 ? (int32_t)pindex->nHeight : chainActive.Tip()->nHeight+1,block,pindex==0||pindex->pprev==0?0:pindex->pprev->nTime) < 0 ) { static uint32_t counter; - //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) + if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) fprintf(stderr,"check deposit rejection\n"); return(false); } @@ -3985,52 +3953,8 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc if (ppindex) *ppindex = pindex; if ( pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK ) - { - if ( IsInitialBlockDownload() == 0 && (tipindex= chainActive.Tip()) != 0 &&KOMODO_LONGESTCHAIN > pindex->nHeight+200 && KOMODO_NEWBLOCKS == 0 ) - { - pindex->nStatus &= ~(BLOCK_FAILED_MASK); - fprintf(stderr,"give ht.%d another chance\n",pindex->nHeight); - } else return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); - } -#ifdef DEXcode - if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 debug test - { - if (!CheckBlockHeader(pindex->nHeight,pindex, block, state,0)) - { - pindex->nStatus |= BLOCK_FAILED_MASK; - fprintf(stderr,"known block failing CheckBlockHeader %d\n",(int32_t)pindex->nHeight); - return false; - } - CBlockIndex* pindexPrev = NULL; - if (hash != chainparams.GetConsensus().hashGenesisBlock) - { - BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); - if (mi == mapBlockIndex.end()) - { - pindex->nStatus |= BLOCK_FAILED_MASK; - fprintf(stderr,"known block.%d failing to find prevblock\n",(int32_t)pindex->nHeight); - return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk"); - } - pindexPrev = (*mi).second; - if (pindexPrev == 0 || (pindexPrev->nStatus & BLOCK_FAILED_MASK) ) - { - pindex->nStatus |= BLOCK_FAILED_MASK; - fprintf(stderr,"known block.%d found invalid prevblock\n",(int32_t)pindex->nHeight); - return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk"); - } - } - if (!ContextualCheckBlockHeader(block, state, pindexPrev)) - { - pindex->nStatus |= BLOCK_FAILED_MASK; - //fprintf(stderr,"known block.%d failing ContextualCheckBlockHeader\n",(int32_t)pindex->nHeight); - return false; - } - } - if ( *ppindex == 0 ) - fprintf(stderr,"unexpected null *ppindex\n"); -#endif - if ( pindex != 0 ) - return true; + return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); + return true; } if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state,0)) { @@ -4162,9 +4086,7 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc auto verifier = libzcash::ProofVerifier::Disabled(); if ( chainActive.Tip() != 0 ) komodo_currentheight_set(chainActive.Tip()->nHeight); - if ( ASSETCHAINS_SYMBOL[0] == 0 ) - checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier,0); - else checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier,0); + checked = CheckBlock(height!=0?height:komodo_block2height(pblock),0,*pblock, state, verifier,0); { LOCK(cs_main); bool fRequested = MarkBlockAsReceived(pblock->GetHash()); From ab0dd7551e991ef07ddd2e97c03a8f92d7fe5fa1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 11:53:56 +0300 Subject: [PATCH 389/507] Revert special case --- src/main.cpp | 40 +--------------------------------------- 1 file changed, 1 insertion(+), 39 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index ccd8bbd19..88073d801 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3748,45 +3748,7 @@ bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBloc *ppindex = pindex; if ( pindex != 0 && pindex->nStatus & BLOCK_FAILED_MASK ) return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate"); -#ifdef DEXcode - if ( pindex != 0 && IsInitialBlockDownload() == 0 ) // jl777 debug test - { - if (!CheckBlockHeader(pindex->nHeight,pindex, block, state,0)) - { - pindex->nStatus |= BLOCK_FAILED_MASK; - fprintf(stderr,"known block failing CheckBlockHeader %d\n",(int32_t)pindex->nHeight); - return false; - } - CBlockIndex* pindexPrev = NULL; - if (hash != chainparams.GetConsensus().hashGenesisBlock) - { - BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); - if (mi == mapBlockIndex.end()) - { - pindex->nStatus |= BLOCK_FAILED_MASK; - fprintf(stderr,"known block.%d failing to find prevblock\n",(int32_t)pindex->nHeight); - return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk"); - } - pindexPrev = (*mi).second; - if (pindexPrev == 0 || (pindexPrev->nStatus & BLOCK_FAILED_MASK) ) - { - pindex->nStatus |= BLOCK_FAILED_MASK; - fprintf(stderr,"known block.%d found invalid prevblock\n",(int32_t)pindex->nHeight); - return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk"); - } - } - if (!ContextualCheckBlockHeader(block, state, pindexPrev)) - { - pindex->nStatus |= BLOCK_FAILED_MASK; - //fprintf(stderr,"known block.%d failing ContextualCheckBlockHeader\n",(int32_t)pindex->nHeight); - return false; - } - } - if ( *ppindex == 0 ) - fprintf(stderr,"unexpected null *ppindex\n"); -#endif - if ( pindex != 0 ) - return true; + return true; } if (!CheckBlockHeader(*ppindex!=0?(*ppindex)->nHeight:0,*ppindex, block, state,0)) From 2cce69c0bdcccd28e4daef4f612729ee5c80fd7b Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 11:56:05 +0300 Subject: [PATCH 390/507] -print --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 88073d801..e680941f2 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3796,7 +3796,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, } if ( pindex == 0 ) { - fprintf(stderr,"unexpected AcceptBlock error null pindex\n"); + //fprintf(stderr,"unexpected AcceptBlock error null pindex\n"); return false; } //fprintf(stderr,"acceptblockheader passed\n"); From b8add6a4663c01858ff5c3383e7ebfd7ded4bb65 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 12:53:59 +0300 Subject: [PATCH 391/507] Init speedup test --- src/main.cpp | 96 +++++++++++++++++++++++++++------------ src/main.h | 4 +- src/rest.cpp | 2 +- src/rpcblockchain.cpp | 6 +-- src/rpcrawtransaction.cpp | 2 +- src/wallet/wallet.cpp | 6 +-- 6 files changed, 77 insertions(+), 39 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 516a01f0c..bf0974941 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1600,7 +1600,7 @@ bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock if (pindexSlow) { CBlock block; - if (ReadBlockFromDisk(block, pindexSlow)) { + if (ReadBlockFromDisk(block, pindexSlow,1)) { BOOST_FOREACH(const CTransaction &tx, block.vtx) { if (tx.GetHash() == hash) { txOut = tx; @@ -1655,7 +1655,7 @@ bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::M return true; } -bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) +bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos,bool checkPOW) { uint8_t pubkey33[33]; block.SetNull(); @@ -1677,23 +1677,26 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos) return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString()); } // Check the header - komodo_block2pubkey33(pubkey33,(CBlock *)&block); - if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus(),block.nTime))) + if ( checkPOW != 0 ) { - int32_t i; for (i=0; i<33; i++) - fprintf(stderr,"%02x",pubkey33[i]); - fprintf(stderr," warning unexpected diff at ht.%d\n",height); - - return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString()); + komodo_block2pubkey33(pubkey33,(CBlock *)&block); + if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus(),block.nTime))) + { + int32_t i; for (i=0; i<33; i++) + fprintf(stderr,"%02x",pubkey33[i]); + fprintf(stderr," warning unexpected diff at ht.%d\n",height); + + return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString()); + } } return true; } -bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex) +bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex,bool checkPOW) { if ( pindex == 0 ) return false; - if (!ReadBlockFromDisk(pindex->nHeight,block, pindex->GetBlockPos())) + if (!ReadBlockFromDisk(pindex->nHeight,block, pindex->GetBlockPos(),checkPOW)) return false; if (block.GetHash() != pindex->GetBlockHash()) return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s", @@ -3080,7 +3083,7 @@ bool static DisconnectTip(CValidationState &state, bool fBare = false) { assert(pindexDelete); // Read block from disk. CBlock block; - if (!ReadBlockFromDisk(block, pindexDelete)) + if (!ReadBlockFromDisk(block, pindexDelete,1)) return AbortNode(state, "Failed to read block"); // Apply the block atomically to the chain state. uint256 anchorBeforeDisconnect = pcoinsTip->GetBestAnchor(); @@ -3147,7 +3150,7 @@ bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock * int64_t nTime1 = GetTimeMicros(); CBlock block; if (!pblock) { - if (!ReadBlockFromDisk(block, pindexNew)) + if (!ReadBlockFromDisk(block, pindexNew,1)) return AbortNode(state, "Failed to read block"); pblock = █ } @@ -3750,7 +3753,7 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl { if ( !CheckEquihashSolution(&blockhdr, Params()) ) return state.DoS(100, error("CheckBlockHeader(): Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); - + } // Check proof of work matches claimed amount /*komodo_index2pubkey33(pubkey33,pindex,height); if ( fCheckPOW && !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(), blockhdr.nBits, Params().GetConsensus(),blockhdr.nTime) ) @@ -3760,6 +3763,38 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtime); +int32_t komodo_fast_checkPOW(CBlock *pblock,int32_t height) +{ + arith_uint256 bnTarget; bool fNegative,fOverflow; uint8_t pubkey33[33],pubkeys[64][33]; int32_t i,n,failed = 0,notaryid = -1; + if ( !CheckEquihashSolution(pblock, Params()) ) + { + fprintf(stderr,"komodo_fast_checkPOW ht.%d CheckEquihashSolution failed\n",height); + return(-1); + } + bnTarget.SetCompact(nBits, &fNegative, &fOverflow); + if ( UintToArith256(hash) > bnTarget ) + { + failed = 1; + if ( ASSETCHAINS_SYMBOL[0] == 0 ) + { + komodo_block2pubkey33(pubkey33,pblock); + if ( (n= komodo_notaries(pubkeys,height,pblock->nTime)) > 0 ) + { + for (i=0; i MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) - return state.DoS(100, error("CheckBlock(): size limits failed"), + return state.DoS(100, error("CheckBlock: size limits failed"), REJECT_INVALID, "bad-blk-length"); // First transaction must be coinbase, the rest must not be if (block.vtx.empty() || !block.vtx[0].IsCoinBase()) - return state.DoS(100, error("CheckBlock(): first tx is not coinbase"), + return state.DoS(100, error("CheckBlock: first tx is not coinbase"), REJECT_INVALID, "bad-cb-missing"); for (unsigned int i = 1; i < block.vtx.size(); i++) if (block.vtx[i].IsCoinBase()) - return state.DoS(100, error("CheckBlock(): more than one coinbase"), + return state.DoS(100, error("CheckBlock: more than one coinbase"), REJECT_INVALID, "bad-cb-multiple"); // Check transactions @@ -3819,7 +3854,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if ( komodo_validate_interest(tx,height == 0 ? komodo_block2height((CBlock *)&block) : height,block.nTime,1) < 0 ) return error("CheckBlock: komodo_validate_interest failed"); if (!CheckTransaction(tx, state, verifier)) - return error("CheckBlock(): CheckTransaction failed"); + return error("CheckBlock: CheckTransaction failed"); } unsigned int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, block.vtx) @@ -3827,7 +3862,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat nSigOps += GetLegacySigOpCount(tx); } if (nSigOps > MAX_BLOCK_SIGOPS) - return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"), + return state.DoS(100, error("CheckBlock: out-of-bounds SigOpCount"), REJECT_INVALID, "bad-blk-sigops", true); if ( komodo_check_deposit(height,block,(pindex==0||pindex->pprev==0)?0:pindex->pprev->nTime) < 0 ) { @@ -4003,7 +4038,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, } if ( pindex == 0 ) { - fprintf(stderr,"unexpected AcceptBlock error null pindex\n"); + //fprintf(stderr,"unexpected AcceptBlock error null pindex\n"); return false; } //fprintf(stderr,"acceptblockheader passed\n"); @@ -4091,6 +4126,8 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc LOCK(cs_main); bool fRequested = MarkBlockAsReceived(pblock->GetHash()); fRequested |= fForceProcessing; + if ( checked != 0 && komodo_fast_checkPOW(pblock,height) < 0 ) + checked = 0; if (!checked) { if ( pfrom != 0 ) @@ -4552,7 +4589,7 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth break; CBlock block; // check level 0: read from disk - if (!ReadBlockFromDisk(block, pindex)) + if (!ReadBlockFromDisk(block, pindex,0)) return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); // check level 1: verify block validity if (nCheckLevel >= 1 && !CheckBlock(pindex->nHeight,pindex,block, state, verifier,0)) @@ -4592,7 +4629,7 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)))); pindex = chainActive.Next(pindex); CBlock block; - if (!ReadBlockFromDisk(block, pindex)) + if (!ReadBlockFromDisk(block, pindex,0)) return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); if (!ConnectBlock(block, state, pindex, coins,false, true)) return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); @@ -4851,7 +4888,8 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) int nLoaded = 0; try { // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor - CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION); + //CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION); + CBufferedFile blkdat(fileIn, 256*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION); uint64_t nRewind = blkdat.GetPos(); while (!blkdat.eof()) { boost::this_thread::interruption_point(); @@ -4917,7 +4955,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) std::pair::iterator, std::multimap::iterator> range = mapBlocksUnknownParent.equal_range(head); while (range.first != range.second) { std::multimap::iterator it = range.first; - if (ReadBlockFromDisk(mapBlockIndex[hash]!=0?mapBlockIndex[hash]->nHeight:0,block, it->second)) + if (ReadBlockFromDisk(mapBlockIndex[hash]!=0?mapBlockIndex[hash]->nHeight:0,block, it->second,1)) { LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(), head.ToString()); @@ -5276,7 +5314,7 @@ void static ProcessGetData(CNode* pfrom) { // Send block from disk CBlock block; - if (!ReadBlockFromDisk(block, (*mi).second)) + if (!ReadBlockFromDisk(block, (*mi).second,1)) { assert(!"cannot load block from disk"); } diff --git a/src/main.h b/src/main.h index 9ae87710a..035328a22 100644 --- a/src/main.h +++ b/src/main.h @@ -780,8 +780,8 @@ bool GetAddressUnspent(uint160 addressHash, int type, /** Functions for disk access for blocks */ bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart); -bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos); -bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex); +bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos,bool checkPOW); +bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex,bool checkPOW); /** Functions for validating blocks and updating the block tree */ diff --git a/src/rest.cpp b/src/rest.cpp index eb0bf8fc4..44d1de533 100644 --- a/src/rest.cpp +++ b/src/rest.cpp @@ -214,7 +214,7 @@ static bool rest_block(HTTPRequest* req, if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0) return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not available (pruned data)"); - if (!ReadBlockFromDisk(block, pblockindex)) + if (!ReadBlockFromDisk(block, pblockindex,1)) return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found"); } diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 00b62c5b1..1ee7d377b 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -438,7 +438,7 @@ UniValue getblockdeltas(const UniValue& params, bool fHelp) if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0) throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)"); - if(!ReadBlockFromDisk(block, pblockindex)) + if(!ReadBlockFromDisk(block, pblockindex,1)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); return blockToDeltasJSON(block, pblockindex); @@ -693,7 +693,7 @@ UniValue getblock(const UniValue& params, bool fHelp) if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0) throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)"); - if(!ReadBlockFromDisk(block, pblockindex)) + if(!ReadBlockFromDisk(block, pblockindex,1)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); if (!fVerbose) @@ -962,7 +962,7 @@ UniValue txMoMproof(const UniValue& params, bool fHelp) if (fHavePruned && !(blockIndex->nStatus & BLOCK_HAVE_DATA) && blockIndex->nTx > 0) throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)"); - if(!ReadBlockFromDisk(block, blockIndex)) + if(!ReadBlockFromDisk(block, blockIndex,1)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); // Locate the transaction in the block diff --git a/src/rpcrawtransaction.cpp b/src/rpcrawtransaction.cpp index 3f93e07d6..d27a47649 100644 --- a/src/rpcrawtransaction.cpp +++ b/src/rpcrawtransaction.cpp @@ -521,7 +521,7 @@ UniValue gettxoutproof(const UniValue& params, bool fHelp) } CBlock block; - if(!ReadBlockFromDisk(block, pblockindex)) + if(!ReadBlockFromDisk(block, pblockindex,1)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); unsigned int ntxFound = 0; diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index eadf7f36d..233af1a4e 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -719,7 +719,7 @@ void CWallet::IncrementNoteWitnesses(const CBlockIndex* pindex, const CBlock* pblock {pblockIn}; CBlock block; if (!pblock) { - ReadBlockFromDisk(block, pindex); + ReadBlockFromDisk(block, pindex,1); pblock = █ } @@ -1749,7 +1749,7 @@ void CWallet::WitnessNoteCommitment(std::vector commitments, while (pindex) { CBlock block; - ReadBlockFromDisk(block, pindex); + ReadBlockFromDisk(block, pindex,1); BOOST_FOREACH(const CTransaction& tx, block.vtx) { @@ -1825,7 +1825,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100)))); CBlock block; - ReadBlockFromDisk(block, pindex); + ReadBlockFromDisk(block, pindex,1); BOOST_FOREACH(CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) From 4e8752e1adac25fd8da6c1b1f1bcb483a5e87240 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 13:06:31 +0300 Subject: [PATCH 392/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index bf0974941..6438cdf0e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3771,7 +3771,7 @@ int32_t komodo_fast_checkPOW(CBlock *pblock,int32_t height) fprintf(stderr,"komodo_fast_checkPOW ht.%d CheckEquihashSolution failed\n",height); return(-1); } - bnTarget.SetCompact(nBits, &fNegative, &fOverflow); + bnTarget.SetCompact(pblock->nBits,&fNegative,&fOverflow); if ( UintToArith256(hash) > bnTarget ) { failed = 1; From 8f91fd2b129a534612d931980861b67f783ab096 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 13:19:36 +0300 Subject: [PATCH 393/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 6438cdf0e..e77ecc3ae 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3772,7 +3772,7 @@ int32_t komodo_fast_checkPOW(CBlock *pblock,int32_t height) return(-1); } bnTarget.SetCompact(pblock->nBits,&fNegative,&fOverflow); - if ( UintToArith256(hash) > bnTarget ) + if ( UintToArith256(pblock.GetHash()) > bnTarget ) { failed = 1; if ( ASSETCHAINS_SYMBOL[0] == 0 ) From 2653fac26c1d6c7b247fc099281fdc9738c1a3ae Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 13:20:48 +0300 Subject: [PATCH 394/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index e77ecc3ae..a32a3dbe9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3772,7 +3772,7 @@ int32_t komodo_fast_checkPOW(CBlock *pblock,int32_t height) return(-1); } bnTarget.SetCompact(pblock->nBits,&fNegative,&fOverflow); - if ( UintToArith256(pblock.GetHash()) > bnTarget ) + if ( UintToArith256(pblock->GetHash()) > bnTarget ) { failed = 1; if ( ASSETCHAINS_SYMBOL[0] == 0 ) From 629191d1e45244af48ec4a458257b869e9e657af Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 13:26:13 +0300 Subject: [PATCH 395/507] Fix --- src/zmq/zmqpublishnotifier.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/zmq/zmqpublishnotifier.cpp b/src/zmq/zmqpublishnotifier.cpp index 75a2523e7..6b344636e 100644 --- a/src/zmq/zmqpublishnotifier.cpp +++ b/src/zmq/zmqpublishnotifier.cpp @@ -167,7 +167,7 @@ bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex) { LOCK(cs_main); CBlock block; - if(!ReadBlockFromDisk(block, pindex)) + if(!ReadBlockFromDisk(block, pindex,1)) { zmqError("Can't read block from disk"); return false; From ef645efa8694ff27cf89abb0b643f594c86a9537 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 13:32:59 +0300 Subject: [PATCH 396/507] Test --- src/main.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main.cpp b/src/main.cpp index a32a3dbe9..1e29bc400 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3766,6 +3766,8 @@ int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtim int32_t komodo_fast_checkPOW(CBlock *pblock,int32_t height) { arith_uint256 bnTarget; bool fNegative,fOverflow; uint8_t pubkey33[33],pubkeys[64][33]; int32_t i,n,failed = 0,notaryid = -1; + if ( height == 0 ) + return(0); if ( !CheckEquihashSolution(pblock, Params()) ) { fprintf(stderr,"komodo_fast_checkPOW ht.%d CheckEquihashSolution failed\n",height); From 484009fe691d63a6c5d4ffe594ae445116cddc2c Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 13:54:27 +0300 Subject: [PATCH 397/507] -print --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index e680941f2..8d09ffcb6 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3937,7 +3937,7 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex } if (!ContextualCheckBlock(block, state, pindexPrev)) { - fprintf(stderr,"TestBlockValidity failure C\n"); + //fprintf(stderr,"TestBlockValidity failure C\n"); return false; } if (!ConnectBlock(block, state, &indexDummy, viewNew, true,fCheckPOW)) From 0e32bd33e6473af7fa37896e549a950758682e3d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 14:22:49 +0300 Subject: [PATCH 398/507] Test --- src/komodo_ccdata.h | 2 +- src/main.cpp | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index ab3ea04b0..f5a4ada19 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -225,7 +225,7 @@ int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccd if ( nonz == 0 ) return(0); memcpy(&hash,&tmp,sizeof(hash)); - fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->MoMdata.notarized_height,hash.ToString().c_str(),ccdata->MoMdata.height,ccdata->MoMdata.txi); + //fprintf(stderr,"[%s] ccdata.%s id.%d notarized_ht.%d MoM.%s height.%d/t%d\n",ASSETCHAINS_SYMBOL,ccdata->symbol,ccdata->CCid,ccdata->MoMdata.notarized_height,hash.ToString().c_str(),ccdata->MoMdata.height,ccdata->MoMdata.txi); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { if ( CC_data != 0 && (CC_data->MoMdata.height > ccdata->MoMdata.height || (CC_data->MoMdata.height == ccdata->MoMdata.height && CC_data->MoMdata.txi >= ccdata->MoMdata.txi)) ) diff --git a/src/main.cpp b/src/main.cpp index 1e29bc400..8c01e2d89 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4181,7 +4181,7 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex } if (!ContextualCheckBlock(block, state, pindexPrev)) { - fprintf(stderr,"TestBlockValidity failure C\n"); + //fprintf(stderr,"TestBlockValidity failure C\n"); return false; } if (!ConnectBlock(block, state, &indexDummy, viewNew, true,fCheckPOW)) @@ -4313,7 +4313,7 @@ bool CheckDiskSpace(uint64_t nAdditionalBytes) FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) { - static int32_t didinit[1000]; long fsize,fpos; int32_t incr = 16*1024*1024; + static int32_t didinit[64]; long fsize,fpos; int32_t incr = 16*1024*1024; if (pos.IsNull()) return NULL; boost::filesystem::path path = GetBlockPosFilename(pos, prefix); @@ -4336,10 +4336,10 @@ FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) if ( ignore != 0 ) { rewind(file); - while ( fread(ignore,1,incr,file) == incr ) + while ( fread(ignore,1,incr,file) == incr ) // prefetch fprintf(stderr,"."); free(ignore); - fprintf(stderr,"blk.%d loaded %ld bytes set fpos.%ld loading.%d\n",(int)pos.nFile,(long)ftell(file),(long)fpos,KOMODO_LOADINGBLOCKS); + // fprintf(stderr,"blk.%d loaded %ld bytes set fpos.%ld loading.%d\n",(int)pos.nFile,(long)ftell(file),(long)fpos,KOMODO_LOADINGBLOCKS); } } fseek(file,fpos,SEEK_SET); @@ -4583,6 +4583,7 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth CValidationState state; // No need to verify JoinSplits twice auto verifier = libzcash::ProofVerifier::Disabled(); + fprintf(stderr,"start VerifyDB %u\n",(uint32_t)time(NULL)); for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) { boost::this_thread::interruption_point(); @@ -4620,6 +4621,7 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth if (ShutdownRequested()) return true; } + fprintf(stderr,"end VerifyDB %u\n",(uint32_t)time(NULL)); if (pindexFailure) return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions); @@ -4891,7 +4893,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) try { // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor //CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION); - CBufferedFile blkdat(fileIn, 256*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION); + CBufferedFile blkdat(fileIn, 32*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION); uint64_t nRewind = blkdat.GetPos(); while (!blkdat.eof()) { boost::this_thread::interruption_point(); From d00db11558f1e4d31612e6c634e8a39ccb596d29 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 14:38:07 +0300 Subject: [PATCH 399/507] Test --- src/main.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 8c01e2d89..f2ba0007a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4395,7 +4395,7 @@ bool static LoadBlockIndexDB() const CChainParams& chainparams = Params(); if (!pblocktree->LoadBlockIndexGuts()) return false; - + fprintf(stderr,"load blockindexDB %u\n",(uint32_t)time(NULL)); boost::this_thread::interruption_point(); // Calculate nChainWork @@ -4407,7 +4407,9 @@ bool static LoadBlockIndexDB() vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } + fprintf(stderr,"load blockindexDB paired %u\n",(uint32_t)time(NULL)); sort(vSortedByHeight.begin(), vSortedByHeight.end()); + fprintf(stderr,"load blockindexDB sorted %u\n",(uint32_t)time(NULL)); BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) { CBlockIndex* pindex = item.second; @@ -4456,7 +4458,8 @@ bool static LoadBlockIndexDB() pindexBestHeader = pindex; //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } - + fprintf(stderr,"load blockindexDB chained %u\n",(uint32_t)time(NULL)); + // Load block file info pblocktree->ReadLastBlockFile(nLastBlockFile); vinfoBlockFile.resize(nLastBlockFile + 1); @@ -4485,6 +4488,7 @@ bool static LoadBlockIndexDB() } //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } + fprintf(stderr,"load blockindexDB %u\n",(uint32_t)time(NULL)); for (std::set::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) { CDiskBlockPos pos(*it, 0); @@ -4583,7 +4587,7 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth CValidationState state; // No need to verify JoinSplits twice auto verifier = libzcash::ProofVerifier::Disabled(); - fprintf(stderr,"start VerifyDB %u\n",(uint32_t)time(NULL)); + //fprintf(stderr,"start VerifyDB %u\n",(uint32_t)time(NULL)); for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) { boost::this_thread::interruption_point(); @@ -4621,7 +4625,7 @@ bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth if (ShutdownRequested()) return true; } - fprintf(stderr,"end VerifyDB %u\n",(uint32_t)time(NULL)); + //fprintf(stderr,"end VerifyDB %u\n",(uint32_t)time(NULL)); if (pindexFailure) return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions); From e1a6427cc700be1ffd7273f14c48342c9e7bcad6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 14:43:59 +0300 Subject: [PATCH 400/507] Test --- src/main.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index f2ba0007a..8714ed927 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4393,9 +4393,10 @@ CBlockIndex * InsertBlockIndex(uint256 hash) bool static LoadBlockIndexDB() { const CChainParams& chainparams = Params(); + fprintf(stderr,"load blockindexDB %u\n",(uint32_t)time(NULL)); if (!pblocktree->LoadBlockIndexGuts()) return false; - fprintf(stderr,"load blockindexDB %u\n",(uint32_t)time(NULL)); + fprintf(stderr,"load blockindexDB guts %u\n",(uint32_t)time(NULL)); boost::this_thread::interruption_point(); // Calculate nChainWork @@ -4407,9 +4408,9 @@ bool static LoadBlockIndexDB() vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex)); //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } - fprintf(stderr,"load blockindexDB paired %u\n",(uint32_t)time(NULL)); + //fprintf(stderr,"load blockindexDB paired %u\n",(uint32_t)time(NULL)); sort(vSortedByHeight.begin(), vSortedByHeight.end()); - fprintf(stderr,"load blockindexDB sorted %u\n",(uint32_t)time(NULL)); + //fprintf(stderr,"load blockindexDB sorted %u\n",(uint32_t)time(NULL)); BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight) { CBlockIndex* pindex = item.second; @@ -4458,7 +4459,7 @@ bool static LoadBlockIndexDB() pindexBestHeader = pindex; //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } - fprintf(stderr,"load blockindexDB chained %u\n",(uint32_t)time(NULL)); + //fprintf(stderr,"load blockindexDB chained %u\n",(uint32_t)time(NULL)); // Load block file info pblocktree->ReadLastBlockFile(nLastBlockFile); @@ -4488,7 +4489,7 @@ bool static LoadBlockIndexDB() } //komodo_pindex_init(pindex,(int32_t)pindex->nHeight); } - fprintf(stderr,"load blockindexDB %u\n",(uint32_t)time(NULL)); + //fprintf(stderr,"load blockindexDB %u\n",(uint32_t)time(NULL)); for (std::set::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) { CDiskBlockPos pos(*it, 0); From 103fde35087671d03d40f11ab9eb873ade609b28 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 14:48:12 +0300 Subject: [PATCH 401/507] Test --- src/main.cpp | 4 ++-- src/txdb.cpp | 11 +++++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 8714ed927..0e449ebcc 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4393,10 +4393,10 @@ CBlockIndex * InsertBlockIndex(uint256 hash) bool static LoadBlockIndexDB() { const CChainParams& chainparams = Params(); - fprintf(stderr,"load blockindexDB %u\n",(uint32_t)time(NULL)); + //fprintf(stderr,"load blockindexDB %u\n",(uint32_t)time(NULL)); if (!pblocktree->LoadBlockIndexGuts()) return false; - fprintf(stderr,"load blockindexDB guts %u\n",(uint32_t)time(NULL)); + //fprintf(stderr,"load blockindexDB guts %u\n",(uint32_t)time(NULL)); boost::this_thread::interruption_point(); // Calculate nChainWork diff --git a/src/txdb.cpp b/src/txdb.cpp index c33816952..c856947ad 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -528,10 +528,13 @@ bool CBlockTreeDB::LoadBlockIndexGuts() if (header.GetHash() != pindexNew->GetBlockHash()) return error("LoadBlockIndex(): block header inconsistency detected: on-disk = %s, in-memory = %s", diskindex.ToString(), pindexNew->ToString()); - uint8_t pubkey33[33]; - komodo_index2pubkey33(pubkey33,pindexNew,pindexNew->nHeight); - if (!CheckProofOfWork(pindexNew->nHeight,pubkey33,pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus(),pindexNew->nTime)) - return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString()); + if ( 0 ) // POW will be checked before any block is connected + { + uint8_t pubkey33[33]; + komodo_index2pubkey33(pubkey33,pindexNew,pindexNew->nHeight); + if (!CheckProofOfWork(pindexNew->nHeight,pubkey33,pindexNew->GetBlockHash(), pindexNew->nBits, Params().GetConsensus(),pindexNew->nTime)) + return error("LoadBlockIndex(): CheckProofOfWork failed: %s", pindexNew->ToString()); + } pcursor->Next(); } else { break; // if shutdown requested or finished loading block index From 6a0c98266cbf93a922535edccbf12daebe325aff Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 15:03:20 +0300 Subject: [PATCH 402/507] Test --- src/main.cpp | 4 ++-- src/policy/fees.cpp | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 0e449ebcc..4bb45e954 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4393,10 +4393,10 @@ CBlockIndex * InsertBlockIndex(uint256 hash) bool static LoadBlockIndexDB() { const CChainParams& chainparams = Params(); - //fprintf(stderr,"load blockindexDB %u\n",(uint32_t)time(NULL)); + LogPrintf("%s: start loading guts\n", __func__); if (!pblocktree->LoadBlockIndexGuts()) return false; - //fprintf(stderr,"load blockindexDB guts %u\n",(uint32_t)time(NULL)); + LogPrintf("%s: loaded guts\n", __func__); boost::this_thread::interruption_point(); // Calculate nChainWork diff --git a/src/policy/fees.cpp b/src/policy/fees.cpp index e1fb1c3c6..014b97cc3 100644 --- a/src/policy/fees.cpp +++ b/src/policy/fees.cpp @@ -57,9 +57,9 @@ unsigned int TxConfirmStats::FindBucketIndex(double val) auto it = bucketMap.lower_bound(val); if ( it != bucketMap.end() ) { - static uint32_t counter; - if ( counter++ < 1 ) - fprintf(stderr,"%s FindBucketIndex violation: from val %f\n",ASSETCHAINS_SYMBOL,val); + //static uint32_t counter; + //if ( counter++ < 1 ) + // fprintf(stderr,"%s FindBucketIndex violation: from val %f\n",ASSETCHAINS_SYMBOL,val); } return it->second; } From 9baf8ee6860aee77e5f03e26245f1f05139a99a4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 15:10:05 +0300 Subject: [PATCH 403/507] Test --- src/komodo_gateway.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 8a3477b92..60d855d8d 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -1972,7 +1972,7 @@ void komodo_passport_iteration() if ( expired == 0 && KOMODO_PASSPORT_INITDONE == 0 ) { KOMODO_PASSPORT_INITDONE = 1; - printf("done PASSPORT %s refid.%d\n",ASSETCHAINS_SYMBOL,refid); + printf("READY for RPC calls at %u! done PASSPORT %s refid.%d\n",(uint32_t)time(NULL),ASSETCHAINS_SYMBOL,refid); } } From 6c0b16b0a6b6f3834368e82c4b1cfb3da0d101d8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 15:11:40 +0300 Subject: [PATCH 404/507] Display init timestamps --- src/bitcoind.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bitcoind.cpp b/src/bitcoind.cpp index bf4934da4..7d57322d0 100644 --- a/src/bitcoind.cpp +++ b/src/bitcoind.cpp @@ -125,7 +125,7 @@ bool AppInit(int argc, char* argv[]) sleep(1); #endif } - printf("initialized %s\n",ASSETCHAINS_SYMBOL); + printf("initialized %s at %u\n",ASSETCHAINS_SYMBOL,(uint32_t)time(NULL)); if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); From 5f5802ae294f68414ff40ed36c78850311720f0e Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 15:30:23 +0300 Subject: [PATCH 405/507] Test --- src/wallet/wallet.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 233af1a4e..2f9858611 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -3049,6 +3049,7 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet) return DB_LOAD_OK; fFirstRunRet = false; DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); + fprintf(stderr,"loading wallet %s %u\n",strWalletFile.ToString().c_str(),(uint32_t)time(NULL)); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) From b7fae74e5859db63c90ad349e0048f554e0a102f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 15:31:35 +0300 Subject: [PATCH 406/507] Test --- src/wallet/wallet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 2f9858611..5335e2525 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -3049,7 +3049,7 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet) return DB_LOAD_OK; fFirstRunRet = false; DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); - fprintf(stderr,"loading wallet %s %u\n",strWalletFile.ToString().c_str(),(uint32_t)time(NULL)); + fprintf(stderr,"loading wallet %s %u\n",strWalletFile.c_str(),(uint32_t)time(NULL)); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) From ccff4876b9965a453b5b4268a518af2cd47fff2b Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 15:48:23 +0300 Subject: [PATCH 407/507] -print --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 2679917a5..fd257cb0a 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -947,7 +947,7 @@ int32_t komodo_checkpoint(int32_t *notarized_heightp,int32_t nHeight,uint256 has fprintf(stderr,"[%s] nHeight.%d == NOTARIZED_HEIGHT.%d, diff hash\n",ASSETCHAINS_SYMBOL,nHeight,notarized_height); return(-1); } - } else fprintf(stderr,"[%s] unexpected error notary_hash %s ht.%d at ht.%d\n",ASSETCHAINS_SYMBOL,notarized_hash.ToString().c_str(),notarized_height,notary->nHeight); + } //else fprintf(stderr,"[%s] unexpected error notary_hash %s ht.%d at ht.%d\n",ASSETCHAINS_SYMBOL,notarized_hash.ToString().c_str(),notarized_height,notary->nHeight); } //else if ( notarized_height > 0 && notarized_height != 73880 && notarized_height >= 170000 ) // fprintf(stderr,"[%s] couldnt find notarized.(%s %d) ht.%d\n",ASSETCHAINS_SYMBOL,notarized_hash.ToString().c_str(),notarized_height,pindex->nHeight); From cf53fd7c3d86c91bd9a48de8c5537757e042b1f9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 16:25:27 +0300 Subject: [PATCH 408/507] Test --- src/komodo_globals.h | 1 + src/komodo_utils.h | 21 +++++++++++++++++++++ src/main.cpp | 20 ++------------------ src/wallet/wallet.cpp | 14 ++++++++++++-- 4 files changed, 36 insertions(+), 20 deletions(-) diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 865f377e2..c884bbc5e 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -15,6 +15,7 @@ #include "komodo_defs.h" +void komodo_prefetch(FILE *fp); uint32_t komodo_heightstamp(int32_t height); void 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,int32_t kheight,uint32_t ktime,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout,uint256 MoM,int32_t MoMdepth); void komodo_init(int32_t height); diff --git a/src/komodo_utils.h b/src/komodo_utils.h index 417ecfb52..5e3a04e9a 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1696,3 +1696,24 @@ struct komodo_state *komodo_stateptr(char *symbol,char *dest) komodo_nameset(symbol,dest,ASSETCHAINS_SYMBOL); return(komodo_stateptrget(symbol)); } + +void komodo_prefetch(FILE *fp) +{ + long fsize,fpos; int32_t incr = 16*1024*1024; + fpos = ftell(fp); + fseek(fp,0,SEEK_END); + fsize = ftell(fp); + if ( fsize > incr ) + { + char *ignore = (char *)malloc(incr); + if ( ignore != 0 ) + { + rewind(fp); + while ( fread(ignore,1,incr,fp) == incr ) // prefetch + fprintf(stderr,"."); + free(ignore); + } + } + fseek(fp,fpos,SEEK_SET); +} + diff --git a/src/main.cpp b/src/main.cpp index 4bb45e954..3aa54f402 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4310,10 +4310,9 @@ bool CheckDiskSpace(uint64_t nAdditionalBytes) return true; } - FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) { - static int32_t didinit[64]; long fsize,fpos; int32_t incr = 16*1024*1024; + static int32_t didinit[64]; if (pos.IsNull()) return NULL; boost::filesystem::path path = GetBlockPosFilename(pos, prefix); @@ -4327,22 +4326,7 @@ FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) } if ( pos.nFile < sizeof(didinit)/sizeof(*didinit) && didinit[pos.nFile] == 0 && strcmp(prefix,(char *)"blk") == 0 ) { - fpos = ftell(file); - fseek(file,0,SEEK_END); - fsize = ftell(file); - if ( fsize > incr ) - { - char *ignore = (char *)malloc(incr); - if ( ignore != 0 ) - { - rewind(file); - while ( fread(ignore,1,incr,file) == incr ) // prefetch - fprintf(stderr,"."); - free(ignore); - // fprintf(stderr,"blk.%d loaded %ld bytes set fpos.%ld loading.%d\n",(int)pos.nFile,(long)ftell(file),(long)fpos,KOMODO_LOADINGBLOCKS); - } - } - fseek(file,fpos,SEEK_SET); + komodo_prefetch(file); didinit[pos.nFile] = 1; } if (pos.nPos) { diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 5335e2525..02e82ba7b 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -3041,15 +3041,25 @@ CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarge } - +void komodo_prefetch(FILE *fp); DBErrors CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return DB_LOAD_OK; fFirstRunRet = false; - DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); fprintf(stderr,"loading wallet %s %u\n",strWalletFile.c_str(),(uint32_t)time(NULL)); + { + FILE *fp; + if ( (fp= fopen(strWalletFile.c_str(),"rb")) != 0 ) + { + komodo_prefetch(fp); + fclose(fp); + } + } + fprintf(stderr,"prefetched wallet %s %u\n",strWalletFile.c_str(),(uint32_t)time(NULL)); + DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); + fprintf(stderr,"loaded wallet %s %u\n",strWalletFile.c_str(),(uint32_t)time(NULL)); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) From e86c03cf0718067858ec9407c008914ea290b7df Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 16:34:07 +0300 Subject: [PATCH 409/507] -walletprefetch --- src/wallet/wallet.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 02e82ba7b..a1c7039cf 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -3048,8 +3048,9 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet) if (!fFileBacked) return DB_LOAD_OK; fFirstRunRet = false; - fprintf(stderr,"loading wallet %s %u\n",strWalletFile.c_str(),(uint32_t)time(NULL)); + if ( 0 ) // doesnt help { + fprintf(stderr,"loading wallet %s %u\n",strWalletFile.c_str(),(uint32_t)time(NULL)); FILE *fp; if ( (fp= fopen(strWalletFile.c_str(),"rb")) != 0 ) { @@ -3057,9 +3058,9 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet) fclose(fp); } } - fprintf(stderr,"prefetched wallet %s %u\n",strWalletFile.c_str(),(uint32_t)time(NULL)); + //fprintf(stderr,"prefetched wallet %s %u\n",strWalletFile.c_str(),(uint32_t)time(NULL)); DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); - fprintf(stderr,"loaded wallet %s %u\n",strWalletFile.c_str(),(uint32_t)time(NULL)); + //fprintf(stderr,"loaded wallet %s %u\n",strWalletFile.c_str(),(uint32_t)time(NULL)); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) From e8fa58ecb575b42290bd1f28b8384b3cc758119f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 16:43:03 +0300 Subject: [PATCH 410/507] Default JUMBLR_PAUSE.1 --- src/komodo_globals.h | 2 +- src/rpcmisc.cpp | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/komodo_globals.h b/src/komodo_globals.h index c884bbc5e..ff15c17c8 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -47,7 +47,7 @@ struct komodo_state KOMODO_STATES[34]; int COINBASE_MATURITY = _COINBASE_MATURITY;//100; int32_t IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAINS_SEED,KOMODO_ON_DEMAND,KOMODO_EXTERNAL_NOTARIES,KOMODO_PASSPORT_INITDONE,KOMODO_PAX,KOMODO_EXCHANGEWALLET,KOMODO_REWIND; -int32_t KOMODO_LASTMINED,prevKOMODO_LASTMINED,JUMBLR_PAUSE; +int32_t KOMODO_LASTMINED,prevKOMODO_LASTMINED,JUMBLR_PAUSE = 1; std::string NOTARY_PUBKEY,ASSETCHAINS_NOTARIES,ASSETCHAINS_OVERRIDE_PUBKEY; uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33]; diff --git a/src/rpcmisc.cpp b/src/rpcmisc.cpp index 20ea27f0a..aac0e178c 100644 --- a/src/rpcmisc.cpp +++ b/src/rpcmisc.cpp @@ -205,6 +205,7 @@ UniValue jumblr_deposit(const UniValue& params, bool fHelp) if ( (retval= Jumblr_depositaddradd((char *)addr.c_str())) >= 0 ) result.push_back(Pair("result", retval)); else result.push_back(Pair("error", retval)); + JUMBLR_PAUSE = 0; } else result.push_back(Pair("error", "invalid address")); return(result); } @@ -222,6 +223,7 @@ UniValue jumblr_secret(const UniValue& params, bool fHelp) retval = Jumblr_secretaddradd((char *)addr.c_str()); result.push_back(Pair("result", "success")); result.push_back(Pair("num", retval)); + JUMBLR_PAUSE = 0; } else result.push_back(Pair("error", "invalid address")); return(result); } @@ -1084,4 +1086,4 @@ UniValue getspentinfo(const UniValue& params, bool fHelp) obj.push_back(Pair("height", value.blockHeight)); return obj; -} \ No newline at end of file +} From 3b03fd34e86b1c3364b7d07ef1a734fe816c5940 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 18:08:57 +0300 Subject: [PATCH 411/507] Ccdata --- src/komodo_ccdata.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/komodo_ccdata.h b/src/komodo_ccdata.h index f5a4ada19..75eaffe48 100644 --- a/src/komodo_ccdata.h +++ b/src/komodo_ccdata.h @@ -204,6 +204,7 @@ void komodo_purge_ccdata(int32_t height) } } +// this is just a demo of ccdata processing to create example data for the MoMoM and allMoMs calls int32_t komodo_rwccdata(char *thischain,int32_t rwflag,struct komodo_ccdata *ccdata,struct komodo_ccdataMoMoM *MoMoMdata) { uint256 hash,zero; bits256 tmp; int32_t i,nonz; struct komodo_ccdata *ptr; struct notarized_checkpoint *np; From df03549da89c7f907ed64c093b350509e471b1e2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 20:27:16 +0300 Subject: [PATCH 412/507] +minerids rpc --- src/komodo_bitcoind.h | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index fd257cb0a..4bb4d3c2c 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -592,7 +592,6 @@ void komodo_disconnect(CBlockIndex *pindex,CBlock& block) } else printf("komodo_disconnect: ht.%d cant get komodo_state.(%s)\n",pindex->nHeight,ASSETCHAINS_SYMBOL); } - int32_t komodo_is_notarytx(const CTransaction& tx) { uint8_t *ptr; static uint8_t crypto777[33]; @@ -836,18 +835,31 @@ int32_t komodo_eligiblenotary(uint8_t pubkeys[66][33],int32_t *mids,uint32_t blo else return(0); } -int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) // deprecate +int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) { - /*int32_t i,n=0; - for (i=0; i Date: Tue, 17 Apr 2018 20:47:09 +0300 Subject: [PATCH 413/507] Add GPU miners --- src/komodo_bitcoind.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 4bb4d3c2c..9f5c80f9c 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -843,6 +843,7 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) { if ( height-i <= 0 ) continue; + minerids[nonz] = numnotaries; if ( (pindex= komodo_chainactive(height-width+i+1)) != 0 ) { if ( komodo_blockload(block,pindex) == 0 ) From 0d8dc237cde291084983075a6b3bfe2b33a704c6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 20:54:10 +0300 Subject: [PATCH 414/507] Test --- src/komodo_bitcoind.h | 3 ++- src/rpcblockchain.cpp | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 9f5c80f9c..b82be68a6 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -843,7 +843,6 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) { if ( height-i <= 0 ) continue; - minerids[nonz] = numnotaries; if ( (pindex= komodo_chainactive(height-width+i+1)) != 0 ) { if ( komodo_blockload(block,pindex) == 0 ) @@ -857,6 +856,8 @@ int32_t komodo_minerids(uint8_t *minerids,int32_t height,int32_t width) break; } } + if ( j == numnotaries ) + minerids[nonz++] = j; } else fprintf(stderr,"couldnt load block.%d\n",height); } } diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index 1ee7d377b..163d7ff18 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -1048,6 +1048,7 @@ UniValue minerids(const UniValue& params, bool fHelp) a.push_back(item); } ret.push_back(Pair("mined", a)); + ret.push_back(Pair("numnotaries", numnotaries)); } else ret.push_back(Pair("error", (char *)"couldnt extract minerids")); return ret; } From dbc800502f7514b0ea56f16df3c66983c16265d1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 21:14:35 +0300 Subject: [PATCH 415/507] Add netinfo fields --- src/rpcmisc.cpp | 26 ++++++++++++++++++++++++++ src/rpcrawtransaction.cpp | 1 + 2 files changed, 27 insertions(+) diff --git a/src/rpcmisc.cpp b/src/rpcmisc.cpp index aac0e178c..fdad05b50 100644 --- a/src/rpcmisc.cpp +++ b/src/rpcmisc.cpp @@ -53,6 +53,10 @@ extern int32_t KOMODO_LASTMINED,JUMBLR_PAUSE; extern char ASSETCHAINS_SYMBOL[]; int32_t notarizedtxid_height(char *dest,char *txidstr,int32_t *kmdnotarized_heightp); #define KOMODO_VERSION "0.1.1" +extern uint16_t ASSETCHAINS_PORT; +extern uint32_t ASSETCHAINS_CC; +extern uint32_t ASSETCHAINS_MAGIC; +extern uint64_t ASSETCHAINS_ENDSUBSIDY,ASSETCHAINS_REWARD,ASSETCHAINS_HALVING,ASSETCHAINS_DECAY,ASSETCHAINS_COMMISSION,ASSETCHAINS_STAKED,ASSETCHAINS_SUPPLY; UniValue getinfo(const UniValue& params, bool fHelp) { @@ -149,6 +153,28 @@ UniValue getinfo(const UniValue& params, bool fHelp) obj.push_back(Pair("lastmined", KOMODO_LASTMINED)); } } + if ( ASSETCHAINS_CC != 0 ) + obj.push_back(Pair("CCid", ASSETCHAINS_CC)); + if ( ASSETCHAINS_SYMBOL[0] != 0 ) + { + obj.push_back(Pair("name", ASSETCHAINS_SYMBOL)); + obj.push_back(Pair("port", ASSETCHAINS_PORT)); + obj.push_back(Pair("magic", ASSETCHAINS_MAGIC)); + if ( ASSETCHAINS_SUPPLY != 0 ) + obj.push_back(Pair("premine", ASSETCHAINS_SUPPLY)); + if ( ASSETCHAINS_REWARD != 0 ) + obj.push_back(Pair("reward", ASSETCHAINS_REWARD)); + if ( ASSETCHAINS_HALVING != 0 ) + obj.push_back(Pair("halving", ASSETCHAINS_HALVING)); + if ( ASSETCHAINS_DECAY != 0 ) + obj.push_back(Pair("decay", ASSETCHAINS_DECAY)); + if ( ASSETCHAINS_ENDSUBSIDY != 0 ) + obj.push_back(Pair("endsubsidy", ASSETCHAINS_ENDSUBSIDY)); + if ( ASSETCHAINS_COMMISSION != 0 ) + obj.push_back(Pair("commission", ASSETCHAINS_COMMISSION)); + if ( ASSETCHAINS_STAKED != 0 ) + obj.push_back(Pair("staked", ASSETCHAINS_STAKED)); + } return obj; } diff --git a/src/rpcrawtransaction.cpp b/src/rpcrawtransaction.cpp index d27a47649..8c88abe43 100644 --- a/src/rpcrawtransaction.cpp +++ b/src/rpcrawtransaction.cpp @@ -174,6 +174,7 @@ void TxToJSONExpanded(const CTransaction& tx, const uint256 hashBlock, UniValue& out.push_back(Pair("interest", ValueFromAmount(interest))); } out.push_back(Pair("valueZat", txout.nValue)); + out.push_back(Pair("valueSat", txout.nValue)); // [+] Decker out.push_back(Pair("n", (int64_t)i)); UniValue o(UniValue::VOBJ); ScriptPubKeyToJSON(txout.scriptPubKey, o, true); From 91e76e0cece790f4a757b6b512f7c43d267bd45d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 21:16:38 +0300 Subject: [PATCH 416/507] Test --- src/rpcmisc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/rpcmisc.cpp b/src/rpcmisc.cpp index fdad05b50..6410c69f9 100644 --- a/src/rpcmisc.cpp +++ b/src/rpcmisc.cpp @@ -154,12 +154,12 @@ UniValue getinfo(const UniValue& params, bool fHelp) } } if ( ASSETCHAINS_CC != 0 ) - obj.push_back(Pair("CCid", ASSETCHAINS_CC)); + obj.push_back(Pair("CCid", (int)ASSETCHAINS_CC)); if ( ASSETCHAINS_SYMBOL[0] != 0 ) { obj.push_back(Pair("name", ASSETCHAINS_SYMBOL)); obj.push_back(Pair("port", ASSETCHAINS_PORT)); - obj.push_back(Pair("magic", ASSETCHAINS_MAGIC)); + obj.push_back(Pair("magic", (int)ASSETCHAINS_MAGIC)); if ( ASSETCHAINS_SUPPLY != 0 ) obj.push_back(Pair("premine", ASSETCHAINS_SUPPLY)); if ( ASSETCHAINS_REWARD != 0 ) From 6a1216c1a139ed66e2f2559e5df135843b5181c1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 21:19:11 +0300 Subject: [PATCH 417/507] Test --- src/rpcserver.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/rpcserver.cpp b/src/rpcserver.cpp index 454953d63..8a63fb4e8 100644 --- a/src/rpcserver.cpp +++ b/src/rpcserver.cpp @@ -238,6 +238,7 @@ UniValue help(const UniValue& params, bool fHelp) return tableRPC.help(strCommand); } +extern char ASSETCHAINS_SYMBOL[]; UniValue stop(const UniValue& params, bool fHelp) { @@ -248,7 +249,7 @@ UniValue stop(const UniValue& params, bool fHelp) "\nStop Komodo server."); // Shutdown will take long enough that the response should get back StartShutdown(); - return "Komodo server stopping"; + return ASSETCHAINS_SYMBOL + " Komodo server stopping"; } /** From 0ce6dd741f9de7d335c33f40a1669382b856e857 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 21:20:50 +0300 Subject: [PATCH 418/507] Test --- src/rpcserver.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rpcserver.cpp b/src/rpcserver.cpp index 8a63fb4e8..3340a4168 100644 --- a/src/rpcserver.cpp +++ b/src/rpcserver.cpp @@ -249,7 +249,7 @@ UniValue stop(const UniValue& params, bool fHelp) "\nStop Komodo server."); // Shutdown will take long enough that the response should get back StartShutdown(); - return ASSETCHAINS_SYMBOL + " Komodo server stopping"; + return ASSETCHAINS_SYMBOL + (char *)" Komodo server stopping"; } /** From ebc4965c1866204ba8bc2c4350680f37fc0ef99c Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 21:22:11 +0300 Subject: [PATCH 419/507] Test --- src/rpcserver.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/rpcserver.cpp b/src/rpcserver.cpp index 3340a4168..55dcabbb5 100644 --- a/src/rpcserver.cpp +++ b/src/rpcserver.cpp @@ -242,6 +242,7 @@ extern char ASSETCHAINS_SYMBOL[]; UniValue stop(const UniValue& params, bool fHelp) { + char buf[64]; // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw runtime_error( @@ -249,7 +250,8 @@ UniValue stop(const UniValue& params, bool fHelp) "\nStop Komodo server."); // Shutdown will take long enough that the response should get back StartShutdown(); - return ASSETCHAINS_SYMBOL + (char *)" Komodo server stopping"; + sprintf(buf,"%s Komodo server stopping",ASSETCHAINS_SYMBOL); + return buf; } /** From 20f6a7273f210f0d15d86c1acba80cc08f624f48 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 21:24:14 +0300 Subject: [PATCH 420/507] Default JUMBLR paused --- src/komodo_globals.h | 2 +- src/rpcmisc.cpp | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 31ba6c32c..dec9a6603 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -46,7 +46,7 @@ struct komodo_state KOMODO_STATES[34]; int COINBASE_MATURITY = _COINBASE_MATURITY;//100; int32_t IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAINS_SEED,KOMODO_ON_DEMAND,KOMODO_EXTERNAL_NOTARIES,KOMODO_PASSPORT_INITDONE,KOMODO_PAX,KOMODO_EXCHANGEWALLET,KOMODO_REWIND; -int32_t KOMODO_LASTMINED,prevKOMODO_LASTMINED,JUMBLR_PAUSE; +int32_t KOMODO_LASTMINED,prevKOMODO_LASTMINED,JUMBLR_PAUSE = 1; std::string NOTARY_PUBKEY,ASSETCHAINS_NOTARIES,ASSETCHAINS_OVERRIDE_PUBKEY; uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33]; diff --git a/src/rpcmisc.cpp b/src/rpcmisc.cpp index 20ea27f0a..7c8d7bb85 100644 --- a/src/rpcmisc.cpp +++ b/src/rpcmisc.cpp @@ -203,7 +203,10 @@ UniValue jumblr_deposit(const UniValue& params, bool fHelp) { string addr = params[0].get_str(); if ( (retval= Jumblr_depositaddradd((char *)addr.c_str())) >= 0 ) + { result.push_back(Pair("result", retval)); + JUMBLR_PAUSE = 0; + } else result.push_back(Pair("error", retval)); } else result.push_back(Pair("error", "invalid address")); return(result); @@ -222,6 +225,7 @@ UniValue jumblr_secret(const UniValue& params, bool fHelp) retval = Jumblr_secretaddradd((char *)addr.c_str()); result.push_back(Pair("result", "success")); result.push_back(Pair("num", retval)); + JUMBLR_PAUSE = 0; } else result.push_back(Pair("error", "invalid address")); return(result); } @@ -1084,4 +1088,4 @@ UniValue getspentinfo(const UniValue& params, bool fHelp) obj.push_back(Pair("height", value.blockHeight)); return obj; -} \ No newline at end of file +} From 958190997fd08c39d7dc25a702f200c008bf98e4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 21:25:10 +0300 Subject: [PATCH 421/507] Default jumble paused --- src/komodo_globals.h | 2 +- src/rpcmisc.cpp | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/komodo_globals.h b/src/komodo_globals.h index aa6546454..8a2f87918 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -45,7 +45,7 @@ struct komodo_state KOMODO_STATES[34]; int COINBASE_MATURITY = _COINBASE_MATURITY;//100; int32_t IS_KOMODO_NOTARY,USE_EXTERNAL_PUBKEY,KOMODO_CHOSEN_ONE,ASSETCHAINS_SEED,KOMODO_ON_DEMAND,KOMODO_EXTERNAL_NOTARIES,KOMODO_PASSPORT_INITDONE,KOMODO_PAX,KOMODO_EXCHANGEWALLET,KOMODO_REWIND; -int32_t KOMODO_LASTMINED,prevKOMODO_LASTMINED,JUMBLR_PAUSE,ASSETCHAINS_CC; +int32_t KOMODO_LASTMINED,prevKOMODO_LASTMINED,JUMBLR_PAUSE=1,ASSETCHAINS_CC; std::string NOTARY_PUBKEY,ASSETCHAINS_NOTARIES,ASSETCHAINS_OVERRIDE_PUBKEY; uint8_t NOTARY_PUBKEY33[33],ASSETCHAINS_OVERRIDE_PUBKEY33[33]; diff --git a/src/rpcmisc.cpp b/src/rpcmisc.cpp index 988c5d6c3..cf7967cb7 100644 --- a/src/rpcmisc.cpp +++ b/src/rpcmisc.cpp @@ -203,7 +203,10 @@ UniValue jumblr_deposit(const UniValue& params, bool fHelp) { string addr = params[0].get_str(); if ( (retval= Jumblr_depositaddradd((char *)addr.c_str())) >= 0 ) + { result.push_back(Pair("result", retval)); + JUMBLR_PAUSE = 0; + } else result.push_back(Pair("error", retval)); } else result.push_back(Pair("error", "invalid address")); return(result); @@ -222,6 +225,7 @@ UniValue jumblr_secret(const UniValue& params, bool fHelp) retval = Jumblr_secretaddradd((char *)addr.c_str()); result.push_back(Pair("result", "success")); result.push_back(Pair("num", retval)); + JUMBLR_PAUSE = 0; } else result.push_back(Pair("error", "invalid address")); return(result); } From e21c70e9a45a5354771c0615f7df173d979bbb3e Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 21:26:08 +0300 Subject: [PATCH 422/507] Test --- src/rpcmisc.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/rpcmisc.cpp b/src/rpcmisc.cpp index 6410c69f9..cab292571 100644 --- a/src/rpcmisc.cpp +++ b/src/rpcmisc.cpp @@ -229,9 +229,11 @@ UniValue jumblr_deposit(const UniValue& params, bool fHelp) { string addr = params[0].get_str(); if ( (retval= Jumblr_depositaddradd((char *)addr.c_str())) >= 0 ) + { result.push_back(Pair("result", retval)); + JUMBLR_PAUSE = 0; + } else result.push_back(Pair("error", retval)); - JUMBLR_PAUSE = 0; } else result.push_back(Pair("error", "invalid address")); return(result); } From a95bf7f719120485edfb5f3c0b7e979eff959533 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 21:28:21 +0300 Subject: [PATCH 423/507] Test --- src/komodo_gateway.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 60d855d8d..349ba1d88 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -1972,7 +1972,7 @@ void komodo_passport_iteration() if ( expired == 0 && KOMODO_PASSPORT_INITDONE == 0 ) { KOMODO_PASSPORT_INITDONE = 1; - printf("READY for RPC calls at %u! done PASSPORT %s refid.%d\n",(uint32_t)time(NULL),ASSETCHAINS_SYMBOL,refid); + printf("READY for %s RPC calls at %u! done PASSPORT %s refid.%d\n",ASSETCHAINS_SYMBOL(uint32_t)time(NULL),ASSETCHAINS_SYMBOL,refid); } } From 9bcc632131b0492346abcfecc80be8660431a008 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 17 Apr 2018 21:31:33 +0300 Subject: [PATCH 424/507] , --- src/komodo_gateway.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 349ba1d88..f6ad28c59 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -1972,7 +1972,7 @@ void komodo_passport_iteration() if ( expired == 0 && KOMODO_PASSPORT_INITDONE == 0 ) { KOMODO_PASSPORT_INITDONE = 1; - printf("READY for %s RPC calls at %u! done PASSPORT %s refid.%d\n",ASSETCHAINS_SYMBOL(uint32_t)time(NULL),ASSETCHAINS_SYMBOL,refid); + printf("READY for %s RPC calls at %u! done PASSPORT %s refid.%d\n",ASSETCHAINS_SYMBOL,(uint32_t)time(NULL),ASSETCHAINS_SYMBOL,refid); } } From 3a443f33783403426de613c24702c6eeb22a39bb Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 14:45:08 +0300 Subject: [PATCH 425/507] -print --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index 790a84860..c952f91cc 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -489,7 +489,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) pblock->nTime = pindexPrev->nTime + 60; while ( pblock->GetBlockTime() > GetAdjustedTime() + 60 ) sleep(1); - fprintf(stderr,"block.nTime %u vs prev.%u, gettime.%u vs adjusted.%u\n",(uint32_t)pblock->nTime,(uint32_t)(pindexPrev->nTime + 60),(uint32_t)pblock->GetBlockTime(),(uint32_t)(GetAdjustedTime() + 60)); + //fprintf(stderr,"block.nTime %u vs prev.%u, gettime.%u vs adjusted.%u\n",(uint32_t)pblock->nTime,(uint32_t)(pindexPrev->nTime + 60),(uint32_t)pblock->GetBlockTime(),(uint32_t)(GetAdjustedTime() + 60)); } pblock->nSolution.clear(); pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); From 869d40e1f38745e5e88796cb49fbab324fc9f9c6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 14:45:38 +0300 Subject: [PATCH 426/507] -print --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index 790a84860..c952f91cc 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -489,7 +489,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) pblock->nTime = pindexPrev->nTime + 60; while ( pblock->GetBlockTime() > GetAdjustedTime() + 60 ) sleep(1); - fprintf(stderr,"block.nTime %u vs prev.%u, gettime.%u vs adjusted.%u\n",(uint32_t)pblock->nTime,(uint32_t)(pindexPrev->nTime + 60),(uint32_t)pblock->GetBlockTime(),(uint32_t)(GetAdjustedTime() + 60)); + //fprintf(stderr,"block.nTime %u vs prev.%u, gettime.%u vs adjusted.%u\n",(uint32_t)pblock->nTime,(uint32_t)(pindexPrev->nTime + 60),(uint32_t)pblock->GetBlockTime(),(uint32_t)(GetAdjustedTime() + 60)); } pblock->nSolution.clear(); pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(pblock->vtx[0]); From 16d589c27b5d5fd8d5855b3fd6d6d1abc4d4497f Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 19:18:20 +0300 Subject: [PATCH 427/507] Fix --- src/komodo.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 11e2194bb..46a2f39f1 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -350,7 +350,7 @@ int32_t komodo_parsestatefiledata(struct komodo_state *sp,uint8_t *filedata,long return(-1); } -void 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,int32_t KMDheight,uint32_t KMDtimestamp,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout)//,uint256 MoM,int32_t MoMdepth) +void 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,int32_t KMDheight,uint32_t KMDtimestamp,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout,uint256 MoM,int32_t MoMdepth) { static FILE *fp; static int32_t errs,didinit; static uint256 zero; struct komodo_state *sp; char fname[512],symbol[KOMODO_ASSETCHAIN_MAXLEN],dest[KOMODO_ASSETCHAIN_MAXLEN]; int32_t retval,ht,func; uint8_t num,pubkeys[64][33]; From ef7159cff073c6c9159253dcd86543939c410bcb Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 19:19:55 +0300 Subject: [PATCH 428/507] Fix --- src/rpcblockchain.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/rpcblockchain.cpp b/src/rpcblockchain.cpp index ea92c6a1c..163d7ff18 100644 --- a/src/rpcblockchain.cpp +++ b/src/rpcblockchain.cpp @@ -994,7 +994,6 @@ UniValue txMoMproof(const UniValue& params, bool fHelp) ssProof << MoMProof(nIndex, branch, notarisationHash); return HexStr(ssProof.begin(), ssProof.end()); } -*/ UniValue minerids(const UniValue& params, bool fHelp) { From 093f2730c80c03bec9c9396be50e00a6083b9aa3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 19:22:51 +0300 Subject: [PATCH 429/507] Fix --- src/bitcoin-cli.cpp | 2 +- src/komodo.h | 8 ++++---- src/komodo_globals.h | 2 +- src/komodo_notary.h | 2 +- src/komodo_pax.h | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/bitcoin-cli.cpp b/src/bitcoin-cli.cpp index 285d06c3f..178f0baed 100644 --- a/src/bitcoin-cli.cpp +++ b/src/bitcoin-cli.cpp @@ -76,7 +76,7 @@ public: #include "komodo_cJSON.c" #include "komodo_notary.h" -void 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,int32_t KMDheight,uint32_t KMDtimestamp,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout) +void 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,int32_t KMDheight,uint32_t KMDtimestamp,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout,uint256 MoM,int32_t MoMdepth) { } diff --git a/src/komodo.h b/src/komodo.h index 46a2f39f1..9212269eb 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -751,7 +751,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr } if ( *isratificationp == 0 && (signedmask != 0 || (scriptbuf[len] != 'X' && scriptbuf[len] != 'A')) ) // && scriptbuf[len] != 'I') - komodo_stateupdate(height,0,0,0,txhash,0,0,0,0,0,0,value,&scriptbuf[len],opretlen,j);//,zero,0); + komodo_stateupdate(height,0,0,0,txhash,0,0,0,0,0,0,value,&scriptbuf[len],opretlen,j,zero,0); } } return(notaryid); @@ -814,7 +814,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block) hwmheight = pindex->nHeight; } komodo_event_rewind(sp,symbol,pindex->nHeight); - komodo_stateupdate(pindex->nHeight,0,0,0,zero,0,0,0,0,-pindex->nHeight,pindex->nTime,0,0,0,0);//,zero,0); + komodo_stateupdate(pindex->nHeight,0,0,0,zero,0,0,0,0,-pindex->nHeight,pindex->nTime,0,0,0,0,zero,0); } komodo_currentheight_set(chainActive.Tip()->nHeight); if ( pindex != 0 ) @@ -946,7 +946,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block) if ( ((signedmask & 1) != 0 && numvalid >= KOMODO_MINRATIFY) || bitweight(signedmask) > (numnotaries/3) ) { memset(&txhash,0,sizeof(txhash)); - komodo_stateupdate(height,pubkeys,numvalid,0,txhash,0,0,0,0,0,0,0,0,0,0);//,zero,0); + komodo_stateupdate(height,pubkeys,numvalid,0,txhash,0,0,0,0,0,0,0,0,0,0,zero,0); printf("RATIFIED! >>>>>>>>>> new notaries.%d newheight.%d from height.%d\n",numvalid,(((height+KOMODO_ELECTION_GAP/2)/KOMODO_ELECTION_GAP)+1)*KOMODO_ELECTION_GAP,height); } else printf("signedmask.%llx numvalid.%d wt.%d numnotaries.%d\n",(long long)signedmask,numvalid,bitweight(signedmask),numnotaries); } @@ -955,7 +955,7 @@ void komodo_connectblock(CBlockIndex *pindex,CBlock& block) if ( NOTARY_PUBKEY33[0] != 0 && ASSETCHAINS_SYMBOL[0] == 0 ) printf("%s ht.%d\n",ASSETCHAINS_SYMBOL[0] == 0 ? "KMD" : ASSETCHAINS_SYMBOL,height); if ( pindex->nHeight == hwmheight ) - komodo_stateupdate(height,0,0,0,zero,0,0,0,0,height,(uint32_t)pindex->nTime,0,0,0,0);//,zero,0); + komodo_stateupdate(height,0,0,0,zero,0,0,0,0,height,(uint32_t)pindex->nTime,0,0,0,0,zero,0); } else fprintf(stderr,"komodo_connectblock: unexpected null pindex\n"); //KOMODO_INITDONE = (uint32_t)time(NULL); //fprintf(stderr,"%s end connect.%d\n",ASSETCHAINS_SYMBOL,pindex->nHeight); diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 3b4e62aa2..ca2145e0f 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -17,7 +17,7 @@ void komodo_prefetch(FILE *fp); uint32_t komodo_heightstamp(int32_t height); -void 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,int32_t kheight,uint32_t ktime,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout); +void 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,int32_t kheight,uint32_t ktime,uint64_t opretvalue,uint8_t *opretbuf,uint16_t opretlen,uint16_t vout,uint256 MoM,int32_t MoMdepth); void komodo_init(int32_t height); int32_t komodo_MoMdata(int32_t *notarized_htp,uint256 *MoMp,uint256 *kmdtxidp,int32_t nHeight,uint256 *MoMoMp,int32_t *MoMoMoffsetp,int32_t *MoMoMdepthp,int32_t *kmdstartip,int32_t *kmdendip); int32_t komodo_notarizeddata(int32_t nHeight,uint256 *notarized_hashp,uint256 *notarized_desttxidp); diff --git a/src/komodo_notary.h b/src/komodo_notary.h index 0ae7838ed..1bd726ce5 100644 --- a/src/komodo_notary.h +++ b/src/komodo_notary.h @@ -540,6 +540,6 @@ void komodo_init(int32_t height) //for (i=0; i Date: Wed, 18 Apr 2018 21:32:00 +0300 Subject: [PATCH 430/507] Exemption for PoS/PoW --- src/main.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 3aa54f402..3056ac11d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3773,6 +3773,8 @@ int32_t komodo_fast_checkPOW(CBlock *pblock,int32_t height) fprintf(stderr,"komodo_fast_checkPOW ht.%d CheckEquihashSolution failed\n",height); return(-1); } + if ( ASSETCHAINS_STAKED != 0 ) // add PoS/PoW checks + return(0); bnTarget.SetCompact(pblock->nBits,&fNegative,&fOverflow); if ( UintToArith256(pblock->GetHash()) > bnTarget ) { @@ -3791,7 +3793,7 @@ int32_t komodo_fast_checkPOW(CBlock *pblock,int32_t height) } } } - fprintf(stderr,"komodo_fast_checkPOW ht.%d notaryid.%d failed.%d\n",height,notaryid,failed); + //fprintf(stderr,"komodo_fast_checkPOW ht.%d notaryid.%d failed.%d\n",height,notaryid,failed); if ( failed != 0 && notaryid < 0 ) return(-1); else return(0); From cdb2a22f71d1c4d4891f76d8f1d6cb273b20a310 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 21:49:15 +0300 Subject: [PATCH 431/507] Test --- src/main.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 3056ac11d..ee5676c62 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2585,8 +2585,11 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin auto disabledVerifier = libzcash::ProofVerifier::Disabled(); // Check it again to verify JoinSplit proofs, and in case a previous version let a bad block in - if (!CheckBlock(pindex->nHeight,pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, fCheckPOW, !fJustCheck)) //!fJustCheck, !fJustCheck)) + if (!CheckBlock(pindex->nHeight,pindex,block, state, fExpensiveChecks ? verifier : disabledVerifier, fCheckPOW, !fJustCheck)) + { + fprintf(stderr,"checkblock failure in connectblock\n"); return false; + } // verify that the view's current state corresponds to the previous block uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash(); @@ -3810,7 +3813,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat // redundant with the call in AcceptBlockHeader. if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW)) { - //fprintf(stderr,"checkblockheader error PoW.%d\n",fCheckPOW); + fprintf(stderr,"checkblockheader error PoW.%d\n",fCheckPOW); return false; } if ( fCheckPOW && !CheckEquihashSolution(&block, Params()) ) @@ -4188,7 +4191,7 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex } if (!ConnectBlock(block, state, &indexDummy, viewNew, true,fCheckPOW)) { - //fprintf(stderr,"TestBlockValidity failure D\n"); + fprintf(stderr,"TestBlockValidity failure D\n"); return false; } assert(state.IsValid()); From 58a17a82a1b292eb6ca21e2a059bd08056ea9064 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 21:54:16 +0300 Subject: [PATCH 432/507] Test --- src/komodo_gateway.h | 2 +- src/main.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index f6ad28c59..539c86754 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -764,7 +764,7 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he if ( percPoS < goalperc ) // increase PoW diff -> lower bnTarget { bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); - if ( 1 ) + if ( 0 ) { for (i=31; i>=24; i--) fprintf(stderr,"%02x",((uint8_t *)&ave)[i]); diff --git a/src/main.cpp b/src/main.cpp index ee5676c62..c2387b39e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4181,12 +4181,12 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex } if (!CheckBlock(indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot)) { - //fprintf(stderr,"TestBlockValidity failure B\n"); + fprintf(stderr,"TestBlockValidity failure B\n"); return false; } if (!ContextualCheckBlock(block, state, pindexPrev)) { - //fprintf(stderr,"TestBlockValidity failure C\n"); + fprintf(stderr,"TestBlockValidity failure C\n"); return false; } if (!ConnectBlock(block, state, &indexDummy, viewNew, true,fCheckPOW)) From 1a26c3fa79ce15da5cb34395d0d66f889e6285b1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 21:56:58 +0300 Subject: [PATCH 433/507] Test --- src/komodo_gateway.h | 4 ++-- src/main.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 539c86754..5df44a2e5 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -896,12 +896,12 @@ int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtim hashval = UintToArith256(block.GetHash()); if ( hashval > bnTarget ) { - /*for (i=31; i>=0; i--) + for (i=31; i>=0; i--) fprintf(stderr,"%02x",((uint8_t *)&hashval)[i]); fprintf(stderr," > "); for (i=31; i>=0; i--) fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); - fprintf(stderr," ht.%d PoW diff violation PoSperc.%d vs goalperc.%d\n",height,PoSperc,(int32_t)ASSETCHAINS_STAKED);*/ + fprintf(stderr," ht.%d PoW diff violation PoSperc.%d vs goalperc.%d\n",height,PoSperc,(int32_t)ASSETCHAINS_STAKED); return(-1); } } diff --git a/src/main.cpp b/src/main.cpp index c2387b39e..071fc018f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3873,8 +3873,8 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat REJECT_INVALID, "bad-blk-sigops", true); if ( komodo_check_deposit(height,block,(pindex==0||pindex->pprev==0)?0:pindex->pprev->nTime) < 0 ) { - static uint32_t counter; - if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) + //static uint32_t counter; + //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) fprintf(stderr,"check deposit rejection\n"); return(false); } From 178273cf249e863f92b68b096464eeb5e288a934 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 22:02:25 +0300 Subject: [PATCH 434/507] Test --- src/miner.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index c952f91cc..1485f80a2 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -882,6 +882,7 @@ void static BitcoinMiner() } while (true) { + hashtarget = HASHTarget; /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt { fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); @@ -926,7 +927,10 @@ void static BitcoinMiner() CValidationState state; if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), true, false)) { - fprintf(stderr,"Invalid block mined, try again\n"); + int32_t z; uint256 h = pblock->GetHash(); + for (z=31; z>=0; z--) + fprintf(stderr,"%02x",((uint8_t *)&h)[z]); + fprintf(stderr," Invalid block mined, try again\n"); return(false); } if ( ASSETCHAINS_STAKED == 0 ) From f8ef6ca931583b4f44f715200f10eb70ff6bbe55 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 22:03:29 +0300 Subject: [PATCH 435/507] Test --- src/miner.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index 1485f80a2..244a4df29 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -882,7 +882,6 @@ void static BitcoinMiner() } while (true) { - hashtarget = HASHTarget; /*if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 && pblock->vtx[0].vout.size() == 1 && Mining_height > ASSETCHAINS_MINHEIGHT ) // skips when it shouldnt { fprintf(stderr,"skip generating %s on-demand block, no tx avail\n",ASSETCHAINS_SYMBOL); From a9550b923b2cd1885e566372cabfdcd2173482b5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 22:07:22 +0300 Subject: [PATCH 436/507] Test --- src/miner.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 244a4df29..652659aaf 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -913,20 +913,22 @@ void static BitcoinMiner() [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams] #endif (std::vector soln) { + int32_t z; arith_uint256 h = UintToArith256(pblock->GetHash()); // Write the solution to the hash and compute the result. LogPrint("pow", "- Checking solution against target\n"); pblock->nSolution = soln; solutionTargetChecks.increment(); - if ( UintToArith256(pblock->GetHash()) > HASHTarget ) + for (z=31; z>=0; z--) + fprintf(stderr,"%02x",((uint8_t *)&h)[z]); + if ( h > HASHTarget ) { - //if ( ASSETCHAINS_SYMBOL[0] != 0 ) - // fprintf(stderr," missed target\n"); + fprintf(stderr," missed target\n"); return false; } + fprintf(stderr," mined hash\n"); CValidationState state; if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), true, false)) { - int32_t z; uint256 h = pblock->GetHash(); for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&h)[z]); fprintf(stderr," Invalid block mined, try again\n"); From aea2d1aaddc1227d6894f7477ce3d57b00fcbdd9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 22:12:00 +0300 Subject: [PATCH 437/507] Test --- src/miner.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 652659aaf..7fd50e426 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -918,14 +918,20 @@ void static BitcoinMiner() LogPrint("pow", "- Checking solution against target\n"); pblock->nSolution = soln; solutionTargetChecks.increment(); - for (z=31; z>=0; z--) + for (z=31; z>=16; z--) fprintf(stderr,"%02x",((uint8_t *)&h)[z]); if ( h > HASHTarget ) { fprintf(stderr," missed target\n"); return false; } - fprintf(stderr," mined hash\n"); + fprintf(stderr," mined "); + for (z=31; z>=16; z--) + fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); + fprintf(stderr," hashTarget "); + for (z=31; z>=16; z--) + fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]); + fprintf(stderr," HASHTarget\n"); CValidationState state; if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), true, false)) { From 23fc88bbda29ec5d59e39ef445d4e3cd28c3ee06 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 22:18:40 +0300 Subject: [PATCH 438/507] Test --- src/miner.cpp | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 7fd50e426..b29c26dac 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -878,7 +878,7 @@ void static BitcoinMiner() HASHTarget = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]); - fprintf(stderr," PoW for staked coin\n"); + fprintf(stderr," PoW for staked coin %p\n",&HASHTarget); } while (true) { @@ -918,13 +918,8 @@ void static BitcoinMiner() LogPrint("pow", "- Checking solution against target\n"); pblock->nSolution = soln; solutionTargetChecks.increment(); - for (z=31; z>=16; z--) - fprintf(stderr,"%02x",((uint8_t *)&h)[z]); if ( h > HASHTarget ) - { - fprintf(stderr," missed target\n"); return false; - } fprintf(stderr," mined "); for (z=31; z>=16; z--) fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); @@ -1095,11 +1090,13 @@ void static BitcoinMiner() pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); pblock->nBits = savebits; if ( ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 ) - UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); - if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks) { - // Changing pblock->nTime can change work required on testnet: - HASHTarget.SetCompact(pblock->nBits); + UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); + if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks) + { + // Changing pblock->nTime can change work required on testnet: + HASHTarget.SetCompact(pblock->nBits); + } } } } From 919fa982ea3b723e1823bf24fde1c3558d28007d Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 22:19:31 +0300 Subject: [PATCH 439/507] Test --- src/main.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 071fc018f..6f43e59b6 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3875,7 +3875,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat { //static uint32_t counter; //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) - fprintf(stderr,"check deposit rejection\n"); + // fprintf(stderr,"check deposit rejection\n"); return(false); } return true; @@ -4176,22 +4176,22 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex // NOTE: CheckBlockHeader is called by CheckBlock if (!ContextualCheckBlockHeader(block, state, pindexPrev)) { - fprintf(stderr,"TestBlockValidity failure A\n"); + //fprintf(stderr,"TestBlockValidity failure A\n"); return false; } if (!CheckBlock(indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot)) { - fprintf(stderr,"TestBlockValidity failure B\n"); + //fprintf(stderr,"TestBlockValidity failure B\n"); return false; } if (!ContextualCheckBlock(block, state, pindexPrev)) { - fprintf(stderr,"TestBlockValidity failure C\n"); + //fprintf(stderr,"TestBlockValidity failure C\n"); return false; } if (!ConnectBlock(block, state, &indexDummy, viewNew, true,fCheckPOW)) { - fprintf(stderr,"TestBlockValidity failure D\n"); + //fprintf(stderr,"TestBlockValidity failure D\n"); return false; } assert(state.IsValid()); From 3fdbd5bf82aaa55aa95de234ee95018075929c34 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 22:23:10 +0300 Subject: [PATCH 440/507] Test --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index b29c26dac..177df1fb7 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1089,7 +1089,7 @@ void static BitcoinMiner() // Update nNonce and nTime pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); pblock->nBits = savebits; - if ( ASSETCHAINS_STAKED == 0 || NOTARY_PUBKEY33[0] == 0 ) + if ( ASSETCHAINS_STAKED == 0 && NOTARY_PUBKEY33[0] == 0 ) { UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks) From 98a5a298ed98b43c72dbbea7c9df52a8762ea7e9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 22:35:24 +0300 Subject: [PATCH 441/507] Test --- src/miner.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index 177df1fb7..6a3451084 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -905,7 +905,9 @@ void static BitcoinMiner() // (x_1, x_2, ...) = A(I, V, n, k) LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString()); arith_uint256 hashTarget = HASHTarget; - //fprintf(stderr,"running solver\n"); + for (z=31; z>=0; z--) + fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); + fprintf(stderr," running solver\n"); std::function)> validBlock = #ifdef ENABLE_WALLET [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams] From 44b34dfba526cb5e0c85294a1d1b51ee2fb038ea Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 22:37:07 +0300 Subject: [PATCH 442/507] Test --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index 6a3451084..1a22a1626 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -905,7 +905,7 @@ void static BitcoinMiner() // (x_1, x_2, ...) = A(I, V, n, k) LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString()); arith_uint256 hashTarget = HASHTarget; - for (z=31; z>=0; z--) + int32_t z; for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); fprintf(stderr," running solver\n"); std::function)> validBlock = From 02c30aac1ea9cc15e368d0ec41ac4eb235c6989c Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 22:39:53 +0300 Subject: [PATCH 443/507] Test --- src/miner.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/miner.cpp b/src/miner.cpp index 1a22a1626..9a3757fe3 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -922,6 +922,8 @@ void static BitcoinMiner() solutionTargetChecks.increment(); if ( h > HASHTarget ) return false; + for (z=31; z>=16; z--) + fprintf(stderr,"%02x",((uint8_t *)&h)[z]); fprintf(stderr," mined "); for (z=31; z>=16; z--) fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); From 30eaf9e23d66813772b434d957cab7a8b917479c Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 22:42:21 +0300 Subject: [PATCH 444/507] Test --- src/main.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 6f43e59b6..071fc018f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3875,7 +3875,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat { //static uint32_t counter; //if ( counter++ < 100 && ASSETCHAINS_STAKED == 0 ) - // fprintf(stderr,"check deposit rejection\n"); + fprintf(stderr,"check deposit rejection\n"); return(false); } return true; @@ -4176,22 +4176,22 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex // NOTE: CheckBlockHeader is called by CheckBlock if (!ContextualCheckBlockHeader(block, state, pindexPrev)) { - //fprintf(stderr,"TestBlockValidity failure A\n"); + fprintf(stderr,"TestBlockValidity failure A\n"); return false; } if (!CheckBlock(indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot)) { - //fprintf(stderr,"TestBlockValidity failure B\n"); + fprintf(stderr,"TestBlockValidity failure B\n"); return false; } if (!ContextualCheckBlock(block, state, pindexPrev)) { - //fprintf(stderr,"TestBlockValidity failure C\n"); + fprintf(stderr,"TestBlockValidity failure C\n"); return false; } if (!ConnectBlock(block, state, &indexDummy, viewNew, true,fCheckPOW)) { - //fprintf(stderr,"TestBlockValidity failure D\n"); + fprintf(stderr,"TestBlockValidity failure D\n"); return false; } assert(state.IsValid()); From 6cbd97e3e90bd0c4cbe96b828bca0f84fa707641 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 18 Apr 2018 22:47:50 +0300 Subject: [PATCH 445/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 6fb357ac6..09e5a4beb 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -192,7 +192,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int return true; if ( ASSETCHAINS_SYMBOL[0] != 0 || height > 792000 ) { - if ( 0 && height > 792000 ) + //if ( 0 && height > 792000 ) { for (i=31; i>=0; i--) printf("%02x",((uint8_t *)&hash)[i]); From 14b5fdf828aef5ef8423947c50c0d713d0cc98d3 Mon Sep 17 00:00:00 2001 From: ca333 Date: Wed, 18 Apr 2018 22:22:31 +0200 Subject: [PATCH 446/507] fix gtest/gmock OSX related path-fix in makefile --- depends/packages/googletest.mk | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/depends/packages/googletest.mk b/depends/packages/googletest.mk index b9fa3e7e8..1275593f5 100644 --- a/depends/packages/googletest.mk +++ b/depends/packages/googletest.mk @@ -14,7 +14,8 @@ endif ifeq ($(build_os),darwin) $(package)_install=ginstall define $(package)_build_cmds - $(MAKE) -C make gtest.a + $(MAKE) -C googlemock/make gmock.a && \ + $(MAKE) -C googletest/make gtest.a endef else $(package)_install=install From 1672d0d9132443351deb971ae65ea44a59841995 Mon Sep 17 00:00:00 2001 From: ca333 Date: Wed, 18 Apr 2018 22:31:58 +0200 Subject: [PATCH 447/507] fix proton.mk 0.17.0 not hosted under legacy URL. moved to apache archive. https://github.com/zcash/zcash/commit/2b0e6432fe6170f4dc0d9c0e2f9921d3b3b24880 --- depends/packages/proton.mk | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/depends/packages/proton.mk b/depends/packages/proton.mk index aa49f380f..39428f54b 100644 --- a/depends/packages/proton.mk +++ b/depends/packages/proton.mk @@ -1,6 +1,6 @@ package=proton $(package)_version=0.17.0 -$(package)_download_path=http://apache.cs.utah.edu/qpid/proton/$($(package)_version) +$(package)_download_path=https://archive.apache.org/dist/qpid/proton/$($(package)_version) $(package)_file_name=qpid-proton-$($(package)_version).tar.gz $(package)_sha256_hash=6ffd26d3d0e495bfdb5d9fefc5349954e6105ea18cc4bb191161d27742c5a01a $(package)_patches=minimal-build.patch @@ -21,4 +21,3 @@ endef define $(package)_stage_cmds cd build; $(MAKE) VERBOSE=1 DESTDIR=$($(package)_staging_prefix_dir) install endef - From 069ee2d327364557821c68ac06ce9221c463e937 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 19 Apr 2018 03:20:54 +0200 Subject: [PATCH 448/507] update libsodium OSX fallback to 1.0.11 due to missing atoll/atoi compiler support --- depends/packages/libsodium.mk | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/depends/packages/libsodium.mk b/depends/packages/libsodium.mk index 91e6f27b7..efa5d90de 100644 --- a/depends/packages/libsodium.mk +++ b/depends/packages/libsodium.mk @@ -1,17 +1,20 @@ +ifeq ($(build_os),darwin) +package=libsodium +$(package)_version=1.0.11 +$(package)_download_path=https://supernetorg.bintray.com/misc +$(package)_file_name=libsodium-1.0.11.tar.gz +$(package)_sha256_hash=a14549db3c49f6ae2170cbbf4664bd48ace50681045e8dbea7c8d9fb96f9c765 +$(package)_dependencies= +$(package)_config_opts= +else package=libsodium -#<<<<<<< HEAD -#$(package)_version=1.0.11 -#$(package)_download_path=https://supernetorg.bintray.com/misc -#$(package)_file_name=libsodium-1.0.11.tar.gz -#$(package)_sha256_hash=a14549db3c49f6ae2170cbbf4664bd48ace50681045e8dbea7c8d9fb96f9c765 -#======= $(package)_version=1.0.15 $(package)_download_path=https://download.libsodium.org/libsodium/releases/ $(package)_file_name=$(package)-$($(package)_version).tar.gz $(package)_sha256_hash=fb6a9e879a2f674592e4328c5d9f79f082405ee4bb05cb6e679b90afe9e178f4 -#>>>>>>> zcash/master $(package)_dependencies= $(package)_config_opts= +endif define $(package)_preprocess_cmds cd $($(package)_build_subdir); ./autogen.sh From f543a1cae00f6ad0e31f3232562c726285e33d99 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 19 Apr 2018 03:25:45 +0200 Subject: [PATCH 449/507] update rust add rust WIN --- depends/packages/rust.mk | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/depends/packages/rust.mk b/depends/packages/rust.mk index eb28c76d1..2e3f0b204 100644 --- a/depends/packages/rust.mk +++ b/depends/packages/rust.mk @@ -1,23 +1,16 @@ package=rust $(package)_version=1.16.0 $(package)_download_path=https://static.rust-lang.org/dist -#<<<<<<< HEAD -#ifeq ($(build_os),darwin) -#$(package)_file_name=rust-$($(package)_version)-x86_64-apple-darwin.tar.gz -#$(package)_sha256_hash=2d08259ee038d3a2c77a93f1a31fc59e7a1d6d1bbfcba3dba3c8213b2e5d1926 -#else ifeq ($(host_os),mingw32) -#$(package)_file_name=rust-$($(package)_version)-i686-unknown-linux-gnu.tar.gz -#$(package)_sha256_hash=b5859161ebb182d3b75fa14a5741e5de87b088146fb0ef4a30f3b2439c6179c5 -#else -#$(package)_file_name=rust-$($(package)_version)-x86_64-unknown-linux-gnu.tar.gz -#$(package)_sha256_hash=48621912c242753ba37cad5145df375eeba41c81079df46f93ffb4896542e8fd -#endif -#======= -$(package)_file_name_linux=rust-$($(package)_version)-x86_64-unknown-linux-gnu.tar.gz -$(package)_sha256_hash_linux=48621912c242753ba37cad5145df375eeba41c81079df46f93ffb4896542e8fd -$(package)_file_name_darwin=rust-$($(package)_version)-x86_64-apple-darwin.tar.gz -$(package)_sha256_hash_darwin=2d08259ee038d3a2c77a93f1a31fc59e7a1d6d1bbfcba3dba3c8213b2e5d1926 -#>>>>>>> zcash/master +ifeq ($(build_os),darwin) +$(package)_file_name=rust-$($(package)_version)-x86_64-apple-darwin.tar.gz +$(package)_sha256_hash=2d08259ee038d3a2c77a93f1a31fc59e7a1d6d1bbfcba3dba3c8213b2e5d1926 +else ifeq ($(host_os),mingw32) +$(package)_file_name=rust-$($(package)_version)-i686-unknown-linux-gnu.tar.gz +$(package)_sha256_hash=b5859161ebb182d3b75fa14a5741e5de87b088146fb0ef4a30f3b2439c6179c5 +else +$(package)_file_name=rust-$($(package)_version)-x86_64-unknown-linux-gnu.tar.gz +$(package)_sha256_hash=48621912c242753ba37cad5145df375eeba41c81079df46f93ffb4896542e8fd +endif define $(package)_stage_cmds ./install.sh --destdir=$($(package)_staging_dir) --prefix=$(host_prefix)/native --disable-ldconfig From 18443f692d9cba5c74a6f93b1bad205c9d22c6bb Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 13:59:36 +0300 Subject: [PATCH 450/507] Cleanup assetchains mining options --- src/komodo_bitcoind.h | 276 ++++++++++++++++++++++++++++++++++++++++++ src/komodo_gateway.h | 200 ------------------------------ src/main.cpp | 58 ++------- src/miner.cpp | 62 ++++------ src/pow.cpp | 3 - 5 files changed, 314 insertions(+), 285 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index b82be68a6..eb8747500 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1046,3 +1046,279 @@ int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_ return(0); } +/* + komodo_checkPOW (fast) is called early in the process and should only refer to data immediately available. it is a filter to prevent bad blocks from going into the local DB + + komodo_checkPOW (slow) is called right before connecting blocks so all prior blocks can be assumed to be there and all checks must pass + + commission must be in coinbase.vout[1] and must be >= 10000 sats + PoS stake must be without txfee and in the last tx in the block at vout[0] + PoW mining on PoS chain must solve a harder diff that adjusts, but never less than KOMODO_POWMINMULT + */ +#define KOMODO_POWMINMULT 16 + +uint64_t komodo_commission(const CBlock *pblock) +{ + int32_t i,j,n=0,txn_count; uint64_t commission,total = 0; + txn_count = pblock->vtx.size(); + for (i=0; ivtx[i].vout.size(); + for (j=0; jvtx[i].vout[j].nValue; + } + } + //fprintf(stderr,"txn.%d n.%d commission total %.8f -> %.8f\n",txn_count,n,dstr(total),dstr((total * ASSETCHAINS_COMMISSION) / COIN)); + commission = ((total * ASSETCHAINS_COMMISSION) / COIN); + if ( commission < 10000 ) + commission = 0; + return(commission); +} + +uint32_t komodo_stake(int32_t validateflag,arith_uint256 bnTarget,int32_t nHeight,uint256 txid,int32_t vout,uint32_t blocktime,uint32_t prevtime,char *destaddr) +{ + CBlockIndex *pindex; uint8_t hashbuf[128]; char address[64]; bits256 addrhash; arith_uint256 hashval; uint256 hash,pasthash; int64_t diff=0; int32_t segid,minage,i,iter=0; uint32_t txtime,winner = 0; uint64_t value,coinage,supply = ASSETCHAINS_SUPPLY + nHeight*ASSETCHAINS_REWARD/SATOSHIDEN; + txtime = komodo_txtime(&value,txid,vout,address); + if ( value == 0 || txtime == 0 ) + return(0); + if ( (minage= nHeight*3) > 6000 ) + minage = 6000; + if ( blocktime > txtime+minage && (pindex= komodo_chainactive(nHeight>200?nHeight-200:1)) != 0 ) + { + vcalc_sha256(0,(uint8_t *)&addrhash,(uint8_t *)address,(int32_t)strlen(address)); + segid = ((nHeight + addrhash.uints[0]) & 0x3f); + pasthash = pindex->GetBlockHash(); + memcpy(hashbuf,&pasthash,sizeof(pasthash)); + memcpy(&hashbuf[sizeof(pasthash)],&addrhash,sizeof(addrhash)); + vcalc_sha256(0,(uint8_t *)&hash,hashbuf,(int32_t)sizeof(uint256)*2); + //fprintf(stderr,"(%s) vs. (%s) %s %.8f txtime.%u\n",address,destaddr,hash.ToString().c_str(),dstr(value),txtime); + for (iter=0; iter<3600; iter++) + { + diff = (iter + blocktime - txtime - minage); + if ( diff > 3600*24 ) + break; + coinage = (value * diff) * ((diff >> 16) + 1); + hashval = arith_uint256(supply * 64) * (UintToArith256(hash) / arith_uint256(coinage+1)); + if ( hashval <= bnTarget ) + { + winner = 1; + if ( validateflag == 0 ) + { + blocktime += iter; + blocktime += segid * 2; + } + break; + } + if ( validateflag != 0 ) + { + for (i=31; i>=24; i--) + fprintf(stderr,"%02x",((uint8_t *)&hashval)[i]); + fprintf(stderr," vs target "); + for (i=31; i>=24; i--) + fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); + fprintf(stderr," segid.%d iter.%d winner.%d coinage.%llu %d ht.%d gap.%d %.8f diff.%d\n",segid,iter,winner,(long long)coinage,(int32_t)(blocktime - txtime),nHeight,(int32_t)(blocktime - prevtime),dstr(value),(int32_t)diff); + break; + } + } + //fprintf(stderr,"iterated until i.%d winner.%d\n",i,winner); + if ( 0 ) + { + for (i=31; i>=24; i--) + fprintf(stderr,"%02x",((uint8_t *)&hashval)[i]); + fprintf(stderr," vs "); + for (i=31; i>=24; i--) + fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); + fprintf(stderr," segid.%d iter.%d winner.%d coinage.%llu %d ht.%d t.%u %.8f diff.%d\n",segid,iter,winner,(long long)coinage,(int32_t)(blocktime - txtime),nHeight,blocktime,dstr(value),(int32_t)diff); + } + } + if ( nHeight < 2 ) + return(blocktime); + return(blocktime * winner); +} + +arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc) +{ + CBlockIndex *pindex; arith_uint256 bnTarget,hashval,sum,ave; bool fNegative,fOverflow; int32_t i,n,ht,percPoS,diff; + *percPoSp = percPoS = 0; + sum = arith_uint256(0); + ave = sum; + for (i=n=0; i<100; i++) + { + ht = height - 100 + i; + if ( (pindex= komodo_chainactive(ht)) != 0 ) + { + bnTarget.SetCompact(pindex->nBits,&fNegative,&fOverflow); + bnTarget = (bnTarget / arith_uint256(KOMODO_POWMINMULT)); + hashval = UintToArith256(pindex->GetBlockHash()); + if ( hashval <= bnTarget ) // PoW is never as easy as PoS/64, some PoS will be counted as PoW + { + sum += hashval; + n++; + } else percPoS++; + } + } + *percPoSp = percPoS; + target = (target / arith_uint256(KOMODO_POWMINMULT)); + if ( n > 0 ) + { + ave = (sum / arith_uint256(n)); + if ( ave > target ) + ave = target; + } else return(target); + if ( percPoS < goalperc ) // increase PoW diff -> lower bnTarget + { + bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); + if ( 0 ) + { + for (i=31; i>=24; i--) + fprintf(stderr,"%02x",((uint8_t *)&ave)[i]); + fprintf(stderr," increase diff -> "); + for (i=31; i>=24; i--) + fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); + fprintf(stderr," floor diff "); + for (i=31; i>=24; i--) + fprintf(stderr,"%02x",((uint8_t *)&target)[i]); + fprintf(stderr," ht.%d percPoS.%d vs goal.%d -> diff %d\n",height,percPoS,goalperc,goalperc - percPoS); + } + } + else if ( percPoS > goalperc ) // decrease PoW diff -> raise bnTarget + { + bnTarget = ((ave * arith_uint256(goalperc)) + (target * arith_uint256(percPoS))) / arith_uint256(percPoS + goalperc); + if ( 0 ) + { + for (i=31; i>=24; i--) + fprintf(stderr,"%02x",((uint8_t *)&ave)[i]); + fprintf(stderr," decrease diff -> "); + for (i=31; i>=24; i--) + fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); + fprintf(stderr," floor diff "); + for (i=31; i>=24; i--) + fprintf(stderr,"%02x",((uint8_t *)&target)[i]); + fprintf(stderr," ht.%d percPoS.%d vs goal.%d -> diff %d\n",height,percPoS,goalperc,goalperc - percPoS); + } + } + else bnTarget = ave; // recent ave is perfect + return(bnTarget); +} + +int32_t komodo_is_PoSblock(int32_t slowflag,CBlock *pblock,arith_uint256 bnTarget) +{ + CBlockIndex *previndex; char voutaddr[64],destaddr[64]; uint256 txid; uint32_t prevtime=0; int32_t vout,txn_count,isPoS = 0; + txn_count = pblock->vtx.size(); + if ( txn_count > 1 ) + { + if ( prevtime == 0 ) + { + if ( (previndex= mapBlockIndex[pblock->hashPrevBlock]) != 0 ) + prevtime = (uint32_t)previndex->nTime; + } + txid = pblock->vtx[txn_count-1].vin[0].prevout.hash; + vout = pblock->vtx[txn_count-1].vin[0].prevout.n; + if ( prevtime != 0 ) + { + eligible = komodo_stake(1,bnTarget,height,txid,vout,pblock->nTime,prevtime,(char *)""); + if ( eligible == 0 || eligible > pblock->nTime ) + { + fprintf(stderr,"komodo_is_PoSblock PoS failure ht.%d eligible.%u vs blocktime.%u, lag.%d -> check to see if it is PoW block\n",height,eligible,(uint32_t)block.nTime,(int32_t)(eligible - block.nTime)); + } else isPoS = 1; + } + else if ( slowflag == 0 )// maybe previous block is not seen yet, do the best approx + { + txtime = komodo_txtime(&value,txid,vout,destaddr); + if ( ExtractDestination(pblock->vtx[txn_count-1].vout[0].scriptPubKey,voutaddress) ) + { + strcpy(voutaddr,CBitcoinAddress(address).ToString().c_str()); + if ( strcmp(destaddr,voutaddr) == 0 && pblock->vtx[txn_count-1].vout[0].value == value ) + isPoS = 1; // close enough for a pre-filter + else fprintf(stderr,"komodo_is_PoSblock ht.%d (%s) != (%s) or %.8f != %.8f\n",height,destaddr,voutaddr,dstr(value),dstr(pblock->vtx[txn_count-1].vout[0].value)); + } else fprintf(stderr,"komodo_is_PoSblock ht.%d couldnt extract voutaddress\n",height); + } else return(-1); + } + return(isPoS); +} + +int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) +{ + arith_uint256 bnTarget,bhash; bool fNegative,fOverflow; uint8_t *script,pubkey33[33],pubkeys[64][33]; int32_t i,PoSperc,is_PoSblock=0,n,failed = 0,notaryid = -1; int64_t checktoshis,value; + if ( height == 0 ) + return(0); + if ( !CheckEquihashSolution(pblock, Params()) ) + { + fprintf(stderr,"komodo_checkPOW slowflag.%d ht.%d CheckEquihashSolution failed\n",slowflag,height); + return(-1); + } + bnTarget.SetCompact(pblock->nBits,&fNegative,&fOverflow); + bhash = UintToArith256(pblock->GetHash()); + komodo_block2pubkey33(pubkey33,pblock); + if ( slowflag != 0 ) + { + if ( !CheckProofOfWork(height,pubkey33,bhash,pblock->nBits,Params().GetConsensus(),pblock->nTime) ) + return state.DoS(1, error("CheckBlock: proof of work failed"),REJECT_INVALID, "high-hash"); + } + if ( bhash > bnTarget ) + { + failed = 1; + if ( ASSETCHAINS_SYMBOL[0] == 0 ) // for the fast case + { + if ( (n= komodo_notaries(pubkeys,height,pblock->nTime)) > 0 ) + { + for (i=0; i= 2 ) // must PoS or have at least 16x better PoW + { + if ( (is_PoSblock= komodo_is_PoSblock(slowflag,&block,bnTarget)) == 0 ) + { + if ( ASSETCHAINS_STAKED == 100 || height <= 100 ) // only PoS allowed! + return(-1); + else + { + if ( slowflag != 0 ) + bnTarget = komodo_PoWtarget(&PoSperc,bnTarget,height,ASSETCHAINS_STAKED); + else bnTarget = (bnTarget / arith_uint256(KOMODO_POWMINMULT)); // lower bound + if ( bhash > bnTarget ) + { + for (i=31; i>=16; i--) + fprintf(stderr,"%02x",((uint8_t *)&hashval)[i]); + fprintf(stderr," > "); + for (i=31; i>=16; i--) + fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); + fprintf(stderr," ht.%d PoW diff violation PoSperc.%d vs goalperc.%d\n",height,PoSperc,(int32_t)ASSETCHAINS_STAKED); + return(-1); + } + } + } else if ( isPoSblock < 0 ) + return(-1); + } + if ( failed == 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 ) + { + checktoshis = komodo_commission(pblock); + if ( checktoshis > 10000 && pblock->vtx[0].vout.size() != 2 ) + return(-1); + else if ( checktoshis != 0 ) + { + script = (uint8_t *)pblock->vtx[0].vout[1].scriptPubKey.data(); + if ( script[0] != 33 || script[34] != OP_CHECKSIG || memcmp(script+1,ASSETCHAINS_OVERRIDE_PUBKEY33,33) != 0 ) + return(-1); + if ( pblock->vtx[0].vout[1].nValue != checktoshis ) + { + fprintf(stderr,"checktoshis %.8f vs actual vout[1] %.8f\n",dstr(checktoshis),dstr(pblock->vtx[0].vout[1].nValue)); + return(-1); + } + } + } + //fprintf(stderr,"komodo_checkPOW slowflag.%d ht.%d notaryid.%d failed.%d\n",slowflag,height,notaryid,failed); + if ( failed != 0 && notaryid < 0 ) + return(-1); + else return(0); +} + diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 5df44a2e5..945f0b71b 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -650,153 +650,6 @@ int32_t komodo_bannedset(int32_t *indallvoutsp,uint256 *array,int32_t max) void komodo_passport_iteration(); -uint64_t komodo_commission(const CBlock &block) -{ - int32_t i,j,n=0,txn_count; uint64_t total = 0; - txn_count = block.vtx.size(); - for (i=0; i %.8f\n",txn_count,n,dstr(total),dstr((total * ASSETCHAINS_COMMISSION) / COIN)); - return((total * ASSETCHAINS_COMMISSION) / COIN); -} - -uint32_t komodo_stake(int32_t validateflag,arith_uint256 bnTarget,int32_t nHeight,uint256 txid,int32_t vout,uint32_t blocktime,uint32_t prevtime,char *destaddr) -{ - CBlockIndex *pindex; uint8_t hashbuf[128]; char address[64]; bits256 addrhash; arith_uint256 hashval; uint256 hash,pasthash; int64_t diff=0; int32_t segid,minage,i,iter=0; uint32_t txtime,winner = 0; uint64_t value,coinage,supply = ASSETCHAINS_SUPPLY + nHeight*ASSETCHAINS_REWARD/SATOSHIDEN; - txtime = komodo_txtime(&value,txid,vout,address); - if ( value == 0 || txtime == 0 ) - return(0); - if ( (minage= nHeight*3) > 6000 ) - minage = 6000; - if ( blocktime > txtime+minage && (pindex= komodo_chainactive(nHeight>200?nHeight-200:1)) != 0 ) - { - vcalc_sha256(0,(uint8_t *)&addrhash,(uint8_t *)address,(int32_t)strlen(address)); - segid = ((nHeight + addrhash.uints[0]) & 0x3f); - pasthash = pindex->GetBlockHash(); - memcpy(hashbuf,&pasthash,sizeof(pasthash)); - memcpy(&hashbuf[sizeof(pasthash)],&addrhash,sizeof(addrhash)); - vcalc_sha256(0,(uint8_t *)&hash,hashbuf,(int32_t)sizeof(uint256)*2); - //fprintf(stderr,"(%s) vs. (%s) %s %.8f txtime.%u\n",address,destaddr,hash.ToString().c_str(),dstr(value),txtime); - for (iter=0; iter<3600; iter++) - { - diff = (iter + blocktime - txtime - minage); - if ( diff > 3600*24 ) - break; - coinage = (value * diff) * ((diff >> 16) + 1); - hashval = arith_uint256(supply * 64) * (UintToArith256(hash) / arith_uint256(coinage+1)); - if ( hashval <= bnTarget ) - { - winner = 1; - if ( validateflag == 0 ) - { - blocktime += iter; - blocktime += segid * 2; - } - break; - } - if ( validateflag != 0 ) - { - for (i=31; i>=24; i--) - fprintf(stderr,"%02x",((uint8_t *)&hashval)[i]); - fprintf(stderr," vs target "); - for (i=31; i>=24; i--) - fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); - fprintf(stderr," segid.%d iter.%d winner.%d coinage.%llu %d ht.%d gap.%d %.8f diff.%d\n",segid,iter,winner,(long long)coinage,(int32_t)(blocktime - txtime),nHeight,(int32_t)(blocktime - prevtime),dstr(value),(int32_t)diff); - break; - } - } - //fprintf(stderr,"iterated until i.%d winner.%d\n",i,winner); - if ( 0 ) - { - for (i=31; i>=24; i--) - fprintf(stderr,"%02x",((uint8_t *)&hashval)[i]); - fprintf(stderr," vs "); - for (i=31; i>=24; i--) - fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); - fprintf(stderr," segid.%d iter.%d winner.%d coinage.%llu %d ht.%d t.%u %.8f diff.%d\n",segid,iter,winner,(long long)coinage,(int32_t)(blocktime - txtime),nHeight,blocktime,dstr(value),(int32_t)diff); - } - } - if ( nHeight < 2 ) - return(blocktime); - return(blocktime * winner); -} - -#define KOMODO_POWMINMULT 16 -arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc) -{ - CBlockIndex *pindex; arith_uint256 bnTarget,hashval,sum,ave; bool fNegative,fOverflow; int32_t i,n,ht,percPoS,diff; - *percPoSp = percPoS = 0; - sum = arith_uint256(0); - ave = sum; - for (i=n=0; i<100; i++) - { - ht = height - 100 + i; - if ( (pindex= komodo_chainactive(ht)) != 0 ) - { - bnTarget.SetCompact(pindex->nBits,&fNegative,&fOverflow); - bnTarget = (bnTarget / arith_uint256(KOMODO_POWMINMULT)); - hashval = UintToArith256(pindex->GetBlockHash()); - if ( hashval <= bnTarget ) // PoW is never as easy as PoS/64, some PoS will be counted as PoW - { - sum += hashval; - n++; - } else percPoS++; - } - } - *percPoSp = percPoS; - target = (target / arith_uint256(KOMODO_POWMINMULT)); - if ( n > 0 ) - { - ave = (sum / arith_uint256(n)); - if ( ave > target ) - ave = target; - } else return(target); - if ( percPoS < goalperc ) // increase PoW diff -> lower bnTarget - { - bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); - if ( 0 ) - { - for (i=31; i>=24; i--) - fprintf(stderr,"%02x",((uint8_t *)&ave)[i]); - fprintf(stderr," increase diff -> "); - for (i=31; i>=24; i--) - fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); - fprintf(stderr," floor diff "); - for (i=31; i>=24; i--) - fprintf(stderr,"%02x",((uint8_t *)&target)[i]); - fprintf(stderr," ht.%d percPoS.%d vs goal.%d -> diff %d\n",height,percPoS,goalperc,goalperc - percPoS); - } - } - else if ( percPoS > goalperc ) // decrease PoW diff -> raise bnTarget - { - bnTarget = ((ave * arith_uint256(goalperc)) + (target * arith_uint256(percPoS))) / arith_uint256(percPoS + goalperc); - if ( 1 ) - { - for (i=31; i>=24; i--) - fprintf(stderr,"%02x",((uint8_t *)&ave)[i]); - fprintf(stderr," decrease diff -> "); - for (i=31; i>=24; i--) - fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); - fprintf(stderr," floor diff "); - for (i=31; i>=24; i--) - fprintf(stderr,"%02x",((uint8_t *)&target)[i]); - fprintf(stderr," ht.%d percPoS.%d vs goal.%d -> diff %d\n",height,percPoS,goalperc,goalperc - percPoS); - } - } - else bnTarget = ave; // recent ave is perfect - return(bnTarget); -} - int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtime) // verify above block is valid pax pricing { static uint256 array[64]; static int32_t numbanned,indallvouts; @@ -867,59 +720,6 @@ int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtim } else { - if ( ASSETCHAINS_STAKED != 0 && height >= 2 ) - { - arith_uint256 bnTarget,hashval; int32_t PoSperc; bool fNegative,fOverflow; CBlockIndex *previndex; uint32_t eligible,isPoS = 0; - bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); - if ( txn_count > 1 ) - { - if ( prevtime == 0 ) - { - if ( (previndex= mapBlockIndex[block.hashPrevBlock]) != 0 ) - prevtime = (uint32_t)previndex->nTime; - } - eligible = komodo_stake(1,bnTarget,height,block.vtx[txn_count-1].vin[0].prevout.hash,block.vtx[txn_count-1].vin[0].prevout.n,block.nTime,prevtime,(char *)""); - if ( eligible == 0 || eligible > block.nTime ) - { - fprintf(stderr,"PoS failure ht.%d eligible.%u vs blocktime.%u, lag.%d -> check to see if it is PoW block\n",height,eligible,(uint32_t)block.nTime,(int32_t)(eligible - block.nTime)); - } else isPoS = 1; - } - if ( isPoS == 0 && height > 100 ) - { - if ( ASSETCHAINS_STAKED == 100 ) - { - fprintf(stderr,"ht.%d 100%% PoS after height 100 rule violated for -ac_staking=100\n",height); - return(-1); - } - // check PoW - bnTarget = komodo_PoWtarget(&PoSperc,bnTarget,height,ASSETCHAINS_STAKED); - hashval = UintToArith256(block.GetHash()); - if ( hashval > bnTarget ) - { - for (i=31; i>=0; i--) - fprintf(stderr,"%02x",((uint8_t *)&hashval)[i]); - fprintf(stderr," > "); - for (i=31; i>=0; i--) - fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); - fprintf(stderr," ht.%d PoW diff violation PoSperc.%d vs goalperc.%d\n",height,PoSperc,(int32_t)ASSETCHAINS_STAKED); - return(-1); - } - } - } - if ( ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && block.vtx[0].vout.size() > 1 ) - { - script = (uint8_t *)block.vtx[0].vout[1].scriptPubKey.data(); - if ( script[0] != 33 || script[34] != OP_CHECKSIG || memcmp(script+1,ASSETCHAINS_OVERRIDE_PUBKEY33,33) != 0 ) - return(-1); - if ( (checktoshis = komodo_commission(block)) != 0 ) - { - if ( block.vtx[0].vout[1].nValue != checktoshis ) - { - fprintf(stderr,"checktoshis %.8f vs actual vout[1] %.8f\n",dstr(checktoshis),dstr(block.vtx[0].vout[1].nValue)); - return(-1); - } else return(0); - } - } if ( overflow != 0 || total > 0 ) return(-1); } diff --git a/src/main.cpp b/src/main.cpp index 071fc018f..c50d3dcd2 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2801,14 +2801,14 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs-1), nTimeConnect * 0.000001); CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus()) + sum; - if ( ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && block.vtx[0].vout.size() > 1 ) + if ( ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 ) { uint64_t checktoshis; - if ( (checktoshis = komodo_commission(block)) != 0 ) + if ( (checktoshis= komodo_commission((CBlock *)&block)) != 0 ) { if ( block.vtx[0].vout.size() == 2 && block.vtx[0].vout[1].nValue == checktoshis ) blockReward += checktoshis; - else fprintf(stderr,"checktoshis %.8f vs actual vout[1] %.8f\n",dstr(checktoshis),dstr(block.vtx[0].vout[1].nValue)); + else fprintf(stderr,"checktoshis %.8f numvouts %d\n",dstr(checktoshis),block.vtx[0].vout.size()); } } if ( block.vtx[0].GetValueOut() > blockReward+1 ) @@ -3765,42 +3765,7 @@ bool CheckBlockHeader(int32_t height,CBlockIndex *pindex, const CBlockHeader& bl } int32_t komodo_check_deposit(int32_t height,const CBlock& block,uint32_t prevtime); - -int32_t komodo_fast_checkPOW(CBlock *pblock,int32_t height) -{ - arith_uint256 bnTarget; bool fNegative,fOverflow; uint8_t pubkey33[33],pubkeys[64][33]; int32_t i,n,failed = 0,notaryid = -1; - if ( height == 0 ) - return(0); - if ( !CheckEquihashSolution(pblock, Params()) ) - { - fprintf(stderr,"komodo_fast_checkPOW ht.%d CheckEquihashSolution failed\n",height); - return(-1); - } - if ( ASSETCHAINS_STAKED != 0 ) // add PoS/PoW checks - return(0); - bnTarget.SetCompact(pblock->nBits,&fNegative,&fOverflow); - if ( UintToArith256(pblock->GetHash()) > bnTarget ) - { - failed = 1; - if ( ASSETCHAINS_SYMBOL[0] == 0 ) - { - komodo_block2pubkey33(pubkey33,pblock); - if ( (n= komodo_notaries(pubkeys,height,pblock->nTime)) > 0 ) - { - for (i=0; iGetHash()); fRequested |= fForceProcessing; - if ( checked != 0 && komodo_fast_checkPOW(pblock,height) < 0 ) + if ( checked != 0 && komodo_checkPOW(0,pblock,height) < 0 ) checked = 0; if (!checked) { diff --git a/src/miner.cpp b/src/miner.cpp index 9a3757fe3..be2bb5e03 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -119,7 +119,7 @@ int32_t komodo_is_issuer(); int32_t komodo_gateway_deposits(CMutableTransaction *txNew,char *symbol,int32_t tokomodo); int32_t komodo_isrealtime(int32_t *kmdheightp); int32_t komodo_validate_interest(const CTransaction &tx,int32_t txheight,uint32_t nTime,int32_t dispflag); -uint64_t komodo_commission(const CBlock &block); +uint64_t komodo_commission(const CBlock *block); int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blocktimep,uint32_t *txtimep,uint256 *utxotxidp,int32_t *utxovoutp,uint64_t *utxovaluep,uint8_t *utxosig); CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) @@ -428,33 +428,9 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) // Add fees txNew.vout[0].nValue += nFees; txNew.vin[0].scriptSig = CScript() << nHeight << OP_0; - - /*if ( ASSETCHAINS_SYMBOL[0] == 0 ) - { - int32_t i,opretlen; uint8_t opret[256],*ptr; - if ( (nHeight % 60) == 0 || komodo_gateway_deposits(&txNew,(char *)"KMD",1) == 0 ) - { - if ( (opretlen= komodo_pax_opreturn((int32_t)nHeight,opret,sizeof(opret))) > 0 ) // have pricefeed - { - txNew.vout.resize(2); - txNew.vout[1].scriptPubKey.resize(opretlen); - ptr = (uint8_t *)txNew.vout[1].scriptPubKey.data(); - for (i=0; i 1 ) - fprintf(stderr,"%s txNew numvouts.%d\n",ASSETCHAINS_SYMBOL,(int32_t)txNew.vout.size()); - }*/ - + pblock->vtx[0] = txNew; - if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission(pblocktemplate->block)) != 0 ) + if ( ASSETCHAINS_SYMBOL[0] != 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 && (commission= komodo_commission((CBlock*)&pblocktemplate->block)) != 0 ) { int32_t i; uint8_t *ptr; txNew.vout.resize(2); @@ -669,7 +645,7 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he int32_t FOUND_BLOCK,KOMODO_MAYBEMINED; extern int32_t KOMODO_LASTMINED; int32_t roundrobin_delay; -arith_uint256 HASHTarget; +arith_uint256 HASHTarget,HASHTarget_POW; #ifdef ENABLE_WALLET void static BitcoinMiner(CWallet *pwallet) @@ -875,7 +851,7 @@ void static BitcoinMiner() sleep(60); continue; } - HASHTarget = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); + HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]); fprintf(stderr," PoW for staked coin %p\n",&HASHTarget); @@ -904,7 +880,10 @@ void static BitcoinMiner() crypto_generichash_blake2b_update(&curr_state,pblock->nNonce.begin(),pblock->nNonce.size()); // (x_1, x_2, ...) = A(I, V, n, k) LogPrint("pow", "Running Equihash solver \"%s\" with nNonce = %s\n",solver, pblock->nNonce.ToString()); - arith_uint256 hashTarget = HASHTarget; + arith_uint256 hashTarget; + if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 ) + hashTarget = HASHTarget_POW; + else hashTarget = HASHTarget; int32_t z; for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); fprintf(stderr," running solver\n"); @@ -920,17 +899,25 @@ void static BitcoinMiner() LogPrint("pow", "- Checking solution against target\n"); pblock->nSolution = soln; solutionTargetChecks.increment(); - if ( h > HASHTarget ) - return false; + if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 ) + { + if ( h > HASHTarget_POW ) + return false; + } + else + { + if ( h > HASHTarget ) + return false; + } for (z=31; z>=16; z--) fprintf(stderr,"%02x",((uint8_t *)&h)[z]); fprintf(stderr," mined "); for (z=31; z>=16; z--) - fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); + fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]); fprintf(stderr," hashTarget "); for (z=31; z>=16; z--) - fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]); - fprintf(stderr," HASHTarget\n"); + fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); + fprintf(stderr," POW\n"); CValidationState state; if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), true, false)) { @@ -958,7 +945,7 @@ void static BitcoinMiner() { if ( NOTARY_PUBKEY33[0] != 0 ) { - printf("need to wait %d seconds to submit\n",(int32_t)(pblock->nTime - GetAdjustedTime())); + printf("need to wait %d seconds to submit staked block\n",(int32_t)(pblock->nTime - GetAdjustedTime())); while ( GetAdjustedTime() < pblock->nTime ) sleep(1); } @@ -1093,13 +1080,14 @@ void static BitcoinMiner() // Update nNonce and nTime pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); pblock->nBits = savebits; - if ( ASSETCHAINS_STAKED == 0 && NOTARY_PUBKEY33[0] == 0 ) + if ( NOTARY_PUBKEY33[0] == 0 ) { UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks) { // Changing pblock->nTime can change work required on testnet: HASHTarget.SetCompact(pblock->nBits); + HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); } } } diff --git a/src/pow.cpp b/src/pow.cpp index 09e5a4beb..0cb6e89ce 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -206,9 +206,6 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int for (i=0; i<33; i++) printf("%02x",origpubkey33[i]); printf(" <- origpubkey\n"); - for (i=0; i<66; i++) - printf("%d ",mids[i]); - printf(" minerids from ht.%d\n",height); } return false; } From 3acce0422987e46307f857fed2022eb972a53dd1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 14:06:01 +0300 Subject: [PATCH 451/507] syntax --- src/komodo_bitcoind.h | 25 +++++++++++++------------ src/main.cpp | 2 +- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index eb8747500..696008623 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1063,7 +1063,7 @@ uint64_t komodo_commission(const CBlock *pblock) txn_count = pblock->vtx.size(); for (i=0; ivtx[i].vout.size(); + n = pblock->vtx[i].vout.size(); for (j=0; jvtx.size(); if ( txn_count > 1 ) { @@ -1230,10 +1230,10 @@ int32_t komodo_is_PoSblock(int32_t slowflag,CBlock *pblock,arith_uint256 bnTarge txtime = komodo_txtime(&value,txid,vout,destaddr); if ( ExtractDestination(pblock->vtx[txn_count-1].vout[0].scriptPubKey,voutaddress) ) { - strcpy(voutaddr,CBitcoinAddress(address).ToString().c_str()); - if ( strcmp(destaddr,voutaddr) == 0 && pblock->vtx[txn_count-1].vout[0].value == value ) + strcpy(voutaddr,CBitcoinAddress(destaddress).ToString().c_str()); + if ( strcmp(destaddr,voutaddr) == 0 && pblock->vtx[txn_count-1].vout[0].nValue == value ) isPoS = 1; // close enough for a pre-filter - else fprintf(stderr,"komodo_is_PoSblock ht.%d (%s) != (%s) or %.8f != %.8f\n",height,destaddr,voutaddr,dstr(value),dstr(pblock->vtx[txn_count-1].vout[0].value)); + else fprintf(stderr,"komodo_is_PoSblock ht.%d (%s) != (%s) or %.8f != %.8f\n",height,destaddr,voutaddr,dstr(value),dstr(pblock->vtx[txn_count-1].vout[0].nValue)); } else fprintf(stderr,"komodo_is_PoSblock ht.%d couldnt extract voutaddress\n",height); } else return(-1); } @@ -1242,7 +1242,7 @@ int32_t komodo_is_PoSblock(int32_t slowflag,CBlock *pblock,arith_uint256 bnTarge int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) { - arith_uint256 bnTarget,bhash; bool fNegative,fOverflow; uint8_t *script,pubkey33[33],pubkeys[64][33]; int32_t i,PoSperc,is_PoSblock=0,n,failed = 0,notaryid = -1; int64_t checktoshis,value; + uint256 hash; arith_uint256 bnTarget,bhash; bool fNegative,fOverflow; uint8_t *script,pubkey33[33],pubkeys[64][33]; int32_t i,PoSperc,is_PoSblock=0,n,failed = 0,notaryid = -1; int64_t checktoshis,value; if ( height == 0 ) return(0); if ( !CheckEquihashSolution(pblock, Params()) ) @@ -1251,12 +1251,13 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) return(-1); } bnTarget.SetCompact(pblock->nBits,&fNegative,&fOverflow); - bhash = UintToArith256(pblock->GetHash()); + hash = pblock->GetHash(); + bhash = UintToArith256(hash); komodo_block2pubkey33(pubkey33,pblock); if ( slowflag != 0 ) { - if ( !CheckProofOfWork(height,pubkey33,bhash,pblock->nBits,Params().GetConsensus(),pblock->nTime) ) - return state.DoS(1, error("CheckBlock: proof of work failed"),REJECT_INVALID, "high-hash"); + if ( !CheckProofOfWork(height,pubkey33,hash,pblock->nBits,Params().GetConsensus(),pblock->nTime) ) + return(-1); } if ( bhash > bnTarget ) { @@ -1276,7 +1277,7 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) } else if ( ASSETCHAINS_STAKED != 0 && height >= 2 ) // must PoS or have at least 16x better PoW { - if ( (is_PoSblock= komodo_is_PoSblock(slowflag,&block,bnTarget)) == 0 ) + if ( (is_PoSblock= komodo_is_PoSblock(slowflag,height,pblock,bnTarget)) == 0 ) { if ( ASSETCHAINS_STAKED == 100 || height <= 100 ) // only PoS allowed! return(-1); @@ -1296,7 +1297,7 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) return(-1); } } - } else if ( isPoSblock < 0 ) + } else if ( is_PoSblock < 0 ) return(-1); } if ( failed == 0 && ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 && ASSETCHAINS_COMMISSION != 0 ) diff --git a/src/main.cpp b/src/main.cpp index c50d3dcd2..42a7fda56 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3786,7 +3786,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat //if ( !CheckEquihashSolution(&block, Params()) ) // return state.DoS(100, error("CheckBlock: Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); komodo_block2pubkey33(pubkey33,(CBlock *)&block); - if ( komodo_checkPOW(1,&block,height) < 0 ) // checks Equihash + if ( komodo_checkPOW(1,(CBlock *)&block,height) < 0 ) // checks Equihash return state.DoS(100, error("CheckBlock: failed slow_checkPOW"),REJECT_INVALID, "failed-slow_checkPOW"); } // Check the merkle root. From 2808b68f942810ab733fd34cebe309970a5e2d89 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 14:09:02 +0300 Subject: [PATCH 452/507] Syntax --- src/komodo_bitcoind.h | 8 ++++---- src/main.cpp | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 696008623..470f6a90e 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1206,7 +1206,7 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he int32_t komodo_is_PoSblock(int32_t slowflag,int32_t height,CBlock *pblock,arith_uint256 bnTarget) { - CBlockIndex *previndex; char voutaddr[64],destaddr[64]; uint256 txid; uint32_t txtime,prevtime=0; int32_t vout,txn_count,eligible,isPoS = 0; CTxDestination destaddress; + CBlockIndex *previndex; char voutaddr[64],destaddr[64]; uint256 txid; uint32_t txtime,prevtime=0; int32_t vout,txn_count,eligible,isPoS = 0; uint64_t value; CTxDestination voutaddress; txn_count = pblock->vtx.size(); if ( txn_count > 1 ) { @@ -1222,7 +1222,7 @@ int32_t komodo_is_PoSblock(int32_t slowflag,int32_t height,CBlock *pblock,arith_ eligible = komodo_stake(1,bnTarget,height,txid,vout,pblock->nTime,prevtime,(char *)""); if ( eligible == 0 || eligible > pblock->nTime ) { - fprintf(stderr,"komodo_is_PoSblock PoS failure ht.%d eligible.%u vs blocktime.%u, lag.%d -> check to see if it is PoW block\n",height,eligible,(uint32_t)block.nTime,(int32_t)(eligible - block.nTime)); + fprintf(stderr,"komodo_is_PoSblock PoS failure ht.%d eligible.%u vs blocktime.%u, lag.%d -> check to see if it is PoW block\n",height,eligible,(uint32_t)pblock->nTime,(int32_t)(eligible - pblock->nTime)); } else isPoS = 1; } else if ( slowflag == 0 )// maybe previous block is not seen yet, do the best approx @@ -1230,7 +1230,7 @@ int32_t komodo_is_PoSblock(int32_t slowflag,int32_t height,CBlock *pblock,arith_ txtime = komodo_txtime(&value,txid,vout,destaddr); if ( ExtractDestination(pblock->vtx[txn_count-1].vout[0].scriptPubKey,voutaddress) ) { - strcpy(voutaddr,CBitcoinAddress(destaddress).ToString().c_str()); + strcpy(voutaddr,CBitcoinAddress(voutaddress).ToString().c_str()); if ( strcmp(destaddr,voutaddr) == 0 && pblock->vtx[txn_count-1].vout[0].nValue == value ) isPoS = 1; // close enough for a pre-filter else fprintf(stderr,"komodo_is_PoSblock ht.%d (%s) != (%s) or %.8f != %.8f\n",height,destaddr,voutaddr,dstr(value),dstr(pblock->vtx[txn_count-1].vout[0].nValue)); @@ -1289,7 +1289,7 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) if ( bhash > bnTarget ) { for (i=31; i>=16; i--) - fprintf(stderr,"%02x",((uint8_t *)&hashval)[i]); + fprintf(stderr,"%02x",((uint8_t *)&bhash)[i]); fprintf(stderr," > "); for (i=31; i>=16; i--) fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); diff --git a/src/main.cpp b/src/main.cpp index 42a7fda56..4792ac536 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2808,7 +2808,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin { if ( block.vtx[0].vout.size() == 2 && block.vtx[0].vout[1].nValue == checktoshis ) blockReward += checktoshis; - else fprintf(stderr,"checktoshis %.8f numvouts %d\n",dstr(checktoshis),block.vtx[0].vout.size()); + else fprintf(stderr,"checktoshis %.8f numvouts %d\n",dstr(checktoshis),(int32_t)block.vtx[0].vout.size()); } } if ( block.vtx[0].GetValueOut() > blockReward+1 ) From f8f740a966178f5f39d524a0dbb2a8a5d5e8ab12 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 14:10:25 +0300 Subject: [PATCH 453/507] Test --- src/miner.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/miner.cpp b/src/miner.cpp index be2bb5e03..fe97b97c7 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1082,6 +1082,7 @@ void static BitcoinMiner() pblock->nBits = savebits; if ( NOTARY_PUBKEY33[0] == 0 ) { + int32_t percPoS; UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks) { From 8fbee9292d5d601d4feb1c82fba075a27c326f02 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 14:17:47 +0300 Subject: [PATCH 454/507] Test --- src/komodo_bitcoind.h | 5 ----- src/main.cpp | 10 ++++++---- src/miner.cpp | 4 ++-- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 470f6a90e..fd9b6e4b8 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1254,11 +1254,6 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) hash = pblock->GetHash(); bhash = UintToArith256(hash); komodo_block2pubkey33(pubkey33,pblock); - if ( slowflag != 0 ) - { - if ( !CheckProofOfWork(height,pubkey33,hash,pblock->nBits,Params().GetConsensus(),pblock->nTime) ) - return(-1); - } if ( bhash > bnTarget ) { failed = 1; diff --git a/src/main.cpp b/src/main.cpp index 4792ac536..304e766c2 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3786,6 +3786,8 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat //if ( !CheckEquihashSolution(&block, Params()) ) // return state.DoS(100, error("CheckBlock: Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); komodo_block2pubkey33(pubkey33,(CBlock *)&block); + if ( !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(),block.nBits,Params().GetConsensus(),block.nTime) ) + return state.DoS(50, error("CheckBlock: proof of work failed"),REJECT_INVALID, "high-hash"); if ( komodo_checkPOW(1,(CBlock *)&block,height) < 0 ) // checks Equihash return state.DoS(100, error("CheckBlock: failed slow_checkPOW"),REJECT_INVALID, "failed-slow_checkPOW"); } @@ -4144,22 +4146,22 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex // NOTE: CheckBlockHeader is called by CheckBlock if (!ContextualCheckBlockHeader(block, state, pindexPrev)) { - fprintf(stderr,"TestBlockValidity failure A\n"); + fprintf(stderr,"TestBlockValidity failure A checkPOW.%d\n",fCheckPOW); return false; } if (!CheckBlock(indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot)) { - fprintf(stderr,"TestBlockValidity failure B\n"); + fprintf(stderr,"TestBlockValidity failure B checkPOW.%d\n",fCheckPOW); return false; } if (!ContextualCheckBlock(block, state, pindexPrev)) { - fprintf(stderr,"TestBlockValidity failure C\n"); + fprintf(stderr,"TestBlockValidity failure C checkPOW.%d\n",fCheckPOW); return false; } if (!ConnectBlock(block, state, &indexDummy, viewNew, true,fCheckPOW)) { - fprintf(stderr,"TestBlockValidity failure D\n"); + fprintf(stderr,"TestBlockValidity failure D checkPOW.%d\n",fCheckPOW); return false; } assert(state.IsValid()); diff --git a/src/miner.cpp b/src/miner.cpp index fe97b97c7..41e6c025f 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -853,8 +853,8 @@ void static BitcoinMiner() } HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); for (z=31; z>=0; z--) - fprintf(stderr,"%02x",((uint8_t *)&HASHTarget)[z]); - fprintf(stderr," PoW for staked coin %p\n",&HASHTarget); + fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); + fprintf(stderr," PoW for staked coin %p\n",&HASHTarget_POW); } while (true) { From fbd15acf157408542be4d049e4332d6244149ad8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 14:18:44 +0300 Subject: [PATCH 455/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 304e766c2..8d607cb5c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3786,7 +3786,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat //if ( !CheckEquihashSolution(&block, Params()) ) // return state.DoS(100, error("CheckBlock: Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); komodo_block2pubkey33(pubkey33,(CBlock *)&block); - if ( !CheckProofOfWork(height,pubkey33,blockhdr.GetHash(),block.nBits,Params().GetConsensus(),block.nTime) ) + if ( !CheckProofOfWork(height,pubkey33,block.GetHash(),block.nBits,Params().GetConsensus(),block.nTime) ) return state.DoS(50, error("CheckBlock: proof of work failed"),REJECT_INVALID, "high-hash"); if ( komodo_checkPOW(1,(CBlock *)&block,height) < 0 ) // checks Equihash return state.DoS(100, error("CheckBlock: failed slow_checkPOW"),REJECT_INVALID, "failed-slow_checkPOW"); From d335898793733060523534a2a1a977710d662f20 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 14:31:27 +0300 Subject: [PATCH 456/507] Test --- src/main.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main.cpp b/src/main.cpp index 8d607cb5c..c92a04d39 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3787,7 +3787,13 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat // return state.DoS(100, error("CheckBlock: Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( !CheckProofOfWork(height,pubkey33,block.GetHash(),block.nBits,Params().GetConsensus(),block.nTime) ) + { + uint256 h = block.GetHash(); + for (z=0; z<32; z++) + fprintf(stderr,"%02x",((uint8_t *)&h)[z]); + fprintf(stderr," failed hash\n"); return state.DoS(50, error("CheckBlock: proof of work failed"),REJECT_INVALID, "high-hash"); + } if ( komodo_checkPOW(1,(CBlock *)&block,height) < 0 ) // checks Equihash return state.DoS(100, error("CheckBlock: failed slow_checkPOW"),REJECT_INVALID, "failed-slow_checkPOW"); } From 4202cc246ca5e8846399126e19029ff33e5fde8f Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 14:32:27 +0300 Subject: [PATCH 457/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index c92a04d39..5e8c76650 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3788,7 +3788,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( !CheckProofOfWork(height,pubkey33,block.GetHash(),block.nBits,Params().GetConsensus(),block.nTime) ) { - uint256 h = block.GetHash(); + int32_t z; uint256 h = block.GetHash(); for (z=0; z<32; z++) fprintf(stderr,"%02x",((uint8_t *)&h)[z]); fprintf(stderr," failed hash\n"); From 80afe35bdca8fdd05ac28e4cabf109676bec18bd Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 14:44:05 +0300 Subject: [PATCH 458/507] test --- src/main.cpp | 4 ++-- src/pow.cpp | 19 +++++++++++-------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 5e8c76650..34c39424d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3789,9 +3789,9 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat if ( !CheckProofOfWork(height,pubkey33,block.GetHash(),block.nBits,Params().GetConsensus(),block.nTime) ) { int32_t z; uint256 h = block.GetHash(); - for (z=0; z<32; z++) + for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&h)[z]); - fprintf(stderr," failed hash\n"); + fprintf(stderr," failed hash ht.%d\n",height); return state.DoS(50, error("CheckBlock: proof of work failed"),REJECT_INVALID, "high-hash"); } if ( komodo_checkPOW(1,(CBlock *)&block,height) < 0 ) // checks Equihash diff --git a/src/pow.cpp b/src/pow.cpp index 0cb6e89ce..2de78050f 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -136,6 +136,9 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int extern int32_t KOMODO_REWIND; bool fNegative,fOverflow; uint8_t origpubkey33[33]; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t tiptime,blocktimes[66]; arith_uint256 bnTarget; uint8_t pubkeys[66][33]; + for (i=31; i>=0; i--) + fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); + fprintf(stderr," checkpow\n"); memcpy(origpubkey33,pubkey33,33); memset(blocktimes,0,sizeof(blocktimes)); tiptime = komodo_chainactive_timestamp(); @@ -195,17 +198,17 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int //if ( 0 && height > 792000 ) { for (i=31; i>=0; i--) - printf("%02x",((uint8_t *)&hash)[i]); - printf(" hash vs "); + fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); + fprintf(stderr," hash vs "); for (i=31; i>=0; i--) - printf("%02x",((uint8_t *)&bnTarget)[i]); - printf(" ht.%d special.%d notaryid.%d ht.%d mod.%d error\n",height,special,notaryid,height,(height % 35)); + fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); + fprintf(stderr," ht.%d special.%d notaryid.%d ht.%d mod.%d error\n",height,special,notaryid,fheight,(height % 35)); for (i=0; i<33; i++) - printf("%02x",pubkey33[i]); - printf(" <- pubkey\n"); + fprintf(stderr,"%02x",pubkey33[i]); + fprintf(stderr," <- pubkey\n"); for (i=0; i<33; i++) - printf("%02x",origpubkey33[i]); - printf(" <- origpubkey\n"); + fprintf(stderr,"%02x",origpubkey33[i]); + fprintf(stderr," <- origpubkey\n"); } return false; } From 4b5d43e3ff6c3c3aa054155497f76e26812e7512 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 14:45:16 +0300 Subject: [PATCH 459/507] Test --- src/pow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pow.cpp b/src/pow.cpp index 2de78050f..1638909e3 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -202,7 +202,7 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int fprintf(stderr," hash vs "); for (i=31; i>=0; i--) fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[i]); - fprintf(stderr," ht.%d special.%d notaryid.%d ht.%d mod.%d error\n",height,special,notaryid,fheight,(height % 35)); + fprintf(stderr," ht.%d special.%d notaryid.%d mod.%d error\n",height,special,notaryid,(height % 35)); for (i=0; i<33; i++) fprintf(stderr,"%02x",pubkey33[i]); fprintf(stderr," <- pubkey\n"); From bb3ab99ac0a1977399a34ce271020f794b8182fd Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 14:50:22 +0300 Subject: [PATCH 460/507] Test --- src/miner.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 41e6c025f..6a72979dd 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -884,9 +884,9 @@ void static BitcoinMiner() if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 ) hashTarget = HASHTarget_POW; else hashTarget = HASHTarget; - int32_t z; for (z=31; z>=0; z--) - fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); - fprintf(stderr," running solver\n"); + //int32_t z; for (z=31; z>=0; z--) + // fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); + //fprintf(stderr," running solver\n"); std::function)> validBlock = #ifdef ENABLE_WALLET [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams] From e5d9a70246db09bf7ed0b3e95317c115cf4d9e90 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 14:57:51 +0300 Subject: [PATCH 461/507] Test --- src/main.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 34c39424d..e7e4a9754 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3771,7 +3771,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat libzcash::ProofVerifier& verifier, bool fCheckPOW, bool fCheckMerkleRoot) { - uint8_t pubkey33[33]; + uint8_t pubkey33[33]; uint256 hash; // These are checks that are independent of context. // Check that the header is valid (particularly PoW). This is mostly @@ -3783,14 +3783,18 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat } if ( fCheckPOW ) { - //if ( !CheckEquihashSolution(&block, Params()) ) + int32_t z; + //if ( !CheckEquihashSolution(&block, Params()) ) // return state.DoS(100, error("CheckBlock: Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); + hash = block.GetHash(); + for (z=31; z>=0; z--) + fprintf(stderr,"%02x",((uint8_t *)&hash)[z]); + fprintf(stderr," check hash ht.%d\n",height); komodo_block2pubkey33(pubkey33,(CBlock *)&block); - if ( !CheckProofOfWork(height,pubkey33,block.GetHash(),block.nBits,Params().GetConsensus(),block.nTime) ) + if ( !CheckProofOfWork(height,pubkey33,hash,block.nBits,Params().GetConsensus(),block.nTime) ) { - int32_t z; uint256 h = block.GetHash(); for (z=31; z>=0; z--) - fprintf(stderr,"%02x",((uint8_t *)&h)[z]); + fprintf(stderr,"%02x",((uint8_t *)&hash)[z]); fprintf(stderr," failed hash ht.%d\n",height); return state.DoS(50, error("CheckBlock: proof of work failed"),REJECT_INVALID, "high-hash"); } From 18dd6a3b58f40dae53221deba96c36c5879ce8e7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 15:12:19 +0300 Subject: [PATCH 462/507] Test --- src/main.cpp | 24 ++++++++++++++++++++++-- src/miner.cpp | 4 ++-- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index e7e4a9754..df911fa7d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3773,7 +3773,11 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat { uint8_t pubkey33[33]; uint256 hash; // These are checks that are independent of context. - + hash = block.GetHash(); + for (z=31; z>=0; z--) + fprintf(stderr,"%02x",((uint8_t *)&hash)[z]); + fprintf(stderr," CheckBlock ht.%d\n",height); + // Check that the header is valid (particularly PoW). This is mostly // redundant with the call in AcceptBlockHeader. if (!CheckBlockHeader(height,pindex,block,state,fCheckPOW)) @@ -4152,23 +4156,39 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex indexDummy.nHeight = pindexPrev->nHeight + 1; // JoinSplit proofs are verified in ConnectBlock auto verifier = libzcash::ProofVerifier::Disabled(); - + uint256 h; + h = block.GetHash(); + for (z=31; z>=16; z--) + fprintf(stderr,"%02x",((uint8_t *)&h)[z]); + fprintf(stderr," test hash\n"); // NOTE: CheckBlockHeader is called by CheckBlock if (!ContextualCheckBlockHeader(block, state, pindexPrev)) { fprintf(stderr,"TestBlockValidity failure A checkPOW.%d\n",fCheckPOW); return false; } + h = block.GetHash(); + for (z=31; z>=16; z--) + fprintf(stderr,"%02x",((uint8_t *)&h)[z]); + fprintf(stderr," test hash2\n"); if (!CheckBlock(indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot)) { fprintf(stderr,"TestBlockValidity failure B checkPOW.%d\n",fCheckPOW); return false; } + h = block.GetHash(); + for (z=31; z>=16; z--) + fprintf(stderr,"%02x",((uint8_t *)&h)[z]); + fprintf(stderr," test hash3\n"); if (!ContextualCheckBlock(block, state, pindexPrev)) { fprintf(stderr,"TestBlockValidity failure C checkPOW.%d\n",fCheckPOW); return false; } + h = block.GetHash(); + for (z=31; z>=16; z--) + fprintf(stderr,"%02x",((uint8_t *)&h)[z]); + fprintf(stderr," test hash4\n"); if (!ConnectBlock(block, state, &indexDummy, viewNew, true,fCheckPOW)) { fprintf(stderr,"TestBlockValidity failure D checkPOW.%d\n",fCheckPOW); diff --git a/src/miner.cpp b/src/miner.cpp index 6a72979dd..149f0ea87 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1080,7 +1080,7 @@ void static BitcoinMiner() // Update nNonce and nTime pblock->nNonce = ArithToUint256(UintToArith256(pblock->nNonce) + 1); pblock->nBits = savebits; - if ( NOTARY_PUBKEY33[0] == 0 ) + /*if ( NOTARY_PUBKEY33[0] == 0 ) { int32_t percPoS; UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); @@ -1090,7 +1090,7 @@ void static BitcoinMiner() HASHTarget.SetCompact(pblock->nBits); HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); } - } + }*/ } } } From fb3cd913efa83ac4c45ea2e735f9f871f233920e Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 15:13:50 +0300 Subject: [PATCH 463/507] Test --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index df911fa7d..b7c77bb51 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3774,6 +3774,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat uint8_t pubkey33[33]; uint256 hash; // These are checks that are independent of context. hash = block.GetHash(); + int32_t z; for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&hash)[z]); fprintf(stderr," CheckBlock ht.%d\n",height); @@ -3787,7 +3788,6 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat } if ( fCheckPOW ) { - int32_t z; //if ( !CheckEquihashSolution(&block, Params()) ) // return state.DoS(100, error("CheckBlock: Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); hash = block.GetHash(); @@ -4156,7 +4156,7 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex indexDummy.nHeight = pindexPrev->nHeight + 1; // JoinSplit proofs are verified in ConnectBlock auto verifier = libzcash::ProofVerifier::Disabled(); - uint256 h; + int32_t z; uint256 h; h = block.GetHash(); for (z=31; z>=16; z--) fprintf(stderr,"%02x",((uint8_t *)&h)[z]); From 2ae7e0b5fa3163d785f144c4ffdba3e1b88f7c40 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 15:19:58 +0300 Subject: [PATCH 464/507] Test --- src/miner.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index 149f0ea87..759c6e013 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -894,11 +894,12 @@ void static BitcoinMiner() [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams] #endif (std::vector soln) { - int32_t z; arith_uint256 h = UintToArith256(pblock->GetHash()); + int32_t z; arith_uint256 h; // Write the solution to the hash and compute the result. LogPrint("pow", "- Checking solution against target\n"); pblock->nSolution = soln; solutionTargetChecks.increment(); + h = UintToArith256(pblock->GetHash()); if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 ) { if ( h > HASHTarget_POW ) @@ -921,6 +922,7 @@ void static BitcoinMiner() CValidationState state; if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), true, false)) { + h = UintToArith256(pblock->GetHash()); for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&h)[z]); fprintf(stderr," Invalid block mined, try again\n"); From c21c630657c638e877b6d45c78ed741ef42151a6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 15:33:36 +0300 Subject: [PATCH 465/507] Test --- src/miner.cpp | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 759c6e013..759567278 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -884,9 +884,6 @@ void static BitcoinMiner() if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 ) hashTarget = HASHTarget_POW; else hashTarget = HASHTarget; - //int32_t z; for (z=31; z>=0; z--) - // fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); - //fprintf(stderr," running solver\n"); std::function)> validBlock = #ifdef ENABLE_WALLET [&pblock, &hashTarget, &pwallet, &reservekey, &m_cs, &cancelSolver, &chainparams] @@ -894,22 +891,22 @@ void static BitcoinMiner() [&pblock, &hashTarget, &m_cs, &cancelSolver, &chainparams] #endif (std::vector soln) { - int32_t z; arith_uint256 h; + int32_t z; arith_uint256 h; CBlock B; // Write the solution to the hash and compute the result. + B = *pblock; + h = UintToArith256(B.GetHash()); + for (z=31; z>=0; z--) + fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); + fprintf(stderr," running solver\n"); LogPrint("pow", "- Checking solution against target\n"); pblock->nSolution = soln; solutionTargetChecks.increment(); - h = UintToArith256(pblock->GetHash()); - if ( NOTARY_PUBKEY33[0] == 0 && ASSETCHAINS_STAKED > 0 && ASSETCHAINS_STAKED < 100 ) - { - if ( h > HASHTarget_POW ) - return false; - } - else - { - if ( h > HASHTarget ) - return false; - } + h = UintToArith256(B.GetHash()); + for (z=31; z>=0; z--) + fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); + fprintf(stderr," running solver2\n"); + if ( h > hashTarget ) + return false; for (z=31; z>=16; z--) fprintf(stderr,"%02x",((uint8_t *)&h)[z]); fprintf(stderr," mined "); @@ -920,9 +917,9 @@ void static BitcoinMiner() fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); fprintf(stderr," POW\n"); CValidationState state; - if ( !TestBlockValidity(state, *pblock, chainActive.Tip(), true, false)) + if ( !TestBlockValidity(state,B, chainActive.Tip(), true, false)) { - h = UintToArith256(pblock->GetHash()); + h = UintToArith256(B.GetHash()); for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&h)[z]); fprintf(stderr," Invalid block mined, try again\n"); From 286d95b1df048c6c69649ceed989f0f4fbc16a87 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 15:38:34 +0300 Subject: [PATCH 466/507] Test --- src/miner.cpp | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 759567278..11f25cb71 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -895,16 +895,9 @@ void static BitcoinMiner() // Write the solution to the hash and compute the result. B = *pblock; h = UintToArith256(B.GetHash()); - for (z=31; z>=0; z--) - fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); - fprintf(stderr," running solver\n"); LogPrint("pow", "- Checking solution against target\n"); pblock->nSolution = soln; solutionTargetChecks.increment(); - h = UintToArith256(B.GetHash()); - for (z=31; z>=0; z--) - fprintf(stderr,"%02x",((uint8_t *)&hashTarget)[z]); - fprintf(stderr," running solver2\n"); if ( h > hashTarget ) return false; for (z=31; z>=16; z--) @@ -950,7 +943,7 @@ void static BitcoinMiner() } else { - uint256 tmp = pblock->GetHash(); + uint256 tmp = B.GetHash(); int32_t z; for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&tmp)[z]); fprintf(stderr," mined block!\n"); From eff2c3a35a07b488bbc08cea0a0c5eeaa3c36719 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 15:43:39 +0300 Subject: [PATCH 467/507] Test --- src/miner.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 11f25cb71..92a274644 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -893,14 +893,14 @@ void static BitcoinMiner() (std::vector soln) { int32_t z; arith_uint256 h; CBlock B; // Write the solution to the hash and compute the result. - B = *pblock; - h = UintToArith256(B.GetHash()); LogPrint("pow", "- Checking solution against target\n"); pblock->nSolution = soln; solutionTargetChecks.increment(); + B = *pblock; + h = UintToArith256(B.GetHash()); if ( h > hashTarget ) return false; - for (z=31; z>=16; z--) + /*for (z=31; z>=16; z--) fprintf(stderr,"%02x",((uint8_t *)&h)[z]); fprintf(stderr," mined "); for (z=31; z>=16; z--) @@ -908,7 +908,7 @@ void static BitcoinMiner() fprintf(stderr," hashTarget "); for (z=31; z>=16; z--) fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); - fprintf(stderr," POW\n"); + fprintf(stderr," POW\n");*/ CValidationState state; if ( !TestBlockValidity(state,B, chainActive.Tip(), true, false)) { @@ -937,8 +937,8 @@ void static BitcoinMiner() { if ( NOTARY_PUBKEY33[0] != 0 ) { - printf("need to wait %d seconds to submit staked block\n",(int32_t)(pblock->nTime - GetAdjustedTime())); - while ( GetAdjustedTime() < pblock->nTime ) + printf("need to wait %d seconds to submit staked block\n",(int32_t)(B.nTime - GetAdjustedTime())); + while ( GetAdjustedTime() < B.nTime ) sleep(1); } else @@ -953,11 +953,11 @@ void static BitcoinMiner() // Found a solution SetThreadPriority(THREAD_PRIORITY_NORMAL); LogPrintf("KomodoMiner:\n"); - LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", pblock->GetHash().GetHex(), HASHTarget.GetHex()); + LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", B.GetHash().GetHex(), HASHTarget.GetHex()); #ifdef ENABLE_WALLET - if (ProcessBlockFound(pblock, *pwallet, reservekey)) { + if (ProcessBlockFound(&B, *pwallet, reservekey)) { #else - if (ProcessBlockFound(pblock)) { + if (ProcessBlockFound(&B)) { #endif // Ignore chain updates caused by us std::lock_guard lock{m_cs}; @@ -1019,7 +1019,7 @@ void static BitcoinMiner() bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled); ehSolverRuns.increment(); if (found) { - int32_t i; uint256 hash = pblock->GetHash(); + int32_t i; uint256 hash = B.GetHash(); for (i=0; i<32; i++) fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height); @@ -1051,7 +1051,7 @@ void static BitcoinMiner() break; } } - if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff) + if ((UintToArith256(B.nNonce) & 0xffff) == 0xffff) { //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) fprintf(stderr,"0xffff, break\n"); From 997ddd92c75d4ff531ef4c86b4a195eb2dadd316 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 15:44:56 +0300 Subject: [PATCH 468/507] Test --- src/miner.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 92a274644..7e8fa4196 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1019,7 +1019,7 @@ void static BitcoinMiner() bool found = EhOptimisedSolve(n, k, curr_state, validBlock, cancelled); ehSolverRuns.increment(); if (found) { - int32_t i; uint256 hash = B.GetHash(); + int32_t i; uint256 hash = pblock->GetHash(); for (i=0; i<32; i++) fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); fprintf(stderr," <- %s Block found %d\n",ASSETCHAINS_SYMBOL,Mining_height); @@ -1051,7 +1051,7 @@ void static BitcoinMiner() break; } } - if ((UintToArith256(B.nNonce) & 0xffff) == 0xffff) + if ((UintToArith256(pblock->nNonce) & 0xffff) == 0xffff) { //if ( 0 && ASSETCHAINS_SYMBOL[0] != 0 ) fprintf(stderr,"0xffff, break\n"); From bf30e02d79618e593f8742ad9a74e59f6ac06dfc Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 15:53:28 +0300 Subject: [PATCH 469/507] Test --- src/main.cpp | 17 ----------------- src/miner.cpp | 2 +- src/pow.cpp | 6 +++--- 3 files changed, 4 insertions(+), 21 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index b7c77bb51..194f3ce7c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4156,39 +4156,22 @@ bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex indexDummy.nHeight = pindexPrev->nHeight + 1; // JoinSplit proofs are verified in ConnectBlock auto verifier = libzcash::ProofVerifier::Disabled(); - int32_t z; uint256 h; - h = block.GetHash(); - for (z=31; z>=16; z--) - fprintf(stderr,"%02x",((uint8_t *)&h)[z]); - fprintf(stderr," test hash\n"); // NOTE: CheckBlockHeader is called by CheckBlock if (!ContextualCheckBlockHeader(block, state, pindexPrev)) { fprintf(stderr,"TestBlockValidity failure A checkPOW.%d\n",fCheckPOW); return false; } - h = block.GetHash(); - for (z=31; z>=16; z--) - fprintf(stderr,"%02x",((uint8_t *)&h)[z]); - fprintf(stderr," test hash2\n"); if (!CheckBlock(indexDummy.nHeight,0,block, state, verifier, fCheckPOW, fCheckMerkleRoot)) { fprintf(stderr,"TestBlockValidity failure B checkPOW.%d\n",fCheckPOW); return false; } - h = block.GetHash(); - for (z=31; z>=16; z--) - fprintf(stderr,"%02x",((uint8_t *)&h)[z]); - fprintf(stderr," test hash3\n"); if (!ContextualCheckBlock(block, state, pindexPrev)) { fprintf(stderr,"TestBlockValidity failure C checkPOW.%d\n",fCheckPOW); return false; } - h = block.GetHash(); - for (z=31; z>=16; z--) - fprintf(stderr,"%02x",((uint8_t *)&h)[z]); - fprintf(stderr," test hash4\n"); if (!ConnectBlock(block, state, &indexDummy, viewNew, true,fCheckPOW)) { fprintf(stderr,"TestBlockValidity failure D checkPOW.%d\n",fCheckPOW); diff --git a/src/miner.cpp b/src/miner.cpp index 7e8fa4196..494629552 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -854,7 +854,7 @@ void static BitcoinMiner() HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); - fprintf(stderr," PoW for staked coin %p\n",&HASHTarget_POW); + fprintf(stderr," PoW for staked coin PoS %d%%\n",&HASHTarget_POW,percPoS); } while (true) { diff --git a/src/pow.cpp b/src/pow.cpp index 1638909e3..310e9721b 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -136,9 +136,9 @@ bool CheckProofOfWork(int32_t height,uint8_t *pubkey33,uint256 hash,unsigned int extern int32_t KOMODO_REWIND; bool fNegative,fOverflow; uint8_t origpubkey33[33]; int32_t i,nonzpkeys=0,nonz=0,special=0,special2=0,notaryid=-1,flag = 0, mids[66]; uint32_t tiptime,blocktimes[66]; arith_uint256 bnTarget; uint8_t pubkeys[66][33]; - for (i=31; i>=0; i--) - fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); - fprintf(stderr," checkpow\n"); + //for (i=31; i>=0; i--) + // fprintf(stderr,"%02x",((uint8_t *)&hash)[i]); + //fprintf(stderr," checkpow\n"); memcpy(origpubkey33,pubkey33,33); memset(blocktimes,0,sizeof(blocktimes)); tiptime = komodo_chainactive_timestamp(); From af0c41ee3df86a2f9dd98966de05979f66b96240 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 15:55:17 +0300 Subject: [PATCH 470/507] Test --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index 494629552..fe01faaad 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -854,7 +854,7 @@ void static BitcoinMiner() HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); - fprintf(stderr," PoW for staked coin PoS %d%%\n",&HASHTarget_POW,percPoS); + fprintf(stderr," PoW for staked coin PoS %d%%\n",percPoS); } while (true) { From 7bb789bb6646edf4921be246c49fccf40202ae4a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 16:03:51 +0300 Subject: [PATCH 471/507] Test --- src/main.cpp | 18 +++++------------- src/main.h | 2 +- src/miner.cpp | 2 +- src/rpcmining.cpp | 4 ++-- src/test/miner_tests.cpp | 4 ++-- 5 files changed, 11 insertions(+), 19 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 194f3ce7c..481adb10d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3774,10 +3774,6 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat uint8_t pubkey33[33]; uint256 hash; // These are checks that are independent of context. hash = block.GetHash(); - int32_t z; - for (z=31; z>=0; z--) - fprintf(stderr,"%02x",((uint8_t *)&hash)[z]); - fprintf(stderr," CheckBlock ht.%d\n",height); // Check that the header is valid (particularly PoW). This is mostly // redundant with the call in AcceptBlockHeader. @@ -3790,10 +3786,6 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat { //if ( !CheckEquihashSolution(&block, Params()) ) // return state.DoS(100, error("CheckBlock: Equihash solution invalid"),REJECT_INVALID, "invalid-solution"); - hash = block.GetHash(); - for (z=31; z>=0; z--) - fprintf(stderr,"%02x",((uint8_t *)&hash)[z]); - fprintf(stderr," check hash ht.%d\n",height); komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( !CheckProofOfWork(height,pubkey33,hash,block.nBits,Params().GetConsensus(),block.nTime) ) { @@ -4105,7 +4097,7 @@ static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned void komodo_currentheight_set(int32_t height); -bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp) +bool ProcessNewBlock(bool from_miner,int32_t height,CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp) { // Preliminary checks bool checked; @@ -4117,7 +4109,7 @@ bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBloc LOCK(cs_main); bool fRequested = MarkBlockAsReceived(pblock->GetHash()); fRequested |= fForceProcessing; - if ( checked != 0 && komodo_checkPOW(0,pblock,height) < 0 ) + if ( checked != 0 && komodo_checkPOW(from_miner,pblock,height) < 0 ) checked = 0; if (!checked) { @@ -4919,7 +4911,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) // process in case the block isn't known yet if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) { CValidationState state; - if (ProcessNewBlock(0,state, NULL, &block, true, dbp)) + if (ProcessNewBlock(0,0,state, NULL, &block, true, dbp)) nLoaded++; if (state.IsError()) break; @@ -4941,7 +4933,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp) LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(), head.ToString()); CValidationState dummy; - if (ProcessNewBlock(0,dummy, NULL, &block, true, &it->second)) + if (ProcessNewBlock(0,0,dummy, NULL, &block, true, &it->second)) { nLoaded++; queue.push_back(block.GetHash()); @@ -6026,7 +6018,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, // Such an unrequested block may still be processed, subject to the // conditions in AcceptBlock(). bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload(); - ProcessNewBlock(0,state, pfrom, &block, forceProcessing, NULL); + ProcessNewBlock(0,0,state, pfrom, &block, forceProcessing, NULL); int nDoS; if (state.IsInvalid(nDoS)) { pfrom->PushMessage("reject", strCommand, state.GetRejectCode(), diff --git a/src/main.h b/src/main.h index 035328a22..f52fa222d 100644 --- a/src/main.h +++ b/src/main.h @@ -190,7 +190,7 @@ void UnregisterNodeSignals(CNodeSignals& nodeSignals); * @param[out] dbp If pblock is stored to disk (or already there), this will be set to its location. * @return True if state.IsValid() */ -bool ProcessNewBlock(int32_t height,CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp); +bool ProcessNewBlock(bool from_miner,int32_t height,CValidationState &state, CNode* pfrom, CBlock* pblock, bool fForceProcessing, CDiskBlockPos *dbp); /** Check whether enough disk space is available for an incoming block */ bool CheckDiskSpace(uint64_t nAdditionalBytes = 0); /** Open a block file (blk?????.dat) */ diff --git a/src/miner.cpp b/src/miner.cpp index fe01faaad..211f55d7a 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -631,7 +631,7 @@ static bool ProcessBlockFound(CBlock* pblock) // Process this block the same as if we had received it from another node CValidationState state; - if (!ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL)) + if (!ProcessNewBlock(1,chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL)) return error("KomodoMiner: ProcessNewBlock, block not accepted"); TrackMinedBlock(pblock->GetHash()); diff --git a/src/rpcmining.cpp b/src/rpcmining.cpp index d141c42c4..aea5694f2 100644 --- a/src/rpcmining.cpp +++ b/src/rpcmining.cpp @@ -267,7 +267,7 @@ UniValue generate(const UniValue& params, bool fHelp) } endloop: CValidationState state; - if (!ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL)) + if (!ProcessNewBlock(1,chainActive.Tip()->nHeight+1,state, NULL, pblock, true, NULL)) throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted"); ++nHeight; blockHashes.push_back(pblock->GetHash().GetHex()); @@ -807,7 +807,7 @@ UniValue submitblock(const UniValue& params, bool fHelp) CValidationState state; submitblock_StateCatcher sc(block.GetHash()); RegisterValidationInterface(&sc); - bool fAccepted = ProcessNewBlock(chainActive.Tip()->nHeight+1,state, NULL, &block, true, NULL); + bool fAccepted = ProcessNewBlock(1,chainActive.Tip()->nHeight+1,state, NULL, &block, true, NULL); UnregisterValidationInterface(&sc); if (fBlockPresent) { diff --git a/src/test/miner_tests.cpp b/src/test/miner_tests.cpp index 9b8674f04..27edc8669 100644 --- a/src/test/miner_tests.cpp +++ b/src/test/miner_tests.cpp @@ -242,7 +242,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) CValidationState state; - if (ProcessNewBlock(state, NULL, pblock, true, NULL) && state.IsValid()) { + if (ProcessNewBlock(1,state, NULL, pblock, true, NULL) && state.IsValid()) { goto foundit; } @@ -261,7 +261,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) */ CValidationState state; - BOOST_CHECK(ProcessNewBlock(state, NULL, pblock, true, NULL)); + BOOST_CHECK(ProcessNewBlock(1,state, NULL, pblock, true, NULL)); BOOST_CHECK_MESSAGE(state.IsValid(), state.GetRejectReason()); pblock->hashPrevBlock = pblock->GetHash(); From 560da193c645ec2904883bd9db65e2275b362ec4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 16:06:31 +0300 Subject: [PATCH 472/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 481adb10d..d104b7992 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3789,7 +3789,7 @@ bool CheckBlock(int32_t height,CBlockIndex *pindex,const CBlock& block, CValidat komodo_block2pubkey33(pubkey33,(CBlock *)&block); if ( !CheckProofOfWork(height,pubkey33,hash,block.nBits,Params().GetConsensus(),block.nTime) ) { - for (z=31; z>=0; z--) + int32_t z; for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&hash)[z]); fprintf(stderr," failed hash ht.%d\n",height); return state.DoS(50, error("CheckBlock: proof of work failed"),REJECT_INVALID, "high-hash"); From b509fdae1431807b3eeb9d65226319c6d2156583 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 16:27:54 +0300 Subject: [PATCH 473/507] Test --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index 211f55d7a..3ead4b6bc 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -854,7 +854,7 @@ void static BitcoinMiner() HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); - fprintf(stderr," PoW for staked coin PoS %d%%\n",percPoS); + fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%%\n",percPoS,(int32_t)ASSETCHAINS_STAKED); } while (true) { From 56930f21f15e87e5982caecf9cf5b4a74ac872ff Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 17:30:09 +0300 Subject: [PATCH 474/507] Test --- src/komodo_bitcoind.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index fd9b6e4b8..41e3fbfd5 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1141,7 +1141,7 @@ uint32_t komodo_stake(int32_t validateflag,arith_uint256 bnTarget,int32_t nHeigh arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc) { - CBlockIndex *pindex; arith_uint256 bnTarget,hashval,sum,ave; bool fNegative,fOverflow; int32_t i,n,ht,percPoS,diff; + CBlockIndex *pindex; arith_uint256 bnTarget,hashval,sum,ave,factor; bool fNegative,fOverflow; int32_t i,n,ht,percPoS,diff; *percPoSp = percPoS = 0; sum = arith_uint256(0); ave = sum; @@ -1170,8 +1170,9 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he } else return(target); if ( percPoS < goalperc ) // increase PoW diff -> lower bnTarget { - bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); - if ( 0 ) + factor = arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); + bnTarget = (ave * factor * factor); + if ( 1 ) { for (i=31; i>=24; i--) fprintf(stderr,"%02x",((uint8_t *)&ave)[i]); From d4da197214160e64ea72c60b1cc1c22a7d7688ad Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 17:31:51 +0300 Subject: [PATCH 475/507] Test --- src/komodo_bitcoind.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 41e3fbfd5..7886576d4 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1170,8 +1170,12 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he } else return(target); if ( percPoS < goalperc ) // increase PoW diff -> lower bnTarget { - factor = arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); - bnTarget = (ave * factor * factor); + if ( height < 1120 ) + { + factor = arith_uint256(goalperc) / arith_uint256(percPoS + goalperc); + bnTarget = (ave * factor * factor); + } + else bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); if ( 1 ) { for (i=31; i>=24; i--) From 861319af5e830f4c9e75c70ed4766922ba19afed Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 17:32:09 +0300 Subject: [PATCH 476/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 7886576d4..095941657 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1170,7 +1170,7 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he } else return(target); if ( percPoS < goalperc ) // increase PoW diff -> lower bnTarget { - if ( height < 1120 ) + if ( height > 1120 ) { factor = arith_uint256(goalperc) / arith_uint256(percPoS + goalperc); bnTarget = (ave * factor * factor); From ff556351ad5ce3e94c2bc235da9f09b97c41bb48 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 17:35:25 +0300 Subject: [PATCH 477/507] Test --- src/komodo_bitcoind.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 095941657..be4c94484 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1170,10 +1170,10 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he } else return(target); if ( percPoS < goalperc ) // increase PoW diff -> lower bnTarget { - if ( height > 1120 ) + if ( height > 1200 ) { - factor = arith_uint256(goalperc) / arith_uint256(percPoS + goalperc); - bnTarget = (ave * factor * factor); + factor = arith_uint256(goalperc * goalperc) / arith_uint256((percPoS + goalperc) * (percPoS + goalperc)); + bnTarget = (ave * factor); } else bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); if ( 1 ) From 6897193353d9c88d3adceaea5090bedeb41e0253 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 17:41:56 +0300 Subject: [PATCH 478/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index be4c94484..625d81cd8 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1172,7 +1172,7 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he { if ( height > 1200 ) { - factor = arith_uint256(goalperc * goalperc) / arith_uint256((percPoS + goalperc) * (percPoS + goalperc)); + factor = arith_uint256(goalperc * goalperc) / arith_uint256(2 * (percPoS + goalperc) * (percPoS + goalperc)); bnTarget = (ave * factor); } else bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); From 96cf6918b7273cea4e4e0e6273dca86ba763b334 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 17:46:08 +0300 Subject: [PATCH 479/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 625d81cd8..b22e3fa56 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1170,7 +1170,7 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he } else return(target); if ( percPoS < goalperc ) // increase PoW diff -> lower bnTarget { - if ( height > 1200 ) + if ( height > 1165 ) { factor = arith_uint256(goalperc * goalperc) / arith_uint256(2 * (percPoS + goalperc) * (percPoS + goalperc)); bnTarget = (ave * factor); From 67eaffd906da86472608638db736869d05d5d0b1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 17:58:27 +0300 Subject: [PATCH 480/507] Test --- src/komodo_bitcoind.h | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index b22e3fa56..40a3e5231 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1141,7 +1141,7 @@ uint32_t komodo_stake(int32_t validateflag,arith_uint256 bnTarget,int32_t nHeigh arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc) { - CBlockIndex *pindex; arith_uint256 bnTarget,hashval,sum,ave,factor; bool fNegative,fOverflow; int32_t i,n,ht,percPoS,diff; + CBlockIndex *pindex; arith_uint256 bnTarget,hashval,sum,ave; bool fNegative,fOverflow; int32_t i,n,ht,percPoS,diff; *percPoSp = percPoS = 0; sum = arith_uint256(0); ave = sum; @@ -1171,10 +1171,7 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he if ( percPoS < goalperc ) // increase PoW diff -> lower bnTarget { if ( height > 1165 ) - { - factor = arith_uint256(goalperc * goalperc) / arith_uint256(2 * (percPoS + goalperc) * (percPoS + goalperc)); - bnTarget = (ave * factor); - } + bnTarget = (ave * arith_uint256(goalperc * goalperc)) / arith_uint256(2 * (percPoS + goalperc) * (percPoS + goalperc)); else bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); if ( 1 ) { From d5a8071bc78e5d0de71104eb1394e9febdd1fdae Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 18:16:01 +0300 Subject: [PATCH 481/507] Test --- src/komodo_bitcoind.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 40a3e5231..7b0eb45f0 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1171,7 +1171,11 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he if ( percPoS < goalperc ) // increase PoW diff -> lower bnTarget { if ( height > 1165 ) - bnTarget = (ave * arith_uint256(goalperc * goalperc)) / arith_uint256(2 * (percPoS + goalperc) * (percPoS + goalperc)); + { + if ( height > 1180 ) + bnTarget = ((ave * arith_uint256(percPoS)) + (target * arith_uint256(goalperc))) / arith_uint256(2 * (percPoS + goalperc)); + else bnTarget = (ave * arith_uint256(goalperc * goalperc)) / arith_uint256(2 * (percPoS + goalperc) * (percPoS + goalperc)); + } else bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); if ( 1 ) { From 1247b7d42915efe0754e57dbcd090f83429e21cf Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 18:32:29 +0300 Subject: [PATCH 482/507] Test --- src/komodo_bitcoind.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 7b0eb45f0..23f8820a6 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1141,7 +1141,7 @@ uint32_t komodo_stake(int32_t validateflag,arith_uint256 bnTarget,int32_t nHeigh arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t height,int32_t goalperc) { - CBlockIndex *pindex; arith_uint256 bnTarget,hashval,sum,ave; bool fNegative,fOverflow; int32_t i,n,ht,percPoS,diff; + CBlockIndex *pindex; arith_uint256 bnTarget,hashval,sum,ave; bool fNegative,fOverflow; int32_t i,n,ht,percPoS,diff,val; *percPoSp = percPoS = 0; sum = arith_uint256(0); ave = sum; @@ -1173,7 +1173,7 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he if ( height > 1165 ) { if ( height > 1180 ) - bnTarget = ((ave * arith_uint256(percPoS)) + (target * arith_uint256(goalperc))) / arith_uint256(2 * (percPoS + goalperc)); + bnTarget = ave * arith_uint256(persPoS * persPoS)) / arith_uint256((percPoS + goalperc) * (percPoS + goalperc)); else bnTarget = (ave * arith_uint256(goalperc * goalperc)) / arith_uint256(2 * (percPoS + goalperc) * (percPoS + goalperc)); } else bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); From b36ad22ad678755f02364e7e449eba1b9d3198fd Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 18:33:15 +0300 Subject: [PATCH 483/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 23f8820a6..e0c340aed 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1173,7 +1173,7 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he if ( height > 1165 ) { if ( height > 1180 ) - bnTarget = ave * arith_uint256(persPoS * persPoS)) / arith_uint256((percPoS + goalperc) * (percPoS + goalperc)); + bnTarget = ave * arith_uint256(percPoS * percPoS)) / arith_uint256((percPoS + goalperc) * (percPoS + goalperc)); else bnTarget = (ave * arith_uint256(goalperc * goalperc)) / arith_uint256(2 * (percPoS + goalperc) * (percPoS + goalperc)); } else bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); From d395043eb3824977b878fe4266c9ac1515c9e3db Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 18:35:16 +0300 Subject: [PATCH 484/507] Test --- src/komodo_bitcoind.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index e0c340aed..9cca24b65 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1173,7 +1173,7 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he if ( height > 1165 ) { if ( height > 1180 ) - bnTarget = ave * arith_uint256(percPoS * percPoS)) / arith_uint256((percPoS + goalperc) * (percPoS + goalperc)); + bnTarget = (ave * arith_uint256(percPoS * percPoS)) / arith_uint256((percPoS + goalperc) * (percPoS + goalperc)); else bnTarget = (ave * arith_uint256(goalperc * goalperc)) / arith_uint256(2 * (percPoS + goalperc) * (percPoS + goalperc)); } else bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); From 689a24a7724b4d76d9278f9636839bfe5f686867 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 18:40:20 +0300 Subject: [PATCH 485/507] Test --- src/komodo_bitcoind.h | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 9cca24b65..dd04d92e2 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1155,11 +1155,18 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he hashval = UintToArith256(pindex->GetBlockHash()); if ( hashval <= bnTarget ) // PoW is never as easy as PoS/64, some PoS will be counted as PoW { + fprintf(stderr,"1"); sum += hashval; n++; - } else percPoS++; + } + else + { + percPoS++; + fprintf(stderr,"0"); + } } } + fprintf(stderr," -> %d%% percPoS ht.%d\n",percPoS,height); *percPoSp = percPoS; target = (target / arith_uint256(KOMODO_POWMINMULT)); if ( n > 0 ) From 23b680a0f4f205e3889cfb0aaef4896361bb1407 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 19:24:53 +0300 Subject: [PATCH 486/507] Test --- src/komodo_bitcoind.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index dd04d92e2..7866595b5 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1180,7 +1180,11 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he if ( height > 1165 ) { if ( height > 1180 ) - bnTarget = (ave * arith_uint256(percPoS * percPoS)) / arith_uint256((percPoS + goalperc) * (percPoS + goalperc)); + { + if ( height > 1230 ) + bnTarget = (ave * arith_uint256(percPoS * percPoS)) / arith_uint256((goalperc) * (goalperc)); + else bnTarget = (ave * arith_uint256(percPoS * percPoS)) / arith_uint256(goalperc * goalperc); + } else bnTarget = (ave * arith_uint256(goalperc * goalperc)) / arith_uint256(2 * (percPoS + goalperc) * (percPoS + goalperc)); } else bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); @@ -1200,7 +1204,7 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he else if ( percPoS > goalperc ) // decrease PoW diff -> raise bnTarget { bnTarget = ((ave * arith_uint256(goalperc)) + (target * arith_uint256(percPoS))) / arith_uint256(percPoS + goalperc); - if ( 0 ) + if ( 1 ) { for (i=31; i>=24; i--) fprintf(stderr,"%02x",((uint8_t *)&ave)[i]); From 7b6d6985a996a102f05eaebee20d094804f9957f Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 20:33:41 +0300 Subject: [PATCH 487/507] Test --- src/komodo_bitcoind.h | 10 ++++++---- src/wallet/rpcwallet.cpp | 4 +++- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 7866595b5..b6c3d651b 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1082,10 +1082,12 @@ uint32_t komodo_stake(int32_t validateflag,arith_uint256 bnTarget,int32_t nHeigh { CBlockIndex *pindex; uint8_t hashbuf[128]; char address[64]; bits256 addrhash; arith_uint256 hashval; uint256 hash,pasthash; int64_t diff=0; int32_t segid,minage,i,iter=0; uint32_t txtime,winner = 0; uint64_t value,coinage,supply = ASSETCHAINS_SUPPLY + nHeight*ASSETCHAINS_REWARD/SATOSHIDEN; txtime = komodo_txtime(&value,txid,vout,address); - if ( value == 0 || txtime == 0 ) + if ( value == 0 || txtime == 0 || blocktime == 0 || prevtime == 0 ) return(0); if ( (minage= nHeight*3) > 6000 ) minage = 6000; + if ( blocktime < prevtime+57 ) + blocktime = prevtime+57; if ( blocktime > txtime+minage && (pindex= komodo_chainactive(nHeight>200?nHeight-200:1)) != 0 ) { vcalc_sha256(0,(uint8_t *)&addrhash,(uint8_t *)address,(int32_t)strlen(address)); @@ -1177,7 +1179,8 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he } else return(target); if ( percPoS < goalperc ) // increase PoW diff -> lower bnTarget { - if ( height > 1165 ) + bnTarget = (ave * arith_uint256(percPoS * percPoS)) / arith_uint256((goalperc) * (goalperc)); + /*if ( height > 1165 ) { if ( height > 1180 ) { @@ -1186,8 +1189,7 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he else bnTarget = (ave * arith_uint256(percPoS * percPoS)) / arith_uint256(goalperc * goalperc); } else bnTarget = (ave * arith_uint256(goalperc * goalperc)) / arith_uint256(2 * (percPoS + goalperc) * (percPoS + goalperc)); - } - else bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc); + } else bnTarget = (ave * arith_uint256(goalperc)) / arith_uint256(percPoS + goalperc);*/ if ( 1 ) { for (i=31; i>=24; i--) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 347c15f2d..010f51319 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -4494,7 +4494,9 @@ int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blockt if ( eligible > 0 ) { if ( eligible != komodo_stake(1,bnTarget,(uint32_t)tipindex->nHeight+1,out.tx->GetHash(),out.i,eligible,(uint32_t)tipindex->nTime,(char *)CBitcoinAddress(address).ToString().c_str()) ) - fprintf(stderr,"validation of winning blocktime failed %u -> eligible.%u\n",*blocktimep,eligible); + { + //fprintf(stderr,"tip.%d validation of winning blocktime failed %u -> eligible.%u\n",(uint32_t)tipindex->nHeight,*blocktimep,eligible); + } else if ( earliest == 0 || eligible < earliest || (eligible == earliest && (*utxovaluep == 0 || nValue < *utxovaluep)) ) { earliest = eligible; From 23b2b0fab8b536108655a395a52ab0f444e79e3e Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 20:42:52 +0300 Subject: [PATCH 488/507] Test --- src/komodo_bitcoind.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index b6c3d651b..00adc28a6 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1086,8 +1086,6 @@ uint32_t komodo_stake(int32_t validateflag,arith_uint256 bnTarget,int32_t nHeigh return(0); if ( (minage= nHeight*3) > 6000 ) minage = 6000; - if ( blocktime < prevtime+57 ) - blocktime = prevtime+57; if ( blocktime > txtime+minage && (pindex= komodo_chainactive(nHeight>200?nHeight-200:1)) != 0 ) { vcalc_sha256(0,(uint8_t *)&addrhash,(uint8_t *)address,(int32_t)strlen(address)); From 6d7537dedb5fe173f4e648935a3746659cd64b07 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 20:48:27 +0300 Subject: [PATCH 489/507] Test --- src/komodo_bitcoind.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 00adc28a6..10a95d3f7 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1086,6 +1086,8 @@ uint32_t komodo_stake(int32_t validateflag,arith_uint256 bnTarget,int32_t nHeigh return(0); if ( (minage= nHeight*3) > 6000 ) minage = 6000; + if ( blocktime < prevtime+57 ) + blocktime = prevtime+57; if ( blocktime > txtime+minage && (pindex= komodo_chainactive(nHeight>200?nHeight-200:1)) != 0 ) { vcalc_sha256(0,(uint8_t *)&addrhash,(uint8_t *)address,(int32_t)strlen(address)); @@ -1291,7 +1293,7 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) { if ( (is_PoSblock= komodo_is_PoSblock(slowflag,height,pblock,bnTarget)) == 0 ) { - if ( ASSETCHAINS_STAKED == 100 || height <= 100 ) // only PoS allowed! + if ( ASSETCHAINS_STAKED == 100 && height > 100 ) // only PoS allowed! return(-1); else { From 8ab6dd61df84968934b6906c6a788c9b1e81834e Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 20:51:43 +0300 Subject: [PATCH 490/507] Test --- src/komodo_bitcoind.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 10a95d3f7..5b0ddf0c3 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1145,6 +1145,8 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he { CBlockIndex *pindex; arith_uint256 bnTarget,hashval,sum,ave; bool fNegative,fOverflow; int32_t i,n,ht,percPoS,diff,val; *percPoSp = percPoS = 0; + if ( height < 100 ) + return(target); sum = arith_uint256(0); ave = sum; for (i=n=0; i<100; i++) From d9935f2b615fd46e88d0d7d3542b9997c2233df2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 20:54:47 +0300 Subject: [PATCH 491/507] Test --- src/miner.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 3ead4b6bc..dbdc87309 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -846,11 +846,11 @@ void static BitcoinMiner() if ( ASSETCHAINS_STAKED != 0 && NOTARY_PUBKEY33[0] == 0 ) { int32_t percPoS,z; - if ( Mining_height <= 100 ) + /*if ( Mining_height <= 100 ) { sleep(60); continue; - } + }*/ HASHTarget_POW = komodo_PoWtarget(&percPoS,HASHTarget,Mining_height,ASSETCHAINS_STAKED); for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&HASHTarget_POW)[z]); From d07308d221a62da3a10a3dd40f1a4d6b34e43c5b Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 20:59:03 +0300 Subject: [PATCH 492/507] Test --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index dbdc87309..d31ebb995 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -384,7 +384,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn) nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; - blocktime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); + blocktime = 1 + std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); //pblock->nTime = blocktime + 1; pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, Params().GetConsensus()); //LogPrintf("CreateNewBlock(): total size %u blocktime.%u nBits.%08x\n", nBlockSize,blocktime,pblock->nBits); From a1a721bd4589923921b6bdd1093f293e9f8f3f8b Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 21:00:57 +0300 Subject: [PATCH 493/507] Test --- src/komodo_bitcoind.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 5b0ddf0c3..10a95d3f7 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1145,8 +1145,6 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he { CBlockIndex *pindex; arith_uint256 bnTarget,hashval,sum,ave; bool fNegative,fOverflow; int32_t i,n,ht,percPoS,diff,val; *percPoSp = percPoS = 0; - if ( height < 100 ) - return(target); sum = arith_uint256(0); ave = sum; for (i=n=0; i<100; i++) From 96df006a14a8b5c594bd2dbb1acb44e8e6aa675d Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 21:11:09 +0300 Subject: [PATCH 494/507] Test --- src/komodo_bitcoind.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 10a95d3f7..2db96544e 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1145,6 +1145,8 @@ arith_uint256 komodo_PoWtarget(int32_t *percPoSp,arith_uint256 target,int32_t he { CBlockIndex *pindex; arith_uint256 bnTarget,hashval,sum,ave; bool fNegative,fOverflow; int32_t i,n,ht,percPoS,diff,val; *percPoSp = percPoS = 0; + if ( height < 3 ) + return(target); sum = arith_uint256(0); ave = sum; for (i=n=0; i<100; i++) From bd87f0c09ee1939644952e707a1ac6226dca2b86 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 22:43:52 +0300 Subject: [PATCH 495/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index d104b7992..56756ee9f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4109,7 +4109,7 @@ bool ProcessNewBlock(bool from_miner,int32_t height,CValidationState &state, CNo LOCK(cs_main); bool fRequested = MarkBlockAsReceived(pblock->GetHash()); fRequested |= fForceProcessing; - if ( checked != 0 && komodo_checkPOW(from_miner,pblock,height) < 0 ) + if ( checked != 0 && komodo_checkPOW(from_miner && ASSETCHAINS_STAKED == 0,pblock,height) < 0 ) checked = 0; if (!checked) { From 13b8b2ed264b4d3f77ee67b28e5118c6bda86646 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 23:11:11 +0300 Subject: [PATCH 496/507] Test --- src/komodo_bitcoind.h | 5 ++++- src/main.cpp | 7 +++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 2db96544e..afbcd537d 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1246,7 +1246,7 @@ int32_t komodo_is_PoSblock(int32_t slowflag,int32_t height,CBlock *pblock,arith_ fprintf(stderr,"komodo_is_PoSblock PoS failure ht.%d eligible.%u vs blocktime.%u, lag.%d -> check to see if it is PoW block\n",height,eligible,(uint32_t)pblock->nTime,(int32_t)(eligible - pblock->nTime)); } else isPoS = 1; } - else if ( slowflag == 0 )// maybe previous block is not seen yet, do the best approx + else if ( slowflag == 0 ) // maybe previous block is not seen yet, do the best approx { txtime = komodo_txtime(&value,txid,vout,destaddr); if ( ExtractDestination(pblock->vtx[txn_count-1].vout[0].scriptPubKey,voutaddress) ) @@ -1265,7 +1265,10 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) { uint256 hash; arith_uint256 bnTarget,bhash; bool fNegative,fOverflow; uint8_t *script,pubkey33[33],pubkeys[64][33]; int32_t i,PoSperc,is_PoSblock=0,n,failed = 0,notaryid = -1; int64_t checktoshis,value; if ( height == 0 ) + { + fprintf(stderr,"komodo_checkPOW slowflag.%d ht.%d null\n",slowflag,height); return(0); + } if ( !CheckEquihashSolution(pblock, Params()) ) { fprintf(stderr,"komodo_checkPOW slowflag.%d ht.%d CheckEquihashSolution failed\n",slowflag,height); diff --git a/src/main.cpp b/src/main.cpp index 56756ee9f..e51e7318b 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4016,12 +4016,12 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CBlockIndex *&pindex = *ppindex; if (!AcceptBlockHeader(block, state, &pindex)) { - //fprintf(stderr,"AcceptBlockHeader rejected\n"); + fprintf(stderr,"AcceptBlockHeader rejected\n"); return false; } if ( pindex == 0 ) { - //fprintf(stderr,"unexpected AcceptBlock error null pindex\n"); + fprintf(stderr,"unexpected AcceptBlock error null pindex\n"); return false; } //fprintf(stderr,"acceptblockheader passed\n"); @@ -4110,7 +4110,10 @@ bool ProcessNewBlock(bool from_miner,int32_t height,CValidationState &state, CNo bool fRequested = MarkBlockAsReceived(pblock->GetHash()); fRequested |= fForceProcessing; if ( checked != 0 && komodo_checkPOW(from_miner && ASSETCHAINS_STAKED == 0,pblock,height) < 0 ) + { checked = 0; + fprintf(stderr,"passed checkblock but failed checkPOW\n"); + } if (!checked) { if ( pfrom != 0 ) From f1b57a6e76a59ebdeafaed182161706ef1e6b1d6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 23:18:23 +0300 Subject: [PATCH 497/507] Test --- src/komodo_bitcoind.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index afbcd537d..17e9752db 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1264,16 +1264,16 @@ int32_t komodo_is_PoSblock(int32_t slowflag,int32_t height,CBlock *pblock,arith_ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) { uint256 hash; arith_uint256 bnTarget,bhash; bool fNegative,fOverflow; uint8_t *script,pubkey33[33],pubkeys[64][33]; int32_t i,PoSperc,is_PoSblock=0,n,failed = 0,notaryid = -1; int64_t checktoshis,value; - if ( height == 0 ) - { - fprintf(stderr,"komodo_checkPOW slowflag.%d ht.%d null\n",slowflag,height); - return(0); - } if ( !CheckEquihashSolution(pblock, Params()) ) { fprintf(stderr,"komodo_checkPOW slowflag.%d ht.%d CheckEquihashSolution failed\n",slowflag,height); return(-1); } + if ( height == 0 ) + { + fprintf(stderr,"komodo_checkPOW slowflag.%d ht.%d null\n",slowflag,height); + return(0); + } bnTarget.SetCompact(pblock->nBits,&fNegative,&fOverflow); hash = pblock->GetHash(); bhash = UintToArith256(hash); From ec5b59fd30e47b35c456cad05a32a28b195481cc Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 19 Apr 2018 23:34:55 +0300 Subject: [PATCH 498/507] Test --- src/komodo_bitcoind.h | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 17e9752db..49efdd38e 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1263,19 +1263,22 @@ int32_t komodo_is_PoSblock(int32_t slowflag,int32_t height,CBlock *pblock,arith_ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) { - uint256 hash; arith_uint256 bnTarget,bhash; bool fNegative,fOverflow; uint8_t *script,pubkey33[33],pubkeys[64][33]; int32_t i,PoSperc,is_PoSblock=0,n,failed = 0,notaryid = -1; int64_t checktoshis,value; + uint256 hash; arith_uint256 bnTarget,bhash; bool fNegative,fOverflow; uint8_t *script,pubkey33[33],pubkeys[64][33]; int32_t i,PoSperc,is_PoSblock=0,n,failed = 0,notaryid = -1; int64_t checktoshis,value; CBlockIndex *pprev; if ( !CheckEquihashSolution(pblock, Params()) ) { fprintf(stderr,"komodo_checkPOW slowflag.%d ht.%d CheckEquihashSolution failed\n",slowflag,height); return(-1); } + hash = pblock->GetHash(); if ( height == 0 ) { - fprintf(stderr,"komodo_checkPOW slowflag.%d ht.%d null\n",slowflag,height); - return(0); + if ( (pprev= mapBlockIndex[pblock->hashPrevBlock]) != 0 ) + height = pprev->nHeight + 1; + fprintf(stderr,"komodo_checkPOW slowflag.%d ht.%d zeroheight\n",slowflag,height); + if ( height == 0 ) + return(0); } bnTarget.SetCompact(pblock->nBits,&fNegative,&fOverflow); - hash = pblock->GetHash(); bhash = UintToArith256(hash); komodo_block2pubkey33(pubkey33,pblock); if ( bhash > bnTarget ) From 8eb43ab4ff24488e92e8686653f5e20c5f8144c3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 20 Apr 2018 00:23:58 +0300 Subject: [PATCH 499/507] Decrement notes for assetchains, need to test --- src/main.cpp | 2 +- src/wallet/wallet.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index e51e7318b..b53e39294 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4021,7 +4021,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, } if ( pindex == 0 ) { - fprintf(stderr,"unexpected AcceptBlock error null pindex\n"); + //fprintf(stderr,"unexpected AcceptBlock error null pindex\n"); return false; } //fprintf(stderr,"acceptblockheader passed\n"); diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index a1c7039cf..77a27c69a 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -414,7 +414,7 @@ void CWallet::ChainTip(const CBlockIndex *pindex, const CBlock *pblock, { if (added) { IncrementNoteWitnesses(pindex, pblock, tree); - } else if ( ASSETCHAINS_SYMBOL[0] == 0 || nWitnessCacheSize > 1 ){ + } else if ( nWitnessCacheSize > 1 ){ //ASSETCHAINS_SYMBOL[0] == 0 || DecrementNoteWitnesses(pindex); } else fprintf(stderr,"would have decremented %s nWitnessCacheSize.%d\n",ASSETCHAINS_SYMBOL,(int32_t)nWitnessCacheSize); } From 65b4e8809d38753ab5a508d921c6e81950448ff1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 20 Apr 2018 00:39:38 +0300 Subject: [PATCH 500/507] Test --- src/miner.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index d31ebb995..7a07bb060 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -635,7 +635,17 @@ static bool ProcessBlockFound(CBlock* pblock) return error("KomodoMiner: ProcessNewBlock, block not accepted"); TrackMinedBlock(pblock->GetHash()); - + fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL)); + { + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + if ( pnode->hSocket == INVALID_SOCKET ) + continue; + pnode->PushMessage("block", *pblock); + } + } + fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL)); return true; } From 7377cedcf6274308bd70b14811a42a732390687f Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 20 Apr 2018 00:40:03 +0300 Subject: [PATCH 501/507] Test --- src/miner.cpp | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index 7a07bb060..7b7b81a19 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -635,17 +635,20 @@ static bool ProcessBlockFound(CBlock* pblock) return error("KomodoMiner: ProcessNewBlock, block not accepted"); TrackMinedBlock(pblock->GetHash()); - fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL)); + if ( ASSETCHAINS_STAKED != 0 ) { - LOCK(cs_vNodes); - BOOST_FOREACH(CNode* pnode, vNodes) + fprintf(stderr,"broadcast new block t.%u\n",(uint32_t)time(NULL)); { - if ( pnode->hSocket == INVALID_SOCKET ) - continue; - pnode->PushMessage("block", *pblock); + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + if ( pnode->hSocket == INVALID_SOCKET ) + continue; + pnode->PushMessage("block", *pblock); + } } + fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL)); } - fprintf(stderr,"finished broadcast new block t.%u\n",(uint32_t)time(NULL)); return true; } From 8d028ba0612e200ff15ee4e614d1c5d264b68322 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 20 Apr 2018 01:06:43 +0300 Subject: [PATCH 502/507] Test --- src/komodo_bitcoind.h | 4 ++-- src/main.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 49efdd38e..ed465b083 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1275,7 +1275,7 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) if ( (pprev= mapBlockIndex[pblock->hashPrevBlock]) != 0 ) height = pprev->nHeight + 1; fprintf(stderr,"komodo_checkPOW slowflag.%d ht.%d zeroheight\n",slowflag,height); - if ( height == 0 ) + //if ( height == 0 ) return(0); } bnTarget.SetCompact(pblock->nBits,&fNegative,&fOverflow); @@ -1339,7 +1339,7 @@ int32_t komodo_checkPOW(int32_t slowflag,CBlock *pblock,int32_t height) } } } - //fprintf(stderr,"komodo_checkPOW slowflag.%d ht.%d notaryid.%d failed.%d\n",slowflag,height,notaryid,failed); + fprintf(stderr,"komodo_checkPOW slowflag.%d ht.%d notaryid.%d failed.%d\n",slowflag,height,notaryid,failed); if ( failed != 0 && notaryid < 0 ) return(-1); else return(0); diff --git a/src/main.cpp b/src/main.cpp index b53e39294..ef7227bfd 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4112,7 +4112,7 @@ bool ProcessNewBlock(bool from_miner,int32_t height,CValidationState &state, CNo if ( checked != 0 && komodo_checkPOW(from_miner && ASSETCHAINS_STAKED == 0,pblock,height) < 0 ) { checked = 0; - fprintf(stderr,"passed checkblock but failed checkPOW\n"); + fprintf(stderr,"passed checkblock but failed checkPOW.%d\n",from_miner && ASSETCHAINS_STAKED == 0); } if (!checked) { From 02290a3fd86453ca023c32c87d0ddbba13afff30 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 20 Apr 2018 01:15:21 +0300 Subject: [PATCH 503/507] Test --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index ef7227bfd..0aee36d10 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1677,7 +1677,7 @@ bool ReadBlockFromDisk(int32_t height,CBlock& block, const CDiskBlockPos& pos,bo return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString()); } // Check the header - if ( checkPOW != 0 ) + if ( 0 && checkPOW != 0 ) { komodo_block2pubkey33(pubkey33,(CBlock *)&block); if (!(CheckEquihashSolution(&block, Params()) && CheckProofOfWork(height,pubkey33,block.GetHash(), block.nBits, Params().GetConsensus(),block.nTime))) From 942e45b592fec507032d3faee06e1b2541f171db Mon Sep 17 00:00:00 2001 From: ca333 Date: Fri, 20 Apr 2018 01:56:09 +0200 Subject: [PATCH 504/507] add windows port use windows.h for WIN crossbuild --- src/cryptoconditions/src/secp256k1.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/cryptoconditions/src/secp256k1.c b/src/cryptoconditions/src/secp256k1.c index 73f7a9164..78b9c4e9e 100644 --- a/src/cryptoconditions/src/secp256k1.c +++ b/src/cryptoconditions/src/secp256k1.c @@ -1,6 +1,11 @@ #define _GNU_SOURCE 1 +#if __linux #include +#elif defined(_WIN32) || defined(_WIN64) +#include +#endif + #include #include From 5a83e4fc3fd4e541b870f51843a779c9bf253285 Mon Sep 17 00:00:00 2001 From: DeckerSU Date: Fri, 20 Apr 2018 03:32:45 +0300 Subject: [PATCH 505/507] src/snark patches for windows build --- src/snark/AUTHORS | 3 + src/snark/Makefile | 21 ++-- src/snark/README.md | 8 +- .../algebra/curves/alt_bn128/alt_bn128_g1.cpp | 11 +- .../algebra/curves/alt_bn128/alt_bn128_g1.hpp | 8 +- .../algebra/curves/alt_bn128/alt_bn128_g2.cpp | 11 +- .../algebra/curves/alt_bn128/alt_bn128_g2.hpp | 8 +- .../curves/alt_bn128/alt_bn128_pairing.cpp | 6 +- .../libsnark/algebra/curves/curve_utils.tcc | 2 +- .../algebra/curves/tests/test_bilinearity.cpp | 42 +++++-- .../algebra/curves/tests/test_groups.cpp | 101 +++++++++------- .../domains/basic_radix2_domain.tcc | 11 +- .../domains/basic_radix2_domain_aux.tcc | 15 +-- .../evaluation_domain/evaluation_domain.hpp | 4 +- .../evaluation_domain/evaluation_domain.tcc | 19 +-- .../algebra/exponentiation/exponentiation.hpp | 2 +- .../algebra/exponentiation/exponentiation.tcc | 4 +- src/snark/libsnark/algebra/fields/bigint.hpp | 4 +- src/snark/libsnark/algebra/fields/bigint.tcc | 27 ++--- .../libsnark/algebra/fields/field_utils.hpp | 8 +- .../libsnark/algebra/fields/field_utils.tcc | 43 +++---- src/snark/libsnark/algebra/fields/fp.hpp | 44 +++---- src/snark/libsnark/algebra/fields/fp.tcc | 38 +++--- .../algebra/fields/fp12_2over3over2.hpp | 4 +- .../algebra/fields/fp12_2over3over2.tcc | 10 +- src/snark/libsnark/algebra/fields/fp2.hpp | 8 +- src/snark/libsnark/algebra/fields/fp2.tcc | 8 +- .../libsnark/algebra/fields/fp6_3over2.hpp | 4 +- .../libsnark/algebra/fields/fp6_3over2.tcc | 4 +- .../algebra/fields/tests/test_bigint.cpp | 88 +++++++------- .../algebra/fields/tests/test_fields.cpp | 108 +++++++++++++----- .../scalar_multiplication/kc_multiexp.hpp | 6 +- .../scalar_multiplication/kc_multiexp.tcc | 4 +- .../scalar_multiplication/multiexp.tcc | 29 ++--- .../algebra/scalar_multiplication/wnaf.hpp | 2 +- .../algebra/scalar_multiplication/wnaf.tcc | 18 +-- .../common/data_structures/merkle_tree.tcc | 18 +-- .../common/data_structures/sparse_vector.hpp | 16 +-- .../common/data_structures/sparse_vector.tcc | 36 +++--- src/snark/libsnark/common/profiling.cpp | 77 ++++++++----- src/snark/libsnark/common/profiling.hpp | 10 +- src/snark/libsnark/common/serialization.hpp | 2 +- src/snark/libsnark/common/serialization.tcc | 3 +- src/snark/libsnark/common/utils.cpp | 28 ++--- src/snark/libsnark/common/utils.hpp | 17 ++- src/snark/libsnark/common/utils.tcc | 8 ++ .../gadgetlib1/gadgets/basic_gadgets.tcc | 40 +++---- .../gadgets/hashes/sha256/sha256_aux.tcc | 2 +- .../hashes/sha256/sha256_components.hpp | 4 +- .../hashes/sha256/sha256_components.tcc | 6 +- .../sha256/tests/test_sha256_gadget.cpp | 6 +- .../merkle_authentication_path_variable.tcc | 4 +- .../merkle_tree_check_read_gadget.tcc | 4 +- .../merkle_tree_check_update_gadget.hpp | 1 + .../merkle_tree_check_update_gadget.tcc | 4 +- .../tests/test_merkle_tree_gadgets.cpp | 22 ++-- src/snark/libsnark/gadgetlib1/pb_variable.hpp | 4 +- src/snark/libsnark/gadgetlib1/pb_variable.tcc | 4 +- src/snark/libsnark/gtests.cpp | 5 +- .../reductions/r1cs_to_qap/r1cs_to_qap.hpp | 2 +- .../qap/tests/test_qap.cpp | 31 +++-- src/snark/libsnark/relations/variable.hpp | 4 +- .../examples/run_r1cs_ppzksnark.tcc | 2 +- .../r1cs_ppzksnark/r1cs_ppzksnark.hpp | 5 +- .../r1cs_ppzksnark/r1cs_ppzksnark.tcc | 2 +- .../tests/test_r1cs_ppzksnark.cpp | 12 +- 66 files changed, 637 insertions(+), 475 deletions(-) diff --git a/src/snark/AUTHORS b/src/snark/AUTHORS index 1b2d7a247..cdc8d66af 100644 --- a/src/snark/AUTHORS +++ b/src/snark/AUTHORS @@ -17,3 +17,6 @@ External contributors: Tadanori TERUYA Sean Bowe Daira Hopwood + @mugatu on forum.z.cash + David Mercer + Joshua Yabut diff --git a/src/snark/Makefile b/src/snark/Makefile index b865f992f..17dcfdc6e 100644 --- a/src/snark/Makefile +++ b/src/snark/Makefile @@ -6,6 +6,13 @@ #* @copyright MIT license (see LICENSE file) #*******************************************************************************/ +# Determine building operating system +ifeq ($(OS),Windows_NT) + uname_S := Windows +else + uname_S := $(shell uname -s) +endif + # To override these, use "make OPTFLAGS=..." etc. CURVE = BN128 OPTFLAGS = -O2 -march=native -mtune=native @@ -106,18 +113,9 @@ EXECUTABLES_WITH_GTEST = EXECUTABLES_WITH_SUPERCOP = \ libsnark/zk_proof_systems/ppzkadsnark/r1cs_ppzkadsnark/examples/demo_r1cs_ppzkadsnark -GTEST_TESTS = libsnark/gtests +GTEST_TESTS = -GTEST_SRCS = \ - libsnark/algebra/curves/tests/test_bilinearity.cpp \ - libsnark/algebra/curves/tests/test_groups.cpp \ - libsnark/algebra/fields/tests/test_bigint.cpp \ - libsnark/algebra/fields/tests/test_fields.cpp \ - libsnark/gadgetlib1/gadgets/hashes/sha256/tests/test_sha256_gadget.cpp \ - libsnark/gadgetlib1/gadgets/merkle_tree/tests/test_merkle_tree_gadgets.cpp \ - libsnark/relations/arithmetic_programs/qap/tests/test_qap.cpp \ - libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/tests/test_r1cs_ppzksnark.cpp \ - libsnark/gtests.cpp +GTEST_SRCS = DOCS = README.html @@ -175,6 +173,7 @@ all: \ $(if $(NO_GTEST),,$(EXECUTABLES_WITH_GTEST) $(GTEST_TESTS)) \ $(if $(NO_SUPERCOP),,$(EXECUTABLES_WITH_SUPERCOP)) \ $(EXECUTABLES) \ + $(LIBSNARK_A) \ $(if $(NO_DOCS),,doc) doc: $(DOCS) diff --git a/src/snark/README.md b/src/snark/README.md index 89183b43a..d5aa34006 100644 --- a/src/snark/README.md +++ b/src/snark/README.md @@ -14,7 +14,7 @@ Copyright (c) 2012-2014 SCIPR Lab and contributors (see [AUTHORS] file). [TOC]