From c1e694dd80b5dd3b77e37bfe929f3ef267201e94 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 16 Dec 2018 04:59:04 -1100 Subject: [PATCH 0001/1145] Update zmigrate --- src/cc/dapps/zmigrate.c | 67 +++++++++++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 23 deletions(-) diff --git a/src/cc/dapps/zmigrate.c b/src/cc/dapps/zmigrate.c index 81de2c13d..8a57ebda5 100644 --- a/src/cc/dapps/zmigrate.c +++ b/src/cc/dapps/zmigrate.c @@ -20,18 +20,18 @@ #include "cJSON.c" /* -z_migrate: the purpose of z_migrate is to make converting of all sprout outputs into sapling. the usage would be for the user to specify a sapling address and call z_migrate zsaddr, until it returns that there is nothing left to be done. - -its main functionality is quite similar to a z_mergetoaddress ANY_ZADDR -> onetime_taddr followed by a z_sendmany onetime_taddr -> zsaddr - -since the z_mergetoaddress will take time, it would just queue up an async operation. When it starts, it should see if there are any onetime_taddr with 10000.0001 funds in it, that is a signal for it to do the sapling tx and it can just do that without async as it is fast enough, especially with a taddr input. Maybe it limits itself to one, or it does all possible taddr -> sapling as fast as it can. either is fine as it will be called over and over anyway. - -It might be that there is nothing to do, but some operations are pending. in that case it would return such a status. as soon as the operation finishes, there would be more work to do. - -the amount sent to the taddr, should be 10000.0001 - -The GUI or user would be expected to generate a sapling address and then call z_migrate saplingaddr in a loop, until it returns that it is all done. this loop should pause for 10 seconds or so, if z_migrate is just waiting for opid to complete. -*/ + z_migrate: the purpose of z_migrate is to make converting of all sprout outputs into sapling. the usage would be for the user to specify a sapling address and call z_migrate zsaddr, until it returns that there is nothing left to be done. + + its main functionality is quite similar to a z_mergetoaddress ANY_ZADDR -> onetime_taddr followed by a z_sendmany onetime_taddr -> zsaddr + + since the z_mergetoaddress will take time, it would just queue up an async operation. When it starts, it should see if there are any onetime_taddr with 10000.0001 funds in it, that is a signal for it to do the sapling tx and it can just do that without async as it is fast enough, especially with a taddr input. Maybe it limits itself to one, or it does all possible taddr -> sapling as fast as it can. either is fine as it will be called over and over anyway. + + It might be that there is nothing to do, but some operations are pending. in that case it would return such a status. as soon as the operation finishes, there would be more work to do. + + the amount sent to the taddr, should be 10000.0001 + + The GUI or user would be expected to generate a sapling address and then call z_migrate saplingaddr in a loop, until it returns that it is all done. this loop should pause for 10 seconds or so, if z_migrate is just waiting for opid to complete. + */ bits256 zeroid; @@ -331,7 +331,7 @@ cJSON *get_komodocli(char *refcoin,char **retstrp,char *acname,char *method,char system(cmdstr); *retstrp = 0; if ( (jsonstr= filestr(&fsize,fname)) != 0 ) - { + { jsonstr[strlen(jsonstr)-1]='\0'; //fprintf(stderr,"%s -> jsonstr.(%s)\n",cmdstr,jsonstr); if ( (jsonstr[0] != '{' && jsonstr[0] != '[') || (retjson= cJSON_Parse(jsonstr)) == 0 ) @@ -599,13 +599,13 @@ int32_t validateaddress(char *refcoin,char *acname,char *depositaddr, char* comp cJSON *retjson; char *retstr; int32_t res=0; if ( (retjson= get_komodocli(refcoin,&retstr,acname,"validateaddress",depositaddr,"","","")) != 0 ) { - if (is_cJSON_True(jobj(retjson,compare)) != 0 ) res=1; + if (is_cJSON_True(jobj(retjson,compare)) != 0 ) res=1; free_json(retjson); } else if ( retstr != 0 ) { fprintf(stderr,"validateaddress.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); + free(retstr); } return (res); } @@ -670,6 +670,7 @@ int64_t find_onetime_amount(char *coinstr,char *coinaddr) coinaddr[0] = 0; if ( (array= get_listunspent(coinstr,"")) != 0 ) { + //printf("got listunspent.(%s)\n",jprint(array,0)); if ( (n= cJSON_GetArraySize(array)) > 0 ) { for (i=0; i %s\n",srcaddr,params); if ( (retjson= get_komodocli(coinstr,&retstr,acname,"z_sendmany",addr,params,"","")) != 0 ) { printf("unexpected json z_sendmany.(%s)\n",jprint(retjson,0)); @@ -797,7 +799,7 @@ int32_t tx_has_voutaddress(char *refcoin,char *acname,bits256 txid,char *coinadd if ( (vouts= jarray(&numarray,txobj,"vout")) != 0 ) { for (i=0; i txfee ) @@ -930,14 +932,33 @@ again: if ( (amount= find_sprout_amount(coinstr,zcaddr)) > txfee ) { // generate taddr, send max of 10000.0001 - if ( amount > stdamount+txfee ) - amount = stdamount + txfee; + static int64_t lastamount,lastamount2,lastamount3,lastamount4,refamount = 5000 * SATOSHIDEN; + stdamount = refamount; + if ( amount == lastamount && amount == lastamount2 ) + { + stdamount /= 10; + if ( amount == lastamount3 && amount == lastamount4 ) + stdamount /= 10; + } + if ( stdamount < COIN ) + { + stdamount = COIN; + refamount = COIN * 50; + } + if ( stdamount < refamount ) + refamount = stdamount; + lastamount4 = lastamount3; + lastamount3 = lastamount2; + lastamount2 = lastamount; + lastamount = amount; + if ( amount > stdamount+2*txfee ) + amount = stdamount + 2*txfee; if ( getnewaddress(coinaddr,coinstr,"") == 0 ) { z_sendmany(opidstr,coinstr,"",zcaddr,coinaddr,amount-txfee); lastopid = (uint32_t)time(NULL); } else printf("couldnt getnewaddress!\n"); - sleep(30); + sleep(3); continue; } if ( time(NULL) > lastopid+600 ) From e9b100e50fac7772b4080c0d182f751f21d0ec58 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 16 Dec 2018 05:51:21 -1100 Subject: [PATCH 0002/1145] COIN -> SATOSHIDEN --- src/cc/dapps/zmigrate.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/dapps/zmigrate.c b/src/cc/dapps/zmigrate.c index 8a57ebda5..d492163c4 100644 --- a/src/cc/dapps/zmigrate.c +++ b/src/cc/dapps/zmigrate.c @@ -940,10 +940,10 @@ again: if ( amount == lastamount3 && amount == lastamount4 ) stdamount /= 10; } - if ( stdamount < COIN ) + if ( stdamount < SATOSHIDEN ) { - stdamount = COIN; - refamount = COIN * 50; + stdamount = SATOSHIDEN; + refamount = SATOSHIDEN * 50; } if ( stdamount < refamount ) refamount = stdamount; From fe32a3be6c8950266d759103d2fb2beda635967e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 16 Dec 2018 07:39:54 -1100 Subject: [PATCH 0003/1145] Fix stuck sync for nodes that are doing full sync MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sapling height is calculated near the sapling activation timestamp. Until it is set, the node doesn’t know when sapling should be active. Depending on the speed at which you get blocks from the future, it was possible that you could see a sapling active block before the sapling height was set. This would happen only if syncing from a node that didn’t know the sapling height and a full resync with the most peers and most variety of incoming block sources was most likely hit by this. The net effect was that the blocks after sapling activation were marked as invalid, so by the time the node synced up to the sapling height, it couldn’t advance. --- src/main.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/main.cpp b/src/main.cpp index 6c33feb08..d822c8686 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5043,6 +5043,19 @@ bool AcceptBlock(int32_t *futureblockp,CBlock& block, CValidationState& state, C auto verifier = libzcash::ProofVerifier::Disabled(); if ((!CheckBlock(futureblockp,pindex->GetHeight(),pindex,block, state, verifier,0)) || !ContextualCheckBlock(block, state, pindex->pprev)) { + static int32_t saplinght = -1; + CBlockIndex *tmpptr; + if ( saplinght == -1 ) + saplinght = Params().GetConsensus().vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight; + if ( saplinght < 0 ) + *futureblockp = 1; + // the problem is when a future sapling block comes in before we detected saplinght + if ( saplinght > 0 && (tmpptr= chainActive.LastTip()) != 0 ) + { + fprintf(stderr,"saplinght.%d tipht.%d blockht.%d cmp.%d\n",saplinght,(int32_t)tmpptr->GetHeight(),pindex->GetHeight(),pindex->GetHeight() < 0 || pindex->GetHeight() >= saplinght || (tmpptr->GetHeight() > saplinght-720 && tmpptr->GetHeight() < saplinght+720)); + if ( pindex->GetHeight() < 0 || pindex->GetHeight() >= saplinght || (tmpptr->GetHeight() > saplinght-720 && tmpptr->GetHeight() < saplinght+720) ) + *futureblockp = 1; + } if ( *futureblockp == 0 ) { if (state.IsInvalid() && !state.CorruptionPossible()) { From b3837525ee282e12144c868edcdd5fbce9ceb2ad Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 18 Dec 2018 09:00:04 -1100 Subject: [PATCH 0004/1145] New migrate --- .gitignore | 2 + src/cc/dapps/zmigrate.c | 86 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 87 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 01e45a168..cd2641c22 100644 --- a/.gitignore +++ b/.gitignore @@ -124,3 +124,5 @@ src/komodo-tx.exe #output during builds, symbol tables? *.dSYM + +src/cryptoconditions/compile diff --git a/src/cc/dapps/zmigrate.c b/src/cc/dapps/zmigrate.c index d492163c4..441b51b19 100644 --- a/src/cc/dapps/zmigrate.c +++ b/src/cc/dapps/zmigrate.c @@ -647,6 +647,25 @@ int64_t z_getbalance(char *refcoin,char *acname,char *coinaddr) return (amount); } +int32_t z_exportkey(char *privkey,char *refcoin,char *acname,char *zaddr) +{ + cJSON *retjson; char *retstr,cmpstr[64]; int64_t amount=0; + privkey[0] = 0; + if ( (retjson= get_komodocli(refcoin,&retstr,acname,"z_exportkey",zaddr,"","","")) != 0 ) + { + fprintf(stderr,"z_exportkey.(%s) %s returned json!\n",refcoin,acname); + free_json(retjson); + return(-1); + } + else if ( retstr != 0 ) + { + //printf("retstr %s -> %.8f\n",retstr,dstr(amount)); + strcpy(privkey,retstr); + free(retstr); + return(0); + } +} + int32_t getnewaddress(char *coinaddr,char *refcoin,char *acname) { cJSON *retjson; char *retstr; int64_t amount=0; @@ -664,6 +683,23 @@ int32_t getnewaddress(char *coinaddr,char *refcoin,char *acname) } } +int32_t z_getnewaddress(char *coinaddr,char *refcoin,char *acname,char *typestr) +{ + cJSON *retjson; char *retstr; int64_t amount=0; + if ( (retjson= get_komodocli(refcoin,&retstr,acname,"z_getnewaddress",typestr,"","","")) != 0 ) + { + fprintf(stderr,"z_getnewaddress.(%s) %s returned json!\n",refcoin,acname); + free_json(retjson); + return(-1); + } + else if ( retstr != 0 ) + { + strcpy(coinaddr,retstr); + free(retstr); + return(0); + } +} + int64_t find_onetime_amount(char *coinstr,char *coinaddr) { cJSON *array,*item; int32_t i,n; char *addr; int64_t amount = 0; @@ -751,6 +787,39 @@ int32_t z_sendmany(char *opidstr,char *coinstr,char *acname,char *srcaddr,char * } } +int32_t z_mergetoaddress(char *opidstr,char *coinstr,char *acname,char *destaddr) +{ + cJSON *retjson; char *retstr,addr[128],*opstr; int32_t retval = -1; + sprintf(addr,"[\\\"ANY_SPROUT\\\"]"); + //printf("z_sendmany from.(%s) -> %s\n",addr,destaddr); + if ( (retjson= get_komodocli(coinstr,&retstr,acname,"z_mergetoaddress",addr,destaddr,"","")) != 0 ) + { + /*{ + "remainingUTXOs": 0, + "remainingTransparentValue": 0.00000000, + "remainingNotes": 222, + "remainingShieldedValue": 5413.39093055, + "mergingUTXOs": 0, + "mergingTransparentValue": 0.00000000, + "mergingNotes": 10, + "mergingShieldedValue": 822.47447172, + "opid": "opid-f28f6261-4120-436c-aca5-859870a40a70" + }*/ + if ( (opstr= jstr(retjson,"opid")) != 0 ) + strcpy(opidstr,opstr); + retval = jint(retjson,"remainingNotes"); + fprintf(stderr,"%s\n",jprint(retjson,0)); + free_json(retjson); + } + else if ( retstr != 0 ) + { + fprintf(stderr,"z_mergetoaddress.(%s) -> opid.(%s)\n",coinstr,retstr); + strcpy(opidstr,retstr); + free(retstr); + } + return(retval); +} + int32_t empty_mempool(char *coinstr,char *acname) { cJSON *array; int32_t n; @@ -907,10 +976,25 @@ int32_t main(int32_t argc,char **argv) } zsaddr = clonestr(argv[2]); printf("%s: %s %s\n",REFCOIN_CLI,coinstr,zsaddr); - uint32_t lastopid; char coinaddr[64],zcaddr[128],opidstr[128]; int32_t finished; int64_t amount,stdamount,txfee; + uint32_t lastopid; char coinaddr[64],privkey[1024],zcaddr[128],opidstr[128]; int32_t finished; int64_t amount,stdamount,txfee; //stdamount = 500 * SATOSHIDEN; txfee = 10000; again: + if ( z_getnewaddress(zcaddr,coinstr,"","sprout") == 0 ) + { + z_exportkey(privkey,coinstr,"",zcaddr); + printf("zcaddr.(%s) -> z_exportkey.(%s)\n",zcaddr,privkey); + while ( 1 ) + { + if ( have_pending_opid(coinstr,0) != 0 ) + { + sleep(10); + continue; + } + if ( z_mergetoaddress(opidstr,coinstr,"",zcaddr) <= 0 ) + break; + } + } printf("start processing zmigrate\n"); lastopid = (uint32_t)time(NULL); finished = 0; From 97658a0c03a35073bdfe45f3922e05af1ed3ea6d Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 19 Dec 2018 09:03:54 -1100 Subject: [PATCH 0005/1145] z_mergetoaddress fix --- src/wallet/rpcwallet.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index f8b507403..f431bce81 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -4789,9 +4789,11 @@ UniValue z_mergetoaddress(const UniValue& params, bool fHelp) if (useAnySprout || useAnySapling || zaddrs.size() > 0) { // Get available notes std::vector sproutEntries; - std::vector saplingEntries; - pwalletMain->GetFilteredNotes(sproutEntries, saplingEntries, zaddrs); - + //std::vector saplingEntries; + //pwalletMain->GetFilteredNotes(sproutEntries, saplingEntries, zaddrs); + std::vector saplingEntries,skipsapling; + pwalletMain->GetFilteredNotes(sproutEntries, useAnySprout == 0 ? saplingEntries : skipsapling, zaddrs); + // If Sapling is not active, do not allow sending from a sapling addresses. if (!saplingActive && saplingEntries.size() > 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, Sapling has not activated"); From 93f18db31afd9afb3103c89b3118c3932e7ab43e Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 19 Dec 2018 09:25:38 -1100 Subject: [PATCH 0006/1145] Skip unspendable addresses in migrate --- src/cc/dapps/zmigrate.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/dapps/zmigrate.c b/src/cc/dapps/zmigrate.c index 441b51b19..6fa3c3cc8 100644 --- a/src/cc/dapps/zmigrate.c +++ b/src/cc/dapps/zmigrate.c @@ -712,6 +712,10 @@ int64_t find_onetime_amount(char *coinstr,char *coinaddr) for (i=0; i Date: Sun, 6 Jan 2019 22:10:59 +0100 Subject: [PATCH 0007/1145] Fixed a 404'd libsodium link --- depends/packages/libsodium.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/depends/packages/libsodium.mk b/depends/packages/libsodium.mk index 67e096fae..76f0d9a28 100644 --- a/depends/packages/libsodium.mk +++ b/depends/packages/libsodium.mk @@ -9,7 +9,7 @@ $(package)_config_opts= else package=libsodium $(package)_version=1.0.15 -$(package)_download_path=https://download.libsodium.org/libsodium/releases +$(package)_download_path=https://download.libsodium.org/libsodium/releases/old $(package)_file_name=$(package)-$($(package)_version).tar.gz $(package)_sha256_hash=fb6a9e879a2f674592e4328c5d9f79f082405ee4bb05cb6e679b90afe9e178f4 $(package)_dependencies= From 7d56db54d1c89218992616f271dbb320f19a5b8e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 7 Jan 2019 07:33:23 -1100 Subject: [PATCH 0008/1145] Messages --- src/net.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/net.h b/src/net.h index e2fbdb0bd..02714e20f 100644 --- a/src/net.h +++ b/src/net.h @@ -48,7 +48,7 @@ static const unsigned int MAX_INV_SZ = 50000; /** The maximum number of new addresses to accumulate before announcing. */ static const unsigned int MAX_ADDR_TO_SEND = 1000; /** Maximum length of incoming protocol messages (no message over 2 MiB is currently acceptable). */ -static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 2 * 1024 * 1024; +static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1024 * 1024; /** Maximum length of strSubVer in `version` message */ static const unsigned int MAX_SUBVERSION_LENGTH = 256; /** -listen default */ From ce5995738b3b4c5dbb953e58b4df590f0c143ffe Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 7 Jan 2019 07:43:15 -1100 Subject: [PATCH 0009/1145] Update version --- src/rpc/misc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp index 7bfb98f7b..323540790 100644 --- a/src/rpc/misc.cpp +++ b/src/rpc/misc.cpp @@ -56,7 +56,7 @@ extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; uint32_t komodo_segid32(char *coinaddr); int64_t komodo_coinsupply(int64_t *zfundsp,int64_t *sproutfundsp,int32_t height); int32_t notarizedtxid_height(char *dest,char *txidstr,int32_t *kmdnotarized_heightp); -#define KOMODO_VERSION "0.3.1" +#define KOMODO_VERSION "0.3.3" #define VERUS_VERSION "0.4.0g" extern uint16_t ASSETCHAINS_P2PPORT,ASSETCHAINS_RPCPORT; extern uint32_t ASSETCHAINS_CC; From 8e172149f632cdcb7944b563c2f0e5819b8abbf9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 8 Jan 2019 23:19:28 -1100 Subject: [PATCH 0010/1145] Add context check in connectTip --- src/main.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main.cpp b/src/main.cpp index 20f28d46a..8dcd3cc10 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3170,6 +3170,11 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin //fprintf(stderr,"checkblock failure in connectblock futureblock.%d\n",futureblock); return false; } + if ( fCheckPOW != 0 && pindex->nTime > 1548979200 && !ContextualCheckBlock(block, state, pindex->pprev) ) // activate check Feb 1, 2019 + { + fprintf(stderr,"ContextualCheckBlock failed ht.%d\n",(int32_t)pindex->GetHeight()); + return false; + } // verify that the view's current state corresponds to the previous block uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash(); From cb64a2dc5673b7e9d94704fdd34013ebbdabf669 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 8 Jan 2019 23:20:34 -1100 Subject: [PATCH 0011/1145] Activate jan 15th --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 8dcd3cc10..861fb7eab 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3170,7 +3170,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin //fprintf(stderr,"checkblock failure in connectblock futureblock.%d\n",futureblock); return false; } - if ( fCheckPOW != 0 && pindex->nTime > 1548979200 && !ContextualCheckBlock(block, state, pindex->pprev) ) // activate check Feb 1, 2019 + if ( fCheckPOW != 0 && pindex->nTime > 1547510400 && !ContextualCheckBlock(block, state, pindex->pprev) ) // activate check Jan 15, 2019 { fprintf(stderr,"ContextualCheckBlock failed ht.%d\n",(int32_t)pindex->GetHeight()); return false; From 0e49163d4af4fba54bce04c47e21c8d2e9cb2067 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 9 Jan 2019 00:04:30 -1100 Subject: [PATCH 0012/1145] Jan 15th activation of stricter block checks --- src/main.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 861fb7eab..fe6fb4030 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3170,10 +3170,12 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin //fprintf(stderr,"checkblock failure in connectblock futureblock.%d\n",futureblock); return false; } - if ( fCheckPOW != 0 && pindex->nTime > 1547510400 && !ContextualCheckBlock(block, state, pindex->pprev) ) // activate check Jan 15, 2019 + if ( fCheckPOW != 0 && !ContextualCheckBlock(block, state, pindex->pprev) ) // Activate Jan 15th, 2019 { fprintf(stderr,"ContextualCheckBlock failed ht.%d\n",(int32_t)pindex->GetHeight()); - return false; + if ( pindex->nTime > 1547510400 ) + return false; + fprintf(stderr,"grandfathered exception, until jan 15th 2019\n"); } // verify that the view's current state corresponds to the previous block From 8a5f7bdf6a35a967c0fad805424a500ce3a8aad4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 9 Jan 2019 00:05:22 -1100 Subject: [PATCH 0013/1145] Version 0.3.3b --- src/rpc/misc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp index 323540790..e29abc60e 100644 --- a/src/rpc/misc.cpp +++ b/src/rpc/misc.cpp @@ -56,7 +56,7 @@ extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; uint32_t komodo_segid32(char *coinaddr); int64_t komodo_coinsupply(int64_t *zfundsp,int64_t *sproutfundsp,int32_t height); int32_t notarizedtxid_height(char *dest,char *txidstr,int32_t *kmdnotarized_heightp); -#define KOMODO_VERSION "0.3.3" +#define KOMODO_VERSION "0.3.3b" #define VERUS_VERSION "0.4.0g" extern uint16_t ASSETCHAINS_P2PPORT,ASSETCHAINS_RPCPORT; extern uint32_t ASSETCHAINS_CC; From 1f46aa58e6913856f4a921305329b407d3af28fc Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 9 Jan 2019 01:26:25 -1100 Subject: [PATCH 0014/1145] Allow tunable maxreorg --- src/komodo_utils.h | 1 + src/main.h | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/komodo_utils.h b/src/komodo_utils.h index 19941a172..aa887bba3 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1701,6 +1701,7 @@ void komodo_args(char *argv0) } } KOMODO_STOPAT = GetArg("-stopat",0); + MAX_REORG_LENGTH = GetArg("-maxreorg",MAX_REORG_LENGTH); ASSETCHAINS_CC = GetArg("-ac_cc",0); KOMODO_CCACTIVATE = GetArg("-ac_ccactivate",0); ASSETCHAINS_PUBLIC = GetArg("-ac_public",0); diff --git a/src/main.h b/src/main.h index fdd9fcae8..775b31eb6 100644 --- a/src/main.h +++ b/src/main.h @@ -63,7 +63,7 @@ static const bool DEFAULT_ALERTS = true; /** Minimum alert priority for enabling safe mode. */ static const int ALERT_PRIORITY_SAFE_MODE = 4000; /** Maximum reorg length we will accept before we shut down and alert the user. */ -static const unsigned int MAX_REORG_LENGTH = _COINBASE_MATURITY - 1; +static unsigned int MAX_REORG_LENGTH = _COINBASE_MATURITY - 1; /** Maximum number of signature check operations in an IsStandard() P2SH script */ static const unsigned int MAX_P2SH_SIGOPS = 15; /** The maximum number of sigops we're willing to relay/mine in a single tx */ From ba1b2b5c5674af96051eb7a22ce86d1b707566d7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 9 Jan 2019 01:43:10 -1100 Subject: [PATCH 0015/1145] -Static assert --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index fe6fb4030..3d2f19b55 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4078,7 +4078,7 @@ static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMo // 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->GetHeight() - (pindexFork ? pindexFork->GetHeight() : -1) : 0; - static_assert(MAX_REORG_LENGTH > 0, "We must be able to reorg some distance"); + assert(MAX_REORG_LENGTH > 0);//, "We must be able to reorg some distance"); if (reorgLength > MAX_REORG_LENGTH) { int32_t notarizedht,prevMoMheight; uint256 notarizedhash,txid; From 9040d03af61ceec11d5c352dca337b480ae8acad Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 9 Jan 2019 02:21:47 -1100 Subject: [PATCH 0016/1145] Match WITNESS_CACHE_SIZE to maxreorg --- src/komodo_utils.h | 1 + src/wallet/wallet.h | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/komodo_utils.h b/src/komodo_utils.h index aa887bba3..d15f7d7e4 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1650,6 +1650,7 @@ uint64_t komodo_ac_block_subsidy(int nHeight) } extern int64_t MAX_MONEY; +extern unsigned int WITNESS_CACHE_SIZE; void komodo_args(char *argv0) { diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index c5cfedda8..5f040dded 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -61,7 +61,7 @@ static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000; // Should be large enough that we can expect not to reorg beyond our cache // unless there is some exceptional network disruption. #define _COINBASE_MATURITY 100 -static const unsigned int WITNESS_CACHE_SIZE = _COINBASE_MATURITY+10; +unsigned int WITNESS_CACHE_SIZE = _COINBASE_MATURITY+10; //! Size of HD seed in bytes static const size_t HD_WALLET_SEED_LENGTH = 32; From 93b616becd062079d1ed44edc9d865617f3c75b8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 9 Jan 2019 02:32:11 -1100 Subject: [PATCH 0017/1145] Move WITNESS_CACHE_SIZE --- src/komodo_globals.h | 1 + src/komodo_utils.h | 1 - src/wallet/wallet.h | 3 +-- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 3e9b84db1..ff3748729 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -44,6 +44,7 @@ struct komodo_state KOMODO_STATES[34]; #define _COINBASE_MATURITY 100 int COINBASE_MATURITY = _COINBASE_MATURITY;//100; +unsigned int WITNESS_CACHE_SIZE = _COINBASE_MATURITY+10; int32_t KOMODO_MININGTHREADS = -1,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,KOMODO_CONNECTING = -1,KOMODO_DEALERNODE,KOMODO_EXTRASATOSHI,ASSETCHAINS_FOUNDERS; int32_t KOMODO_INSYNC,KOMODO_LASTMINED,prevKOMODO_LASTMINED,KOMODO_CCACTIVATE,JUMBLR_PAUSE = 1; diff --git a/src/komodo_utils.h b/src/komodo_utils.h index d15f7d7e4..aa887bba3 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1650,7 +1650,6 @@ uint64_t komodo_ac_block_subsidy(int nHeight) } extern int64_t MAX_MONEY; -extern unsigned int WITNESS_CACHE_SIZE; void komodo_args(char *argv0) { diff --git a/src/wallet/wallet.h b/src/wallet/wallet.h index 5f040dded..7adfb4e35 100644 --- a/src/wallet/wallet.h +++ b/src/wallet/wallet.h @@ -60,8 +60,7 @@ static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000; //! Size of witness cache // Should be large enough that we can expect not to reorg beyond our cache // unless there is some exceptional network disruption. -#define _COINBASE_MATURITY 100 -unsigned int WITNESS_CACHE_SIZE = _COINBASE_MATURITY+10; +extern unsigned int WITNESS_CACHE_SIZE; //! Size of HD seed in bytes static const size_t HD_WALLET_SEED_LENGTH = 32; From 7598204bf98d5316c3dad7c40a458810b6c71d55 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 10 Jan 2019 18:49:38 -1100 Subject: [PATCH 0018/1145] Fix bip44 code --- src/chainparams.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/chainparams.cpp b/src/chainparams.cpp index a04e4131a..02b73f04b 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -92,7 +92,8 @@ public: strNetworkID = "main"; strCurrencyUnits = "KMD"; - bip44CoinType = 133; // As registered in https://github.com/satoshilabs/slips/blob/master/slip-0044.md (ZCASH, should be VRSC) + bip44CoinType = 141; // As registered in https://github.com/satoshilabs/slips/blob/master/slip-0044.md + consensus.fCoinbaseMustBeProtected = false; // true this is only true wuth Verus and enforced after block 12800 consensus.nSubsidySlowStartInterval = 20000; consensus.nSubsidyHalvingInterval = 840000; From bfd4917613ae58e6c4d49354f2efb9406aec141d Mon Sep 17 00:00:00 2001 From: ca333 Date: Sun, 20 Jan 2019 06:41:11 +0100 Subject: [PATCH 0019/1145] [update] cclib OSX makefile --- src/cc/Makefile | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/Makefile b/src/cc/Makefile index 3522a0c08..a3c54d81d 100644 --- a/src/cc/Makefile +++ b/src/cc/Makefile @@ -1,7 +1,8 @@ SHELL = /bin/sh CC = gcc +CC_DARWIN = g++-6 CC_WIN = x86_64-w64-mingw32-gcc-posix -CFLAGS_DARWIN = -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c +CFLAGS_DARWIN = -std=c++11 -arch x86_64 -I/usr/local/Cellar/gcc\@6/6.4.0_2/include/c++/6.4.0/ -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -c -Wl,-undefined -Wl,dynamic_lookup CFLAGS = -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c CFLAGS_WIN = -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c DEBUGFLAGS = -O0 -D _DEBUG @@ -19,13 +20,13 @@ all: $(TARGET) $(TARGET): $(SOURCES) $(info Building cclib to src/) ifeq ($(OS),Darwin) - $(CC) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET) $(SOURCES) + $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET) $(SOURCES) else ifeq ($(OS),Linux) $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) $(SOURCES) #else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host else - $(info else) - #$(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) $(SOURCES) + $(info WINDOWS) + $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) $(SOURCES) endif clean: From 28195d218b86a35b4d61993ba0e72661c85bdef1 Mon Sep 17 00:00:00 2001 From: ca333 Date: Sun, 20 Jan 2019 07:11:58 +0100 Subject: [PATCH 0020/1145] [add] cclib README --- src/cc/README.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 src/cc/README.md diff --git a/src/cc/README.md b/src/cc/README.md new file mode 100644 index 000000000..d12a75c43 --- /dev/null +++ b/src/cc/README.md @@ -0,0 +1,7 @@ +## CCLIB +Please follow the below instructions to build the cryptoconditions library into the Komodo source directory `komodo/src` - supported operating systems are Linux, OSX and Windows (mingw crossbuild): + +``` +make clean +make +``` From 923b87a6ecf93b294522207f668d3a3be5be75fc Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 21 Jan 2019 13:04:18 +0100 Subject: [PATCH 0021/1145] [add] dylib --- src/cc/Makefile | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/Makefile b/src/cc/Makefile index a3c54d81d..92fbe0da9 100644 --- a/src/cc/Makefile +++ b/src/cc/Makefile @@ -2,7 +2,7 @@ SHELL = /bin/sh CC = gcc CC_DARWIN = g++-6 CC_WIN = x86_64-w64-mingw32-gcc-posix -CFLAGS_DARWIN = -std=c++11 -arch x86_64 -I/usr/local/Cellar/gcc\@6/6.4.0_2/include/c++/6.4.0/ -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -c -Wl,-undefined -Wl,dynamic_lookup +CFLAGS_DARWIN = -std=c++11 -arch x86_64 -I/usr/local/Cellar/gcc\@6/6.4.0_2/include/c++/6.4.0/ -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -c -Wl,-undefined -Wl,dynamic_lookup -dynamiclib CFLAGS = -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c CFLAGS_WIN = -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c DEBUGFLAGS = -O0 -D _DEBUG @@ -10,8 +10,9 @@ RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program $(info $(OS)) OS := $(shell uname -s) $(info $(OS)) -TARGET = ../cclib.so -TARGET_WIN = ../cclib.dll +TARGET = ../libcc.so +TARGET_DARWIN = ../libcc.dylib +TARGET_WIN = ../libcc.dll SOURCES = cclib.cpp #HEADERS = $(shell echo ../cryptoconditions/include/*.h) @@ -20,7 +21,7 @@ all: $(TARGET) $(TARGET): $(SOURCES) $(info Building cclib to src/) ifeq ($(OS),Darwin) - $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET) $(SOURCES) + $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET_DARWIN) $(SOURCES) else ifeq ($(OS),Linux) $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) $(SOURCES) #else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host From d8289cd12813f6f440559541e5f04d62ddfc8ae5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 21 Jan 2019 23:13:58 -1100 Subject: [PATCH 0022/1145] Test --- src/miner.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/miner.cpp b/src/miner.cpp index 01ff9da0c..ab0a770c1 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1707,6 +1707,7 @@ void static BitcoinMiner() for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&h)[z]); fprintf(stderr," Invalid block mined, try again\n"); + break; return(false); } KOMODO_CHOSEN_ONE = 1; From ba46fa56d9734204ee7ae748980960130d504810 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 21 Jan 2019 23:18:38 -1100 Subject: [PATCH 0023/1145] Got invalid --- src/miner.cpp | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/miner.cpp b/src/miner.cpp index ab0a770c1..05d324075 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1604,16 +1604,12 @@ void static BitcoinMiner() fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%% ht.%d\n",percPoS,(int32_t)ASSETCHAINS_STAKED,Mining_height); } } + int32_t gotinvalid = 0; while (true) { - /*if ( KOMODO_INSYNC == 0 ) - { - KOMODO_LONGESTCHAIN = komodo_longestchain(); - fprintf(stderr,"Mining when blockchain might not be in sync longest.%d vs %d\n",KOMODO_LONGESTCHAIN,Mining_height); - if ( KOMODO_LONGESTCHAIN != 0 && Mining_height >= KOMODO_LONGESTCHAIN ) - KOMODO_INSYNC = Mining_height; - sleep(3); - }*/ + fprintf(stderr,"gotinvalid.%d\n",gotinvalid); + if ( gotinvalid != 0 ) + break; komodo_longestchain(); // Hash state KOMODO_CHOSEN_ONE = 0; @@ -1707,7 +1703,7 @@ void static BitcoinMiner() for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&h)[z]); fprintf(stderr," Invalid block mined, try again\n"); - break; + gotinvalid = 1; return(false); } KOMODO_CHOSEN_ONE = 1; From 8706511de79c1fe073f023390f03397562fd7507 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 21 Jan 2019 23:19:29 -1100 Subject: [PATCH 0024/1145] Static --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index 05d324075..9db051d78 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1604,7 +1604,7 @@ void static BitcoinMiner() fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%% ht.%d\n",percPoS,(int32_t)ASSETCHAINS_STAKED,Mining_height); } } - int32_t gotinvalid = 0; + static int32_t gotinvalid = 0; while (true) { fprintf(stderr,"gotinvalid.%d\n",gotinvalid); From c2d4129409d7c1de25d085372392ebb83e26b7c1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 21 Jan 2019 23:36:41 -1100 Subject: [PATCH 0025/1145] Got invalid as global --- src/miner.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index 9db051d78..a6ef345bb 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1396,6 +1396,8 @@ void static BitcoinMiner_noeq() miningTimer.stop(); } +int32_t gotinvalid; + #ifdef ENABLE_WALLET void static BitcoinMiner(CWallet *pwallet) #else @@ -1604,7 +1606,7 @@ void static BitcoinMiner() fprintf(stderr," PoW for staked coin PoS %d%% vs target %d%% ht.%d\n",percPoS,(int32_t)ASSETCHAINS_STAKED,Mining_height); } } - static int32_t gotinvalid = 0; + gotinvalid = 0; while (true) { fprintf(stderr,"gotinvalid.%d\n",gotinvalid); From 6bfe8357db2a8d8c2d119b6cb07932d51115e4d3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 21 Jan 2019 23:40:36 -1100 Subject: [PATCH 0026/1145] -print --- src/miner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miner.cpp b/src/miner.cpp index a6ef345bb..7ffcaebc2 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -1609,7 +1609,7 @@ void static BitcoinMiner() gotinvalid = 0; while (true) { - fprintf(stderr,"gotinvalid.%d\n",gotinvalid); + //fprintf(stderr,"gotinvalid.%d\n",gotinvalid); if ( gotinvalid != 0 ) break; komodo_longestchain(); From a84a48e48ffcc6d13998b91296949a52fdc1a63f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 21 Jan 2019 23:43:01 -1100 Subject: [PATCH 0027/1145] Reset staker for marmara --- 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 c9a91d289..1fe6af409 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -2120,7 +2120,7 @@ int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blockt { CBlockIndex* pblockindex = chainActive[tipindex->GetHeight()]; CBlock block; CTxDestination addressout; - if( ReadBlockFromDisk(block, pblockindex, 1) && komodo_WhoStaked(&block, addressout) != 0 && IsMine(*pwalletMain,addressout) != 0 ) + if( ASSETCHAINS_MARMARA != 0 || ReadBlockFromDisk(block, pblockindex, 1) && komodo_WhoStaked(&block, addressout) != 0 && IsMine(*pwalletMain,addressout) != 0 ) { resetstaker = true; fprintf(stderr, "Reset ram staker after mining a block!\n"); From 7e6d9ff0650c24c7d7a672a83defd934aba2edf5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 21 Jan 2019 23:43:38 -1100 Subject: [PATCH 0028/1145] () --- 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 1fe6af409..26f010d1d 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -2120,7 +2120,7 @@ int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blockt { CBlockIndex* pblockindex = chainActive[tipindex->GetHeight()]; CBlock block; CTxDestination addressout; - if( ASSETCHAINS_MARMARA != 0 || ReadBlockFromDisk(block, pblockindex, 1) && komodo_WhoStaked(&block, addressout) != 0 && IsMine(*pwalletMain,addressout) != 0 ) + if( ASSETCHAINS_MARMARA != 0 || (ReadBlockFromDisk(block, pblockindex, 1) && komodo_WhoStaked(&block, addressout) != 0 && IsMine(*pwalletMain,addressout) != 0) ) { resetstaker = true; fprintf(stderr, "Reset ram staker after mining a block!\n"); From 8496dc63a4909ff47032ae227830c32284e5c773 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 21 Jan 2019 23:44:38 -1100 Subject: [PATCH 0029/1145] -print --- 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 26f010d1d..c530db4fb 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -2120,7 +2120,9 @@ int32_t komodo_staked(CMutableTransaction &txNew,uint32_t nBits,uint32_t *blockt { CBlockIndex* pblockindex = chainActive[tipindex->GetHeight()]; CBlock block; CTxDestination addressout; - if( ASSETCHAINS_MARMARA != 0 || (ReadBlockFromDisk(block, pblockindex, 1) && komodo_WhoStaked(&block, addressout) != 0 && IsMine(*pwalletMain,addressout) != 0) ) + if ( ASSETCHAINS_MARMARA != 0 ) + resetstaker = true; + else if( ReadBlockFromDisk(block, pblockindex, 1) && komodo_WhoStaked(&block, addressout) != 0 && IsMine(*pwalletMain,addressout) != 0 ) { resetstaker = true; fprintf(stderr, "Reset ram staker after mining a block!\n"); From 088ea2bfb49f19ab83c8bd5ecc66f138f73d988e Mon Sep 17 00:00:00 2001 From: ca333 Date: Wed, 23 Jan 2019 19:02:05 +0100 Subject: [PATCH 0030/1145] update cclib to match autotools/libtools naming convention --- src/Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index 96ab3f1fa..ad9842f09 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -572,7 +572,7 @@ komodod_LDADD += \ $(LIBVERUS_CRYPTO) \ $(LIBVERUS_PORTABLE_CRYPTO) \ $(LIBZCASH_LIBS) \ - cclib.so + libcc.so if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) From 0d1effd93b42f2dcd8991ecd996a3c10fa410ca7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 23 Jan 2019 22:04:21 -1100 Subject: [PATCH 0031/1145] Text --- src/sendalert.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sendalert.cpp b/src/sendalert.cpp index 700146338..6525cb356 100644 --- a/src/sendalert.cpp +++ b/src/sendalert.cpp @@ -103,7 +103,7 @@ void ThreadSendAlert() // 4000 or higher will put the RPC into safe mode alert.nPriority = 4000; alert.strComment = ""; - alert.strStatusBar = "Your client version has degraded networking behavior. Please update to the most recent version of Verus (0.3.2 or later)."; + alert.strStatusBar = "Your client version has degraded networking behavior. Please update to the most recent version of Komodo (0.3.3 or later)."; alert.strRPCError = alert.strStatusBar; // Set specific client version/versions here. If setSubVer is empty, no filtering on subver is done: From c3df1b8747750b8ef4a43738be8cfc28f8dffc88 Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Thu, 24 Jan 2019 17:16:42 +0800 Subject: [PATCH 0032/1145] add auto purge of orphans from before notarisation. --- src/komodo.h | 2 ++ src/main.cpp | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.h | 2 +- 3 files changed, 69 insertions(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 4a8bd7d96..62310a0ed 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -707,6 +707,8 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr 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 (RemoveOrphanedBlocks(*notarizedheightp)) + fprintf(stderr, "Sucessfully removed all known orphaned blocks before height %d\n",*notarizedheightp); if ( ASSETCHAINS_SYMBOL[0] == 0 ) { if ( signedfp == 0 ) diff --git a/src/main.cpp b/src/main.cpp index 614f13d44..a2980dea8 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1979,6 +1979,72 @@ bool GetAddressUnspent(uint160 addressHash, int type, return true; } +struct CompareBlocksByHeightMain +{ + bool operator()(const CBlockIndex* a, const CBlockIndex* b) const + { + /* Make sure that unequal blocks with the same height do not compare + equal. Use the pointers themselves to make a distinction. */ + + if (a->GetHeight() != b->GetHeight()) + return (a->GetHeight() > b->GetHeight()); + + return a < b; + } +}; + +bool RemoveOrphanedBlocks(int32_t notarized_height) +{ + LOCK(cs_main); + std::vector prunedblocks; + std::set setTips; + int32_t n = 0; + // get notarised timestamp and use this as a backup incase the forked block has no height. + // we -600 to make sure the time is within future block constraints. + uint32_t notarized_timestamp = komodo_heightstamp(notarized_height)-600; + fprintf(stderr, "removing oprhans from before %d\n", notarized_height); + // Most of this code is a direct copy from GetChainTips RPC. Which gives a return of all + // blocks that are not in the main chain. + BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) + { + n++; + setTips.insert(item.second); + } + n = 0; + BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) + { + const CBlockIndex* pprev=0; + n++; + if ( item.second != 0 ) + pprev = item.second->pprev; + if (pprev) + setTips.erase(pprev); + } + const CBlockIndex *forked; + BOOST_FOREACH(const CBlockIndex* block, setTips) + { + // We skip anything over notarised height to avoid breaking normal consensus rules. + if ( block->GetHeight() > notarized_height || block->nTime > notarized_timestamp ) + continue; + // We can also check if the block is in the active chain as a backup test. + forked = chainActive.FindFork(block); + // Here we save each forked block to a vector for removal later. + if ( forked != 0 ) + prunedblocks.push_back(block); + } + if (pblocktree->EraseBatchSync(prunedblocks)) + { + // Blocks cleared from disk succesfully, using internal DB batch erase function. Which exists, but has never been used before. + // We need to try and clear the block index from mapBlockIndex now, otherwise node will need a restart. + BOOST_FOREACH(const CBlockIndex* block, prunedblocks) + { + mapBlockIndex.erase(block->GetBlockHash()); + } + return true; + } + return false; +} + /*uint64_t myGettxout(uint256 hash,int32_t n) { CCoins coins; diff --git a/src/main.h b/src/main.h index 463c91237..35c01c23a 100644 --- a/src/main.h +++ b/src/main.h @@ -806,7 +806,7 @@ bool GetAddressUnspent(uint160 addressHash, int type, bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart); bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos,bool checkPOW); bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex,bool checkPOW); - +bool RemoveOrphanedBlocks(int32_t notarized_height); /** Functions for validating blocks and updating the block tree */ From effb3a2a10269cc627c80baf225375cd684f7cc4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 23 Jan 2019 22:20:21 -1100 Subject: [PATCH 0033/1145] Tweak error check --- src/main.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index a2980dea8..1da977ab9 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4658,7 +4658,7 @@ bool CheckBlockHeader(int32_t *futureblockp,int32_t height,CBlockIndex *pindex, *futureblockp = 0; if (blockhdr.GetBlockTime() > GetAdjustedTime() + 60) { - CBlockIndex *tipindex; + /*CBlockIndex *tipindex; //fprintf(stderr,"ht.%d future block %u vs time.%u + 60\n",height,(uint32_t)blockhdr.GetBlockTime(),(uint32_t)GetAdjustedTime()); if ( (tipindex= chainActive.Tip()) != 0 && tipindex->GetBlockHash() == blockhdr.hashPrevBlock && blockhdr.GetBlockTime() < GetAdjustedTime() + 60 + 5 ) { @@ -4667,9 +4667,9 @@ bool CheckBlockHeader(int32_t *futureblockp,int32_t height,CBlockIndex *pindex, sleep(1); //fprintf(stderr,"now its valid\n"); } - else + else*/ { - if (blockhdr.GetBlockTime() < GetAdjustedTime() + 600) + if (blockhdr.GetBlockTime() < GetAdjustedTime() + 300) *futureblockp = 1; //LogPrintf("CheckBlockHeader block from future %d error",blockhdr.GetBlockTime() - GetAdjustedTime()); return false; //state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),REJECT_INVALID, "time-too-new"); From 1a9476e844df4d83dfc4c33924333e0ae95bd782 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 23 Jan 2019 22:22:52 -1100 Subject: [PATCH 0034/1145] +/- prints --- src/komodo.h | 4 +++- src/main.cpp | 7 ++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/komodo.h b/src/komodo.h index 62310a0ed..35fee05ad 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -708,7 +708,9 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr 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 (RemoveOrphanedBlocks(*notarizedheightp)) - fprintf(stderr, "Sucessfully removed all known orphaned blocks before height %d\n",*notarizedheightp); + { + //fprintf(stderr, "Sucessfully removed all known orphaned blocks before height %d\n",*notarizedheightp); + } if ( ASSETCHAINS_SYMBOL[0] == 0 ) { if ( signedfp == 0 ) diff --git a/src/main.cpp b/src/main.cpp index 1da977ab9..be2317891 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1998,12 +1998,11 @@ bool RemoveOrphanedBlocks(int32_t notarized_height) LOCK(cs_main); std::vector prunedblocks; std::set setTips; - int32_t n = 0; + int32_t m=0,n = 0; // get notarised timestamp and use this as a backup incase the forked block has no height. // we -600 to make sure the time is within future block constraints. uint32_t notarized_timestamp = komodo_heightstamp(notarized_height)-600; - fprintf(stderr, "removing oprhans from before %d\n", notarized_height); - // Most of this code is a direct copy from GetChainTips RPC. Which gives a return of all + // Most of this code is a direct copy from GetChainTips RPC. Which gives a return of all // blocks that are not in the main chain. BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) { @@ -2038,8 +2037,10 @@ bool RemoveOrphanedBlocks(int32_t notarized_height) // We need to try and clear the block index from mapBlockIndex now, otherwise node will need a restart. BOOST_FOREACH(const CBlockIndex* block, prunedblocks) { + m++; mapBlockIndex.erase(block->GetBlockHash()); } + fprintf(stderr, "%s removed %d of %d orphans from before %d\n",ASSETCHAINS_SYMBOL,m,n, notarized_height); return true; } return false; From 2a36abaf5d0a50ad612a04ac7fab2f248a54e7e4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 23 Jan 2019 22:51:10 -1100 Subject: [PATCH 0035/1145] skip Zero pruned blocks --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index be2317891..4bd7ed3e3 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2031,7 +2031,7 @@ bool RemoveOrphanedBlocks(int32_t notarized_height) if ( forked != 0 ) prunedblocks.push_back(block); } - if (pblocktree->EraseBatchSync(prunedblocks)) + if (prunedblocks.size() > 0 && pblocktree->EraseBatchSync(prunedblocks)) { // Blocks cleared from disk succesfully, using internal DB batch erase function. Which exists, but has never been used before. // We need to try and clear the block index from mapBlockIndex now, otherwise node will need a restart. @@ -2040,7 +2040,7 @@ bool RemoveOrphanedBlocks(int32_t notarized_height) m++; mapBlockIndex.erase(block->GetBlockHash()); } - fprintf(stderr, "%s removed %d of %d orphans from before %d\n",ASSETCHAINS_SYMBOL,m,n, notarized_height); + fprintf(stderr, "%s removed %d orphans from %d blocks before %d\n",ASSETCHAINS_SYMBOL,m,n, notarized_height); return true; } return false; From d192f1d1f35db442f7a747288a51db671fd34701 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 23 Jan 2019 23:46:45 -1100 Subject: [PATCH 0036/1145] Rawtx->hex for marmara --- src/cc/marmara.cpp | 12 ++++++------ src/main.cpp | 1 - 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/cc/marmara.cpp b/src/cc/marmara.cpp index 8f8de12e2..0e301ba97 100644 --- a/src/cc/marmara.cpp +++ b/src/cc/marmara.cpp @@ -496,7 +496,7 @@ UniValue MarmaraLock(uint64_t txfee,int64_t amount,int32_t height) else { result.push_back(Pair("result",(char *)"success")); - result.push_back(Pair("rawtx",rawtx)); + result.push_back(Pair("hex",rawtx)); return(result); } } else errorstr = (char *)"insufficient funds"; @@ -600,7 +600,7 @@ UniValue MarmaraSettlement(uint64_t txfee,uint256 refbatontxid) mtx.vout.push_back(MakeCC1of2vout(EVAL_MARMARA,change,Marmarapk,pk)); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,MarmaraLoopOpret('S',createtxid,mypk,0,refmatures,currency),pubkeys); result.push_back(Pair("result",(char *)"success")); - result.push_back(Pair("rawtx",rawtx)); + result.push_back(Pair("hex",rawtx)); return(result); } else remaining -= inputsum; if ( mtx.vin.size() >= CC_MAXVINS - MARMARA_VINS ) @@ -616,7 +616,7 @@ UniValue MarmaraSettlement(uint64_t txfee,uint256 refbatontxid) rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,MarmaraLoopOpret('D',createtxid,mypk,-remaining,refmatures,currency),pubkeys); result.push_back(Pair("result",(char *)"error")); result.push_back(Pair("error",(char *)"insufficient funds")); - result.push_back(Pair("rawtx",rawtx)); + result.push_back(Pair("hex",rawtx)); result.push_back(Pair("remaining",ValueFromAmount(remaining))); } else @@ -731,7 +731,7 @@ UniValue MarmaraReceive(uint64_t txfee,CPubKey senderpk,int64_t amount,std::stri else { result.push_back(Pair("result",(char *)"success")); - result.push_back(Pair("rawtx",rawtx)); + result.push_back(Pair("hex",rawtx)); result.push_back(Pair("funcid","R")); result.push_back(Pair("createtxid",createtxid.GetHex())); if ( batontxid != zeroid ) @@ -787,7 +787,7 @@ UniValue MarmaraIssue(uint64_t txfee,uint8_t funcid,CPubKey receiverpk,int64_t a else { result.push_back(Pair("result",(char *)"success")); - result.push_back(Pair("rawtx",rawtx)); + result.push_back(Pair("hex",rawtx)); char str[2]; str[0] = funcid, str[1] = 0; result.push_back(Pair("funcid",str)); result.push_back(Pair("createtxid",createtxid.GetHex())); @@ -1025,7 +1025,7 @@ UniValue MarmaraPoolPayout(uint64_t txfee,int32_t firstheight,double perc,char * else { result.push_back(Pair("result",(char *)"success")); - result.push_back(Pair("rawtx",rawtx)); + result.push_back(Pair("hex",rawtx)); if ( totalpayout > 0 && total > totalpayout-txfee ) { result.push_back(Pair("firstheight",firstheight)); diff --git a/src/main.cpp b/src/main.cpp index 4bd7ed3e3..b4f0acef0 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5662,7 +5662,6 @@ bool static LoadBlockIndexDB() if (pindex->nStatus & BLOCK_HAVE_DATA) { setBlkDataFiles.insert(pindex->nFile); } - //komodo_pindex_init(pindex,(int32_t)pindex->GetHeight()); } //fprintf(stderr,"load blockindexDB %u\n",(uint32_t)time(NULL)); for (std::set::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) From 0f6ee83311bad26912256c7e6b9080d66c5a9b05 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 01:44:20 -1100 Subject: [PATCH 0037/1145] Tmp files --- src/chain.h | 1 + src/main.cpp | 79 +++++++++++++++++++++++++++++++++++++--------------- 2 files changed, 58 insertions(+), 22 deletions(-) diff --git a/src/chain.h b/src/chain.h index 49b206480..45db77720 100644 --- a/src/chain.h +++ b/src/chain.h @@ -115,6 +115,7 @@ enum BlockStatus: uint32_t { BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD, BLOCK_ACTIVATES_UPGRADE = 128, //! block activates a network upgrade + BLOCK_IN_TMPFILE = 256 }; //! Short-hand for the highest consensus validity we implement. diff --git a/src/main.cpp b/src/main.cpp index b4f0acef0..29096308b 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -76,6 +76,7 @@ using namespace std; * Global state */ +#define TMPFILE_START 100000000 CCriticalSection cs_main; extern uint8_t NOTARY_PUBKEY33[33]; extern int32_t KOMODO_LOADINGBLOCKS,KOMODO_LONGESTCHAIN,KOMODO_INSYNC,KOMODO_CONNECTING,KOMODO_EXTRASATOSHI; @@ -182,8 +183,9 @@ namespace { multimap mapBlocksUnlinked; CCriticalSection cs_LastBlockFile; - std::vector vinfoBlockFile; + std::vector vinfoBlockFile,tmpBlockFiles; int nLastBlockFile = 0; + int nLastTmpFile = 0; /** Global flag to indicate we should check to see if there are * block/undo files that should be deleted. Set on startup * or if we allocate more file space when we're in prune mode @@ -3256,6 +3258,17 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin return false; fprintf(stderr,"grandfathered exception, until jan 15th 2019\n"); } + if ( (pindex->nStatus & BLOCK_IN_TMPFILE) != 0 ) + { + unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); + CDiskBlockPos blockPos; + if (!FindBlockPos(1,state, blockPos, nBlockSize+8, pindex->GetHeight(), block.GetBlockTime(),false)) + return error("ConnectBlock(): FindBlockPos failed"); + if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) + return error("ConnectBlock(): FindBlockPos failed"); + pindex->nStatus &= (~BLOCK_IN_TMPFILE); + fprintf(stderr,"added ht.%d copy of tmpfile\n",pindex->GetHeight()); + } // verify that the view's current state corresponds to the previous block uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash(); if ( hashPrevBlock != view.GetBestBlock() ) @@ -4550,43 +4563,57 @@ bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBl return true; } -bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false) +bool FindBlockPos(int32_t tmpflag,CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false) { + std::vector *ptr; int *lastfilep; LOCK(cs_LastBlockFile); - unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile; - if (vinfoBlockFile.size() <= nFile) { - vinfoBlockFile.resize(nFile + 1); + unsigned int nFile; + if ( tmpflag != 0 ) + { + ptr = &tmpBlockFiles; + nFile = nLastTmpFile; + lastfilep = &nLastTmpFile; + } + else + { + ptr = &vinfoBlockFile; + lastfilep = &nLastBlockFile; + nFile = fKnown ? pos.nFile : nLastBlockFile; + if (vinfoBlockFile.size() <= nFile) { + vinfoBlockFile.resize(nFile + 1); + } } - if (!fKnown) { - while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) { + while ((*ptr)[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) { nFile++; - if (vinfoBlockFile.size() <= nFile) { - vinfoBlockFile.resize(nFile + 1); + if ((*ptr).size() <= nFile) { + (*ptr).resize(nFile + 1); } } - pos.nFile = nFile; - pos.nPos = vinfoBlockFile[nFile].nSize; + pos.nFile = nFile + tmpflag*TMPFILE_START; + pos.nPos = (*ptr)[nFile].nSize; + if ( tmpflag != 0 ) + fprintf(stderr,"pos.nFile %d nPos %u\n",pos.nFile,pos.nPos); } - if (nFile != nLastBlockFile) { + if (nFile != *lastfilep) { if (!fKnown) { - LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString()); + LogPrintf("Leaving block file %i: %s\n", nFile, (*ptr)[nFile].ToString()); } FlushBlockFile(!fKnown); - nLastBlockFile = nFile; + *lastfilep = nFile; } - vinfoBlockFile[nFile].AddBlock(nHeight, nTime); + (*ptr)[nFile].AddBlock(nHeight, nTime); if (fKnown) - vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize); + (*ptr)[nFile].nSize = std::max(pos.nPos + nAddSize, (*ptr)[nFile].nSize); else - vinfoBlockFile[nFile].nSize += nAddSize; + (*ptr)[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; + unsigned int nNewChunks = ((*ptr)[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; if (nNewChunks > nOldChunks) { if (fPruneMode) fCheckForPruning = true; @@ -4603,12 +4630,17 @@ bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAdd } } - setDirtyFileInfo.insert(nFile); + setDirtyFileInfo.insert(nFile + tmpflag*TMPFILE_START); return true; } bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize) { + if ( nFile >= TMPFILE_START ) + { + fprintf(stderr,"FindUndoPos unexpected tmpfile %d\n",nFile); + return(false); + } pos.nFile = nFile; LOCK(cs_LastBlockFile); @@ -5171,13 +5203,14 @@ bool AcceptBlock(int32_t *futureblockp,CBlock& block, CValidationState& state, C CDiskBlockPos blockPos; if (dbp != NULL) blockPos = *dbp; - if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL)) + if (!FindBlockPos(1,state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL)) return error("AcceptBlock(): FindBlockPos failed"); if (dbp == NULL) if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) AbortNode(state, "Failed to write block"); if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) return error("AcceptBlock(): ReceivedBlockTransactions failed"); + pindex->nStatus |= BLOCK_IN_TMPFILE; } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error: ") + e.what()); } @@ -5495,7 +5528,7 @@ bool CheckDiskSpace(uint64_t nAdditionalBytes) FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly) { - static int32_t didinit[64]; + static int32_t didinit[256]; if (pos.IsNull()) return NULL; boost::filesystem::path path = GetBlockPosFilename(pos, prefix); @@ -6002,6 +6035,7 @@ void UnloadBlockIndex() nSyncStarted = 0; mapBlocksUnlinked.clear(); vinfoBlockFile.clear(); + tmpBlockFiles.clear(); nLastBlockFile = 0; nBlockSequenceId = 1; mapBlockSource.clear(); @@ -6037,6 +6071,7 @@ bool LoadBlockIndex() bool InitBlockIndex() { const CChainParams& chainparams = Params(); LOCK(cs_main); + tmpBlockFiles.clear(); // Initialize global variables that cannot be constructed at startup. recentRejects.reset(new CRollingBloomFilter(120000, 0.000001)); @@ -6069,7 +6104,7 @@ bool InitBlockIndex() { unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); CDiskBlockPos blockPos; CValidationState state; - if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime())) + if (!FindBlockPos(0,state, blockPos, nBlockSize+8, 0, block.GetBlockTime())) return error("LoadBlockIndex(): FindBlockPos failed"); if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) return error("LoadBlockIndex(): writing genesis block to disk failed"); From 82bc38fabf051317f9b1b6ca230c5ffa3cdb4e4e Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 01:51:33 -1100 Subject: [PATCH 0038/1145] Syntax --- src/main.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 29096308b..9d4e1f243 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3226,6 +3226,7 @@ static int64_t nTimeConnect = 0; static int64_t nTimeIndex = 0; static int64_t nTimeCallbacks = 0; static int64_t nTimeTotal = 0; +bool FindBlockPos(int32_t tmpflag,CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false); bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck,bool fCheckPOW) { @@ -3264,7 +3265,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin CDiskBlockPos blockPos; if (!FindBlockPos(1,state, blockPos, nBlockSize+8, pindex->GetHeight(), block.GetBlockTime(),false)) return error("ConnectBlock(): FindBlockPos failed"); - if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) + if (!WriteBlockToDisk((CBlock)block, blockPos, chainparams.MessageStart())) return error("ConnectBlock(): FindBlockPos failed"); pindex->nStatus &= (~BLOCK_IN_TMPFILE); fprintf(stderr,"added ht.%d copy of tmpfile\n",pindex->GetHeight()); From 669f5c4d391f112dc1c549703c8297547196f31d Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 01:55:15 -1100 Subject: [PATCH 0039/1145] Const --- src/main.cpp | 4 ++-- src/main.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 9d4e1f243..43cca5266 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2195,7 +2195,7 @@ bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock // CBlock and CBlockIndex // -bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart) +bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart) { // Open history file to append CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION); @@ -3265,7 +3265,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin CDiskBlockPos blockPos; if (!FindBlockPos(1,state, blockPos, nBlockSize+8, pindex->GetHeight(), block.GetBlockTime(),false)) return error("ConnectBlock(): FindBlockPos failed"); - if (!WriteBlockToDisk((CBlock)block, blockPos, chainparams.MessageStart())) + if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) return error("ConnectBlock(): FindBlockPos failed"); pindex->nStatus &= (~BLOCK_IN_TMPFILE); fprintf(stderr,"added ht.%d copy of tmpfile\n",pindex->GetHeight()); diff --git a/src/main.h b/src/main.h index 35c01c23a..40170fa70 100644 --- a/src/main.h +++ b/src/main.h @@ -803,7 +803,7 @@ bool GetAddressUnspent(uint160 addressHash, int type, std::vector > &unspentOutputs); /** Functions for disk access for blocks */ -bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart); +bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart); bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos,bool checkPOW); bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex,bool checkPOW); bool RemoveOrphanedBlocks(int32_t notarized_height); From 3c1e3aede1cfd767d6c7d6f25f328600de3e88c4 Mon Sep 17 00:00:00 2001 From: Anton Lysakov Date: Thu, 24 Jan 2019 19:55:55 +0700 Subject: [PATCH 0040/1145] initial heir tests --- qa/pull-tester/cc-tests.sh | 1 + qa/rpc-tests/cryptoconditions_heir.py | 121 ++++++++++++++++++++++++++ 2 files changed, 122 insertions(+) create mode 100755 qa/rpc-tests/cryptoconditions_heir.py diff --git a/qa/pull-tester/cc-tests.sh b/qa/pull-tester/cc-tests.sh index 9bc8c155d..742763f1d 100755 --- a/qa/pull-tester/cc-tests.sh +++ b/qa/pull-tester/cc-tests.sh @@ -18,6 +18,7 @@ testScripts=( 'cryptoconditions_rewards.py' 'cryptoconditions_token.py' #'cryptoconditions_gateways.py' + 'cryptoconditions_hair.py' # TODO: cant reconnect nodes back in channels test because of crash (seems regtest only specific) 'cryptoconditions_channels.py' ); diff --git a/qa/rpc-tests/cryptoconditions_heir.py b/qa/rpc-tests/cryptoconditions_heir.py new file mode 100755 index 000000000..95b90b397 --- /dev/null +++ b/qa/rpc-tests/cryptoconditions_heir.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python2 +# Copyright (c) 2018 SuperNET developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. + + +import time +from test_framework.test_framework import CryptoconditionsTestFramework +from test_framework.authproxy import JSONRPCException +from test_framework.util import assert_equal, assert_greater_than, \ + initialize_chain_clean, initialize_chain, start_nodes, start_node, connect_nodes_bi, \ + stop_nodes, sync_blocks, sync_mempools, wait_bitcoinds, rpc_port, assert_raises +from cryptoconditions import assert_success, assert_error, generate_random_string + + +class CryptoconditionsHeirTest(CryptoconditionsTestFramework): + + def run_heir_tests(self): + + rpc = self.nodes[0] + rpc1 = self.nodes[1] + + result = rpc.heiraddress() + assert_success(result) + # verify all keys look like valid AC addrs, could be better + for x in ['myCCaddress', 'HeirCCaddress', 'Heirmarker', 'myaddress']: + assert_equal(result[x][0], 'R') + + result = rpc.heiraddress(self.pubkey) + assert_success(result) + # test that additional CCaddress key is returned + for x in ['myCCaddress', 'HeirCCaddress', 'Heirmarker', 'myaddress', 'CCaddress']: + assert_equal(result[x][0], 'R') + + # getting empty heir list + result = rpc.heirlist() + assert_equal(len(result), 1) + assert_success(result) + + # valid heirfund case with coins + result = rpc.heirfund("0", "1000", "UNITHEIR", self.pubkey1, "10") + assert_success(result) + + heir_fund_txid = self.send_and_mine(result["hextx"], rpc) + assert heir_fund_txid, "got heir funding txid" + + # heir fund txid should be in heirlist now + result = rpc.heirlist() + assert_equal(len(result), 2) + assert_success(result) + assert_equal(result["fundingtxid"], heir_fund_txid) + + # checking heirinfo + result = rpc.heirinfo(heir_fund_txid) + assert_success(result) + assert_equal(result["fundingtxid"], heir_fund_txid) + assert_equal(result["name"], "UNITHEIR") + assert_equal(result["owner"], self.pubkey) + assert_equal(result["heir"], self.pubkey1) + assert_equal(result["funding total in coins"], "1000.00000000") + assert_equal(result["funding available in coins"], "1000.00000000") + assert_equal(result["inactivity time setting, sec"], "10") + assert_equal(result["spending allowed for the heir"], "false") + + # TODO: heirlist keys are duplicating now + + # waiting for 11 seconds to be sure that needed time passed for heir claiming + time.sleep(11) + rpc.generate(1) + self.sync_all() + result = rpc.heirinfo(heir_fund_txid) + assert_equal(result["funding available in coins"], "1000.00000000") + assert_equal(result["spending allowed for the heir"], "true") + + # have to check that second node have coins to cover txfee at least + rpc.sendtoaddress(rpc1.getnewaddress(), 1) + rpc.sendtoaddress(rpc1.getnewaddress(), 1) + rpc.generate(2) + self.sync_all() + second_node_balance = rpc1.getbalance() + assert_greater_than(second_node_balance, 0.1) + + # let's claim whole heir sum from second node + result = rpc1.heirclaim("0", "1000", heir_fund_txid) + assert_success(result) + + heir_claim_txid = self.send_and_mine(result["hextx"], rpc1) + assert heir_claim_txid, "got claim txid" + + # balance of second node after heirclaim should increase for 1000 coins - txfees + # + get one block reward when broadcasted heir_claim_txid + result = round(rpc1.getbalance()) - round(second_node_balance) + assert_greater_than(result, 100999) + + self.sync_all() + + # no more funds should be available for claiming + result = rpc.heirinfo(heir_fund_txid) + assert_equal(result["funding available in coins"], "0.00000000") + + # TODO: valid heirfund case with tokens + + def run_test(self): + print("Mining blocks...") + rpc = self.nodes[0] + rpc1 = self.nodes[1] + # utxos from block 1 become mature in block 101 + if not self.options.noshutdown: + rpc.generate(101) + self.sync_all() + rpc.getinfo() + rpc1.getinfo() + # this corresponds to -pubkey above + print("Importing privkeys") + rpc.importprivkey(self.privkey) + rpc1.importprivkey(self.privkey1) + self.run_heir_tests() + + +if __name__ == '__main__': + CryptoconditionsHeirTest().main() From 9f663ad841dc2f3cde6bdf8465b370df8df23b8f Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 02:00:37 -1100 Subject: [PATCH 0041/1145] Remove fKnown = false --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 43cca5266..cef3e29ab 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4564,7 +4564,7 @@ bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBl return true; } -bool FindBlockPos(int32_t tmpflag,CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false) +bool FindBlockPos(int32_t tmpflag,CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown) { std::vector *ptr; int *lastfilep; LOCK(cs_LastBlockFile); From 87a12db2d1e667f66ea78490c823e8c72f23046b Mon Sep 17 00:00:00 2001 From: Anton Lysakov Date: Thu, 24 Jan 2019 20:11:42 +0700 Subject: [PATCH 0042/1145] Omg --- qa/pull-tester/cc-tests.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qa/pull-tester/cc-tests.sh b/qa/pull-tester/cc-tests.sh index 742763f1d..d68671e12 100755 --- a/qa/pull-tester/cc-tests.sh +++ b/qa/pull-tester/cc-tests.sh @@ -18,7 +18,7 @@ testScripts=( 'cryptoconditions_rewards.py' 'cryptoconditions_token.py' #'cryptoconditions_gateways.py' - 'cryptoconditions_hair.py' + 'cryptoconditions_heir.py' # TODO: cant reconnect nodes back in channels test because of crash (seems regtest only specific) 'cryptoconditions_channels.py' ); From 2367a5cc0b78880dbdbec6f4b5e3e0a6c1f7c840 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 02:14:31 -1100 Subject: [PATCH 0043/1145] Create first entry for tmpBlockfiles --- src/main.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main.cpp b/src/main.cpp index cef3e29ab..73f910d10 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5673,6 +5673,7 @@ bool static LoadBlockIndexDB() // Load block file info pblocktree->ReadLastBlockFile(nLastBlockFile); vinfoBlockFile.resize(nLastBlockFile + 1); + tmpBlockFiles.resize(nLastTmpFile + 1); LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile); for (int nFile = 0; nFile <= nLastBlockFile; nFile++) { pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]); From 420158a628c9c23be84487e6ae3d6514bf71004d Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 02:29:23 -1100 Subject: [PATCH 0044/1145] Undo for tmp files --- src/main.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 73f910d10..fe1503434 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4637,18 +4637,18 @@ bool FindBlockPos(int32_t tmpflag,CValidationState &state, CDiskBlockPos &pos, u bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize) { + std::vector *ptr; int *lastfilep; + LOCK(cs_LastBlockFile); if ( nFile >= TMPFILE_START ) { - fprintf(stderr,"FindUndoPos unexpected tmpfile %d\n",nFile); - return(false); - } + nFile %= TMPFILE_START; + ptr = &tmpBlockFiles; + } else ptr = &vinfoBlockFile; + pos.nFile = nFile; - - LOCK(cs_LastBlockFile); - unsigned int nNewSize; - pos.nPos = vinfoBlockFile[nFile].nUndoSize; - nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize; + pos.nPos = (*ptr)[nFile].nUndoSize; + nNewSize = (*ptr)[nFile].nUndoSize += nAddSize; setDirtyFileInfo.insert(nFile); unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; From 05371f93bd144fd85dffc622443b364388ca7196 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 02:30:39 -1100 Subject: [PATCH 0045/1145] +print --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index fe1503434..d10166ab3 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3268,7 +3268,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) return error("ConnectBlock(): FindBlockPos failed"); pindex->nStatus &= (~BLOCK_IN_TMPFILE); - fprintf(stderr,"added ht.%d copy of tmpfile\n",pindex->GetHeight()); + fprintf(stderr,"added ht.%d copy of tmpfile to %d.%d\n",pindex->GetHeight(),blockPos.nFile,blockPos.nPos); } // verify that the view's current state corresponds to the previous block uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash(); From 86ee8f65502f3d039fa7165c97a383d47f3b7bec Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 02:33:21 -1100 Subject: [PATCH 0046/1145] Switch to main file from temp files --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index d10166ab3..cc37ba316 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3263,7 +3263,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin { unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); CDiskBlockPos blockPos; - if (!FindBlockPos(1,state, blockPos, nBlockSize+8, pindex->GetHeight(), block.GetBlockTime(),false)) + if (!FindBlockPos(0,state, blockPos, nBlockSize+8, pindex->GetHeight(), block.GetBlockTime(),false)) return error("ConnectBlock(): FindBlockPos failed"); if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) return error("ConnectBlock(): FindBlockPos failed"); From f9e2487fdde647734b8417319f5fe05d1d6a1a0f Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 02:37:35 -1100 Subject: [PATCH 0047/1145] Mark new file as dirty --- src/main.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index cc37ba316..f243cef8e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3268,7 +3268,8 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) return error("ConnectBlock(): FindBlockPos failed"); pindex->nStatus &= (~BLOCK_IN_TMPFILE); - fprintf(stderr,"added ht.%d copy of tmpfile to %d.%d\n",pindex->GetHeight(),blockPos.nFile,blockPos.nPos); + setDirtyFileInfo.insert(blockPos.nFile); + //fprintf(stderr,"added ht.%d copy of tmpfile to %d.%d\n",pindex->GetHeight(),blockPos.nFile,blockPos.nPos); } // verify that the view's current state corresponds to the previous block uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash(); @@ -4594,7 +4595,7 @@ bool FindBlockPos(int32_t tmpflag,CValidationState &state, CDiskBlockPos &pos, u } pos.nFile = nFile + tmpflag*TMPFILE_START; pos.nPos = (*ptr)[nFile].nSize; - if ( tmpflag != 0 ) + if ( 0 && tmpflag != 0 ) fprintf(stderr,"pos.nFile %d nPos %u\n",pos.nFile,pos.nPos); } From b963af2269d4d0ee20305bff25aa29a6981bc8e7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 02:41:08 -1100 Subject: [PATCH 0048/1145] Tmp undo file --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index f243cef8e..3d5128de2 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4640,13 +4640,13 @@ bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigne { std::vector *ptr; int *lastfilep; LOCK(cs_LastBlockFile); + pos.nFile = nFile; if ( nFile >= TMPFILE_START ) { nFile %= TMPFILE_START; ptr = &tmpBlockFiles; } else ptr = &vinfoBlockFile; - pos.nFile = nFile; unsigned int nNewSize; pos.nPos = (*ptr)[nFile].nUndoSize; nNewSize = (*ptr)[nFile].nUndoSize += nAddSize; From 4c4c50cbd7bb543631045b6da911d19b47b0aa35 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 03:01:02 -1100 Subject: [PATCH 0049/1145] Receive transactions --- src/main.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 3d5128de2..945243351 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3230,6 +3230,7 @@ bool FindBlockPos(int32_t tmpflag,CValidationState &state, CDiskBlockPos &pos, u bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck,bool fCheckPOW) { + CDiskBlockPos blockPos; const CChainParams& chainparams = Params(); if ( KOMODO_STOPAT != 0 && pindex->GetHeight() > KOMODO_STOPAT ) return(false); @@ -3262,12 +3263,15 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin if ( (pindex->nStatus & BLOCK_IN_TMPFILE) != 0 ) { unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); - CDiskBlockPos blockPos; if (!FindBlockPos(0,state, blockPos, nBlockSize+8, pindex->GetHeight(), block.GetBlockTime(),false)) return error("ConnectBlock(): FindBlockPos failed"); if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) return error("ConnectBlock(): FindBlockPos failed"); pindex->nStatus &= (~BLOCK_IN_TMPFILE); + pindex->nFile = blockPos.nFile; + pindex->nPos = blockPos.nPos; + if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) + return error("AcceptBlock(): ReceivedBlockTransactions failed"); setDirtyFileInfo.insert(blockPos.nFile); //fprintf(stderr,"added ht.%d copy of tmpfile to %d.%d\n",pindex->GetHeight(),blockPos.nFile,blockPos.nPos); } From f44e95a3f585169c01c833744db4cb7f68c9d640 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 03:02:21 -1100 Subject: [PATCH 0050/1145] nDataPos --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 945243351..850aa1c1b 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3269,7 +3269,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin return error("ConnectBlock(): FindBlockPos failed"); pindex->nStatus &= (~BLOCK_IN_TMPFILE); pindex->nFile = blockPos.nFile; - pindex->nPos = blockPos.nPos; + pindex->nDataPos = blockPos.nPos; if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) return error("AcceptBlock(): ReceivedBlockTransactions failed"); setDirtyFileInfo.insert(blockPos.nFile); From eda67fa9d67d514587afa84680ef6d5922c1f840 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 03:04:10 -1100 Subject: [PATCH 0051/1145] bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos) --- src/main.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main.cpp b/src/main.cpp index 850aa1c1b..91d90aa14 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3227,6 +3227,7 @@ static int64_t nTimeIndex = 0; static int64_t nTimeCallbacks = 0; static int64_t nTimeTotal = 0; bool FindBlockPos(int32_t tmpflag,CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false); +bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos); bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck,bool fCheckPOW) { From df9d2ddc97eb80b7b3442eac7c4c91faf092b8cd Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 03:11:31 -1100 Subject: [PATCH 0052/1145] Test --- src/main.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main.cpp b/src/main.cpp index 91d90aa14..bfb1a0535 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4648,6 +4648,8 @@ bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigne pos.nFile = nFile; if ( nFile >= TMPFILE_START ) { + fprintf(stderr,"skip tmp undo\n"); + return(false); nFile %= TMPFILE_START; ptr = &tmpBlockFiles; } else ptr = &vinfoBlockFile; From f5ad6948fcb2690df7ca03c0872b0160b095df51 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 03:28:26 -1100 Subject: [PATCH 0053/1145] -recvtx --- src/main.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index bfb1a0535..71c04aa56 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3274,7 +3274,8 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) return error("AcceptBlock(): ReceivedBlockTransactions failed"); setDirtyFileInfo.insert(blockPos.nFile); - //fprintf(stderr,"added ht.%d copy of tmpfile to %d.%d\n",pindex->GetHeight(),blockPos.nFile,blockPos.nPos); + FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files + fprintf(stderr,"added ht.%d copy of tmpfile to %d.%d\n",pindex->GetHeight(),blockPos.nFile,blockPos.nPos); } // verify that the view's current state corresponds to the previous block uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash(); @@ -5217,8 +5218,8 @@ bool AcceptBlock(int32_t *futureblockp,CBlock& block, CValidationState& state, C if (dbp == NULL) if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) AbortNode(state, "Failed to write block"); - if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) - return error("AcceptBlock(): ReceivedBlockTransactions failed"); + //if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) + // return error("AcceptBlock(): ReceivedBlockTransactions failed"); pindex->nStatus |= BLOCK_IN_TMPFILE; } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error: ") + e.what()); From d8611d936de13c7832efced30870a062b5fa3660 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 03:30:17 -1100 Subject: [PATCH 0054/1145] FlushStateMode --- src/main.cpp | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 71c04aa56..45ec46b45 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3229,6 +3229,14 @@ static int64_t nTimeTotal = 0; bool FindBlockPos(int32_t tmpflag,CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false); bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos); + +enum FlushStateMode { + FLUSH_STATE_NONE, + FLUSH_STATE_IF_NEEDED, + FLUSH_STATE_PERIODIC, + FLUSH_STATE_ALWAYS +}; + bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck,bool fCheckPOW) { CDiskBlockPos blockPos; @@ -3670,12 +3678,6 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin return true; } -enum FlushStateMode { - FLUSH_STATE_NONE, - FLUSH_STATE_IF_NEEDED, - FLUSH_STATE_PERIODIC, - FLUSH_STATE_ALWAYS -}; /** * Update the on-disk chain state. From 10b7fff5bc24b0dc820380044f2feef73f14ec73 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 03:32:22 -1100 Subject: [PATCH 0055/1145] Static --- src/main.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main.cpp b/src/main.cpp index 45ec46b45..4bd49b557 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3236,6 +3236,7 @@ enum FlushStateMode { FLUSH_STATE_PERIODIC, FLUSH_STATE_ALWAYS }; +bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode); bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck,bool fCheckPOW) { From d797bce94d35b61b108029a7d26ff0e41307f680 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 03:34:10 -1100 Subject: [PATCH 0056/1145] Test --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 4bd49b557..e9af9231f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5221,8 +5221,8 @@ bool AcceptBlock(int32_t *futureblockp,CBlock& block, CValidationState& state, C if (dbp == NULL) if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) AbortNode(state, "Failed to write block"); - //if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) - // return error("AcceptBlock(): ReceivedBlockTransactions failed"); + if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) + return error("AcceptBlock(): ReceivedBlockTransactions failed"); pindex->nStatus |= BLOCK_IN_TMPFILE; } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error: ") + e.what()); From d682dfd830f92659512847ed70bf793779c5b09c Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 03:42:27 -1100 Subject: [PATCH 0057/1145] +print --- src/main.cpp | 16 ++++++---------- src/txdb.cpp | 2 +- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index e9af9231f..0198c046d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3229,15 +3229,6 @@ static int64_t nTimeTotal = 0; bool FindBlockPos(int32_t tmpflag,CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false); bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos); - -enum FlushStateMode { - FLUSH_STATE_NONE, - FLUSH_STATE_IF_NEEDED, - FLUSH_STATE_PERIODIC, - FLUSH_STATE_ALWAYS -}; -bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode); - bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck,bool fCheckPOW) { CDiskBlockPos blockPos; @@ -3283,7 +3274,6 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) return error("AcceptBlock(): ReceivedBlockTransactions failed"); setDirtyFileInfo.insert(blockPos.nFile); - FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files fprintf(stderr,"added ht.%d copy of tmpfile to %d.%d\n",pindex->GetHeight(),blockPos.nFile,blockPos.nPos); } // verify that the view's current state corresponds to the previous block @@ -3679,6 +3669,12 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin return true; } +enum FlushStateMode { + FLUSH_STATE_NONE, + FLUSH_STATE_IF_NEEDED, + FLUSH_STATE_PERIODIC, + FLUSH_STATE_ALWAYS +}; /** * Update the on-disk chain state. diff --git a/src/txdb.cpp b/src/txdb.cpp index 164167c29..4d84b1cd2 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -686,7 +686,7 @@ bool CBlockTreeDB::LoadBlockIndexGuts() pindexNew->nTx = diskindex.nTx; pindexNew->nSproutValue = diskindex.nSproutValue; pindexNew->nSaplingValue = diskindex.nSaplingValue; - +fprintf(stderr,"loadguts ht.%d\n",pindexNew->GetHeight()); // Consistency checks auto header = pindexNew->GetBlockHeader(); if (header.GetHash() != pindexNew->GetBlockHash()) From ed73fd8423d455775f2b429f707011bae0caf830 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 04:16:01 -1100 Subject: [PATCH 0058/1145] Undo tmpfile --- src/main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 0198c046d..adf445255 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5212,14 +5212,14 @@ bool AcceptBlock(int32_t *futureblockp,CBlock& block, CValidationState& state, C CDiskBlockPos blockPos; if (dbp != NULL) blockPos = *dbp; - if (!FindBlockPos(1,state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL)) + if (!FindBlockPos(0,state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL)) return error("AcceptBlock(): FindBlockPos failed"); if (dbp == NULL) if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) AbortNode(state, "Failed to write block"); if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) return error("AcceptBlock(): ReceivedBlockTransactions failed"); - pindex->nStatus |= BLOCK_IN_TMPFILE; + //pindex->nStatus |= BLOCK_IN_TMPFILE; } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error: ") + e.what()); } From 1b53f34527a7cdeb986c7a26790e91781367fcae Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 24 Jan 2019 04:18:54 -1100 Subject: [PATCH 0059/1145] Use tmp --- src/main.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index adf445255..344224902 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5206,20 +5206,22 @@ bool AcceptBlock(int32_t *futureblockp,CBlock& block, CValidationState& state, C } int nHeight = pindex->GetHeight(); + int32_t usetmp = 0; // Write block to history file try { unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); CDiskBlockPos blockPos; if (dbp != NULL) blockPos = *dbp; - if (!FindBlockPos(0,state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL)) + if (!FindBlockPos(usetmp,state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL)) return error("AcceptBlock(): FindBlockPos failed"); if (dbp == NULL) if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) AbortNode(state, "Failed to write block"); if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) return error("AcceptBlock(): ReceivedBlockTransactions failed"); - //pindex->nStatus |= BLOCK_IN_TMPFILE; + if ( usetmp != 0 ) + pindex->nStatus |= BLOCK_IN_TMPFILE; } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error: ") + e.what()); } From b4a9c7e5043b9b857c93146dfed55e9f07a52f7a Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 25 Jan 2019 00:57:40 -1100 Subject: [PATCH 0060/1145] Init nonz --- 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 289a84d7c..3701f5257 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1654,7 +1654,7 @@ extern int64_t MAX_MONEY; void komodo_args(char *argv0) { extern const char *Notaries_elected1[][2]; - std::string name,addn; char *dirname,fname[512],arg0str[64],magicstr[9]; uint8_t magic[4],extrabuf[8192],disablebits[32],*extraptr=0; FILE *fp; uint64_t val; uint16_t port; int32_t i,nonz,baseid,len,n,extralen = 0; uint64_t ccenables[256]; + std::string name,addn; char *dirname,fname[512],arg0str[64],magicstr[9]; uint8_t magic[4],extrabuf[8192],disablebits[32],*extraptr=0; FILE *fp; uint64_t val; uint16_t port; int32_t i,nonz=0,baseid,len,n,extralen = 0; uint64_t ccenables[256]; IS_KOMODO_NOTARY = GetBoolArg("-notary", false); memset(ccenables,0,sizeof(ccenables)); memset(disablebits,0,sizeof(disablebits)); From 9dda24f9134a506c55cffb113ba4935be70f05f0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 25 Jan 2019 01:23:36 -1100 Subject: [PATCH 0061/1145] set nonz = 0 --- 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 289a84d7c..3701f5257 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1654,7 +1654,7 @@ extern int64_t MAX_MONEY; void komodo_args(char *argv0) { extern const char *Notaries_elected1[][2]; - std::string name,addn; char *dirname,fname[512],arg0str[64],magicstr[9]; uint8_t magic[4],extrabuf[8192],disablebits[32],*extraptr=0; FILE *fp; uint64_t val; uint16_t port; int32_t i,nonz,baseid,len,n,extralen = 0; uint64_t ccenables[256]; + std::string name,addn; char *dirname,fname[512],arg0str[64],magicstr[9]; uint8_t magic[4],extrabuf[8192],disablebits[32],*extraptr=0; FILE *fp; uint64_t val; uint16_t port; int32_t i,nonz=0,baseid,len,n,extralen = 0; uint64_t ccenables[256]; IS_KOMODO_NOTARY = GetBoolArg("-notary", false); memset(ccenables,0,sizeof(ccenables)); memset(disablebits,0,sizeof(disablebits)); From 07a05ccd6b65afcf01e4683d06996e599a9864e2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 25 Jan 2019 01:27:55 -1100 Subject: [PATCH 0062/1145] -print --- src/txdb.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/txdb.cpp b/src/txdb.cpp index 4d84b1cd2..c86ee9bfa 100644 --- a/src/txdb.cpp +++ b/src/txdb.cpp @@ -686,7 +686,7 @@ bool CBlockTreeDB::LoadBlockIndexGuts() pindexNew->nTx = diskindex.nTx; pindexNew->nSproutValue = diskindex.nSproutValue; pindexNew->nSaplingValue = diskindex.nSaplingValue; -fprintf(stderr,"loadguts ht.%d\n",pindexNew->GetHeight()); +//fprintf(stderr,"loadguts ht.%d\n",pindexNew->GetHeight()); // Consistency checks auto header = pindexNew->GetBlockHeader(); if (header.GetHash() != pindexNew->GetBlockHash()) From a6e7da55e27cfac3bfb2f6f77c7109717cd9043d Mon Sep 17 00:00:00 2001 From: DeckerSU Date: Sat, 26 Jan 2019 03:09:54 +0300 Subject: [PATCH 0063/1145] fix gcc-8 / g++-8 build --- src/chain.h | 2 +- src/consensus/params.h | 4 ++-- src/crypto/verus_hash.h | 1 + 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/chain.h b/src/chain.h index 0b6e2b046..d5310e4e5 100644 --- a/src/chain.h +++ b/src/chain.h @@ -335,7 +335,7 @@ public: nSolution = block.nSolution; } - int32_t SetHeight(int32_t height) + void SetHeight(int32_t height) { this->chainPower.nHeight = height; } diff --git a/src/consensus/params.h b/src/consensus/params.h index b7dc8b475..0ea5b1fff 100644 --- a/src/consensus/params.h +++ b/src/consensus/params.h @@ -115,8 +115,8 @@ struct Params { int64_t AveragingWindowTimespan() const { return nPowAveragingWindow * nPowTargetSpacing; } int64_t MinActualTimespan() const { return (AveragingWindowTimespan() * (100 - nPowMaxAdjustUp )) / 100; } int64_t MaxActualTimespan() const { return (AveragingWindowTimespan() * (100 + nPowMaxAdjustDown)) / 100; } - int32_t SetSaplingHeight(int32_t height) { vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight = height; } - int32_t SetOverwinterHeight(int32_t height) { vUpgrades[Consensus::UPGRADE_OVERWINTER].nActivationHeight = height; } + void SetSaplingHeight(int32_t height) { vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight = height; } + void SetOverwinterHeight(int32_t height) { vUpgrades[Consensus::UPGRADE_OVERWINTER].nActivationHeight = height; } uint256 nMinimumChainWork; }; } // namespace Consensus diff --git a/src/crypto/verus_hash.h b/src/crypto/verus_hash.h index 5ac49c209..2f1f2cd26 100644 --- a/src/crypto/verus_hash.h +++ b/src/crypto/verus_hash.h @@ -86,6 +86,7 @@ class CVerusHashV2 result = buf2; curPos = 0; std::fill(buf1, buf1 + sizeof(buf1), 0); + return *this; } int64_t *ExtraI64Ptr() { return (int64_t *)(curBuf + 32); } From 52cfb02f408de11c81a59bb1e0976e299491e2e0 Mon Sep 17 00:00:00 2001 From: DeckerSU Date: Sat, 26 Jan 2019 04:21:55 +0300 Subject: [PATCH 0064/1145] komodo_activate_sapling return value fix --- src/main.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 3d2f19b55..84f1b611a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3839,7 +3839,8 @@ bool static DisconnectTip(CValidationState &state, bool fBare = false) { int32_t komodo_activate_sapling(CBlockIndex *pindex) { - uint32_t blocktime,prevtime; CBlockIndex *prev; int32_t i,transition=0,height,prevht,activation = 0; + uint32_t blocktime,prevtime; CBlockIndex *prev; int32_t i,transition=0,height,prevht; + int32_t activation = 0; if ( pindex == 0 ) { fprintf(stderr,"komodo_activate_sapling null pindex\n"); @@ -3897,6 +3898,7 @@ int32_t komodo_activate_sapling(CBlockIndex *pindex) fprintf(stderr,"%s sapling activation at %d\n",ASSETCHAINS_SYMBOL,activation); ASSETCHAINS_SAPLING = activation; } + return activation; } static int64_t nTimeReadFromDisk = 0; From 524342f7ba685dad74d2c4388c548b8680bfafb2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 25 Jan 2019 16:43:57 -1100 Subject: [PATCH 0065/1145] Single #define _MAX_BLOCK_SIZE to set max block size --- src/chainparams.cpp | 2 +- src/net.h | 3 ++- src/util.h | 17 +++++++++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/chainparams.cpp b/src/chainparams.cpp index c7232761b..d01b9af1a 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -229,7 +229,7 @@ int32_t MAX_BLOCK_SIZE(int32_t height) // make sure to change MAX_PROTOCOL_MESSA { //fprintf(stderr,"MAX_BLOCK_SIZE %d vs. %d\n",height,mainParams.consensus.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight); if ( height <= 0 || (mainParams.consensus.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight > 0 && height >= mainParams.consensus.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight) ) - return(4096 * 1024); + return(_MAX_BLOCK_SIZE); else return(2000000); } diff --git a/src/net.h b/src/net.h index 3f30175c3..ff47737d8 100644 --- a/src/net.h +++ b/src/net.h @@ -33,6 +33,7 @@ #include "sync.h" #include "uint256.h" #include "utilstrencodings.h" +#include "util.h" #include #include @@ -63,7 +64,7 @@ static const unsigned int MAX_INV_SZ = 50000; /** The maximum number of new addresses to accumulate before announcing. */ static const unsigned int MAX_ADDR_TO_SEND = 1000; /** Maximum length of incoming protocol messages (no message over 2 MiB is currently acceptable). */ -static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1024 * 1024; // depends on MAX_BLOCK_SIZE +static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = _MAX_BLOCK_SIZE; /** Maximum length of strSubVer in `version` message */ static const unsigned int MAX_SUBVERSION_LENGTH = 256; /** -listen default */ diff --git a/src/util.h b/src/util.h index bd1a2542a..dc421092a 100644 --- a/src/util.h +++ b/src/util.h @@ -3,6 +3,21 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. +/****************************************************************************** + * Copyright © 2014-2019 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. * + * * + ******************************************************************************/ + /** * Server/client environment: argument handling, config file parsing, * logging, thread wrappers @@ -29,6 +44,8 @@ #include #include +#define _MAX_BLOCK_SIZE (4096 * 1024) // changing just _MAX_BLOCK_SIZE will hardfork to that size + static const bool DEFAULT_LOGTIMEMICROS = false; static const bool DEFAULT_LOGIPS = false; static const bool DEFAULT_LOGTIMESTAMPS = true; From 91f213c4b8209d5a91bee592ea97ff883c4fe83d Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 25 Jan 2019 16:54:42 -1100 Subject: [PATCH 0066/1145] +// --- src/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.cpp b/src/main.cpp index 344224902..8c652350e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5220,7 +5220,7 @@ bool AcceptBlock(int32_t *futureblockp,CBlock& block, CValidationState& state, C AbortNode(state, "Failed to write block"); if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) return error("AcceptBlock(): ReceivedBlockTransactions failed"); - if ( usetmp != 0 ) + if ( usetmp != 0 ) // not during initialdownload or if futureflag==0 and contextchecks ok pindex->nStatus |= BLOCK_IN_TMPFILE; } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error: ") + e.what()); From 352c93f2c4d58fd6bcb245fab1b3db67fd82868c Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 25 Jan 2019 16:59:55 -1100 Subject: [PATCH 0067/1145] -<<<<< HEAD --- src/net.h | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/net.h b/src/net.h index b3df42df7..ff47737d8 100644 --- a/src/net.h +++ b/src/net.h @@ -64,11 +64,7 @@ static const unsigned int MAX_INV_SZ = 50000; /** The maximum number of new addresses to accumulate before announcing. */ static const unsigned int MAX_ADDR_TO_SEND = 1000; /** Maximum length of incoming protocol messages (no message over 2 MiB is currently acceptable). */ -<<<<<<< HEAD static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = _MAX_BLOCK_SIZE; -======= -static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1024 * 1024; ->>>>>>> origin/FSM /** Maximum length of strSubVer in `version` message */ static const unsigned int MAX_SUBVERSION_LENGTH = 256; /** -listen default */ From 932b3582437021f3c52c101f2d72f406dca0bc36 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 25 Jan 2019 17:15:56 -1100 Subject: [PATCH 0068/1145] +comments how to update to 8MB blocks --- src/chainparams.cpp | 25 +++++++++++++++++++++++-- src/net.h | 2 +- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/chainparams.cpp b/src/chainparams.cpp index d01b9af1a..5c9efb276 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -225,11 +225,32 @@ void CChainParams::SetCheckpointData(CChainParams::CCheckpointData checkpointDat CChainParams::checkpointData = checkpointData; } -int32_t MAX_BLOCK_SIZE(int32_t height) // make sure to change MAX_PROTOCOL_MESSAGE_LENGTH also!!!! +/* + To change the max block size, all that needs to be updated is the #define _MAX_BLOCK_SIZE in utils.h + + However, doing that without any other changes will allow forking non-updated nodes by creating a larger block. So, make sure to height activate the new blocksize properly. + + Assuming it is 8MB, then: + #define _OLD_MAX_BLOCK_SIZE (4096 * 1024) + #define _MAX_BLOCK_SIZE (2 * 4096 * 1024) + + change the body of if: + { + if ( height < saplinght+1000000 ) // activates 8MB blocks 1 million blocks after saplinght + return(_OLD_MAX_BLOCK_SIZE); + else return(_MAX_BLOCK_SIZE); + } + +*/ + +int32_t MAX_BLOCK_SIZE(int32_t height) { + int32_t saplinght = mainParams.consensus.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight; //fprintf(stderr,"MAX_BLOCK_SIZE %d vs. %d\n",height,mainParams.consensus.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight); - if ( height <= 0 || (mainParams.consensus.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight > 0 && height >= mainParams.consensus.vUpgrades[Consensus::UPGRADE_SAPLING].nActivationHeight) ) + if ( height <= 0 || (saplinght > 0 && height >= saplinght) ) + { return(_MAX_BLOCK_SIZE); + } else return(2000000); } diff --git a/src/net.h b/src/net.h index ff47737d8..3e06e9831 100644 --- a/src/net.h +++ b/src/net.h @@ -64,7 +64,7 @@ static const unsigned int MAX_INV_SZ = 50000; /** The maximum number of new addresses to accumulate before announcing. */ static const unsigned int MAX_ADDR_TO_SEND = 1000; /** Maximum length of incoming protocol messages (no message over 2 MiB is currently acceptable). */ -static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = _MAX_BLOCK_SIZE; +static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = (_MAX_BLOCK_SIZE + 24); // 24 is msgheader size /** Maximum length of strSubVer in `version` message */ static const unsigned int MAX_SUBVERSION_LENGTH = 256; /** -listen default */ From fe4b34e9e31294f19b867744afe226cffef3cf59 Mon Sep 17 00:00:00 2001 From: ca333 Date: Sat, 26 Jan 2019 13:08:29 +0100 Subject: [PATCH 0069/1145] add linux headers --- src/cc/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/Makefile b/src/cc/Makefile index 92fbe0da9..52db18fca 100644 --- a/src/cc/Makefile +++ b/src/cc/Makefile @@ -3,7 +3,7 @@ CC = gcc CC_DARWIN = g++-6 CC_WIN = x86_64-w64-mingw32-gcc-posix CFLAGS_DARWIN = -std=c++11 -arch x86_64 -I/usr/local/Cellar/gcc\@6/6.4.0_2/include/c++/6.4.0/ -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -c -Wl,-undefined -Wl,dynamic_lookup -dynamiclib -CFLAGS = -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c +CFLAGS = -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c CFLAGS_WIN = -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c DEBUGFLAGS = -O0 -D _DEBUG RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program From 18f8c77197aa9ba57fa6a62a16da11a392fa0c56 Mon Sep 17 00:00:00 2001 From: ca333 Date: Sat, 26 Jan 2019 13:09:27 +0100 Subject: [PATCH 0070/1145] update linux makefile --- zcutil/build.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/zcutil/build.sh b/zcutil/build.sh index 68239e16e..dc312c8e8 100755 --- a/zcutil/build.sh +++ b/zcutil/build.sh @@ -101,6 +101,9 @@ eval "$MAKE" --version as --version ld -v + +HOST="$HOST" BUILD="$BUILD" NO_PROTON="$PROTON_ARG" "$MAKE" "$@" -C ./depends/ V=1 + #BUILD CCLIB WD=$PWD @@ -116,8 +119,6 @@ fi cd $WD -HOST="$HOST" BUILD="$BUILD" NO_PROTON="$PROTON_ARG" "$MAKE" "$@" -C ./depends/ V=1 ./autogen.sh - CONFIG_SITE="$PWD/depends/$HOST/share/config.site" ./configure "$HARDENING_ARG" "$LCOV_ARG" "$TEST_ARG" "$MINING_ARG" "$PROTON_ARG" $CONFIGURE_FLAGS CXXFLAGS='-g' "$MAKE" "$@" V=1 From 4b6b2a5540f0b4ac93b5322c45396c7e4908e113 Mon Sep 17 00:00:00 2001 From: dimxy Date: Sat, 26 Jan 2019 18:31:46 +0500 Subject: [PATCH 0071/1145] 'throw' changed to 'return result' on incorrect params tx hex name = 'hex' heirlist returns simple txid array now --- src/cc/heir.cpp | 16 ++++------- src/wallet/rpcwallet.cpp | 57 +++++++++++++++++++++++++++------------- 2 files changed, 44 insertions(+), 29 deletions(-) diff --git a/src/cc/heir.cpp b/src/cc/heir.cpp index d00cab795..0e1c7d177 100644 --- a/src/cc/heir.cpp +++ b/src/cc/heir.cpp @@ -657,13 +657,7 @@ template UniValue _HeirFund(int64_t txfee, int64_t amount, std int64_t markerfee = 10000; //std::cerr << "HeirFund() amount=" << amount << " txfee=" << txfee << " heirPubkey IsValid()=" << heirPubkey.IsValid() << " inactivityTime(sec)=" << inactivityTimeSec << " tokenid=" << tokenid.GetHex() << std::endl; - - if (!heirPubkey.IsValid()) { - std::cerr << "HeirFund() heirPubkey is not valid!" << std::endl; - result.push_back(Pair("result", "error")); - result.push_back(Pair("error", "invalid heir pubkey")); - } - + CPubKey myPubkey = pubkey2pk(Mypubkey()); if (AddNormalinputs(mtx, myPubkey, markerfee, 3) > 0) { @@ -714,7 +708,7 @@ template UniValue _HeirFund(int64_t txfee, int64_t amount, std Helper::makeCreateOpRet(tokenid, voutTokenPubkeys, myPubkey, heirPubkey, inactivityTimeSec, heirName)); if (!rawhextx.empty()) { result.push_back(Pair("result", "success")); - result.push_back(Pair("hextx", rawhextx)); + result.push_back(Pair("hex", rawhextx)); } else { std::cerr << "HeirAdd error in FinalizeCCtx" << std::endl; @@ -835,7 +829,7 @@ template UniValue _HeirAdd(uint256 fundingtxid, int64_t txfee, in Helper::makeAddOpRet(tokenid, voutTokenPubkeys, fundingtxid, hasHeirSpendingBegun))); if (!rawhextx.empty()) { - result.push_back(Pair("hextx", rawhextx)); + result.push_back(Pair("hex", rawhextx)); } else { std::cerr << "HeirAdd error in FinalizeCCtx" << std::endl; @@ -1008,7 +1002,7 @@ template UniValue _HeirClaim(uint256 fundingtxid, int64_t txfee if (!rawhextx.empty()) { result.push_back(Pair("result", "success")); - result.push_back(Pair("hextx", rawhextx)); + result.push_back(Pair("hex", rawhextx)); } else { std::cerr << "HeirAdd error in FinalizeCCtx" << std::endl; @@ -1273,7 +1267,7 @@ void _HeirList(struct CCcontract_info *cp, UniValue &result) // note: if it is not Heir token funcId would be equal to 0 if (funcId == 'F') { //result.push_back(Pair("fundingtxid kind name", txid.GetHex() + std::string(" ") + (typeid(Helper) == typeid(TokenHelper) ? std::string("token") : std::string("coin")) + std::string(" ") + heirName)); - result.push_back( Pair("fundingtxid", txid.GetHex()) ); + result.push_back( txid.GetHex() ); } else { std::cerr << "HeirList() this is not the initial F transaction=" << txid.GetHex() << std::endl; diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 14620aa0b..8a1dab638 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -7382,30 +7382,45 @@ UniValue heirfund(const UniValue& params, bool fHelp) LOCK2(cs_main, pwalletMain->cs_wallet); txfee = atoll(params[0].get_str().c_str()); - if (txfee < 0) - throw runtime_error("incorrect txfee param\n"); + if (txfee < 0) { + result.push_back(Pair("result", "error")); + result.push_back(Pair("error", "incorrect txfee")); + return result; + } if(params.size() == 6) // tokens in satoshis: amount = atoll(params[1].get_str().c_str()); else // coins: amount = atof(params[1].get_str().c_str()) * COIN; - if( amount <= 0 ) - throw runtime_error("incorrect amount\n"); + if (amount <= 0) { + result.push_back(Pair("result", "error")); + result.push_back(Pair("error", "incorrect amount")); + return result; + } name = params[2].get_str(); pubkey = ParseHex(params[3].get_str().c_str()); - if( !pubkey2pk(pubkey).IsValid() ) - throw runtime_error("incorrect pubkey\n"); + if (!pubkey2pk(pubkey).IsValid()) { + result.push_back(Pair("result", "error")); + result.push_back(Pair("error", "incorrect pubkey")); + return result; + } inactivitytime = atoll(params[4].get_str().c_str()); - if (inactivitytime <= 0) - throw runtime_error("incorrect inactivity time param\n"); + if (inactivitytime <= 0) { + result.push_back(Pair("result", "error")); + result.push_back(Pair("error", "incorrect inactivity time")); + return result; + } if (params.size() == 6) { tokenid = Parseuint256((char*)params[5].get_str().c_str()); - if(tokenid == zeroid) - throw runtime_error("incorrect tokenid\n"); + if (tokenid == zeroid) { + result.push_back(Pair("result", "error")); + result.push_back(Pair("error", "incorrect tokenid")); + return result; + } } if( tokenid == zeroid ) @@ -7439,8 +7454,11 @@ UniValue heiradd(const UniValue& params, bool fHelp) LOCK2(cs_main, pwalletMain->cs_wallet); txfee = atoll(params[0].get_str().c_str()); - if (txfee < 0) - throw runtime_error("incorrect txfee param\n"); + if (txfee < 0) { + result.push_back(Pair("result", "error")); + result.push_back(Pair("error", "incorrect txfee")); + return result; + } fundingtxid = Parseuint256((char*)params[2].get_str().c_str()); @@ -7450,7 +7468,7 @@ UniValue heiradd(const UniValue& params, bool fHelp) UniValue heirclaim(const UniValue& params, bool fHelp) { - UniValue result; // result(UniValue::VOBJ); + UniValue result; uint256 fundingtxid; int64_t txfee; int64_t inactivitytime; @@ -7458,7 +7476,6 @@ UniValue heirclaim(const UniValue& params, bool fHelp) std::vector pubkey; std::string name; - // do we need this? if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; @@ -7471,8 +7488,11 @@ UniValue heirclaim(const UniValue& params, bool fHelp) LOCK2(cs_main, pwalletMain->cs_wallet); txfee = atoll(params[0].get_str().c_str()); - if (txfee < 0) - throw runtime_error("incorrect txfee param\n"); + if (txfee < 0) { + result.push_back(Pair("result", "error")); + result.push_back(Pair("error", "incorrect txfee")); + return result; + } fundingtxid = Parseuint256((char*)params[2].get_str().c_str()); @@ -7483,8 +7503,9 @@ UniValue heirclaim(const UniValue& params, bool fHelp) UniValue heirinfo(const UniValue& params, bool fHelp) { uint256 fundingtxid; - if (fHelp || params.size() != 1) // or 0? + if (fHelp || params.size() != 1) throw runtime_error("heirinfo fundingtxid\n"); + // if ( ensure_CCrequirements() < 0 ) // throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); @@ -7494,7 +7515,7 @@ UniValue heirinfo(const UniValue& params, bool fHelp) UniValue heirlist(const UniValue& params, bool fHelp) { - if (fHelp || params.size() != 0) // or 0? + if (fHelp || params.size() != 0) throw runtime_error("heirlist\n"); // if ( ensure_CCrequirements() < 0 ) From 2ac92d7d6ec87469584e89d44b731bb5feb8a081 Mon Sep 17 00:00:00 2001 From: dimxy Date: Sat, 26 Jan 2019 19:10:46 +0500 Subject: [PATCH 0072/1145] result changed to VARR --- src/cc/heir.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/heir.cpp b/src/cc/heir.cpp index 0e1c7d177..a148cdc3f 100644 --- a/src/cc/heir.cpp +++ b/src/cc/heir.cpp @@ -1282,7 +1282,7 @@ void _HeirList(struct CCcontract_info *cp, UniValue &result) UniValue HeirList() { - UniValue result(UniValue::VOBJ); + UniValue result(UniValue::VARR); result.push_back(Pair("result", "success")); struct CCcontract_info *cpHeir, *cpTokens, heirC, tokenC; // NOTE we must use a separate 'C' structure for each CCinit! From 9bad115496362250102962b221d40d5823b0f902 Mon Sep 17 00:00:00 2001 From: dimxy Date: Sat, 26 Jan 2019 20:18:00 +0500 Subject: [PATCH 0073/1145] in heirlist added list header --- src/cc/heir.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/cc/heir.cpp b/src/cc/heir.cpp index a148cdc3f..2c4a85037 100644 --- a/src/cc/heir.cpp +++ b/src/cc/heir.cpp @@ -1284,14 +1284,12 @@ UniValue HeirList() { UniValue result(UniValue::VARR); result.push_back(Pair("result", "success")); + result.push_back(Pair("name", "Heir List")); - struct CCcontract_info *cpHeir, *cpTokens, heirC, tokenC; // NOTE we must use a separate 'C' structure for each CCinit! + struct CCcontract_info *cpHeir, heirC; cpHeir = CCinit(&heirC, EVAL_HEIR); - //cpTokens = CCinit(&tokenC, EVAL_TOKENS); - _HeirList(cpHeir, result); - //_HeirList(cpTokens, result); not used anymore return result; } From 82956c357a1ef0182638707789cfe1ae07986e8d Mon Sep 17 00:00:00 2001 From: dimxy Date: Sat, 26 Jan 2019 20:31:48 +0500 Subject: [PATCH 0074/1145] removed heir list header - simply txid array --- src/cc/heir.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/heir.cpp b/src/cc/heir.cpp index 2c4a85037..5861d347a 100644 --- a/src/cc/heir.cpp +++ b/src/cc/heir.cpp @@ -1283,8 +1283,8 @@ void _HeirList(struct CCcontract_info *cp, UniValue &result) UniValue HeirList() { UniValue result(UniValue::VARR); - result.push_back(Pair("result", "success")); - result.push_back(Pair("name", "Heir List")); + //result.push_back(Pair("result", "success")); + //result.push_back(Pair("name", "Heir List")); struct CCcontract_info *cpHeir, heirC; From d963a55cc85003ac41a8d4528d9a560aae5b5b59 Mon Sep 17 00:00:00 2001 From: Anton Lysakov Date: Sun, 27 Jan 2019 03:16:53 +0700 Subject: [PATCH 0075/1145] added valid tokens heir case --- qa/rpc-tests/cryptoconditions_heir.py | 53 ++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/qa/rpc-tests/cryptoconditions_heir.py b/qa/rpc-tests/cryptoconditions_heir.py index 95b90b397..3aa4ee69c 100755 --- a/qa/rpc-tests/cryptoconditions_heir.py +++ b/qa/rpc-tests/cryptoconditions_heir.py @@ -98,7 +98,58 @@ class CryptoconditionsHeirTest(CryptoconditionsTestFramework): result = rpc.heirinfo(heir_fund_txid) assert_equal(result["funding available in coins"], "0.00000000") - # TODO: valid heirfund case with tokens + # creating tokens which we put to heir contract + token_hex = rpc.tokencreate("TEST", "1", "TESTING") + token_txid = self.send_and_mine(token_hex["hex"], rpc) + assert token_txid, "got token txid" + + # checking possesion over the tokens and balance + result = rpc.tokenbalance(token_txid, self.pubkey)["balance"] + assert_equal(result, 100000000) + + # valid heir case with tokens + token_heir_hex = rpc.heirfund("0", "100000000", "UNITHEIR", self.pubkey1, "10", token_txid) + token_heir_txid = self.send_and_mine(token_heir_hex["hextx"], rpc) + assert token_heir_txid, "got txid of heirfund with tokens" + + self.sync_all() + + # checking heirinfo + result = rpc.heirinfo(token_heir_txid) + assert_success(result) + assert_equal(result["fundingtxid"], token_heir_txid) + assert_equal(result["name"], "UNITHEIR") + assert_equal(result["owner"], self.pubkey) + assert_equal(result["heir"], self.pubkey1) + assert_equal(result["funding total in tokens"], "100000000") + assert_equal(result["funding available in tokens"], "100000000") + assert_equal(result["inactivity time setting, sec"], "10") + assert_equal(result["spending allowed for the heir"], "false") + + # waiting for 11 seconds to be sure that needed time passed for heir claiming + time.sleep(11) + rpc.generate(1) + self.sync_all() + result = rpc.heirinfo(token_heir_txid) + assert_equal(result["funding available in tokens"], "100000000") + assert_equal(result["spending allowed for the heir"], "true") + + # let's claim whole heir sum from second node + result = rpc1.heirclaim("0", "100000000", token_heir_txid) + assert_success(result) + + heir_tokens_claim_txid = self.send_and_mine(result["hextx"], rpc1) + assert heir_tokens_claim_txid, "got claim txid" + + # claiming node should have correct token balance now + result = rpc1.tokenbalance(token_txid, self.pubkey1)["balance"] + assert_equal(result, 100000000) + + self.sync_all() + + # no more funds should be available for claiming + result = rpc.heirinfo(token_heir_txid) + assert_equal(result["funding available in tokens"], "0") def run_test(self): print("Mining blocks...") From 45d35fb971d50307fc4aa916ab0caf8e6c05e536 Mon Sep 17 00:00:00 2001 From: Anton Lysakov Date: Sun, 27 Jan 2019 03:21:16 +0700 Subject: [PATCH 0076/1145] actualize comment --- qa/rpc-tests/cryptoconditions_channels.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/qa/rpc-tests/cryptoconditions_channels.py b/qa/rpc-tests/cryptoconditions_channels.py index b2a49b477..5ba15b572 100755 --- a/qa/rpc-tests/cryptoconditions_channels.py +++ b/qa/rpc-tests/cryptoconditions_channels.py @@ -26,6 +26,8 @@ class CryptoconditionsChannelsTest(CryptoconditionsTestFramework): rpc = self.nodes[0] rpc1 = self.nodes[1] + # TODO: check channelsaddress + # getting empty channels list result = rpc.channelslist() assert_equal(len(result), 2) @@ -143,7 +145,7 @@ class CryptoconditionsChannelsTest(CryptoconditionsTestFramework): refund_txid = self.send_and_mine(result["hex"], rpc) assert refund_txid, "got txid" - # TODO: check if it refunded to opener address + # checking if it refunded to opener address raw_transaction = rpc.getrawtransaction(refund_txid, 1) result = raw_transaction["vout"][2]["valueSat"] From dc510cdde4ea1adcdbc624840ffc4caf9b78a7a7 Mon Sep 17 00:00:00 2001 From: Anton Lysakov Date: Sun, 27 Jan 2019 03:32:24 +0700 Subject: [PATCH 0077/1145] checking channelsaddress --- qa/rpc-tests/cryptoconditions_channels.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/qa/rpc-tests/cryptoconditions_channels.py b/qa/rpc-tests/cryptoconditions_channels.py index 5ba15b572..722cce66e 100755 --- a/qa/rpc-tests/cryptoconditions_channels.py +++ b/qa/rpc-tests/cryptoconditions_channels.py @@ -26,7 +26,13 @@ class CryptoconditionsChannelsTest(CryptoconditionsTestFramework): rpc = self.nodes[0] rpc1 = self.nodes[1] - # TODO: check channelsaddress + # checking channelsaddress call + + result = rpc.channelsaddress(self.pubkey) + assert_success(result) + # test that additional CCaddress key is returned + for x in ['myCCaddress', 'ChannelsCCaddress', 'Channelsmarker', 'myaddress', 'CCaddress']: + assert_equal(result[x][0], 'R') # getting empty channels list result = rpc.channelslist() From fdcc9d71c2c6e9fe4798f1e55256ee2b58cb96db Mon Sep 17 00:00:00 2001 From: dimxy Date: Sun, 27 Jan 2019 17:03:38 +0500 Subject: [PATCH 0078/1145] heirinfo var names corrected memo field added --- src/cc/CCHeir.h | 8 +- src/cc/heir.cpp | 194 +++++++++++++++++---------------------- src/cc/heir_validate.h | 24 ++--- src/wallet/rpcwallet.cpp | 18 ++-- 4 files changed, 108 insertions(+), 136 deletions(-) diff --git a/src/cc/CCHeir.h b/src/cc/CCHeir.h index 30334f6e1..2943d747c 100644 --- a/src/cc/CCHeir.h +++ b/src/cc/CCHeir.h @@ -27,15 +27,11 @@ bool HeirValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx, class CoinHelper; class TokenHelper; -UniValue HeirFundCoinCaller(int64_t txfee, int64_t satoshis, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, uint256 tokenid); -UniValue HeirFundTokenCaller(int64_t txfee, int64_t satoshis, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, uint256 tokenid); +UniValue HeirFundCoinCaller(int64_t txfee, int64_t satoshis, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string memo); +UniValue HeirFundTokenCaller(int64_t txfee, int64_t satoshis, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string memo, uint256 tokenid); UniValue HeirClaimCaller(uint256 fundingtxid, int64_t txfee, std::string amount); UniValue HeirAddCaller(uint256 fundingtxid, int64_t txfee, std::string amount); - UniValue HeirInfo(uint256 fundingtxid); UniValue HeirList(); -//std::string Heir_MakeBadTx(uint256 fundingtxid, uint8_t funcId, int64_t amount, CPubKey ownerPubkey, CPubKey heirPubkey, int64_t inactivityTime, uint32_t errMask); - -//bool HeirExactTokenAmounts(bool compareTotals, struct CCcontract_info *cpHeir, Eval* eval, uint256 assetid, const CTransaction &tx); #endif diff --git a/src/cc/heir.cpp b/src/cc/heir.cpp index 5861d347a..8e7f3f08b 100644 --- a/src/cc/heir.cpp +++ b/src/cc/heir.cpp @@ -255,11 +255,11 @@ template int64_t IsHeirFundingVout(struct CCcontract_info* cp, co } // makes coin initial tx opret -CScript EncodeHeirCreateOpRet(uint8_t funcid, CPubKey ownerPubkey, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string heirName) +CScript EncodeHeirCreateOpRet(uint8_t funcid, CPubKey ownerPubkey, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string heirName, std::string memo) { uint8_t evalcode = EVAL_HEIR; - return CScript() << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << ownerPubkey << heirPubkey << inactivityTimeSec << heirName); + return CScript() << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << ownerPubkey << heirPubkey << inactivityTimeSec << heirName << memo); } // makes coin additional tx opret @@ -273,7 +273,7 @@ CScript EncodeHeirOpRet(uint8_t funcid, uint256 fundingtxid, uint8_t hasHeirSpe // decode opret vout for Heir contract -uint8_t _DecodeHeirOpRet(std::vector vopret, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, uint256& fundingTxidInOpret, uint8_t &hasHeirSpendingBegun, bool noLogging) +uint8_t _DecodeHeirOpRet(std::vector vopret, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, std::string& memo, uint256& fundingTxidInOpret, uint8_t &hasHeirSpendingBegun, bool noLogging) { uint8_t evalCodeInOpret = 0; uint8_t heirFuncId = 0; @@ -287,13 +287,13 @@ uint8_t _DecodeHeirOpRet(std::vector vopret, CPubKey& ownerPubkey, CPub uint8_t heirFuncId = 0; hasHeirSpendingBegun = 0; - bool result = E_UNMARSHAL(vopret, { ss >> evalCodeInOpret; ss >> heirFuncId; \ - if (heirFuncId == 'F') { \ - ss >> ownerPubkey; ss >> heirPubkey; ss >> inactivityTime; ss >> heirName; \ - } \ - else { \ - ss >> fundingTxidInOpret >> hasHeirSpendingBegun; \ - } \ + bool result = E_UNMARSHAL(vopret, { ss >> evalCodeInOpret; ss >> heirFuncId; \ + if (heirFuncId == 'F') { \ + ss >> ownerPubkey; ss >> heirPubkey; ss >> inactivityTime; ss >> heirName; ss >> memo; \ + } \ + else { \ + ss >> fundingTxidInOpret >> hasHeirSpendingBegun; \ + } \ }); if (!result) { @@ -322,84 +322,49 @@ uint8_t _DecodeHeirOpRet(std::vector vopret, CPubKey& ownerPubkey, CPub return (uint8_t)0; } -/* not used, see DecodeHeirOpRet(vopret,...) - // overload for 'F' opret - uint8_t DecodeHeirOpRet(CScript scriptPubKey, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, bool noLogging) - { - uint256 dummytxid; - uint8_t dummyHasHeirSpendingBegun; - std::vector vopret; - - GetOpReturnData(scriptPubKey, vopret); - if (vopret.size() == 0) { - if (!noLogging) std::cerr << "DecodeHeirOpRet() warning: empty opret" << std::endl; - return (uint8_t)0; - } - return _DecodeHeirOpRet(vopret, ownerPubkey, heirPubkey, inactivityTime, heirName, dummytxid, dummyHasHeirSpendingBegun, noLogging); - }*/ - - -/* not used, see DecodeHeirOpRet(vopret,...) - // overload for A, C oprets and AddHeirContractInputs - uint8_t DecodeHeirOpRet(CScript scriptPubKey, uint256& fundingtxidInOpret, uint8_t &hasHeirSpendingBegun, bool noLogging) - { - CPubKey dummyOwnerPubkey, dummyHeirPubkey; - int64_t dummyInactivityTime; - std::string dummyHeirName; - std::vector vopret; - - GetOpReturnData(scriptPubKey, vopret); - if (vopret.size() == 0) { - if (!noLogging) std::cerr << "DecodeHeirOpRet() warning: empty opret" << std::endl; - return (uint8_t)0; - } - - return _DecodeHeirOpRet(vopret, dummyOwnerPubkey, dummyHeirPubkey, dummyInactivityTime, dummyHeirName, fundingtxidInOpret, hasHeirSpendingBegun, noLogging); - } */ - // decode combined opret: -uint8_t _DecodeHeirEitherOpRet(CScript scriptPubKey, uint256 &tokenid, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, uint256& fundingTxidInOpret, uint8_t &hasHeirSpendingBegun, bool noLogging) +uint8_t _DecodeHeirEitherOpRet(CScript scriptPubKey, uint256 &tokenid, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, std::string& memo, uint256& fundingTxidInOpret, uint8_t &hasHeirSpendingBegun, bool noLogging) { - uint8_t evalCodeTokens = 0; - std::vector voutPubkeysDummy; - std::vector vopretExtra, vopretStripped; - - if (DecodeTokenOpRet(scriptPubKey, evalCodeTokens, tokenid, voutPubkeysDummy, vopretExtra) != 0) { - if (vopretExtra.size() > 1) { - // restore the second opret: - - if (!E_UNMARSHAL(vopretExtra, { ss >> vopretStripped; })) { //strip string size - if (!noLogging) std::cerr << "_DecodeHeirEitherOpret() could not unmarshal vopretStripped" << std::endl; - return (uint8_t)0; - } - } - else { - if (!noLogging) std::cerr << "_DecodeHeirEitherOpret() empty vopretExtra" << std::endl; - return (uint8_t)0; - } - } - else - GetOpReturnData(scriptPubKey, vopretStripped); - - return _DecodeHeirOpRet(vopretStripped, ownerPubkey, heirPubkey, inactivityTime, heirName, fundingTxidInOpret, hasHeirSpendingBegun, noLogging); + uint8_t evalCodeTokens = 0; + std::vector voutPubkeysDummy; + std::vector vopretExtra, vopretStripped; + + if (DecodeTokenOpRet(scriptPubKey, evalCodeTokens, tokenid, voutPubkeysDummy, vopretExtra) != 0) { + if (vopretExtra.size() > 1) { + // restore the second opret: + + if (!E_UNMARSHAL(vopretExtra, { ss >> vopretStripped; })) { //strip string size + if (!noLogging) std::cerr << "_DecodeHeirEitherOpret() could not unmarshal vopretStripped" << std::endl; + return (uint8_t)0; + } + } + else { + if (!noLogging) std::cerr << "_DecodeHeirEitherOpret() empty vopretExtra" << std::endl; + return (uint8_t)0; + } + } + else { + GetOpReturnData(scriptPubKey, vopretStripped); + } + return _DecodeHeirOpRet(vopretStripped, ownerPubkey, heirPubkey, inactivityTime, heirName, memo, fundingTxidInOpret, hasHeirSpendingBegun, noLogging); } // overload to decode opret in fundingtxid: -uint8_t DecodeHeirEitherOpRet(CScript scriptPubKey, uint256 &tokenid, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, bool noLogging) { +uint8_t DecodeHeirEitherOpRet(CScript scriptPubKey, uint256 &tokenid, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, std::string& memo, bool noLogging) { uint256 dummyFundingTxidInOpret; uint8_t dummyHasHeirSpendingBegun; - return _DecodeHeirEitherOpRet(scriptPubKey, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, dummyFundingTxidInOpret, dummyHasHeirSpendingBegun, noLogging); + return _DecodeHeirEitherOpRet(scriptPubKey, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, memo, dummyFundingTxidInOpret, dummyHasHeirSpendingBegun, noLogging); } // overload to decode opret in A and C heir tx: uint8_t DecodeHeirEitherOpRet(CScript scriptPubKey, uint256 &tokenid, uint256 &fundingTxidInOpret, uint8_t &hasHeirSpendingBegun, bool noLogging) { CPubKey dummyOwnerPubkey, dummyHeirPubkey; int64_t dummyInactivityTime; - std::string dummyHeirName; + std::string dummyHeirName, dummyMemo; - return _DecodeHeirEitherOpRet(scriptPubKey, tokenid, dummyOwnerPubkey, dummyHeirPubkey, dummyInactivityTime, dummyHeirName, fundingTxidInOpret, hasHeirSpendingBegun, noLogging); + return _DecodeHeirEitherOpRet(scriptPubKey, tokenid, dummyOwnerPubkey, dummyHeirPubkey, dummyInactivityTime, dummyHeirName, dummyMemo, fundingTxidInOpret, hasHeirSpendingBegun, noLogging); } // check if pubkey is in vins @@ -423,7 +388,7 @@ void CheckVinPubkey(std::vector vins, CPubKey pubkey, bool &hasPubkey, bo * find the latest funding tx: it may be the first F tx or one of A or C tx's * Note: this function is also called from validation code (use non-locking calls) */ -uint256 _FindLatestFundingTx(uint256 fundingtxid, uint8_t& funcId, uint256 &tokenid, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, CScript& fundingOpretScript, uint8_t &hasHeirSpendingBegun) +uint256 _FindLatestFundingTx(uint256 fundingtxid, uint8_t& funcId, uint256 &tokenid, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, std::string& memo, CScript& fundingOpretScript, uint8_t &hasHeirSpendingBegun) { CTransaction fundingtx; uint256 hashBlock; @@ -440,7 +405,7 @@ uint256 _FindLatestFundingTx(uint256 fundingtxid, uint8_t& funcId, uint256 &toke if (myGetTransaction(fundingtxid, fundingtx, hashBlock) && fundingtx.vout.size()) { CScript heirScript = (fundingtx.vout.size() > 0) ? fundingtx.vout[fundingtx.vout.size() - 1].scriptPubKey : CScript(); - uint8_t funcId = DecodeHeirEitherOpRet(heirScript, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, true); + uint8_t funcId = DecodeHeirEitherOpRet(heirScript, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, memo, true); if (funcId != 0) { // found at least funding tx! //std::cerr << "FindLatestFundingTx() lasttx currently is fundingtx, txid=" << fundingtxid.GetHex() << " opreturn type=" << (char)funcId << '\n'; @@ -522,17 +487,17 @@ uint256 FindLatestFundingTx(uint256 fundingtxid, uint256 &tokenid, CScript& opRe CPubKey ownerPubkey; CPubKey heirPubkey; int64_t inactivityTime; - std::string heirName; + std::string heirName, memo; - return _FindLatestFundingTx(fundingtxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, opRetScript, hasHeirSpendingBegun); + return _FindLatestFundingTx(fundingtxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, memo, opRetScript, hasHeirSpendingBegun); } // overload for transaction creation code -uint256 FindLatestFundingTx(uint256 fundingtxid, uint8_t& funcId, uint256 &tokenid, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, uint8_t &hasHeirSpendingBegun) +uint256 FindLatestFundingTx(uint256 fundingtxid, uint8_t& funcId, uint256 &tokenid, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, std::string& memo, uint8_t &hasHeirSpendingBegun) { CScript opRetScript; - return _FindLatestFundingTx(fundingtxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, opRetScript, hasHeirSpendingBegun); + return _FindLatestFundingTx(fundingtxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, memo, opRetScript, hasHeirSpendingBegun); } // add inputs of 1 of 2 cc address @@ -561,7 +526,7 @@ template int64_t Add1of2AddressInputs(struct CCcontract_info* cp, // no need to prevent dup // dimxy: maybe it is good to put tx's in cache? - std::cerr << "Add1of2AddressInputs() txid=" << txid.GetHex() << std::endl; + //std::cerr << "Add1of2AddressInputs() txid=" << txid.GetHex() << std::endl; if (GetTransaction(txid, heirtx, hashBlock, false) != 0) { uint256 tokenid; @@ -644,7 +609,7 @@ template int64_t LifetimeHeirContractFunds(struct CCcontract_info * and also for setting spending plan for the funds' owner and heir * @return fundingtxid handle for subsequent references to this heir funding plan */ -template UniValue _HeirFund(int64_t txfee, int64_t amount, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, uint256 tokenid) +template UniValue _HeirFund(int64_t txfee, int64_t amount, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string memo, uint256 tokenid) { UniValue result(UniValue::VOBJ); CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); @@ -705,7 +670,7 @@ template UniValue _HeirFund(int64_t txfee, int64_t amount, std // add change for txfee and opreturn vouts and sign tx: std::string rawhextx = FinalizeCCTx(0, cp, mtx, myPubkey, txfee, - Helper::makeCreateOpRet(tokenid, voutTokenPubkeys, myPubkey, heirPubkey, inactivityTimeSec, heirName)); + Helper::makeCreateOpRet(tokenid, voutTokenPubkeys, myPubkey, heirPubkey, inactivityTimeSec, heirName, memo)); if (!rawhextx.empty()) { result.push_back(Pair("result", "success")); result.push_back(Pair("hex", rawhextx)); @@ -731,12 +696,12 @@ template UniValue _HeirFund(int64_t txfee, int64_t amount, std } // if no these callers - it could not link -UniValue HeirFundCoinCaller(int64_t txfee, int64_t satoshis, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, uint256 tokenid){ - return _HeirFund(txfee, satoshis, heirName, heirPubkey, inactivityTimeSec, tokenid); +UniValue HeirFundCoinCaller(int64_t txfee, int64_t satoshis, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string memo){ + return _HeirFund(txfee, satoshis, heirName, heirPubkey, inactivityTimeSec, memo, zeroid); } -UniValue HeirFundTokenCaller(int64_t txfee, int64_t satoshis, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, uint256 tokenid) { - return _HeirFund(txfee, satoshis, heirName, heirPubkey, inactivityTimeSec, tokenid); +UniValue HeirFundTokenCaller(int64_t txfee, int64_t satoshis, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string memo, uint256 tokenid) { + return _HeirFund(txfee, satoshis, heirName, heirPubkey, inactivityTimeSec, memo, tokenid); } /** @@ -744,7 +709,7 @@ UniValue HeirFundTokenCaller(int64_t txfee, int64_t satoshis, std::string heirNa * creates tx to add more funds to cryptocondition address for spending by either funds' owner or heir * @return result object with raw tx or error text */ -template UniValue _HeirAdd(uint256 fundingtxid, int64_t txfee, int64_t amount, uint256 latesttxid, uint8_t funcId, uint256 tokenid, CPubKey ownerPubkey, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string heirName, uint8_t hasHeirSpendingBegun) +template UniValue _HeirAdd(uint256 fundingtxid, int64_t txfee, int64_t amount, uint256 latesttxid, uint8_t funcId, uint256 tokenid, CPubKey ownerPubkey, CPubKey heirPubkey, int64_t inactivityTimeSec, uint8_t hasHeirSpendingBegun) { UniValue result(UniValue::VOBJ); CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); @@ -862,10 +827,10 @@ UniValue HeirAddCaller(uint256 fundingtxid, int64_t txfee, std::string strAmount uint256 latesttxid, tokenid = zeroid; uint8_t funcId; - std::string heirName; + std::string heirName, memo; uint8_t hasHeirSpendingBegun = 0; - if ((latesttxid = FindLatestFundingTx(fundingtxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, heirName, hasHeirSpendingBegun)) != zeroid) { + if ((latesttxid = FindLatestFundingTx(fundingtxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, heirName, memo, hasHeirSpendingBegun)) != zeroid) { if (tokenid == zeroid) { int64_t amount = (int64_t)(atof(strAmount.c_str()) * COIN); if (amount <= 0) { @@ -874,8 +839,7 @@ UniValue HeirAddCaller(uint256 fundingtxid, int64_t txfee, std::string strAmount result.push_back(Pair("error", "invalid amount")); return result; } - - return _HeirAdd(fundingtxid, txfee, amount, latesttxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, heirName, hasHeirSpendingBegun); + return _HeirAdd(fundingtxid, txfee, amount, latesttxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, hasHeirSpendingBegun); } else { int64_t amount = atoll(strAmount.c_str()); @@ -885,7 +849,7 @@ UniValue HeirAddCaller(uint256 fundingtxid, int64_t txfee, std::string strAmount result.push_back(Pair("error", "invalid amount")); return result; } - return _HeirAdd(fundingtxid, txfee, amount, latesttxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, heirName, hasHeirSpendingBegun); + return _HeirAdd(fundingtxid, txfee, amount, latesttxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, hasHeirSpendingBegun); } } else { @@ -904,7 +868,7 @@ UniValue HeirAddCaller(uint256 fundingtxid, int64_t txfee, std::string strAmount * creates tx to spend funds from cryptocondition address by either funds' owner or heir * @return result object with raw tx or error text */ -template UniValue _HeirClaim(uint256 fundingtxid, int64_t txfee, int64_t amount, uint256 latesttxid, uint8_t funcId, uint256 tokenid, CPubKey ownerPubkey, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string heirName, uint8_t hasHeirSpendingBegun) +template UniValue _HeirClaim(uint256 fundingtxid, int64_t txfee, int64_t amount, uint256 latesttxid, uint8_t funcId, uint256 tokenid, CPubKey ownerPubkey, CPubKey heirPubkey, int64_t inactivityTimeSec, uint8_t hasHeirSpendingBegun) { UniValue result(UniValue::VOBJ); CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); @@ -1032,10 +996,10 @@ UniValue HeirClaimCaller(uint256 fundingtxid, int64_t txfee, std::string strAmou uint256 latesttxid, tokenid = zeroid; uint8_t funcId; - std::string heirName; + std::string heirName, memo; uint8_t hasHeirSpendingBegun = 0; - if ((latesttxid = FindLatestFundingTx(fundingtxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, heirName, hasHeirSpendingBegun)) != zeroid) { + if ((latesttxid = FindLatestFundingTx(fundingtxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, heirName, memo, hasHeirSpendingBegun)) != zeroid) { if (tokenid == zeroid) { int64_t amount = (int64_t)(atof(strAmount.c_str()) * COIN); if (amount < 0) { @@ -1044,7 +1008,7 @@ UniValue HeirClaimCaller(uint256 fundingtxid, int64_t txfee, std::string strAmou result.push_back(Pair("error", "invalid amount")); return result; } - return _HeirClaim(fundingtxid, txfee, amount, latesttxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, heirName, hasHeirSpendingBegun); + return _HeirClaim(fundingtxid, txfee, amount, latesttxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, hasHeirSpendingBegun); } else { int64_t amount = atoll(strAmount.c_str()); @@ -1054,7 +1018,7 @@ UniValue HeirClaimCaller(uint256 fundingtxid, int64_t txfee, std::string strAmou result.push_back(Pair("error", "invalid amount")); return result; } - return _HeirClaim(fundingtxid, txfee, amount, latesttxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, heirName, hasHeirSpendingBegun); + return _HeirClaim(fundingtxid, txfee, amount, latesttxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, hasHeirSpendingBegun); } } @@ -1093,7 +1057,7 @@ UniValue HeirInfo(uint256 fundingtxid) CPubKey ownerPubkey, heirPubkey; uint256 dummyTokenid, tokenid = zeroid; // important to clear tokenid - std::string heirName; + std::string heirName, memo; int64_t inactivityTimeSec; const bool noLogging = false; uint8_t funcId; @@ -1112,7 +1076,7 @@ UniValue HeirInfo(uint256 fundingtxid) uint8_t hasHeirSpendingBegun = 0; - uint256 latestFundingTxid = FindLatestFundingTx(fundingtxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, heirName, hasHeirSpendingBegun); + uint256 latestFundingTxid = FindLatestFundingTx(fundingtxid, funcId, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, heirName, memo, hasHeirSpendingBegun); if (latestFundingTxid != zeroid) { int32_t numblocks; @@ -1153,12 +1117,22 @@ UniValue HeirInfo(uint256 fundingtxid) else total = LifetimeHeirContractFunds(cp, fundingtxid, ownerPubkey, heirPubkey); + msg = "type"; + if (tokenid == zeroid) { + stream << "coins"; + } + else { + stream << "tokens"; + } + result.push_back(Pair(msg, stream.str().c_str())); + stream.str(""); + stream.clear(); + + msg = "lifetime"; if (tokenid == zeroid) { - msg = "funding total in coins"; stream << std::fixed << std::setprecision(8) << (double)total / COIN; } else { - msg = "funding total in tokens"; stream << total; } result.push_back(Pair(msg, stream.str().c_str())); @@ -1171,12 +1145,11 @@ UniValue HeirInfo(uint256 fundingtxid) else inputs = Add1of2AddressInputs(cp, fundingtxid, mtx, ownerPubkey, heirPubkey, 0, 60); + msg = "available"; if (tokenid == zeroid) { - msg = "funding available in coins"; stream << std::fixed << std::setprecision(8) << (double)inputs / COIN; } else { - msg = "funding available in tokens"; stream << inputs; } result.push_back(Pair(msg, stream.str().c_str())); @@ -1186,14 +1159,14 @@ UniValue HeirInfo(uint256 fundingtxid) if (tokenid != zeroid) { int64_t ownerInputs = TokenHelper::addOwnerInputs(tokenid, mtx, ownerPubkey, 0, (int32_t)64); stream << ownerInputs; - msg = "owner funding available in tokens"; + msg = "OwnerRemainderTokens"; result.push_back(Pair(msg, stream.str().c_str())); stream.str(""); stream.clear(); } stream << inactivityTimeSec; - result.push_back(Pair("inactivity time setting, sec", stream.str().c_str())); + result.push_back(Pair("InactivityTimeSetting", stream.str().c_str())); stream.str(""); stream.clear(); @@ -1203,18 +1176,20 @@ UniValue HeirInfo(uint256 fundingtxid) } stream << std::boolalpha << (hasHeirSpendingBegun || durationSec > inactivityTimeSec); - result.push_back(Pair("spending allowed for the heir", stream.str().c_str())); + result.push_back(Pair("IsHeirSpendingAllowed", stream.str().c_str())); stream.str(""); stream.clear(); // adding owner current inactivity time: if (!hasHeirSpendingBegun && durationSec <= inactivityTimeSec) { stream << durationSec; - result.push_back(Pair("owner inactivity time, sec", stream.str().c_str())); + result.push_back(Pair("InactivityTime", stream.str().c_str())); stream.str(""); stream.clear(); } - + + result.push_back(Pair("memo", memo.c_str())); + result.push_back(Pair("result", "success")); } else { @@ -1256,13 +1231,13 @@ void _HeirList(struct CCcontract_info *cp, UniValue &result) CTransaction fundingtx; if (GetTransaction(txid, fundingtx, hashBlock, false)) { CPubKey ownerPubkey, heirPubkey; - std::string heirName; + std::string heirName, memo; int64_t inactivityTimeSec; const bool noLogging = true; uint256 tokenid; CScript opret = (fundingtx.vout.size() > 0) ? fundingtx.vout[fundingtx.vout.size() - 1].scriptPubKey : CScript(); - uint8_t funcId = DecodeHeirEitherOpRet(opret, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, heirName, true); + uint8_t funcId = DecodeHeirEitherOpRet(opret, tokenid, ownerPubkey, heirPubkey, inactivityTimeSec, heirName, memo, true); // note: if it is not Heir token funcId would be equal to 0 if (funcId == 'F') { @@ -1293,4 +1268,3 @@ UniValue HeirList() return result; } - diff --git a/src/cc/heir_validate.h b/src/cc/heir_validate.h index df58e3bf1..15ab133e4 100644 --- a/src/cc/heir_validate.h +++ b/src/cc/heir_validate.h @@ -7,13 +7,13 @@ #define IS_CHARINSTR(c, str) (std::string(str).find((char)(c)) != std::string::npos) // makes coin initial tx opret -CScript EncodeHeirCreateOpRet(uint8_t funcid, CPubKey ownerPubkey, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string heirName); +CScript EncodeHeirCreateOpRet(uint8_t funcid, CPubKey ownerPubkey, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string heirName, std::string memo); CScript EncodeHeirOpRet(uint8_t funcid, uint256 fundingtxid, uint8_t isHeirSpendingBegan); uint256 FindLatestFundingTx(uint256 fundingtxid, uint256 &tokenid, CScript& opRetScript, uint8_t &isHeirSpendingBegan); //uint8_t DecodeHeirOpRet(CScript scriptPubKey, uint256& fundingtxid, uint8_t &isHeirSpendingBegan, bool noLogging = false); //uint8_t DecodeHeirOpRet(CScript scriptPubKey, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, bool noLogging = false); -uint8_t DecodeHeirEitherOpRet(CScript scriptPubKey, uint256 &tokenid, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, bool noLogging = false); +uint8_t DecodeHeirEitherOpRet(CScript scriptPubKey, uint256 &tokenid, CPubKey& ownerPubkey, CPubKey& heirPubkey, int64_t& inactivityTime, std::string& heirName, std::string& memo, bool noLogging = false); uint8_t DecodeHeirEitherOpRet(CScript scriptPubKey, uint256 &tokenid, uint256 &fundingTxidInOpret, uint8_t &hasHeirSpendingBegun, bool noLogging = false); inline static bool isMyFuncId(uint8_t funcid) { return IS_CHARINSTR(funcid, "FAC"); } @@ -28,8 +28,8 @@ public: return AddNormalinputs(mtx, ownerPubkey, total, maxinputs); } - static CScript makeCreateOpRet(uint256 dummyid, std::vector dummyPubkeys, CPubKey ownerPubkey, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string heirName) { - return EncodeHeirCreateOpRet((uint8_t)'F', ownerPubkey, heirPubkey, inactivityTimeSec, heirName); + static CScript makeCreateOpRet(uint256 dummyid, std::vector dummyPubkeys, CPubKey ownerPubkey, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string heirName, std::string memo) { + return EncodeHeirCreateOpRet((uint8_t)'F', ownerPubkey, heirPubkey, inactivityTimeSec, heirName, memo); } static CScript makeAddOpRet(uint256 dummyid, std::vector dummyPubkeys, uint256 fundingtxid, uint8_t isHeirSpendingBegan) { return EncodeHeirOpRet((uint8_t)'A', fundingtxid, isHeirSpendingBegan); @@ -66,9 +66,9 @@ public: return AddTokenCCInputs(cpHeir, mtx, ownerPubkey, tokenid, total, maxinputs); } - static CScript makeCreateOpRet(uint256 tokenid, std::vector voutTokenPubkeys, CPubKey ownerPubkey, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string heirName) { + static CScript makeCreateOpRet(uint256 tokenid, std::vector voutTokenPubkeys, CPubKey ownerPubkey, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string heirName, std::string memo) { return EncodeTokenOpRet(tokenid, voutTokenPubkeys, - EncodeHeirCreateOpRet((uint8_t)'F', ownerPubkey, heirPubkey, inactivityTimeSec, heirName)); + EncodeHeirCreateOpRet((uint8_t)'F', ownerPubkey, heirPubkey, inactivityTimeSec, heirName, memo)); } static CScript makeAddOpRet(uint256 tokenid, std::vector voutTokenPubkeys, uint256 fundingtxid, uint8_t isHeirSpendingBegan) { return EncodeTokenOpRet(tokenid, voutTokenPubkeys, @@ -407,10 +407,10 @@ public: //std::cerr << "CCC1of2AddressValidator::validateVout() entered" << std::endl; CPubKey ownerPubkey, heirPubkey; int64_t inactivityTime; - std::string heirName; + std::string heirName, memo; uint256 tokenid; - uint8_t funcId = DecodeHeirEitherOpRet(m_fundingOpretScript, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, true); + uint8_t funcId = DecodeHeirEitherOpRet(m_fundingOpretScript, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, memo, true); if (funcId == 0) { message = m_customMessage + std::string(" invalid opreturn format"); std::cerr << "CCC1of2AddressValidator::validateVout() exits with false: " << message << std::endl; @@ -462,13 +462,13 @@ public: CPubKey ownerPubkey, heirPubkey; int64_t inactivityTime; - std::string heirName; + std::string heirName, memo; uint256 tokenid; ///std::cerr << "CMyPubkeyVoutValidator::validateVout() m_opRetScript=" << m_opRetScript.ToString() << std::endl; // get both pubkeys: - uint8_t funcId = DecodeHeirEitherOpRet(m_fundingOpretScript, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, true); + uint8_t funcId = DecodeHeirEitherOpRet(m_fundingOpretScript, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, memo, true); if (funcId == 0) { message = std::string("invalid opreturn format"); return false; @@ -522,11 +522,11 @@ public: CPubKey ownerPubkey, heirPubkey; int64_t inactivityTime; - std::string heirName; + std::string heirName, memo; uint256 tokenid; // get heir pubkey: - uint8_t funcId = DecodeHeirEitherOpRet(m_fundingOpretScript, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, true); + uint8_t funcId = DecodeHeirEitherOpRet(m_fundingOpretScript, tokenid, ownerPubkey, heirPubkey, inactivityTime, heirName, memo, true); if (funcId == 0) { message = std::string("invalid opreturn format"); return false; diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 8a1dab638..2adf931bb 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -7368,13 +7368,13 @@ UniValue heirfund(const UniValue& params, bool fHelp) int64_t inactivitytime; std::string hex; std::vector pubkey; - std::string name; + std::string name, memo; if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; - if (fHelp || params.size() != 5 && params.size() != 6) - throw runtime_error("heirfund txfee funds heirname heirpubkey inactivitytime [tokenid]\n"); + if (fHelp || params.size() != 6 && params.size() != 7) + throw runtime_error("heirfund txfee funds heirname heirpubkey inactivitytime memo [tokenid]\n"); if (ensure_CCrequirements() < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); @@ -7392,7 +7392,6 @@ UniValue heirfund(const UniValue& params, bool fHelp) amount = atoll(params[1].get_str().c_str()); else // coins: amount = atof(params[1].get_str().c_str()) * COIN; - if (amount <= 0) { result.push_back(Pair("result", "error")); result.push_back(Pair("error", "incorrect amount")); @@ -7400,6 +7399,7 @@ UniValue heirfund(const UniValue& params, bool fHelp) } name = params[2].get_str(); + pubkey = ParseHex(params[3].get_str().c_str()); if (!pubkey2pk(pubkey).IsValid()) { result.push_back(Pair("result", "error")); @@ -7414,8 +7414,10 @@ UniValue heirfund(const UniValue& params, bool fHelp) return result; } - if (params.size() == 6) { - tokenid = Parseuint256((char*)params[5].get_str().c_str()); + memo = params[5].get_str(); + + if (params.size() == 7) { + tokenid = Parseuint256((char*)params[6].get_str().c_str()); if (tokenid == zeroid) { result.push_back(Pair("result", "error")); result.push_back(Pair("error", "incorrect tokenid")); @@ -7424,9 +7426,9 @@ UniValue heirfund(const UniValue& params, bool fHelp) } if( tokenid == zeroid ) - result = HeirFundCoinCaller(txfee, amount, name, pubkey2pk(pubkey), inactivitytime, zeroid); + result = HeirFundCoinCaller(txfee, amount, name, pubkey2pk(pubkey), inactivitytime, memo); else - result = HeirFundTokenCaller(txfee, amount, name, pubkey2pk(pubkey), inactivitytime, tokenid); + result = HeirFundTokenCaller(txfee, amount, name, pubkey2pk(pubkey), inactivitytime, memo, tokenid); return result; } From daf34e231501c55ce0b4009c2befd3196b71836b Mon Sep 17 00:00:00 2001 From: dimxy Date: Sun, 27 Jan 2019 17:17:27 +0500 Subject: [PATCH 0079/1145] corrected rpc param size check --- src/wallet/rpcwallet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 2adf931bb..e111ad98a 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -7388,7 +7388,7 @@ UniValue heirfund(const UniValue& params, bool fHelp) return result; } - if(params.size() == 6) // tokens in satoshis: + if(params.size() == 7) // tokens in satoshis: amount = atoll(params[1].get_str().c_str()); else // coins: amount = atof(params[1].get_str().c_str()) * COIN; From 134534b3847fd0a229049b9569f0f9ae920f9f17 Mon Sep 17 00:00:00 2001 From: dimxy Date: Sun, 27 Jan 2019 17:56:08 +0500 Subject: [PATCH 0080/1145] var naming improved --- src/cc/CCHeir.h | 2 +- src/cc/heir.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/CCHeir.h b/src/cc/CCHeir.h index 2943d747c..fa1f72263 100644 --- a/src/cc/CCHeir.h +++ b/src/cc/CCHeir.h @@ -27,7 +27,7 @@ bool HeirValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx, class CoinHelper; class TokenHelper; -UniValue HeirFundCoinCaller(int64_t txfee, int64_t satoshis, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string memo); +UniValue HeirFundCoinCaller(int64_t txfee, int64_t coins, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string memo); UniValue HeirFundTokenCaller(int64_t txfee, int64_t satoshis, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string memo, uint256 tokenid); UniValue HeirClaimCaller(uint256 fundingtxid, int64_t txfee, std::string amount); UniValue HeirAddCaller(uint256 fundingtxid, int64_t txfee, std::string amount); diff --git a/src/cc/heir.cpp b/src/cc/heir.cpp index 8e7f3f08b..04866594d 100644 --- a/src/cc/heir.cpp +++ b/src/cc/heir.cpp @@ -696,8 +696,8 @@ template UniValue _HeirFund(int64_t txfee, int64_t amount, std } // if no these callers - it could not link -UniValue HeirFundCoinCaller(int64_t txfee, int64_t satoshis, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string memo){ - return _HeirFund(txfee, satoshis, heirName, heirPubkey, inactivityTimeSec, memo, zeroid); +UniValue HeirFundCoinCaller(int64_t txfee, int64_t coins, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string memo){ + return _HeirFund(txfee, coins, heirName, heirPubkey, inactivityTimeSec, memo, zeroid); } UniValue HeirFundTokenCaller(int64_t txfee, int64_t satoshis, std::string heirName, CPubKey heirPubkey, int64_t inactivityTimeSec, std::string memo, uint256 tokenid) { From fbd07edee2b011cb6fa62ebb09ec13d2e3ec9e05 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 27 Jan 2019 04:51:48 -1100 Subject: [PATCH 0081/1145] Disable removeorphan --- src/komodo.h | 2 +- src/main.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/komodo.h b/src/komodo.h index 35fee05ad..d3cda4e22 100644 --- a/src/komodo.h +++ b/src/komodo.h @@ -707,7 +707,7 @@ int32_t komodo_voutupdate(int32_t *isratificationp,int32_t notaryid,uint8_t *scr 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 (RemoveOrphanedBlocks(*notarizedheightp)) + if ( 0 && RemoveOrphanedBlocks(*notarizedheightp)) { //fprintf(stderr, "Sucessfully removed all known orphaned blocks before height %d\n",*notarizedheightp); } diff --git a/src/main.cpp b/src/main.cpp index 45989a4f1..f519cab9d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3254,6 +3254,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin //fprintf(stderr,"checkblock failure in connectblock futureblock.%d\n",futureblock); return false; } + // check pindex->CONTEXT_VALIDATED flag if ( fCheckPOW != 0 && !ContextualCheckBlock(block, state, pindex->pprev) ) // Activate Jan 15th, 2019 { fprintf(stderr,"ContextualCheckBlock failed ht.%d\n",(int32_t)pindex->GetHeight()); From 7bd8f456c30bb2bcb500ea77e6687e8ce8deb3fb Mon Sep 17 00:00:00 2001 From: Anton Lysakov Date: Mon, 28 Jan 2019 00:03:25 +0700 Subject: [PATCH 0082/1145] tests adjusted for heirCC json enhancement --- qa/rpc-tests/cryptoconditions_heir.py | 54 +++++++++++++-------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/qa/rpc-tests/cryptoconditions_heir.py b/qa/rpc-tests/cryptoconditions_heir.py index 3aa4ee69c..b79ae7bba 100755 --- a/qa/rpc-tests/cryptoconditions_heir.py +++ b/qa/rpc-tests/cryptoconditions_heir.py @@ -34,21 +34,18 @@ class CryptoconditionsHeirTest(CryptoconditionsTestFramework): # getting empty heir list result = rpc.heirlist() - assert_equal(len(result), 1) - assert_success(result) + assert_equal(result, []) # valid heirfund case with coins - result = rpc.heirfund("0", "1000", "UNITHEIR", self.pubkey1, "10") + result = rpc.heirfund("0", "1000", "UNITHEIR", self.pubkey1, "10", "TESTMEMO") assert_success(result) - heir_fund_txid = self.send_and_mine(result["hextx"], rpc) + heir_fund_txid = self.send_and_mine(result["hex"], rpc) assert heir_fund_txid, "got heir funding txid" # heir fund txid should be in heirlist now result = rpc.heirlist() - assert_equal(len(result), 2) - assert_success(result) - assert_equal(result["fundingtxid"], heir_fund_txid) + assert_equal(result, [heir_fund_txid]) # checking heirinfo result = rpc.heirinfo(heir_fund_txid) @@ -57,20 +54,20 @@ class CryptoconditionsHeirTest(CryptoconditionsTestFramework): assert_equal(result["name"], "UNITHEIR") assert_equal(result["owner"], self.pubkey) assert_equal(result["heir"], self.pubkey1) - assert_equal(result["funding total in coins"], "1000.00000000") - assert_equal(result["funding available in coins"], "1000.00000000") - assert_equal(result["inactivity time setting, sec"], "10") - assert_equal(result["spending allowed for the heir"], "false") - - # TODO: heirlist keys are duplicating now + assert_equal(result["memo"], "TESTMEMO") + assert_equal(result["lifetime"], "1000.00000000") + assert_equal(result["type"], "coins") + assert_equal(result["InactivityTimeSetting"], "10") + assert_equal(result["InactivityTime"], "0") + assert_equal(result["IsHeirSpendingAllowed"], "false") # waiting for 11 seconds to be sure that needed time passed for heir claiming time.sleep(11) rpc.generate(1) self.sync_all() result = rpc.heirinfo(heir_fund_txid) - assert_equal(result["funding available in coins"], "1000.00000000") - assert_equal(result["spending allowed for the heir"], "true") + assert_equal(result["lifetime"], "1000.00000000") + assert_equal(result["IsHeirSpendingAllowed"], "true") # have to check that second node have coins to cover txfee at least rpc.sendtoaddress(rpc1.getnewaddress(), 1) @@ -84,7 +81,7 @@ class CryptoconditionsHeirTest(CryptoconditionsTestFramework): result = rpc1.heirclaim("0", "1000", heir_fund_txid) assert_success(result) - heir_claim_txid = self.send_and_mine(result["hextx"], rpc1) + heir_claim_txid = self.send_and_mine(result["hex"], rpc1) assert heir_claim_txid, "got claim txid" # balance of second node after heirclaim should increase for 1000 coins - txfees @@ -96,7 +93,8 @@ class CryptoconditionsHeirTest(CryptoconditionsTestFramework): # no more funds should be available for claiming result = rpc.heirinfo(heir_fund_txid) - assert_equal(result["funding available in coins"], "0.00000000") + assert_equal(result["lifetime"], "1000.00000000") + assert_equal(result["available"], "0.00000000") # creating tokens which we put to heir contract token_hex = rpc.tokencreate("TEST", "1", "TESTING") @@ -108,8 +106,8 @@ class CryptoconditionsHeirTest(CryptoconditionsTestFramework): assert_equal(result, 100000000) # valid heir case with tokens - token_heir_hex = rpc.heirfund("0", "100000000", "UNITHEIR", self.pubkey1, "10", token_txid) - token_heir_txid = self.send_and_mine(token_heir_hex["hextx"], rpc) + token_heir_hex = rpc.heirfund("0", "100000000", "UNITHEIR", self.pubkey1, "10", "TESTMEMO", token_txid) + token_heir_txid = self.send_and_mine(token_heir_hex["hex"], rpc) assert token_heir_txid, "got txid of heirfund with tokens" self.sync_all() @@ -121,24 +119,25 @@ class CryptoconditionsHeirTest(CryptoconditionsTestFramework): assert_equal(result["name"], "UNITHEIR") assert_equal(result["owner"], self.pubkey) assert_equal(result["heir"], self.pubkey1) - assert_equal(result["funding total in tokens"], "100000000") - assert_equal(result["funding available in tokens"], "100000000") - assert_equal(result["inactivity time setting, sec"], "10") - assert_equal(result["spending allowed for the heir"], "false") + assert_equal(result["lifetime"], "100000000") + assert_equal(result["type"], "tokens") + assert_equal(result["InactivityTimeSetting"], "10") + assert_equal(result["InactivityTime"], "0") + assert_equal(result["IsHeirSpendingAllowed"], "false") # waiting for 11 seconds to be sure that needed time passed for heir claiming time.sleep(11) rpc.generate(1) self.sync_all() result = rpc.heirinfo(token_heir_txid) - assert_equal(result["funding available in tokens"], "100000000") - assert_equal(result["spending allowed for the heir"], "true") + assert_equal(result["lifetime"], "100000000") + assert_equal(result["IsHeirSpendingAllowed"], "true") # let's claim whole heir sum from second node result = rpc1.heirclaim("0", "100000000", token_heir_txid) assert_success(result) - heir_tokens_claim_txid = self.send_and_mine(result["hextx"], rpc1) + heir_tokens_claim_txid = self.send_and_mine(result["hex"], rpc1) assert heir_tokens_claim_txid, "got claim txid" # claiming node should have correct token balance now @@ -149,7 +148,8 @@ class CryptoconditionsHeirTest(CryptoconditionsTestFramework): # no more funds should be available for claiming result = rpc.heirinfo(token_heir_txid) - assert_equal(result["funding available in tokens"], "0") + assert_equal(result["lifetime"], "100000000") + assert_equal(result["available"], "0") def run_test(self): print("Mining blocks...") From 59c67afa11e33705eb6aab1d3f75186f5d0aabb2 Mon Sep 17 00:00:00 2001 From: Mihailo Milenkovic Date: Mon, 28 Jan 2019 13:22:29 +0100 Subject: [PATCH 0083/1145] Fixing FinalizeCCTx to return error if not possible to sign vin. --- src/cc/CCtx.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index ae7483f4d..630a00d8f 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -242,7 +242,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran if ( flag == 0 ) { fprintf(stderr,"CC signing error: vini.%d has unknown CC address.(%s)\n",i,destaddr); - continue; + return(""); } } uint256 sighash = SignatureHash(CCPubKey(cond), mtx, i, SIGHASH_ALL, utxovalues[i],consensusBranchId, &txdata); From 463caf96ec1251afdee1939dc5359ba96e3e6bd5 Mon Sep 17 00:00:00 2001 From: Mihailo Milenkovic Date: Mon, 28 Jan 2019 13:54:21 +0100 Subject: [PATCH 0084/1145] Gateways with new TokensCC (#15) - Adapting Gateways to new Tokens - Making withdraws serialized until solution for parallel is made --- src/cc/CCGateways.h | 3 +- src/cc/CCtx.cpp | 10 +- src/cc/dapps/oraclefeed.c | 184 +++----- src/cc/gateways.cpp | 970 ++++++++++++++++++++++++-------------- src/rpc/server.cpp | 4 +- src/rpc/server.h | 4 +- src/wallet/rpcwallet.cpp | 29 +- 7 files changed, 700 insertions(+), 504 deletions(-) diff --git a/src/cc/CCGateways.h b/src/cc/CCGateways.h index b629ade1f..7ecae2228 100644 --- a/src/cc/CCGateways.h +++ b/src/cc/CCGateways.h @@ -28,10 +28,9 @@ std::string GatewaysWithdraw(uint64_t txfee,uint256 bindtxid,std::string refcoin std::string GatewaysPartialSign(uint64_t txfee,uint256 txidaddr,std::string refcoin,std::string hex); std::string GatewaysCompleteSigning(uint64_t txfee,uint256 txidaddr,std::string refcoin,std::string hex); std::string GatewaysMarkDone(uint64_t txfee,uint256 withdrawtxid,std::string refcoin); +UniValue GatewaysPendingDeposits(uint256 bindtxid,std::string refcoin); UniValue GatewaysPendingWithdraws(uint256 bindtxid,std::string refcoin); UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin); -UniValue GatewaysMultisig(char *txidaddr); - // CCcustom UniValue GatewaysInfo(uint256 bindtxid); diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index 630a00d8f..a8d832661 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -390,9 +390,9 @@ int64_t CCfullsupply(uint256 tokenid) return(0); } -int64_t CCtoken_balance(char *coinaddr,uint256 tokenid) +int64_t CCtoken_balance(char *coinaddr,uint256 reftokenid) { - int64_t price,sum = 0; int32_t numvouts; CTransaction tx; uint256 assetid,assetid2,txid,hashBlock; + int64_t price,sum = 0; int32_t numvouts; CTransaction tx; uint256 tokenid,txid,hashBlock; std::vector vopretExtra; std::vector > unspentOutputs; uint8_t evalCode; @@ -401,11 +401,11 @@ int64_t CCtoken_balance(char *coinaddr,uint256 tokenid) for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { txid = it->first.txhash; - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 ) + if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts=tx.vout.size()) > 0 ) { - char str[65]; fprintf(stderr,"check %s %.8f\n",uint256_str(str,txid),(double)it->second.satoshis/COIN); + char str[65]; std::vector voutTokenPubkeys; - if ( DecodeTokenOpRet(tx.vout[numvouts-1].scriptPubKey, evalCode, assetid, voutTokenPubkeys, vopretExtra) != 0 && assetid == tokenid ) + if ( reftokenid==txid || (DecodeTokenOpRet(tx.vout[numvouts-1].scriptPubKey, evalCode, tokenid, voutTokenPubkeys, vopretExtra) != 0 && reftokenid == tokenid)) { sum += it->second.satoshis; } diff --git a/src/cc/dapps/oraclefeed.c b/src/cc/dapps/oraclefeed.c index 8a819a147..8f7ccb197 100644 --- a/src/cc/dapps/oraclefeed.c +++ b/src/cc/dapps/oraclefeed.c @@ -475,7 +475,7 @@ int32_t get_coinheader(char *refcoin,char *acname,bits256 *blockhashp,bits256 *m cJSON *get_gatewayspending(char *refcoin,char *acname,char *bindtxidstr) { cJSON *retjson; char *retstr; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewayspending",bindtxidstr,refcoin,"","")) != 0 ) + if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewayspendingwithdraws",bindtxidstr,refcoin,"","")) != 0 ) { //printf("pending.(%s)\n",jprint(retjson,0)); return(retjson); @@ -588,13 +588,12 @@ void importaddress(char *refcoin,char *acname,char *depositaddr, char *label,int } } -void addmultisigaddress(char *refcoin,char *acname,int32_t M, char *pubkeys,char *bindtxidstr) +void addmultisigaddress(char *refcoin,char *acname,int32_t M, char *pubkeys) { cJSON *retjson; char *retstr,Mstr[10],tmp[128]; sprintf(Mstr,"%d",M); - sprintf(tmp,"\"%s\"",bindtxidstr); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"addmultisigaddress",Mstr,pubkeys,tmp,"")) != 0 ) + if ( (retjson= get_komodocli(refcoin,&retstr,acname,"addmultisigaddress",Mstr,pubkeys,"","")) != 0 ) { fprintf(stderr,"unexpected addmultisigaddress json.(%s)\n",jprint(retjson,0)); free(retstr); @@ -644,7 +643,6 @@ char *createrawtx(char *refcoin,char *acname,char *depositaddr,char *withdrawadd printf("createrawtx satoshis %.8f < txfee %.8f\n",(double)satoshis/SATOSHIDEN,(double)txfee/SATOSHIDEN); return(0); } - satoshis -= txfee; sprintf(array,"\'[\"%s\"]\'",depositaddr); if ( (retjson= get_komodocli(refcoin,&retstr,acname,"listunspent","1","99999999",array,"")) != 0 ) { @@ -699,7 +697,7 @@ cJSON *addsignature(char *refcoin,char *acname,char *rawtx) { if ( is_cJSON_True(jobj(retjson,"complete")) != 0 ) return(retjson); - else if ( (hexstr= jstr(retjson,"hex")) != 0 && strlen(hexstr) > strlen(rawtx) ) + else if ( (hexstr= jstr(retjson,"hex")) != 0 && strlen(hexstr) > strlen(rawtx) + 2 ) { jaddnum(retjson,"partialtx",1); return(retjson); @@ -714,32 +712,14 @@ cJSON *addsignature(char *refcoin,char *acname,char *rawtx) return(0); } -char *get_gatewaysmultisig(char *refcoin,char *acname,char *txidaddr,int32_t *K) -{ - char *retstr,*hexstr,*hex=0; cJSON *retjson; - if ( (retjson= get_komodocli("KMD",&retstr,acname,"gatewaysmultisig",txidaddr,"","","")) != 0 ) - { - if ((hexstr=jstr(retjson,"hex")) != 0 ) - { - if (strlen(hexstr)>0) hex = clonestr(hexstr); - } - *K=jint(retjson,"number_of_signs"); - free_json(retjson); - } - else if ( retstr != 0 ) - { - printf("error parsing gatewaysmultisig.(%s)\n",retstr); - free(retstr); - } - return(hex); -} - -bits256 gatewayspartialsign(char *refcoin,char *acname,bits256 txid,char *hex) +bits256 gatewayspartialsign(char *refcoin,char *acname,bits256 txid,char *coin,char *hex) { char str[65],*retstr; cJSON *retjson; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewayspartialsign",bits256_str(str,txid),refcoin,hex,"")) != 0 ) + if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewayspartialsign",bits256_str(str,txid),coin,hex,"")) != 0 ) { - return(komodobroadcast(refcoin,acname,retjson)); + txid=komodobroadcast(refcoin,acname,retjson); + free(retjson); + return (txid); } else if ( retstr != 0 ) { @@ -749,36 +729,38 @@ bits256 gatewayspartialsign(char *refcoin,char *acname,bits256 txid,char *hex) return (zeroid); } -void gatewayscompletesigning(char *refcoin,char *acname,bits256 withtxid,char *coin,char *hex) +bits256 gatewayscompletesigning(char *refcoin,char *acname,bits256 withtxid,char *coin,char *hex) { - char str[65],str2[65],*retstr; cJSON *retjson; - printf("spend %s %s/v2 as marker\n",acname,bits256_str(str,withtxid)); + char str[65],str2[65],*retstr; cJSON *retjson; bits256 txid; if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewayscompletesigning",bits256_str(str,withtxid),coin,hex,"")) != 0 ) { - komodobroadcast(refcoin,acname,retjson); - free_json(retjson); + txid=komodobroadcast(refcoin,acname,retjson); + free(retjson); + return (txid); } else if ( retstr != 0 ) { printf("error parsing gatewayscompletesigning.(%s)\n",retstr); free(retstr); } + return (zeroid); } -void gatewaysmarkdone(char *refcoin,char *acname,bits256 withtxid,char *coin) +bits256 gatewaysmarkdone(char *refcoin,char *acname,bits256 withtxid,char *coin) { - char str[65],str2[65],*retstr; cJSON *retjson; - printf("spend %s %s/v2 as marker\n",acname,bits256_str(str,withtxid)); + char str[65],str2[65],*retstr; cJSON *retjson; bits256 txid; if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewaysmarkdone",bits256_str(str,withtxid),coin,"","")) != 0 ) { - komodobroadcast(refcoin,acname,retjson); - free_json(retjson); + txid=komodobroadcast(refcoin,acname,retjson); + free(retjson); + return (txid); } else if ( retstr != 0 ) { printf("error parsing gatewaysmarkdone.(%s)\n",retstr); free(retstr); } + return (zeroid); } int32_t get_gatewaysinfo(char *refcoin,char *acname,char *depositaddr,int32_t *Mp,int32_t *Np,char *bindtxidstr,char *coin,char *oraclestr, char **pubkeys) @@ -882,55 +864,9 @@ int32_t markerexists(char *refcoin,char *acname,char *coinaddr) free_json(array); } } - fprintf(stderr,"Num=%d\n",num); return(num); } -int32_t markerfromthisnodeorunconfirmed(char *refcoin,char *acname,char *coinaddr) -{ - cJSON *array,*item,*rawtx,*vins,*vin; bits256 txid,tmptxid; int32_t i,n,m,num=0; char *retstr; - if ( (array= get_addressutxos(refcoin,acname,coinaddr)) != 0 ) - { - n=cJSON_GetArraySize(array); - for (i=0; i 0 ) - { - num = 1; - break; - } - } - } - free_json(array); - } else return(-1); - } - return(num); -} void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t M,int32_t N) { @@ -941,7 +877,9 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t /// if enough sigs, sendrawtransaction and when it confirms spend marker (txid.2) /// if not enough sigs, post partially signed to acname with marker2 // monitor marker2, for the partially signed withdraws - cJSON *retjson,*pending,*item,*clijson; char str[65],*rawtx,*coinstr,*txidaddr,*signeraddr,*depositaddr,*withdrawaddr; int32_t i,j,n,K,retval,processed = 0; bits256 txid,cointxid,origtxid; int64_t satoshis; + cJSON *retjson,*pending,*item,*clijson; char str[65],str1[65],str2[65],*rawtx,*coinstr,*txidaddr,*signeraddr,*depositaddr,*withdrawaddr; + int32_t i,j,n,K,retval,processed = 0; bits256 txid,cointxid,withdrawtxid,lasttxid,completetxid; int64_t satoshis; + memset(&zeroid,0,sizeof(zeroid)); if ( (retjson= get_gatewayspending("KMD",acname,bindtxidstr)) != 0 ) { @@ -954,52 +892,55 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t if ( processed != 0 ) // avoid out of utxo conditions break; item = jitem(pending,i); - origtxid = jbits256(item,"txid"); + withdrawtxid = jbits256(item,"withdrawtxid"); //process item.0 {"txid":"10ec8f4dad6903df6b249b361b879ac77b0617caad7629b97e10f29fa7e99a9b","txidaddr":"RMbite4TGugVmkGmu76ytPHDEQZQGSUjxz","withdrawaddr":"RNJmgYaFF5DbnrNUX6pMYz9rcnDKC2tuAc","amount":"1.00000000","depositaddr":"RHV2As4rox97BuE3LK96vMeNY8VsGRTmBj","signeraddr":"RHV2As4rox97BuE3LK96vMeNY8VsGRTmBj"} - if ( (txidaddr= jstr(item,"txidaddr")) != 0 && (withdrawaddr= jstr(item,"withdrawaddr")) != 0 && (depositaddr= jstr(item,"depositaddr")) != 0 && (signeraddr= jstr(item,"signeraddr")) != 0 ) + if ( (txidaddr=jstr(item,"withdrawtxidaddr"))!= 0 && (withdrawaddr=jstr(item,"withdrawaddr")) != 0 && (depositaddr= jstr(item,"depositaddr")) != 0 && (signeraddr= jstr(item,"signeraddr")) != 0 ) { - if ( (satoshis= jdouble(item,"amount")*SATOSHIDEN) != 0 && is_cJSON_True(jobj(item,"confirmed_or_notarized")) != 0 && markerfromthisnodeorunconfirmed("KMD",acname,txidaddr) == 0) + if ( (satoshis= jdouble(item,"amount")*SATOSHIDEN) != 0 && is_cJSON_True(jobj(item,"confirmed_or_notarized")) != 0) { if ( strcmp(depositaddr,signeraddr) == 0 ) { rawtx = createrawtx(refcoin,"",depositaddr,withdrawaddr,txidaddr,satoshis); if ( rawtx != 0 ) { - if ( (clijson= addsignature(refcoin,"",rawtx)) != 0 && is_cJSON_True(jobj(clijson,"complete")) != 0) + if ( (clijson=addsignature(refcoin,"",rawtx)) != 0 && is_cJSON_True(jobj(clijson,"complete")) != 0) { - gatewayscompletesigning("KMD",acname,origtxid,refcoin,jstr(clijson,"hex")); - fprintf(stderr,"withdraw %.8f %s to %s processed\n",(double)satoshis/SATOSHIDEN,refcoin,withdrawaddr); + txid=gatewayscompletesigning("KMD",acname,withdrawtxid,refcoin,jstr(clijson,"hex")); + if (txid.txid!=zeroid.txid) fprintf(stderr,"#WITHDRAW (%s) complete signing tx sent - %s\n",bits256_str(str,withdrawtxid),bits256_str(str1,txid)); + else fprintf(stderr,"error broadcasting tx on %s",acname); free_json(clijson); - } - processed++; + processed++; + } free(rawtx); } else fprintf(stderr,"couldnt create rawtx\n"); } else { - if ( (rawtx= get_gatewaysmultisig(refcoin,acname,txidaddr,&K)) == 0) + lasttxid = jbits256(item,"last_txid"); + if ( lasttxid.txid==withdrawtxid.txid) { rawtx = createrawtx(refcoin,"",depositaddr,withdrawaddr,txidaddr,satoshis); } - if ( rawtx != 0 ) + else rawtx=jstr(item,"hex"); + K=jint(item,"number_of_signs"); + if ( (clijson= addsignature(refcoin,"",rawtx)) != 0 ) { - if ( (clijson= addsignature(refcoin,"",rawtx)) != 0 ) - { - if ( is_cJSON_True(jobj(clijson,"complete")) != 0 ) - { - gatewayscompletesigning("KMD",acname,origtxid,refcoin,jstr(clijson,"hex")); - fprintf(stderr,"withdraw %.8f %s M.%d N.%d to %s processed\n",(double)satoshis/SATOSHIDEN,refcoin,M,N,withdrawaddr); - } - else if ( jint(clijson,"partialtx") != 0 ) - { - txid=gatewayspartialsign(refcoin,acname,origtxid,jstr(clijson,"hex")); - fprintf(stderr,"%d sign(s) %dof%d partialtx %s sent\n",K+1,M,N,bits256_str(str,txid)); - } - free_json(clijson); + if ( is_cJSON_True(jobj(clijson,"complete")) != 0 ) + { + txid=gatewayscompletesigning("KMD",acname,lasttxid,refcoin,jstr(clijson,"hex")); + if (txid.txid!=zeroid.txid) fprintf(stderr,"#WITHDRAW (%s) complete signing tx (%dof%d) sent - %s\n",bits256_str(str,withdrawtxid),M,N,bits256_str(str1,txid)); + else fprintf(stderr,"error broadcasting tx on %s",acname); } + else if ( jint(clijson,"partialtx") != 0 ) + { + txid=gatewayspartialsign("KMD",acname,lasttxid,refcoin,jstr(clijson,"hex")); + if (txid.txid!=zeroid.txid) fprintf(stderr,"#WITHDRAW (%s) partial tx (%d/%dof%d) sent - %s\n",bits256_str(str,withdrawtxid),K+1,M,N,bits256_str(str1,txid)); + else fprintf(stderr,"error broadcasting tx on %s",acname); + } + free_json(clijson); processed++; - free(rawtx); - } else fprintf(stderr,"couldnt create msig rawtx\n"); + } + free(rawtx); } } } @@ -1012,24 +953,27 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t { if ( jint(retjson,"queueflag") != 0 && (coinstr= jstr(retjson,"coin")) != 0 && strcmp(coinstr,refcoin) == 0 ) { - if ( (pending=jarray(&n,retjson,"processed")) != 0 ) + if ((pending=jarray(&n,retjson,"processed")) != 0) { for (i=0; i pubkeys,uint8_t taddr,uint8_t prefix,uint8_t prefix2) +CScript EncodeGatewaysBindOpRet(uint8_t funcid,uint256 tokenid,std::string coin,int64_t totalsupply,uint256 oracletxid,uint8_t M,uint8_t N,std::vector gatewaypubkeys,uint8_t taddr,uint8_t prefix,uint8_t prefix2) { - CScript opret; uint8_t evalcode = EVAL_GATEWAYS; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << coin << prefix << prefix2 << taddr << tokenid << totalsupply << M << N << pubkeys << oracletxid); - return(opret); + CScript opret; uint8_t evalcode = EVAL_GATEWAYS; struct CCcontract_info *cp,C; CPubKey gatewayspk; + std::vector pubkeys; + + cp = CCinit(&C,EVAL_GATEWAYS); + gatewayspk = GetUnspendable(cp,0); + pubkeys.push_back(gatewayspk); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << coin << totalsupply << oracletxid << M << N << gatewaypubkeys << taddr << prefix << prefix2); + return(EncodeTokenOpRet(tokenid,pubkeys,opret)); } -uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,std::string &coin,uint256 &tokenid,int64_t &totalsupply,uint256 &oracletxid,uint8_t &M,uint8_t &N,std::vector &pubkeys,uint8_t &taddr,uint8_t &prefix,uint8_t &prefix2) +uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,uint256 &tokenid,std::string &coin,int64_t &totalsupply,uint256 &oracletxid,uint8_t &M,uint8_t &N,std::vector &gatewaypubkeys,uint8_t &taddr,uint8_t &prefix,uint8_t &prefix2) { - std::vector vopret; uint8_t *script,e,f; - GetOpReturnData(scriptPubKey, vopret); + std::vector vopret; uint8_t *script,e,f,tokenevalcode; + std::vector vOpretExtra; std::vector pubkeys; + + if (DecodeTokenOpRet(scriptPubKey,tokenevalcode,tokenid,pubkeys,vOpretExtra)!=0 && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) + { + if (!E_UNMARSHAL(vOpretExtra, { ss >> vopret; })) return (0); + } + else GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); depositaddr[0] = 0; - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> coin; ss >> prefix; ss >> prefix2; ss >> taddr; ss >> tokenid; ss >> totalsupply; ss >> M; ss >> N; ss >> pubkeys; ss >> oracletxid) != 0 ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> coin; ss >> totalsupply; ss >> oracletxid; ss >> M; ss >> N; ss >> gatewaypubkeys; ss >> taddr; ss >> prefix; ss >> prefix2;) != 0 ) { if ( prefix == 60 ) { if ( N > 1 ) { - strcpy(depositaddr,CBitcoinAddress(CScriptID(GetScriptForMultisig(M,pubkeys))).ToString().c_str()); - //Getscriptaddress(depositaddr,GetScriptForMultisig(M,pubkeys)); - fprintf(stderr,"f.%c M.%d of N.%d size.%d -> %s\n",f,M,N,(int32_t)pubkeys.size(),depositaddr); - } else Getscriptaddress(depositaddr,CScript() << ParseHex(HexStr(pubkeys[0])) << OP_CHECKSIG); + strcpy(depositaddr,CBitcoinAddress(CScriptID(GetScriptForMultisig(M,gatewaypubkeys))).ToString().c_str()); + //fprintf(stderr,"f.%c M.%d of N.%d size.%d -> %s\n",f,M,N,(int32_t)gatewaypubkeys.size(),depositaddr); + } else Getscriptaddress(depositaddr,CScript() << ParseHex(HexStr(gatewaypubkeys[0])) << OP_CHECKSIG); } else { @@ -189,118 +190,134 @@ uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,st return(0); } -CScript EncodeGatewaysDepositOpRet(uint8_t funcid,std::string coin,uint256 bindtxid,std::vector publishers,std::vectortxids,int32_t height,uint256 cointxid,int32_t claimvout,std::string deposithex,std::vectorproof,CPubKey destpub,int64_t amount) +CScript EncodeGatewaysDepositOpRet(uint8_t funcid,uint256 bindtxid,std::string refcoin,std::vector publishers,std::vectortxids,int32_t height,uint256 cointxid,int32_t claimvout,std::string deposithex,std::vectorproof,CPubKey destpub,int64_t amount) { CScript opret; uint8_t evalcode = EVAL_GATEWAYS; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << coin << bindtxid << publishers << txids << height << cointxid << claimvout << deposithex << proof << destpub << amount); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << refcoin << bindtxid << publishers << txids << height << cointxid << claimvout << deposithex << proof << destpub << amount); return(opret); } -uint8_t DecodeGatewaysDepositOpRet(const CScript &scriptPubKey,std::string &coin,uint256 &bindtxid,std::vector&publishers,std::vector&txids,int32_t &height,uint256 &cointxid, int32_t &claimvout,std::string &deposithex,std::vector &proof,CPubKey &destpub,int64_t &amount) +uint8_t DecodeGatewaysDepositOpRet(const CScript &scriptPubKey,uint256 &bindtxid,std::string &refcoin,std::vector&publishers,std::vector&txids,int32_t &height,uint256 &cointxid, int32_t &claimvout,std::string &deposithex,std::vector &proof,CPubKey &destpub,int64_t &amount) { std::vector vopret; uint8_t *script,e,f; GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> coin; ss >> bindtxid; ss >> publishers; ss >> txids; ss >> height; ss >> cointxid; ss >> claimvout; ss >> deposithex; ss >> proof; ss >> destpub; ss >> amount) != 0 ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> refcoin; ss >> bindtxid; ss >> publishers; ss >> txids; ss >> height; ss >> cointxid; ss >> claimvout; ss >> deposithex; ss >> proof; ss >> destpub; ss >> amount) != 0 ) { return(f); } return(0); } -// encodes payload for the token opret (needs to be added to the tail of it) -CScript EncodeGatewaysClaimOpRet(uint8_t funcid, std::string refcoin, uint256 bindtxid, uint256 deposittxid, CPubKey destpub, int64_t amount) +CScript EncodeGatewaysClaimOpRet(uint8_t funcid,uint256 tokenid,uint256 bindtxid,std::string refcoin,uint256 deposittxid,CPubKey destpub,int64_t amount) { - CScript opret; + CScript opret; uint8_t evalcode = EVAL_GATEWAYS; struct CCcontract_info *cp,C; CPubKey gatewayspk; + std::vector pubkeys; - opret << OP_RETURN << E_MARSHAL(ss << funcid << refcoin << bindtxid << deposittxid << destpub << amount); - return(opret); + pubkeys.push_back(destpub); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << bindtxid << refcoin << deposittxid << destpub << amount); + return(EncodeTokenOpRet(tokenid,pubkeys,opret)); } -uint8_t DecodeGatewaysClaimOpRet(const CScript &scriptPubKey,uint256 &tokenid,std::string &refcoin,uint256 &bindtxid,uint256 &deposittxid,CPubKey &destpub,int64_t &amount) +uint8_t DecodeGatewaysClaimOpRet(const CScript &scriptPubKey,uint256 &tokenid,uint256 &bindtxid,std::string &refcoin,uint256 &deposittxid,CPubKey &destpub,int64_t &amount) { - std::vector vopret; uint8_t *script,e,f; - GetOpReturnData(scriptPubKey, vopret); + std::vector vopret; uint8_t *script,e,f,tokenevalcode; + std::vector pubkeys; std::vector vOpretExtra; + + if (DecodeTokenOpRet(scriptPubKey,tokenevalcode,tokenid,pubkeys,vOpretExtra)!=0 && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) + { + if (!E_UNMARSHAL(vOpretExtra, { ss >> vopret; })) return (0); + } + else GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> tokenid; ss >> refcoin; ss >> bindtxid; ss >> deposittxid; ss >> destpub; ss >> amount) != 0 ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> bindtxid; ss >> refcoin; ss >> deposittxid; ss >> destpub; ss >> amount) != 0 ) { return(f); } return(0); } -CScript EncodeGatewaysWithdrawOpRet(uint8_t funcid, std::string refcoin, CPubKey withdrawpub, int64_t amount) +CScript EncodeGatewaysWithdrawOpRet(uint8_t funcid,uint256 tokenid,uint256 bindtxid,std::string refcoin,CPubKey withdrawpub,int64_t amount) { - CScript opret; - opret << OP_RETURN << E_MARSHAL(ss << funcid << refcoin << withdrawpub << amount); - return(opret); + CScript opret; uint8_t evalcode = EVAL_GATEWAYS; struct CCcontract_info *cp,C; CPubKey gatewayspk; + std::vector pubkeys; + + cp = CCinit(&C,EVAL_GATEWAYS); + gatewayspk = GetUnspendable(cp,0); + pubkeys.push_back(gatewayspk); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << bindtxid << refcoin << withdrawpub << amount); + return(EncodeTokenOpRet(tokenid,pubkeys,opret)); } -uint8_t DecodeGatewaysWithdrawOpRet(const CScript &scriptPubKey, uint256 &tokenid, std::string &refcoin, CPubKey &withdrawpub, int64_t &amount) +uint8_t DecodeGatewaysWithdrawOpRet(const CScript &scriptPubKey, uint256& tokenid, uint256 &bindtxid, std::string &refcoin, CPubKey &withdrawpub, int64_t &amount) { - std::vector vopret; uint8_t *script,e,f; + std::vector vopret; uint8_t *script,e,f,tokenevalcode; + std::vector pubkeys; std::vector vOpretExtra; - - GetOpReturnData(scriptPubKey, vopret); + if (DecodeTokenOpRet(scriptPubKey,tokenevalcode,tokenid,pubkeys,vOpretExtra)!=0 && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) + { + if (!E_UNMARSHAL(vOpretExtra, { ss >> vopret; })) return (0); + } + else GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> tokenid; ss >> refcoin; ss >> withdrawpub; ss >> amount) != 0 ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> bindtxid; ss >> refcoin; ss >> withdrawpub; ss >> amount) != 0 ) { return(f); } return(0); } -CScript EncodeGatewaysPartialOpRet(uint8_t funcid,int32_t K, CPubKey signerpk, std::string refcoin,std::string hex) +CScript EncodeGatewaysPartialOpRet(uint8_t funcid, uint256 withdrawtxid,std::string refcoin,int32_t K, CPubKey signerpk,std::string hex) { CScript opret; uint8_t evalcode = EVAL_GATEWAYS; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << K << signerpk << refcoin << hex); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << withdrawtxid << refcoin << K << signerpk << hex); return(opret); } -uint8_t DecodeGatewaysPartialOpRet(const CScript &scriptPubKey,int32_t &K, CPubKey &signerpk, std::string &refcoin,std::string &hex) +uint8_t DecodeGatewaysPartialOpRet(const CScript &scriptPubKey,uint256 &withdrawtxid,std::string &refcoin,int32_t &K, CPubKey &signerpk,std::string &hex) { std::vector vopret; uint8_t *script,e,f; GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> K; ss >> signerpk; ss >> refcoin; ss >> hex) != 0 ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> withdrawtxid; ss >> refcoin; ss >> K; ss >> signerpk; ss >> hex) != 0 ) { return(f); } return(0); } -CScript EncodeGatewaysCompleteSigningOpRet(uint8_t funcid,std::string refcoin,uint256 withdrawtxid,std::string hex) +CScript EncodeGatewaysCompleteSigningOpRet(uint8_t funcid,uint256 withdrawtxid,std::string refcoin,std::string hex) { CScript opret; uint8_t evalcode = EVAL_GATEWAYS; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << refcoin << withdrawtxid << hex); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << withdrawtxid << refcoin << hex); return(opret); } -uint8_t DecodeGatewaysCompleteSigningOpRet(const CScript &scriptPubKey, std::string &refcoin, uint256 &withdrawtxid,std::string &hex) +uint8_t DecodeGatewaysCompleteSigningOpRet(const CScript &scriptPubKey,uint256 &withdrawtxid,std::string &refcoin,std::string &hex) { std::vector vopret; uint8_t *script,e,f; GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> refcoin; ss >> withdrawtxid; ss >> hex) != 0 ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> withdrawtxid; ss >> refcoin; ss >> hex) != 0 ) { return(f); } return(0); } -CScript EncodeGatewaysMarkDoneOpRet(uint8_t funcid,std::string refcoin,uint256 withdrawtxid) +CScript EncodeGatewaysMarkDoneOpRet(uint8_t funcid,std::string refcoin,uint256 completetxid,uint256 withdrawtxid) { CScript opret; uint8_t evalcode = EVAL_GATEWAYS; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << refcoin << withdrawtxid); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << refcoin << completetxid < vopret; uint8_t *script,e,f; GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> refcoin; ss >> withdrawtxid;) != 0 ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> refcoin; ss >> completetxid; ss >> withdrawtxid;) != 0 ) { return(f); } @@ -309,12 +326,19 @@ uint8_t DecodeGatewaysMarkDoneOpRet(const CScript &scriptPubKey, std::string &re uint8_t DecodeGatewaysOpRet(const CScript &scriptPubKey) { - std::vector vopret; uint8_t *script,e,f; - GetOpReturnData(scriptPubKey, vopret); - script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && (script[0] == EVAL_GATEWAYS || script[0] == EVAL_TOKENS) && E_UNMARSHAL(vopret,ss >> e; ss >> f) != 0 ) + std::vector vopret; uint8_t *script,e,f,tokenevalcode; + std::vector pubkeys; std::vector vOpretExtra; uint256 tokenid; + + if (DecodeTokenOpRet(scriptPubKey,tokenevalcode,tokenid,pubkeys,vOpretExtra)!=0 && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) { - if (f == 'B' && f == 'D' && f == 't' && f == 'W' && f == 'P' && f == 'M') + if (!E_UNMARSHAL(vOpretExtra, { ss >> vopret; })) return (0); + } + else GetOpReturnData(scriptPubKey, vopret); + script = (uint8_t *)vopret.data(); + if ( vopret.size() > 2 && script[0] == EVAL_GATEWAYS) + { + f=script[1]; + if (f == 'B' || f == 'D' || f == 'C' || f == 'W' || f == 'P' || f == 'S' || f == 'M') return(f); } return(0); @@ -429,7 +453,7 @@ uint256 GatewaysReverseScan(uint256 &txid,int32_t height,uint256 reforacletxid,u return(zeroid); } -int32_t GatewaysCointxidExists(struct CCcontract_info *cp,uint256 cointxid) // dont forget to check mempool! +int32_t GatewaysCointxidExists(struct CCcontract_info *cp,uint256 cointxid) { char txidaddr[64]; std::string coin; int32_t numvouts; uint256 hashBlock; std::vector > addressIndex; @@ -457,7 +481,9 @@ uint256 BitcoinGetProofMerkleRoot(const std::vector &proofData, std::ve int64_t GatewaysVerify(char *refdepositaddr,uint256 oracletxid,int32_t claimvout,std::string refcoin,uint256 cointxid,const std::string deposithex,std::vectorproof,uint256 merkleroot,CPubKey destpub) { - std::vector txids; uint256 proofroot,hashBlock,txid = zeroid; CTransaction tx; std::string name,description,format; char destaddr[64],destpubaddr[64],claimaddr[64],str[65],str2[65]; int32_t i,numvouts; int64_t nValue = 0; + std::vector txids; uint256 proofroot,hashBlock,txid = zeroid; CTransaction tx; std::string name,description,format; + char destaddr[64],destpubaddr[64],claimaddr[64],str[65],str2[65]; int32_t i,numvouts; int64_t nValue = 0; + if ( myGetTransaction(oracletxid,tx,hashBlock) == 0 || (numvouts= tx.vout.size()) <= 0 ) { fprintf(stderr,"GatewaysVerify cant find oracletxid %s\n",uint256_str(str,oracletxid)); @@ -505,7 +531,7 @@ int64_t GatewaysDepositval(CTransaction tx,CPubKey mypk) int32_t numvouts,claimvout,height; int64_t amount; std::string coin,deposithex; std::vector publishers; std::vectortxids; uint256 bindtxid,cointxid; std::vector proof; CPubKey claimpubkey; if ( (numvouts= tx.vout.size()) > 0 ) { - if ( DecodeGatewaysDepositOpRet(tx.vout[numvouts-1].scriptPubKey,coin,bindtxid,publishers,txids,height,cointxid,claimvout,deposithex,proof,claimpubkey,amount) == 'D' && claimpubkey == mypk ) + if ( DecodeGatewaysDepositOpRet(tx.vout[numvouts-1].scriptPubKey,bindtxid,coin,publishers,txids,height,cointxid,claimvout,deposithex,proof,claimpubkey,amount) == 'D' && claimpubkey == mypk ) { // coin, bindtxid, publishers fprintf(stderr,"need to validate deposittxid more\n"); @@ -574,74 +600,74 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & //vout.0: CC vout of total tokens from deposit amount to asset eval code //(vout.1): CC vout if there is change of unused tokens back to owner of tokens (deposit amount less than available tokens) //vout.n-1: opreturn - 't' tokenid zeroid 0 mypubkey (NOTE: opreturn is with asset eval code) - if ((numvouts=tx.vout.size()) > 0 && DecodeGatewaysClaimOpRet(tx.vout[numvouts-1].scriptPubKey,tokenidClaim,refcoin,bindtxid,deposittxid,destpub,amount)==0) - return eval->Invalid("invalid gatewaysclaim OP_RETURN data!"); - else if ( IsCCInput(tx.vin[0].scriptSig) != 0 ) - return eval->Invalid("vin.0 is normal for gatewaysClaim!"); - else if ( IsCCInput(tx.vin[1].scriptSig) == 0 ) - return eval->Invalid("vin.1 is CC for gatewaysClaim!"); - else if ( IsCCInput(tx.vin[2].scriptSig) == 0 ) - return eval->Invalid("vin.2 is CC for gatewaysClaim!"); - else if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) - return eval->Invalid("vout.0 is CC for gatewaysClaim!"); - else if ( numvouts > 2 && tx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 ) - return eval->Invalid("vout.1 is CC for gatewaysClaim!"); - else if (myGetTransaction(bindtxid,bindtx,hashblock) == 0) - return eval->Invalid("invalid gatewaysbind txid!"); - else if ((numvouts=bindtx.vout.size()) > 0 && DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tmprefcoin,tokenidBind,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B') - return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); - else if (tmprefcoin!=refcoin) - return eval->Invalid("refcoin different in bind tx"); - else if (tokenidClaim!=tokenidBind) - return eval->Invalid("tokenid does not match tokenid from gatewaysbind"); - else if (komodo_txnotarizedconfirmed(bindtxid) == false) - return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); - else if (myGetTransaction(deposittxid,deposittx,hashblock) == 0) - return eval->Invalid("invalid gatewaysdeposittxid!"); - else if ((numvouts=deposittx.vout.size()) > 0 && DecodeGatewaysDepositOpRet(deposittx.vout[numvouts-1].scriptPubKey,tmprefcoin,tmptxid,tmppublishers,txids,height,cointxid,claimvout,deposithex,proof,tmpdestpub,tmpamount) != 'D') - return eval->Invalid("invalid gatewaysdeposit OP_RETURN data!"); - else if (tmprefcoin!=refcoin) - return eval->Invalid("refcoin different in deposit tx"); - else if (bindtxid!=tmptxid) - return eval->Invalid("bindtxid does not match to bindtxid from gatewaysdeposit"); - else if (tmpamount>totalsupply) - return eval->Invalid("deposit amount greater then bind total supply"); - else if (komodo_txnotarizedconfirmed(deposittxid) == false) - return eval->Invalid("gatewaysdeposit tx is not yet confirmed(notarised)!"); - else if (amount>tmpamount) - return eval->Invalid("claimed amount greater then deposit amount"); - else if (destpub!=tmpdestpub) - return eval->Invalid("destination pubkey different than in deposit tx"); - else - { - int32_t m; - merkleroot = zeroid; - for (i=m=0; iInvalid(validationError); - } - if ( GatewaysCointxidExists(cp,cointxid) != 0 ) - { - sprintf(validationError,"cointxid.%s already exists\n",uint256_str(str,cointxid)); - return eval->Invalid(validationError); - } - if (GatewaysVerify(depositaddr,oracletxid,claimvout,tmprefcoin,cointxid,deposithex,proof,merkleroot,destpub)!=amount) - return eval->Invalid("deposittxid didnt validate\n"); - } + // if ((numvouts=tx.vout.size()) > 0 && DecodeGatewaysClaimOpRet(tx.vout[numvouts-1].scriptPubKey,tokenidClaim,refcoin,bindtxid,deposittxid,destpub,amount)==0) + // return eval->Invalid("invalid gatewaysclaim OP_RETURN data!"); + // else if ( IsCCInput(tx.vin[0].scriptSig) != 0 ) + // return eval->Invalid("vin.0 is normal for gatewaysClaim!"); + // else if ( IsCCInput(tx.vin[1].scriptSig) == 0 ) + // return eval->Invalid("vin.1 is CC for gatewaysClaim!"); + // else if ( IsCCInput(tx.vin[2].scriptSig) == 0 ) + // return eval->Invalid("vin.2 is CC for gatewaysClaim!"); + // else if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) + // return eval->Invalid("vout.0 is CC for gatewaysClaim!"); + // else if ( numvouts > 2 && tx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 ) + // return eval->Invalid("vout.1 is CC for gatewaysClaim!"); + // else if (myGetTransaction(bindtxid,bindtx,hashblock) == 0) + // return eval->Invalid("invalid gatewaysbind txid!"); + // else if ((numvouts=bindtx.vout.size()) > 0 && DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tmprefcoin,tokenidBind,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B') + // return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); + // else if (tmprefcoin!=refcoin) + // return eval->Invalid("refcoin different in bind tx"); + // else if (tokenidClaim!=tokenidBind) + // return eval->Invalid("tokenid does not match tokenid from gatewaysbind"); + // else if (komodo_txnotarizedconfirmed(bindtxid) == false) + // return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); + // else if (myGetTransaction(deposittxid,deposittx,hashblock) == 0) + // return eval->Invalid("invalid gatewaysdeposittxid!"); + // else if ((numvouts=deposittx.vout.size()) > 0 && DecodeGatewaysDepositOpRet(deposittx.vout[numvouts-1].scriptPubKey,tmprefcoin,tmptxid,tmppublishers,txids,height,cointxid,claimvout,deposithex,proof,tmpdestpub,tmpamount) != 'D') + // return eval->Invalid("invalid gatewaysdeposit OP_RETURN data!"); + // else if (tmprefcoin!=refcoin) + // return eval->Invalid("refcoin different in deposit tx"); + // else if (bindtxid!=tmptxid) + // return eval->Invalid("bindtxid does not match to bindtxid from gatewaysdeposit"); + // else if (tmpamount>totalsupply) + // return eval->Invalid("deposit amount greater then bind total supply"); + // else if (komodo_txnotarizedconfirmed(deposittxid) == false) + // return eval->Invalid("gatewaysdeposit tx is not yet confirmed(notarised)!"); + // else if (amount>tmpamount) + // return eval->Invalid("claimed amount greater then deposit amount"); + // else if (destpub!=tmpdestpub) + // return eval->Invalid("destination pubkey different than in deposit tx"); + // else + // { + // int32_t m; + // merkleroot = zeroid; + // for (i=m=0; iInvalid(validationError); + // } + // if ( GatewaysCointxidExists(cp,cointxid) != 0 ) + // { + // sprintf(validationError,"cointxid.%s already exists\n",uint256_str(str,cointxid)); + // return eval->Invalid(validationError); + // } + // if (GatewaysVerify(depositaddr,oracletxid,claimvout,tmprefcoin,cointxid,deposithex,proof,merkleroot,destpub)!=amount) + // return eval->Invalid("deposittxid didnt validate\n"); + // } break; case 'W': //vin.0: normal input @@ -669,8 +695,6 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & break; } } - - retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts); if ( retval != 0 ) fprintf(stderr,"Gatewaysget validated\n"); @@ -683,65 +707,81 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & // helper functions for rpc calls in rpcwallet.cpp -int64_t AddGatewaysInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,uint256 reftokenid,int64_t total,int32_t maxinputs) +int64_t AddGatewaysInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,uint256 bindtxid,int64_t total,int32_t maxinputs) { - char coinaddr[64],destaddr[64]; int64_t threshold,nValue,price,totalinputs = 0; uint256 tokenid,txid,hashBlock; std::vector origpubkey; std::vector vopret; CTransaction vintx; int32_t j,vout,n = 0; uint8_t evalcode,funcid; - std::vector > unspentOutputs; - GetCCaddress(cp,coinaddr,pk); - SetCCunspents(unspentOutputs,coinaddr); - threshold = total/(maxinputs+1); - //fprintf(stderr,"check %s for gateway inputs\n",coinaddr); - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) + char coinaddr[64],depositaddr[64]; int64_t threshold,nValue,price,totalinputs = 0,totalsupply,amount; + CTransaction vintx,bindtx; int32_t vout,numvouts,n = 0; uint8_t M,N,evalcode,funcid,taddr,prefix,prefix2; std::vector pubkeys; + std::vector > unspentOutputs; std::string refcoin,tmprefcoin; CPubKey withdrawpub,destpub; + uint256 tokenid,txid,oracletxid,tmpbindtxid,tmptokenid,deposittxid,hashBlock; + + if ( GetTransaction(bindtxid,bindtx,hashBlock,false) != 0 ) { - txid = it->first.txhash; - vout = (int32_t)it->first.index; - if ( it->second.satoshis < threshold ) - continue; - for (j=0; jsecond.satoshis/COIN); - if ( strcmp(destaddr,coinaddr) != 0 && strcmp(destaddr,cp->unspendableCCaddr) != 0 && strcmp(destaddr,cp->unspendableaddr2) != 0 ) - continue; - GetOpReturnData(vintx.vout[vintx.vout.size()-1].scriptPubKey, vopret); - if ( E_UNMARSHAL(vopret,ss >> evalcode; ss >> funcid; ss >> tokenid) != 0 ) + GetTokensCCaddress(cp,coinaddr,pk); + SetCCunspents(unspentOutputs,coinaddr); + threshold = total/(maxinputs+1); + fprintf(stderr,"check %s for gateway inputs\n",coinaddr); + for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { - tokenid = revuint256(tokenid); - char str[65],str2[65]; fprintf(stderr,"vout.%d %d:%d (%c) check for reftokenid.%s vs %s %.8f\n",vout,evalcode,cp->evalcode,funcid,uint256_str(str,reftokenid),uint256_str(str2,tokenid),(double)vintx.vout[vout].nValue/COIN); - if ( tokenid == reftokenid && funcid == 't' && (nValue= vintx.vout[vout].nValue) > 0 && myIsutxo_spentinmempool(txid,vout) == 0 ) + txid = it->first.txhash; + vout = (int32_t)it->first.index; + if ( it->second.satoshis < threshold ) + continue; + // for (j=0; jsecond.satoshis/COIN); - if ( total != 0 && maxinputs != 0 ) + funcid=DecodeGatewaysOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey); + if (vout==0 && funcid=='B' && bindtxid==txid && total != 0 && maxinputs != 0) + { mtx.vin.push_back(CTxIn(txid,vout,CScript())); - //nValue = it->second.satoshis; - totalinputs += nValue; - n++; - if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) ) - break; + totalinputs += it->second.satoshis; + n++; + if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs)) break; + } + else if (vout==1 && funcid=='W' && DecodeGatewaysWithdrawOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey,tmptokenid,tmpbindtxid,tmprefcoin,withdrawpub,amount) == 'W' && + tmpbindtxid==bindtxid && tmprefcoin==refcoin && tmptokenid==tokenid && total != 0 && maxinputs != 0) + { + mtx.vin.push_back(CTxIn(txid,vout,CScript())); + totalinputs += it->second.satoshis; + n++; + if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs)) break; + } + else if (vout==1 && funcid=='C' && DecodeGatewaysClaimOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey,tmptokenid,tmpbindtxid,tmprefcoin,deposittxid,destpub,amount) == 'C' && + tmpbindtxid==bindtxid && tmprefcoin==refcoin && tmptokenid==tokenid && total != 0 && maxinputs != 0) + { + mtx.vin.push_back(CTxIn(txid,vout,CScript())); + totalinputs += it->second.satoshis; + n++; + if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs)) break; + } } } + return(totalinputs); } + else fprintf(stderr,"invalid GatewaysBind\n"); } - return(totalinputs); + else fprintf(stderr,"can't find GatewaysBind txid\n"); + return(0); } -int32_t GatewaysBindExists(struct CCcontract_info *cp,CPubKey gatewayspk,uint256 reftokenid) // dont forget to check mempool! +int32_t GatewaysBindExists(struct CCcontract_info *cp,CPubKey gatewayspk,uint256 reftokenid) { - char markeraddr[64],depositaddr[64]; std::string coin; int32_t numvouts; int64_t totalsupply; uint256 tokenid,oracletxid,hashBlock; uint8_t M,N,taddr,prefix,prefix2; std::vector pubkeys; CTransaction tx; + char markeraddr[64],depositaddr[64]; std::string coin; int32_t numvouts; int64_t totalsupply; uint256 tokenid,oracletxid,hashBlock; + uint8_t M,N,taddr,prefix,prefix2; std::vector pubkeys; CTransaction tx; std::vector > addressIndex; + _GetCCaddress(markeraddr,EVAL_GATEWAYS,gatewayspk); - fprintf(stderr,"bind markeraddr.(%s) need to scan mempool also\n",markeraddr); SetCCtxids(addressIndex,markeraddr); for (std::vector >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) { if ( GetTransaction(it->first.txhash,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 ) { - if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,coin,tokenid,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) == 'B' ) + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) == 'B' ) { if ( tokenid == reftokenid ) { @@ -751,15 +791,29 @@ int32_t GatewaysBindExists(struct CCcontract_info *cp,CPubKey gatewayspk,uint256 } } } + BOOST_FOREACH(const CTxMemPoolEntry &e, mempool.mapTx) + { + const CTransaction &txmempool = e.GetTx(); + const uint256 &hash = txmempool.GetHash(); + + if ((numvouts=txmempool.vout.size()) > 0 && DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) == 'B' && + tokenid == reftokenid) + return(1); + } + return(0); } std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t totalsupply,uint256 oracletxid,uint8_t M,uint8_t N,std::vector pubkeys) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CTransaction oracletx; uint8_t taddr,prefix,prefix2; CPubKey mypk,gatewayspk; CScript opret; uint256 hashBlock; struct CCcontract_info *cp,C; std::string name,description,format; int32_t i,numvouts; int64_t fullsupply; char destaddr[64],coinaddr[64],str[65],*fstr; + CTransaction oracletx; uint8_t taddr,prefix,prefix2; CPubKey mypk,gatewayspk; CScript opret; uint256 hashBlock; + struct CCcontract_info *cp,*cpTokens,C,CTokens; std::string name,description,format; int32_t i,numvouts; int64_t fullsupply; + char destaddr[64],coinaddr[64],myTokenCCaddr[64],str[65],*fstr; + cp = CCinit(&C,EVAL_GATEWAYS); - if ( strcmp((char *)"KMD",coin.c_str()) == 0 ) + cpTokens = CCinit(&CTokens,EVAL_TOKENS); + if (coin=="KMD") { taddr = 0; prefix = 60; @@ -794,20 +848,21 @@ std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); + _GetCCaddress(myTokenCCaddr,EVAL_TOKENS,mypk); gatewayspk = GetUnspendable(cp,0); if ( _GetCCaddress(destaddr,EVAL_GATEWAYS,gatewayspk) == 0 ) { fprintf(stderr,"Gateway bind.%s (%s) cant create globaladdr\n",coin.c_str(),uint256_str(str,tokenid)); return(""); } - if ( (fullsupply= CCfullsupply(tokenid)) != totalsupply ) + if ( (fullsupply=CCfullsupply(tokenid)) != totalsupply ) { fprintf(stderr,"Gateway bind.%s (%s) globaladdr.%s totalsupply %.8f != fullsupply %.8f\n",coin.c_str(),uint256_str(str,tokenid),cp->unspendableCCaddr,(double)totalsupply/COIN,(double)fullsupply/COIN); return(""); } - if ( CCtoken_balance(destaddr,tokenid) != totalsupply ) + if ( CCtoken_balance(myTokenCCaddr,tokenid) != totalsupply ) { - fprintf(stderr,"Gateway bind.%s (%s) destaddr.%s globaladdr.%s token balance %.8f != %.8f\n",coin.c_str(),uint256_str(str,tokenid),destaddr,cp->unspendableCCaddr,(double)CCtoken_balance(destaddr,tokenid)/COIN,(double)totalsupply/COIN); + fprintf(stderr,"token balance on %s %.8f != %.8f\n",myTokenCCaddr,(double)CCtoken_balance(myTokenCCaddr,tokenid)/COIN,(double)totalsupply/COIN); return(""); } if ( GetTransaction(oracletxid,oracletx,hashBlock,false) == 0 || (numvouts= oracletx.vout.size()) <= 0 ) @@ -820,20 +875,24 @@ std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t fprintf(stderr,"mismatched oracle name %s != %s\n",name.c_str(),coin.c_str()); return(""); } - if ( (fstr= (char *)format.c_str()) == 0 || strncmp(fstr,"Ihh",3) != 0 ) + if ( (fstr=(char *)format.c_str()) == 0 || strncmp(fstr,"Ihh",3) != 0 ) { fprintf(stderr,"illegal format (%s) != (%s)\n",fstr,(char *)"Ihh"); return(""); } - if ( GatewaysBindExists(cp,gatewayspk,tokenid) != 0 ) // dont forget to check mempool! + if ( GatewaysBindExists(cp,gatewayspk,tokenid) != 0 ) { fprintf(stderr,"Gateway bind.%s (%s) already exists\n",coin.c_str(),uint256_str(str,tokenid)); return(""); } if ( AddNormalinputs(mtx,mypk,2*txfee,3) > 0 ) { - mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,gatewayspk)); - return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysBindOpRet('B',coin,tokenid,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2))); + if (AddTokenCCInputs(cpTokens, mtx, mypk, tokenid, totalsupply, 64)>0) + { + mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,totalsupply,gatewayspk)); + mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,gatewayspk)); + return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysBindOpRet('B',tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2))); + } } CCerror = strprintf("cant find enough inputs"); fprintf(stderr,"%s\n", CCerror.c_str() ); @@ -843,7 +902,7 @@ std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t std::string GatewaysDeposit(uint64_t txfee,uint256 bindtxid,int32_t height,std::string refcoin,uint256 cointxid,int32_t claimvout,std::string deposithex,std::vectorproof,CPubKey destpub,int64_t amount) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CTransaction bindtx; CPubKey mypk,gatewayspk; uint256 oracletxid,merkleroot,mhash,hashBlock,tokenid,txid; + CTransaction bindtx; CPubKey mypk; uint256 oracletxid,merkleroot,mhash,hashBlock,tokenid,txid; int64_t totalsupply; int32_t i,m,n,numvouts; uint8_t M,N,taddr,prefix,prefix2; std::string coin; struct CCcontract_info *cp,C; std::vector pubkeys,publishers; std::vectortxids; char str[67],depositaddr[64],txidaddr[64]; @@ -851,14 +910,13 @@ std::string GatewaysDeposit(uint64_t txfee,uint256 bindtxid,int32_t height,std:: if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); - gatewayspk = GetUnspendable(cp,0); //fprintf(stderr,"GatewaysDeposit ht.%d %s %.8f numpks.%d\n",height,refcoin.c_str(),(double)amount/COIN,(int32_t)pubkeys.size()); if ( GetTransaction(bindtxid,bindtx,hashBlock,false) == 0 || (numvouts= bindtx.vout.size()) <= 0 ) { fprintf(stderr,"cant find bindtxid %s\n",uint256_str(str,bindtxid)); return(""); } - if ( DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,coin,tokenid,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin ) + if ( DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin ) { fprintf(stderr,"invalid coin - bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); return(""); @@ -901,7 +959,7 @@ std::string GatewaysDeposit(uint64_t txfee,uint256 bindtxid,int32_t height,std:: { mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,destpub)); mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(HexStr(CCtxidaddr(txidaddr,cointxid))) << OP_CHECKSIG)); - return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysDepositOpRet('D',coin,bindtxid,publishers,txids,height,cointxid,claimvout,deposithex,proof,destpub,amount))); + return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysDepositOpRet('D',bindtxid,coin,publishers,txids,height,cointxid,claimvout,deposithex,proof,destpub,amount))); } fprintf(stderr,"cant find enough inputs\n"); return(""); @@ -925,7 +983,7 @@ std::string GatewaysClaim(uint64_t txfee,uint256 bindtxid,std::string refcoin,ui fprintf(stderr,"cant find bindtxid %s\n",uint256_str(str,bindtxid)); return(""); } - if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,coin,tokenid,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || coin != refcoin ) + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || coin != refcoin ) { fprintf(stderr,"invalid coin - bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); return(""); @@ -935,7 +993,7 @@ std::string GatewaysClaim(uint64_t txfee,uint256 bindtxid,std::string refcoin,ui fprintf(stderr,"cant find deposittxid %s\n",uint256_str(str,bindtxid)); return(""); } - if (DecodeGatewaysDepositOpRet(tx.vout[numvouts-1].scriptPubKey,coin,tmptxid,publishers,txids,height,cointxid,claimvout,deposithex,proof,tmpdestpub,tmpamount) != 'D' || coin != refcoin) + if (DecodeGatewaysDepositOpRet(tx.vout[numvouts-1].scriptPubKey,tmptxid,coin,publishers,txids,height,cointxid,claimvout,deposithex,proof,tmpdestpub,tmpamount) != 'D' || coin != refcoin) { fprintf(stderr,"invalid coin - deposittxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); return(""); @@ -945,32 +1003,20 @@ std::string GatewaysClaim(uint64_t txfee,uint256 bindtxid,std::string refcoin,ui fprintf(stderr,"different destination pubkey from desdeposittxid\n"); return(""); } - if ( (depositamount= GatewaysDepositval(tx,mypk)) != amount ) + if ( (depositamount=GatewaysDepositval(tx,mypk)) != amount ) { fprintf(stderr,"invalid Gateways deposittxid %s %.8f != %.8f\n",uint256_str(str,deposittxid),(double)depositamount/COIN,(double)amount/COIN); return(""); } - //fprintf(stderr,"depositaddr.(%s) vs %s\n",depositaddr,cp->unspendableaddr2); if ( AddNormalinputs(mtx,mypk,txfee,3) > 0 ) { - ///////// if ( (inputs= AddGatewaysInputs(cp,mtx,gatewayspk,tokenid,amount,60)) > 0 ) - if ((inputs = AddTokenCCInputs(cp, mtx, gatewayspk, tokenid, amount, 60)) > 0) + if ((inputs=AddGatewaysInputs(cp, mtx, gatewayspk, bindtxid, amount, 60)) > 0) { - if ( inputs > amount ) - CCchange = (inputs - amount); - _GetCCaddress(destaddr,EVAL_GATEWAYS,mypk); - //printf("expecting deposittxid/v0 to be to %s\n",destaddr); - mtx.vin.push_back(CTxIn(deposittxid,0,CScript())); // triggers EVAL_GATEWAYS validation - mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS,amount,mypk)); // transfer back to normal token - if ( CCchange != 0 ) - mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,CCchange,gatewayspk)); - - std::vector voutTokenPubkeys; - voutTokenPubkeys.push_back(mypk); // the pubkey where tokens are going (vout[0]) - - return(FinalizeCCTx(0,cp,mtx,mypk,txfee, - EncodeTokenOpRet('t', EVAL_GATEWAYS, tokenid, voutTokenPubkeys, - EncodeGatewaysClaimOpRet('t', refcoin, bindtxid, deposittxid, destpub, amount)))); // yes, 't' is passed twice + if ( inputs > amount ) CCchange = (inputs - amount); + mtx.vin.push_back(CTxIn(deposittxid,0,CScript())); + mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS,amount,destpub)); + if ( CCchange != 0 ) mtx.vout.push_back(MakeTokensCC1vout(EVAL_GATEWAYS,CCchange,gatewayspk)); + return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysClaimOpRet('C',tokenid,bindtxid,refcoin,deposittxid,destpub,amount))); } } CCerror = strprintf("cant find enough inputs or mismatched total"); @@ -981,159 +1027,377 @@ std::string GatewaysClaim(uint64_t txfee,uint256 bindtxid,std::string refcoin,ui std::string GatewaysWithdraw(uint64_t txfee,uint256 bindtxid,std::string refcoin,CPubKey withdrawpub,int64_t amount) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CTransaction tx; - CPubKey mypk, gatewayspk; - uint256 tokenid,hashBlock,oracletxid; int32_t numvouts; int64_t totalsupply,inputs,CCchange=0; uint8_t M,N,taddr,prefix,prefix2; std::string coin; - std::vector msigpubkeys; char depositaddr[64],str[65],coinaddr[64]; - struct CCcontract_info *cpGateways, gatewaysC; - struct CCcontract_info *cpTokens, tokensC; - - cpGateways = CCinit(&gatewaysC, EVAL_GATEWAYS); - cpTokens = CCinit(&tokensC, EVAL_TOKENS); + CTransaction tx; CPubKey mypk,gatewayspk,signerpk; uint256 txid,tokenid,hashBlock,oracletxid,tmptokenid,tmpbindtxid,withdrawtxid; int32_t K,vout,numvouts; + int64_t nValue,totalsupply,inputs,CCchange=0; uint8_t funcid,M,N,taddr,prefix,prefix2; std::string coin,hex; + std::vector msigpubkeys; char depositaddr[64],str[65],coinaddr[64]; struct CCcontract_info *cp,C,*cpTokens,CTokens; + std::vector > unspentOutputs; + cp = CCinit(&C,EVAL_GATEWAYS); + cpTokens = CCinit(&CTokens,EVAL_TOKENS); if ( txfee == 0 ) txfee = 10000; - mypk = pubkey2pk(Mypubkey()); - gatewayspk = GetUnspendable(cpGateways, 0); + gatewayspk = GetUnspendable(cp, 0); if( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 ) { fprintf(stderr,"cant find bindtxid %s\n",uint256_str(str,bindtxid)); return(""); } - if( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,coin,tokenid,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || coin != refcoin ) + if( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || coin != refcoin ) { fprintf(stderr,"invalid bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); return(""); } + _GetCCaddress(coinaddr,EVAL_GATEWAYS,gatewayspk); + SetCCunspents(unspentOutputs,coinaddr); + for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) + { + txid = it->first.txhash; + vout = (int32_t)it->first.index; + nValue = (int64_t)it->second.satoshis; + K=0; + if ( vout == 0 && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 && + (funcid=DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey))!=0 && (funcid=='W' || funcid=='P')) + { + if (funcid=='W' && DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,tmpbindtxid,coin,withdrawpub,amount)=='W' + && refcoin==coin && tmptokenid==tokenid && tmpbindtxid==bindtxid) + { + CCerror = strprintf("unable to create withdraw, another withdraw pending\n"); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + + else if (funcid=='P' && DecodeGatewaysPartialOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,K,signerpk,hex)=='P' && + GetTransaction(withdrawtxid,tx,hashBlock,false)!=0 && (numvouts=tx.vout.size())>0 && DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,tmpbindtxid,coin,withdrawpub,amount)=='W' + && refcoin==coin && tmptokenid==tokenid && tmpbindtxid==bindtxid) + { + CCerror = strprintf("unable to create withdraw, another withdraw pending\n"); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + } + } if( AddNormalinputs(mtx, mypk, 3*txfee, 4) > 0 ) { - /////if ( (inputs= AddGatewaysInputs(cp,mtx,mypk,tokenid,amount,60)) > 0 ) if ((inputs = AddTokenCCInputs(cpTokens, mtx, mypk, tokenid, amount, 60)) > 0) { - if ( inputs > amount ) - CCchange = (inputs - amount); - mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, amount, gatewayspk)); - mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(HexStr(withdrawpub)) << OP_CHECKSIG)); - mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS, txfee, gatewayspk)); - if ( CCchange != 0 ) - mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, CCchange, mypk)); - - char unspendableGatewaysAddr[64]; - GetCCaddress(cpGateways, unspendableGatewaysAddr, gatewayspk); - - uint8_t unspendableGatewaysPrivkey[32]; - GetUnspendable(cpGateways, unspendableGatewaysPrivkey); - - // add additional unspendable addr from Gateways: - CCaddr2set(cpTokens, EVAL_GATEWAYS, gatewayspk, unspendableGatewaysPrivkey, unspendableGatewaysAddr); - - std::vector voutTokenPubkeys; - voutTokenPubkeys.push_back(gatewayspk); // the pubkey where tokens are going vout[0] (and for checking the 'change' the Tokens contract will find pubkeys itself) - - return(FinalizeCCTx(0, cpTokens, mtx, mypk, txfee, - EncodeTokenOpRet('t', EVAL_GATEWAYS, tokenid, voutTokenPubkeys, - EncodeGatewaysWithdrawOpRet('W', refcoin, withdrawpub, amount)))); + if ( inputs > amount ) CCchange = (inputs - amount); + mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,txfee,gatewayspk)); + mtx.vout.push_back(MakeTokensCC1vout(EVAL_GATEWAYS,amount,gatewayspk)); + //mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(HexStr(withdrawpub)) << OP_CHECKSIG)); + if ( CCchange != 0 ) mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, CCchange, mypk)); + return(FinalizeCCTx(0, cpTokens, mtx, mypk, txfee,EncodeGatewaysWithdrawOpRet('W',tokenid,bindtxid,refcoin,withdrawpub,amount))); + } + else + { + CCerror = strprintf("not enough balance of tokens for withdraw"); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); } - CCerror = strprintf("cant find enough token inputs or mismatched total"); - fprintf(stderr, "%s\n", CCerror.c_str()); - return(""); - } - CCerror = strprintf("cant find enough normal inputs or mismatched total"); + CCerror = strprintf("cant find enough normal inputs"); fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } -std::string GatewaysPartialSign(uint64_t txfee,uint256 txid,std::string refcoin, std::string hex) +std::string GatewaysPartialSign(uint64_t txfee,uint256 lasttxid,std::string refcoin, std::string hex) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CPubKey mypk,txidaddrpk,signerpk; struct CCcontract_info *cp,C; CTransaction tx; - std::vector > unspentOutputs; char txidaddr[65]; - int32_t maxK,K=0; uint256 tmptxid,parttxid,hashBlock; + CPubKey mypk,withdrawpub,signerpk,gatewayspk; struct CCcontract_info *cp,C; CTransaction tx,bindtx; + std::vector > unspentOutputs; char funcid,str[65],depositaddr[64]; + int32_t numvouts,K=0; uint256 withdrawtxid,hashBlock,bindtxid,tokenid,oracletxid,tmptokenid; std::string coin,tmphex; int64_t amount,totalsupply; + uint8_t M,N,taddr,prefix,prefix2; std::vector pubkeys; + cp = CCinit(&C,EVAL_GATEWAYS); if ( txfee == 0 ) - txfee = 5000; + txfee = 10000; mypk = pubkey2pk(Mypubkey()); - txidaddrpk=CCtxidaddr(txidaddr,txid); - SetCCunspents(unspentOutputs,txidaddr); - maxK=0; - if (unspentOutputs.size()==0) + gatewayspk = GetUnspendable(cp,0); + if (GetTransaction(lasttxid,tx,hashBlock,false)==0 || (numvouts= tx.vout.size())<=0 + || (funcid=DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey))==0 || (funcid!='W' && funcid!='P')) { - if (AddNormalinputs(mtx,mypk,2*txfee,3)==0) fprintf(stderr,"error adding funds for partialsign\n"); + CCerror = strprintf("can't find last tx %s\n",uint256_str(str,lasttxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); } - else + if (funcid=='W') { - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) + withdrawtxid=lasttxid; + if (DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) { - tmptxid = it->first.txhash; - if (GetTransaction(tmptxid,tx,hashBlock,false) != 0 && tx.vout.size() > 0 && DecodeGatewaysPartialOpRet(tx.vout[tx.vout.size()-1].scriptPubKey,K,signerpk,refcoin,hex) == 'P' && K>maxK ) - { - maxK=K; - parttxid=tmptxid; - } + CCerror = strprintf("invalid withdraw tx %s\n",uint256_str(str,lasttxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); } - if (maxK>0) + else if (GetTransaction(bindtxid,bindtx,hashBlock,false)==0 || (numvouts=bindtx.vout.size())<=0) { - if (AddNormalinputs(mtx,mypk,txfee,3)==0) fprintf(stderr,"error adding funds for partialsign\n"); - mtx.vin.push_back(CTxIn(parttxid,0,CScript())); + CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + || refcoin!=coin || tokenid!=tmptokenid) + { + CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); } - else fprintf(stderr,"Error finding previous partial tx\n"); } - - mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,5000,txidaddrpk)); - return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysPartialOpRet('P',maxK+1,mypk,refcoin,hex))); + else if (funcid=='P') + { + if (DecodeGatewaysPartialOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,K,signerpk,tmphex)!='P' || refcoin!=coin) + { + CCerror = strprintf("cannot decode partialsign tx opret %s\n",uint256_str(str,lasttxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (GetTransaction(withdrawtxid,tx,hashBlock,false)==0 || (numvouts= tx.vout.size())<=0) + { + CCerror = strprintf("can't find withdraw tx %s\n",uint256_str(str,withdrawtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' + || refcoin!=coin) + { + CCerror = strprintf("invalid withdraw tx %s\n",uint256_str(str,lasttxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (GetTransaction(bindtxid,bindtx,hashBlock,false)==0 || (numvouts=bindtx.vout.size())<=0) + { + CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + || refcoin!=coin || tokenid!=tmptokenid) + { + CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + } + if (AddNormalinputs(mtx,mypk,txfee,3)==0) fprintf(stderr,"error adding funds for partialsign\n"); + mtx.vin.push_back(CTxIn(tx.GetHash(),0,CScript())); + mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,txfee,gatewayspk)); + return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysPartialOpRet('P',withdrawtxid,refcoin,K+1,mypk,hex))); } -std::string GatewaysCompleteSigning(uint64_t txfee,uint256 withdrawtxid,std::string refcoin,std::string hex) +std::string GatewaysCompleteSigning(uint64_t txfee,uint256 lasttxid,std::string refcoin,std::string hex) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CPubKey mypk,gatewayspk; struct CCcontract_info *cp,C; char txidaddr[65]; + CPubKey mypk,gatewayspk,signerpk,withdrawpub; struct CCcontract_info *cp,C; char funcid,str[65],depositaddr[64]; int64_t amount,totalsupply; + std::string coin,tmphex; CTransaction tx,bindtx; uint256 withdrawtxid,hashBlock,tokenid,tmptokenid,bindtxid,oracletxid; int32_t K=0,numvouts; + uint8_t M,N,taddr,prefix,prefix2; std::vector pubkeys; + cp = CCinit(&C,EVAL_GATEWAYS); mypk = pubkey2pk(Mypubkey()); gatewayspk = GetUnspendable(cp,0); if ( txfee == 0 ) - txfee = 10000; - - mtx.vin.push_back(CTxIn(withdrawtxid,2,CScript())); + txfee = 10000; + if (GetTransaction(lasttxid,tx,hashBlock,false)==0 || (numvouts= tx.vout.size())<=0 + || (funcid=DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey))==0 || (funcid!='W' && funcid!='P')) + { + CCerror = strprintf("invalid last txid %s\n",uint256_str(str,lasttxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + if (funcid=='W') + { + withdrawtxid=lasttxid; + if (DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) + { + CCerror = strprintf("cannot decode withdraw tx opret %s\n",uint256_str(str,lasttxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (GetTransaction(bindtxid,bindtx,hashBlock,false)==0 || (numvouts=tx.vout.size())<=0) + { + CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + || refcoin!=coin || tokenid!=tmptokenid) + { + CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + } + else if (funcid=='P') + { + if (DecodeGatewaysPartialOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,K,signerpk,tmphex)!='P' || refcoin!=coin) + { + CCerror = strprintf("cannot decode partialsign tx opret %s\n",uint256_str(str,lasttxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (GetTransaction(withdrawtxid,tx,hashBlock,false)==0 || (numvouts=tx.vout.size())==0) + { + CCerror = strprintf("invalid withdraw txid %s\n",uint256_str(str,withdrawtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) + { + printf("aaaaaaaaaaa\n"); + CCerror = strprintf("cannot decode withdraw tx opret %s\n",uint256_str(str,withdrawtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (GetTransaction(bindtxid,bindtx,hashBlock,false)==0 || (numvouts=bindtx.vout.size())<=0) + { + CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + || refcoin!=coin || tokenid!=tmptokenid) + { + CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + } + if (AddNormalinputs(mtx,mypk,txfee,3)==0) fprintf(stderr,"error adding funds for completesigning\n"); + mtx.vin.push_back(CTxIn(lasttxid,0,CScript())); mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,txfee,gatewayspk)); - return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysCompleteSigningOpRet('C',refcoin,withdrawtxid,hex))); + return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysCompleteSigningOpRet('S',withdrawtxid,refcoin,hex))); } std::string GatewaysMarkDone(uint64_t txfee,uint256 completetxid,std::string refcoin) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CPubKey mypk,gatewayspk; struct CCcontract_info *cp,C; char txidaddr[65]; + CPubKey mypk; struct CCcontract_info *cp,C; char str[65],depositaddr[64]; CTransaction tx,bindtx; int32_t numvouts; + uint256 withdrawtxid,bindtxid,oracletxid,tokenid,tmptokenid,hashBlock; std::string coin,hex; + uint8_t M,N,taddr,prefix,prefix2; std::vector pubkeys; int64_t amount,totalsupply; CPubKey withdrawpub; + cp = CCinit(&C,EVAL_GATEWAYS); mypk = pubkey2pk(Mypubkey()); if ( txfee == 0 ) txfee = 10000; + if (GetTransaction(completetxid,tx,hashBlock,false)==0 || (numvouts= tx.vout.size())<=0) + { + CCerror = strprintf("invalid completesigning txid %s\n",uint256_str(str,completetxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (DecodeGatewaysCompleteSigningOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,hex)!='S' || refcoin!=coin) + { + CCerror = strprintf("cannot decode completesigning tx opret %s\n",uint256_str(str,completetxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (GetTransaction(withdrawtxid,tx,hashBlock,false)==0 || (numvouts= tx.vout.size())==0) + { + CCerror = strprintf("invalid withdraw txid %s\n",uint256_str(str,withdrawtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) + { + CCerror = strprintf("cannot decode withdraw tx opret %s\n",uint256_str(str,withdrawtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (GetTransaction(bindtxid,bindtx,hashBlock,false)==0 || (numvouts=bindtx.vout.size())<=0) + { + CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + else if (DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + || refcoin!=coin || tokenid!=tmptokenid) + { + CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } mtx.vin.push_back(CTxIn(completetxid,0,CScript())); - return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysMarkDoneOpRet('M',refcoin,completetxid))); + return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysMarkDoneOpRet('M',refcoin,completetxid,withdrawtxid))); +} + +UniValue GatewaysPendingDeposits(uint256 bindtxid,std::string refcoin) +{ + UniValue result(UniValue::VOBJ),pending(UniValue::VARR); CTransaction tx; std::string coin,hex,pub; + CPubKey mypk,gatewayspk,destpub; std::vector pubkeys,publishers; std::vector txids; + uint256 tmpbindtxid,hashBlock,txid,tokenid,oracletxid,cointxid; uint8_t M,N,taddr,prefix,prefix2; + char depositaddr[65],coinaddr[65],str[65],destaddr[65],txidaddr[65]; std::vector proof; + int32_t numvouts,vout,claimvout,height; int64_t totalsupply,nValue,amount; struct CCcontract_info *cp,C; + std::vector > unspentOutputs; + + cp = CCinit(&C,EVAL_GATEWAYS); + mypk = pubkey2pk(Mypubkey()); + gatewayspk = GetUnspendable(cp,0); + _GetCCaddress(coinaddr,EVAL_GATEWAYS,mypk); + if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 ) + { + CCerror = strprintf("cant find bindtxid %s\n",uint256_str(str,bindtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin) + { + CCerror = strprintf("invalid bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); + } + SetCCunspents(unspentOutputs,coinaddr); + for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) + { + txid = it->first.txhash; + vout = (int32_t)it->first.index; + nValue = (int64_t)it->second.satoshis; + if ( vout == 0 && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts=tx.vout.size())>0 && + DecodeGatewaysDepositOpRet(tx.vout[numvouts-1].scriptPubKey,tmpbindtxid,coin,publishers,txids,height,cointxid,claimvout,hex,proof,destpub,amount) == 'D' + && tmpbindtxid==bindtxid && refcoin == coin && myIsutxo_spentinmempool(txid,vout) == 0) + { + UniValue obj(UniValue::VOBJ); + obj.push_back(Pair("cointxid",uint256_str(str,cointxid))); + obj.push_back(Pair("deposittxid",uint256_str(str,txid))); + CCtxidaddr(txidaddr,txid); + obj.push_back(Pair("deposittxidaddr",txidaddr)); + _GetCCaddress(destaddr,EVAL_TOKENS,destpub); + obj.push_back(Pair("tokens_destination_address",destaddr)); + pub=HexStr(destpub); + obj.push_back(Pair("claim_pubkey",pub)); + obj.push_back(Pair("amount",(double)amount/COIN)); + obj.push_back(Pair("confirmed_or_notarized",komodo_txnotarizedconfirmed(txid))); + pending.push_back(obj); + } + } + result.push_back(Pair("coin",refcoin)); + result.push_back(Pair("pending",pending)); + return(result); } UniValue GatewaysPendingWithdraws(uint256 bindtxid,std::string refcoin) { - UniValue result(UniValue::VOBJ),pending(UniValue::VARR); CTransaction tx; std::string tmprefcoin; CPubKey mypk,gatewayspk,withdrawpub; std::vector msigpubkeys; - uint256 hashBlock,tokenid,txid,oracletxid; uint8_t M,N,taddr,prefix,prefix2; - char depositaddr[64],coinaddr[64],destaddr[64],str[65],withaddr[64],numstr[32],txidaddr[64],cctxidaddr[64],signeraddr[64]; - int32_t i,n,numvouts,vout,queueflag; int64_t totalsupply,amount,nValue; struct CCcontract_info *cp,C; + UniValue result(UniValue::VOBJ),pending(UniValue::VARR); CTransaction tx; std::string coin,hex; CPubKey mypk,gatewayspk,withdrawpub,signerpk; + std::vector msigpubkeys; uint256 hashBlock,tokenid,txid,tmpbindtxid,tmptokenid,oracletxid,withdrawtxid; uint8_t M,N,taddr,prefix,prefix2; + char funcid,depositaddr[65],coinaddr[65],tokensaddr[65],destaddr[65],str[65],withaddr[65],numstr[32],signeraddr[65],txidaddr[65]; + int32_t i,n,numvouts,vout,queueflag,K; int64_t totalsupply,amount,nValue; struct CCcontract_info *cp,C; std::vector > unspentOutputs; cp = CCinit(&C,EVAL_GATEWAYS); mypk = pubkey2pk(Mypubkey()); gatewayspk = GetUnspendable(cp,0); _GetCCaddress(coinaddr,EVAL_GATEWAYS,gatewayspk); + GetTokensCCaddress(cp,tokensaddr,gatewayspk); if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 ) { - fprintf(stderr,"cant find bindtxid %s\n",uint256_str(str,bindtxid)); - return(result); + CCerror = strprintf("cant find bindtxid %s\n",uint256_str(str,bindtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); } - if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tmprefcoin,tokenid,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || tmprefcoin != refcoin ) + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin ) { - fprintf(stderr,"invalid bindtxid %s coin.%s\n",uint256_str(str,bindtxid),tmprefcoin.c_str()); - return(result); + CCerror = strprintf("invalid bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); } n = msigpubkeys.size(); queueflag = 0; @@ -1149,28 +1413,45 @@ UniValue GatewaysPendingWithdraws(uint256 bindtxid,std::string refcoin) txid = it->first.txhash; vout = (int32_t)it->first.index; nValue = (int64_t)it->second.satoshis; - fprintf(stderr,"%s %d %ld\n",txid.ToString().c_str(),vout,(long)nValue); - if ( vout == 2 && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 && - DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,withdrawpub,amount) == 'W' && myIsutxo_spentinmempool(txid,vout) == 0) + K=0; + if ( vout == 0 && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 && + (funcid=DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey))!=0 && (funcid=='W' || funcid=='P') && myIsutxo_spentinmempool(txid,vout) == 0) { - Getscriptaddress(destaddr,tx.vout[0].scriptPubKey); - Getscriptaddress(withaddr,tx.vout[1].scriptPubKey); - if ( strcmp(destaddr,coinaddr) == 0 ) + if (funcid=='W') + { + if (DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,tmpbindtxid,coin,withdrawpub,amount)==0 || refcoin!=coin || tmptokenid!=tokenid || tmpbindtxid!=bindtxid) continue; + } + else if (funcid=='P') + { + if (DecodeGatewaysPartialOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,K,signerpk,hex)!='P' || GetTransaction(withdrawtxid,tx,hashBlock,false)==0 + || (numvouts=tx.vout.size())<=0 || DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,tmpbindtxid,coin,withdrawpub,amount)!='W' + || refcoin!=coin || tmptokenid!=tokenid || tmpbindtxid!=bindtxid) + continue; + } + Getscriptaddress(destaddr,tx.vout[1].scriptPubKey); + Getscriptaddress(withaddr,CScript() << ParseHex(HexStr(withdrawpub)) << OP_CHECKSIG); + if ( strcmp(destaddr,tokensaddr) == 0 ) { UniValue obj(UniValue::VOBJ); - obj.push_back(Pair("txid",uint256_str(str,txid))); - _GetCCaddress(cctxidaddr,EVAL_GATEWAYS,CCtxidaddr(txidaddr,txid)); - obj.push_back(Pair("txidaddr",cctxidaddr)); + obj.push_back(Pair("withdrawtxid",uint256_str(str,tx.GetHash()))); + CCtxidaddr(txidaddr,tx.GetHash()); + obj.push_back(Pair("withdrawtxidaddr",txidaddr)); obj.push_back(Pair("withdrawaddr",withaddr)); - sprintf(numstr,"%.8f",(double)tx.vout[0].nValue/COIN); - obj.push_back(Pair("amount",numstr)); - obj.push_back(Pair("confirmed_or_notarized",komodo_txnotarizedconfirmed(txid))); + sprintf(numstr,"%.8f",(double)tx.vout[1].nValue/COIN); + obj.push_back(Pair("amount",numstr)); + obj.push_back(Pair("confirmed_or_notarized",komodo_txnotarizedconfirmed(tx.GetHash()))); if ( queueflag != 0 ) { obj.push_back(Pair("depositaddr",depositaddr)); Getscriptaddress(signeraddr,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG); obj.push_back(Pair("signeraddr",signeraddr)); } + if (N>1) + { + obj.push_back(Pair("number_of_signs",K)); + obj.push_back(Pair("last_txid",uint256_str(str,txid))); + if (K>0) obj.push_back(Pair("hex",hex)); + } pending.push_back(obj); } } @@ -1183,9 +1464,10 @@ UniValue GatewaysPendingWithdraws(uint256 bindtxid,std::string refcoin) UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin) { - UniValue result(UniValue::VOBJ),processed(UniValue::VARR); CTransaction tx; std::string tmprefcoin,hex; CPubKey mypk,gatewayspk,withdrawpub; std::vector msigpubkeys; - uint256 withdrawtxid,hashBlock,txid,tokenid,oracletxid; uint8_t M,N,taddr,prefix,prefix2; - char depositaddr[64],coinaddr[64],str[65],numstr[32],txidaddr[64],cctxidaddr[64],withaddr[64]; + UniValue result(UniValue::VOBJ),processed(UniValue::VARR); CTransaction tx; std::string coin,hex; + CPubKey mypk,gatewayspk,withdrawpub; std::vector msigpubkeys; + uint256 withdrawtxid,hashBlock,txid,tokenid,tmptokenid,oracletxid; uint8_t M,N,taddr,prefix,prefix2; + char depositaddr[65],coinaddr[65],str[65],numstr[32],withaddr[65],txidaddr[65]; int32_t i,n,numvouts,vout,queueflag; int64_t totalsupply,nValue,amount; struct CCcontract_info *cp,C; std::vector > unspentOutputs; @@ -1194,14 +1476,16 @@ UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin) gatewayspk = GetUnspendable(cp,0); _GetCCaddress(coinaddr,EVAL_GATEWAYS,gatewayspk); if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 ) - { - fprintf(stderr,"cant find bindtxid %s\n",uint256_str(str,bindtxid)); - return(result); + { + CCerror = strprintf("cant find bindtxid %s\n",uint256_str(str,bindtxid)); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); } - if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tmprefcoin,tokenid,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || tmprefcoin != refcoin ) + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin) { - fprintf(stderr,"invalid bindtxid %s coin.%s\n",uint256_str(str,bindtxid),tmprefcoin.c_str()); - return(result); + CCerror = strprintf("invalid bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); + fprintf(stderr,"%s\n", CCerror.c_str() ); + return(""); } n = msigpubkeys.size(); queueflag = 0; @@ -1217,20 +1501,21 @@ UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin) txid = it->first.txhash; vout = (int32_t)it->first.index; nValue = (int64_t)it->second.satoshis; - //fprintf(stderr,"%s %d %ld\n",txid.ToString().c_str(),vout,(long)nValue); if ( vout == 0 && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 && - DecodeGatewaysCompleteSigningOpRet(tx.vout[numvouts-1].scriptPubKey,tmprefcoin,withdrawtxid,hex) == 'C' && myIsutxo_spentinmempool(txid,vout) == 0) + DecodeGatewaysCompleteSigningOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,hex) == 'S' && refcoin == coin && myIsutxo_spentinmempool(txid,vout) == 0) { - if (GetTransaction(withdrawtxid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 && DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,withdrawpub,amount) == 'W') + if (GetTransaction(withdrawtxid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 + && DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount) == 'W' || refcoin!=coin || tmptokenid!=tokenid) { UniValue obj(UniValue::VOBJ); - obj.push_back(Pair("txid",uint256_str(str,txid))); - obj.push_back(Pair("withdrawtxid",uint256_str(str,withdrawtxid))); - _GetCCaddress(cctxidaddr,EVAL_GATEWAYS,CCtxidaddr(txidaddr,withdrawtxid)); - obj.push_back(Pair("withdrawtxidaddr",cctxidaddr)); - Getscriptaddress(withaddr,tx.vout[1].scriptPubKey); + obj.push_back(Pair("completesigningtxid",uint256_str(str,txid))); + obj.push_back(Pair("withdrawtxid",uint256_str(str,withdrawtxid))); + CCtxidaddr(txidaddr,withdrawtxid); + obj.push_back(Pair("withdrawtxidaddr",txidaddr)); + Getscriptaddress(withaddr,CScript() << ParseHex(HexStr(withdrawpub)) << OP_CHECKSIG); obj.push_back(Pair("withdrawaddr",withaddr)); - obj.push_back(Pair("confirmed_or_notarized",komodo_txnotarizedconfirmed(txid))); + sprintf(numstr,"%.8f",(double)tx.vout[1].nValue/COIN); + obj.push_back(Pair("amount",numstr)); obj.push_back(Pair("hex",hex)); processed.push_back(obj); } @@ -1242,40 +1527,6 @@ UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin) return(result); } -UniValue GatewaysMultisig(char *cctxidaddr) -{ - std::string parthex,hex,refcoin; uint256 txid,hashBlock; CTransaction tx; int32_t i,maxK,K,numvouts; CPubKey signerpk; - std::vector > unspentOutputs; UniValue result(UniValue::VOBJ); - - SetCCunspents(unspentOutputs,cctxidaddr); - maxK=0; - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) - { - txid = it->first.txhash; - if (GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts=tx.vout.size()) > 0 && DecodeGatewaysPartialOpRet(tx.vout[tx.vout.size()-1].scriptPubKey,K,signerpk,refcoin,hex) == 'P' && K>maxK ) - { - maxK=K; - parthex=hex; - } - } - - BOOST_FOREACH(const CTxMemPoolEntry &e, mempool.mapTx) - { - const CTransaction &txmempool = e.GetTx(); - const uint256 &hash = txmempool.GetHash(); - - if ((numvouts=txmempool.vout.size()) > 0 && DecodeGatewaysPartialOpRet(txmempool.vout[numvouts-1].scriptPubKey,K,signerpk,refcoin,hex) == 'P' && K>maxK) - { - maxK=K; - parthex=hex; - } - } - - result.push_back(Pair("hex",parthex)); - result.push_back(Pair("number_of_signs",maxK)); - return (result); -} - UniValue GatewaysList() { UniValue result(UniValue::VARR); std::vector > addressIndex; struct CCcontract_info *cp,C; uint256 txid,hashBlock,oracletxid,tokenid; CTransaction vintx; std::string coin; int64_t totalsupply; char str[65],depositaddr[64]; uint8_t M,N,taddr,prefix,prefix2; std::vector pubkeys; @@ -1286,7 +1537,7 @@ UniValue GatewaysList() txid = it->first.txhash; if ( GetTransaction(txid,vintx,hashBlock,false) != 0 ) { - if ( vintx.vout.size() > 0 && DecodeGatewaysBindOpRet(depositaddr,vintx.vout[vintx.vout.size()-1].scriptPubKey,coin,tokenid,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 0 ) + if ( vintx.vout.size() > 0 && DecodeGatewaysBindOpRet(depositaddr,vintx.vout[vintx.vout.size()-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 0 ) { result.push_back(uint256_str(str,txid)); } @@ -1298,16 +1549,19 @@ UniValue GatewaysList() UniValue GatewaysInfo(uint256 bindtxid) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ),a(UniValue::VARR); std::string coin; char str[67],numstr[65],depositaddr[64],gatewaysassets[64]; uint8_t M,N; std::vector pubkeys; uint8_t taddr,prefix,prefix2; uint256 tokenid,oracletxid,hashBlock; CTransaction tx; CPubKey Gatewayspk; struct CCcontract_info *cp,C; int32_t i; int64_t totalsupply,remaining; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); std::string coin; char str[67],numstr[65],depositaddr[64],gatewaystokens[64]; + uint8_t M,N; std::vector pubkeys; uint8_t taddr,prefix,prefix2; uint256 tokenid,oracletxid,hashBlock; CTransaction tx; + CPubKey Gatewayspk; struct CCcontract_info *cp,C; int32_t i; int64_t totalsupply,remaining; + result.push_back(Pair("result","success")); result.push_back(Pair("name","Gateways")); cp = CCinit(&C,EVAL_GATEWAYS); Gatewayspk = GetUnspendable(cp,0); - _GetCCaddress(gatewaysassets,EVAL_GATEWAYS,Gatewayspk); + GetTokensCCaddress(cp,gatewaystokens,Gatewayspk); if ( GetTransaction(bindtxid,tx,hashBlock,false) != 0 ) { depositaddr[0] = 0; - if ( tx.vout.size() > 0 && DecodeGatewaysBindOpRet(depositaddr,tx.vout[tx.vout.size()-1].scriptPubKey,coin,tokenid,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 0 && M <= N && N > 0 ) + if ( tx.vout.size() > 0 && DecodeGatewaysBindOpRet(depositaddr,tx.vout[tx.vout.size()-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 0 && M <= N && N > 0 ) { if ( N > 1 ) { @@ -1326,7 +1580,7 @@ UniValue GatewaysInfo(uint256 bindtxid) result.push_back(Pair("tokenid",uint256_str(str,tokenid))); sprintf(numstr,"%.8f",(double)totalsupply/COIN); result.push_back(Pair("totalsupply",numstr)); - remaining = CCtoken_balance(gatewaysassets,tokenid); + remaining = CCtoken_balance(gatewaystokens,tokenid); sprintf(numstr,"%.8f",(double)remaining/COIN); result.push_back(Pair("remaining",numstr)); sprintf(numstr,"%.8f",(double)(totalsupply - remaining)/COIN); diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index 82a400e71..208b3cf02 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -478,9 +478,9 @@ static const CRPCCommand vRPCCommands[] = { "gateways", "gatewayspartialsign", &gatewayspartialsign, true }, { "gateways", "gatewayscompletesigning", &gatewayscompletesigning, true }, { "gateways", "gatewaysmarkdone", &gatewaysmarkdone, true }, - { "gateways", "gatewayspending", &gatewayspending, true }, + { "gateways", "gatewayspendingdeposits", &gatewayspendingdeposits, true }, + { "gateways", "gatewayspendingwithdraws", &gatewayspendingwithdraws, true }, { "gateways", "gatewaysprocessed", &gatewaysprocessed, true }, - { "gateways", "gatewaysmultisig", &gatewaysmultisig, true }, // dice { "dice", "dicelist", &dicelist, true }, diff --git a/src/rpc/server.h b/src/rpc/server.h index 3edc85ebf..b812ccc9d 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -300,9 +300,9 @@ extern UniValue gatewayswithdraw(const UniValue& params, bool fHelp); extern UniValue gatewayspartialsign(const UniValue& params, bool fHelp); extern UniValue gatewayscompletesigning(const UniValue& params, bool fHelp); extern UniValue gatewaysmarkdone(const UniValue& params, bool fHelp); -extern UniValue gatewayspending(const UniValue& params, bool fHelp); +extern UniValue gatewayspendingdeposits(const UniValue& params, bool fHelp); +extern UniValue gatewayspendingwithdraws(const UniValue& params, bool fHelp); extern UniValue gatewaysprocessed(const UniValue& params, bool fHelp); -extern UniValue gatewaysmultisig(const UniValue& params, bool fHelp); extern UniValue channelslist(const UniValue& params, bool fHelp); extern UniValue channelsinfo(const UniValue& params, bool fHelp); extern UniValue channelsopen(const UniValue& params, bool fHelp); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index e111ad98a..0ffc370e2 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -6263,11 +6263,23 @@ UniValue gatewaysmarkdone(const UniValue& params, bool fHelp) return(result); } -UniValue gatewayspending(const UniValue& params, bool fHelp) +UniValue gatewayspendingdeposits(const UniValue& params, bool fHelp) { uint256 bindtxid; std::string coin; if ( fHelp || params.size() != 2 ) - throw runtime_error("gatewayspending bindtxid coin\n"); + throw runtime_error("gatewayspendingdeposits bindtxid coin\n"); + if ( ensure_CCrequirements() < 0 ) + throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + bindtxid = Parseuint256((char *)params[0].get_str().c_str()); + coin = params[1].get_str(); + return(GatewaysPendingDeposits(bindtxid,coin)); +} + +UniValue gatewayspendingwithdraws(const UniValue& params, bool fHelp) +{ + uint256 bindtxid; std::string coin; + if ( fHelp || params.size() != 2 ) + throw runtime_error("gatewayspendingwithdraws bindtxid coin\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); bindtxid = Parseuint256((char *)params[0].get_str().c_str()); @@ -6287,19 +6299,6 @@ UniValue gatewaysprocessed(const UniValue& params, bool fHelp) return(GatewaysProcessedWithdraws(bindtxid,coin)); } -UniValue gatewaysmultisig(const UniValue& params, bool fHelp) -{ - UniValue result(UniValue::VOBJ); std::string hex; char *txidaddr; - if ( fHelp || params.size() != 1 ) - throw runtime_error("gatewaysmultisig txidaddr\n"); - if ( ensure_CCrequirements() < 0 ) - throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); - const CKeyStore& keystore = *pwalletMain; - LOCK2(cs_main, pwalletMain->cs_wallet); - txidaddr = (char *)params[0].get_str().c_str(); - return(GatewaysMultisig(txidaddr)); -} - UniValue oracleslist(const UniValue& params, bool fHelp) { if ( fHelp || params.size() > 0 ) From fef5683d7521da8cc6f2c8aa09f1c89b88c7f1dc Mon Sep 17 00:00:00 2001 From: Mihailo Milenkovic Date: Mon, 28 Jan 2019 14:52:19 +0100 Subject: [PATCH 0085/1145] Refactor CCaddress --- src/wallet/rpcwallet.cpp | 88 +++++++++++++++++++++------------------- 1 file changed, 46 insertions(+), 42 deletions(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 0ffc370e2..5616ce5df 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5198,7 +5198,7 @@ int32_t ensure_CCrequirements() UniValue CCaddress(struct CCcontract_info *cp,char *name,std::vector &pubkey) { - UniValue result(UniValue::VOBJ); char destaddr[64],str[64]; CPubKey pk; + UniValue result(UniValue::VOBJ); char destaddr[64],str[64]; CPubKey mypk,pk; pk = GetUnspendable(cp,0); GetCCaddress(cp,destaddr,pk); if ( strcmp(destaddr,cp->unspendableCCaddr) != 0 ) @@ -5209,25 +5209,46 @@ UniValue CCaddress(struct CCcontract_info *cp,char *name,std::vectorunspendableCCaddr,destaddr); } result.push_back(Pair("result", "success")); - sprintf(str,"%sCCaddress",name); + sprintf(str,"%sCCAddress",name); result.push_back(Pair(str,cp->unspendableCCaddr)); - sprintf(str,"%smarker",name); + sprintf(str,"%sNormalAddress",name); result.push_back(Pair(str,cp->normaladdr)); - result.push_back(Pair("GatewaysPubkey","03ea9c062b9652d8eff34879b504eda0717895d27597aaeb60347d65eed96ccb40")); - if ( _GetCCaddress(destaddr,EVAL_ASSETS,pubkey2pk(pubkey)) > 0 ) + if (strcmp(name,"Gateways")==0) result.push_back(Pair("GatewaysPubkey","03ea9c062b9652d8eff34879b504eda0717895d27597aaeb60347d65eed96ccb40")); + if ((strcmp(name,"Channels")==0 || strcmp(name,"Heir")==0) && pubkey.size() == 33) { - sprintf(str,"%sCCassets",name); + sprintf(str,"%sCC1of2Address",name); + mypk = pubkey2pk(Mypubkey()); + GetCCaddress1of2(cp,destaddr,mypk,pubkey2pk(pubkey)); result.push_back(Pair(str,destaddr)); + if (GetTokensCCaddress1of2(cp,destaddr,mypk,pubkey2pk(pubkey))>0) + { + sprintf(str,"%sCC1of2TokensAddress",name); + result.push_back(Pair(str,destaddr)); + } } + else if (strcmp(name,"Tokens")!=0) + { + if (GetTokensCCaddress(cp,destaddr,pk)>0) + { + sprintf(str,"%sCCTokensAddress",name); + result.push_back(Pair(str,destaddr)); + } + } + if ( Getscriptaddress(destaddr,(CScript() << Mypubkey() << OP_CHECKSIG)) != 0 ) + result.push_back(Pair("myAddress",destaddr)); + if ( GetCCaddress(cp,destaddr,pubkey2pk(Mypubkey())) != 0 ) + { + sprintf(str,"myCCAddress(%s)",name); + result.push_back(Pair(str,destaddr)); + } if ( pubkey.size() == 33 ) { if ( GetCCaddress(cp,destaddr,pubkey2pk(pubkey)) != 0 ) - result.push_back(Pair("CCaddress",destaddr)); + { + sprintf(str,"PubkeyCCaddress(%s)",name); + result.push_back(Pair(str,destaddr)); + } } - if ( GetCCaddress(cp,destaddr,pubkey2pk(Mypubkey())) != 0 ) - result.push_back(Pair("myCCaddress",destaddr)); - if ( Getscriptaddress(destaddr,(CScript() << Mypubkey() << OP_CHECKSIG)) != 0 ) - result.push_back(Pair("myaddress",destaddr)); return(result); } @@ -5299,29 +5320,15 @@ UniValue setpubkey(const UniValue& params, bool fHelp) UniValue channelsaddress(const UniValue& params, bool fHelp) { - UniValue result(UniValue::VOBJ); struct CCcontract_info *cp,C; std::vector destpubkey; CPubKey pk,pk2; char destaddr[64]; + UniValue result(UniValue::VOBJ); struct CCcontract_info *cp,C; std::vector pubkey; + cp = CCinit(&C,EVAL_CHANNELS); if ( fHelp || params.size() != 1 ) - throw runtime_error("channelsaddress destpubkey\n"); + throw runtime_error("channelsaddress pubkey\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); - destpubkey = ParseHex(params[0].get_str().c_str()); - pk = pubkey2pk(Mypubkey()); - pk2 = pubkey2pk(destpubkey); - result = CCaddress(cp,(char *)"Channels",destpubkey); - result.push_back(Pair("otherpubkey", params[0].get_str())); - GetCCaddress1of2(cp,destaddr,pk,pk2); - result.push_back(Pair("channeladdress",destaddr)); - if ( 0 ) - { - int32_t i; - for (i=0; i<100; i++) - { - GetCCaddress1of2(cp,destaddr,pk,pk2); - fprintf(stderr,"i.%d %s\n",i,destaddr); - } - } - return(result); + pubkey = ParseHex(params[0].get_str().c_str()); + return(CCaddress(cp,(char *)"Channels",pubkey)); } UniValue cclibaddress(const UniValue& params, bool fHelp) @@ -5453,17 +5460,14 @@ UniValue heiraddress(const UniValue& params, bool fHelp) { struct CCcontract_info *cp,C; std::vector pubkey; cp = CCinit(&C,EVAL_HEIR); - if ( fHelp || params.size() > 1 ) - throw runtime_error("heiraddress [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) - throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); - if ( params.size() == 1 ) - pubkey = ParseHex(params[0].get_str().c_str()); + if ( fHelp || params.size() > 1 ) + throw runtime_error("heiraddress pubkey\n"); + if ( ensure_CCrequirements() < 0 ) + throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + pubkey = ParseHex(params[0].get_str().c_str()); return(CCaddress(cp,(char *)"Heir",pubkey)); } - - UniValue lottoaddress(const UniValue& params, bool fHelp) { struct CCcontract_info *cp,C; std::vector pubkey; @@ -5519,13 +5523,13 @@ UniValue diceaddress(const UniValue& params, bool fHelp) UniValue faucetaddress(const UniValue& params, bool fHelp) { struct CCcontract_info *cp,C; std::vector pubkey; - int errno; + int error; cp = CCinit(&C,EVAL_FAUCET); if ( fHelp || params.size() > 1 ) throw runtime_error("faucetaddress [pubkey]\n"); - errno = ensure_CCrequirements(); - if ( errno < 0 ) - throw runtime_error(strprintf("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet. ERR=%d\n", errno)); + error = ensure_CCrequirements(); + if ( error < 0 ) + throw runtime_error(strprintf("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet. ERR=%d\n", error)); if ( params.size() == 1 ) pubkey = ParseHex(params[0].get_str().c_str()); return(CCaddress(cp,(char *)"Faucet",pubkey)); From ff22a1aedbc554b5036eafa25f987ff12fded467 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 28 Jan 2019 21:30:42 -1100 Subject: [PATCH 0086/1145] Priv2addr --- src/cc/CCinclude.h | 2 + src/cc/CCutils.cpp | 24 ++- src/cc/sudoku.cpp | 476 +++++++++++++++++++++++++++++++++++++++++++++ src/key.cpp | 16 ++ src/key.h | 1 + 5 files changed, 517 insertions(+), 2 deletions(-) create mode 100644 src/cc/sudoku.cpp diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index 66c001969..5d847800a 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -42,6 +42,7 @@ one other technical note is that komodod has the insight-explorer extensions bui #include #include "../script/standard.h" #include "../base58.h" +#include "../key.h" #include "../core_io.h" #include "../script/sign.h" #include "../wallet/wallet.h" @@ -179,6 +180,7 @@ int32_t oracle_format(uint256 *hashp,int64_t *valp,char *str,uint8_t fmt,uint8_t CPubKey GetUnspendable(struct CCcontract_info *cp,uint8_t *unspendablepriv); // CCutils +bool priv2addr(char *coinaddr,uint8_t buf33[33],uint8_t priv32[32]); CPubKey buf2pk(uint8_t *buf33); void endiancpy(uint8_t *dest,uint8_t *src,int32_t len); uint256 DiceHashEntropy(uint256 &entropy,uint256 _txidpriv,int32_t entropyvout,int32_t usevout); diff --git a/src/cc/CCutils.cpp b/src/cc/CCutils.cpp index 766ce1188..6dff5d3cd 100644 --- a/src/cc/CCutils.cpp +++ b/src/cc/CCutils.cpp @@ -442,6 +442,20 @@ bool PreventCC(Eval* eval,const CTransaction &tx,int32_t preventCCvins,int32_t n return(true); } +bool priv2addr(char *coinaddr,uint8_t *buf33,uint8_t priv32[32]) +{ + CKey priv; CPubKey pk; int32_t i; uint8_t *src; + priv.SetKey32(priv32); + pk = priv.GetPubKey(); + if ( buf33 != 0 ) + { + src = (uint8_t *)pk.begin(); + for (i=0; i<33; i++) + buf33[i] = src[i]; + } + return(Getscriptaddress(coinaddr, CScript() << ParseHex(HexStr(pk)) << OP_CHECKSIG)); +} + std::vector Mypubkey() { extern uint8_t NOTARY_PUBKEY33[33]; @@ -456,7 +470,7 @@ std::vector Mypubkey() bool Myprivkey(uint8_t myprivkey[]) { - char coinaddr[64]; std::string strAddress; char *dest; int32_t i,n; CBitcoinAddress address; CKeyID keyID; CKey vchSecret; + char coinaddr[64],checkaddr[64]; std::string strAddress; char *dest; int32_t i,n; CBitcoinAddress address; CKeyID keyID; CKey vchSecret; uint8_t buf33[33]; if ( Getscriptaddress(coinaddr,CScript() << Mypubkey() << OP_CHECKSIG) != 0 ) { n = (int32_t)strlen(coinaddr); @@ -477,7 +491,13 @@ bool Myprivkey(uint8_t myprivkey[]) fprintf(stderr,"0x%02x, ",myprivkey[i]); fprintf(stderr," found privkey for %s!\n",dest); } - return(true); + if ( priv2addr(checkaddr,buf33,myprivkey) != 0 ) + { + if ( buf2pk(buf33) == Mypubkey() && strcmp(checkaddr,coinaddr) == 0 ) + return(true); + else printf("mismatched privkey -> addr %s vs %s\n",checkaddr,coinaddr); + } + return(false); } #endif } diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp new file mode 100644 index 000000000..a79e3d161 --- /dev/null +++ b/src/cc/sudoku.cpp @@ -0,0 +1,476 @@ + +// start https://github.com/mentalmove/SudokuGenerator +// +// main.c +// SudokuGenerator +// +// Malte Pagel +// + +#include +#include +#include +#include +#include + + +#define SMALL_LINE 3 +#define LINE 9 +#define TOTAL 81 + +#define LIMIT 16777216 + +#define SHOW_SOLVED 1 + + +struct dimensions_collection { + int row; + int column; + int small_square; +}; + + +static int indices[TOTAL]; +static int riddle[TOTAL]; +static int solved[TOTAL]; +static int unsolved[TOTAL]; +static int tries_to_set = 0; +static int taking_back; +static int global_unset_count = 0; + + +struct dimensions_collection get_collection(int); +int contains_element(int*, int, int); +void get_horizontal(int, int*); +void get_vertical(int, int*); +void get_square(int, int*); +int set_values(int, int); +void take_back(int); + +int show_solution(int*); + + +int show_solution (int* solution) { + + int i; + int counter = 0; + + printf( " -----------------------------------\n" ); + + for ( i = 0; i < TOTAL; i++ ) { + if ( i % LINE == 0 ) + printf( "|" ); + + if ( solution[i] ) { + printf( " %d ", solution[i]); + counter++; + } + else + printf( " "); + + if ( i % LINE == (LINE - 1) ) { + printf( "|\n" ); + if ( i != (TOTAL - 1) ) { + if ( i % (SMALL_LINE * LINE) == (SMALL_LINE * LINE - 1) ) + printf( "|-----------+-----------+-----------|\n" ); + else + printf( "|- - - - - -|- - - - - -|- - - - - -|\n" ); + } + } + else { + if ( i % SMALL_LINE == (SMALL_LINE - 1) ) + printf( "|"); + else + printf( ":" ); + } + } + + printf( " -----------------------------------" ); + + return counter; +} + + +/** + * Takes a position inside the large square and returns + * - the row number + * - the column number + * - the small square number + * where this position is situated in + */ +struct dimensions_collection get_collection (int index) { + struct dimensions_collection ret; + + ret.row = (int) (index / LINE); + ret.column = index % LINE; + ret.small_square = SMALL_LINE * (int) (ret.row / SMALL_LINE) + (int) (ret.column / SMALL_LINE); + + return ret; +} + +/** + * Is 'the_element' in 'the_array'? + */ +int contains_element (int* the_array, int the_element, int length) { + for ( int i = 0; i < length; i++ ) + if ( the_array[i] == the_element ) + return 1; + return 0; +} + +/** + * Sets all members of row 'row' + */ +void get_horizontal (int row, int* ret) { + int j = 0; + for ( int i = (row * LINE); i < (row * LINE) + LINE; i++ ) + ret[j++] = riddle[i]; +} +/** + * Sets all members of column 'col' + */ +void get_vertical (int col, int* ret) { + int j = 0; + for ( int i = col; i < TOTAL; i += LINE ) + ret[j++] = riddle[i]; +} +/** + * Sets all members of small square 'which' + */ +void get_square (int which, int* ret) { + for ( int i = 0; i < SMALL_LINE; i++ ) + for ( int j = 0; j < SMALL_LINE; j++ ) + ret[SMALL_LINE * i + j] = riddle[LINE * i + which * SMALL_LINE + j + ((int) (which / SMALL_LINE) * (SMALL_LINE - 1) * LINE)]; +} + +/** + * Recursive function: + * Try for each position the numbers from 1 to LINE + * (except 'forbidden_number' if given). + * If all numbers collide with already set numbers, move is bad. + * If a number doesn't collide with already set numbers, + * - move is bad if next move collides with the already set numbers + * (including actual one) + * - move is good if it's the last one + */ +int set_values (int index, int forbidden_number) { + + if ( taking_back && tries_to_set > (2 * LIMIT) ) + return 1; + + int real_index = indices[index]; + struct dimensions_collection blocks = get_collection(real_index); + int elements[LINE]; + + for ( int i = 1; i <= LINE; i++ ) { + if ( forbidden_number && i == forbidden_number ) + continue; + + tries_to_set++; + + get_horizontal(blocks.row, elements); + if ( contains_element(elements, i, LINE) ) + continue; + + get_vertical(blocks.column, elements); + if ( contains_element(elements, i, LINE) ) + continue; + + get_square(blocks.small_square, elements); + if ( contains_element(elements, i, LINE) ) + continue; + + riddle[real_index] = i; + + if ( index == (TOTAL - 1) || set_values((index + 1), 0) ) + return 1; + } + + riddle[real_index] = 0; + + return 0; +} + +/** + * Some steps to hide unnecessary numbers: + * a) Define last piece as 'special piece' + * b) Remember this piece's value + * c) Try to create riddle from this position on, + * but forbid the value of the special piece + * d) I) If operation fails, define the piece before the special piece + * as 'special piece' and continue with b) + * II) If operation is possible, reset 'special piece' + * and put it to start of list + * e) Stop if all pieces are tried or calculation limit is reached + */ +void take_back (int unset_count) { + + global_unset_count++; + + int i; + + int tmp = riddle[indices[TOTAL - unset_count]]; + int redundant = set_values((TOTAL - unset_count), tmp); + + if ( !redundant ) { + unsolved[indices[TOTAL - unset_count]] = 0; + take_back(++unset_count); + } + else { + riddle[indices[TOTAL - unset_count]] = tmp; + for ( i = 1; i < unset_count; i++ ) + riddle[indices[TOTAL - unset_count + i]] = 0; + + for ( i = (TOTAL - unset_count); i > 0; i-- ) + indices[i] = indices[i - 1]; + indices[0] = tmp; + + if ( global_unset_count < TOTAL && tries_to_set < LIMIT ) + take_back(unset_count); + } +} + + +int sudoku(uint8_t solved9[LINE][LINE],uint8_t unsolved9[LINE][LINE],uint32_t srandi) +{ + int i, j, random, small_rows, small_cols, tmp, redundant,ind; + int multi_raw[LINE][LINE]; + + memset(indices,0,sizeof(indices)); + memset(solved,0,sizeof(solved)); + memset(unsolved,0,sizeof(unsolved)); + tries_to_set = 0; + taking_back = 0; + global_unset_count = 0; + + //time_t t; + //time(&t); + srand(srandi); + + /** + * Initialization: + * Fields are set to 0 ( i.e. we dont' know the number yet) + */ + for ( i = 0; i < TOTAL; i++ ) + riddle[i] = 0; + + /** + * Second initialization: + * LINE times numbers from 0 to (LINE - 1), + * i.e. every square + */ + int big_rows_array[] = {0, 1, 2}; + int big_cols_array[] = {0, 1, 2}; + random = rand() % 4; + switch (random) { + case 1: + big_rows_array[0] = 2; + big_rows_array[1] = 1; + big_rows_array[2] = 0; + break; + case 2: + big_cols_array[0] = 2; + big_cols_array[1] = 1; + big_cols_array[2] = 0; + break; + case 3: + big_rows_array[0] = 2; + big_rows_array[1] = 1; + big_rows_array[2] = 0; + big_cols_array[0] = 2; + big_cols_array[1] = 1; + big_cols_array[2] = 0; + } + int big_rows, big_cols, big_rows_index, big_cols_index, start_value; + i = 0; + j = 0; + for ( big_rows_index = 0; big_rows_index < SMALL_LINE; big_rows_index++ ) { + big_rows = big_rows_array[big_rows_index]; + for ( big_cols_index = 0; big_cols_index < SMALL_LINE; big_cols_index++ ) { + big_cols = big_cols_array[big_cols_index]; + start_value = big_rows * LINE * SMALL_LINE + (big_cols * SMALL_LINE); + for ( small_rows = 0; small_rows < SMALL_LINE; small_rows++ ) + for ( small_cols = 0; small_cols < SMALL_LINE; small_cols++ ) + multi_raw[i][j++] = small_rows * LINE + small_cols + start_value; + i++; + j = 0; + } + } + + + /** + * Randomization for every element of multi_raw. + * Suffle only inside squares + */ + for ( i = 0; i < LINE; i++ ) { + for ( j = 0; j < LINE; j++ ) { + random = rand() % LINE; + if ( j == random ) + continue; + tmp = multi_raw[i][j]; + multi_raw[i][j] = multi_raw[i][random]; + multi_raw[i][random] = tmp; + } + } + + /** + * Linearization + */ + for ( i = 0; i < LINE; i++ ) + for ( j = 0; j < LINE; j++ ) + indices[i * LINE + j] = multi_raw[i][j]; + + + /** + * Setting numbers, start with the first one. + * Variable 'redundant' is needed only for formal reasons + */ + taking_back = 0; + redundant = set_values(0, 0); + + + memcpy(solved, riddle, (TOTAL * sizeof(int))); + memcpy(unsolved, riddle, (TOTAL * sizeof(int))); + + + /** + * Exchanging some (few) indices for more randomized game + */ + int random2; + for ( i = (LINE - 1); i > 0; i-- ) { + for ( j = 0; j < (int) (sqrt(i)); j++ ) { + + if ( !(rand() % ((int) (i * sqrt(i)))) || !(LINE - j) ) + continue; + + random = i * LINE + (int) (rand() % (LINE - j)); + random2 = rand() % TOTAL; + + if ( random == random2 ) + continue; + + tmp = indices[random]; + indices[random] = indices[random2]; + indices[random2] = tmp; + } + } + + + tries_to_set = 0; + taking_back = 1; + take_back(1); + + + if ( SHOW_SOLVED ) { + printf( "\n\n" ); + redundant = show_solution(solved); + } + + int counter = show_solution(unsolved); + printf( "\t *** %d numbers left *** \n", counter ); + ind = 0; + for (i=0; i=0; j--) + { + x *= 9; + x += vals9[i][j]-1; + } + if ( i < 8 ) + keyvals[i] = x; + else + { + for (j=0; j<8; j++) + keyvals[j] += SUDOKU_NINETH * (vals9[i][j]-1); + } + } + for (i=ind=0; i<8; i++) + { + privkey[ind++] = ((keyvals[i] >> 24) & 0xff); + privkey[ind++] = ((keyvals[i] >> 16) & 0xff); + privkey[ind++] = ((keyvals[i] >> 8) & 0xff); + privkey[ind++] = (keyvals[i] & 0xff); + } +} + +void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) +{ + uint8_t vals9[9][9],uniq9[9][9]; int32_t i,j; + sudoku(vals9,unsolved,srandi); + sudoku_privkey(key32,vals9); + sudoku_privkeydisp(key32); +} diff --git a/src/key.cpp b/src/key.cpp index 3b6fed81b..6e2370dc2 100644 --- a/src/key.cpp +++ b/src/key.cpp @@ -179,6 +179,22 @@ void CKey::MakeNewKey(bool fCompressedIn) { fCompressed = fCompressedIn; } +int32_t CKey::SetKey32(uint8_t Key32[32]) +{ + memcpy(vch,Key32,32); + fCompressed = true; + if ( Check(vch) == 0 ) + { + fValid = false; + return(-1); + } + else + { + fValid = true; + return(0); + } +} + bool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) { if (!ec_privkey_import_der(secp256k1_context_sign, (unsigned char*)begin(), &privkey[0], privkey.size())) return false; diff --git a/src/key.h b/src/key.h index c41208003..857e8a8ae 100644 --- a/src/key.h +++ b/src/key.h @@ -128,6 +128,7 @@ public: //! Generate a new private key using a cryptographic PRNG. void MakeNewKey(bool fCompressed); + int32_t SetKey32(uint8_t Key32[32]); /** * Convert the private key to a CPrivKey (serialized OpenSSL private key data). From c7fa58b74a2d212cb90baca5c34c18fcac230e40 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 28 Jan 2019 22:16:22 -1100 Subject: [PATCH 0087/1145] Check cclib addr --- src/cc/CCcustom.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/cc/CCcustom.cpp b/src/cc/CCcustom.cpp index 577332b63..7d6d80043 100644 --- a/src/cc/CCcustom.cpp +++ b/src/cc/CCcustom.cpp @@ -245,7 +245,7 @@ uint8_t CClibCCpriv[32] = { 0x57, 0xcf, 0x49, 0x71, 0x7d, 0xb4, 0x15, 0x1b, 0x4f int32_t CClib_initcp(struct CCcontract_info *cp,uint8_t evalcode) { - CPubKey pk; uint8_t pub33[33]; char CCaddr[64]; + CPubKey pk; uint8_t pub33[33],check33[33]; char CCaddr[64],checkaddr[64],str[67]; if ( evalcode == EVAL_FIRSTUSER ) // eventually make a hashchain for each evalcode { cp->evalcode = evalcode; @@ -258,7 +258,14 @@ int32_t CClib_initcp(struct CCcontract_info *cp,uint8_t evalcode) if ( strcmp(cp->normaladdr,CClibNormaladdr) != 0 ) fprintf(stderr,"CClib_initcp addr mismatch %s vs %s\n",cp->normaladdr,CClibNormaladdr); GetCCaddress(cp,cp->unspendableCCaddr,pk); - return(0); + if ( priv2addr(checkaddr,check33,myprivkey) != 0 ) + { + if ( buf2pk(check33) == pk && strcmp(checkaddr,cp->normaladdr) == 0 ) + { + fprinf(stderr,"verified evalcode.%d %s %s\n",cp->evalcode,checkaddr,pubkey33_str(str,pub33)); + return(0); + } else fprintf(stderr,"CClib_initcp mismatched privkey -> addr %s vs %s\n",checkaddr,cp->normaladdr); + } } return(-1); } From 980a5efbafaeddff9d33f8dae54636a612c0c40f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 28 Jan 2019 22:22:54 -1100 Subject: [PATCH 0088/1145] Syntax --- src/cc/CCcustom.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/CCcustom.cpp b/src/cc/CCcustom.cpp index 7d6d80043..e60ed2997 100644 --- a/src/cc/CCcustom.cpp +++ b/src/cc/CCcustom.cpp @@ -258,11 +258,11 @@ int32_t CClib_initcp(struct CCcontract_info *cp,uint8_t evalcode) if ( strcmp(cp->normaladdr,CClibNormaladdr) != 0 ) fprintf(stderr,"CClib_initcp addr mismatch %s vs %s\n",cp->normaladdr,CClibNormaladdr); GetCCaddress(cp,cp->unspendableCCaddr,pk); - if ( priv2addr(checkaddr,check33,myprivkey) != 0 ) + if ( priv2addr(checkaddr,check33,cp->CCpriv) != 0 ) { if ( buf2pk(check33) == pk && strcmp(checkaddr,cp->normaladdr) == 0 ) { - fprinf(stderr,"verified evalcode.%d %s %s\n",cp->evalcode,checkaddr,pubkey33_str(str,pub33)); + fprintf(stderr,"verified evalcode.%d %s %s\n",cp->evalcode,checkaddr,pubkey33_str(str,pub33)); return(0); } else fprintf(stderr,"CClib_initcp mismatched privkey -> addr %s vs %s\n",checkaddr,cp->normaladdr); } From 886003602724ed4a3ae9ac8058f7013ac770b458 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 28 Jan 2019 22:36:34 -1100 Subject: [PATCH 0089/1145] Autocalc all cclib cp --- src/cc/CCcustom.cpp | 24 ++++++++++++++++++++---- src/wallet/rpcwallet.cpp | 19 +++++++++++++------ 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/src/cc/CCcustom.cpp b/src/cc/CCcustom.cpp index e60ed2997..e00b5a0a0 100644 --- a/src/cc/CCcustom.cpp +++ b/src/cc/CCcustom.cpp @@ -245,13 +245,13 @@ uint8_t CClibCCpriv[32] = { 0x57, 0xcf, 0x49, 0x71, 0x7d, 0xb4, 0x15, 0x1b, 0x4f int32_t CClib_initcp(struct CCcontract_info *cp,uint8_t evalcode) { - CPubKey pk; uint8_t pub33[33],check33[33]; char CCaddr[64],checkaddr[64],str[67]; + CPubKey pk; int32_t i; uint8_t pub33[33],check33[33],hash[32]; char CCaddr[64],checkaddr[64],str[67]; + cp->evalcode = evalcode; + cp->ismyvin = IsCClibInput; + memcpy(cp->CCpriv,CClibCCpriv,32); if ( evalcode == EVAL_FIRSTUSER ) // eventually make a hashchain for each evalcode { - cp->evalcode = evalcode; - cp->ismyvin = IsCClibInput; strcpy(cp->CChexstr,CClibCChexstr); - memcpy(cp->CCpriv,CClibCCpriv,32); decode_hex(pub33,33,cp->CChexstr); pk = buf2pk(pub33); Getscriptaddress(cp->normaladdr,CScript() << ParseHex(HexStr(pk)) << OP_CHECKSIG); @@ -267,6 +267,22 @@ int32_t CClib_initcp(struct CCcontract_info *cp,uint8_t evalcode) } else fprintf(stderr,"CClib_initcp mismatched privkey -> addr %s vs %s\n",checkaddr,cp->normaladdr); } } + else + { + for (i=EVAL_FIRSTUSER; iCCpriv,32); + memcpy(cp->CCpriv,hash,32); + } + if ( priv2addr(cp->normaladdr,pub33,cp->CCpriv) != 0 ) + { + pk = buf2pk(pub33); + for (i=0; i<33; i++) + sprintf(&cp->CChexstr[i*2],"%02x",pub33[i]); + cp->CChexstr[i*2] = 0; + GetCCaddress(cp,cp->unspendableCCaddr,pk); + } + } return(-1); } diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 0ffc370e2..b799c6672 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5327,13 +5327,20 @@ UniValue channelsaddress(const UniValue& params, bool fHelp) UniValue cclibaddress(const UniValue& params, bool fHelp) { struct CCcontract_info *cp,C; std::vector pubkey; - cp = CCinit(&C,EVAL_FIRSTUSER); - if ( fHelp || params.size() > 1 ) - throw runtime_error("cclibaddress [pubkey]\n"); + if ( fHelp || params.size() > 2 ) + throw runtime_error("cclibaddress [evalcode] [pubkey]\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); - if ( params.size() == 1 ) - pubkey = ParseHex(params[0].get_str().c_str()); + cp = CCinit(&C,EVAL_FIRSTUSER); + if ( params.size() >= 1 ) + { + evalcode = atoi(params[0].get_str().c_str()); + if ( evalcode < EVAL_FIRSTUSER || evalcode > EVAL_LASTUSER ) + throw runtime_error("evalcode not between EVAL_FIRSTUSER and EVAL_LASTUSER\n"); + cp = CCinit(&C,evalcode); + if ( params.size() == 2 ) + pubkey = ParseHex(params[1].get_str().c_str()); + } return(CCaddress(cp,(char *)"CClib",pubkey)); } @@ -7695,4 +7702,4 @@ UniValue test_heirmarker(const UniValue& params, bool fHelp) cp = CCinit(&C, EVAL_HEIR); return(FinalizeCCTx(0, cp, mtx, myPubkey, 10000, opret)); -} \ No newline at end of file +} From 534c5ee516354074a029643cb48b3f4534cf5f4e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 28 Jan 2019 22:38:06 -1100 Subject: [PATCH 0090/1145] Err --- src/wallet/rpcwallet.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index b799c6672..2d4ba25d7 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5326,21 +5326,22 @@ UniValue channelsaddress(const UniValue& params, bool fHelp) UniValue cclibaddress(const UniValue& params, bool fHelp) { - struct CCcontract_info *cp,C; std::vector pubkey; + struct CCcontract_info *cp,C; std::vector pubkey; uint8_t evalcode = EVAL_FIRSTUSER; if ( fHelp || params.size() > 2 ) throw runtime_error("cclibaddress [evalcode] [pubkey]\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); - cp = CCinit(&C,EVAL_FIRSTUSER); if ( params.size() >= 1 ) { evalcode = atoi(params[0].get_str().c_str()); if ( evalcode < EVAL_FIRSTUSER || evalcode > EVAL_LASTUSER ) throw runtime_error("evalcode not between EVAL_FIRSTUSER and EVAL_LASTUSER\n"); - cp = CCinit(&C,evalcode); if ( params.size() == 2 ) pubkey = ParseHex(params[1].get_str().c_str()); } + cp = CCinit(&C,evalcode); + if ( cp == 0 ) + throw runtime_error("error creating *cp\n"); return(CCaddress(cp,(char *)"CClib",pubkey)); } From 42a362165ff2f8a209ee74e2ca6f84ac2c047d3f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 28 Jan 2019 22:43:52 -1100 Subject: [PATCH 0091/1145] Add [evalcode] to cclib roc --- src/cc/CCcustom.cpp | 1 + src/wallet/rpcwallet.cpp | 26 ++++++++++++++++++++------ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/cc/CCcustom.cpp b/src/cc/CCcustom.cpp index e00b5a0a0..477487390 100644 --- a/src/cc/CCcustom.cpp +++ b/src/cc/CCcustom.cpp @@ -281,6 +281,7 @@ int32_t CClib_initcp(struct CCcontract_info *cp,uint8_t evalcode) sprintf(&cp->CChexstr[i*2],"%02x",pub33[i]); cp->CChexstr[i*2] = 0; GetCCaddress(cp,cp->unspendableCCaddr,pk); + return(0); } } return(-1); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 2d4ba25d7..c6370d762 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5347,25 +5347,39 @@ UniValue cclibaddress(const UniValue& params, bool fHelp) UniValue cclibinfo(const UniValue& params, bool fHelp) { - struct CCcontract_info *cp,C; - cp = CCinit(&C,EVAL_FIRSTUSER); + struct CCcontract_info *cp,C; uint8_t evalcode = EVAL_FIRSTUSER; if ( fHelp || params.size() > 0 ) throw runtime_error("cclibinfo\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + if ( params.size() >= 1 ) + { + evalcode = atoi(params[0].get_str().c_str()); + if ( evalcode < EVAL_FIRSTUSER || evalcode > EVAL_LASTUSER ) + throw runtime_error("evalcode not between EVAL_FIRSTUSER and EVAL_LASTUSER\n"); + } + cp = CCinit(&C,evalcode); return(CClib_info(cp)); } UniValue cclib(const UniValue& params, bool fHelp) { - struct CCcontract_info *cp,C; char *method; cJSON *jsonparams; + struct CCcontract_info *cp,C; char *method; cJSON *jsonparams=0; uint8_t evalcode; cp = CCinit(&C,EVAL_FIRSTUSER); - if ( fHelp || params.size() > 2 ) - throw runtime_error("cclib method [JSON params]\n"); + if ( fHelp || params.size() > 3 ) + throw runtime_error("cclib method [evalcode] [JSON params]\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); method = (char *)params[0].get_str().c_str(); - jsonparams = cJSON_Parse(params[1].get_str().c_str()); + if ( params.size() >= 1 ) + { + evalcode = atoi(params[1].get_str().c_str()); + if ( evalcode < EVAL_FIRSTUSER || evalcode > EVAL_LASTUSER ) + throw runtime_error("evalcode not between EVAL_FIRSTUSER and EVAL_LASTUSER\n"); + if ( params.size() == 2 ) + jsonparams = cJSON_Parse(params[2].get_str().c_str()); + } + cp = CCinit(&C,evalcode); return(CClib(cp,method,jsonparams)); } From 087d590f36b5e62db7508f2807df9d6cca372e9e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 28 Jan 2019 23:35:17 -1100 Subject: [PATCH 0092/1145] Link in sudoku --- src/cc/Makefile | 2 +- src/cc/cclib.cpp | 79 ++++++++++++++++++++++++++++++++++++----------- src/cc/makecclib | 2 +- src/cc/sudoku.cpp | 52 +++++++++++++++++++++++++++++++ 4 files changed, 115 insertions(+), 20 deletions(-) diff --git a/src/cc/Makefile b/src/cc/Makefile index 52db18fca..97798e41e 100644 --- a/src/cc/Makefile +++ b/src/cc/Makefile @@ -13,7 +13,7 @@ $(info $(OS)) TARGET = ../libcc.so TARGET_DARWIN = ../libcc.dylib TARGET_WIN = ../libcc.dll -SOURCES = cclib.cpp +SOURCES = cclib.cpp sudoku.cpp #HEADERS = $(shell echo ../cryptoconditions/include/*.h) all: $(TARGET) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 971258d90..2875ce4b0 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -28,24 +28,63 @@ #include "crosschain.h" #define FAUCET2SIZE COIN +#defein EVAL_FAUCET2 EVAL_FIRSTUSER +#define EVAL_SUDOKU 17 + +std::string MYCCLIBNAME = (char *)"sudoku"; +char *CClib_name() { return((char *)MYCCLIBNAME.c_str()); } struct CClib_rpcinfo { - char *method,*help; + char *CCname,*method,*help; int32_t numrequiredargs,maxargs; // frontloaded with required - uint8_t funcid; + uint8_t funcid,evalcode; } CClib_methods[] = { - { (char *)"faucet2_fund", (char *)"amount", 1, 1, 'F' }, - { (char *)"faucet2_get", (char *)"", 0, 0, 'G' }, + { (char *)"faucet2", (char *)"fund", (char *)"amount", 1, 1, 'F', EVAL_FAUCET2 }, + { (char *)"faucet2", (char *)"get", (char *)"", 0, 0, 'G', EVAL_FAUCET2 }, + { (char *)"sudoku", (char *)"gen", (char *)"amount", 1, 1, 'G', EVAL_SUDOKU }, + { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, + { (char *)"sudoku", (char *)"pending", (char *)"", 0, 0, 'U', EVAL_SUDOKU }, + { (char *)"sudoku", (char *)"solution", (char *)"solution timestamps[]", 2, 2, 'S', EVAL_SUDOKU }, }; -std::string MYCCLIBNAME = (char *)"faucet2"; - -char *CClib_name() { return((char *)MYCCLIBNAME.c_str()); } - std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *params); +UniValue sudoku_txidinfo(struct CCcontract_info *cp,cJSON *params); +UniValue sudoku_generate(struct CCcontract_info *cp,cJSON *params); +UniValue sudoku_solution(struct CCcontract_info *cp,cJSON *params); +UniValue sudoku_pending(struct CCcontract_info *cp,cJSON *params); + +UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + if ( cp->evalcode == EVAL_SUDOKU ) + { + if ( strcmp(method,"txidinfo") == 0 ) + return(sudoku_txidinfo(cp,params)); + else if ( strcmp(method,"gen") == 0 ) + return(sudoku_generate(cp,params)); + else if ( strcmp(method,"solution") == 0 ) + return(sudoku_solution(cp,params)); + else if ( strcmp(method,"pending") == 0 ) + return(sudoku_pending(cp,params)); + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","invalid sudoku method")); + result.push_back(Pair("method",method)); + return(result); + } + } + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","only sudoku supported for now")); + result.push_back(Pair("evalcode",(int)cp->evalcode)); + return(result); + } +} UniValue CClib_info(struct CCcontract_info *cp) { @@ -55,6 +94,7 @@ UniValue CClib_info(struct CCcontract_info *cp) for (i=0; i= 128 ) obj.push_back(Pair("funcid",CClib_methods[i].funcid)); else @@ -63,7 +103,8 @@ UniValue CClib_info(struct CCcontract_info *cp) str[1] = 0; obj.push_back(Pair("funcid",str)); } - obj.push_back(Pair("name",CClib_methods[i].method)); + obj.push_back(Pair("name",CClib_methods[i].CCname)); + obj.push_back(Pair("method",CClib_methods[i].method)); obj.push_back(Pair("help",CClib_methods[i].help)); obj.push_back(Pair("params_required",CClib_methods[i].numrequiredargs)); obj.push_back(Pair("params_max",CClib_methods[i].maxargs)); @@ -78,13 +119,16 @@ UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params) UniValue result(UniValue::VOBJ); int32_t i; std::string rawtx; for (i=0; ievalcode == CClib_methods[i].evalcode && strcmp(method,CClib_methods[i].method) == 0 ) { - result.push_back(Pair("result","success")); - result.push_back(Pair("method",CClib_methods[i].method)); - rawtx = CClib_rawtxgen(cp,CClib_methods[i].funcid,params); - result.push_back(Pair("rawtx",rawtx)); - return(result); + if ( cp->evalcode == EVAL_FAUCET2 ) + { + result.push_back(Pair("result","success")); + result.push_back(Pair("method",CClib_methods[i].method)); + rawtx = CClib_rawtxgen(cp,CClib_methods[i].funcid,params); + result.push_back(Pair("rawtx",rawtx)); + return(result); + } else return(CClib_method(cp,method,params)); } } result.push_back(Pair("result","error")); @@ -234,7 +278,6 @@ int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK return(totalinputs); } - std::string Faucet2Fund(struct CCcontract_info *cp,uint64_t txfee,int64_t funds) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); @@ -289,14 +332,14 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para if ( inputs > nValue ) CCchange = (inputs - nValue - txfee); if ( CCchange != 0 ) - mtx.vout.push_back(MakeCC1vout(EVAL_FIRSTUSER,CCchange,cclibpk)); + mtx.vout.push_back(MakeCC1vout(EVAL_FAUCET2,CCchange,cclibpk)); mtx.vout.push_back(CTxOut(nValue,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); fprintf(stderr,"start at %u\n",(uint32_t)time(NULL)); j = rand() & 0xfffffff; for (i=0; i<1000000; i++,j++) { tmpmtx = mtx; - rawhex = FinalizeCCTx(-1LL,cp,tmpmtx,mypk,txfee,CScript() << OP_RETURN << E_MARSHAL(ss << (uint8_t)EVAL_FIRSTUSER << (uint8_t)'G' << j)); + rawhex = FinalizeCCTx(-1LL,cp,tmpmtx,mypk,txfee,CScript() << OP_RETURN << E_MARSHAL(ss << (uint8_t)EVAL_FAUCET2 << (uint8_t)'G' << j)); if ( (len= (int32_t)rawhex.size()) > 0 && len < 65536 ) { len >>= 1; diff --git a/src/cc/makecclib b/src/cc/makecclib index 47aec377d..6131148f1 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1 +1 @@ -gcc -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../cclib.so cclib.cpp +gcc -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../cclib.so cclib.cpp sudoku.cpp diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index a79e3d161..6e54d0709 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -474,3 +474,55 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) sudoku_privkey(key32,vals9); sudoku_privkeydisp(key32); } + +//////////////////////// start of CClib interface +#include +#include + +#include "primitives/block.h" +#include "primitives/transaction.h" +#include "script/cc.h" +#include "cc/eval.h" +#include "cc/utils.h" +#include "cc/CCinclude.h" +#include "main.h" +#include "chain.h" +#include "core_io.h" +#include "crosschain.h" + +UniValue sudoku_txidinfo(struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + if ( params != 0 ) + printf("params.(%s)\n",jprint(params,0)); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue sudoku_generate(struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + if ( params != 0 ) + printf("params.(%s)\n",jprint(params,0)); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue sudoku_solution(struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + if ( params != 0 ) + printf("params.(%s)\n",jprint(params,0)); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue sudoku_pending(struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + if ( params != 0 ) + printf("params.(%s)\n",jprint(params,0)); + result.push_back(Pair("result","success")); + return(result); +} + From 6999011a90e945a716cd9a1e96006a3cbd83e8d6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 28 Jan 2019 23:37:17 -1100 Subject: [PATCH 0093/1145] #include sudoku.cpp as linker errors --- src/cc/Makefile | 2 +- src/cc/cclib.cpp | 3 +++ src/cc/makecclib | 2 +- src/cc/sudoku.cpp | 13 ------------- 4 files changed, 5 insertions(+), 15 deletions(-) diff --git a/src/cc/Makefile b/src/cc/Makefile index 97798e41e..3e988f279 100644 --- a/src/cc/Makefile +++ b/src/cc/Makefile @@ -13,7 +13,7 @@ $(info $(OS)) TARGET = ../libcc.so TARGET_DARWIN = ../libcc.dylib TARGET_WIN = ../libcc.dll -SOURCES = cclib.cpp sudoku.cpp +SOURCES = cclib.cpp #HEADERS = $(shell echo ../cryptoconditions/include/*.h) all: $(TARGET) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 2875ce4b0..06982fe92 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -358,3 +358,6 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para } else fprintf(stderr,"cant find faucet inputs\n"); return(""); } + +#include "sudoku.cpp" + diff --git a/src/cc/makecclib b/src/cc/makecclib index 6131148f1..47aec377d 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1 +1 @@ -gcc -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../cclib.so cclib.cpp sudoku.cpp +gcc -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../cclib.so cclib.cpp diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 6e54d0709..c5cbc1b31 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -476,19 +476,6 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) } //////////////////////// start of CClib interface -#include -#include - -#include "primitives/block.h" -#include "primitives/transaction.h" -#include "script/cc.h" -#include "cc/eval.h" -#include "cc/utils.h" -#include "cc/CCinclude.h" -#include "main.h" -#include "chain.h" -#include "core_io.h" -#include "crosschain.h" UniValue sudoku_txidinfo(struct CCcontract_info *cp,cJSON *params) { From 2c7d564a908534530727dabf22f940c29f7e5afc Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 28 Jan 2019 23:38:14 -1100 Subject: [PATCH 0094/1145] Define --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 06982fe92..4405cda87 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -28,7 +28,7 @@ #include "crosschain.h" #define FAUCET2SIZE COIN -#defein EVAL_FAUCET2 EVAL_FIRSTUSER +#define EVAL_FAUCET2 EVAL_FIRSTUSER #define EVAL_SUDOKU 17 std::string MYCCLIBNAME = (char *)"sudoku"; From 72c4217d3904592f8bdbb4b4268ca208e49ddc53 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 28 Jan 2019 23:54:41 -1100 Subject: [PATCH 0095/1145] +print --- src/wallet/rpcwallet.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index c6370d762..1ea66bb5e 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5174,11 +5174,20 @@ int32_t ensure_CCrequirements() { CCerror = ""; if ( NOTARY_PUBKEY33[0] == 0 ) + { + fprintf(stderr,"no -pubkey set\n"); return(-1); + } else if ( GetBoolArg("-addressindex", DEFAULT_ADDRESSINDEX) == 0 ) + { + fprintf(stderr,"no -addressindex\n"); return(-1); + } else if ( GetBoolArg("-spentindex", DEFAULT_SPENTINDEX) == 0 ) + { + fprintf(stderr,"no -spentindex\n"); return(-1); + } else return(0); } From 47294fb7362fc94b3c6cca6e93f4fda7bcf85a87 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 28 Jan 2019 23:59:13 -1100 Subject: [PATCH 0096/1145] -pubkey --- src/komodo_utils.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/komodo_utils.h b/src/komodo_utils.h index 96c9cd922..5b3a6cd39 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1671,6 +1671,7 @@ void komodo_args(char *argv0) KOMODO_DEALERNODE = GetArg("-dealer",0); if ( strlen(NOTARY_PUBKEY.c_str()) == 66 ) { + decode_hex(NOTARY_PUBKEY33,33,NOTARY_PUBKEY.c_str()); USE_EXTERNAL_PUBKEY = 1; if ( IS_KOMODO_NOTARY == 0 ) { From 7b24fb0d45cec28654833f7264cc50b4dc8848c8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 00:00:17 -1100 Subject: [PATCH 0097/1145] (Char *) --- 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 5b3a6cd39..bcd95e698 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1671,7 +1671,7 @@ void komodo_args(char *argv0) KOMODO_DEALERNODE = GetArg("-dealer",0); if ( strlen(NOTARY_PUBKEY.c_str()) == 66 ) { - decode_hex(NOTARY_PUBKEY33,33,NOTARY_PUBKEY.c_str()); + decode_hex(NOTARY_PUBKEY33,33,(char *)NOTARY_PUBKEY.c_str()); USE_EXTERNAL_PUBKEY = 1; if ( IS_KOMODO_NOTARY == 0 ) { From 812d9235ebc476516c339b235c69d4e782facff9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 00:04:50 -1100 Subject: [PATCH 0098/1145] Test --- src/wallet/rpcwallet.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 1ea66bb5e..bc10da7bc 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5384,7 +5384,10 @@ UniValue cclib(const UniValue& params, bool fHelp) { evalcode = atoi(params[1].get_str().c_str()); if ( evalcode < EVAL_FIRSTUSER || evalcode > EVAL_LASTUSER ) + { + printf("evalcode.%d vs (%d, %d)\n",evalcode,EVAL_FIRSTUSER,EVAL_LASTUSER); throw runtime_error("evalcode not between EVAL_FIRSTUSER and EVAL_LASTUSER\n"); + } if ( params.size() == 2 ) jsonparams = cJSON_Parse(params[2].get_str().c_str()); } From a614b0555fa02c176a570c007701b86f4ddbba0a Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 00:10:42 -1100 Subject: [PATCH 0099/1145] Prints --- src/cc/CCcustom.cpp | 1 + src/cc/sudoku.cpp | 4 ++++ src/wallet/rpcwallet.cpp | 10 ++-------- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/cc/CCcustom.cpp b/src/cc/CCcustom.cpp index 477487390..0b150e6e0 100644 --- a/src/cc/CCcustom.cpp +++ b/src/cc/CCcustom.cpp @@ -281,6 +281,7 @@ int32_t CClib_initcp(struct CCcontract_info *cp,uint8_t evalcode) sprintf(&cp->CChexstr[i*2],"%02x",pub33[i]); cp->CChexstr[i*2] = 0; GetCCaddress(cp,cp->unspendableCCaddr,pk); + printf("evalcode.%d initialized\n",evalcode); return(0); } } diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index c5cbc1b31..6f9d2d1d1 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -483,6 +483,7 @@ UniValue sudoku_txidinfo(struct CCcontract_info *cp,cJSON *params) if ( params != 0 ) printf("params.(%s)\n",jprint(params,0)); result.push_back(Pair("result","success")); + result.push_back(Pair("method","txidinfo")); return(result); } @@ -492,6 +493,7 @@ UniValue sudoku_generate(struct CCcontract_info *cp,cJSON *params) if ( params != 0 ) printf("params.(%s)\n",jprint(params,0)); result.push_back(Pair("result","success")); + result.push_back(Pair("method","gen")); return(result); } @@ -501,6 +503,7 @@ UniValue sudoku_solution(struct CCcontract_info *cp,cJSON *params) if ( params != 0 ) printf("params.(%s)\n",jprint(params,0)); result.push_back(Pair("result","success")); + result.push_back(Pair("method","solution")); return(result); } @@ -510,6 +513,7 @@ UniValue sudoku_pending(struct CCcontract_info *cp,cJSON *params) if ( params != 0 ) printf("params.(%s)\n",jprint(params,0)); result.push_back(Pair("result","success")); + result.push_back(Pair("method","pending")); return(result); } diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index bc10da7bc..c0fe4caa8 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5361,20 +5361,13 @@ UniValue cclibinfo(const UniValue& params, bool fHelp) throw runtime_error("cclibinfo\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); - if ( params.size() >= 1 ) - { - evalcode = atoi(params[0].get_str().c_str()); - if ( evalcode < EVAL_FIRSTUSER || evalcode > EVAL_LASTUSER ) - throw runtime_error("evalcode not between EVAL_FIRSTUSER and EVAL_LASTUSER\n"); - } cp = CCinit(&C,evalcode); return(CClib_info(cp)); } UniValue cclib(const UniValue& params, bool fHelp) { - struct CCcontract_info *cp,C; char *method; cJSON *jsonparams=0; uint8_t evalcode; - cp = CCinit(&C,EVAL_FIRSTUSER); + struct CCcontract_info *cp,C; char *method; cJSON *jsonparams=0; uint8_t evalcode = EVAL_FIRSTUSER; if ( fHelp || params.size() > 3 ) throw runtime_error("cclib method [evalcode] [JSON params]\n"); if ( ensure_CCrequirements() < 0 ) @@ -5391,6 +5384,7 @@ UniValue cclib(const UniValue& params, bool fHelp) if ( params.size() == 2 ) jsonparams = cJSON_Parse(params[2].get_str().c_str()); } + printf("evalcode.%d\n",evalcode); cp = CCinit(&C,evalcode); return(CClib(cp,method,jsonparams)); } From 946808ba40d1117372f39be7ac1c8767d1a81e6d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 00:16:49 -1100 Subject: [PATCH 0100/1145] libcc.so --- src/cc/makecclib | 2 +- src/cc/sudoku.cpp | 4 ++++ src/wallet/rpcwallet.cpp | 1 - 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/makecclib b/src/cc/makecclib index 47aec377d..0aecab072 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1 +1 @@ -gcc -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../cclib.so cclib.cpp +gcc -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 6f9d2d1d1..62a7ea91c 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -483,6 +483,7 @@ UniValue sudoku_txidinfo(struct CCcontract_info *cp,cJSON *params) if ( params != 0 ) printf("params.(%s)\n",jprint(params,0)); result.push_back(Pair("result","success")); + result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","txidinfo")); return(result); } @@ -493,6 +494,7 @@ UniValue sudoku_generate(struct CCcontract_info *cp,cJSON *params) if ( params != 0 ) printf("params.(%s)\n",jprint(params,0)); result.push_back(Pair("result","success")); + result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","gen")); return(result); } @@ -503,6 +505,7 @@ UniValue sudoku_solution(struct CCcontract_info *cp,cJSON *params) if ( params != 0 ) printf("params.(%s)\n",jprint(params,0)); result.push_back(Pair("result","success")); + result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","solution")); return(result); } @@ -513,6 +516,7 @@ UniValue sudoku_pending(struct CCcontract_info *cp,cJSON *params) if ( params != 0 ) printf("params.(%s)\n",jprint(params,0)); result.push_back(Pair("result","success")); + result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","pending")); return(result); } diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index c0fe4caa8..970dfa3cf 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5384,7 +5384,6 @@ UniValue cclib(const UniValue& params, bool fHelp) if ( params.size() == 2 ) jsonparams = cJSON_Parse(params[2].get_str().c_str()); } - printf("evalcode.%d\n",evalcode); cp = CCinit(&C,evalcode); return(CClib(cp,method,jsonparams)); } From db4e2fc5380b5d520b481d64bde57ad103c3c743 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 00:20:14 -1100 Subject: [PATCH 0101/1145] Hex --- src/cc/sudoku.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 62a7ea91c..f03fbd69b 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -496,6 +496,7 @@ UniValue sudoku_generate(struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("result","success")); result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","gen")); + result.push_back(Pair("hex","deadbeef")); return(result); } From ca2a5e048bb61857a2d630d6b906d35831e0d690 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 00:48:59 -1100 Subject: [PATCH 0102/1145] sudoku_gen --- src/cc/cclib.cpp | 18 +++++++++--------- src/cc/sudoku.cpp | 36 ++++++++++++++++++++++++++++++------ 2 files changed, 39 insertions(+), 15 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 4405cda87..8a7d054f7 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -51,24 +51,24 @@ CClib_methods[] = }; std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *params); -UniValue sudoku_txidinfo(struct CCcontract_info *cp,cJSON *params); -UniValue sudoku_generate(struct CCcontract_info *cp,cJSON *params); -UniValue sudoku_solution(struct CCcontract_info *cp,cJSON *params); -UniValue sudoku_pending(struct CCcontract_info *cp,cJSON *params); +UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) { - UniValue result(UniValue::VOBJ); + UniValue result(UniValue::VOBJ); uint64_t txfee = 10000; if ( cp->evalcode == EVAL_SUDOKU ) { if ( strcmp(method,"txidinfo") == 0 ) - return(sudoku_txidinfo(cp,params)); + return(sudoku_txidinfo(txfee,cp,params)); else if ( strcmp(method,"gen") == 0 ) - return(sudoku_generate(cp,params)); + return(sudoku_generate(txfee,cp,params)); else if ( strcmp(method,"solution") == 0 ) - return(sudoku_solution(cp,params)); + return(sudoku_solution(txfee,cp,params)); else if ( strcmp(method,"pending") == 0 ) - return(sudoku_pending(cp,params)); + return(sudoku_pending(txfee,cp,params)); else { result.push_back(Pair("result","error")); diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index f03fbd69b..5132d7c98 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -477,7 +477,7 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) //////////////////////// start of CClib interface -UniValue sudoku_txidinfo(struct CCcontract_info *cp,cJSON *params) +UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); if ( params != 0 ) @@ -488,19 +488,43 @@ UniValue sudoku_txidinfo(struct CCcontract_info *cp,cJSON *params) return(result); } -UniValue sudoku_generate(struct CCcontract_info *cp,cJSON *params) +CScript sudoku_genopret(uint8_t unsolved[9][9]) { - UniValue result(UniValue::VOBJ); + CScript opret; uint8_t evalcode = EVAL_SUDOKU; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'G' << unsolved); + return(opret); +} + +UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + UniValue result(UniValue::VOBJ); CPubKey sudokupk,pk; uint8_t privkey[32],unsolved[9][9],pub33[33]; uint32_t srandi; uint256 hash; char coinaddr[64]; uint64_t inputsum,amount; std::string hex; if ( params != 0 ) + { printf("params.(%s)\n",jprint(params,0)); + amount = jdouble(jitem(params,0),0) * COIN + 0.0000000049; + } else amount = COIN; result.push_back(Pair("result","success")); result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","gen")); - result.push_back(Pair("hex","deadbeef")); + hash = chainActive.LastTip()->GetHash(); + memcpy(&srandi,&hash,sizeof(srandi)) + srandi ^= (uint32_t)time(NULL); + sudoku_gen(privkey,unsolved,srandi); + priv2addr(coinaddr,pub33,privkey); + pk = buf2pk(pub33); + sudokupk = GetUnspendable(cp,0); + inputsum = amount + 2*txfee; + mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,sudokupk)); + mtx.vout.push_back(MakeCC1vout(cp->evalcode,inputsum - 2*txfee,pk)); + rawtx = FinalizeCCTx(0,cp,mtx,sudokupk,txfee,sudoku_genopret(unsolved)); + result.push_back(Pair("srand",srandi)); + result.push_back(Pair("amount",ValueFromAmount(amount))); + result.push_back(Pair("hex",rawtx)); return(result); } -UniValue sudoku_solution(struct CCcontract_info *cp,cJSON *params) +UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); if ( params != 0 ) @@ -511,7 +535,7 @@ UniValue sudoku_solution(struct CCcontract_info *cp,cJSON *params) return(result); } -UniValue sudoku_pending(struct CCcontract_info *cp,cJSON *params) +UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); if ( params != 0 ) From fb3246204be4c24a683b5666674c371bd69eae7b Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 00:50:17 -1100 Subject: [PATCH 0103/1145] Syntax --- src/cc/sudoku.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 5132d7c98..50a04e22e 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -498,7 +498,7 @@ CScript sudoku_genopret(uint8_t unsolved[9][9]) UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); CPubKey sudokupk,pk; uint8_t privkey[32],unsolved[9][9],pub33[33]; uint32_t srandi; uint256 hash; char coinaddr[64]; uint64_t inputsum,amount; std::string hex; + UniValue result(UniValue::VOBJ); CPubKey sudokupk,pk; uint8_t privkey[32],unsolved[9][9],pub33[33]; uint32_t srandi; uint256 hash; char coinaddr[64]; uint64_t inputsum,amount; std::string rawtx; if ( params != 0 ) { printf("params.(%s)\n",jprint(params,0)); @@ -508,7 +508,7 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","gen")); hash = chainActive.LastTip()->GetHash(); - memcpy(&srandi,&hash,sizeof(srandi)) + memcpy(&srandi,&hash,sizeof(srandi)); srandi ^= (uint32_t)time(NULL); sudoku_gen(privkey,unsolved,srandi); priv2addr(coinaddr,pub33,privkey); @@ -518,7 +518,7 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,sudokupk)); mtx.vout.push_back(MakeCC1vout(cp->evalcode,inputsum - 2*txfee,pk)); rawtx = FinalizeCCTx(0,cp,mtx,sudokupk,txfee,sudoku_genopret(unsolved)); - result.push_back(Pair("srand",srandi)); + result.push_back(Pair("srand",(int)srandi)); result.push_back(Pair("amount",ValueFromAmount(amount))); result.push_back(Pair("hex",rawtx)); return(result); From d4e8f4afa9e99eb4f6f0fd79556b8ddde21f1385 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 00:51:00 -1100 Subject: [PATCH 0104/1145] GetBlockHash() --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 50a04e22e..770620565 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -507,7 +507,7 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("result","success")); result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","gen")); - hash = chainActive.LastTip()->GetHash(); + hash = chainActive.LastTip()->GetBlockHash(); memcpy(&srandi,&hash,sizeof(srandi)); srandi ^= (uint32_t)time(NULL); sudoku_gen(privkey,unsolved,srandi); From 91f3a0fcbd0dfb3eeb5c5aec9b45d507d3d6f1a0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 00:52:52 -1100 Subject: [PATCH 0105/1145] Gen opret --- src/cc/sudoku.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 770620565..42f5791f8 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -490,8 +490,11 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params CScript sudoku_genopret(uint8_t unsolved[9][9]) { - CScript opret; uint8_t evalcode = EVAL_SUDOKU; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'G' << unsolved); + CScript opret; uint8_t evalcode = EVAL_SUDOKU; std::vector data; + for (i=0; i<9; i++) + for (j=0; j<9; j++) + data.push_back(unsolved[i][j]); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'G' << data); return(opret); } From 0d81615f616b645f78fabe9634d79e69805a56d1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 00:53:27 -1100 Subject: [PATCH 0106/1145] i,j --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 42f5791f8..20d11567a 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -490,7 +490,7 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params CScript sudoku_genopret(uint8_t unsolved[9][9]) { - CScript opret; uint8_t evalcode = EVAL_SUDOKU; std::vector data; + CScript opret; uint8_t evalcode = EVAL_SUDOKU; std::vector data; int32_t i,j; for (i=0; i<9; i++) for (j=0; j<9; j++) data.push_back(unsolved[i][j]); From 7e35f61a63bb7a7b92e66419e339d3be313f9f0c Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 01:25:02 -1100 Subject: [PATCH 0107/1145] Gen tx --- src/cc/sudoku.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 20d11567a..adba75920 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -476,6 +476,7 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) } //////////////////////// start of CClib interface +// ./komodod -ac_name=SUDOKU -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -gen -genproclimit=1 -ac_cclib=sudoku -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60000 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { @@ -517,13 +518,15 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params priv2addr(coinaddr,pub33,privkey); pk = buf2pk(pub33); sudokupk = GetUnspendable(cp,0); - inputsum = amount + 2*txfee; - mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,sudokupk)); - mtx.vout.push_back(MakeCC1vout(cp->evalcode,inputsum - 2*txfee,pk)); - rawtx = FinalizeCCTx(0,cp,mtx,sudokupk,txfee,sudoku_genopret(unsolved)); result.push_back(Pair("srand",(int)srandi)); result.push_back(Pair("amount",ValueFromAmount(amount))); - result.push_back(Pair("hex",rawtx)); + if ( (inputsum= AddCClibInputs(cp,mtx,sudokupk,amount+2*txfee,16)) >= amount+2*txfee ) + { + mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,sudokupk)); + mtx.vout.push_back(MakeCC1vout(cp->evalcode,inputsum - 2*txfee,pk)); + rawtx = FinalizeCCTx(0,cp,mtx,sudokupk,txfee,sudoku_genopret(unsolved)); + result.push_back(Pair("hex",rawtx)); + } else result.push_back(Pair("error","not enough SUDOKU funds")); return(result); } From 89a9ce3b121332c92c0826dce8d51cea859bb675 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 01:29:19 -1100 Subject: [PATCH 0108/1145] +print --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 8a7d054f7..7d5a26e42 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -257,9 +257,9 @@ int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK { txid = it->first.txhash; vout = (int32_t)it->first.index; + char str[65]; fprintf(stderr,"check %s/v%d %.8f`\n",uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( it->second.satoshis < threshold ) continue; - //char str[65]; fprintf(stderr,"check %s/v%d %.8f`\n",uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); // no need to prevent dup if ( GetTransaction(txid,vintx,hashBlock,false) != 0 ) { From 21ee88562ce2b4fe2c8d7fff9197f83a070d1bdf Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 01:39:10 -1100 Subject: [PATCH 0109/1145] CCbalance --- src/cc/cclib.cpp | 2 +- src/wallet/rpcwallet.cpp | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 7d5a26e42..83afb86ef 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -257,7 +257,7 @@ int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK { txid = it->first.txhash; vout = (int32_t)it->first.index; - char str[65]; fprintf(stderr,"check %s/v%d %.8f`\n",uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); + char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( it->second.satoshis < threshold ) continue; // no need to prevent dup diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 970dfa3cf..fc1839de2 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5220,6 +5220,7 @@ UniValue CCaddress(struct CCcontract_info *cp,char *name,std::vectorunspendableCCaddr)); + result.push_back(Pair("CCbalance",ValueFromAmount(CCaddress_balance(cp->unspendableCCaddr)))); sprintf(str,"%smarker",name); result.push_back(Pair(str,cp->normaladdr)); result.push_back(Pair("GatewaysPubkey","03ea9c062b9652d8eff34879b504eda0717895d27597aaeb60347d65eed96ccb40")); @@ -5234,7 +5235,10 @@ UniValue CCaddress(struct CCcontract_info *cp,char *name,std::vector Date: Tue, 29 Jan 2019 01:45:41 -1100 Subject: [PATCH 0110/1145] Sudokupk signing --- src/cc/sudoku.cpp | 9 +++++++-- src/wallet/rpcwallet.cpp | 3 +++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index adba75920..336edffcd 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -502,7 +502,7 @@ CScript sudoku_genopret(uint8_t unsolved[9][9]) UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); CPubKey sudokupk,pk; uint8_t privkey[32],unsolved[9][9],pub33[33]; uint32_t srandi; uint256 hash; char coinaddr[64]; uint64_t inputsum,amount; std::string rawtx; + UniValue result(UniValue::VOBJ); CPubKey sudokupk,pk; uint8_t privkey[32],unsolved[9][9],pub33[33]; uint32_t srandi; uint256 hash; char coinaddr[64]; uint64_t inputsum,amount,change=0; std::string rawtx; if ( params != 0 ) { printf("params.(%s)\n",jprint(params,0)); @@ -523,7 +523,12 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( (inputsum= AddCClibInputs(cp,mtx,sudokupk,amount+2*txfee,16)) >= amount+2*txfee ) { mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,sudokupk)); - mtx.vout.push_back(MakeCC1vout(cp->evalcode,inputsum - 2*txfee,pk)); + mtx.vout.push_back(MakeCC1vout(cp->evalcode,amount,pk)); + if ( inputsum > amount + 2*txfee ) + change = (inputsum - amount - 2*txfee); + if ( change > txfee ) + mtx.vout.push_back(MakeCC1vout(cp->evalcode,change,sudokupk)); + CCaddr2set(cp,cp->evalcode,sudokupk,cp->CCpriv,cp->CCaddr); rawtx = FinalizeCCTx(0,cp,mtx,sudokupk,txfee,sudoku_genopret(unsolved)); result.push_back(Pair("hex",rawtx)); } else result.push_back(Pair("error","not enough SUDOKU funds")); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index fc1839de2..3409710ad 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5240,7 +5240,10 @@ UniValue CCaddress(struct CCcontract_info *cp,char *name,std::vector Date: Tue, 29 Jan 2019 01:47:34 -1100 Subject: [PATCH 0111/1145] Test --- src/cc/sudoku.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 336edffcd..d460b5fdd 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -522,6 +522,7 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("amount",ValueFromAmount(amount))); if ( (inputsum= AddCClibInputs(cp,mtx,sudokupk,amount+2*txfee,16)) >= amount+2*txfee ) { + printf("inputsum %.8f\n",(double)inputsum/COIN); mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,sudokupk)); mtx.vout.push_back(MakeCC1vout(cp->evalcode,amount,pk)); if ( inputsum > amount + 2*txfee ) From d1389403787889dca59e51500adfcba76183e57c Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 01:50:31 -1100 Subject: [PATCH 0112/1145] Test --- src/cc/cclib.cpp | 2 +- src/cc/sudoku.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 83afb86ef..77b9edcf6 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -257,7 +257,7 @@ int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK { txid = it->first.txhash; vout = (int32_t)it->first.index; - char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); + //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( it->second.satoshis < threshold ) continue; // no need to prevent dup diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index d460b5fdd..38b4e242f 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -529,7 +529,7 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params change = (inputsum - amount - 2*txfee); if ( change > txfee ) mtx.vout.push_back(MakeCC1vout(cp->evalcode,change,sudokupk)); - CCaddr2set(cp,cp->evalcode,sudokupk,cp->CCpriv,cp->CCaddr); + CCaddr2set(cp,cp->evalcode,sudokupk,cp->CCpriv,cp->unspendableCCaddr); rawtx = FinalizeCCTx(0,cp,mtx,sudokupk,txfee,sudoku_genopret(unsolved)); result.push_back(Pair("hex",rawtx)); } else result.push_back(Pair("error","not enough SUDOKU funds")); From 1a7fbca0da6472493cc508085c63b550eeac477f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 01:55:20 -1100 Subject: [PATCH 0113/1145] Test --- src/cc/CCtx.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index a8d832661..25e13df7f 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -177,7 +177,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran { privkey = unspendablepriv; cond = othercond; - //fprintf(stderr,"FinalizeCCTx() matched unspendable CC addr.(%s)\n",unspendable); + fprintf(stderr,"FinalizeCCTx(%d) matched unspendable CC addr.(%s)\n",cp->evalcode,unspendable); } else if (strcmp(destaddr, tokensunspendable) == 0) { From 9de5df85e89e48324e4edc983e36cf28ae8fc20a Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 01:59:32 -1100 Subject: [PATCH 0114/1145] Use mypk --- src/cc/CCtx.cpp | 2 +- src/cc/sudoku.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index 25e13df7f..4fe4d9673 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -73,7 +73,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran unspendablepk = GetUnspendable(cp, unspendablepriv); GetCCaddress(cp, unspendable, unspendablepk); othercond = MakeCCcond1(cp->evalcode, unspendablepk); - +printf("evalcode.%d (%s)\n",cp->evalcode,unspendable); // tokens support: // to spend from dual-eval mypk vout diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 38b4e242f..d97b81b0d 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -530,7 +530,7 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( change > txfee ) mtx.vout.push_back(MakeCC1vout(cp->evalcode,change,sudokupk)); CCaddr2set(cp,cp->evalcode,sudokupk,cp->CCpriv,cp->unspendableCCaddr); - rawtx = FinalizeCCTx(0,cp,mtx,sudokupk,txfee,sudoku_genopret(unsolved)); + rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_genopret(unsolved)); result.push_back(Pair("hex",rawtx)); } else result.push_back(Pair("error","not enough SUDOKU funds")); return(result); From 1aefc8dbff7167374dfeceb3280bde387ea31e4b Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:05:22 -1100 Subject: [PATCH 0115/1145] Default validation for sudoku --- src/cc/CCtx.cpp | 4 ++-- src/cc/cclib.cpp | 4 ++++ src/cc/sudoku.cpp | 7 ++++++- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index 4fe4d9673..5228703ea 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -73,7 +73,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran unspendablepk = GetUnspendable(cp, unspendablepriv); GetCCaddress(cp, unspendable, unspendablepk); othercond = MakeCCcond1(cp->evalcode, unspendablepk); -printf("evalcode.%d (%s)\n",cp->evalcode,unspendable); + //printf("evalcode.%d (%s)\n",cp->evalcode,unspendable); // tokens support: // to spend from dual-eval mypk vout @@ -177,7 +177,7 @@ printf("evalcode.%d (%s)\n",cp->evalcode,unspendable); { privkey = unspendablepriv; cond = othercond; - fprintf(stderr,"FinalizeCCTx(%d) matched unspendable CC addr.(%s)\n",cp->evalcode,unspendable); + //fprintf(stderr,"FinalizeCCTx(%d) matched unspendable CC addr.(%s)\n",cp->evalcode,unspendable); } else if (strcmp(destaddr, tokensunspendable) == 0) { diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 77b9edcf6..112fba5de 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -51,6 +51,8 @@ CClib_methods[] = }; std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *params); + +bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); @@ -190,6 +192,8 @@ bool CClib_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { int32_t numvins,numvouts,preventCCvins,preventCCvouts,i,numblocks; bool retval; uint256 txid; uint8_t hash[32]; char str[65],destaddr[64]; std::vector > txids; + if ( cp->evalcode != EVAL_FAUCET2 ) + return(sudoku_validate(cp,height,eval,tx)); numvins = tx.vin.size(); numvouts = tx.vout.size(); preventCCvins = preventCCvouts = -1; diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index d97b81b0d..ccd5a913f 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -522,7 +522,7 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("amount",ValueFromAmount(amount))); if ( (inputsum= AddCClibInputs(cp,mtx,sudokupk,amount+2*txfee,16)) >= amount+2*txfee ) { - printf("inputsum %.8f\n",(double)inputsum/COIN); + //printf("inputsum %.8f\n",(double)inputsum/COIN); mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,sudokupk)); mtx.vout.push_back(MakeCC1vout(cp->evalcode,amount,pk)); if ( inputsum > amount + 2*txfee ) @@ -558,3 +558,8 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } + +bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) +{ + return(true); +} From 66dc70b22804cb518ae049e6f2073e01cbc91585 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:10:38 -1100 Subject: [PATCH 0116/1145] Print --- src/cc/sudoku.cpp | 2 ++ src/wallet/rpcwallet.cpp | 3 +++ 2 files changed, 5 insertions(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index ccd5a913f..097a01d86 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -477,6 +477,8 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) //////////////////////// start of CClib interface // ./komodod -ac_name=SUDOKU -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -gen -genproclimit=1 -ac_cclib=sudoku -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60000 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & +// cclib "gen" 17 "1" +// 5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432 UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 3409710ad..e09ddc89f 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5389,7 +5389,10 @@ UniValue cclib(const UniValue& params, bool fHelp) throw runtime_error("evalcode not between EVAL_FIRSTUSER and EVAL_LASTUSER\n"); } if ( params.size() == 2 ) + { jsonparams = cJSON_Parse(params[2].get_str().c_str()); + printf("Parse.(%s) -> %p\n",params[2].get_str().c_str(),jsonparams); + } } cp = CCinit(&C,evalcode); return(CClib(cp,method,jsonparams)); From 220bf38e5de0ca7ee59f3dfcedef70f0124d8c50 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:14:30 -1100 Subject: [PATCH 0117/1145] Print --- src/wallet/rpcwallet.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index e09ddc89f..34ee7ce95 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5380,6 +5380,7 @@ UniValue cclib(const UniValue& params, bool fHelp) if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); method = (char *)params[0].get_str().c_str(); + printf("params.size() %d (%s)\n",(int32_t)params.size(),params[2].get_str().c_str()); if ( params.size() >= 1 ) { evalcode = atoi(params[1].get_str().c_str()); From 542e08db60d4e046df46897bffb722993f404449 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:16:59 -1100 Subject: [PATCH 0118/1145] Test --- src/wallet/rpcwallet.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 34ee7ce95..3104a5006 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5380,8 +5380,7 @@ UniValue cclib(const UniValue& params, bool fHelp) if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); method = (char *)params[0].get_str().c_str(); - printf("params.size() %d (%s)\n",(int32_t)params.size(),params[2].get_str().c_str()); - if ( params.size() >= 1 ) + if ( params.size() >= 2 ) { evalcode = atoi(params[1].get_str().c_str()); if ( evalcode < EVAL_FIRSTUSER || evalcode > EVAL_LASTUSER ) @@ -5389,7 +5388,7 @@ UniValue cclib(const UniValue& params, bool fHelp) printf("evalcode.%d vs (%d, %d)\n",evalcode,EVAL_FIRSTUSER,EVAL_LASTUSER); throw runtime_error("evalcode not between EVAL_FIRSTUSER and EVAL_LASTUSER\n"); } - if ( params.size() == 2 ) + if ( params.size() == 3 ) { jsonparams = cJSON_Parse(params[2].get_str().c_str()); printf("Parse.(%s) -> %p\n",params[2].get_str().c_str(),jsonparams); From 3f5b87742be1a0496f53fd590d0ea791d0afae67 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:21:11 -1100 Subject: [PATCH 0119/1145] Print --- src/cc/sudoku.cpp | 9 +++++++++ src/wallet/rpcwallet.cpp | 4 ++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 097a01d86..590cc9c9b 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -484,7 +484,16 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params { UniValue result(UniValue::VOBJ); if ( params != 0 ) + { printf("params.(%s)\n",jprint(params,0)); + int32_t i,n = cJSON_GetArraySize(); + for (i=0; i EVAL_LASTUSER ) { - printf("evalcode.%d vs (%d, %d)\n",evalcode,EVAL_FIRSTUSER,EVAL_LASTUSER); + //printf("evalcode.%d vs (%d, %d)\n",evalcode,EVAL_FIRSTUSER,EVAL_LASTUSER); throw runtime_error("evalcode not between EVAL_FIRSTUSER and EVAL_LASTUSER\n"); } if ( params.size() == 3 ) { jsonparams = cJSON_Parse(params[2].get_str().c_str()); - printf("Parse.(%s) -> %p\n",params[2].get_str().c_str(),jsonparams); + //printf("Parse.(%s) -> %p\n",params[2].get_str().c_str(),jsonparams); } } cp = CCinit(&C,evalcode); From 7b2612734453d4e526ecbc032d81f4bc076c7247 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:22:11 -1100 Subject: [PATCH 0120/1145] +print --- src/cc/sudoku.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 590cc9c9b..26548ea0e 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -479,6 +479,7 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) // ./komodod -ac_name=SUDOKU -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -gen -genproclimit=1 -ac_cclib=sudoku -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60000 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & // cclib "gen" 17 "1" // 5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432 +// cclib "txidinfo" 17 \"[5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432]\" UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { @@ -486,7 +487,7 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( params != 0 ) { printf("params.(%s)\n",jprint(params,0)); - int32_t i,n = cJSON_GetArraySize(); + cJSON *item; int32_t i,n = cJSON_GetArraySize(params); for (i=0; i Date: Tue, 29 Jan 2019 02:26:19 -1100 Subject: [PATCH 0121/1145] Prints --- src/cc/sudoku.cpp | 2 +- src/wallet/rpcwallet.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 26548ea0e..95cb05684 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -486,7 +486,7 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue result(UniValue::VOBJ); if ( params != 0 ) { - printf("params.(%s)\n",jprint(params,0)); + printf("%p params.(%s) is array.%d\n",params,jprint(params,0),is_cJSON_Array(params)); cJSON *item; int32_t i,n = cJSON_GetArraySize(params); for (i=0; i %p\n",params[2].get_str().c_str(),jsonparams); + printf("Parse.(%s) -> %p\n",params[2].get_str().c_str(),jsonparams); } } cp = CCinit(&C,evalcode); From caca5ec036fa5d370203ce6f9296995c3007e593 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:27:45 -1100 Subject: [PATCH 0122/1145] Test --- src/cc/sudoku.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 95cb05684..20d18018c 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -395,6 +395,7 @@ int sudoku(uint8_t solved9[LINE][LINE],uint8_t unsolved9[LINE][LINE],uint32_t sr * * ******************************************************************************/ +#include "cJSON.h" #define SUDOKU_NINETH 387420489 void sudoku_rowdisp(uint32_t x) From 44cce95c52f89ee88c0af7fac6c178c23959aaa4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:30:05 -1100 Subject: [PATCH 0123/1145] Test --- src/cc/sudoku.cpp | 39 +++++++++++++++++++-------------------- src/wallet/rpcwallet.cpp | 3 ++- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 20d18018c..b60373e23 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -482,26 +482,6 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) // 5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432 // cclib "txidinfo" 17 \"[5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432]\" -UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - if ( params != 0 ) - { - printf("%p params.(%s) is array.%d\n",params,jprint(params,0),is_cJSON_Array(params)); - cJSON *item; int32_t i,n = cJSON_GetArraySize(params); - for (i=0; i data; int32_t i,j; @@ -549,6 +529,25 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params return(result); } +UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + if ( params != 0 ) + { + cJSON *item; int32_t i,n = cJSON_GetArraySize(params); + for (i=0; i %p\n",params[2].get_str().c_str(),jsonparams); + printf("%p params.(%s) is array.%d\n",params,jprint(params,0),is_cJSON_Array(params)); + //printf("Parse.(%s) -> %p\n",params[2].get_str().c_str(),jsonparams); } } cp = CCinit(&C,evalcode); From ccbbb3291c54b88fc8540c20d082b815d4d21b53 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:31:28 -1100 Subject: [PATCH 0124/1145] Test --- src/wallet/rpcwallet.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 39a88c9eb..5cea2f7ac 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5391,7 +5391,8 @@ UniValue cclib(const UniValue& params, bool fHelp) if ( params.size() == 3 ) { jsonparams = cJSON_Parse(params[2].get_str().c_str()); - printf("%p params.(%s) is array.%d\n",params,jprint(params,0),is_cJSON_Array(params)); + if ( jsonparams != 0 ) + printf("%p params.(%s) is array.%d\n",jsonparams,jprint(jsonparams,0),is_cJSON_Array(params)); //printf("Parse.(%s) -> %p\n",params[2].get_str().c_str(),jsonparams); } } From e2a1c43d8a6fc81e9e9e4daff4460a613a770ad1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:33:01 -1100 Subject: [PATCH 0125/1145] Test --- src/cc/includes/cJSON.h | 4 ++-- src/cryptoconditions/src/include/cJSON.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/includes/cJSON.h b/src/cc/includes/cJSON.h index ed8c26b7f..d919a47a9 100755 --- a/src/cc/includes/cJSON.h +++ b/src/cc/includes/cJSON.h @@ -35,8 +35,8 @@ * * ******************************************************************************/ -#ifndef cJSON__h -#define cJSON__h +#ifndef cJSON__ccih +#define cJSON__ccih #include #include diff --git a/src/cryptoconditions/src/include/cJSON.h b/src/cryptoconditions/src/include/cJSON.h index 2a6139680..547dddad5 100644 --- a/src/cryptoconditions/src/include/cJSON.h +++ b/src/cryptoconditions/src/include/cJSON.h @@ -35,8 +35,8 @@ * * ******************************************************************************/ -#ifndef cJSON__h -#define cJSON__h +#ifndef cJSON__cch +#define cJSON__cch #ifdef __cplusplus extern "C" From 4123105b95e49de239884f9f071799091793d01b Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:34:19 -1100 Subject: [PATCH 0126/1145] Test --- src/wallet/rpcwallet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 5cea2f7ac..6a6f64237 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5392,7 +5392,7 @@ UniValue cclib(const UniValue& params, bool fHelp) { jsonparams = cJSON_Parse(params[2].get_str().c_str()); if ( jsonparams != 0 ) - printf("%p params.(%s) is array.%d\n",jsonparams,jprint(jsonparams,0),is_cJSON_Array(params)); + printf("%p params.(%s)\n",jsonparams,jprint(jsonparams,0)); //printf("Parse.(%s) -> %p\n",params[2].get_str().c_str(),jsonparams); } } From af6030a98b5d88e360ad581b3fbec23902e2ecd3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:38:12 -1100 Subject: [PATCH 0127/1145] Test --- src/cc/cclib.cpp | 2 ++ src/cc/sudoku.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 112fba5de..614fb8567 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -63,6 +63,7 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) UniValue result(UniValue::VOBJ); uint64_t txfee = 10000; if ( cp->evalcode == EVAL_SUDOKU ) { + printf("CClib_method params.%p\n",params); if ( strcmp(method,"txidinfo") == 0 ) return(sudoku_txidinfo(txfee,cp,params)); else if ( strcmp(method,"gen") == 0 ) @@ -119,6 +120,7 @@ UniValue CClib_info(struct CCcontract_info *cp) UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params) { UniValue result(UniValue::VOBJ); int32_t i; std::string rawtx; + printf("CClib params.%p\n",params); for (i=0; ievalcode == CClib_methods[i].evalcode && strcmp(method,CClib_methods[i].method) == 0 ) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index b60373e23..fdc70211a 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -498,7 +498,7 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue result(UniValue::VOBJ); CPubKey sudokupk,pk; uint8_t privkey[32],unsolved[9][9],pub33[33]; uint32_t srandi; uint256 hash; char coinaddr[64]; uint64_t inputsum,amount,change=0; std::string rawtx; if ( params != 0 ) { - printf("params.(%s)\n",jprint(params,0)); + printf("%p params.(%s)\n",params,jprint(params,0)); amount = jdouble(jitem(params,0),0) * COIN + 0.0000000049; } else amount = COIN; result.push_back(Pair("result","success")); From a4beca11a346d22b90fb12295218eceaba351b81 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:39:57 -1100 Subject: [PATCH 0128/1145] Test --- src/cc/sudoku.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index fdc70211a..a820f2231 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -534,6 +534,7 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue result(UniValue::VOBJ); if ( params != 0 ) { + printf("%p params.(%s)\n",params,jprint(params,0)); cJSON *item; int32_t i,n = cJSON_GetArraySize(params); for (i=0; i Date: Tue, 29 Jan 2019 02:44:02 -1100 Subject: [PATCH 0129/1145] Test --- src/cc/sudoku.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index a820f2231..a44b2d329 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -534,14 +534,20 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue result(UniValue::VOBJ); if ( params != 0 ) { - printf("%p params.(%s)\n",params,jprint(params,0)); - cJSON *item; int32_t i,n = cJSON_GetArraySize(params); - for (i=0; i Date: Tue, 29 Jan 2019 02:50:02 -1100 Subject: [PATCH 0130/1145] txid: --- src/cc/cclib.cpp | 4 ++-- src/cc/sudoku.cpp | 17 +++-------------- src/wallet/rpcwallet.cpp | 3 --- 3 files changed, 5 insertions(+), 19 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 614fb8567..c1c3d9f24 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -63,7 +63,7 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) UniValue result(UniValue::VOBJ); uint64_t txfee = 10000; if ( cp->evalcode == EVAL_SUDOKU ) { - printf("CClib_method params.%p\n",params); + //printf("CClib_method params.%p\n",params); if ( strcmp(method,"txidinfo") == 0 ) return(sudoku_txidinfo(txfee,cp,params)); else if ( strcmp(method,"gen") == 0 ) @@ -120,7 +120,7 @@ UniValue CClib_info(struct CCcontract_info *cp) UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params) { UniValue result(UniValue::VOBJ); int32_t i; std::string rawtx; - printf("CClib params.%p\n",params); + //printf("CClib params.%p\n",params); for (i=0; ievalcode == CClib_methods[i].evalcode && strcmp(method,CClib_methods[i].method) == 0 ) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index a44b2d329..b2ca38321 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -534,20 +534,9 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue result(UniValue::VOBJ); if ( params != 0 ) { - char *jsonstr; cJSON *item; int32_t i,n; - jsonstr = jprint(params,0); - params = cJSON_Parse(jsonstr); - if ( params != 0 ) - { - n = cJSON_GetArraySize(params); - printf("%p params.(%s) <- (%s)\n",params,jprint(params,0),jsonstr); - for (i=0; i %p\n",params[2].get_str().c_str(),jsonparams); } } cp = CCinit(&C,evalcode); From 4fafbdeeadecc175395dacf4ab428fd1d8ba4768 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:52:05 -1100 Subject: [PATCH 0131/1145] Uint256 --- src/cc/sudoku.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index b2ca38321..e77455352 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -480,7 +480,7 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) // ./komodod -ac_name=SUDOKU -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -gen -genproclimit=1 -ac_cclib=sudoku -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60000 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & // cclib "gen" 17 "1" // 5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432 -// cclib "txidinfo" 17 \"[5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432]\" +// cclib "txidinfo" 17 \"{"txid":"5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432"}\" CScript sudoku_genopret(uint8_t unsolved[9][9]) { @@ -534,9 +534,10 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue result(UniValue::VOBJ); if ( params != 0 ) { - char str[65]; bits256 txid; - txid = jbits256(params,"txid"); - printf("txid.(%s)\n",bits256_str(str,txid)); + char str[65]; bits256 _txid; uint256 txid; + _txid = jbits256(params,(char *)"txid"); + memcpy(&txid,*_txid,sizeof(txid)); + printf("txid.(%s)\n",txid.GetHex().c_str()); } result.push_back(Pair("result","success")); result.push_back(Pair("name","sudoku")); From d1e3f85f54832e66d565ec8df17f94ad9c6cab1e Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:52:39 -1100 Subject: [PATCH 0132/1145] Test --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index e77455352..61b1eb389 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -536,7 +536,7 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params { char str[65]; bits256 _txid; uint256 txid; _txid = jbits256(params,(char *)"txid"); - memcpy(&txid,*_txid,sizeof(txid)); + memcpy(&txid,&_txid,sizeof(txid)); printf("txid.(%s)\n",txid.GetHex().c_str()); } result.push_back(Pair("result","success")); From 26ca2c628bf6ba309b86a5f10287575f1e0ff550 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:55:04 -1100 Subject: [PATCH 0133/1145] Test --- src/cc/sudoku.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 61b1eb389..deee89023 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -534,10 +534,13 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue result(UniValue::VOBJ); if ( params != 0 ) { - char str[65]; bits256 _txid; uint256 txid; - _txid = jbits256(params,(char *)"txid"); - memcpy(&txid,&_txid,sizeof(txid)); - printf("txid.(%s)\n",txid.GetHex().c_str()); + char str[65],*txidstr; uint256 txid; + printf("params -> (%s)\n",jprint(params,0)); + if ( (txidstr= jstr(params,(char *)"txid")) != 0 ) + { + decode_hex((uint8_t *)&txid,32,txidstr); + printf("txid.(%s) <- %s\n",txid.GetHex().c_str(),txidstr); + } } result.push_back(Pair("result","success")); result.push_back(Pair("name","sudoku")); From 124ad45bc86e46394db88e020992d1fa684cf9b8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 02:59:27 -1100 Subject: [PATCH 0134/1145] Test --- src/cc/sudoku.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index deee89023..8c30ad462 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -480,7 +480,7 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) // ./komodod -ac_name=SUDOKU -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -gen -genproclimit=1 -ac_cclib=sudoku -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60000 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & // cclib "gen" 17 "1" // 5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432 -// cclib "txidinfo" 17 \"{"txid":"5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432"}\" +// cclib "txidinfo" 17 \"5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432\" CScript sudoku_genopret(uint8_t unsolved[9][9]) { @@ -535,9 +535,9 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( params != 0 ) { char str[65],*txidstr; uint256 txid; - printf("params -> (%s)\n",jprint(params,0)); - if ( (txidstr= jstr(params,(char *)"txid")) != 0 ) + if ( (txidstr= jprint(params,0)) != 0 ) { + printf("params -> (%s)\n",txidstr); decode_hex((uint8_t *)&txid,32,txidstr); printf("txid.(%s) <- %s\n",txid.GetHex().c_str(),txidstr); } From 08ee5412fae588bdd768204bf6dbced9aa957277 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 03:01:40 -1100 Subject: [PATCH 0135/1145] Test --- src/cc/sudoku.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 8c30ad462..af41ac9b0 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -537,7 +537,9 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params char str[65],*txidstr; uint256 txid; if ( (txidstr= jprint(params,0)) != 0 ) { - printf("params -> (%s)\n",txidstr); + if ( txidstr[0] == '"' ) + txidstr++; + //printf("params -> (%s)\n",txidstr); decode_hex((uint8_t *)&txid,32,txidstr); printf("txid.(%s) <- %s\n",txid.GetHex().c_str(),txidstr); } From 70fb39618932912de5b4b17460ead72fdde71736 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 03:04:20 -1100 Subject: [PATCH 0136/1145] Test --- src/cc/sudoku.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index af41ac9b0..34d3201c4 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -537,8 +537,11 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params char str[65],*txidstr; uint256 txid; if ( (txidstr= jprint(params,0)) != 0 ) { - if ( txidstr[0] == '"' ) + if ( txidstr[0] == '"' && txidstr[strlen(txidstr)-1] == '"' ) + { + txidstr[strlen(txidstr)-1] = 0; txidstr++; + } //printf("params -> (%s)\n",txidstr); decode_hex((uint8_t *)&txid,32,txidstr); printf("txid.(%s) <- %s\n",txid.GetHex().c_str(),txidstr); From b4dda82a701732e39815f42e74fe9849ed3dcdf7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 03:06:07 -1100 Subject: [PATCH 0137/1145] Revtxid --- src/cc/sudoku.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 34d3201c4..a3f6ce525 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -544,6 +544,7 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params } //printf("params -> (%s)\n",txidstr); decode_hex((uint8_t *)&txid,32,txidstr); + txid = revuint256(txid); printf("txid.(%s) <- %s\n",txid.GetHex().c_str(),txidstr); } } From a9dcf78e331f2486d175f62d6deb07fec96ee641 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 03:17:56 -1100 Subject: [PATCH 0138/1145] sudoku_txidinfo --- src/cc/CCcustom.cpp | 2 +- src/cc/sudoku.cpp | 48 +++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/src/cc/CCcustom.cpp b/src/cc/CCcustom.cpp index 0b150e6e0..8e878d37d 100644 --- a/src/cc/CCcustom.cpp +++ b/src/cc/CCcustom.cpp @@ -281,7 +281,7 @@ int32_t CClib_initcp(struct CCcontract_info *cp,uint8_t evalcode) sprintf(&cp->CChexstr[i*2],"%02x",pub33[i]); cp->CChexstr[i*2] = 0; GetCCaddress(cp,cp->unspendableCCaddr,pk); - printf("evalcode.%d initialized\n",evalcode); + //printf("evalcode.%d initialized\n",evalcode); return(0); } } diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index a3f6ce525..cf382a518 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -492,6 +492,23 @@ CScript sudoku_genopret(uint8_t unsolved[9][9]) return(opret); } +uint8_t sudoku_genopreturndecode(char *unsolved,CScript scriptPubKey) +{ + std::vector vopret; uint8_t *script,e,f; std::vector data; int32_t i; + GetOpReturnData(scriptPubKey,vopret); + script = (uint8_t *)vopret.data(); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> data) != 0 && e == EVAL_SUDOKU && f == 'G' ) + { + if ( data.size() == 81 ) + { + for (i=0; i<81; i++) + unsolved[i] = data[i] == 0 ? '-' : '0' + data[i]; + unsolved[i] = 0; + return(f); + } + } + return(0);} + UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); @@ -531,10 +548,10 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); + UniValue result(UniValue::VOBJ); int32_t numvouts; char str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; char unsolved[82]; if ( params != 0 ) { - char str[65],*txidstr; uint256 txid; + result.push_back(Pair("result","success")); if ( (txidstr= jprint(params,0)) != 0 ) { if ( txidstr[0] == '"' && txidstr[strlen(txidstr)-1] == '"' ) @@ -545,10 +562,33 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params //printf("params -> (%s)\n",txidstr); decode_hex((uint8_t *)&txid,32,txidstr); txid = revuint256(txid); - printf("txid.(%s) <- %s\n",txid.GetHex().c_str(),txidstr); + result.push_back(Pair("txid",txid.GetHex())); + if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + { + if ( sudoku_genopreturndecode(unsolved,tx.vout[numvouts-1].scriptPubKey) == 'G' ) + { + result.push_back(Pair("result","success")); + result.push_back(Pair("amount",ValueFromAmount(tx.vout[1].nValue))); + result.push_back(Pair("unsolved",unsolved)); + } + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","couldnt extract sudoku_generate opreturn")); + } + } + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","couldnt find txid")); + } } } - result.push_back(Pair("result","success")); + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","missing txid in params")); + } result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","txidinfo")); return(result); From 7217c87e60a8e7ae0e479f766b79e099585157bd Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 03:25:46 -1100 Subject: [PATCH 0139/1145] sudoku_pending --- src/cc/sudoku.cpp | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index cf382a518..fdeac91fa 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -481,6 +481,15 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) // cclib "gen" 17 "1" // 5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432 // cclib "txidinfo" 17 \"5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432\" +/*{ + "result": "success", + "txid": "5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432", + "result": "success", + "amount": 1.00000000, + "unsolved": "46-8---15-75-61-3----4----8-1--75-----3--24----2-----6-4----------73----------36-", + "name": "sudoku", + "method": "txidinfo" +}*/ CScript sudoku_genopret(uint8_t unsolved[9][9]) { @@ -607,12 +616,31 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - if ( params != 0 ) - printf("params.(%s)\n",jprint(params,0)); + UniValue result(UniValue::VOBJ),a(UniValue::VARRAY); + char coinaddr[64],unsolved[82]; int64_t nValue; uint256 txid,hashBlock; CTransaction tx; int32_t vout,numvouts; + std::vector > unspentOutputs; + GetCCaddress(cp,coinaddr,pk); + SetCCunspents(unspentOutputs,coinaddr); + for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) + { + txid = it->first.txhash; + vout = (int32_t)it->first.index; + //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); + if ( it->second.satoshis != txfee || vout != 0 ) + continue; + if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + { + if ( (nValue= IsCClibvout(cp,tx,vout)) == txfee && myIsutxo_spentinmempool(txid,vout) == 0 ) + { + if ( sudoku_genopreturndecode(unsolved,tx.vout[numvouts-1].scriptPubKey) == 'G' ) + a.push_back(txid); + } + } + } result.push_back(Pair("result","success")); result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","pending")); + result.push_back(Pair("pending",a)); return(result); } From b5aa0536c2f8d314101158444b7fa4375ffadcba Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 03:27:22 -1100 Subject: [PATCH 0140/1145] syntax --- src/cc/sudoku.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index fdeac91fa..268281eb7 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -616,10 +616,11 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARRAY); - char coinaddr[64],unsolved[82]; int64_t nValue; uint256 txid,hashBlock; CTransaction tx; int32_t vout,numvouts; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); + char coinaddr[64],unsolved[82]; int64_t nValue; uint256 txid,hashBlock; CTransaction tx; int32_t vout,numvouts; CPubKey sudokupk; std::vector > unspentOutputs; - GetCCaddress(cp,coinaddr,pk); + sudokupk = GetUnspendable(cp,0); + GetCCaddress(cp,coinaddr,sudokupk); SetCCunspents(unspentOutputs,coinaddr); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { From b60a712efbefda09e4657a230c18b8bda8aa81d8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 03:28:05 -1100 Subject: [PATCH 0141/1145] GetHex() --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 268281eb7..9fa714665 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -634,7 +634,7 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( (nValue= IsCClibvout(cp,tx,vout)) == txfee && myIsutxo_spentinmempool(txid,vout) == 0 ) { if ( sudoku_genopreturndecode(unsolved,tx.vout[numvouts-1].scriptPubKey) == 'G' ) - a.push_back(txid); + a.push_back(txid.GetHex()); } } } From 43b78b093b946ddb9b30a97788ab5c5c6435e138 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 04:41:00 -1100 Subject: [PATCH 0142/1145] Jsonstr --- src/cc/sudoku.cpp | 59 +++++++++++++++++++++++++++++++------------- src/komodo_globals.h | 2 +- src/komodo_utils.h | 2 +- 3 files changed, 44 insertions(+), 19 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 9fa714665..d0e5ad543 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -478,10 +478,12 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) //////////////////////// start of CClib interface // ./komodod -ac_name=SUDOKU -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -gen -genproclimit=1 -ac_cclib=sudoku -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60000 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & -// cclib "gen" 17 "1" -// 5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432 -// cclib "txidinfo" 17 \"5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432\" -/*{ +/* cclib "gen" 17 "1" + 5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432 +*/ + +/* cclib "txidinfo" 17 \"5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432\" +{ "result": "success", "txid": "5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432", "result": "success", @@ -491,6 +493,16 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) "method": "txidinfo" }*/ +/* cclib "pending" 17 +{ + "result": "success", + "name": "sudoku", + "method": "pending", + "pending": [ + "5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432" + ] +}*/ + CScript sudoku_genopret(uint8_t unsolved[9][9]) { CScript opret; uint8_t evalcode = EVAL_SUDOKU; std::vector data; int32_t i,j; @@ -516,7 +528,8 @@ uint8_t sudoku_genopreturndecode(char *unsolved,CScript scriptPubKey) return(f); } } - return(0);} + return(0); +} UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { @@ -548,7 +561,6 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params change = (inputsum - amount - 2*txfee); if ( change > txfee ) mtx.vout.push_back(MakeCC1vout(cp->evalcode,change,sudokupk)); - CCaddr2set(cp,cp->evalcode,sudokupk,cp->CCpriv,cp->unspendableCCaddr); rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_genopret(unsolved)); result.push_back(Pair("hex",rawtx)); } else result.push_back(Pair("error","not enough SUDOKU funds")); @@ -603,17 +615,6 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params return(result); } -UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - if ( params != 0 ) - printf("params.(%s)\n",jprint(params,0)); - result.push_back(Pair("result","success")); - result.push_back(Pair("name","sudoku")); - result.push_back(Pair("method","solution")); - return(result); -} - UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ),a(UniValue::VARR); @@ -645,6 +646,30 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } +UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); char *jsonstr; + if ( params != 0 ) + { + if ( (jsonstr= jprint(params,0)) != 0 ) + { + if ( jsonstr[0] == '"' && jsonstr[strlen(jsonstr)-1] == '"' ) + { + jsonstr[strlen(jsonstr)-1] = 0; + jsonstr++; + } + params = cJSON_Parse(jsonstr); + free(jsonstr); + } + if ( params != 0 ) + printf("params.(%s)\n",jprint(params,0)); + } + CCaddr2set(cp,cp->evalcode,pk,priv32,coinaddr); + result.push_back(Pair("result","success")); + result.push_back(Pair("name","sudoku")); + result.push_back(Pair("method","solution")); + return(result); +} bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 79b56cbbb..c85c68451 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -173,7 +173,7 @@ int64_t komodo_current_supply(uint32_t nHeight) else if ( decay == SATOSHIDEN ) { int64_t lowestSubsidy, subsidyDifference, stepDifference, stepTriangle; - int64_t denominator, modulo; + int64_t denominator, modulo=1; int32_t sign = 1; if ( j == ASSETCHAINS_LASTERA ) diff --git a/src/komodo_utils.h b/src/komodo_utils.h index bcd95e698..862f0c6b0 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1047,7 +1047,7 @@ uint64_t komodo_block_prg(uint32_t nHeight) { int i; uint8_t hashSrc[8]; - uint64_t result, hashSrc64 = (uint64_t)ASSETCHAINS_MAGIC << 32 + nHeight; + uint64_t result=0, hashSrc64 = (uint64_t)ASSETCHAINS_MAGIC << 32 + nHeight; bits256 hashResult; for ( i = 0; i < sizeof(hashSrc); i++ ) From 2781b296ef3b7af07b657efc649c95075df78bce Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 04:42:14 -1100 Subject: [PATCH 0143/1145] Syntax --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index d0e5ad543..e51703456 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -648,7 +648,7 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); char *jsonstr; + UniValue result(UniValue::VOBJ); char *jsonstr,coinaddr[64]; CPubKey pk; uint8_t priv32[32]; if ( params != 0 ) { if ( (jsonstr= jprint(params,0)) != 0 ) From 10b462a7db4b5ef2f447fc9f13c4bcd3a715b946 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 04:43:29 -1100 Subject: [PATCH 0144/1145] Test --- src/cc/sudoku.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index e51703456..698242aea 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -659,7 +659,6 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params jsonstr++; } params = cJSON_Parse(jsonstr); - free(jsonstr); } if ( params != 0 ) printf("params.(%s)\n",jprint(params,0)); From 145a386aab6358727969e4d632b683be23752585 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 04:45:08 -1100 Subject: [PATCH 0145/1145] Test --- src/cc/sudoku.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 698242aea..76b148836 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -662,6 +662,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params } if ( params != 0 ) printf("params.(%s)\n",jprint(params,0)); + else printf("couldnt parse.(%s)\n",jsonstr); } CCaddr2set(cp,cp->evalcode,pk,priv32,coinaddr); result.push_back(Pair("result","success")); From 3c43c027a8de82d51ad5981d82141cc3941d5db9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 04:54:58 -1100 Subject: [PATCH 0146/1145] %22 conversion --- src/cc/sudoku.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 76b148836..ba5ed156c 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -648,7 +648,7 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); char *jsonstr,coinaddr[64]; CPubKey pk; uint8_t priv32[32]; + UniValue result(UniValue::VOBJ); int32_t i,j; char *jsonstr,*newstr,coinaddr[64]; CPubKey pk; uint8_t priv32[32]; if ( params != 0 ) { if ( (jsonstr= jprint(params,0)) != 0 ) @@ -658,7 +658,17 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params jsonstr[strlen(jsonstr)-1] = 0; jsonstr++; } - params = cJSON_Parse(jsonstr); + newstr = malloc(strlen(jsonstr)+1); + for (i=j=0; jsonstr[i]!=0; i++) + { + if ( jsonstr[i] == '%' && jsonstr[i+1] == '2' && jsonstr[i+2] == '2' ) + { + newstr[j++] = '"'; + i += 2; + } else newstr[j++] = jsonstr[i]; + } + newstr[j] = 0; + params = cJSON_Parse(newstr); } if ( params != 0 ) printf("params.(%s)\n",jprint(params,0)); From e2028c9616d04f365b874e12775f1edd3ad9454d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 04:56:44 -1100 Subject: [PATCH 0147/1145] (Char *) --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index ba5ed156c..95a2269f5 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -658,7 +658,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params jsonstr[strlen(jsonstr)-1] = 0; jsonstr++; } - newstr = malloc(strlen(jsonstr)+1); + newstr = (char *)malloc(strlen(jsonstr)+1); for (i=j=0; jsonstr[i]!=0; i++) { if ( jsonstr[i] == '%' && jsonstr[i+1] == '2' && jsonstr[i+2] == '2' ) From 127261626619af84296f02b0e898d5da74fe06b2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 05:22:17 -1100 Subject: [PATCH 0148/1145] sudoku_solution --- src/cc/sudoku.cpp | 72 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 64 insertions(+), 8 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 95a2269f5..35e947996 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -503,6 +503,10 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) ] }*/ +/* + cclib "solution" 17 \"[%22469823715875961234231457698914675823653182479782394156346219587528736941197548362%22,1548777525,1548777526,...]\" + */ + CScript sudoku_genopret(uint8_t unsolved[9][9]) { CScript opret; uint8_t evalcode = EVAL_SUDOKU; std::vector data; int32_t i,j; @@ -513,6 +517,13 @@ CScript sudoku_genopret(uint8_t unsolved[9][9]) return(opret); } +CScript sudoku_solutionopret(char *solution,uint32_t timestamps[81]) +{ + CScript opret; uint8_t evalcode = EVAL_SUDOKU; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'S' << solution << timestamps); + return(opret); +} + uint8_t sudoku_genopreturndecode(char *unsolved,CScript scriptPubKey) { std::vector vopret; uint8_t *script,e,f; std::vector data; int32_t i; @@ -562,7 +573,9 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( change > txfee ) mtx.vout.push_back(MakeCC1vout(cp->evalcode,change,sudokupk)); rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_genopret(unsolved)); - result.push_back(Pair("hex",rawtx)); + if ( rawtx.size() > 0 ) + result.push_back(Pair("hex",rawtx)); + else result.push_back(Pair("error","couldnt finalize CCtx")); } else result.push_back(Pair("error","not enough SUDOKU funds")); return(result); } @@ -648,7 +661,12 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); int32_t i,j; char *jsonstr,*newstr,coinaddr[64]; CPubKey pk; uint8_t priv32[32]; + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + UniValue result(UniValue::VOBJ); int32_t i,j,ind,n; char *jsonstr,*newstr,coinaddr[64],CCaddr[64],*solution=0; CPubKey pk,mypk; uint8_t vals9[9][9],priv32[32],pubk33[33]; uint32_t timestamps[81]; uint64_t balance,inputsum; std::string rawhex; + mypk = pubkey2pk(Mypubkey()); + memset(timestamps,0,sizeof(timestamps)); + result.push_back(Pair("name","sudoku")); + result.push_back(Pair("method","solution")); if ( params != 0 ) { if ( (jsonstr= jprint(params,0)) != 0 ) @@ -669,15 +687,53 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params } newstr[j] = 0; params = cJSON_Parse(newstr); - } + } else params = 0; if ( params != 0 ) + { + if ( (n= cJSON_GetArraySize(params)) > 2 && n < (sizeof(timestamps)/sizeof(*timestamps))+1 ) + { + for (i=1; i= balance ) + { + mtx.vout.push_back(CTxOut(balance-txfee,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + CCaddr2set(cp,cp->evalcode,pk,priv32,CCaddr); + rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_solutionopret(solution,timestamps)); + } + } + } + result.push_back(Pair("result","success")); + if ( rawtx.size() > 0 ) + result.push_back(Pair("hex",rawtx)); + else result.push_back(Pair("error","couldnt finalize CCtx")); printf("params.(%s)\n",jprint(params,0)); - else printf("couldnt parse.(%s)\n",jsonstr); + return(result); + } + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","couldnt parse parameters")); + result.push_back(Pair("parameters",newstr)); + return(result); + } } - CCaddr2set(cp,cp->evalcode,pk,priv32,coinaddr); - result.push_back(Pair("result","success")); - result.push_back(Pair("name","sudoku")); - result.push_back(Pair("method","solution")); + result.push_back(Pair("result","error")); + result.push_back(Pair("error","missing parameters")); return(result); } From 28973e71c4e8d02a021bcf93870e4e81c9083493 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 05:23:09 -1100 Subject: [PATCH 0149/1145] Test --- src/cc/sudoku.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 35e947996..4d9443200 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -662,7 +662,7 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); int32_t i,j,ind,n; char *jsonstr,*newstr,coinaddr[64],CCaddr[64],*solution=0; CPubKey pk,mypk; uint8_t vals9[9][9],priv32[32],pubk33[33]; uint32_t timestamps[81]; uint64_t balance,inputsum; std::string rawhex; + UniValue result(UniValue::VOBJ); int32_t i,j,ind,n; char *jsonstr,*newstr,coinaddr[64],CCaddr[64],*solution=0; CPubKey pk,mypk; uint8_t vals9[9][9],priv32[32],pub33[33]; uint32_t timestamps[81]; uint64_t balance,inputsum; std::string rawtx; mypk = pubkey2pk(Mypubkey()); memset(timestamps,0,sizeof(timestamps)); result.push_back(Pair("name","sudoku")); @@ -711,7 +711,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("amount",ValueFromAmount(balance))); if ( (inputsum= AddCClibInputs(cp,mtx,pk,balance,16)) >= balance ) { - mtx.vout.push_back(CTxOut(balance-txfee,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + mtx.vout.push_back(CTxOut(balance-txfee,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); CCaddr2set(cp,cp->evalcode,pk,priv32,CCaddr); rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_solutionopret(solution,timestamps)); } From 3b5218ccdf23e740019ccfb3b8f8c91837d4d9eb Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 05:25:27 -1100 Subject: [PATCH 0150/1145] Serialize timestamps --- src/cc/sudoku.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 4d9443200..5e5247acd 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -519,8 +519,15 @@ CScript sudoku_genopret(uint8_t unsolved[9][9]) CScript sudoku_solutionopret(char *solution,uint32_t timestamps[81]) { - CScript opret; uint8_t evalcode = EVAL_SUDOKU; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'S' << solution << timestamps); + CScript opret; uint8_t evalcode = EVAL_SUDOKU; std::vector data; int32_t i; + for (i=0; i<81; i++) + { + data.push_back((timestamps[i] >> 24) & 0xff); + data.push_back((timestamps[i] >> 16) & 0xff); + data.push_back((timestamps[i] >> 8) & 0xff); + data.push_back(timestamps[i] & 0xff); + } + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'S' << solution << data); return(opret); } From 17ccb0fc88f621bc0bdcad1e22a74b671c1fe44f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 05:26:17 -1100 Subject: [PATCH 0151/1145] Test --- src/cc/sudoku.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 5e5247acd..f1f0a1e89 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -519,7 +519,7 @@ CScript sudoku_genopret(uint8_t unsolved[9][9]) CScript sudoku_solutionopret(char *solution,uint32_t timestamps[81]) { - CScript opret; uint8_t evalcode = EVAL_SUDOKU; std::vector data; int32_t i; + CScript opret; uint8_t evalcode = EVAL_SUDOKU; std::string str(solution); std::vector data; int32_t i; for (i=0; i<81; i++) { data.push_back((timestamps[i] >> 24) & 0xff); @@ -527,7 +527,7 @@ CScript sudoku_solutionopret(char *solution,uint32_t timestamps[81]) data.push_back((timestamps[i] >> 8) & 0xff); data.push_back(timestamps[i] & 0xff); } - opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'S' << solution << data); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'S' << str << data); return(opret); } From 357d1979a9a0f0153b67cecf563b9ec154b6ed67 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 05:31:49 -1100 Subject: [PATCH 0152/1145] Check privacy --- src/cc/sudoku.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index f1f0a1e89..e71c9df5a 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -708,8 +708,12 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params { for (i=ind=0; i<9; i++) for (j=0; j<9; j++) - vals9[i][j] = solution[ind++]; + vals9[i][j] = solution[ind++] - '0'; sudoku_privkey(priv32,vals9); + // 0a760244c109bb5c9ef989126205f6585b9d4167afa0a2733fbab7fe74967049 privkey + for (i=0; i<32; i++) + printf("%02x",priv32[i]); + printf(" priv32\n"); priv2addr(coinaddr,pub33,priv32); pk = buf2pk(pub33); GetCCaddress(cp,CCaddr,pk); From f262751d437ff0d88865d12e6a7bf08f1cfad27e Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 05:35:29 -1100 Subject: [PATCH 0153/1145] Prints --- src/cc/cclib.cpp | 4 ++-- src/cc/sudoku.cpp | 4 ---- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index c1c3d9f24..adc17f54c 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -263,7 +263,7 @@ int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK { txid = it->first.txhash; vout = (int32_t)it->first.index; - //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); + char str[65]; fprintf(stderr,"%s check %s/v%d %.8f vs %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN,(double)threshold/COIN); if ( it->second.satoshis < threshold ) continue; // no need to prevent dup @@ -278,7 +278,7 @@ int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK n++; if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) ) break; - } else fprintf(stderr,"nValue too small or already spent in mempool\n"); + } else fprintf(stderr,"nValue %.8f too small or already spent in mempool\n",(double)nValue/COIN); } else fprintf(stderr,"couldnt get tx\n"); } return(totalinputs); diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index e71c9df5a..7ff297004 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -710,10 +710,6 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params for (j=0; j<9; j++) vals9[i][j] = solution[ind++] - '0'; sudoku_privkey(priv32,vals9); - // 0a760244c109bb5c9ef989126205f6585b9d4167afa0a2733fbab7fe74967049 privkey - for (i=0; i<32; i++) - printf("%02x",priv32[i]); - printf(" priv32\n"); priv2addr(coinaddr,pub33,priv32); pk = buf2pk(pub33); GetCCaddress(cp,CCaddr,pk); From 9195d9034aa4be0846fa77620bddb60358e1953a Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 05:39:17 -1100 Subject: [PATCH 0154/1145] Cmpaddr as arg to IsCClibvout --- src/cc/cclib.cpp | 12 ++++++------ src/cc/sudoku.cpp | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index adc17f54c..d1817b2ce 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -141,12 +141,12 @@ UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params) return(result); } -int64_t IsCClibvout(struct CCcontract_info *cp,const CTransaction& tx,int32_t v) +int64_t IsCClibvout(struct CCcontract_info *cp,const CTransaction& tx,int32_t v,char *cmpaddr) { char destaddr[64]; if ( tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0 ) { - if ( Getscriptaddress(destaddr,tx.vout[v].scriptPubKey) > 0 && strcmp(destaddr,cp->unspendableCCaddr) == 0 ) + if ( Getscriptaddress(destaddr,tx.vout[v].scriptPubKey) > 0 && strcmp(destaddr,cmpaddr) == 0 ) return(tx.vout[v].nValue); } return(0); @@ -171,7 +171,7 @@ bool CClibExactAmounts(struct CCcontract_info *cp,Eval* eval,const CTransaction //fprintf(stderr,"vini.%d check hash and vout\n",i); if ( hashBlock == zerohash ) return eval->Invalid("cant faucet2 from mempool"); - if ( (assetoshis= IsCClibvout(cp,vinTx,tx.vin[i].prevout.n)) != 0 ) + if ( (assetoshis= IsCClibvout(cp,vinTx,tx.vin[i].prevout.n,cp->unspendableCCaddr)) != 0 ) inputs += assetoshis; } } @@ -179,7 +179,7 @@ bool CClibExactAmounts(struct CCcontract_info *cp,Eval* eval,const CTransaction for (i=0; iunspendableCCaddr)) != 0 ) outputs += assetoshis; } if ( inputs != outputs+FAUCET2SIZE+txfee ) @@ -220,7 +220,7 @@ bool CClib_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C else { preventCCvouts = 1; - if ( IsCClibvout(cp,tx,0) != 0 ) + if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) != 0 ) { preventCCvouts++; i = 1; @@ -269,7 +269,7 @@ int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK // no need to prevent dup if ( GetTransaction(txid,vintx,hashBlock,false) != 0 ) { - if ( (nValue= IsCClibvout(cp,vintx,vout)) > 1000000 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( (nValue= IsCClibvout(cp,vintx,vout,cp->unspendableCCaddr)) > 1000000 && myIsutxo_spentinmempool(txid,vout) == 0 ) { if ( total != 0 && maxinputs != 0 ) mtx.vin.push_back(CTxIn(txid,vout,CScript())); diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 7ff297004..87f66d751 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -652,7 +652,7 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) continue; if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) { - if ( (nValue= IsCClibvout(cp,tx,vout)) == txfee && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( (nValue= IsCClibvout(cp,tx,vout,coinaddr)) == txfee && myIsutxo_spentinmempool(txid,vout) == 0 ) { if ( sudoku_genopreturndecode(unsolved,tx.vout[numvouts-1].scriptPubKey) == 'G' ) a.push_back(txid.GetHex()); From b2435c8c1637d3aba2d1c666996123793b527527 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 05:41:26 -1100 Subject: [PATCH 0155/1145] Set cmpaddr --- src/cc/cclib.cpp | 6 +++--- src/cc/sudoku.cpp | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index d1817b2ce..036a7d119 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -252,7 +252,7 @@ bool CClib_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } } -int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,int64_t total,int32_t maxinputs) +int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,int64_t total,int32_t maxinputs,char *cmpaddr) { char coinaddr[64]; int64_t threshold,nValue,price,totalinputs = 0; uint256 txid,hashBlock; std::vector origpubkey; CTransaction vintx; int32_t vout,n = 0; std::vector > unspentOutputs; @@ -269,7 +269,7 @@ int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK // no need to prevent dup if ( GetTransaction(txid,vintx,hashBlock,false) != 0 ) { - if ( (nValue= IsCClibvout(cp,vintx,vout,cp->unspendableCCaddr)) > 1000000 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( (nValue= IsCClibvout(cp,vintx,vout,cmpaddr)) > 1000000 && myIsutxo_spentinmempool(txid,vout) == 0 ) { if ( total != 0 && maxinputs != 0 ) mtx.vin.push_back(CTxIn(txid,vout,CScript())); @@ -333,7 +333,7 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para return(""); cclibpk = GetUnspendable(cp,0); mypk = pubkey2pk(Mypubkey()); - if ( (inputs= AddCClibInputs(cp,mtx,cclibpk,nValue+txfee,60)) > 0 ) + if ( (inputs= AddCClibInputs(cp,mtx,cclibpk,nValue+txfee,60,cp->unspendableCCaddr)) > 0 ) { if ( inputs > nValue ) CCchange = (inputs - nValue - txfee); diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 87f66d751..b407c5c3a 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -570,7 +570,7 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params sudokupk = GetUnspendable(cp,0); result.push_back(Pair("srand",(int)srandi)); result.push_back(Pair("amount",ValueFromAmount(amount))); - if ( (inputsum= AddCClibInputs(cp,mtx,sudokupk,amount+2*txfee,16)) >= amount+2*txfee ) + if ( (inputsum= AddCClibInputs(cp,mtx,sudokupk,amount+2*txfee,16,cp->unspendableCCaddr)) >= amount+2*txfee ) { //printf("inputsum %.8f\n",(double)inputsum/COIN); mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,sudokupk)); @@ -716,7 +716,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("sudokuaddr",CCaddr)); balance = CCaddress_balance(CCaddr); result.push_back(Pair("amount",ValueFromAmount(balance))); - if ( (inputsum= AddCClibInputs(cp,mtx,pk,balance,16)) >= balance ) + if ( (inputsum= AddCClibInputs(cp,mtx,pk,balance,16,CCaddr)) >= balance ) { mtx.vout.push_back(CTxOut(balance-txfee,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); CCaddr2set(cp,cp->evalcode,pk,priv32,CCaddr); From eee12923bcbef17db21380d266a80001e3267666 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 05:49:54 -1100 Subject: [PATCH 0156/1145] jsonstr --- src/cc/cclib.cpp | 2 +- src/cc/sudoku.cpp | 36 ++++++++++++++++++++++++++++++------ 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 036a7d119..eb93a5042 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -263,7 +263,7 @@ int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK { txid = it->first.txhash; vout = (int32_t)it->first.index; - char str[65]; fprintf(stderr,"%s check %s/v%d %.8f vs %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN,(double)threshold/COIN); + //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f vs %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN,(double)threshold/COIN); if ( it->second.satoshis < threshold ) continue; // no need to prevent dup diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index b407c5c3a..c3fa87c74 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -478,7 +478,7 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) //////////////////////// start of CClib interface // ./komodod -ac_name=SUDOKU -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -gen -genproclimit=1 -ac_cclib=sudoku -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60000 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & -/* cclib "gen" 17 "1" +/* cclib "gen" 17 \"1\" 5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432 */ @@ -505,6 +505,14 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) /* cclib "solution" 17 \"[%22469823715875961234231457698914675823653182479782394156346219587528736941197548362%22,1548777525,1548777526,...]\" + { + "name": "sudoku", + "method": "solution", + "sudokuaddr": "RSeoPJvMUSLfUHM1BomB97geW9zPznwHXk", + "amount": 1.00000000, + "result": "success", + "hex": "0400008085202f8901328455ce926086f00be1b2adac0ba9adc22067a30948c71572f3da80adc1135d010000007b4c79a276a072a26ba067a565802102c57d40c1ddc92a5246a937bd7338823f1e8c916b137f2092d38cf250d74cb5ab8140f92d54f611aa3cb3d187eaadd56b06f3a8c0f5fba23956b26fdefc6038d9b6282de38525f72ebd8945a7994cef63ebca711ecf8fe6baeefcc218cf58efb59dc2a100af03800111a10001ffffffff02f0b9f505000000002321039433dc3749aece1bd568f374a45da3b0bc6856990d7da3cd175399577940a775ac0000000000000000fd9f016a4d9b01115351343639383233373135383735393631323334323331343537363938393134363735383233363533313832343739373832333934313536333436323139353837353238373336393431313937353438333632fd4401000000005c5078355c50783600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000" + } */ CScript sudoku_genopret(uint8_t unsolved[9][9]) @@ -552,12 +560,20 @@ uint8_t sudoku_genopreturndecode(char *unsolved,CScript scriptPubKey) UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); CPubKey sudokupk,pk; uint8_t privkey[32],unsolved[9][9],pub33[33]; uint32_t srandi; uint256 hash; char coinaddr[64]; uint64_t inputsum,amount,change=0; std::string rawtx; + UniValue result(UniValue::VOBJ); CPubKey sudokupk,pk; uint8_t privkey[32],unsolved[9][9],pub33[33]; uint32_t srandi; uint256 hash; char coinaddr[64],*jsonstr; uint64_t inputsum,amount,change=0; std::string rawtx; + amount = COIN; if ( params != 0 ) { - printf("%p params.(%s)\n",params,jprint(params,0)); - amount = jdouble(jitem(params,0),0) * COIN + 0.0000000049; - } else amount = COIN; + if ( (jsonstr= jprint(params,0)) != 0 ) + { + if ( jsonstr[0] == '"' && jsonstr[strlen(jsonstr)-1] == '"' ) + { + jsonstr[strlen(jsonstr)-1] = 0; + jsonstr++; + } + amount = atof(jsonstr) * COIN + 0.0000000049; + } + } result.push_back(Pair("result","success")); result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","gen")); @@ -581,8 +597,16 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params mtx.vout.push_back(MakeCC1vout(cp->evalcode,change,sudokupk)); rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_genopret(unsolved)); if ( rawtx.size() > 0 ) + { + CTransaction tx; result.push_back(Pair("hex",rawtx)); - else result.push_back(Pair("error","couldnt finalize CCtx")); + if ( DecodeHexTx(tx,rawtx) != 0 ) + { + LOCK(cs_main); + if ( myAddtomempool(tx) != 0 ) + RelayTransaction(tx); + } + } else result.push_back(Pair("error","couldnt finalize CCtx")); } else result.push_back(Pair("error","not enough SUDOKU funds")); return(result); } From 24136eae68cf48fa6178afa1bafe0d713eed620f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 05:52:18 -1100 Subject: [PATCH 0157/1145] Add taxied --- src/cc/sudoku.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index c3fa87c74..d767acab6 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -478,7 +478,7 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) //////////////////////// start of CClib interface // ./komodod -ac_name=SUDOKU -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -gen -genproclimit=1 -ac_cclib=sudoku -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60000 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & -/* cclib "gen" 17 \"1\" +/* cclib "gen" 17 \"10\" 5d13c1ad80daf37215c74809a36720c2ada90bacadb2e10bf0866092ce558432 */ @@ -604,7 +604,10 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params { LOCK(cs_main); if ( myAddtomempool(tx) != 0 ) + { RelayTransaction(tx); + result.push_back(Pair("txid",tx.GetHash().ToString())); + } } } else result.push_back(Pair("error","couldnt finalize CCtx")); } else result.push_back(Pair("error","not enough SUDOKU funds")); From 69aedc198169602fc42ac00971f24c6de3498c4e Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 06:14:29 -1100 Subject: [PATCH 0158/1145] Nun-ending --- src/cc/sudoku.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index d767acab6..db2ea24bd 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -690,6 +690,7 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","pending")); result.push_back(Pair("pending",a)); + result.push_back(Pair("numpending",a.size())); return(result); } From a783c9d7f52c8e0cb0a59d6d2ccabeea63a76fb1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 07:10:01 -1100 Subject: [PATCH 0159/1145] sudoku_captcha --- src/cc/sudoku.cpp | 61 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 55 insertions(+), 6 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index db2ea24bd..bdc47ea61 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -515,6 +515,46 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) } */ +int32_t sudoku_captcha(uint32_t timestamps[81]) +{ + int32_t i,solvetime,avetime,n = 0; uint64_t variance = 0; std::vector list; + for (i=0; i<81; i++) + { + if ( timestamps[i] != 0 ) + { + list.push_back(timestamps[i]); + n++; + } + } + if ( n > 81/2 ) + { + std::sort(list.begin(),list.end()); + solvetime = (list[0] - list[n-1]); + if ( list[0] < list[n-1] ) + return(-1); + else if ( list[0] > chainActive.LastTip()->nTime+200 ) + return(-1); + else if ( solvetime >= 777 ) + return(0); + else + { + avetime = (solvetime / (n-1)); + if ( avetime == 0 ) + return(-1); + for (i=0; i data; int32_t i,j; @@ -730,7 +770,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params for (i=1; i= balance ) + if ( sudoku_captcha(timestamps) < 0 ) { - mtx.vout.push_back(CTxOut(balance-txfee,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); - CCaddr2set(cp,cp->evalcode,pk,priv32,CCaddr); - rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_solutionopret(solution,timestamps)); + result.push_back(Pair("result","error")); + result.push_back(Pair("error","captcha failure")); + return(result); + } + else + { + if ( (inputsum= AddCClibInputs(cp,mtx,pk,balance,16,CCaddr)) >= balance ) + { + mtx.vout.push_back(CTxOut(balance-txfee,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + CCaddr2set(cp,cp->evalcode,pk,priv32,CCaddr); + rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_solutionopret(solution,timestamps)); + } } } } @@ -756,7 +805,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( rawtx.size() > 0 ) result.push_back(Pair("hex",rawtx)); else result.push_back(Pair("error","couldnt finalize CCtx")); - printf("params.(%s)\n",jprint(params,0)); + //printf("params.(%s)\n",jprint(params,0)); return(result); } else From 1c6dd009cf6807710dc048de06067bc1024ba1a9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 07:11:46 -1100 Subject: [PATCH 0160/1145] Print --- src/cc/sudoku.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index bdc47ea61..d0db3db90 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -531,7 +531,10 @@ int32_t sudoku_captcha(uint32_t timestamps[81]) std::sort(list.begin(),list.end()); solvetime = (list[0] - list[n-1]); if ( list[0] < list[n-1] ) + { + printf("list[0] %u vs list[%d-1] %u\n",list[0],list[n-1]); return(-1); + } else if ( list[0] > chainActive.LastTip()->nTime+200 ) return(-1); else if ( solvetime >= 777 ) @@ -543,7 +546,9 @@ int32_t sudoku_captcha(uint32_t timestamps[81]) return(-1); for (i=0; i Date: Tue, 29 Jan 2019 07:12:46 -1100 Subject: [PATCH 0161/1145] N --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index d0db3db90..0be42cba5 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -532,7 +532,7 @@ int32_t sudoku_captcha(uint32_t timestamps[81]) solvetime = (list[0] - list[n-1]); if ( list[0] < list[n-1] ) { - printf("list[0] %u vs list[%d-1] %u\n",list[0],list[n-1]); + printf("list[0] %u vs list[%d-1] %u\n",list[0],n,list[n-1]); return(-1); } else if ( list[0] > chainActive.LastTip()->nTime+200 ) From 82cf345e94de801e4dcec919932ff4d6ec33ad83 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 07:13:16 -1100 Subject: [PATCH 0162/1145] Diff --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 0be42cba5..0b45c8483 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -517,7 +517,7 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) int32_t sudoku_captcha(uint32_t timestamps[81]) { - int32_t i,solvetime,avetime,n = 0; uint64_t variance = 0; std::vector list; + int32_t i,solvetime,diff,avetime,n = 0; uint64_t variance = 0; std::vector list; for (i=0; i<81; i++) { if ( timestamps[i] != 0 ) From 2bc78f3998919bc7ec292480effa9629ef43ee6f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 07:16:17 -1100 Subject: [PATCH 0163/1145] N --- src/cc/sudoku.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 0b45c8483..0696ec979 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -526,7 +526,7 @@ int32_t sudoku_captcha(uint32_t timestamps[81]) n++; } } - if ( n > 81/2 ) + //if ( n > 81/2 ) { std::sort(list.begin(),list.end()); solvetime = (list[0] - list[n-1]); @@ -557,7 +557,7 @@ int32_t sudoku_captcha(uint32_t timestamps[81]) return(-1 * 0); else return(0); } - } else return(-1); + } //else return(-1); } CScript sudoku_genopret(uint8_t unsolved[9][9]) From 03274df1f9fc444b7faa600620986ec4739078a6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 07:18:13 -1100 Subject: [PATCH 0164/1145] Reverse polarity --- src/cc/sudoku.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 0696ec979..0fa750d6d 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -529,13 +529,13 @@ int32_t sudoku_captcha(uint32_t timestamps[81]) //if ( n > 81/2 ) { std::sort(list.begin(),list.end()); - solvetime = (list[0] - list[n-1]); - if ( list[0] < list[n-1] ) + solvetime = (list[n-1] - list[0]); + if ( list[0] >= list[n-1] ) { printf("list[0] %u vs list[%d-1] %u\n",list[0],n,list[n-1]); return(-1); } - else if ( list[0] > chainActive.LastTip()->nTime+200 ) + else if ( list[n-1] > chainActive.LastTip()->nTime+200 ) return(-1); else if ( solvetime >= 777 ) return(0); From 425d5ddbafe762f9629ce6b6fba915a550cf8deb Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 07:20:02 -1100 Subject: [PATCH 0165/1145] Enable captcha --- src/cc/sudoku.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 0fa750d6d..05450659a 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -526,7 +526,7 @@ int32_t sudoku_captcha(uint32_t timestamps[81]) n++; } } - //if ( n > 81/2 ) + if ( n > 81/2 ) { std::sort(list.begin(),list.end()); solvetime = (list[n-1] - list[0]); @@ -557,7 +557,7 @@ int32_t sudoku_captcha(uint32_t timestamps[81]) return(-1 * 0); else return(0); } - } //else return(-1); + } else return(-1); } CScript sudoku_genopret(uint8_t unsolved[9][9]) From a7f14184a71fdd9437524a68ebfa9566272679db Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 07:21:58 -1100 Subject: [PATCH 0166/1145] Split gen --- src/cc/sudoku.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 05450659a..5e3801efb 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -639,7 +639,13 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( inputsum > amount + 2*txfee ) change = (inputsum - amount - 2*txfee); if ( change > txfee ) - mtx.vout.push_back(MakeCC1vout(cp->evalcode,change,sudokupk)); + { + if ( change > 10000*COIN ) + { + mtx.vout.push_back(MakeCC1vout(cp->evalcode,change/2,sudokupk)); + mtx.vout.push_back(MakeCC1vout(cp->evalcode,change/2,sudokupk)); + } else mtx.vout.push_back(MakeCC1vout(cp->evalcode,change,sudokupk)); + } rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_genopret(unsolved)); if ( rawtx.size() > 0 ) { From 16512daaaa1939c6977b9a653a062c6834a6ce4d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 07:34:07 -1100 Subject: [PATCH 0167/1145] -print --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index eb93a5042..69d8d4aaa 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -278,7 +278,7 @@ int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK n++; if ( (total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs) ) break; - } else fprintf(stderr,"nValue %.8f too small or already spent in mempool\n",(double)nValue/COIN); + } //else fprintf(stderr,"nValue %.8f too small or already spent in mempool\n",(double)nValue/COIN); } else fprintf(stderr,"couldnt get tx\n"); } return(totalinputs); From 6283d6dd284d62e2eb1b5c279154911dc3e6d043 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 07:36:23 -1100 Subject: [PATCH 0168/1145] Pending total --- src/cc/sudoku.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 5e3801efb..3e19ba964 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -716,7 +716,7 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ),a(UniValue::VARR); - char coinaddr[64],unsolved[82]; int64_t nValue; uint256 txid,hashBlock; CTransaction tx; int32_t vout,numvouts; CPubKey sudokupk; + char coinaddr[64],unsolved[82]; int64_t nValue,total=0; uint256 txid,hashBlock; CTransaction tx; int32_t vout,numvouts; CPubKey sudokupk; std::vector > unspentOutputs; sudokupk = GetUnspendable(cp,0); GetCCaddress(cp,coinaddr,sudokupk); @@ -733,7 +733,10 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( (nValue= IsCClibvout(cp,tx,vout,coinaddr)) == txfee && myIsutxo_spentinmempool(txid,vout) == 0 ) { if ( sudoku_genopreturndecode(unsolved,tx.vout[numvouts-1].scriptPubKey) == 'G' ) + { a.push_back(txid.GetHex()); + total += tx.vout[1].nValue; + } } } } @@ -742,6 +745,7 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("method","pending")); result.push_back(Pair("pending",a)); result.push_back(Pair("numpending",a.size())); + result.push_back(Pair("total",ValueFromAmount(total))); return(result); } From e66ebf2a862d754cf0bee59eca7e4e8c582f871e Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 08:04:19 -1100 Subject: [PATCH 0169/1145] Add txid for solution --- src/cc/sudoku.cpp | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 3e19ba964..e7861fa97 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -504,7 +504,7 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) }*/ /* - cclib "solution" 17 \"[%22469823715875961234231457698914675823653182479782394156346219587528736941197548362%22,1548777525,1548777526,...]\" + cclib "solution" 17 \"[%22fdc9409741f2ede29307da1a06438da0ea6f8d885d2d5c3199c4ef541ec1b5fd%22,%22469823715875961234231457698914675823653182479782394156346219587528736941197548362%22,1548777525,1548777526,...]\" { "name": "sudoku", "method": "solution", @@ -752,7 +752,7 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); int32_t i,j,ind,n; char *jsonstr,*newstr,coinaddr[64],CCaddr[64],*solution=0; CPubKey pk,mypk; uint8_t vals9[9][9],priv32[32],pub33[33]; uint32_t timestamps[81]; uint64_t balance,inputsum; std::string rawtx; + UniValue result(UniValue::VOBJ); int32_t i,j,ind,n; uint256 txid; char *jsonstr,*newstr,*txidstr,coinaddr[64],CCaddr[64],*solution=0; CPubKey pk,mypk; uint8_t vals9[9][9],priv32[32],pub33[33]; uint32_t timestamps[81]; uint64_t balance,inputsum; std::string rawtx; CTransaction tx; mypk = pubkey2pk(Mypubkey()); memset(timestamps,0,sizeof(timestamps)); result.push_back(Pair("name","sudoku")); @@ -780,14 +780,21 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params } else params = 0; if ( params != 0 ) { - if ( (n= cJSON_GetArraySize(params)) > 2 && n < (sizeof(timestamps)/sizeof(*timestamps))+1 ) + if ( (n= cJSON_GetArraySize(params)) > 2 && n < (sizeof(timestamps)/sizeof(*timestamps))+2 ) { - for (i=1; i= balance ) { - mtx.vout.push_back(CTxOut(balance-txfee,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + mtx.vout.push_back(CTxOut(balance,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); CCaddr2set(cp,cp->evalcode,pk,priv32,CCaddr); rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_solutionopret(solution,timestamps)); } } } - } - result.push_back(Pair("result","success")); + result.push_back(Pair("result","success")); + } else result.push_back(Pair("error","couldnt get all params")); if ( rawtx.size() > 0 ) result.push_back(Pair("hex",rawtx)); else result.push_back(Pair("error","couldnt finalize CCtx")); From 81f9d7046ed823231c2e4e473a484042f61a4139 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 08:04:49 -1100 Subject: [PATCH 0170/1145] Test --- src/cc/sudoku.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index e7861fa97..113ee11b5 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -782,13 +782,6 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params { if ( (n= cJSON_GetArraySize(params)) > 2 && n < (sizeof(timestamps)/sizeof(*timestamps))+2 ) { - if ( (txidstr= jstri(params,0)) != 0 ) - { - decode_hex((uint8_t *)&txid,32,txidstr); - txid = revuint256(txid); - result.push_back(Pair("txid",txid.GetHex())); - // get tx and validate solution is for that txid - } for (i=2; i= balance ) { From b399529ec84274978dcb01c1154f141630caa69f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 08:08:29 -1100 Subject: [PATCH 0171/1145] Ignore --- src/cc/sudoku.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 113ee11b5..3f0052d3b 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -803,9 +803,9 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params { result.push_back(Pair("result","error")); result.push_back(Pair("error","captcha failure")); - return(result); + //return(result); } - else + //else { if ( (txidstr= jstri(params,0)) != 0 ) { From 07131cab6035386d141af0662c710509dc921e8b Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 08:12:05 -1100 Subject: [PATCH 0172/1145] Disable --- src/cc/sudoku.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 3f0052d3b..267504120 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -799,13 +799,13 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("sudokuaddr",CCaddr)); balance = CCaddress_balance(CCaddr); result.push_back(Pair("amount",ValueFromAmount(balance))); - if ( sudoku_captcha(timestamps) < 0 ) + if ( 0 && sudoku_captcha(timestamps) < 0 ) { result.push_back(Pair("result","error")); result.push_back(Pair("error","captcha failure")); - //return(result); + return(result); } - //else + else { if ( (txidstr= jstri(params,0)) != 0 ) { From 5cdd5f8722ace517a5283da7f22611ee35adf3ae Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 08:14:03 -1100 Subject: [PATCH 0173/1145] Reenable captcha --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 267504120..113ee11b5 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -799,7 +799,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("sudokuaddr",CCaddr)); balance = CCaddress_balance(CCaddr); result.push_back(Pair("amount",ValueFromAmount(balance))); - if ( 0 && sudoku_captcha(timestamps) < 0 ) + if ( sudoku_captcha(timestamps) < 0 ) { result.push_back(Pair("result","error")); result.push_back(Pair("error","captcha failure")); From 0a61cd4e2ec409f73655c0c254c4eebd6cd64624 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 08:20:29 -1100 Subject: [PATCH 0174/1145] +err print --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 113ee11b5..3024f821c 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -820,7 +820,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params mtx.vout.push_back(CTxOut(balance,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); CCaddr2set(cp,cp->evalcode,pk,priv32,CCaddr); rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_solutionopret(solution,timestamps)); - } + } else result.push_back(Pair("error","couldnt find funds in solution address")); } } result.push_back(Pair("result","success")); From 51721e30bb9c9d4f3788593f061a206bba60ca51 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 08:28:21 -1100 Subject: [PATCH 0175/1145] Mixup errors --- src/cc/sudoku.cpp | 44 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 9 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 3024f821c..c844e1591 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -752,11 +752,12 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); int32_t i,j,ind,n; uint256 txid; char *jsonstr,*newstr,*txidstr,coinaddr[64],CCaddr[64],*solution=0; CPubKey pk,mypk; uint8_t vals9[9][9],priv32[32],pub33[33]; uint32_t timestamps[81]; uint64_t balance,inputsum; std::string rawtx; CTransaction tx; + UniValue result(UniValue::VOBJ); int32_t i,j,good,ind,n,numvouts; uint256 txid; char *jsonstr,*newstr,*txidstr,coinaddr[64],CCaddr[64],*solution=0; CPubKey pk,mypk; uint8_t vals9[9][9],priv32[32],pub33[33],unsolved[81]; uint32_t timestamps[81]; uint64_t balance,inputsum; std::string rawtx; CTransaction tx; uint256 hashBlock; mypk = pubkey2pk(Mypubkey()); memset(timestamps,0,sizeof(timestamps)); result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","solution")); + good = 0; if ( params != 0 ) { if ( (jsonstr= jprint(params,0)) != 0 ) @@ -812,21 +813,46 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params decode_hex((uint8_t *)&txid,32,txidstr); txid = revuint256(txid); result.push_back(Pair("txid",txid.GetHex())); - // get tx and validate solution is for that txid + if ( CCgettxout(txid,0,1) < 0 ) + result.push_back(Pair("error","already solved")); + else if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + { + if ( sudoku_genopreturndecode(unsolved,tx.vout[numvouts-1].scriptPubKey) == 'G' ) + { + for (i=0; i<81; i++) + { + if ( unsolved[i] == 0 ) + continue; + else if ( unsolved[i] != solution[i]-'0' ) + { + printf("i.%d %d != %d\n",i,unsolved[i],solution[i]-'0'); + result.push_back(Pair("error","wrong sudoku solved")); + break; + } + } + if ( i == 81 ) + good = 1; + } else result.push_back(Pair("error","cant decode sudoku")); + } else result.push_back(Pair("error","couldnt find sudoku")); } - mtx.vin.push_back(CTxIn(txid,0,CScript())); - if ( (inputsum= AddCClibInputs(cp,mtx,pk,balance,16,CCaddr)) >= balance ) + if ( good != 0 ) { - mtx.vout.push_back(CTxOut(balance,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); - CCaddr2set(cp,cp->evalcode,pk,priv32,CCaddr); - rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_solutionopret(solution,timestamps)); - } else result.push_back(Pair("error","couldnt find funds in solution address")); + mtx.vin.push_back(CTxIn(txid,0,CScript())); + if ( (inputsum= AddCClibInputs(cp,mtx,pk,balance,16,CCaddr)) >= balance ) + { + mtx.vout.push_back(CTxOut(balance,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + CCaddr2set(cp,cp->evalcode,pk,priv32,CCaddr); + rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_solutionopret(solution,timestamps)); + } else result.push_back(Pair("error","couldnt find funds in solution address")); + } } } - result.push_back(Pair("result","success")); } else result.push_back(Pair("error","couldnt get all params")); if ( rawtx.size() > 0 ) + { + result.push_back(Pair("result","success")); result.push_back(Pair("hex",rawtx)); + } else result.push_back(Pair("error","couldnt finalize CCtx")); //printf("params.(%s)\n",jprint(params,0)); return(result); From 892d237b03b1f19c3ba355b4287f296cceba2c52 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 08:30:04 -1100 Subject: [PATCH 0176/1145] ,unsolved[81] --- src/cc/sudoku.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index c844e1591..3cb9469f1 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -752,7 +752,7 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); int32_t i,j,good,ind,n,numvouts; uint256 txid; char *jsonstr,*newstr,*txidstr,coinaddr[64],CCaddr[64],*solution=0; CPubKey pk,mypk; uint8_t vals9[9][9],priv32[32],pub33[33],unsolved[81]; uint32_t timestamps[81]; uint64_t balance,inputsum; std::string rawtx; CTransaction tx; uint256 hashBlock; + UniValue result(UniValue::VOBJ); int32_t i,j,good,ind,n,numvouts; uint256 txid; char *jsonstr,*newstr,*txidstr,coinaddr[64],CCaddr[64],*solution=0,unsolved[82]; CPubKey pk,mypk; uint8_t vals9[9][9],priv32[32],pub33[33]; uint32_t timestamps[81]; uint64_t balance,inputsum; std::string rawtx; CTransaction tx; uint256 hashBlock; mypk = pubkey2pk(Mypubkey()); memset(timestamps,0,sizeof(timestamps)); result.push_back(Pair("name","sudoku")); @@ -823,9 +823,9 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params { if ( unsolved[i] == 0 ) continue; - else if ( unsolved[i] != solution[i]-'0' ) + else if ( unsolved[i] != solution[i] ) { - printf("i.%d %d != %d\n",i,unsolved[i],solution[i]-'0'); + printf("i.%d [%c] != [%c]\n",i,unsolved[i],solution[i]); result.push_back(Pair("error","wrong sudoku solved")); break; } From 70df4c1acf569c5db05480d0a0a1987d37b08246 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 21:39:11 -1100 Subject: [PATCH 0177/1145] '-' --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 3cb9469f1..06bc35db6 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -821,7 +821,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params { for (i=0; i<81; i++) { - if ( unsolved[i] == 0 ) + if ( unsolved[i] < '1' || unsolved[i] > '9') continue; else if ( unsolved[i] != solution[i] ) { From 3ba832b6bc8828594ad666ac84bafb781db2864a Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 21:48:26 -1100 Subject: [PATCH 0178/1145] Pending object --- src/cc/CCinclude.h | 1 + src/cc/sudoku.cpp | 13 ++++++++++--- src/komodo_bitcoind.h | 8 ++++++++ 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index 5d847800a..4da696547 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -134,6 +134,7 @@ int32_t CCgetspenttxid(uint256 &spenttxid,int32_t &vini,int32_t &height,uint256 void CCclearvars(struct CCcontract_info *cp); UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params); UniValue CClib_info(struct CCcontract_info *cp); +CBlockIndex *komodo_blockindex(uint256 hash); static const uint256 zeroid; bool myGetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock); diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 06bc35db6..4b6a6e749 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -667,7 +667,7 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); int32_t numvouts; char str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; char unsolved[82]; + UniValue result(UniValue::VOBJ); int32_t numvouts; char str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; char unsolved[82]; CBlockIndex *pindex; if ( params != 0 ) { result.push_back(Pair("result","success")); @@ -687,6 +687,8 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( sudoku_genopreturndecode(unsolved,tx.vout[numvouts-1].scriptPubKey) == 'G' ) { result.push_back(Pair("result","success")); + if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) + result.push_back(Pair("height",pindex->nHeight)); result.push_back(Pair("amount",ValueFromAmount(tx.vout[1].nValue))); result.push_back(Pair("unsolved",unsolved)); } @@ -716,7 +718,7 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ),a(UniValue::VARR); - char coinaddr[64],unsolved[82]; int64_t nValue,total=0; uint256 txid,hashBlock; CTransaction tx; int32_t vout,numvouts; CPubKey sudokupk; + char coinaddr[64],unsolved[82]; int64_t nValue,total=0; uint256 txid,hashBlock; CTransaction tx; int32_t vout,numvouts; CPubKey sudokupk; CBlockIndex *pindex; std::vector > unspentOutputs; sudokupk = GetUnspendable(cp,0); GetCCaddress(cp,coinaddr,sudokupk); @@ -734,7 +736,12 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( sudoku_genopreturndecode(unsolved,tx.vout[numvouts-1].scriptPubKey) == 'G' ) { - a.push_back(txid.GetHex()); + UniValue obj(UniValue::VOBJ); + if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) + obj.push_back(Pair("height",pindex->nHeight)); + obj.push_back(Pair("amount",ValueFromAmount(tx.vout[1].nValue))); + obj.push_back(Pair("txid",txid.GetHex())); + a.push_back(obj); total += tx.vout[1].nValue; } } diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index c530db4fb..b3248d7d4 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1033,6 +1033,14 @@ int32_t komodo_MoM(int32_t *notarized_heightp,uint256 *MoMp,uint256 *kmdtxidp,in return(depth); } +CBlockIndex *komodo_blockindex(uint256 hash) +{ + BlockMap::const_iterator it; CBlockIndex *pindex = 0; + if ( (it = mapBlockIndex.find(hash)) != mapBlockIndex.end() ) + pindex = it->second; + return(pindex); +} + int32_t komodo_checkpoint(int32_t *notarized_heightp,int32_t nHeight,uint256 hash) { int32_t notarized_height,MoMdepth; uint256 MoM,notarized_hash,notarized_desttxid; CBlockIndex *notary,*pindex; From 86aafb3761a8d86f8b87ae82bc550ace48d91061 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 21:49:05 -1100 Subject: [PATCH 0179/1145] GetHeight() --- src/cc/sudoku.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 4b6a6e749..dea9cb007 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -688,7 +688,7 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params { result.push_back(Pair("result","success")); if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) - result.push_back(Pair("height",pindex->nHeight)); + result.push_back(Pair("height",pindex->GetHeight())); result.push_back(Pair("amount",ValueFromAmount(tx.vout[1].nValue))); result.push_back(Pair("unsolved",unsolved)); } @@ -738,7 +738,7 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue obj(UniValue::VOBJ); if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) - obj.push_back(Pair("height",pindex->nHeight)); + obj.push_back(Pair("height",pindex->GetHeight())); obj.push_back(Pair("amount",ValueFromAmount(tx.vout[1].nValue))); obj.push_back(Pair("txid",txid.GetHex())); a.push_back(obj); From 1d4236867120cf28952c1f7287335ac6375f860f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 21:56:50 -1100 Subject: [PATCH 0180/1145] +print --- src/cc/sudoku.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index dea9cb007..10667461d 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -850,18 +850,22 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params mtx.vout.push_back(CTxOut(balance,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); CCaddr2set(cp,cp->evalcode,pk,priv32,CCaddr); rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,sudoku_solutionopret(solution,timestamps)); + if ( rawtx.size() > 0 ) + { + result.push_back(Pair("result","success")); + result.push_back(Pair("hex",rawtx)); + } + else result.push_back(Pair("error","couldnt finalize CCtx")); } else result.push_back(Pair("error","couldnt find funds in solution address")); } } } - } else result.push_back(Pair("error","couldnt get all params")); - if ( rawtx.size() > 0 ) - { - result.push_back(Pair("result","success")); - result.push_back(Pair("hex",rawtx)); } - else result.push_back(Pair("error","couldnt finalize CCtx")); - //printf("params.(%s)\n",jprint(params,0)); + else + { + printf("n.%d params.(%s)\n",n,jprint(params,0)); + result.push_back(Pair("error","couldnt get all params")); + } return(result); } else From b006656f9f0171045ea9647ca205408ee9943241 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 29 Jan 2019 21:58:04 -1100 Subject: [PATCH 0181/1145] Off by 1 --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 10667461d..59eb83309 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -788,7 +788,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params } else params = 0; if ( params != 0 ) { - if ( (n= cJSON_GetArraySize(params)) > 2 && n < (sizeof(timestamps)/sizeof(*timestamps))+2 ) + if ( (n= cJSON_GetArraySize(params)) > 2 && n <= (sizeof(timestamps)/sizeof(*timestamps))+2 ) { for (i=2; i Date: Wed, 30 Jan 2019 01:15:44 -1100 Subject: [PATCH 0182/1145] Check address --- src/cc/sudoku.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 59eb83309..841a67d81 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -667,7 +667,7 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); int32_t numvouts; char str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; char unsolved[82]; CBlockIndex *pindex; + UniValue result(UniValue::VOBJ); int32_t numvouts; char CCaddr[64],str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; char unsolved[82]; CBlockIndex *pindex; if ( params != 0 ) { result.push_back(Pair("result","success")); @@ -689,6 +689,8 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("result","success")); if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) result.push_back(Pair("height",pindex->GetHeight())); + Getscriptaddress(CCaddr,tx.vout[1].scriptPubKey); + result.push_back(Pair("sudokuaddr",CCaddr)); result.push_back(Pair("amount",ValueFromAmount(tx.vout[1].nValue))); result.push_back(Pair("unsolved",unsolved)); } @@ -759,7 +761,7 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); int32_t i,j,good,ind,n,numvouts; uint256 txid; char *jsonstr,*newstr,*txidstr,coinaddr[64],CCaddr[64],*solution=0,unsolved[82]; CPubKey pk,mypk; uint8_t vals9[9][9],priv32[32],pub33[33]; uint32_t timestamps[81]; uint64_t balance,inputsum; std::string rawtx; CTransaction tx; uint256 hashBlock; + UniValue result(UniValue::VOBJ); int32_t i,j,good,ind,n,numvouts; uint256 txid; char *jsonstr,*newstr,*txidstr,coinaddr[64],checkaddr[64],CCaddr[64],*solution=0,unsolved[82]; CPubKey pk,mypk; uint8_t vals9[9][9],priv32[32],pub33[33]; uint32_t timestamps[81]; uint64_t balance,inputsum; std::string rawtx; CTransaction tx; uint256 hashBlock; mypk = pubkey2pk(Mypubkey()); memset(timestamps,0,sizeof(timestamps)); result.push_back(Pair("name","sudoku")); @@ -804,6 +806,15 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params priv2addr(coinaddr,pub33,priv32); pk = buf2pk(pub33); GetCCaddress(cp,CCaddr,pk); + Getscriptaddress(checkaddr,tx.vout[1].scriptPubKey); + if ( strcmp(checkaddr,CCaddr) != 0 ) + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","wrong solution")); + result.push_back(Pair("yours",CCaddr)); + result.push_back(Pair("sudokuaddr",checkaddr)); + return(result); + } result.push_back(Pair("sudokuaddr",CCaddr)); balance = CCaddress_balance(CCaddr); result.push_back(Pair("amount",ValueFromAmount(balance))); From 15663f6fa93923676ab24c100ee2320b4dfb4a00 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 30 Jan 2019 02:34:33 -1100 Subject: [PATCH 0183/1145] Make sure sudoku has just one solution and set amount to difficulty score --- src/cc/cclib.cpp | 4 +- src/cc/sudoku.cpp | 2014 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 2012 insertions(+), 6 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 69d8d4aaa..dd79d22d9 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -44,10 +44,10 @@ CClib_methods[] = { { (char *)"faucet2", (char *)"fund", (char *)"amount", 1, 1, 'F', EVAL_FAUCET2 }, { (char *)"faucet2", (char *)"get", (char *)"", 0, 0, 'G', EVAL_FAUCET2 }, - { (char *)"sudoku", (char *)"gen", (char *)"amount", 1, 1, 'G', EVAL_SUDOKU }, + { (char *)"sudoku", (char *)"gen", (char *)"", 1, 1, 'G', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"pending", (char *)"", 0, 0, 'U', EVAL_SUDOKU }, - { (char *)"sudoku", (char *)"solution", (char *)"solution timestamps[]", 2, 2, 'S', EVAL_SUDOKU }, + { (char *)"sudoku", (char *)"solution", (char *)"txid solution timestamps[]", 2, 2, 'S', EVAL_SUDOKU }, }; std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *params); diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 841a67d81..b34eccd39 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -1,3 +1,1997 @@ +// start https://github.com/attractivechaos/plb/blob/master/sudoku/incoming/sudoku_solver.c +/************************************************************************************/ +/* */ +/* Author: Bill DuPree */ +/* Name: sudoku_solver.c */ +/* Language: C */ +/* Date: Feb. 25, 2006 */ +/* Copyright (C) Feb. 25, 2006, All rights reserved. */ +/* */ +/* This is a program that solves Su Doku (aka Sudoku, Number Place, etc.) puzzles */ +/* primarily using deductive logic. It will only resort to trial-and-error and */ +/* backtracking approaches upon exhausting all of its deductive moves. */ +/* */ +/* Puzzles must be of the standard 9x9 variety using the (ASCII) characters '1' */ +/* through '9' for the puzzle solution set. Puzzles should be submitted as 81 */ +/* character strings which, when read left-to-right will fill a 9x9 Sudoku grid */ +/* from left-to-right and top-to-bottom. In the puzzle specification, the */ +/* characters 1 - 9 represent the puzzle "givens" or clues. Any other non-blank */ +/* character represents an unsolved cell. */ +/* */ +/* The puzzle solving algorithm is "home grown." I did not borrow any of the usual */ +/* techniques from the literature, e.g. Donald Knuth's "Dancing Links." Instead */ +/* I "rolled my own" from scratch. As such, its performance can only be blamed */ +/* on yours truly. Still, I feel it is quite fast. On a 333 MHz Pentium II Linux */ +/* box it solves typical medium force puzzles in approximately 800 microseconds or */ +/* about 1,200 puzzles per second, give or take. On an Athlon XP 3000 (Barton core) */ +/* it solves about 6,600 puzzles per sec. */ +/* */ +/* DESCRIPTION OF ALGORITHM: */ +/* */ +/* The puzzle algorithm initially assumes every unsolved cell can assume every */ +/* possible value. It then uses the placement of the givens to refine the choices */ +/* available to each cell. I call this the markup phase. */ +/* */ +/* After markup completes, the algorithm then looks for "singleton" cells with */ +/* values that, due to constraints imposed by the row, column, or 3x3 region, may */ +/* only assume one possible value. Once these cells are assigned values, the */ +/* algorithm returns to the markup phase to apply these changes to the remaining */ +/* candidate solutions. The markup/singleton phases alternate until either no more */ +/* changes occur, or the puzzle is solved. I call the markup/singleton elimination */ +/* loop the "Simple Solver" because in a large percentage of cases it solves the */ +/* puzzle. */ +/* */ +/* If the simple solver portion of the algorithm doesn't produce a solution, then */ +/* more advanced deductive rules are applied. I've implemented two additional rules */ +/* as part of the deductive puzzle solver. The first is subset elimination wherein */ +/* a row/column/region is scanned for X number of cells with X number of matching */ +/* candidate solutions. If such subsets are found in the row, column, or region, */ +/* then the candidates values from the subset may be eliminated from all other */ +/* unsolved cells within the row, column, or region, respectively. */ +/* */ +/* The second advanced deductive rule examines each region looking for candidate */ +/* values that exclusively align themselves along a single row or column, i.e. a */ +/* a vector. If such candidate values are found, then they may be eliminated from */ +/* the cells outside of the region that are part of the aligned row or column. */ +/* */ +/* Note that each of the advanced deductive rules calls all preceeding rules, in */ +/* order, if that advanced rule has effected a change in puzzle markup. */ +/* */ +/* Finally, if no solution is found after iteratively applying all deductive rules, */ +/* then we begin trial-and-error using recursion for backtracking. A working copy */ +/* is created from our puzzle, and using this copy the first cell with the */ +/* smallest number of candidate solutions is chosen. One of the solutions values is */ +/* assigned to that cell, and the solver algorithm is called using this working */ +/* copy as its starting point. Eventually, either a solution, or an impasse is */ +/* reached. */ +/* */ +/* If we reach an impasse, the recursion unwinds and the next trial solution is */ +/* attempted. If a solution is found (at any point) the values for the solution are */ +/* added to a list. Again, so long as we are examining all possibilities, the */ +/* recursion unwinds so that the next trial may be attempted. It is in this manner */ +/* that we enumerate puzzles with multiple solutions. */ +/* */ +/* Note that it is certainly possible to add to the list of applied deductive */ +/* rules. The techniques known as "X-Wing" and "Swordfish" come to mind. On the */ +/* other hand, adding these additional rules will, in all likelihood, slow the */ +/* solver down by adding to the computational burden while producing very few */ +/* results. I've seen the law of diminishing returns even in some of the existing */ +/* rules, e.g. in subset elimination I only look at two and three valued subsets */ +/* because taking it any further than that degraded performance. */ +/* */ +/* PROGRAM INVOCATION: */ +/* */ +/* This program is a console (or command line) based utility and has the following */ +/* usage: */ +/* */ +/* sudoku_solver {-p puzzle | -f } [-o ] */ +/* [-r ] [-1][-a][-c][-g][-l][-m][-n][-s] */ +/* */ +/* where: */ +/* */ +/* -1 Search for first solution, otherwise all solutions are returned */ +/* -a Requests that the answer (solution) be printed */ +/* -c Print a count of solutions for each puzzle */ +/* -d Print the recursive trial depth required to solve the puzzle */ +/* -e Print a step-by-step explanation of the solution(s) */ +/* -f Takes an argument which specifes an input file */ +/* containing one or more unsolved puzzles (default: stdin) */ +/* -G Print the puzzle solution(s) in a 9x9 grid format */ +/* -g Print the number of given clues */ +/* -l Print the recursive trial depth required to solve the puzzle */ +/* -m Print an octal mask for the puzzle givens */ +/* -n Number each result */ +/* -o Specifies an output file for the solutions (default: stdout) */ +/* -p Takes an argument giving a single inline puzzle to be solved */ +/* -r Specifies an output file for unsolvable puzzles */ +/* (default: stderr) */ +/* -s Print the puzzle's score or difficulty rating */ +/* -? Print usage information */ +/* */ +/* The return code is zero if all puzzles had unique solutions, */ +/* (or have one or more solutions when -1 is specified) and non-zero */ +/* when no unique solution exists. */ +/* */ +/* PUZZLE SCORING */ +/* */ +/* A word about puzzle scoring, i.e. rating a puzzle's difficulty, is in order. */ +/* Rating Sudoku puzzles is a rather subjective thing, and thus it is difficult to */ +/* really develop an objective puzzle rating system. I, however, have attempted */ +/* this feat (several times with varying degrees of success ;-) and I think the */ +/* heuristics I'm currently applying aren't too bad for rating the relative */ +/* difficulty of solving a puzzle. */ +/* */ +/* The following is a brief rundown of how it works. The initial puzzle markup is */ +/* a "free" operation, i.e. no points are scored for the first markup pass. I feel */ +/* this is appropriate because a person solving a puzzle will always have to do */ +/* their own eyeballing and scanning of the puzzle. Subsequent passes are */ +/* scored at one point per candidate eliminated because these passes indicate */ +/* that more deductive work is required. Secondly, the "reward" for solving a cell */ +/* is set to one point, and as long as the solution only requires simple markup */ +/* and elimination of singletons, this level of reward remains unchanged. */ +/* */ +/* This reward changes, however, when advanced solving rules are required. Puzzles */ +/* that remain unsolved after the first pass through the simple solver phase have */ +/* a higher "reward", i.e. it is incremented by two. Thus, if subset or vector */ +/* elimination is required, all subsequently solved cells score higher bounties. */ +/* In addition, the successful application of these deductive techniques score */ +/* their own penalties. */ +/* */ +/* Finally, if a trial-and-error approach is called for, then the "reward" is */ +/* incremented by another five points. Thus, the total penalty for each level of */ +/* recursion is an additional seven points per solved cell, i.e. */ +/* (recursive_depth * 7) + 1 points per solved cell. Trial solutions are also */ +/* penalized by a weighting factor that is based upon the number of unsolved cells */ +/* that remain upon reentry to the solver and the depth of recursion. (I've seen a */ +/* pathological puzzle from the "Minimum Sudoku" web site require 16 levels of */ +/* recursion and score a whopping 228,642 points using this scoring system!) */ +/* */ +/* And that brings me to this topic: What do all these points mean? */ +/* */ +/* Well, who knows? This is still subjective, and the weighting system I've chosen */ +/* for point scoring is is largely arbitrary. But based upon feedback from a number */ +/* of individuals, a rough scale of difficulty plays out as follows: */ +/* */ +/* DEGREE OF DIFFICULTY | SCORE */ +/* -------------------------+------------------------------------------ */ +/* TRIVIAL | 80 points or less */ +/* EASY | 81 - 150 points */ +/* MEDIUM | 151 - 250 points */ +/* HARD | 251 - 400 points */ +/* VERY HARD | 401 - 900 points */ +/* DIABOLICAL | 901 and up */ +/* */ +/* Experience shows that puzzles in the HARD category, in a few cases, will */ +/* require a small amount of trial-and-error. The VERY HARD puzzles will likely */ +/* require trial-and-error, and in some cases more than one level of trial-and- */ +/* error. As for the DIABOLICAL puzzles--why waste your time? These are best left */ +/* to masochists, savants and automated solvers. YMMV. */ +/* */ +/* LICENSE: */ +/* */ +/* This program is free software; you can redistribute it and/or modify */ +/* it under the terms of the GNU General Public License as published by */ +/* the Free Software Foundation; either version 2 of the License, or */ +/* (at your option) any later version. */ +/* */ +/* This program is distributed in the hope that it will be useful, */ +/* but WITHOUT ANY WARRANTY; without even the implied warranty of */ +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ +/* GNU General Public License for more details. */ +/* */ +/* You should have received a copy of the GNU General Public License */ +/* along with this program; if not, write to the Free Software */ +/* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ +/* */ +/* CONTACT: */ +/* */ +/* Email: bdupree@techfinesse.com */ +/* Post: Bill DuPree, 609 Wenonah Ave, Oak Park, IL 60304 USA */ +/* */ +/************************************************************************************/ +/* */ +/* CHANGE LOG: */ +/* */ +/* Rev. Date Init. Description */ +/* -------------------------------------------------------------------------------- */ +/* 1.00 2006-02-25 WD Initial version. */ +/* 1.01 2006-03-13 WD Fixed return code calc. Added signon message. */ +/* 1.10 2006-03-20 WD Added explain option, add'l speed optimizations */ +/* 1.11 2006-03-23 WD More simple speed optimizations, cleanup, bug fixes */ +/* */ +/************************************************************************************/ + +#include +#include +#include +#include +#include +#include + +#define VERSION "1.11" + +#define PUZZLE_ORDER 3 +#define PUZZLE_DIM (PUZZLE_ORDER*PUZZLE_ORDER) +#define PUZZLE_CELLS (PUZZLE_DIM*PUZZLE_DIM) + +/* Command line options */ +#ifdef EXPLAIN +#define OPTIONS "?1acdef:Ggmno:p:r:s" +#else +#define OPTIONS "?1acdf:Ggmno:p:r:s" +#endif +extern char *optarg; +extern int optind, opterr, optopt; + +static char *myname; /* Name that we were invoked under */ + +static FILE *solnfile, *rejects; + +/* This is the list of cell coordinates specified on a row basis */ + +static int const row[PUZZLE_DIM][PUZZLE_DIM] = { + { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, + { 9, 10, 11, 12, 13, 14, 15, 16, 17 }, + { 18, 19, 20, 21, 22, 23, 24, 25, 26 }, + { 27, 28, 29, 30, 31, 32, 33, 34, 35 }, + { 36, 37, 38, 39, 40, 41, 42, 43, 44 }, + { 45, 46, 47, 48, 49, 50, 51, 52, 53 }, + { 54, 55, 56, 57, 58, 59, 60, 61, 62 }, + { 63, 64, 65, 66, 67, 68, 69, 70, 71 }, + { 72, 73, 74, 75, 76, 77, 78, 79, 80 }}; + +/* This is the list of cell coordinates specified on a column basis */ + +static int const col[PUZZLE_DIM][PUZZLE_DIM] = { + { 0, 9, 18, 27, 36, 45, 54, 63, 72 }, + { 1, 10, 19, 28, 37, 46, 55, 64, 73 }, + { 2, 11, 20, 29, 38, 47, 56, 65, 74 }, + { 3, 12, 21, 30, 39, 48, 57, 66, 75 }, + { 4, 13, 22, 31, 40, 49, 58, 67, 76 }, + { 5, 14, 23, 32, 41, 50, 59, 68, 77 }, + { 6, 15, 24, 33, 42, 51, 60, 69, 78 }, + { 7, 16, 25, 34, 43, 52, 61, 70, 79 }, + { 8, 17, 26, 35, 44, 53, 62, 71, 80 }}; + +/* This is the list of cell coordinates specified on a 3x3 region basis */ + +static int const region[PUZZLE_DIM][PUZZLE_DIM] = { + { 0, 1, 2, 9, 10, 11, 18, 19, 20 }, + { 3, 4, 5, 12, 13, 14, 21, 22, 23 }, + { 6, 7, 8, 15, 16, 17, 24, 25, 26 }, + { 27, 28, 29, 36, 37, 38, 45, 46, 47 }, + { 30, 31, 32, 39, 40, 41, 48, 49, 50 }, + { 33, 34, 35, 42, 43, 44, 51, 52, 53 }, + { 54, 55, 56, 63, 64, 65, 72, 73, 74 }, + { 57, 58, 59, 66, 67, 68, 75, 76, 77 }, + { 60, 61, 62, 69, 70, 71, 78, 79, 80 }}; + +/* Flags for cellflags member */ +#define GIVEN 1 +#define FOUND 2 +#define STUCK 3 + +/* Return codes for funcs that modify puzzle markup */ +#define NOCHANGE 0 +#define CHANGE 1 + +typedef struct grd { + short cellflags[PUZZLE_CELLS]; + short solved[PUZZLE_CELLS]; + short cell[PUZZLE_CELLS]; + short tail, givens, exposed, maxlvl, inc, reward; + unsigned int score, solncount; + struct grd *next; +} grid; + +typedef int (*return_soln)(grid *g); + +static grid *soln_list = NULL; + +typedef struct { + short row, col, region; +} cellmap; + +/* Array structure to help map cell index back to row, column, and region */ +static cellmap const map[PUZZLE_CELLS] = { + { 0, 0, 0 }, + { 0, 1, 0 }, + { 0, 2, 0 }, + { 0, 3, 1 }, + { 0, 4, 1 }, + { 0, 5, 1 }, + { 0, 6, 2 }, + { 0, 7, 2 }, + { 0, 8, 2 }, + { 1, 0, 0 }, + { 1, 1, 0 }, + { 1, 2, 0 }, + { 1, 3, 1 }, + { 1, 4, 1 }, + { 1, 5, 1 }, + { 1, 6, 2 }, + { 1, 7, 2 }, + { 1, 8, 2 }, + { 2, 0, 0 }, + { 2, 1, 0 }, + { 2, 2, 0 }, + { 2, 3, 1 }, + { 2, 4, 1 }, + { 2, 5, 1 }, + { 2, 6, 2 }, + { 2, 7, 2 }, + { 2, 8, 2 }, + { 3, 0, 3 }, + { 3, 1, 3 }, + { 3, 2, 3 }, + { 3, 3, 4 }, + { 3, 4, 4 }, + { 3, 5, 4 }, + { 3, 6, 5 }, + { 3, 7, 5 }, + { 3, 8, 5 }, + { 4, 0, 3 }, + { 4, 1, 3 }, + { 4, 2, 3 }, + { 4, 3, 4 }, + { 4, 4, 4 }, + { 4, 5, 4 }, + { 4, 6, 5 }, + { 4, 7, 5 }, + { 4, 8, 5 }, + { 5, 0, 3 }, + { 5, 1, 3 }, + { 5, 2, 3 }, + { 5, 3, 4 }, + { 5, 4, 4 }, + { 5, 5, 4 }, + { 5, 6, 5 }, + { 5, 7, 5 }, + { 5, 8, 5 }, + { 6, 0, 6 }, + { 6, 1, 6 }, + { 6, 2, 6 }, + { 6, 3, 7 }, + { 6, 4, 7 }, + { 6, 5, 7 }, + { 6, 6, 8 }, + { 6, 7, 8 }, + { 6, 8, 8 }, + { 7, 0, 6 }, + { 7, 1, 6 }, + { 7, 2, 6 }, + { 7, 3, 7 }, + { 7, 4, 7 }, + { 7, 5, 7 }, + { 7, 6, 8 }, + { 7, 7, 8 }, + { 7, 8, 8 }, + { 8, 0, 6 }, + { 8, 1, 6 }, + { 8, 2, 6 }, + { 8, 3, 7 }, + { 8, 4, 7 }, + { 8, 5, 7 }, + { 8, 6, 8 }, + { 8, 7, 8 }, + { 8, 8, 8 } +}; + +static const short symtab[1<= '1') && (c <= '9'); } + +#if defined(DEBUG) +static void mypause() +{ + char buf[8]; + printf("\tPress enter -> "); + fgets(buf, 8, stdin); +} +#endif + +#if 0 +/* Generic (and slow) bitcount function */ +static int bitcount(short cell) +{ + int i, count, mask; + + mask = 1; + for (i = count = 0; i < 16; i++) { + if (mask & cell) count++; + mask <<= 1; + } + return count; +} +#endif + +/*****************************************************/ +/* Return the number of '1' bits in a cell. */ +/* Rather than count bits, do a quick table lookup. */ +/* Warning: Only valid for 9 low order bits. */ +/*****************************************************/ + +static inline short bitcount(short cell) +{ + static const short bcounts[512] = { + 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5, + 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, + 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, + 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, + 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, + 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, + 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, + 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8, + 1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6, + 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, + 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, + 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8, + 2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7, + 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8, + 3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8, + 4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8,5,6,6,7,6,7,7,8,6,7,7,8,7,8,8,9}; + + return bcounts[cell]; +} + +#ifdef EXPLAIN + +/**************************************************/ +/* Indent two spaces for each level of recursion. */ +/**************************************************/ +static inline void explain_indent(FILE *h) +{ + int i; + + for (i = 0; i < lvl-1; i++) fprintf(h, " "); +} + +/******************************************************************/ +/* Construct a string representing the possible values a cell may */ +/* contain according to current markup. */ +/******************************************************************/ +static char *clues(short cell) +{ + int i, m, multi, mask; + static char buf[64], *p; + + multi = m = bitcount(cell); + + if (!multi) return "NULL"; + + if (multi > 1) { + strcpy(buf, "tuple ("); + } + else { + strcpy(buf, "value "); + } + + p = buf + strlen(buf); + + for (mask = i = 1; i <= PUZZLE_DIM; i++) { + if (mask & cell) { + *p++ = symtab[mask]; + multi -= 1; + if (multi) { *p++ = ','; *p++ = ' '; } + } + mask <<= 1; + } + if (m > 1) *p++ = ')'; + *p = 0; + return buf; +} + +/*************************************************************/ +/* Explain removal of a candidate value from a changed cell. */ +/*************************************************************/ +static void explain_markup_elim(grid *g, int chgd, int clue) +{ + int chgd_row, chgd_col, clue_row, clue_col; + + chgd_row = map[chgd].row+1; + chgd_col = map[chgd].col+1; + clue_row = map[clue].row+1; + clue_col = map[clue].col+1; + + explain_indent(solnfile); + fprintf(solnfile, "Candidate %s removed from row %d, col %d because of cell at row %d, col %d\n", + clues(g->cell[clue]), chgd_row, chgd_col, clue_row, clue_col); +} + +/*****************************************/ +/* Dump the state of the current markup. */ +/*****************************************/ +static void explain_current_markup(grid *g) +{ + if (g->exposed >= PUZZLE_CELLS) return; + + fprintf(solnfile, "\n"); + explain_indent(solnfile); + fprintf(solnfile, "Current markup is as follows:"); + diagnostic_grid(g, solnfile); + fprintf(solnfile, "\n"); +} + +/****************************************/ +/* Explain the solving of a given cell. */ +/****************************************/ +static void explain_solve_cell(grid *g, int chgd) +{ + int chgd_row, chgd_col; + + chgd_row = map[chgd].row+1; + chgd_col = map[chgd].col+1; + + explain_indent(solnfile); + fprintf(solnfile, "Cell at row %d, col %d solved with %s\n", + chgd_row, chgd_col, clues(g->cell[chgd])); +} + +/******************************************************************/ +/* Explain the current impasse reached during markup elimination. */ +/******************************************************************/ +static void explain_markup_impasse(grid *g, int chgd, int clue) +{ + int chgd_row, chgd_col, clue_row, clue_col; + + chgd_row = map[chgd].row+1; + chgd_col = map[chgd].col+1; + clue_row = map[clue].row+1; + clue_col = map[clue].col+1; + + explain_indent(solnfile); + fprintf(solnfile, "Impasse for cell at row %d, col %d because cell at row %d, col %d removes last candidate\n", + chgd_row, chgd_col, clue_row, clue_col); + explain_current_markup(g); +} + +/****************************************/ +/* Explain naked and/or hidden singles. */ +/****************************************/ +static void explain_singleton(grid *g, int chgd, int mask, char *vdesc) +{ + int chgd_row, chgd_col, chgd_reg; + + chgd_row = map[chgd].row+1; + chgd_col = map[chgd].col+1; + chgd_reg = map[chgd].region+1; + + explain_indent(solnfile); + fprintf(solnfile, "Cell of region %d at row %d, col %d will only solve for %s in this %s\n", + chgd_reg, chgd_row, chgd_col, clues(mask), vdesc); + explain_solve_cell(g, chgd); +} + +/*********************************/ +/* Explain initial puzzle state. */ +/*********************************/ +static void explain_markup() +{ + fprintf(solnfile, "\n"); + explain_indent(solnfile); + fprintf(solnfile, "Assume all cells may contain any values in the range: [1 - 9]\n"); +} + +/************************/ +/* Explain given clues. */ +/************************/ +static void explain_given(int cell, char val) +{ + int cell_row, cell_col; + + cell_row = map[cell].row+1; + cell_col = map[cell].col+1; + + explain_indent(solnfile); + fprintf(solnfile, "Cell at row %d, col %d is given clue value %c\n", cell_row, cell_col, val); +} + +/*******************************************/ +/* Explain region/row/column interactions. */ +/*******************************************/ +static void explain_vector_elim(char *desc, int i, int cell, int val, int region) +{ + int cell_row, cell_col; + + cell_row = map[cell].row+1; + cell_col = map[cell].col+1; + + explain_indent(solnfile); + fprintf(solnfile, "Candidate %s removed from cell at row %d, col %d because it aligns along %s %d in region %d\n", + clues(val), cell_row, cell_col, desc, i+1, region+1); +} + +/******************************************************************/ +/* Explain the current impasse reached during vector elimination. */ +/******************************************************************/ +static void explain_vector_impasse(grid *g, char *desc, int i, int cell, int val, int region) +{ + int cell_row, cell_col; + + cell_row = map[cell].row+1; + cell_col = map[cell].col+1; + + explain_indent(solnfile); + fprintf(solnfile, "Impasse at cell at row %d, col %d because candidate %s aligns along %s %d in region %d\n", + cell_row, cell_col, clues(val), desc, i+1, region+1); + explain_current_markup(g); +} + +/*****************************************************************/ +/* Explain the current impasse reached during tuple elimination. */ +/*****************************************************************/ +static void explain_tuple_impasse(grid *g, char *desc, int elt, int tuple, int count, int bits) +{ + explain_indent(solnfile); + fprintf(solnfile, "Impasse in %s %d because too many (%d) cells have %d-valued %s\n", + desc, elt+1, count, bits, clues(tuple)); + explain_current_markup(g); +} + +/*********************************************************************/ +/* Explain the removal of a tuple of candidate solutions from a cell */ +/*********************************************************************/ +static void explain_tuple_elim(char *desc, int elt, int tuple, int cell) +{ + explain_indent(solnfile); + fprintf(solnfile, "Values of %s in %s %d removed from cell at row %d, col %d\n", + clues(tuple), desc, elt+1, map[cell].row+1, map[cell].col+1); + +} + +/**************************************************/ +/* Indicate that a viable solution has been found */ +/**************************************************/ +static void explain_soln_found(grid *g) +{ + char buf[90]; + + fprintf(solnfile, "\n"); + explain_indent(solnfile); + fprintf(solnfile, "Solution found: %s\n", format_answer(g, buf)); + print_grid(buf, solnfile); + fprintf(solnfile, "\n"); +} + +/***************************/ +/* Show the initial puzzle */ +/***************************/ +static void explain_grid(grid *g) +{ + char buf[90]; + + fprintf(solnfile, "Initial puzzle: %s\n", format_answer(g, buf)); + print_grid(buf, solnfile); + explain_current_markup(g); + fprintf(solnfile, "\n"); +} + +/*************************************************/ +/* Explain attempt at a trial and error solution */ +/*************************************************/ +static void explain_trial(int cell, int value) +{ + explain_indent(solnfile); + fprintf(solnfile, "Attempt trial where cell at row %d, col %d is assigned value %s\n", + map[cell].row+1, map[cell].col+1, clues(value)); +} + +/**********************************************/ +/* Explain back out of current trial solution */ +/**********************************************/ +static void explain_backtrack() +{ + if (lvl <= 1) return; + + explain_indent(solnfile); + fprintf(solnfile, "Backtracking\n\n"); +} + +#define EXPLAIN_MARKUP if (explain) explain_markup() +#define EXPLAIN_CURRENT_MARKUP(g) if (explain) explain_current_markup((g)) +#define EXPLAIN_GIVEN(cell, val) if (explain) explain_given((cell), (val)) +#define EXPLAIN_MARKUP_ELIM(g, chgd, clue) if (explain) explain_markup_elim((g), (chgd), (clue)) +#define EXPLAIN_MARKUP_SOLVE(g, cell) if (explain) explain_solve_cell((g), (cell)) +#define EXPLAIN_MARKUP_IMPASSE(g, chgd, clue) if (explain) explain_markup_impasse((g), (chgd), (clue)) +#define EXPLAIN_SINGLETON(g, chgd, mask, vdesc) if (explain) explain_singleton((g), (chgd), (mask), (vdesc)) +#define EXPLAIN_VECTOR_ELIM(desc, i, cell, v, r) if (explain) explain_vector_elim((desc), (i), (cell), (v), (r)) +#define EXPLAIN_VECTOR_IMPASSE(g, desc, i, cell, v, r) if (explain) explain_vector_impasse((g), (desc), (i), (cell), (v), (r)) +#define EXPLAIN_VECTOR_SOLVE(g, cell) if (explain) explain_solve_cell((g), (cell)) +#define EXPLAIN_TUPLE_IMPASSE(g, desc, j, c, count, i) if (explain) explain_tuple_impasse((g), (desc), (j), (c), (count), (i)) +#define EXPLAIN_TUPLE_ELIM(desc, j, c, cell) if (explain) explain_tuple_elim((desc), (j), (c), (cell)) +#define EXPLAIN_TUPLE_SOLVE(g, cell) if (explain) explain_solve_cell((g), (cell)) +#define EXPLAIN_SOLN_FOUND(g) if (explain) explain_soln_found((g)); +#define EXPLAIN_GRID(g) if (explain) explain_grid((g)); +#define EXPLAIN_TRIAL(cell, val) if (explain) explain_trial((cell), (val)); +#define EXPLAIN_BACKTRACK if (explain) explain_backtrack(); +#define EXPLAIN_INDENT(h) if (explain) explain_indent((h)) + +#else + +#define EXPLAIN_MARKUP +#define EXPLAIN_CURRENT_MARKUP(g) +#define EXPLAIN_GIVEN(cell, val) +#define EXPLAIN_MARKUP_ELIM(g, chgd, clue) +#define EXPLAIN_MARKUP_SOLVE(g, cell) +#define EXPLAIN_MARKUP_IMPASSE(g, chgd, clue) +#define EXPLAIN_SINGLETON(g, chgd, mask, vdesc); +#define EXPLAIN_VECTOR_ELIM(desc, i, cell, v, r) +#define EXPLAIN_VECTOR_IMPASSE(g, desc, i, cell, v, r) +#define EXPLAIN_VECTOR_SOLVE(g, cell) +#define EXPLAIN_TUPLE_IMPASSE(g, desc, j, c, count, i) +#define EXPLAIN_TUPLE_ELIM(desc, j, c, cell) +#define EXPLAIN_TUPLE_SOLVE(g, cell) +#define EXPLAIN_SOLN_FOUND(g) +#define EXPLAIN_GRID(g) +#define EXPLAIN_TRIAL(cell, val) +#define EXPLAIN_BACKTRACK +#define EXPLAIN_INDENT(h) + +#endif + + +/*****************************************************/ +/* Initialize a grid to an empty state. */ +/* At the start, all cells can have any value */ +/* so set all 9 lower order bits in each cell. */ +/* In effect, the 9x9 grid now has markup that */ +/* specifies that each cell can assume any value */ +/* of 1 through 9. */ +/*****************************************************/ + +static void init_grid(grid *g) +{ + int i; + + for (i = 0; i < PUZZLE_CELLS; i++) g->cell[i] = 0x01ff; + memset(g->cellflags, 0, PUZZLE_CELLS*sizeof(g->cellflags[0])); + g->exposed = 0; + g->givens = 0; + g->inc = 0; + g->maxlvl = 0; + g->score = 0; + g->solncount = 0; + g->reward = 1; + g->next = NULL; + g->tail = 0; + EXPLAIN_MARKUP; +} + +/*****************************************************/ +/* Convert a puzzle from the input format, */ +/* i.e. a string of 81 non-blank characters */ +/* with ASCII digits '1' thru '9' specified */ +/* for the givens, and non-numeric characters */ +/* for the remaining cells. The string, read */ +/* left-to-right fills the 9x9 Sudoku grid */ +/* in left-to-right, top-to-bottom order. */ +/*****************************************************/ + +static void cvt_to_grid(grid *g, char *game) +{ + int i; + + init_grid(g); + + for (i = 0; i < PUZZLE_CELLS; i++) { + if (is_given(game[i])) { + /* warning -- ASCII charset assumed */ + g->cell[i] = 1 << (game[i] - '1'); + g->cellflags[i] = GIVEN; + g->givens += 1; + g->solved[g->exposed++] = i; + EXPLAIN_GIVEN(i, game[i]); + } + } + EXPLAIN_GRID(g); +} + +/****************************************************************/ +/* Print the partially solved puzzle and all associated markup */ +/* in 9x9 fashion. */ +/****************************************************************/ + +static void diagnostic_grid(grid *g, FILE *h) +{ + int i, j, flag; + short c; + char line1[40], line2[40], line3[40], cbuf1[5], cbuf2[5], cbuf3[5], outbuf[PUZZLE_CELLS+1]; + + /* Sanity check */ + for (flag = 1, i = 0; flag && i < PUZZLE_CELLS; i++) { + if (bitcount(g->cell[i]) != 1) { + flag = 0; + } + } + + /* Don't need to print grid with diagnostic markup? */ + if (flag) { + format_answer(g, outbuf); + print_grid(outbuf, h); + fflush(h); + return; + } + + strcpy(cbuf1, " |"); + strcpy(cbuf2, cbuf1); + strcpy(cbuf3, cbuf1); + fprintf(h, "\n"); + + for (i = 0; i < PUZZLE_DIM; i++) { + + *line1 = *line2 = *line3 = 0; + + for (j = 0; j < PUZZLE_DIM; j++) { + + c = g->cell[row[i][j]]; + + if (bitcount(c) == 1) { + strcpy(cbuf1, " |"); + strcpy(cbuf2, cbuf1); + strcpy(cbuf3, cbuf1); + cbuf2[1] = symtab[c]; + } + else { + if (c & 1) cbuf1[0] = '*'; else cbuf1[0] = '.'; + if (c & 2) cbuf1[1] = '*'; else cbuf1[1] = '.'; + if (c & 4) cbuf1[2] = '*'; else cbuf1[2] = '.'; + if (c & 8) cbuf2[0] = '*'; else cbuf2[0] = '.'; + if (c & 16) cbuf2[1] = '*'; else cbuf2[1] = '.'; + if (c & 32) cbuf2[2] = '*'; else cbuf2[2] = '.'; + if (c & 64) cbuf3[0] = '*'; else cbuf3[0] = '.'; + if (c & 128) cbuf3[1] = '*'; else cbuf3[1] = '.'; + if (c & 256) cbuf3[2] = '*'; else cbuf3[2] = '.'; + } + + strcat(line1, cbuf1); + strcat(line2, cbuf2); + strcat(line3, cbuf3); + } + + EXPLAIN_INDENT(h); + fprintf(h, "+---+---+---+---+---+---+---+---+---+\n"); + EXPLAIN_INDENT(h); + fprintf(h, "|%s\n", line1); + EXPLAIN_INDENT(h); + fprintf(h, "|%s\n", line2); + EXPLAIN_INDENT(h); + fprintf(h, "|%s\n", line3); + } + EXPLAIN_INDENT(h); + fprintf(h, "+---+---+---+---+---+---+---+---+---+\n"); fflush(h); +} + +/***********************************************************************/ +/* Validate that a sudoku grid contains a valid solution. Return 1 if */ +/* true, 0 if false. If the verbose argument is non-zero, then print */ +/* reasons for invalidating the solution to stderr. */ +/***********************************************************************/ + +static int validate(grid *g, int verbose) +{ + int i, j, regmask, rowmask, colmask, flag = 1; + + /* Sanity check */ + for (i = 0; i < PUZZLE_CELLS; i++) { + if (bitcount(g->cell[i]) != 1) { + if (verbose) { + fprintf(rejects, "Cell %d at row %d, col %d has no unique soln.\n", 1+i, 1+map[i].row, 1+map[i].col); fflush(rejects); + flag = 0; + } else return 0; + } + } + + /* Check rows */ + for (i = 0; i < PUZZLE_DIM; i++) { + for (rowmask = j = 0; j < PUZZLE_DIM; j++) { + if (bitcount(g->cell[row[i][j]]) == 1) rowmask |= g->cell[row[i][j]]; + } + if (rowmask != 0x01ff) { + if (verbose) { + fprintf(rejects, "Row %d is inconsistent.\n", 1+i); fflush(rejects); + flag = 0; + } else return 0; + } + } + + /* Check columns */ + for (i = 0; i < PUZZLE_DIM; i++) { + for (colmask = j = 0; j < PUZZLE_DIM; j++) { + if (bitcount(g->cell[col[i][j]]) == 1) colmask |= g->cell[col[i][j]]; + } + if (colmask != 0x01ff) { + if (verbose) { + fprintf(rejects, "Column %d is inconsistent.\n", 1+i); fflush(rejects); + flag = 0; + } else return 0; + } + } + + /* Check 3x3 regions */ + for (i = 0; i < PUZZLE_DIM; i++) { + for (regmask = j = 0; j < PUZZLE_DIM; j++) { + if (bitcount(g->cell[region[i][j]]) == 1) regmask |= g->cell[region[i][j]]; + } + if (regmask != 0x01ff) { + if (verbose) { + fprintf(rejects, "Region %d is inconsistent.\n", 1+i); fflush(rejects); + flag = 0; + } else return 0; + } + } + + return flag; +} + +/********************************************************************************/ +/* This function uses the cells with unique values, i.e. the given */ +/* or subsequently discovered solution values, to eliminate said values */ +/* as candidates in other as yet unsolved cells in the associated */ +/* rows, columns, and 3x3 regions. */ +/* */ +/* The function has three possible return values: */ +/* NOCHANGE - Markup did not change during the last pass, */ +/* CHANGE - Markup was modified, and */ +/* STUCK - Markup results are invalid, i.e. a cell has no candidate values */ +/********************************************************************************/ + +static int mark_cells(grid *g) +{ + int i, chgflag, bc; + int const *r, *c, *reg; + short elt, mask, before; + + + chgflag = NOCHANGE; + + while (g->tail < g->exposed) { + + elt = g->solved[g->tail++]; + + r = row[map[elt].row]; + c = col[map[elt].col]; + reg = region[map[elt].region]; + + mask = ~g->cell[elt]; + + for (i = 0; i < PUZZLE_DIM; i++) { + + if (r[i] != elt) { + + /* Get the cell value */ + before = g->cell[r[i]]; + + /* Eliminate this candidate value whilst preserving other candidate values */ + g->cell[r[i]] &= mask; + + /* Did the cell change value? */ + if (before != g->cell[r[i]]) { + + chgflag |= CHANGE; /* Flag that puzzle markup was changed */ + g->score += g->inc; /* More work means higher scoring */ + + if (!(bc = bitcount(g->cell[r[i]]))) { + EXPLAIN_MARKUP_IMPASSE(g, r[i], elt); + return STUCK; /* Crap out if no candidates remain */ + } + + EXPLAIN_MARKUP_ELIM(g, r[i], elt); + + /* Check if we solved for this cell, i.e. bit count indicates a unique value */ + if (bc == 1) { + g->cellflags[r[i]] = FOUND; /* Mark cell as found */ + g->score += g->reward; /* Add to puzzle score */ + g->solved[g->exposed++] = r[i]; + EXPLAIN_MARKUP_SOLVE(g, r[i]); + } + } + } + + if (c[i] != elt) { + + /* Get the cell value */ + before = g->cell[c[i]]; + + /* Eliminate this candidate value whilst preserving other candidate values */ + g->cell[c[i]] &= mask; + + /* Did the cell change value? */ + if (before != g->cell[c[i]]) { + + chgflag |= CHANGE; /* Flag that puzzle markup was changed */ + g->score += g->inc; /* More work means higher scoring */ + + if (!(bc = bitcount(g->cell[c[i]]))) { + EXPLAIN_MARKUP_IMPASSE(g, c[i], elt); + return STUCK; /* Crap out if no candidates remain */ + } + + EXPLAIN_MARKUP_ELIM(g, c[i], elt); + + /* Check if we solved for this cell, i.e. bit count indicates a unique value */ + if (bc == 1) { + g->cellflags[c[i]] = FOUND; /* Mark cell as found */ + g->score += g->reward; /* Add to puzzle score */ + g->solved[g->exposed++] = c[i]; + EXPLAIN_MARKUP_SOLVE(g, c[i]); + } + } + } + + if (reg[i] != elt) { + + /* Get the cell value */ + before = g->cell[reg[i]]; + + /* Eliminate this candidate value whilst preserving other candidate values */ + g->cell[reg[i]] &= mask; + + /* Did the cell change value? */ + if (before != g->cell[reg[i]]) { + + chgflag |= CHANGE; /* Flag that puzzle markup was changed */ + g->score += g->inc; /* More work means higher scoring */ + + if (!(bc = bitcount(g->cell[reg[i]]))) { + EXPLAIN_MARKUP_IMPASSE(g, reg[i], elt); + return STUCK; /* Crap out if no candidates remain */ + } + + EXPLAIN_MARKUP_ELIM(g, reg[i], elt); + + /* Check if we solved for this cell, i.e. bit count indicates a unique value */ + if (bc == 1) { + g->cellflags[reg[i]] = FOUND; /* Mark cell as found */ + g->score += g->reward; /* Add to puzzle score */ + g->solved[g->exposed++] = reg[i]; + EXPLAIN_MARKUP_SOLVE(g, reg[i]); + } + } + } + + } + } + + return chgflag; +} + + +/*******************************************************************/ +/* Identify and "solve" all cells that, by reason of their markup, */ +/* can only assume one specific value, i.e. the cell is the only */ +/* one in a row/column/region (specified by vector) that is */ +/* able to assume a particular value. */ +/* */ +/* The function has two possible return values: */ +/* NOCHANGE - Markup did not change during the last pass, */ +/* CHANGE - Markup was modified. */ +/*******************************************************************/ + +static int find_singletons(grid *g, int const *vector, char *vdesc) +{ + int i, j, mask, hist[PUZZLE_DIM], value[PUZZLE_DIM], found = NOCHANGE; + + /* We are going to create a histogram of cell candidate values */ + /* for the specified cell vector (row/column/region). */ + /* First set all buckets to zero. */ + memset(hist, 0, sizeof(hist[0])*PUZZLE_DIM); + + /* For each cell in the vector... */ + for (i = 0; i < PUZZLE_DIM; i++) { + + /* For each possible candidate value... */ + for (mask = 1, j = 0; j < PUZZLE_DIM; j++) { + + /* If the cell may possibly assume this value... */ + if (g->cell[vector[i]] & mask) { + + value[j] = vector[i]; /* Save the cell coordinate */ + hist[j] += 1; /* Bump bucket in histogram */ + } + + mask <<= 1; /* Next candidate value */ + } + } + + /* Examine each bucket in the histogram... */ + for (mask = 1, i = 0; i < PUZZLE_DIM; i++) { + + /* If the bucket == 1 and the cell is not already solved, */ + /* then the cell has a unique solution specified by "mask" */ + if (hist[i] == 1 && !g->cellflags[value[i]]) { + + found = CHANGE; /* Indicate that markup has been changed */ + g->cell[value[i]] = mask; /* Assign solution value to cell */ + g->cellflags[value[i]] = FOUND; /* Mark cell as solved */ + g->score += g->reward; /* Bump puzzle score */ + g->solved[g->exposed++] = value[i]; + EXPLAIN_SINGLETON(g, value[i], mask, vdesc); + } + + mask <<= 1; /* Get next candidate value */ + } + + return found; +} + + +/*******************************************************************/ +/* Find all cells with unique solutions (according to markup) */ +/* and mark them as found. Do this for each row, column, and */ +/* region. */ +/* */ +/* The function has two possible return values: */ +/* NOCHANGE - Markup did not change during the last pass, */ +/* CHANGE - Markup was modified. */ +/*******************************************************************/ + +static int eliminate_singles(grid *g) +{ + int i, found = NOCHANGE; + + /* Do rows */ + for (i = 0; i < PUZZLE_DIM; i++) { + found |= find_singletons(g, row[i], "row"); + } + + /* Do columns */ + for (i = 0; i < PUZZLE_DIM; i++) { + found |= find_singletons(g, col[i], "column"); + } + + /* Do regions */ + for (i = 0; i < PUZZLE_DIM; i++) { + found |= find_singletons(g, region[i], "region"); + } + + return found; +} + +/********************************************************************************/ +/* Solves simple puzzles, i.e. single elimination */ +/* */ +/* The function has three possible return values: */ +/* NOCHANGE - Markup did not change during the last pass, */ +/* CHANGE - Markup was modified, and */ +/* STUCK - Markup results are invalid, i.e. a cell has no candidate values */ +/********************************************************************************/ +static int simple_solver(grid *g) +{ + int flag = NOCHANGE; + + /* Mark the unsolved cells with candidate solutions based upon the current set of "givens" and solved cells */ + while ((flag |= mark_cells(g)) == CHANGE) { + + g->inc = 1; /* After initial markup, we start scoring for additional markup work */ + + EXPLAIN_CURRENT_MARKUP(g); + + /* Continue to eliminate cells with unique candidate solutions from the game until */ + /* elimination and repeated markup efforts produce no changes in the remaining */ + /* candidate solutions. */ + if (eliminate_singles(g) == NOCHANGE) break; + + EXPLAIN_CURRENT_MARKUP(g); + } + + return flag; +} + +/************************************************************************************/ +/* Test a region to see if the candidate solutions for a paticular number */ +/* are confined to one row or column, and if so, eliminate */ +/* their occurences in the remainder of the given row or column. */ +/* */ +/* The function has three possible return values: */ +/* NOCHANGE - Markup did not change during the last pass, */ +/* CHANGE - Markup was modified, and */ +/* STUCK - Markup results are invalid, i.e. a cell has no candidate values */ +/************************************************************************************/ + +static int region_vector_elim(grid *g, int region_no, int num) +{ + int i, j, r, c, mask, t, found; + short rowhist[PUZZLE_DIM], colhist[PUZZLE_DIM]; + + /* Init */ + found = NOCHANGE; + memset(rowhist, 0, sizeof(rowhist[0])*PUZZLE_DIM); + memset(colhist, 0, sizeof(colhist[0])*PUZZLE_DIM); + + mask = 1 << num; + + /* Create histograms for row and column placements for the value being checked */ + for (i = 0; i < PUZZLE_DIM; i++) { + j = region[region_no][i]; + if ((g->cell[j] & mask)) { + rowhist[map[j].row] += 1; + colhist[map[j].col] += 1; + } + } + + /* Figure out if this number lies in only one row or column */ + + /* Check rows first*/ + r = c = -1; + for (i = 0; i < PUZZLE_DIM; i++) { + if (rowhist[i]) { + if (r < 0) { + r = i; + } + else { + r = -1; + break; + } + } + } + + /* Now check columns */ + for (i = 0; i < PUZZLE_DIM; i++) { + if (colhist[i]) { + if (c < 0) { + c = i; + } + else { + c = -1; + break; + } + } + } + + /* If the number is only in one row, then eliminate this number from the cells in the row outside of this region */ + if (r >= 0) { + for (i = 0; i < PUZZLE_DIM; i++) { + j = row[r][i]; + if (map[j].region != region_no && !g->cellflags[j]) { + t = g->cell[j]; + if ((g->cell[j] &= ~mask) == 0) { + EXPLAIN_VECTOR_IMPASSE(g, "row", r, j, mask, region_no); + g->score += 10; + return STUCK; + } + if (t != g->cell[j]) { + found = CHANGE; + g->score += g->inc; + EXPLAIN_VECTOR_ELIM("row", r, j, mask, region_no); + if (bitcount(g->cell[j]) == 1) { + g->cellflags[j] = FOUND; + g->score += g->reward; + g->solved[g->exposed++] = j; + EXPLAIN_VECTOR_SOLVE(g, j); + } + } + } + } + } + + /* If the number is only in one column, then eliminate this number from the cells in the column outside of this region */ + else if (c >= 0) { + for (i = 0; i < PUZZLE_DIM; i++) { + j = col[c][i]; + if (map[j].region != region_no && !g->cellflags[j]) { + t = g->cell[j]; + if ((g->cell[j] &= ~mask) == 0) { + EXPLAIN_VECTOR_IMPASSE(g, "column", c, j, mask, region_no); + g->score += 10; + return STUCK; + } + if (t != g->cell[j]) { + found = CHANGE; + g->score += g->inc; + EXPLAIN_VECTOR_ELIM("column", c, j, mask, region_no); + if (bitcount(g->cell[j]) == 1) { + g->cellflags[j] = FOUND; + g->score += g->reward; + g->solved[g->exposed++] = j; + EXPLAIN_VECTOR_SOLVE(g, j); + } + } + } + } + } + + if (found == CHANGE) { + g->score += 10; /* Bump score for sucessfully invoking this rule */ + } + + return found; +} + +/**********************************************************************************/ +/* Test all regions to see if the possibilities for a number */ +/* are confined to specific rows or columns, and if so, eliminate */ +/* the occurence of candidate solutions from the remainder of the */ +/* specified row or column. */ +/* */ +/* The function has three possible return values: */ +/* NOCHANGE - Markup did not change during the last pass, */ +/* CHANGE - Markup was modified, and */ +/* STUCK - Markup results are invalid, i.e. a cell has no candidate values */ +/**********************************************************************************/ + +static int vector_elimination(grid *g) +{ + int i, j, rc; + + /* For each region... */ + for (rc = NOCHANGE, i = 0; i < PUZZLE_DIM && rc != STUCK; i++) { + + /* For each digit... */ + for (j = 0; j < PUZZLE_DIM && rc != STUCK; j++) { + + /* Eliminate candidates outside of regions when a particular */ + /* candidate value aligns itself to a row or column within */ + /* a 3x3 region. */ + rc |= region_vector_elim(g, i, j); + } + } + + return rc; +} + +/**********************************************************************************/ +/* This function implements the rule that when a subset of cells */ +/* in a row/column/region contain matching subsets of candidate */ +/* solutions, i.e. 2 matching possibilities for 2 cells, 3 */ +/* matching possibilities for 3 cells, etc., then those */ +/* candidates may be eliminated from the other cells in the */ +/* row, column, or region. */ +/* */ +/* The function has three possible return values: */ +/* NOCHANGE - Markup did not change during the last pass, */ +/* CHANGE - Markup was modified, and */ +/* STUCK - Markup results are invalid, i.e. a cell has no candidate values */ +/**********************************************************************************/ + +static int elim_matches(grid *g, int const *cell_list, char *desc, int ndx) +{ + int i, j, k, e, count, rc, flag; + short c, mask, tmp, elts[PUZZLE_DIM], eliminated[PUZZLE_DIM]; + static int counts[1<cell[k]; /* Copy original cell candidates */ + + if (bitcount(g->cell[k]) == i) { + counts[g->cell[k]] += 1; /* The bucket records the number of cells with this subset */ + } + } + + /* For each cell in the list... */ + for (e = j = 0; j < PUZZLE_DIM; j++) { + + c = g->cell[cell_list[j]]; /* Get cell's candidates */ + + /* Check to see if we've already eliminated this subset */ + for (k = 0; k < e; k++) + if (c == eliminated[k]) break; + if (e && k < e) continue; + + /* Get count from histogram bucket */ + count = (int) (counts[c]); + + /* If too few solution candidates for the number of cells, then we're stuck */ + if (count > i) { + EXPLAIN_TUPLE_IMPASSE(g, desc, ndx, c, count, i); + /* Clean up static array */ + for (k = 0; k < 9; k++) counts[elts[k]] = 0; + g->score += 10; + return STUCK; + } + + /* Do candidate and cell counts match? */ + if (count == i) { + + /* Compute mask used to eliminate candidates from other cells */ + mask = ~c; + + /* Record (for later) the values being eliminated */ + eliminated[e++] = c; + + /* Eliminate candidates from the other cells in the list */ + + /* For each cell... */ + for (k = 0; k < PUZZLE_DIM; k++) { + + /* If the cell candidates do not exactly match the current subset... */ + if (c != g->cell[cell_list[k]] && !g->cellflags[cell_list[k]]) { + + /* Get cell candidates */ + tmp = g->cell[cell_list[k]]; + + /* Eliminate candidates with our mask */ + g->cell[cell_list[k]] &= mask; + + /* Did the elimination change the candidates? */ + if (tmp != g->cell[cell_list[k]]) { + + /* Note the change and bump the score */ + flag = CHANGE; + g->score += i; + + EXPLAIN_TUPLE_ELIM(desc, ndx, c, cell_list[k]); + + /* Did we solve the cell under consideration? */ + if (bitcount(g->cell[cell_list[k]]) == 1) { + + /* Mark cell as found and bump the score */ + g->cellflags[cell_list[k]] = FOUND; + g->score += g->reward; + g->solved[g->exposed++] = cell_list[k]; + EXPLAIN_TUPLE_SOLVE(g, cell_list[k]); + } + } + } + } + } + } + + /* Cleanup the static histogram array */ + for (j = 0; j < PUZZLE_DIM; j++) counts[elts[j]] = 0; + + rc |= flag; + } + + return rc; +} + +/**********************************************************************************/ +/* Eliminate subsets from rows, columns, and regions. */ +/* */ +/* The function has three possible return values: */ +/* NOCHANGE - Markup did not change during the last pass, */ +/* CHANGE - Markup was modified, and */ +/* STUCK - Markup results are invalid, i.e. a cell has no candidate values */ +/**********************************************************************************/ + +static int mult_elimination(grid *g) +{ + int i, rc = NOCHANGE; + + /* Eliminate subsets from rows */ + for (i = 0; i < PUZZLE_DIM; i++) { + rc |= elim_matches(g, row[i], "row", i); + } + + /* Eliminate subsets from columns */ + for (i = 0; i < PUZZLE_DIM; i++) { + rc |= elim_matches(g, col[i], "column", i); + } + + /* Eliminate subsets from regions */ + for (i = 0; i < PUZZLE_DIM; i++) { + rc |= elim_matches(g, region[i], "region", i); + } + + return rc; +} + +/**************************************************/ +/* Entry point to the recursive solver algorithm. */ +/**************************************************/ +static int rsolve(grid *g, return_soln soln_callback) +{ + int i, j, min, c, weight, mask, flag = 0; + grid mygrid; + + /* Keep track of recursive depth */ + lvl += 1; + if (lvl > g->maxlvl) g->maxlvl = lvl; + + for (;;) { + + /* Attempt a simple solution */ + if (simple_solver(g) == STUCK) break; + + /* Check for solution */ + if (g->exposed >= PUZZLE_CELLS) break; + + g->reward += 2; /* Bump reward as we graduate to more "advanced" solving techniques */ + + /* Eliminate tuples */ + if ((flag = mult_elimination(g)) == CHANGE) { + EXPLAIN_CURRENT_MARKUP(g); + continue; + } + + /* Check if impasse */ + if (flag == STUCK) break; + + /* Check for solution */ + if (g->exposed >= PUZZLE_CELLS) break; + + /* Eliminate clues aligned within regions from exterior cells in rows or columns */ + if ((flag = vector_elimination(g)) == CHANGE) { + EXPLAIN_CURRENT_MARKUP(g); + continue; + } + + /* Check if impasse */ + if (flag == STUCK) break; + + /* Check for solution */ + if (g->exposed >= PUZZLE_CELLS) break; + + g->reward += 5; /* Bump reward as we are about to start trial soutions */ + + /* Attempt a trial solution */ + memcpy(&mygrid, g, sizeof(grid)); /* Make working copy of puzzle */ + + /* Find the first cell with the smallest number of alternatives */ + for (weight= 0, c = -1, min = PUZZLE_DIM, i = 0; i < PUZZLE_CELLS; i++) { + if (!mygrid.cellflags[i]) { + j = bitcount(mygrid.cell[i]); + weight += 1; + if (j < min) { + min = j; + c = i; + } + } + } + + mygrid.score += weight; /* Add penalty to score */ + + /* Cell at index 'c' will be our starting point */ + if (c >= 0) for (mask = 1, i = 0; i < PUZZLE_DIM; i++) { + + /* Is this a candidate? */ + if (mask & g->cell[c]) { + + EXPLAIN_TRIAL(c, mask); + + mygrid.score += (int)(((50.0 * lvl * weight) / (double)(PUZZLE_CELLS)) + 0.5); /* Add'l penalty */ + + /* Try one of the possible candidates for this cell */ + mygrid.cell[c] = mask; + mygrid.cellflags[c] = FOUND; + mygrid.solved[mygrid.exposed++] = c; + + EXPLAIN_CURRENT_MARKUP(&mygrid); + flag = rsolve(&mygrid, soln_callback); /* Recurse with working copy of puzzle */ + + /* Did we find a solution? */ + if (flag == FOUND && !enumerate_all) { + EXPLAIN_BACKTRACK; + lvl -= 1; + return FOUND; + } + + /* Preserve score, solution count and recursive depth as we back out of recursion */ + g->score = mygrid.score; + g->solncount = mygrid.solncount; + g->maxlvl = mygrid.maxlvl; + memcpy(&mygrid, g, sizeof(grid)); + } + mask <<= 1; /* Get next possible candidate */ + } + + break; + } + + if (g->exposed == PUZZLE_CELLS && validate(g, 0)) { + soln_callback(g); + g->solncount += 1; + EXPLAIN_SOLN_FOUND(g); + EXPLAIN_BACKTRACK; + lvl -= 1; + flag = FOUND; + } else { + EXPLAIN_BACKTRACK; + lvl -= 1; + flag = STUCK; + if (!lvl && !g->solncount) validate(g, 1); /* Print verbose diagnostic for insoluble puzzle */ + } + + return flag; +} + +/*****************************************************************/ +/* Add a puzzle solution to the singly linked list of solutions. */ +/* Crap out if no memory available. */ +/*****************************************************************/ + +static int add_soln(grid *g) +{ + grid *tmp; + + if ((tmp = malloc(sizeof(grid))) == NULL) { + fprintf(stderr, "Out of memory.\n"); + exit(1); + } + memcpy(tmp, g, sizeof(grid)); + tmp->next = soln_list; + soln_list = tmp; + return 0; +} + +/************************************/ +/* Print hints as to command usage. */ +/************************************/ + +static void usage() +{ + fprintf(stderr, "Usage:\n\t%s {-p puzzle | -f } [-o ]\n", myname); + fprintf(stderr, "\t\t[-r ] [-1][-a][-c][-G][-g][-l][-m][-n][-s]\n"); + fprintf(stderr, "where:\n\t-1\tSearch for first solution, otherwise all solutions are returned\n" + "\t-a\tRequests that the answer (solution) be printed\n" + "\t-c\tPrint a count of solutions for each puzzle\n" + "\t-d\tPrint the recursive trial depth required to solve the puzzle\n" +#ifdef EXPLAIN + "\t-e\tPrint a step-by-step explanation of the solution(s)\n" +#endif + "\t-f\tTakes an argument which specifes an input file\n\t\tcontaining one or more unsolved puzzles (default: stdin)\n" + "\t-G\tPrint the puzzle solution(s) in a 9x9 grid format\n" + "\t-g\tPrint the number of given clues\n" + "\t-m\tPrint an octal mask for the puzzle givens\n" + "\t-n\tNumber each result\n" + "\t-o\tSpecifies an output file for the solutions (default: stdout)\n" + "\t-p\tTakes an argument giving a single inline puzzle to be solved\n" + "\t-r\tSpecifies an output file for unsolvable puzzles\n\t\t(default: stderr)\n" + "\t-s\tPrint the puzzle's score or difficulty rating\n" + "\t-?\tPrint usage information\n\n"); + fprintf(stderr, "The return code is zero if all puzzles had unique solutions,\n" + "(or have one or more solutions when -1 is specified) and non-zero\n" + "when no unique solution exists.\n"); +} + +/********************************************************/ +/* Print the puzzle as an 81 character string of digits */ +/********************************************************/ + +static char *format_answer(grid *g, char *outbuf) +{ + int i; + + for (i = 0; i < PUZZLE_CELLS; i++) + outbuf[i] = symtab[g->cell[i]]; + outbuf[i] = 0; + + return outbuf; +} + +/*******************************************/ +/* Print the puzzle as a standard 9x9 grid */ +/*******************************************/ + +static void print_grid(char *sud, FILE *h) +{ + + fprintf(h, "\n"); + EXPLAIN_INDENT(h); + fprintf(h, "+---+---+---+\n"); + + EXPLAIN_INDENT(h); + fprintf(h, "|%*.*s|%*.*s|%*.*s|\n", PUZZLE_ORDER, PUZZLE_ORDER, sud, PUZZLE_ORDER, PUZZLE_ORDER, sud+3, PUZZLE_ORDER, PUZZLE_ORDER, sud+6); + EXPLAIN_INDENT(h); + fprintf(h, "|%*.*s|%*.*s|%*.*s|\n", PUZZLE_ORDER, PUZZLE_ORDER, sud+9, PUZZLE_ORDER, PUZZLE_ORDER, sud+12, PUZZLE_ORDER, PUZZLE_ORDER, sud+15); + EXPLAIN_INDENT(h); + fprintf(h, "|%*.*s|%*.*s|%*.*s|\n", PUZZLE_ORDER, PUZZLE_ORDER, sud+18, PUZZLE_ORDER, PUZZLE_ORDER, sud+21, PUZZLE_ORDER, PUZZLE_ORDER, sud+24); + + EXPLAIN_INDENT(h); + fprintf(h, "+---+---+---+\n"); + + EXPLAIN_INDENT(h); + fprintf(h, "|%*.*s|%*.*s|%*.*s|\n", PUZZLE_ORDER, PUZZLE_ORDER, sud+27, PUZZLE_ORDER, PUZZLE_ORDER, sud+30, PUZZLE_ORDER, PUZZLE_ORDER, sud+33); + EXPLAIN_INDENT(h); + fprintf(h, "|%*.*s|%*.*s|%*.*s|\n", PUZZLE_ORDER, PUZZLE_ORDER, sud+36, PUZZLE_ORDER, PUZZLE_ORDER, sud+39, PUZZLE_ORDER, PUZZLE_ORDER, sud+42); + EXPLAIN_INDENT(h); + fprintf(h, "|%*.*s|%*.*s|%*.*s|\n", PUZZLE_ORDER, PUZZLE_ORDER, sud+45, PUZZLE_ORDER, PUZZLE_ORDER, sud+48, PUZZLE_ORDER, PUZZLE_ORDER, sud+51); + + EXPLAIN_INDENT(h); + fprintf(h, "+---+---+---+\n"); + + EXPLAIN_INDENT(h); + fprintf(h, "|%*.*s|%*.*s|%*.*s|\n", PUZZLE_ORDER, PUZZLE_ORDER, sud+54, PUZZLE_ORDER, PUZZLE_ORDER, sud+57, PUZZLE_ORDER, PUZZLE_ORDER, sud+60); + EXPLAIN_INDENT(h); + fprintf(h, "|%*.*s|%*.*s|%*.*s|\n", PUZZLE_ORDER, PUZZLE_ORDER, sud+63, PUZZLE_ORDER, PUZZLE_ORDER, sud+66, PUZZLE_ORDER, PUZZLE_ORDER, sud+69); + EXPLAIN_INDENT(h); + fprintf(h, "|%*.*s|%*.*s|%*.*s|\n", PUZZLE_ORDER, PUZZLE_ORDER, sud+72, PUZZLE_ORDER, PUZZLE_ORDER, sud+75, PUZZLE_ORDER, PUZZLE_ORDER, sud+78); + + EXPLAIN_INDENT(h); + fprintf(h, "+---+---+---+\n"); +} + +/*****************************************************/ +/* Based upon the Left-to-Right-Top-to-Bottom puzzle */ +/* presented in "sbuf", create a 27 octal digit */ +/* mask of the givens in the 28 character buffer */ +/* pointed to by "mbuf." Return a pointer to mbuf. */ +/*****************************************************/ + +static char *cvt_to_mask(char *mbuf, char *sbuf) +{ + char *mask_buf = mbuf; + static const char *maskchar = "01234567"; + int i, m; + + mask_buf[PUZZLE_DIM*3] = 0; + for (i = 0; i < PUZZLE_CELLS; i += 3) { + m = 0; + if (is_given(sbuf[i])) { + m |= 4; + } + else { + sbuf[i] = '0'; + } + if (is_given(sbuf[i+1])) { + m |= 2; + } + else { + sbuf[i+1] = '0'; + } + if (is_given(sbuf[i+2])) { + m |= 1; + } + else { + sbuf[i+2] = '0'; + } + *mask_buf++ = maskchar[m]; + } + return mbuf; +} + +/*******************/ +/* Mainline logic. */ +/*******************/ + +int dupree_solver(int32_t *scorep,char *puzzle) +{ + int argc; char *argv[4]; + int i, rc, bog, count, solved, unsolved, solncount=0, flag, prt_count, prt_num, prt_score, prt_answer, prt_depth, prt_grid, prt_mask, prt_givens, prt, len; + char *infile=0, *outfile=0, *rejectfile=0, inbuf[128], outbuf[128], mbuf[28]; + grid g, *s=0; + FILE *h=0; + soln_list = NULL; + /* Get our command name from invoking command line */ + if ((myname = strrchr(argv[0], '/')) == NULL) + myname = argv[0]; + else + myname++; + /*argc = 3; + argv[1] = "-p"; + argv[2] = puzzle; + argv[3] = 0;*/ + /* Print sign-on message to console */ + //fprintf(stderr, "%s version %s\n", myname, VERSION); fflush(stderr); + argc = 1; + /* Init */ + h = 0;//stdin; + solnfile = stdout; + rejects = stderr; + rejectfile = infile = outfile = NULL; + rc = bog = prt_mask = prt_grid = prt_score = prt_depth = prt_answer = prt_count = prt_num = prt_givens = 0; + *inbuf = 0; +#ifdef skip + /* Parse command line options */ + while ((opt = getopt(argc, argv, OPTIONS)) != -1) { + switch (opt) { + case '1': + enumerate_all = 0; /* only find first soln */ + break; + case 'a': + prt_answer = 1; /* print solution */ + break; + case 'c': + prt_count = 1; /* number solutions */ + break; + case 'd': + prt_depth = 1; + break; +#ifdef EXPLAIN + case 'e': + explain = 1; + break; +#endif + case 'f': + if (*inbuf) { // -p and -f options are mutually exclusive + fprintf(stderr, "The -p and -f options are mutually exclusive\n"); + usage(); + exit(1); + } + infile = optarg; // get name of input file + break; + case 'G': + prt_grid = 1; + break; + case 'g': + prt_givens = 1; + break; + case 'm': + prt_mask = 1; + break; + case 'n': + prt_num = 1; + break; + case 'o': + outfile = optarg; + break; + case 'p': + if (infile) { + fprintf(stderr, "The -p and -f options are mutually exclusive\n"); + usage(); + exit(1); + } + if (strlen(optarg) == PUZZLE_CELLS) { + strcpy(inbuf, optarg); + } + else { + fprintf(stderr, "Invalid puzzle specified: %s\n", optarg); + usage(); + exit(1); + } + h = NULL; + break; + case 'r': + rejectfile = optarg; + break; + case 's': + prt_score = 1; + break; + default: + case '?': + usage(); + exit(1); + } + } +#endif + prt_answer = 1; /* print solution */ + //prt_count = 1; /* number solutions */ + prt_score = 1; + prt_givens = 1; + prt_num = 1; + /* Set prt flag if we're printing anything at all */ + prt = prt_mask | prt_grid | prt_score | prt_depth | prt_answer | prt_num | prt_givens; + + /* Anthing else on the command line is bogus */ + if (argc > optind) { + fprintf(stderr, "Extraneous args: "); + for (i = optind; i < argc; i++) { + fprintf(stderr, "%s ", argv[i]); + } + fprintf(stderr, "\n\n"); + usage(); + exit(1); + } + + if (!enumerate_all && prt_score) { + fprintf(stderr, "Scoring is meaningless when multi-solution mode is disabled.\n"); + } + + if (rejectfile && !(rejects = fopen(rejectfile, "w"))) { + fprintf(stderr, "Failed to open reject output file: %s\n", rejectfile); + exit(1); + } + + if (outfile && !(solnfile = fopen(outfile, "w"))) { + fprintf(stderr, "Failed to open solution output file: %s\n", outfile); + exit(1); + } + + /*if (infile && strcmp(infile, "-") && !(h = fopen(infile, "r"))) { + fprintf(stderr, "Failed to open input game file: %s\n", infile); + exit(1); + } + if (h) fgets(inbuf, 128, h);*/ + strcpy(inbuf,puzzle); + count = solved = unsolved = 0; + //printf("inbuf.(%s)\n",inbuf); + while (*inbuf) { + + if ((len = (int32_t)strlen(inbuf)) && inbuf[len-1] == '\n') { + len -= 1; + inbuf[len] = 0; + } + + count += 1; + if (len != PUZZLE_CELLS) { + fprintf(rejects, "%d: %s bogus puzzle format\n", count, inbuf); fflush(rejects); + *inbuf = 0; + bog += 1; + if (h) fgets(inbuf, 128, h); + continue; + } + + cvt_to_grid(&g, inbuf); + if (g.givens < 17) { + fprintf(rejects, "%d: %*.*s bogus puzzle has less than 17 givens\n", count, PUZZLE_CELLS, PUZZLE_CELLS, inbuf); fflush(rejects); + *inbuf = 0; + bog += 1; + if (h) fgets(inbuf, 128, h); + continue; + } + + for (s = soln_list; s;) { + s = soln_list->next; + free(soln_list); + soln_list = s; + } + + flag = rsolve(&g, add_soln); + if (soln_list) { + solved++; + for (solncount = 0, s = soln_list; s; s = s->next) { + solncount += 1; + if (prt_num) { + char nbuf[32]; + if (!enumerate_all) + sprintf(nbuf, "%d: ", count); + else + sprintf(nbuf, "%d:%d ", count, solncount); + fprintf(solnfile, "%-s", nbuf); + } + if (solncount > 1 || !enumerate_all) g.score = 0; + if (prt_score) fprintf(solnfile, "score: %-7d ", g.score); + if (prt_depth) fprintf(solnfile, "depth: %-3d ", g.maxlvl); + if (prt_answer || prt_grid) format_answer(s, outbuf); + if (prt_answer) fprintf(solnfile, "%s", outbuf); + if (prt_mask) fprintf(solnfile, " %s", cvt_to_mask(mbuf, inbuf)); + if (prt_givens) fprintf(solnfile, " %d", g.givens); + if (prt_grid) print_grid(outbuf, solnfile); + if (prt) fprintf(solnfile, "\n"); + if (s->next == NULL && prt_count) fprintf(solnfile, "count: %d\n", solncount); + } + if (solncount > 1 && enumerate_all) { + rc |= 1; + } + } + else { + unsolved++; + rc |= 1; + fprintf(rejects, "%d: %*.*s unsolved\n", count, PUZZLE_CELLS, PUZZLE_CELLS, inbuf); fflush(rejects); + diagnostic_grid(&g, rejects); +#if defined(DEBUG) + mypause(); +#endif + } + + *inbuf = 0; + if (h) fgets(inbuf, 128, h); + } + + //if (prt) fprintf(solnfile, "\nPuzzles: %d, Solved: %d, Unsolved: %d, Bogus: %d\n", count, solved, unsolved, bog); + *scorep = g.score; + return solncount; +} +// end https://github.com/attractivechaos/plb/blob/master/sudoku/incoming/sudoku_solver.c // start https://github.com/mentalmove/SudokuGenerator // @@ -605,9 +2599,9 @@ uint8_t sudoku_genopreturndecode(char *unsolved,CScript scriptPubKey) UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); CPubKey sudokupk,pk; uint8_t privkey[32],unsolved[9][9],pub33[33]; uint32_t srandi; uint256 hash; char coinaddr[64],*jsonstr; uint64_t inputsum,amount,change=0; std::string rawtx; + UniValue result(UniValue::VOBJ); CPubKey sudokupk,pk; uint8_t privkey[32],unsolved[9][9],pub33[33]; uint32_t srandi; int32_t i,score; uint256 hash; char coinaddr[64],str[82],*jsonstr; uint64_t inputsum,amount,change=0; std::string rawtx; amount = COIN; - if ( params != 0 ) + /*if ( params != 0 ) { if ( (jsonstr= jprint(params,0)) != 0 ) { @@ -618,14 +2612,26 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params } amount = atof(jsonstr) * COIN + 0.0000000049; } - } + }*/ result.push_back(Pair("result","success")); result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","gen")); hash = chainActive.LastTip()->GetBlockHash(); memcpy(&srandi,&hash,sizeof(srandi)); srandi ^= (uint32_t)time(NULL); - sudoku_gen(privkey,unsolved,srandi); + while ( 1 ) + { + sudoku_gen(privkey,unsolved,srandi); + for (i=0; i Date: Wed, 30 Jan 2019 02:36:44 -1100 Subject: [PATCH 0184/1145] syntax --- src/cc/sudoku.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index b34eccd39..02c47ef97 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -1160,17 +1160,17 @@ static int eliminate_singles(grid *g) /* Do rows */ for (i = 0; i < PUZZLE_DIM; i++) { - found |= find_singletons(g, row[i], "row"); + found |= find_singletons(g, row[i], (char *)"row"); } /* Do columns */ for (i = 0; i < PUZZLE_DIM; i++) { - found |= find_singletons(g, col[i], "column"); + found |= find_singletons(g, col[i], (char *)"column"); } /* Do regions */ for (i = 0; i < PUZZLE_DIM; i++) { - found |= find_singletons(g, region[i], "region"); + found |= find_singletons(g, region[i], (char *)"region"); } return found; @@ -1489,17 +1489,17 @@ static int mult_elimination(grid *g) /* Eliminate subsets from rows */ for (i = 0; i < PUZZLE_DIM; i++) { - rc |= elim_matches(g, row[i], "row", i); + rc |= elim_matches(g, row[i], (char *)"row", i); } /* Eliminate subsets from columns */ for (i = 0; i < PUZZLE_DIM; i++) { - rc |= elim_matches(g, col[i], "column", i); + rc |= elim_matches(g, col[i], (char *)"column", i); } /* Eliminate subsets from regions */ for (i = 0; i < PUZZLE_DIM; i++) { - rc |= elim_matches(g, region[i], "region", i); + rc |= elim_matches(g, region[i], (char *)"region", i); } return rc; @@ -1633,7 +1633,7 @@ static int add_soln(grid *g) { grid *tmp; - if ((tmp = malloc(sizeof(grid))) == NULL) { + if ((tmp = (grid *)malloc(sizeof(grid))) == NULL) { fprintf(stderr, "Out of memory.\n"); exit(1); } @@ -2623,7 +2623,7 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params { sudoku_gen(privkey,unsolved,srandi); for (i=0; i Date: Wed, 30 Jan 2019 03:35:35 -1100 Subject: [PATCH 0185/1145] Check for illegal solution --- src/cc/cclib.cpp | 6 +++--- src/cc/sudoku.cpp | 8 ++++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index dd79d22d9..000245e56 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -37,17 +37,17 @@ char *CClib_name() { return((char *)MYCCLIBNAME.c_str()); } struct CClib_rpcinfo { char *CCname,*method,*help; - int32_t numrequiredargs,maxargs; // frontloaded with required + int32_t numrequiredargs,maxargs; uint8_t funcid,evalcode; } CClib_methods[] = { { (char *)"faucet2", (char *)"fund", (char *)"amount", 1, 1, 'F', EVAL_FAUCET2 }, { (char *)"faucet2", (char *)"get", (char *)"", 0, 0, 'G', EVAL_FAUCET2 }, - { (char *)"sudoku", (char *)"gen", (char *)"", 1, 1, 'G', EVAL_SUDOKU }, + { (char *)"sudoku", (char *)"gen", (char *)"", 0, 0, 'G', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"pending", (char *)"", 0, 0, 'U', EVAL_SUDOKU }, - { (char *)"sudoku", (char *)"solution", (char *)"txid solution timestamps[]", 2, 2, 'S', EVAL_SUDOKU }, + { (char *)"sudoku", (char *)"solution", (char *)"txid solution timestamps[81]", 83, 83, 'S', EVAL_SUDOKU }, }; std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *params); diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 02c47ef97..e3cf7095d 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2807,7 +2807,15 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params { for (i=ind=0; i<9; i++) for (j=0; j<9; j++) + { + if ( solution[ind] < '1' || solution[ind] > '9' ) + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","illegal solution")); + return(result); + } vals9[i][j] = solution[ind++] - '0'; + } sudoku_privkey(priv32,vals9); priv2addr(coinaddr,pub33,priv32); pk = buf2pk(pub33); From a4055d478a079721e2b43a9d31578478ff03e9a5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 30 Jan 2019 03:45:50 -1100 Subject: [PATCH 0186/1145] Move sudokuaddr check --- src/cc/sudoku.cpp | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index e3cf7095d..5968f59d9 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2507,6 +2507,8 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) "result": "success", "hex": "0400008085202f8901328455ce926086f00be1b2adac0ba9adc22067a30948c71572f3da80adc1135d010000007b4c79a276a072a26ba067a565802102c57d40c1ddc92a5246a937bd7338823f1e8c916b137f2092d38cf250d74cb5ab8140f92d54f611aa3cb3d187eaadd56b06f3a8c0f5fba23956b26fdefc6038d9b6282de38525f72ebd8945a7994cef63ebca711ecf8fe6baeefcc218cf58efb59dc2a100af03800111a10001ffffffff02f0b9f505000000002321039433dc3749aece1bd568f374a45da3b0bc6856990d7da3cd175399577940a775ac0000000000000000fd9f016a4d9b01115351343639383233373135383735393631323334323331343537363938393134363735383233363533313832343739373832333934313536333436323139353837353238373336393431313937353438333632fd4401000000005c5078355c50783600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000" } + + cclib solution 17 \"[%224d50336780d5a300a1f01b12fe36f46a82f3b9935bb115e01e0113dc4f337aae%22,%22234791685716258943589643712865934127341827596927516438492375861178462359653189274%22,0,0,1548859143,1548859146,0,1548859146,0,1548859148,1548859149,0,1548859151,1548859152,0,1548859154,1548859155,1548859158,1548859159,0,0,0,1548859161,1548859163,0,1548859164,1548859168,0,1548859168,1548859170,1548859172,1548859172,1548859175,0,0,1548859176,0,0,1548859178,1548859178,0,0,1548859180,1548859181,1548859183,1548859184,1548859185,1548859186,1548859188,1548859190,1548859191,1548859192,1548859192,0,0,1548859195,1548859196,1548859197,1548859198,0,0,1548859199,1548859202,1548859202,0,1548859204,1548859205,1548859206,1548859209,1548859210,1548859211,1548859212,0,1548859214,1548859216,0,1548859217,1548859218,1548859219,1548859220,0,1548859222,1548859222]\" */ int32_t sudoku_captcha(uint32_t timestamps[81]) @@ -2820,15 +2822,6 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params priv2addr(coinaddr,pub33,priv32); pk = buf2pk(pub33); GetCCaddress(cp,CCaddr,pk); - Getscriptaddress(checkaddr,tx.vout[1].scriptPubKey); - if ( strcmp(checkaddr,CCaddr) != 0 ) - { - result.push_back(Pair("result","error")); - result.push_back(Pair("error","wrong solution")); - result.push_back(Pair("yours",CCaddr)); - result.push_back(Pair("sudokuaddr",checkaddr)); - return(result); - } result.push_back(Pair("sudokuaddr",CCaddr)); balance = CCaddress_balance(CCaddr); result.push_back(Pair("amount",ValueFromAmount(balance))); @@ -2849,6 +2842,14 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("error","already solved")); else if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) { + Getscriptaddress(checkaddr,tx.vout[1].scriptPubKey); + if ( strcmp(checkaddr,CCaddr) != 0 ) + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","wrong solution")); + result.push_back(Pair("yours",CCaddr)); + return(result); + } if ( sudoku_genopreturndecode(unsolved,tx.vout[numvouts-1].scriptPubKey) == 'G' ) { for (i=0; i<81; i++) From 2ad90b9bd0c0a37a90c7d3bda6df5b4e2ace755b Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 30 Jan 2019 21:42:29 -1100 Subject: [PATCH 0187/1145] Skip staking utxo for ac_perc chains that stake --- src/komodo_bitcoind.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index b3248d7d4..f638afa8a 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1190,6 +1190,8 @@ uint64_t komodo_commission(const CBlock *pblock,int32_t height) n = pblock->vtx[i].vout.size(); for (j=0; j 100000 && ASSETCHAINS_STAKED != 0 && txn_count > 1 && i == txn_count-1 && n == 1 ) + break; //fprintf(stderr,"(%d %.8f).%d ",i,dstr(pblock->vtx[i].vout[j].nValue),j); if ( i != 0 || j != 1 ) total += pblock->vtx[i].vout[j].nValue; From 093635e9a8c750ecb8e5f93d321d94e5eb97e48f Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 30 Jan 2019 23:15:44 -1100 Subject: [PATCH 0188/1145] Initial validation skeleton --- src/cc/rewards.cpp | 2 +- src/cc/sudoku.cpp | 33 ++++++++++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/cc/rewards.cpp b/src/cc/rewards.cpp index bd5a6d919..b9f4677be 100644 --- a/src/cc/rewards.cpp +++ b/src/cc/rewards.cpp @@ -203,7 +203,7 @@ bool RewardsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &t else { txid = tx.GetHash(); - if ( (funcid= DecodeRewardsOpRet(txid,tx.vout[numvouts-1].scriptPubKey,sbits,fundingtxid)) != 0 ) + if ( (funcid= DecodeRewardsOpRet(txid,tx.vout[numvouts-1].scriptPubKey,sbits,fundingtxid)) != 0 ) { if ( eval->GetTxUnconfirmed(fundingtxid,fundingTx,hashBlock) == 0 ) return eval->Invalid("cant find fundingtxid"); diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 5968f59d9..9d52728a3 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2909,5 +2909,36 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - return(true); + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t score,numvouts; char unsolved[82]; + if ( (numvouts= tx.vout.size()) > 1 ) + { + scriptPubKey = tx.vout[numvouts-1].scriptPubKey; + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() > 2 ) + { + script = (uint8_t *)vopret.data(); + if ( script[0] == EVAL_SUDOKU ) + { + switch ( script[1] ) + { + case 'G': + if ( sudoku_genopreturndecode(unsolved,scriptPubKey) == 'G' ) + { + if ( dupree_solver(&score,unsolved) != 1 || score*COIN != tx.vout[1].nValue ) + { + fprintf(stderr,"ht.%d score.%d vs %.8f %s\n",height,score,(double)tx.vout[1].nValue/COIN,tx.GetHash().ToString()); + } + } + return(true); + case 'S': + fprintf(stderr,"SOLVED ht.%d %.8f %s\n",height,score,(double)tx.vout[0].nValue/COIN,tx.GetHash().ToString()); + return(true); + default: return eval->Invalid("invalid funcid"); + } + } else return eval->Invalid("invalid evalcode"); + + } + } + return eval->Invalid("not enough vouts"); } + From d6104a35c5c9200bed91806bbe41e2f40d8c9886 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 30 Jan 2019 23:17:34 -1100 Subject: [PATCH 0189/1145] Fix --- src/cc/sudoku.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 9d52728a3..4dd096082 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2926,12 +2926,12 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const { if ( dupree_solver(&score,unsolved) != 1 || score*COIN != tx.vout[1].nValue ) { - fprintf(stderr,"ht.%d score.%d vs %.8f %s\n",height,score,(double)tx.vout[1].nValue/COIN,tx.GetHash().ToString()); + fprintf(stderr,"ht.%d score.%d vs %.8f %s\n",height,score,(double)tx.vout[1].nValue/COIN,tx.GetHash().ToString().c_str()); } } return(true); case 'S': - fprintf(stderr,"SOLVED ht.%d %.8f %s\n",height,score,(double)tx.vout[0].nValue/COIN,tx.GetHash().ToString()); + fprintf(stderr,"SOLVED ht.%d %.8f %s\n",height,(double)tx.vout[0].nValue/COIN,tx.GetHash().ToString().c_str()); return(true); default: return eval->Invalid("invalid funcid"); } From c738557c58f90a3e166ca2a3b7b9ccdbe5dd44ef Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 30 Jan 2019 23:38:17 -1100 Subject: [PATCH 0190/1145] Test --- src/cc/sudoku.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 4dd096082..b55024036 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -1781,12 +1781,13 @@ int dupree_solver(int32_t *scorep,char *puzzle) grid g, *s=0; FILE *h=0; soln_list = NULL; - /* Get our command name from invoking command line */ + myname = "internal"; + /* Get our command name from invoking command line if ((myname = strrchr(argv[0], '/')) == NULL) myname = argv[0]; else myname++; - /*argc = 3; + argc = 3; argv[1] = "-p"; argv[2] = puzzle; argv[3] = 0;*/ @@ -2924,6 +2925,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const case 'G': if ( sudoku_genopreturndecode(unsolved,scriptPubKey) == 'G' ) { + fprintf(stderr,"unsolved.(%s)\n",unsolved); if ( dupree_solver(&score,unsolved) != 1 || score*COIN != tx.vout[1].nValue ) { fprintf(stderr,"ht.%d score.%d vs %.8f %s\n",height,score,(double)tx.vout[1].nValue/COIN,tx.GetHash().ToString().c_str()); From 1856fca69c89a52a597cd0ea7929c661cccb3258 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 30 Jan 2019 23:57:06 -1100 Subject: [PATCH 0191/1145] Free mem in solver --- src/cc/sudoku.cpp | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index b55024036..ad6927b6b 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -1773,7 +1773,7 @@ static char *cvt_to_mask(char *mbuf, char *sbuf) /* Mainline logic. */ /*******************/ -int dupree_solver(int32_t *scorep,char *puzzle) +int dupree_solver(int32_t dispflag,int32_t *scorep,char *puzzle) { int argc; char *argv[4]; int i, rc, bog, count, solved, unsolved, solncount=0, flag, prt_count, prt_num, prt_score, prt_answer, prt_depth, prt_grid, prt_mask, prt_givens, prt, len; @@ -1781,7 +1781,7 @@ int dupree_solver(int32_t *scorep,char *puzzle) grid g, *s=0; FILE *h=0; soln_list = NULL; - myname = "internal"; + myname = (char *)"internal"; /* Get our command name from invoking command line if ((myname = strrchr(argv[0], '/')) == NULL) myname = argv[0]; @@ -1873,15 +1873,6 @@ int dupree_solver(int32_t *scorep,char *puzzle) exit(1); } } -#endif - prt_answer = 1; /* print solution */ - //prt_count = 1; /* number solutions */ - prt_score = 1; - prt_givens = 1; - prt_num = 1; - /* Set prt flag if we're printing anything at all */ - prt = prt_mask | prt_grid | prt_score | prt_depth | prt_answer | prt_num | prt_givens; - /* Anthing else on the command line is bogus */ if (argc > optind) { fprintf(stderr, "Extraneous args: "); @@ -1912,6 +1903,15 @@ int dupree_solver(int32_t *scorep,char *puzzle) exit(1); } if (h) fgets(inbuf, 128, h);*/ +#endif + prt_answer = dispflag; /* print solution */ + //prt_count = dispflag; /* number solutions */ + prt_score = dispflag; + prt_givens = dispflag; + prt_num = dispflag; + /* Set prt flag if we're printing anything at all */ + prt = prt_mask | prt_grid | prt_score | prt_depth | prt_answer | prt_num | prt_givens; + strcpy(inbuf,puzzle); count = solved = unsolved = 0; //printf("inbuf.(%s)\n",inbuf); @@ -1927,7 +1927,7 @@ int dupree_solver(int32_t *scorep,char *puzzle) fprintf(rejects, "%d: %s bogus puzzle format\n", count, inbuf); fflush(rejects); *inbuf = 0; bog += 1; - if (h) fgets(inbuf, 128, h); + //if (h) fgets(inbuf, 128, h); continue; } @@ -1936,7 +1936,7 @@ int dupree_solver(int32_t *scorep,char *puzzle) fprintf(rejects, "%d: %*.*s bogus puzzle has less than 17 givens\n", count, PUZZLE_CELLS, PUZZLE_CELLS, inbuf); fflush(rejects); *inbuf = 0; bog += 1; - if (h) fgets(inbuf, 128, h); + //if (h) fgets(inbuf, 128, h); continue; } @@ -1973,6 +1973,11 @@ int dupree_solver(int32_t *scorep,char *puzzle) if (solncount > 1 && enumerate_all) { rc |= 1; } + for (s = soln_list; s;) { + s = soln_list->next; + free(soln_list); + soln_list = s; + } } else { unsolved++; @@ -1985,7 +1990,7 @@ int dupree_solver(int32_t *scorep,char *puzzle) } *inbuf = 0; - if (h) fgets(inbuf, 128, h); + //if (h) fgets(inbuf, 128, h); } //if (prt) fprintf(solnfile, "\nPuzzles: %d, Solved: %d, Unsolved: %d, Bogus: %d\n", count, solved, unsolved, bog); @@ -2629,7 +2634,7 @@ UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params str[i] = '0' + unsolved[i/9][i%9]; str[i] = 0; printf("solve: %s\n",str); - if ( dupree_solver(&score,str) == 1 ) + if ( dupree_solver(1,&score,str) == 1 ) { amount = score * COIN; break; @@ -2926,7 +2931,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const if ( sudoku_genopreturndecode(unsolved,scriptPubKey) == 'G' ) { fprintf(stderr,"unsolved.(%s)\n",unsolved); - if ( dupree_solver(&score,unsolved) != 1 || score*COIN != tx.vout[1].nValue ) + if ( dupree_solver(0,&score,unsolved) != 1 || score*COIN != tx.vout[1].nValue ) { fprintf(stderr,"ht.%d score.%d vs %.8f %s\n",height,score,(double)tx.vout[1].nValue/COIN,tx.GetHash().ToString().c_str()); } From 71e47834e2bbcc8eacb15cb2b35a15c467fa3d21 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 00:01:19 -1100 Subject: [PATCH 0192/1145] Enforce score == payout --- src/cc/sudoku.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index ad6927b6b..10485ec2d 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2930,10 +2930,12 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const case 'G': if ( sudoku_genopreturndecode(unsolved,scriptPubKey) == 'G' ) { - fprintf(stderr,"unsolved.(%s)\n",unsolved); + //fprintf(stderr,"unsolved.(%s)\n",unsolved); if ( dupree_solver(0,&score,unsolved) != 1 || score*COIN != tx.vout[1].nValue ) { fprintf(stderr,"ht.%d score.%d vs %.8f %s\n",height,score,(double)tx.vout[1].nValue/COIN,tx.GetHash().ToString().c_str()); + if ( ht > 2000 ) + return eval->Invalid("mismatched sudoku value vs score"); } } return(true); From a5833d00f701966efeb6adf04fd0555a48ef46b1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 00:04:51 -1100 Subject: [PATCH 0193/1145] Height --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 10485ec2d..395fac577 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2934,7 +2934,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const if ( dupree_solver(0,&score,unsolved) != 1 || score*COIN != tx.vout[1].nValue ) { fprintf(stderr,"ht.%d score.%d vs %.8f %s\n",height,score,(double)tx.vout[1].nValue/COIN,tx.GetHash().ToString().c_str()); - if ( ht > 2000 ) + if ( height > 2000 ) return eval->Invalid("mismatched sudoku value vs score"); } } From d97754614d9365f9aa3a1e575e9ed8048f2069e4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 00:40:38 -1100 Subject: [PATCH 0194/1145] Check solution I-return --- src/cc/sudoku.cpp | 44 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 395fac577..6a0f97583 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2586,6 +2586,35 @@ CScript sudoku_solutionopret(char *solution,uint32_t timestamps[81]) return(opret); } +uint8_t sudoku_solutionopreturndecode(char solution[82],uint32_t timestamps[81],CScript scriptPubKey) +{ + std::vector vopret; uint8_t *script,e,f; std::string str; std::vector data; int32_t i,ind; uint32_t x; + GetOpReturnData(scriptPubKey,vopret); + script = (uint8_t *)vopret.data(); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> str; ss >> data) != 0 && e == EVAL_SUDOKU && f == 'S' ) + { + if ( data.size() == 81*sizeof(uint32_t) && strlen(solution) == 81 ) + { + for (i=ind=0; i<81; i++) + { + if ( solution[i] < '1' || solution[i] > '9' ) + break; + x = data[ind++]; + x <<= 8, x |= (data[ind++] & 0xff); + x <<= 8, x |= (data[ind++] & 0xff); + x <<= 8, x |= (data[ind++] & 0xff); + timestamps[i] = x; + } + if ( i == 81 ) + { + strcpy(solution,str.c_str()); + return(f); + } + } + } + return(0); +} + uint8_t sudoku_genopreturndecode(char *unsolved,CScript scriptPubKey) { std::vector vopret; uint8_t *script,e,f; std::vector data; int32_t i; @@ -2915,7 +2944,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t score,numvouts; char unsolved[82]; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t score,numvouts; char unsolved[82],solution[82]; uint32_t timestamps[81]; if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -2936,12 +2965,19 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const fprintf(stderr,"ht.%d score.%d vs %.8f %s\n",height,score,(double)tx.vout[1].nValue/COIN,tx.GetHash().ToString().c_str()); if ( height > 2000 ) return eval->Invalid("mismatched sudoku value vs score"); - } + } else return(true); } - return(true); + return eval->Invalid("invalid generate opreturn"); case 'S': fprintf(stderr,"SOLVED ht.%d %.8f %s\n",height,(double)tx.vout[0].nValue/COIN,tx.GetHash().ToString().c_str()); - return(true); + if ( sudoku_solutionopreturndecode(solution,timestamps,scriptPubKey) == 'S' ) + { + for (i=0; i<81; i++) + fprintf(stderr,"%u ",timestamps[i]); + fprintf(stderr,"%s\n",solution); + return(true); + } + return eval->Invalid("invalid solution opreturn"); default: return eval->Invalid("invalid funcid"); } } else return eval->Invalid("invalid evalcode"); From 4aa8fce7d2f79f3282c7c3899deaab2dd18af01a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 00:41:15 -1100 Subject: [PATCH 0195/1145] Declare I --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 6a0f97583..4f8702c0a 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2944,7 +2944,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t score,numvouts; char unsolved[82],solution[82]; uint32_t timestamps[81]; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,score,numvouts; char unsolved[82],solution[82]; uint32_t timestamps[81]; if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; From 503ef504482963e300722d60d0e52a3957d984b2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 00:45:08 -1100 Subject: [PATCH 0196/1145] Exempt height 123 --- src/cc/sudoku.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 4f8702c0a..c83cf3464 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2967,6 +2967,8 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const return eval->Invalid("mismatched sudoku value vs score"); } else return(true); } + else if ( height == 123 ) // early version invalid gen + return(true); return eval->Invalid("invalid generate opreturn"); case 'S': fprintf(stderr,"SOLVED ht.%d %.8f %s\n",height,(double)tx.vout[0].nValue/COIN,tx.GetHash().ToString().c_str()); From 0a0d310f7f2c296caa124cbf38aa0e4c362f1682 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 00:47:23 -1100 Subject: [PATCH 0197/1145] Print --- src/cc/sudoku.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index c83cf3464..878d9a86d 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2969,6 +2969,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const } else if ( height == 123 ) // early version invalid gen return(true); + fprintf(stderr,"height.%d txid.%s\n",height,tx.GetHash().ToString().c_str()); return eval->Invalid("invalid generate opreturn"); case 'S': fprintf(stderr,"SOLVED ht.%d %.8f %s\n",height,(double)tx.vout[0].nValue/COIN,tx.GetHash().ToString().c_str()); From d23000ccf5290756fa5bd899a49b2bccc188c7ff Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 00:48:57 -1100 Subject: [PATCH 0198/1145] Add return true path --- src/cc/sudoku.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 878d9a86d..49b23a367 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2965,10 +2965,9 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const fprintf(stderr,"ht.%d score.%d vs %.8f %s\n",height,score,(double)tx.vout[1].nValue/COIN,tx.GetHash().ToString().c_str()); if ( height > 2000 ) return eval->Invalid("mismatched sudoku value vs score"); + else return(true); } else return(true); } - else if ( height == 123 ) // early version invalid gen - return(true); fprintf(stderr,"height.%d txid.%s\n",height,tx.GetHash().ToString().c_str()); return eval->Invalid("invalid generate opreturn"); case 'S': From 7fc53be997b90353e56e377e7ff9fb8adef828c1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 00:51:32 -1100 Subject: [PATCH 0199/1145] Bad solution ? --- src/cc/sudoku.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 49b23a367..87570e7e2 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2963,7 +2963,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const if ( dupree_solver(0,&score,unsolved) != 1 || score*COIN != tx.vout[1].nValue ) { fprintf(stderr,"ht.%d score.%d vs %.8f %s\n",height,score,(double)tx.vout[1].nValue/COIN,tx.GetHash().ToString().c_str()); - if ( height > 2000 ) + if ( strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") != 0 || height > 2000 ) return eval->Invalid("mismatched sudoku value vs score"); else return(true); } else return(true); @@ -2979,6 +2979,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const fprintf(stderr,"%s\n",solution); return(true); } + fprintf(stderr,"solution ht.%d %s bad opret\n",height,tx.GetHash().ToString().c_str()); return eval->Invalid("invalid solution opreturn"); default: return eval->Invalid("invalid funcid"); } From 8dc9205db0e5604e647f19d8305ec794608fa48e Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 00:52:53 -1100 Subject: [PATCH 0200/1145] Ht 236 exemption --- src/cc/sudoku.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 87570e7e2..097153d40 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2980,6 +2980,8 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const return(true); } fprintf(stderr,"solution ht.%d %s bad opret\n",height,tx.GetHash().ToString().c_str()); + if ( height == 236 && strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") == 0 ) + return(true); return eval->Invalid("invalid solution opreturn"); default: return eval->Invalid("invalid funcid"); } From 03bad588edf2836a8629429174a2336d4068a6c8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 00:57:52 -1100 Subject: [PATCH 0201/1145] 1220 exemption --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 097153d40..57a88707e 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2980,7 +2980,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const return(true); } fprintf(stderr,"solution ht.%d %s bad opret\n",height,tx.GetHash().ToString().c_str()); - if ( height == 236 && strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") == 0 ) + if ( (height == 236 || height == 1220) && strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") == 0 ) return(true); return eval->Invalid("invalid solution opreturn"); default: return eval->Invalid("invalid funcid"); From 16be17121fba408c7674f4a34a9f487ea4de9812 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 01:01:30 -1100 Subject: [PATCH 0202/1145] str.size()! --- src/cc/sudoku.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 57a88707e..2624fc54c 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2593,7 +2593,7 @@ uint8_t sudoku_solutionopreturndecode(char solution[82],uint32_t timestamps[81], script = (uint8_t *)vopret.data(); if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> str; ss >> data) != 0 && e == EVAL_SUDOKU && f == 'S' ) { - if ( data.size() == 81*sizeof(uint32_t) && strlen(solution) == 81 ) + if ( data.size() == 81*sizeof(uint32_t) && str.size() == 81 ) { for (i=ind=0; i<81; i++) { @@ -2610,7 +2610,7 @@ uint8_t sudoku_solutionopreturndecode(char solution[82],uint32_t timestamps[81], strcpy(solution,str.c_str()); return(f); } - } + } else fprintf(stderr,"datasize %d sol[%d]\n",(int32_t)data.size(),(int32_t)str.size()); } return(0); } @@ -2982,7 +2982,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const fprintf(stderr,"solution ht.%d %s bad opret\n",height,tx.GetHash().ToString().c_str()); if ( (height == 236 || height == 1220) && strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") == 0 ) return(true); - return eval->Invalid("invalid solution opreturn"); + return true; //eval->Invalid("invalid solution opreturn"); default: return eval->Invalid("invalid funcid"); } } else return eval->Invalid("invalid evalcode"); From c0e2024b3c46888aa66c12792bab734433076737 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 01:03:29 -1100 Subject: [PATCH 0203/1145] Dont use uninitialized variables --- src/cc/sudoku.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 2624fc54c..c151e25fc 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2595,6 +2595,7 @@ uint8_t sudoku_solutionopreturndecode(char solution[82],uint32_t timestamps[81], { if ( data.size() == 81*sizeof(uint32_t) && str.size() == 81 ) { + strcpy(solution,str.c_str()); for (i=ind=0; i<81; i++) { if ( solution[i] < '1' || solution[i] > '9' ) @@ -2606,10 +2607,7 @@ uint8_t sudoku_solutionopreturndecode(char solution[82],uint32_t timestamps[81], timestamps[i] = x; } if ( i == 81 ) - { - strcpy(solution,str.c_str()); return(f); - } } else fprintf(stderr,"datasize %d sol[%d]\n",(int32_t)data.size(),(int32_t)str.size()); } return(0); From 9b966a4e725f584e7b031bc79275a42cd6766bc6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 01:06:30 -1100 Subject: [PATCH 0204/1145] filter prints --- src/cc/sudoku.cpp | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index c151e25fc..585f4fb3d 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2942,7 +2942,8 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,score,numvouts; char unsolved[82],solution[82]; uint32_t timestamps[81]; + static char laststr[512]; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,score,numvouts; char unsolved[82],solution[82],str[512]; uint32_t timestamps[81]; if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -2960,7 +2961,12 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const //fprintf(stderr,"unsolved.(%s)\n",unsolved); if ( dupree_solver(0,&score,unsolved) != 1 || score*COIN != tx.vout[1].nValue ) { - fprintf(stderr,"ht.%d score.%d vs %.8f %s\n",height,score,(double)tx.vout[1].nValue/COIN,tx.GetHash().ToString().c_str()); + sprintf(str,"ht.%d score.%d vs %.8f %s",height,score,(double)tx.vout[1].nValue/COIN,tx.GetHash().ToString().c_str()); + if ( strcmp(str,laststr) != 0 ) + { + strcpy(laststr,str); + fprintf(stderr,"%s\n",str); + } if ( strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") != 0 || height > 2000 ) return eval->Invalid("mismatched sudoku value vs score"); else return(true); @@ -2969,7 +2975,12 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const fprintf(stderr,"height.%d txid.%s\n",height,tx.GetHash().ToString().c_str()); return eval->Invalid("invalid generate opreturn"); case 'S': - fprintf(stderr,"SOLVED ht.%d %.8f %s\n",height,(double)tx.vout[0].nValue/COIN,tx.GetHash().ToString().c_str()); + sprintf(str,"SOLVED ht.%d %.8f %s\n",height,(double)tx.vout[0].nValue/COIN,tx.GetHash().ToString().c_str()); + if ( strcmp(str,laststr) != 0 ) + { + strcpy(laststr,str); + fprintf(stderr,"%s\n",str); + } if ( sudoku_solutionopreturndecode(solution,timestamps,scriptPubKey) == 'S' ) { for (i=0; i<81; i++) From 31e3cba48be4a0da0f0accae6dd64721b856fa0e Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 01:07:27 -1100 Subject: [PATCH 0205/1145] Prints --- src/cc/sudoku.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 585f4fb3d..7fcfedb52 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2943,7 +2943,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { static char laststr[512]; - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,score,numvouts; char unsolved[82],solution[82],str[512]; uint32_t timestamps[81]; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,dispflag,score,numvouts; char unsolved[82],solution[82],str[512]; uint32_t timestamps[81]; if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -2980,18 +2980,20 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const { strcpy(laststr,str); fprintf(stderr,"%s\n",str); - } + dispflag = 1; + } else dispflag = 0; if ( sudoku_solutionopreturndecode(solution,timestamps,scriptPubKey) == 'S' ) { - for (i=0; i<81; i++) - fprintf(stderr,"%u ",timestamps[i]); - fprintf(stderr,"%s\n",solution); + if ( dispflag != 0 ) + { + for (i=0; i<81; i++) + fprintf(stderr,"%u ",timestamps[i]); + fprintf(stderr,"%s\n",solution); + } return(true); } fprintf(stderr,"solution ht.%d %s bad opret\n",height,tx.GetHash().ToString().c_str()); - if ( (height == 236 || height == 1220) && strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") == 0 ) - return(true); - return true; //eval->Invalid("invalid solution opreturn"); + return eval->Invalid("invalid solution opreturn"); default: return eval->Invalid("invalid funcid"); } } else return eval->Invalid("invalid evalcode"); From 75834b5beb2c78cfb4b040e6a04b5058008c4d28 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 01:21:21 -1100 Subject: [PATCH 0206/1145] Print captcha data --- src/cc/sudoku.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 7fcfedb52..3457a5840 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2517,7 +2517,7 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) cclib solution 17 \"[%224d50336780d5a300a1f01b12fe36f46a82f3b9935bb115e01e0113dc4f337aae%22,%22234791685716258943589643712865934127341827596927516438492375861178462359653189274%22,0,0,1548859143,1548859146,0,1548859146,0,1548859148,1548859149,0,1548859151,1548859152,0,1548859154,1548859155,1548859158,1548859159,0,0,0,1548859161,1548859163,0,1548859164,1548859168,0,1548859168,1548859170,1548859172,1548859172,1548859175,0,0,1548859176,0,0,1548859178,1548859178,0,0,1548859180,1548859181,1548859183,1548859184,1548859185,1548859186,1548859188,1548859190,1548859191,1548859192,1548859192,0,0,1548859195,1548859196,1548859197,1548859198,0,0,1548859199,1548859202,1548859202,0,1548859204,1548859205,1548859206,1548859209,1548859210,1548859211,1548859212,0,1548859214,1548859216,0,1548859217,1548859218,1548859219,1548859220,0,1548859222,1548859222]\" */ -int32_t sudoku_captcha(uint32_t timestamps[81]) +int32_t sudoku_captcha(uint32_t timestamps[81],int32_t height) { int32_t i,solvetime,diff,avetime,n = 0; uint64_t variance = 0; std::vector list; for (i=0; i<81; i++) @@ -2858,7 +2858,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("sudokuaddr",CCaddr)); balance = CCaddress_balance(CCaddr); result.push_back(Pair("amount",ValueFromAmount(balance))); - if ( sudoku_captcha(timestamps) < 0 ) + if ( sudoku_captcha(timestamps,komodo_nextheight()) < 0 ) { result.push_back(Pair("result","error")); result.push_back(Pair("error","captcha failure")); @@ -2975,11 +2975,11 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const fprintf(stderr,"height.%d txid.%s\n",height,tx.GetHash().ToString().c_str()); return eval->Invalid("invalid generate opreturn"); case 'S': - sprintf(str,"SOLVED ht.%d %.8f %s\n",height,(double)tx.vout[0].nValue/COIN,tx.GetHash().ToString().c_str()); + sprintf(str,"SOLVED ht.%d %.8f %s",height,(double)tx.vout[0].nValue/COIN,tx.GetHash().ToString().c_str()); if ( strcmp(str,laststr) != 0 ) { strcpy(laststr,str); - fprintf(stderr,"%s\n",str); + fprintf(stderr,"\n%s\n",str); dispflag = 1; } else dispflag = 0; if ( sudoku_solutionopreturndecode(solution,timestamps,scriptPubKey) == 'S' ) @@ -2989,6 +2989,8 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const for (i=0; i<81; i++) fprintf(stderr,"%u ",timestamps[i]); fprintf(stderr,"%s\n",solution); + if ( sudoku_captcha(timestamps,height) < 0 ) + return eval->Invalid("failed captcha"); } return(true); } From 0b297c6c859dd4bc6d854706a86fc43605fb90b2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 01:26:08 -1100 Subject: [PATCH 0207/1145] Test --- src/cc/sudoku.cpp | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 3457a5840..613a38e8b 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2519,7 +2519,7 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) int32_t sudoku_captcha(uint32_t timestamps[81],int32_t height) { - int32_t i,solvetime,diff,avetime,n = 0; uint64_t variance = 0; std::vector list; + int32_t i,solvetime,diff,avetime,n = 0,retval = 0; uint64_t variance = 0; std::vector list; for (i=0; i<81; i++) { if ( timestamps[i] != 0 ) @@ -2535,17 +2535,17 @@ int32_t sudoku_captcha(uint32_t timestamps[81],int32_t height) if ( list[0] >= list[n-1] ) { printf("list[0] %u vs list[%d-1] %u\n",list[0],n,list[n-1]); - return(-1); + retval = -1; } else if ( list[n-1] > chainActive.LastTip()->nTime+200 ) - return(-1); + retval = -2; else if ( solvetime >= 777 ) - return(0); + retval = 0; else { avetime = (solvetime / (n-1)); if ( avetime == 0 ) - return(-1); + retval = -3; for (i=0; i Date: Thu, 31 Jan 2019 01:54:33 -1100 Subject: [PATCH 0208/1145] More validation --- src/cc/sudoku.cpp | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 613a38e8b..426d46971 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2948,7 +2948,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { static char laststr[512]; - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,dispflag,score,numvouts; char unsolved[82],solution[82],str[512]; uint32_t timestamps[81]; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,dispflag,score,numvouts; char unsolved[82],solution[82],str[512]; uint32_t timestamps[81]; CTransaction vintx; uint256 hashBlock; if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -2989,15 +2989,33 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const } else dispflag = 0; if ( sudoku_solutionopreturndecode(solution,timestamps,scriptPubKey) == 'S' ) { - if ( dispflag != 0 ) + if ( tx.vin.size() > 1 && tx.vin[0].prevout.hash == tx.vin[1].prevout.hash && tx.vin[0].prevout.n == 0 && tx.vin[1].prevout.n == 1 && myGetTransaction(tx.vin[0].prevout.hash,vintx,hashBlock) != 0 ) { - for (i=0; i<81; i++) - fprintf(stderr,"%u ",timestamps[i]); - fprintf(stderr,"%s\n",solution); - if ( sudoku_captcha(timestamps,height) < 0 ) - return eval->Invalid("failed captcha"); - } - return(true); + if ( vintx.vout.size() > 1 && sudoku_genopreturndecode(unsolved,vintx.vout[vintx.vout.size()-1].scriptPubKey) == 'G' ) + { + if ( dispflag != 0 ) + { + for (i=0; i<81; i++) + { + fprintf(stderr,"%u ",timestamps[i]); + if ( (timestamps[i] == 0 && unsolved[i] >= '1' && unsolved[i] <= '9') || (timestamps[i] != 0 && (unsolved[i] < '1' || unsolved[i] > '9')) ) + { + fprintf(stderr,"i.%d invalid timestamp vs unsolved.[%c]\n",i,unsolved[i]); + return eval->Invalid("invalid timestamp vs unsolved"); + } + } + if ( dupree_solver(0,&score,unsolved) != 1 ) + { + fprintf(stderr,"non-unique sudoku at ht.%d\n",height); + return eval->Invalid("invalid sudoku with multiple solutions"); + } + fprintf(stderr,"%s score.%d\n",solution,score); + } + if ( sudoku_captcha(timestamps,height) < 0 ) + return eval->Invalid("failed captcha"); + return(true); + } else return eval->Invalid("invalid solution opret"); + } else return eval->Invalid("invalid solution vin"); } fprintf(stderr,"solution ht.%d %s bad opret\n",height,tx.GetHash().ToString().c_str()); return eval->Invalid("invalid solution opreturn"); From 40f628504af4e5412add4cdf5cef5fae0d344a6a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 01:56:57 -1100 Subject: [PATCH 0209/1145] Test --- src/cc/sudoku.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 426d46971..86f61ee0a 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -3015,7 +3015,10 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const return eval->Invalid("failed captcha"); return(true); } else return eval->Invalid("invalid solution opret"); - } else return eval->Invalid("invalid solution vin"); + } + else if ( strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") == 0 && height == 236 ) + return(true); + else return eval->Invalid("invalid solution vin"); } fprintf(stderr,"solution ht.%d %s bad opret\n",height,tx.GetHash().ToString().c_str()); return eval->Invalid("invalid solution opreturn"); From 6b3d8f710dcef2b95d6795ebb4fbc74cbfe7052e Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 02:00:11 -1100 Subject: [PATCH 0210/1145] 1220 exemption --- src/cc/sudoku.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 86f61ee0a..b8cdb88e5 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -3000,8 +3000,9 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const fprintf(stderr,"%u ",timestamps[i]); if ( (timestamps[i] == 0 && unsolved[i] >= '1' && unsolved[i] <= '9') || (timestamps[i] != 0 && (unsolved[i] < '1' || unsolved[i] > '9')) ) { - fprintf(stderr,"i.%d invalid timestamp vs unsolved.[%c]\n",i,unsolved[i]); - return eval->Invalid("invalid timestamp vs unsolved"); + fprintf(stderr,"i.%d invalid timestamp vs unsolved.[%c] %s\n",i,unsolved[i],unsolved); + if ( strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") != 0 || height != 1220 ) + return eval->Invalid("invalid timestamp vs unsolved"); } } if ( dupree_solver(0,&score,unsolved) != 1 ) From ba0a1b5ae4bcf64b0359dca7a8696f2649956517 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 02:04:06 -1100 Subject: [PATCH 0211/1145] Test --- src/cc/sudoku.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index b8cdb88e5..4f283b69d 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -3000,9 +3000,9 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const fprintf(stderr,"%u ",timestamps[i]); if ( (timestamps[i] == 0 && unsolved[i] >= '1' && unsolved[i] <= '9') || (timestamps[i] != 0 && (unsolved[i] < '1' || unsolved[i] > '9')) ) { - fprintf(stderr,"i.%d invalid timestamp vs unsolved.[%c] %s\n",i,unsolved[i],unsolved); - if ( strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") != 0 || height != 1220 ) + if ( strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") != 0 || (height != 1220 && height != 1383) ) return eval->Invalid("invalid timestamp vs unsolved"); + else fprintf(stderr,"i.%d invalid timestamp vs unsolved.[%c] %s\n",i,unsolved[i],unsolved); } } if ( dupree_solver(0,&score,unsolved) != 1 ) From de547e23accdc55e803faaf9a37a8061cf35b99d Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 02:09:21 -1100 Subject: [PATCH 0212/1145] Unsolved print --- src/cc/sudoku.cpp | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 4f283b69d..a31bf4d60 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2948,7 +2948,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { static char laststr[512]; - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,dispflag,score,numvouts; char unsolved[82],solution[82],str[512]; uint32_t timestamps[81]; CTransaction vintx; uint256 hashBlock; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,errflag,dispflag,score,numvouts; char unsolved[82],solution[82],str[512]; uint32_t timestamps[81]; CTransaction vintx; uint256 hashBlock; if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -2993,25 +2993,28 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const { if ( vintx.vout.size() > 1 && sudoku_genopreturndecode(unsolved,vintx.vout[vintx.vout.size()-1].scriptPubKey) == 'G' ) { - if ( dispflag != 0 ) + for (i=errflag=0; i<81; i++) { - for (i=0; i<81; i++) - { + if ( dispflag != 0 ) fprintf(stderr,"%u ",timestamps[i]); - if ( (timestamps[i] == 0 && unsolved[i] >= '1' && unsolved[i] <= '9') || (timestamps[i] != 0 && (unsolved[i] < '1' || unsolved[i] > '9')) ) - { - if ( strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") != 0 || (height != 1220 && height != 1383) ) - return eval->Invalid("invalid timestamp vs unsolved"); - else fprintf(stderr,"i.%d invalid timestamp vs unsolved.[%c] %s\n",i,unsolved[i],unsolved); - } - } - if ( dupree_solver(0,&score,unsolved) != 1 ) - { - fprintf(stderr,"non-unique sudoku at ht.%d\n",height); - return eval->Invalid("invalid sudoku with multiple solutions"); - } - fprintf(stderr,"%s score.%d\n",solution,score); + if ( (timestamps[i] == 0 && unsolved[i] >= '1' && unsolved[i] <= '9') || (timestamps[i] != 0 && (unsolved[i] < '1' || unsolved[i] > '9')) ) + errflag++; } + if ( errflag != 0 ) + { + if ( dispflag != 0 ) + fprintf(stderr,"errflag.%d %s\n",height,errflag,unsolved); + if ( (height != 1220 && height != 1383) || strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") != 0 ) + return eval->Invalid("invalid timestamp vs unsolved"); + } + if ( dupree_solver(0,&score,unsolved) != 1 ) + { + if ( dispflag != 0 ) + fprintf(stderr,"non-unique sudoku at ht.%d\n",height); + return eval->Invalid("invalid sudoku with multiple solutions"); + } + if ( dispflag != 0 ) + fprintf(stderr,"%s score.%d\n",solution,score); if ( sudoku_captcha(timestamps,height) < 0 ) return eval->Invalid("failed captcha"); return(true); From cc8fadd7c554d1b342ad9485553dadd741a65cf0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 02:09:52 -1100 Subject: [PATCH 0213/1145] Fix print --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index a31bf4d60..228ccc095 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -3003,7 +3003,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const if ( errflag != 0 ) { if ( dispflag != 0 ) - fprintf(stderr,"errflag.%d %s\n",height,errflag,unsolved); + fprintf(stderr,"ht.%d errflag.%d %s\n",height,errflag,unsolved); if ( (height != 1220 && height != 1383) || strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") != 0 ) return eval->Invalid("invalid timestamp vs unsolved"); } From d9a8323b60a7305008e7ddab4ff05576409d01ed Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 02:11:52 -1100 Subject: [PATCH 0214/1145] Reverse polarity --- src/cc/sudoku.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 228ccc095..0d1a33e07 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2997,7 +2997,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const { if ( dispflag != 0 ) fprintf(stderr,"%u ",timestamps[i]); - if ( (timestamps[i] == 0 && unsolved[i] >= '1' && unsolved[i] <= '9') || (timestamps[i] != 0 && (unsolved[i] < '1' || unsolved[i] > '9')) ) + if ( (timestamps[i] != 0 && unsolved[i] >= '1' && unsolved[i] <= '9') || (timestamps[i] == 0 && (unsolved[i] < '1' || unsolved[i] > '9')) ) errflag++; } if ( errflag != 0 ) @@ -3014,7 +3014,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const return eval->Invalid("invalid sudoku with multiple solutions"); } if ( dispflag != 0 ) - fprintf(stderr,"%s score.%d\n",solution,score); + fprintf(stderr,"%s score.%d %s\n",solution,score,unsolved); if ( sudoku_captcha(timestamps,height) < 0 ) return eval->Invalid("failed captcha"); return(true); From e37fd6ef9081e3b8a1fc63f6e6c47e489d98fbc6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 02:19:27 -1100 Subject: [PATCH 0215/1145] Scores convergence --- src/cc/sudoku.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 0d1a33e07..dc8fb2f42 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -3017,6 +3017,20 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const fprintf(stderr,"%s score.%d %s\n",solution,score,unsolved); if ( sudoku_captcha(timestamps,height) < 0 ) return eval->Invalid("failed captcha"); + for (i=0; i<81; i++) + { + if ( (ind= sudoku_minval(timestamps)) >= 0 ) + { + unsolved[ind] = solution[ind]; + if ( dupree_solver(0,&score,unsolved) != 1 ) + fprintf(stderr,"i.%d ind.%d non-unique\n",i,ind); + if ( dispflag != 0 ) + fprintf(stderr,"%d ",score); + timestamps[ind] = 0; + } else break; + } + if ( dispflag != 0 ) + fprintf(stderr,"scores convergence\n"); return(true); } else return eval->Invalid("invalid solution opret"); } From 9e9f33d00c62ef874cef3a3ec52e681e638b065a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 02:22:04 -1100 Subject: [PATCH 0216/1145] mintimestamp --- src/cc/sudoku.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index dc8fb2f42..b69081065 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2945,6 +2945,15 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params return(result); } +sudoku_minval(uint32_t timestamps[81]) +{ + int32_t i,ind = -1; uint32_t mintimestamp = 0xffffffff; + for (i=0; i<81; i++) + if ( timestamps[i] != 0 && timestamps[i] < mintimestamp ) + mintimestamp = timestamps[i], ind = i; + return(ind); +} + bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { static char laststr[512]; From fea0e3f845bebe93438fe12dcf0ec13b6c2ee968 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 02:22:51 -1100 Subject: [PATCH 0217/1145] Ind --- src/cc/sudoku.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index b69081065..ff48af50c 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2957,7 +2957,7 @@ sudoku_minval(uint32_t timestamps[81]) bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { static char laststr[512]; - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,errflag,dispflag,score,numvouts; char unsolved[82],solution[82],str[512]; uint32_t timestamps[81]; CTransaction vintx; uint256 hashBlock; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,ind,errflag,dispflag,score,numvouts; char unsolved[82],solution[82],str[512]; uint32_t timestamps[81]; CTransaction vintx; uint256 hashBlock; if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; From 94f4c7c7de1a29a4befcd3147ce1cea34bb07dcf Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 02:25:46 -1100 Subject: [PATCH 0218/1145] sudoku_minval --- src/cc/sudoku.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index ff48af50c..af404807f 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2945,12 +2945,16 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params return(result); } -sudoku_minval(uint32_t timestamps[81]) +int32_t sudoku_minval(uint32_t timestamps[81]) { int32_t i,ind = -1; uint32_t mintimestamp = 0xffffffff; for (i=0; i<81; i++) if ( timestamps[i] != 0 && timestamps[i] < mintimestamp ) + { mintimestamp = timestamps[i], ind = i; + fprintf(stderr,"%d ",i); + } + fprintf(stderr,"mintimestamp.%u\n",mintimestamp); return(ind); } From 7ed14754e59909bbf0519404304f42a199379fe8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 02:27:52 -1100 Subject: [PATCH 0219/1145] -print --- src/cc/sudoku.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index af404807f..ca2eddd91 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2952,9 +2952,9 @@ int32_t sudoku_minval(uint32_t timestamps[81]) if ( timestamps[i] != 0 && timestamps[i] < mintimestamp ) { mintimestamp = timestamps[i], ind = i; - fprintf(stderr,"%d ",i); + //fprintf(stderr,"%d ",i); } - fprintf(stderr,"mintimestamp.%u\n",mintimestamp); + //fprintf(stderr,"mintimestamp.%u\n",mintimestamp); return(ind); } @@ -3035,11 +3035,11 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const if ( (ind= sudoku_minval(timestamps)) >= 0 ) { unsolved[ind] = solution[ind]; + timestamps[ind] = 0; if ( dupree_solver(0,&score,unsolved) != 1 ) fprintf(stderr,"i.%d ind.%d non-unique\n",i,ind); if ( dispflag != 0 ) fprintf(stderr,"%d ",score); - timestamps[ind] = 0; } else break; } if ( dispflag != 0 ) From b79e7c623192f22f833527994d2625341138b343 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 02:31:35 -1100 Subject: [PATCH 0220/1145] Time diffs --- src/cc/sudoku.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index ca2eddd91..b650b1d00 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2961,7 +2961,7 @@ int32_t sudoku_minval(uint32_t timestamps[81]) bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { static char laststr[512]; - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,ind,errflag,dispflag,score,numvouts; char unsolved[82],solution[82],str[512]; uint32_t timestamps[81]; CTransaction vintx; uint256 hashBlock; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,ind,errflag,dispflag,score,numvouts; char unsolved[82],solution[82],str[512]; uint32_t lasttime,timestamps[81]; CTransaction vintx; uint256 hashBlock; if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -3030,16 +3030,19 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const fprintf(stderr,"%s score.%d %s\n",solution,score,unsolved); if ( sudoku_captcha(timestamps,height) < 0 ) return eval->Invalid("failed captcha"); - for (i=0; i<81; i++) + for (i=lasttime=0; i<81; i++) { if ( (ind= sudoku_minval(timestamps)) >= 0 ) { unsolved[ind] = solution[ind]; - timestamps[ind] = 0; + if ( lasttime == 0 ) + lasttime = timestamps[ind]; if ( dupree_solver(0,&score,unsolved) != 1 ) fprintf(stderr,"i.%d ind.%d non-unique\n",i,ind); if ( dispflag != 0 ) - fprintf(stderr,"%d ",score); + fprintf(stderr,"%d.%d ",score,timestamps[ind]-lasttime); + lasttime = timestamps[ind]; + timestamps[ind] = 0; } else break; } if ( dispflag != 0 ) From 7cb34662f7d9ccb569637b57eafad9b90bf094b2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 02:41:53 -1100 Subject: [PATCH 0221/1145] Errcheck --- src/cc/sudoku.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index b650b1d00..01016de81 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2555,13 +2555,13 @@ int32_t sudoku_captcha(uint32_t timestamps[81],int32_t height) } variance /= (n - 1); printf("solvetime.%d n.%d avetime.%d variance.%llu vs ave2 %d\n",solvetime,n,avetime,(long long)variance,avetime*avetime); - if ( variance < avetime*avetime ) - return(-1 * 0); + if ( variance < avetime ) + retval = -5; else return(0); } - } else retval = -5; + } else retval = -6; if ( retval != 0 ) - fprintf(stderr,"retval.%d\n",retval); + fprintf(stderr,"ERR >>>>>>>>>>>>>>> ht.%d retval.%d\n",height,retval); if ( height < 2000 ) return(0); else return(retval); @@ -2961,7 +2961,7 @@ int32_t sudoku_minval(uint32_t timestamps[81]) bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { static char laststr[512]; - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,ind,errflag,dispflag,score,numvouts; char unsolved[82],solution[82],str[512]; uint32_t lasttime,timestamps[81]; CTransaction vintx; uint256 hashBlock; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,ind,errflag,dispflag,score,numvouts; char unsolved[82],solution[82],str[512]; uint32_t timestamps[81]; CTransaction vintx; uint256 hashBlock; if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -2997,7 +2997,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const if ( strcmp(str,laststr) != 0 ) { strcpy(laststr,str); - fprintf(stderr,"\n%s\n",str); + fprintf(stderr,"%s\n",str); dispflag = 1; } else dispflag = 0; if ( sudoku_solutionopreturndecode(solution,timestamps,scriptPubKey) == 'S' ) @@ -3008,7 +3008,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const { for (i=errflag=0; i<81; i++) { - if ( dispflag != 0 ) + if ( 0 && dispflag != 0 ) fprintf(stderr,"%u ",timestamps[i]); if ( (timestamps[i] != 0 && unsolved[i] >= '1' && unsolved[i] <= '9') || (timestamps[i] == 0 && (unsolved[i] < '1' || unsolved[i] > '9')) ) errflag++; @@ -3030,7 +3030,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const fprintf(stderr,"%s score.%d %s\n",solution,score,unsolved); if ( sudoku_captcha(timestamps,height) < 0 ) return eval->Invalid("failed captcha"); - for (i=lasttime=0; i<81; i++) + /*for (i=lasttime=0; i<81; i++) { if ( (ind= sudoku_minval(timestamps)) >= 0 ) { @@ -3046,7 +3046,7 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const } else break; } if ( dispflag != 0 ) - fprintf(stderr,"scores convergence\n"); + fprintf(stderr,"scores convergence\n");*/ return(true); } else return eval->Invalid("invalid solution opret"); } From 659a5dda2a99090d67fc8d4de8a2d315ca600497 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 02:50:29 -1100 Subject: [PATCH 0222/1145] Initial validation --- src/cc/sudoku.cpp | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 01016de81..7cff6b280 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2517,7 +2517,7 @@ void sudoku_gen(uint8_t key32[32],uint8_t unsolved[9][9],uint32_t srandi) cclib solution 17 \"[%224d50336780d5a300a1f01b12fe36f46a82f3b9935bb115e01e0113dc4f337aae%22,%22234791685716258943589643712865934127341827596927516438492375861178462359653189274%22,0,0,1548859143,1548859146,0,1548859146,0,1548859148,1548859149,0,1548859151,1548859152,0,1548859154,1548859155,1548859158,1548859159,0,0,0,1548859161,1548859163,0,1548859164,1548859168,0,1548859168,1548859170,1548859172,1548859172,1548859175,0,0,1548859176,0,0,1548859178,1548859178,0,0,1548859180,1548859181,1548859183,1548859184,1548859185,1548859186,1548859188,1548859190,1548859191,1548859192,1548859192,0,0,1548859195,1548859196,1548859197,1548859198,0,0,1548859199,1548859202,1548859202,0,1548859204,1548859205,1548859206,1548859209,1548859210,1548859211,1548859212,0,1548859214,1548859216,0,1548859217,1548859218,1548859219,1548859220,0,1548859222,1548859222]\" */ -int32_t sudoku_captcha(uint32_t timestamps[81],int32_t height) +int32_t sudoku_captcha(int32_t dispflag,uint32_t timestamps[81],int32_t height) { int32_t i,solvetime,diff,avetime,n = 0,retval = 0; uint64_t variance = 0; std::vector list; for (i=0; i<81; i++) @@ -2549,20 +2549,22 @@ int32_t sudoku_captcha(uint32_t timestamps[81],int32_t height) for (i=0; i>>>>>>>>>>>>>> ht.%d retval.%d\n",height,retval); - if ( height < 2000 ) + if ( height <= 2036 ) return(0); else return(retval); } @@ -2863,7 +2865,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("sudokuaddr",CCaddr)); balance = CCaddress_balance(CCaddr); result.push_back(Pair("amount",ValueFromAmount(balance))); - if ( sudoku_captcha(timestamps,komodo_nextheight()) < 0 ) + if ( sudoku_captcha(1,timestamps,komodo_nextheight()) < 0 ) { result.push_back(Pair("result","error")); result.push_back(Pair("error","captcha failure")); @@ -3024,11 +3026,12 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const { if ( dispflag != 0 ) fprintf(stderr,"non-unique sudoku at ht.%d\n",height); - return eval->Invalid("invalid sudoku with multiple solutions"); + if ( strcmp(ASSETCHAINS_SYMBOL,"SUDOKU") != 0 ) + return eval->Invalid("invalid sudoku with multiple solutions"); } if ( dispflag != 0 ) fprintf(stderr,"%s score.%d %s\n",solution,score,unsolved); - if ( sudoku_captcha(timestamps,height) < 0 ) + if ( sudoku_captcha(dispflag,timestamps,height) < 0 ) return eval->Invalid("failed captcha"); /*for (i=lasttime=0; i<81; i++) { From 38c2c935099ef364e6ff0915f2d05f1f19b3953c Mon Sep 17 00:00:00 2001 From: Mihailo Milenkovic Date: Thu, 31 Jan 2019 18:44:36 +0100 Subject: [PATCH 0223/1145] Gateways validation (#16) - Validation implemented and enabled - Fixed partial sign spending marker - OracleFeed fixes --- src/cc/CCtx.cpp | 4 +- src/cc/dapps/oraclefeed.c | 16 +- src/cc/gateways.cpp | 496 ++++++++++++++++++++++++-------------- 3 files changed, 332 insertions(+), 184 deletions(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index 5228703ea..48b5927a5 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -380,7 +380,7 @@ int64_t CCaddress_balance(char *coinaddr) int64_t CCfullsupply(uint256 tokenid) { uint256 hashBlock; int32_t numvouts; CTransaction tx; std::vector origpubkey; std::string name,description; - if ( GetTransaction(tokenid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 ) + if ( myGetTransaction(tokenid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 0 ) { if (DecodeTokenCreateOpRet(tx.vout[numvouts-1].scriptPubKey,origpubkey,name,description)) { @@ -401,7 +401,7 @@ int64_t CCtoken_balance(char *coinaddr,uint256 reftokenid) for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { txid = it->first.txhash; - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts=tx.vout.size()) > 0 ) + if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts=tx.vout.size()) > 0 ) { char str[65]; std::vector voutTokenPubkeys; diff --git a/src/cc/dapps/oraclefeed.c b/src/cc/dapps/oraclefeed.c index 8f7ccb197..d6cf753f9 100644 --- a/src/cc/dapps/oraclefeed.c +++ b/src/cc/dapps/oraclefeed.c @@ -320,13 +320,13 @@ cJSON *get_komodocli(char *refcoin,char **retstrp,char *acname,char *method,char { if ( refcoin[0] != 0 && strcmp(refcoin,"KMD") != 0 ) printf("unexpected: refcoin.(%s) acname.(%s)\n",refcoin,acname); - sprintf(cmdstr,"./komodo-cli -ac_name=%s %s %s %s %s %s > %s\n",acname,method,arg0,arg1,arg2,arg3,fname); + sprintf(cmdstr,"./komodo-cli -ac_name=%s %s %s %s %s %s > %s 2>/tmp/oraclefeed.error\n",acname,method,arg0,arg1,arg2,arg3,fname); } else if ( strcmp(refcoin,"KMD") == 0 ) - sprintf(cmdstr,"./komodo-cli %s %s %s %s %s > %s\n",method,arg0,arg1,arg2,arg3,fname); + sprintf(cmdstr,"./komodo-cli %s %s %s %s %s > %s 2>/tmp/oraclefeed.error\n",method,arg0,arg1,arg2,arg3,fname); else if ( REFCOIN_CLI != 0 && REFCOIN_CLI[0] != 0 ) { - sprintf(cmdstr,"%s %s %s %s %s %s > %s\n",REFCOIN_CLI,method,arg0,arg1,arg2,arg3,fname); + sprintf(cmdstr,"%s %s %s %s %s %s > %s 2>/tmp/oraclefeed.error\n",REFCOIN_CLI,method,arg0,arg1,arg2,arg3,fname); printf("ref.(%s) REFCOIN_CLI (%s)\n",refcoin,cmdstr); } #ifdef TESTMODE @@ -590,7 +590,7 @@ void importaddress(char *refcoin,char *acname,char *depositaddr, char *label,int void addmultisigaddress(char *refcoin,char *acname,int32_t M, char *pubkeys) { - cJSON *retjson; char *retstr,Mstr[10],tmp[128]; + cJSON *retjson; char *retstr,Mstr[10],addr[64]; sprintf(Mstr,"%d",M); if ( (retjson= get_komodocli(refcoin,&retstr,acname,"addmultisigaddress",Mstr,pubkeys,"","")) != 0 ) @@ -600,6 +600,8 @@ void addmultisigaddress(char *refcoin,char *acname,int32_t M, char *pubkeys) } else if ( retstr != 0 ) { + sprintf(addr,"\"%s\"",retstr); + get_komodocli(refcoin,&retstr,acname,"importaddress",addr,"\"\"","false",""); printf("addmultisigaddress.(%s)\n",retstr); free_json(retjson); } @@ -678,7 +680,7 @@ char *createrawtx(char *refcoin,char *acname,char *depositaddr,char *withdrawadd free(argB); } else printf("not enough funds to create withdraw tx\n"); - } + } free_json(retjson); } else if ( retstr != 0 ) @@ -697,7 +699,7 @@ cJSON *addsignature(char *refcoin,char *acname,char *rawtx) { if ( is_cJSON_True(jobj(retjson,"complete")) != 0 ) return(retjson); - else if ( (hexstr= jstr(retjson,"hex")) != 0 && strlen(hexstr) > strlen(rawtx) + 2 ) + else if ((hexstr=jstr(retjson,"hex"))!= 0 && strlen(hexstr) > strlen(rawtx) + 2 ) { jaddnum(retjson,"partialtx",1); return(retjson); @@ -923,7 +925,7 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t } else rawtx=jstr(item,"hex"); K=jint(item,"number_of_signs"); - if ( (clijson= addsignature(refcoin,"",rawtx)) != 0 ) + if ( rawtx!=0 && (clijson= addsignature(refcoin,"",rawtx)) != 0 ) { if ( is_cJSON_True(jobj(clijson,"complete")) != 0 ) { diff --git a/src/cc/gateways.cpp b/src/cc/gateways.cpp index a16c2cf32..4e2f64184 100644 --- a/src/cc/gateways.cpp +++ b/src/cc/gateways.cpp @@ -267,14 +267,14 @@ uint8_t DecodeGatewaysWithdrawOpRet(const CScript &scriptPubKey, uint256& tokeni return(0); } -CScript EncodeGatewaysPartialOpRet(uint8_t funcid, uint256 withdrawtxid,std::string refcoin,int32_t K, CPubKey signerpk,std::string hex) +CScript EncodeGatewaysPartialOpRet(uint8_t funcid, uint256 withdrawtxid,std::string refcoin,uint8_t K, CPubKey signerpk,std::string hex) { CScript opret; uint8_t evalcode = EVAL_GATEWAYS; opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << withdrawtxid << refcoin << K << signerpk << hex); return(opret); } -uint8_t DecodeGatewaysPartialOpRet(const CScript &scriptPubKey,uint256 &withdrawtxid,std::string &refcoin,int32_t &K, CPubKey &signerpk,std::string &hex) +uint8_t DecodeGatewaysPartialOpRet(const CScript &scriptPubKey,uint256 &withdrawtxid,std::string &refcoin,uint8_t &K,CPubKey &signerpk,std::string &hex) { std::vector vopret; uint8_t *script,e,f; GetOpReturnData(scriptPubKey, vopret); @@ -286,38 +286,38 @@ uint8_t DecodeGatewaysPartialOpRet(const CScript &scriptPubKey,uint256 &withdraw return(0); } -CScript EncodeGatewaysCompleteSigningOpRet(uint8_t funcid,uint256 withdrawtxid,std::string refcoin,std::string hex) +CScript EncodeGatewaysCompleteSigningOpRet(uint8_t funcid,uint256 withdrawtxid,std::string refcoin,uint8_t K,std::string hex) { CScript opret; uint8_t evalcode = EVAL_GATEWAYS; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << withdrawtxid << refcoin << hex); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << withdrawtxid << refcoin << K << hex); return(opret); } -uint8_t DecodeGatewaysCompleteSigningOpRet(const CScript &scriptPubKey,uint256 &withdrawtxid,std::string &refcoin,std::string &hex) +uint8_t DecodeGatewaysCompleteSigningOpRet(const CScript &scriptPubKey,uint256 &withdrawtxid,std::string &refcoin,uint8_t &K,std::string &hex) { std::vector vopret; uint8_t *script,e,f; GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> withdrawtxid; ss >> refcoin; ss >> hex) != 0 ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> withdrawtxid; ss >> refcoin; ss >> K; ss >> hex) != 0 ) { return(f); } return(0); } -CScript EncodeGatewaysMarkDoneOpRet(uint8_t funcid,std::string refcoin,uint256 completetxid,uint256 withdrawtxid) +CScript EncodeGatewaysMarkDoneOpRet(uint8_t funcid,uint256 withdrawtxid,std::string refcoin,uint256 completetxid) { CScript opret; uint8_t evalcode = EVAL_GATEWAYS; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << refcoin << completetxid < vopret; uint8_t *script,e,f; GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> refcoin; ss >> completetxid; ss >> withdrawtxid;) != 0 ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> withdrawtxid; ss >> refcoin; ss >> completetxid;) != 0 ) { return(f); } @@ -541,16 +541,52 @@ int64_t GatewaysDepositval(CTransaction tx,CPubKey mypk) return(0); } +int32_t GatewaysBindExists(struct CCcontract_info *cp,CPubKey gatewayspk,uint256 reftokenid) +{ + char markeraddr[64],depositaddr[64]; std::string coin; int32_t numvouts; int64_t totalsupply; uint256 tokenid,oracletxid,hashBlock; + uint8_t M,N,taddr,prefix,prefix2; std::vector pubkeys; CTransaction tx; + std::vector > addressIndex; + + _GetCCaddress(markeraddr,EVAL_GATEWAYS,gatewayspk); + SetCCtxids(addressIndex,markeraddr); + for (std::vector >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) + { + if ( myGetTransaction(it->first.txhash,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 0 && DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey)=='B' ) + { + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) == 'B' ) + { + if ( tokenid == reftokenid ) + { + fprintf(stderr,"trying to bind an existing tokenid\n"); + return(1); + } + } + } + } + BOOST_FOREACH(const CTxMemPoolEntry &e, mempool.mapTx) + { + const CTransaction &txmempool = e.GetTx(); + const uint256 &hash = txmempool.GetHash(); + + if ((numvouts=txmempool.vout.size()) > 0 && DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey)=='B') + if (DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) == 'B' && + tokenid == reftokenid) + return(1); + } + + return(0); +} + bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction &tx, uint32_t nIn) { - int32_t numvins,numvouts,preventCCvins,preventCCvouts,i,numblocks,height,claimvout; bool retval; uint8_t funcid,hash[32],M,N,taddr,prefix,prefix2; + int32_t numvins,numvouts,preventCCvins,preventCCvouts,i,numblocks,height,claimvout; bool retval; uint8_t funcid,hash[32],K,M,N,taddr,prefix,prefix2; char str[65],destaddr[64],depositaddr[65],validationError[512]; - std::vector txids; std::vector pubkeys,publishers,tmppublishers; std::vector proof; int64_t totalsupply,amount,tmpamount; - uint256 hashblock,txid,bindtxid,deposittxid,tokenidClaim,oracletxid,tokenidBind,cointxid,tmptxid,tmpxtxid2,merkleroot,mhash; CTransaction bindtx,deposittx,oracletx; - std::string refcoin,tmprefcoin,deposithex; CPubKey destpub,tmpdestpub; + std::vector txids; std::vector pubkeys,publishers,tmppublishers; std::vector proof; int64_t fullsupply,totalsupply,amount,tmpamount; + uint256 hashblock,txid,bindtxid,deposittxid,withdrawtxid,completetxid,tokenid,tmptokenid,oracletxid,bindtokenid,cointxid,tmptxid,merkleroot,mhash; CTransaction bindtx,tmptx; + std::string refcoin,tmprefcoin,hex,name,description,format; CPubKey pubkey,tmppubkey,gatewayspk; - fprintf(stderr,"return true without gateways validation\n"); - return(true); + // fprintf(stderr,"return true without gateways validation\n"); + // return(true); numvins = tx.vin.size(); numvouts = tx.vout.size(); preventCCvins = preventCCvouts = -1; @@ -573,8 +609,9 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & // } // else // { - txid = tx.GetHash(); - memcpy(hash,&txid,sizeof(hash)); + // txid = tx.GetHash(); + // memcpy(hash,&txid,sizeof(hash)); + gatewayspk = GetUnspendable(cp,0); if ( (funcid = DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey)) != 0) { @@ -582,116 +619,261 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & { case 'B': //vin.0: normal input - //vout.0: CC vout txfee marker - //vout.n-1: opreturn - 'B' coin tokenid totalsupply oracletxid M N pubkeys taddr prefix prefix2 + //vin.1: CC input of tokens + //vout.0: CC vout of gateways tokens to gateways tokens CC address + //vout.1: CC vout txfee marker + //vout.n-1: opreturn - 'B' tokenid coin totalsupply oracletxid M N pubkeys taddr prefix prefix2 return eval->Invalid("unexpected GatewaysValidate for gatewaysbind!"); break; case 'D': //vin.0: normal input //vout.0: CC vout txfee marker to destination pubkey //vout.1: normal output txfee marker to txidaddr - //vout.n-1: opreturn - 'D' coin bindtxid publishers txids height cointxid deposithex proof destpub amount + //vout.n-1: opreturn - 'D' bindtxid coin publishers txids height cointxid claimvout deposithex proof destpub amount return eval->Invalid("unexpected GatewaysValidate for gatewaysdeposit!"); break; - case 't': + case 'C': //vin.0: normal input - //vin.1: CC input of converted token to gateways eval code + //vin.1: CC input of gateways tokens //vin.2: CC input of marker from gatewaysdeposit tx - //vout.0: CC vout of total tokens from deposit amount to asset eval code - //(vout.1): CC vout if there is change of unused tokens back to owner of tokens (deposit amount less than available tokens) - //vout.n-1: opreturn - 't' tokenid zeroid 0 mypubkey (NOTE: opreturn is with asset eval code) - // if ((numvouts=tx.vout.size()) > 0 && DecodeGatewaysClaimOpRet(tx.vout[numvouts-1].scriptPubKey,tokenidClaim,refcoin,bindtxid,deposittxid,destpub,amount)==0) - // return eval->Invalid("invalid gatewaysclaim OP_RETURN data!"); - // else if ( IsCCInput(tx.vin[0].scriptSig) != 0 ) - // return eval->Invalid("vin.0 is normal for gatewaysClaim!"); - // else if ( IsCCInput(tx.vin[1].scriptSig) == 0 ) - // return eval->Invalid("vin.1 is CC for gatewaysClaim!"); - // else if ( IsCCInput(tx.vin[2].scriptSig) == 0 ) - // return eval->Invalid("vin.2 is CC for gatewaysClaim!"); - // else if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) - // return eval->Invalid("vout.0 is CC for gatewaysClaim!"); - // else if ( numvouts > 2 && tx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 ) - // return eval->Invalid("vout.1 is CC for gatewaysClaim!"); - // else if (myGetTransaction(bindtxid,bindtx,hashblock) == 0) - // return eval->Invalid("invalid gatewaysbind txid!"); - // else if ((numvouts=bindtx.vout.size()) > 0 && DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tmprefcoin,tokenidBind,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B') - // return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); - // else if (tmprefcoin!=refcoin) - // return eval->Invalid("refcoin different in bind tx"); - // else if (tokenidClaim!=tokenidBind) - // return eval->Invalid("tokenid does not match tokenid from gatewaysbind"); - // else if (komodo_txnotarizedconfirmed(bindtxid) == false) - // return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); - // else if (myGetTransaction(deposittxid,deposittx,hashblock) == 0) - // return eval->Invalid("invalid gatewaysdeposittxid!"); - // else if ((numvouts=deposittx.vout.size()) > 0 && DecodeGatewaysDepositOpRet(deposittx.vout[numvouts-1].scriptPubKey,tmprefcoin,tmptxid,tmppublishers,txids,height,cointxid,claimvout,deposithex,proof,tmpdestpub,tmpamount) != 'D') - // return eval->Invalid("invalid gatewaysdeposit OP_RETURN data!"); - // else if (tmprefcoin!=refcoin) - // return eval->Invalid("refcoin different in deposit tx"); - // else if (bindtxid!=tmptxid) - // return eval->Invalid("bindtxid does not match to bindtxid from gatewaysdeposit"); - // else if (tmpamount>totalsupply) - // return eval->Invalid("deposit amount greater then bind total supply"); - // else if (komodo_txnotarizedconfirmed(deposittxid) == false) - // return eval->Invalid("gatewaysdeposit tx is not yet confirmed(notarised)!"); - // else if (amount>tmpamount) - // return eval->Invalid("claimed amount greater then deposit amount"); - // else if (destpub!=tmpdestpub) - // return eval->Invalid("destination pubkey different than in deposit tx"); - // else - // { - // int32_t m; - // merkleroot = zeroid; - // for (i=m=0; iInvalid(validationError); - // } - // if ( GatewaysCointxidExists(cp,cointxid) != 0 ) - // { - // sprintf(validationError,"cointxid.%s already exists\n",uint256_str(str,cointxid)); - // return eval->Invalid(validationError); - // } - // if (GatewaysVerify(depositaddr,oracletxid,claimvout,tmprefcoin,cointxid,deposithex,proof,merkleroot,destpub)!=amount) - // return eval->Invalid("deposittxid didnt validate\n"); - // } + //vout.0: CC vout of tokens from deposit amount to destinatoin pubkey + //vout.1: CC vout change of gateways tokens to gateways tokens CC address (if any) + //vout.n-1: opreturn - 'C' tokenid bindtxid coin deposittxid destpub amount + if ((numvouts=tx.vout.size()) < 1 || DecodeGatewaysClaimOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,refcoin,deposittxid,pubkey,amount)!='C') + return eval->Invalid("invalid gatewaysClaim OP_RETURN data!"); + else if ( IsCCInput(tx.vin[0].scriptSig) != 0 ) + return eval->Invalid("vin.0 is normal for gatewaysClaim!"); + else if ( IsCCInput(tx.vin[1].scriptSig) == 0 ) + return eval->Invalid("vin.1 is CC for gatewaysClaim!"); + else if ( IsCCInput(tx.vin[2].scriptSig) == 0 ) + return eval->Invalid("vin.2 is CC for gatewaysClaim!"); + else if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) + return eval->Invalid("vout.0 is CC for gatewaysClaim!"); + else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) + return eval->Invalid("invalid gatewaysbind txid!"); + else if ((numvouts=tmptx.vout.size()) < 1 || DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B') + return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); + else if (tmprefcoin!=refcoin) + return eval->Invalid("refcoin different than in bind tx"); + else if (tmptokenid!=tokenid) + return eval->Invalid("tokenid does not match tokenid from gatewaysbind"); + else if ( N == 0 || N > 15 || M > N ) + return eval->Invalid("invalid MofN in gatewaysbind"); + else if (pubkeys.size()!=N) + { + sprintf(validationError,"not enough pubkeys(%ld) for N.%d gatewaysbind ",pubkeys.size(),N); + return eval->Invalid(validationError); + } + else if ( (fullsupply=CCfullsupply(tokenid)) != totalsupply ) + { + sprintf(validationError,"Gateway bind.%s (%s) globaladdr.%s totalsupply %.8f != fullsupply %.8f\n",refcoin.c_str(),uint256_str(str,tokenid),cp->unspendableCCaddr,(double)totalsupply/COIN,(double)fullsupply/COIN); + return eval->Invalid(validationError); + } + else if (myGetTransaction(oracletxid,tmptx,hashblock) == 0 || (numvouts=tmptx.vout.size()) <= 0 ) + { + sprintf(validationError,"cant find oracletxid %s\n",uint256_str(str,oracletxid)); + return eval->Invalid(validationError); + } + else if ( DecodeOraclesCreateOpRet(tmptx.vout[numvouts-1].scriptPubKey,name,description,format) != 'C' ) + { + sprintf(validationError,"mismatched oracle name %s != %s\n",name.c_str(),refcoin.c_str()); + return eval->Invalid(validationError); + } + else if (format.size()!=3 || strncmp(format.c_str(),"Ihh",3)!=0) + { + sprintf(validationError,"illegal format %s != Ihh\n",format.c_str()); + return eval->Invalid(validationError); + } + else if (komodo_txnotarizedconfirmed(bindtxid) == false) + return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); + else if (myGetTransaction(deposittxid,tmptx,hashblock) == 0) + return eval->Invalid("invalid gatewaysdeposittxid!"); + else if ((numvouts=tmptx.vout.size()) < 1 || DecodeGatewaysDepositOpRet(tmptx.vout[numvouts-1].scriptPubKey,tmptxid,tmprefcoin,tmppublishers,txids,height,cointxid,claimvout,hex,proof,tmppubkey,tmpamount) != 'D') + return eval->Invalid("invalid gatewaysdeposit OP_RETURN data!"); + else if (tmprefcoin!=refcoin) + return eval->Invalid("refcoin different than in deposit tx"); + else if (bindtxid!=tmptxid) + return eval->Invalid("bindtxid does not match to bindtxid from gatewaysdeposit"); + else if (tmpamount>totalsupply) + return eval->Invalid("deposit amount greater then bind total supply"); + else if (komodo_txnotarizedconfirmed(deposittxid) == false) + return eval->Invalid("gatewaysdeposit tx is not yet confirmed(notarised)!"); + else if (amount!=tmpamount) + return eval->Invalid("claimed amount different then deposit amount"); + else if (tx.vout[0].nValue!=amount) + return eval->Invalid("claim amount not matching amount in opret"); + else if (pubkey!=tmppubkey) + return eval->Invalid("claim destination pubkey different than in deposit tx"); + else + { + int32_t m; + merkleroot = zeroid; + for (i=m=0; iInvalid(validationError); + } + else if (GatewaysVerify(depositaddr,oracletxid,claimvout,tmprefcoin,cointxid,hex,proof,merkleroot,pubkey)!=amount) + return eval->Invalid("external deposit not verified\n"); + } break; case 'W': //vin.0: normal input - //vin.1: CC input of converted token back to gateways eval code - //vout.0: CC vout of tokens back to gateways CC address - //vout.1: normal vout txfee marker to withdraw destination pubkey - //vout.2: CC vout txfee marker to gateways CC address - //vout.n-2: CC vout if there is change of unused tokens back to owner of tokens (withdraw amount less than owner available tokens) - //vout.n-1: opreturn - 'W' tokenid refcoin withdrawpub amount + //vin.1: CC input of tokens + //vout.0: CC vout txfee marker to gateways CC address + //vout.1: CC vout of gateways tokens back to gateways tokens CC address + //vout.2: CC vout change of tokens back to owners pubkey (if any) + //vout.n-1: opreturn - 'W' tokenid bindtxid refcoin withdrawpub amount + return eval->Invalid("unexpected GatewaysValidate for gatewaysWithdraw!"); break; case 'P': //vin.0: normal input - //(vin.1): CC input form previous marker of gatewayspartialsign tx (if exists) - //vout.0: CC vout 5k sat marker to senders pubKey - //vout.n-1: opreturn - 'P' number_of_signs mypk refcoin hex + //vin.1: CC input of marker from previous tx (withdraw or partialsing) + //vout.0: CC vout txfee marker to gateways CC address + //vout.n-1: opreturn - 'P' withdrawtxid refcoin number_of_signs mypk hex + if ((numvouts=tx.vout.size()) > 0 && DecodeGatewaysPartialOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,refcoin,K,pubkey,hex)!='P') + return eval->Invalid("invalid gatewaysPartialSign OP_RETURN data!"); + else if ( IsCCInput(tx.vin[0].scriptSig) != 0 ) + return eval->Invalid("vin.0 is normal for gatewaysPartialSign!"); + else if ( IsCCInput(tx.vin[1].scriptSig) == 0 ) + return eval->Invalid("vin.1 is CC for gatewaysPartialSign!"); + else if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) + return eval->Invalid("vout.0 is CC for gatewaysPartialSign!"); + else if (myGetTransaction(withdrawtxid,tmptx,hashblock) == 0) + return eval->Invalid("invalid withdraw txid!"); + else if ((numvouts=tmptx.vout.size()) > 0 && DecodeGatewaysWithdrawOpRet(tmptx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,tmprefcoin,pubkey,amount)!='W') + return eval->Invalid("invalid gatewayswithdraw OP_RETURN data!"); + else if (tmprefcoin!=refcoin) + return eval->Invalid("refcoin different than in bind tx"); + else if ( IsCCInput(tmptx.vin[0].scriptSig) != 0 ) + return eval->Invalid("vin.0 is normal for gatewaysWithdraw!"); + else if ( IsCCInput(tmptx.vin[1].scriptSig) == 0 ) + return eval->Invalid("vin.1 is CC for gatewaysWithdraw!"); + else if ( tmptx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) + return eval->Invalid("vout.0 is CC for gatewaysWithdraw!"); + else if ( tmptx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 ) + return eval->Invalid("vout.1 is CC for gatewaysWithdraw!"); + else if (tmptx.vout[1].nValue!=amount) + return eval->Invalid("amount in opret not matching tx tokens amount!"); + else if (komodo_txnotarizedconfirmed(withdrawtxid) == false) + return eval->Invalid("gatewayswithdraw tx is not yet confirmed(notarised)!"); + else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) + return eval->Invalid("invalid gatewaysbind txid!"); + else if ((numvouts=tmptx.vout.size()) < 1 || DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B') + return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); + else if (tmprefcoin!=refcoin) + return eval->Invalid("refcoin different than in bind tx"); + else if (tmptokenid!=tokenid) + return eval->Invalid("tokenid does not match tokenid from gatewaysbind"); + else if (komodo_txnotarizedconfirmed(bindtxid) == false) + return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); + else if (K>M) + return eval->Invalid("invalid number of signs!"); break; - case 'C': - //vin.0: CC input from gatewayswithdraw tx marker to gateways CC address + case 'S': + //vin.0: normal input + //vin.1: CC input of marker from previous tx (withdraw or partialsing) //vout.0: CC vout txfee marker to gateways CC address - //vout.n-1: opreturn - 'C' refcoin cointxid external_tx_hex + //vout.n-1: opreturn - 'S' withdrawtxid refcoin hex + if ((numvouts=tx.vout.size()) > 0 && DecodeGatewaysCompleteSigningOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,refcoin,K,hex)!='S') + return eval->Invalid("invalid gatewayscompletesigning OP_RETURN data!"); + else if ( IsCCInput(tx.vin[0].scriptSig) != 0 ) + return eval->Invalid("vin.0 is normal for gatewayscompletesigning!"); + else if ( IsCCInput(tx.vin[1].scriptSig) == 0 ) + return eval->Invalid("vin.1 is CC for gatewayscompletesigning!"); + else if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) + return eval->Invalid("vout.0 is CC for gatewayscompletesigning!"); + else if (myGetTransaction(withdrawtxid,tmptx,hashblock) == 0) + return eval->Invalid("invalid withdraw txid!"); + else if ((numvouts=tmptx.vout.size()) > 0 && DecodeGatewaysWithdrawOpRet(tmptx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,tmprefcoin,pubkey,amount)!='W') + return eval->Invalid("invalid gatewayswithdraw OP_RETURN data!"); + else if (tmprefcoin!=refcoin) + return eval->Invalid("refcoin different than in bind tx"); + else if ( IsCCInput(tmptx.vin[0].scriptSig) != 0 ) + return eval->Invalid("vin.0 is normal for gatewaysWithdraw!"); + else if ( IsCCInput(tmptx.vin[1].scriptSig) == 0 ) + return eval->Invalid("vin.1 is CC for gatewaysWithdraw!"); + else if ( tmptx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) + return eval->Invalid("vout.0 is CC for gatewaysWithdraw!"); + else if ( tmptx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 ) + return eval->Invalid("vout.1 is CC for gatewaysWithdraw!"); + else if (tmptx.vout[1].nValue!=amount) + return eval->Invalid("amount in opret not matching tx tokens amount!"); + else if (komodo_txnotarizedconfirmed(withdrawtxid) == false) + return eval->Invalid("gatewayswithdraw tx is not yet confirmed(notarised)!"); + else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) + return eval->Invalid("invalid gatewaysbind txid!"); + else if ((numvouts=tmptx.vout.size()) < 1 || DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B') + return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); + else if (tmprefcoin!=refcoin) + return eval->Invalid("refcoin different than in bind tx"); + else if (tmptokenid!=tokenid) + return eval->Invalid("tokenid does not match tokenid from gatewaysbind"); + else if (komodo_txnotarizedconfirmed(bindtxid) == false) + return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); + else if (K!=M) + return eval->Invalid("invalid number of signs!"); break; case 'M': - //vin.0: CC input from gatewayscompletesigning tx marker to gateways CC address - //vout.0: opreturn - 'M' refcoin cointxid + //vin.0: CC input of gatewayscompletesigning tx marker to gateways CC address + //vout.0: opreturn - 'M' withdrawtxid refcoin completetxid + if ((numvouts=tx.vout.size()) > 0 && DecodeGatewaysMarkDoneOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,refcoin,completetxid)!='M') + return eval->Invalid("invalid gatewaysmarkdone OP_RETURN data!"); + else if ( IsCCInput(tx.vin[0].scriptSig) == 0 ) + return eval->Invalid("vin.0 is CC for gatewaysmarkdone!"); + else if (myGetTransaction(completetxid,tmptx,hashblock) == 0) + return eval->Invalid("invalid gatewaygatewayscompletesigning txid!"); + else if ((numvouts=tmptx.vout.size()) > 0 && DecodeGatewaysCompleteSigningOpRet(tmptx.vout[numvouts-1].scriptPubKey,withdrawtxid,tmprefcoin,K,hex)!='S') + return eval->Invalid("invalid gatewayscompletesigning OP_RETURN data!"); + else if ( IsCCInput(tmptx.vin[0].scriptSig) != 0 ) + return eval->Invalid("vin.0 is normal for gatewayscompletesigning!"); + else if ( IsCCInput(tmptx.vin[1].scriptSig) == 0 ) + return eval->Invalid("vin.1 is CC for gatewayscompletesigning!"); + else if ( tmptx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) + return eval->Invalid("vout.0 is CC for gatewayscompletesigning!"); + else if (myGetTransaction(withdrawtxid,tmptx,hashblock) == 0) + return eval->Invalid("invalid withdraw txid!"); + else if ((numvouts=tmptx.vout.size()) > 0 && DecodeGatewaysWithdrawOpRet(tmptx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,tmprefcoin,pubkey,amount)!='W') + return eval->Invalid("invalid gatewayswithdraw OP_RETURN data!"); + else if (tmprefcoin!=refcoin) + return eval->Invalid("refcoin different than in bind tx"); + else if ( IsCCInput(tmptx.vin[0].scriptSig) != 0 ) + return eval->Invalid("vin.0 is normal for gatewaysWithdraw!"); + else if ( IsCCInput(tmptx.vin[1].scriptSig) == 0 ) + return eval->Invalid("vin.1 is CC for gatewaysWithdraw!"); + else if ( tmptx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) + return eval->Invalid("vout.0 is CC for gatewaysWithdraw!"); + else if ( tmptx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 ) + return eval->Invalid("vout.1 is CC for gatewaysWithdraw!"); + else if ( tmptx.vout[1].nValue!=amount) + return eval->Invalid("amount in opret not matching tx tokens amount!"); + else if (komodo_txnotarizedconfirmed(withdrawtxid) == false) + return eval->Invalid("gatewayswithdraw tx is not yet confirmed(notarised)!"); + else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) + return eval->Invalid("invalid gatewaysbind txid!"); + else if ((numvouts=tmptx.vout.size()) < 1 || DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B') + return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); + else if (tmprefcoin!=refcoin) + return eval->Invalid("refcoin different than in bind tx"); + else if (tmptokenid!=tokenid) + return eval->Invalid("tokenid does not match tokenid from gatewaysbind"); + else if (komodo_txnotarizedconfirmed(bindtxid) == false) + return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); + else if (K!=M) + return eval->Invalid("invalid number of signs!"); break; } } @@ -769,41 +951,6 @@ int64_t AddGatewaysInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CP return(0); } -int32_t GatewaysBindExists(struct CCcontract_info *cp,CPubKey gatewayspk,uint256 reftokenid) -{ - char markeraddr[64],depositaddr[64]; std::string coin; int32_t numvouts; int64_t totalsupply; uint256 tokenid,oracletxid,hashBlock; - uint8_t M,N,taddr,prefix,prefix2; std::vector pubkeys; CTransaction tx; - std::vector > addressIndex; - - _GetCCaddress(markeraddr,EVAL_GATEWAYS,gatewayspk); - SetCCtxids(addressIndex,markeraddr); - for (std::vector >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) - { - if ( GetTransaction(it->first.txhash,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 ) - { - if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) == 'B' ) - { - if ( tokenid == reftokenid ) - { - fprintf(stderr,"trying to bind an existing tokenid\n"); - return(1); - } - } - } - } - BOOST_FOREACH(const CTxMemPoolEntry &e, mempool.mapTx) - { - const CTransaction &txmempool = e.GetTx(); - const uint256 &hash = txmempool.GetHash(); - - if ((numvouts=txmempool.vout.size()) > 0 && DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) == 'B' && - tokenid == reftokenid) - return(1); - } - - return(0); -} - std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t totalsupply,uint256 oracletxid,uint8_t M,uint8_t N,std::vector pubkeys) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); @@ -1027,8 +1174,8 @@ std::string GatewaysClaim(uint64_t txfee,uint256 bindtxid,std::string refcoin,ui std::string GatewaysWithdraw(uint64_t txfee,uint256 bindtxid,std::string refcoin,CPubKey withdrawpub,int64_t amount) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CTransaction tx; CPubKey mypk,gatewayspk,signerpk; uint256 txid,tokenid,hashBlock,oracletxid,tmptokenid,tmpbindtxid,withdrawtxid; int32_t K,vout,numvouts; - int64_t nValue,totalsupply,inputs,CCchange=0; uint8_t funcid,M,N,taddr,prefix,prefix2; std::string coin,hex; + CTransaction tx; CPubKey mypk,gatewayspk,signerpk; uint256 txid,tokenid,hashBlock,oracletxid,tmptokenid,tmpbindtxid,withdrawtxid; int32_t vout,numvouts; + int64_t nValue,totalsupply,inputs,CCchange=0; uint8_t funcid,K,M,N,taddr,prefix,prefix2; std::string coin,hex; std::vector msigpubkeys; char depositaddr[64],str[65],coinaddr[64]; struct CCcontract_info *cp,C,*cpTokens,CTokens; std::vector > unspentOutputs; @@ -1084,8 +1231,7 @@ std::string GatewaysWithdraw(uint64_t txfee,uint256 bindtxid,std::string refcoin { if ( inputs > amount ) CCchange = (inputs - amount); mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,txfee,gatewayspk)); - mtx.vout.push_back(MakeTokensCC1vout(EVAL_GATEWAYS,amount,gatewayspk)); - //mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(HexStr(withdrawpub)) << OP_CHECKSIG)); + mtx.vout.push_back(MakeTokensCC1vout(EVAL_GATEWAYS,amount,gatewayspk)); if ( CCchange != 0 ) mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, CCchange, mypk)); return(FinalizeCCTx(0, cpTokens, mtx, mypk, txfee,EncodeGatewaysWithdrawOpRet('W',tokenid,bindtxid,refcoin,withdrawpub,amount))); } @@ -1104,10 +1250,10 @@ std::string GatewaysWithdraw(uint64_t txfee,uint256 bindtxid,std::string refcoin std::string GatewaysPartialSign(uint64_t txfee,uint256 lasttxid,std::string refcoin, std::string hex) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CPubKey mypk,withdrawpub,signerpk,gatewayspk; struct CCcontract_info *cp,C; CTransaction tx,bindtx; + CPubKey mypk,withdrawpub,signerpk,gatewayspk; struct CCcontract_info *cp,C; CTransaction tx,tmptx; std::vector > unspentOutputs; char funcid,str[65],depositaddr[64]; - int32_t numvouts,K=0; uint256 withdrawtxid,hashBlock,bindtxid,tokenid,oracletxid,tmptokenid; std::string coin,tmphex; int64_t amount,totalsupply; - uint8_t M,N,taddr,prefix,prefix2; std::vector pubkeys; + int32_t numvouts; uint256 withdrawtxid,hashBlock,bindtxid,tokenid,oracletxid,tmptokenid; std::string coin,tmphex; int64_t amount,totalsupply; + uint8_t K=0,M,N,taddr,prefix,prefix2; std::vector pubkeys; cp = CCinit(&C,EVAL_GATEWAYS); if ( txfee == 0 ) @@ -1130,13 +1276,13 @@ std::string GatewaysPartialSign(uint64_t txfee,uint256 lasttxid,std::string refc fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (GetTransaction(bindtxid,bindtx,hashBlock,false)==0 || (numvouts=bindtx.vout.size())<=0) + else if (GetTransaction(bindtxid,tmptx,hashBlock,false)==0 || (numvouts=tmptx.vout.size())<=0) { CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); @@ -1152,26 +1298,26 @@ std::string GatewaysPartialSign(uint64_t txfee,uint256 lasttxid,std::string refc fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (GetTransaction(withdrawtxid,tx,hashBlock,false)==0 || (numvouts= tx.vout.size())<=0) + else if (GetTransaction(withdrawtxid,tmptx,hashBlock,false)==0 || (numvouts= tmptx.vout.size())<=0) { CCerror = strprintf("can't find withdraw tx %s\n",uint256_str(str,withdrawtxid)); fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' + else if (DecodeGatewaysWithdrawOpRet(tmptx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) { CCerror = strprintf("invalid withdraw tx %s\n",uint256_str(str,lasttxid)); fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (GetTransaction(bindtxid,bindtx,hashBlock,false)==0 || (numvouts=bindtx.vout.size())<=0) + else if (GetTransaction(bindtxid,tmptx,hashBlock,false)==0 || (numvouts=tmptx.vout.size())<=0) { CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); @@ -1189,8 +1335,8 @@ std::string GatewaysCompleteSigning(uint64_t txfee,uint256 lasttxid,std::string { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); CPubKey mypk,gatewayspk,signerpk,withdrawpub; struct CCcontract_info *cp,C; char funcid,str[65],depositaddr[64]; int64_t amount,totalsupply; - std::string coin,tmphex; CTransaction tx,bindtx; uint256 withdrawtxid,hashBlock,tokenid,tmptokenid,bindtxid,oracletxid; int32_t K=0,numvouts; - uint8_t M,N,taddr,prefix,prefix2; std::vector pubkeys; + std::string coin,tmphex; CTransaction tx,tmptx; uint256 withdrawtxid,hashBlock,tokenid,tmptokenid,bindtxid,oracletxid; int32_t numvouts; + uint8_t K=0,M,N,taddr,prefix,prefix2; std::vector pubkeys; cp = CCinit(&C,EVAL_GATEWAYS); mypk = pubkey2pk(Mypubkey()); @@ -1213,13 +1359,13 @@ std::string GatewaysCompleteSigning(uint64_t txfee,uint256 lasttxid,std::string fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (GetTransaction(bindtxid,bindtx,hashBlock,false)==0 || (numvouts=tx.vout.size())<=0) + else if (GetTransaction(bindtxid,tmptx,hashBlock,false)==0 || (numvouts=tmptx.vout.size())<=0) { CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); @@ -1235,26 +1381,26 @@ std::string GatewaysCompleteSigning(uint64_t txfee,uint256 lasttxid,std::string fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (GetTransaction(withdrawtxid,tx,hashBlock,false)==0 || (numvouts=tx.vout.size())==0) + else if (GetTransaction(withdrawtxid,tmptx,hashBlock,false)==0 || (numvouts=tmptx.vout.size())==0) { CCerror = strprintf("invalid withdraw txid %s\n",uint256_str(str,withdrawtxid)); fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) + else if (DecodeGatewaysWithdrawOpRet(tmptx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) { printf("aaaaaaaaaaa\n"); CCerror = strprintf("cannot decode withdraw tx opret %s\n",uint256_str(str,withdrawtxid)); fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (GetTransaction(bindtxid,bindtx,hashBlock,false)==0 || (numvouts=bindtx.vout.size())<=0) + else if (GetTransaction(bindtxid,tmptx,hashBlock,false)==0 || (numvouts=tmptx.vout.size())<=0) { CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); @@ -1265,15 +1411,15 @@ std::string GatewaysCompleteSigning(uint64_t txfee,uint256 lasttxid,std::string if (AddNormalinputs(mtx,mypk,txfee,3)==0) fprintf(stderr,"error adding funds for completesigning\n"); mtx.vin.push_back(CTxIn(lasttxid,0,CScript())); mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,txfee,gatewayspk)); - return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysCompleteSigningOpRet('S',withdrawtxid,refcoin,hex))); + return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysCompleteSigningOpRet('S',withdrawtxid,refcoin,K+1,hex))); } std::string GatewaysMarkDone(uint64_t txfee,uint256 completetxid,std::string refcoin) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CPubKey mypk; struct CCcontract_info *cp,C; char str[65],depositaddr[64]; CTransaction tx,bindtx; int32_t numvouts; + CPubKey mypk; struct CCcontract_info *cp,C; char str[65],depositaddr[64]; CTransaction tx; int32_t numvouts; uint256 withdrawtxid,bindtxid,oracletxid,tokenid,tmptokenid,hashBlock; std::string coin,hex; - uint8_t M,N,taddr,prefix,prefix2; std::vector pubkeys; int64_t amount,totalsupply; CPubKey withdrawpub; + uint8_t K,M,N,taddr,prefix,prefix2; std::vector pubkeys; int64_t amount,totalsupply; CPubKey withdrawpub; cp = CCinit(&C,EVAL_GATEWAYS); mypk = pubkey2pk(Mypubkey()); @@ -1285,7 +1431,7 @@ std::string GatewaysMarkDone(uint64_t txfee,uint256 completetxid,std::string ref fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (DecodeGatewaysCompleteSigningOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,hex)!='S' || refcoin!=coin) + else if (DecodeGatewaysCompleteSigningOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,K,hex)!='S' || refcoin!=coin) { CCerror = strprintf("cannot decode completesigning tx opret %s\n",uint256_str(str,completetxid)); fprintf(stderr,"%s\n", CCerror.c_str() ); @@ -1303,13 +1449,13 @@ std::string GatewaysMarkDone(uint64_t txfee,uint256 completetxid,std::string ref fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (GetTransaction(bindtxid,bindtx,hashBlock,false)==0 || (numvouts=bindtx.vout.size())<=0) + else if (GetTransaction(bindtxid,tx,hashBlock,false)==0 || (numvouts=tx.vout.size())<=0) { CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); fprintf(stderr,"%s\n", CCerror.c_str() ); return(""); } - else if (DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + else if (DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); @@ -1317,7 +1463,7 @@ std::string GatewaysMarkDone(uint64_t txfee,uint256 completetxid,std::string ref return(""); } mtx.vin.push_back(CTxIn(completetxid,0,CScript())); - return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysMarkDoneOpRet('M',refcoin,completetxid,withdrawtxid))); + return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysMarkDoneOpRet('M',withdrawtxid,refcoin,completetxid))); } UniValue GatewaysPendingDeposits(uint256 bindtxid,std::string refcoin) @@ -1377,9 +1523,9 @@ UniValue GatewaysPendingDeposits(uint256 bindtxid,std::string refcoin) UniValue GatewaysPendingWithdraws(uint256 bindtxid,std::string refcoin) { UniValue result(UniValue::VOBJ),pending(UniValue::VARR); CTransaction tx; std::string coin,hex; CPubKey mypk,gatewayspk,withdrawpub,signerpk; - std::vector msigpubkeys; uint256 hashBlock,tokenid,txid,tmpbindtxid,tmptokenid,oracletxid,withdrawtxid; uint8_t M,N,taddr,prefix,prefix2; + std::vector msigpubkeys; uint256 hashBlock,tokenid,txid,tmpbindtxid,tmptokenid,oracletxid,withdrawtxid; uint8_t K,M,N,taddr,prefix,prefix2; char funcid,depositaddr[65],coinaddr[65],tokensaddr[65],destaddr[65],str[65],withaddr[65],numstr[32],signeraddr[65],txidaddr[65]; - int32_t i,n,numvouts,vout,queueflag,K; int64_t totalsupply,amount,nValue; struct CCcontract_info *cp,C; + int32_t i,n,numvouts,vout,queueflag; int64_t totalsupply,amount,nValue; struct CCcontract_info *cp,C; std::vector > unspentOutputs; cp = CCinit(&C,EVAL_GATEWAYS); @@ -1466,7 +1612,7 @@ UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin) { UniValue result(UniValue::VOBJ),processed(UniValue::VARR); CTransaction tx; std::string coin,hex; CPubKey mypk,gatewayspk,withdrawpub; std::vector msigpubkeys; - uint256 withdrawtxid,hashBlock,txid,tokenid,tmptokenid,oracletxid; uint8_t M,N,taddr,prefix,prefix2; + uint256 withdrawtxid,hashBlock,txid,tokenid,tmptokenid,oracletxid; uint8_t K,M,N,taddr,prefix,prefix2; char depositaddr[65],coinaddr[65],str[65],numstr[32],withaddr[65],txidaddr[65]; int32_t i,n,numvouts,vout,queueflag; int64_t totalsupply,nValue,amount; struct CCcontract_info *cp,C; std::vector > unspentOutputs; @@ -1502,7 +1648,7 @@ UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin) vout = (int32_t)it->first.index; nValue = (int64_t)it->second.satoshis; if ( vout == 0 && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 && - DecodeGatewaysCompleteSigningOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,hex) == 'S' && refcoin == coin && myIsutxo_spentinmempool(txid,vout) == 0) + DecodeGatewaysCompleteSigningOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,K,hex) == 'S' && refcoin == coin && myIsutxo_spentinmempool(txid,vout) == 0) { if (GetTransaction(withdrawtxid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 && DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount) == 'W' || refcoin!=coin || tmptokenid!=tokenid) From 8ceece2007059e47d1a1e11128c19e18848ce6fa Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 08:32:06 -1100 Subject: [PATCH 0224/1145] Marmaralock fix --- src/cc/marmara.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/marmara.cpp b/src/cc/marmara.cpp index 0e301ba97..f10e88924 100644 --- a/src/cc/marmara.cpp +++ b/src/cc/marmara.cpp @@ -441,7 +441,7 @@ UniValue MarmaraLock(uint64_t txfee,int64_t amount,int32_t height) val -= txfee; else val = amount; if ( val > txfee ) - inputsum = AddNormalinputs2(mtx,val,CC_MAXVINS/2); + inputsum = AddNormalinputs(mtx,val,CC_MAXVINS/2); //fprintf(stderr,"normal inputs %.8f val %.8f\n",(double)inputsum/COIN,(double)val/COIN); mtx.vout.push_back(MakeCC1of2vout(EVAL_MARMARA,amount,Marmarapk,mypk)); if ( inputsum < amount+txfee ) From 02398a92e58380bf71731eebe2c58ad4e111c0f9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 08:35:23 -1100 Subject: [PATCH 0225/1145] Addnormalinputs --- src/cc/marmara.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/marmara.cpp b/src/cc/marmara.cpp index f10e88924..be3c02432 100644 --- a/src/cc/marmara.cpp +++ b/src/cc/marmara.cpp @@ -441,7 +441,7 @@ UniValue MarmaraLock(uint64_t txfee,int64_t amount,int32_t height) val -= txfee; else val = amount; if ( val > txfee ) - inputsum = AddNormalinputs(mtx,val,CC_MAXVINS/2); + inputsum = AddNormalinputs(mtx,mypk,val,CC_MAXVINS/2); //fprintf(stderr,"normal inputs %.8f val %.8f\n",(double)inputsum/COIN,(double)val/COIN); mtx.vout.push_back(MakeCC1of2vout(EVAL_MARMARA,amount,Marmarapk,mypk)); if ( inputsum < amount+txfee ) From 7f042611e4f21d0d40722448b8d120e8e8bcb4dd Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 08:59:09 -1100 Subject: [PATCH 0226/1145] Add rpcwallet locks --- src/cc/marmara.cpp | 2 +- src/wallet/rpcwallet.cpp | 46 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/cc/marmara.cpp b/src/cc/marmara.cpp index be3c02432..0e301ba97 100644 --- a/src/cc/marmara.cpp +++ b/src/cc/marmara.cpp @@ -441,7 +441,7 @@ UniValue MarmaraLock(uint64_t txfee,int64_t amount,int32_t height) val -= txfee; else val = amount; if ( val > txfee ) - inputsum = AddNormalinputs(mtx,mypk,val,CC_MAXVINS/2); + inputsum = AddNormalinputs2(mtx,val,CC_MAXVINS/2); //fprintf(stderr,"normal inputs %.8f val %.8f\n",(double)inputsum/COIN,(double)val/COIN); mtx.vout.push_back(MakeCC1of2vout(EVAL_MARMARA,amount,Marmarapk,mypk)); if ( inputsum < amount+txfee ) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 74733e08c..f8fe7de20 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5390,6 +5390,8 @@ UniValue cclib(const UniValue& params, bool fHelp) throw runtime_error("cclib method [evalcode] [JSON params]\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); method = (char *)params[0].get_str().c_str(); if ( params.size() >= 2 ) { @@ -5625,6 +5627,8 @@ UniValue marmara_poolpayout(const UniValue& params, bool fHelp) } if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); perc = atof(params[0].get_str().c_str()) / 100.; firstheight = atol(params[1].get_str().c_str()); jsonstr = (char *)params[2].get_str().c_str(); @@ -5643,6 +5647,8 @@ UniValue marmara_receive(const UniValue& params, bool fHelp) } if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); memset(&batontxid,0,sizeof(batontxid)); senderpub = ParseHex(params[0].get_str().c_str()); if (senderpub.size()!= 33) @@ -5672,6 +5678,8 @@ UniValue marmara_issue(const UniValue& params, bool fHelp) } if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); receiverpub = ParseHex(params[0].get_str().c_str()); if (receiverpub.size()!= 33) { @@ -5701,6 +5709,8 @@ UniValue marmara_transfer(const UniValue& params, bool fHelp) ERR_RESULT("invalid receiverpub pubkey"); return result; } + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); amount = atof(params[1].get_str().c_str()) * COIN + 0.00000000499999; currency = params[2].get_str(); matures = atol(params[3].get_str().c_str()); @@ -5719,6 +5729,8 @@ UniValue marmara_info(const UniValue& params, bool fHelp) } if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); firstheight = atol(params[0].get_str().c_str()); lastheight = atol(params[1].get_str().c_str()); minamount = atof(params[2].get_str().c_str()) * COIN + 0.00000000499999; @@ -5749,6 +5761,8 @@ UniValue marmara_creditloop(const UniValue& params, bool fHelp) } if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); txid = Parseuint256((char *)params[0].get_str().c_str()); result = MarmaraCreditloop(txid); return(result); @@ -5765,6 +5779,8 @@ UniValue marmara_settlement(const UniValue& params, bool fHelp) } if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); batontxid = Parseuint256((char *)params[0].get_str().c_str()); result = MarmaraSettlement(0,batontxid); return(result); @@ -5777,6 +5793,8 @@ UniValue marmara_lock(const UniValue& params, bool fHelp) { throw runtime_error("marmaralock amount unlockht\n"); } + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); amount = atof(params[0].get_str().c_str()) * COIN + 0.00000000499999; if ( params.size() == 2 ) height = atol(params[1].get_str().c_str()); @@ -5790,6 +5808,8 @@ UniValue channelslist(const UniValue& params, bool fHelp) throw runtime_error("channelsinfo\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); return(ChannelsList()); } @@ -5800,6 +5820,8 @@ UniValue channelsinfo(const UniValue& params, bool fHelp) throw runtime_error("channelsinfo [opentxid]\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); opentxid=zeroid; if (params.size() > 0 && !params[0].isNull() && !params[0].get_str().empty()) opentxid = Parseuint256((char *)params[0].get_str().c_str()); @@ -6089,6 +6111,8 @@ UniValue rewardslist(const UniValue& params, bool fHelp) throw runtime_error("rewardslist\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); return(RewardsList()); } @@ -6099,6 +6123,8 @@ UniValue rewardsinfo(const UniValue& params, bool fHelp) throw runtime_error("rewardsinfo fundingtxid\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); fundingtxid = Parseuint256((char *)params[0].get_str().c_str()); return(RewardsInfo(fundingtxid)); } @@ -6109,6 +6135,8 @@ UniValue gatewayslist(const UniValue& params, bool fHelp) throw runtime_error("gatewayslist\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); return(GatewaysList()); } @@ -6119,6 +6147,8 @@ UniValue gatewaysinfo(const UniValue& params, bool fHelp) throw runtime_error("gatewaysinfo bindtxid\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); txid = Parseuint256((char *)params[0].get_str().c_str()); return(GatewaysInfo(txid)); } @@ -6314,6 +6344,8 @@ UniValue gatewayspendingdeposits(const UniValue& params, bool fHelp) throw runtime_error("gatewayspendingdeposits bindtxid coin\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); bindtxid = Parseuint256((char *)params[0].get_str().c_str()); coin = params[1].get_str(); return(GatewaysPendingDeposits(bindtxid,coin)); @@ -6326,6 +6358,8 @@ UniValue gatewayspendingwithdraws(const UniValue& params, bool fHelp) throw runtime_error("gatewayspendingwithdraws bindtxid coin\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); bindtxid = Parseuint256((char *)params[0].get_str().c_str()); coin = params[1].get_str(); return(GatewaysPendingWithdraws(bindtxid,coin)); @@ -6338,6 +6372,8 @@ UniValue gatewaysprocessed(const UniValue& params, bool fHelp) throw runtime_error("gatewaysprocessed bindtxid coin\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); bindtxid = Parseuint256((char *)params[0].get_str().c_str()); coin = params[1].get_str(); return(GatewaysProcessedWithdraws(bindtxid,coin)); @@ -6349,6 +6385,8 @@ UniValue oracleslist(const UniValue& params, bool fHelp) throw runtime_error("oracleslist\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); return(OraclesList()); } @@ -6359,6 +6397,8 @@ UniValue oraclesinfo(const UniValue& params, bool fHelp) throw runtime_error("oraclesinfo oracletxid\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); txid = Parseuint256((char *)params[0].get_str().c_str()); return(OracleInfo(txid)); } @@ -6414,6 +6454,8 @@ UniValue oraclessamples(const UniValue& params, bool fHelp) throw runtime_error("oraclessamples oracletxid batonutxo num\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); txid = Parseuint256((char *)params[0].get_str().c_str()); batontxid = Parseuint256((char *)params[1].get_str().c_str()); num = atoi((char *)params[2].get_str().c_str()); @@ -6931,6 +6973,8 @@ UniValue tokeninfo(const UniValue& params, bool fHelp) throw runtime_error("tokeninfo tokenid\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); tokenid = Parseuint256((char *)params[0].get_str().c_str()); return(TokenInfo(tokenid)); } @@ -6942,6 +6986,8 @@ UniValue tokenorders(const UniValue& params, bool fHelp) throw runtime_error("tokenorders [tokenid]\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); if (params.size() == 1) { tokenid = Parseuint256((char *)params[0].get_str().c_str()); if (tokenid == zeroid) From 6d4d25ca102b4cb55d582b0c8d07413c1ceb8300 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 09:15:14 -1100 Subject: [PATCH 0227/1145] Test --- src/cc/CCtx.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index 48b5927a5..c9af64e59 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -579,7 +579,7 @@ int64_t AddNormalinputs2(CMutableTransaction &mtx,int64_t total,int32_t maxinput vout = (int32_t)it->first.index; if ( it->second.satoshis < threshold ) continue; - if ( myGetTransaction(txid,tx,hashBlock) != 0 && tx.vout.size() > 0 && vout < tx.vout.size() && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() == 0 ) + if ( GetTransaction(txid,tx,hashBlock,false) != 0 && tx.vout.size() > 0 && vout < tx.vout.size() && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() == 0 ) { //fprintf(stderr,"check %.8f to vins array.%d of %d %s/v%d\n",(double)out.tx->vout[out.i].nValue/COIN,n,maxutxos,txid.GetHex().c_str(),(int32_t)vout); if ( mtx.vin.size() > 0 ) From f3a93ed84b602d5db45e3ca5444be5d17f4a0d59 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 31 Jan 2019 09:18:28 -1100 Subject: [PATCH 0228/1145] CC_MAXVINS --- src/cc/CCtx.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index c9af64e59..d93185ca4 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -471,7 +471,7 @@ int32_t CC_vinselect(int32_t *aboveip,int64_t *abovep,int32_t *belowip,int64_t * int64_t AddNormalinputs(CMutableTransaction &mtx,CPubKey mypk,int64_t total,int32_t maxinputs) { - int32_t abovei,belowi,ind,vout,i,n = 0,maxutxos=64; int64_t sum,threshold,above,below; int64_t remains,nValue,totalinputs = 0; uint256 txid,hashBlock; std::vector vecOutputs; CTransaction tx; struct CC_utxo *utxos,*up; + int32_t abovei,belowi,ind,vout,i,n = 0,maxutxos=CC_MAXVINS; int64_t sum,threshold,above,below; int64_t remains,nValue,totalinputs = 0; uint256 txid,hashBlock; std::vector vecOutputs; CTransaction tx; struct CC_utxo *utxos,*up; #ifdef ENABLE_WALLET assert(pwalletMain != NULL); const CKeyStore& keystore = *pwalletMain; @@ -564,7 +564,7 @@ int64_t AddNormalinputs(CMutableTransaction &mtx,CPubKey mypk,int64_t total,int3 int64_t AddNormalinputs2(CMutableTransaction &mtx,int64_t total,int32_t maxinputs) { - int32_t abovei,belowi,ind,vout,i,n = 0,maxutxos=64; int64_t sum,threshold,above,below; int64_t remains,nValue,totalinputs = 0; char coinaddr[64]; uint256 txid,hashBlock; CTransaction tx; struct CC_utxo *utxos,*up; + int32_t abovei,belowi,ind,vout,i,n = 0,maxutxos=CC_MAXVINS; int64_t sum,threshold,above,below; int64_t remains,nValue,totalinputs = 0; char coinaddr[64]; uint256 txid,hashBlock; CTransaction tx; struct CC_utxo *utxos,*up; std::vector > unspentOutputs; utxos = (struct CC_utxo *)calloc(maxutxos,sizeof(*utxos)); threshold = total/(maxinputs+1); @@ -579,7 +579,7 @@ int64_t AddNormalinputs2(CMutableTransaction &mtx,int64_t total,int32_t maxinput vout = (int32_t)it->first.index; if ( it->second.satoshis < threshold ) continue; - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && tx.vout.size() > 0 && vout < tx.vout.size() && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() == 0 ) + if ( myGetTransaction(txid,tx,hashBlock) != 0 && tx.vout.size() > 0 && vout < tx.vout.size() && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() == 0 ) { //fprintf(stderr,"check %.8f to vins array.%d of %d %s/v%d\n",(double)out.tx->vout[out.i].nValue/COIN,n,maxutxos,txid.GetHex().c_str(),(int32_t)vout); if ( mtx.vin.size() > 0 ) From 6fc97c61e33c0d01c47d26d66acf0ec9dae8a3df Mon Sep 17 00:00:00 2001 From: Mihailo Milenkovic Date: Fri, 1 Feb 2019 13:46:49 +0100 Subject: [PATCH 0229/1145] Add support for dual opret with Token opret. --- src/rpc/misc.cpp | 46 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp index e6d8025b1..1b522293e 100644 --- a/src/rpc/misc.cpp +++ b/src/rpc/misc.cpp @@ -29,6 +29,7 @@ #include "txmempool.h" #include "util.h" #include "cc/eval.h" +#include "cc/CCinclude.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #include "wallet/walletdb.h" @@ -1343,17 +1344,17 @@ UniValue txnotarizedconfirmed(const UniValue& params, bool fHelp) UniValue decodeccopret(const UniValue& params, bool fHelp) { - CTransaction tx; uint256 txid,hashBlock; - std::vector vopret; uint8_t *script; - UniValue result(UniValue::VOBJ); + CTransaction tx; uint256 tokenid,txid,hashblock; + std::vector vopret,vOpretExtra; uint8_t *script,tokenevalcode; + UniValue result(UniValue::VOBJ),array(UniValue::VARR); std::vector pubkeys; if (fHelp || params.size() < 1 || params.size() > 1) { - string msg = "decodeccopret hex\n" + string msg = "decodeccopret scriptPubKey\n" "\nReturns eval code and function id for CC OP RETURN data.\n" "\nArguments:\n" - "1. txid (string, required) Transaction id.\n" + "1. scriptPubKey (string, required) Hex of scriptPubKey with OP_RETURN data.\n" "\nResult:\n" "{\n" @@ -1363,21 +1364,38 @@ UniValue decodeccopret(const UniValue& params, bool fHelp) ; throw runtime_error(msg); } - txid = uint256S((char *)params[0].get_str().c_str()); + std::vector hex(ParseHex(params[0].get_str())); + CScript scripthex(hex.begin(),hex.end()); + if (DecodeTokenOpRet(scripthex,tokenevalcode,tokenid,pubkeys,vOpretExtra)!=0 && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) { - LOCK(cs_main); - if (!GetTransaction(txid, tx, hashBlock, true)) - throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); + UniValue obj(UniValue::VOBJ); + GetOpReturnData(scripthex,vopret); + script = (uint8_t *)vopret.data(); + if ( vopret.size() > 1) + { + char func[5]; + sprintf(func,"%c",script[1]); + obj.push_back(Pair("eval_code", EvalToStr(script[0]))); + obj.push_back(Pair("function", func)); + } + else + { + obj.push_back(Pair("error", "invalid or no CC opret data for Token OP_RETURN")); + } + array.push_back(obj); + if (!E_UNMARSHAL(vOpretExtra, { ss >> vopret; })) return (0); } - GetOpReturnData(tx.vout[tx.vout.size()-1].scriptPubKey,vopret); + else GetOpReturnData(scripthex,vopret); script = (uint8_t *)vopret.data(); if ( vopret.size() > 1) { - char func[5]; - sprintf(func,"%c",script[1]); + char func[5]; UniValue obj(UniValue::VOBJ); result.push_back(Pair("result", "success")); - result.push_back(Pair("eval_code", EvalToStr(script[0]))); - result.push_back(Pair("function", func)); + sprintf(func,"%c",script[1]); + obj.push_back(Pair("eval_code", EvalToStr(script[0]))); + obj.push_back(Pair("function", func)); + array.push_back(obj); + result.push_back(Pair("OpRets",array)); } else { From 00f7f545c90fb88addeb94cf4491ec00db71f5d5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 1 Feb 2019 10:27:47 -1100 Subject: [PATCH 0230/1145] Fix skip code for ac_perc --- src/cc/cclib.cpp | 31 ++++++++++++++++++++++++++++++- src/cc/makecclib | 2 +- src/komodo_bitcoind.h | 2 +- 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 000245e56..8a0f0aeca 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -29,9 +29,16 @@ #define FAUCET2SIZE COIN #define EVAL_FAUCET2 EVAL_FIRSTUSER -#define EVAL_SUDOKU 17 +#ifdef BUILD_ROGUE +#define EVAL_ROGUE 17 +std::string MYCCLIBNAME = (char *)"rogue"; +#else + +#define EVAL_SUDOKU 17 std::string MYCCLIBNAME = (char *)"sudoku"; +#endif + char *CClib_name() { return((char *)MYCCLIBNAME.c_str()); } struct CClib_rpcinfo @@ -44,23 +51,34 @@ CClib_methods[] = { { (char *)"faucet2", (char *)"fund", (char *)"amount", 1, 1, 'F', EVAL_FAUCET2 }, { (char *)"faucet2", (char *)"get", (char *)"", 0, 0, 'G', EVAL_FAUCET2 }, +#ifdef BUILD_ROGUE +#else { (char *)"sudoku", (char *)"gen", (char *)"", 0, 0, 'G', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"pending", (char *)"", 0, 0, 'U', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"solution", (char *)"txid solution timestamps[81]", 83, 83, 'S', EVAL_SUDOKU }, +#endif }; std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *params); +#ifdef BUILD_ROGUE +#else bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +#endif UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) { UniValue result(UniValue::VOBJ); uint64_t txfee = 10000; +#ifdef BUILD_ROGUE + if ( cp->evalcode == EVAL_ROGUE ) + { + } +#else if ( cp->evalcode == EVAL_SUDOKU ) { //printf("CClib_method params.%p\n",params); @@ -80,6 +98,7 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) return(result); } } +#endif else { result.push_back(Pair("result","error")); @@ -195,7 +214,14 @@ bool CClib_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C int32_t numvins,numvouts,preventCCvins,preventCCvouts,i,numblocks; bool retval; uint256 txid; uint8_t hash[32]; char str[65],destaddr[64]; std::vector > txids; if ( cp->evalcode != EVAL_FAUCET2 ) + { +#ifdef BUILD_ROGUE + //return(rogue_validate(cp,height,eval,tx)); + return(false); +#else return(sudoku_validate(cp,height,eval,tx)); +#endif + } numvins = tx.vin.size(); numvouts = tx.vout.size(); preventCCvins = preventCCvouts = -1; @@ -365,5 +391,8 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para return(""); } +#ifdef BUILD_ROGUE +#else #include "sudoku.cpp" +#endif diff --git a/src/cc/makecclib b/src/cc/makecclib index 0aecab072..b9a50a892 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1 +1 @@ -gcc -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp +gcc -std=c++11 $1 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index f638afa8a..b0d299090 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1190,7 +1190,7 @@ uint64_t komodo_commission(const CBlock *pblock,int32_t height) n = pblock->vtx[i].vout.size(); for (j=0; j 100000 && ASSETCHAINS_STAKED != 0 && txn_count > 1 && i == txn_count-1 && n == 1 ) + if ( height > 100000 && ASSETCHAINS_STAKED != 0 && txn_count > 1 && i == txn_count-1 && j == 1 ) break; //fprintf(stderr,"(%d %.8f).%d ",i,dstr(pblock->vtx[i].vout[j].nValue),j); if ( i != 0 || j != 1 ) From 71742e5d5639d91a8dcdc8484b72268caadd2fb8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 1 Feb 2019 10:28:25 -1100 Subject: [PATCH 0231/1145] J == n-1 --- 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 b0d299090..f6756e676 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1190,7 +1190,7 @@ uint64_t komodo_commission(const CBlock *pblock,int32_t height) n = pblock->vtx[i].vout.size(); for (j=0; j 100000 && ASSETCHAINS_STAKED != 0 && txn_count > 1 && i == txn_count-1 && j == 1 ) + if ( height > 100000 && ASSETCHAINS_STAKED != 0 && txn_count > 1 && i == txn_count-1 && j == n-1 ) break; //fprintf(stderr,"(%d %.8f).%d ",i,dstr(pblock->vtx[i].vout[j].nValue),j); if ( i != 0 || j != 1 ) From 9dd98002290e757088c1e7cb3c687c2aa273b808 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 03:06:32 -1100 Subject: [PATCH 0232/1145] Initial rogue libcc --- src/cc/makecclib | 2 +- src/cc/makerogue | 2 + src/cc/rogue/LICENSE.TXT | 93 ++ src/cc/rogue/Makefile.std | 158 +++ src/cc/rogue/armor.c | 89 ++ src/cc/rogue/chase.c | 541 +++++++++ src/cc/rogue/command.c | 820 +++++++++++++ src/cc/rogue/config.guess | 1500 ++++++++++++++++++++++++ src/cc/rogue/config.h | 270 +++++ src/cc/rogue/config.h.in | 269 +++++ src/cc/rogue/config.sub | 1608 ++++++++++++++++++++++++++ src/cc/rogue/configure.ac | 246 ++++ src/cc/rogue/daemon.c | 181 +++ src/cc/rogue/daemons.c | 294 +++++ src/cc/rogue/extern.c | 391 +++++++ src/cc/rogue/extern.h | 181 +++ src/cc/rogue/fight.c | 686 +++++++++++ src/cc/rogue/init.c | 447 ++++++++ src/cc/rogue/install-sh | 323 ++++++ src/cc/rogue/io.c | 327 ++++++ src/cc/rogue/list.c | 113 ++ src/cc/rogue/mach_dep.c | 457 ++++++++ src/cc/rogue/main.c | 49 + src/cc/rogue/mdport.c | 1432 +++++++++++++++++++++++ src/cc/rogue/misc.c | 597 ++++++++++ src/cc/rogue/monsters.c | 252 ++++ src/cc/rogue/move.c | 425 +++++++ src/cc/rogue/new_level.c | 231 ++++ src/cc/rogue/options.c | 501 ++++++++ src/cc/rogue/pack.c | 503 ++++++++ src/cc/rogue/passages.c | 424 +++++++ src/cc/rogue/potions.c | 375 ++++++ src/cc/rogue/rings.c | 204 ++++ src/cc/rogue/rip.c | 449 ++++++++ src/cc/rogue/rogue.6 | 96 ++ src/cc/rogue/rogue.6.in | 96 ++ src/cc/rogue/rogue.777.0 | 1 + src/cc/rogue/rogue.777.1 | 1 + src/cc/rogue/rogue.777.2 | 1 + src/cc/rogue/rogue.777.3 | 0 src/cc/rogue/rogue.c | 534 +++++++++ src/cc/rogue/rogue.cat | 61 + src/cc/rogue/rogue.cat.in | 61 + src/cc/rogue/rogue.desktop | 11 + src/cc/rogue/rogue.doc | 858 ++++++++++++++ src/cc/rogue/rogue.doc.in | 858 ++++++++++++++ src/cc/rogue/rogue.h | 785 +++++++++++++ src/cc/rogue/rogue.html | 1060 +++++++++++++++++ src/cc/rogue/rogue.html.in | 1060 +++++++++++++++++ src/cc/rogue/rogue.me | 892 +++++++++++++++ src/cc/rogue/rogue.me.in | 892 +++++++++++++++ src/cc/rogue/rogue.png | Bin 0 -> 1005 bytes src/cc/rogue/rogue.spec | 107 ++ src/cc/rogue/rogue54.sln | 19 + src/cc/rogue/rogue54.vcproj | 396 +++++++ src/cc/rogue/rooms.c | 472 ++++++++ src/cc/rogue/save.c | 400 +++++++ src/cc/rogue/score.h | 26 + src/cc/rogue/scrolls.c | 329 ++++++ src/cc/rogue/state.c | 2148 +++++++++++++++++++++++++++++++++++ src/cc/rogue/sticks.c | 431 +++++++ src/cc/rogue/test.zip | Bin 0 -> 5451 bytes src/cc/rogue/things.c | 713 ++++++++++++ src/cc/rogue/vers.c | 17 + src/cc/rogue/weapons.c | 288 +++++ src/cc/rogue/wizard.c | 284 +++++ src/cc/rogue/xcrypt.c | 707 ++++++++++++ 67 files changed, 28043 insertions(+), 1 deletion(-) create mode 100755 src/cc/makerogue create mode 100644 src/cc/rogue/LICENSE.TXT create mode 100755 src/cc/rogue/Makefile.std create mode 100644 src/cc/rogue/armor.c create mode 100644 src/cc/rogue/chase.c create mode 100644 src/cc/rogue/command.c create mode 100755 src/cc/rogue/config.guess create mode 100644 src/cc/rogue/config.h create mode 100644 src/cc/rogue/config.h.in create mode 100755 src/cc/rogue/config.sub create mode 100644 src/cc/rogue/configure.ac create mode 100644 src/cc/rogue/daemon.c create mode 100644 src/cc/rogue/daemons.c create mode 100644 src/cc/rogue/extern.c create mode 100644 src/cc/rogue/extern.h create mode 100644 src/cc/rogue/fight.c create mode 100644 src/cc/rogue/init.c create mode 100755 src/cc/rogue/install-sh create mode 100644 src/cc/rogue/io.c create mode 100644 src/cc/rogue/list.c create mode 100644 src/cc/rogue/mach_dep.c create mode 100644 src/cc/rogue/main.c create mode 100644 src/cc/rogue/mdport.c create mode 100644 src/cc/rogue/misc.c create mode 100644 src/cc/rogue/monsters.c create mode 100644 src/cc/rogue/move.c create mode 100644 src/cc/rogue/new_level.c create mode 100644 src/cc/rogue/options.c create mode 100644 src/cc/rogue/pack.c create mode 100644 src/cc/rogue/passages.c create mode 100644 src/cc/rogue/potions.c create mode 100644 src/cc/rogue/rings.c create mode 100644 src/cc/rogue/rip.c create mode 100644 src/cc/rogue/rogue.6 create mode 100644 src/cc/rogue/rogue.6.in create mode 100644 src/cc/rogue/rogue.777.0 create mode 100644 src/cc/rogue/rogue.777.1 create mode 100644 src/cc/rogue/rogue.777.2 create mode 100644 src/cc/rogue/rogue.777.3 create mode 100644 src/cc/rogue/rogue.c create mode 100644 src/cc/rogue/rogue.cat create mode 100644 src/cc/rogue/rogue.cat.in create mode 100644 src/cc/rogue/rogue.desktop create mode 100644 src/cc/rogue/rogue.doc create mode 100644 src/cc/rogue/rogue.doc.in create mode 100644 src/cc/rogue/rogue.h create mode 100644 src/cc/rogue/rogue.html create mode 100644 src/cc/rogue/rogue.html.in create mode 100644 src/cc/rogue/rogue.me create mode 100644 src/cc/rogue/rogue.me.in create mode 100644 src/cc/rogue/rogue.png create mode 100644 src/cc/rogue/rogue.spec create mode 100644 src/cc/rogue/rogue54.sln create mode 100644 src/cc/rogue/rogue54.vcproj create mode 100644 src/cc/rogue/rooms.c create mode 100644 src/cc/rogue/save.c create mode 100644 src/cc/rogue/score.h create mode 100644 src/cc/rogue/scrolls.c create mode 100644 src/cc/rogue/state.c create mode 100644 src/cc/rogue/sticks.c create mode 100644 src/cc/rogue/test.zip create mode 100644 src/cc/rogue/things.c create mode 100644 src/cc/rogue/vers.c create mode 100644 src/cc/rogue/weapons.c create mode 100644 src/cc/rogue/wizard.c create mode 100644 src/cc/rogue/xcrypt.c diff --git a/src/cc/makecclib b/src/cc/makecclib index b9a50a892..0aecab072 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1 +1 @@ -gcc -std=c++11 $1 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp +gcc -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp diff --git a/src/cc/makerogue b/src/cc/makerogue new file mode 100755 index 000000000..c9e55c28c --- /dev/null +++ b/src/cc/makerogue @@ -0,0 +1,2 @@ +cd rogue; make; cd .. +gcc -DROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp rogue/rogue.so diff --git a/src/cc/rogue/LICENSE.TXT b/src/cc/rogue/LICENSE.TXT new file mode 100644 index 000000000..ae3f4715b --- /dev/null +++ b/src/cc/rogue/LICENSE.TXT @@ -0,0 +1,93 @@ +Rogue: Exploring the Dungeons of Doom +Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name(s) of the author(s) nor the names of other contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +=========================================================================== + +Portions of this software (state.c, mdport.c) are based on the work +of Nicholas J. Kisseberth. Used under license: + +Copyright (C) 1999, 2000, 2005 Nicholas J. Kisseberth +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name(s) of the author(s) nor the names of other contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +=========================================================================== + +Portions of this software (xcrypt.c) are based on the work +of David Burren. Used under license: + +FreeSec: libcrypt + +Copyright (C) 1994 David Burren +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name(s) of the author(s) nor the names of other contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTORS BE LIABLE +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. diff --git a/src/cc/rogue/Makefile.std b/src/cc/rogue/Makefile.std new file mode 100755 index 000000000..923c74672 --- /dev/null +++ b/src/cc/rogue/Makefile.std @@ -0,0 +1,158 @@ +# +# Makefile for rogue +# @(#)Makefile 4.21 (Berkeley) 02/04/99 +# +# Rogue: Exploring the Dungeons of Doom +# Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman +# All rights reserved. +# +# See the file LICENSE.TXT for full copyright and licensing information. +# + +DISTNAME = rogue5.4.4 +PROGRAM = rogue54 +O = o +HDRS = rogue.h extern.h score.h +OBJS1 = vers.$(O) extern.$(O) armor.$(O) chase.$(O) command.$(O) \ + daemon.$(O) daemons.$(O) fight.$(O) init.$(O) io.$(O) list.$(O) \ + mach_dep.$(O) main.$(O) mdport.$(O) misc.$(O) monsters.$(O) \ + move.$(O) new_level.$(O) +OBJS2 = options.$(O) pack.$(O) passages.$(O) potions.$(O) rings.$(O) \ + rip.$(O) rooms.$(O) save.$(O) scrolls.$(O) state.$(O) sticks.$(O) \ + things.$(O) weapons.$(O) wizard.$(O) xcrypt.$(O) +OBJS = $(OBJS1) $(OBJS2) +CFILES = vers.c extern.c armor.c chase.c command.c daemon.c \ + daemons.c fight.c init.c io.c list.c mach_dep.c \ + main.c mdport.c misc.c monsters.c move.c new_level.c \ + options.c pack.c passages.c potions.c rings.c rip.c \ + rooms.c save.c scrolls.c state.c sticks.c things.c \ + weapons.c wizard.c xcrypt.c +MISC_C = findpw.c scedit.c scmisc.c +DOCSRC = rogue.me.in rogue.6.in rogue.doc.in rogue.html.in rogue.cat.in +DOCS = $(PROGRAM).doc $(PROGRAM).html $(PROGRAM).cat $(PROGRAM).me \ + $(PROGRAM).6 +AFILES = configure Makefile.in configure.ac config.h.in config.sub config.guess \ + install-sh rogue.6.in rogue.me.in rogue.html.in rogue.doc.in rogue.cat.in +MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ + rogue.png rogue.desktop +CC = gcc +FEATURES = -DALLSCORES -DSCOREFILE=\"$(SCOREFILE)\" -DLOCKFILE=\"$(LOCKFILE)\" +CPPFLAGS = +CFLAGS = -O3 +LDFLAGS = +LIBS = -lcurses +RM = rm -f +MAKEFILE = -f Makefile.std +SCOREFILE= $(PROGRAM).scr +LOCKFILE = $(PROGRAM).lck +OUTFLAG = -o +EXE = + +.SUFFIXES: .obj + +.c.obj: + $(CC) $(CFLAGS) $(CPPFLAGS) $(FEATURES) /c $*.c + +.c.o: + $(CC) $(CFLAGS) $(CPPFLAGS) $(FEATURES) -c $*.c + +$(PROGRAM): $(HDRS) $(OBJS) fixdocs + $(CC) $(LDFLAGS) $(OBJS) $(LIBS) $(OUTFLAG)$@$(EXE) + +clean: + $(RM) $(OBJS1) + $(RM) $(OBJS2) + $(RM) core a.exe a.out a.exe.stackdump $(PROGRAM) $(PROGRAM).exe $(PROGRAM).lck + $(RM) $(PROGRAM).tar $(PROGRAM).tar.gz $(PROGRAM).zip + $(RM) $(DISTNAME)/* + +dist.src: + $(MAKE) $(MAKEFILE) clean + mkdir $(DISTNAME) + cp $(CFILES) $(HDRS) $(MISC) $(AFILES) $(DISTNAME) + tar cf $(DISTNAME)-src.tar $(DISTNAME) + gzip -f $(DISTNAME)-src.tar + rm -fr $(DISTNAME) + +findpw: findpw.c xcrypt.o mdport.o xcrypt.o + $(CC) -s -o findpw findpw.c xcrypt.o mdport.o -lcurses + +scedit: scedit.o scmisc.o vers.o mdport.o xcrypt.o + $(CC) -s -o scedit vers.o scedit.o scmisc.o mdport.o xcrypt.o -lcurses + +scmisc.o scedit.o: + $(CC) -O -c $(SF) $*.c + +doc.nroff: + tbl rogue.me | nroff -me | colcrt - > rogue.doc + nroff -man rogue.6 | colcrt - > rogue.cat + +doc.groff: + groff -P-c -t -me -Tascii rogue.me | sed -e 's/.\x08//g' > rogue.doc + groff -man rogue.6 | sed -e 's/.\x08//g' > rogue.cat + +fixdocs: + sed -e 's/@PROGRAM@/$(PROGRAM)/' -e 's/@SCOREFILE@/$(SCOREFILE)/' rogue.6.in > $(PROGRAM).6 + sed -e 's/@PROGRAM@/$(PROGRAM)/' -e 's/@SCOREFILE@/$(SCOREFILE)/' rogue.me.in > $(PROGRAM).me + sed -e 's/@PROGRAM@/$(PROGRAM)/' -e 's/@SCOREFILE@/$(SCOREFILE)/' rogue.html.in > $(PROGRAM).html + sed -e 's/@PROGRAM@/$(PROGRAM)/' -e 's/@SCOREFILE@/$(SCOREFILE)/' rogue.doc.in > $(PROGRAM).doc + sed -e 's/@PROGRAM@/$(PROGRAM)/' -e 's/@SCOREFILE@/$(SCOREFILE)/' rogue.cat.in > $(PROGRAM).cat + +dist.irix: + $(MAKE) $(MAKEFILE) clean + $(MAKE) $(MAKEFILE) CC=cc $(PROGRAM) + tar cf $(DISTNAME)-irix.tar $(PROGRAM) LICENSE.TXT $(DOCS) + gzip -f $(DISTNAME)-irix.tar + +dist.aix: + $(MAKE) $(MAKEFILE) clean + $(MAKE) $(MAKEFILE) CC=xlc CFLAGS="-qmaxmem=16768 -O3 -qstrict" $(PROGRAM) + tar cf $(DISTNAME)-aix.tar $(PROGRAM) LICENSE.TXT $(DOCS) + gzip -f $(DISTNAME)-aix.tar + +dist.linux: + $(MAKE) $(MAKEFILE) clean + $(MAKE) $(MAKEFILE) $(PROGRAM) + tar cf $(DISTNAME)-linux.tar $(PROGRAM) LICENSE.TXT $(DOCS) + gzip -f $(DISTNAME)-linux.tar + +dist.interix: + @$(MAKE) $(MAKEFILE) clean + @$(MAKE) $(MAKEFILE) CFLAGS="-ansi" $(PROGRAM) + tar cf $(DISTNAME)-interix.tar $(PROGRAM) LICENSE.TXT $(DOCS) + gzip -f $(DISTNAME)-interix.tar + +dist.cygwin: + @$(MAKE) $(MAKEFILE) --no-print-directory clean + @$(MAKE) $(MAKEFILE) CPPFLAGS="-I/usr/include/ncurses" --no-print-directory $(PROGRAM) + tar cf $(DISTNAME)-cygwin.tar $(PROGRAM).exe LICENSE.TXT $(DOCS) + gzip -f $(DISTNAME)-cygwin.tar + +# +# Use MINGW32-MAKE to build this target +# +dist.mingw32: + @$(MAKE) $(MAKEFILE) --no-print-directory RM="cmd /c del" clean + @$(MAKE) $(MAKEFILE) --no-print-directory CPPFLAGS="-I../pdcurses" LIBS="../pdcurses/pdcurses.a" $(PROGRAM) + cmd /c del $(DISTNAME)-mingw32.zip + zip $(DISTNAME)-mingw32.zip $(PROGRAM).exe LICENSE.TXT $(DOCS) + +dist.djgpp: + @$(MAKE) $(MAKEFILE) --no-print-directory clean + @$(MAKE) $(MAKEFILE) --no-print-directory LDFLAGS="-L$(DJDIR)/LIB" \ + LIBS="-lpdcurses" $(PROGRAM) + rm -f $(DISTNAME)-djgpp.zip + zip $(DISTNAME)-djgpp.zip $(PROGRAM) LICENSE.TXT $(DOCS) + +# +# Use NMAKE to build this targer +# + +dist.win32: + @$(MAKE) $(MAKEFILE) /NOLOGO O="obj" RM="-del" clean + @$(MAKE) $(MAKEFILE) /NOLOGO O="obj" CC="CL" \ + LIBS="..\pdcurses\pdcurses.lib shell32.lib user32.lib Advapi32.lib" \ + EXE=".exe" OUTFLAG="/Fe" CPPFLAGS="-I..\pdcurses" \ + CFLAGS="-nologo -Ox -wd4033 -wd4716" $(PROGRAM) + -del $(DISTNAME)-win32.zip + zip $(DISTNAME)-win32.zip $(PROGRAM).exe LICENSE.TXT $(DOCS) diff --git a/src/cc/rogue/armor.c b/src/cc/rogue/armor.c new file mode 100644 index 000000000..5244628b1 --- /dev/null +++ b/src/cc/rogue/armor.c @@ -0,0 +1,89 @@ +/* + * This file contains misc functions for dealing with armor + * @(#)armor.c 4.14 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include "rogue.h" + +/* + * wear: + * The player wants to wear something, so let him/her put it on. + */ +void +wear(struct rogue_state *rs) +{ + register THING *obj; + register char *sp; + + if ((obj = get_item(rs,"wear", ARMOR)) == NULL) + return; + if (cur_armor != NULL) + { + addmsg(rs,"you are already wearing some"); + if (!terse) + addmsg(rs,". You'll have to take it off first"); + endmsg(rs); + after = FALSE; + return; + } + if (obj->o_type != ARMOR) + { + msg(rs,"you can't wear that"); + return; + } + waste_time(rs); + obj->o_flags |= ISKNOW; + sp = inv_name(obj, TRUE); + cur_armor = obj; + if (!terse) + addmsg(rs,"you are now "); + msg(rs,"wearing %s", sp); +} + +/* + * take_off: + * Get the armor off of the players back + */ +void +take_off(struct rogue_state *rs) +{ + register THING *obj; + + if ((obj = cur_armor) == NULL) + { + after = FALSE; + if (terse) + msg(rs,"not wearing armor"); + else + msg(rs,"you aren't wearing any armor"); + return; + } + if (!dropcheck(rs,cur_armor)) + return; + cur_armor = NULL; + if (terse) + addmsg(rs,"was"); + else + addmsg(rs,"you used to be"); + msg(rs," wearing %c) %s", obj->o_packch, inv_name(obj, TRUE)); +} + +/* + * waste_time: + * Do nothing but let other things happen + */ +void +waste_time(struct rogue_state *rs) +{ + do_daemons(rs,BEFORE); + do_fuses(rs,BEFORE); + do_daemons(rs,AFTER); + do_fuses(rs,AFTER); +} diff --git a/src/cc/rogue/chase.c b/src/cc/rogue/chase.c new file mode 100644 index 000000000..168993edb --- /dev/null +++ b/src/cc/rogue/chase.c @@ -0,0 +1,541 @@ +/* + * Code for one creature to chase another + * + * @(#)chase.c 4.57 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include "rogue.h" + +#define DRAGONSHOT 5 /* one chance in DRAGONSHOT that a dragon will flame */ + +static coord ch_ret; /* Where chasing takes you */ + +/* + * runners: + * Make all the running monsters move. + */ +void +runners(struct rogue_state *rs,int arg) +{ + register THING *tp; + THING *next; + bool wastarget; + static coord orig_pos; + + for (tp = mlist; tp != NULL; tp = next) + { + /* remember this in case the monster's "next" is changed */ + next = next(tp); + if (!on(*tp, ISHELD) && on(*tp, ISRUN)) + { + orig_pos = tp->t_pos; + wastarget = on(*tp, ISTARGET); + if (move_monst(rs,tp) == -1) + continue; + if (on(*tp, ISFLY) && dist_cp(&hero, &tp->t_pos) >= 3) + move_monst(rs,tp); + if (wastarget && !ce(orig_pos, tp->t_pos)) + { + tp->t_flags &= ~ISTARGET; + to_death = FALSE; + } + } + } + if (has_hit) + { + endmsg(rs); + has_hit = FALSE; + } +} + +/* + * move_monst: + * Execute a single turn of running for a monster + */ +int +move_monst(struct rogue_state *rs,THING *tp) +{ + if (!on(*tp, ISSLOW) || tp->t_turn) + if (do_chase(rs,tp) == -1) + return(-1); + if (on(*tp, ISHASTE)) + if (do_chase(rs,tp) == -1) + return(-1); + tp->t_turn ^= TRUE; + return(0); +} + +/* + * relocate: + * Make the monster's new location be the specified one, updating + * all the relevant state. + */ +void +relocate(struct rogue_state *rs,THING *th, coord *new_loc) +{ + struct room *oroom; + + if (!ce(*new_loc, th->t_pos)) + { + mvaddch(th->t_pos.y, th->t_pos.x, th->t_oldch); + th->t_room = roomin(rs,new_loc); + set_oldch(th, new_loc); + oroom = th->t_room; + moat(th->t_pos.y, th->t_pos.x) = NULL; + + if (oroom != th->t_room) + th->t_dest = find_dest(rs,th); + th->t_pos = *new_loc; + moat(new_loc->y, new_loc->x) = th; + } + move(new_loc->y, new_loc->x); + if (see_monst(th)) + addch(th->t_disguise); + else if (on(player, SEEMONST)) + { + standout(); + addch(th->t_type); + standend(); + } +} + +/* + * do_chase: + * Make one thing chase another. + */ +int +do_chase(struct rogue_state *rs,THING *th) +{ + register coord *cp; + register struct room *rer, *ree; /* room of chaser, room of chasee */ + register int mindist = 32767, curdist; + register bool stoprun = FALSE; /* TRUE means we are there */ + register bool door; + register THING *obj; + static coord this; /* Temporary destination for chaser */ + + rer = th->t_room; /* Find room of chaser */ + if (on(*th, ISGREED) && rer->r_goldval == 0) + th->t_dest = &hero; /* If gold has been taken, run after hero */ + if (th->t_dest == &hero) /* Find room of chasee */ + ree = proom; + else + ree = roomin(rs,th->t_dest); + /* + * We don't count doors as inside rooms for this routine + */ + door = (chat(th->t_pos.y, th->t_pos.x) == DOOR); + /* + * If the object of our desire is in a different room, + * and we are not in a corridor, run to the door nearest to + * our goal. + */ +over: + if (rer != ree) + { + for (cp = rer->r_exit; cp < &rer->r_exit[rer->r_nexits]; cp++) + { + curdist = dist_cp(th->t_dest, cp); + if (curdist < mindist) + { + this = *cp; + mindist = curdist; + } + } + if (door) + { + rer = &passages[flat(th->t_pos.y, th->t_pos.x) & F_PNUM]; + door = FALSE; + goto over; + } + } + else + { + this = *th->t_dest; + /* + * For dragons check and see if (a) the hero is on a straight + * line from it, and (b) that it is within shooting distance, + * but outside of striking range. + */ + if (th->t_type == 'D' && (th->t_pos.y == hero.y || th->t_pos.x == hero.x + || abs(th->t_pos.y - hero.y) == abs(th->t_pos.x - hero.x)) + && dist_cp(&th->t_pos, &hero) <= BOLT_LENGTH * BOLT_LENGTH + && !on(*th, ISCANC) && rnd(DRAGONSHOT) == 0) + { + delta.y = sign(hero.y - th->t_pos.y); + delta.x = sign(hero.x - th->t_pos.x); + if (has_hit) + endmsg(rs); + fire_bolt(rs,&th->t_pos, &delta, "flame"); + running = FALSE; + count = 0; + quiet = 0; + if (to_death && !on(*th, ISTARGET)) + { + to_death = FALSE; + kamikaze = FALSE; + } + return(0); + } + } + /* + * This now contains what we want to run to this time + * so we run to it. If we hit it we either want to fight it + * or stop running + */ + if (!chase(th, &this)) + { + if (ce(this, hero)) + { + return( attack(rs,th) ); + } + else if (ce(this, *th->t_dest)) + { + for (obj = lvl_obj; obj != NULL; obj = next(obj)) + if (th->t_dest == &obj->o_pos) + { + detach(lvl_obj, obj); + attach(th->t_pack, obj); + chat(obj->o_pos.y, obj->o_pos.x) = + (th->t_room->r_flags & ISGONE) ? PASSAGE : FLOOR; + th->t_dest = find_dest(rs,th); + break; + } + if (th->t_type != 'F') + stoprun = TRUE; + } + } + else + { + if (th->t_type == 'F') + return(0); + } + relocate(rs,th, &ch_ret); + /* + * And stop running if need be + */ + if (stoprun && ce(th->t_pos, *(th->t_dest))) + th->t_flags &= ~ISRUN; + return(0); +} + +/* + * set_oldch: + * Set the oldch character for the monster + */ +void +set_oldch(THING *tp, coord *cp) +{ + char sch; + + if (ce(tp->t_pos, *cp)) + return; + + sch = tp->t_oldch; + tp->t_oldch = CCHAR( mvinch(cp->y,cp->x) ); + if (!on(player, ISBLIND)) + { + if ((sch == FLOOR || tp->t_oldch == FLOOR) && + (tp->t_room->r_flags & ISDARK)) + tp->t_oldch = ' '; + else if (dist_cp(cp, &hero) <= LAMPDIST && see_floor) + tp->t_oldch = chat(cp->y, cp->x); + } +} + +/* + * see_monst: + * Return TRUE if the hero can see the monster + */ +bool +see_monst(THING *mp) +{ + int y, x; + + if (on(player, ISBLIND)) + return FALSE; + if (on(*mp, ISINVIS) && !on(player, CANSEE)) + return FALSE; + y = mp->t_pos.y; + x = mp->t_pos.x; + if (dist(y, x, hero.y, hero.x) < LAMPDIST) + { + if (y != hero.y && x != hero.x && + !step_ok(chat(y, hero.x)) && !step_ok(chat(hero.y, x))) + return FALSE; + return TRUE; + } + if (mp->t_room != proom) + return FALSE; + return ((bool)!(mp->t_room->r_flags & ISDARK)); +} + +/* + * runto: + * Set a monster running after the hero. + */ +void +runto(struct rogue_state *rs,coord *runner) +{ + register THING *tp; + + /* + * If we couldn't find him, something is funny + */ +#ifdef MASTER + if ((tp = moat(runner->y, runner->x)) == NULL) + msg(rs,"couldn't find monster in runto at (%d,%d)", runner->y, runner->x); +#else + tp = moat(runner->y, runner->x); +#endif + /* + * Start the beastie running + */ + tp->t_flags |= ISRUN; + tp->t_flags &= ~ISHELD; + tp->t_dest = find_dest(rs,tp); +} + +/* + * chase: + * Find the spot for the chaser(er) to move closer to the + * chasee(ee). Returns TRUE if we want to keep on chasing later + * FALSE if we reach the goal. + */ +bool +chase(THING *tp, coord *ee) +{ + register THING *obj; + register int x, y; + register int curdist, thisdist; + register coord *er = &tp->t_pos; + register char ch; + register int plcnt = 1; + static coord tryp; + + /* + * If the thing is confused, let it move randomly. Invisible + * Stalkers are slightly confused all of the time, and bats are + * quite confused all the time + */ + if ((on(*tp, ISHUH) && rnd(5) != 0) || (tp->t_type == 'P' && rnd(5) == 0) + || (tp->t_type == 'B' && rnd(2) == 0)) + { + /* + * get a valid random move + */ + ch_ret = *rndmove(tp); + curdist = dist_cp(&ch_ret, ee); + /* + * Small chance that it will become un-confused + */ + if (rnd(20) == 0) + tp->t_flags &= ~ISHUH; + } + /* + * Otherwise, find the empty spot next to the chaser that is + * closest to the chasee. + */ + else + { + register int ey, ex; + /* + * This will eventually hold where we move to get closer + * If we can't find an empty spot, we stay where we are. + */ + curdist = dist_cp(er, ee); + ch_ret = *er; + + ey = er->y + 1; + if (ey >= NUMLINES - 1) + ey = NUMLINES - 2; + ex = er->x + 1; + if (ex >= NUMCOLS) + ex = NUMCOLS - 1; + + for (x = er->x - 1; x <= ex; x++) + { + if (x < 0) + continue; + tryp.x = x; + for (y = er->y - 1; y <= ey; y++) + { + tryp.y = y; + if (!diag_ok(er, &tryp)) + continue; + ch = winat(y, x); + if (step_ok(ch)) + { + /* + * If it is a scroll, it might be a scare monster scroll + * so we need to look it up to see what type it is. + */ + if (ch == SCROLL) + { + for (obj = lvl_obj; obj != NULL; obj = next(obj)) + { + if (y == obj->o_pos.y && x == obj->o_pos.x) + break; + } + if (obj != NULL && obj->o_which == S_SCARE) + continue; + } + /* + * It can also be a Xeroc, which we shouldn't step on + */ + if ((obj = moat(y, x)) != NULL && obj->t_type == 'X') + continue; + /* + * If we didn't find any scrolls at this place or it + * wasn't a scare scroll, then this place counts + */ + thisdist = dist(y, x, ee->y, ee->x); + if (thisdist < curdist) + { + plcnt = 1; + ch_ret = tryp; + curdist = thisdist; + } + else if (thisdist == curdist && rnd(++plcnt) == 0) + { + ch_ret = tryp; + curdist = thisdist; + } + } + } + } + } + return (bool)(curdist != 0 && !ce(ch_ret, hero)); +} + +/* + * roomin: + * Find what room some coordinates are in. NULL means they aren't + * in any room. + */ +struct room * +roomin(struct rogue_state *rs,coord *cp) +{ + register struct room *rp; + register char *fp; + + + fp = &flat(cp->y, cp->x); + if (*fp & F_PASS) + return &passages[*fp & F_PNUM]; + + for (rp = rooms; rp < &rooms[MAXROOMS]; rp++) + if (cp->x <= rp->r_pos.x + rp->r_max.x && rp->r_pos.x <= cp->x + && cp->y <= rp->r_pos.y + rp->r_max.y && rp->r_pos.y <= cp->y) + return rp; + + msg(rs,"in some bizarre place (%d, %d)", unc(*cp)); +#ifdef MASTER + abort(); + return NULL; +#else + return NULL; +#endif +} + +/* + * diag_ok: + * Check to see if the move is legal if it is diagonal + */ +bool +diag_ok(coord *sp, coord *ep) +{ + if (ep->x < 0 || ep->x >= NUMCOLS || ep->y <= 0 || ep->y >= NUMLINES - 1) + return FALSE; + if (ep->x == sp->x || ep->y == sp->y) + return TRUE; + return (bool)(step_ok(chat(ep->y, sp->x)) && step_ok(chat(sp->y, ep->x))); +} + +/* + * cansee: + * Returns true if the hero can see a certain coordinate. + */ +bool +cansee(struct rogue_state *rs,int y, int x) +{ + register struct room *rer; + static coord tp; + + if (on(player, ISBLIND)) + return FALSE; + if (dist(y, x, hero.y, hero.x) < LAMPDIST) + { + if (flat(y, x) & F_PASS) + if (y != hero.y && x != hero.x && + !step_ok(chat(y, hero.x)) && !step_ok(chat(hero.y, x))) + return FALSE; + return TRUE; + } + /* + * We can only see if the hero in the same room as + * the coordinate and the room is lit or if it is close. + */ + tp.y = y; + tp.x = x; + return (bool)((rer = roomin(rs,&tp)) == proom && !(rer->r_flags & ISDARK)); +} + +/* + * find_dest: + * find the proper destination for the monster + */ +coord * +find_dest(struct rogue_state *rs,THING *tp) +{ + register THING *obj; + register int prob; + + if ((prob = monsters[tp->t_type - 'A'].m_carry) <= 0 || tp->t_room == proom + || see_monst(tp)) + return &hero; + for (obj = lvl_obj; obj != NULL; obj = next(obj)) + { + if (obj->o_type == SCROLL && obj->o_which == S_SCARE) + continue; + if (roomin(rs,&obj->o_pos) == tp->t_room && rnd(100) < prob) + { + for (tp = mlist; tp != NULL; tp = next(tp)) + if (tp->t_dest == &obj->o_pos) + break; + if (tp == NULL) + return &obj->o_pos; + } + } + return &hero; +} + +/* + * dist: + * Calculate the "distance" between to points. Actually, + * this calculates d^2, not d, but that's good enough for + * our purposes, since it's only used comparitively. + */ +int +dist(int y1, int x1, int y2, int x2) +{ + return ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); +} + +/* + * dist_cp: + * Call dist() with appropriate arguments for coord pointers + */ +int +dist_cp(coord *c1, coord *c2) +{ + return dist(c1->y, c1->x, c2->y, c2->x); +} diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c new file mode 100644 index 000000000..ce02da076 --- /dev/null +++ b/src/cc/rogue/command.c @@ -0,0 +1,820 @@ +/* + * Read and execute the user commands + * + * @(#)command.c 4.73 (Berkeley) 08/06/83 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include +#include +#include "rogue.h" + +/* + * command: + * Process the user commands + */ +void +command(struct rogue_state *rs) +{ + register char ch; + register int ntimes = 1; /* Number of player moves */ + char *fp; + THING *mp; + static char countch, direction, newcount = FALSE; + + if (on(player, ISHASTE)) + ntimes++; + /* + * Let the daemons start up + */ + do_daemons(rs,BEFORE); + do_fuses(rs,BEFORE); + while (ntimes--) + { + again = FALSE; + if (has_hit) + { + endmsg(rs); + has_hit = FALSE; + } + /* + * these are illegal things for the player to be, so if any are + * set, someone's been poking in memeory + */ + if (on(player, ISSLOW|ISGREED|ISINVIS|ISREGEN|ISTARGET)) + exit(1); + + look(rs,TRUE); + if (!running) + door_stop = FALSE; + status(rs); + lastscore = purse; + move(hero.y, hero.x); + if (!((running || count) && jump)) + refresh(); /* Draw screen */ + take = 0; + after = TRUE; + /* + * Read command or continue run + */ +#ifdef MASTER + if (wizard) + noscore = TRUE; +#endif + if (!no_command) + { + if (running || to_death) + ch = runch; + else if (count) + ch = countch; + else + { + ch = readchar(rs); + move_on = FALSE; + if (mpos != 0) /* Erase message if its there */ + msg(rs,""); + } + } + else + ch = '.'; + if (no_command) + { + if (--no_command == 0) + { + player.t_flags |= ISRUN; + msg(rs,"you can move again"); + } + } + else + { + /* + * check for prefixes + */ + newcount = FALSE; + if (isdigit(ch)) + { + count = 0; + newcount = TRUE; + while (isdigit(ch)) + { + count = count * 10 + (ch - '0'); + if (count > 255) + count = 255; + ch = readchar(rs); + } + countch = ch; + /* + * turn off count for commands which don't make sense + * to repeat + */ + switch (ch) + { + case CTRL('B'): case CTRL('H'): case CTRL('J'): + case CTRL('K'): case CTRL('L'): case CTRL('N'): + case CTRL('U'): case CTRL('Y'): + case '.': case 'a': case 'b': case 'h': case 'j': + case 'k': case 'l': case 'm': case 'n': case 'q': + case 'r': case 's': case 't': case 'u': case 'y': + case 'z': case 'B': case 'C': case 'H': case 'I': + case 'J': case 'K': case 'L': case 'N': case 'U': + case 'Y': +#ifdef MASTER + case CTRL('D'): case CTRL('A'): +#endif + break; + default: + count = 0; + } + } + /* + * execute a command + */ + if (count && !running) + count--; + if (ch != 'a' && ch != ESCAPE && !(running || count || to_death)) + { + l_last_comm = last_comm; + l_last_dir = last_dir; + l_last_pick = last_pick; + last_comm = ch; + last_dir = '\0'; + last_pick = NULL; + } +over: + switch (ch) + { + case ',': { + THING *obj = NULL; + int found = 0; + for (obj = lvl_obj; obj != NULL; obj = next(obj)) + { + if (obj->o_pos.y == hero.y && obj->o_pos.x == hero.x) + { + found=1; + break; + } + } + + if (found) { + if (levit_check(rs)) + ; + else + pick_up(rs,(char)obj->o_type); + } + else { + if (!terse) + addmsg(rs,"there is "); + addmsg(rs,"nothing here"); + if (!terse) + addmsg(rs," to pick up"); + endmsg(rs); + } + } + when '!': shell(rs); + when 'h': do_move(rs,0, -1); + when 'j': do_move(rs,1, 0); + when 'k': do_move(rs,-1, 0); + when 'l': do_move(rs,0, 1); + when 'y': do_move(rs,-1, -1); + when 'u': do_move(rs,-1, 1); + when 'b': do_move(rs,1, -1); + when 'n': do_move(rs,1, 1); + when 'H': do_run('h'); + when 'J': do_run('j'); + when 'K': do_run('k'); + when 'L': do_run('l'); + when 'Y': do_run('y'); + when 'U': do_run('u'); + when 'B': do_run('b'); + when 'N': do_run('n'); + when CTRL('H'): case CTRL('J'): case CTRL('K'): case CTRL('L'): + case CTRL('Y'): case CTRL('U'): case CTRL('B'): case CTRL('N'): + { + if (!on(player, ISBLIND)) + { + door_stop = TRUE; + firstmove = TRUE; + } + if (count && !newcount) + ch = direction; + else + { + ch += ('A' - CTRL('A')); + direction = ch; + } + goto over; + } + when 'F': + kamikaze = TRUE; + /* FALLTHROUGH */ + case 'f': + if (!get_dir(rs)) + { + after = FALSE; + break; + } + delta.y += hero.y; + delta.x += hero.x; + if ( ((mp = moat(delta.y, delta.x)) == NULL) + || ((!see_monst(mp)) && !on(player, SEEMONST))) + { + if (!terse) + addmsg(rs,"I see "); + msg(rs,"no monster there"); + after = FALSE; + } + else if (diag_ok(&hero, &delta)) + { + to_death = TRUE; + max_hit = 0; + mp->t_flags |= ISTARGET; + runch = ch = dir_ch; + goto over; + } + when 't': + if (!get_dir(rs)) + after = FALSE; + else + missile(rs,delta.y, delta.x); + when 'a': + if (last_comm == '\0') + { + msg(rs,"you haven't typed a command yet"); + after = FALSE; + } + else + { + ch = last_comm; + again = TRUE; + goto over; + } + when 'q': quaff(rs); + when 'Q': + after = FALSE; + q_comm = TRUE; + quit(0); + q_comm = FALSE; + when 'i': after = FALSE; inventory(rs,pack, 0); + when 'I': after = FALSE; picky_inven(rs); + when 'd': drop(rs); + when 'r': read_scroll(rs); + when 'e': eat(rs); + when 'w': wield(rs); + when 'W': wear(rs); + when 'T': take_off(rs); + when 'P': ring_on(rs); + when 'R': ring_off(rs); + when 'o': option(rs); after = FALSE; + when 'c': call(rs); after = FALSE; + when '>': after = FALSE; d_level(rs); + when '<': after = FALSE; u_level(rs); + when '?': after = FALSE; help(rs); + when '/': after = FALSE; identify(rs); + when 's': search(rs); + when 'z': + if (get_dir(rs)) + do_zap(rs); + else + after = FALSE; + when 'D': after = FALSE; discovered(rs); + when CTRL('P'): after = FALSE; msg(rs,huh); + when CTRL('R'): + after = FALSE; + clearok(curscr,TRUE); + wrefresh(curscr); + when 'v': + after = FALSE; + msg(rs,"version %s. (mctesq was here)", release); + when 'S': + after = FALSE; + save_game(rs); + when '.': ; /* Rest command */ + when ' ': after = FALSE; /* "Legal" illegal command */ + when '^': + after = FALSE; + if (get_dir(rs)) { + delta.y += hero.y; + delta.x += hero.x; + fp = &flat(delta.y, delta.x); + if (!terse) + addmsg(rs,"You have found "); + if (chat(delta.y, delta.x) != TRAP) + msg(rs,"no trap there"); + else if (on(player, ISHALU)) + msg(rs,tr_name[rnd(NTRAPS)]); + else { + msg(rs,tr_name[*fp & F_TMASK]); + *fp |= F_SEEN; + } + } +#ifdef MASTER + when '+': + after = FALSE; + if (wizard) + { + wizard = FALSE; + turn_see(TRUE); + msg(rs,"not wizard any more"); + } + else + { + wizard = passwd(); + if (wizard) + { + noscore = TRUE; + turn_see(FALSE); + msg(rs,"you are suddenly as smart as Ken Arnold in dungeon #%d", dnum); + } + else + msg(rs,"sorry"); + } +#endif + when ESCAPE: /* Escape */ + door_stop = FALSE; + count = 0; + after = FALSE; + again = FALSE; + when 'm': + move_on = TRUE; + if (!get_dir(rs)) + after = FALSE; + else + { + ch = dir_ch; + countch = dir_ch; + goto over; + } + when ')': current(rs,cur_weapon, "wielding", NULL); + when ']': current(rs,cur_armor, "wearing", NULL); + when '=': + current(rs,cur_ring[LEFT], "wearing", + terse ? "(L)" : "on left hand"); + current(rs,cur_ring[RIGHT], "wearing", + terse ? "(R)" : "on right hand"); + when '@': + stat_msg = TRUE; + status(rs); + stat_msg = FALSE; + after = FALSE; + otherwise: + after = FALSE; +#ifdef MASTER + if (wizard) switch (ch) + { + case '|': msg(rs,"@ %d,%d", hero.y, hero.x); + when 'C': create_obj(); + when '$': msg(rs,"inpack = %d", inpack); + when CTRL('G'): inventory(rs,lvl_obj, 0); + when CTRL('W'): whatis(rs,FALSE, 0); + when CTRL('D'): level++; new_level(); + when CTRL('A'): level--; new_level(); + when CTRL('F'): show_map(); + when CTRL('T'): teleport(); + when CTRL('E'): msg(rs,"food left: %d", food_left); + when CTRL('C'): add_pass(); + when CTRL('X'): turn_see(on(player, SEEMONST)); + when CTRL('~'): + { + THING *item; + + if ((item = get_item(rs,"charge", STICK)) != NULL) + item->o_charges = 10000; + } + when CTRL('I'): + { + int i; + THING *obj; + + for (i = 0; i < 9; i++) + raise_level(rs); + /* + * Give him a sword (+1,+1) + */ + obj = new_item(); + init_weapon(obj, TWOSWORD); + obj->o_hplus = 1; + obj->o_dplus = 1; + add_pack(rs,obj, TRUE); + cur_weapon = obj; + /* + * And his suit of armor + */ + obj = new_item(); + obj->o_type = ARMOR; + obj->o_which = PLATE_MAIL; + obj->o_arm = -5; + obj->o_flags |= ISKNOW; + obj->o_count = 1; + obj->o_group = 0; + cur_armor = obj; + add_pack(rs,obj, TRUE); + } + when '*' : + pr_list(); + otherwise: + illcom(rs,ch); + } + else +#endif + illcom(rs,ch); + } + /* + * turn off flags if no longer needed + */ + if (!running) + door_stop = FALSE; + } + /* + * If he ran into something to take, let him pick it up. + */ + if (take != 0) + pick_up(rs,take); + if (!running) + door_stop = FALSE; + if (!after) + ntimes++; + } + do_daemons(rs,AFTER); + do_fuses(rs,AFTER); + if (ISRING(LEFT, R_SEARCH)) + search(rs); + else if (ISRING(LEFT, R_TELEPORT) && rnd(50) == 0) + teleport(rs); + if (ISRING(RIGHT, R_SEARCH)) + search(rs); + else if (ISRING(RIGHT, R_TELEPORT) && rnd(50) == 0) + teleport(rs); +} + +/* + * illcom: + * What to do with an illegal command + */ +void +illcom(struct rogue_state *rs,int ch) +{ + save_msg = FALSE; + count = 0; + msg(rs,"illegal command '%s'", unctrl(ch)); + save_msg = TRUE; +} + +/* + * search: + * player gropes about him to find hidden things. + */ +void +search(struct rogue_state *rs) +{ + register int y, x; + register char *fp; + register int ey, ex; + int probinc; + bool found; + + ey = hero.y + 1; + ex = hero.x + 1; + probinc = (on(player, ISHALU) ? 3 : 0); + probinc += (on(player, ISBLIND) ? 2 : 0); + found = FALSE; + for (y = hero.y - 1; y <= ey; y++) + for (x = hero.x - 1; x <= ex; x++) + { + if (y == hero.y && x == hero.x) + continue; + fp = &flat(y, x); + if (!(*fp & F_REAL)) + switch (chat(y, x)) + { + case '|': + case '-': + if (rnd(5 + probinc) != 0) + break; + chat(y, x) = DOOR; + msg(rs,"a secret door"); +foundone: + found = TRUE; + *fp |= F_REAL; + count = FALSE; + running = FALSE; + break; + case FLOOR: + if (rnd(2 + probinc) != 0) + break; + chat(y, x) = TRAP; + if (!terse) + addmsg(rs,"you found "); + if (on(player, ISHALU)) + msg(rs,tr_name[rnd(NTRAPS)]); + else { + msg(rs,tr_name[*fp & F_TMASK]); + *fp |= F_SEEN; + } + goto foundone; + break; + case ' ': + if (rnd(3 + probinc) != 0) + break; + chat(y, x) = PASSAGE; + goto foundone; + } + } + if (found) + look(rs,FALSE); +} + +/* + * help: + * Give single character help, or the whole mess if he wants it + */ +void +help(struct rogue_state *rs) +{ + register struct h_list *strp; + register char helpch; + register int numprint, cnt; + msg(rs,"character you want help for (* for all): "); + helpch = readchar(rs); + mpos = 0; + /* + * If its not a *, print the right help string + * or an error if he typed a funny character. + */ + if (helpch != '*') + { + move(0, 0); + for (strp = helpstr; strp->h_desc != NULL; strp++) + if (strp->h_ch == helpch) + { + lower_msg = TRUE; + msg(rs,"%s%s", unctrl(strp->h_ch), strp->h_desc); + lower_msg = FALSE; + return; + } + msg(rs,"unknown character '%s'", unctrl(helpch)); + return; + } + /* + * Here we print help for everything. + * Then wait before we return to command mode + */ + numprint = 0; + for (strp = helpstr; strp->h_desc != NULL; strp++) + if (strp->h_print) + numprint++; + if (numprint & 01) /* round odd numbers up */ + numprint++; + numprint /= 2; + if (numprint > LINES - 1) + numprint = LINES - 1; + + wclear(hw); + cnt = 0; + for (strp = helpstr; strp->h_desc != NULL; strp++) + if (strp->h_print) + { + wmove(hw, cnt % numprint, cnt >= numprint ? COLS / 2 : 0); + if (strp->h_ch) + waddstr(hw, unctrl(strp->h_ch)); + waddstr(hw, strp->h_desc); + if (++cnt >= numprint * 2) + break; + } + wmove(hw, LINES - 1, 0); + waddstr(hw, "--Press space to continue--"); + wrefresh(hw); + wait_for(rs,' '); + clearok(stdscr, TRUE); +/* + refresh(); +*/ + msg(rs,""); + touchwin(stdscr); + wrefresh(stdscr); +} + +/* + * identify: + * Tell the player what a certain thing is. + */ +void +identify(struct rogue_state *rs) +{ + register int ch; + register struct h_list *hp; + register char *str; + static struct h_list ident_list[] = { + {'|', "wall of a room", FALSE}, + {'-', "wall of a room", FALSE}, + {GOLD, "gold", FALSE}, + {STAIRS, "a staircase", FALSE}, + {DOOR, "door", FALSE}, + {FLOOR, "room floor", FALSE}, + {PLAYER, "you", FALSE}, + {PASSAGE, "passage", FALSE}, + {TRAP, "trap", FALSE}, + {POTION, "potion", FALSE}, + {SCROLL, "scroll", FALSE}, + {FOOD, "food", FALSE}, + {WEAPON, "weapon", FALSE}, + {' ', "solid rock", FALSE}, + {ARMOR, "armor", FALSE}, + {AMULET, "the Amulet of Yendor", FALSE}, + {RING, "ring", FALSE}, + {STICK, "wand or staff", FALSE}, + {'\0'} + }; + + msg(rs,"what do you want identified? "); + ch = readchar(rs); + mpos = 0; + if (ch == ESCAPE) + { + msg(rs,""); + return; + } + if (isupper(ch)) + str = monsters[ch-'A'].m_name; + else + { + str = "unknown character"; + for (hp = ident_list; hp->h_ch != '\0'; hp++) + if (hp->h_ch == ch) + { + str = hp->h_desc; + break; + } + } + msg(rs,"'%s': %s", unctrl(ch), str); +} + +/* + * d_level: + * He wants to go down a level + */ +void +d_level(struct rogue_state *rs) +{ + if (levit_check(rs)) + return; + if (chat(hero.y, hero.x) != STAIRS) + msg(rs,"I see no way down"); + else + { + level++; + seenstairs = FALSE; + new_level(rs); + } +} + +/* + * u_level: + * He wants to go up a level + */ +void +u_level(struct rogue_state *rs) +{ + if (levit_check(rs)) + return; + if (chat(hero.y, hero.x) == STAIRS) + if (amulet) + { + level--; + if (level == 0) + total_winner(rs); + new_level(rs); + msg(rs,"you feel a wrenching sensation in your gut"); + } + else + msg(rs,"your way is magically blocked"); + else + msg(rs,"I see no way up"); +} + +/* + * levit_check: + * Check to see if she's levitating, and if she is, print an + * appropriate message. + */ +bool +levit_check(struct rogue_state *rs) +{ + if (!on(player, ISLEVIT)) + return FALSE; + msg(rs,"You can't. You're floating off the ground!"); + return TRUE; +} + +/* + * call: + * Allow a user to call a potion, scroll, or ring something + */ +void +call(struct rogue_state *rs) +{ + register THING *obj; + register struct obj_info *op = NULL; + register char **guess, *elsewise = NULL; + register bool *know; + + obj = get_item(rs,"call", CALLABLE); + /* + * Make certain that it is somethings that we want to wear + */ + if (obj == NULL) + return; + switch (obj->o_type) + { + case RING: + op = &ring_info[obj->o_which]; + elsewise = r_stones[obj->o_which]; + goto norm; + when POTION: + op = &pot_info[obj->o_which]; + elsewise = p_colors[obj->o_which]; + goto norm; + when SCROLL: + op = &scr_info[obj->o_which]; + elsewise = s_names[obj->o_which]; + goto norm; + when STICK: + op = &ws_info[obj->o_which]; + elsewise = ws_made[obj->o_which]; +norm: + know = &op->oi_know; + guess = &op->oi_guess; + if (*guess != NULL) + elsewise = *guess; + when FOOD: + msg(rs,"you can't call that anything"); + return; + otherwise: + guess = &obj->o_label; + know = NULL; + elsewise = obj->o_label; + } + if (know != NULL && *know) + { + msg(rs,"that has already been identified"); + return; + } + if (elsewise != NULL && elsewise == *guess) + { + if (!terse) + addmsg(rs,"Was "); + msg(rs,"called \"%s\"", elsewise); + } + if (terse) + msg(rs,"call it: "); + else + msg(rs,"what do you want to call it? "); + + if (elsewise == NULL) + strcpy(prbuf, ""); + else + strcpy(prbuf, elsewise); + if (get_str(rs,prbuf, stdscr) == NORM) + { + if (*guess != NULL) + free(*guess); + *guess = malloc((unsigned int) strlen(prbuf) + 1); + strcpy(*guess, prbuf); + } +} + +/* + * current: + * Print the current weapon/armor + */ +void +current(struct rogue_state *rs,THING *cur, char *how, char *where) +{ + after = FALSE; + if (cur != NULL) + { + if (!terse) + addmsg(rs,"you are %s (", how); + inv_describe = FALSE; + addmsg(rs,"%c) %s", cur->o_packch, inv_name(cur, TRUE)); + inv_describe = TRUE; + if (where) + addmsg(rs," %s", where); + endmsg(rs); + } + else + { + if (!terse) + addmsg(rs,"you are "); + addmsg(rs,"%s nothing", how); + if (where) + addmsg(rs," %s", where); + endmsg(rs); + } +} diff --git a/src/cc/rogue/config.guess b/src/cc/rogue/config.guess new file mode 100755 index 000000000..396482d6c --- /dev/null +++ b/src/cc/rogue/config.guess @@ -0,0 +1,1500 @@ +#! /bin/sh +# Attempt to guess a canonical system name. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, +# Inc. + +timestamp='2006-07-02' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA +# 02110-1301, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + + +# Originally written by Per Bothner . +# Please send patches to . Submit a context +# diff and a properly formatted ChangeLog entry. +# +# This script attempts to guess a canonical system name similar to +# config.sub. If it succeeds, it prints the system name on stdout, and +# exits with 0. Otherwise, it exits with 1. +# +# The plan is that this can be called by configure scripts if you +# don't specify an explicit build system type. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] + +Output the configuration name of the system \`$me' is run on. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.guess ($timestamp) + +Originally written by Per Bothner. +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + * ) + break ;; + esac +done + +if test $# != 0; then + echo "$me: too many arguments$help" >&2 + exit 1 +fi + +trap 'exit 1' 1 2 15 + +# CC_FOR_BUILD -- compiler used by this script. Note that the use of a +# compiler to aid in system detection is discouraged as it requires +# temporary files to be created and, as you can see below, it is a +# headache to deal with in a portable fashion. + +# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still +# use `HOST_CC' if defined, but it is deprecated. + +# Portable tmp directory creation inspired by the Autoconf team. + +set_cc_for_build=' +trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; +trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; +: ${TMPDIR=/tmp} ; + { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || + { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || + { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || + { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; +dummy=$tmp/dummy ; +tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; +case $CC_FOR_BUILD,$HOST_CC,$CC in + ,,) echo "int x;" > $dummy.c ; + for c in cc gcc c89 c99 ; do + if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then + CC_FOR_BUILD="$c"; break ; + fi ; + done ; + if test x"$CC_FOR_BUILD" = x ; then + CC_FOR_BUILD=no_compiler_found ; + fi + ;; + ,,*) CC_FOR_BUILD=$CC ;; + ,*,*) CC_FOR_BUILD=$HOST_CC ;; +esac ; set_cc_for_build= ;' + +# This is needed to find uname on a Pyramid OSx when run in the BSD universe. +# (ghazi@noc.rutgers.edu 1994-08-24) +if (test -f /.attbin/uname) >/dev/null 2>&1 ; then + PATH=$PATH:/.attbin ; export PATH +fi + +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + +# Note: order is significant - the case branches are not exclusive. + +case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in + *:NetBSD:*:*) + # NetBSD (nbsd) targets should (where applicable) match one or + # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*, + # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently + # switched to ELF, *-*-netbsd* would select the old + # object file format. This provides both forward + # compatibility and a consistent mechanism for selecting the + # object file format. + # + # Note: NetBSD doesn't particularly care about the vendor + # portion of the name. We always set it to "unknown". + sysctl="sysctl -n hw.machine_arch" + UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ + /usr/sbin/$sysctl 2>/dev/null || echo unknown)` + case "${UNAME_MACHINE_ARCH}" in + armeb) machine=armeb-unknown ;; + arm*) machine=arm-unknown ;; + sh3el) machine=shl-unknown ;; + sh3eb) machine=sh-unknown ;; + *) machine=${UNAME_MACHINE_ARCH}-unknown ;; + esac + # The Operating System including object format, if it has switched + # to ELF recently, or will in the future. + case "${UNAME_MACHINE_ARCH}" in + arm*|i386|m68k|ns32k|sh3*|sparc|vax) + eval $set_cc_for_build + if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep __ELF__ >/dev/null + then + # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). + # Return netbsd for either. FIX? + os=netbsd + else + os=netbsdelf + fi + ;; + *) + os=netbsd + ;; + esac + # The OS release + # Debian GNU/NetBSD machines have a different userland, and + # thus, need a distinct triplet. However, they do not need + # kernel version information, so it can be replaced with a + # suitable tag, in the style of linux-gnu. + case "${UNAME_VERSION}" in + Debian*) + release='-gnu' + ;; + *) + release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` + ;; + esac + # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: + # contains redundant information, the shorter form: + # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. + echo "${machine}-${os}${release}" + exit ;; + *:OpenBSD:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` + echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} + exit ;; + *:ekkoBSD:*:*) + echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} + exit ;; + *:SolidBSD:*:*) + echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} + exit ;; + macppc:MirBSD:*:*) + echo powerpc-unknown-mirbsd${UNAME_RELEASE} + exit ;; + *:MirBSD:*:*) + echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} + exit ;; + alpha:OSF1:*:*) + case $UNAME_RELEASE in + *4.0) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` + ;; + *5.*) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` + ;; + esac + # According to Compaq, /usr/sbin/psrinfo has been available on + # OSF/1 and Tru64 systems produced since 1995. I hope that + # covers most systems running today. This code pipes the CPU + # types through head -n 1, so we only detect the type of CPU 0. + ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` + case "$ALPHA_CPU_TYPE" in + "EV4 (21064)") + UNAME_MACHINE="alpha" ;; + "EV4.5 (21064)") + UNAME_MACHINE="alpha" ;; + "LCA4 (21066/21068)") + UNAME_MACHINE="alpha" ;; + "EV5 (21164)") + UNAME_MACHINE="alphaev5" ;; + "EV5.6 (21164A)") + UNAME_MACHINE="alphaev56" ;; + "EV5.6 (21164PC)") + UNAME_MACHINE="alphapca56" ;; + "EV5.7 (21164PC)") + UNAME_MACHINE="alphapca57" ;; + "EV6 (21264)") + UNAME_MACHINE="alphaev6" ;; + "EV6.7 (21264A)") + UNAME_MACHINE="alphaev67" ;; + "EV6.8CB (21264C)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8AL (21264B)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8CX (21264D)") + UNAME_MACHINE="alphaev68" ;; + "EV6.9A (21264/EV69A)") + UNAME_MACHINE="alphaev69" ;; + "EV7 (21364)") + UNAME_MACHINE="alphaev7" ;; + "EV7.9 (21364A)") + UNAME_MACHINE="alphaev79" ;; + esac + # A Pn.n version is a patched version. + # A Vn.n version is a released version. + # A Tn.n version is a released field test version. + # A Xn.n version is an unreleased experimental baselevel. + # 1.2 uses "1.2" for uname -r. + echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + exit ;; + Alpha\ *:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # Should we change UNAME_MACHINE based on the output of uname instead + # of the specific Alpha model? + echo alpha-pc-interix + exit ;; + 21064:Windows_NT:50:3) + echo alpha-dec-winnt3.5 + exit ;; + Amiga*:UNIX_System_V:4.0:*) + echo m68k-unknown-sysv4 + exit ;; + *:[Aa]miga[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-amigaos + exit ;; + *:[Mm]orph[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-morphos + exit ;; + *:OS/390:*:*) + echo i370-ibm-openedition + exit ;; + *:z/VM:*:*) + echo s390-ibm-zvmoe + exit ;; + *:OS400:*:*) + echo powerpc-ibm-os400 + exit ;; + arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) + echo arm-acorn-riscix${UNAME_RELEASE} + exit ;; + arm:riscos:*:*|arm:RISCOS:*:*) + echo arm-unknown-riscos + exit ;; + SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) + echo hppa1.1-hitachi-hiuxmpp + exit ;; + Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) + # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. + if test "`(/bin/universe) 2>/dev/null`" = att ; then + echo pyramid-pyramid-sysv3 + else + echo pyramid-pyramid-bsd + fi + exit ;; + NILE*:*:*:dcosx) + echo pyramid-pyramid-svr4 + exit ;; + DRS?6000:unix:4.0:6*) + echo sparc-icl-nx6 + exit ;; + DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) + case `/usr/bin/uname -p` in + sparc) echo sparc-icl-nx7; exit ;; + esac ;; + sun4H:SunOS:5.*:*) + echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) + echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + i86pc:SunOS:5.*:*) + echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:6*:*) + # According to config.sub, this is the proper way to canonicalize + # SunOS6. Hard to guess exactly what SunOS6 will be like, but + # it's likely to be more like Solaris than SunOS4. + echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:*:*) + case "`/usr/bin/arch -k`" in + Series*|S4*) + UNAME_RELEASE=`uname -v` + ;; + esac + # Japanese Language versions have a version number like `4.1.3-JL'. + echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` + exit ;; + sun3*:SunOS:*:*) + echo m68k-sun-sunos${UNAME_RELEASE} + exit ;; + sun*:*:4.2BSD:*) + UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` + test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 + case "`/bin/arch`" in + sun3) + echo m68k-sun-sunos${UNAME_RELEASE} + ;; + sun4) + echo sparc-sun-sunos${UNAME_RELEASE} + ;; + esac + exit ;; + aushp:SunOS:*:*) + echo sparc-auspex-sunos${UNAME_RELEASE} + exit ;; + # The situation for MiNT is a little confusing. The machine name + # can be virtually everything (everything which is not + # "atarist" or "atariste" at least should have a processor + # > m68000). The system name ranges from "MiNT" over "FreeMiNT" + # to the lowercase version "mint" (or "freemint"). Finally + # the system name "TOS" denotes a system which is actually not + # MiNT. But MiNT is downward compatible to TOS, so this should + # be no problem. + atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) + echo m68k-milan-mint${UNAME_RELEASE} + exit ;; + hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) + echo m68k-hades-mint${UNAME_RELEASE} + exit ;; + *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) + echo m68k-unknown-mint${UNAME_RELEASE} + exit ;; + m68k:machten:*:*) + echo m68k-apple-machten${UNAME_RELEASE} + exit ;; + powerpc:machten:*:*) + echo powerpc-apple-machten${UNAME_RELEASE} + exit ;; + RISC*:Mach:*:*) + echo mips-dec-mach_bsd4.3 + exit ;; + RISC*:ULTRIX:*:*) + echo mips-dec-ultrix${UNAME_RELEASE} + exit ;; + VAX*:ULTRIX*:*:*) + echo vax-dec-ultrix${UNAME_RELEASE} + exit ;; + 2020:CLIX:*:* | 2430:CLIX:*:*) + echo clipper-intergraph-clix${UNAME_RELEASE} + exit ;; + mips:*:*:UMIPS | mips:*:*:RISCos) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif + #if defined (host_mips) && defined (MIPSEB) + #if defined (SYSTYPE_SYSV) + printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_SVR4) + printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) + printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); + #endif + #endif + exit (-1); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && + dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && + SYSTEM_NAME=`$dummy $dummyarg` && + { echo "$SYSTEM_NAME"; exit; } + echo mips-mips-riscos${UNAME_RELEASE} + exit ;; + Motorola:PowerMAX_OS:*:*) + echo powerpc-motorola-powermax + exit ;; + Motorola:*:4.3:PL8-*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:Power_UNIX:*:*) + echo powerpc-harris-powerunix + exit ;; + m88k:CX/UX:7*:*) + echo m88k-harris-cxux7 + exit ;; + m88k:*:4*:R4*) + echo m88k-motorola-sysv4 + exit ;; + m88k:*:3*:R3*) + echo m88k-motorola-sysv3 + exit ;; + AViiON:dgux:*:*) + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` + if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] + then + if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ + [ ${TARGET_BINARY_INTERFACE}x = x ] + then + echo m88k-dg-dgux${UNAME_RELEASE} + else + echo m88k-dg-dguxbcs${UNAME_RELEASE} + fi + else + echo i586-dg-dgux${UNAME_RELEASE} + fi + exit ;; + M88*:DolphinOS:*:*) # DolphinOS (SVR3) + echo m88k-dolphin-sysv3 + exit ;; + M88*:*:R3*:*) + # Delta 88k system running SVR3 + echo m88k-motorola-sysv3 + exit ;; + XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) + echo m88k-tektronix-sysv3 + exit ;; + Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) + echo m68k-tektronix-bsd + exit ;; + *:IRIX*:*:*) + echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` + exit ;; + ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. + echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id + exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + i*86:AIX:*:*) + echo i386-ibm-aix + exit ;; + ia64:AIX:*:*) + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} + exit ;; + *:AIX:2:3) + if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + + main() + { + if (!__power_pc()) + exit(1); + puts("powerpc-ibm-aix3.2.5"); + exit(0); + } +EOF + if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` + then + echo "$SYSTEM_NAME" + else + echo rs6000-ibm-aix3.2.5 + fi + elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then + echo rs6000-ibm-aix3.2.4 + else + echo rs6000-ibm-aix3.2 + fi + exit ;; + *:AIX:*:[45]) + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` + if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then + IBM_ARCH=rs6000 + else + IBM_ARCH=powerpc + fi + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${IBM_ARCH}-ibm-aix${IBM_REV} + exit ;; + *:AIX:*:*) + echo rs6000-ibm-aix + exit ;; + ibmrt:4.4BSD:*|romp-ibm:BSD:*) + echo romp-ibm-bsd4.4 + exit ;; + ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and + echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to + exit ;; # report: romp-ibm BSD 4.3 + *:BOSX:*:*) + echo rs6000-bull-bosx + exit ;; + DPX/2?00:B.O.S.:*:*) + echo m68k-bull-sysv3 + exit ;; + 9000/[34]??:4.3bsd:1.*:*) + echo m68k-hp-bsd + exit ;; + hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) + echo m68k-hp-bsd4.4 + exit ;; + 9000/[34678]??:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + case "${UNAME_MACHINE}" in + 9000/31? ) HP_ARCH=m68000 ;; + 9000/[34]?? ) HP_ARCH=m68k ;; + 9000/[678][0-9][0-9]) + if [ -x /usr/bin/getconf ]; then + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case "${sc_cpu_version}" in + 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 + 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case "${sc_kernel_bits}" in + 32) HP_ARCH="hppa2.0n" ;; + 64) HP_ARCH="hppa2.0w" ;; + '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 + esac ;; + esac + fi + if [ "${HP_ARCH}" = "" ]; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + + #define _HPUX_SOURCE + #include + #include + + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); + + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } +EOF + (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` + test -z "$HP_ARCH" && HP_ARCH=hppa + fi ;; + esac + if [ ${HP_ARCH} = "hppa2.0w" ] + then + eval $set_cc_for_build + + # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating + # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler + # generating 64-bit code. GNU and HP use different nomenclature: + # + # $ CC_FOR_BUILD=cc ./config.guess + # => hppa2.0w-hp-hpux11.23 + # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess + # => hppa64-hp-hpux11.23 + + if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | + grep __LP64__ >/dev/null + then + HP_ARCH="hppa2.0w" + else + HP_ARCH="hppa64" + fi + fi + echo ${HP_ARCH}-hp-hpux${HPUX_REV} + exit ;; + ia64:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + echo ia64-hp-hpux${HPUX_REV} + exit ;; + 3050*:HI-UX:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + int + main () + { + long cpu = sysconf (_SC_CPU_VERSION); + /* The order matters, because CPU_IS_HP_MC68K erroneously returns + true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct + results, however. */ + if (CPU_IS_PA_RISC (cpu)) + { + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; + case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; + default: puts ("hppa-hitachi-hiuxwe2"); break; + } + } + else if (CPU_IS_HP_MC68K (cpu)) + puts ("m68k-hitachi-hiuxwe2"); + else puts ("unknown-hitachi-hiuxwe2"); + exit (0); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + echo unknown-hitachi-hiuxwe2 + exit ;; + 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) + echo hppa1.1-hp-bsd + exit ;; + 9000/8??:4.3bsd:*:*) + echo hppa1.0-hp-bsd + exit ;; + *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) + echo hppa1.0-hp-mpeix + exit ;; + hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) + echo hppa1.1-hp-osf + exit ;; + hp8??:OSF1:*:*) + echo hppa1.0-hp-osf + exit ;; + i*86:OSF1:*:*) + if [ -x /usr/sbin/sysversion ] ; then + echo ${UNAME_MACHINE}-unknown-osf1mk + else + echo ${UNAME_MACHINE}-unknown-osf1 + fi + exit ;; + parisc*:Lites*:*:*) + echo hppa1.1-hp-lites + exit ;; + C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) + echo c1-convex-bsd + exit ;; + C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) + echo c34-convex-bsd + exit ;; + C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) + echo c38-convex-bsd + exit ;; + C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) + echo c4-convex-bsd + exit ;; + CRAY*Y-MP:*:*:*) + echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*[A-Z]90:*:*:*) + echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ + | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ + -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ + -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*TS:*:*:*) + echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*T3E:*:*:*) + echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*SV1:*:*:*) + echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + *:UNICOS/mp:*:*) + echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) + FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` + echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + 5000:UNIX_System_V:4.*:*) + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` + echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) + echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} + exit ;; + sparc*:BSD/OS:*:*) + echo sparc-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:BSD/OS:*:*) + echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:FreeBSD:*:*) + case ${UNAME_MACHINE} in + pc98) + echo i386-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + amd64) + echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + *) + echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + esac + exit ;; + i*:CYGWIN*:*) + echo ${UNAME_MACHINE}-pc-cygwin + exit ;; + i*:MINGW*:*) + echo ${UNAME_MACHINE}-pc-mingw32 + exit ;; + i*:windows32*:*) + # uname -m includes "-pc" on this system. + echo ${UNAME_MACHINE}-mingw32 + exit ;; + i*:PW*:*) + echo ${UNAME_MACHINE}-pc-pw32 + exit ;; + x86:Interix*:[3456]*) + echo i586-pc-interix${UNAME_RELEASE} + exit ;; + EM64T:Interix*:[3456]*) + echo x86_64-unknown-interix${UNAME_RELEASE} + exit ;; + [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) + echo i${UNAME_MACHINE}-pc-mks + exit ;; + i*:Windows_NT*:* | Pentium*:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we + # UNAME_MACHINE based on the output of uname instead of i386? + echo i586-pc-interix + exit ;; + i*:UWIN*:*) + echo ${UNAME_MACHINE}-pc-uwin + exit ;; + amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) + echo x86_64-unknown-cygwin + exit ;; + p*:CYGWIN*:*) + echo powerpcle-unknown-cygwin + exit ;; + prep*:SunOS:5.*:*) + echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + *:GNU:*:*) + # the GNU system + echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` + exit ;; + *:GNU/*:*:*) + # other systems with GNU libc and userland + echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu + exit ;; + i*86:Minix:*:*) + echo ${UNAME_MACHINE}-pc-minix + exit ;; + arm*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + avr32*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + cris:Linux:*:*) + echo cris-axis-linux-gnu + exit ;; + crisv32:Linux:*:*) + echo crisv32-axis-linux-gnu + exit ;; + frv:Linux:*:*) + echo frv-unknown-linux-gnu + exit ;; + ia64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + m32r*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + m68*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + mips:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef mips + #undef mipsel + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=mipsel + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=mips + #else + CPU= + #endif + #endif +EOF + eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' + /^CPU/{ + s: ::g + p + }'`" + test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } + ;; + mips64:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef mips64 + #undef mips64el + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=mips64el + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=mips64 + #else + CPU= + #endif + #endif +EOF + eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' + /^CPU/{ + s: ::g + p + }'`" + test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } + ;; + or32:Linux:*:*) + echo or32-unknown-linux-gnu + exit ;; + ppc:Linux:*:*) + echo powerpc-unknown-linux-gnu + exit ;; + ppc64:Linux:*:*) + echo powerpc64-unknown-linux-gnu + exit ;; + alpha:Linux:*:*) + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in + EV5) UNAME_MACHINE=alphaev5 ;; + EV56) UNAME_MACHINE=alphaev56 ;; + PCA56) UNAME_MACHINE=alphapca56 ;; + PCA57) UNAME_MACHINE=alphapca56 ;; + EV6) UNAME_MACHINE=alphaev6 ;; + EV67) UNAME_MACHINE=alphaev67 ;; + EV68*) UNAME_MACHINE=alphaev68 ;; + esac + objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null + if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi + echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} + exit ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) echo hppa1.1-unknown-linux-gnu ;; + PA8*) echo hppa2.0-unknown-linux-gnu ;; + *) echo hppa-unknown-linux-gnu ;; + esac + exit ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) + echo hppa64-unknown-linux-gnu + exit ;; + s390:Linux:*:* | s390x:Linux:*:*) + echo ${UNAME_MACHINE}-ibm-linux + exit ;; + sh64*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + sh*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + sparc:Linux:*:* | sparc64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + vax:Linux:*:*) + echo ${UNAME_MACHINE}-dec-linux-gnu + exit ;; + x86_64:Linux:*:*) + echo x86_64-unknown-linux-gnu + exit ;; + i*86:Linux:*:*) + # The BFD linker knows what the default object file format is, so + # first see if it will tell us. cd to the root directory to prevent + # problems with other programs or directories called `ld' in the path. + # Set LC_ALL=C to ensure ld outputs messages in English. + ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \ + | sed -ne '/supported targets:/!d + s/[ ][ ]*/ /g + s/.*supported targets: *// + s/ .*// + p'` + case "$ld_supported_targets" in + elf32-i386) + TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu" + ;; + a.out-i386-linux) + echo "${UNAME_MACHINE}-pc-linux-gnuaout" + exit ;; + coff-i386) + echo "${UNAME_MACHINE}-pc-linux-gnucoff" + exit ;; + "") + # Either a pre-BFD a.out linker (linux-gnuoldld) or + # one that does not give us useful --help. + echo "${UNAME_MACHINE}-pc-linux-gnuoldld" + exit ;; + esac + # Determine whether the default compiler is a.out or elf + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + #ifdef __ELF__ + # ifdef __GLIBC__ + # if __GLIBC__ >= 2 + LIBC=gnu + # else + LIBC=gnulibc1 + # endif + # else + LIBC=gnulibc1 + # endif + #else + #if defined(__INTEL_COMPILER) || defined(__PGI) || defined(__SUNPRO_C) || defined(__SUNPRO_CC) + LIBC=gnu + #else + LIBC=gnuaout + #endif + #endif + #ifdef __dietlibc__ + LIBC=dietlibc + #endif +EOF + eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' + /^LIBC/{ + s: ::g + p + }'`" + test x"${LIBC}" != x && { + echo "${UNAME_MACHINE}-pc-linux-${LIBC}" + exit + } + test x"${TENTATIVE}" != x && { echo "${TENTATIVE}"; exit; } + ;; + i*86:DYNIX/ptx:4*:*) + # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. + # earlier versions are messed up and put the nodename in both + # sysname and nodename. + echo i386-sequent-sysv4 + exit ;; + i*86:UNIX_SV:4.2MP:2.*) + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, + # I just have to hope. -- rms. + # Use sysv4.2uw... so that sysv4* matches it. + echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} + exit ;; + i*86:OS/2:*:*) + # If we were able to find `uname', then EMX Unix compatibility + # is probably installed. + echo ${UNAME_MACHINE}-pc-os2-emx + exit ;; + i*86:XTS-300:*:STOP) + echo ${UNAME_MACHINE}-unknown-stop + exit ;; + i*86:atheos:*:*) + echo ${UNAME_MACHINE}-unknown-atheos + exit ;; + i*86:syllable:*:*) + echo ${UNAME_MACHINE}-pc-syllable + exit ;; + i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*) + echo i386-unknown-lynxos${UNAME_RELEASE} + exit ;; + i*86:*DOS:*:*) + echo ${UNAME_MACHINE}-pc-msdosdjgpp + exit ;; + i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) + UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` + if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then + echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} + else + echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} + fi + exit ;; + i*86:*:5:[678]*) + # UnixWare 7.x, OpenUNIX and OpenServer 6. + case `/bin/uname -X | grep "^Machine"` in + *486*) UNAME_MACHINE=i486 ;; + *Pentium) UNAME_MACHINE=i586 ;; + *Pent*|*Celeron) UNAME_MACHINE=i686 ;; + esac + echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} + exit ;; + i*86:*:3.2:*) + if test -f /usr/options/cb.name; then + UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then + UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` + (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 + (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ + && UNAME_MACHINE=i586 + (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ + && UNAME_MACHINE=i686 + (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ + && UNAME_MACHINE=i686 + echo ${UNAME_MACHINE}-pc-sco$UNAME_REL + else + echo ${UNAME_MACHINE}-pc-sysv32 + fi + exit ;; + pc:*:*:*) + # Left here for compatibility: + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i386. + echo i386-pc-msdosdjgpp + exit ;; + Intel:Mach:3*:*) + echo i386-pc-mach3 + exit ;; + paragon:*:*:*) + echo i860-intel-osf1 + exit ;; + i860:*:4.*:*) # i860-SVR4 + if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then + echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 + else # Add other i860-SVR4 vendors below as they are discovered. + echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 + fi + exit ;; + mini*:CTIX:SYS*5:*) + # "miniframe" + echo m68010-convergent-sysv + exit ;; + mc68k:UNIX:SYSTEM5:3.51m) + echo m68k-convergent-sysv + exit ;; + M680?0:D-NIX:5.3:*) + echo m68k-diab-dnix + exit ;; + M68*:*:R3V[5678]*:*) + test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; + 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) + OS_REL='' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; + 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4; exit; } ;; + m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) + echo m68k-unknown-lynxos${UNAME_RELEASE} + exit ;; + mc68030:UNIX_System_V:4.*:*) + echo m68k-atari-sysv4 + exit ;; + TSUNAMI:LynxOS:2.*:*) + echo sparc-unknown-lynxos${UNAME_RELEASE} + exit ;; + rs6000:LynxOS:2.*:*) + echo rs6000-unknown-lynxos${UNAME_RELEASE} + exit ;; + PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*) + echo powerpc-unknown-lynxos${UNAME_RELEASE} + exit ;; + SM[BE]S:UNIX_SV:*:*) + echo mips-dde-sysv${UNAME_RELEASE} + exit ;; + RM*:ReliantUNIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + RM*:SINIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + *:SINIX-*:*:*) + if uname -p 2>/dev/null >/dev/null ; then + UNAME_MACHINE=`(uname -p) 2>/dev/null` + echo ${UNAME_MACHINE}-sni-sysv4 + else + echo ns32k-sni-sysv + fi + exit ;; + PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + # says + echo i586-unisys-sysv4 + exit ;; + *:UNIX_System_V:4*:FTX*) + # From Gerald Hewes . + # How about differentiating between stratus architectures? -djm + echo hppa1.1-stratus-sysv4 + exit ;; + *:*:*:FTX*) + # From seanf@swdc.stratus.com. + echo i860-stratus-sysv4 + exit ;; + i*86:VOS:*:*) + # From Paul.Green@stratus.com. + echo ${UNAME_MACHINE}-stratus-vos + exit ;; + *:VOS:*:*) + # From Paul.Green@stratus.com. + echo hppa1.1-stratus-vos + exit ;; + mc68*:A/UX:*:*) + echo m68k-apple-aux${UNAME_RELEASE} + exit ;; + news*:NEWS-OS:6*:*) + echo mips-sony-newsos6 + exit ;; + R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) + if [ -d /usr/nec ]; then + echo mips-nec-sysv${UNAME_RELEASE} + else + echo mips-unknown-sysv${UNAME_RELEASE} + fi + exit ;; + BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. + echo powerpc-be-beos + exit ;; + BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. + echo powerpc-apple-beos + exit ;; + BePC:BeOS:*:*) # BeOS running on Intel PC compatible. + echo i586-pc-beos + exit ;; + SX-4:SUPER-UX:*:*) + echo sx4-nec-superux${UNAME_RELEASE} + exit ;; + SX-5:SUPER-UX:*:*) + echo sx5-nec-superux${UNAME_RELEASE} + exit ;; + SX-6:SUPER-UX:*:*) + echo sx6-nec-superux${UNAME_RELEASE} + exit ;; + Power*:Rhapsody:*:*) + echo powerpc-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Rhapsody:*:*) + echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Darwin:*:*) + UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown + case $UNAME_PROCESSOR in + unknown) UNAME_PROCESSOR=powerpc ;; + esac + echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} + exit ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) + UNAME_PROCESSOR=`uname -p` + if test "$UNAME_PROCESSOR" = "x86"; then + UNAME_PROCESSOR=i386 + UNAME_MACHINE=pc + fi + echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} + exit ;; + *:QNX:*:4*) + echo i386-pc-qnx + exit ;; + NSE-?:NONSTOP_KERNEL:*:*) + echo nse-tandem-nsk${UNAME_RELEASE} + exit ;; + NSR-?:NONSTOP_KERNEL:*:*) + echo nsr-tandem-nsk${UNAME_RELEASE} + exit ;; + *:NonStop-UX:*:*) + echo mips-compaq-nonstopux + exit ;; + BS2000:POSIX*:*:*) + echo bs2000-siemens-sysv + exit ;; + DS/*:UNIX_System_V:*:*) + echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} + exit ;; + *:Plan9:*:*) + # "uname -m" is not consistent, so use $cputype instead. 386 + # is converted to i386 for consistency with other x86 + # operating systems. + if test "$cputype" = "386"; then + UNAME_MACHINE=i386 + else + UNAME_MACHINE="$cputype" + fi + echo ${UNAME_MACHINE}-unknown-plan9 + exit ;; + *:TOPS-10:*:*) + echo pdp10-unknown-tops10 + exit ;; + *:TENEX:*:*) + echo pdp10-unknown-tenex + exit ;; + KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) + echo pdp10-dec-tops20 + exit ;; + XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) + echo pdp10-xkl-tops20 + exit ;; + *:TOPS-20:*:*) + echo pdp10-unknown-tops20 + exit ;; + *:ITS:*:*) + echo pdp10-unknown-its + exit ;; + SEI:*:*:SEIUX) + echo mips-sei-seiux${UNAME_RELEASE} + exit ;; + *:DragonFly:*:*) + echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + exit ;; + *:*VMS:*:*) + UNAME_MACHINE=`(uname -p) 2>/dev/null` + case "${UNAME_MACHINE}" in + A*) echo alpha-dec-vms ; exit ;; + I*) echo ia64-dec-vms ; exit ;; + V*) echo vax-dec-vms ; exit ;; + esac ;; + *:XENIX:*:SysV) + echo i386-pc-xenix + exit ;; + i*86:skyos:*:*) + echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' + exit ;; + i*86:rdos:*:*) + echo ${UNAME_MACHINE}-pc-rdos + exit ;; +esac + +#echo '(No uname command or uname output not recognized.)' 1>&2 +#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 + +eval $set_cc_for_build +cat >$dummy.c < +# include +#endif +main () +{ +#if defined (sony) +#if defined (MIPSEB) + /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, + I don't know.... */ + printf ("mips-sony-bsd\n"); exit (0); +#else +#include + printf ("m68k-sony-newsos%s\n", +#ifdef NEWSOS4 + "4" +#else + "" +#endif + ); exit (0); +#endif +#endif + +#if defined (__arm) && defined (__acorn) && defined (__unix) + printf ("arm-acorn-riscix\n"); exit (0); +#endif + +#if defined (hp300) && !defined (hpux) + printf ("m68k-hp-bsd\n"); exit (0); +#endif + +#if defined (NeXT) +#if !defined (__ARCHITECTURE__) +#define __ARCHITECTURE__ "m68k" +#endif + int version; + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; + if (version < 4) + printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); + else + printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); + exit (0); +#endif + +#if defined (MULTIMAX) || defined (n16) +#if defined (UMAXV) + printf ("ns32k-encore-sysv\n"); exit (0); +#else +#if defined (CMU) + printf ("ns32k-encore-mach\n"); exit (0); +#else + printf ("ns32k-encore-bsd\n"); exit (0); +#endif +#endif +#endif + +#if defined (__386BSD__) + printf ("i386-pc-bsd\n"); exit (0); +#endif + +#if defined (sequent) +#if defined (i386) + printf ("i386-sequent-dynix\n"); exit (0); +#endif +#if defined (ns32000) + printf ("ns32k-sequent-dynix\n"); exit (0); +#endif +#endif + +#if defined (_SEQUENT_) + struct utsname un; + + uname(&un); + + if (strncmp(un.version, "V2", 2) == 0) { + printf ("i386-sequent-ptx2\n"); exit (0); + } + if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ + printf ("i386-sequent-ptx1\n"); exit (0); + } + printf ("i386-sequent-ptx\n"); exit (0); + +#endif + +#if defined (vax) +# if !defined (ultrix) +# include +# if defined (BSD) +# if BSD == 43 + printf ("vax-dec-bsd4.3\n"); exit (0); +# else +# if BSD == 199006 + printf ("vax-dec-bsd4.3reno\n"); exit (0); +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# endif +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# else + printf ("vax-dec-ultrix\n"); exit (0); +# endif +#endif + +#if defined (alliant) && defined (i860) + printf ("i860-alliant-bsd\n"); exit (0); +#endif + + exit (1); +} +EOF + +$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + +# Apollos put the system type in the environment. + +test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } + +# Convex versions that predate uname can use getsysinfo(1) + +if [ -x /usr/convex/getsysinfo ] +then + case `getsysinfo -f cpu_type` in + c1*) + echo c1-convex-bsd + exit ;; + c2*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + c34*) + echo c34-convex-bsd + exit ;; + c38*) + echo c38-convex-bsd + exit ;; + c4*) + echo c4-convex-bsd + exit ;; + esac +fi + +cat >&2 < in order to provide the needed +information to handle your system. + +config.guess timestamp = $timestamp + +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` + +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` + +UNAME_MACHINE = ${UNAME_MACHINE} +UNAME_RELEASE = ${UNAME_RELEASE} +UNAME_SYSTEM = ${UNAME_SYSTEM} +UNAME_VERSION = ${UNAME_VERSION} +EOF + +exit 1 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/src/cc/rogue/config.h b/src/cc/rogue/config.h new file mode 100644 index 000000000..558ae3ba1 --- /dev/null +++ b/src/cc/rogue/config.h @@ -0,0 +1,270 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.ac by autoheader. */ + +/* Define if scorefile is top scores, not top players */ +#define ALLSCORES 1 + +/* Define if checktime feature should be enabled */ +/* #undef CHECKTIME */ + +/* Define to group owner of setgid executable */ +/* #undef GROUPOWNER */ + +/* Define to 1 if you have the `alarm' function. */ +#define HAVE_ALARM 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_ARPA_INET_H 1 + +/* Define to 1 if libcurses is requested */ +#define HAVE_CURSES_H 1 + +/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */ +/* #undef HAVE_DOPRNT */ + +/* Define to 1 if you have the `erasechar' function. */ +#define HAVE_ERASECHAR 1 + +/* Define if ncurses has ESCDELAY variable */ +#define HAVE_ESCDELAY 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_FCNTL_H 1 + +/* Define to 1 if you have the `fork' function. */ +#define HAVE_FORK 1 + +/* Define to 1 if you have the `getgid' function. */ +#define HAVE_GETGID 1 + +/* Define to 1 if you have the `getloadavg' function. */ +#define HAVE_GETLOADAVG 1 + +/* Define to 1 if you have the `getpass' function. */ +#define HAVE_GETPASS 1 + +/* Define to 1 if you have the `getpwuid' function. */ +#define HAVE_GETPWUID 1 + +/* Define to 1 if you have the `getuid' function. */ +#define HAVE_GETUID 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `killchar' function. */ +#define HAVE_KILLCHAR 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_LIMITS_H 1 + +/* Define to 1 if you have the `loadav' function. */ +/* #undef HAVE_LOADAV */ + +/* Define to 1 if `lstat' has the bug that it succeeds when given the + zero-length file name argument. */ +/* #undef HAVE_LSTAT_EMPTY_STRING_BUG */ + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the `memset' function. */ +#define HAVE_MEMSET 1 + +/* Define to 1 if libncurses is requested */ +/* #undef HAVE_NCURSES_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_NCURSES_TERM_H */ + +/* Define to 1 if you have the `nlist' function. */ +/* #undef HAVE_NLIST */ + +/* Define to 1 if you have the header file. */ +#define HAVE_NLIST_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_PROCESS_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_PWD_H 1 + +/* Define to 1 if you have the `setenv' function. */ +#define HAVE_SETENV 1 + +/* Define to 1 if you have the `setgid' function. */ +#define HAVE_SETGID 1 + +/* Define to 1 if you have the `setregid' function. */ +#define HAVE_SETREGID 1 + +/* Define to 1 if you have the `setresgid' function. */ +/* #undef HAVE_SETRESGID */ + +/* Define to 1 if you have the `setresuid' function. */ +/* #undef HAVE_SETRESUID */ + +/* Define to 1 if you have the `setreuid' function. */ +#define HAVE_SETREUID 1 + +/* Define to 1 if you have the `setuid' function. */ +#define HAVE_SETUID 1 + +/* Define to 1 if you have the `spawnl' function. */ +/* #undef HAVE_SPAWNL */ + +/* Define to 1 if `stat' has the bug that it succeeds when given the + zero-length file name argument. */ +/* #undef HAVE_STAT_EMPTY_STRING_BUG */ + +/* Define to 1 if stdbool.h conforms to C99. */ +#define HAVE_STDBOOL_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the `strchr' function. */ +#define HAVE_STRCHR 1 + +/* Define to 1 if you have the `strerror' function. */ +#define HAVE_STRERROR 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_IOCTL_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_UTSNAME_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_TERMIOS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_TERM_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UTMP_H 1 + +/* Define to 1 if you have the `vfork' function. */ +#define HAVE_VFORK 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_VFORK_H */ + +/* Define to 1 if you have the `vprintf' function. */ +#define HAVE_VPRINTF 1 + +/* Define to 1 if `fork' works. */ +#define HAVE_WORKING_FORK 1 + +/* Define to 1 if `vfork' works. */ +#define HAVE_WORKING_VFORK 1 + +/* Define to 1 if the system has the type `_Bool'. */ +#define HAVE__BOOL 1 + +/* Define to 1 if you have the `_spawnl' function. */ +/* #undef HAVE__SPAWNL */ + +/* define if we should use program's load average function instead of system + */ +/* #undef LOADAV */ + +/* Define to file to use for scoreboard lockfile */ +#define LOCKFILE "rogue.lck" + +/* Define to 1 if `lstat' dereferences a symlink specified with a trailing + slash. */ +/* #undef LSTAT_FOLLOWS_SLASHED_SYMLINK */ + +/* Define to include wizard mode */ +/* #undef MASTER */ + +/* Define if maxusers feature should be enabled */ +/* #undef MAXLOAD */ + +/* Define if maxusers feature should be enabled */ +/* #undef MAXUSERS */ + +/* kernel file to pass to nlist() when reading load average (unlikely to work) + */ +/* #undef NAMELIST */ + +/* word for the number of scores to store in scoreboard */ +#define NUMNAME "Ten" + +/* number of scores to store in scoreboard */ +#define NUMSCORES 10 + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "yendor@rogueforge.net" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "Rogue" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "Rogue 5.4.4" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "rogue" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "5.4.4" + +/* Define crypt(3) wizard mode password */ +/* #undef PASSWD */ + +/* Define as the return type of signal handlers (`int' or `void'). */ +#define RETSIGTYPE void + +/* Define to file to use for scoreboard */ +#define SCOREFILE "rogue.scr" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define to 1 if your declares `struct tm'. */ +/* #undef TM_IN_SYS_TIME */ + +/* define if we should use program's user counting function instead of + system's */ +/* #undef UCOUNT */ + +/* utmp like file to pass to ucount() when counting online users (unlikely to + work) */ +/* #undef UTMP */ + +/* Define to empty if `const' does not conform to ANSI C. */ +/* #undef const */ + +/* Define to `int' if doesn't define. */ +/* #undef gid_t */ + +/* Define to `int' if does not define. */ +/* #undef pid_t */ + +/* Define to `unsigned int' if does not define. */ +/* #undef size_t */ + +/* Define to `int' if doesn't define. */ +/* #undef uid_t */ + +/* Define as `fork' if `vfork' does not work. */ +/* #undef vfork */ diff --git a/src/cc/rogue/config.h.in b/src/cc/rogue/config.h.in new file mode 100644 index 000000000..54f9b7cba --- /dev/null +++ b/src/cc/rogue/config.h.in @@ -0,0 +1,269 @@ +/* config.h.in. Generated from configure.ac by autoheader. */ + +/* Define if scorefile is top scores, not top players */ +#undef ALLSCORES + +/* Define if checktime feature should be enabled */ +#undef CHECKTIME + +/* Define to group owner of setgid executable */ +#undef GROUPOWNER + +/* Define to 1 if you have the `alarm' function. */ +#undef HAVE_ALARM + +/* Define to 1 if you have the header file. */ +#undef HAVE_ARPA_INET_H + +/* Define to 1 if libcurses is requested */ +#undef HAVE_CURSES_H + +/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */ +#undef HAVE_DOPRNT + +/* Define to 1 if you have the `erasechar' function. */ +#undef HAVE_ERASECHAR + +/* Define if ncurses has ESCDELAY variable */ +#undef HAVE_ESCDELAY + +/* Define to 1 if you have the header file. */ +#undef HAVE_FCNTL_H + +/* Define to 1 if you have the `fork' function. */ +#undef HAVE_FORK + +/* Define to 1 if you have the `getgid' function. */ +#undef HAVE_GETGID + +/* Define to 1 if you have the `getloadavg' function. */ +#undef HAVE_GETLOADAVG + +/* Define to 1 if you have the `getpass' function. */ +#undef HAVE_GETPASS + +/* Define to 1 if you have the `getpwuid' function. */ +#undef HAVE_GETPWUID + +/* Define to 1 if you have the `getuid' function. */ +#undef HAVE_GETUID + +/* Define to 1 if you have the header file. */ +#undef HAVE_INTTYPES_H + +/* Define to 1 if you have the `killchar' function. */ +#undef HAVE_KILLCHAR + +/* Define to 1 if you have the header file. */ +#undef HAVE_LIMITS_H + +/* Define to 1 if you have the `loadav' function. */ +#undef HAVE_LOADAV + +/* Define to 1 if `lstat' has the bug that it succeeds when given the + zero-length file name argument. */ +#undef HAVE_LSTAT_EMPTY_STRING_BUG + +/* Define to 1 if you have the header file. */ +#undef HAVE_MEMORY_H + +/* Define to 1 if you have the `memset' function. */ +#undef HAVE_MEMSET + +/* Define to 1 if libncurses is requested */ +#undef HAVE_NCURSES_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NCURSES_TERM_H + +/* Define to 1 if you have the `nlist' function. */ +#undef HAVE_NLIST + +/* Define to 1 if you have the header file. */ +#undef HAVE_NLIST_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_PROCESS_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_PWD_H + +/* Define to 1 if you have the `setenv' function. */ +#undef HAVE_SETENV + +/* Define to 1 if you have the `setgid' function. */ +#undef HAVE_SETGID + +/* Define to 1 if you have the `setregid' function. */ +#undef HAVE_SETREGID + +/* Define to 1 if you have the `setresgid' function. */ +#undef HAVE_SETRESGID + +/* Define to 1 if you have the `setresuid' function. */ +#undef HAVE_SETRESUID + +/* Define to 1 if you have the `setreuid' function. */ +#undef HAVE_SETREUID + +/* Define to 1 if you have the `setuid' function. */ +#undef HAVE_SETUID + +/* Define to 1 if you have the `spawnl' function. */ +#undef HAVE_SPAWNL + +/* Define to 1 if `stat' has the bug that it succeeds when given the + zero-length file name argument. */ +#undef HAVE_STAT_EMPTY_STRING_BUG + +/* Define to 1 if stdbool.h conforms to C99. */ +#undef HAVE_STDBOOL_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDINT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDLIB_H + +/* Define to 1 if you have the `strchr' function. */ +#undef HAVE_STRCHR + +/* Define to 1 if you have the `strerror' function. */ +#undef HAVE_STRERROR + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRINGS_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRING_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_IOCTL_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_STAT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_TYPES_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_UTSNAME_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_TERMIOS_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_TERM_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_UNISTD_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_UTMP_H + +/* Define to 1 if you have the `vfork' function. */ +#undef HAVE_VFORK + +/* Define to 1 if you have the header file. */ +#undef HAVE_VFORK_H + +/* Define to 1 if you have the `vprintf' function. */ +#undef HAVE_VPRINTF + +/* Define to 1 if `fork' works. */ +#undef HAVE_WORKING_FORK + +/* Define to 1 if `vfork' works. */ +#undef HAVE_WORKING_VFORK + +/* Define to 1 if the system has the type `_Bool'. */ +#undef HAVE__BOOL + +/* Define to 1 if you have the `_spawnl' function. */ +#undef HAVE__SPAWNL + +/* define if we should use program's load average function instead of system + */ +#undef LOADAV + +/* Define to file to use for scoreboard lockfile */ +#undef LOCKFILE + +/* Define to 1 if `lstat' dereferences a symlink specified with a trailing + slash. */ +#undef LSTAT_FOLLOWS_SLASHED_SYMLINK + +/* Define to include wizard mode */ +#undef MASTER + +/* Define if maxusers feature should be enabled */ +#undef MAXLOAD + +/* Define if maxusers feature should be enabled */ +#undef MAXUSERS + +/* kernel file to pass to nlist() when reading load average (unlikely to work) + */ +#undef NAMELIST + +/* word for the number of scores to store in scoreboard */ +#undef NUMNAME + +/* number of scores to store in scoreboard */ +#undef NUMSCORES + +/* Define to the address where bug reports for this package should be sent. */ +#undef PACKAGE_BUGREPORT + +/* Define to the full name of this package. */ +#undef PACKAGE_NAME + +/* Define to the full name and version of this package. */ +#undef PACKAGE_STRING + +/* Define to the one symbol short name of this package. */ +#undef PACKAGE_TARNAME + +/* Define to the version of this package. */ +#undef PACKAGE_VERSION + +/* Define crypt(3) wizard mode password */ +#undef PASSWD + +/* Define as the return type of signal handlers (`int' or `void'). */ +#undef RETSIGTYPE + +/* Define to file to use for scoreboard */ +#undef SCOREFILE + +/* Define to 1 if you have the ANSI C header files. */ +#undef STDC_HEADERS + +/* Define to 1 if your declares `struct tm'. */ +#undef TM_IN_SYS_TIME + +/* define if we should use program's user counting function instead of + system's */ +#undef UCOUNT + +/* utmp like file to pass to ucount() when counting online users (unlikely to + work) */ +#undef UTMP + +/* Define to empty if `const' does not conform to ANSI C. */ +#undef const + +/* Define to `int' if doesn't define. */ +#undef gid_t + +/* Define to `int' if does not define. */ +#undef pid_t + +/* Define to `unsigned int' if does not define. */ +#undef size_t + +/* Define to `int' if doesn't define. */ +#undef uid_t + +/* Define as `fork' if `vfork' does not work. */ +#undef vfork diff --git a/src/cc/rogue/config.sub b/src/cc/rogue/config.sub new file mode 100755 index 000000000..387c18d1a --- /dev/null +++ b/src/cc/rogue/config.sub @@ -0,0 +1,1608 @@ +#! /bin/sh +# Configuration validation subroutine script. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, +# Inc. + +timestamp='2006-07-02' + +# This file is (in principle) common to ALL GNU software. +# The presence of a machine in this file suggests that SOME GNU software +# can handle that machine. It does not imply ALL GNU software can. +# +# This file is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA +# 02110-1301, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + + +# Please send patches to . Submit a context +# diff and a properly formatted ChangeLog entry. +# +# Configuration subroutine to validate and canonicalize a configuration type. +# Supply the specified configuration type as an argument. +# If it is invalid, we print an error message on stderr and exit with code 1. +# Otherwise, we print the canonical config type on stdout and succeed. + +# This file is supposed to be the same for all GNU packages +# and recognize all the CPU types, system types and aliases +# that are meaningful with *any* GNU software. +# Each package is responsible for reporting which valid configurations +# it does not support. The user should be able to distinguish +# a failure to support a valid configuration from a meaningless +# configuration. + +# The goal of this file is to map all the various variations of a given +# machine specification into a single specification in the form: +# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM +# or in some cases, the newer four-part form: +# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM +# It is wrong to echo any other type of specification. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] CPU-MFR-OPSYS + $0 [OPTION] ALIAS + +Canonicalize a configuration name. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.sub ($timestamp) + +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" + exit 1 ;; + + *local*) + # First pass through any local machine types. + echo $1 + exit ;; + + * ) + break ;; + esac +done + +case $# in + 0) echo "$me: missing argument$help" >&2 + exit 1;; + 1) ;; + *) echo "$me: too many arguments$help" >&2 + exit 1;; +esac + +# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). +# Here we must recognize all the valid KERNEL-OS combinations. +maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` +case $maybe_os in + nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \ + uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \ + storm-chaos* | os2-emx* | rtmk-nova*) + os=-$maybe_os + basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` + ;; + *) + basic_machine=`echo $1 | sed 's/-[^-]*$//'` + if [ $basic_machine != $1 ] + then os=`echo $1 | sed 's/.*-/-/'` + else os=; fi + ;; +esac + +### Let's recognize common machines as not being operating systems so +### that things like config.sub decstation-3100 work. We also +### recognize some manufacturers as not being operating systems, so we +### can provide default operating systems below. +case $os in + -sun*os*) + # Prevent following clause from handling this invalid input. + ;; + -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ + -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ + -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ + -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ + -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ + -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ + -apple | -axis | -knuth | -cray) + os= + basic_machine=$1 + ;; + -sim | -cisco | -oki | -wec | -winbond) + os= + basic_machine=$1 + ;; + -scout) + ;; + -wrs) + os=-vxworks + basic_machine=$1 + ;; + -chorusos*) + os=-chorusos + basic_machine=$1 + ;; + -chorusrdb) + os=-chorusrdb + basic_machine=$1 + ;; + -hiux*) + os=-hiuxwe2 + ;; + -sco6) + os=-sco5v6 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco5) + os=-sco3.2v5 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco4) + os=-sco3.2v4 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2.[4-9]*) + os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2v[4-9]*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco5v6*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco*) + os=-sco3.2v2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -udk*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -isc) + os=-isc2.2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -clix*) + basic_machine=clipper-intergraph + ;; + -isc*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -lynx*) + os=-lynxos + ;; + -ptx*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` + ;; + -windowsnt*) + os=`echo $os | sed -e 's/windowsnt/winnt/'` + ;; + -psos*) + os=-psos + ;; + -mint | -mint[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; +esac + +# Decode aliases for certain CPU-COMPANY combinations. +case $basic_machine in + # Recognize the basic CPU types without company name. + # Some are omitted here because they have special meanings below. + 1750a | 580 \ + | a29k \ + | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ + | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ + | am33_2.0 \ + | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \ + | bfin \ + | c4x | clipper \ + | d10v | d30v | dlx | dsp16xx \ + | fr30 | frv \ + | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ + | i370 | i860 | i960 | ia64 \ + | ip2k | iq2000 \ + | m32c | m32r | m32rle | m68000 | m68k | m88k \ + | maxq | mb | microblaze | mcore \ + | mips | mipsbe | mipseb | mipsel | mipsle \ + | mips16 \ + | mips64 | mips64el \ + | mips64vr | mips64vrel \ + | mips64orion | mips64orionel \ + | mips64vr4100 | mips64vr4100el \ + | mips64vr4300 | mips64vr4300el \ + | mips64vr5000 | mips64vr5000el \ + | mips64vr5900 | mips64vr5900el \ + | mipsisa32 | mipsisa32el \ + | mipsisa32r2 | mipsisa32r2el \ + | mipsisa64 | mipsisa64el \ + | mipsisa64r2 | mipsisa64r2el \ + | mipsisa64sb1 | mipsisa64sb1el \ + | mipsisa64sr71k | mipsisa64sr71kel \ + | mipstx39 | mipstx39el \ + | mn10200 | mn10300 \ + | mt \ + | msp430 \ + | nios | nios2 \ + | ns16k | ns32k \ + | or32 \ + | pdp10 | pdp11 | pj | pjl \ + | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \ + | pyramid \ + | sh | sh[1234] | sh[24]a | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ + | sh64 | sh64le \ + | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ + | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ + | spu | strongarm \ + | tahoe | thumb | tic4x | tic80 | tron \ + | v850 | v850e \ + | we32k \ + | x86 | xscale | xscalee[bl] | xstormy16 | xtensa \ + | z8k) + basic_machine=$basic_machine-unknown + ;; + m6811 | m68hc11 | m6812 | m68hc12) + # Motorola 68HC11/12. + basic_machine=$basic_machine-unknown + os=-none + ;; + m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) + ;; + ms1) + basic_machine=mt-unknown + ;; + + # We use `pc' rather than `unknown' + # because (1) that's what they normally are, and + # (2) the word "unknown" tends to confuse beginning users. + i*86 | x86_64) + basic_machine=$basic_machine-pc + ;; + # Object if more than one company name word. + *-*-*) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; + # Recognize the basic CPU types with company name. + 580-* \ + | a29k-* \ + | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ + | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ + | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ + | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ + | avr-* | avr32-* \ + | bfin-* | bs2000-* \ + | c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \ + | clipper-* | craynv-* | cydra-* \ + | d10v-* | d30v-* | dlx-* \ + | elxsi-* \ + | f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \ + | h8300-* | h8500-* \ + | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ + | i*86-* | i860-* | i960-* | ia64-* \ + | ip2k-* | iq2000-* \ + | m32c-* | m32r-* | m32rle-* \ + | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ + | m88110-* | m88k-* | maxq-* | mcore-* \ + | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ + | mips16-* \ + | mips64-* | mips64el-* \ + | mips64vr-* | mips64vrel-* \ + | mips64orion-* | mips64orionel-* \ + | mips64vr4100-* | mips64vr4100el-* \ + | mips64vr4300-* | mips64vr4300el-* \ + | mips64vr5000-* | mips64vr5000el-* \ + | mips64vr5900-* | mips64vr5900el-* \ + | mipsisa32-* | mipsisa32el-* \ + | mipsisa32r2-* | mipsisa32r2el-* \ + | mipsisa64-* | mipsisa64el-* \ + | mipsisa64r2-* | mipsisa64r2el-* \ + | mipsisa64sb1-* | mipsisa64sb1el-* \ + | mipsisa64sr71k-* | mipsisa64sr71kel-* \ + | mipstx39-* | mipstx39el-* \ + | mmix-* \ + | mt-* \ + | msp430-* \ + | nios-* | nios2-* \ + | none-* | np1-* | ns16k-* | ns32k-* \ + | orion-* \ + | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ + | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \ + | pyramid-* \ + | romp-* | rs6000-* \ + | sh-* | sh[1234]-* | sh[24]a-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ + | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ + | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ + | sparclite-* \ + | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | strongarm-* | sv1-* | sx?-* \ + | tahoe-* | thumb-* \ + | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ + | tron-* \ + | v850-* | v850e-* | vax-* \ + | we32k-* \ + | x86-* | x86_64-* | xps100-* | xscale-* | xscalee[bl]-* \ + | xstormy16-* | xtensa-* \ + | ymp-* \ + | z8k-*) + ;; + # Recognize the various machine names and aliases which stand + # for a CPU type and a company and sometimes even an OS. + 386bsd) + basic_machine=i386-unknown + os=-bsd + ;; + 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) + basic_machine=m68000-att + ;; + 3b*) + basic_machine=we32k-att + ;; + a29khif) + basic_machine=a29k-amd + os=-udi + ;; + abacus) + basic_machine=abacus-unknown + ;; + adobe68k) + basic_machine=m68010-adobe + os=-scout + ;; + alliant | fx80) + basic_machine=fx80-alliant + ;; + altos | altos3068) + basic_machine=m68k-altos + ;; + am29k) + basic_machine=a29k-none + os=-bsd + ;; + amd64) + basic_machine=x86_64-pc + ;; + amd64-*) + basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + amdahl) + basic_machine=580-amdahl + os=-sysv + ;; + amiga | amiga-*) + basic_machine=m68k-unknown + ;; + amigaos | amigados) + basic_machine=m68k-unknown + os=-amigaos + ;; + amigaunix | amix) + basic_machine=m68k-unknown + os=-sysv4 + ;; + apollo68) + basic_machine=m68k-apollo + os=-sysv + ;; + apollo68bsd) + basic_machine=m68k-apollo + os=-bsd + ;; + aux) + basic_machine=m68k-apple + os=-aux + ;; + balance) + basic_machine=ns32k-sequent + os=-dynix + ;; + c90) + basic_machine=c90-cray + os=-unicos + ;; + convex-c1) + basic_machine=c1-convex + os=-bsd + ;; + convex-c2) + basic_machine=c2-convex + os=-bsd + ;; + convex-c32) + basic_machine=c32-convex + os=-bsd + ;; + convex-c34) + basic_machine=c34-convex + os=-bsd + ;; + convex-c38) + basic_machine=c38-convex + os=-bsd + ;; + cray | j90) + basic_machine=j90-cray + os=-unicos + ;; + craynv) + basic_machine=craynv-cray + os=-unicosmp + ;; + cr16c) + basic_machine=cr16c-unknown + os=-elf + ;; + crds | unos) + basic_machine=m68k-crds + ;; + crisv32 | crisv32-* | etraxfs*) + basic_machine=crisv32-axis + ;; + cris | cris-* | etrax*) + basic_machine=cris-axis + ;; + crx) + basic_machine=crx-unknown + os=-elf + ;; + da30 | da30-*) + basic_machine=m68k-da30 + ;; + decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) + basic_machine=mips-dec + ;; + decsystem10* | dec10*) + basic_machine=pdp10-dec + os=-tops10 + ;; + decsystem20* | dec20*) + basic_machine=pdp10-dec + os=-tops20 + ;; + delta | 3300 | motorola-3300 | motorola-delta \ + | 3300-motorola | delta-motorola) + basic_machine=m68k-motorola + ;; + delta88) + basic_machine=m88k-motorola + os=-sysv3 + ;; + djgpp) + basic_machine=i586-pc + os=-msdosdjgpp + ;; + dpx20 | dpx20-*) + basic_machine=rs6000-bull + os=-bosx + ;; + dpx2* | dpx2*-bull) + basic_machine=m68k-bull + os=-sysv3 + ;; + ebmon29k) + basic_machine=a29k-amd + os=-ebmon + ;; + elxsi) + basic_machine=elxsi-elxsi + os=-bsd + ;; + encore | umax | mmax) + basic_machine=ns32k-encore + ;; + es1800 | OSE68k | ose68k | ose | OSE) + basic_machine=m68k-ericsson + os=-ose + ;; + fx2800) + basic_machine=i860-alliant + ;; + genix) + basic_machine=ns32k-ns + ;; + gmicro) + basic_machine=tron-gmicro + os=-sysv + ;; + go32) + basic_machine=i386-pc + os=-go32 + ;; + h3050r* | hiux*) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + h8300hms) + basic_machine=h8300-hitachi + os=-hms + ;; + h8300xray) + basic_machine=h8300-hitachi + os=-xray + ;; + h8500hms) + basic_machine=h8500-hitachi + os=-hms + ;; + harris) + basic_machine=m88k-harris + os=-sysv3 + ;; + hp300-*) + basic_machine=m68k-hp + ;; + hp300bsd) + basic_machine=m68k-hp + os=-bsd + ;; + hp300hpux) + basic_machine=m68k-hp + os=-hpux + ;; + hp3k9[0-9][0-9] | hp9[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k2[0-9][0-9] | hp9k31[0-9]) + basic_machine=m68000-hp + ;; + hp9k3[2-9][0-9]) + basic_machine=m68k-hp + ;; + hp9k6[0-9][0-9] | hp6[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k7[0-79][0-9] | hp7[0-79][0-9]) + basic_machine=hppa1.1-hp + ;; + hp9k78[0-9] | hp78[0-9]) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][13679] | hp8[0-9][13679]) + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][0-9] | hp8[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hppa-next) + os=-nextstep3 + ;; + hppaosf) + basic_machine=hppa1.1-hp + os=-osf + ;; + hppro) + basic_machine=hppa1.1-hp + os=-proelf + ;; + i370-ibm* | ibm*) + basic_machine=i370-ibm + ;; +# I'm not sure what "Sysv32" means. Should this be sysv3.2? + i*86v32) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv32 + ;; + i*86v4*) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv4 + ;; + i*86v) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv + ;; + i*86sol2) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-solaris2 + ;; + i386mach) + basic_machine=i386-mach + os=-mach + ;; + i386-vsta | vsta) + basic_machine=i386-unknown + os=-vsta + ;; + iris | iris4d) + basic_machine=mips-sgi + case $os in + -irix*) + ;; + *) + os=-irix4 + ;; + esac + ;; + isi68 | isi) + basic_machine=m68k-isi + os=-sysv + ;; + m88k-omron*) + basic_machine=m88k-omron + ;; + magnum | m3230) + basic_machine=mips-mips + os=-sysv + ;; + merlin) + basic_machine=ns32k-utek + os=-sysv + ;; + mingw32) + basic_machine=i386-pc + os=-mingw32 + ;; + miniframe) + basic_machine=m68000-convergent + ;; + *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; + mips3*-*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` + ;; + mips3*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown + ;; + monitor) + basic_machine=m68k-rom68k + os=-coff + ;; + morphos) + basic_machine=powerpc-unknown + os=-morphos + ;; + msdos) + basic_machine=i386-pc + os=-msdos + ;; + ms1-*) + basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` + ;; + mvs) + basic_machine=i370-ibm + os=-mvs + ;; + ncr3000) + basic_machine=i486-ncr + os=-sysv4 + ;; + netbsd386) + basic_machine=i386-unknown + os=-netbsd + ;; + netwinder) + basic_machine=armv4l-rebel + os=-linux + ;; + news | news700 | news800 | news900) + basic_machine=m68k-sony + os=-newsos + ;; + news1000) + basic_machine=m68030-sony + os=-newsos + ;; + news-3600 | risc-news) + basic_machine=mips-sony + os=-newsos + ;; + necv70) + basic_machine=v70-nec + os=-sysv + ;; + next | m*-next ) + basic_machine=m68k-next + case $os in + -nextstep* ) + ;; + -ns2*) + os=-nextstep2 + ;; + *) + os=-nextstep3 + ;; + esac + ;; + nh3000) + basic_machine=m68k-harris + os=-cxux + ;; + nh[45]000) + basic_machine=m88k-harris + os=-cxux + ;; + nindy960) + basic_machine=i960-intel + os=-nindy + ;; + mon960) + basic_machine=i960-intel + os=-mon960 + ;; + nonstopux) + basic_machine=mips-compaq + os=-nonstopux + ;; + np1) + basic_machine=np1-gould + ;; + nsr-tandem) + basic_machine=nsr-tandem + ;; + op50n-* | op60c-*) + basic_machine=hppa1.1-oki + os=-proelf + ;; + openrisc | openrisc-*) + basic_machine=or32-unknown + ;; + os400) + basic_machine=powerpc-ibm + os=-os400 + ;; + OSE68000 | ose68000) + basic_machine=m68000-ericsson + os=-ose + ;; + os68k) + basic_machine=m68k-none + os=-os68k + ;; + pa-hitachi) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + paragon) + basic_machine=i860-intel + os=-osf + ;; + pbd) + basic_machine=sparc-tti + ;; + pbb) + basic_machine=m68k-tti + ;; + pc532 | pc532-*) + basic_machine=ns32k-pc532 + ;; + pc98) + basic_machine=i386-pc + ;; + pc98-*) + basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium | p5 | k5 | k6 | nexgen | viac3) + basic_machine=i586-pc + ;; + pentiumpro | p6 | 6x86 | athlon | athlon_*) + basic_machine=i686-pc + ;; + pentiumii | pentium2 | pentiumiii | pentium3) + basic_machine=i686-pc + ;; + pentium4) + basic_machine=i786-pc + ;; + pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) + basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumpro-* | p6-* | 6x86-* | athlon-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium4-*) + basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pn) + basic_machine=pn-gould + ;; + power) basic_machine=power-ibm + ;; + ppc) basic_machine=powerpc-unknown + ;; + ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppcle | powerpclittle | ppc-le | powerpc-little) + basic_machine=powerpcle-unknown + ;; + ppcle-* | powerpclittle-*) + basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64) basic_machine=powerpc64-unknown + ;; + ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64le | powerpc64little | ppc64-le | powerpc64-little) + basic_machine=powerpc64le-unknown + ;; + ppc64le-* | powerpc64little-*) + basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ps2) + basic_machine=i386-ibm + ;; + pw32) + basic_machine=i586-unknown + os=-pw32 + ;; + rdos) + basic_machine=i386-pc + os=-rdos + ;; + rom68k) + basic_machine=m68k-rom68k + os=-coff + ;; + rm[46]00) + basic_machine=mips-siemens + ;; + rtpc | rtpc-*) + basic_machine=romp-ibm + ;; + s390 | s390-*) + basic_machine=s390-ibm + ;; + s390x | s390x-*) + basic_machine=s390x-ibm + ;; + sa29200) + basic_machine=a29k-amd + os=-udi + ;; + sb1) + basic_machine=mipsisa64sb1-unknown + ;; + sb1el) + basic_machine=mipsisa64sb1el-unknown + ;; + sei) + basic_machine=mips-sei + os=-seiux + ;; + sequent) + basic_machine=i386-sequent + ;; + sh) + basic_machine=sh-hitachi + os=-hms + ;; + sh64) + basic_machine=sh64-unknown + ;; + sparclite-wrs | simso-wrs) + basic_machine=sparclite-wrs + os=-vxworks + ;; + sps7) + basic_machine=m68k-bull + os=-sysv2 + ;; + spur) + basic_machine=spur-unknown + ;; + st2000) + basic_machine=m68k-tandem + ;; + stratus) + basic_machine=i860-stratus + os=-sysv4 + ;; + sun2) + basic_machine=m68000-sun + ;; + sun2os3) + basic_machine=m68000-sun + os=-sunos3 + ;; + sun2os4) + basic_machine=m68000-sun + os=-sunos4 + ;; + sun3os3) + basic_machine=m68k-sun + os=-sunos3 + ;; + sun3os4) + basic_machine=m68k-sun + os=-sunos4 + ;; + sun4os3) + basic_machine=sparc-sun + os=-sunos3 + ;; + sun4os4) + basic_machine=sparc-sun + os=-sunos4 + ;; + sun4sol2) + basic_machine=sparc-sun + os=-solaris2 + ;; + sun3 | sun3-*) + basic_machine=m68k-sun + ;; + sun4) + basic_machine=sparc-sun + ;; + sun386 | sun386i | roadrunner) + basic_machine=i386-sun + ;; + sv1) + basic_machine=sv1-cray + os=-unicos + ;; + symmetry) + basic_machine=i386-sequent + os=-dynix + ;; + t3e) + basic_machine=alphaev5-cray + os=-unicos + ;; + t90) + basic_machine=t90-cray + os=-unicos + ;; + tic54x | c54x*) + basic_machine=tic54x-unknown + os=-coff + ;; + tic55x | c55x*) + basic_machine=tic55x-unknown + os=-coff + ;; + tic6x | c6x*) + basic_machine=tic6x-unknown + os=-coff + ;; + tx39) + basic_machine=mipstx39-unknown + ;; + tx39el) + basic_machine=mipstx39el-unknown + ;; + toad1) + basic_machine=pdp10-xkl + os=-tops20 + ;; + tower | tower-32) + basic_machine=m68k-ncr + ;; + tpf) + basic_machine=s390x-ibm + os=-tpf + ;; + udi29k) + basic_machine=a29k-amd + os=-udi + ;; + ultra3) + basic_machine=a29k-nyu + os=-sym1 + ;; + v810 | necv810) + basic_machine=v810-nec + os=-none + ;; + vaxv) + basic_machine=vax-dec + os=-sysv + ;; + vms) + basic_machine=vax-dec + os=-vms + ;; + vpp*|vx|vx-*) + basic_machine=f301-fujitsu + ;; + vxworks960) + basic_machine=i960-wrs + os=-vxworks + ;; + vxworks68) + basic_machine=m68k-wrs + os=-vxworks + ;; + vxworks29k) + basic_machine=a29k-wrs + os=-vxworks + ;; + w65*) + basic_machine=w65-wdc + os=-none + ;; + w89k-*) + basic_machine=hppa1.1-winbond + os=-proelf + ;; + xbox) + basic_machine=i686-pc + os=-mingw32 + ;; + xps | xps100) + basic_machine=xps100-honeywell + ;; + ymp) + basic_machine=ymp-cray + os=-unicos + ;; + z8k-*-coff) + basic_machine=z8k-unknown + os=-sim + ;; + none) + basic_machine=none-none + os=-none + ;; + +# Here we handle the default manufacturer of certain CPU types. It is in +# some cases the only manufacturer, in others, it is the most popular. + w89k) + basic_machine=hppa1.1-winbond + ;; + op50n) + basic_machine=hppa1.1-oki + ;; + op60c) + basic_machine=hppa1.1-oki + ;; + romp) + basic_machine=romp-ibm + ;; + mmix) + basic_machine=mmix-knuth + ;; + rs6000) + basic_machine=rs6000-ibm + ;; + vax) + basic_machine=vax-dec + ;; + pdp10) + # there are many clones, so DEC is not a safe bet + basic_machine=pdp10-unknown + ;; + pdp11) + basic_machine=pdp11-dec + ;; + we32k) + basic_machine=we32k-att + ;; + sh[1234] | sh[24]a | sh[34]eb | sh[1234]le | sh[23]ele) + basic_machine=sh-unknown + ;; + sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) + basic_machine=sparc-sun + ;; + cydra) + basic_machine=cydra-cydrome + ;; + orion) + basic_machine=orion-highlevel + ;; + orion105) + basic_machine=clipper-highlevel + ;; + mac | mpw | mac-mpw) + basic_machine=m68k-apple + ;; + pmac | pmac-mpw) + basic_machine=powerpc-apple + ;; + *-unknown) + # Make sure to match an already-canonicalized machine name. + ;; + *) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; +esac + +# Here we canonicalize certain aliases for manufacturers. +case $basic_machine in + *-digital*) + basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` + ;; + *-commodore*) + basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` + ;; + *) + ;; +esac + +# Decode manufacturer-specific aliases for certain operating systems. + +if [ x"$os" != x"" ] +then +case $os in + # First match some system type aliases + # that might get confused with valid system types. + # -solaris* is a basic system type, with this one exception. + -solaris1 | -solaris1.*) + os=`echo $os | sed -e 's|solaris1|sunos4|'` + ;; + -solaris) + os=-solaris2 + ;; + -svr4*) + os=-sysv4 + ;; + -unixware*) + os=-sysv4.2uw + ;; + -gnu/linux*) + os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` + ;; + # First accept the basic system types. + # The portable systems comes first. + # Each alternative MUST END IN A *, to match a version number. + # -sysv* is not here because it comes later, after sysvr4. + -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ + | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\ + | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \ + | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ + | -aos* \ + | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ + | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ + | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ + | -openbsd* | -solidbsd* \ + | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ + | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ + | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ + | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ + | -chorusos* | -chorusrdb* \ + | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ + | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \ + | -uxpv* | -beos* | -mpeix* | -udk* \ + | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ + | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ + | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ + | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ + | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ + | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ + | -skyos* | -haiku* | -rdos* | -toppers*) + # Remember, each alternative MUST END IN *, to match a version number. + ;; + -qnx*) + case $basic_machine in + x86-* | i*86-*) + ;; + *) + os=-nto$os + ;; + esac + ;; + -nto-qnx*) + ;; + -nto*) + os=`echo $os | sed -e 's|nto|nto-qnx|'` + ;; + -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ + | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ + | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) + ;; + -mac*) + os=`echo $os | sed -e 's|mac|macos|'` + ;; + -linux-dietlibc) + os=-linux-dietlibc + ;; + -linux*) + os=`echo $os | sed -e 's|linux|linux-gnu|'` + ;; + -sunos5*) + os=`echo $os | sed -e 's|sunos5|solaris2|'` + ;; + -sunos6*) + os=`echo $os | sed -e 's|sunos6|solaris3|'` + ;; + -opened*) + os=-openedition + ;; + -os400*) + os=-os400 + ;; + -wince*) + os=-wince + ;; + -osfrose*) + os=-osfrose + ;; + -osf*) + os=-osf + ;; + -utek*) + os=-bsd + ;; + -dynix*) + os=-bsd + ;; + -acis*) + os=-aos + ;; + -atheos*) + os=-atheos + ;; + -syllable*) + os=-syllable + ;; + -386bsd) + os=-bsd + ;; + -ctix* | -uts*) + os=-sysv + ;; + -nova*) + os=-rtmk-nova + ;; + -ns2 ) + os=-nextstep2 + ;; + -nsk*) + os=-nsk + ;; + # Preserve the version number of sinix5. + -sinix5.*) + os=`echo $os | sed -e 's|sinix|sysv|'` + ;; + -sinix*) + os=-sysv4 + ;; + -tpf*) + os=-tpf + ;; + -triton*) + os=-sysv3 + ;; + -oss*) + os=-sysv3 + ;; + -svr4) + os=-sysv4 + ;; + -svr3) + os=-sysv3 + ;; + -sysvr4) + os=-sysv4 + ;; + # This must come after -sysvr4. + -sysv*) + ;; + -ose*) + os=-ose + ;; + -es1800*) + os=-ose + ;; + -xenix) + os=-xenix + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + os=-mint + ;; + -aros*) + os=-aros + ;; + -kaos*) + os=-kaos + ;; + -zvmoe) + os=-zvmoe + ;; + -none) + ;; + *) + # Get rid of the `-' at the beginning of $os. + os=`echo $os | sed 's/[^-]*-//'` + echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 + exit 1 + ;; +esac +else + +# Here we handle the default operating systems that come with various machines. +# The value should be what the vendor currently ships out the door with their +# machine or put another way, the most popular os provided with the machine. + +# Note that if you're going to try to match "-MANUFACTURER" here (say, +# "-sun"), then you have to tell the case statement up towards the top +# that MANUFACTURER isn't an operating system. Otherwise, code above +# will signal an error saying that MANUFACTURER isn't an operating +# system, and we'll never get to this point. + +case $basic_machine in + spu-*) + os=-elf + ;; + *-acorn) + os=-riscix1.2 + ;; + arm*-rebel) + os=-linux + ;; + arm*-semi) + os=-aout + ;; + c4x-* | tic4x-*) + os=-coff + ;; + # This must come before the *-dec entry. + pdp10-*) + os=-tops20 + ;; + pdp11-*) + os=-none + ;; + *-dec | vax-*) + os=-ultrix4.2 + ;; + m68*-apollo) + os=-domain + ;; + i386-sun) + os=-sunos4.0.2 + ;; + m68000-sun) + os=-sunos3 + # This also exists in the configure program, but was not the + # default. + # os=-sunos4 + ;; + m68*-cisco) + os=-aout + ;; + mips*-cisco) + os=-elf + ;; + mips*-*) + os=-elf + ;; + or32-*) + os=-coff + ;; + *-tti) # must be before sparc entry or we get the wrong os. + os=-sysv3 + ;; + sparc-* | *-sun) + os=-sunos4.1.1 + ;; + *-be) + os=-beos + ;; + *-haiku) + os=-haiku + ;; + *-ibm) + os=-aix + ;; + *-knuth) + os=-mmixware + ;; + *-wec) + os=-proelf + ;; + *-winbond) + os=-proelf + ;; + *-oki) + os=-proelf + ;; + *-hp) + os=-hpux + ;; + *-hitachi) + os=-hiux + ;; + i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) + os=-sysv + ;; + *-cbm) + os=-amigaos + ;; + *-dg) + os=-dgux + ;; + *-dolphin) + os=-sysv3 + ;; + m68k-ccur) + os=-rtu + ;; + m88k-omron*) + os=-luna + ;; + *-next ) + os=-nextstep + ;; + *-sequent) + os=-ptx + ;; + *-crds) + os=-unos + ;; + *-ns) + os=-genix + ;; + i370-*) + os=-mvs + ;; + *-next) + os=-nextstep3 + ;; + *-gould) + os=-sysv + ;; + *-highlevel) + os=-bsd + ;; + *-encore) + os=-bsd + ;; + *-sgi) + os=-irix + ;; + *-siemens) + os=-sysv4 + ;; + *-masscomp) + os=-rtu + ;; + f30[01]-fujitsu | f700-fujitsu) + os=-uxpv + ;; + *-rom68k) + os=-coff + ;; + *-*bug) + os=-coff + ;; + *-apple) + os=-macos + ;; + *-atari*) + os=-mint + ;; + *) + os=-none + ;; +esac +fi + +# Here we handle the case where we know the os, and the CPU type, but not the +# manufacturer. We pick the logical manufacturer. +vendor=unknown +case $basic_machine in + *-unknown) + case $os in + -riscix*) + vendor=acorn + ;; + -sunos*) + vendor=sun + ;; + -aix*) + vendor=ibm + ;; + -beos*) + vendor=be + ;; + -hpux*) + vendor=hp + ;; + -mpeix*) + vendor=hp + ;; + -hiux*) + vendor=hitachi + ;; + -unos*) + vendor=crds + ;; + -dgux*) + vendor=dg + ;; + -luna*) + vendor=omron + ;; + -genix*) + vendor=ns + ;; + -mvs* | -opened*) + vendor=ibm + ;; + -os400*) + vendor=ibm + ;; + -ptx*) + vendor=sequent + ;; + -tpf*) + vendor=ibm + ;; + -vxsim* | -vxworks* | -windiss*) + vendor=wrs + ;; + -aux*) + vendor=apple + ;; + -hms*) + vendor=hitachi + ;; + -mpw* | -macos*) + vendor=apple + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + vendor=atari + ;; + -vos*) + vendor=stratus + ;; + esac + basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` + ;; +esac + +echo $basic_machine$os +exit + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/src/cc/rogue/configure.ac b/src/cc/rogue/configure.ac new file mode 100644 index 000000000..15c9cc7e4 --- /dev/null +++ b/src/cc/rogue/configure.ac @@ -0,0 +1,246 @@ +# -*- Autoconf -*- +# Process this file with autoconf to produce a configure script. + +AC_PREREQ(2.56) +AC_INIT([Rogue],[5.4.4], [yendor@rogueforge.net]) +AC_CONFIG_SRCDIR([armor.c]) +AC_CONFIG_HEADER([config.h]) +AC_CONFIG_FILES([Makefile rogue.6 rogue.cat rogue.doc rogue.html rogue.me]) +AC_CANONICAL_SYSTEM([]) + +# Checks for programs. +AC_PROG_CC + +# Checks for libraries. + +# Checks for header files. +AC_HEADER_STDC +AC_CHECK_HEADERS([arpa/inet.h sys/utsname.h pwd.h fcntl.h limits.h nlist.h stdlib.h string.h sys/ioctl.h termios.h unistd.h utmp.h term.h ncurses/term.h process.h]) + +# Checks for typedefs, structures, and compiler characteristics. +AC_HEADER_STDBOOL +AC_C_CONST +AC_TYPE_UID_T +AC_TYPE_SIZE_T +AC_STRUCT_TM +MP_WITH_CURSES +# Checks for library functions. +AC_FUNC_FORK +AC_PROG_GCC_TRADITIONAL +AC_FUNC_LSTAT +AC_FUNC_LSTAT_FOLLOWS_SLASHED_SYMLINK +AC_TYPE_SIGNAL +AC_FUNC_STAT +AC_FUNC_VPRINTF +AC_CHECK_FUNCS([erasechar killchar alarm getpass memset setenv strchr nlist _spawnl spawnl getpwuid loadav getloadavg strerror setresgid setregid setgid setresuid setreuid setuid getuid getgid]) + +AC_CHECK_PROG([NROFF], [nroff], [nroff],) +AC_CHECK_PROG([GROFF], [groff], [groff],) +AC_CHECK_PROG([COLCRT], [colcrt], [colcrt],) +AC_CHECK_PROG([TBL], [tbl], [tbl],) +AC_CHECK_PROG([SED], [sed], [sed],) + +AC_ARG_WITH(program-name, AC_HELP_STRING([--with-program-name=NAME],[alternate executable name]),[progname="$withval" ], [progname="rogue"] ) +PROGRAM=$progname +AC_SUBST(PROGRAM) + +AC_ARG_ENABLE(setgid, AC_HELP_STRING([--enable-setgid=NAME],[install executable as setgid with group ownership of NAME @<:@default=no@:>@])],[],[]) +AC_MSG_CHECKING([if using setgid execute bit]) +if test "x$enable_setgid" = "xno" ; then +GROUPOWNER= +elif test "x$enable_setgid" = "xyes" ; then +GROUPOWNER=games +elif test "x$enable_setgid" = "x" ; then +GROUPOWNER= +else +GROUPOWNER=$enable_setgid +fi + +if test "x$GROUPOWNER" != "x" ; then +AC_DEFINE_UNQUOTED([GROUPOWNER],[$GROUPOWNER], [Define to group owner of setgid executable]) +AC_MSG_RESULT([$GROUPOWNER]) +else +AC_MSG_RESULT([no]) +fi + +AC_SUBST(GROUPOWNER) + +AC_ARG_ENABLE([scorefile],[AC_HELP_STRING([--enable-scorefile=SCOREFILE], [enable scoreboard with given filename])],[],[]) +AC_MSG_CHECKING([for scoreboard file]) +if test "x$enable_scorefile" = "xno" ; then +SCOREFILE= +elif test "x$enable_scorefile" = "xyes" ; then +SCOREFILE=$progname.scr +elif test "x$enable_scorefile" = "x" ; then +SCOREFILE=$progname.scr +else +SCOREFILE=$enable_scorefile +fi + +if test "x$SCOREFILE" != "x" ; then +AC_DEFINE_UNQUOTED([SCOREFILE], ["$SCOREFILE"], [Define to file to use for scoreboard]) +AC_MSG_RESULT([$SCOREFILE]) +else +AC_MSG_RESULT([disabled]) +fi + +AC_SUBST(SCOREFILE) + +AC_ARG_ENABLE([lockfile],[AC_HELP_STRING([--enable-lockfile=LOCKFILE], [enable scoreboard lockfile with given filename])],[],[]) +AC_MSG_CHECKING([for scoreboard lockfile file]) +if test "x$enable_lockfile" = "xno" ; then +LOCKFILE= +elif test "x$enable_lockfile" = "xyes" ; then +LOCKFILE=$progname.lck +elif test "x$enable_lockfile" = "x" ; then +LOCKFILE=$progname.lck +else +LOCKFILE=$enable_lockfile +fi + +if test "x$LOCKFILE" != "x" ; then +AC_DEFINE_UNQUOTED([LOCKFILE], ["$LOCKFILE"], [Define to file to use for scoreboard lockfile]) +AC_MSG_RESULT([$LOCKFILE]) +else +AC_MSG_RESULT([disabled]) +fi + +AC_SUBST(LOCKFILE) + +AC_ARG_ENABLE([wizardmode],[AC_HELP_STRING([--enable-wizardmode], [enable availability of wizard mode @<:@default=no@:>@])],[],[]) +AC_MSG_CHECKING([if wizard mode is enabled]) +if test "x$enable_wizardmode" = "xno" ; then +AC_MSG_RESULT([no]) +elif test "x$enable_wizardmode" = "x" ; then +AC_MSG_RESULT([no]) +else +AC_DEFINE([MASTER], [], [Define to include wizard mode]) +if test "x$enable_wizardmode" != "xyes" ; then +AC_DEFINE_UNQUOTED([PASSWD],[$enable_wizardmode], [Define crypt(3) wizard mode password]) +fi +AC_MSG_RESULT([yes]) +fi + +AC_ARG_ENABLE([allscores],[AC_HELP_STRING([--enable-allscores], [enable scoreboard to show top scores, not just top players @<:@default=yes@:>@])],[],[enable_allscores=yes]) +AC_MSG_CHECKING([if allscores is enabled]) +if test "x$enable_allscores" = "xyes" ; then +AC_DEFINE([ALLSCORES], [1], [Define if scorefile is top scores, not top players]) +AC_MSG_RESULT([yes]) +else +AC_MSG_RESULT([no]) +fi + +AC_ARG_ENABLE([checktime],[AC_HELP_STRING([--enable-checktime], [enable checktime @<:@default=no@:>@])],[],[]) +AC_MSG_CHECKING([if checktime is enabled]) +if test "x$enable_checktime" = "xyes" ; then +AC_DEFINE([CHECKTIME], [1], [Define if checktime feature should be enabled]) +AC_MSG_RESULT([yes]) +else +AC_MSG_RESULT([no]) +fi + +AC_ARG_ENABLE([maxload],[AC_HELP_STRING([--enable-maxload], [enable maxload @<:@default=no@:>@])],[],[]) +AC_MSG_CHECKING([runtime execution limit (maximum system load average)]) +if test "x$enable_maxload" = "xyes" ; then +AC_DEFINE([MAXLOAD], [100], [Define if maxload feature should be enabled]) +AC_MSG_RESULT([100]) +elif test "x$enable_maxload" = "x" ; then +AC_MSG_RESULT([unlimited]) +elif test "x$enable_maxload" = "xno" ; then +AC_MSG_RESULT([unlimited]) +else +AC_DEFINE_UNQUOTED([MAXLOAD], [$enable_maxload], [Define if maxload feature should be enabled]) +AC_MSG_RESULT([$enable_maxload]) +fi + +AC_ARG_ENABLE([maxusers],[AC_HELP_STRING([--enable-maxusers], [enable maxuser @<:@default=no@:>@])],[],[]) +AC_MSG_CHECKING([runtime execution limit (maximum online system users)]) +if test "x$enable_maxusers" = "xyes" ; then +AC_DEFINE([MAXUSERS], [100], [Define if maxusers feature should be enabled]) +AC_MSG_RESULT([100]) +elif test "x$enable_maxusers" = "x" ; then +AC_MSG_RESULT([unlimited]) +elif test "x$enable_maxload" = "xno" ; then +AC_MSG_RESULT([unlimited]) +else +AC_DEFINE_UNQUOTED([MAXLOAD], [$enable_maxusers], [Define if maxusers feature should be enabled]) +AC_MSG_RESULT([$enable_maxusers]) +fi + +AC_ARG_ENABLE([numscores],[AC_HELP_STRING([--enable-numscores], [number of scores to store in scoreboard @<:@default=10@:>@])],[],[]) +AC_MSG_CHECKING([what the number of scores to store in scoreboard is]) +if test "x$numscores" = "xyes" ; then +AC_DEFINE([NUMSCORES], [10], [number of scores to store in scoreboard]) +AC_MSG_RESULT([10]) +elif test "x$enable_numscores" = "x" ; then +AC_DEFINE([NUMSCORES], [10], [number of scores to store in scoreboard]) +AC_MSG_RESULT([10]) +elif test "x$enable_numscores" = "xno" ; then +AC_DEFINE([NUMSCORES], [10], [number of scores to store in scoreboard]) +AC_MSG_RESULT([10]) +else +AC_DEFINE_UNQUOTED([NUMSCORES], [$enable_numscores], [number of scores to store in scoreboard]) +AC_MSG_RESULT([$enable_numscores]) +fi + +AC_ARG_ENABLE([numname],[AC_HELP_STRING([--enable-numname], [word for number of scores to store in scoreboard @<:@default=Ten@:>@])],[],[]) +AC_MSG_CHECKING([word for the number of scores to store in scoreboard is]) +if test "x$enable_numname" = "xyes" ; then +AC_DEFINE([NUMNAME], ["Ten"], [word for the number of scores to store in scoreboard]) +AC_MSG_RESULT([Ten]) +elif test "x$enable_numname" = "x" ; then +AC_DEFINE([NUMNAME], ["Ten"], [word for the number of scores to store in scoreboard]) +AC_MSG_RESULT([Ten]) +elif test "x$enable_numname" = "xno" ; then +AC_DEFINE([NUMNAME], ["Ten"], [word for the number of scores to store in scoreboard]) +AC_MSG_RESULT([Ten]) +else +AC_DEFINE_UNQUOTED([NUMNAME], ["$enable_numname"], [word for the number of scores to store in scoreboard]) +AC_MSG_RESULT([$enable_numname]) +fi + +AC_ARG_ENABLE([loadav],[AC_HELP_STRING([--enable-loadav=NAMELIST], [use program's load average function (unlikely to work) @<:@default=no@:>@])],[],[]) +AC_MSG_CHECKING([whether to use program's built in load average function]) +if test "x$enable_loadav" = "xyes" ; then +AC_DEFINE([LOADAV], [], [define if we should use program's load average function instead of system]) +AC_DEFINE([NAMELIST], [/vmunix], [kernel file to pass to nlist() when reading load average (unlikely to work)]) +AC_MSG_RESULT([/vmunix]) +elif test "x$enable_loadav" = "x" ; then +AC_MSG_RESULT([no]) +elif test "x$enable_loadav" = "xno" ; then +AC_MSG_RESULT([no]) +else +AC_DEFINE([LOADAV], [], [define if we should use program's load average function instead of system]) +AC_DEFINE_UNQUOTED([NAMELIST], [$enable_loadav], [kernel file to pass to nlist() when reading load average (unlikely to work)]) +AC_MSG_RESULT([$enable_loadav]) +fi + +AC_ARG_ENABLE([ucount],[AC_HELP_STRING([--enable-ucount=UTMPFILE], [use program's own function to count users (unlikely to work) @<:@default=no@:>@])],[],[]) +AC_MSG_CHECKING([whether to use program's built in user counting function]) +if test "x$enable_ucount" = "xyes" ; then +AC_DEFINE([UCOUNT], [], [define if we should use program's user counting function instead of system's]) +AC_DEFINE([UTMP], [/etc/utmp], [utmp like file to pass to ucount() when counting online users (unlikely to work)]) +AC_MSG_RESULT([/etc/utmp]) +elif test "x$enable_ucount" = "x" ; then +AC_MSG_RESULT([no]) +elif test "x$enable_count" = "xno" ; then +AC_MSG_RESULT([no]) +else +AC_DEFINE([UCOUNT], [], [define if we should use program's user counting function instead of system's]) +AC_DEFINE_UNQUOTED([UTMP], [$enable_ucount], [utmp like file to pass to ucount() when counting online users (unlikely to work)]) +AC_MSG_RESULT([$enable_ucount]) +fi + +TARGET=$target +AC_SUBST(TARGET) + +AC_MSG_CHECKING([whether to docdir is defined]) +if test "x$docdir" = "x" ; then +AC_MSG_RESULT([docdir undefined]) +docdir=\${datadir}/doc/\${PACKAGE_TARNAME} +AC_SUBST(docdir) +else +AC_MSG_RESULT([docdir defined]) +fi + +AC_OUTPUT diff --git a/src/cc/rogue/daemon.c b/src/cc/rogue/daemon.c new file mode 100644 index 000000000..8309dc642 --- /dev/null +++ b/src/cc/rogue/daemon.c @@ -0,0 +1,181 @@ +/* + * Contains functions for dealing with things that happen in the + * future. + * + * @(#)daemon.c 4.7 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include "rogue.h" + +#define EMPTY 0 +#define DAEMON -1 +#define MAXDAEMONS 20 + +#define _X_ { EMPTY } + +struct delayed_action d_list[MAXDAEMONS] = { + _X_, _X_, _X_, _X_, _X_, _X_, _X_, _X_, _X_, _X_, + _X_, _X_, _X_, _X_, _X_, _X_, _X_, _X_, _X_, _X_, +}; + +/* + * d_slot: + * Find an empty slot in the daemon/fuse list + */ +struct delayed_action * +d_slot() +{ + register struct delayed_action *dev; + + for (dev = d_list; dev <= &d_list[MAXDAEMONS-1]; dev++) + if (dev->d_type == EMPTY) + return dev; +#ifdef MASTER + debug("Ran out of fuse slots"); +#endif + return NULL; +} + +/* + * find_slot: + * Find a particular slot in the table + */ +struct delayed_action * +find_slot(void (*func)(struct rogue_state *rs,int)) +{ + register struct delayed_action *dev; + + for (dev = d_list; dev <= &d_list[MAXDAEMONS-1]; dev++) + if (dev->d_type != EMPTY && func == dev->d_func) + return dev; + return NULL; +} + +/* + * start_daemon: + * Start a daemon, takes a function. + */ +void +start_daemon(void (*func)(struct rogue_state *rs,int), int arg, int type) +{ + register struct delayed_action *dev; + + dev = d_slot(); + dev->d_type = type; + dev->d_func = func; + dev->d_arg = arg; + dev->d_time = DAEMON; +} + +/* + * kill_daemon: + * Remove a daemon from the list + */ +void +kill_daemon(void (*func)(struct rogue_state *rs,int)) +{ + register struct delayed_action *dev; + + if ((dev = find_slot(func)) == NULL) + return; + /* + * Take it out of the list + */ + dev->d_type = EMPTY; +} + +/* + * do_daemons: + * Run all the daemons that are active with the current flag, + * passing the argument to the function. + */ +void +do_daemons(struct rogue_state *rs,int flag) +{ + register struct delayed_action *dev; + + /* + * Loop through the devil list + */ + for (dev = d_list; dev <= &d_list[MAXDAEMONS-1]; dev++) + /* + * Executing each one, giving it the proper arguments + */ + if (dev->d_type == flag && dev->d_time == DAEMON) + (*dev->d_func)(rs,dev->d_arg); +} + +/* + * fuse: + * Start a fuse to go off in a certain number of turns + */ +void +fuse(void (*func)(struct rogue_state *rs,int), int arg, int time, int type) +{ + register struct delayed_action *wire; + + wire = d_slot(); + wire->d_type = type; + wire->d_func = func; + wire->d_arg = arg; + wire->d_time = time; +} + +/* + * lengthen: + * Increase the time until a fuse goes off + */ +void +lengthen(void (*func)(struct rogue_state *rs,int), int xtime) +{ + register struct delayed_action *wire; + + if ((wire = find_slot(func)) == NULL) + return; + wire->d_time += xtime; +} + +/* + * extinguish: + * Put out a fuse + */ +void +extinguish(void (*func)(struct rogue_state *rs,int)) +{ + register struct delayed_action *wire; + + if ((wire = find_slot(func)) == NULL) + return; + wire->d_type = EMPTY; +} + +/* + * do_fuses: + * Decrement counters and start needed fuses + */ +void +do_fuses(struct rogue_state *rs,int flag) +{ + register struct delayed_action *wire; + + /* + * Step though the list + */ + for (wire = d_list; wire <= &d_list[MAXDAEMONS-1]; wire++) + /* + * Decrementing counters and starting things we want. We also need + * to remove the fuse from the list once it has gone off. + */ + if (flag == wire->d_type && wire->d_time > 0 && --wire->d_time == 0) + { + wire->d_type = EMPTY; + (*wire->d_func)(rs,wire->d_arg); + } +} diff --git a/src/cc/rogue/daemons.c b/src/cc/rogue/daemons.c new file mode 100644 index 000000000..75d544cda --- /dev/null +++ b/src/cc/rogue/daemons.c @@ -0,0 +1,294 @@ +/* + * All the daemon and fuse functions are in here + * + * @(#)daemons.c 4.24 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include "rogue.h" + +/* + * doctor: + * A healing daemon that restors hit points after rest + */ +void +doctor(struct rogue_state *rs,int arg) +{ + register int lv, ohp; + + lv = pstats.s_lvl; + ohp = pstats.s_hpt; + quiet++; + if (lv < 8) + { + if (quiet + (lv << 1) > 20) + pstats.s_hpt++; + } + else + if (quiet >= 3) + pstats.s_hpt += rnd(lv - 7) + 1; + if (ISRING(LEFT, R_REGEN)) + pstats.s_hpt++; + if (ISRING(RIGHT, R_REGEN)) + pstats.s_hpt++; + if (ohp != pstats.s_hpt) + { + if (pstats.s_hpt > max_hp) + pstats.s_hpt = max_hp; + quiet = 0; + } +} + +/* + * Swander: + * Called when it is time to start rolling for wandering monsters + */ +void +swander(struct rogue_state *rs,int arg) +{ + start_daemon(rollwand, 0, BEFORE); +} + +/* + * rollwand: + * Called to roll to see if a wandering monster starts up + */ +int between = 0; +void +rollwand(struct rogue_state *rs,int arg) +{ + if (++between >= 4) + { + if (roll(1, 6) == 4) + { + wanderer(rs); + kill_daemon(rollwand); + fuse(swander, 0, WANDERTIME, BEFORE); + } + between = 0; + } +} + +/* + * unconfuse: + * Release the poor player from his confusion + */ +void +unconfuse(struct rogue_state *rs,int arg) +{ + player.t_flags &= ~ISHUH; + msg(rs,"you feel less %s now", choose_str("trippy", "confused")); +} + +/* + * unsee: + * Turn off the ability to see invisible + */ +void +unsee(struct rogue_state *rs,int arg) +{ + register THING *th; + + for (th = mlist; th != NULL; th = next(th)) + if (on(*th, ISINVIS) && see_monst(th)) + mvaddch(th->t_pos.y, th->t_pos.x, th->t_oldch); + player.t_flags &= ~CANSEE; +} + +/* + * sight: + * He gets his sight back + */ +void +sight(struct rogue_state *rs,int arg) +{ + if (on(player, ISBLIND)) + { + extinguish(sight); + player.t_flags &= ~ISBLIND; + if (!(proom->r_flags & ISGONE)) + enter_room(rs,&hero); + msg(rs,choose_str("far out! Everything is all cosmic again", + "the veil of darkness lifts")); + } +} + +/* + * nohaste: + * End the hasting + */ +void +nohaste(struct rogue_state *rs,int arg) +{ + player.t_flags &= ~ISHASTE; + msg(rs,"you feel yourself slowing down"); +} + +/* + * stomach: + * Digest the hero's food + */ +void +stomach(struct rogue_state *rs,int arg) +{ + register int oldfood; + int orig_hungry = hungry_state; + + if (food_left <= 0) + { + if (food_left-- < -STARVETIME) + death('s'); + /* + * the hero is fainting + */ + if (no_command || rnd(5) != 0) + return; + no_command += rnd(8) + 4; + hungry_state = 3; + if (!terse) + addmsg(rs,choose_str("the munchies overpower your motor capabilities. ", + "you feel too weak from lack of food. ")); + msg(rs,choose_str("You freak out", "You faint")); + } + else + { + oldfood = food_left; + food_left -= ring_eat(LEFT) + ring_eat(RIGHT) + 1 - amulet; + + if (food_left < MORETIME && oldfood >= MORETIME) + { + hungry_state = 2; + msg(rs,choose_str("the munchies are interfering with your motor capabilites", + "you are starting to feel weak")); + } + else if (food_left < 2 * MORETIME && oldfood >= 2 * MORETIME) + { + hungry_state = 1; + if (terse) + msg(rs,choose_str("getting the munchies", "getting hungry")); + else + msg(rs,choose_str("you are getting the munchies", + "you are starting to get hungry")); + } + } + if (hungry_state != orig_hungry) { + player.t_flags &= ~ISRUN; + running = FALSE; + to_death = FALSE; + count = 0; + } +} + +/* + * come_down: + * Take the hero down off her acid trip. + */ +void +come_down(struct rogue_state *rs,int arg) +{ + register THING *tp; + register bool seemonst; + + if (!on(player, ISHALU)) + return; + + kill_daemon(visuals); + player.t_flags &= ~ISHALU; + + if (on(player, ISBLIND)) + return; + + /* + * undo the things + */ + for (tp = lvl_obj; tp != NULL; tp = next(tp)) + if (cansee(rs,tp->o_pos.y, tp->o_pos.x)) + mvaddch(tp->o_pos.y, tp->o_pos.x, tp->o_type); + + /* + * undo the monsters + */ + seemonst = on(player, SEEMONST); + for (tp = mlist; tp != NULL; tp = next(tp)) + { + move(tp->t_pos.y, tp->t_pos.x); + if (cansee(rs,tp->t_pos.y, tp->t_pos.x)) + if (!on(*tp, ISINVIS) || on(player, CANSEE)) + addch(tp->t_disguise); + else + addch(chat(tp->t_pos.y, tp->t_pos.x)); + else if (seemonst) + { + standout(); + addch(tp->t_type); + standend(); + } + } + msg(rs,"Everything looks SO boring now."); +} + +/* + * visuals: + * change the characters for the player + */ +void +visuals(struct rogue_state *rs,int arg) +{ + register THING *tp; + register bool seemonst; + + if (!after || (running && jump)) + return; + /* + * change the things + */ + for (tp = lvl_obj; tp != NULL; tp = next(tp)) + if (cansee(rs,tp->o_pos.y, tp->o_pos.x)) + mvaddch(tp->o_pos.y, tp->o_pos.x, rnd_thing()); + + /* + * change the stairs + */ + if (!seenstairs && cansee(rs,stairs.y, stairs.x)) + mvaddch(stairs.y, stairs.x, rnd_thing()); + + /* + * change the monsters + */ + seemonst = on(player, SEEMONST); + for (tp = mlist; tp != NULL; tp = next(tp)) + { + move(tp->t_pos.y, tp->t_pos.x); + if (see_monst(tp)) + { + if (tp->t_type == 'X' && tp->t_disguise != 'X') + addch(rnd_thing()); + else + addch(rnd(26) + 'A'); + } + else if (seemonst) + { + standout(); + addch(rnd(26) + 'A'); + standend(); + } + } +} + +/* + * land: + * Land from a levitation potion + */ +void +land(struct rogue_state *rs,int arg) +{ + player.t_flags &= ~ISLEVIT; + msg(rs,choose_str("bummer! You've hit the ground", + "you float gently to the ground")); +} diff --git a/src/cc/rogue/extern.c b/src/cc/rogue/extern.c new file mode 100644 index 000000000..fb732dfde --- /dev/null +++ b/src/cc/rogue/extern.c @@ -0,0 +1,391 @@ +/* + * global variable initializaton + * + * @(#)extern.c 4.82 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include "rogue.h" + +bool after; /* True if we want after daemons */ +bool again; /* Repeating the last command */ +int noscore; /* Was a wizard sometime */ +bool seenstairs; /* Have seen the stairs (for lsd) */ +bool amulet = FALSE; /* He found the amulet */ +bool door_stop = FALSE; /* Stop running when we pass a door */ +bool fight_flush = FALSE; /* True if toilet input */ +bool firstmove = FALSE; /* First move after setting door_stop */ +bool got_ltc = FALSE; /* We have gotten the local tty chars */ +bool has_hit = FALSE; /* Has a "hit" message pending in msg */ +bool in_shell = FALSE; /* True if executing a shell */ +bool inv_describe = TRUE; /* Say which way items are being used */ +bool jump = FALSE; /* Show running as series of jumps */ +bool kamikaze = FALSE; /* to_death really to DEATH */ +bool lower_msg = FALSE; /* Messages should start w/lower case */ +bool move_on = FALSE; /* Next move shouldn't pick up items */ +bool msg_esc = FALSE; /* Check for ESC from msg's --More-- */ +bool passgo = FALSE; /* Follow passages */ +bool playing = TRUE; /* True until he quits */ +bool q_comm = FALSE; /* Are we executing a 'Q' command? */ +bool running = FALSE; /* True if player is running */ +bool save_msg = TRUE; /* Remember last msg */ +bool see_floor = TRUE; /* Show the lamp illuminated floor */ +bool stat_msg = FALSE; /* Should status() print as a msg() */ +bool terse = FALSE; /* True if we should be short */ +bool to_death = FALSE; /* Fighting is to the death! */ +bool tombstone = TRUE; /* Print out tombstone at end */ +#ifdef MASTER +int wizard = FALSE; /* True if allows wizard commands */ +#endif +bool pack_used[26] = { /* Is the character used in the pack? */ + FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, + FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, + FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE +}; + +char dir_ch; /* Direction from last get_dir() call */ +char file_name[MAXSTR]; /* Save file name */ +char huh[MAXSTR]; /* The last message printed */ +char *p_colors[MAXPOTIONS]; /* Colors of the potions */ +char prbuf[2*MAXSTR]; /* buffer for sprintfs */ +char *r_stones[MAXRINGS]; /* Stone settings of the rings */ +char runch; /* Direction player is running */ +char *s_names[MAXSCROLLS]; /* Names of the scrolls */ +char take; /* Thing she is taking */ +char whoami[MAXSTR]; /* Name of player */ +char *ws_made[MAXSTICKS]; /* What sticks are made of */ +char *ws_type[MAXSTICKS]; /* Is it a wand or a staff */ +int orig_dsusp; /* Original dsusp char */ +char fruit[MAXSTR] = /* Favorite fruit */ + { 's', 'l', 'i', 'm', 'e', '-', 'm', 'o', 'l', 'd', '\0' }; +char home[MAXSTR] = { '\0' }; /* User's home directory */ +char *inv_t_name[] = { + "Overwrite", + "Slow", + "Clear" +}; +char l_last_comm = '\0'; /* Last last_comm */ +char l_last_dir = '\0'; /* Last last_dir */ +char last_comm = '\0'; /* Last command typed */ +char last_dir = '\0'; /* Last direction given */ +char *tr_name[] = { /* Names of the traps */ + "a trapdoor", + "an arrow trap", + "a sleeping gas trap", + "a beartrap", + "a teleport trap", + "a poison dart trap", + "a rust trap", + "a mysterious trap" +}; + + +int n_objs; /* # items listed in inventory() call */ +int ntraps; /* Number of traps on this level */ +int hungry_state = 0; /* How hungry is he */ +int inpack = 0; /* Number of things in pack */ +int inv_type = 0; /* Type of inventory to use */ +int level = 1; /* What level she is on */ +int max_hit; /* Max damage done to her in to_death */ +int max_level; /* Deepest player has gone */ +int mpos = 0; /* Where cursor is on top line */ +int no_food = 0; /* Number of levels without food */ +int a_class[MAXARMORS] = { /* Armor class for each armor type */ + 8, /* LEATHER */ + 7, /* RING_MAIL */ + 7, /* STUDDED_LEATHER */ + 6, /* SCALE_MAIL */ + 5, /* CHAIN_MAIL */ + 4, /* SPLINT_MAIL */ + 4, /* BANDED_MAIL */ + 3, /* PLATE_MAIL */ +}; + +int count = 0; /* Number of times to repeat command */ +FILE *scoreboard = NULL; /* File descriptor for score file */ +int food_left; /* Amount of food in hero's stomach */ +int lastscore = -1; /* Score before this turn */ +int no_command = 0; /* Number of turns asleep */ +int no_move = 0; /* Number of turns held in place */ +int purse = 0; /* How much gold he has */ +int quiet = 0; /* Number of quiet turns */ +int vf_hit = 0; /* Number of time flytrap has hit */ + +int dnum; /* Dungeon number */ +uint64_t seed; /* Random number seed */ +int e_levels[] = { + 10L, + 20L, + 40L, + 80L, + 160L, + 320L, + 640L, + 1300L, + 2600L, + 5200L, + 13000L, + 26000L, + 50000L, + 100000L, + 200000L, + 400000L, + 800000L, + 2000000L, + 4000000L, + 8000000L, + 0L +}; + +coord delta; /* Change indicated to get_dir() */ +coord oldpos; /* Position before last look() call */ +coord stairs; /* Location of staircase */ + +PLACE places[MAXLINES*MAXCOLS]; /* level map */ + +THING *cur_armor; /* What he is wearing */ +THING *cur_ring[2]; /* Which rings are being worn */ +THING *cur_weapon; /* Which weapon he is weilding */ +THING *l_last_pick = NULL; /* Last last_pick */ +THING *last_pick = NULL; /* Last object picked in get_item() */ +THING *lvl_obj = NULL; /* List of objects on this level */ +THING *mlist = NULL; /* List of monsters on the level */ +THING player; /* His stats */ + /* restart of game */ + +WINDOW *hw = NULL; /* used as a scratch window */ + +#define INIT_STATS { 16, 0, 1, 10, 12, "1x4", 12 } + +struct stats max_stats = INIT_STATS; /* The maximum for the player */ + +struct room *oldrp; /* Roomin(&oldpos) */ +struct room rooms[MAXROOMS]; /* One for each room -- A level */ +struct room passages[MAXPASS] = /* One for each passage */ +{ + { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, + { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, + { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, + { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, + { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, + { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, + { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, + { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, + { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, + { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, + { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, + { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} } +}; + +#define ___ 1 +#define XX 10 +struct monster monsters[26] = + { +/* Name CARRY FLAG str, exp, lvl, amr, hpt, dmg */ +{ "aquator", 0, ISMEAN, { XX, 20, 5, 2, ___, "0x0/0x0" } }, +{ "bat", 0, ISFLY, { XX, 1, 1, 3, ___, "1x2" } }, +{ "centaur", 15, 0, { XX, 17, 4, 4, ___, "1x2/1x5/1x5" } }, +{ "dragon", 100, ISMEAN, { XX,5000, 10, -1, ___, "1x8/1x8/3x10" } }, +{ "emu", 0, ISMEAN, { XX, 2, 1, 7, ___, "1x2" } }, +{ "venus flytrap", 0, ISMEAN, { XX, 80, 8, 3, ___, "%%%x0" } }, + /* NOTE: the damage is %%% so that xstr won't merge this */ + /* string with others, since it is written on in the program */ +{ "griffin", 20, ISMEAN|ISFLY|ISREGEN, { XX,2000, 13, 2, ___, "4x3/3x5" } }, +{ "hobgoblin", 0, ISMEAN, { XX, 3, 1, 5, ___, "1x8" } }, +{ "ice monster", 0, 0, { XX, 5, 1, 9, ___, "0x0" } }, +{ "jabberwock", 70, 0, { XX,3000, 15, 6, ___, "2x12/2x4" } }, +{ "kestrel", 0, ISMEAN|ISFLY, { XX, 1, 1, 7, ___, "1x4" } }, +{ "leprechaun", 0, 0, { XX, 10, 3, 8, ___, "1x1" } }, +{ "medusa", 40, ISMEAN, { XX,200, 8, 2, ___, "3x4/3x4/2x5" } }, +{ "nymph", 100, 0, { XX, 37, 3, 9, ___, "0x0" } }, +{ "orc", 15, ISGREED,{ XX, 5, 1, 6, ___, "1x8" } }, +{ "phantom", 0, ISINVIS,{ XX,120, 8, 3, ___, "4x4" } }, +{ "quagga", 0, ISMEAN, { XX, 15, 3, 3, ___, "1x5/1x5" } }, +{ "rattlesnake", 0, ISMEAN, { XX, 9, 2, 3, ___, "1x6" } }, +{ "snake", 0, ISMEAN, { XX, 2, 1, 5, ___, "1x3" } }, +{ "troll", 50, ISREGEN|ISMEAN,{ XX, 120, 6, 4, ___, "1x8/1x8/2x6" } }, +{ "black unicorn", 0, ISMEAN, { XX,190, 7, -2, ___, "1x9/1x9/2x9" } }, +{ "vampire", 20, ISREGEN|ISMEAN,{ XX,350, 8, 1, ___, "1x10" } }, +{ "wraith", 0, 0, { XX, 55, 5, 4, ___, "1x6" } }, +{ "xeroc", 30, 0, { XX,100, 7, 7, ___, "4x4" } }, +{ "yeti", 30, 0, { XX, 50, 4, 6, ___, "1x6/1x6" } }, +{ "zombie", 0, ISMEAN, { XX, 6, 2, 8, ___, "1x8" } } + }; +#undef ___ +#undef XX + +struct obj_info things[NUMTHINGS] = { + { 0, 26 }, /* potion */ + { 0, 36 }, /* scroll */ + { 0, 16 }, /* food */ + { 0, 7 }, /* weapon */ + { 0, 7 }, /* armor */ + { 0, 4 }, /* ring */ + { 0, 4 }, /* stick */ +}; + +struct obj_info arm_info[MAXARMORS] = { + { "leather armor", 20, 20, NULL, FALSE }, + { "ring mail", 15, 25, NULL, FALSE }, + { "studded leather armor", 15, 20, NULL, FALSE }, + { "scale mail", 13, 30, NULL, FALSE }, + { "chain mail", 12, 75, NULL, FALSE }, + { "splint mail", 10, 80, NULL, FALSE }, + { "banded mail", 10, 90, NULL, FALSE }, + { "plate mail", 5, 150, NULL, FALSE }, +}; +struct obj_info pot_info[MAXPOTIONS] = { + { "confusion", 7, 5, NULL, FALSE }, + { "hallucination", 8, 5, NULL, FALSE }, + { "poison", 8, 5, NULL, FALSE }, + { "gain strength", 13, 150, NULL, FALSE }, + { "see invisible", 3, 100, NULL, FALSE }, + { "healing", 13, 130, NULL, FALSE }, + { "monster detection", 6, 130, NULL, FALSE }, + { "magic detection", 6, 105, NULL, FALSE }, + { "raise level", 2, 250, NULL, FALSE }, + { "extra healing", 5, 200, NULL, FALSE }, + { "haste self", 5, 190, NULL, FALSE }, + { "restore strength", 13, 130, NULL, FALSE }, + { "blindness", 5, 5, NULL, FALSE }, + { "levitation", 6, 75, NULL, FALSE }, +}; +struct obj_info ring_info[MAXRINGS] = { + { "protection", 9, 400, NULL, FALSE }, + { "add strength", 9, 400, NULL, FALSE }, + { "sustain strength", 5, 280, NULL, FALSE }, + { "searching", 10, 420, NULL, FALSE }, + { "see invisible", 10, 310, NULL, FALSE }, + { "adornment", 1, 10, NULL, FALSE }, + { "aggravate monster", 10, 10, NULL, FALSE }, + { "dexterity", 8, 440, NULL, FALSE }, + { "increase damage", 8, 400, NULL, FALSE }, + { "regeneration", 4, 460, NULL, FALSE }, + { "slow digestion", 9, 240, NULL, FALSE }, + { "teleportation", 5, 30, NULL, FALSE }, + { "stealth", 7, 470, NULL, FALSE }, + { "maintain armor", 5, 380, NULL, FALSE }, +}; +struct obj_info scr_info[MAXSCROLLS] = { + { "monster confusion", 7, 140, NULL, FALSE }, + { "magic mapping", 4, 150, NULL, FALSE }, + { "hold monster", 2, 180, NULL, FALSE }, + { "sleep", 3, 5, NULL, FALSE }, + { "enchant armor", 7, 160, NULL, FALSE }, + { "identify potion", 10, 80, NULL, FALSE }, + { "identify scroll", 10, 80, NULL, FALSE }, + { "identify weapon", 6, 80, NULL, FALSE }, + { "identify armor", 7, 100, NULL, FALSE }, + { "identify ring, wand or staff", 10, 115, NULL, FALSE }, + { "scare monster", 3, 200, NULL, FALSE }, + { "food detection", 2, 60, NULL, FALSE }, + { "teleportation", 5, 165, NULL, FALSE }, + { "enchant weapon", 8, 150, NULL, FALSE }, + { "create monster", 4, 75, NULL, FALSE }, + { "remove curse", 7, 105, NULL, FALSE }, + { "aggravate monsters", 3, 20, NULL, FALSE }, + { "protect armor", 2, 250, NULL, FALSE }, +}; +struct obj_info weap_info[MAXWEAPONS + 1] = { + { "mace", 11, 8, NULL, FALSE }, + { "long sword", 11, 15, NULL, FALSE }, + { "short bow", 12, 15, NULL, FALSE }, + { "arrow", 12, 1, NULL, FALSE }, + { "dagger", 8, 3, NULL, FALSE }, + { "two handed sword", 10, 75, NULL, FALSE }, + { "dart", 12, 2, NULL, FALSE }, + { "shuriken", 12, 5, NULL, FALSE }, + { "spear", 12, 5, NULL, FALSE }, + { NULL, 0 }, /* DO NOT REMOVE: fake entry for dragon's breath */ +}; +struct obj_info ws_info[MAXSTICKS] = { + { "light", 12, 250, NULL, FALSE }, + { "invisibility", 6, 5, NULL, FALSE }, + { "lightning", 3, 330, NULL, FALSE }, + { "fire", 3, 330, NULL, FALSE }, + { "cold", 3, 330, NULL, FALSE }, + { "polymorph", 15, 310, NULL, FALSE }, + { "magic missile", 10, 170, NULL, FALSE }, + { "haste monster", 10, 5, NULL, FALSE }, + { "slow monster", 11, 350, NULL, FALSE }, + { "drain life", 9, 300, NULL, FALSE }, + { "nothing", 1, 5, NULL, FALSE }, + { "teleport away", 6, 340, NULL, FALSE }, + { "teleport to", 6, 50, NULL, FALSE }, + { "cancellation", 5, 280, NULL, FALSE }, +}; + +struct h_list helpstr[] = { + {'?', " prints help", TRUE}, + {'/', " identify object", TRUE}, + {'h', " left", TRUE}, + {'j', " down", TRUE}, + {'k', " up", TRUE}, + {'l', " right", TRUE}, + {'y', " up & left", TRUE}, + {'u', " up & right", TRUE}, + {'b', " down & left", TRUE}, + {'n', " down & right", TRUE}, + {'H', " run left", FALSE}, + {'J', " run down", FALSE}, + {'K', " run up", FALSE}, + {'L', " run right", FALSE}, + {'Y', " run up & left", FALSE}, + {'U', " run up & right", FALSE}, + {'B', " run down & left", FALSE}, + {'N', " run down & right", FALSE}, + {CTRL('H'), " run left until adjacent", FALSE}, + {CTRL('J'), " run down until adjacent", FALSE}, + {CTRL('K'), " run up until adjacent", FALSE}, + {CTRL('L'), " run right until adjacent", FALSE}, + {CTRL('Y'), " run up & left until adjacent", FALSE}, + {CTRL('U'), " run up & right until adjacent", FALSE}, + {CTRL('B'), " run down & left until adjacent", FALSE}, + {CTRL('N'), " run down & right until adjacent", FALSE}, + {'\0', " : run that way", TRUE}, + {'\0', " : run till adjacent", TRUE}, + {'f', " fight till death or near death", TRUE}, + {'t', " throw something", TRUE}, + {'m', " move onto without picking up", TRUE}, + {'z', " zap a wand in a direction", TRUE}, + {'^', " identify trap type", TRUE}, + {'s', " search for trap/secret door", TRUE}, + {'>', " go down a staircase", TRUE}, + {'<', " go up a staircase", TRUE}, + {'.', " rest for a turn", TRUE}, + {',', " pick something up", TRUE}, + {'i', " inventory", TRUE}, + {'I', " inventory single item", TRUE}, + {'q', " quaff potion", TRUE}, + {'r', " read scroll", TRUE}, + {'e', " eat food", TRUE}, + {'w', " wield a weapon", TRUE}, + {'W', " wear armor", TRUE}, + {'T', " take armor off", TRUE}, + {'P', " put on ring", TRUE}, + {'R', " remove ring", TRUE}, + {'d', " drop object", TRUE}, + {'c', " call object", TRUE}, + {'a', " repeat last command", TRUE}, + {')', " print current weapon", TRUE}, + {']', " print current armor", TRUE}, + {'=', " print current rings", TRUE}, + {'@', " print current stats", TRUE}, + {'D', " recall what's been discovered", TRUE}, + {'o', " examine/set options", TRUE}, + {CTRL('R'), " redraw screen", TRUE}, + {CTRL('P'), " repeat last message", TRUE}, + {ESCAPE, " cancel command", TRUE}, + {'S', " save game", TRUE}, + {'Q', " quit", TRUE}, + {'!', " shell escape", TRUE}, + {'F', " fight till either of you dies", TRUE}, + {'v', " print version number", TRUE}, + {0, NULL } +}; diff --git a/src/cc/rogue/extern.h b/src/cc/rogue/extern.h new file mode 100644 index 000000000..e8c13d27d --- /dev/null +++ b/src/cc/rogue/extern.h @@ -0,0 +1,181 @@ +/* + * Defines for things used in mach_dep.c + * + * @(#)extern.h 4.35 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + + +#ifdef HAVE_CONFIG_H +#ifdef PDCURSES +#undef HAVE_UNISTD_H +#undef HAVE_LIMITS_H +#undef HAVE_MEMORY_H +#undef HAVE_STRING_H +#endif +#include "config.h" +#elif defined(__DJGPP__) +#define HAVE_SYS_TYPES_H 1 +#define HAVE_PROCESS_H 1 +#define HAVE_PWD_H 1 +#define HAVE_TERMIOS_H 1 +#define HAVE_SETGID 1 +#define HAVE_GETGID 1 +#define HAVE_SETUID 1 +#define HAVE_GETUID 1 +#define HAVE_GETPASS 1 +#define HAVE_SPAWNL 1 +#define HAVE_ALARM 1 +#define HAVE_ERASECHAR 1 +#define HAVE_KILLCHAR 1 +#elif defined(_WIN32) +#define HAVE_CURSES_H +#define HAVE_TERM_H +#define HAVE__SPAWNL +#define HAVE_SYS_TYPES_H +#define HAVE_PROCESS_H +#define HAVE_ERASECHAR 1 +#define HAVE_KILLCHAR 1 +#elif defined(__CYGWIN__) +#define HAVE_SYS_TYPES_H 1 +#define HAVE_PWD_H 1 +#define HAVE_PWD_H 1 +#define HAVE_SYS_UTSNAME_H 1 +#define HAVE_ARPA_INET_H 1 +#define HAVE_UNISTD_H 1 +#define HAVE_TERMIOS_H 1 +#define HAVE_NCURSES_TERM_H 1 +#define HAVE_ESCDELAY +#define HAVE_SETGID 1 +#define HAVE_GETGID 1 +#define HAVE_SETUID 1 +#define HAVE_GETUID 1 +#define HAVE_GETPASS 1 +#define HAVE_GETPWUID 1 +#define HAVE_WORKING_FORK 1 +#define HAVE_ALARM 1 +#define HAVE_SPAWNL 1 +#define HAVE__SPAWNL 1 +#define HAVE_ERASECHAR 1 +#define HAVE_KILLCHAR 1 +#else /* POSIX */ +#define HAVE_SYS_TYPES_H 1 +#define HAVE_PWD_H 1 +#define HAVE_PWD_H 1 +#define HAVE_SYS_UTSNAME_H 1 +#define HAVE_ARPA_INET_H 1 +#define HAVE_UNISTD_H 1 +#define HAVE_TERMIOS_H 1 +#define HAVE_TERM_H 1 +#define HAVE_SETGID 1 +#define HAVE_GETGID 1 +#define HAVE_SETUID 1 +#define HAVE_GETUID 1 +#define HAVE_SETREUID 1 +#define HAVE_SETREGID 1 +#define HAVE_GETPASS 1 +#define HAVE_GETPWUID 1 +#define HAVE_WORKING_FORK 1 +#define HAVE_ERASECHAR 1 +#define HAVE_KILLCHAR 1 +#ifndef _AIX +#define HAVE_GETLOADAVG 1 +#endif +#define HAVE_ALARM 1 +#endif + +#ifdef __DJGPP__ +#undef HAVE_GETPWUID /* DJGPP's limited version doesn't even work as documented */ +#endif + +/* + * Don't change the constants, since they are used for sizes in many + * places in the program. + */ + +#include +#include + +#undef SIGTSTP + +#define MAXSTR 1024 /* maximum length of strings */ +#define MAXLINES 32 /* maximum number of screen lines used */ +#define MAXCOLS 80 /* maximum number of screen columns used */ + +#define RN ((int32_t)((seed = seed*11109+13849) >> 16) & 0xffff) +#ifdef CTRL +#undef CTRL +#endif +#define CTRL(c) (c & 037) + +/* + * Now all the global variables + */ + +extern bool got_ltc, in_shell; +extern int wizard; +extern char fruit[], prbuf[], whoami[]; +extern int orig_dsusp; +extern FILE *scoreboard; + +/* + * Function types + */ + +void auto_save(int); +void endit(int sig); +void fatal(char *); +void getltchars(void); +void leave(int); +void my_exit(int st); +void playltchars(void); +void quit(int); +void resetltchars(void); +void set_order(int *order, int numthings); +void tstp(int ignored); + +char *killname(char monst, bool doart); +char *nothing(char type); +char *type_name(int type); + +#ifdef CHECKTIME +int checkout(void); +#endif + +int md_chmod(char *filename, int mode); +char *md_crypt(char *key, char *salt); +int md_dsuspchar(void); +int md_erasechar(void); +char *md_gethomedir(void); +char *md_getusername(void); +int md_getuid(void); +char *md_getpass(char *prompt); +int md_getpid(void); +char *md_getrealname(int uid); +void md_init(void); +int md_killchar(void); +void md_normaluser(void); +void md_raw_standout(void); +void md_raw_standend(void); +int md_readchar(void); +int md_setdsuspchar(int c); +int md_shellescape(void); +void md_sleep(int s); +int md_suspchar(void); +int md_hasclreol(void); +int md_unlink(char *file); +int md_unlink_open_file(char *file, FILE *inf); +void md_tstpsignal(void); +void md_tstphold(void); +void md_tstpresume(void); +void md_ignoreallsignals(void); +void md_onsignal_autosave(void); +void md_onsignal_exit(void); +void md_onsignal_default(void); +int md_issymlink(char *sp); + diff --git a/src/cc/rogue/fight.c b/src/cc/rogue/fight.c new file mode 100644 index 000000000..ba1c9112e --- /dev/null +++ b/src/cc/rogue/fight.c @@ -0,0 +1,686 @@ +/* + * All the fighting gets done here + * + * @(#)fight.c 4.67 (Berkeley) 09/06/83 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include +#include +#include "rogue.h" + +#define EQSTR(a, b) (strcmp(a, b) == 0) + +char *h_names[] = { /* strings for hitting */ + " scored an excellent hit on ", + " hit ", + " have injured ", + " swing and hit ", + " scored an excellent hit on ", + " hit ", + " has injured ", + " swings and hits " +}; + +char *m_names[] = { /* strings for missing */ + " miss", + " swing and miss", + " barely miss", + " don't hit", + " misses", + " swings and misses", + " barely misses", + " doesn't hit", +}; + +/* + * adjustments to hit probabilities due to strength + */ +static int str_plus[] = { + -7, -6, -5, -4, -3, -2, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, + 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, +}; + +/* + * adjustments to damage done due to strength + */ +static int add_dam[] = { + -7, -6, -5, -4, -3, -2, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, + 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6 +}; + +/* + * fight: + * The player attacks the monster. + */ +int +fight(struct rogue_state *rs,coord *mp, THING *weap, bool thrown) +{ + register THING *tp; + register bool did_hit = TRUE; + register char *mname, ch; + + /* + * Find the monster we want to fight + */ +#ifdef MASTER + if ((tp = moat(mp->y, mp->x)) == NULL) + debug("Fight what @ %d,%d", mp->y, mp->x); +#else + tp = moat(mp->y, mp->x); +#endif + /* + * Since we are fighting, things are not quiet so no healing takes + * place. + */ + count = 0; + quiet = 0; + runto(rs,mp); + /* + * Let him know it was really a xeroc (if it was one). + */ + ch = '\0'; + if (tp->t_type == 'X' && tp->t_disguise != 'X' && !on(player, ISBLIND)) + { + tp->t_disguise = 'X'; + if (on(player, ISHALU)) { + ch = (char)(rnd(26) + 'A'); + mvaddch(tp->t_pos.y, tp->t_pos.x, ch); + } + msg(rs,choose_str("heavy! That's a nasty critter!", + "wait! That's a xeroc!")); + if (!thrown) + return FALSE; + } + mname = set_mname(tp); + did_hit = FALSE; + has_hit = (terse && !to_death); + if (roll_em(&player, tp, weap, thrown)) + { + did_hit = FALSE; + if (thrown) + thunk(rs,weap, mname, terse); + else + hit(rs,(char *) NULL, mname, terse); + if (on(player, CANHUH)) + { + did_hit = TRUE; + tp->t_flags |= ISHUH; + player.t_flags &= ~CANHUH; + endmsg(rs); + has_hit = FALSE; + msg(rs,"your hands stop glowing %s", pick_color("red")); + } + if (tp->t_stats.s_hpt <= 0) + killed(rs,tp, TRUE); + else if (did_hit && !on(player, ISBLIND)) + msg(rs,"%s appears confused", mname); + did_hit = TRUE; + } + else + if (thrown) + bounce(rs,weap, mname, terse); + else + miss(rs,(char *) NULL, mname, terse); + return did_hit; +} + +/* + * attack: + * The monster attacks the player + */ +int +attack(struct rogue_state *rs,THING *mp) +{ + register char *mname; + register int oldhp; + + /* + * Since this is an attack, stop running and any healing that was + * going on at the time. + */ + running = FALSE; + count = 0; + quiet = 0; + if (to_death && !on(*mp, ISTARGET)) + { + to_death = FALSE; + kamikaze = FALSE; + } + if (mp->t_type == 'X' && mp->t_disguise != 'X' && !on(player, ISBLIND)) + { + mp->t_disguise = 'X'; + if (on(player, ISHALU)) + mvaddch(mp->t_pos.y, mp->t_pos.x, rnd(26) + 'A'); + } + mname = set_mname(mp); + oldhp = pstats.s_hpt; + if (roll_em(mp, &player, (THING *) NULL, FALSE)) + { + if (mp->t_type != 'I') + { + if (has_hit) + addmsg(rs,". "); + hit(rs,mname, (char *) NULL, FALSE); + } + else + if (has_hit) + endmsg(rs); + has_hit = FALSE; + if (pstats.s_hpt <= 0) + death(mp->t_type); /* Bye bye life ... */ + else if (!kamikaze) + { + oldhp -= pstats.s_hpt; + if (oldhp > max_hit) + max_hit = oldhp; + if (pstats.s_hpt <= max_hit) + to_death = FALSE; + } + if (!on(*mp, ISCANC)) + switch (mp->t_type) + { + case 'A': + /* + * If an aquator hits, you can lose armor class. + */ + rust_armor(rs,cur_armor); + when 'I': + /* + * The ice monster freezes you + */ + player.t_flags &= ~ISRUN; + if (!no_command) + { + addmsg(rs,"you are frozen"); + if (!terse) + addmsg(rs," by the %s", mname); + endmsg(rs); + } + no_command += rnd(2) + 2; + if (no_command > BORE_LEVEL) + death('h'); + when 'R': + /* + * Rattlesnakes have poisonous bites + */ + if (!save(VS_POISON)) + { + if (!ISWEARING(R_SUSTSTR)) + { + chg_str(-1); + if (!terse) + msg(rs,"you feel a bite in your leg and now feel weaker"); + else + msg(rs,"a bite has weakened you"); + } + else if (!to_death) + { + if (!terse) + msg(rs,"a bite momentarily weakens you"); + else + msg(rs,"bite has no effect"); + } + } + when 'W': + case 'V': + /* + * Wraiths might drain energy levels, and Vampires + * can steal max_hp + */ + if (rnd(100) < (mp->t_type == 'W' ? 15 : 30)) + { + register int fewer; + + if (mp->t_type == 'W') + { + if (pstats.s_exp == 0) + death('W'); /* All levels gone */ + if (--pstats.s_lvl == 0) + { + pstats.s_exp = 0; + pstats.s_lvl = 1; + } + else + pstats.s_exp = e_levels[pstats.s_lvl-1]+1; + fewer = roll(1, 10); + } + else + fewer = roll(1, 3); + pstats.s_hpt -= fewer; + max_hp -= fewer; + if (pstats.s_hpt <= 0) + pstats.s_hpt = 1; + if (max_hp <= 0) + death(mp->t_type); + msg(rs,"you suddenly feel weaker"); + } + when 'F': + /* + * Venus Flytrap stops the poor guy from moving + */ + player.t_flags |= ISHELD; + sprintf(monsters['F'-'A'].m_stats.s_dmg,"%dx1", ++vf_hit); + if (--pstats.s_hpt <= 0) + death('F'); + when 'L': + { + /* + * Leperachaun steals some gold + */ + register int lastpurse; + + lastpurse = purse; + purse -= GOLDCALC; + if (!save(VS_MAGIC)) + purse -= GOLDCALC + GOLDCALC + GOLDCALC + GOLDCALC; + if (purse < 0) + purse = 0; + remove_mon(rs,&mp->t_pos, mp, FALSE); + mp=NULL; + if (purse != lastpurse) + msg(rs,"your purse feels lighter"); + } + when 'N': + { + register THING *obj, *steal; + register int nobj; + + /* + * Nymph's steal a magic item, look through the pack + * and pick out one we like. + */ + steal = NULL; + for (nobj = 0, obj = pack; obj != NULL; obj = next(obj)) + if (obj != cur_armor && obj != cur_weapon + && obj != cur_ring[LEFT] && obj != cur_ring[RIGHT] + && is_magic(obj) && rnd(++nobj) == 0) + steal = obj; + if (steal != NULL) + { + remove_mon(rs,&mp->t_pos, moat(mp->t_pos.y, mp->t_pos.x), FALSE); + mp=NULL; + leave_pack(rs,steal, FALSE, FALSE); + msg(rs,"she stole %s!", inv_name(steal, TRUE)); + discard(steal); + } + } + otherwise: + break; + } + } + else if (mp->t_type != 'I') + { + if (has_hit) + { + addmsg(rs,". "); + has_hit = FALSE; + } + if (mp->t_type == 'F') + { + pstats.s_hpt -= vf_hit; + if (pstats.s_hpt <= 0) + death(mp->t_type); /* Bye bye life ... */ + } + miss(rs,mname, (char *) NULL, FALSE); + } + if (fight_flush && !to_death) + flush_type(); + count = 0; + status(rs); + if (mp == NULL) + return(-1); + else + return(0); +} + +/* + * set_mname: + * return the monster name for the given monster + */ +char * +set_mname(THING *tp) +{ + int ch; + char *mname; + static char tbuf[MAXSTR] = { 't', 'h', 'e', ' ' }; + + if (!see_monst(tp) && !on(player, SEEMONST)) + return (terse ? "it" : "something"); + else if (on(player, ISHALU)) + { + move(tp->t_pos.y, tp->t_pos.x); + ch = toascii(inch()); + if (!isupper(ch)) + ch = rnd(26); + else + ch -= 'A'; + mname = monsters[ch].m_name; + } + else + mname = monsters[tp->t_type - 'A'].m_name; + strcpy(&tbuf[4], mname); + return tbuf; +} + +/* + * swing: + * Returns true if the swing hits + */ +int +swing(int at_lvl, int op_arm, int wplus) +{ + int res = rnd(20); + int need = (20 - at_lvl) - op_arm; + + return (res + wplus >= need); +} + +/* + * roll_em: + * Roll several attacks + */ +bool +roll_em(THING *thatt, THING *thdef, THING *weap, bool hurl) +{ + register struct stats *att, *def; + register char *cp; + register int ndice, nsides, def_arm; + register bool did_hit = FALSE; + register int hplus; + register int dplus; + register int damage; + + att = &thatt->t_stats; + def = &thdef->t_stats; + if (weap == NULL) + { + cp = att->s_dmg; + dplus = 0; + hplus = 0; + } + else + { + hplus = (weap == NULL ? 0 : weap->o_hplus); + dplus = (weap == NULL ? 0 : weap->o_dplus); + if (weap == cur_weapon) + { + if (ISRING(LEFT, R_ADDDAM)) + dplus += cur_ring[LEFT]->o_arm; + else if (ISRING(LEFT, R_ADDHIT)) + hplus += cur_ring[LEFT]->o_arm; + if (ISRING(RIGHT, R_ADDDAM)) + dplus += cur_ring[RIGHT]->o_arm; + else if (ISRING(RIGHT, R_ADDHIT)) + hplus += cur_ring[RIGHT]->o_arm; + } + cp = weap->o_damage; + if (hurl) + { + if ((weap->o_flags&ISMISL) && cur_weapon != NULL && + cur_weapon->o_which == weap->o_launch) + { + cp = weap->o_hurldmg; + hplus += cur_weapon->o_hplus; + dplus += cur_weapon->o_dplus; + } + else if (weap->o_launch < 0) + cp = weap->o_hurldmg; + } + } + /* + * If the creature being attacked is not running (alseep or held) + * then the attacker gets a plus four bonus to hit. + */ + if (!on(*thdef, ISRUN)) + hplus += 4; + def_arm = def->s_arm; + if (def == &pstats) + { + if (cur_armor != NULL) + def_arm = cur_armor->o_arm; + if (ISRING(LEFT, R_PROTECT)) + def_arm -= cur_ring[LEFT]->o_arm; + if (ISRING(RIGHT, R_PROTECT)) + def_arm -= cur_ring[RIGHT]->o_arm; + } + while(cp != NULL && *cp != '\0') + { + ndice = atoi(cp); + if ((cp = strchr(cp, 'x')) == NULL) + break; + nsides = atoi(++cp); + if (swing(att->s_lvl, def_arm, hplus + str_plus[att->s_str])) + { + int proll; + + proll = roll(ndice, nsides); +#ifdef MASTER + if (ndice + nsides > 0 && proll <= 0) + debug("Damage for %dx%d came out %d, dplus = %d, add_dam = %d, def_arm = %d", ndice, nsides, proll, dplus, add_dam[att->s_str], def_arm); +#endif + damage = dplus + proll + add_dam[att->s_str]; + def->s_hpt -= max(0, damage); + did_hit = TRUE; + } + if ((cp = strchr(cp, '/')) == NULL) + break; + cp++; + } + return did_hit; +} + +/* + * prname: + * The print name of a combatant + */ +char * +prname(char *mname, bool upper) +{ + static char tbuf[MAXSTR]; + + *tbuf = '\0'; + if (mname == 0) + strcpy(tbuf, "you"); + else + strcpy(tbuf, mname); + if (upper) + *tbuf = (char) toupper(*tbuf); + return tbuf; +} + +/* + * thunk: + * A missile hits a monster + */ +void +thunk(struct rogue_state *rs,THING *weap, char *mname, bool noend) +{ + if (to_death) + return; + if (weap->o_type == WEAPON) + addmsg(rs,"the %s hits ", weap_info[weap->o_which].oi_name); + else + addmsg(rs,"you hit "); + addmsg(rs,"%s", mname); + if (!noend) + endmsg(rs); +} + +/* + * hit: + * Print a message to indicate a succesful hit + */ + +void +hit(struct rogue_state *rs,char *er, char *ee, bool noend) +{ + int i; + char *s; + extern char *h_names[]; + + if (to_death) + return; + addmsg(rs,prname(er, TRUE)); + if (terse) + s = " hit"; + else + { + i = rnd(4); + if (er != NULL) + i += 4; + s = h_names[i]; + } + addmsg(rs,s); + if (!terse) + addmsg(rs,prname(ee, FALSE)); + if (!noend) + endmsg(rs); +} + +/* + * miss: + * Print a message to indicate a poor swing + */ +void +miss(struct rogue_state *rs,char *er, char *ee, bool noend) +{ + int i; + extern char *m_names[]; + + if (to_death) + return; + addmsg(rs,prname(er, TRUE)); + if (terse) + i = 0; + else + i = rnd(4); + if (er != NULL) + i += 4; + addmsg(rs,m_names[i]); + if (!terse) + addmsg(rs," %s", prname(ee, FALSE)); + if (!noend) + endmsg(rs); +} + +/* + * bounce: + * A missile misses a monster + */ +void +bounce(struct rogue_state *rs,THING *weap, char *mname, bool noend) +{ + if (to_death) + return; + if (weap->o_type == WEAPON) + addmsg(rs,"the %s misses ", weap_info[weap->o_which].oi_name); + else + addmsg(rs,"you missed "); + addmsg(rs,mname); + if (!noend) + endmsg(rs); +} + +/* + * remove_mon: + * Remove a monster from the screen + */ +void +remove_mon(struct rogue_state *rs,coord *mp, THING *tp, bool waskill) +{ + register THING *obj, *nexti; + + for (obj = tp->t_pack; obj != NULL; obj = nexti) + { + nexti = next(obj); + obj->o_pos = tp->t_pos; + detach(tp->t_pack, obj); + if (waskill) + fall(rs,obj, FALSE); + else + discard(obj); + } + moat(mp->y, mp->x) = NULL; + mvaddch(mp->y, mp->x, tp->t_oldch); + detach(mlist, tp); + if (on(*tp, ISTARGET)) + { + kamikaze = FALSE; + to_death = FALSE; + if (fight_flush) + flush_type(); + } + discard(tp); +} + +/* + * killed: + * Called to put a monster to death + */ +void +killed(struct rogue_state *rs,THING *tp, bool pr) +{ + char *mname; + + pstats.s_exp += tp->t_stats.s_exp; + + /* + * If the monster was a venus flytrap, un-hold him + */ + switch (tp->t_type) + { + case 'F': + player.t_flags &= ~ISHELD; + vf_hit = 0; + strcpy(monsters['F'-'A'].m_stats.s_dmg, "000x0"); + when 'L': + { + THING *gold; + + if (fallpos(&tp->t_pos, &tp->t_room->r_gold) && level >= max_level) + { + gold = new_item(); + gold->o_type = GOLD; + gold->o_goldval = GOLDCALC; + if (save(VS_MAGIC)) + gold->o_goldval += GOLDCALC + GOLDCALC + + GOLDCALC + GOLDCALC; + attach(tp->t_pack, gold); + } + } + } + /* + * Get rid of the monster. + */ + mname = set_mname(tp); + remove_mon(rs,&tp->t_pos, tp, TRUE); + if (pr) + { + if (has_hit) + { + addmsg(rs,". Defeated "); + has_hit = FALSE; + } + else + { + if (!terse) + addmsg(rs,"you have "); + addmsg(rs,"defeated "); + } + msg(rs,mname); + } + /* + * Do adjustments if he went up a level + */ + check_level(rs); + if (fight_flush) + flush_type(); +} diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c new file mode 100644 index 000000000..51a9d2d51 --- /dev/null +++ b/src/cc/rogue/init.c @@ -0,0 +1,447 @@ +/* + * global variable initializaton + * + * @(#)init.c 4.31 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include +#include +#include "rogue.h" + +/* + * init_player: + * Roll her up + */ +void +init_player(struct rogue_state *rs) +{ + register THING *obj; + + pstats = max_stats; + food_left = HUNGERTIME; + /* + * Give him some food + */ + obj = new_item(); + obj->o_type = FOOD; + obj->o_count = 1; + add_pack(rs,obj, TRUE); + /* + * And his suit of armor + */ + obj = new_item(); + obj->o_type = ARMOR; + obj->o_which = RING_MAIL; + obj->o_arm = a_class[RING_MAIL] - 1; + obj->o_flags |= ISKNOW; + obj->o_count = 1; + cur_armor = obj; + add_pack(rs,obj, TRUE); + /* + * Give him his weaponry. First a mace. + */ + obj = new_item(); + init_weapon(obj, MACE); + obj->o_hplus = 1; + obj->o_dplus = 1; + obj->o_flags |= ISKNOW; + add_pack(rs,obj, TRUE); + cur_weapon = obj; + /* + * Now a +1 bow + */ + obj = new_item(); + init_weapon(obj, BOW); + obj->o_hplus = 1; + obj->o_flags |= ISKNOW; + add_pack(rs,obj, TRUE); + /* + * Now some arrows + */ + obj = new_item(); + init_weapon(obj, ARROW); + obj->o_count = rnd(15) + 25; + obj->o_flags |= ISKNOW; + add_pack(rs,obj, TRUE); +} + +/* + * Contains defintions and functions for dealing with things like + * potions and scrolls + */ + +char *rainbow[] = { + "amber", + "aquamarine", + "black", + "blue", + "brown", + "clear", + "crimson", + "cyan", + "ecru", + "gold", + "green", + "grey", + "magenta", + "orange", + "pink", + "plaid", + "purple", + "red", + "silver", + "tan", + "tangerine", + "topaz", + "turquoise", + "vermilion", + "violet", + "white", + "yellow", +}; + +#define NCOLORS (sizeof rainbow / sizeof (char *)) +int cNCOLORS = NCOLORS; + +static char *sylls[] = { + "a", "ab", "ag", "aks", "ala", "an", "app", "arg", "arze", "ash", + "bek", "bie", "bit", "bjor", "blu", "bot", "bu", "byt", "comp", + "con", "cos", "cre", "dalf", "dan", "den", "do", "e", "eep", "el", + "eng", "er", "ere", "erk", "esh", "evs", "fa", "fid", "fri", "fu", + "gan", "gar", "glen", "gop", "gre", "ha", "hyd", "i", "ing", "ip", + "ish", "it", "ite", "iv", "jo", "kho", "kli", "klis", "la", "lech", + "mar", "me", "mi", "mic", "mik", "mon", "mung", "mur", "nej", + "nelg", "nep", "ner", "nes", "nes", "nih", "nin", "o", "od", "ood", + "org", "orn", "ox", "oxy", "pay", "ple", "plu", "po", "pot", + "prok", "re", "rea", "rhov", "ri", "ro", "rog", "rok", "rol", "sa", + "san", "sat", "sef", "seh", "shu", "ski", "sna", "sne", "snik", + "sno", "so", "sol", "sri", "sta", "sun", "ta", "tab", "tem", + "ther", "ti", "tox", "trol", "tue", "turs", "u", "ulk", "um", "un", + "uni", "ur", "val", "viv", "vly", "vom", "wah", "wed", "werg", + "wex", "whon", "wun", "xo", "y", "yot", "yu", "zant", "zeb", "zim", + "zok", "zon", "zum", +}; + +STONE stones[] = { + { "agate", 25}, + { "alexandrite", 40}, + { "amethyst", 50}, + { "carnelian", 40}, + { "diamond", 300}, + { "emerald", 300}, + { "germanium", 225}, + { "granite", 5}, + { "garnet", 50}, + { "jade", 150}, + { "kryptonite", 300}, + { "lapis lazuli", 50}, + { "moonstone", 50}, + { "obsidian", 15}, + { "onyx", 60}, + { "opal", 200}, + { "pearl", 220}, + { "peridot", 63}, + { "ruby", 350}, + { "sapphire", 285}, + { "stibotantalite", 200}, + { "tiger eye", 50}, + { "topaz", 60}, + { "turquoise", 70}, + { "taaffeite", 300}, + { "zircon", 80}, +}; + +#define NSTONES (sizeof stones / sizeof (STONE)) +int cNSTONES = NSTONES; + +char *wood[] = { + "avocado wood", + "balsa", + "bamboo", + "banyan", + "birch", + "cedar", + "cherry", + "cinnibar", + "cypress", + "dogwood", + "driftwood", + "ebony", + "elm", + "eucalyptus", + "fall", + "hemlock", + "holly", + "ironwood", + "kukui wood", + "mahogany", + "manzanita", + "maple", + "oaken", + "persimmon wood", + "pecan", + "pine", + "poplar", + "redwood", + "rosewood", + "spruce", + "teak", + "walnut", + "zebrawood", +}; + +#define NWOOD (sizeof wood / sizeof (char *)) +int cNWOOD = NWOOD; + +char *metal[] = { + "aluminum", + "beryllium", + "bone", + "brass", + "bronze", + "copper", + "electrum", + "gold", + "iron", + "lead", + "magnesium", + "mercury", + "nickel", + "pewter", + "platinum", + "steel", + "silver", + "silicon", + "tin", + "titanium", + "tungsten", + "zinc", +}; + +#define NMETAL (sizeof metal / sizeof (char *)) +int cNMETAL = NMETAL; +#define MAX3(a,b,c) (a > b ? (a > c ? a : c) : (b > c ? b : c)) + +static bool used[MAX3(NCOLORS, NSTONES, NWOOD)]; + +/* + * init_colors: + * Initialize the potion color scheme for this time + */ +void +init_colors() +{ + register int i, j; + + for (i = 0; i < NCOLORS; i++) + used[i] = FALSE; + for (i = 0; i < MAXPOTIONS; i++) + { + do + j = rnd(NCOLORS); + until (!used[j]); + used[j] = TRUE; + p_colors[i] = rainbow[j]; + } +} + +/* + * init_names: + * Generate the names of the various scrolls + */ +#define MAXNAME 40 /* Max number of characters in a name */ + +void +init_names() +{ + register int nsyl; + register char *cp, *sp; + register int i, nwords; + + for (i = 0; i < MAXSCROLLS; i++) + { + cp = prbuf; + nwords = rnd(3) + 2; + while (nwords--) + { + nsyl = rnd(3) + 1; + while (nsyl--) + { + sp = sylls[rnd((sizeof sylls) / (sizeof (char *)))]; + if (&cp[strlen(sp)] > &prbuf[MAXNAME]) + break; + while (*sp) + *cp++ = *sp++; + } + *cp++ = ' '; + } + *--cp = '\0'; + s_names[i] = (char *) malloc((unsigned) strlen(prbuf)+1); + strcpy(s_names[i], prbuf); + } +} + +/* + * init_stones: + * Initialize the ring stone setting scheme for this time + */ +void +init_stones() +{ + register int i, j; + + for (i = 0; i < NSTONES; i++) + used[i] = FALSE; + for (i = 0; i < MAXRINGS; i++) + { + do + j = rnd(NSTONES); + until (!used[j]); + used[j] = TRUE; + r_stones[i] = stones[j].st_name; + ring_info[i].oi_worth += stones[j].st_value; + } +} + +/* + * init_materials: + * Initialize the construction materials for wands and staffs + */ +void +init_materials() +{ + register int i, j; + register char *str; + static bool metused[NMETAL]; + + for (i = 0; i < NWOOD; i++) + used[i] = FALSE; + for (i = 0; i < NMETAL; i++) + metused[i] = FALSE; + for (i = 0; i < MAXSTICKS; i++) + { + for (;;) + if (rnd(2) == 0) + { + j = rnd(NMETAL); + if (!metused[j]) + { + ws_type[i] = "wand"; + str = metal[j]; + metused[j] = TRUE; + break; + } + } + else + { + j = rnd(NWOOD); + if (!used[j]) + { + ws_type[i] = "staff"; + str = wood[j]; + used[j] = TRUE; + break; + } + } + ws_made[i] = str; + } +} + +#ifdef MASTER +# define NT NUMTHINGS, "things" +# define MP MAXPOTIONS, "potions" +# define MS MAXSCROLLS, "scrolls" +# define MR MAXRINGS, "rings" +# define MWS MAXSTICKS, "sticks" +# define MW MAXWEAPONS, "weapons" +# define MA MAXARMORS, "armor" +#else +# define NT NUMTHINGS +# define MP MAXPOTIONS +# define MS MAXSCROLLS +# define MR MAXRINGS +# define MWS MAXSTICKS +# define MW MAXWEAPONS +# define MA MAXARMORS +#endif + +/* + * sumprobs: + * Sum up the probabilities for items appearing + */ +void +sumprobs(struct obj_info *info, int bound +#ifdef MASTER + , char *name +#endif +) +{ +#ifdef MASTER + struct obj_info *start = info; +#endif + struct obj_info *endp; + + endp = info + bound; + while (++info < endp) + info->oi_prob += (info - 1)->oi_prob; +#ifdef MASTER + badcheck(name, start, bound); +#endif +} + +/* + * init_probs: + * Initialize the probabilities for the various items + */ +void +init_probs() +{ + sumprobs(things, NT); + sumprobs(pot_info, MP); + sumprobs(scr_info, MS); + sumprobs(ring_info, MR); + sumprobs(ws_info, MWS); + sumprobs(weap_info, MW); + sumprobs(arm_info, MA); +} + +#ifdef MASTER +/* + * badcheck: + * Check to see if a series of probabilities sums to 100 + */ +void +badcheck(char *name, struct obj_info *info, int bound) +{ + register struct obj_info *end; + + if (info[bound - 1].oi_prob == 100) + return; + printf("\nBad percentages for %s (bound = %d):\n", name, bound); + for (end = &info[bound]; info < end; info++) + printf("%3d%% %s\n", info->oi_prob, info->oi_name); + printf("[hit RETURN to continue]"); + fflush(stdout); + while (getchar() != '\n') + continue; +} +#endif + +/* + * pick_color: + * If he is halucinating, pick a random color name and return it, + * otherwise return the given color. + */ +char * +pick_color(char *col) +{ + return (on(player, ISHALU) ? rainbow[rnd(NCOLORS)] : col); +} diff --git a/src/cc/rogue/install-sh b/src/cc/rogue/install-sh new file mode 100755 index 000000000..4d4a9519e --- /dev/null +++ b/src/cc/rogue/install-sh @@ -0,0 +1,323 @@ +#!/bin/sh +# install - install a program, script, or datafile + +scriptversion=2005-05-14.22 + +# This originates from X11R5 (mit/util/scripts/install.sh), which was +# later released in X11R6 (xc/config/util/install.sh) with the +# following copyright and license. +# +# Copyright (C) 1994 X Consortium +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- +# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# +# Except as contained in this notice, the name of the X Consortium shall not +# be used in advertising or otherwise to promote the sale, use or other deal- +# ings in this Software without prior written authorization from the X Consor- +# tium. +# +# +# FSF changes to this file are in the public domain. +# +# Calling this script install-sh is preferred over install.sh, to prevent +# `make' implicit rules from creating a file called install from it +# when there is no Makefile. +# +# This script is compatible with the BSD install script, but was written +# from scratch. It can only install one file at a time, a restriction +# shared with many OS's install programs. + +# set DOITPROG to echo to test this script + +# Don't use :- since 4.3BSD and earlier shells don't like it. +doit="${DOITPROG-}" + +# put in absolute paths if you don't have them in your path; or use env. vars. + +mvprog="${MVPROG-mv}" +cpprog="${CPPROG-cp}" +chmodprog="${CHMODPROG-chmod}" +chownprog="${CHOWNPROG-chown}" +chgrpprog="${CHGRPPROG-chgrp}" +stripprog="${STRIPPROG-strip}" +rmprog="${RMPROG-rm}" +mkdirprog="${MKDIRPROG-mkdir}" + +chmodcmd="$chmodprog 0755" +chowncmd= +chgrpcmd= +stripcmd= +rmcmd="$rmprog -f" +mvcmd="$mvprog" +src= +dst= +dir_arg= +dstarg= +no_target_directory= + +usage="Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE + or: $0 [OPTION]... SRCFILES... DIRECTORY + or: $0 [OPTION]... -t DIRECTORY SRCFILES... + or: $0 [OPTION]... -d DIRECTORIES... + +In the 1st form, copy SRCFILE to DSTFILE. +In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. +In the 4th, create DIRECTORIES. + +Options: +-c (ignored) +-d create directories instead of installing files. +-g GROUP $chgrpprog installed files to GROUP. +-m MODE $chmodprog installed files to MODE. +-o USER $chownprog installed files to USER. +-s $stripprog installed files. +-t DIRECTORY install into DIRECTORY. +-T report an error if DSTFILE is a directory. +--help display this help and exit. +--version display version info and exit. + +Environment variables override the default commands: + CHGRPPROG CHMODPROG CHOWNPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG +" + +while test -n "$1"; do + case $1 in + -c) shift + continue;; + + -d) dir_arg=true + shift + continue;; + + -g) chgrpcmd="$chgrpprog $2" + shift + shift + continue;; + + --help) echo "$usage"; exit $?;; + + -m) chmodcmd="$chmodprog $2" + shift + shift + continue;; + + -o) chowncmd="$chownprog $2" + shift + shift + continue;; + + -s) stripcmd=$stripprog + shift + continue;; + + -t) dstarg=$2 + shift + shift + continue;; + + -T) no_target_directory=true + shift + continue;; + + --version) echo "$0 $scriptversion"; exit $?;; + + *) # When -d is used, all remaining arguments are directories to create. + # When -t is used, the destination is already specified. + test -n "$dir_arg$dstarg" && break + # Otherwise, the last argument is the destination. Remove it from $@. + for arg + do + if test -n "$dstarg"; then + # $@ is not empty: it contains at least $arg. + set fnord "$@" "$dstarg" + shift # fnord + fi + shift # arg + dstarg=$arg + done + break;; + esac +done + +if test -z "$1"; then + if test -z "$dir_arg"; then + echo "$0: no input file specified." >&2 + exit 1 + fi + # It's OK to call `install-sh -d' without argument. + # This can happen when creating conditional directories. + exit 0 +fi + +for src +do + # Protect names starting with `-'. + case $src in + -*) src=./$src ;; + esac + + if test -n "$dir_arg"; then + dst=$src + src= + + if test -d "$dst"; then + mkdircmd=: + chmodcmd= + else + mkdircmd=$mkdirprog + fi + else + # Waiting for this to be detected by the "$cpprog $src $dsttmp" command + # might cause directories to be created, which would be especially bad + # if $src (and thus $dsttmp) contains '*'. + if test ! -f "$src" && test ! -d "$src"; then + echo "$0: $src does not exist." >&2 + exit 1 + fi + + if test -z "$dstarg"; then + echo "$0: no destination specified." >&2 + exit 1 + fi + + dst=$dstarg + # Protect names starting with `-'. + case $dst in + -*) dst=./$dst ;; + esac + + # If destination is a directory, append the input filename; won't work + # if double slashes aren't ignored. + if test -d "$dst"; then + if test -n "$no_target_directory"; then + echo "$0: $dstarg: Is a directory" >&2 + exit 1 + fi + dst=$dst/`basename "$src"` + fi + fi + + # This sed command emulates the dirname command. + dstdir=`echo "$dst" | sed -e 's,/*$,,;s,[^/]*$,,;s,/*$,,;s,^$,.,'` + + # Make sure that the destination directory exists. + + # Skip lots of stat calls in the usual case. + if test ! -d "$dstdir"; then + defaultIFS=' + ' + IFS="${IFS-$defaultIFS}" + + oIFS=$IFS + # Some sh's can't handle IFS=/ for some reason. + IFS='%' + set x `echo "$dstdir" | sed -e 's@/@%@g' -e 's@^%@/@'` + shift + IFS=$oIFS + + pathcomp= + + while test $# -ne 0 ; do + pathcomp=$pathcomp$1 + shift + if test ! -d "$pathcomp"; then + $mkdirprog "$pathcomp" + # mkdir can fail with a `File exist' error in case several + # install-sh are creating the directory concurrently. This + # is OK. + test -d "$pathcomp" || exit + fi + pathcomp=$pathcomp/ + done + fi + + if test -n "$dir_arg"; then + $doit $mkdircmd "$dst" \ + && { test -z "$chowncmd" || $doit $chowncmd "$dst"; } \ + && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } \ + && { test -z "$stripcmd" || $doit $stripcmd "$dst"; } \ + && { test -z "$chmodcmd" || $doit $chmodcmd "$dst"; } + + else + dstfile=`basename "$dst"` + + # Make a couple of temp file names in the proper directory. + dsttmp=$dstdir/_inst.$$_ + rmtmp=$dstdir/_rm.$$_ + + # Trap to clean up those temp files at exit. + trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 + trap '(exit $?); exit' 1 2 13 15 + + # Copy the file name to the temp name. + $doit $cpprog "$src" "$dsttmp" && + + # and set any options; do chmod last to preserve setuid bits. + # + # If any of these fail, we abort the whole thing. If we want to + # ignore errors from any of these, just make sure not to ignore + # errors from the above "$doit $cpprog $src $dsttmp" command. + # + { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } \ + && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } \ + && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } \ + && { test -z "$chmodcmd" || $doit $chmodcmd "$dsttmp"; } && + + # Now rename the file to the real destination. + { $doit $mvcmd -f "$dsttmp" "$dstdir/$dstfile" 2>/dev/null \ + || { + # The rename failed, perhaps because mv can't rename something else + # to itself, or perhaps because mv is so ancient that it does not + # support -f. + + # Now remove or move aside any old file at destination location. + # We try this two ways since rm can't unlink itself on some + # systems and the destination file might be busy for other + # reasons. In this case, the final cleanup might fail but the new + # file should still install successfully. + { + if test -f "$dstdir/$dstfile"; then + $doit $rmcmd -f "$dstdir/$dstfile" 2>/dev/null \ + || $doit $mvcmd -f "$dstdir/$dstfile" "$rmtmp" 2>/dev/null \ + || { + echo "$0: cannot unlink or rename $dstdir/$dstfile" >&2 + (exit 1); exit 1 + } + else + : + fi + } && + + # Now rename the file to the real destination. + $doit $mvcmd "$dsttmp" "$dstdir/$dstfile" + } + } + fi || { (exit 1); exit 1; } +done + +# The final little trick to "correctly" pass the exit status to the exit trap. +{ + (exit 0); exit 0 +} + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-end: "$" +# End: diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c new file mode 100644 index 000000000..0e9347a70 --- /dev/null +++ b/src/cc/rogue/io.c @@ -0,0 +1,327 @@ +/* + * Various input/output functions + * + * @(#)io.c 4.32 (Berkeley) 02/05/99 + */ + +#include +#include +#include +#include +#include "rogue.h" + +/* + * msg: + * Display a message at the top of the screen. + */ +#define MAXMSG (NUMCOLS - sizeof "--More--") + +static char msgbuf[2*MAXMSG+1]; +static int newpos = 0; + +/* VARARGS1 */ +int +msg(struct rogue_state *rs,char *fmt, ...) +{ + va_list args; + + /* + * if the string is "", just clear the line + */ + if (*fmt == '\0') + { + move(0, 0); + clrtoeol(); + mpos = 0; + return ~ESCAPE; + } + /* + * otherwise add to the message and flush it out + */ + va_start(args, fmt); + doadd(rs,fmt, args); + va_end(args); + return endmsg(rs); +} + +/* + * addmsg: + * Add things to the current message + */ +/* VARARGS1 */ +void +addmsg(struct rogue_state *rs,char *fmt, ...) +{ + va_list args; + + va_start(args, fmt); + doadd(rs,fmt, args); + va_end(args); +} + +/* + * endmsg: + * Display a new msg (giving him a chance to see the previous one + * if it is up there with the --More--) + */ +int +endmsg(struct rogue_state *rs) +{ + char ch; + + if (save_msg) + strcpy(huh, msgbuf); + if (mpos) + { + look(rs,FALSE); + mvaddstr(0, mpos, "--More--"); + refresh(); + if (!msg_esc) + wait_for(rs,' '); + else + { + while ((ch = readchar(rs)) != ' ') + if (ch == ESCAPE) + { + msgbuf[0] = '\0'; + mpos = 0; + newpos = 0; + msgbuf[0] = '\0'; + return ESCAPE; + } + } + } + /* + * All messages should start with uppercase, except ones that + * start with a pack addressing character + */ + if (islower(msgbuf[0]) && !lower_msg && msgbuf[1] != ')') + msgbuf[0] = (char) toupper(msgbuf[0]); + mvaddstr(0, 0, msgbuf); + clrtoeol(); + mpos = newpos; + newpos = 0; + msgbuf[0] = '\0'; + refresh(); + return ~ESCAPE; +} + +/* + * doadd: + * Perform an add onto the message buffer + */ +void +doadd(struct rogue_state *rs,char *fmt, va_list args) +{ + static char buf[MAXSTR]; + + /* + * Do the printf into buf + */ + vsprintf(buf, fmt, args); + if (strlen(buf) + newpos >= MAXMSG) + endmsg(rs); + strcat(msgbuf, buf); + newpos = (int) strlen(msgbuf); +} + +/* + * step_ok: + * Returns true if it is ok to step on ch + */ +int +step_ok(int ch) +{ + switch (ch) + { + case ' ': + case '|': + case '-': + return FALSE; + default: + return (!isalpha(ch)); + } +} + +/* + * readchar: + * Reads and returns a character, checking for gross input errors + */ +char +readchar(struct rogue_state *rs) +{ + char ch = -1; + if ( rs != 0 && rs->guiflag == 0 ) + { + if ( rs->ind < rs->numkeys ) + { + if ( rs->ind == rs->numkeys-1 ) + rs->replaydone = (uint32_t)time(NULL); + return(rs->keystrokes[rs->ind++]); + } + fatal("replay finished but readchar called\n"); + return(' '); + } + if ( rs == 0 || rs->guiflag != 0 ) + { + ch = (char) md_readchar(); + + if (ch == 3) + { + quit(0); + return(27); + } + if ( rs != 0 && rs->guiflag != 0 ) + { + if (rs->num < sizeof(rs->buffered) ) + { + rs->buffered[rs->num++] = ch; + if ( rs->num > (sizeof(rs->buffered)*9)/10 && rs->needflush == 0 ) + rs->needflush = (uint32_t)time(NULL); + } else fprintf(stderr,"buffer filled without flushed\n"); + } + } else fprintf(stderr,"readchar rs.%p non-gui error?\n",rs); + return(ch); +} + +/*char readchar() +{ + static FILE *keystrokefp; int c; + + if ( keystrokefp == 0 ) + keystrokefp = fopen("keystrokes","rb"); + if ( keystrokefp != 0 ) + { + if ( (c= fgetc(keystrokefp)) == EOF ) + eofflag = 1; + else return(c); + } else eofflag = 1; + ch = (char) md_readchar(); + + if (ch == 3) + { + quit(0); + return(27); + } + { + static FILE *replayfp; + if ( replayfp == 0 ) + replayfp = fopen("replay","wb"); + if ( replayfp != 0 ) + fputc(ch,replayfp), fflush(replayfp); + } + return(ch); +}*/ + +/* + * status: + * Display the important stats line. Keep the cursor where it was. + */ +void +status(struct rogue_state *rs) +{ + register int oy, ox, temp; + static int hpwidth = 0; + static int s_hungry = 0; + static int s_lvl = 0; + static int s_pur = -1; + static int s_hp = 0; + static int s_arm = 0; + static str_t s_str = 0; + static int s_exp = 0; + static char *state_name[] = + { + "", "Hungry", "Weak", "Faint" + }; + + /* + * If nothing has changed since the last status, don't + * bother. + */ + temp = (cur_armor != NULL ? cur_armor->o_arm : pstats.s_arm); + if (s_hp == pstats.s_hpt && s_exp == pstats.s_exp && s_pur == purse + && s_arm == temp && s_str == pstats.s_str && s_lvl == level + && s_hungry == hungry_state + && !stat_msg + ) + return; + + s_arm = temp; + + getyx(stdscr, oy, ox); + if (s_hp != max_hp) + { + temp = max_hp; + s_hp = max_hp; + for (hpwidth = 0; temp; hpwidth++) + temp /= 10; + } + + /* + * Save current status + */ + s_lvl = level; + s_pur = purse; + s_hp = pstats.s_hpt; + s_str = pstats.s_str; + s_exp = pstats.s_exp; + s_hungry = hungry_state; + + if (stat_msg) + { + move(0, 0); + msg(rs,"Level: %d Gold: %-5d Hp: %*d(%*d) Str: %2d(%d) Arm: %-2d Exp: %d/%ld %s", + level, purse, hpwidth, pstats.s_hpt, hpwidth, max_hp, pstats.s_str, + max_stats.s_str, 10 - s_arm, pstats.s_lvl, pstats.s_exp, + state_name[hungry_state]); + } + else + { + move(STATLINE, 0); + + printw("Level: %d Gold: %-5d Hp: %*d(%*d) Str: %2d(%d) Arm: %-2d Exp: %d/%d %s", + level, purse, hpwidth, pstats.s_hpt, hpwidth, max_hp, pstats.s_str, + max_stats.s_str, 10 - s_arm, pstats.s_lvl, pstats.s_exp, + state_name[hungry_state]); + } + + clrtoeol(); + move(oy, ox); +} + +/* + * wait_for + * Sit around until the guy types the right key + */ +void +wait_for(struct rogue_state *rs,int ch) +{ + register char c; + + if (ch == '\n') + while ((c = readchar(rs)) != '\n' && c != '\r') + continue; + else + while (readchar(rs) != ch) + continue; +} + +/* + * show_win: + * Function used to display a window and wait before returning + */ +void +show_win(struct rogue_state *rs,char *message) +{ + WINDOW *win; + + win = hw; + wmove(win, 0, 0); + waddstr(win, message); + touchwin(win); + wmove(win, hero.y, hero.x); + wrefresh(win); + wait_for(rs,' '); + clearok(curscr, TRUE); + touchwin(stdscr); +} diff --git a/src/cc/rogue/list.c b/src/cc/rogue/list.c new file mode 100644 index 000000000..6c069d06e --- /dev/null +++ b/src/cc/rogue/list.c @@ -0,0 +1,113 @@ +/* + * Functions for dealing with linked lists of goodies + * + * @(#)list.c 4.12 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include "rogue.h" + +#ifdef MASTER +int total = 0; /* total dynamic memory bytes */ +#endif + +/* + * detach: + * takes an item out of whatever linked list it might be in + */ + +void +_detach(THING **list, THING *item) +{ + if (*list == item) + *list = next(item); + if (prev(item) != NULL) + item->l_prev->l_next = next(item); + if (next(item) != NULL) + item->l_next->l_prev = prev(item); + item->l_next = NULL; + item->l_prev = NULL; +} + +/* + * _attach: + * add an item to the head of a list + */ + +void +_attach(THING **list, THING *item) +{ + if (*list != NULL) + { + item->l_next = *list; + (*list)->l_prev = item; + item->l_prev = NULL; + } + else + { + item->l_next = NULL; + item->l_prev = NULL; + } + *list = item; +} + +/* + * _free_list: + * Throw the whole blamed thing away + */ + +void +_free_list(THING **ptr) +{ + THING *item; + + while (*ptr != NULL) + { + item = *ptr; + *ptr = next(item); + discard(item); + } +} + +/* + * discard: + * Free up an item + */ + +void +discard(THING *item) +{ +#ifdef MASTER + total--; +#endif + free((char *) item); +} + +/* + * new_item + * Get a new item with a specified size + */ +THING * +new_item(void) +{ + THING *item; + +#ifdef MASTER + if ((item = calloc(1, sizeof *item)) == NULL) + msg(rs,"ran out of memory after %d items", total); + else + total++; +#else + item = calloc(1, sizeof *item); +#endif + item->l_next = NULL; + item->l_prev = NULL; + return item; +} diff --git a/src/cc/rogue/mach_dep.c b/src/cc/rogue/mach_dep.c new file mode 100644 index 000000000..7f1af9c67 --- /dev/null +++ b/src/cc/rogue/mach_dep.c @@ -0,0 +1,457 @@ +/* + * Various installation dependent routines + * + * @(#)mach_dep.c 4.37 (Berkeley) 05/23/83 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +/* + * The various tuneable defines are: + * + * SCOREFILE Where/if the score file should live. + * ALLSCORES Score file is top ten scores, not top ten + * players. This is only useful when only a few + * people will be playing; otherwise the score file + * gets hogged by just a few people. + * NUMSCORES Number of scores in the score file (default 10). + * NUMNAME String version of NUMSCORES (first character + * should be capitalized) (default "Ten"). + * MAXLOAD What (if any) the maximum load average should be + * when people are playing. Since it is divided + * by 10, to specify a load limit of 4.0, MAXLOAD + * should be "40". If defined, then + * LOADAV Should it use it's own routine to get + * the load average? + * NAMELIST If so, where does the system namelist + * hide? + * MAXUSERS What (if any) the maximum user count should be + * when people are playing. If defined, then + * UCOUNT Should it use it's own routine to count + * users? + * UTMP If so, where does the user list hide? + * CHECKTIME How often/if it should check during the game + * for high load average. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "extern.h" + +#define NOOP(x) (x += 0) + +# ifndef NUMSCORES +# define NUMSCORES 10 +# define NUMNAME "Ten" +# endif + +unsigned int numscores = NUMSCORES; +char *Numname = NUMNAME; + +# ifdef ALLSCORES +bool allscore = TRUE; +# else /* ALLSCORES */ +bool allscore = FALSE; +# endif /* ALLSCORES */ + +#ifdef CHECKTIME +static int num_checks; /* times we've gone over in checkout() */ +#endif /* CHECKTIME */ + +/* + * init_check: + * Check out too see if it is proper to play the game now + */ + +void +init_check() +{ +#if defined(MAXLOAD) || defined(MAXUSERS) + if (too_much()) + { + printf("Sorry, %s, but the system is too loaded now.\n", whoami); + printf("Try again later. Meanwhile, why not enjoy a%s %s?\n", + vowelstr(fruit), fruit); + if (author()) + printf("However, since you're a good guy, it's up to you\n"); + else + exit(1); + } +#endif +} + +/* + * open_score: + * Open up the score file for future use + */ + +void +open_score() +{ +#ifdef SCOREFILE + char *scorefile = SCOREFILE; + /* + * We drop setgid privileges after opening the score file, so subsequent + * open()'s will fail. Just reuse the earlier filehandle. + */ + + if (scoreboard != NULL) { + rewind(scoreboard); + return; + } + + scoreboard = fopen(scorefile, "r+"); + + if ((scoreboard == NULL) && (errno == ENOENT)) + { + scoreboard = fopen(scorefile, "w+"); + md_chmod(scorefile,0664); + } + + if (scoreboard == NULL) { + fprintf(stderr, "Could not open %s for writing: %s\n", scorefile, strerror(errno)); + fflush(stderr); + } +#else + scoreboard = NULL; +#endif +} + +/* + * setup: + * Get starting setup for all games + */ + +void +setup() +{ +#ifdef CHECKTIME + int checkout(); +#endif + +#ifdef DUMP + md_onsignal_autosave(); +#else + md_onsignal_default(); +#endif + +#ifdef CHECKTIME + md_start_checkout_timer(CHECKTIME*60); + num_checks = 0; +#endif + + raw(); /* Raw mode */ + noecho(); /* Echo off */ + keypad(stdscr,1); + getltchars(); /* get the local tty chars */ +} + +/* + * getltchars: + * Get the local tty chars for later use + */ + +void +getltchars() +{ + got_ltc = TRUE; + orig_dsusp = md_dsuspchar(); + md_setdsuspchar( md_suspchar() ); +} + +/* + * resetltchars: + * Reset the local tty chars to original values. + */ +void +resetltchars(void) +{ + if (got_ltc) { + md_setdsuspchar(orig_dsusp); + } +} + +/* + * playltchars: + * Set local tty chars to the values we use when playing. + */ +void +playltchars(void) +{ + if (got_ltc) { + md_setdsuspchar( md_suspchar() ); + } +} + +/* + * start_score: + * Start the scoring sequence + */ + +void +start_score() +{ +#ifdef CHECKTIME + md_stop_checkout_timer(); +#endif +} + +/* + * is_symlink: + * See if the file has a symbolic link + */ +bool +is_symlink(char *sp) +{ +#ifdef S_IFLNK + struct stat sbuf2; + + if (lstat(sp, &sbuf2) < 0) + return FALSE; + else + return ((sbuf2.st_mode & S_IFMT) != S_IFREG); +#else + NOOP(sp); + return FALSE; +#endif +} + +#if defined(MAXLOAD) || defined(MAXUSERS) +/* + * too_much: + * See if the system is being used too much for this game + */ +bool +too_much() +{ +#ifdef MAXLOAD + double avec[3]; +#else + int cnt; +#endif + +#ifdef MAXLOAD + md_loadav(avec); + if (avec[1] > (MAXLOAD / 10.0)) + return TRUE; +#endif +#ifdef MAXUSERS + if (ucount() > MAXUSERS) + return TRUE; +#endif + return FALSE; +} + +/* + * author: + * See if a user is an author of the program + */ +bool +author() +{ +#ifdef MASTER + if (wizard) + return TRUE; +#endif + switch (md_getuid()) + { + case -1: + return TRUE; + default: + return FALSE; + } +} +#endif + +#ifdef CHECKTIME +/* + * checkout: + * Check each CHECKTIME seconds to see if the load is too high + */ + +checkout(struct rogue_state *rs,int sig) +{ + static char *msgs[] = { + "The load is too high to be playing. Please leave in %0.1f minutes", + "Please save your game. You have %0.1f minutes", + "Last warning. You have %0.1f minutes to leave", + }; + int checktime; + + if (too_much()) + { + if (author()) + { + num_checks = 1; + chmsg(rs,"The load is rather high, O exaulted one"); + } + else if (num_checks++ == 3) + fatal("Sorry. You took too long. You are dead\n"); + checktime = (CHECKTIME * 60) / num_checks; + chmsg(rs,msgs[num_checks - 1], ((double) checktime / 60.0)); + } + else + { + if (num_checks) + { + num_checks = 0; + chmsg(rs,"The load has dropped back down. You have a reprieve"); + } + checktime = (CHECKTIME * 60); + } + + md_start_checkout_timer(checktime); +} + +/* + * chmsg: + * checkout()'s version of msg. If we are in the middle of a + * shell, do a printf instead of a msg to a the refresh. + */ +/* VARARGS1 */ + +chmsg(struct rogue_state *rs,char *fmt, int arg) +{ + if (!in_shell) + msg(rs,fmt, arg); + else + { + printf(fmt, arg); + putchar('\n'); + fflush(stdout); + } +} +#endif + +#ifdef UCOUNT +/* + * ucount: + * count number of users on the system + */ +#include + +struct utmp buf; + +int +ucount() +{ + struct utmp *up; + FILE *utmp; + int count; + + if ((utmp = fopen(UTMP, "r")) == NULL) + return 0; + + up = &buf; + count = 0; + + while (fread(up, 1, sizeof (*up), utmp) > 0) + if (buf.ut_name[0] != '\0') + count++; + fclose(utmp); + return count; +} +#endif + +/* + * lock_sc: + * lock the score file. If it takes too long, ask the user if + * they care to wait. Return TRUE if the lock is successful. + */ +static FILE *lfd = NULL; +bool +lock_sc() +{ +#if defined(SCOREFILE) && defined(LOCKFILE) + int cnt; + static struct stat sbuf; + char *lockfile = LOCKFILE; + +over: + if ((lfd=fopen(lockfile, "w+")) != NULL) + return TRUE; + for (cnt = 0; cnt < 5; cnt++) + { + md_sleep(1); + if ((lfd=fopen(lockfile, "w+")) != NULL) + return TRUE; + } + if (stat(lockfile, &sbuf) < 0) + { + lfd=fopen(lockfile, "w+"); + return TRUE; + } + if (time(NULL) - sbuf.st_mtime > 10) + { + if (md_unlink(lockfile) < 0) + return FALSE; + goto over; + } + else + { + printf("The score file is very busy. Do you want to wait longer\n"); + printf("for it to become free so your score can get posted?\n"); + printf("If so, type \"y\"\n"); + (void) fgets(prbuf, MAXSTR, stdin); + if (prbuf[0] == 'y') + for (;;) + { + if ((lfd=fopen(lockfile, "w+")) != 0) + return TRUE; + if (stat(lockfile, &sbuf) < 0) + { + lfd=fopen(lockfile, "w+"); + return TRUE; + } + if (time(NULL) - sbuf.st_mtime > 10) + { + if (md_unlink(lockfile) < 0) + return FALSE; + } + md_sleep(1); + } + else + return FALSE; + } +#else + return TRUE; +#endif +} + +/* + * unlock_sc: + * Unlock the score file + */ + +void +unlock_sc() +{ +#if defined(SCOREFILE) && defined(LOCKFILE) + if (lfd != NULL) + fclose(lfd); + lfd = NULL; + md_unlink(LOCKFILE); +#endif +} + +/* + * flush_type: + * Flush typeahead for traps, etc. + */ + +void +flush_type() +{ + flushinp(); +} diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c new file mode 100644 index 000000000..681d51e31 --- /dev/null +++ b/src/cc/rogue/main.c @@ -0,0 +1,49 @@ +/****************************************************************************** + * Copyright © 2014-2019 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. * + * * + ******************************************************************************/ + + + +// creategame, register (inventory + baton + buyin), progress (events + statehash + [compr state]?), claimwin +// create game buyin, newbie flag, 10 blocks registration seed is starting blockhash! +// inheritance of items across games! +// binding tokens to specific items to allow for built in market +// pubkey token inventory creates items can be used for a specific campaign +// player wins buyins + ingame gold -> ROGUE + ingame items -> tokens via 1 vout per item to be spent into a token opreturn + +#include +#include +#include + +int32_t rogue_replay(uint64_t seed); +int rogue(int argc, char **argv, char **envp); + +int main(int argc, char **argv, char **envp) +{ + uint64_t seed; FILE *fp = 0; + if ( argc > 1 && (fp=fopen(argv[1],"rb")) == 0 ) + { + seed = atol(argv[1]); + fprintf(stderr,"replay %llu\n",(long long)seed); + return(rogue_replay(seed)); + } + else + { + if ( fp != 0 ) + fclose(fp); + return(rogue(argc,argv,envp)); + } +} + + diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c new file mode 100644 index 000000000..72fdbb75e --- /dev/null +++ b/src/cc/rogue/mdport.c @@ -0,0 +1,1432 @@ +/* + mdport.c - Machine Dependent Code for Porting Unix/Curses games + + Copyright (C) 2005 Nicholas J. Kisseberth + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name(s) of the author(s) nor the names of other contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTORS ``AS IS'' AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. +*/ + +#include +#include + +#if defined(_WIN32) +#include +#include +#include +#include +#pragma warning( disable: 4201 ) +#include +#pragma warning( default: 4201 ) +#include +#undef MOUSE_MOVED +#endif + +#include +#include "extern.h" + +#if defined(HAVE_SYS_TYPES) +#include +#endif + +#if defined(HAVE_PROCESS_H) +#include +#endif + +#if defined(HAVE_PWD_H) +#include +#endif + +#if defined(HAVE_SYS_UTSNAME) +#include +#endif + +#if defined(HAVE_ARPA_INET_H) +#include /* Solaris 2.8 required this for htonl() and ntohl() */ +#endif + +#if defined(HAVE_TERMIOS_H) +#include +#endif + +#if defined(HAVE_UNISTD_H) +#ifndef __USE_GNU +#define __USE_GNU +#include +#undef __USE_GNU +#else +#include +#endif +#endif + +#include /* AIX requires curses.h be included before term.h */ + +#if defined(HAVE_TERM_H) +#include +#elif defined(HAVE_NCURSES_TERM_H) +#include +#endif + +#if defined(HAVE_WORKING_FORK) +#include +#endif + +#include +#include +#include +#include +#include +#include "extern.h" + +#if !defined(PATH_MAX) && defined(_MAX_PATH) +#define PATH_MAX _MAX_PATH +#endif + +#if !defined(PATH_MAX) && defined(_PATH_MAX) +#define PATH_MAX _PATH_MAX +#endif + +#define NOOP(x) (x += 0) + +void +md_init() +{ +#if defined(__INTERIX) + char *term; + + term = getenv("TERM"); + + if (term == NULL) + setenv("TERM","interix"); +#elif defined(__DJGPP__) + _fmode = _O_BINARY; +#elif defined(_WIN32) + _fmode = _O_BINARY; +#endif + +#if defined(HAVE_ESCDELAY) || defined(NCURSES_VERSION) + ESCDELAY=64; +#endif + +#if defined(DUMP) + md_onsignal_default(); +#else + md_onsignal_exit(); +#endif +} + +void +md_onsignal_default() +{ +#ifdef SIGHUP + signal(SIGHUP, SIG_DFL); +#endif +#ifdef SIGQUIT + signal(SIGQUIT, SIG_DFL); +#endif +#ifdef SIGILL + signal(SIGILL, SIG_DFL); +#endif +#ifdef SIGTRAP + signal(SIGTRAP, SIG_DFL); +#endif +#ifdef SIGIOT + signal(SIGIOT, SIG_DFL); +#endif +#ifdef SIGEMT + signal(SIGEMT, SIG_DFL); +#endif +#ifdef SIGFPE + signal(SIGFPE, SIG_DFL); +#endif +#ifdef SIGBUS + signal(SIGBUS, SIG_DFL); +#endif +#ifdef SIGSEGV + signal(SIGSEGV, SIG_DFL); +#endif +#ifdef SIGSYS + signal(SIGSYS, SIG_DFL); +#endif +#ifdef SIGTERM + signal(SIGTERM, SIG_DFL); +#endif +} + +void +md_onsignal_exit() +{ +#ifdef SIGHUP + signal(SIGHUP, SIG_DFL); +#endif +#ifdef SIGQUIT + signal(SIGQUIT, exit); +#endif +#ifdef SIGILL + signal(SIGILL, exit); +#endif +#ifdef SIGTRAP + signal(SIGTRAP, exit); +#endif +#ifdef SIGIOT + signal(SIGIOT, exit); +#endif +#ifdef SIGEMT + signal(SIGEMT, exit); +#endif +#ifdef SIGFPE + signal(SIGFPE, exit); +#endif +#ifdef SIGBUS + signal(SIGBUS, exit); +#endif +#ifdef SIGSEGV + signal(SIGSEGV, exit); +#endif +#ifdef SIGSYS + signal(SIGSYS, exit); +#endif +#ifdef SIGTERM + signal(SIGTERM, exit); +#endif +} + +void +md_onsignal_autosave() +{ +#ifdef SIGHUP + signal(SIGHUP, auto_save); +#endif +#ifdef SIGQUIT + signal(SIGQUIT, endit); +#endif +#ifdef SIGILL + signal(SIGILL, auto_save); +#endif +#ifdef SIGTRAP + signal(SIGTRAP, auto_save); +#endif +#ifdef SIGIOT + signal(SIGIOT, auto_save); +#endif +#ifdef SIGEMT + signal(SIGEMT, auto_save); +#endif +#ifdef SIGFPE + signal(SIGFPE, auto_save); +#endif +#ifdef SIGBUS + signal(SIGBUS, auto_save); +#endif +#ifdef SIGSEGV + signal(SIGSEGV, auto_save); +#endif +#ifdef SIGSYS + signal(SIGSYS, auto_save); +#endif +#ifdef SIGTERM + signal(SIGTERM, auto_save); +#endif +#ifdef SIGINT + signal(SIGINT, quit); +#endif +} + +int +md_hasclreol() +{ +#if defined(clr_eol) +#ifdef NCURSES_VERSION + if (cur_term == NULL) + return(0); + if (cur_term->type.Strings == NULL) + return(0); +#endif + return((clr_eol != NULL) && (*clr_eol != 0)); +#elif defined(__PDCURSES__) + return(TRUE); +#else + return((CE != NULL) && (*CE != 0)); +#endif +} + +void +md_putchar(int c) +{ + putchar(c); +} + +#ifdef _WIN32 +static int md_standout_mode = 0; +#endif + +void +md_raw_standout() +{ +#ifdef _WIN32 + CONSOLE_SCREEN_BUFFER_INFO csbiInfo; + HANDLE hStdout; + WORD fgattr,bgattr; + + if (md_standout_mode == 0) + { + hStdout = GetStdHandle(STD_OUTPUT_HANDLE); + GetConsoleScreenBufferInfo(hStdout, &csbiInfo); + fgattr = (csbiInfo.wAttributes & 0xF); + bgattr = (csbiInfo.wAttributes & 0xF0); + SetConsoleTextAttribute(hStdout,(fgattr << 4) | (bgattr >> 4)); + md_standout_mode = 1; + } +#elif defined(SO) + tputs(SO,0,md_putchar); + fflush(stdout); +#endif +} + +void +md_raw_standend() +{ +#ifdef _WIN32 + CONSOLE_SCREEN_BUFFER_INFO csbiInfo; + HANDLE hStdout; + WORD fgattr,bgattr; + + if (md_standout_mode == 1) + { + hStdout = GetStdHandle(STD_OUTPUT_HANDLE); + GetConsoleScreenBufferInfo(hStdout, &csbiInfo); + fgattr = (csbiInfo.wAttributes & 0xF); + bgattr = (csbiInfo.wAttributes & 0xF0); + SetConsoleTextAttribute(hStdout,(fgattr << 4) | (bgattr >> 4)); + md_standout_mode = 0; + } +#elif defined(SE) + tputs(SE,0,md_putchar); + fflush(stdout); +#endif +} + +int +md_unlink_open_file(char *file, FILE *inf) +{ +#ifdef _WIN32 + fclose(inf); + _chmod(file, 0600); + return( _unlink(file) ); +#else + return(unlink(file)); +#endif +} + +int +md_unlink(char *file) +{ +#ifdef _WIN32 + _chmod(file, 0600); + return( _unlink(file) ); +#else + return(unlink(file)); +#endif +} + +int +md_chmod(char *filename, int mode) +{ +#ifdef _WIN32 + return( _chmod(filename, mode) ); +#else + return( chmod(filename, mode) ); +#endif +} + +void +md_normaluser() +{ +#if defined(HAVE_GETGID) && defined(HAVE_GETUID) + gid_t realgid = getgid(); + uid_t realuid = getuid(); + +#if defined(HAVE_SETRESGID) + if (setresgid(-1, realgid, realgid) != 0) { +#elif defined (HAVE_SETREGID) + if (setregid(realgid, realgid) != 0) { +#elif defined (HAVE_SETGID) + if (setgid(realgid) != 0) { +#else + if (0) { +#endif + perror("Could not drop setgid privileges. Aborting."); + exit(1); + } + +#if defined(HAVE_SETRESUID) + if (setresuid(-1, realuid, realuid) != 0) { +#elif defined(HAVE_SETREUID) + if (setreuid(realuid, realuid) != 0) { +#elif defined(HAVE_SETUID) + if (setuid(realuid) != 0) { +#else + if (0) { +#endif + perror("Could not drop setuid privileges. Aborting."); + exit(1); + } +#endif +} + +int +md_getuid() +{ +#ifdef HAVE_GETUID + return( getuid() ); +#else + return(42); +#endif +} + +int +md_getpid() +{ +#ifdef _WIN32 + return( _getpid() ); +#else + return( getpid() ); +#endif +} + +char * +md_getusername() +{ + static char login[80]; + char *l = NULL; +#ifdef _WIN32 + LPSTR mybuffer; + DWORD size = UNLEN + 1; + TCHAR buffer[UNLEN + 1]; + + mybuffer = buffer; + GetUserName(mybuffer,&size); + l = mybuffer; +#elif defined(HAVE_GETPWUID)&& !defined(__DJGPP__) + struct passwd *pw; + + pw = getpwuid(getuid()); + + l = pw->pw_name; +#endif + + if ((l == NULL) || (*l == '\0')) + if ( (l = getenv("USERNAME")) == NULL ) + if ( (l = getenv("LOGNAME")) == NULL ) + if ( (l = getenv("USER")) == NULL ) + l = "nobody"; + + strncpy(login,l,80); + login[79] = 0; + + return(login); +} + +char * +md_gethomedir() +{ + static char homedir[PATH_MAX]; + char *h = NULL; + size_t len; +#if defined(_WIN32) + TCHAR szPath[PATH_MAX]; +#endif +#if defined(_WIN32) || defined(DJGPP) + char slash = '\\'; +#else + char slash = '/'; + struct passwd *pw; + pw = getpwuid(getuid()); + + h = pw->pw_dir; + + if (strcmp(h,"/") == 0) + h = NULL; +#endif + homedir[0] = 0; +#ifdef _WIN32 + if(SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, szPath))) + h = szPath; +#endif + + if ( (h == NULL) || (*h == '\0') ) + { + if ( (h = getenv("HOME")) == NULL ) + { + if ( (h = getenv("HOMEDRIVE")) == NULL) + h = ""; + else + { + strncpy(homedir,h,PATH_MAX-1); + homedir[PATH_MAX-1] = 0; + + if ( (h = getenv("HOMEPATH")) == NULL) + h = ""; + } + } + } + + + len = strlen(homedir); + strncat(homedir,h,PATH_MAX-len-1); + len = strlen(homedir); + + if ((len > 0) && (homedir[len-1] != slash)) { + homedir[len] = slash; + homedir[len+1] = 0; + } + + return(homedir); +} + +void +md_sleep(int s) +{ +#ifdef _WIN32 + Sleep(s); +#else + sleep(s); +#endif +} + +char * +md_getshell() +{ + static char shell[PATH_MAX]; + char *s = NULL; +#ifdef _WIN32 + char *def = "C:\\WINDOWS\\SYSTEM32\\CMD.EXE"; +#elif defined(__DJGPP__) + char *def = "C:\\COMMAND.COM"; +#else + char *def = "/bin/sh"; + struct passwd *pw; + pw = getpwuid(getuid()); + s = pw->pw_shell; +#endif + if ((s == NULL) || (*s == '\0')) + if ( (s = getenv("COMSPEC")) == NULL) + if ( (s = getenv("SHELL")) == NULL) + if ( (s = getenv("SystemRoot")) == NULL) + s = def; + + strncpy(shell,s,PATH_MAX); + shell[PATH_MAX-1] = 0; + + return(shell); +} + +int +md_shellescape() +{ +#if defined(HAVE_WORKING_FORK) + int ret_status; + int pid; + void (*myquit)(int); + void (*myend)(int); + char *sh; + + sh = md_getshell(); + + while((pid = fork()) < 0) + sleep(1); + + if (pid == 0) /* Shell Process */ + { + /* + * Set back to original user, just in case + */ + md_normaluser(); + execl(sh == NULL ? "/bin/sh" : sh, "shell", "-i", NULL); + perror("No shelly"); + _exit(-1); + } + else /* Application */ + { + myend = signal(SIGINT, SIG_IGN); +#ifdef SIGQUIT + myquit = signal(SIGQUIT, SIG_IGN); +#endif + while (wait(&ret_status) != pid) + continue; + + signal(SIGINT, myquit); +#ifdef SIGQUIT + signal(SIGQUIT, myend); +#endif + } + return(ret_status); +#elif defined(HAVE__SPAWNL) + return((int)_spawnl(_P_WAIT,md_getshell(),"shell",NULL,0)); +#elif defined(HAVE_SPAWNL) + return ( spawnl(P_WAIT,md_getshell(),"shell",NULL,0) ); +#else + return(0); +#endif +} + +int +directory_exists(char *dirname) +{ + struct stat sb; + + if (stat(dirname, &sb) == 0) /* path exists */ + return (sb.st_mode & S_IFDIR); + + return(0); +} + +char * +md_getrealname(int uid) +{ + static char uidstr[20]; +#if !defined(_WIN32) && !defined(DJGPP) + struct passwd *pp; + + if ((pp = getpwuid(uid)) == NULL) + { + sprintf(uidstr,"%d", uid); + return(uidstr); + } + else + return(pp->pw_name); +#else + sprintf(uidstr,"%d", uid); + return(uidstr); +#endif +} + +extern char *xcrypt(char *key, char *salt); + +char * +md_crypt(char *key, char *salt) +{ + return( xcrypt(key,salt) ); +} + +char * +md_getpass(char *prompt) +{ +#ifndef HAVE_GETPASS + static char password_buffer[9]; + char *p = password_buffer; + int c, count = 0; + int max_length = 9; + + fflush(stdout); + /* If we can't prompt, abort */ + if (fputs(prompt, stderr) < 0) + { + *p = '\0'; + return NULL; + } + + for(;;) + { + /* Get a character with no echo */ + c = _getch(); + + /* Exit on interrupt (^c or ^break) */ + if (c == '\003' || c == 0x100) + exit(1); + + /* Terminate on end of line or file (^j, ^m, ^d, ^z) */ + if (c == '\r' || c == '\n' || c == '\004' || c == '\032') + break; + + /* Back up on backspace */ + if (c == '\b') + { + if (count) + count--; + else if (p > password_buffer) + p--; + continue; + } + + /* Ignore DOS extended characters */ + if ((c & 0xff) != c) + continue; + + /* Add to password if it isn't full */ + if (p < password_buffer + max_length - 1) + *p++ = (char) c; + else + count++; + } + *p = '\0'; + + fputc('\n', stderr); + + return password_buffer; +#else + return( (char *) getpass(prompt) ); +#endif +} + +int +md_erasechar() +{ +#ifdef HAVE_ERASECHAR + return( erasechar() ); /* process erase character */ +#elif defined(VERASE) + return(_tty.c_cc[VERASE]); /* process erase character */ +#else + return(_tty.sg_erase); /* process erase character */ +#endif +} + +int +md_killchar() +{ +#ifdef HAVE_KILLCHAR + return( killchar() ); +#elif defined(VKILL) + return(_tty.c_cc[VKILL]); +#else + return(_tty.sg_kill); +#endif +} + +int +md_dsuspchar() +{ +#if defined(VDSUSP) /* POSIX has priority */ + struct termios attr; + tcgetattr(STDIN_FILENO, &attr); + return( attr.c_cc[VDSUSP] ); +#elif defined(TIOCGLTC) + struct ltchars ltc; + ioctl(1, TIOCGLTC, <c); + return(ltc.t_dsuspc); +#elif defined(_POSIX_VDISABLE) + return(_POSIX_VDISABLE); +#else + return(0); +#endif +} + +int +md_setdsuspchar(int c) +{ +#if defined(VDSUSP) /* POSIX has priority */ + struct termios attr; + tcgetattr(STDIN_FILENO, &attr); + attr.c_cc[VDSUSP] = c; + tcgetattr(STDIN_FILENO, &attr); +#elif defined(TIOCSLTC) + struct ltchars ltc; + ioctl(1, TIOCGLTC, <c); + ltc.t_dsuspc = c; + ioctl(1, TIOCSLTC, <c); +#else + NOOP(c); +#endif + return(0); +} + +int +md_suspchar() +{ +#if defined(VSUSP) /* POSIX has priority */ + struct termios attr; + tcgetattr(STDIN_FILENO, &attr); + return( attr.c_cc[VSUSP] ); +#elif defined(TIOCGLTC) + struct ltchars ltc; + ioctl(1, TIOCGLTC, <c); + return(ltc.t_suspc); +#elif defined(_POSIX_VDISABLE) + return(_POSIX_VDISABLE); +#else + return(0); +#endif +} + +int +md_setsuspchar(int c) +{ +#if defined(VSUSP) /* POSIX has priority */ + struct termios attr; + tcgetattr(STDIN_FILENO, &attr); + attr.c_cc[VSUSP] = c; + tcgetattr(STDIN_FILENO, &attr); +#elif defined(TIOCSLTC) + struct ltchars ltc; + ioctl(1, TIOCGLTC, <c); + ltc.t_suspc = c; + ioctl(1, TIOCSLTC, <c); +#else + NOOP(c); +#endif + + return(0); +} + +/* + Cursor/Keypad Support + + Sadly Cursor/Keypad support is less straightforward than it should be. + + The various terminal emulators/consoles choose to differentiate the + cursor and keypad keys (with modifiers) in different ways (if at all!). + Furthermore they use different code set sequences for each key only + a subset of which the various curses libraries recognize. Partly due + to incomplete termcap/terminfo entries and partly due to inherent + limitations of those terminal capability databases. + + I give curses first crack at decoding the sequences. If it fails to decode + it we check for common ESC-prefixed sequences. + + All cursor/keypad results are translated into standard rogue movement + commands. + + Unmodified keys are translated to walk commands: hjklyubn + Modified (shift,control,alt) are translated to run commands: HJKLYUBN + + Console and supported (differentiated) keys + Interix: Cursor Keys, Keypad, Ctl-Keypad + Cygwin: Cursor Keys, Keypad, Alt-Cursor Keys + MSYS: Cursor Keys, Keypad, Ctl-Cursor Keys, Ctl-Keypad + Win32: Cursor Keys, Keypad, Ctl/Shift/Alt-Cursor Keys, Ctl/Alt-Keypad + DJGPP: Cursor Keys, Keypad, Ctl/Shift/Alt-Cursor Keys, Ctl/Alt-Keypad + + Interix Console (raw, ncurses) + ============================== + normal shift ctrl alt + ESC [D, ESC F^, ESC [D, ESC [D /# Left #/ + ESC [C, ESC F$, ESC [C, ESC [C /# Right #/ + ESC [A, ESC F-, local win, ESC [A /# Up #/ + ESC [B, ESC F+, local win, ESC [B /# Down #/ + ESC [H, ESC [H, ESC [H, ESC [H /# Home #/ + ESC [S, local win, ESC [S, ESC [S /# Page Up #/ + ESC [T, local win, ESC [T, ESC [T /# Page Down #/ + ESC [U, ESC [U, ESC [U, ESC [U /# End #/ + ESC [D, ESC F^, ESC [D, O /# Keypad Left #/ + ESC [C, ESC F$, ESC [C, O /# Keypad Right #/ + ESC [A, ESC [A, ESC [-1, O /# Keypad Up #/ + ESC [B, ESC [B, ESC [-2, O /# Keypad Down #/ + ESC [H, ESC [H, ESC [-263, O /# Keypad Home #/ + ESC [S, ESC [S, ESC [-19, O /# Keypad PgUp #/ + ESC [T, ESC [T, ESC [-20, O /# Keypad PgDn #/ + ESC [U, ESC [U, ESC [-21, O /# Keypad End #/ + nothing, nothing, nothing, O /# Kaypad 5 #/ + + Interix Console (term=interix, ncurses) + ============================== + KEY_LEFT, ESC F^, KEY_LEFT, KEY_LEFT /# Left #/ + KEY_RIGHT, ESC F$, KEY_RIGHT, KEY_RIGHT /# Right #/ + KEY_UP, 0x146, local win, KEY_UP /# Up #/ + KEY_DOWN, 0x145, local win, KEY_DOWN /# Down #/ + ESC [H, ESC [H, ESC [H, ESC [H /# Home #/ + KEY_PPAGE, local win, KEY_PPAGE, KEY_PPAGE /# Page Up #/ + KEY_NPAGE, local win, KEY_NPAGE, KEY_NPAGE /# Page Down #/ + KEY_LL, KEY_LL, KEY_LL, KEY_LL /# End #/ + KEY_LEFT, ESC F^, ESC [-4, O /# Keypad Left #/ + KEY_RIGHT, ESC F$, ESC [-3, O /# Keypad Right #/ + KEY_UP, KEY_UP, ESC [-1, O /# Keypad Up #/ + KEY_DOWN, KEY_DOWN, ESC [-2, O /# Keypad Down #/ + ESC [H, ESC [H, ESC [-263, O /# Keypad Home #/ + KEY_PPAGE, KEY_PPAGE, ESC [-19, O /# Keypad PgUp #/ + KEY_NPAGE, KEY_NPAGE, ESC [-20, O /# Keypad PgDn #/ + KEY_LL, KEY_LL, ESC [-21, O /# Keypad End #/ + nothing, nothing, nothing, O /# Keypad 5 #/ + + Cygwin Console (raw, ncurses) + ============================== + normal shift ctrl alt + ESC [D, ESC [D, ESC [D, ESC ESC [D /# Left #/ + ESC [C, ESC [C, ESC [C, ESC ESC [C /# Rght #/ + ESC [A, ESC [A, ESC [A, ESC ESC [A /# Up #/ + ESC [B, ESC [B, ESC [B, ESC ESC [B /# Down #/ + ESC [1~, ESC [1~, ESC [1~, ESC ESC [1~ /# Home #/ + ESC [5~, ESC [5~, ESC [5~, ESC ESC [5~ /# Page Up #/ + ESC [6~, ESC [6~, ESC [6~, ESC ESC [6~ /# Page Down #/ + ESC [4~, ESC [4~, ESC [4~, ESC ESC [4~ /# End #/ + ESC [D, ESC [D, ESC [D, ESC ESC [D,O /# Keypad Left #/ + ESC [C, ESC [C, ESC [C, ESC ESC [C,O /# Keypad Right #/ + ESC [A, ESC [A, ESC [A, ESC ESC [A,O /# Keypad Up #/ + ESC [B, ESC [B, ESC [B, ESC ESC [B,O /# Keypad Down #/ + ESC [1~, ESC [1~, ESC [1~, ESC ESC [1~,O /# Keypad Home #/ + ESC [5~, ESC [5~, ESC [5~, ESC ESC [5~,O /# Keypad PgUp #/ + ESC [6~, ESC [6~, ESC [6~, ESC ESC [6~,O /# Keypad PgDn #/ + ESC [4~, ESC [4~, ESC [4~, ESC ESC [4~,O /# Keypad End #/ + ESC [-71, nothing, nothing, O /# Keypad 5 #/ + + Cygwin Console (term=cygwin, ncurses) + ============================== + KEY_LEFT, KEY_LEFT, KEY_LEFT, ESC-260 /# Left #/ + KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, ESC-261 /# Rght #/ + KEY_UP, KEY_UP, KEY_UP, ESC-259 /# Up #/ + KEY_DOWN, KEY_DOWN, KEY_DOWN, ESC-258 /# Down #/ + KEY_HOME, KEY_HOME, KEY_HOME, ESC-262 /# Home #/ + KEY_PPAGE, KEY_PPAGE, KEY_PPAGE, ESC-339 /# Page Up #/ + KEY_NPAGE, KEY_NPAGE, KEY_NPAGE, ESC-338 /# Page Down #/ + KEY_END, KEY_END, KEY_END, ESC-360 /# End #/ + KEY_LEFT, KEY_LEFT, KEY_LEFT, ESC-260,O /# Keypad Left #/ + KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, ESC-261,O /# Keypad Right #/ + KEY_UP, KEY_UP, KEY_UP, ESC-259,O /# Keypad Up #/ + KEY_DOWN, KEY_DOWN, KEY_DOWN, ESC-258,O /# Keypad Down #/ + KEY_HOME, KEY_HOME, KEY_HOME, ESC-262,O /# Keypad Home #/ + KEY_PPAGE, KEY_PPAGE, KEY_PPAGE, ESC-339,O /# Keypad PgUp #/ + KEY_NPAGE, KEY_NPAGE, KEY_NPAGE, ESC-338,O /# Keypad PgDn #/ + KEY_END, KEY_END, KEY_END, ESC-360,O /# Keypad End #/ + ESC [G, nothing, nothing, O /# Keypad 5 #/ + + MSYS Console (raw, ncurses) + ============================== + normal shift ctrl alt + ESC OD, ESC [d, ESC Od nothing /# Left #/ + ESC OE, ESC [e, ESC Oe, nothing /# Right #/ + ESC OA, ESC [a, ESC Oa, nothing /# Up #/ + ESC OB, ESC [b, ESC Ob, nothing /# Down #/ + ESC [7~, ESC [7$, ESC [7^, nothing /# Home #/ + ESC [5~, local window, ESC [5^, nothing /# Page Up #/ + ESC [6~, local window, ESC [6^, nothing /# Page Down #/ + ESC [8~, ESC [8$, ESC [8^, nothing /# End #/ + ESC OD, ESC [d, ESC Od O /# Keypad Left #/ + ESC OE, ESC [c, ESC Oc, O /# Keypad Right #/ + ESC OA, ESC [a, ESC Oa, O /# Keypad Up #/ + ESC OB, ESC [b, ESC Ob, O /# Keypad Down #/ + ESC [7~, ESC [7$, ESC [7^, O /# Keypad Home #/ + ESC [5~, local window, ESC [5^, O /# Keypad PgUp #/ + ESC [6~, local window, ESC [6^, O /# Keypad PgDn #/ + ESC [8~, ESC [8$, ESC [8^, O /# Keypad End #/ + 11, 11, 11, O /# Keypad 5 #/ + + MSYS Console (term=rxvt, ncurses) + ============================== + normal shift ctrl alt + KEY_LEFT, KEY_SLEFT, 514 nothing /# Left #/ + KEY_RIGHT, KEY_SRIGHT, 516, nothing /# Right #/ + KEY_UP, 518, 519, nothing /# Up #/ + KEY_DOWN, 511, 512, nothing /# Down #/ + KEY_HOME, KEY_SHOME, ESC [7^, nothing /# Home #/ + KEY_PPAGE, local window, ESC [5^, nothing /# Page Up #/ + KEY_NPAGE, local window, ESC [6^, nothing /# Page Down #/ + KEY_END, KEY_SEND, KEY_EOL, nothing /# End #/ + KEY_LEFT, KEY_SLEFT, 514 O /# Keypad Left #/ + KEY_RIGHT, KEY_SRIGHT, 516, O /# Keypad Right #/ + KEY_UP, 518, 519, O /# Keypad Up #/ + KEY_DOWN, 511, 512, O /# Keypad Down #/ + KEY_HOME, KEY_SHOME, ESC [7^, O /# Keypad Home #/ + KEY_PPAGE, local window, ESC [5^, O /# Keypad PgUp #/ + KEY_NPAGE, local window, ESC [6^, O /# Keypad PgDn #/ + KEY_END, KEY_SEND, KEY_EOL, O /# Keypad End #/ + 11, 11, 11, O /# Keypad 5 #/ + + Win32 Console (raw, pdcurses) + DJGPP Console (raw, pdcurses) + ============================== + normal shift ctrl alt + 260, 391, 443, 493 /# Left #/ + 261, 400, 444, 492 /# Right #/ + 259, 547, 480, 490 /# Up #/ + 258, 548, 481, 491 /# Down #/ + 262, 388, 447, 524 /# Home #/ + 339, 396, 445, 526 /# Page Up #/ + 338, 394, 446, 520 /# Page Down #/ + 358, 384, 448, 518 /# End #/ + 452, 52('4'), 511, 521 /# Keypad Left #/ + 454, 54('6'), 513, 523 /# Keypad Right #/ + 450, 56('8'), 515, 525 /# Keypad Up #/ + 456, 50('2'), 509, 519 /# Keypad Down #/ + 449, 55('7'), 514, 524 /# Keypad Home #/ + 451, 57('9'), 516, 526 /# Keypad PgUp #/ + 457, 51('3'), 510, 520 /# Keypad PgDn #/ + 455, 49('1'), 508, 518 /# Keypad End #/ + 453, 53('5'), 512, 522 /# Keypad 5 #/ + + Win32 Console (pdcurses, MSVC/MingW32) + DJGPP Console (pdcurses) + ============================== + normal shift ctrl alt + KEY_LEFT, KEY_SLEFT, CTL_LEFT, ALT_LEFT /# Left #/ + KEY_RIGHT, KEY_SRIGHT, CTL_RIGHT, ALT_RIGHT /# Right #/ + KEY_UP, KEY_SUP, CTL_UP, ALT_UP /# Up #/ + KEY_DOWN, KEY_SDOWN, CTL_DOWN, ALT_DOWN /# Down #/ + KEY_HOME, KEY_SHOME, CTL_HOME, ALT_HOME /# Home #/ + KEY_PPAGE, KEY_SPREVIOUS, CTL_PGUP, ALT_PGUP /# Page Up #/ + KEY_NPAGE, KEY_SNEXTE, CTL_PGDN, ALT_PGDN /# Page Down #/ + KEY_END, KEY_SEND, CTL_END, ALT_END /# End #/ + KEY_B1, 52('4'), CTL_PAD4, ALT_PAD4 /# Keypad Left #/ + KEY_B3, 54('6'), CTL_PAD6, ALT_PAD6 /# Keypad Right #/ + KEY_A2, 56('8'), CTL_PAD8, ALT_PAD8 /# Keypad Up #/ + KEY_C2, 50('2'), CTL_PAD2, ALT_PAD2 /# Keypad Down #/ + KEY_A1, 55('7'), CTL_PAD7, ALT_PAD7 /# Keypad Home #/ + KEY_A3, 57('9'), CTL_PAD9, ALT_PAD9 /# Keypad PgUp #/ + KEY_C3, 51('3'), CTL_PAD3, ALT_PAD3 /# Keypad PgDn #/ + KEY_C1, 49('1'), CTL_PAD1, ALT_PAD1 /# Keypad End #/ + KEY_B2, 53('5'), CTL_PAD5, ALT_PAD5 /# Keypad 5 #/ + + Windows Telnet (raw) + ============================== + normal shift ctrl alt + ESC [D, ESC [D, ESC [D, ESC [D /# Left #/ + ESC [C, ESC [C, ESC [C, ESC [C /# Right #/ + ESC [A, ESC [A, ESC [A, ESC [A /# Up #/ + ESC [B, ESC [B, ESC [B, ESC [B /# Down #/ + ESC [1~, ESC [1~, ESC [1~, ESC [1~ /# Home #/ + ESC [5~, ESC [5~, ESC [5~, ESC [5~ /# Page Up #/ + ESC [6~, ESC [6~, ESC [6~, ESC [6~ /# Page Down #/ + ESC [4~, ESC [4~, ESC [4~, ESC [4~ /# End #/ + ESC [D, ESC [D, ESC [D, ESC [D /# Keypad Left #/ + ESC [C, ESC [C, ESC [C, ESC [C /# Keypad Right #/ + ESC [A, ESC [A, ESC [A, ESC [A /# Keypad Up #/ + ESC [B, ESC [B, ESC [B, ESC [B /# Keypad Down #/ + ESC [1~, ESC [1~, ESC [1~, ESC [1~ /# Keypad Home #/ + ESC [5~, ESC [5~, ESC [5~, ESC [5~ /# Keypad PgUp #/ + ESC [6~, ESC [6~, ESC [6~, ESC [6~ /# Keypad PgDn #/ + ESC [4~, ESC [4~, ESC [4~, ESC [4~ /# Keypad End #/ + nothing, nothing, nothing, nothing /# Keypad 5 #/ + + Windows Telnet (term=xterm) + ============================== + normal shift ctrl alt + KEY_LEFT, KEY_LEFT, KEY_LEFT, KEY_LEFT /# Left #/ + KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, KEY_RIGHT /# Right #/ + KEY_UP, KEY_UP, KEY_UP, KEY_UP /# Up #/ + KEY_DOWN, KEY_DOWN, KEY_DOWN, KEY_DOWN /# Down #/ + ESC [1~, ESC [1~, ESC [1~, ESC [1~ /# Home #/ + KEY_PPAGE, KEY_PPAGE, KEY_PPAGE, KEY_PPAGE /# Page Up #/ + KEY_NPAGE, KEY_NPAGE, KEY_NPAGE, KEY_NPAGE /# Page Down #/ + ESC [4~, ESC [4~, ESC [4~, ESC [4~ /# End #/ + KEY_LEFT, KEY_LEFT, KEY_LEFT, O /# Keypad Left #/ + KEY_RIGHT, KEY_RIGHT, KEY_RIGHT, O /# Keypad Right #/ + KEY_UP, KEY_UP, KEY_UP, O /# Keypad Up #/ + KEY_DOWN, KEY_DOWN, KEY_DOWN, O /# Keypad Down #/ + ESC [1~, ESC [1~, ESC [1~, ESC [1~ /# Keypad Home #/ + KEY_PPAGE, KEY_PPAGE, KEY_PPAGE, KEY_PPAGE /# Keypad PgUp #/ + KEY_NPAGE, KEY_NPAGE, KEY_NPAGE, KEY_NPAGE /# Keypad PgDn #/ + ESC [4~, ESC [4~, ESC [4~, O /# Keypad End #/ + ESC [-71, nothing, nothing, O /# Keypad 5 #/ + + PuTTY + ============================== + normal shift ctrl alt + ESC [D, ESC [D, ESC OD, ESC [D /# Left #/ + ESC [C, ESC [C, ESC OC, ESC [C /# Right #/ + ESC [A, ESC [A, ESC OA, ESC [A /# Up #/ + ESC [B, ESC [B, ESC OB, ESC [B /# Down #/ + ESC [1~, ESC [1~, local win, ESC [1~ /# Home #/ + ESC [5~, local win, local win, ESC [5~ /# Page Up #/ + ESC [6~, local win, local win, ESC [6~ /# Page Down #/ + ESC [4~, ESC [4~, local win, ESC [4~ /# End #/ + ESC [D, ESC [D, ESC [D, O /# Keypad Left #/ + ESC [C, ESC [C, ESC [C, O /# Keypad Right #/ + ESC [A, ESC [A, ESC [A, O /# Keypad Up #/ + ESC [B, ESC [B, ESC [B, O /# Keypad Down #/ + ESC [1~, ESC [1~, ESC [1~, O /# Keypad Home #/ + ESC [5~, ESC [5~, ESC [5~, O /# Keypad PgUp #/ + ESC [6~, ESC [6~, ESC [6~, O /# Keypad PgDn #/ + ESC [4~, ESC [4~, ESC [4~, O /# Keypad End #/ + nothing, nothing, nothing, O /# Keypad 5 #/ + + PuTTY + ============================== + normal shift ctrl alt + KEY_LEFT, KEY_LEFT, ESC OD, ESC KEY_LEFT /# Left #/ + KEY_RIGHT KEY_RIGHT, ESC OC, ESC KEY_RIGHT /# Right #/ + KEY_UP, KEY_UP, ESC OA, ESC KEY_UP /# Up #/ + KEY_DOWN, KEY_DOWN, ESC OB, ESC KEY_DOWN /# Down #/ + ESC [1~, ESC [1~, local win, ESC ESC [1~ /# Home #/ + KEY_PPAGE local win, local win, ESC KEY_PPAGE /# Page Up #/ + KEY_NPAGE local win, local win, ESC KEY_NPAGE /# Page Down #/ + ESC [4~, ESC [4~, local win, ESC ESC [4~ /# End #/ + ESC Ot, ESC Ot, ESC Ot, O /# Keypad Left #/ + ESC Ov, ESC Ov, ESC Ov, O /# Keypad Right #/ + ESC Ox, ESC Ox, ESC Ox, O /# Keypad Up #/ + ESC Or, ESC Or, ESC Or, O /# Keypad Down #/ + ESC Ow, ESC Ow, ESC Ow, O /# Keypad Home #/ + ESC Oy, ESC Oy, ESC Oy, O /# Keypad PgUp #/ + ESC Os, ESC Os, ESC Os, O /# Keypad PgDn #/ + ESC Oq, ESC Oq, ESC Oq, O /# Keypad End #/ + ESC Ou, ESC Ou, ESC Ou, O /# Keypad 5 #/ +*/ + +#define M_NORMAL 0 +#define M_ESC 1 +#define M_KEYPAD 2 +#define M_TRAIL 3 + +int +md_readchar() +{ + int ch = 0; + int lastch = 0; + int mode = M_NORMAL; + int mode2 = M_NORMAL; + + for(;;) + { + ch = getch(); + + if (ch == ERR) /* timed out waiting for valid sequence */ + { /* flush input so far and start over */ + mode = M_NORMAL; + nocbreak(); + raw(); + ch = 27; + break; + } + + if (mode == M_TRAIL) + { + if (ch == '^') /* msys console : 7,5,6,8: modified*/ + ch = CTRL( toupper(lastch) ); + + if (ch == '~') /* cygwin console: 1,5,6,4: normal */ + ch = tolower(lastch); /* windows telnet: 1,5,6,4: normal */ + /* msys console : 7,5,6,8: normal */ + + if (mode2 == M_ESC) /* cygwin console: 1,5,6,4: modified*/ + ch = CTRL( toupper(ch) ); + + break; + } + + if (mode == M_ESC) + { + if (ch == 27) + { + mode2 = M_ESC; + continue; + } + + if ((ch == 'F') || (ch == 'O') || (ch == '[')) + { + mode = M_KEYPAD; + continue; + } + + + switch(ch) + { + /* Cygwin Console */ + /* PuTTY */ + case KEY_LEFT : ch = CTRL('H'); break; + case KEY_RIGHT: ch = CTRL('L'); break; + case KEY_UP : ch = CTRL('K'); break; + case KEY_DOWN : ch = CTRL('J'); break; + case KEY_HOME : ch = CTRL('Y'); break; + case KEY_PPAGE: ch = CTRL('U'); break; + case KEY_NPAGE: ch = CTRL('N'); break; + case KEY_END : ch = CTRL('B'); break; + + default: break; + } + + break; + } + + if (mode == M_KEYPAD) + { + switch(ch) + { + /* ESC F - Interix Console codes */ + case '^': ch = CTRL('H'); break; /* Shift-Left */ + case '$': ch = CTRL('L'); break; /* Shift-Right */ + + /* ESC [ - Interix Console codes */ + case 'H': ch = 'y'; break; /* Home */ + case 1: ch = CTRL('K'); break; /* Ctl-Keypad Up */ + case 2: ch = CTRL('J'); break; /* Ctl-Keypad Down */ + case 3: ch = CTRL('L'); break; /* Ctl-Keypad Right */ + case 4: ch = CTRL('H'); break; /* Ctl-Keypad Left */ + case 263: ch = CTRL('Y'); break; /* Ctl-Keypad Home */ + case 19: ch = CTRL('U'); break; /* Ctl-Keypad PgUp */ + case 20: ch = CTRL('N'); break; /* Ctl-Keypad PgDn */ + case 21: ch = CTRL('B'); break; /* Ctl-Keypad End */ + + /* ESC [ - Cygwin Console codes */ + case 'G': ch = '.'; break; /* Keypad 5 */ + case '7': lastch = 'Y'; mode=M_TRAIL; break; /* Ctl-Home */ + case '5': lastch = 'U'; mode=M_TRAIL; break; /* Ctl-PgUp */ + case '6': lastch = 'N'; mode=M_TRAIL; break; /* Ctl-PgDn */ + + /* ESC [ - Win32 Telnet, PuTTY */ + case '1': lastch = 'y'; mode=M_TRAIL; break; /* Home */ + case '4': lastch = 'b'; mode=M_TRAIL; break; /* End */ + + /* ESC O - PuTTY */ + case 'D': ch = CTRL('H'); break; + case 'C': ch = CTRL('L'); break; + case 'A': ch = CTRL('K'); break; + case 'B': ch = CTRL('J'); break; + case 't': ch = 'h'; break; + case 'v': ch = 'l'; break; + case 'x': ch = 'k'; break; + case 'r': ch = 'j'; break; + case 'w': ch = 'y'; break; + case 'y': ch = 'u'; break; + case 's': ch = 'n'; break; + case 'q': ch = 'b'; break; + case 'u': ch = '.'; break; + } + + if (mode != M_KEYPAD) + continue; + } + + if (ch == 27) + { + halfdelay(1); + mode = M_ESC; + continue; + } + + switch(ch) + { + case KEY_LEFT : ch = 'h'; break; + case KEY_DOWN : ch = 'j'; break; + case KEY_UP : ch = 'k'; break; + case KEY_RIGHT : ch = 'l'; break; + case KEY_HOME : ch = 'y'; break; + case KEY_PPAGE : ch = 'u'; break; + case KEY_END : ch = 'b'; break; +#ifdef KEY_LL + case KEY_LL : ch = 'b'; break; +#endif + case KEY_NPAGE : ch = 'n'; break; + +#ifdef KEY_B1 + case KEY_B1 : ch = 'h'; break; + case KEY_C2 : ch = 'j'; break; + case KEY_A2 : ch = 'k'; break; + case KEY_B3 : ch = 'l'; break; +#endif + case KEY_A1 : ch = 'y'; break; + case KEY_A3 : ch = 'u'; break; + case KEY_C1 : ch = 'b'; break; + case KEY_C3 : ch = 'n'; break; + /* next should be '.', but for problem with putty/linux */ + case KEY_B2 : ch = 'u'; break; + +#ifdef KEY_SLEFT + case KEY_SRIGHT : ch = CTRL('L'); break; + case KEY_SLEFT : ch = CTRL('H'); break; +#ifdef KEY_SUP + case KEY_SUP : ch = CTRL('K'); break; + case KEY_SDOWN : ch = CTRL('J'); break; +#endif + case KEY_SHOME : ch = CTRL('Y'); break; + case KEY_SPREVIOUS:ch = CTRL('U'); break; + case KEY_SEND : ch = CTRL('B'); break; + case KEY_SNEXT : ch = CTRL('N'); break; +#endif + case 0x146 : ch = CTRL('K'); break; /* Shift-Up */ + case 0x145 : ch = CTRL('J'); break; /* Shift-Down */ + + +#ifdef CTL_RIGHT + case CTL_RIGHT : ch = CTRL('L'); break; + case CTL_LEFT : ch = CTRL('H'); break; + case CTL_UP : ch = CTRL('K'); break; + case CTL_DOWN : ch = CTRL('J'); break; + case CTL_HOME : ch = CTRL('Y'); break; + case CTL_PGUP : ch = CTRL('U'); break; + case CTL_END : ch = CTRL('B'); break; + case CTL_PGDN : ch = CTRL('N'); break; +#endif +#ifdef KEY_EOL + case KEY_EOL : ch = CTRL('B'); break; +#endif + +#ifndef CTL_PAD1 + /* MSYS rxvt console */ + case 511 : ch = CTRL('J'); break; /* Shift Dn */ + case 512 : ch = CTRL('J'); break; /* Ctl Down */ + case 514 : ch = CTRL('H'); break; /* Ctl Left */ + case 516 : ch = CTRL('L'); break; /* Ctl Right*/ + case 518 : ch = CTRL('K'); break; /* Shift Up */ + case 519 : ch = CTRL('K'); break; /* Ctl Up */ +#endif + +#ifdef CTL_PAD1 + case CTL_PAD1 : ch = CTRL('B'); break; + case CTL_PAD2 : ch = CTRL('J'); break; + case CTL_PAD3 : ch = CTRL('N'); break; + case CTL_PAD4 : ch = CTRL('H'); break; + case CTL_PAD5 : ch = '.'; break; + case CTL_PAD6 : ch = CTRL('L'); break; + case CTL_PAD7 : ch = CTRL('Y'); break; + case CTL_PAD8 : ch = CTRL('K'); break; + case CTL_PAD9 : ch = CTRL('U'); break; +#endif + +#ifdef ALT_RIGHT + case ALT_RIGHT : ch = CTRL('L'); break; + case ALT_LEFT : ch = CTRL('H'); break; + case ALT_DOWN : ch = CTRL('J'); break; + case ALT_HOME : ch = CTRL('Y'); break; + case ALT_PGUP : ch = CTRL('U'); break; + case ALT_END : ch = CTRL('B'); break; + case ALT_PGDN : ch = CTRL('N'); break; +#endif + +#ifdef ALT_PAD1 + case ALT_PAD1 : ch = CTRL('B'); break; + case ALT_PAD2 : ch = CTRL('J'); break; + case ALT_PAD3 : ch = CTRL('N'); break; + case ALT_PAD4 : ch = CTRL('H'); break; + case ALT_PAD5 : ch = '.'; break; + case ALT_PAD6 : ch = CTRL('L'); break; + case ALT_PAD7 : ch = CTRL('Y'); break; + case ALT_PAD8 : ch = CTRL('K'); break; + case ALT_PAD9 : ch = CTRL('U'); break; +#endif +#ifdef KEY_BACKSPACE /* NCURSES in Keypad mode sends this for Ctrl-H */ + case KEY_BACKSPACE: ch = CTRL('H'); break; +#endif + } + + break; + } + + nocbreak(); /* disable halfdelay mode if on */ + raw(); + + return(ch & 0x7F); +} + +#if defined(LOADAV) && defined(HAVE_NLIST_H) && defined(HAVE_NLIST) +/* + * loadav: + * Looking up load average in core (for system where the loadav() + * system call isn't defined + */ + +#include + +struct nlist avenrun = { + "_avenrun" +}; + +void +md_loadav(double *avg) +{ + int kmem; + + if ((kmem = open("/dev/kmem", 0)) < 0) + goto bad; + nlist(NAMELIST, &avenrun); + if (avenrun.n_type == 0) + { + close(kmem); +bad: + avg[0] = 0.0; + avg[1] = 0.0; + avg[2] = 0.0; + return; + } + + lseek(kmem, avenrun.n_value, 0); + read(kmem, (char *) avg, 3 * sizeof (double)); + close(kmem); +} +#else +void +md_loadav(double *avg) +{ +#if defined(HAVE_LOADAV) + loadav(avg); +#elif defined(HAVE_GETLOADAVG) + getloadavg(avg,3); +#else + avg[0] = avg[1] = avg[2] = 0; +#endif +} +#endif + +#ifndef NSIG +#define NSIG 32 +#endif + +void +md_ignoreallsignals() +{ + int i; + + for (i = 0; i < NSIG; i++) + signal(i, SIG_IGN); +} + +void +md_tstphold() +{ +#ifdef SIGTSTP + /* + * If a process can be suspended, this code wouldn't work + */ +# ifdef SIG_HOLD + signal(SIGTSTP, SIG_HOLD); +# else + signal(SIGTSTP, SIG_IGN); +# endif +#endif +} + +void +md_tstpresume() +{ +#ifdef SIGTSTP + signal(SIGTSTP, tstp); +#endif +} + +void +md_tstpsignal() +{ +#ifdef SIGTSTP + kill(0, SIGTSTP); /* send actual signal and suspend process */ +#endif +} + +#if defined(CHECKTIME) +void +md_start_checkout_timer(int time) +{ + int checkout(); + +#if defined(HAVE_ALARM) && defined(SIGALRM) + signal(SIGALRM, checkout); + alarm(time); +#endif +} + +void +md_stop_checkout_timer() +{ +#if defined(SIGALRM) + signal(SIGALRM, SIG_IGN); +#endif +} + +#endif diff --git a/src/cc/rogue/misc.c b/src/cc/rogue/misc.c new file mode 100644 index 000000000..87bc40b4d --- /dev/null +++ b/src/cc/rogue/misc.c @@ -0,0 +1,597 @@ +/* + * All sorts of miscellaneous routines + * + * @(#)misc.c 4.66 (Berkeley) 08/06/83 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include +#include +#include "rogue.h" + +/* + * look: + * A quick glance all around the player + */ +#undef DEBUG + + +void +look(struct rogue_state *rs,bool wakeup) +{ + int x, y; + int ch; + THING *tp; + PLACE *pp; + struct room *rp; + int ey, ex; + int passcount; + char pfl, *fp, pch; + int sy, sx, sumhero = 0, diffhero = 0; +# ifdef DEBUG + static bool done = FALSE; + + if (done) + return; + done = TRUE; +# endif /* DEBUG */ + passcount = 0; + rp = proom; + if (!ce(oldpos, hero)) + { + erase_lamp(&oldpos, oldrp); + oldpos = hero; + oldrp = rp; + } + ey = hero.y + 1; + ex = hero.x + 1; + sx = hero.x - 1; + sy = hero.y - 1; + if (door_stop && !firstmove && running) + { + sumhero = hero.y + hero.x; + diffhero = hero.y - hero.x; + } + pp = INDEX(hero.y, hero.x); + pch = pp->p_ch; + pfl = pp->p_flags; + + for (y = sy; y <= ey; y++) + if (y > 0 && y < NUMLINES - 1) for (x = sx; x <= ex; x++) + { + if (x < 0 || x >= NUMCOLS) + continue; + if (!on(player, ISBLIND)) + { + if (y == hero.y && x == hero.x) + continue; + } + + pp = INDEX(y, x); + ch = pp->p_ch; + if (ch == ' ') /* nothing need be done with a ' ' */ + continue; + fp = &pp->p_flags; + if (pch != DOOR && ch != DOOR) + if ((pfl & F_PASS) != (*fp & F_PASS)) + continue; + if (((*fp & F_PASS) || ch == DOOR) && + ((pfl & F_PASS) || pch == DOOR)) + { + if (hero.x != x && hero.y != y && + !step_ok(chat(y, hero.x)) && !step_ok(chat(hero.y, x))) + continue; + } + + if ((tp = pp->p_monst) == NULL) + ch = trip_ch(y, x, ch); + else + if (on(player, SEEMONST) && on(*tp, ISINVIS)) + { + if (door_stop && !firstmove) + running = FALSE; + continue; + } + else + { + if (wakeup) + wake_monster(rs,y, x); + if (see_monst(tp)) + { + if (on(player, ISHALU)) + ch = rnd(26) + 'A'; + else + ch = tp->t_disguise; + } + } + if (on(player, ISBLIND) && (y != hero.y || x != hero.x)) + continue; + + move(y, x); + + if ((proom->r_flags & ISDARK) && !see_floor && ch == FLOOR) + ch = ' '; + + if (tp != NULL || ch != CCHAR( inch() )) + addch(ch); + + if (door_stop && !firstmove && running) + { + switch (runch) + { + case 'h': + if (x == ex) + continue; + when 'j': + if (y == sy) + continue; + when 'k': + if (y == ey) + continue; + when 'l': + if (x == sx) + continue; + when 'y': + if ((y + x) - sumhero >= 1) + continue; + when 'u': + if ((y - x) - diffhero >= 1) + continue; + when 'n': + if ((y + x) - sumhero <= -1) + continue; + when 'b': + if ((y - x) - diffhero <= -1) + continue; + } + switch (ch) + { + case DOOR: + if (x == hero.x || y == hero.y) + running = FALSE; + break; + case PASSAGE: + if (x == hero.x || y == hero.y) + passcount++; + break; + case FLOOR: + case '|': + case '-': + case ' ': + break; + default: + running = FALSE; + break; + } + } + } + if (door_stop && !firstmove && passcount > 1) + running = FALSE; + if (!running || !jump) + mvaddch(hero.y, hero.x, PLAYER); +# ifdef DEBUG + done = FALSE; +# endif /* DEBUG */ +} + +/* + * trip_ch: + * Return the character appropriate for this space, taking into + * account whether or not the player is tripping. + */ +int +trip_ch(int y, int x, int ch) +{ + if (on(player, ISHALU) && after) + switch (ch) + { + case FLOOR: + case ' ': + case PASSAGE: + case '-': + case '|': + case DOOR: + case TRAP: + break; + default: + if (y != stairs.y || x != stairs.x || !seenstairs) + ch = rnd_thing(); + break; + } + return ch; +} + +/* + * erase_lamp: + * Erase the area shown by a lamp in a dark room. + */ + +void +erase_lamp(coord *pos, struct room *rp) +{ + int y, x, ey, sy, ex; + + if (!(see_floor && (rp->r_flags & (ISGONE|ISDARK)) == ISDARK + && !on(player,ISBLIND))) + return; + + ey = pos->y + 1; + ex = pos->x + 1; + sy = pos->y - 1; + for (x = pos->x - 1; x <= ex; x++) + for (y = sy; y <= ey; y++) + { + if (y == hero.y && x == hero.x) + continue; + move(y, x); + if (inch() == FLOOR) + addch(' '); + } +} + +/* + * show_floor: + * Should we show the floor in her room at this time? + */ +bool +show_floor() +{ + if ((proom->r_flags & (ISGONE|ISDARK)) == ISDARK && !on(player, ISBLIND)) + return see_floor; + else + return TRUE; +} + +/* + * find_obj: + * Find the unclaimed object at y, x + */ +THING * +find_obj(struct rogue_state *rs,int y, int x) +{ + THING *obj; + + for (obj = lvl_obj; obj != NULL; obj = next(obj)) + { + if (obj->o_pos.y == y && obj->o_pos.x == x) + return obj; + } +#ifdef MASTER + sprintf(prbuf, "Non-object %d,%d", y, x); + msg(rs,prbuf); + return NULL; +#else + /* NOTREACHED */ + return NULL; +#endif +} + +/* + * eat: + * She wants to eat something, so let her try + */ + +void +eat(struct rogue_state *rs) +{ + THING *obj; + + if ((obj = get_item(rs,"eat", FOOD)) == NULL) + return; + if (obj->o_type != FOOD) + { + if (!terse) + msg(rs,"ugh, you would get ill if you ate that"); + else + msg(rs,"that's Inedible!"); + return; + } + if (food_left < 0) + food_left = 0; + if ((food_left += HUNGERTIME - 200 + rnd(400)) > STOMACHSIZE) + food_left = STOMACHSIZE; + hungry_state = 0; + if (obj == cur_weapon) + cur_weapon = NULL; + if (obj->o_which == 1) + msg(rs,"my, that was a yummy %s", fruit); + else + if (rnd(100) > 70) + { + pstats.s_exp++; + msg(rs,"%s, this food tastes awful", choose_str("bummer", "yuk")); + check_level(rs); + } + else + msg(rs,"%s, that tasted good", choose_str("oh, wow", "yum")); + leave_pack(rs,obj, FALSE, FALSE); +} + +/* + * check_level: + * Check to see if the guy has gone up a level. + */ + +void +check_level(struct rogue_state *rs) +{ + int i, add, olevel; + + for (i = 0; e_levels[i] != 0; i++) + if (e_levels[i] > pstats.s_exp) + break; + i++; + olevel = pstats.s_lvl; + pstats.s_lvl = i; + if (i > olevel) + { + add = roll(i - olevel, 10); + max_hp += add; + pstats.s_hpt += add; + msg(rs,"welcome to level %d", i); + } +} + +/* + * chg_str: + * used to modify the playes strength. It keeps track of the + * highest it has been, just in case + */ + +void +chg_str(int amt) +{ + auto str_t comp; + + if (amt == 0) + return; + add_str(&pstats.s_str, amt); + comp = pstats.s_str; + if (ISRING(LEFT, R_ADDSTR)) + add_str(&comp, -cur_ring[LEFT]->o_arm); + if (ISRING(RIGHT, R_ADDSTR)) + add_str(&comp, -cur_ring[RIGHT]->o_arm); + if (comp > max_stats.s_str) + max_stats.s_str = comp; +} + +/* + * add_str: + * Perform the actual add, checking upper and lower bound limits + */ +void +add_str(str_t *sp, int amt) +{ + if ((*sp += amt) < 3) + *sp = 3; + else if (*sp > 31) + *sp = 31; +} + +/* + * add_haste: + * Add a haste to the player + */ +bool +add_haste(struct rogue_state *rs,bool potion) +{ + if (on(player, ISHASTE)) + { + no_command += rnd(8); + player.t_flags &= ~(ISRUN|ISHASTE); + extinguish(nohaste); + msg(rs,"you faint from exhaustion"); + return FALSE; + } + else + { + player.t_flags |= ISHASTE; + if (potion) + fuse(nohaste, 0, rnd(4)+4, AFTER); + return TRUE; + } +} + +/* + * aggravate: + * Aggravate all the monsters on this level + */ + +void +aggravate(struct rogue_state *rs) +{ + THING *mp; + + for (mp = mlist; mp != NULL; mp = next(mp)) + runto(rs,&mp->t_pos); +} + +/* + * vowelstr: + * For printfs: if string starts with a vowel, return "n" for an + * "an". + */ +char * +vowelstr(char *str) +{ + switch (*str) + { + case 'a': case 'A': + case 'e': case 'E': + case 'i': case 'I': + case 'o': case 'O': + case 'u': case 'U': + return "n"; + default: + return ""; + } +} + +/* + * is_current: + * See if the object is one of the currently used items + */ +bool +is_current(struct rogue_state *rs,THING *obj) +{ + if (obj == NULL) + return FALSE; + if (obj == cur_armor || obj == cur_weapon || obj == cur_ring[LEFT] + || obj == cur_ring[RIGHT]) + { + if (!terse) + addmsg(rs,"That's already "); + msg(rs,"in use"); + return TRUE; + } + return FALSE; +} + +/* + * get_dir: + * Set up the direction co_ordinate for use in varios "prefix" + * commands + */ +bool +get_dir(struct rogue_state *rs) +{ + char *prompt; + bool gotit; + static coord last_delt= {0,0}; + + if (again && last_dir != '\0') + { + delta.y = last_delt.y; + delta.x = last_delt.x; + dir_ch = last_dir; + } + else + { + if (!terse) + msg(rs,prompt = "which direction? "); + else + prompt = "direction: "; + do + { + gotit = TRUE; + switch (dir_ch = readchar(rs)) + { + case 'h': case'H': delta.y = 0; delta.x = -1; + when 'j': case'J': delta.y = 1; delta.x = 0; + when 'k': case'K': delta.y = -1; delta.x = 0; + when 'l': case'L': delta.y = 0; delta.x = 1; + when 'y': case'Y': delta.y = -1; delta.x = -1; + when 'u': case'U': delta.y = -1; delta.x = 1; + when 'b': case'B': delta.y = 1; delta.x = -1; + when 'n': case'N': delta.y = 1; delta.x = 1; + when ESCAPE: last_dir = '\0'; reset_last(); return FALSE; + otherwise: + mpos = 0; + msg(rs,prompt); + gotit = FALSE; + } + } until (gotit); + if (isupper(dir_ch)) + dir_ch = (char) tolower(dir_ch); + last_dir = dir_ch; + last_delt.y = delta.y; + last_delt.x = delta.x; + } + if (on(player, ISHUH) && rnd(5) == 0) + do + { + delta.y = rnd(3) - 1; + delta.x = rnd(3) - 1; + } while (delta.y == 0 && delta.x == 0); + mpos = 0; + return TRUE; +} + +/* + * sign: + * Return the sign of the number + */ +int +sign(int nm) +{ + if (nm < 0) + return -1; + else + return (nm > 0); +} + +/* + * spread: + * Give a spread around a given number (+/- 20%) + */ +int +spread(int nm) +{ + return nm - nm / 20 + rnd(nm / 10); +} + +/* + * call_it: + * Call an object something after use. + */ + +void +call_it(struct rogue_state *rs,struct obj_info *info) +{ + if (info->oi_know) + { + if (info->oi_guess) + { + free(info->oi_guess); + info->oi_guess = NULL; + } + } + else if (!info->oi_guess) + { + msg(rs,terse ? "call it: " : "what do you want to call it? "); + if (get_str(rs,prbuf, stdscr) == NORM) + { + if (info->oi_guess != NULL) + free(info->oi_guess); + info->oi_guess = malloc((unsigned int) strlen(prbuf) + 1); + strcpy(info->oi_guess, prbuf); + } + } +} + +/* + * rnd_thing: + * Pick a random thing appropriate for this level + */ +char +rnd_thing() +{ + int i; + static char thing_list[] = { + POTION, SCROLL, RING, STICK, FOOD, WEAPON, ARMOR, STAIRS, GOLD, AMULET + }; + + if (level >= AMULETLEVEL) + i = rnd(sizeof thing_list / sizeof (char)); + else + i = rnd(sizeof thing_list / sizeof (char) - 1); + return thing_list[i]; +} + +/* + str str: + * Choose the first or second string depending on whether it the + * player is tripping + */ +char * +choose_str(char *ts, char *ns) +{ + return (on(player, ISHALU) ? ts : ns); +} diff --git a/src/cc/rogue/monsters.c b/src/cc/rogue/monsters.c new file mode 100644 index 000000000..c9441efa3 --- /dev/null +++ b/src/cc/rogue/monsters.c @@ -0,0 +1,252 @@ +/* + * File with various monster functions in it + * + * @(#)monsters.c 4.46 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include "rogue.h" +#include + +/* + * List of monsters in rough order of vorpalness + */ +static char lvl_mons[] = { + 'K', 'E', 'B', 'S', 'H', 'I', 'R', 'O', 'Z', 'L', 'C', 'Q', 'A', + 'N', 'Y', 'F', 'T', 'W', 'P', 'X', 'U', 'M', 'V', 'G', 'J', 'D' +}; + +static char wand_mons[] = { + 'K', 'E', 'B', 'S', 'H', 0, 'R', 'O', 'Z', 0, 'C', 'Q', 'A', + 0, 'Y', 0, 'T', 'W', 'P', 0, 'U', 'M', 'V', 'G', 'J', 0 +}; + +/* + * randmonster: + * Pick a monster to show up. The lower the level, + * the meaner the monster. + */ +char +randmonster(bool wander) +{ + int d; + char *mons; + + mons = (wander ? wand_mons : lvl_mons); + do + { + d = level + (rnd(10) - 6); + if (d < 0) + d = rnd(5); + if (d > 25) + d = rnd(5) + 21; + } while (mons[d] == 0); + return mons[d]; +} + +/* + * new_monster: + * Pick a new monster and add it to the list + */ + +void +new_monster(struct rogue_state *rs,THING *tp, char type, coord *cp) +{ + struct monster *mp; + int lev_add; + + if ((lev_add = level - AMULETLEVEL) < 0) + lev_add = 0; + attach(mlist, tp); + tp->t_type = type; + tp->t_disguise = type; + tp->t_pos = *cp; + move(cp->y, cp->x); + tp->t_oldch = CCHAR( inch() ); + tp->t_room = roomin(rs,cp); + moat(cp->y, cp->x) = tp; + mp = &monsters[tp->t_type-'A']; + tp->t_stats.s_lvl = mp->m_stats.s_lvl + lev_add; + tp->t_stats.s_maxhp = tp->t_stats.s_hpt = roll(tp->t_stats.s_lvl, 8); + tp->t_stats.s_arm = mp->m_stats.s_arm - lev_add; + strcpy(tp->t_stats.s_dmg,mp->m_stats.s_dmg); + tp->t_stats.s_str = mp->m_stats.s_str; + tp->t_stats.s_exp = mp->m_stats.s_exp + lev_add * 10 + exp_add(tp); + tp->t_flags = mp->m_flags; + if (level > 29) + tp->t_flags |= ISHASTE; + tp->t_turn = TRUE; + tp->t_pack = NULL; + if (ISWEARING(R_AGGR)) + runto(rs,cp); + if (type == 'X') + tp->t_disguise = rnd_thing(); +} + +/* + * expadd: + * Experience to add for this monster's level/hit points + */ +int +exp_add(THING *tp) +{ + int mod; + + if (tp->t_stats.s_lvl == 1) + mod = tp->t_stats.s_maxhp / 8; + else + mod = tp->t_stats.s_maxhp / 6; + if (tp->t_stats.s_lvl > 9) + mod *= 20; + else if (tp->t_stats.s_lvl > 6) + mod *= 4; + return mod; +} + +/* + * wanderer: + * Create a new wandering monster and aim it at the player + */ + +void +wanderer(struct rogue_state *rs) +{ + THING *tp; + static coord cp; + + tp = new_item(); + do + { + find_floor((struct room *) NULL, &cp, FALSE, TRUE); + } while (roomin(rs,&cp) == proom); + new_monster(rs,tp, randmonster(TRUE), &cp); + if (on(player, SEEMONST)) + { + standout(); + if (!on(player, ISHALU)) + addch(tp->t_type); + else + addch(rnd(26) + 'A'); + standend(); + } + runto(rs,&tp->t_pos); +#ifdef MASTER + if (wizard) + msg(rs,"started a wandering %s", monsters[tp->t_type-'A'].m_name); +#endif +} + +/* + * wake_monster: + * What to do when the hero steps next to a monster + */ +THING * +wake_monster(struct rogue_state *rs,int y, int x) +{ + THING *tp; + struct room *rp; + char ch, *mname; + +#ifdef MASTER + if ((tp = moat(y, x)) == NULL) + msg(rs,"can't find monster in wake_monster"); +#else + tp = moat(y, x); + if (tp == NULL) + endwin(), abort(); +#endif + ch = tp->t_type; + /* + * Every time he sees mean monster, it might start chasing him + */ + if (!on(*tp, ISRUN) && rnd(3) != 0 && on(*tp, ISMEAN) && !on(*tp, ISHELD) + && !ISWEARING(R_STEALTH) && !on(player, ISLEVIT)) + { + tp->t_dest = &hero; + tp->t_flags |= ISRUN; + } + if (ch == 'M' && !on(player, ISBLIND) && !on(player, ISHALU) + && !on(*tp, ISFOUND) && !on(*tp, ISCANC) && on(*tp, ISRUN)) + { + rp = proom; + if ((rp != NULL && !(rp->r_flags & ISDARK)) + || dist(y, x, hero.y, hero.x) < LAMPDIST) + { + tp->t_flags |= ISFOUND; + if (!save(VS_MAGIC)) + { + if (on(player, ISHUH)) + lengthen(unconfuse, spread(HUHDURATION)); + else + fuse(unconfuse, 0, spread(HUHDURATION), AFTER); + player.t_flags |= ISHUH; + mname = set_mname(tp); + addmsg(rs,"%s", mname); + if (strcmp(mname, "it") != 0) + addmsg(rs,"'"); + msg(rs,"s gaze has confused you"); + } + } + } + /* + * Let greedy ones guard gold + */ + if (on(*tp, ISGREED) && !on(*tp, ISRUN)) + { + tp->t_flags |= ISRUN; + if (proom->r_goldval) + tp->t_dest = &proom->r_gold; + else + tp->t_dest = &hero; + } + return tp; +} + +/* + * give_pack: + * Give a pack to a monster if it deserves one + */ + +void +give_pack(struct rogue_state *rs,THING *tp) +{ + if (level >= max_level && rnd(100) < monsters[tp->t_type-'A'].m_carry) + attach(tp->t_pack, new_thing(rs)); +} + +/* + * save_throw: + * See if a creature save against something + */ +int +save_throw(int which, THING *tp) +{ + int need; + + need = 14 + which - tp->t_stats.s_lvl / 2; + return (roll(1, 20) >= need); +} + +/* + * save: + * See if he saves against various nasty things + */ +int +save(int which) +{ + if (which == VS_MAGIC) + { + if (ISRING(LEFT, R_PROTECT)) + which -= cur_ring[LEFT]->o_arm; + if (ISRING(RIGHT, R_PROTECT)) + which -= cur_ring[RIGHT]->o_arm; + } + return save_throw(which, &player); +} diff --git a/src/cc/rogue/move.c b/src/cc/rogue/move.c new file mode 100644 index 000000000..b402f4fa1 --- /dev/null +++ b/src/cc/rogue/move.c @@ -0,0 +1,425 @@ +/* + * hero movement commands + * + * @(#)move.c 4.49 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include "rogue.h" + +/* + * used to hold the new hero position + */ + +coord nh; + +/* + * do_run: + * Start the hero running + */ + +void +do_run(char ch) +{ + running = TRUE; + after = FALSE; + runch = ch; +} + +/* + * do_move: + * Check to see that a move is legal. If it is handle the + * consequences (fighting, picking up, etc.) + */ + +void +do_move(struct rogue_state *rs,int dy, int dx) +{ + char ch, fl; + + firstmove = FALSE; + if (no_move) + { + no_move--; + msg(rs,"you are still stuck in the bear trap"); + return; + } + /* + * Do a confused move (maybe) + */ + if (on(player, ISHUH) && rnd(5) != 0) + { + nh = *rndmove(&player); + if (ce(nh, hero)) + { + after = FALSE; + running = FALSE; + to_death = FALSE; + return; + } + } + else + { +over: + nh.y = hero.y + dy; + nh.x = hero.x + dx; + } + + /* + * Check if he tried to move off the screen or make an illegal + * diagonal move, and stop him if he did. + */ + if (nh.x < 0 || nh.x >= NUMCOLS || nh.y <= 0 || nh.y >= NUMLINES - 1) + goto hit_bound; + if (!diag_ok(&hero, &nh)) + { + after = FALSE; + running = FALSE; + return; + } + if (running && ce(hero, nh)) + after = running = FALSE; + fl = flat(nh.y, nh.x); + ch = winat(nh.y, nh.x); + if (!(fl & F_REAL) && ch == FLOOR) + { + if (!on(player, ISLEVIT)) + { + chat(nh.y, nh.x) = ch = TRAP; + flat(nh.y, nh.x) |= F_REAL; + } + } + else if (on(player, ISHELD) && ch != 'F') + { + msg(rs,"you are being held"); + return; + } + switch (ch) + { + case ' ': + case '|': + case '-': +hit_bound: + if (passgo && running && (proom->r_flags & ISGONE) + && !on(player, ISBLIND)) + { + bool b1, b2; + + switch (runch) + { + case 'h': + case 'l': + b1 = (bool)(hero.y != 1 && turn_ok(hero.y - 1, hero.x)); + b2 = (bool)(hero.y != NUMLINES - 2 && turn_ok(hero.y + 1, hero.x)); + if (!(b1 ^ b2)) + break; + if (b1) + { + runch = 'k'; + dy = -1; + } + else + { + runch = 'j'; + dy = 1; + } + dx = 0; + turnref(); + goto over; + case 'j': + case 'k': + b1 = (bool)(hero.x != 0 && turn_ok(hero.y, hero.x - 1)); + b2 = (bool)(hero.x != NUMCOLS - 1 && turn_ok(hero.y, hero.x + 1)); + if (!(b1 ^ b2)) + break; + if (b1) + { + runch = 'h'; + dx = -1; + } + else + { + runch = 'l'; + dx = 1; + } + dy = 0; + turnref(); + goto over; + } + } + running = FALSE; + after = FALSE; + break; + case DOOR: + running = FALSE; + if (flat(hero.y, hero.x) & F_PASS) + enter_room(rs,&nh); + goto move_stuff; + case TRAP: + ch = be_trapped(rs,&nh); + if (ch == T_DOOR || ch == T_TELEP) + return; + goto move_stuff; + case PASSAGE: + /* + * when you're in a corridor, you don't know if you're in + * a maze room or not, and there ain't no way to find out + * if you're leaving a maze room, so it is necessary to + * always recalculate proom. + */ + proom = roomin(rs,&hero); + goto move_stuff; + case FLOOR: + if (!(fl & F_REAL)) + be_trapped(rs,&hero); + goto move_stuff; + case STAIRS: + seenstairs = TRUE; + /* FALLTHROUGH */ + default: + running = FALSE; + if (isupper(ch) || moat(nh.y, nh.x)) + fight(rs,&nh, cur_weapon, FALSE); + else + { + if (ch != STAIRS) + take = ch; +move_stuff: + mvaddch(hero.y, hero.x, floor_at()); + if ((fl & F_PASS) && chat(oldpos.y, oldpos.x) == DOOR) + leave_room(rs,&nh); + hero = nh; + } + } +} + +/* + * turn_ok: + * Decide whether it is legal to turn onto the given space + */ +bool +turn_ok(int y, int x) +{ + PLACE *pp; + + pp = INDEX(y, x); + return (pp->p_ch == DOOR + || (pp->p_flags & (F_REAL|F_PASS)) == (F_REAL|F_PASS)); +} + +/* + * turnref: + * Decide whether to refresh at a passage turning or not + */ + +void +turnref() +{ + PLACE *pp; + + pp = INDEX(hero.y, hero.x); + if (!(pp->p_flags & F_SEEN)) + { + if (jump) + { + leaveok(stdscr, TRUE); + refresh(); + leaveok(stdscr, FALSE); + } + pp->p_flags |= F_SEEN; + } +} + +/* + * door_open: + * Called to illuminate a room. If it is dark, remove anything + * that might move. + */ + +void +door_open(struct rogue_state *rs,struct room *rp) +{ + int y, x; + + if (!(rp->r_flags & ISGONE)) + for (y = rp->r_pos.y; y < rp->r_pos.y + rp->r_max.y; y++) + for (x = rp->r_pos.x; x < rp->r_pos.x + rp->r_max.x; x++) + if (isupper(winat(y, x))) + wake_monster(rs,y, x); +} + +/* + * be_trapped: + * The guy stepped on a trap.... Make him pay. + */ +char +be_trapped(struct rogue_state *rs,coord *tc) +{ + PLACE *pp; + THING *arrow; + char tr; + + if (on(player, ISLEVIT)) + return T_RUST; /* anything that's not a door or teleport */ + running = FALSE; + count = FALSE; + pp = INDEX(tc->y, tc->x); + pp->p_ch = TRAP; + tr = pp->p_flags & F_TMASK; + pp->p_flags |= F_SEEN; + switch (tr) + { + case T_DOOR: + level++; + new_level(rs); + msg(rs,"you fell into a trap!"); + when T_BEAR: + no_move += BEARTIME; + msg(rs,"you are caught in a bear trap"); + when T_MYST: + switch(rnd(11)) + { + case 0: msg(rs,"you are suddenly in a parallel dimension"); + when 1: msg(rs,"the light in here suddenly seems %s", rainbow[rnd(cNCOLORS)]); + when 2: msg(rs,"you feel a sting in the side of your neck"); + when 3: msg(rs,"multi-colored lines swirl around you, then fade"); + when 4: msg(rs,"a %s light flashes in your eyes", rainbow[rnd(cNCOLORS)]); + when 5: msg(rs,"a spike shoots past your ear!"); + when 6: msg(rs,"%s sparks dance across your armor", rainbow[rnd(cNCOLORS)]); + when 7: msg(rs,"you suddenly feel very thirsty"); + when 8: msg(rs,"you feel time speed up suddenly"); + when 9: msg(rs,"time now seems to be going slower"); + when 10: msg(rs,"you pack turns %s!", rainbow[rnd(cNCOLORS)]); + } + when T_SLEEP: + no_command += SLEEPTIME; + player.t_flags &= ~ISRUN; + msg(rs,"a strange white mist envelops you and you fall asleep"); + when T_ARROW: + if (swing(pstats.s_lvl - 1, pstats.s_arm, 1)) + { + pstats.s_hpt -= roll(1, 6); + if (pstats.s_hpt <= 0) + { + msg(rs,"an arrow killed you"); + death('a'); + } + else + msg(rs,"oh no! An arrow shot you"); + } + else + { + arrow = new_item(); + init_weapon(arrow, ARROW); + arrow->o_count = 1; + arrow->o_pos = hero; + fall(rs,arrow, FALSE); + msg(rs,"an arrow shoots past you"); + } + when T_TELEP: + /* + * since the hero's leaving, look() won't put a TRAP + * down for us, so we have to do it ourself + */ + teleport(rs); + mvaddch(tc->y, tc->x, TRAP); + when T_DART: + if (!swing(pstats.s_lvl+1, pstats.s_arm, 1)) + msg(rs,"a small dart whizzes by your ear and vanishes"); + else + { + pstats.s_hpt -= roll(1, 4); + if (pstats.s_hpt <= 0) + { + msg(rs,"a poisoned dart killed you"); + death('d'); + } + if (!ISWEARING(R_SUSTSTR) && !save(VS_POISON)) + chg_str(-1); + msg(rs,"a small dart just hit you in the shoulder"); + } + when T_RUST: + msg(rs,"a gush of water hits you on the head"); + rust_armor(rs,cur_armor); + } + flush_type(); + return tr; +} + +/* + * rndmove: + * Move in a random direction if the monster/person is confused + */ +coord * +rndmove(THING *who) +{ + THING *obj; + int x, y; + char ch; + static coord ret; /* what we will be returning */ + + y = ret.y = who->t_pos.y + rnd(3) - 1; + x = ret.x = who->t_pos.x + rnd(3) - 1; + /* + * Now check to see if that's a legal move. If not, don't move. + * (I.e., bump into the wall or whatever) + */ + if (y == who->t_pos.y && x == who->t_pos.x) + return &ret; + if (!diag_ok(&who->t_pos, &ret)) + goto bad; + else + { + ch = winat(y, x); + if (!step_ok(ch)) + goto bad; + if (ch == SCROLL) + { + for (obj = lvl_obj; obj != NULL; obj = next(obj)) + if (y == obj->o_pos.y && x == obj->o_pos.x) + break; + if (obj != NULL && obj->o_which == S_SCARE) + goto bad; + } + } + return &ret; + +bad: + ret = who->t_pos; + return &ret; +} + +/* + * rust_armor: + * Rust the given armor, if it is a legal kind to rust, and we + * aren't wearing a magic ring. + */ + +void +rust_armor(struct rogue_state *rs,THING *arm) +{ + if (arm == NULL || arm->o_type != ARMOR || arm->o_which == LEATHER || + arm->o_arm >= 9) + return; + + if ((arm->o_flags & ISPROT) || ISWEARING(R_SUSTARM)) + { + if (!to_death) + msg(rs,"the rust vanishes instantly"); + } + else + { + arm->o_arm++; + if (!terse) + msg(rs,"your armor appears to be weaker now. Oh my!"); + else + msg(rs,"your armor weakens"); + } +} diff --git a/src/cc/rogue/new_level.c b/src/cc/rogue/new_level.c new file mode 100644 index 000000000..2c0ae7b51 --- /dev/null +++ b/src/cc/rogue/new_level.c @@ -0,0 +1,231 @@ +/* + * new_level: + * Dig and draw a new level + * + * @(#)new_level.c 4.38 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include "rogue.h" + +#define TREAS_ROOM 20 /* one chance in TREAS_ROOM for a treasure room */ +#define MAXTREAS 10 /* maximum number of treasures in a treasure room */ +#define MINTREAS 2 /* minimum number of treasures in a treasure room */ + +void +new_level(struct rogue_state *rs) +{ + THING *tp; + PLACE *pp; + char *sp; + int i; + + player.t_flags &= ~ISHELD; /* unhold when you go down just in case */ + if (level > max_level) + max_level = level; + /* + * Clean things off from last level + */ + for (pp = places; pp < &places[MAXCOLS*MAXLINES]; pp++) + { + pp->p_ch = ' '; + pp->p_flags = F_REAL; + pp->p_monst = NULL; + } + clear(); + /* + * Free up the monsters on the last level + */ + for (tp = mlist; tp != NULL; tp = next(tp)) + free_list(tp->t_pack); + free_list(mlist); + /* + * Throw away stuff left on the previous level (if anything) + */ + free_list(lvl_obj); + do_rooms(rs); /* Draw rooms */ + do_passages(rs); /* Draw passages */ + no_food++; + put_things(rs); /* Place objects (if any) */ + /* + * Place the traps + */ + if (rnd(10) < level) + { + ntraps = rnd(level / 4) + 1; + if (ntraps > MAXTRAPS) + ntraps = MAXTRAPS; + i = ntraps; + while (i--) + { + /* + * not only wouldn't it be NICE to have traps in mazes + * (not that we care about being nice), since the trap + * number is stored where the passage number is, we + * can't actually do it. + */ + do + { + find_floor((struct room *) NULL, &stairs, FALSE, FALSE); + } while (chat(stairs.y, stairs.x) != FLOOR); + sp = &flat(stairs.y, stairs.x); + *sp &= ~F_REAL; + *sp |= rnd(NTRAPS); + } + } + /* + * Place the staircase down. + */ + find_floor((struct room *) NULL, &stairs, FALSE, FALSE); + chat(stairs.y, stairs.x) = STAIRS; + seenstairs = FALSE; + + for (tp = mlist; tp != NULL; tp = next(tp)) + tp->t_room = roomin(rs,&tp->t_pos); + + find_floor((struct room *) NULL, &hero, FALSE, TRUE); + enter_room(rs,&hero); + mvaddch(hero.y, hero.x, PLAYER); + if (on(player, SEEMONST)) + turn_see(FALSE); + if (on(player, ISHALU)) + visuals(rs,0); +} + +/* + * rnd_room: + * Pick a room that is really there + */ +int +rnd_room() +{ + int rm; + + do + { + rm = rnd(MAXROOMS); + } while (rooms[rm].r_flags & ISGONE); + return rm; +} + +/* + * put_things: + * Put potions and scrolls on this level + */ + +void +put_things(struct rogue_state *rs) +{ + int i; + THING *obj; + + /* + * Once you have found the amulet, the only way to get new stuff is + * go down into the dungeon. + */ + if (amulet && level < max_level) + return; + /* + * check for treasure rooms, and if so, put it in. + */ + if (rnd(TREAS_ROOM) == 0) + treas_room(rs); + /* + * Do MAXOBJ attempts to put things on a level + */ + for (i = 0; i < MAXOBJ; i++) + if (rnd(100) < 36) + { + /* + * Pick a new object and link it in the list + */ + obj = new_thing(rs); + attach(lvl_obj, obj); + /* + * Put it somewhere + */ + find_floor((struct room *) NULL, &obj->o_pos, FALSE, FALSE); + chat(obj->o_pos.y, obj->o_pos.x) = (char) obj->o_type; + } + /* + * If he is really deep in the dungeon and he hasn't found the + * amulet yet, put it somewhere on the ground + */ + if (level >= AMULETLEVEL && !amulet) + { + obj = new_item(); + attach(lvl_obj, obj); + obj->o_hplus = 0; + obj->o_dplus = 0; + strncpy(obj->o_damage,"0x0",sizeof(obj->o_damage)); + strncpy(obj->o_hurldmg,"0x0",sizeof(obj->o_hurldmg)); + obj->o_arm = 11; + obj->o_type = AMULET; + /* + * Put it somewhere + */ + find_floor((struct room *) NULL, &obj->o_pos, FALSE, FALSE); + chat(obj->o_pos.y, obj->o_pos.x) = AMULET; + } +} + +/* + * treas_room: + * Add a treasure room + */ +#define MAXTRIES 10 /* max number of tries to put down a monster */ + + +void +treas_room(struct rogue_state *rs) +{ + int nm; + THING *tp; + struct room *rp; + int spots, num_monst; + static coord mp; + + rp = &rooms[rnd_room()]; + spots = (rp->r_max.y - 2) * (rp->r_max.x - 2) - MINTREAS; + if (spots > (MAXTREAS - MINTREAS)) + spots = (MAXTREAS - MINTREAS); + num_monst = nm = rnd(spots) + MINTREAS; + while (nm--) + { + find_floor(rp, &mp, 2 * MAXTRIES, FALSE); + tp = new_thing(rs); + tp->o_pos = mp; + attach(lvl_obj, tp); + chat(mp.y, mp.x) = (char) tp->o_type; + } + + /* + * fill up room with monsters from the next level down + */ + + if ((nm = rnd(spots) + MINTREAS) < num_monst + 2) + nm = num_monst + 2; + spots = (rp->r_max.y - 2) * (rp->r_max.x - 2); + if (nm > spots) + nm = spots; + level++; + while (nm--) + { + spots = 0; + if (find_floor(rp, &mp, MAXTRIES, TRUE)) + { + tp = new_item(); + new_monster(rs,tp, randmonster(FALSE), &mp); + tp->t_flags |= ISMEAN; /* no sloughers in THIS room */ + give_pack(rs,tp); + } + } + level--; +} diff --git a/src/cc/rogue/options.c b/src/cc/rogue/options.c new file mode 100644 index 000000000..667d83248 --- /dev/null +++ b/src/cc/rogue/options.c @@ -0,0 +1,501 @@ +/* + * This file has all the code for the option command. I would rather + * this command were not necessary, but it is the only way to keep the + * wolves off of my back. + * + * @(#)options.c 4.24 (Berkeley) 05/10/83 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include +#include +#include "rogue.h" + +#define EQSTR(a, b, c) (strncmp(a, b, c) == 0) + +#define NUM_OPTS (sizeof optlist / sizeof (OPTION)) + +/* + * description of an option and what to do with it + */ +struct optstruct { + char *o_name; /* option name */ + char *o_prompt; /* prompt for interactive entry */ + void *o_opt; /* pointer to thing to set */ + /* function to print value */ + void (*o_putfunc)(void *opt); + /* function to get value interactively */ + int (*o_getfunc)(struct rogue_state *rs,void *opt, WINDOW *win); +}; + +typedef struct optstruct OPTION; + +void pr_optname(OPTION *op); + +OPTION optlist[] = { + {"terse", "Terse output", + &terse, put_bool, get_bool }, + {"flush", "Flush typeahead during battle", + &fight_flush, put_bool, get_bool }, + {"jump", "Show position only at end of run", + &jump, put_bool, get_bool }, + {"seefloor", "Show the lamp-illuminated floor", + &see_floor, put_bool, get_sf }, + {"passgo", "Follow turnings in passageways", + &passgo, put_bool, get_bool }, + {"tombstone", "Print out tombstone when killed", + &tombstone, put_bool, get_bool }, + {"inven", "Inventory style", + &inv_type, put_inv_t, get_inv_t }, + {"name", "Name", + whoami, put_str, get_str }, + {"fruit", "Fruit", + fruit, put_str, get_str }, + {"file", "Save file", + file_name, put_str, get_str } +}; + +/* + * option: + * Print and then set options from the terminal + */ + +void +option(struct rogue_state *rs) +{ + OPTION *op; + int retval; + + wclear(hw); + /* + * Display current values of options + */ + for (op = optlist; op <= &optlist[NUM_OPTS-1]; op++) + { + pr_optname(op); + (*op->o_putfunc)(op->o_opt); + waddch(hw, '\n'); + } + /* + * Set values + */ + wmove(hw, 0, 0); + for (op = optlist; op <= &optlist[NUM_OPTS-1]; op++) + { + pr_optname(op); + retval = (*op->o_getfunc)(rs,op->o_opt, hw); + if (retval) + { + if (retval == QUIT) + break; + else if (op > optlist) { /* MINUS */ + wmove(hw, (int)(op - optlist) - 1, 0); + op -= 2; + } + else /* trying to back up beyond the top */ + { + putchar('\007'); + wmove(hw, 0, 0); + op--; + } + } + } + /* + * Switch back to original screen + */ + wmove(hw, LINES - 1, 0); + waddstr(hw, "--Press space to continue--"); + wrefresh(hw); + wait_for(rs,' '); + clearok(curscr, TRUE); + touchwin(stdscr); + after = FALSE; +} + +/* + * pr_optname: + * Print out the option name prompt + */ + +void +pr_optname(OPTION *op) +{ + wprintw(hw, "%s (\"%s\"): ", op->o_prompt, op->o_name); +} + +/* + * put_bool + * Put out a boolean + */ + +void +put_bool(void *b) +{ + waddstr(hw, *(bool *) b ? "True" : "False"); +} + +/* + * put_str: + * Put out a string + */ + +void +put_str(void *str) +{ + waddstr(hw, (char *) str); +} + +/* + * put_inv_t: + * Put out an inventory type + */ + +void +put_inv_t(void *ip) +{ + waddstr(hw, inv_t_name[*(int *) ip]); +} + +/* + * get_bool: + * Allow changing a boolean option and print it out + */ +int +get_bool(struct rogue_state *rs,void *vp, WINDOW *win) +{ + bool *bp = (bool *) vp; + int oy, ox; + bool op_bad; + + op_bad = TRUE; + getyx(win, oy, ox); + waddstr(win, *bp ? "True" : "False"); + while (op_bad) + { + wmove(win, oy, ox); + wrefresh(win); + switch (readchar(rs)) + { + case 't': + case 'T': + *bp = TRUE; + op_bad = FALSE; + break; + case 'f': + case 'F': + *bp = FALSE; + op_bad = FALSE; + break; + case '\n': + case '\r': + op_bad = FALSE; + break; + case ESCAPE: + return QUIT; + case '-': + return MINUS; + default: + wmove(win, oy, ox + 10); + waddstr(win, "(T or F)"); + } + } + wmove(win, oy, ox); + waddstr(win, *bp ? "True" : "False"); + waddch(win, '\n'); + return NORM; +} + +/* + * get_sf: + * Change value and handle transition problems from see_floor to + * !see_floor. + */ +int +get_sf(struct rogue_state *rs,void *vp, WINDOW *win) +{ + bool *bp = (bool *) vp; + bool was_sf; + int retval; + + was_sf = see_floor; + retval = get_bool(rs,bp, win); + if (retval == QUIT) return(QUIT); + if (was_sf != see_floor) + { + if (!see_floor) { + see_floor = TRUE; + erase_lamp(&hero, proom); + see_floor = FALSE; + } + else + look(rs,FALSE); + } + return(NORM); +} + +/* + * get_str: + * Set a string option + */ +#define MAXINP 50 /* max string to read from terminal or environment */ + +int +get_str(struct rogue_state *rs,void *vopt, WINDOW *win) +{ + char *opt = (char *) vopt; + char *sp; + int oy, ox; + int i; + signed char c; + static char buf[MAXSTR]; + + getyx(win, oy, ox); + wrefresh(win); + /* + * loop reading in the string, and put it in a temporary buffer + */ + for (sp = buf; (c = readchar(rs)) != '\n' && c != '\r' && c != ESCAPE; + wclrtoeol(win), wrefresh(win)) + { + if (c == -1) + continue; + else if (c == erasechar()) /* process erase character */ + { + if (sp > buf) + { + sp--; + for (i = (int) strlen(unctrl(*sp)); i; i--) + waddch(win, '\b'); + } + continue; + } + else if (c == killchar()) /* process kill character */ + { + sp = buf; + wmove(win, oy, ox); + continue; + } + else if (sp == buf) + { + if (c == '-' && win != stdscr) + break; + else if (c == '~') + { + strcpy(buf, home); + waddstr(win, home); + sp += strlen(home); + continue; + } + } + if (sp >= &buf[MAXINP] || !(isprint(c) || c == ' ')) + putchar(CTRL('G')); + else + { + *sp++ = c; + waddstr(win, unctrl(c)); + } + } + *sp = '\0'; + if (sp > buf) /* only change option if something has been typed */ + strucpy(opt, buf, (int) strlen(buf)); + mvwprintw(win, oy, ox, "%s\n", opt); + wrefresh(win); + if (win == stdscr) + mpos += (int)(sp - buf); + if (c == '-') + return MINUS; + else if (c == ESCAPE) + return QUIT; + else + return NORM; +} + +/* + * get_inv_t + * Get an inventory type name + */ +int +get_inv_t(struct rogue_state *rs,void *vp, WINDOW *win) +{ + int *ip = (int *) vp; + int oy, ox; + bool op_bad; + + op_bad = TRUE; + getyx(win, oy, ox); + waddstr(win, inv_t_name[*ip]); + while (op_bad) + { + wmove(win, oy, ox); + wrefresh(win); + switch (readchar(rs)) + { + case 'o': + case 'O': + *ip = INV_OVER; + op_bad = FALSE; + break; + case 's': + case 'S': + *ip = INV_SLOW; + op_bad = FALSE; + break; + case 'c': + case 'C': + *ip = INV_CLEAR; + op_bad = FALSE; + break; + case '\n': + case '\r': + op_bad = FALSE; + break; + case ESCAPE: + return QUIT; + case '-': + return MINUS; + default: + wmove(win, oy, ox + 15); + waddstr(win, "(O, S, or C)"); + } + } + mvwprintw(win, oy, ox, "%s\n", inv_t_name[*ip]); + return NORM; +} + + +#ifdef MASTER +/* + * get_num: + * Get a numeric option + */ +int +get_num(struct rogue_state *rs,void *vp, WINDOW *win) +{ + short *opt = (short *) vp; + int i; + static char buf[MAXSTR]; + + if ((i = get_str(rs,buf, win)) == NORM) + *opt = (short) atoi(buf); + return i; +} +#endif + +/* + * parse_opts: + * Parse options from string, usually taken from the environment. + * The string is a series of comma seperated values, with booleans + * being stated as "name" (true) or "noname" (false), and strings + * being "name=....", with the string being defined up to a comma + * or the end of the entire option string. + */ + +void +parse_opts(char *str) +{ + char *sp; + OPTION *op; + int len; + char **i; + char *start; + + while (*str) + { + /* + * Get option name + */ + for (sp = str; isalpha(*sp); sp++) + continue; + len = (int)(sp - str); + /* + * Look it up and deal with it + */ + for (op = optlist; op <= &optlist[NUM_OPTS-1]; op++) + if (EQSTR(str, op->o_name, len)) + { + if (op->o_putfunc == put_bool) /* if option is a boolean */ + *(bool *)op->o_opt = TRUE; /* NOSTRICT */ + else /* string option */ + { + /* + * Skip to start of string value + */ + for (str = sp + 1; *str == '='; str++) + continue; + if (*str == '~') + { + strcpy((char *) op->o_opt, home); /* NOSTRICT */ + start = (char *) op->o_opt + strlen(home);/* NOSTRICT */ + while (*++str == '/') + continue; + } + else + start = (char *) op->o_opt; /* NOSTRICT */ + /* + * Skip to end of string value + */ + for (sp = str + 1; *sp && *sp != ','; sp++) + continue; + /* + * check for type of inventory + */ + if (op->o_putfunc == put_inv_t) + { + if (islower(*str)) + *str = (char) toupper(*str); + for (i = inv_t_name; i <= &inv_t_name[INV_CLEAR]; i++) + if (strncmp(str, *i, sp - str) == 0) + { + inv_type = (int)(i - inv_t_name); + break; + } + } + else + strucpy(start, str, (int)(sp - str)); + } + break; + } + /* + * check for "noname" for booleans + */ + else if (op->o_putfunc == put_bool + && EQSTR(str, "no", 2) && EQSTR(str + 2, op->o_name, len - 2)) + { + *(bool *)op->o_opt = FALSE; /* NOSTRICT */ + break; + } + + /* + * skip to start of next option name + */ + while (*sp && !isalpha(*sp)) + sp++; + str = sp; + } +} + +/* + * strucpy: + * Copy string using unctrl for things + */ + +void +strucpy(char *s1, char *s2, int len) +{ + if (len > MAXINP) + len = MAXINP; + while (len--) + { + if (isprint(*s2) || *s2 == ' ') + *s1++ = *s2; + s2++; + } + *s1 = '\0'; +} diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c new file mode 100644 index 000000000..8c92718b5 --- /dev/null +++ b/src/cc/rogue/pack.c @@ -0,0 +1,503 @@ +/* + * Routines to deal with the pack + * + * @(#)pack.c 4.40 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include +#include "rogue.h" + +/* + * add_pack: + * Pick up an object and add it to the pack. If the argument is + * non-null use it as the linked_list pointer instead of gettting + * it off the ground. + */ + +void +add_pack(struct rogue_state *rs,THING *obj, bool silent) +{ + THING *op, *lp; + bool from_floor; + + from_floor = FALSE; + if (obj == NULL) + { + if ((obj = find_obj(rs,hero.y, hero.x)) == NULL) + return; + from_floor = TRUE; + } + + /* + * Check for and deal with scare monster scrolls + */ + if (obj->o_type == SCROLL && obj->o_which == S_SCARE) + if (obj->o_flags & ISFOUND) + { + detach(lvl_obj, obj); + mvaddch(hero.y, hero.x, floor_ch()); + chat(hero.y, hero.x) = (proom->r_flags & ISGONE) ? PASSAGE : FLOOR; + discard(obj); + msg(rs,"the scroll turns to dust as you pick it up"); + return; + } + + if (pack == NULL) + { + pack = obj; + obj->o_packch = pack_char(); + inpack++; + } + else + { + lp = NULL; + for (op = pack; op != NULL; op = next(op)) + { + if (op->o_type != obj->o_type) + lp = op; + else + { + while (op->o_type == obj->o_type && op->o_which != obj->o_which) + { + lp = op; + if (next(op) == NULL) + break; + else + op = next(op); + } + if (op->o_type == obj->o_type && op->o_which == obj->o_which) + { + if (ISMULT(op->o_type)) + { + if (!pack_room(rs,from_floor, obj)) + return; + op->o_count++; +dump_it: + discard(obj); + obj = op; + lp = NULL; + goto out; + } + else if (obj->o_group) + { + lp = op; + while (op->o_type == obj->o_type + && op->o_which == obj->o_which + && op->o_group != obj->o_group) + { + lp = op; + if (next(op) == NULL) + break; + else + op = next(op); + } + if (op->o_type == obj->o_type + && op->o_which == obj->o_which + && op->o_group == obj->o_group) + { + op->o_count += obj->o_count; + inpack--; + if (!pack_room(rs,from_floor, obj)) + return; + goto dump_it; + } + } + else + lp = op; + } +out: + break; + } + } + + if (lp != NULL) + { + if (!pack_room(rs,from_floor, obj)) + return; + else + { + obj->o_packch = pack_char(); + next(obj) = next(lp); + prev(obj) = lp; + if (next(lp) != NULL) + prev(next(lp)) = obj; + next(lp) = obj; + } + } + } + + obj->o_flags |= ISFOUND; + + /* + * If this was the object of something's desire, that monster will + * get mad and run at the hero. + */ + for (op = mlist; op != NULL; op = next(op)) + if (op->t_dest == &obj->o_pos) + op->t_dest = &hero; + + if (obj->o_type == AMULET) + amulet = TRUE; + /* + * Notify the user + */ + if (!silent) + { + if (!terse) + addmsg(rs,"you now have "); + msg(rs,"%s (%c)", inv_name(obj, !terse), obj->o_packch); + } +} + +/* + * pack_room: + * See if there's room in the pack. If not, print out an + * appropriate message + */ +bool +pack_room(struct rogue_state *rs,bool from_floor, THING *obj) +{ + if (++inpack > MAXPACK) + { + if (!terse) + addmsg(rs,"there's "); + addmsg(rs,"no room"); + if (!terse) + addmsg(rs," in your pack"); + endmsg(rs); + if (from_floor) + move_msg(rs,obj); + inpack = MAXPACK; + return FALSE; + } + + if (from_floor) + { + detach(lvl_obj, obj); + mvaddch(hero.y, hero.x, floor_ch()); + chat(hero.y, hero.x) = (proom->r_flags & ISGONE) ? PASSAGE : FLOOR; + } + + return TRUE; +} + +/* + * leave_pack: + * take an item out of the pack + */ +THING * +leave_pack(struct rogue_state *rs,THING *obj, bool newobj, bool all) +{ + THING *nobj; + + inpack--; + nobj = obj; + if (obj->o_count > 1 && !all) + { + last_pick = obj; + obj->o_count--; + if (obj->o_group) + inpack++; + if (newobj) + { + nobj = new_item(); + *nobj = *obj; + next(nobj) = NULL; + prev(nobj) = NULL; + nobj->o_count = 1; + } + } + else + { + last_pick = NULL; + pack_used[obj->o_packch - 'a'] = FALSE; + detach(pack, obj); + } + return nobj; +} + +/* + * pack_char: + * Return the next unused pack character. + */ +char +pack_char() +{ + bool *bp; + + for (bp = pack_used; *bp; bp++) + continue; + *bp = TRUE; + return (char)((int)(bp - pack_used) + 'a'); +} + +/* + * inventory: + * List what is in the pack. Return TRUE if there is something of + * the given type. + */ +bool +inventory(struct rogue_state *rs,THING *list, int type) +{ + static char inv_temp[MAXSTR]; + + n_objs = 0; + for (; list != NULL; list = next(list)) + { + if (type && type != list->o_type && !(type == CALLABLE && + list->o_type != FOOD && list->o_type != AMULET) && + !(type == R_OR_S && (list->o_type == RING || list->o_type == STICK))) + continue; + n_objs++; +#ifdef MASTER + if (!list->o_packch) + strcpy(inv_temp, "%s"); + else +#endif + sprintf(inv_temp, "%c) %%s", list->o_packch); + msg_esc = TRUE; + if (add_line(rs,inv_temp, inv_name(list, FALSE)) == ESCAPE) + { + msg_esc = FALSE; + msg(rs,""); + return TRUE; + } + msg_esc = FALSE; + } + if (n_objs == 0) + { + if (terse) + msg(rs,type == 0 ? "empty handed" : + "nothing appropriate"); + else + msg(rs,type == 0 ? "you are empty handed" : + "you don't have anything appropriate"); + return FALSE; + } + end_line(rs); + return TRUE; +} + +/* + * pick_up: + * Add something to characters pack. + */ + +void +pick_up(struct rogue_state *rs,char ch) +{ + THING *obj; + + if (on(player, ISLEVIT)) + return; + + obj = find_obj(rs,hero.y, hero.x); + if (move_on) + move_msg(rs,obj); + else + switch (ch) + { + case GOLD: + if (obj == NULL) + return; + money(rs,obj->o_goldval); + detach(lvl_obj, obj); + discard(obj); + proom->r_goldval = 0; + break; + default: +#ifdef MASTER + debug("Where did you pick a '%s' up???", unctrl(ch)); +#endif + case ARMOR: + case POTION: + case FOOD: + case WEAPON: + case SCROLL: + case AMULET: + case RING: + case STICK: + add_pack(rs,(THING *) NULL, FALSE); + break; + } +} + +/* + * move_msg: + * Print out the message if you are just moving onto an object + */ + +void +move_msg(struct rogue_state *rs,THING *obj) +{ + if (!terse) + addmsg(rs,"you "); + msg(rs,"moved onto %s", inv_name(obj, TRUE)); +} + +/* + * picky_inven: + * Allow player to inventory a single item + */ + +void +picky_inven(struct rogue_state *rs) +{ + THING *obj; + char mch; + + if (pack == NULL) + msg(rs,"you aren't carrying anything"); + else if (next(pack) == NULL) + msg(rs,"a) %s", inv_name(pack, FALSE)); + else + { + msg(rs,terse ? "item: " : "which item do you wish to inventory: "); + mpos = 0; + if ((mch = readchar(rs)) == ESCAPE) + { + msg(rs,""); + return; + } + for (obj = pack; obj != NULL; obj = next(obj)) + if (mch == obj->o_packch) + { + msg(rs,"%c) %s", mch, inv_name(obj, FALSE)); + return; + } + msg(rs,"'%s' not in pack", unctrl(mch)); + } +} + +/* + * get_item: + * Pick something out of a pack for a purpose + */ +THING * +get_item(struct rogue_state *rs,char *purpose, int type) +{ + THING *obj; + char ch; + + if (pack == NULL) + msg(rs,"you aren't carrying anything"); + else if (again) + if (last_pick) + return last_pick; + else + msg(rs,"you ran out"); + else + { + for (;;) + { + if (!terse) + addmsg(rs,"which object do you want to "); + addmsg(rs,purpose); + if (terse) + addmsg(rs," what"); + msg(rs,"? (* for list): "); + ch = readchar(rs); + mpos = 0; + /* + * Give the poor player a chance to abort the command + */ + if (ch == ESCAPE) + { + reset_last(); + after = FALSE; + msg(rs,""); + return NULL; + } + n_objs = 1; /* normal case: person types one char */ + if (ch == '*') + { + mpos = 0; + if (inventory(rs,pack, type) == 0) + { + after = FALSE; + return NULL; + } + continue; + } + for (obj = pack; obj != NULL; obj = next(obj)) + if (obj->o_packch == ch) + break; + if (obj == NULL) + { + msg(rs,"'%s' is not a valid item",unctrl(ch)); + continue; + } + else + return obj; + } + } + return NULL; +} + +/* + * money: + * Add or subtract gold from the pack + */ + +void +money(struct rogue_state *rs,int value) +{ + purse += value; + mvaddch(hero.y, hero.x, floor_ch()); + chat(hero.y, hero.x) = (proom->r_flags & ISGONE) ? PASSAGE : FLOOR; + if (value > 0) + { + if (!terse) + addmsg(rs,"you found "); + msg(rs,"%d gold pieces", value); + } +} + +/* + * floor_ch: + * Return the appropriate floor character for her room + */ +char +floor_ch() +{ + if (proom->r_flags & ISGONE) + return PASSAGE; + return (show_floor() ? FLOOR : ' '); +} + +/* + * floor_at: + * Return the character at hero's position, taking see_floor + * into account + */ +char +floor_at() +{ + char ch; + + ch = chat(hero.y, hero.x); + if (ch == FLOOR) + ch = floor_ch(); + return ch; +} + +/* + * reset_last: + * Reset the last command when the current one is aborted + */ + +void +reset_last() +{ + last_comm = l_last_comm; + last_dir = l_last_dir; + last_pick = l_last_pick; +} diff --git a/src/cc/rogue/passages.c b/src/cc/rogue/passages.c new file mode 100644 index 000000000..6d9cd17b1 --- /dev/null +++ b/src/cc/rogue/passages.c @@ -0,0 +1,424 @@ +/* + * Draw the connecting passages + * + * @(#)passages.c 4.22 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include "rogue.h" + +/* + * do_passages: + * Draw all the passages on a level. + */ + +void +do_passages(struct rogue_state *rs) +{ + struct rdes *r1, *r2 = NULL; + int i, j; + int roomcount; + static struct rdes + { + bool conn[MAXROOMS]; /* possible to connect to room i? */ + bool isconn[MAXROOMS]; /* connection been made to room i? */ + bool ingraph; /* this room in graph already? */ + } rdes[MAXROOMS] = { + { { 0, 1, 0, 1, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0 }, + { { 1, 0, 1, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0 }, + { { 0, 1, 0, 0, 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0 }, + { { 1, 0, 0, 0, 1, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0 }, + { { 0, 1, 0, 1, 0, 1, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0 }, + { { 0, 0, 1, 0, 1, 0, 0, 0, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0 }, + { { 0, 0, 0, 1, 0, 0, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0 }, + { { 0, 0, 0, 0, 1, 0, 1, 0, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0 }, + { { 0, 0, 0, 0, 0, 1, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0 }, + }; + + /* + * reinitialize room graph description + */ + for (r1 = rdes; r1 <= &rdes[MAXROOMS-1]; r1++) + { + for (j = 0; j < MAXROOMS; j++) + r1->isconn[j] = FALSE; + r1->ingraph = FALSE; + } + + /* + * starting with one room, connect it to a random adjacent room and + * then pick a new room to start with. + */ + roomcount = 1; + r1 = &rdes[rnd(MAXROOMS)]; + r1->ingraph = TRUE; + do + { + /* + * find a room to connect with + */ + j = 0; + for (i = 0; i < MAXROOMS; i++) + if (r1->conn[i] && !rdes[i].ingraph && rnd(++j) == 0) + r2 = &rdes[i]; + /* + * if no adjacent rooms are outside the graph, pick a new room + * to look from + */ + if (j == 0) + { + do + r1 = &rdes[rnd(MAXROOMS)]; + until (r1->ingraph); + } + /* + * otherwise, connect new room to the graph, and draw a tunnel + * to it + */ + else + { + r2->ingraph = TRUE; + i = (int)(r1 - rdes); + j = (int)(r2 - rdes); + conn(rs,i, j); + r1->isconn[j] = TRUE; + r2->isconn[i] = TRUE; + roomcount++; + } + } while (roomcount < MAXROOMS); + + /* + * attempt to add passages to the graph a random number of times so + * that there isn't always just one unique passage through it. + */ + for (roomcount = rnd(5); roomcount > 0; roomcount--) + { + r1 = &rdes[rnd(MAXROOMS)]; /* a random room to look from */ + /* + * find an adjacent room not already connected + */ + j = 0; + for (i = 0; i < MAXROOMS; i++) + if (r1->conn[i] && !r1->isconn[i] && rnd(++j) == 0) + r2 = &rdes[i]; + /* + * if there is one, connect it and look for the next added + * passage + */ + if (j != 0) + { + i = (int)(r1 - rdes); + j = (int)(r2 - rdes); + conn(rs,i, j); + r1->isconn[j] = TRUE; + r2->isconn[i] = TRUE; + } + } + passnum(); +} + +/* + * conn: + * Draw a corridor from a room in a certain direction. + */ + +void +conn(struct rogue_state *rs,int r1, int r2) +{ + struct room *rpf, *rpt = NULL; + int rmt; + int distance = 0, turn_spot, turn_distance = 0; + int rm; + char direc; + static coord del, curr, turn_delta, spos, epos; + + if (r1 < r2) + { + rm = r1; + if (r1 + 1 == r2) + direc = 'r'; + else + direc = 'd'; + } + else + { + rm = r2; + if (r2 + 1 == r1) + direc = 'r'; + else + direc = 'd'; + } + rpf = &rooms[rm]; + /* + * Set up the movement variables, in two cases: + * first drawing one down. + */ + if (direc == 'd') + { + rmt = rm + 3; /* room # of dest */ + rpt = &rooms[rmt]; /* room pointer of dest */ + del.x = 0; /* direction of move */ + del.y = 1; + spos.x = rpf->r_pos.x; /* start of move */ + spos.y = rpf->r_pos.y; + epos.x = rpt->r_pos.x; /* end of move */ + epos.y = rpt->r_pos.y; + if (!(rpf->r_flags & ISGONE)) /* if not gone pick door pos */ + do + { + spos.x = rpf->r_pos.x + rnd(rpf->r_max.x - 2) + 1; + spos.y = rpf->r_pos.y + rpf->r_max.y - 1; + } while ((rpf->r_flags&ISMAZE) && !(flat(spos.y, spos.x)&F_PASS)); + if (!(rpt->r_flags & ISGONE)) + do + { + epos.x = rpt->r_pos.x + rnd(rpt->r_max.x - 2) + 1; + } while ((rpt->r_flags&ISMAZE) && !(flat(epos.y, epos.x)&F_PASS)); + distance = abs(spos.y - epos.y) - 1; /* distance to move */ + turn_delta.y = 0; /* direction to turn */ + turn_delta.x = (spos.x < epos.x ? 1 : -1); + turn_distance = abs(spos.x - epos.x); /* how far to turn */ + } + else if (direc == 'r') /* setup for moving right */ + { + rmt = rm + 1; + rpt = &rooms[rmt]; + del.x = 1; + del.y = 0; + spos.x = rpf->r_pos.x; + spos.y = rpf->r_pos.y; + epos.x = rpt->r_pos.x; + epos.y = rpt->r_pos.y; + if (!(rpf->r_flags & ISGONE)) + do + { + spos.x = rpf->r_pos.x + rpf->r_max.x - 1; + spos.y = rpf->r_pos.y + rnd(rpf->r_max.y - 2) + 1; + } while ((rpf->r_flags&ISMAZE) && !(flat(spos.y, spos.x)&F_PASS)); + if (!(rpt->r_flags & ISGONE)) + do + { + epos.y = rpt->r_pos.y + rnd(rpt->r_max.y - 2) + 1; + } while ((rpt->r_flags&ISMAZE) && !(flat(epos.y, epos.x)&F_PASS)); + distance = abs(spos.x - epos.x) - 1; + turn_delta.y = (spos.y < epos.y ? 1 : -1); + turn_delta.x = 0; + turn_distance = abs(spos.y - epos.y); + } +#ifdef MASTER + else + debug("error in connection tables"); +#endif + + turn_spot = rnd(distance - 1) + 1; /* where turn starts */ + + /* + * Draw in the doors on either side of the passage or just put #'s + * if the rooms are gone. + */ + if (!(rpf->r_flags & ISGONE)) + door(rpf, &spos); + else + putpass(&spos); + if (!(rpt->r_flags & ISGONE)) + door(rpt, &epos); + else + putpass(&epos); + /* + * Get ready to move... + */ + curr.x = spos.x; + curr.y = spos.y; + while (distance > 0) + { + /* + * Move to new position + */ + curr.x += del.x; + curr.y += del.y; + /* + * Check if we are at the turn place, if so do the turn + */ + if (distance == turn_spot) + while (turn_distance--) + { + putpass(&curr); + curr.x += turn_delta.x; + curr.y += turn_delta.y; + } + /* + * Continue digging along + */ + putpass(&curr); + distance--; + } + curr.x += del.x; + curr.y += del.y; + if (!ce(curr, epos)) + msg(rs,"warning, connectivity problem on this level"); +} + +/* + * putpass: + * add a passage character or secret passage here + */ + +void +putpass(coord *cp) +{ + PLACE *pp; + + pp = INDEX(cp->y, cp->x); + pp->p_flags |= F_PASS; + if (rnd(10) + 1 < level && rnd(40) == 0) + pp->p_flags &= ~F_REAL; + else + pp->p_ch = PASSAGE; +} + +/* + * door: + * Add a door or possibly a secret door. Also enters the door in + * the exits array of the room. + */ + +void +door(struct room *rm, coord *cp) +{ + PLACE *pp; + + rm->r_exit[rm->r_nexits++] = *cp; + + if (rm->r_flags & ISMAZE) + return; + + pp = INDEX(cp->y, cp->x); + if (rnd(10) + 1 < level && rnd(5) == 0) + { + if (cp->y == rm->r_pos.y || cp->y == rm->r_pos.y + rm->r_max.y - 1) + pp->p_ch = '-'; + else + pp->p_ch = '|'; + pp->p_flags &= ~F_REAL; + } + else + pp->p_ch = DOOR; +} + +#ifdef MASTER +/* + * add_pass: + * Add the passages to the current window (wizard command) + */ + +void +add_pass() +{ + PLACE *pp; + int y, x; + char ch; + + for (y = 1; y < NUMLINES - 1; y++) + for (x = 0; x < NUMCOLS; x++) + { + pp = INDEX(y, x); + if ((pp->p_flags & F_PASS) || pp->p_ch == DOOR || + (!(pp->p_flags&F_REAL) && (pp->p_ch == '|' || pp->p_ch == '-'))) + { + ch = pp->p_ch; + if (pp->p_flags & F_PASS) + ch = PASSAGE; + pp->p_flags |= F_SEEN; + move(y, x); + if (pp->p_monst != NULL) + pp->p_monst->t_oldch = pp->p_ch; + else if (pp->p_flags & F_REAL) + addch(ch); + else + { + standout(); + addch((pp->p_flags & F_PASS) ? PASSAGE : DOOR); + standend(); + } + } + } +} +#endif + +/* + * passnum: + * Assign a number to each passageway + */ +static int pnum; +static bool newpnum; + + +void +passnum() +{ + struct room *rp; + int i; + + pnum = 0; + newpnum = FALSE; + for (rp = passages; rp < &passages[MAXPASS]; rp++) + rp->r_nexits = 0; + for (rp = rooms; rp < &rooms[MAXROOMS]; rp++) + for (i = 0; i < rp->r_nexits; i++) + { + newpnum++; + numpass(rp->r_exit[i].y, rp->r_exit[i].x); + } +} + +/* + * numpass: + * Number a passageway square and its brethren + */ + +void +numpass(int y, int x) +{ + char *fp; + struct room *rp; + char ch; + + if (x >= NUMCOLS || x < 0 || y >= NUMLINES || y <= 0) + return; + fp = &flat(y, x); + if (*fp & F_PNUM) + return; + if (newpnum) + { + pnum++; + newpnum = FALSE; + } + /* + * check to see if it is a door or secret door, i.e., a new exit, + * or a numerable type of place + */ + if ((ch = chat(y, x)) == DOOR || + (!(*fp & F_REAL) && (ch == '|' || ch == '-'))) + { + rp = &passages[pnum]; + rp->r_exit[rp->r_nexits].y = y; + rp->r_exit[rp->r_nexits++].x = x; + } + else if (!(*fp & F_PASS)) + return; + *fp |= pnum; + /* + * recurse on the surrounding places + */ + numpass(y + 1, x); + numpass(y - 1, x); + numpass(y, x + 1); + numpass(y, x - 1); +} diff --git a/src/cc/rogue/potions.c b/src/cc/rogue/potions.c new file mode 100644 index 000000000..9839319ee --- /dev/null +++ b/src/cc/rogue/potions.c @@ -0,0 +1,375 @@ +/* + * Function(s) for dealing with potions + * + * @(#)potions.c 4.46 (Berkeley) 06/07/83 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include "rogue.h" + +typedef struct +{ + int pa_flags; + void (*pa_daemon)(struct rogue_state *rs,int); + int pa_time; + char *pa_high, *pa_straight; +} PACT; + +static PACT p_actions[] = +{ + { ISHUH, unconfuse, HUHDURATION, /* P_CONFUSE */ + "what a tripy feeling!", + "wait, what's going on here. Huh? What? Who?" }, + { ISHALU, come_down, SEEDURATION, /* P_LSD */ + "Oh, wow! Everything seems so cosmic!", + "Oh, wow! Everything seems so cosmic!" }, + { 0, NULL, 0 }, /* P_POISON */ + { 0, NULL, 0 }, /* P_STRENGTH */ + { CANSEE, unsee, SEEDURATION, /* P_SEEINVIS */ + prbuf, + prbuf }, + { 0, NULL, 0 }, /* P_HEALING */ + { 0, NULL, 0 }, /* P_MFIND */ + { 0, NULL, 0 }, /* P_TFIND */ + { 0, NULL, 0 }, /* P_RAISE */ + { 0, NULL, 0 }, /* P_XHEAL */ + { 0, NULL, 0 }, /* P_HASTE */ + { 0, NULL, 0 }, /* P_RESTORE */ + { ISBLIND, sight, SEEDURATION, /* P_BLIND */ + "oh, bummer! Everything is dark! Help!", + "a cloak of darkness falls around you" }, + { ISLEVIT, land, HEALTIME, /* P_LEVIT */ + "oh, wow! You're floating in the air!", + "you start to float in the air" } +}; + +/* + * quaff: + * Quaff a potion from the pack + */ + +void +quaff(struct rogue_state *rs) +{ + THING *obj, *tp, *mp; + bool discardit = FALSE; + bool show, trip; + + obj = get_item(rs,"quaff", POTION); + /* + * Make certain that it is somethings that we want to drink + */ + if (obj == NULL) + return; + if (obj->o_type != POTION) + { + if (!terse) + msg(rs,"yuk! Why would you want to drink that?"); + else + msg(rs,"that's undrinkable"); + return; + } + if (obj == cur_weapon) + cur_weapon = NULL; + + /* + * Calculate the effect it has on the poor guy. + */ + trip = on(player, ISHALU); + discardit = (bool)(obj->o_count == 1); + leave_pack(rs,obj, FALSE, FALSE); + switch (obj->o_which) + { + case P_CONFUSE: + do_pot(rs,P_CONFUSE, !trip); + when P_POISON: + pot_info[P_POISON].oi_know = TRUE; + if (ISWEARING(R_SUSTSTR)) + msg(rs,"you feel momentarily sick"); + else + { + chg_str(-(rnd(3) + 1)); + msg(rs,"you feel very sick now"); + come_down(rs,0); + } + when P_HEALING: + pot_info[P_HEALING].oi_know = TRUE; + if ((pstats.s_hpt += roll(pstats.s_lvl, 4)) > max_hp) + pstats.s_hpt = ++max_hp; + sight(rs,0); + msg(rs,"you begin to feel better"); + when P_STRENGTH: + pot_info[P_STRENGTH].oi_know = TRUE; + chg_str(1); + msg(rs,"you feel stronger, now. What bulging muscles!"); + when P_MFIND: + player.t_flags |= SEEMONST; + fuse((void(*)(struct rogue_state *rs,int))turn_see, TRUE, HUHDURATION, AFTER); + if (!turn_see(FALSE)) + msg(rs,"you have a %s feeling for a moment, then it passes", + choose_str("normal", "strange")); + when P_TFIND: + /* + * Potion of magic detection. Show the potions and scrolls + */ + show = FALSE; + if (lvl_obj != NULL) + { + wclear(hw); + for (tp = lvl_obj; tp != NULL; tp = next(tp)) + { + if (is_magic(tp)) + { + show = TRUE; + wmove(hw, tp->o_pos.y, tp->o_pos.x); + waddch(hw, MAGIC); + pot_info[P_TFIND].oi_know = TRUE; + } + } + for (mp = mlist; mp != NULL; mp = next(mp)) + { + for (tp = mp->t_pack; tp != NULL; tp = next(tp)) + { + if (is_magic(tp)) + { + show = TRUE; + wmove(hw, mp->t_pos.y, mp->t_pos.x); + waddch(hw, MAGIC); + } + } + } + } + if (show) + { + pot_info[P_TFIND].oi_know = TRUE; + show_win(rs,"You sense the presence of magic on this level.--More--"); + } + else + msg(rs,"you have a %s feeling for a moment, then it passes", + choose_str("normal", "strange")); + when P_LSD: + if (!trip) + { + if (on(player, SEEMONST)) + turn_see(FALSE); + start_daemon(visuals, 0, BEFORE); + seenstairs = seen_stairs(); + } + do_pot(rs,P_LSD, TRUE); + when P_SEEINVIS: + sprintf(prbuf, "this potion tastes like %s juice", fruit); + show = on(player, CANSEE); + do_pot(rs,P_SEEINVIS, FALSE); + if (!show) + invis_on(); + sight(rs,0); + when P_RAISE: + pot_info[P_RAISE].oi_know = TRUE; + msg(rs,"you suddenly feel much more skillful"); + raise_level(rs); + when P_XHEAL: + pot_info[P_XHEAL].oi_know = TRUE; + if ((pstats.s_hpt += roll(pstats.s_lvl, 8)) > max_hp) + { + if (pstats.s_hpt > max_hp + pstats.s_lvl + 1) + ++max_hp; + pstats.s_hpt = ++max_hp; + } + sight(rs,0); + come_down(rs,0); + msg(rs,"you begin to feel much better"); + when P_HASTE: + pot_info[P_HASTE].oi_know = TRUE; + after = FALSE; + if (add_haste(rs,TRUE)) + msg(rs,"you feel yourself moving much faster"); + when P_RESTORE: + if (ISRING(LEFT, R_ADDSTR)) + add_str(&pstats.s_str, -cur_ring[LEFT]->o_arm); + if (ISRING(RIGHT, R_ADDSTR)) + add_str(&pstats.s_str, -cur_ring[RIGHT]->o_arm); + if (pstats.s_str < max_stats.s_str) + pstats.s_str = max_stats.s_str; + if (ISRING(LEFT, R_ADDSTR)) + add_str(&pstats.s_str, cur_ring[LEFT]->o_arm); + if (ISRING(RIGHT, R_ADDSTR)) + add_str(&pstats.s_str, cur_ring[RIGHT]->o_arm); + msg(rs,"hey, this tastes great. It make you feel warm all over"); + when P_BLIND: + do_pot(rs,P_BLIND, TRUE); + when P_LEVIT: + do_pot(rs,P_LEVIT, TRUE); +#ifdef MASTER + otherwise: + msg(rs,"what an odd tasting potion!"); + return; +#endif + } + status(rs); + /* + * Throw the item away + */ + + call_it(rs,&pot_info[obj->o_which]); + + if (discardit) + discard(obj); + return; +} + +/* + * is_magic: + * Returns true if an object radiates magic + */ +bool +is_magic(THING *obj) +{ + switch (obj->o_type) + { + case ARMOR: + return (bool)((obj->o_flags&ISPROT) || obj->o_arm != a_class[obj->o_which]); + case WEAPON: + return (bool)(obj->o_hplus != 0 || obj->o_dplus != 0); + case POTION: + case SCROLL: + case STICK: + case RING: + case AMULET: + return TRUE; + } + return FALSE; +} + +/* + * invis_on: + * Turn on the ability to see invisible + */ + +void +invis_on() +{ + THING *mp; + + player.t_flags |= CANSEE; + for (mp = mlist; mp != NULL; mp = next(mp)) + if (on(*mp, ISINVIS) && see_monst(mp) && !on(player, ISHALU)) + mvaddch(mp->t_pos.y, mp->t_pos.x, mp->t_disguise); +} + +/* + * turn_see: + * Put on or off seeing monsters on this level + */ +bool +turn_see(bool turn_off) +{ + THING *mp; + bool can_see, add_new; + + add_new = FALSE; + for (mp = mlist; mp != NULL; mp = next(mp)) + { + move(mp->t_pos.y, mp->t_pos.x); + can_see = see_monst(mp); + if (turn_off) + { + if (!can_see) + addch(mp->t_oldch); + } + else + { + if (!can_see) + standout(); + if (!on(player, ISHALU)) + addch(mp->t_type); + else + addch(rnd(26) + 'A'); + if (!can_see) + { + standend(); + add_new++; + } + } + } + if (turn_off) + player.t_flags &= ~SEEMONST; + else + player.t_flags |= SEEMONST; + return add_new; +} + +/* + * seen_stairs: + * Return TRUE if the player has seen the stairs + */ +bool +seen_stairs() +{ + THING *tp; + + move(stairs.y, stairs.x); + if (inch() == STAIRS) /* it's on the map */ + return TRUE; + if (ce(hero, stairs)) /* It's under him */ + return TRUE; + + /* + * if a monster is on the stairs, this gets hairy + */ + if ((tp = moat(stairs.y, stairs.x)) != NULL) + { + if (see_monst(tp) && on(*tp, ISRUN)) /* if it's visible and awake */ + return TRUE; /* it must have moved there */ + + if (on(player, SEEMONST) /* if she can detect monster */ + && tp->t_oldch == STAIRS) /* and there once were stairs */ + return TRUE; /* it must have moved there */ + } + return FALSE; +} + +/* + * raise_level: + * The guy just magically went up a level. + */ + +void +raise_level(struct rogue_state *rs) +{ + pstats.s_exp = e_levels[pstats.s_lvl-1] + 1L; + check_level(rs); +} + +/* + * do_pot: + * Do a potion with standard setup. This means it uses a fuse and + * turns on a flag + */ + +void +do_pot(struct rogue_state *rs,int type, bool knowit) +{ + PACT *pp; + int t; + + pp = &p_actions[type]; + if (!pot_info[type].oi_know) + pot_info[type].oi_know = knowit; + t = spread(pp->pa_time); + if (!on(player, pp->pa_flags)) + { + player.t_flags |= pp->pa_flags; + fuse(pp->pa_daemon, 0, t, AFTER); + look(rs,FALSE); + } + else + lengthen(pp->pa_daemon, t); + msg(rs,choose_str(pp->pa_high, pp->pa_straight)); +} diff --git a/src/cc/rogue/rings.c b/src/cc/rogue/rings.c new file mode 100644 index 000000000..56f7a0294 --- /dev/null +++ b/src/cc/rogue/rings.c @@ -0,0 +1,204 @@ +/* + * Routines dealing specifically with rings + * + * @(#)rings.c 4.19 (Berkeley) 05/29/83 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include "rogue.h" + +/* + * ring_on: + * Put a ring on a hand + */ + +void +ring_on(struct rogue_state *rs) +{ + THING *obj; + int ring; + + obj = get_item(rs,"put on", RING); + /* + * Make certain that it is somethings that we want to wear + */ + if (obj == NULL) + return; + if (obj->o_type != RING) + { + if (!terse) + msg(rs,"it would be difficult to wrap that around a finger"); + else + msg(rs,"not a ring"); + return; + } + + /* + * find out which hand to put it on + */ + if (is_current(rs,obj)) + return; + + if (cur_ring[LEFT] == NULL && cur_ring[RIGHT] == NULL) + { + if ((ring = gethand(rs)) < 0) + return; + } + else if (cur_ring[LEFT] == NULL) + ring = LEFT; + else if (cur_ring[RIGHT] == NULL) + ring = RIGHT; + else + { + if (!terse) + msg(rs,"you already have a ring on each hand"); + else + msg(rs,"wearing two"); + return; + } + cur_ring[ring] = obj; + + /* + * Calculate the effect it has on the poor guy. + */ + switch (obj->o_which) + { + case R_ADDSTR: + chg_str(obj->o_arm); + break; + case R_SEEINVIS: + invis_on(); + break; + case R_AGGR: + aggravate(rs); + break; + } + + if (!terse) + addmsg(rs,"you are now wearing "); + msg(rs,"%s (%c)", inv_name(obj, TRUE), obj->o_packch); +} + +/* + * ring_off: + * take off a ring + */ + +void +ring_off(struct rogue_state *rs) +{ + int ring; + THING *obj; + + if (cur_ring[LEFT] == NULL && cur_ring[RIGHT] == NULL) + { + if (terse) + msg(rs,"no rings"); + else + msg(rs,"you aren't wearing any rings"); + return; + } + else if (cur_ring[LEFT] == NULL) + ring = RIGHT; + else if (cur_ring[RIGHT] == NULL) + ring = LEFT; + else + if ((ring = gethand(rs)) < 0) + return; + mpos = 0; + obj = cur_ring[ring]; + if (obj == NULL) + { + msg(rs,"not wearing such a ring"); + return; + } + if (dropcheck(rs,obj)) + msg(rs,"was wearing %s(%c)", inv_name(obj, TRUE), obj->o_packch); +} + +/* + * gethand: + * Which hand is the hero interested in? + */ +int +gethand(struct rogue_state *rs) +{ + int c; + + for (;;) + { + if (terse) + msg(rs,"left or right ring? "); + else + msg(rs,"left hand or right hand? "); + if ((c = readchar(rs)) == ESCAPE) + return -1; + mpos = 0; + if (c == 'l' || c == 'L') + return LEFT; + else if (c == 'r' || c == 'R') + return RIGHT; + if (terse) + msg(rs,"L or R"); + else + msg(rs,"please type L or R"); + } +} + +/* + * ring_eat: + * How much food does this ring use up? + */ +int +ring_eat(int hand) +{ + THING *ring; + int eat; + static int uses[] = { + 1, /* R_PROTECT */ 1, /* R_ADDSTR */ + 1, /* R_SUSTSTR */ -3, /* R_SEARCH */ + -5, /* R_SEEINVIS */ 0, /* R_NOP */ + 0, /* R_AGGR */ -3, /* R_ADDHIT */ + -3, /* R_ADDDAM */ 2, /* R_REGEN */ + -2, /* R_DIGEST */ 0, /* R_TELEPORT */ + 1, /* R_STEALTH */ 1 /* R_SUSTARM */ + }; + + if ((ring = cur_ring[hand]) == NULL) + return 0; + if ((eat = uses[ring->o_which]) < 0) + eat = (rnd(-eat) == 0); + if (ring->o_which == R_DIGEST) + eat = -eat; + return eat; +} + +/* + * ring_num: + * Print ring bonuses + */ +char * +ring_num(THING *obj) +{ + static char buf[10]; + + if (!(obj->o_flags & ISKNOW)) + return ""; + switch (obj->o_which) + { + case R_PROTECT: + case R_ADDSTR: + case R_ADDDAM: + case R_ADDHIT: + sprintf(buf, " [%s]", num(obj->o_arm, 0, RING)); + otherwise: + return ""; + } + return buf; +} diff --git a/src/cc/rogue/rip.c b/src/cc/rogue/rip.c new file mode 100644 index 000000000..6f2793615 --- /dev/null +++ b/src/cc/rogue/rip.c @@ -0,0 +1,449 @@ +/* + * File for the fun ends + * Death or a total win + * + * @(#)rip.c 4.57 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "rogue.h" +#include "score.h" + +static char *rip[] = { +" __________\n", +" / \\\n", +" / REST \\\n", +" / IN \\\n", +" / PEACE \\\n", +" / \\\n", +" | |\n", +" | |\n", +" | killed by a |\n", +" | |\n", +" | 1980 |\n", +" *| * * * | *\n", +" ________)/\\\\_//(\\/(/\\)/\\//\\/|_)_______\n", + 0 +}; + +/* + * score: + * Figure score and post it. + */ +/* VARARGS2 */ + +void +score(int amount, int flags, char monst) +{ + SCORE *scp; + int i; + SCORE *sc2; + SCORE *top_ten, *endp; +# ifdef MASTER + int prflags = 0; +# endif + void (*fp)(int); + unsigned int uid; + static char *reason[] = { + "killed", + "quit", + "A total winner", + "killed with Amulet" + }; + + start_score(); + + if (flags >= 0 +#ifdef MASTER + || wizard +#endif + ) + { + mvaddstr(LINES - 1, 0 , "[Press return to continue]"); + refresh(); + wgetnstr(stdscr,prbuf,80); + endwin(); + printf("\n"); + resetltchars(); + /* + * free up space to "guarantee" there is space for the top_ten + */ + delwin(stdscr); + delwin(curscr); + if (hw != NULL) + delwin(hw); + } + + top_ten = (SCORE *) malloc(numscores * sizeof (SCORE)); + endp = &top_ten[numscores]; + for (scp = top_ten; scp < endp; scp++) + { + scp->sc_score = 0; + for (i = 0; i < MAXSTR; i++) + scp->sc_name[i] = (unsigned char) rnd(255); + scp->sc_flags = RN; + scp->sc_level = RN; + scp->sc_monster = (unsigned short) RN; + scp->sc_uid = RN; + } + + signal(SIGINT, SIG_DFL); + +#ifdef MASTER + if (wizard) + if (strcmp(prbuf, "names") == 0) + prflags = 1; + else if (strcmp(prbuf, "edit") == 0) + prflags = 2; +#endif + rd_score(top_ten); + /* + * Insert her in list if need be + */ + sc2 = NULL; + if (!noscore) + { + uid = md_getuid(); + for (scp = top_ten; scp < endp; scp++) + if (amount > scp->sc_score) + break; + else if (!allscore && /* only one score per nowin uid */ + flags != 2 && scp->sc_uid == uid && scp->sc_flags != 2) + scp = endp; + if (scp < endp) + { + if (flags != 2 && !allscore) + { + for (sc2 = scp; sc2 < endp; sc2++) + { + if (sc2->sc_uid == uid && sc2->sc_flags != 2) + break; + } + if (sc2 >= endp) + sc2 = endp - 1; + } + else + sc2 = endp - 1; + while (sc2 > scp) + { + *sc2 = sc2[-1]; + sc2--; + } + scp->sc_score = amount; + strncpy(scp->sc_name, whoami, MAXSTR); + scp->sc_flags = flags; + if (flags == 2) + scp->sc_level = max_level; + else + scp->sc_level = level; + scp->sc_monster = monst; + scp->sc_uid = uid; + sc2 = scp; + } + } + /* + * Print the list + */ + if (flags != -1) + putchar('\n'); + printf("Top %s %s:\n", Numname, allscore ? "Scores" : "Rogueists"); + printf(" Score Name\n"); + for (scp = top_ten; scp < endp; scp++) + { + if (scp->sc_score) { + if (sc2 == scp) + md_raw_standout(); + printf("%2d %5d %s: %s on level %d", (int) (scp - top_ten + 1), + scp->sc_score, scp->sc_name, reason[scp->sc_flags], + scp->sc_level); + if (scp->sc_flags == 0 || scp->sc_flags == 3) + printf(" by %s", killname((char) scp->sc_monster, TRUE)); +#ifdef MASTER + if (prflags == 1) + { + printf(" (%s)", md_getrealname(scp->sc_uid)); + } + else if (prflags == 2) + { + fflush(stdout); + (void) fgets(prbuf,10,stdin); + if (prbuf[0] == 'd') + { + for (sc2 = scp; sc2 < endp - 1; sc2++) + *sc2 = *(sc2 + 1); + sc2 = endp - 1; + sc2->sc_score = 0; + for (i = 0; i < MAXSTR; i++) + sc2->sc_name[i] = (char) rnd(255); + sc2->sc_flags = RN; + sc2->sc_level = RN; + sc2->sc_monster = (unsigned short) RN; + scp--; + } + } + else +#endif /* MASTER */ + printf("."); + if (sc2 == scp) + md_raw_standend(); + putchar('\n'); + } + else + break; + } + /* + * Update the list file + */ + if (sc2 != NULL) + { + if (lock_sc()) + { + fp = signal(SIGINT, SIG_IGN); + wr_score(top_ten); + unlock_sc(); + signal(SIGINT, fp); + } + } +} + +/* + * death: + * Do something really fun when he dies + */ + +void +death(char monst) +{ + char **dp, *killer; + struct tm *lt; + static time_t date; + //struct tm *localtime(const time_t *); + + signal(SIGINT, SIG_IGN); + purse -= purse / 10; + signal(SIGINT, leave); + clear(); + killer = killname(monst, FALSE); + if (!tombstone) + { + mvprintw(LINES - 2, 0, "Killed by "); + killer = killname(monst, FALSE); + if (monst != 's' && monst != 'h') + printw("a%s ", vowelstr(killer)); + printw("%s with %d gold", killer, purse); + } + else + { + time(&date); + lt = localtime(&date); + move(8, 0); + dp = rip; + while (*dp) + addstr(*dp++); + mvaddstr(17, center(killer), killer); + if (monst == 's' || monst == 'h') + mvaddch(16, 32, ' '); + else + mvaddstr(16, 33, vowelstr(killer)); + mvaddstr(14, center(whoami), whoami); + sprintf(prbuf, "%d Au", purse); + move(15, center(prbuf)); + addstr(prbuf); + sprintf(prbuf, "%4d", 1900+lt->tm_year); + mvaddstr(18, 26, prbuf); + } + move(LINES - 1, 0); + refresh(); + score(purse, amulet ? 3 : 0, monst); + printf("[Press return to continue]"); + fflush(stdout); + (void) fgets(prbuf,10,stdin); + my_exit(0); +} + +/* + * center: + * Return the index to center the given string + */ +int +center(char *str) +{ + return 28 - (((int)strlen(str) + 1) / 2); +} + +/* + * total_winner: + * Code for a winner + */ + +void +total_winner(struct rogue_state *rs) +{ + THING *obj; + struct obj_info *op; + int worth = 0; + int oldpurse; + + clear(); + standout(); + addstr(" \n"); + addstr(" @ @ @ @ @ @@@ @ @ \n"); + addstr(" @ @ @@ @@ @ @ @ @ \n"); + addstr(" @ @ @@@ @ @ @ @ @ @@@ @@@@ @@@ @ @@@ @ \n"); + addstr(" @@@@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ \n"); + addstr(" @ @ @ @ @ @ @ @@@@ @ @ @@@@@ @ @ @ \n"); + addstr(" @ @ @ @ @ @@ @ @ @ @ @ @ @ @ @ @ \n"); + addstr(" @@@ @@@ @@ @ @ @ @@@@ @@@@ @@@ @@@ @@ @ \n"); + addstr(" \n"); + addstr(" Congratulations, you have made it to the light of day! \n"); + standend(); + addstr("\nYou have joined the elite ranks of those who have escaped the\n"); + addstr("Dungeons of Doom alive. You journey home and sell all your loot at\n"); + addstr("a great profit and are admitted to the Fighters' Guild.\n"); + mvaddstr(LINES - 1, 0, "--Press space to continue--"); + refresh(); + wait_for(rs,' '); + clear(); + mvaddstr(0, 0, " Worth Item\n"); + oldpurse = purse; + for (obj = pack; obj != NULL; obj = next(obj)) + { + switch (obj->o_type) + { + case FOOD: + worth = 2 * obj->o_count; + when WEAPON: + worth = weap_info[obj->o_which].oi_worth; + worth *= 3 * (obj->o_hplus + obj->o_dplus) + obj->o_count; + obj->o_flags |= ISKNOW; + when ARMOR: + worth = arm_info[obj->o_which].oi_worth; + worth += (9 - obj->o_arm) * 100; + worth += (10 * (a_class[obj->o_which] - obj->o_arm)); + obj->o_flags |= ISKNOW; + when SCROLL: + worth = scr_info[obj->o_which].oi_worth; + worth *= obj->o_count; + op = &scr_info[obj->o_which]; + if (!op->oi_know) + worth /= 2; + op->oi_know = TRUE; + when POTION: + worth = pot_info[obj->o_which].oi_worth; + worth *= obj->o_count; + op = &pot_info[obj->o_which]; + if (!op->oi_know) + worth /= 2; + op->oi_know = TRUE; + when RING: + op = &ring_info[obj->o_which]; + worth = op->oi_worth; + if (obj->o_which == R_ADDSTR || obj->o_which == R_ADDDAM || + obj->o_which == R_PROTECT || obj->o_which == R_ADDHIT) + { + if (obj->o_arm > 0) + worth += obj->o_arm * 100; + else + worth = 10; + } + if (!(obj->o_flags & ISKNOW)) + worth /= 2; + obj->o_flags |= ISKNOW; + op->oi_know = TRUE; + when STICK: + op = &ws_info[obj->o_which]; + worth = op->oi_worth; + worth += 20 * obj->o_charges; + if (!(obj->o_flags & ISKNOW)) + worth /= 2; + obj->o_flags |= ISKNOW; + op->oi_know = TRUE; + when AMULET: + worth = 1000; + } + if (worth < 0) + worth = 0; + printw("%c) %5d %s\n", obj->o_packch, worth, inv_name(obj, FALSE)); + purse += worth; + } + printw(" %5d Gold Pieces ", oldpurse); + refresh(); + score(purse, 2, ' '); + my_exit(0); +} + +/* + * killname: + * Convert a code to a monster name + */ +char * +killname(char monst, bool doart) +{ + struct h_list *hp; + char *sp; + bool article; + static struct h_list nlist[] = { + {'a', "arrow", TRUE}, + {'b', "bolt", TRUE}, + {'d', "dart", TRUE}, + {'h', "hypothermia", FALSE}, + {'s', "starvation", FALSE}, + {'\0'} + }; + + if (isupper(monst)) + { + sp = monsters[monst-'A'].m_name; + article = TRUE; + } + else + { + sp = "Wally the Wonder Badger"; + article = FALSE; + for (hp = nlist; hp->h_ch; hp++) + if (hp->h_ch == monst) + { + sp = hp->h_desc; + article = hp->h_print; + break; + } + } + if (doart && article) + sprintf(prbuf, "a%s ", vowelstr(sp)); + else + prbuf[0] = '\0'; + strcat(prbuf, sp); + return prbuf; +} + +/* + * death_monst: + * Return a monster appropriate for a random death. + */ +char +death_monst() +{ + static char poss[] = + { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', + 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', + 'Y', 'Z', 'a', 'b', 'h', 'd', 's', + ' ' /* This is provided to generate the "Wally the Wonder Badger" + message for killer */ + }; + + return poss[rnd(sizeof poss / sizeof (char))]; +} diff --git a/src/cc/rogue/rogue.6 b/src/cc/rogue/rogue.6 new file mode 100644 index 000000000..6b63252ab --- /dev/null +++ b/src/cc/rogue/rogue.6 @@ -0,0 +1,96 @@ +.\" +.\" @(#)rogue.6 6.2 (Berkeley) 5/6/86 +.\" +.\" Rogue: Exploring the Dungeons of Doom +.\" Copyright (C) 1980-1983, 1985, 1986 Michael Toy, Ken Arnold and Glenn Wichman +.\" All rights reserved. +.\" +.\" See the file LICENSE.TXT for full copyright and licensing information. +.\" +.TH ROGUE 6 "May 6, 1986" +.UC 4 +.SH NAME +rogue \- Exploring The Dungeons of Doom +.SH SYNOPSIS +.B rogue +[ +.B \-r +] +[ +.I save_file +] +[ +.B \-s +] +[ +.B \-d +] +.SH DESCRIPTION +.PP +.I Rogue +is a computer fantasy game with a new twist. It is crt oriented and the +object of the game is to survive the attacks of various monsters and get +a lot of gold, rather than the puzzle solving orientation of most computer +fantasy games. +.PP +To get started you really only need to know two commands. The command +.B ? +will give you a list of the available commands and the command +.B / +will identify the things you see on the screen. +.PP +To win the game (as opposed to merely playing to beat other people's high +scores) you must locate the Amulet of Yendor which is somewhere below +the 20th level of the dungeon and get it out. Nobody has achieved this +yet and if somebody does, they will probably go down in history as a hero +among heroes. +.PP +When the game ends, either by your death, when you quit, or if you (by +some miracle) manage to win, +.I rogue +will give you a list of the top-ten scorers. The scoring is based entirely +upon how much gold you get. There is a 10% penalty for getting yourself +killed. +.PP +If +.I save_file +is specified, +rogue will be restored from the specified saved game file. +If the +.B \-r +option is used, the save game file is presumed to be the default. +.PP +The +.B \-s +option will print out the list of scores. +.PP +The +.B \-d +option will kill you and try to add you to the score file. +.PP +For more detailed directions, read the document +.I "A Guide to the Dungeons of Doom." +.SH AUTHORS +Michael C. Toy, +Kenneth C. R. C. Arnold, +Glenn Wichman +.SH FILES +.DT +.ta \w'rogue.scr\ \ \ 'u +rogue.scr Score file +.br +\fB~\fP/rogue.save Default save file +.SH SEE ALSO +Michael C. Toy +and +Kenneth C. R. C. Arnold, +.I "A guide to the Dungeons of Doom" +.SH BUGS +.PP +Probably infinite +(although countably infinite). +However, +that Ice Monsters sometimes transfix you permanently is +.I not +a bug. +It's a feature. diff --git a/src/cc/rogue/rogue.6.in b/src/cc/rogue/rogue.6.in new file mode 100644 index 000000000..a9d6d9903 --- /dev/null +++ b/src/cc/rogue/rogue.6.in @@ -0,0 +1,96 @@ +.\" +.\" @(#)rogue.6 6.2 (Berkeley) 5/6/86 +.\" +.\" Rogue: Exploring the Dungeons of Doom +.\" Copyright (C) 1980-1983, 1985, 1986 Michael Toy, Ken Arnold and Glenn Wichman +.\" All rights reserved. +.\" +.\" See the file LICENSE.TXT for full copyright and licensing information. +.\" +.TH ROGUE 6 "May 6, 1986" +.UC 4 +.SH NAME +rogue \- Exploring The Dungeons of Doom +.SH SYNOPSIS +.B @PROGRAM@ +[ +.B \-r +] +[ +.I save_file +] +[ +.B \-s +] +[ +.B \-d +] +.SH DESCRIPTION +.PP +.I Rogue +is a computer fantasy game with a new twist. It is crt oriented and the +object of the game is to survive the attacks of various monsters and get +a lot of gold, rather than the puzzle solving orientation of most computer +fantasy games. +.PP +To get started you really only need to know two commands. The command +.B ? +will give you a list of the available commands and the command +.B / +will identify the things you see on the screen. +.PP +To win the game (as opposed to merely playing to beat other people's high +scores) you must locate the Amulet of Yendor which is somewhere below +the 20th level of the dungeon and get it out. Nobody has achieved this +yet and if somebody does, they will probably go down in history as a hero +among heroes. +.PP +When the game ends, either by your death, when you quit, or if you (by +some miracle) manage to win, +.I rogue +will give you a list of the top-ten scorers. The scoring is based entirely +upon how much gold you get. There is a 10% penalty for getting yourself +killed. +.PP +If +.I save_file +is specified, +rogue will be restored from the specified saved game file. +If the +.B \-r +option is used, the save game file is presumed to be the default. +.PP +The +.B \-s +option will print out the list of scores. +.PP +The +.B \-d +option will kill you and try to add you to the score file. +.PP +For more detailed directions, read the document +.I "A Guide to the Dungeons of Doom." +.SH AUTHORS +Michael C. Toy, +Kenneth C. R. C. Arnold, +Glenn Wichman +.SH FILES +.DT +.ta \w'@SCOREFILE@\ \ \ 'u +@SCOREFILE@ Score file +.br +\fB~\fP/rogue.save Default save file +.SH SEE ALSO +Michael C. Toy +and +Kenneth C. R. C. Arnold, +.I "A guide to the Dungeons of Doom" +.SH BUGS +.PP +Probably infinite +(although countably infinite). +However, +that Ice Monsters sometimes transfix you permanently is +.I not +a bug. +It's a feature. diff --git a/src/cc/rogue/rogue.777.0 b/src/cc/rogue/rogue.777.0 new file mode 100644 index 000000000..e56f7b148 --- /dev/null +++ b/src/cc/rogue/rogue.777.0 @@ -0,0 +1 @@ +llllljhhl jllllllllllllllllllkkllllklllljllljjllllllllllll \ No newline at end of file diff --git a/src/cc/rogue/rogue.777.1 b/src/cc/rogue/rogue.777.1 new file mode 100644 index 000000000..68b8ab099 --- /dev/null +++ b/src/cc/rogue/rogue.777.1 @@ -0,0 +1 @@ +hhhhhhhhhhkkhhhhhhhhhhhhhjjhhhhhhhhjjjjjjjjjlllllllllllllk \ No newline at end of file diff --git a/src/cc/rogue/rogue.777.2 b/src/cc/rogue/rogue.777.2 new file mode 100644 index 000000000..93a664d1e --- /dev/null +++ b/src/cc/rogue/rogue.777.2 @@ -0,0 +1 @@ +lllljjllllll l ll lll l lll l ll l ljjj j j jhhhhhjjllllll \ No newline at end of file diff --git a/src/cc/rogue/rogue.777.3 b/src/cc/rogue/rogue.777.3 new file mode 100644 index 000000000..e69de29bb diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c new file mode 100644 index 000000000..d463ddc49 --- /dev/null +++ b/src/cc/rogue/rogue.c @@ -0,0 +1,534 @@ +/* + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + * + * @(#)main.c 4.22 (Berkeley) 02/05/99 + */ + +#include +#include +#include +#include +#include +#include +#include "rogue.h" + +/* + * main: + * The main program, of course + */ +struct rogue_state globalR; + +void rogueiterate(struct rogue_state *rs) +{ + seed = rs->seed; + + initscr(); /* Start up cursor package */ + init_probs(); /* Set up prob tables for objects */ + init_player(rs); /* Set up initial player stats */ + init_names(); /* Set up names of scrolls */ + init_colors(); /* Set up colors of potions */ + init_stones(); /* Set up stone settings of rings */ + init_materials(); /* Set up materials of wands */ + setup(); + + /* + * The screen must be at least NUMLINES x NUMCOLS + */ + if (LINES < NUMLINES || COLS < NUMCOLS) + { + printf("\nSorry, the screen must be at least %dx%d\n", NUMLINES, NUMCOLS); + endwin(); + my_exit(1); + } + // Set up windows + hw = newwin(LINES, COLS, 0, 0); + idlok(stdscr, TRUE); + idlok(hw, TRUE); +#ifdef MASTER + noscore = wizard; +#endif + new_level(rs); // Draw current level + // Start up daemons and fuses + start_daemon(runners, 0, AFTER); + start_daemon(doctor, 0, AFTER); + fuse(swander, 0, WANDERTIME, AFTER); + start_daemon(stomach, 0, AFTER); + playit(rs); +} + +int32_t roguefname(char *fname,uint64_t seed,int32_t counter) +{ + sprintf(fname,"rogue.%llu.%d",(long long)seed,counter); + return(0); +} + +int32_t flushkeystrokes(struct rogue_state *rs) +{ + char fname[1024]; FILE *fp; int32_t i,retflag = -1; + roguefname(fname,rs->seed,rs->counter); + if ( (fp= fopen(fname,"wb")) != 0 ) + { + if ( fwrite(rs->buffered,1,rs->num,fp) == rs->num ) + { + rs->counter++; + rs->num = 0; + retflag = 0; + fclose(fp); + if ( (fp= fopen("savefile","wb")) != 0 ) + { + save_file(fp,0); + if ( 0 && (fp= fopen("savefile","rb")) != 0 ) + { + for (i=0; i<0x150; i++) + fprintf(stderr,"%02x",fgetc(fp)); + fprintf(stderr," first part rnd.%d\n",rnd(1000)); + fclose(fp); + } + roguefname(fname,rs->seed,rs->counter); + if ( (fp= fopen(fname,"wb")) != 0 ) // truncate next file + fclose(fp); + //fprintf(stderr,"savefile <- %s retflag.%d\n",fname,retflag); + } + } else fprintf(stderr,"error writing (%s)\n",fname); + } else fprintf(stderr,"error creating (%s)\n",fname); + return(retflag); +} + +long get_filesize(FILE *fp) +{ + long fsize,fpos = ftell(fp); + fseek(fp,0,SEEK_END); + fsize = ftell(fp); + fseek(fp,fpos,SEEK_SET); + return(fsize); +} + +int32_t rogue_replay(uint64_t seed) +{ + FILE *fp; char fname[1024]; char *keystrokes = 0; long num=0,fsize; int32_t i,counter = 0; struct rogue_state *rs; + while ( 1 ) + { + roguefname(fname,seed,counter); + if ( (fp= fopen(fname,"rb")) == 0 ) + break; + if ( (fsize= get_filesize(fp)) <= 0 ) + { + fclose(fp); + break; + } + if ( (keystrokes= (char *)realloc(keystrokes,num+fsize)) == 0 ) + { + fprintf(stderr,"error reallocating keystrokes\n"); + fclose(fp); + return(-1); + } + if ( fread(&keystrokes[num],1,fsize,fp) != fsize ) + { + fprintf(stderr,"error reading keystrokes from (%s)\n",fname); + fclose(fp); + return(-1); + } + fclose(fp); + num += fsize; + counter++; + fprintf(stderr,"loaded %ld from (%s) total %ld\n",fsize,fname,num); + } + if ( num > 0 ) + { + rs = calloc(1,sizeof(*rs)); + rs->seed = seed; + rs->keystrokes = keystrokes; + rs->numkeys = num; + rogueiterate(rs); + if ( (fp= fopen("checkfile","wb")) != 0 ) + { + save_file(fp,0); + fclose(fp); + if ( 0 && (fp= fopen("checkfile","rb")) != 0 ) + { + for (i=0; i<0x150; i++) + fprintf(stderr,"%02x",fgetc(fp)); + fprintf(stderr," first part rnd.%d\n",rnd(1000)); + fclose(fp); + } + } + fatal("finished replay\n"); + } + if ( keystrokes != 0 ) + free(keystrokes); + return(num); +} + +int rogue(int argc, char **argv, char **envp) +{ + char *env; int lowtime; struct rogue_state *rs = &globalR; + memset(rs,0,sizeof(*rs)); + rs->seed = 777; + rs->guiflag = 1; + md_init(); + +#ifdef MASTER + /* + * Check to see if he is a wizard + */ + if (argc >= 2 && argv[1][0] == '\0') + if (strcmp(PASSWD, md_crypt(md_getpass("wizard's password: "), "mT")) == 0) + { + wizard = TRUE; + player.t_flags |= SEEMONST; + argv++; + argc--; + } + +#endif + + /* + * get home and options from environment + */ + + strncpy(home, md_gethomedir(), MAXSTR); + + strcpy(file_name, home); + strcat(file_name, "rogue.save"); + + if ((env = getenv("ROGUEOPTS")) != NULL) + parse_opts(env); + if (env == NULL || whoami[0] == '\0') + strucpy(whoami, md_getusername(), (int) strlen(md_getusername())); + lowtime = (int) time(NULL); +#ifdef MASTER + if (wizard && getenv("SEED") != NULL) + dnum = atoi(getenv("SEED")); + else +#endif + dnum = lowtime + md_getpid(); + if ( rs != 0 ) + seed = rs->seed; + else seed = 777; + dnum = (int)seed; + + open_score(); + + /* + * Drop setuid/setgid after opening the scoreboard file. + */ + + md_normaluser(); + + /* + * check for print-score option + */ + + md_normaluser(); /* we drop any setgid/setuid priveldges here */ + + if (argc == 2) + { + if (strcmp(argv[1], "-s") == 0) + { + noscore = TRUE; + score(0, -1, 0); + exit(0); + } + else if (strcmp(argv[1], "-d") == 0) + { + dnum = rnd(100); /* throw away some rnd()s to break patterns */ + while (--dnum) + rnd(100); + purse = rnd(100) + 1; + level = rnd(100) + 1; + initscr(); + getltchars(); + death(death_monst()); + exit(0); + } + } + + init_check(); /* check for legal startup */ + if (argc == 2) + if (!restore(rs,argv[1], envp)) /* Note: restore will never return */ + my_exit(1); +#ifdef MASTER + if (wizard) + printf("Hello %s, welcome to dungeon #%d", whoami, dnum); + else +#endif + printf("Hello %s, just a moment while I dig the dungeon... seed.%llu", whoami,(long long)rs->seed); + fflush(stdout); + + rogueiterate(rs); + return(0); +} + +/* + * endit: + * Exit the program abnormally. + */ + +void +endit(int sig) +{ + NOOP(sig); + fatal("Okay, bye bye!\n"); +} + +/* + * fatal: + * Exit the program, printing a message. + */ + +void +fatal(char *s) +{ + mvaddstr(LINES - 2, 0, s); + refresh(); + endwin(); + my_exit(0); +} + +/* + * rnd: + * Pick a very random number. + */ +int +rnd(int range) +{ + return range == 0 ? 0 : abs((int) RN) % range; +} + +/* + * roll: + * Roll a number of dice + */ +int +roll(int number, int sides) +{ + int dtotal = 0; + + while (number--) + dtotal += rnd(sides)+1; + return dtotal; +} + +/* + * tstp: + * Handle stop and start signals + */ + +void +tstp(int ignored) +{ + int y, x; + int oy, ox; + + NOOP(ignored); + + /* + * leave nicely + */ + getyx(curscr, oy, ox); + mvcur(0, COLS - 1, LINES - 1, 0); + endwin(); + resetltchars(); + fflush(stdout); + md_tstpsignal(); + + /* + * start back up again + */ + md_tstpresume(); + raw(); + noecho(); + keypad(stdscr,1); + playltchars(); + clearok(curscr, TRUE); + wrefresh(curscr); + getyx(curscr, y, x); + mvcur(y, x, oy, ox); + fflush(stdout); + //wmove(curscr,oy,ox); +#ifndef __APPLE__ + curscr->_cury = oy; + curscr->_curx = ox; +#endif +} + +/* + * playit: + * The main loop of the program. Loop until the game is over, + * refreshing things and looking at the proper times. + */ + +void +playit(struct rogue_state *rs) +{ + char *opts; + + /* + * set up defaults for slow terminals + */ + + if (baudrate() <= 1200) + { + terse = TRUE; + jump = TRUE; + see_floor = FALSE; + } + + if (md_hasclreol()) + inv_type = INV_CLEAR; + + /* + * parse environment declaration of options + */ + if ((opts = getenv("ROGUEOPTS")) != NULL) + parse_opts(opts); + + + oldpos = hero; + oldrp = roomin(rs,&hero); + while (playing) + { + command(rs); // Command execution + if ( rs->guiflag == 0 ) + { + if ( rs->replaydone != 0 ) + { + //fprintf(stderr,"replaydone\n"); sleep(3); + return; + } + //usleep(100000); + } + else + { + if ( rs->needflush != 0 ) + { + if ( flushkeystrokes(rs) == 0 ) + rs->needflush = 0; + } + } + } + endit(0); +} + +/* + * quit: + * Have player make certain, then exit. + */ + +void +quit(int sig) +{ + struct rogue_state *rs = &globalR; + int oy, ox; + + NOOP(sig); + + /* + * Reset the signal in case we got here via an interrupt + */ + if (!q_comm) + mpos = 0; + getyx(curscr, oy, ox); + msg(rs,"really quit?"); + if (readchar(rs) == 'y') + { + signal(SIGINT, leave); + clear(); + mvprintw(LINES - 2, 0, "You quit with %d gold pieces", purse); + move(LINES - 1, 0); + refresh(); + score(purse, 1, 0); + my_exit(0); + } + else + { + move(0, 0); + clrtoeol(); + status(rs); + move(oy, ox); + refresh(); + mpos = 0; + count = 0; + to_death = FALSE; + } +} + +/* + * leave: + * Leave quickly, but curteously + */ + +void +leave(int sig) +{ + static char buf[BUFSIZ]; + + NOOP(sig); + + setbuf(stdout, buf); /* throw away pending output */ + + if (!isendwin()) + { + mvcur(0, COLS - 1, LINES - 1, 0); + endwin(); + } + + putchar('\n'); + my_exit(0); +} + +/* + * shell: + * Let them escape for a while + */ + +void +shell(struct rogue_state *rs) +{ + if ( rs != 0 && rs->guiflag != 0 ) + { + /* + * Set the terminal back to original mode + */ + move(LINES-1, 0); + refresh(); + endwin(); + resetltchars(); + putchar('\n'); + in_shell = TRUE; + after = FALSE; + fflush(stdout); + /* + * Fork and do a shell + */ + md_shellescape(); + + printf("\n[Press return to continue]"); + fflush(stdout); + noecho(); + raw(); + keypad(stdscr,1); + playltchars(); + in_shell = FALSE; + wait_for(rs,'\n'); + clearok(stdscr, TRUE); + } + else fprintf(stderr,"no shell in the blockchain\n"); +} + +/* + * my_exit: + * Leave the process properly + */ + +void +my_exit(int st) +{ + resetltchars(); + exit(st); +} + diff --git a/src/cc/rogue/rogue.cat b/src/cc/rogue/rogue.cat new file mode 100644 index 000000000..66d9605a2 --- /dev/null +++ b/src/cc/rogue/rogue.cat @@ -0,0 +1,61 @@ +ROGUE(6) ROGUE(6) + + + +NAME + rogue - Exploring The Dungeons of Doom + +SYNOPSIS + rogue [ -r ] [ save_file ] [ -s ] [ -d ] + +DESCRIPTION + Rogue is a computer fantasy game with a new twist. It is crt oriented + and the object of the game is to survive the attacks of various mon- + sters and get a lot of gold, rather than the puzzle solving orientation + of most computer fantasy games. + + To get started you really only need to know two commands. The command + ? will give you a list of the available commands and the command / + will identify the things you see on the screen. + + To win the game (as opposed to merely playing to beat other people's + high scores) you must locate the Amulet of Yendor which is somewhere + below the 20th level of the dungeon and get it out. Nobody has + achieved this yet and if somebody does, they will probably go down in + history as a hero among heroes. + + When the game ends, either by your death, when you quit, or if you (by + some miracle) manage to win, rogue will give you a list of the top-ten + scorers. The scoring is based entirely upon how much gold you get. + There is a 10% penalty for getting yourself killed. + + If save_file is specified, rogue will be restored from the specified + saved game file. If the -r option is used, the save game file is pre- + sumed to be the default. + + The -s option will print out the list of scores. + + The -d option will kill you and try to add you to the score file. + + For more detailed directions, read the document A Guide to the Dungeons + of Doom. + +AUTHORS + Michael C. Toy, Kenneth C. R. C. Arnold, Glenn Wichman + +FILES + rogue.scr Score file + ~/rogue.save Default save file + +SEE ALSO + Michael C. Toy and Kenneth C. R. C. Arnold, A guide to the Dungeons of + Doom + +BUGS + Probably infinite (although countably infinite). However, that Ice + Monsters sometimes transfix you permanently is not a bug. It's a fea- + ture. + + + +4th Berkeley Distribution May 6, 1986 ROGUE(6) diff --git a/src/cc/rogue/rogue.cat.in b/src/cc/rogue/rogue.cat.in new file mode 100644 index 000000000..8dbef73c1 --- /dev/null +++ b/src/cc/rogue/rogue.cat.in @@ -0,0 +1,61 @@ +ROGUE(6) ROGUE(6) + + + +NAME + rogue - Exploring The Dungeons of Doom + +SYNOPSIS + @PROGRAM@ [ -r ] [ save_file ] [ -s ] [ -d ] + +DESCRIPTION + Rogue is a computer fantasy game with a new twist. It is crt oriented + and the object of the game is to survive the attacks of various mon- + sters and get a lot of gold, rather than the puzzle solving orientation + of most computer fantasy games. + + To get started you really only need to know two commands. The command + ? will give you a list of the available commands and the command / + will identify the things you see on the screen. + + To win the game (as opposed to merely playing to beat other people's + high scores) you must locate the Amulet of Yendor which is somewhere + below the 20th level of the dungeon and get it out. Nobody has + achieved this yet and if somebody does, they will probably go down in + history as a hero among heroes. + + When the game ends, either by your death, when you quit, or if you (by + some miracle) manage to win, rogue will give you a list of the top-ten + scorers. The scoring is based entirely upon how much gold you get. + There is a 10% penalty for getting yourself killed. + + If save_file is specified, rogue will be restored from the specified + saved game file. If the -r option is used, the save game file is pre- + sumed to be the default. + + The -s option will print out the list of scores. + + The -d option will kill you and try to add you to the score file. + + For more detailed directions, read the document A Guide to the Dungeons + of Doom. + +AUTHORS + Michael C. Toy, Kenneth C. R. C. Arnold, Glenn Wichman + +FILES + @SCOREFILE@ Score file + ~/rogue.save Default save file + +SEE ALSO + Michael C. Toy and Kenneth C. R. C. Arnold, A guide to the Dungeons of + Doom + +BUGS + Probably infinite (although countably infinite). However, that Ice + Monsters sometimes transfix you permanently is not a bug. It's a fea- + ture. + + + +4th Berkeley Distribution May 6, 1986 ROGUE(6) diff --git a/src/cc/rogue/rogue.desktop b/src/cc/rogue/rogue.desktop new file mode 100644 index 000000000..74f9518c7 --- /dev/null +++ b/src/cc/rogue/rogue.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Name=Rogue +GenericName=Rogue +Comment=The original curses-based adventure game +Exec=rogue +Icon=rogue.png +Terminal=true +Type=Application +Categories=Game;RolePlaying; +Version=1.0 diff --git a/src/cc/rogue/rogue.doc b/src/cc/rogue/rogue.doc new file mode 100644 index 000000000..684738d11 --- /dev/null +++ b/src/cc/rogue/rogue.doc @@ -0,0 +1,858 @@ + + + + + + + + A Guide to the Dungeons of Doom + + + Michael C. Toy + Kenneth C. R. C. Arnold + + + Computer Systems Research Group + Department of Electrical Engineering and Computer Science + University of California + Berkeley, California 94720 + + + + + ABSTRACT + + Rogue is a visual CRT based fantasy game which runs + under the UNIX timesharing system. This paper de- + scribes how to play rogue, and gives a few hints for + those who might otherwise get lost in the Dungeons + of Doom. + + + + +1. Introduction + + You have just finished your years as a student at the +local fighter's guild. After much practice and sweat you +have finally completed your training and are ready to embark +upon a perilous adventure. As a test of your skills, the +local guildmasters have sent you into the Dungeons of Doom. +Your task is to return with the Amulet of Yendor. Your +reward for the completion of this task will be a full mem- +bership in the local guild. In addition, you are allowed to +keep all the loot you bring back from the dungeons. + + In preparation for your journey, you are given an +enchanted mace, a bow, and a quiver of arrows taken from a +dragon's hoard in the far off Dark Mountains. You are also +outfitted with elf-crafted armor and given enough food to +reach the dungeons. You say goodbye to family and friends +for what may be the last time and head up the road. + + You set out on your way to the dungeons and after sev- +eral days of uneventful travel, you see the ancient ruins +that mark the entrance to the Dungeons of Doom. It is late +at night, so you make camp at the entrance and spend the +____________________ + UNIX is a trademark of Bell Laboratories + + + + + + + + + + + + +USD:33-2 A Guide to the Dungeons of Doom + + +night sleeping under the open skies. In the morning you +gather your weapons, put on your armor, eat what is almost +your last food, and enter the dungeons. + +2. What is going on here? + + You have just begun a game of rogue. Your goal is to +grab as much treasure as you can, find the Amulet of Yendor, +and get out of the Dungeons of Doom alive. On the screen, a +map of where you have been and what you have seen on the +current dungeon level is kept. As you explore more of the +level, it appears on the screen in front of you. + + Rogue differs from most computer fantasy games in that +it is screen oriented. Commands are all one or two +keystrokes1 and the results of your commands are displayed +graphically on the screen rather than being explained in +words.2 + + Another major difference between rogue and other com- +puter fantasy games is that once you have solved all the +puzzles in a standard fantasy game, it has lost most of its +excitement and it ceases to be fun. Rogue, on the other +hand, generates a new dungeon every time you play it and +even the author finds it an entertaining and exciting game. + +3. What do all those things on the screen mean? + + In order to understand what is going on in rogue you +have to first get some grasp of what rogue is doing with the +screen. The rogue screen is intended to replace the "You +can see ..." descriptions of standard fantasy games. Figure +1 is a sample of what a rogue screen might look like. + +3.1. The bottom line + + At the bottom line of the screen are a few pieces of +cryptic information describing your current status. Here is +an explanation of what these things mean: + +Level This number indicates how deep you have gone in the + dungeon. It starts at one and goes up as you go + deeper into the dungeon. + +Gold The number of gold pieces you have managed to find + and keep with you so far. +____________________ + 1 As opposed to pseudo English sentences. + 2 A minimum screen size of 24 lines by 80 columns is re- +quired. If the screen is larger, only the 24x80 section +will be used for the map. + + + + + + + + + + + + +A Guide to the Dungeons of Doom USD:33-3 + + + +____________________________________________________________ + + + ------------ + |..........+ + |..@....]..| + |....B.....| + |..........| + -----+------ + + + +Level: 1 Gold: 0 Hp: 12(12) Str: 16(16) Arm: 4 Exp: 1/0 + + Figure 1 +____________________________________________________________ + + +Hp Your current and maximum health points. Health + points indicate how much damage you can take before + you die. The more you get hit in a fight, the lower + they get. You can regain health points by resting. + The number in parentheses is the maximum number your + health points can reach. + +Str Your current strength and maximum ever strength. + This can be any integer less than or equal to 31, or + greater than or equal to three. The higher the num- + ber, the stronger you are. The number in the paren- + theses is the maximum strength you have attained so + far this game. + +Arm Your current armor protection. This number indicates + how effective your armor is in stopping blows from + unfriendly creatures. The higher this number is, the + more effective the armor. + +Exp These two numbers give your current experience level + and experience points. As you do things, you gain + experience points. At certain experience point + totals, you gain an experience level. The more expe- + rienced you are, the better you are able to fight and + to withstand magical attacks. + +3.2. The top line + + The top line of the screen is reserved for printing +messages that describe things that are impossible to repre- +sent visually. If you see a "--More--" on the top line, +this means that rogue wants to print another message on the +screen, but it wants to make certain that you have read the +one that is there first. To read the next message, just + + + + + + + + + + +USD:33-4 A Guide to the Dungeons of Doom + + +type a space. + +3.3. The rest of the screen + + The rest of the screen is the map of the level as you +have explored it so far. Each symbol on the screen repre- +sents something. Here is a list of what the various symbols +mean: + +@ This symbol represents you, the adventurer. + +-| These symbols represent the walls of rooms. + ++ A door to/from a room. + +. The floor of a room. + +# The floor of a passage between rooms. + +* A pile or pot of gold. + +) A weapon of some sort. + +] A piece of armor. + +! A flask containing a magic potion. + +? A piece of paper, usually a magic scroll. + += A ring with magic properties + +/ A magical staff or wand + +^ A trap, watch out for these. + +% A staircase to other levels + +: A piece of food. + +A-Z The uppercase letters represent the various inhabitants + of the Dungeons of Doom. Watch out, they can be nasty + and vicious. + +4. Commands + + Commands are given to rogue by typing one or two char- +acters. Most commands can be preceded by a count to repeat +them (e.g. typing "10s" will do ten searches). Commands for +which counts make no sense have the count ignored. To can- +cel a count or a prefix, type . The list of com- +mands is rather long, but it can be read at any time during +the game with the "?" command. Here it is for reference, +with a short explanation of each command. + + + + + + + + + + +A Guide to the Dungeons of Doom USD:33-5 + + +? The help command. Asks for a character to give help + on. If you type a "*", it will list all the commands, + otherwise it will explain what the character you typed + does. + +/ This is the "What is that on the screen?" command. A + "/" followed by any character that you see on the + level, will tell you what that character is. For + instance, typing "/@" will tell you that the "@" symbol + represents you, the player. + +h, H, ^H + Move left. You move one space to the left. If you use + upper case "h", you will continue to move left until + you run into something. This works for all movement + commands (e.g. "L" means run in direction "l") If you + use the "control" "h", you will continue moving in the + specified direction until you pass something interest- + ing or run into a wall. You should experiment with + this, since it is a very useful command, but very dif- + ficult to describe. This also works for all movement + commands. + +j Move down. + +k Move up. + +l Move right. + +y Move diagonally up and left. + +u Move diagonally up and right. + +b Move diagonally down and left. + +n Move diagonally down and right. + +t Throw an object. This is a prefix command. When fol- + lowed with a direction it throws an object in the spec- + ified direction. (e.g. type "th" to throw something to + the left.) + +f Fight until someone dies. When followed with a direc- + tion this will force you to fight the creature in that + direction until either you or it bites the big one. + +m Move onto something without picking it up. This will + move you one space in the direction you specify and, if + there is an object there you can pick up, it won't do + it. + +z Zap prefix. Point a staff or wand in a given direction + and fire it. Even non-directional staves must be + + + + + + + + + + +USD:33-6 A Guide to the Dungeons of Doom + + + pointed in some direction to be used. + +^ Identify trap command. If a trap is on your map and + you can't remember what type it is, you can get rogue + to remind you by getting next to it and typing "^" fol- + lowed by the direction that would move you on top of + it. + +s Search for traps and secret doors. Examine each space + immediately adjacent to you for the existence of a trap + or secret door. There is a large chance that even if + there is something there, you won't find it, so you + might have to search a while before you find something. + +> Climb down a staircase to the next level. Not surpris- + ingly, this can only be done if you are standing on + staircase. + +< Climb up a staircase to the level above. This can't be + done without the Amulet of Yendor in your possession. + +. Rest. This is the "do nothing" command. This is good + for waiting and healing. + +, Pick up something. This picks up whatever you are cur- + rently standing on, if you are standing on anything at + all. + +i Inventory. List what you are carrying in your pack. + +I Selective inventory. Tells you what a single item in + your pack is. + +q Quaff one of the potions you are carrying. + +r Read one of the scrolls in your pack. + +e Eat food from your pack. + +w Wield a weapon. Take a weapon out of your pack and + carry it for use in combat, replacing the one you are + currently using (if any). + +W Wear armor. You can only wear one suit of armor at a + time. This takes extra time. + +T Take armor off. You can't remove armor that is cursed. + This takes extra time. + +P Put on a ring. You can wear only two rings at a time + (one on each hand). If you aren't wearing any rings, + this command will ask you which hand you want to wear + it on, otherwise, it will place it on the unused hand. + + + + + + + + + + +A Guide to the Dungeons of Doom USD:33-7 + + + The program assumes that you wield your sword in your + right hand. + +R Remove a ring. If you are only wearing one ring, this + command takes it off. If you are wearing two, it will + ask you which one you wish to remove, + +d Drop an object. Take something out of your pack and + leave it lying on the floor. Only one object can + occupy each space. You cannot drop a cursed object at + all if you are wielding or wearing it. + +c Call an object something. If you have a type of object + in your pack which you wish to remember something + about, you can use the call command to give a name to + that type of object. This is usually used when you + figure out what a potion, scroll, ring, or staff is + after you pick it up, or when you want to remember + which of those swords in your pack you were wielding. + +D Print out which things you've discovered something + about. This command will ask you what type of thing + you are interested in. If you type the character for a + given type of object (e.g. "!" for potion) it will + tell you which kinds of that type of object you've dis- + covered (i.e., figured out what they are). This com- + mand works for potions, scrolls, rings, and staves and + wands. + +o Examine and set options. This command is further + explained in the section on options. + +^R Redraws the screen. Useful if spurious messages or + transmission errors have messed up the display. + +^P Print last message. Useful when a message disappears + before you can read it. This only repeats the last + message that was not a mistyped command so that you + don't loose anything by accidentally typing the wrong + character instead of ^P. + + + Cancel a command, prefix, or count. + +! Escape to a shell for some commands. + +Q Quit. Leave the game. + +S Save the current game in a file. It will ask you + whether you wish to use the default save file. Caveat: + Rogue won't let you start up a copy of a saved game, + and it removes the save file as soon as you start up a + restored game. This is to prevent people from saving a + + + + + + + + + + +USD:33-8 A Guide to the Dungeons of Doom + + + game just before a dangerous position and then restart- + ing it if they die. To restore a saved game, give the + file name as an argument to rogue. As in + % rogue save_file + + To restart from the default save file (see below), run + % rogue -r + +v Prints the program version number. + +) Print the weapon you are currently wielding + +] Print the armor you are currently wearing + += Print the rings you are currently wearing + +@ Reprint the status line on the message line + +5. Rooms + + Rooms in the dungeons are either lit or dark. If you +walk into a lit room, the entire room will be drawn on the +screen as soon as you enter. If you walk into a dark room, +it will only be displayed as you explore it. Upon leaving a +room, all monsters inside the room are erased from the +screen. In the darkness you can only see one space in all +directions around you. A corridor is always dark. + +6. Fighting + + If you see a monster and you wish to fight it, just +attempt to run into it. Many times a monster you find will +mind its own business unless you attack it. It is often the +case that discretion is the better part of valor. + +7. Objects you can find + + When you find something in the dungeon, it is common to +want to pick the object up. This is accomplished in rogue +by walking over the object (unless you use the "m" prefix, +see above). If you are carrying too many things, the pro- +gram will tell you and it won't pick up the object, other- +wise it will add it to your pack and tell you what you just +picked up. + + Many of the commands that operate on objects must +prompt you to find out which object you want to use. If you +change your mind and don't want to do that command after +all, just type an and the command will be aborted. + + Some objects, like armor and weapons, are easily dif- +ferentiated. Others, like scrolls and potions, are given +labels which vary according to type. During a game, any two + + + + + + + + + + +A Guide to the Dungeons of Doom USD:33-9 + + +of the same kind of object with the same label are the same +type. However, the labels will vary from game to game. + + When you use one of these labeled objects, if its +effect is obvious, rogue will remember what it is for you. +If it's effect isn't extremely obvious you will be asked +what you want to scribble on it so you will recognize it +later, or you can use the "call" command (see above). + +7.1. Weapons + + Some weapons, like arrows, come in bunches, but most +come one at a time. In order to use a weapon, you must +wield it. To fire an arrow out of a bow, you must first +wield the bow, then throw the arrow. You can only wield one +weapon at a time, but you can't change weapons if the one +you are currently wielding is cursed. The commands to use +weapons are "w" (wield) and "t" (throw). + +7.2. Armor + + There are various sorts of armor lying around in the +dungeon. Some of it is enchanted, some is cursed, and some +is just normal. Different armor types have different armor +protection. The higher the armor protection, the more pro- +tection the armor affords against the blows of monsters. +Here is a list of the various armor types and their normal +armor protection: + + + +-----------------------------------------+ + | Type Protection | + |None 0 | + |Leather armor 2 | + |Studded leather / Ring mail 3 | + |Scale mail 4 | + |Chain mail 5 | + |Banded mail / Splint mail 6 | + |Plate mail 7 | + +-----------------------------------------+ + + +If a piece of armor is enchanted, its armor protection will +be higher than normal. If a suit of armor is cursed, its +armor protection will be lower, and you will not be able to +remove it. However, not all armor with a protection that is +lower than normal is cursed. + + The commands to use weapons are "W" (wear) and "T" +(take off). + + + + + + + + + + + + + +USD:33-10 A Guide to the Dungeons of Doom + + +7.3. Scrolls + + Scrolls come with titles in an unknown tongue3. After +you read a scroll, it disappears from your pack. The com- +mand to use a scroll is "r" (read). + +7.4. Potions + + Potions are labeled by the color of the liquid inside +the flask. They disappear after being quaffed. The command +to use a scroll is "q" (quaff). + +7.5. Staves and Wands + + Staves and wands do the same kinds of things. Staves +are identified by a type of wood; wands by a type of metal +or bone. They are generally things you want to do to some- +thing over a long distance, so you must point them at what +you wish to affect to use them. Some staves are not +affected by the direction they are pointed, though. Staves +come with multiple magic charges, the number being random, +and when they are used up, the staff is just a piece of wood +or metal. + + The command to use a wand or staff is "z" (zap) + +7.6. Rings + + Rings are very useful items, since they are relatively +permanent magic, unlike the usually fleeting effects of +potions, scrolls, and staves. Of course, the bad rings are +also more powerful. Most rings also cause you to use up +food more rapidly, the rate varying with the type of ring. +Rings are differentiated by their stone settings. The com- +mands to use rings are "P" (put on) and "R" (remove). + +7.7. Food + + Food is necessary to keep you going. If you go too +long without eating you will faint, and eventually die of +starvation. The command to use food is "e" (eat). + +8. Options + + Due to variations in personal tastes and conceptions of +the way rogue should do things, there are a set of options +you can set that cause rogue to behave in various different +____________________ + 3 Actually, it's a dialect spoken only by the twenty-sev- +en members of a tribe in Outer Mongolia, but you're not sup- +posed to know that. + + + + + + + + + + + + +A Guide to the Dungeons of Doom USD:33-11 + + +ways. + +8.1. Setting the options + + There are two ways to set the options. The first is +with the "o" command of rogue; the second is with the +"ROGUEOPTS" environment variable4. + +8.1.1. Using the `o' command + + When you type "o" in rogue, it clears the screen and +displays the current settings for all the options. It then +places the cursor by the value of the first option and waits +for you to type. You can type a which means to go +to the next option, a "-" which means to go to the previous +option, an which means to return to the game, or +you can give the option a value. For boolean options this +merely involves typing "t" for true or "f" for false. For +string options, type the new value followed by a . + +8.1.2. Using the ROGUEOPTS variable + + The ROGUEOPTS variable is a string containing a comma +separated list of initial values for the various options. +Boolean variables can be turned on by listing their name or +turned off by putting a "no" in front of the name. Thus to +set up an environment variable so that jump is on, terse is +off, and the name is set to "Blue Meanie", use the command + % setenv ROGUEOPTS "jump,noterse,name=Blue Meanie"5 + +8.2. Option list + + Here is a list of the options and an explanation of +what each one is for. The default value for each is +enclosed in square brackets. For character string options, +input over fifty characters will be ignored. + +terse [noterse] + Useful for those who are tired of the sometimes lengthy + messages of rogue. This is a useful option for playing + on slow terminals, so this option defaults to terse if + you are on a slow (1200 baud or under) terminal. + + +____________________ + 4 On Version 6 systems, there is no equivalent of the +ROGUEOPTS feature. + 5 For those of you who use the Bourne shell sh (1), the +commands would be + $ ROGUEOPTS="jump,noterse,name=Blue Meanie" + $ export ROGUEOPTS + + + + + + + + + + + + +USD:33-12 A Guide to the Dungeons of Doom + + +jump [nojump] + If this option is set, running moves will not be dis- + played until you reach the end of the move. This saves + considerable cpu and display time. This option + defaults to jump if you are using a slow terminal. + +flush [noflush] + All typeahead is thrown away after each round of bat- + tle. This is useful for those who type far ahead and + then watch in dismay as a Bat kills them. + +seefloor [seefloor] + Display the floor around you on the screen as you move + through dark rooms. Due to the amount of characters + generated, this option defaults to noseefloor if you + are using a slow terminal. + +passgo [nopassgo] + Follow turnings in passageways. If you run in a pas- + sage and you run into stone or a wall, rogue will see + if it can turn to the right or left. If it can only + turn one way, it will turn that way. If it can turn + either or neither, it will stop. This algorithm can + sometimes lead to slightly confusing occurrences which + is why it defaults to nopassgo. + +tombstone [tombstone] + Print out the tombstone at the end if you get killed. + This is nice but slow, so you can turn it off if you + like. + +inven [overwrite] + Inventory type. This can have one of three values: + overwrite, slow, or clear. With overwrite the top + lines of the map are overwritten with the list when + inventory is requested or when "Which item do you wish + to . . .? " questions are answered with a "*". How- + ever, if the list is longer than a screenful, the + screen is cleared. With slow, lists are displayed one + item at a time on the top of the screen, and with + clear, the screen is cleared, the list is displayed, + and then the dungeon level is re-displayed. Due to + speed considerations, clear is the default for termi- + nals without clear-to-end-of-line capabilities. + +name [account name] + This is the name of your character. It is used if you + get on the top ten scorer's list. + +fruit [slime-mold] + This should hold the name of a fruit that you enjoy + eating. It is basically a whimsey that rogue uses in a + couple of places. + + + + + + + + + + +A Guide to the Dungeons of Doom USD:33-13 + + +file [~/rogue.save] + The default file name for saving the game. If your + phone is hung up by accident, rogue will automatically + save the game in this file. The file name may start + with the special character "~" which expands to be your + home directory. + +9. Scoring + + Rogue usually maintains a list of the top scoring peo- +ple or scores on your machine. Depending on how it is set +up, it can post either the top scores or the top players. +In the latter case, each account on the machine can post +only one non-winning score on this list. If you score +higher than someone else on this list, or better your previ- +ous score on the list, you will be inserted in the proper +place under your current name. How many scores are kept can +also be set up by whoever installs it on your machine. + + If you quit the game, you get out with all of your gold +intact. If, however, you get killed in the Dungeons of +Doom, your body is forwarded to your next-of-kin, along with +90% of your gold; ten percent of your gold is kept by the +Dungeons' wizard as a fee6. This should make you consider +whether you want to take one last hit at that monster and +possibly live, or quit and thus stop with whatever you have. +If you quit, you do get all your gold, but if you swing and +live, you might find more. + + If you just want to see what the current top play- +ers/games list is, you can type + % rogue -s + +10. Acknowledgements + + Rogue was originally conceived of by Glenn Wichman and +Michael Toy. Ken Arnold and Michael Toy then smoothed out +the user interface, and added jillions of new features. We +would like to thank Bob Arnold, Michelle Busch, Andy +Hatcher, Kipp Hickman, Mark Horton, Daniel Jensen, Bill Joy, +Joe Kalash, Steve Maurer, Marty McNary, Jan Miller, and +Scott Nelson for their ideas and assistance; and also the +teeming multitudes who graciously ignored work, school, and +social life to play rogue and send us bugs, complaints, sug- +gestions, and just plain flames. And also Mom. + + + +____________________ + 6 The Dungeon's wizard is named Wally the Wonder Badger. +Invocations should be accompanied by a sizable donation. + + + + + + + + diff --git a/src/cc/rogue/rogue.doc.in b/src/cc/rogue/rogue.doc.in new file mode 100644 index 000000000..3031d0d24 --- /dev/null +++ b/src/cc/rogue/rogue.doc.in @@ -0,0 +1,858 @@ + + + + + + + + A Guide to the Dungeons of Doom + + + Michael C. Toy + Kenneth C. R. C. Arnold + + + Computer Systems Research Group + Department of Electrical Engineering and Computer Science + University of California + Berkeley, California 94720 + + + + + ABSTRACT + + Rogue is a visual CRT based fantasy game which runs + under the UNIX timesharing system. This paper de- + scribes how to play rogue, and gives a few hints for + those who might otherwise get lost in the Dungeons + of Doom. + + + + +1. Introduction + + You have just finished your years as a student at the +local fighter's guild. After much practice and sweat you +have finally completed your training and are ready to embark +upon a perilous adventure. As a test of your skills, the +local guildmasters have sent you into the Dungeons of Doom. +Your task is to return with the Amulet of Yendor. Your +reward for the completion of this task will be a full mem- +bership in the local guild. In addition, you are allowed to +keep all the loot you bring back from the dungeons. + + In preparation for your journey, you are given an +enchanted mace, a bow, and a quiver of arrows taken from a +dragon's hoard in the far off Dark Mountains. You are also +outfitted with elf-crafted armor and given enough food to +reach the dungeons. You say goodbye to family and friends +for what may be the last time and head up the road. + + You set out on your way to the dungeons and after sev- +eral days of uneventful travel, you see the ancient ruins +that mark the entrance to the Dungeons of Doom. It is late +at night, so you make camp at the entrance and spend the +____________________ + UNIX is a trademark of Bell Laboratories + + + + + + + + + + + + +USD:33-2 A Guide to the Dungeons of Doom + + +night sleeping under the open skies. In the morning you +gather your weapons, put on your armor, eat what is almost +your last food, and enter the dungeons. + +2. What is going on here? + + You have just begun a game of rogue. Your goal is to +grab as much treasure as you can, find the Amulet of Yendor, +and get out of the Dungeons of Doom alive. On the screen, a +map of where you have been and what you have seen on the +current dungeon level is kept. As you explore more of the +level, it appears on the screen in front of you. + + Rogue differs from most computer fantasy games in that +it is screen oriented. Commands are all one or two +keystrokes1 and the results of your commands are displayed +graphically on the screen rather than being explained in +words.2 + + Another major difference between rogue and other com- +puter fantasy games is that once you have solved all the +puzzles in a standard fantasy game, it has lost most of its +excitement and it ceases to be fun. Rogue, on the other +hand, generates a new dungeon every time you play it and +even the author finds it an entertaining and exciting game. + +3. What do all those things on the screen mean? + + In order to understand what is going on in rogue you +have to first get some grasp of what rogue is doing with the +screen. The rogue screen is intended to replace the "You +can see ..." descriptions of standard fantasy games. Figure +1 is a sample of what a rogue screen might look like. + +3.1. The bottom line + + At the bottom line of the screen are a few pieces of +cryptic information describing your current status. Here is +an explanation of what these things mean: + +Level This number indicates how deep you have gone in the + dungeon. It starts at one and goes up as you go + deeper into the dungeon. + +Gold The number of gold pieces you have managed to find + and keep with you so far. +____________________ + 1 As opposed to pseudo English sentences. + 2 A minimum screen size of 24 lines by 80 columns is re- +quired. If the screen is larger, only the 24x80 section +will be used for the map. + + + + + + + + + + + + +A Guide to the Dungeons of Doom USD:33-3 + + + +____________________________________________________________ + + + ------------ + |..........+ + |..@....]..| + |....B.....| + |..........| + -----+------ + + + +Level: 1 Gold: 0 Hp: 12(12) Str: 16(16) Arm: 4 Exp: 1/0 + + Figure 1 +____________________________________________________________ + + +Hp Your current and maximum health points. Health + points indicate how much damage you can take before + you die. The more you get hit in a fight, the lower + they get. You can regain health points by resting. + The number in parentheses is the maximum number your + health points can reach. + +Str Your current strength and maximum ever strength. + This can be any integer less than or equal to 31, or + greater than or equal to three. The higher the num- + ber, the stronger you are. The number in the paren- + theses is the maximum strength you have attained so + far this game. + +Arm Your current armor protection. This number indicates + how effective your armor is in stopping blows from + unfriendly creatures. The higher this number is, the + more effective the armor. + +Exp These two numbers give your current experience level + and experience points. As you do things, you gain + experience points. At certain experience point + totals, you gain an experience level. The more expe- + rienced you are, the better you are able to fight and + to withstand magical attacks. + +3.2. The top line + + The top line of the screen is reserved for printing +messages that describe things that are impossible to repre- +sent visually. If you see a "--More--" on the top line, +this means that rogue wants to print another message on the +screen, but it wants to make certain that you have read the +one that is there first. To read the next message, just + + + + + + + + + + +USD:33-4 A Guide to the Dungeons of Doom + + +type a space. + +3.3. The rest of the screen + + The rest of the screen is the map of the level as you +have explored it so far. Each symbol on the screen repre- +sents something. Here is a list of what the various symbols +mean: + +@ This symbol represents you, the adventurer. + +-| These symbols represent the walls of rooms. + ++ A door to/from a room. + +. The floor of a room. + +# The floor of a passage between rooms. + +* A pile or pot of gold. + +) A weapon of some sort. + +] A piece of armor. + +! A flask containing a magic potion. + +? A piece of paper, usually a magic scroll. + += A ring with magic properties + +/ A magical staff or wand + +^ A trap, watch out for these. + +% A staircase to other levels + +: A piece of food. + +A-Z The uppercase letters represent the various inhabitants + of the Dungeons of Doom. Watch out, they can be nasty + and vicious. + +4. Commands + + Commands are given to rogue by typing one or two char- +acters. Most commands can be preceded by a count to repeat +them (e.g. typing "10s" will do ten searches). Commands for +which counts make no sense have the count ignored. To can- +cel a count or a prefix, type . The list of com- +mands is rather long, but it can be read at any time during +the game with the "?" command. Here it is for reference, +with a short explanation of each command. + + + + + + + + + + +A Guide to the Dungeons of Doom USD:33-5 + + +? The help command. Asks for a character to give help + on. If you type a "*", it will list all the commands, + otherwise it will explain what the character you typed + does. + +/ This is the "What is that on the screen?" command. A + "/" followed by any character that you see on the + level, will tell you what that character is. For + instance, typing "/@" will tell you that the "@" symbol + represents you, the player. + +h, H, ^H + Move left. You move one space to the left. If you use + upper case "h", you will continue to move left until + you run into something. This works for all movement + commands (e.g. "L" means run in direction "l") If you + use the "control" "h", you will continue moving in the + specified direction until you pass something interest- + ing or run into a wall. You should experiment with + this, since it is a very useful command, but very dif- + ficult to describe. This also works for all movement + commands. + +j Move down. + +k Move up. + +l Move right. + +y Move diagonally up and left. + +u Move diagonally up and right. + +b Move diagonally down and left. + +n Move diagonally down and right. + +t Throw an object. This is a prefix command. When fol- + lowed with a direction it throws an object in the spec- + ified direction. (e.g. type "th" to throw something to + the left.) + +f Fight until someone dies. When followed with a direc- + tion this will force you to fight the creature in that + direction until either you or it bites the big one. + +m Move onto something without picking it up. This will + move you one space in the direction you specify and, if + there is an object there you can pick up, it won't do + it. + +z Zap prefix. Point a staff or wand in a given direction + and fire it. Even non-directional staves must be + + + + + + + + + + +USD:33-6 A Guide to the Dungeons of Doom + + + pointed in some direction to be used. + +^ Identify trap command. If a trap is on your map and + you can't remember what type it is, you can get rogue + to remind you by getting next to it and typing "^" fol- + lowed by the direction that would move you on top of + it. + +s Search for traps and secret doors. Examine each space + immediately adjacent to you for the existence of a trap + or secret door. There is a large chance that even if + there is something there, you won't find it, so you + might have to search a while before you find something. + +> Climb down a staircase to the next level. Not surpris- + ingly, this can only be done if you are standing on + staircase. + +< Climb up a staircase to the level above. This can't be + done without the Amulet of Yendor in your possession. + +. Rest. This is the "do nothing" command. This is good + for waiting and healing. + +, Pick up something. This picks up whatever you are cur- + rently standing on, if you are standing on anything at + all. + +i Inventory. List what you are carrying in your pack. + +I Selective inventory. Tells you what a single item in + your pack is. + +q Quaff one of the potions you are carrying. + +r Read one of the scrolls in your pack. + +e Eat food from your pack. + +w Wield a weapon. Take a weapon out of your pack and + carry it for use in combat, replacing the one you are + currently using (if any). + +W Wear armor. You can only wear one suit of armor at a + time. This takes extra time. + +T Take armor off. You can't remove armor that is cursed. + This takes extra time. + +P Put on a ring. You can wear only two rings at a time + (one on each hand). If you aren't wearing any rings, + this command will ask you which hand you want to wear + it on, otherwise, it will place it on the unused hand. + + + + + + + + + + +A Guide to the Dungeons of Doom USD:33-7 + + + The program assumes that you wield your sword in your + right hand. + +R Remove a ring. If you are only wearing one ring, this + command takes it off. If you are wearing two, it will + ask you which one you wish to remove, + +d Drop an object. Take something out of your pack and + leave it lying on the floor. Only one object can + occupy each space. You cannot drop a cursed object at + all if you are wielding or wearing it. + +c Call an object something. If you have a type of object + in your pack which you wish to remember something + about, you can use the call command to give a name to + that type of object. This is usually used when you + figure out what a potion, scroll, ring, or staff is + after you pick it up, or when you want to remember + which of those swords in your pack you were wielding. + +D Print out which things you've discovered something + about. This command will ask you what type of thing + you are interested in. If you type the character for a + given type of object (e.g. "!" for potion) it will + tell you which kinds of that type of object you've dis- + covered (i.e., figured out what they are). This com- + mand works for potions, scrolls, rings, and staves and + wands. + +o Examine and set options. This command is further + explained in the section on options. + +^R Redraws the screen. Useful if spurious messages or + transmission errors have messed up the display. + +^P Print last message. Useful when a message disappears + before you can read it. This only repeats the last + message that was not a mistyped command so that you + don't loose anything by accidentally typing the wrong + character instead of ^P. + + + Cancel a command, prefix, or count. + +! Escape to a shell for some commands. + +Q Quit. Leave the game. + +S Save the current game in a file. It will ask you + whether you wish to use the default save file. Caveat: + Rogue won't let you start up a copy of a saved game, + and it removes the save file as soon as you start up a + restored game. This is to prevent people from saving a + + + + + + + + + + +USD:33-8 A Guide to the Dungeons of Doom + + + game just before a dangerous position and then restart- + ing it if they die. To restore a saved game, give the + file name as an argument to rogue. As in + % rogue save_file + + To restart from the default save file (see below), run + % rogue -r + +v Prints the program version number. + +) Print the weapon you are currently wielding + +] Print the armor you are currently wearing + += Print the rings you are currently wearing + +@ Reprint the status line on the message line + +5. Rooms + + Rooms in the dungeons are either lit or dark. If you +walk into a lit room, the entire room will be drawn on the +screen as soon as you enter. If you walk into a dark room, +it will only be displayed as you explore it. Upon leaving a +room, all monsters inside the room are erased from the +screen. In the darkness you can only see one space in all +directions around you. A corridor is always dark. + +6. Fighting + + If you see a monster and you wish to fight it, just +attempt to run into it. Many times a monster you find will +mind its own business unless you attack it. It is often the +case that discretion is the better part of valor. + +7. Objects you can find + + When you find something in the dungeon, it is common to +want to pick the object up. This is accomplished in rogue +by walking over the object (unless you use the "m" prefix, +see above). If you are carrying too many things, the pro- +gram will tell you and it won't pick up the object, other- +wise it will add it to your pack and tell you what you just +picked up. + + Many of the commands that operate on objects must +prompt you to find out which object you want to use. If you +change your mind and don't want to do that command after +all, just type an and the command will be aborted. + + Some objects, like armor and weapons, are easily dif- +ferentiated. Others, like scrolls and potions, are given +labels which vary according to type. During a game, any two + + + + + + + + + + +A Guide to the Dungeons of Doom USD:33-9 + + +of the same kind of object with the same label are the same +type. However, the labels will vary from game to game. + + When you use one of these labeled objects, if its +effect is obvious, rogue will remember what it is for you. +If it's effect isn't extremely obvious you will be asked +what you want to scribble on it so you will recognize it +later, or you can use the "call" command (see above). + +7.1. Weapons + + Some weapons, like arrows, come in bunches, but most +come one at a time. In order to use a weapon, you must +wield it. To fire an arrow out of a bow, you must first +wield the bow, then throw the arrow. You can only wield one +weapon at a time, but you can't change weapons if the one +you are currently wielding is cursed. The commands to use +weapons are "w" (wield) and "t" (throw). + +7.2. Armor + + There are various sorts of armor lying around in the +dungeon. Some of it is enchanted, some is cursed, and some +is just normal. Different armor types have different armor +protection. The higher the armor protection, the more pro- +tection the armor affords against the blows of monsters. +Here is a list of the various armor types and their normal +armor protection: + + + +-----------------------------------------+ + | Type Protection | + |None 0 | + |Leather armor 2 | + |Studded leather / Ring mail 3 | + |Scale mail 4 | + |Chain mail 5 | + |Banded mail / Splint mail 6 | + |Plate mail 7 | + +-----------------------------------------+ + + +If a piece of armor is enchanted, its armor protection will +be higher than normal. If a suit of armor is cursed, its +armor protection will be lower, and you will not be able to +remove it. However, not all armor with a protection that is +lower than normal is cursed. + + The commands to use weapons are "W" (wear) and "T" +(take off). + + + + + + + + + + + + + +USD:33-10 A Guide to the Dungeons of Doom + + +7.3. Scrolls + + Scrolls come with titles in an unknown tongue3. After +you read a scroll, it disappears from your pack. The com- +mand to use a scroll is "r" (read). + +7.4. Potions + + Potions are labeled by the color of the liquid inside +the flask. They disappear after being quaffed. The command +to use a scroll is "q" (quaff). + +7.5. Staves and Wands + + Staves and wands do the same kinds of things. Staves +are identified by a type of wood; wands by a type of metal +or bone. They are generally things you want to do to some- +thing over a long distance, so you must point them at what +you wish to affect to use them. Some staves are not +affected by the direction they are pointed, though. Staves +come with multiple magic charges, the number being random, +and when they are used up, the staff is just a piece of wood +or metal. + + The command to use a wand or staff is "z" (zap) + +7.6. Rings + + Rings are very useful items, since they are relatively +permanent magic, unlike the usually fleeting effects of +potions, scrolls, and staves. Of course, the bad rings are +also more powerful. Most rings also cause you to use up +food more rapidly, the rate varying with the type of ring. +Rings are differentiated by their stone settings. The com- +mands to use rings are "P" (put on) and "R" (remove). + +7.7. Food + + Food is necessary to keep you going. If you go too +long without eating you will faint, and eventually die of +starvation. The command to use food is "e" (eat). + +8. Options + + Due to variations in personal tastes and conceptions of +the way rogue should do things, there are a set of options +you can set that cause rogue to behave in various different +____________________ + 3 Actually, it's a dialect spoken only by the twenty-sev- +en members of a tribe in Outer Mongolia, but you're not sup- +posed to know that. + + + + + + + + + + + + +A Guide to the Dungeons of Doom USD:33-11 + + +ways. + +8.1. Setting the options + + There are two ways to set the options. The first is +with the "o" command of rogue; the second is with the +"ROGUEOPTS" environment variable4. + +8.1.1. Using the `o' command + + When you type "o" in rogue, it clears the screen and +displays the current settings for all the options. It then +places the cursor by the value of the first option and waits +for you to type. You can type a which means to go +to the next option, a "-" which means to go to the previous +option, an which means to return to the game, or +you can give the option a value. For boolean options this +merely involves typing "t" for true or "f" for false. For +string options, type the new value followed by a . + +8.1.2. Using the ROGUEOPTS variable + + The ROGUEOPTS variable is a string containing a comma +separated list of initial values for the various options. +Boolean variables can be turned on by listing their name or +turned off by putting a "no" in front of the name. Thus to +set up an environment variable so that jump is on, terse is +off, and the name is set to "Blue Meanie", use the command + % setenv ROGUEOPTS "jump,noterse,name=Blue Meanie"5 + +8.2. Option list + + Here is a list of the options and an explanation of +what each one is for. The default value for each is +enclosed in square brackets. For character string options, +input over fifty characters will be ignored. + +terse [noterse] + Useful for those who are tired of the sometimes lengthy + messages of rogue. This is a useful option for playing + on slow terminals, so this option defaults to terse if + you are on a slow (1200 baud or under) terminal. + + +____________________ + 4 On Version 6 systems, there is no equivalent of the +ROGUEOPTS feature. + 5 For those of you who use the Bourne shell sh (1), the +commands would be + $ ROGUEOPTS="jump,noterse,name=Blue Meanie" + $ export ROGUEOPTS + + + + + + + + + + + + +USD:33-12 A Guide to the Dungeons of Doom + + +jump [nojump] + If this option is set, running moves will not be dis- + played until you reach the end of the move. This saves + considerable cpu and display time. This option + defaults to jump if you are using a slow terminal. + +flush [noflush] + All typeahead is thrown away after each round of bat- + tle. This is useful for those who type far ahead and + then watch in dismay as a Bat kills them. + +seefloor [seefloor] + Display the floor around you on the screen as you move + through dark rooms. Due to the amount of characters + generated, this option defaults to noseefloor if you + are using a slow terminal. + +passgo [nopassgo] + Follow turnings in passageways. If you run in a pas- + sage and you run into stone or a wall, rogue will see + if it can turn to the right or left. If it can only + turn one way, it will turn that way. If it can turn + either or neither, it will stop. This algorithm can + sometimes lead to slightly confusing occurrences which + is why it defaults to nopassgo. + +tombstone [tombstone] + Print out the tombstone at the end if you get killed. + This is nice but slow, so you can turn it off if you + like. + +inven [overwrite] + Inventory type. This can have one of three values: + overwrite, slow, or clear. With overwrite the top + lines of the map are overwritten with the list when + inventory is requested or when "Which item do you wish + to . . .? " questions are answered with a "*". How- + ever, if the list is longer than a screenful, the + screen is cleared. With slow, lists are displayed one + item at a time on the top of the screen, and with + clear, the screen is cleared, the list is displayed, + and then the dungeon level is re-displayed. Due to + speed considerations, clear is the default for termi- + nals without clear-to-end-of-line capabilities. + +name [account name] + This is the name of your character. It is used if you + get on the top ten scorer's list. + +fruit [slime-mold] + This should hold the name of a fruit that you enjoy + eating. It is basically a whimsey that rogue uses in a + couple of places. + + + + + + + + + + +A Guide to the Dungeons of Doom USD:33-13 + + +file [~/rogue.save] + The default file name for saving the game. If your + phone is hung up by accident, rogue will automatically + save the game in this file. The file name may start + with the special character "~" which expands to be your + home directory. + +9. Scoring + + Rogue usually maintains a list of the top scoring peo- +ple or scores on your machine. Depending on how it is set +up, it can post either the top scores or the top players. +In the latter case, each account on the machine can post +only one non-winning score on this list. If you score +higher than someone else on this list, or better your previ- +ous score on the list, you will be inserted in the proper +place under your current name. How many scores are kept can +also be set up by whoever installs it on your machine. + + If you quit the game, you get out with all of your gold +intact. If, however, you get killed in the Dungeons of +Doom, your body is forwarded to your next-of-kin, along with +90% of your gold; ten percent of your gold is kept by the +Dungeons' wizard as a fee6. This should make you consider +whether you want to take one last hit at that monster and +possibly live, or quit and thus stop with whatever you have. +If you quit, you do get all your gold, but if you swing and +live, you might find more. + + If you just want to see what the current top play- +ers/games list is, you can type + % @PROGRAM@ -s + +10. Acknowledgements + + Rogue was originally conceived of by Glenn Wichman and +Michael Toy. Ken Arnold and Michael Toy then smoothed out +the user interface, and added jillions of new features. We +would like to thank Bob Arnold, Michelle Busch, Andy +Hatcher, Kipp Hickman, Mark Horton, Daniel Jensen, Bill Joy, +Joe Kalash, Steve Maurer, Marty McNary, Jan Miller, and +Scott Nelson for their ideas and assistance; and also the +teeming multitudes who graciously ignored work, school, and +social life to play rogue and send us bugs, complaints, sug- +gestions, and just plain flames. And also Mom. + + + +____________________ + 6 The Dungeon's wizard is named Wally the Wonder Badger. +Invocations should be accompanied by a sizable donation. + + + + + + + + diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h new file mode 100644 index 000000000..ae834eb7a --- /dev/null +++ b/src/cc/rogue/rogue.h @@ -0,0 +1,785 @@ +/* + * Rogue definitions and variable declarations + * + * @(#)rogue.h 5.42 (Berkeley) 08/06/83 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include "extern.h" + +#undef lines + +#define NOOP(x) (x += 0) +#define CCHAR(x) ( (char) (x & A_CHARTEXT) ) +/* + * Maximum number of different things + */ +#define MAXROOMS 9 +#define MAXTHINGS 9 +#define MAXOBJ 9 +#define MAXPACK 23 +#define MAXTRAPS 10 +#define AMULETLEVEL 26 +#define NUMTHINGS 7 /* number of types of things */ +#define MAXPASS 13 /* upper limit on number of passages */ +#define NUMLINES 24 +#define NUMCOLS 80 +#define STATLINE (NUMLINES - 1) +#define BORE_LEVEL 50 + +/* + * return values for get functions + */ +#define NORM 0 /* normal exit */ +#define QUIT 1 /* quit option setting */ +#define MINUS 2 /* back up one option */ + +/* + * inventory types + */ +#define INV_OVER 0 +#define INV_SLOW 1 +#define INV_CLEAR 2 + +/* + * All the fun defines + */ +#define when break;case +#define otherwise break;default +#define until(expr) while(!(expr)) +#define next(ptr) (*ptr).l_next +#define prev(ptr) (*ptr).l_prev +#define winat(y,x) (moat(y,x) != NULL ? moat(y,x)->t_disguise : chat(y,x)) +#define ce(a,b) ((a).x == (b).x && (a).y == (b).y) +#define hero player.t_pos +#define pstats player.t_stats +#define pack player.t_pack +#define proom player.t_room +#define max_hp player.t_stats.s_maxhp +#define attach(a,b) _attach(&a,b) +#define detach(a,b) _detach(&a,b) +#define free_list(a) _free_list(&a) +#undef max +#define max(a,b) ((a) > (b) ? (a) : (b)) +#define on(thing,flag) ((bool)(((thing).t_flags & (flag)) != 0)) +#define GOLDCALC (rnd(50 + 10 * level) + 2) +#define ISRING(h,r) (cur_ring[h] != NULL && cur_ring[h]->o_which == r) +#define ISWEARING(r) (ISRING(LEFT, r) || ISRING(RIGHT, r)) +#define ISMULT(type) (type == POTION || type == SCROLL || type == FOOD) +#define INDEX(y,x) (&places[((x) << 5) + (y)]) +#define chat(y,x) (places[((x) << 5) + (y)].p_ch) +#define flat(y,x) (places[((x) << 5) + (y)].p_flags) +#define moat(y,x) (places[((x) << 5) + (y)].p_monst) +#define unc(cp) (cp).y, (cp).x +#ifdef MASTER +#define debug if (wizard) msg +#endif + +/* + * things that appear on the screens + */ +#define PASSAGE '#' +#define DOOR '+' +#define FLOOR '.' +#define PLAYER '@' +#define TRAP '^' +#define STAIRS '%' +#define GOLD '*' +#define POTION '!' +#define SCROLL '?' +#define MAGIC '$' +#define FOOD ':' +#define WEAPON ')' +#define ARMOR ']' +#define AMULET ',' +#define RING '=' +#define STICK '/' +#define CALLABLE -1 +#define R_OR_S -2 + +/* + * Various constants + */ +#define BEARTIME spread(3) +#define SLEEPTIME spread(5) +#define HOLDTIME spread(2) +#define WANDERTIME spread(70) +#define BEFORE spread(1) +#define AFTER spread(2) +#define HEALTIME 30 +#define HUHDURATION 20 +#define SEEDURATION 850 +#define HUNGERTIME 1300 +#define MORETIME 150 +#define STOMACHSIZE 2000 +#define STARVETIME 850 +#define ESCAPE 27 +#define LEFT 0 +#define RIGHT 1 +#define BOLT_LENGTH 6 +#define LAMPDIST 3 +#ifdef MASTER +#ifndef PASSWD +#define PASSWD "mTBellIQOsLNA" +#endif +#endif + +/* + * Save against things + */ +#define VS_POISON 00 +#define VS_PARALYZATION 00 +#define VS_DEATH 00 +#define VS_BREATH 02 +#define VS_MAGIC 03 + +/* + * Various flag bits + */ +/* flags for rooms */ +#define ISDARK 0000001 /* room is dark */ +#define ISGONE 0000002 /* room is gone (a corridor) */ +#define ISMAZE 0000004 /* room is gone (a corridor) */ + +/* flags for objects */ +#define ISCURSED 000001 /* object is cursed */ +#define ISKNOW 0000002 /* player knows details about the object */ +#define ISMISL 0000004 /* object is a missile type */ +#define ISMANY 0000010 /* object comes in groups */ +/* ISFOUND 0000020 ...is used for both objects and creatures */ +#define ISPROT 0000040 /* armor is permanently protected */ + +/* flags for creatures */ +#define CANHUH 0000001 /* creature can confuse */ +#define CANSEE 0000002 /* creature can see invisible creatures */ +#define ISBLIND 0000004 /* creature is blind */ +#define ISCANC 0000010 /* creature has special qualities cancelled */ +#define ISLEVIT 0000010 /* hero is levitating */ +#define ISFOUND 0000020 /* creature has been seen (used for objects) */ +#define ISGREED 0000040 /* creature runs to protect gold */ +#define ISHASTE 0000100 /* creature has been hastened */ +#define ISTARGET 000200 /* creature is the target of an 'f' command */ +#define ISHELD 0000400 /* creature has been held */ +#define ISHUH 0001000 /* creature is confused */ +#define ISINVIS 0002000 /* creature is invisible */ +#define ISMEAN 0004000 /* creature can wake when player enters room */ +#define ISHALU 0004000 /* hero is on acid trip */ +#define ISREGEN 0010000 /* creature can regenerate */ +#define ISRUN 0020000 /* creature is running at the player */ +#define SEEMONST 040000 /* hero can detect unseen monsters */ +#define ISFLY 0040000 /* creature can fly */ +#define ISSLOW 0100000 /* creature has been slowed */ + +/* + * Flags for level map + */ +#define F_PASS 0x80 /* is a passageway */ +#define F_SEEN 0x40 /* have seen this spot before */ +#define F_DROPPED 0x20 /* object was dropped here */ +#define F_LOCKED 0x20 /* door is locked */ +#define F_REAL 0x10 /* what you see is what you get */ +#define F_PNUM 0x0f /* passage number mask */ +#define F_TMASK 0x07 /* trap number mask */ + +/* + * Trap types + */ +#define T_DOOR 00 +#define T_ARROW 01 +#define T_SLEEP 02 +#define T_BEAR 03 +#define T_TELEP 04 +#define T_DART 05 +#define T_RUST 06 +#define T_MYST 07 +#define NTRAPS 8 + +/* + * Potion types + */ +#define P_CONFUSE 0 +#define P_LSD 1 +#define P_POISON 2 +#define P_STRENGTH 3 +#define P_SEEINVIS 4 +#define P_HEALING 5 +#define P_MFIND 6 +#define P_TFIND 7 +#define P_RAISE 8 +#define P_XHEAL 9 +#define P_HASTE 10 +#define P_RESTORE 11 +#define P_BLIND 12 +#define P_LEVIT 13 +#define MAXPOTIONS 14 + +/* + * Scroll types + */ +#define S_CONFUSE 0 +#define S_MAP 1 +#define S_HOLD 2 +#define S_SLEEP 3 +#define S_ARMOR 4 +#define S_ID_POTION 5 +#define S_ID_SCROLL 6 +#define S_ID_WEAPON 7 +#define S_ID_ARMOR 8 +#define S_ID_R_OR_S 9 +#define S_SCARE 10 +#define S_FDET 11 +#define S_TELEP 12 +#define S_ENCH 13 +#define S_CREATE 14 +#define S_REMOVE 15 +#define S_AGGR 16 +#define S_PROTECT 17 +#define MAXSCROLLS 18 + +/* + * Weapon types + */ +#define MACE 0 +#define SWORD 1 +#define BOW 2 +#define ARROW 3 +#define DAGGER 4 +#define TWOSWORD 5 +#define DART 6 +#define SHIRAKEN 7 +#define SPEAR 8 +#define FLAME 9 /* fake entry for dragon breath (ick) */ +#define MAXWEAPONS 9 /* this should equal FLAME */ + +/* + * Armor types + */ +#define LEATHER 0 +#define RING_MAIL 1 +#define STUDDED_LEATHER 2 +#define SCALE_MAIL 3 +#define CHAIN_MAIL 4 +#define SPLINT_MAIL 5 +#define BANDED_MAIL 6 +#define PLATE_MAIL 7 +#define MAXARMORS 8 + +/* + * Ring types + */ +#define R_PROTECT 0 +#define R_ADDSTR 1 +#define R_SUSTSTR 2 +#define R_SEARCH 3 +#define R_SEEINVIS 4 +#define R_NOP 5 +#define R_AGGR 6 +#define R_ADDHIT 7 +#define R_ADDDAM 8 +#define R_REGEN 9 +#define R_DIGEST 10 +#define R_TELEPORT 11 +#define R_STEALTH 12 +#define R_SUSTARM 13 +#define MAXRINGS 14 + +/* + * Rod/Wand/Staff types + */ +#define WS_LIGHT 0 +#define WS_INVIS 1 +#define WS_ELECT 2 +#define WS_FIRE 3 +#define WS_COLD 4 +#define WS_POLYMORPH 5 +#define WS_MISSILE 6 +#define WS_HASTE_M 7 +#define WS_SLOW_M 8 +#define WS_DRAIN 9 +#define WS_NOP 10 +#define WS_TELAWAY 11 +#define WS_TELTO 12 +#define WS_CANCEL 13 +#define MAXSTICKS 14 + +/* + * Now we define the structures and types + */ +struct rogue_state +{ + uint64_t seed; + char *keystrokes; + uint32_t needflush,replaydone; + int32_t numkeys,ind,num,guiflag,counter; + char buffered[64]; +}; + +int rogue(int argc, char **argv, char **envp); +void rogueiterate(struct rogue_state *rs); +int32_t roguefname(char *fname,uint64_t seed,int32_t counter); +int32_t flushkeystrokes(struct rogue_state *rs); + +/* + * Help list + */ +struct h_list { + char h_ch; + char *h_desc; + bool h_print; +}; + +/* + * Coordinate data type + */ +typedef struct { + int x; + int y; +} coord; + +typedef unsigned int str_t; + +/* + * Stuff about objects + */ +struct obj_info { + char *oi_name; + int oi_prob; + int oi_worth; + char *oi_guess; + bool oi_know; +}; + +/* + * Room structure + */ +struct room { + coord r_pos; /* Upper left corner */ + coord r_max; /* Size of room */ + coord r_gold; /* Where the gold is */ + int r_goldval; /* How much the gold is worth */ + short r_flags; /* info about the room */ + int r_nexits; /* Number of exits */ + coord r_exit[12]; /* Where the exits are */ +}; + +/* + * Structure describing a fighting being + */ +struct stats { + str_t s_str; /* Strength */ + int s_exp; /* Experience */ + int s_lvl; /* level of mastery */ + int s_arm; /* Armor class */ + int s_hpt; /* Hit points */ + char s_dmg[13]; /* String describing damage done */ + int s_maxhp; /* Max hit points */ +}; + +/* + * Structure for monsters and player + */ +union thing { + struct { + union thing *_l_next, *_l_prev; /* Next pointer in link */ + coord _t_pos; /* Position */ + bool _t_turn; /* If slowed, is it a turn to move */ + char _t_type; /* What it is */ + char _t_disguise; /* What mimic looks like */ + char _t_oldch; /* Character that was where it was */ + coord *_t_dest; /* Where it is running to */ + short _t_flags; /* State word */ + struct stats _t_stats; /* Physical description */ + struct room *_t_room; /* Current room for thing */ + union thing *_t_pack; /* What the thing is carrying */ + int _t_reserved; + } _t; + struct { + union thing *_l_next, *_l_prev; /* Next pointer in link */ + int _o_type; /* What kind of object it is */ + coord _o_pos; /* Where it lives on the screen */ + char *_o_text; /* What it says if you read it */ + int _o_launch; /* What you need to launch it */ + char _o_packch; /* What character it is in the pack */ + char _o_damage[8]; /* Damage if used like sword */ + char _o_hurldmg[8]; /* Damage if thrown */ + int _o_count; /* count for plural objects */ + int _o_which; /* Which object of a type it is */ + int _o_hplus; /* Plusses to hit */ + int _o_dplus; /* Plusses to damage */ + int _o_arm; /* Armor protection */ + int _o_flags; /* information about objects */ + int _o_group; /* group number for this object */ + char *_o_label; /* Label for object */ + } _o; +}; + +typedef union thing THING; + +#define l_next _t._l_next +#define l_prev _t._l_prev +#define t_pos _t._t_pos +#define t_turn _t._t_turn +#define t_type _t._t_type +#define t_disguise _t._t_disguise +#define t_oldch _t._t_oldch +#define t_dest _t._t_dest +#define t_flags _t._t_flags +#define t_stats _t._t_stats +#define t_pack _t._t_pack +#define t_room _t._t_room +#define t_reserved _t._t_reserved +#define o_type _o._o_type +#define o_pos _o._o_pos +#define o_text _o._o_text +#define o_launch _o._o_launch +#define o_packch _o._o_packch +#define o_damage _o._o_damage +#define o_hurldmg _o._o_hurldmg +#define o_count _o._o_count +#define o_which _o._o_which +#define o_hplus _o._o_hplus +#define o_dplus _o._o_dplus +#define o_arm _o._o_arm +#define o_charges o_arm +#define o_goldval o_arm +#define o_flags _o._o_flags +#define o_group _o._o_group +#define o_label _o._o_label + +/* + * describe a place on the level map + */ +typedef struct { + char p_ch; + char p_flags; + THING *p_monst; +} PLACE; + +/* + * Array containing information on all the various types of monsters + */ +struct monster { + char *m_name; /* What to call the monster */ + int m_carry; /* Probability of carrying something */ + short m_flags; /* things about the monster */ + struct stats m_stats; /* Initial stats */ +}; + +/* + * External variables + */ + +extern bool after, again, allscore, amulet, door_stop, fight_flush, + firstmove, has_hit, inv_describe, jump, kamikaze, + lower_msg, move_on, msg_esc, pack_used[], + passgo, playing, q_comm, running, save_msg, see_floor, + seenstairs, stat_msg, terse, to_death, tombstone; + +extern char dir_ch, file_name[], home[], huh[], *inv_t_name[], + l_last_comm, l_last_dir, last_comm, last_dir, *Numname, + outbuf[], *p_colors[], *r_stones[], *release, runch, + *s_names[], take, *tr_name[], *ws_made[], *ws_type[]; + +extern int a_class[], count, food_left, hungry_state, inpack, + inv_type, lastscore, level, max_hit, max_level, mpos, + n_objs, no_command, no_food, no_move, noscore, ntraps, purse, + quiet, vf_hit; + +extern unsigned int numscores; + +extern int dnum, e_levels[]; +extern uint64_t seed; + +extern WINDOW *hw; + +extern coord delta, oldpos, stairs; + +extern PLACE places[]; + +extern THING *cur_armor, *cur_ring[], *cur_weapon, *l_last_pick, + *last_pick, *lvl_obj, *mlist, player; + +extern struct h_list helpstr[]; + +extern struct room *oldrp, passages[], rooms[]; + +extern struct stats max_stats; + +extern struct monster monsters[]; + +extern struct obj_info arm_info[], pot_info[], ring_info[], + scr_info[], things[], ws_info[], weap_info[]; + +/* + * Function types + */ +void _attach(THING **list, THING *item); +void _detach(THING **list, THING *item); +void _free_list(THING **ptr); +void addmsg(struct rogue_state *rs,char *fmt, ...); +bool add_haste(struct rogue_state *rs,bool potion); +char add_line(struct rogue_state *rs,char *fmt, char *arg); +void add_pack(struct rogue_state *rs,THING *obj, bool silent); +void add_pass(void); +void add_str(str_t *sp, int amt); +void accnt_maze(int y, int x, int ny, int nx); +void aggravate(struct rogue_state *rs); +int attack(struct rogue_state *rs,THING *mp); +void badcheck(char *name, struct obj_info *info, int bound); +void bounce(struct rogue_state *rs,THING *weap, char *mname, bool noend); +void call(struct rogue_state *rs); +void call_it(struct rogue_state *rs,struct obj_info *info); +bool cansee(struct rogue_state *rs,int y, int x); +int center(char *str); +void chg_str(int amt); +void check_level(struct rogue_state *rs); +void conn(struct rogue_state *rs,int r1, int r2); +void command(struct rogue_state *rs); +void create_obj(struct rogue_state *rs); + +void current(struct rogue_state *rs,THING *cur, char *how, char *where); +void d_level(struct rogue_state *rs); +void death(char monst); +char death_monst(void); +void dig(int y, int x); +void discard(THING *item); +void discovered(struct rogue_state *rs); +int dist(int y1, int x1, int y2, int x2); +int dist_cp(coord *c1, coord *c2); +int do_chase(struct rogue_state *rs,THING *th); +void do_daemons(struct rogue_state *rs,int flag); +void do_fuses(struct rogue_state *rs,int flag); +void do_maze(struct room *rp); +void do_motion(struct rogue_state *rs,THING *obj, int ydelta, int xdelta); +void do_move(struct rogue_state *rs,int dy, int dx); +void do_passages(struct rogue_state *rs); +void do_pot(struct rogue_state *rs,int type, bool knowit); +void do_rooms(struct rogue_state *rs); +void do_run(char ch); +void do_zap(struct rogue_state *rs); +void doadd(struct rogue_state *rs,char *fmt, va_list args); +void door(struct room *rm, coord *cp); +void door_open(struct rogue_state *rs,struct room *rp); +void drain(struct rogue_state *rs); +void draw_room(struct room *rp); +void drop(struct rogue_state *rs); +void eat(struct rogue_state *rs); +size_t encread(char *start, size_t size, FILE *inf); +size_t encwrite(char *start, size_t size, FILE *outf); +int endmsg(struct rogue_state *rs); +void enter_room(struct rogue_state *rs,coord *cp); +void erase_lamp(coord *pos, struct room *rp); +int exp_add(THING *tp); +void extinguish(void (*func)(struct rogue_state *rs,int)); +void fall(struct rogue_state *rs,THING *obj, bool pr); +void fire_bolt(struct rogue_state *rs,coord *start, coord *dir, char *name); +char floor_at(void); +void flush_type(void); +int fight(struct rogue_state *rs,coord *mp, THING *weap, bool thrown); +void fix_stick(THING *cur); +void fuse(void (*func)(struct rogue_state *rs,int), int arg, int time, int type); +bool get_dir(struct rogue_state *rs); +int gethand(struct rogue_state *rs); +void give_pack(struct rogue_state *rs,THING *tp); +void help(struct rogue_state *rs); +void hit(struct rogue_state *rs,char *er, char *ee, bool noend); +void horiz(struct room *rp, int starty); +void leave_room(struct rogue_state *rs,coord *cp); +void lengthen(void (*func)(struct rogue_state *rs,int), int xtime); +void look(struct rogue_state *rs,bool wakeup); +int hit_monster(struct rogue_state *rs,int y, int x, THING *obj); +void identify(struct rogue_state *rs); +void illcom(struct rogue_state *rs,int ch); +void init_check(void); +void init_colors(void); +void init_materials(void); +void init_names(void); +void init_player(struct rogue_state *rs); +void init_probs(void); +void init_stones(void); +void init_weapon(THING *weap, int which); +bool inventory(struct rogue_state *rs,THING *list, int type); +void invis_on(void); +void killed(struct rogue_state *rs,THING *tp, bool pr); +void kill_daemon(void (*func)(struct rogue_state *rs,int)); +bool lock_sc(void); +void miss(struct rogue_state *rs,char *er, char *ee, bool noend); +void missile(struct rogue_state *rs,int ydelta, int xdelta); +void money(struct rogue_state *rs,int value); +int move_monst(struct rogue_state *rs,THING *tp); +void move_msg(struct rogue_state *rs,THING *obj); +int msg(struct rogue_state *rs,char *fmt, ...); +void nameit(THING *obj, char *type, char *which, struct obj_info *op, char *(*prfunc)(THING *)); +void new_level(struct rogue_state *rs); +void new_monster(struct rogue_state *rs,THING *tp, char type, coord *cp); +void numpass(int y, int x); +void option(struct rogue_state *rs); +void open_score(void); +void parse_opts(char *str); +void passnum(void); +char *pick_color(char *col); +int pick_one(struct rogue_state *rs,struct obj_info *info, int nitems); +void pick_up(struct rogue_state *rs,char ch); +void picky_inven(struct rogue_state *rs); +void pr_spec(struct obj_info *info, int nitems); +void pr_list(void); +void put_bool(void *b); +void put_inv_t(void *ip); +void put_str(void *str); +void put_things(struct rogue_state *rs); +void putpass(coord *cp); +void print_disc(struct rogue_state *rs,char); +void quaff(struct rogue_state *rs); +void raise_level(struct rogue_state *rs); +char randmonster(bool wander); +void read_scroll(struct rogue_state *rs); +void relocate(struct rogue_state *rs,THING *th, coord *new_loc); +void remove_mon(struct rogue_state *rs,coord *mp, THING *tp, bool waskill); +void reset_last(void); +bool restore(struct rogue_state *rs,char *file, char **envp); +int ring_eat(int hand); +void ring_on(struct rogue_state *rs); +void ring_off(struct rogue_state *rs); +int rnd(int range); +int rnd_room(void); +int roll(int number, int sides); +int rs_save_file(FILE *savef); +int rs_restore_file(FILE *inf); +void runto(struct rogue_state *rs,coord *runner); +void rust_armor(struct rogue_state *rs,THING *arm); +int save(int which); +void save_file(FILE *savef,int32_t guiflag); +void save_game(struct rogue_state *rs); +int save_throw(int which, THING *tp); +void score(int amount, int flags, char monst); +void search(struct rogue_state *rs); +void set_know(THING *obj, struct obj_info *info); +void set_oldch(THING *tp, coord *cp); +void setup(void); +void shell(struct rogue_state *rs); +bool show_floor(void); +void show_map(void); +void show_win(struct rogue_state *rs,char *message); +int sign(int nm); +int spread(int nm); +void start_daemon(void (*func)(struct rogue_state *rs,int), int arg, int type); +void start_score(void); +void status(struct rogue_state *rs); +int step_ok(int ch); +void strucpy(char *s1, char *s2, int len); +int swing(int at_lvl, int op_arm, int wplus); +void take_off(struct rogue_state *rs); +void teleport(struct rogue_state *rs); +void total_winner(struct rogue_state *rs); +void thunk(struct rogue_state *rs,THING *weap, char *mname, bool noend); +void treas_room(struct rogue_state *rs); +void turnref(void); +void u_level(struct rogue_state *rs); +void uncurse(THING *obj); +void unlock_sc(void); +void vert(struct room *rp, int startx); +void wait_for(struct rogue_state *rs,int ch); +THING *wake_monster(struct rogue_state *rs,int y, int x); +void wanderer(struct rogue_state *rs); +void waste_time(struct rogue_state *rs); +void wear(struct rogue_state *rs); +void whatis(struct rogue_state *rs,bool insist, int type); +void wield(struct rogue_state *rs); + +bool chase(THING *tp, coord *ee); +bool diag_ok(coord *sp, coord *ep); +bool dropcheck(struct rogue_state *rs,THING *obj); +bool fallpos(coord *pos, coord *newpos); +bool find_floor(struct room *rp, coord *cp, int limit, bool monst); +bool is_magic(THING *obj); +bool is_symlink(char *sp); +bool levit_check(struct rogue_state *rs); +bool pack_room(struct rogue_state *rs,bool from_floor, THING *obj); +bool roll_em(THING *thatt, THING *thdef, THING *weap, bool hurl); +bool see_monst(THING *mp); +bool seen_stairs(void); +bool turn_ok(int y, int x); +bool turn_see(bool turn_off); +bool is_current(struct rogue_state *rs,THING *obj); +int passwd(void); + +char be_trapped(struct rogue_state *rs,coord *tc); +char floor_ch(void); +char pack_char(void); +char readchar(struct rogue_state *rs); +char rnd_thing(void); + +char *charge_str(THING *obj); +char *choose_str(char *ts, char *ns); +char *inv_name(THING *obj, bool drop); +char *nullstr(THING *ignored); +char *num(int n1, int n2, char type); +char *ring_num(THING *obj); +char *set_mname(THING *tp); +char *vowelstr(char *str); + +int get_bool(struct rogue_state *rs,void *vp, WINDOW *win); +int get_inv_t(struct rogue_state *rs,void *vp, WINDOW *win); +int get_num(struct rogue_state *rs,void *vp, WINDOW *win); +int get_sf(struct rogue_state *rs,void *vp, WINDOW *win); +int get_str(struct rogue_state *rs,void *vopt, WINDOW *win); +int trip_ch(int y, int x, int ch); + +coord *find_dest(struct rogue_state *rs,THING *tp); +coord *rndmove(THING *who); + +THING *find_obj(struct rogue_state *rs,int y, int x); +THING *get_item(struct rogue_state *rs,char *purpose, int type); +THING *leave_pack(struct rogue_state *rs,THING *obj, bool newobj, bool all); +THING *new_item(void); +THING *new_thing(struct rogue_state *rs); +void end_line(struct rogue_state *rs); + +void runners(struct rogue_state *rs,int); +void land(struct rogue_state *rs,int); +void visuals(struct rogue_state *rs,int); +void come_down(struct rogue_state *rs,int); +void stomach(struct rogue_state *rs,int); +void nohaste(struct rogue_state *rs,int); +void sight(struct rogue_state *rs,int); +void unconfuse(struct rogue_state *rs,int); +void rollwand(struct rogue_state *rs,int); +void unsee(struct rogue_state *rs,int); +void swander(struct rogue_state *rs,int); +void doctor(struct rogue_state *rs,int); + +void playit(struct rogue_state *rs); + +struct room *roomin(struct rogue_state *rs,coord *cp); + +#define MAXDAEMONS 20 + +extern struct delayed_action { + int d_type; + void (*d_func)(struct rogue_state *rs,int); + int d_arg; + int d_time; +} d_list[MAXDAEMONS]; + +typedef struct { + char *st_name; + int st_value; +} STONE; + +extern int total; +extern int between; +extern int group; +extern coord nh; +extern char *rainbow[]; +extern int cNCOLORS; +extern STONE stones[]; +extern int cNSTONES; +extern char *wood[]; +extern int cNWOOD; +extern char *metal[]; +extern int cNMETAL; diff --git a/src/cc/rogue/rogue.html b/src/cc/rogue/rogue.html new file mode 100644 index 000000000..00dab46bf --- /dev/null +++ b/src/cc/rogue/rogue.html @@ -0,0 +1,1060 @@ + + + + + + + + + + +

A Guide to the Dungeons of Doom

+ +

Michael C. Toy
+Kenneth C. R. C. Arnold

+ +

Computer Systems Research +Group
+Department of Electrical Engineering and Computer +Science
+University of California
+Berkeley, California 94720

+ + +

ABSTRACT

+ +
+
+

Rogue is a visual CRT based fantasy game which runs under the + UNIX† timesharing system. This paper describes how + to play rogue, and gives a few hints for those who might otherwise get + lost in the Dungeons of Doom.

+
+
+ +

1. Introduction

+ +

You have just finished your years as a +student at the local fighter’s guild. After much +practice and sweat you have finally completed your training +and are ready to embark upon a perilous adventure. As a test +of your skills, the local guildmasters have sent you into +the Dungeons of Doom. Your task is to return with the Amulet +of Yendor. Your reward for the completion of this task will +be a full membership in the local guild. In addition, you +are allowed to keep all the loot you bring back from the +dungeons.

+ +

In preparation for your journey, you are +given an enchanted mace, a bow, and a quiver of arrows taken +from a dragon’s hoard in the far off Dark Mountains. +You are also outfitted with elf-crafted armor and given +enough food to reach the dungeons. You say goodbye to family +and friends for what may be the last time and head up the +road.

+ +

You set out on your way to the dungeons and +after several days of uneventful travel, you see the +ancient ruins that mark the entrance to the Dungeons of +Doom. It is late at night, so you make camp at the entrance +and spend the night sleeping under the open skies. In the +morning you gather your weapons, put on your armor, eat what +is almost your last food, and enter the +dungeons.

+ +

2. What is going on here?

+

You have just begun a game of rogue. Your +goal is to grab as much treasure as you can, find the Amulet +of Yendor, and get out of the Dungeons of Doom alive. On the +screen, a map of where you have been and what you have seen +on the current dungeon level is kept. As you explore more of +the level, it appears on the screen in front of +you.

+

Rogue differs from most computer fantasy +games in that it is screen oriented. Commands are all one or +two keystrokes1 and the +results of your commands are displayed graphically on the +screen rather than being explained in words2.

+

Another major difference between rogue and other computer fantasy games is that once you have solved +all the puzzles in a standard fantasy game, it has lost most +of its excitement and it ceases to be fun. Rogue, on the +other hand, generates a new dungeon every time you play it +and even the author finds it an entertaining and exciting +game.

+ +

3. What do all those things on the screen mean?

+

In order to understand what is going on in +rogue you have to first get some grasp of what rogue is +doing with the screen. The rogue screen is intended to +replace the “You can see ...” descriptions of +standard fantasy games. Figure 1 is a sample of what a +rogue screen might look like.

+ +
+ +
+
+____________________________________________________________
+
+
+                        ------------
+                        |..........+
+                        |..@....]..|
+                        |....B.....|
+                        |..........|
+                        -----+------
+
+
+
+Level: 1  Gold: 0      Hp: 12(12)  Str: 16(16)  Arm: 4  Exp: 1/0
+
+                          Figure 1
+____________________________________________________________
+
+
+
+

3.1. The bottom line

+

At the bottom line of the screen are a few +pieces of cryptic information describing your current +status. Here is an explanation of what these things +mean:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
+

Level

+

This number indicates how deep you +have gone in the dungeon. It starts at one and goes up as +you go deeper into the dungeon.

+

Gold

+

The number of gold pieces you have managed to find and keep with you + so far.

+

Hp

+

Your current and maximum health points. +Health points indicate how much damage you can take before +you die. The more you get hit in a fight, the lower they +get. You can regain health points by resting. The number in +parentheses is the maximum number your health points can +reach.

+ +
+

Str

+ +

Your current strength and maximum ever +strength. This can be any integer less than or equal to 31, +or greater than or equal to three. The higher the num- ber, +the stronger you are. The number in the parentheses is the +maximum strength you have attained so far this +game.

+ +
+

Arm

+

Your current armor protection. This +number indicates how effective your armor is in stopping +blows from unfriendly creatures. The higher this number is, +the more effective the armor.

+ +
+

Exp

+

These two numbers give your current +experience level and experience points. As you do things, +you gain experience points. At certain experience point +totals, you gain an experience level. The more experienced +you are, the better you are able to fight and to withstand +magical attacks.

+ +
+ +

 

+ +

3.2. The top line

+

The top line of the screen is reserved for +printing messages that describe things that are impossible +to represent visually. If you see a “--More--” +on the top line, this means that rogue wants to print +another message on the screen, but it wants to make certain +that you have read the one that is there first. To read the +next message, just type a space.

+ + +

3.3. The rest of the screen

+

The rest of the screen is the map of the +level as you have explored it so far. Each symbol on the +screen repre- sents something. Here is a list of what the +various symbols mean:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

@

+

This symbol represents you, the adventurer.

+

- |

+

These symbols represent the walls of rooms.

+

+

+

A door to/from a room.

+

.

+

The floor of a room.

+

#

+

The floor of a passage between rooms.

+

*

+

A pile or pot of gold.

+

)

+

A weapon of some sort.

+

]

+

A piece of armor.

+

!

+

A flask containing a magic potion.

+

?

+

A piece of paper, usually a magic scroll.

+

=

+

A ring with magic properties

+

/

+

A magical staff or wand

+

^

+

A trap, watch out for these.

+

%

+

A staircase to other levels

+

:

+

A piece of food.

+

A-Z

+

The uppercase letters represent the various + inhabitants of the Dungeons of Doom. Watch out, they can be nasty and + vicious.

+ + +

4. Commands

+

Commands are given to rogue by typing one or two characters. +Most commands can be preceded by a count to repeat them (e.g. typing “10s” will +do ten searches). Commands for which counts make no sense have the count +ignored. To cancel a count or a prefix, type <ESCAPE> . The list of commands is +rather long, but it can be read at any time during the game +with the “?” command. Here it is for reference, +with a short explanation of each +command.

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

?

+

The help command. Asks for a character to give help + on. If you type a “*”, it will list all the commands, otherwise it will + explain what the character you typed does.

+

/

+

This is the “What is that on the screen?” command. A + “/” followed by any character that you see on the level, will tell you + what that character is. For instance, typing “/@” will tell you that the + “@” symbol represents you, the player.

+

h, H, ^H

+   +

Move left. You move one space to the left. If you use + upper case “h”, you will continue to move left until you run into + something. This works for all movement commands (e.g. “L” means run in + direction “l”) If you use the “control” “h”, you will continue moving in + the specified direction until you pass something interesting or run into + a wall. You should experiment with this, since it is a very useful + command, but very difficult to describe. This also works for all movement +commands.

+

j

+

Move down.

+

k

+

Move up.

+

l

+

Move right.

+

y

+

Move diagonally up and left.

+

u

+

Move diagonally up and right.

+

b

+

Move diagonally down and left.

+

n

+

Move diagonally down and right.

+

t

+

Throw an object. This is a prefix command. When followed with a + direction it throws an object in the specified direction. (e.g. type +“th” to throw something to the +left.)

+

f

+

Fight until someone dies. When followed with a direction this will force you to fight the creature +in that direction until either you or it bites the big +one.

+

m

+

Move onto something without picking it up. This will move you one + space in the direction you specify and, if there is an object there you + can pick up, it won’t do it.

+

z

+

Zap prefix. Point a staff or wand in a given direction and fire it. + Even non-directional staves must be pointed in some direction to be + used.

+

^

+

Identify trap command. If a trap is on your map and you can’t + remember what type it is, you can get rogue to remind you by getting + next to it and typing “^” followed by the direction that would move +you on top of it.

+

s

+

Search for traps and secret doors. Examine each space immediately + adjacent to you for the existence of a trap or secret door. There is a + large chance that even if there is something there, you won’t find it, + so you might have to search a while before you find something.

+

>

+

Climb down a staircase to the next level. Not surprisingly, this can only be done if you are +standing on staircase.

+

<

+

Climb up a staircase to the level above. This can’t be done without + the Amulet of Yendor +in your possession.

+

.

+

Rest. This is the “do nothing” command. This is good for waiting and + healing.

+

,

+

Pick up something. This picks up whatever you are currently standing on, if you are +standing on anything at all.

+

i

+

Inventory. List what you are carrying in +your pack.

+

I

+

Selective inventory. Tells you what a single item in your pack is.

+

q

+

Quaff one of the potions you are carrying.

+

r

+

Read one of the scrolls in your pack.

+

e

+

Eat food from your pack.

+

w

+

Wield a weapon. Take a weapon out of your pack and carry it for use + in combat, replacing the one you are currently using (if any).

+

W

+

Wear armor. You can only wear one suit of armor at a time. This + takes extra time.

+

T

+

Take armor off. You can’t remove armor that is cursed. This takes + extra time.

+

P

+

Put on a ring. You can wear only two rings at a time (one on each + hand). If you aren’t wearing any rings, this command will ask you which + hand you want to wear it on, otherwise, it will place it on the unused + hand. The program assumes that you wield your sword in your right hand.

+

R

+

Remove a ring. If you are only wearing one ring, this command takes + it off. If you are wearing two, it will ask you which one you wish to + remove,

+

d

+

Drop an object. Take something out of your pack and leave it lying + on the floor. Only one object can occupy each space. You cannot drop a + cursed object at all if you are wielding or wearing it.

+

c

+

Call an object something. If you have a type of object in your pack + which you wish to remember something about, you can use the call command + to give a name to that type of object. This is usually used when you + figure out what a potion, scroll, ring, or staff is after you pick it + up, or when you want to remember which of those swords in your pack you + were wielding.

+

D

+

Print out which things you’ve discovered something about. This + command will ask you what type of thing you are interested in. If you + type the character for a given type of object (e.g. +“!” for potion) it will tell you which kinds of +that type of object you’ve discovered (i.e., figured out what they + are). This command works for +potions, scrolls, rings, and staves and +wands.

+

o

+

Examine and set options. This command is further explained in the + section on options.

+

^R

+

Redraws the screen. Useful if spurious messages or transmission + errors have messed up the display.

+

^P

+

Print last message. Useful when a message disappears before you can + read it. This only repeats the last message that was not a mistyped + command so that you don’t loose anything by accidentally typing the + wrong character instead of ^P.

+

<ESCAPE>

+   + Cancel a command, prefix, or count.
+

!

+

Escape to a shell for some commands.

+

Q

+

Quit. Leave the game.

+

S

+

Save the current game in a file. It will ask you whether you wish to + use the default save file. +Caveat: Rogue won’t let you start up a copy of +a saved game, and it removes the save file as soon as you +start up a restored game. This is to prevent people from +saving a game just before a dangerous position and then +restart- ing it if they die. To restore a saved game, give +the file name as an argument to rogue. As +in

+

% rogue +save_file

+

To restart from the default save file (see below), run

+

% rogue -r

+

v

+

Prints the program version number.

+

)

+

Print the weapon you are currently wielding

+

]

+

Print the armor you are currently wearing

+

=

+

Print the rings you are currently wearing

+

@

+

Reprint the status line on the message line

+ +
+ +

5. Rooms

+

Rooms in the dungeons are either lit or +dark. If you walk into a lit room, the entire room will be +drawn on the screen as soon as you enter. If you walk into a +dark room, it will only be displayed as you explore it. Upon +leaving a room, all monsters inside the room are erased from +the screen. In the darkness you can only see one space in +all directions around you. A corridor is always +dark.

+ +

6. Fighting

+

If you see a monster and you wish to fight +it, just attempt to run into it. Many times a monster you +find will mind its own business unless you attack it. It is +often the case that discretion is the better part of +valor.

+ +

7. Objects you can find

+

When you find something in the dungeon, it +is common to want to pick the object up. This is +accomplished in rogue by walking over the object (unless you +use the “m” prefix, see above). If you are +carrying too many things, the pro- gram will tell you and it +won’t pick up the object, other- wise it will add it +to your pack and tell you what you just picked +up.

+ +

Many of the commands that operate on +objects must prompt you to find out which object you want to +use. If you change your mind and don’t want to do that +command after all, just type an +<ESCAPE> and the command will be +aborted.

+ +

Some objects, like armor and weapons, are +easily dif- ferentiated. Others, like scrolls and potions, +are given labels which vary according to type. During a +game, any two of the same kind of object with the same label +are the same type. However, the labels will vary from game +to game.

+ +

When you use one of these labeled objects, +if its effect is obvious, rogue will remember what it is for +you. If it’s effect isn’t extremely obvious you +will be asked what you want to scribble on it so you will +recognize it later, or you can use the “call” +command (see above).

+ +

7.1. Weapons

+

Some weapons, like arrows, come in bunches, +but most come one at a time. In order to use a weapon, you +must wield it. To fire an arrow out of a bow, you must first +wield the bow, then throw the arrow. You can only wield one +weapon at a time, but you can’t change weapons if the +one you are currently wielding is cursed. The commands to +use weapons are “w” (wield) and “t” +(throw).

+ +

7.2. Armor

+ +

There are various sorts of armor lying around in the dungeon. Some of it is +enchanted, some is cursed, and some is just normal. Different armor types have +different armor protection. The higher the armor protection, the more protection the armor affords against the blows of +monsters. Here is a list of the various armor types and +their normal armor protection:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeProtection
None0
Leather armor2
Studded leather / Ring mail3
Scale mail 4
Chain mail  5
Banded mail / Splint mail6
Plate mail     7
+

 

+

+If a piece of armor is enchanted, its +armor protection will be higher than normal. If a suit of +armor is cursed, its armor protection will be lower, and you +will not be able to remove it. However, not all armor with a +protection that is lower than normal is +cursed. + +

+ +

The commands to use weapons are +“W” (wear) and “T” (take +off).

+ +

+ +7.3. Scrolls

+

Scrolls come with titles in an unknown tongue3. After you read a scroll, it +disappears from your pack. The com mand to use a +scroll is “r” (read).

+ +

+ +7.4. Potions + +

+ +

Potions are labeled by the color of the +liquid inside the flask. They disappear after being quaffed. +The command to use a scroll is “q” +(quaff).

+ +

7.5. Staves and Wands

+

Staves and wands do the same kinds of +things. Staves are identified by a type of wood; wands by a +type of metal or bone. They are generally things you want to +do to some- thing over a long distance, so you must point +them at what you wish to affect to use them. Some staves are +not affected by the direction they are pointed, though. +Staves come with multiple magic charges, the number being +random, and when they are used up, the staff is just a piece +of wood or metal.

+ +

The command to use a wand or staff is +“z” (zap)

+ +

7.6. Rings

+ +

Rings are very useful items, since they are +relatively permanent magic, unlike the usually fleeting +effects of potions, scrolls, and staves. Of course, the bad +rings are also more powerful. Most rings also cause you to +use up food more rapidly, the rate varying with the type of +ring. Rings are differentiated by their stone settings. The +com- mands to use rings are “P” (put on) and +“R” (remove).

+ +

7.7. Food

+ +

Food is necessary to keep you going. If you +go too long without eating you will faint, and eventually +die of starvation. The command to use food is +“e” (eat).

+ +

8. Options

+

Due to variations in personal tastes and +conceptions of the way rogue should do things, there are a +set of options you can set that cause rogue to behave in +various different ways.

+ +

8.1 Setting the options

+ +

There are two ways to set the options. The +first is with the “o” command of rogue; the +second is with the “ROGUEOPTS” environment +variable.

+ +

8.1.1. Using the ‘o’ command

+ +

When you type “o” in rogue, it +clears the screen and displays the current settings for all +the options. It then places the cursor by the value of the +first option and waits for you to type. You can type a +<RETURN> which means to go to the next +option, a “−” which means to go to the +previous option, an <ESCAPE> which +means to return to the game, or you can give the option a +value. For boolean options this merely involves typing +“t” for true or “f” for false. For +string options, type the new value followed by a +<RETURN> .

+ +

8.1.2. Using the ROGUEOPTS variable

+ +

The ROGUEOPTS variable is a string +containing a comma separated list of initial values for the +various options. Boolean variables can be turned on by +listing their name or turned off by putting a +“no” in front of the name. Thus to set up an +environment variable so that jump is on, terse +is off, and the name is set to “Blue +Meanie”, use the command

+ +

% setenv ROGUEOPTS +"jump,noterse,name=Blue Meanie"4

+ +

8.2. Option list

+ +

Here is a list of the options and an +explanation of what each one is for. The default value for +each is enclosed in square brackets. For character string +options, input over fifty characters will be +ignored.

+ +

terse +[noterse]

+
+

+ Useful for those who are tired of the +sometimes lengthy messages of rogue. This is a useful option +for playing on slow terminals, so this option defaults to +terse if you are on a slow (1200 baud or under) +terminal.

+
+ +

jump +[nojump]

+
+

If this option is set, running moves will +not be displayed until you reach the end of the move. This +saves considerable cpu and display time. This option +defaults to jump if you are using a slow +terminal.

+
+

flush +[noflush]

+
+

All typeahead is thrown away after each round of battle. This is useful for those who type far +ahead and then watch in dismay as a Bat kills +them.

+
+

seefloor +[seefloor]

+
+

Display the floor around you on the screen +as you move through dark rooms. Due to the amount of +characters generated, this option defaults to +noseefloor if you are using a slow +terminal.

+
+

passgo +[nopassgo]

+
+

Follow turnings in passageways. If you run +in a pas- sage and you run into stone or a wall, rogue will +see if it can turn to the right or left. If it can only turn +one way, it will turn that way. If it can turn either or +neither, it will stop. This algorithm can sometimes lead to +slightly confusing occurrences which is why it defaults to +nopassgo.

+
+

tombstone +[tombstone]

+
+

Print out the tombstone at the end if you +get killed. This is nice but slow, so you can turn it off if +you like.

+
+

inven +[overwrite]

+
+

Inventory type. This can have one of three +values: overwrite, slow, or clear. With +overwrite the top lines of the map are overwritten +with the list when inventory is requested or when +“Which item do you wish to . . .? ” +questions are answered with a “*”. How- ever, if +the list is longer than a screenful, the screen is cleared. +With slow, lists are displayed one item at a time on +the top of the screen, and with clear, the screen is +cleared, the list is displayed, and then the dungeon level +is re-displayed. Due to speed considerations, clear +is the default for terminals without clear-to-end-of-line +capabilities.

+
+

name [account +name]

+
+

This is the name of your character. It is +used if you get on the top ten scorer’s +list.

+
+

fruit +[slime-mold]

+
+

This should hold the name of a fruit that +you enjoy eating. It is basically a whimsy that rogue uses +in a couple of places.

+
+

file +[~/rogue.save]

+
+

The default file name for saving the game. +If your phone is hung up by accident, rogue will +automatically save the game in this file. The file name may +start with the special character “~” which +expands to be your home directory.

+
+

9. Scoring

+ +

Rogue usually maintains a list of the top +scoring people or scores on your machine. Depending on how +it is set up, it can post either the top scores or the top +players. In the latter case, each account on the machine can +post only one non-winning score on this list. If you score +higher than someone else on this list, or better your previous score on the list, you will be inserted in the proper +place under your current name. How many scores are kept can +also be set up by whoever installs it on your +machine.

+ +

If you quit the game, you get out with all +of your gold intact. If, however, you get killed in the +Dungeons of Doom, your body is forwarded to your +next-of-kin, along with 90% of your gold; ten percent of +your gold is kept by the Dungeons’ wizard as a fee5. This should make you +consider whether you want to take one last hit at that +monster and possibly live, or quit and thus stop with +whatever you have. If you quit, you do get all your gold, +but if you swing and live, you might find +more.

+ +

If you just want to see what the current top players/games list is, you can +type

+

% rogue −s

+ +

10. Acknowledgements

+ +

Rogue was originally conceived of by Glenn +Wichman and Michael Toy. Ken Arnold and Michael Toy then +smoothed out the user interface, and added jillions of new +features. We would like to thank Bob Arnold, Michelle Busch, +Andy Hatcher, Kipp Hickman, Mark Horton, Daniel Jensen, Bill +Joy, Joe Kalash, Steve Maurer, Marty McNary, Jan Miller, and +Scott Nelson for their ideas and assistance; and also the +teeming multitudes who graciously ignored work, school, and +social life to play rogue and send us bugs, complaints, suggestions, and just plain flames. And also +Mom.

+ + + + + + + + + + + + + + + + + + + + + + + + + +
UNIX is a registered trademark of The Open Group
1As opposed to pseudo English sentences.
2A minimum screen size of 24 lines by 80 columns is required. If the + screen is larger, only the 24x80 section +will be used for the map.
3Actually, it's a dialect spoken only by the twenty-seven members of + a tribe in Outer Mongolia, but you're not supposed to know that.
4For those of you who use the Bourne shell sh (1), the commands would be

$ ROGUEOPTS="jump,noterse,name=Blue Meanie"
+$ export ROGUEOPTS

5The Dungeon's wizard is named Wally the Wonder Badger. Invocations + should be accompanied by a sizable donation.
+ + diff --git a/src/cc/rogue/rogue.html.in b/src/cc/rogue/rogue.html.in new file mode 100644 index 000000000..260cb7a4d --- /dev/null +++ b/src/cc/rogue/rogue.html.in @@ -0,0 +1,1060 @@ + + + + + + + + + + +

A Guide to the Dungeons of Doom

+ +

Michael C. Toy
+Kenneth C. R. C. Arnold

+ +

Computer Systems Research +Group
+Department of Electrical Engineering and Computer +Science
+University of California
+Berkeley, California 94720

+ + +

ABSTRACT

+ +
+
+

Rogue is a visual CRT based fantasy game which runs under the + UNIX† timesharing system. This paper describes how + to play rogue, and gives a few hints for those who might otherwise get + lost in the Dungeons of Doom.

+
+
+ +

1. Introduction

+ +

You have just finished your years as a +student at the local fighter’s guild. After much +practice and sweat you have finally completed your training +and are ready to embark upon a perilous adventure. As a test +of your skills, the local guildmasters have sent you into +the Dungeons of Doom. Your task is to return with the Amulet +of Yendor. Your reward for the completion of this task will +be a full membership in the local guild. In addition, you +are allowed to keep all the loot you bring back from the +dungeons.

+ +

In preparation for your journey, you are +given an enchanted mace, a bow, and a quiver of arrows taken +from a dragon’s hoard in the far off Dark Mountains. +You are also outfitted with elf-crafted armor and given +enough food to reach the dungeons. You say goodbye to family +and friends for what may be the last time and head up the +road.

+ +

You set out on your way to the dungeons and +after several days of uneventful travel, you see the +ancient ruins that mark the entrance to the Dungeons of +Doom. It is late at night, so you make camp at the entrance +and spend the night sleeping under the open skies. In the +morning you gather your weapons, put on your armor, eat what +is almost your last food, and enter the +dungeons.

+ +

2. What is going on here?

+

You have just begun a game of rogue. Your +goal is to grab as much treasure as you can, find the Amulet +of Yendor, and get out of the Dungeons of Doom alive. On the +screen, a map of where you have been and what you have seen +on the current dungeon level is kept. As you explore more of +the level, it appears on the screen in front of +you.

+

Rogue differs from most computer fantasy +games in that it is screen oriented. Commands are all one or +two keystrokes1 and the +results of your commands are displayed graphically on the +screen rather than being explained in words2.

+

Another major difference between rogue and other computer fantasy games is that once you have solved +all the puzzles in a standard fantasy game, it has lost most +of its excitement and it ceases to be fun. Rogue, on the +other hand, generates a new dungeon every time you play it +and even the author finds it an entertaining and exciting +game.

+ +

3. What do all those things on the screen mean?

+

In order to understand what is going on in +rogue you have to first get some grasp of what rogue is +doing with the screen. The rogue screen is intended to +replace the “You can see ...” descriptions of +standard fantasy games. Figure 1 is a sample of what a +rogue screen might look like.

+ +
+ +
+
+____________________________________________________________
+
+
+                        ------------
+                        |..........+
+                        |..@....]..|
+                        |....B.....|
+                        |..........|
+                        -----+------
+
+
+
+Level: 1  Gold: 0      Hp: 12(12)  Str: 16(16)  Arm: 4  Exp: 1/0
+
+                          Figure 1
+____________________________________________________________
+
+
+
+

3.1. The bottom line

+

At the bottom line of the screen are a few +pieces of cryptic information describing your current +status. Here is an explanation of what these things +mean:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
+

Level

+

This number indicates how deep you +have gone in the dungeon. It starts at one and goes up as +you go deeper into the dungeon.

+

Gold

+

The number of gold pieces you have managed to find and keep with you + so far.

+

Hp

+

Your current and maximum health points. +Health points indicate how much damage you can take before +you die. The more you get hit in a fight, the lower they +get. You can regain health points by resting. The number in +parentheses is the maximum number your health points can +reach.

+ +
+

Str

+ +

Your current strength and maximum ever +strength. This can be any integer less than or equal to 31, +or greater than or equal to three. The higher the num- ber, +the stronger you are. The number in the parentheses is the +maximum strength you have attained so far this +game.

+ +
+

Arm

+

Your current armor protection. This +number indicates how effective your armor is in stopping +blows from unfriendly creatures. The higher this number is, +the more effective the armor.

+ +
+

Exp

+

These two numbers give your current +experience level and experience points. As you do things, +you gain experience points. At certain experience point +totals, you gain an experience level. The more experienced +you are, the better you are able to fight and to withstand +magical attacks.

+ +
+ +

 

+ +

3.2. The top line

+

The top line of the screen is reserved for +printing messages that describe things that are impossible +to represent visually. If you see a “--More--” +on the top line, this means that rogue wants to print +another message on the screen, but it wants to make certain +that you have read the one that is there first. To read the +next message, just type a space.

+ + +

3.3. The rest of the screen

+

The rest of the screen is the map of the +level as you have explored it so far. Each symbol on the +screen repre- sents something. Here is a list of what the +various symbols mean:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

@

+

This symbol represents you, the adventurer.

+

- |

+

These symbols represent the walls of rooms.

+

+

+

A door to/from a room.

+

.

+

The floor of a room.

+

#

+

The floor of a passage between rooms.

+

*

+

A pile or pot of gold.

+

)

+

A weapon of some sort.

+

]

+

A piece of armor.

+

!

+

A flask containing a magic potion.

+

?

+

A piece of paper, usually a magic scroll.

+

=

+

A ring with magic properties

+

/

+

A magical staff or wand

+

^

+

A trap, watch out for these.

+

%

+

A staircase to other levels

+

:

+

A piece of food.

+

A-Z

+

The uppercase letters represent the various + inhabitants of the Dungeons of Doom. Watch out, they can be nasty and + vicious.

+ + +

4. Commands

+

Commands are given to rogue by typing one or two characters. +Most commands can be preceded by a count to repeat them (e.g. typing “10s” will +do ten searches). Commands for which counts make no sense have the count +ignored. To cancel a count or a prefix, type <ESCAPE> . The list of commands is +rather long, but it can be read at any time during the game +with the “?” command. Here it is for reference, +with a short explanation of each +command.

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

?

+

The help command. Asks for a character to give help + on. If you type a “*”, it will list all the commands, otherwise it will + explain what the character you typed does.

+

/

+

This is the “What is that on the screen?” command. A + “/” followed by any character that you see on the level, will tell you + what that character is. For instance, typing “/@” will tell you that the + “@” symbol represents you, the player.

+

h, H, ^H

+   +

Move left. You move one space to the left. If you use + upper case “h”, you will continue to move left until you run into + something. This works for all movement commands (e.g. “L” means run in + direction “l”) If you use the “control” “h”, you will continue moving in + the specified direction until you pass something interesting or run into + a wall. You should experiment with this, since it is a very useful + command, but very difficult to describe. This also works for all movement +commands.

+

j

+

Move down.

+

k

+

Move up.

+

l

+

Move right.

+

y

+

Move diagonally up and left.

+

u

+

Move diagonally up and right.

+

b

+

Move diagonally down and left.

+

n

+

Move diagonally down and right.

+

t

+

Throw an object. This is a prefix command. When followed with a + direction it throws an object in the specified direction. (e.g. type +“th” to throw something to the +left.)

+

f

+

Fight until someone dies. When followed with a direction this will force you to fight the creature +in that direction until either you or it bites the big +one.

+

m

+

Move onto something without picking it up. This will move you one + space in the direction you specify and, if there is an object there you + can pick up, it won’t do it.

+

z

+

Zap prefix. Point a staff or wand in a given direction and fire it. + Even non-directional staves must be pointed in some direction to be + used.

+

^

+

Identify trap command. If a trap is on your map and you can’t + remember what type it is, you can get rogue to remind you by getting + next to it and typing “^” followed by the direction that would move +you on top of it.

+

s

+

Search for traps and secret doors. Examine each space immediately + adjacent to you for the existence of a trap or secret door. There is a + large chance that even if there is something there, you won’t find it, + so you might have to search a while before you find something.

+

>

+

Climb down a staircase to the next level. Not surprisingly, this can only be done if you are +standing on staircase.

+

<

+

Climb up a staircase to the level above. This can’t be done without + the Amulet of Yendor +in your possession.

+

.

+

Rest. This is the “do nothing” command. This is good for waiting and + healing.

+

,

+

Pick up something. This picks up whatever you are currently standing on, if you are +standing on anything at all.

+

i

+

Inventory. List what you are carrying in +your pack.

+

I

+

Selective inventory. Tells you what a single item in your pack is.

+

q

+

Quaff one of the potions you are carrying.

+

r

+

Read one of the scrolls in your pack.

+

e

+

Eat food from your pack.

+

w

+

Wield a weapon. Take a weapon out of your pack and carry it for use + in combat, replacing the one you are currently using (if any).

+

W

+

Wear armor. You can only wear one suit of armor at a time. This + takes extra time.

+

T

+

Take armor off. You can’t remove armor that is cursed. This takes + extra time.

+

P

+

Put on a ring. You can wear only two rings at a time (one on each + hand). If you aren’t wearing any rings, this command will ask you which + hand you want to wear it on, otherwise, it will place it on the unused + hand. The program assumes that you wield your sword in your right hand.

+

R

+

Remove a ring. If you are only wearing one ring, this command takes + it off. If you are wearing two, it will ask you which one you wish to + remove,

+

d

+

Drop an object. Take something out of your pack and leave it lying + on the floor. Only one object can occupy each space. You cannot drop a + cursed object at all if you are wielding or wearing it.

+

c

+

Call an object something. If you have a type of object in your pack + which you wish to remember something about, you can use the call command + to give a name to that type of object. This is usually used when you + figure out what a potion, scroll, ring, or staff is after you pick it + up, or when you want to remember which of those swords in your pack you + were wielding.

+

D

+

Print out which things you’ve discovered something about. This + command will ask you what type of thing you are interested in. If you + type the character for a given type of object (e.g. +“!” for potion) it will tell you which kinds of +that type of object you’ve discovered (i.e., figured out what they + are). This command works for +potions, scrolls, rings, and staves and +wands.

+

o

+

Examine and set options. This command is further explained in the + section on options.

+

^R

+

Redraws the screen. Useful if spurious messages or transmission + errors have messed up the display.

+

^P

+

Print last message. Useful when a message disappears before you can + read it. This only repeats the last message that was not a mistyped + command so that you don’t loose anything by accidentally typing the + wrong character instead of ^P.

+

<ESCAPE>

+   + Cancel a command, prefix, or count.
+

!

+

Escape to a shell for some commands.

+

Q

+

Quit. Leave the game.

+

S

+

Save the current game in a file. It will ask you whether you wish to + use the default save file. +Caveat: Rogue won’t let you start up a copy of +a saved game, and it removes the save file as soon as you +start up a restored game. This is to prevent people from +saving a game just before a dangerous position and then +restart- ing it if they die. To restore a saved game, give +the file name as an argument to rogue. As +in

+

% rogue +save_file

+

To restart from the default save file (see below), run

+

% rogue -r

+

v

+

Prints the program version number.

+

)

+

Print the weapon you are currently wielding

+

]

+

Print the armor you are currently wearing

+

=

+

Print the rings you are currently wearing

+

@

+

Reprint the status line on the message line

+ +
+ +

5. Rooms

+

Rooms in the dungeons are either lit or +dark. If you walk into a lit room, the entire room will be +drawn on the screen as soon as you enter. If you walk into a +dark room, it will only be displayed as you explore it. Upon +leaving a room, all monsters inside the room are erased from +the screen. In the darkness you can only see one space in +all directions around you. A corridor is always +dark.

+ +

6. Fighting

+

If you see a monster and you wish to fight +it, just attempt to run into it. Many times a monster you +find will mind its own business unless you attack it. It is +often the case that discretion is the better part of +valor.

+ +

7. Objects you can find

+

When you find something in the dungeon, it +is common to want to pick the object up. This is +accomplished in rogue by walking over the object (unless you +use the “m” prefix, see above). If you are +carrying too many things, the pro- gram will tell you and it +won’t pick up the object, other- wise it will add it +to your pack and tell you what you just picked +up.

+ +

Many of the commands that operate on +objects must prompt you to find out which object you want to +use. If you change your mind and don’t want to do that +command after all, just type an +<ESCAPE> and the command will be +aborted.

+ +

Some objects, like armor and weapons, are +easily dif- ferentiated. Others, like scrolls and potions, +are given labels which vary according to type. During a +game, any two of the same kind of object with the same label +are the same type. However, the labels will vary from game +to game.

+ +

When you use one of these labeled objects, +if its effect is obvious, rogue will remember what it is for +you. If it’s effect isn’t extremely obvious you +will be asked what you want to scribble on it so you will +recognize it later, or you can use the “call” +command (see above).

+ +

7.1. Weapons

+

Some weapons, like arrows, come in bunches, +but most come one at a time. In order to use a weapon, you +must wield it. To fire an arrow out of a bow, you must first +wield the bow, then throw the arrow. You can only wield one +weapon at a time, but you can’t change weapons if the +one you are currently wielding is cursed. The commands to +use weapons are “w” (wield) and “t” +(throw).

+ +

7.2. Armor

+ +

There are various sorts of armor lying around in the dungeon. Some of it is +enchanted, some is cursed, and some is just normal. Different armor types have +different armor protection. The higher the armor protection, the more protection the armor affords against the blows of +monsters. Here is a list of the various armor types and +their normal armor protection:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeProtection
None0
Leather armor2
Studded leather / Ring mail3
Scale mail 4
Chain mail  5
Banded mail / Splint mail6
Plate mail     7
+

 

+

+If a piece of armor is enchanted, its +armor protection will be higher than normal. If a suit of +armor is cursed, its armor protection will be lower, and you +will not be able to remove it. However, not all armor with a +protection that is lower than normal is +cursed. + +

+ +

The commands to use weapons are +“W” (wear) and “T” (take +off).

+ +

+ +7.3. Scrolls

+

Scrolls come with titles in an unknown tongue3. After you read a scroll, it +disappears from your pack. The com mand to use a +scroll is “r” (read).

+ +

+ +7.4. Potions + +

+ +

Potions are labeled by the color of the +liquid inside the flask. They disappear after being quaffed. +The command to use a scroll is “q” +(quaff).

+ +

7.5. Staves and Wands

+

Staves and wands do the same kinds of +things. Staves are identified by a type of wood; wands by a +type of metal or bone. They are generally things you want to +do to some- thing over a long distance, so you must point +them at what you wish to affect to use them. Some staves are +not affected by the direction they are pointed, though. +Staves come with multiple magic charges, the number being +random, and when they are used up, the staff is just a piece +of wood or metal.

+ +

The command to use a wand or staff is +“z” (zap)

+ +

7.6. Rings

+ +

Rings are very useful items, since they are +relatively permanent magic, unlike the usually fleeting +effects of potions, scrolls, and staves. Of course, the bad +rings are also more powerful. Most rings also cause you to +use up food more rapidly, the rate varying with the type of +ring. Rings are differentiated by their stone settings. The +com- mands to use rings are “P” (put on) and +“R” (remove).

+ +

7.7. Food

+ +

Food is necessary to keep you going. If you +go too long without eating you will faint, and eventually +die of starvation. The command to use food is +“e” (eat).

+ +

8. Options

+

Due to variations in personal tastes and +conceptions of the way rogue should do things, there are a +set of options you can set that cause rogue to behave in +various different ways.

+ +

8.1 Setting the options

+ +

There are two ways to set the options. The +first is with the “o” command of rogue; the +second is with the “ROGUEOPTS” environment +variable.

+ +

8.1.1. Using the ‘o’ command

+ +

When you type “o” in rogue, it +clears the screen and displays the current settings for all +the options. It then places the cursor by the value of the +first option and waits for you to type. You can type a +<RETURN> which means to go to the next +option, a “−” which means to go to the +previous option, an <ESCAPE> which +means to return to the game, or you can give the option a +value. For boolean options this merely involves typing +“t” for true or “f” for false. For +string options, type the new value followed by a +<RETURN> .

+ +

8.1.2. Using the ROGUEOPTS variable

+ +

The ROGUEOPTS variable is a string +containing a comma separated list of initial values for the +various options. Boolean variables can be turned on by +listing their name or turned off by putting a +“no” in front of the name. Thus to set up an +environment variable so that jump is on, terse +is off, and the name is set to “Blue +Meanie”, use the command

+ +

% setenv ROGUEOPTS +"jump,noterse,name=Blue Meanie"4

+ +

8.2. Option list

+ +

Here is a list of the options and an +explanation of what each one is for. The default value for +each is enclosed in square brackets. For character string +options, input over fifty characters will be +ignored.

+ +

terse +[noterse]

+
+

+ Useful for those who are tired of the +sometimes lengthy messages of rogue. This is a useful option +for playing on slow terminals, so this option defaults to +terse if you are on a slow (1200 baud or under) +terminal.

+
+ +

jump +[nojump]

+
+

If this option is set, running moves will +not be displayed until you reach the end of the move. This +saves considerable cpu and display time. This option +defaults to jump if you are using a slow +terminal.

+
+

flush +[noflush]

+
+

All typeahead is thrown away after each round of battle. This is useful for those who type far +ahead and then watch in dismay as a Bat kills +them.

+
+

seefloor +[seefloor]

+
+

Display the floor around you on the screen +as you move through dark rooms. Due to the amount of +characters generated, this option defaults to +noseefloor if you are using a slow +terminal.

+
+

passgo +[nopassgo]

+
+

Follow turnings in passageways. If you run +in a pas- sage and you run into stone or a wall, rogue will +see if it can turn to the right or left. If it can only turn +one way, it will turn that way. If it can turn either or +neither, it will stop. This algorithm can sometimes lead to +slightly confusing occurrences which is why it defaults to +nopassgo.

+
+

tombstone +[tombstone]

+
+

Print out the tombstone at the end if you +get killed. This is nice but slow, so you can turn it off if +you like.

+
+

inven +[overwrite]

+
+

Inventory type. This can have one of three +values: overwrite, slow, or clear. With +overwrite the top lines of the map are overwritten +with the list when inventory is requested or when +“Which item do you wish to . . .? ” +questions are answered with a “*”. How- ever, if +the list is longer than a screenful, the screen is cleared. +With slow, lists are displayed one item at a time on +the top of the screen, and with clear, the screen is +cleared, the list is displayed, and then the dungeon level +is re-displayed. Due to speed considerations, clear +is the default for terminals without clear-to-end-of-line +capabilities.

+
+

name [account +name]

+
+

This is the name of your character. It is +used if you get on the top ten scorer’s +list.

+
+

fruit +[slime-mold]

+
+

This should hold the name of a fruit that +you enjoy eating. It is basically a whimsy that rogue uses +in a couple of places.

+
+

file +[~/rogue.save]

+
+

The default file name for saving the game. +If your phone is hung up by accident, rogue will +automatically save the game in this file. The file name may +start with the special character “~” which +expands to be your home directory.

+
+

9. Scoring

+ +

Rogue usually maintains a list of the top +scoring people or scores on your machine. Depending on how +it is set up, it can post either the top scores or the top +players. In the latter case, each account on the machine can +post only one non-winning score on this list. If you score +higher than someone else on this list, or better your previous score on the list, you will be inserted in the proper +place under your current name. How many scores are kept can +also be set up by whoever installs it on your +machine.

+ +

If you quit the game, you get out with all +of your gold intact. If, however, you get killed in the +Dungeons of Doom, your body is forwarded to your +next-of-kin, along with 90% of your gold; ten percent of +your gold is kept by the Dungeons’ wizard as a fee5. This should make you +consider whether you want to take one last hit at that +monster and possibly live, or quit and thus stop with +whatever you have. If you quit, you do get all your gold, +but if you swing and live, you might find +more.

+ +

If you just want to see what the current top players/games list is, you can +type

+

% @PROGRAM@ −s

+ +

10. Acknowledgements

+ +

Rogue was originally conceived of by Glenn +Wichman and Michael Toy. Ken Arnold and Michael Toy then +smoothed out the user interface, and added jillions of new +features. We would like to thank Bob Arnold, Michelle Busch, +Andy Hatcher, Kipp Hickman, Mark Horton, Daniel Jensen, Bill +Joy, Joe Kalash, Steve Maurer, Marty McNary, Jan Miller, and +Scott Nelson for their ideas and assistance; and also the +teeming multitudes who graciously ignored work, school, and +social life to play rogue and send us bugs, complaints, suggestions, and just plain flames. And also +Mom.

+ + + + + + + + + + + + + + + + + + + + + + + + + +
UNIX is a registered trademark of The Open Group
1As opposed to pseudo English sentences.
2A minimum screen size of 24 lines by 80 columns is required. If the + screen is larger, only the 24x80 section +will be used for the map.
3Actually, it's a dialect spoken only by the twenty-seven members of + a tribe in Outer Mongolia, but you're not supposed to know that.
4For those of you who use the Bourne shell sh (1), the commands would be

$ ROGUEOPTS="jump,noterse,name=Blue Meanie"
+$ export ROGUEOPTS

5The Dungeon's wizard is named Wally the Wonder Badger. Invocations + should be accompanied by a sizable donation.
+ + diff --git a/src/cc/rogue/rogue.me b/src/cc/rogue/rogue.me new file mode 100644 index 000000000..1a2568477 --- /dev/null +++ b/src/cc/rogue/rogue.me @@ -0,0 +1,892 @@ +.\" +.\" @(#)rogue.me 6.2 (Berkeley) 4/28/86 +.\" +.\" Rogue: Exploring the Dungeons of Doom +.\" Copyright (C) 1980-1983, 1985, 1986 Michael Toy, Ken Arnold and Glenn Wichman +.\" All rights reserved. +.\" +.\" See the file LICENSE.TXT for full copyright and licensing information. +.\" +.ds E \s-2\s0 +.ds R \s-2\s0 +.ds U \s-2UNIX\s0 +.ie t .ds _ \d\(mi\u +.el .ds _ _ +.de Cs +\&\\$3\*(lq\\$1\*(rq\\$2 +.. +.sp 5 +.ce 1000 +.ps +4 +.vs +4p +.b +A Guide to the Dungeons of Doom +.r +.vs +.ps +.sp 2 +.i +Michael C. Toy +Kenneth C. R. C. Arnold +.r +.sp 2 +Computer Systems Research Group +Department of Electrical Engineering and Computer Science +University of California +Berkeley, California 94720 +.sp 4 +.i ABSTRACT +.ce 0 +.(b I F +.bi Rogue +is a visual CRT based fantasy game +which runs under the \*U\(dg timesharing system. +.(f +\fR\(dg\*U is a trademark of Bell Laboratories\fP +.)f +This paper describes how to play rogue, +and gives a few hints +for those who might otherwise get lost in the Dungeons of Doom. +.)b +\".he '''\fBA Guide to the Dungeons of Doom\fP' +\" .fo ''- % -'' +.eh 'USD:33-%''A Guide to the Dungeons of Doom' +.oh 'A Guide to the Dungeons of Doom''USD:33-%' +.sh 1 Introduction +.pp +You have just finished your years as a student at the local fighter's guild. +After much practice and sweat you have finally completed your training +and are ready to embark upon a perilous adventure. +As a test of your skills, +the local guildmasters have sent you into the Dungeons of Doom. +Your task is to return with the Amulet of Yendor. +Your reward for the completion of this task +will be a full membership in the local guild. +In addition, +you are allowed to keep all the loot you bring back from the dungeons. +.pp +In preparation for your journey, +you are given an enchanted mace, +a bow, and a quiver of arrows +taken from a dragon's hoard in the far off Dark Mountains. +You are also outfitted with elf-crafted armor +and given enough food to reach the dungeons. +You say goodbye to family and friends for what may be the last time +and head up the road. +.pp +You set out on your way to the dungeons +and after several days of uneventful travel, +you see the ancient ruins +that mark the entrance to the Dungeons of Doom. +It is late at night, +so you make camp at the entrance +and spend the night sleeping under the open skies. +In the morning you gather your weapons, +put on your armor, +eat what is almost your last food, +and enter the dungeons. +.sh 1 "What is going on here?" +.pp +You have just begun a game of rogue. +Your goal is to grab as much treasure as you can, +find the Amulet of Yendor, +and get out of the Dungeons of Doom alive. +On the screen, +a map of where you have been +and what you have seen on the current dungeon level is kept. +As you explore more of the level, +it appears on the screen in front of you. +.pp +Rogue differs from most computer fantasy games in that it is screen oriented. +Commands are all one or two keystrokes\** +.(f +\** As opposed to pseudo English sentences. +.)f +and the results of your commands +are displayed graphically on the screen rather +than being explained in words.\** +.(f +\** A minimum screen size of 24 lines by 80 columns is required. +If the screen is larger, only the 24x80 section will be used +for the map. +.)f +.pp +Another major difference between rogue and other computer fantasy games +is that once you have solved all the puzzles in a standard fantasy game, +it has lost most of its excitement and it ceases to be fun. +Rogue, +on the other hand, +generates a new dungeon every time you play it +and even the author finds it an entertaining and exciting game. +.sh 1 "What do all those things on the screen mean?" +.pp +In order to understand what is going on in rogue +you have to first get some grasp of what rogue is doing with the screen. +The rogue screen is intended +to replace the \*(lqYou can see ...\*(rq descriptions +of standard fantasy games. +Figure 1 is a sample of what a rogue screen might look like. +.(z +.hl +.nf +.TS +center; +ce0 ce0 ce0 ce0 ce0 ce0 ce0 ce0 ce0 ce0 ce0 ce. +- - - - - - - - - - - - +| . . . . . . . . . . + +| . . @ . . . . ] . . | +| . . . . B . . . . . | +| . . . . . . . . . . | +- - - - - + - - - - - - +.TE + + +.ce 1000 +Level: 1 Gold: 0 Hp: 12(12) Str: 16(16) Arm: 4 Exp: 1/0 + +Figure 1 +.ce +.hl +.)z +.sh 2 "The bottom line" +.pp +At the bottom line of the screen +are a few pieces of cryptic information +describing your current status. +Here is an explanation of what these things mean: +.ip Level \w'Level\ \ 'u +This number indicates how deep you have gone in the dungeon. +It starts at one and goes up as you go deeper into the dungeon. +.ip Gold \w'Level\ \ 'u +The number of gold pieces you have managed to find +and keep with you so far. +.ip Hp \w'Level\ \ 'u +Your current and maximum health points. +Health points indicate how much damage you can take before you die. +The more you get hit in a fight, +the lower they get. +You can regain health points by resting. +The number in parentheses +is the maximum number your health points can reach. +.ip Str \w'Level\ \ 'u +Your current strength and maximum ever strength. +This can be any integer less than or equal to 31, +or greater than or equal to three. +The higher the number, +the stronger you are. +The number in the parentheses +is the maximum strength you have attained so far this game. +.ip Arm \w'Level\ \ 'u +Your current armor protection. +This number indicates how effective your armor is +in stopping blows from unfriendly creatures. +The higher this number is, +the more effective the armor. +.ip Exp \w'Level\ \ 'u +These two numbers give your current experience level +and experience points. +As you do things, +you gain experience points. +At certain experience point totals, +you gain an experience level. +The more experienced you are, +the better you are able to fight and to withstand magical attacks. +.sh 2 "The top line" +.pp +The top line of the screen is reserved +for printing messages that describe things +that are impossible to represent visually. +If you see a \*(lq--More--\*(rq on the top line, +this means that rogue wants to print another message on the screen, +but it wants to make certain +that you have read the one that is there first. +To read the next message, +just type a space. +.sh 2 "The rest of the screen" +.pp +The rest of the screen is the map of the level +as you have explored it so far. +Each symbol on the screen represents something. +Here is a list of what the various symbols mean: +.ip @ +This symbol represents you, the adventurer. +.ip "-\^|" +These symbols represent the walls of rooms. +.ip + +A door to/from a room. +.ip . +The floor of a room. +.ip # +The floor of a passage between rooms. +.ip * +A pile or pot of gold. +.ip ) +A weapon of some sort. +.ip ] +A piece of armor. +.ip ! +A flask containing a magic potion. +.ip ? +A piece of paper, usually a magic scroll. +.ip = +A ring with magic properties +.ip / +A magical staff or wand +.ip ^ +A trap, watch out for these. +.ip % +A staircase to other levels +.ip : +A piece of food. +.ip A-Z +The uppercase letters +represent the various inhabitants of the Dungeons of Doom. +Watch out, they can be nasty and vicious. +.sh 1 Commands +.pp +Commands are given to rogue by typing one or two characters. +Most commands can be preceded by a count to repeat them +(e.g. typing +.Cs 10s +will do ten searches). +Commands for which counts make no sense +have the count ignored. +To cancel a count or a prefix, +type \*E. +The list of commands is rather long, +but it can be read at any time during the game with the +.Cs ? +command. +Here it is for reference, +with a short explanation of each command. +.ip ? +The help command. +Asks for a character to give help on. +If you type a +.Cs * , +it will list all the commands, +otherwise it will explain what the character you typed does. +.ip / +This is the \*(lqWhat is that on the screen?\*(rq command. +A +.Cs / +followed by any character that you see on the level, +will tell you what that character is. +For instance, +typing +.Cs /@ +will tell you that the +.Cs @ +symbol represents you, the player. +.ip "h, H, ^H" +Move left. +You move one space to the left. +If you use upper case +.Cs h , +you will continue to move left until you run into something. +This works for all movement commands +(e.g. +.Cs L +means run in direction +.Cs l ) +If you use the \*(lqcontrol\*(rq +.Cs h , +you will continue moving in the specified direction +until you pass something interesting or run into a wall. +You should experiment with this, +since it is a very useful command, +but very difficult to describe. +This also works for all movement commands. +.ip j +Move down. +.ip k +Move up. +.ip l +Move right. +.ip y +Move diagonally up and left. +.ip u +Move diagonally up and right. +.ip b +Move diagonally down and left. +.ip n +Move diagonally down and right. +.ip t +Throw an object. +This is a prefix command. +When followed with a direction +it throws an object in the specified direction. +(e.g. type +.Cs th +to throw +something to the left.) +.ip f +Fight until someone dies. +When followed with a direction +this will force you to fight the creature in that direction +until either you or it bites the big one. +.ip m +Move onto something without picking it up. +This will move you one space in the direction you specify and, +if there is an object there you can pick up, +it won't do it. +.ip z +Zap prefix. +Point a staff or wand in a given direction +and fire it. +Even non-directional staves must be pointed in some direction +to be used. +.ip ^ +Identify trap command. +If a trap is on your map +and you can't remember what type it is, +you can get rogue to remind you +by getting next to it and typing +.Cs ^ +followed by the direction that would move you on top of it. +.ip s +Search for traps and secret doors. +Examine each space immediately adjacent to you +for the existence of a trap or secret door. +There is a large chance that even if there is something there, +you won't find it, +so you might have to search a while before you find something. +.ip > +Climb down a staircase to the next level. +Not surprisingly, this can only be done if you are standing on staircase. +.ip < +Climb up a staircase to the level above. +This can't be done without the Amulet of Yendor in your possession. +.ip "." +Rest. +This is the \*(lqdo nothing\*(rq command. +This is good for waiting and healing. +.ip , +Pick up something. +This picks up whatever you are currently standing on, +if you are standing on anything at all. +.ip i +Inventory. +List what you are carrying in your pack. +.ip I +Selective inventory. +Tells you what a single item in your pack is. +.ip q +Quaff one of the potions you are carrying. +.ip r +Read one of the scrolls in your pack. +.ip e +Eat food from your pack. +.ip w +Wield a weapon. +Take a weapon out of your pack and carry it for use in combat, +replacing the one you are currently using (if any). +.ip W +Wear armor. +You can only wear one suit of armor at a time. +This takes extra time. +.ip T +Take armor off. +You can't remove armor that is cursed. +This takes extra time. +.ip P +Put on a ring. +You can wear only two rings at a time +(one on each hand). +If you aren't wearing any rings, +this command will ask you which hand you want to wear it on, +otherwise, it will place it on the unused hand. +The program assumes that you wield your sword in your right hand. +.ip R +Remove a ring. +If you are only wearing one ring, +this command takes it off. +If you are wearing two, +it will ask you which one you wish to remove, +.ip d +Drop an object. +Take something out of your pack and leave it lying on the floor. +Only one object can occupy each space. +You cannot drop a cursed object at all +if you are wielding or wearing it. +.ip c +Call an object something. +If you have a type of object in your pack +which you wish to remember something about, +you can use the call command to give a name to that type of object. +This is usually used when you figure out what a +potion, scroll, ring, or staff is +after you pick it up, +or when you want to remember +which of those swords in your pack you were wielding. +.ip D +Print out which things you've discovered something about. +This command will ask you what type of thing you are interested in. +If you type the character for a given type of object +(\fIe.g.\fP +.Cs ! +for potion) +it will tell you which kinds of that type of object you've discovered +(\fIi.e.\fP, figured out what they are). +This command works for potions, scrolls, rings, and staves and wands. +.ip o +Examine and set options. +This command is further explained in the section on options. +.ip ^R +Redraws the screen. +Useful if spurious messages or transmission errors +have messed up the display. +.ip ^P +Print last message. +Useful when a message disappears before you can read it. +This only repeats the last message +that was not a mistyped command +so that you don't loose anything by accidentally typing +the wrong character instead of ^P. +.ip \*E +Cancel a command, prefix, or count. +.ip ! +Escape to a shell for some commands. +.ip Q +Quit. +Leave the game. +.ip S +Save the current game in a file. +It will ask you whether you wish to use the default save file. +.i Caveat : +Rogue won't let you start up a copy of a saved game, +and it removes the save file as soon as you start up a restored game. +This is to prevent people from saving a game just before a dangerous position +and then restarting it if they die. +To restore a saved game, +give the file name as an argument to rogue. +As in +.ti +1i +.nf +% rogue \fIsave\*_file\fP +.ip +To restart from the default save file (see below), +run +.ti +1i +.nf +% rogue \-r +.ip v +Prints the program version number. +.ip ) +Print the weapon you are currently wielding +.ip ] +Print the armor you are currently wearing +.ip = +Print the rings you are currently wearing +.ip @ +Reprint the status line on the message line +.sh 1 Rooms +.pp +Rooms in the dungeons are either lit or dark. +If you walk into a lit room, +the entire room will be drawn on the screen as soon as you enter. +If you walk into a dark room, +it will only be displayed as you explore it. +Upon leaving a room, +all monsters inside the room +are erased from the screen. +In the darkness you can only see one space +in all directions around you. +A corridor is always dark. +.sh 1 Fighting +.pp +If you see a monster and you wish to fight it, +just attempt to run into it. +Many times a monster you find will mind its own business +unless you attack it. +It is often the case that discretion is the better part of valor. +.sh 1 "Objects you can find" +.pp +When you find something in the dungeon, +it is common to want to pick the object up. +This is accomplished in rogue by walking over the object +(unless you use the +.Cs m +prefix, see above). +If you are carrying too many things, +the program will tell you and it won't pick up the object, +otherwise it will add it to your pack +and tell you what you just picked up. +.pp +Many of the commands that operate on objects must prompt you +to find out which object you want to use. +If you change your mind and don't want to do that command after all, +just type an \*E and the command will be aborted. +.pp +Some objects, like armor and weapons, +are easily differentiated. +Others, like scrolls and potions, +are given labels which vary according to type. +During a game, +any two of the same kind of object +with the same label +are the same type. +However, +the labels will vary from game to game. +.pp +When you use one of these labeled objects, +if its effect is obvious, +rogue will remember what it is for you. +If it's effect isn't extremely obvious +you will be asked what you want to scribble on it +so you will recognize it later, +or you can use the +.Cs call +command +(see above). +.sh 2 Weapons +.pp +Some weapons, +like arrows, +come in bunches, +but most come one at a time. +In order to use a weapon, +you must wield it. +To fire an arrow out of a bow, +you must first wield the bow, +then throw the arrow. +You can only wield one weapon at a time, +but you can't change weapons if the one +you are currently wielding is cursed. +The commands to use weapons are +.Cs w +(wield) +and +.Cs t +(throw). +.sh 2 Armor +.pp +There are various sorts of armor lying around in the dungeon. +Some of it is enchanted, +some is cursed, +and some is just normal. +Different armor types have different armor protection. +The higher the armor protection, +the more protection the armor affords against the blows of monsters. +Here is a list of the various armor types and their normal armor protection: +.(b +.TS +box center; +l r. +\ \ \fIType Protection\fP +None 0 +Leather armor 2 +Studded leather / Ring mail 3 +Scale mail 4 +Chain mail 5 +Banded mail / Splint mail 6 +Plate mail 7 +.TE +.)b +.lp +If a piece of armor is enchanted, +its armor protection will be higher than normal. +If a suit of armor is cursed, +its armor protection will be lower, +and you will not be able to remove it. +However, not all armor with a protection that is lower than normal is cursed. +.pp +The commands to use weapons are +.Cs W +(wear) +and +.Cs T +(take off). +.sh 2 Scrolls +.pp +Scrolls come with titles in an unknown tongue\**. +.(f +\** Actually, it's a dialect spoken only by the twenty-seven members +of a tribe in Outer Mongolia, +but you're not supposed to +.i know +that. +.)f +After you read a scroll, +it disappears from your pack. +The command to use a scroll is +.Cs r +(read). +.sh 2 Potions +.pp +Potions are labeled by the color of the liquid inside the flask. +They disappear after being quaffed. +The command to use a scroll is +.Cs q +(quaff). +.sh 2 "Staves and Wands" +.pp +Staves and wands do the same kinds of things. +Staves are identified by a type of wood; +wands by a type of metal or bone. +They are generally things you want to do to something +over a long distance, +so you must point them at what you wish to affect +to use them. +Some staves are not affected by the direction they are pointed, though. +Staves come with multiple magic charges, +the number being random, +and when they are used up, +the staff is just a piece of wood or metal. +.pp +The command to use a wand or staff is +.Cs z +(zap) +.sh 2 Rings +.pp +Rings are very useful items, +since they are relatively permanent magic, +unlike the usually fleeting effects of potions, scrolls, and staves. +Of course, +the bad rings are also more powerful. +Most rings also cause you to use up food more rapidly, +the rate varying with the type of ring. +Rings are differentiated by their stone settings. +The commands to use rings are +.Cs P +(put on) +and +.Cs R +(remove). +.sh 2 Food +.pp +Food is necessary to keep you going. +If you go too long without eating you will faint, +and eventually die of starvation. +The command to use food is +.Cs e +(eat). +.sh 1 Options +.pp +Due to variations in personal tastes +and conceptions of the way rogue should do things, +there are a set of options you can set +that cause rogue to behave in various different ways. +.sh 2 "Setting the options" +.pp +There are two ways to set the options. +The first is with the +.Cs o +command of rogue; +the second is with the +.Cs ROGUEOPTS +environment variable\**. +.(f +\** On Version 6 systems, +there is no equivalent of the ROGUEOPTS feature. +.br +.)f +.br +.sh 3 "Using the `o' command" +.pp +When you type +.Cs o +in rogue, +it clears the screen +and displays the current settings for all the options. +It then places the cursor by the value of the first option +and waits for you to type. +You can type a \*R +which means to go to the next option, +a +.Cs \- +which means to go to the previous option, +an \*E +which means to return to the game, +or you can give the option a value. +For boolean options this merely involves typing +.Cs t +for true or +.Cs f +for false. +For string options, +type the new value followed by a \*R. +.sh 3 "Using the ROGUEOPTS variable" +.pp +The ROGUEOPTS variable is a string +containing a comma separated list of initial values +for the various options. +Boolean variables can be turned on by listing their name +or turned off by putting a +.Cs no +in front of the name. +Thus to set up an environment variable so that +.b jump +is on, +.b terse +is off, +and the +.b name +is set to \*(lqBlue Meanie\*(rq, +use the command +.nf +.ti +3n +% setenv ROGUEOPTS "jump,noterse,name=Blue Meanie"\** +.fi +.(f +\** +For those of you who use the Bourne shell sh (1), the commands would be +.in +3 +.nf +$ ROGUEOPTS="jump,noterse,name=Blue Meanie" +$ export ROGUEOPTS +.fi +.in +0 +.)f +.sh 2 "Option list" +.pp +Here is a list of the options +and an explanation of what each one is for. +The default value for each is enclosed in square brackets. +For character string options, +input over fifty characters will be ignored. +.ip "\fBterse\fP [\fI\^noterse\^\fP]" +Useful for those who are tired of the sometimes lengthy messages of rogue. +This is a useful option for playing on slow terminals, +so this option defaults to +.i terse +if you +are on a slow (1200 baud or under) terminal. +.ip "\fBjump\fP [\fI\^nojump\^\fP]" +If this option is set, +running moves will not be displayed +until you reach the end of the move. +This saves considerable cpu and display time. +This option defaults to +.i jump +if you are using a slow terminal. +.ip "\fBflush\fP [\fI\^noflush\^\fP]" +All typeahead is thrown away after each round of battle. +This is useful for those who type far ahead +and then watch in dismay as a Bat kills them. +.ip "\fBseefloor\fP [\fI\^seefloor\^\fP]" +Display the floor around you on the screen +as you move through dark rooms. +Due to the amount of characters generated, +this option defaults to +.i noseefloor +if you are using a slow terminal. +.ip "\fBpassgo\fP [\fI\^nopassgo\^\fP]" +Follow turnings in passageways. +If you run in a passage +and you run into stone or a wall, +rogue will see if it can turn to the right or left. +If it can only turn one way, +it will turn that way. +If it can turn either or neither, +it will stop. +This algorithm can sometimes lead to slightly confusing occurrences +which is why it defaults to \fInopassgo\fP. +.ip "\fBtombstone\fP [\fI\^tombstone\^\fP]" +Print out the tombstone at the end if you get killed. +This is nice but slow, so you can turn it off if you like. +.ip "\fBinven\fP [\fI\^overwrite\^\fP]" +Inventory type. +This can have one of three values: +.i overwrite , +.i slow , +or +.i clear . +With +.i overwrite +the top lines of the map are overwritten +with the list +when inventory is requested +or when +\*(lqWhich item do you wish to \fB. . .\fP? \*(rq questions +are answered with a +.Cs * . +However, if the list is longer than a screenful, +the screen is cleared. +With +.i slow , +lists are displayed one item at a time on the top of the screen, +and with +.i clear , +the screen is cleared, +the list is displayed, +and then the dungeon level is re-displayed. +Due to speed considerations, +.i clear +is the default for terminals without +clear-to-end-of-line capabilities. +.ip "\fBname\fP [account name]" +This is the name of your character. +It is used if you get on the top ten scorer's list. +.ip "\fBfruit\fP [\fI\^slime-mold\^\fP]" +This should hold the name of a fruit that you enjoy eating. +It is basically a whimsey that rogue uses in a couple of places. +.ip "\fBfile\fP [\fI\^~/rogue.save\^\fP]" +The default file name for saving the game. +If your phone is hung up by accident, +rogue will automatically save the game in this file. +The file name may start with the special character +.Cs ~ +which expands to be your home directory. +.sh 1 Scoring +.pp +Rogue usually maintains a list +of the top scoring people or scores on your machine. +Depending on how it is set up, +it can post either the top scores +or the top players. +In the latter case, +each account on the machine +can post only one non-winning score on this list. +If you score higher than someone else on this list, +or better your previous score on the list, +you will be inserted in the proper place +under your current name. +How many scores are kept +can also be set up by whoever installs it on your machine. +.pp +If you quit the game, you get out with all of your gold intact. +If, however, you get killed in the Dungeons of Doom, +your body is forwarded to your next-of-kin, +along with 90% of your gold; +ten percent of your gold is kept by the Dungeons' wizard as a fee\**. +.(f +\** The Dungeon's wizard is named Wally the Wonder Badger. +Invocations should be accompanied by a sizable donation. +.)f +This should make you consider whether you want to take one last hit +at that monster and possibly live, +or quit and thus stop with whatever you have. +If you quit, you do get all your gold, +but if you swing and live, you might find more. +.pp +If you just want to see what the current top players/games list is, +you can type +.ti +1i +.nf +% rogue \-s +.br +.sh 1 Acknowledgements +.pp +Rogue was originally conceived of by Glenn Wichman and Michael Toy. +Ken Arnold and Michael Toy then smoothed out the user interface, +and added jillions of new features. +We would like to thank +Bob Arnold, +Michelle Busch, +Andy Hatcher, +Kipp Hickman, +Mark Horton, +Daniel Jensen, +Bill Joy, +Joe Kalash, +Steve Maurer, +Marty McNary, +Jan Miller, +and +Scott Nelson +for their ideas and assistance; +and also the teeming multitudes +who graciously ignored work, school, and social life to play rogue +and send us bugs, complaints, suggestions, and just plain flames. +And also Mom. diff --git a/src/cc/rogue/rogue.me.in b/src/cc/rogue/rogue.me.in new file mode 100644 index 000000000..a73d1504e --- /dev/null +++ b/src/cc/rogue/rogue.me.in @@ -0,0 +1,892 @@ +.\" +.\" @(#)rogue.me 6.2 (Berkeley) 4/28/86 +.\" +.\" Rogue: Exploring the Dungeons of Doom +.\" Copyright (C) 1980-1983, 1985, 1986 Michael Toy, Ken Arnold and Glenn Wichman +.\" All rights reserved. +.\" +.\" See the file LICENSE.TXT for full copyright and licensing information. +.\" +.ds E \s-2\s0 +.ds R \s-2\s0 +.ds U \s-2UNIX\s0 +.ie t .ds _ \d\(mi\u +.el .ds _ _ +.de Cs +\&\\$3\*(lq\\$1\*(rq\\$2 +.. +.sp 5 +.ce 1000 +.ps +4 +.vs +4p +.b +A Guide to the Dungeons of Doom +.r +.vs +.ps +.sp 2 +.i +Michael C. Toy +Kenneth C. R. C. Arnold +.r +.sp 2 +Computer Systems Research Group +Department of Electrical Engineering and Computer Science +University of California +Berkeley, California 94720 +.sp 4 +.i ABSTRACT +.ce 0 +.(b I F +.bi Rogue +is a visual CRT based fantasy game +which runs under the \*U\(dg timesharing system. +.(f +\fR\(dg\*U is a trademark of Bell Laboratories\fP +.)f +This paper describes how to play rogue, +and gives a few hints +for those who might otherwise get lost in the Dungeons of Doom. +.)b +\".he '''\fBA Guide to the Dungeons of Doom\fP' +\" .fo ''- % -'' +.eh 'USD:33-%''A Guide to the Dungeons of Doom' +.oh 'A Guide to the Dungeons of Doom''USD:33-%' +.sh 1 Introduction +.pp +You have just finished your years as a student at the local fighter's guild. +After much practice and sweat you have finally completed your training +and are ready to embark upon a perilous adventure. +As a test of your skills, +the local guildmasters have sent you into the Dungeons of Doom. +Your task is to return with the Amulet of Yendor. +Your reward for the completion of this task +will be a full membership in the local guild. +In addition, +you are allowed to keep all the loot you bring back from the dungeons. +.pp +In preparation for your journey, +you are given an enchanted mace, +a bow, and a quiver of arrows +taken from a dragon's hoard in the far off Dark Mountains. +You are also outfitted with elf-crafted armor +and given enough food to reach the dungeons. +You say goodbye to family and friends for what may be the last time +and head up the road. +.pp +You set out on your way to the dungeons +and after several days of uneventful travel, +you see the ancient ruins +that mark the entrance to the Dungeons of Doom. +It is late at night, +so you make camp at the entrance +and spend the night sleeping under the open skies. +In the morning you gather your weapons, +put on your armor, +eat what is almost your last food, +and enter the dungeons. +.sh 1 "What is going on here?" +.pp +You have just begun a game of rogue. +Your goal is to grab as much treasure as you can, +find the Amulet of Yendor, +and get out of the Dungeons of Doom alive. +On the screen, +a map of where you have been +and what you have seen on the current dungeon level is kept. +As you explore more of the level, +it appears on the screen in front of you. +.pp +Rogue differs from most computer fantasy games in that it is screen oriented. +Commands are all one or two keystrokes\** +.(f +\** As opposed to pseudo English sentences. +.)f +and the results of your commands +are displayed graphically on the screen rather +than being explained in words.\** +.(f +\** A minimum screen size of 24 lines by 80 columns is required. +If the screen is larger, only the 24x80 section will be used +for the map. +.)f +.pp +Another major difference between rogue and other computer fantasy games +is that once you have solved all the puzzles in a standard fantasy game, +it has lost most of its excitement and it ceases to be fun. +Rogue, +on the other hand, +generates a new dungeon every time you play it +and even the author finds it an entertaining and exciting game. +.sh 1 "What do all those things on the screen mean?" +.pp +In order to understand what is going on in rogue +you have to first get some grasp of what rogue is doing with the screen. +The rogue screen is intended +to replace the \*(lqYou can see ...\*(rq descriptions +of standard fantasy games. +Figure 1 is a sample of what a rogue screen might look like. +.(z +.hl +.nf +.TS +center; +ce0 ce0 ce0 ce0 ce0 ce0 ce0 ce0 ce0 ce0 ce0 ce. +- - - - - - - - - - - - +| . . . . . . . . . . + +| . . @ . . . . ] . . | +| . . . . B . . . . . | +| . . . . . . . . . . | +- - - - - + - - - - - - +.TE + + +.ce 1000 +Level: 1 Gold: 0 Hp: 12(12) Str: 16(16) Arm: 4 Exp: 1/0 + +Figure 1 +.ce +.hl +.)z +.sh 2 "The bottom line" +.pp +At the bottom line of the screen +are a few pieces of cryptic information +describing your current status. +Here is an explanation of what these things mean: +.ip Level \w'Level\ \ 'u +This number indicates how deep you have gone in the dungeon. +It starts at one and goes up as you go deeper into the dungeon. +.ip Gold \w'Level\ \ 'u +The number of gold pieces you have managed to find +and keep with you so far. +.ip Hp \w'Level\ \ 'u +Your current and maximum health points. +Health points indicate how much damage you can take before you die. +The more you get hit in a fight, +the lower they get. +You can regain health points by resting. +The number in parentheses +is the maximum number your health points can reach. +.ip Str \w'Level\ \ 'u +Your current strength and maximum ever strength. +This can be any integer less than or equal to 31, +or greater than or equal to three. +The higher the number, +the stronger you are. +The number in the parentheses +is the maximum strength you have attained so far this game. +.ip Arm \w'Level\ \ 'u +Your current armor protection. +This number indicates how effective your armor is +in stopping blows from unfriendly creatures. +The higher this number is, +the more effective the armor. +.ip Exp \w'Level\ \ 'u +These two numbers give your current experience level +and experience points. +As you do things, +you gain experience points. +At certain experience point totals, +you gain an experience level. +The more experienced you are, +the better you are able to fight and to withstand magical attacks. +.sh 2 "The top line" +.pp +The top line of the screen is reserved +for printing messages that describe things +that are impossible to represent visually. +If you see a \*(lq--More--\*(rq on the top line, +this means that rogue wants to print another message on the screen, +but it wants to make certain +that you have read the one that is there first. +To read the next message, +just type a space. +.sh 2 "The rest of the screen" +.pp +The rest of the screen is the map of the level +as you have explored it so far. +Each symbol on the screen represents something. +Here is a list of what the various symbols mean: +.ip @ +This symbol represents you, the adventurer. +.ip "-\^|" +These symbols represent the walls of rooms. +.ip + +A door to/from a room. +.ip . +The floor of a room. +.ip # +The floor of a passage between rooms. +.ip * +A pile or pot of gold. +.ip ) +A weapon of some sort. +.ip ] +A piece of armor. +.ip ! +A flask containing a magic potion. +.ip ? +A piece of paper, usually a magic scroll. +.ip = +A ring with magic properties +.ip / +A magical staff or wand +.ip ^ +A trap, watch out for these. +.ip % +A staircase to other levels +.ip : +A piece of food. +.ip A-Z +The uppercase letters +represent the various inhabitants of the Dungeons of Doom. +Watch out, they can be nasty and vicious. +.sh 1 Commands +.pp +Commands are given to rogue by typing one or two characters. +Most commands can be preceded by a count to repeat them +(e.g. typing +.Cs 10s +will do ten searches). +Commands for which counts make no sense +have the count ignored. +To cancel a count or a prefix, +type \*E. +The list of commands is rather long, +but it can be read at any time during the game with the +.Cs ? +command. +Here it is for reference, +with a short explanation of each command. +.ip ? +The help command. +Asks for a character to give help on. +If you type a +.Cs * , +it will list all the commands, +otherwise it will explain what the character you typed does. +.ip / +This is the \*(lqWhat is that on the screen?\*(rq command. +A +.Cs / +followed by any character that you see on the level, +will tell you what that character is. +For instance, +typing +.Cs /@ +will tell you that the +.Cs @ +symbol represents you, the player. +.ip "h, H, ^H" +Move left. +You move one space to the left. +If you use upper case +.Cs h , +you will continue to move left until you run into something. +This works for all movement commands +(e.g. +.Cs L +means run in direction +.Cs l ) +If you use the \*(lqcontrol\*(rq +.Cs h , +you will continue moving in the specified direction +until you pass something interesting or run into a wall. +You should experiment with this, +since it is a very useful command, +but very difficult to describe. +This also works for all movement commands. +.ip j +Move down. +.ip k +Move up. +.ip l +Move right. +.ip y +Move diagonally up and left. +.ip u +Move diagonally up and right. +.ip b +Move diagonally down and left. +.ip n +Move diagonally down and right. +.ip t +Throw an object. +This is a prefix command. +When followed with a direction +it throws an object in the specified direction. +(e.g. type +.Cs th +to throw +something to the left.) +.ip f +Fight until someone dies. +When followed with a direction +this will force you to fight the creature in that direction +until either you or it bites the big one. +.ip m +Move onto something without picking it up. +This will move you one space in the direction you specify and, +if there is an object there you can pick up, +it won't do it. +.ip z +Zap prefix. +Point a staff or wand in a given direction +and fire it. +Even non-directional staves must be pointed in some direction +to be used. +.ip ^ +Identify trap command. +If a trap is on your map +and you can't remember what type it is, +you can get rogue to remind you +by getting next to it and typing +.Cs ^ +followed by the direction that would move you on top of it. +.ip s +Search for traps and secret doors. +Examine each space immediately adjacent to you +for the existence of a trap or secret door. +There is a large chance that even if there is something there, +you won't find it, +so you might have to search a while before you find something. +.ip > +Climb down a staircase to the next level. +Not surprisingly, this can only be done if you are standing on staircase. +.ip < +Climb up a staircase to the level above. +This can't be done without the Amulet of Yendor in your possession. +.ip "." +Rest. +This is the \*(lqdo nothing\*(rq command. +This is good for waiting and healing. +.ip , +Pick up something. +This picks up whatever you are currently standing on, +if you are standing on anything at all. +.ip i +Inventory. +List what you are carrying in your pack. +.ip I +Selective inventory. +Tells you what a single item in your pack is. +.ip q +Quaff one of the potions you are carrying. +.ip r +Read one of the scrolls in your pack. +.ip e +Eat food from your pack. +.ip w +Wield a weapon. +Take a weapon out of your pack and carry it for use in combat, +replacing the one you are currently using (if any). +.ip W +Wear armor. +You can only wear one suit of armor at a time. +This takes extra time. +.ip T +Take armor off. +You can't remove armor that is cursed. +This takes extra time. +.ip P +Put on a ring. +You can wear only two rings at a time +(one on each hand). +If you aren't wearing any rings, +this command will ask you which hand you want to wear it on, +otherwise, it will place it on the unused hand. +The program assumes that you wield your sword in your right hand. +.ip R +Remove a ring. +If you are only wearing one ring, +this command takes it off. +If you are wearing two, +it will ask you which one you wish to remove, +.ip d +Drop an object. +Take something out of your pack and leave it lying on the floor. +Only one object can occupy each space. +You cannot drop a cursed object at all +if you are wielding or wearing it. +.ip c +Call an object something. +If you have a type of object in your pack +which you wish to remember something about, +you can use the call command to give a name to that type of object. +This is usually used when you figure out what a +potion, scroll, ring, or staff is +after you pick it up, +or when you want to remember +which of those swords in your pack you were wielding. +.ip D +Print out which things you've discovered something about. +This command will ask you what type of thing you are interested in. +If you type the character for a given type of object +(\fIe.g.\fP +.Cs ! +for potion) +it will tell you which kinds of that type of object you've discovered +(\fIi.e.\fP, figured out what they are). +This command works for potions, scrolls, rings, and staves and wands. +.ip o +Examine and set options. +This command is further explained in the section on options. +.ip ^R +Redraws the screen. +Useful if spurious messages or transmission errors +have messed up the display. +.ip ^P +Print last message. +Useful when a message disappears before you can read it. +This only repeats the last message +that was not a mistyped command +so that you don't loose anything by accidentally typing +the wrong character instead of ^P. +.ip \*E +Cancel a command, prefix, or count. +.ip ! +Escape to a shell for some commands. +.ip Q +Quit. +Leave the game. +.ip S +Save the current game in a file. +It will ask you whether you wish to use the default save file. +.i Caveat : +Rogue won't let you start up a copy of a saved game, +and it removes the save file as soon as you start up a restored game. +This is to prevent people from saving a game just before a dangerous position +and then restarting it if they die. +To restore a saved game, +give the file name as an argument to rogue. +As in +.ti +1i +.nf +% rogue \fIsave\*_file\fP +.ip +To restart from the default save file (see below), +run +.ti +1i +.nf +% rogue \-r +.ip v +Prints the program version number. +.ip ) +Print the weapon you are currently wielding +.ip ] +Print the armor you are currently wearing +.ip = +Print the rings you are currently wearing +.ip @ +Reprint the status line on the message line +.sh 1 Rooms +.pp +Rooms in the dungeons are either lit or dark. +If you walk into a lit room, +the entire room will be drawn on the screen as soon as you enter. +If you walk into a dark room, +it will only be displayed as you explore it. +Upon leaving a room, +all monsters inside the room +are erased from the screen. +In the darkness you can only see one space +in all directions around you. +A corridor is always dark. +.sh 1 Fighting +.pp +If you see a monster and you wish to fight it, +just attempt to run into it. +Many times a monster you find will mind its own business +unless you attack it. +It is often the case that discretion is the better part of valor. +.sh 1 "Objects you can find" +.pp +When you find something in the dungeon, +it is common to want to pick the object up. +This is accomplished in rogue by walking over the object +(unless you use the +.Cs m +prefix, see above). +If you are carrying too many things, +the program will tell you and it won't pick up the object, +otherwise it will add it to your pack +and tell you what you just picked up. +.pp +Many of the commands that operate on objects must prompt you +to find out which object you want to use. +If you change your mind and don't want to do that command after all, +just type an \*E and the command will be aborted. +.pp +Some objects, like armor and weapons, +are easily differentiated. +Others, like scrolls and potions, +are given labels which vary according to type. +During a game, +any two of the same kind of object +with the same label +are the same type. +However, +the labels will vary from game to game. +.pp +When you use one of these labeled objects, +if its effect is obvious, +rogue will remember what it is for you. +If it's effect isn't extremely obvious +you will be asked what you want to scribble on it +so you will recognize it later, +or you can use the +.Cs call +command +(see above). +.sh 2 Weapons +.pp +Some weapons, +like arrows, +come in bunches, +but most come one at a time. +In order to use a weapon, +you must wield it. +To fire an arrow out of a bow, +you must first wield the bow, +then throw the arrow. +You can only wield one weapon at a time, +but you can't change weapons if the one +you are currently wielding is cursed. +The commands to use weapons are +.Cs w +(wield) +and +.Cs t +(throw). +.sh 2 Armor +.pp +There are various sorts of armor lying around in the dungeon. +Some of it is enchanted, +some is cursed, +and some is just normal. +Different armor types have different armor protection. +The higher the armor protection, +the more protection the armor affords against the blows of monsters. +Here is a list of the various armor types and their normal armor protection: +.(b +.TS +box center; +l r. +\ \ \fIType Protection\fP +None 0 +Leather armor 2 +Studded leather / Ring mail 3 +Scale mail 4 +Chain mail 5 +Banded mail / Splint mail 6 +Plate mail 7 +.TE +.)b +.lp +If a piece of armor is enchanted, +its armor protection will be higher than normal. +If a suit of armor is cursed, +its armor protection will be lower, +and you will not be able to remove it. +However, not all armor with a protection that is lower than normal is cursed. +.pp +The commands to use weapons are +.Cs W +(wear) +and +.Cs T +(take off). +.sh 2 Scrolls +.pp +Scrolls come with titles in an unknown tongue\**. +.(f +\** Actually, it's a dialect spoken only by the twenty-seven members +of a tribe in Outer Mongolia, +but you're not supposed to +.i know +that. +.)f +After you read a scroll, +it disappears from your pack. +The command to use a scroll is +.Cs r +(read). +.sh 2 Potions +.pp +Potions are labeled by the color of the liquid inside the flask. +They disappear after being quaffed. +The command to use a scroll is +.Cs q +(quaff). +.sh 2 "Staves and Wands" +.pp +Staves and wands do the same kinds of things. +Staves are identified by a type of wood; +wands by a type of metal or bone. +They are generally things you want to do to something +over a long distance, +so you must point them at what you wish to affect +to use them. +Some staves are not affected by the direction they are pointed, though. +Staves come with multiple magic charges, +the number being random, +and when they are used up, +the staff is just a piece of wood or metal. +.pp +The command to use a wand or staff is +.Cs z +(zap) +.sh 2 Rings +.pp +Rings are very useful items, +since they are relatively permanent magic, +unlike the usually fleeting effects of potions, scrolls, and staves. +Of course, +the bad rings are also more powerful. +Most rings also cause you to use up food more rapidly, +the rate varying with the type of ring. +Rings are differentiated by their stone settings. +The commands to use rings are +.Cs P +(put on) +and +.Cs R +(remove). +.sh 2 Food +.pp +Food is necessary to keep you going. +If you go too long without eating you will faint, +and eventually die of starvation. +The command to use food is +.Cs e +(eat). +.sh 1 Options +.pp +Due to variations in personal tastes +and conceptions of the way rogue should do things, +there are a set of options you can set +that cause rogue to behave in various different ways. +.sh 2 "Setting the options" +.pp +There are two ways to set the options. +The first is with the +.Cs o +command of rogue; +the second is with the +.Cs ROGUEOPTS +environment variable\**. +.(f +\** On Version 6 systems, +there is no equivalent of the ROGUEOPTS feature. +.br +.)f +.br +.sh 3 "Using the `o' command" +.pp +When you type +.Cs o +in rogue, +it clears the screen +and displays the current settings for all the options. +It then places the cursor by the value of the first option +and waits for you to type. +You can type a \*R +which means to go to the next option, +a +.Cs \- +which means to go to the previous option, +an \*E +which means to return to the game, +or you can give the option a value. +For boolean options this merely involves typing +.Cs t +for true or +.Cs f +for false. +For string options, +type the new value followed by a \*R. +.sh 3 "Using the ROGUEOPTS variable" +.pp +The ROGUEOPTS variable is a string +containing a comma separated list of initial values +for the various options. +Boolean variables can be turned on by listing their name +or turned off by putting a +.Cs no +in front of the name. +Thus to set up an environment variable so that +.b jump +is on, +.b terse +is off, +and the +.b name +is set to \*(lqBlue Meanie\*(rq, +use the command +.nf +.ti +3n +% setenv ROGUEOPTS "jump,noterse,name=Blue Meanie"\** +.fi +.(f +\** +For those of you who use the Bourne shell sh (1), the commands would be +.in +3 +.nf +$ ROGUEOPTS="jump,noterse,name=Blue Meanie" +$ export ROGUEOPTS +.fi +.in +0 +.)f +.sh 2 "Option list" +.pp +Here is a list of the options +and an explanation of what each one is for. +The default value for each is enclosed in square brackets. +For character string options, +input over fifty characters will be ignored. +.ip "\fBterse\fP [\fI\^noterse\^\fP]" +Useful for those who are tired of the sometimes lengthy messages of rogue. +This is a useful option for playing on slow terminals, +so this option defaults to +.i terse +if you +are on a slow (1200 baud or under) terminal. +.ip "\fBjump\fP [\fI\^nojump\^\fP]" +If this option is set, +running moves will not be displayed +until you reach the end of the move. +This saves considerable cpu and display time. +This option defaults to +.i jump +if you are using a slow terminal. +.ip "\fBflush\fP [\fI\^noflush\^\fP]" +All typeahead is thrown away after each round of battle. +This is useful for those who type far ahead +and then watch in dismay as a Bat kills them. +.ip "\fBseefloor\fP [\fI\^seefloor\^\fP]" +Display the floor around you on the screen +as you move through dark rooms. +Due to the amount of characters generated, +this option defaults to +.i noseefloor +if you are using a slow terminal. +.ip "\fBpassgo\fP [\fI\^nopassgo\^\fP]" +Follow turnings in passageways. +If you run in a passage +and you run into stone or a wall, +rogue will see if it can turn to the right or left. +If it can only turn one way, +it will turn that way. +If it can turn either or neither, +it will stop. +This algorithm can sometimes lead to slightly confusing occurrences +which is why it defaults to \fInopassgo\fP. +.ip "\fBtombstone\fP [\fI\^tombstone\^\fP]" +Print out the tombstone at the end if you get killed. +This is nice but slow, so you can turn it off if you like. +.ip "\fBinven\fP [\fI\^overwrite\^\fP]" +Inventory type. +This can have one of three values: +.i overwrite , +.i slow , +or +.i clear . +With +.i overwrite +the top lines of the map are overwritten +with the list +when inventory is requested +or when +\*(lqWhich item do you wish to \fB. . .\fP? \*(rq questions +are answered with a +.Cs * . +However, if the list is longer than a screenful, +the screen is cleared. +With +.i slow , +lists are displayed one item at a time on the top of the screen, +and with +.i clear , +the screen is cleared, +the list is displayed, +and then the dungeon level is re-displayed. +Due to speed considerations, +.i clear +is the default for terminals without +clear-to-end-of-line capabilities. +.ip "\fBname\fP [account name]" +This is the name of your character. +It is used if you get on the top ten scorer's list. +.ip "\fBfruit\fP [\fI\^slime-mold\^\fP]" +This should hold the name of a fruit that you enjoy eating. +It is basically a whimsey that rogue uses in a couple of places. +.ip "\fBfile\fP [\fI\^~/rogue.save\^\fP]" +The default file name for saving the game. +If your phone is hung up by accident, +rogue will automatically save the game in this file. +The file name may start with the special character +.Cs ~ +which expands to be your home directory. +.sh 1 Scoring +.pp +Rogue usually maintains a list +of the top scoring people or scores on your machine. +Depending on how it is set up, +it can post either the top scores +or the top players. +In the latter case, +each account on the machine +can post only one non-winning score on this list. +If you score higher than someone else on this list, +or better your previous score on the list, +you will be inserted in the proper place +under your current name. +How many scores are kept +can also be set up by whoever installs it on your machine. +.pp +If you quit the game, you get out with all of your gold intact. +If, however, you get killed in the Dungeons of Doom, +your body is forwarded to your next-of-kin, +along with 90% of your gold; +ten percent of your gold is kept by the Dungeons' wizard as a fee\**. +.(f +\** The Dungeon's wizard is named Wally the Wonder Badger. +Invocations should be accompanied by a sizable donation. +.)f +This should make you consider whether you want to take one last hit +at that monster and possibly live, +or quit and thus stop with whatever you have. +If you quit, you do get all your gold, +but if you swing and live, you might find more. +.pp +If you just want to see what the current top players/games list is, +you can type +.ti +1i +.nf +% @PROGRAM@ \-s +.br +.sh 1 Acknowledgements +.pp +Rogue was originally conceived of by Glenn Wichman and Michael Toy. +Ken Arnold and Michael Toy then smoothed out the user interface, +and added jillions of new features. +We would like to thank +Bob Arnold, +Michelle Busch, +Andy Hatcher, +Kipp Hickman, +Mark Horton, +Daniel Jensen, +Bill Joy, +Joe Kalash, +Steve Maurer, +Marty McNary, +Jan Miller, +and +Scott Nelson +for their ideas and assistance; +and also the teeming multitudes +who graciously ignored work, school, and social life to play rogue +and send us bugs, complaints, suggestions, and just plain flames. +And also Mom. diff --git a/src/cc/rogue/rogue.png b/src/cc/rogue/rogue.png new file mode 100644 index 0000000000000000000000000000000000000000..fc3779e83223dbb46ec33f8c1d936e6db202eb86 GIT binary patch literal 1005 zcmVWFU8GbZ8({Xk{QrNlj4iWF>9@00U7;L_t(o!`0VYjGa>y z2k_rGt+py1)hR8ZqY@&nbx+ZVh>{5LU|uwR5FrvTgb00*z7V8O8YD#GiMU4*f+q=? zc6dPyQW`bN(90M#opOek^~uW4cg}n>m56_`bJqU$UVE>-?uY*vJ+t6B0_Wgj^kYe! zGlm~9h#~CxHwB%CtMMd$#b48mNj#4mLf}KfaoB{>1{arOAD+O9*_hxkoR8o;2)+xi ze-US5b(m;v>{*Vt(s|oDoc9kl6l%M%##vY6i(+3JA7V%3gs~71u1))X!}Z;w;;XcI zYt5c(;?>iI;Qn+`557!mo4dt)e%0N@`uv*6*c@7$D!vcnti=0NVb)pFP- zU}IW;rx4&}EJ*8jq_v-NvdQRA^sX2cPQZ0(J`}I2@O^RCUKW^L9AurSdR#S1RO;Yqmn3f?mkJ%X=`^iyj0E25;|p60{&q*ESPlVWwe2)iw5 z?b~?O`yI02XSf;nM{AbT_4;mgpce-c!=|)$YZRSMsduVDdVZ}iWi4JUTB_x#v_4*Q z(PR{%%ke@7LB``TeNAfk`f!wr`N0$oOYv}+U^1GPyHW@qAKlP!M8jUZf}4sQ(-lkc zMiO8Qch)#;Q!Ky*cr40tBV18b#oggl^Jj2z3+Lk5&{$Ok8~+!%r)VtOkzfX*%r1^_ z>xth!oD!YTy^(C%g)g*mWz)92H&p*X@qHp1lAY0X{1HB~DBAKB!CRg^il?K0*fkRy zuB&N6nvMgZwT+>%S)qkf!@GAhym(L8ejQHC<@ZqkoVKE>t-@)M8|Fl190_L|j8c5i b{{epk<~&Tog&~z@00000NkvXXu0mjfa>>^0 literal 0 HcmV?d00001 diff --git a/src/cc/rogue/rogue.spec b/src/cc/rogue/rogue.spec new file mode 100644 index 000000000..6c8770fdc --- /dev/null +++ b/src/cc/rogue/rogue.spec @@ -0,0 +1,107 @@ +Name: rogue +Version: 5.4.4 +Release: 1%{?dist} +Summary: The original graphical adventure game + +Group: Amusements/Games +License: BSD +URL: http://rogue.rogueforge.net/ +Source0: http://rogue.rogueforge.net/files/rogue5.4/rogue5.4.4-src.tar.gz +Source1: rogue.desktop +Source2: rogue.png +BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n) + +BuildRequires: desktop-file-utils +BuildRequires: ncurses-devel + +%description +The one, the only, the original graphical adventure game that spawned +an entire genre. + +%prep +%setup -q -n %{name}%{version} + + +%build +%configure --enable-setgid=games --enable-scorefile=%{_var}/games/roguelike/rogue54.scr --enable-lockfile=%{_var}/games/roguelike/rogue54.lck +make %{_smp_mflags} + + +%install +rm -rf $RPM_BUILD_ROOT + +make install DESTDIR=$RPM_BUILD_ROOT + +desktop-file-install --vendor fedora \ + --dir ${RPM_BUILD_ROOT}%{_datadir}/applications \ + %{SOURCE1} +mkdir -p $RPM_BUILD_ROOT/%{_datadir}/icons/hicolor/32x32/apps/ +install -p -m 644 %{SOURCE2} $RPM_BUILD_ROOT/%{_datadir}/icons/hicolor/32x32/apps/ + + +%clean +rm -rf $RPM_BUILD_ROOT + +%post +touch --no-create %{_datadir}/icons/hicolor || : +if [ -x %{_bindir}/gtk-update-icon-cache ]; then + %{_bindir}/gtk-update-icon-cache --quiet %{_datadir}/icons/hicolor || : +fi + +%postun +touch --no-create %{_datadir}/icons/hicolor || : +if [ -x %{_bindir}/gtk-update-icon-cache ]; then + %{_bindir}/gtk-update-icon-cache --quiet %{_datadir}/icons/hicolor || : +fi + + +%files +%defattr(-,root,root,-) +%attr(2755,games,games) %{_bindir}/rogue +%{_mandir}/man6/rogue.6.gz +%{_datadir}/applications/fedora-%{name}.desktop +%{_datadir}/icons/hicolor/32x32/apps/rogue.png +%dir %attr(0775,games,games) %{_var}/games/roguelike +%config(noreplace) %attr(0664,games,games) %{_var}/games/roguelike/rogue54.scr +%doc %{_docdir}/%{name}-%{version} + + +%changelog +* Sun Sep 2 2007 Wart 5.4.4-1 +- Update to 5.4.4 + +* Mon Aug 20 2007 Wart 5.4.3-1 +- Update to 5.4.3 + +* Sun Jul 15 2007 Wart 5.4.2-9 +- New upstream home page and download URL +- Add patch when reading long values from the save file on 64-bit arch + (BZ #248283) +- Add patch removing many compiler warnings +- Use proper version in the .desktop file + +* Sat Mar 3 2007 Wart 5.4.2-8 +- Use better sourceforge download url +- Use more precise desktop file categories + +* Mon Aug 28 2006 Wart 5.4.2-7 +- Rebuild for Fedora Extras + +* Tue May 16 2006 Wart 5.4.2-6 +- Added empty initial scoreboard file. + +* Mon May 15 2006 Wart 5.4.2-5 +- Better setuid/setgid handling (again) (BZ #187392) + +* Thu Mar 30 2006 Wart 5.4.2-4 +- Better setuid/setgid handling (BZ #187392) +- Resize desktop icon to match directory name + +* Mon Mar 13 2006 Wart 5.4.2-3 +- Added icon for .desktop file. + +* Sun Mar 12 2006 Wart 5.4.2-2 +- Added missing BR: ncurses-devel, desktop-file-utils + +* Sat Feb 25 2006 Wart 5.4.2-1 +- Initial spec file. diff --git a/src/cc/rogue/rogue54.sln b/src/cc/rogue/rogue54.sln new file mode 100644 index 000000000..da1c58f07 --- /dev/null +++ b/src/cc/rogue/rogue54.sln @@ -0,0 +1,19 @@ +Microsoft Visual Studio Solution File, Format Version 9.00 +# Visual C++ Express 2005 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "rogue54", "rogue54.vcproj", "{9EA0D326-8097-4ADA-82EA-4DB1F5CAA8F6}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9EA0D326-8097-4ADA-82EA-4DB1F5CAA8F6}.Debug|Win32.ActiveCfg = Debug|Win32 + {9EA0D326-8097-4ADA-82EA-4DB1F5CAA8F6}.Debug|Win32.Build.0 = Debug|Win32 + {9EA0D326-8097-4ADA-82EA-4DB1F5CAA8F6}.Release|Win32.ActiveCfg = Release|Win32 + {9EA0D326-8097-4ADA-82EA-4DB1F5CAA8F6}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/src/cc/rogue/rogue54.vcproj b/src/cc/rogue/rogue54.vcproj new file mode 100644 index 000000000..7e39b98dd --- /dev/null +++ b/src/cc/rogue/rogue54.vcproj @@ -0,0 +1,396 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/cc/rogue/rooms.c b/src/cc/rogue/rooms.c new file mode 100644 index 000000000..1dcf3019a --- /dev/null +++ b/src/cc/rogue/rooms.c @@ -0,0 +1,472 @@ +/* + * Create the layout for the new level + * + * @(#)rooms.c 4.45 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include "rogue.h" + +typedef struct spot { /* position matrix for maze positions */ + int nexits; + coord exits[4]; + int used; +} SPOT; + +#define GOLDGRP 1 + +/* + * do_rooms: + * Create rooms and corridors with a connectivity graph + */ + +void +do_rooms(struct rogue_state *rs) +{ + int i; + struct room *rp; + THING *tp; + int left_out; + static coord top; + coord bsze; /* maximum room size */ + coord mp; + + bsze.x = NUMCOLS / 3; + bsze.y = NUMLINES / 3; + /* + * Clear things for a new level + */ + for (rp = rooms; rp < &rooms[MAXROOMS]; rp++) + { + rp->r_goldval = 0; + rp->r_nexits = 0; + rp->r_flags = 0; + } + /* + * Put the gone rooms, if any, on the level + */ + left_out = rnd(4); + for (i = 0; i < left_out; i++) + rooms[rnd_room()].r_flags |= ISGONE; + /* + * dig and populate all the rooms on the level + */ + for (i = 0, rp = rooms; i < MAXROOMS; rp++, i++) + { + /* + * Find upper left corner of box that this room goes in + */ + top.x = (i % 3) * bsze.x + 1; + top.y = (i / 3) * bsze.y; + if (rp->r_flags & ISGONE) + { + /* + * Place a gone room. Make certain that there is a blank line + * for passage drawing. + */ + do + { + rp->r_pos.x = top.x + rnd(bsze.x - 2) + 1; + rp->r_pos.y = top.y + rnd(bsze.y - 2) + 1; + rp->r_max.x = -NUMCOLS; + rp->r_max.y = -NUMLINES; + } until (rp->r_pos.y > 0 && rp->r_pos.y < NUMLINES-1); + continue; + } + /* + * set room type + */ + if (rnd(10) < level - 1) + { + rp->r_flags |= ISDARK; /* dark room */ + if (rnd(15) == 0) + rp->r_flags = ISMAZE; /* maze room */ + } + /* + * Find a place and size for a random room + */ + if (rp->r_flags & ISMAZE) + { + rp->r_max.x = bsze.x - 1; + rp->r_max.y = bsze.y - 1; + if ((rp->r_pos.x = top.x) == 1) + rp->r_pos.x = 0; + if ((rp->r_pos.y = top.y) == 0) + { + rp->r_pos.y++; + rp->r_max.y--; + } + } + else + do + { + rp->r_max.x = rnd(bsze.x - 4) + 4; + rp->r_max.y = rnd(bsze.y - 4) + 4; + rp->r_pos.x = top.x + rnd(bsze.x - rp->r_max.x); + rp->r_pos.y = top.y + rnd(bsze.y - rp->r_max.y); + } until (rp->r_pos.y != 0); + draw_room(rp); + /* + * Put the gold in + */ + if (rnd(2) == 0 && (!amulet || level >= max_level)) + { + THING *gold; + + gold = new_item(); + gold->o_goldval = rp->r_goldval = GOLDCALC; + find_floor(rp, &rp->r_gold, FALSE, FALSE); + gold->o_pos = rp->r_gold; + chat(rp->r_gold.y, rp->r_gold.x) = GOLD; + gold->o_flags = ISMANY; + gold->o_group = GOLDGRP; + gold->o_type = GOLD; + attach(lvl_obj, gold); + } + /* + * Put the monster in + */ + if (rnd(100) < (rp->r_goldval > 0 ? 80 : 25)) + { + tp = new_item(); + find_floor(rp, &mp, FALSE, TRUE); + new_monster(rs,tp, randmonster(FALSE), &mp); + give_pack(rs,tp); + } + } +} + +/* + * draw_room: + * Draw a box around a room and lay down the floor for normal + * rooms; for maze rooms, draw maze. + */ + +void +draw_room(struct room *rp) +{ + int y, x; + + if (rp->r_flags & ISMAZE) + do_maze(rp); + else + { + vert(rp, rp->r_pos.x); /* Draw left side */ + vert(rp, rp->r_pos.x + rp->r_max.x - 1); /* Draw right side */ + horiz(rp, rp->r_pos.y); /* Draw top */ + horiz(rp, rp->r_pos.y + rp->r_max.y - 1); /* Draw bottom */ + + /* + * Put the floor down + */ + for (y = rp->r_pos.y + 1; y < rp->r_pos.y + rp->r_max.y - 1; y++) + for (x = rp->r_pos.x + 1; x < rp->r_pos.x + rp->r_max.x - 1; x++) + chat(y, x) = FLOOR; + } +} + +/* + * vert: + * Draw a vertical line + */ + +void +vert(struct room *rp, int startx) +{ + int y; + + for (y = rp->r_pos.y + 1; y <= rp->r_max.y + rp->r_pos.y - 1; y++) + chat(y, startx) = '|'; +} + +/* + * horiz: + * Draw a horizontal line + */ + +void +horiz(struct room *rp, int starty) +{ + int x; + + for (x = rp->r_pos.x; x <= rp->r_pos.x + rp->r_max.x - 1; x++) + chat(starty, x) = '-'; +} + +/* + * do_maze: + * Dig a maze + */ + +static int Maxy, Maxx, Starty, Startx; + +static SPOT maze[NUMLINES/3+1][NUMCOLS/3+1]; + + +void +do_maze(struct room *rp) +{ + SPOT *sp; + int starty, startx; + static coord pos; + + for (sp = &maze[0][0]; sp <= &maze[NUMLINES / 3][NUMCOLS / 3]; sp++) + { + sp->used = FALSE; + sp->nexits = 0; + } + + Maxy = rp->r_max.y; + Maxx = rp->r_max.x; + Starty = rp->r_pos.y; + Startx = rp->r_pos.x; + starty = (rnd(rp->r_max.y) / 2) * 2; + startx = (rnd(rp->r_max.x) / 2) * 2; + pos.y = starty + Starty; + pos.x = startx + Startx; + putpass(&pos); + dig(starty, startx); +} + +/* + * dig: + * Dig out from around where we are now, if possible + */ + +void +dig(int y, int x) +{ + coord *cp; + int cnt, newy, newx, nexty = 0, nextx = 0; + static coord pos; + static coord del[4] = { + {2, 0}, {-2, 0}, {0, 2}, {0, -2} + }; + + for (;;) + { + cnt = 0; + for (cp = del; cp <= &del[3]; cp++) + { + newy = y + cp->y; + newx = x + cp->x; + if (newy < 0 || newy > Maxy || newx < 0 || newx > Maxx) + continue; + if (flat(newy + Starty, newx + Startx) & F_PASS) + continue; + if (rnd(++cnt) == 0) + { + nexty = newy; + nextx = newx; + } + } + if (cnt == 0) + return; + accnt_maze(y, x, nexty, nextx); + accnt_maze(nexty, nextx, y, x); + if (nexty == y) + { + pos.y = y + Starty; + if (nextx - x < 0) + pos.x = nextx + Startx + 1; + else + pos.x = nextx + Startx - 1; + } + else + { + pos.x = x + Startx; + if (nexty - y < 0) + pos.y = nexty + Starty + 1; + else + pos.y = nexty + Starty - 1; + } + putpass(&pos); + pos.y = nexty + Starty; + pos.x = nextx + Startx; + putpass(&pos); + dig(nexty, nextx); + } +} + +/* + * accnt_maze: + * Account for maze exits + */ + +void +accnt_maze(int y, int x, int ny, int nx) +{ + SPOT *sp; + coord *cp; + + sp = &maze[y][x]; + for (cp = sp->exits; cp < &sp->exits[sp->nexits]; cp++) + if (cp->y == ny && cp->x == nx) + return; + cp->y = ny; + cp->x = nx; +} + +/* + * rnd_pos: + * Pick a random spot in a room + */ + +void +rnd_pos(struct room *rp, coord *cp) +{ + cp->x = rp->r_pos.x + rnd(rp->r_max.x - 2) + 1; + cp->y = rp->r_pos.y + rnd(rp->r_max.y - 2) + 1; +} + +/* + * find_floor: + * Find a valid floor spot in this room. If rp is NULL, then + * pick a new room each time around the loop. + */ +bool +find_floor(struct room *rp, coord *cp, int limit, bool monst) +{ + PLACE *pp; + int cnt; + char compchar = 0; + bool pickroom; + + pickroom = (bool)(rp == NULL); + + if (!pickroom) + compchar = ((rp->r_flags & ISMAZE) ? PASSAGE : FLOOR); + cnt = limit; + for (;;) + { + if (limit && cnt-- == 0) + return FALSE; + if (pickroom) + { + rp = &rooms[rnd_room()]; + compchar = ((rp->r_flags & ISMAZE) ? PASSAGE : FLOOR); + } + rnd_pos(rp, cp); + pp = INDEX(cp->y, cp->x); + if (monst) + { + if (pp->p_monst == NULL && step_ok(pp->p_ch)) + return TRUE; + } + else if (pp->p_ch == compchar) + return TRUE; + } +} + +/* + * enter_room: + * Code that is executed whenver you appear in a room + */ + +void +enter_room(struct rogue_state *rs,coord *cp) +{ + struct room *rp; + THING *tp; + int y, x; + char ch; + + rp = proom = roomin(rs,cp); + door_open(rs,rp); + if (!(rp->r_flags & ISDARK) && !on(player, ISBLIND)) + for (y = rp->r_pos.y; y < rp->r_max.y + rp->r_pos.y; y++) + { + move(y, rp->r_pos.x); + for (x = rp->r_pos.x; x < rp->r_max.x + rp->r_pos.x; x++) + { + tp = moat(y, x); + ch = chat(y, x); + if (tp == NULL) + if (CCHAR(inch()) != ch) + addch(ch); + else + move(y, x + 1); + else + { + tp->t_oldch = ch; + if (!see_monst(tp)) + if (on(player, SEEMONST)) + { + standout(); + addch(tp->t_disguise); + standend(); + } + else + addch(ch); + else + addch(tp->t_disguise); + } + } + } +} + +/* + * leave_room: + * Code for when we exit a room + */ + +void +leave_room(struct rogue_state *rs,coord *cp) +{ + PLACE *pp; + struct room *rp; + int y, x; + char floor; + char ch; + + rp = proom; + + if (rp->r_flags & ISMAZE) + return; + + if (rp->r_flags & ISGONE) + floor = PASSAGE; + else if (!(rp->r_flags & ISDARK) || on(player, ISBLIND)) + floor = FLOOR; + else + floor = ' '; + + proom = &passages[flat(cp->y, cp->x) & F_PNUM]; + for (y = rp->r_pos.y; y < rp->r_max.y + rp->r_pos.y; y++) + for (x = rp->r_pos.x; x < rp->r_max.x + rp->r_pos.x; x++) + { + move(y, x); + switch ( ch = CCHAR(inch()) ) + { + case FLOOR: + if (floor == ' ' && ch != ' ') + addch(' '); + break; + default: + /* + * to check for monster, we have to strip out + * standout bit + */ + if (isupper(toascii(ch))) + { + if (on(player, SEEMONST)) + { + standout(); + addch(ch); + standend(); + break; + } + pp = INDEX(y,x); + addch(pp->p_ch == DOOR ? DOOR : floor); + } + } + } + door_open(rs,rp); +} diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c new file mode 100644 index 000000000..e12d14ea9 --- /dev/null +++ b/src/cc/rogue/save.c @@ -0,0 +1,400 @@ +/* + * save and restore routines + * + * @(#)save.c 4.33 (Berkeley) 06/01/83 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "rogue.h" +#include "score.h" + +typedef struct stat STAT; + +extern char version[], encstr[]; + +static STAT sbuf; + +/* + * save_game: + * Implement the "save game" command + */ + +void +save_game(struct rogue_state *rs) +{ + FILE *savef; + int c; + auto char buf[MAXSTR]; + + /* + * get file name + */ + mpos = 0; +over: + if (file_name[0] != '\0') + { + for (;;) + { + msg(rs,"save file (%s)? ", file_name); + c = readchar(rs); + mpos = 0; + if (c == ESCAPE) + { + msg(rs,""); + return; + } + else if (c == 'n' || c == 'N' || c == 'y' || c == 'Y') + break; + else + msg(rs,"please answer Y or N"); + } + if (c == 'y' || c == 'Y') + { + addstr("Yes\n"); + refresh(); + strcpy(buf, file_name); + goto gotfile; + } + } + + do + { + mpos = 0; + msg(rs,"file name: "); + buf[0] = '\0'; + if (get_str(rs,buf, stdscr) == QUIT) + { +quit_it: + msg(rs,""); + return; + } + mpos = 0; +gotfile: + /* + * test to see if the file exists + */ + if (stat(buf, &sbuf) >= 0) + { + for (;;) + { + msg(rs,"File exists. Do you wish to overwrite it?"); + mpos = 0; + if ((c = readchar(rs)) == ESCAPE) + goto quit_it; + if (c == 'y' || c == 'Y') + break; + else if (c == 'n' || c == 'N') + goto over; + else + msg(rs,"Please answer Y or N"); + } + msg(rs,"file name: %s", buf); + md_unlink(file_name); + } + strcpy(file_name, buf); + if ((savef = fopen(file_name, "w")) == NULL) + msg(rs,strerror(errno)); + } while (savef == NULL); + + save_file(savef,1); + /* NOTREACHED */ +} + +/* + * auto_save: + * Automatically save a file. This is used if a HUP signal is + * recieved + */ + +void +auto_save(int sig) +{ + FILE *savef; + NOOP(sig); + + md_ignoreallsignals(); + if (file_name[0] != '\0' && ((savef = fopen(file_name, "w")) != NULL || + (md_unlink_open_file(file_name, savef) >= 0 && (savef = fopen(file_name, "w")) != NULL))) + save_file(savef,1); + exit(0); +} + +/* + * save_file: + * Write the saved game on the file + */ + +void +save_file(FILE *savef,int32_t guiflag) +{ + char buf[80]; + mvcur(0, COLS - 1, LINES - 1, 0); + putchar('\n'); + endwin(); + resetltchars(); + md_chmod(file_name, 0400); + if ( guiflag != 0 ) + { + encwrite(version, strlen(version)+1, savef); + sprintf(buf,"%d x %d\n", LINES, COLS); + encwrite(buf,80,savef); + } + rs_save_file(savef); + fflush(savef); + fclose(savef); + if ( guiflag != 0 ) + exit(0); +} + +/* + * restore: + * Restore a saved game from a file with elaborate checks for file + * integrity from cheaters + */ +bool +restore(struct rogue_state *rs,char *file, char **envp) +{ + FILE *inf; + int syml; + extern char **environ; + auto char buf[MAXSTR]; + auto STAT sbuf2; + int lines, cols; + + if (strcmp(file, "-r") == 0) + file = file_name; + + md_tstphold(); + + if ((inf = fopen(file,"r")) == NULL) + { + perror(file); + return FALSE; + } + stat(file, &sbuf2); + syml = is_symlink(file); + + fflush(stdout); + encread(buf, (unsigned) strlen(version) + 1, inf); + if (strcmp(buf, version) != 0) + { + printf("Sorry, saved game is out of date.\n"); + return FALSE; + } + encread(buf,80,inf); + sscanf(buf,"%d x %d\n", &lines, &cols); + + initscr(); /* Start up cursor package */ + keypad(stdscr, 1); + + if (lines > LINES) + { + endwin(); + printf("Sorry, original game was played on a screen with %d lines.\n",lines); + printf("Current screen only has %d lines. Unable to restore game\n",LINES); + return(FALSE); + } + if (cols > COLS) + { + endwin(); + printf("Sorry, original game was played on a screen with %d columns.\n",cols); + printf("Current screen only has %d columns. Unable to restore game\n",COLS); + return(FALSE); + } + + hw = newwin(LINES, COLS, 0, 0); + setup(); + + rs_restore_file(inf); + /* + * we do not close the file so that we will have a hold of the + * inode for as long as possible + */ + + if ( +#ifdef MASTER + !wizard && +#endif + md_unlink_open_file(file, inf) < 0) + { + printf("Cannot unlink file\n"); + return FALSE; + } + mpos = 0; +/* printw(0, 0, "%s: %s", file, ctime(&sbuf2.st_mtime)); */ +/* + printw("%s: %s", file, ctime(&sbuf2.st_mtime)); +*/ + clearok(stdscr,TRUE); + /* + * defeat multiple restarting from the same place + */ +#ifdef MASTER + if (!wizard) +#endif + if (sbuf2.st_nlink != 1 || syml) + { + endwin(); + printf("\nCannot restore from a linked file\n"); + return FALSE; + } + + if (pstats.s_hpt <= 0) + { + endwin(); + printf("\n\"He's dead, Jim\"\n"); + return FALSE; + } + + md_tstpresume(); + + environ = envp; + strcpy(file_name, file); + clearok(curscr, TRUE); + srand((int32_t)rs->seed);//md_getpid()); + msg(rs,"file name: %s", file); + playit(rs); + /*NOTREACHED*/ + return(0); +} + +/* + * encwrite: + * Perform an encrypted write + */ +#define CRYPT_ENABLE 0 + +size_t +encwrite(char *start, size_t size, FILE *outf) +{ + char *e1, *e2, fb; + int temp; + extern char statlist[]; + size_t o_size = size; + e1 = encstr; + e2 = statlist; + fb = 0; + + while(size) + { + if ( CRYPT_ENABLE ) + { + if (putc(*start++ ^ *e1 ^ *e2 ^ fb, outf) == EOF) + break; + + temp = *e1++; + fb = fb + ((char) (temp * *e2++)); + if (*e1 == '\0') + e1 = encstr; + if (*e2 == '\0') + e2 = statlist; + } + else if ( putc(*start++,outf) == EOF ) + break; + size--; + } + + return(o_size - size); +} + +/* + * encread: + * Perform an encrypted read + */ +size_t +encread(char *start, size_t size, FILE *inf) +{ + char *e1, *e2, fb; + int temp; + size_t read_size; + extern char statlist[]; + + fb = 0; + + if ((read_size = fread(start,1,size,inf)) == 0 || read_size == -1) + return(read_size); + if ( CRYPT_ENABLE ) + { + e1 = encstr; + e2 = statlist; + while (size--) + { + *start++ ^= *e1 ^ *e2 ^ fb; + temp = *e1++; + fb = fb + (char)(temp * *e2++); + if (*e1 == '\0') + e1 = encstr; + if (*e2 == '\0') + e2 = statlist; + } + } + return(read_size); +} + +static char scoreline[100]; +/* + * read_scrore + * Read in the score file + */ +void +rd_score(SCORE *top_ten) +{ + unsigned int i; + + if (scoreboard == NULL) + return; + + rewind(scoreboard); + + for(i = 0; i < numscores; i++) + { + encread(top_ten[i].sc_name, MAXSTR, scoreboard); + encread(scoreline, 100, scoreboard); + sscanf(scoreline, " %u %d %u %hu %d %x \n", + &top_ten[i].sc_uid, &top_ten[i].sc_score, + &top_ten[i].sc_flags, &top_ten[i].sc_monster, + &top_ten[i].sc_level, &top_ten[i].sc_time); + } + + rewind(scoreboard); +} + +/* + * write_scrore + * Read in the score file + */ +void +wr_score(SCORE *top_ten) +{ + unsigned int i; + + if (scoreboard == NULL) + return; + + rewind(scoreboard); + + for(i = 0; i < numscores; i++) + { + memset(scoreline,0,100); + encwrite(top_ten[i].sc_name, MAXSTR, scoreboard); + sprintf(scoreline, " %u %d %u %hu %d %x \n", + top_ten[i].sc_uid, top_ten[i].sc_score, + top_ten[i].sc_flags, top_ten[i].sc_monster, + top_ten[i].sc_level, top_ten[i].sc_time); + encwrite(scoreline,100,scoreboard); + } + + rewind(scoreboard); +} diff --git a/src/cc/rogue/score.h b/src/cc/rogue/score.h new file mode 100644 index 000000000..fb51bf8bc --- /dev/null +++ b/src/cc/rogue/score.h @@ -0,0 +1,26 @@ +/* + * Score file structure + * + * @(#)score.h 4.6 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +struct sc_ent { + unsigned int sc_uid; + int sc_score; + unsigned int sc_flags; + unsigned short sc_monster; + char sc_name[MAXSTR]; + int sc_level; + unsigned int sc_time; +}; + +typedef struct sc_ent SCORE; + +void rd_score(SCORE *top_ten); +void wr_score(SCORE *top_ten); diff --git a/src/cc/rogue/scrolls.c b/src/cc/rogue/scrolls.c new file mode 100644 index 000000000..b6854ab07 --- /dev/null +++ b/src/cc/rogue/scrolls.c @@ -0,0 +1,329 @@ +/* + * Read a scroll and let it happen + * + * @(#)scrolls.c 4.44 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include "rogue.h" + +/* + * read_scroll: + * Read a scroll from the pack and do the appropriate thing + */ + +void +read_scroll(struct rogue_state *rs) +{ + THING *obj; + PLACE *pp; + int y, x; + char ch; + int i; + bool discardit = FALSE; + struct room *cur_room; + THING *orig_obj; + static coord mp; + + obj = get_item(rs,"read", SCROLL); + if (obj == NULL) + return; + if (obj->o_type != SCROLL) + { + if (!terse) + msg(rs,"there is nothing on it to read"); + else + msg(rs,"nothing to read"); + return; + } + /* + * Calculate the effect it has on the poor guy. + */ + if (obj == cur_weapon) + cur_weapon = NULL; + /* + * Get rid of the thing + */ + discardit = (bool)(obj->o_count == 1); + leave_pack(rs,obj, FALSE, FALSE); + orig_obj = obj; + + switch (obj->o_which) + { + case S_CONFUSE: + /* + * Scroll of monster confusion. Give him that power. + */ + player.t_flags |= CANHUH; + msg(rs,"your hands begin to glow %s", pick_color("red")); + when S_ARMOR: + if (cur_armor != NULL) + { + cur_armor->o_arm--; + cur_armor->o_flags &= ~ISCURSED; + msg(rs,"your armor glows %s for a moment", pick_color("silver")); + } + when S_HOLD: + /* + * Hold monster scroll. Stop all monsters within two spaces + * from chasing after the hero. + */ + + ch = 0; + for (x = hero.x - 2; x <= hero.x + 2; x++) + if (x >= 0 && x < NUMCOLS) + for (y = hero.y - 2; y <= hero.y + 2; y++) + if (y >= 0 && y <= NUMLINES - 1) + if ((obj = moat(y, x)) != NULL && on(*obj, ISRUN)) + { + obj->t_flags &= ~ISRUN; + obj->t_flags |= ISHELD; + ch++; + } + if (ch) + { + addmsg(rs,"the monster"); + if (ch > 1) + addmsg(rs,"s around you"); + addmsg(rs," freeze"); + if (ch == 1) + addmsg(rs,"s"); + endmsg(rs); + scr_info[S_HOLD].oi_know = TRUE; + } + else + msg(rs,"you feel a strange sense of loss"); + when S_SLEEP: + /* + * Scroll which makes you fall asleep + */ + scr_info[S_SLEEP].oi_know = TRUE; + no_command += rnd(SLEEPTIME) + 4; + player.t_flags &= ~ISRUN; + msg(rs,"you fall asleep"); + when S_CREATE: + /* + * Create a monster: + * First look in a circle around him, next try his room + * otherwise give up + */ + i = 0; + for (y = hero.y - 1; y <= hero.y + 1; y++) + for (x = hero.x - 1; x <= hero.x + 1; x++) + /* + * Don't put a monster in top of the player. + */ + if (y == hero.y && x == hero.x) + continue; + /* + * Or anything else nasty + */ + else if (step_ok(ch = winat(y, x))) + { + if (ch == SCROLL + && find_obj(rs,y, x)->o_which == S_SCARE) + continue; + else if (rnd(++i) == 0) + { + mp.y = y; + mp.x = x; + } + } + if (i == 0) + msg(rs,"you hear a faint cry of anguish in the distance"); + else + { + obj = new_item(); + new_monster(rs,obj, randmonster(FALSE), &mp); + } + when S_ID_POTION: + case S_ID_SCROLL: + case S_ID_WEAPON: + case S_ID_ARMOR: + case S_ID_R_OR_S: + { + static char id_type[S_ID_R_OR_S + 1] = + { 0, 0, 0, 0, 0, POTION, SCROLL, WEAPON, ARMOR, R_OR_S }; + /* + * Identify, let him figure something out + */ + scr_info[obj->o_which].oi_know = TRUE; + msg(rs,"this scroll is an %s scroll", scr_info[obj->o_which].oi_name); + whatis(rs,TRUE, id_type[obj->o_which]); + } + when S_MAP: + /* + * Scroll of magic mapping. + */ + scr_info[S_MAP].oi_know = TRUE; + msg(rs,"oh, now this scroll has a map on it"); + /* + * take all the things we want to keep hidden out of the window + */ + for (y = 1; y < NUMLINES - 1; y++) + for (x = 0; x < NUMCOLS; x++) + { + pp = INDEX(y, x); + switch (ch = pp->p_ch) + { + case DOOR: + case STAIRS: + break; + + case '-': + case '|': + if (!(pp->p_flags & F_REAL)) + { + ch = pp->p_ch = DOOR; + pp->p_flags |= F_REAL; + } + break; + + case ' ': + if (pp->p_flags & F_REAL) + goto def; + pp->p_flags |= F_REAL; + ch = pp->p_ch = PASSAGE; + /* FALLTHROUGH */ + + case PASSAGE: +pass: + if (!(pp->p_flags & F_REAL)) + pp->p_ch = PASSAGE; + pp->p_flags |= (F_SEEN|F_REAL); + ch = PASSAGE; + break; + + case FLOOR: + if (pp->p_flags & F_REAL) + ch = ' '; + else + { + ch = TRAP; + pp->p_ch = TRAP; + pp->p_flags |= (F_SEEN|F_REAL); + } + break; + + default: +def: + if (pp->p_flags & F_PASS) + goto pass; + ch = ' '; + break; + } + if (ch != ' ') + { + if ((obj = pp->p_monst) != NULL) + obj->t_oldch = ch; + if (obj == NULL || !on(player, SEEMONST)) + mvaddch(y, x, ch); + } + } + when S_FDET: + /* + * Potion of gold detection + */ + ch = FALSE; + wclear(hw); + for (obj = lvl_obj; obj != NULL; obj = next(obj)) + if (obj->o_type == FOOD) + { + ch = TRUE; + wmove(hw, obj->o_pos.y, obj->o_pos.x); + waddch(hw, FOOD); + } + if (ch) + { + scr_info[S_FDET].oi_know = TRUE; + show_win(rs,"Your nose tingles and you smell food.--More--"); + } + else + msg(rs,"your nose tingles"); + when S_TELEP: + /* + * Scroll of teleportation: + * Make him dissapear and reappear + */ + { + cur_room = proom; + teleport(rs); + if (cur_room != proom) + scr_info[S_TELEP].oi_know = TRUE; + } + when S_ENCH: + if (cur_weapon == NULL || cur_weapon->o_type != WEAPON) + msg(rs,"you feel a strange sense of loss"); + else + { + cur_weapon->o_flags &= ~ISCURSED; + if (rnd(2) == 0) + cur_weapon->o_hplus++; + else + cur_weapon->o_dplus++; + msg(rs,"your %s glows %s for a moment", + weap_info[cur_weapon->o_which].oi_name, pick_color("blue")); + } + when S_SCARE: + /* + * Reading it is a mistake and produces laughter at her + * poor boo boo. + */ + msg(rs,"you hear maniacal laughter in the distance"); + when S_REMOVE: + uncurse(cur_armor); + uncurse(cur_weapon); + uncurse(cur_ring[LEFT]); + uncurse(cur_ring[RIGHT]); + msg(rs,choose_str("you feel in touch with the Universal Onenes", + "you feel as if somebody is watching over you")); + when S_AGGR: + /* + * This scroll aggravates all the monsters on the current + * level and sets them running towards the hero + */ + aggravate(rs); + msg(rs,"you hear a high pitched humming noise"); + when S_PROTECT: + if (cur_armor != NULL) + { + cur_armor->o_flags |= ISPROT; + msg(rs,"your armor is covered by a shimmering %s shield", + pick_color("gold")); + } + else + msg(rs,"you feel a strange sense of loss"); +#ifdef MASTER + otherwise: + msg(rs,"what a puzzling scroll!"); + return; +#endif + } + obj = orig_obj; + look(rs,TRUE); /* put the result of the scroll on the screen */ + status(rs); + + call_it(rs,&scr_info[obj->o_which]); + + if (discardit) + discard(obj); +} + +/* + * uncurse: + * Uncurse an item + */ + +void +uncurse(THING *obj) +{ + if (obj != NULL) + obj->o_flags &= ~ISCURSED; +} diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c new file mode 100644 index 000000000..60a83c333 --- /dev/null +++ b/src/cc/rogue/state.c @@ -0,0 +1,2148 @@ +/* + state.c - Portable Rogue Save State Code + + Copyright (C) 1999, 2000, 2005 Nicholas J. Kisseberth + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name(s) of the author(s) nor the names of other contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTORS ``AS IS'' AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. +*/ + +#include +#include +#include +#include "rogue.h" + +/************************************************************************/ +/* Save State Code */ +/************************************************************************/ + +#define RSID_STATS 0xABCD0001 +#define RSID_THING 0xABCD0002 +#define RSID_THING_NULL 0xDEAD0002 +#define RSID_OBJECT 0xABCD0003 +#define RSID_MAGICITEMS 0xABCD0004 +#define RSID_KNOWS 0xABCD0005 +#define RSID_GUESSES 0xABCD0006 +#define RSID_OBJECTLIST 0xABCD0007 +#define RSID_BAGOBJECT 0xABCD0008 +#define RSID_MONSTERLIST 0xABCD0009 +#define RSID_MONSTERSTATS 0xABCD000A +#define RSID_MONSTERS 0xABCD000B +#define RSID_TRAP 0xABCD000C +#define RSID_WINDOW 0xABCD000D +#define RSID_DAEMONS 0xABCD000E +#define RSID_IWEAPS 0xABCD000F +#define RSID_IARMOR 0xABCD0010 +#define RSID_SPELLS 0xABCD0011 +#define RSID_ILIST 0xABCD0012 +#define RSID_HLIST 0xABCD0013 +#define RSID_DEATHTYPE 0xABCD0014 +#define RSID_CTYPES 0XABCD0015 +#define RSID_COORDLIST 0XABCD0016 +#define RSID_ROOMS 0XABCD0017 + +#define READSTAT (format_error || read_error ) +#define WRITESTAT (write_error) + +static int read_error = FALSE; +static int write_error = FALSE; +static int format_error = FALSE; +static int endian = 0x01020304; +#define big_endian ( *((char *)&endian) == 0x01 ) + +int +rs_write(FILE *savef, void *ptr, size_t size) +{ + if (write_error) + return(WRITESTAT); + + if (encwrite(ptr, size, savef) != size) + write_error = 1; + + return(WRITESTAT); +} + +int +rs_read(FILE *inf, void *ptr, size_t size) +{ + if (read_error || format_error) + return(READSTAT); + + if (encread(ptr, size, inf) != size) + read_error = 1; + + return(READSTAT); +} + +int +rs_write_int(FILE *savef, int c) +{ + unsigned char bytes[4]; + unsigned char *buf = (unsigned char *) &c; + + if (write_error) + return(WRITESTAT); + + if (big_endian) + { + bytes[3] = buf[0]; + bytes[2] = buf[1]; + bytes[1] = buf[2]; + bytes[0] = buf[3]; + buf = bytes; + } + + rs_write(savef, buf, 4); + + return(WRITESTAT); +} + +int +rs_read_int(FILE *inf, int *i) +{ + unsigned char bytes[4]; + int input = 0; + unsigned char *buf = (unsigned char *)&input; + + if (read_error || format_error) + return(READSTAT); + + rs_read(inf, &input, 4); + + if (big_endian) + { + bytes[3] = buf[0]; + bytes[2] = buf[1]; + bytes[1] = buf[2]; + bytes[0] = buf[3]; + buf = bytes; + } + + *i = *((int *) buf); + + return(READSTAT); +} + +int +rs_write_char(FILE *savef, char c) +{ + if (write_error) + return(WRITESTAT); + + rs_write(savef, &c, 1); + + return(WRITESTAT); +} + +int +rs_read_char(FILE *inf, char *c) +{ + if (read_error || format_error) + return(READSTAT); + + rs_read(inf, c, 1); + + return(READSTAT); +} + +int +rs_write_chars(FILE *savef, char *c, int count) +{ + if (write_error) + return(WRITESTAT); + + rs_write_int(savef, count); + rs_write(savef, c, count); + + return(WRITESTAT); +} + +int +rs_read_chars(FILE *inf, char *i, int count) +{ + int value = 0; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf, &value); + + if (value != count) + format_error = TRUE; + + rs_read(inf, i, count); + + return(READSTAT); +} + +int +rs_write_ints(FILE *savef, int *c, int count) +{ + int n = 0; + + if (write_error) + return(WRITESTAT); + + rs_write_int(savef, count); + + for(n = 0; n < count; n++) + if( rs_write_int(savef,c[n]) != 0) + break; + + return(WRITESTAT); +} + +int +rs_read_ints(FILE *inf, int *i, int count) +{ + int n, value; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf,&value); + + if (value != count) + format_error = TRUE; + + for(n = 0; n < count; n++) + if (rs_read_int(inf, &i[n]) != 0) + break; + + return(READSTAT); +} + +int +rs_write_boolean(FILE *savef, int c) +{ + unsigned char buf = (c == 0) ? 0 : 1; + + if (write_error) + return(WRITESTAT); + + rs_write(savef, &buf, 1); + + return(WRITESTAT); +} + +int +rs_read_boolean(FILE *inf, bool *i) +{ + unsigned char buf = 0; + + if (read_error || format_error) + return(READSTAT); + + rs_read(inf, &buf, 1); + + *i = (buf != 0); + + return(READSTAT); +} + +int +rs_write_booleans(FILE *savef, bool *c, int count) +{ + int n = 0; + + if (write_error) + return(WRITESTAT); + + rs_write_int(savef, count); + + for(n = 0; n < count; n++) + if (rs_write_boolean(savef, c[n]) != 0) + break; + + return(WRITESTAT); +} + +int +rs_read_booleans(FILE *inf, bool *i, int count) +{ + int n = 0, value = 0; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf,&value); + + if (value != count) + format_error = TRUE; + + for(n = 0; n < count; n++) + if (rs_read_boolean(inf, &i[n]) != 0) + break; + + return(READSTAT); +} + +int +rs_write_short(FILE *savef, short c) +{ + unsigned char bytes[2]; + unsigned char *buf = (unsigned char *) &c; + + if (write_error) + return(WRITESTAT); + + if (big_endian) + { + bytes[1] = buf[0]; + bytes[0] = buf[1]; + buf = bytes; + } + + rs_write(savef, buf, 2); + + return(WRITESTAT); +} + +int +rs_read_short(FILE *inf, short *i) +{ + unsigned char bytes[2]; + short input; + unsigned char *buf = (unsigned char *)&input; + + if (read_error || format_error) + return(READSTAT); + + rs_read(inf, &input, 2); + + if (big_endian) + { + bytes[1] = buf[0]; + bytes[0] = buf[1]; + buf = bytes; + } + + *i = *((short *) buf); + + return(READSTAT); +} + +int +rs_write_shorts(FILE *savef, short *c, int count) +{ + int n = 0; + + if (write_error) + return(WRITESTAT); + + rs_write_int(savef, count); + + for(n = 0; n < count; n++) + if (rs_write_short(savef, c[n]) != 0) + break; + + return(WRITESTAT); +} + +int +rs_read_shorts(FILE *inf, short *i, int count) +{ + int n = 0, value = 0; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf,&value); + + if (value != count) + format_error = TRUE; + + for(n = 0; n < value; n++) + if (rs_read_short(inf, &i[n]) != 0) + break; + + return(READSTAT); +} + +int +rs_write_ushort(FILE *savef, unsigned short c) +{ + unsigned char bytes[2]; + unsigned char *buf = (unsigned char *) &c; + + if (write_error) + return(WRITESTAT); + + if (big_endian) + { + bytes[1] = buf[0]; + bytes[0] = buf[1]; + buf = bytes; + } + + rs_write(savef, buf, 2); + + return(WRITESTAT); +} + +int +rs_read_ushort(FILE *inf, unsigned short *i) +{ + unsigned char bytes[2]; + unsigned short input; + unsigned char *buf = (unsigned char *)&input; + + if (read_error || format_error) + return(READSTAT); + + rs_read(inf, &input, 2); + + if (big_endian) + { + bytes[1] = buf[0]; + bytes[0] = buf[1]; + buf = bytes; + } + + *i = *((unsigned short *) buf); + + return(READSTAT); +} + +int +rs_write_uint(FILE *savef, unsigned int c) +{ + unsigned char bytes[4]; + unsigned char *buf = (unsigned char *) &c; + + if (write_error) + return(WRITESTAT); + + if (big_endian) + { + bytes[3] = buf[0]; + bytes[2] = buf[1]; + bytes[1] = buf[2]; + bytes[0] = buf[3]; + buf = bytes; + } + + rs_write(savef, buf, 4); + + return(WRITESTAT); +} + +int +rs_read_uint(FILE *inf, unsigned int *i) +{ + unsigned char bytes[4]; + int input; + unsigned char *buf = (unsigned char *)&input; + + if (read_error || format_error) + return(READSTAT); + + rs_read(inf, &input, 4); + + if (big_endian) + { + bytes[3] = buf[0]; + bytes[2] = buf[1]; + bytes[1] = buf[2]; + bytes[0] = buf[3]; + buf = bytes; + } + + *i = *((unsigned int *) buf); + + return(READSTAT); +} + +int +rs_write_marker(FILE *savef, int id) +{ + if (write_error) + return(WRITESTAT); + + rs_write_int(savef, id); + + return(WRITESTAT); +} + +int +rs_read_marker(FILE *inf, int id) +{ + int nid; + + if (read_error || format_error) + return(READSTAT); + + if (rs_read_int(inf, &nid) == 0) + if (id != nid) + format_error = 1; + + return(READSTAT); +} + + + +/******************************************************************************/ + +int +rs_write_string(FILE *savef, char *s) +{ + int len = 0; + + if (write_error) + return(WRITESTAT); + + len = (s == NULL) ? 0 : (int) strlen(s) + 1; + + rs_write_int(savef, len); + rs_write_chars(savef, s, len); + + return(WRITESTAT); +} + +int +rs_read_string(FILE *inf, char *s, int max) +{ + int len = 0; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf, &len); + + if (len > max) + format_error = TRUE; + + rs_read_chars(inf, s, len); + + return(READSTAT); +} + +int +rs_read_new_string(FILE *inf, char **s) +{ + int len=0; + char *buf=0; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf, &len); + + if (len == 0) + buf = NULL; + else + { + buf = malloc(len); + + if (buf == NULL) + read_error = TRUE; + } + + rs_read_chars(inf, buf, len); + + *s = buf; + + return(READSTAT); +} + +int +rs_write_strings(FILE *savef, char *s[], int count) +{ + int n = 0; + + if (write_error) + return(WRITESTAT); + + rs_write_int(savef, count); + + for(n = 0; n < count; n++) + if (rs_write_string(savef, s[n]) != 0) + break; + + return(WRITESTAT); +} + +int +rs_read_strings(FILE *inf, char **s, int count, int max) +{ + int n = 0; + int value = 0; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf, &value); + + if (value != count) + format_error = TRUE; + + for(n = 0; n < count; n++) + if (rs_read_string(inf, s[n], max) != 0) + break; + + return(READSTAT); +} + +int +rs_read_new_strings(FILE *inf, char **s, int count) +{ + int n = 0; + int value = 0; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf, &value); + + if (value != count) + format_error = TRUE; + + for(n = 0; n < count; n++) + if (rs_read_new_string(inf, &s[n]) != 0) + break; + + return(READSTAT); +} + +int +rs_write_string_index(FILE *savef, char *master[], int max, const char *str) +{ + int i; + + if (write_error) + return(WRITESTAT); + + for(i = 0; i < max; i++) + if (str == master[i]) + return( rs_write_int(savef, i) ); + + return( rs_write_int(savef,-1) ); +} + +int +rs_read_string_index(FILE *inf, char *master[], int maxindex, char **str) +{ + int i; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf, &i); + + if (i > maxindex) + format_error = TRUE; + else if (i >= 0) + *str = master[i]; + else + *str = NULL; + + return(READSTAT); +} + +int +rs_write_str_t(FILE *savef, str_t st) +{ + if (write_error) + return(WRITESTAT); + + rs_write_uint(savef, st); + + return( WRITESTAT ); +} + +int +rs_read_str_t(FILE *inf, str_t *st) +{ + if (read_error || format_error) + return(READSTAT); + + rs_read_uint(inf, st); + + return(READSTAT); +} + +int +rs_write_coord(FILE *savef, coord c) +{ + if (write_error) + return(WRITESTAT); + + rs_write_int(savef, c.x); + rs_write_int(savef, c.y); + + return(WRITESTAT); +} + +int +rs_read_coord(FILE *inf, coord *c) +{ + coord in; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf,&in.x); + rs_read_int(inf,&in.y); + + if (READSTAT == 0) + { + c->x = in.x; + c->y = in.y; + } + + return(READSTAT); +} + +int +rs_write_window(FILE *savef, WINDOW *win) +{ + int row,col,height,width; + + if (write_error) + return(WRITESTAT); + + width = getmaxx(win); + height = getmaxy(win); + + rs_write_marker(savef,RSID_WINDOW); + rs_write_int(savef,height); + rs_write_int(savef,width); + + for(row=0;rowl_next) + if (count == i) + return(l); + + return(NULL); +} + +int +find_list_ptr(THING *l, void *ptr) +{ + int count; + + for(count = 0; l != NULL; count++, l = l->l_next) + if (l == ptr) + return(count); + + return(-1); +} + +int +list_size(THING *l) +{ + int count; + + for(count = 0; l != NULL; count++, l = l->l_next) + ; + + return(count); +} + +/******************************************************************************/ + +int +rs_write_stats(FILE *savef, struct stats *s) +{ + if (write_error) + return(WRITESTAT); + + rs_write_marker(savef, RSID_STATS); + rs_write_str_t(savef, s->s_str); + rs_write_int(savef, s->s_exp); + rs_write_int(savef, s->s_lvl); + rs_write_int(savef, s->s_arm); + rs_write_int(savef, s->s_hpt); + rs_write_chars(savef, s->s_dmg, sizeof(s->s_dmg)); + rs_write_int(savef,s->s_maxhp); + + return(WRITESTAT); +} + +int +rs_read_stats(FILE *inf, struct stats *s) +{ + if (read_error || format_error) + return(READSTAT); + + rs_read_marker(inf, RSID_STATS); + rs_read_str_t(inf,&s->s_str); + rs_read_int(inf,&s->s_exp); + rs_read_int(inf,&s->s_lvl); + rs_read_int(inf,&s->s_arm); + rs_read_int(inf,&s->s_hpt); + rs_read_chars(inf,s->s_dmg,sizeof(s->s_dmg)); + rs_read_int(inf,&s->s_maxhp); + + return(READSTAT); +} + +int +rs_write_stone_index(FILE *savef, STONE master[], int max, const char *str) +{ + int i; + + if (write_error) + return(WRITESTAT); + + for(i = 0; i < max; i++) + if (str == master[i].st_name) + { + rs_write_int(savef,i); + return(WRITESTAT); + } + + rs_write_int(savef,-1); + + return(WRITESTAT); +} + +int +rs_read_stone_index(FILE *inf, STONE master[], int maxindex, char **str) +{ + int i = 0; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf,&i); + + if (i > maxindex) + format_error = TRUE; + else if (i >= 0) + *str = master[i].st_name; + else + *str = NULL; + + return(READSTAT); +} + +int +rs_write_scrolls(FILE *savef) +{ + int i; + + if (write_error) + return(WRITESTAT); + + for(i = 0; i < MAXSCROLLS; i++) + rs_write_string(savef, s_names[i]); + + return(READSTAT); +} + +int +rs_read_scrolls(FILE *inf) +{ + int i; + + if (read_error || format_error) + return(READSTAT); + + for(i = 0; i < MAXSCROLLS; i++) + rs_read_new_string(inf, &s_names[i]); + + return(READSTAT); +} + +int +rs_write_potions(FILE *savef) +{ + int i; + + if (write_error) + return(WRITESTAT); + + for(i = 0; i < MAXPOTIONS; i++) + rs_write_string_index(savef, rainbow, cNCOLORS, p_colors[i]); + + return(WRITESTAT); +} + +int +rs_read_potions(FILE *inf) +{ + int i; + + if (read_error || format_error) + return(READSTAT); + + for(i = 0; i < MAXPOTIONS; i++) + rs_read_string_index(inf, rainbow, cNCOLORS, &p_colors[i]); + + return(READSTAT); +} + +int +rs_write_rings(FILE *savef) +{ + int i; + + if (write_error) + return(WRITESTAT); + + for(i = 0; i < MAXRINGS; i++) + rs_write_stone_index(savef, stones, cNSTONES, r_stones[i]); + + return(WRITESTAT); +} + +int +rs_read_rings(FILE *inf) +{ + int i; + + if (read_error || format_error) + return(READSTAT); + + for(i = 0; i < MAXRINGS; i++) + rs_read_stone_index(inf, stones, cNSTONES, &r_stones[i]); + + return(READSTAT); +} + +int +rs_write_sticks(FILE *savef) +{ + int i; + + if (write_error) + return(WRITESTAT); + + for (i = 0; i < MAXSTICKS; i++) + { + if (strcmp(ws_type[i],"staff") == 0) + { + rs_write_int(savef,0); + rs_write_string_index(savef, wood, cNWOOD, ws_made[i]); + } + else + { + rs_write_int(savef,1); + rs_write_string_index(savef, metal, cNMETAL, ws_made[i]); + } + } + + return(WRITESTAT); +} + +int +rs_read_sticks(FILE *inf) +{ + int i = 0, list = 0; + + if (read_error || format_error) + return(READSTAT); + + for(i = 0; i < MAXSTICKS; i++) + { + rs_read_int(inf,&list); + + if (list == 0) + { + rs_read_string_index(inf, wood, cNWOOD, &ws_made[i]); + ws_type[i] = "staff"; + } + else + { + rs_read_string_index(inf, metal, cNMETAL, &ws_made[i]); + ws_type[i] = "wand"; + } + } + + return(READSTAT); +} + +int +rs_write_daemons(FILE *savef, struct delayed_action *d_list, int count) +{ + int i = 0; + int func = 0; + + if (write_error) + return(WRITESTAT); + + rs_write_marker(savef, RSID_DAEMONS); + rs_write_int(savef, count); + + for(i = 0; i < count; i++) + { + if (d_list[i].d_func == rollwand) + func = 1; + else if (d_list[i].d_func == doctor) + func = 2; + else if (d_list[i].d_func == stomach) + func = 3; + else if (d_list[i].d_func == runners) + func = 4; + else if (d_list[i].d_func == swander) + func = 5; + else if (d_list[i].d_func == nohaste) + func = 6; + else if (d_list[i].d_func == unconfuse) + func = 7; + else if (d_list[i].d_func == unsee) + func = 8; + else if (d_list[i].d_func == sight) + func = 9; + else if (d_list[i].d_func == NULL) + func = 0; + else + func = -1; + + rs_write_int(savef, d_list[i].d_type); + rs_write_int(savef, func); + rs_write_int(savef, d_list[i].d_arg); + rs_write_int(savef, d_list[i].d_time); + } + + return(WRITESTAT); +} + +int +rs_read_daemons(FILE *inf, struct delayed_action *d_list, int count) +{ + int i = 0; + int func = 0; + int value = 0; + + if (read_error || format_error) + return(READSTAT); + + rs_read_marker(inf, RSID_DAEMONS); + rs_read_int(inf, &value); + + if (value > count) + format_error = TRUE; + + for(i=0; i < count; i++) + { + func = 0; + rs_read_int(inf, &d_list[i].d_type); + rs_read_int(inf, &func); + rs_read_int(inf, &d_list[i].d_arg); + rs_read_int(inf, &d_list[i].d_time); + + switch(func) + { + case 1: d_list[i].d_func = rollwand; + break; + case 2: d_list[i].d_func = doctor; + break; + case 3: d_list[i].d_func = stomach; + break; + case 4: d_list[i].d_func = runners; + break; + case 5: d_list[i].d_func = swander; + break; + case 6: d_list[i].d_func = nohaste; + break; + case 7: d_list[i].d_func = unconfuse; + break; + case 8: d_list[i].d_func = unsee; + break; + case 9: d_list[i].d_func = sight; + break; + default:d_list[i].d_func = NULL; + break; + } + } + + if (d_list[i].d_func == NULL) + { + d_list[i].d_type = 0; + d_list[i].d_arg = 0; + d_list[i].d_time = 0; + } + + return(READSTAT); +} + +int +rs_write_obj_info(FILE *savef, struct obj_info *i, int count) +{ + int n; + + if (write_error) + return(WRITESTAT); + + rs_write_marker(savef, RSID_MAGICITEMS); + rs_write_int(savef, count); + + for(n = 0; n < count; n++) + { + /* mi_name is constant, defined at compile time in all cases */ + rs_write_int(savef,i[n].oi_prob); + rs_write_int(savef,i[n].oi_worth); + rs_write_string(savef,i[n].oi_guess); + rs_write_boolean(savef,i[n].oi_know); + } + + return(WRITESTAT); +} + +int +rs_read_obj_info(FILE *inf, struct obj_info *mi, int count) +{ + int n; + int value; + + if (read_error || format_error) + return(READSTAT); + + rs_read_marker(inf, RSID_MAGICITEMS); + + rs_read_int(inf, &value); + + if (value > count) + format_error = TRUE; + + for(n = 0; n < value; n++) + { + /* mi_name is const, defined at compile time in all cases */ + rs_read_int(inf,&mi[n].oi_prob); + rs_read_int(inf,&mi[n].oi_worth); + rs_read_new_string(inf,&mi[n].oi_guess); + rs_read_boolean(inf,&mi[n].oi_know); + } + + return(READSTAT); +} + +int +rs_write_room(FILE *savef, struct room *r) +{ + if (write_error) + return(WRITESTAT); + + rs_write_coord(savef, r->r_pos); + rs_write_coord(savef, r->r_max); + rs_write_coord(savef, r->r_gold); + rs_write_int(savef, r->r_goldval); + rs_write_short(savef, r->r_flags); + rs_write_int(savef, r->r_nexits); + rs_write_coord(savef, r->r_exit[0]); + rs_write_coord(savef, r->r_exit[1]); + rs_write_coord(savef, r->r_exit[2]); + rs_write_coord(savef, r->r_exit[3]); + rs_write_coord(savef, r->r_exit[4]); + rs_write_coord(savef, r->r_exit[5]); + rs_write_coord(savef, r->r_exit[6]); + rs_write_coord(savef, r->r_exit[7]); + rs_write_coord(savef, r->r_exit[8]); + rs_write_coord(savef, r->r_exit[9]); + rs_write_coord(savef, r->r_exit[10]); + rs_write_coord(savef, r->r_exit[11]); + + return(WRITESTAT); +} + +int +rs_read_room(FILE *inf, struct room *r) +{ + if (read_error || format_error) + return(READSTAT); + + rs_read_coord(inf,&r->r_pos); + rs_read_coord(inf,&r->r_max); + rs_read_coord(inf,&r->r_gold); + rs_read_int(inf,&r->r_goldval); + rs_read_short(inf,&r->r_flags); + rs_read_int(inf,&r->r_nexits); + rs_read_coord(inf,&r->r_exit[0]); + rs_read_coord(inf,&r->r_exit[1]); + rs_read_coord(inf,&r->r_exit[2]); + rs_read_coord(inf,&r->r_exit[3]); + rs_read_coord(inf,&r->r_exit[4]); + rs_read_coord(inf,&r->r_exit[5]); + rs_read_coord(inf,&r->r_exit[6]); + rs_read_coord(inf,&r->r_exit[7]); + rs_read_coord(inf,&r->r_exit[8]); + rs_read_coord(inf,&r->r_exit[9]); + rs_read_coord(inf,&r->r_exit[10]); + rs_read_coord(inf,&r->r_exit[11]); + + return(READSTAT); +} + +int +rs_write_rooms(FILE *savef, struct room r[], int count) +{ + int n = 0; + + if (write_error) + return(WRITESTAT); + //fprintf(stderr,"rooms %ld -> ",ftell(savef)); + rs_write_int(savef, count); + + for(n = 0; n < count; n++) + rs_write_room(savef, &r[n]); + //fprintf(stderr,"%ld\n",ftell(savef)); + + return(WRITESTAT); +} + +int +rs_read_rooms(FILE *inf, struct room *r, int count) +{ + int value = 0, n = 0; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf,&value); + + if (value > count) + format_error = TRUE; + + for(n = 0; n < value; n++) + rs_read_room(inf,&r[n]); + + return(READSTAT); +} + +int +rs_write_room_reference(FILE *savef, struct room *rp) +{ + int i, room = -1; + + if (write_error) + return(WRITESTAT); + + for (i = 0; i < MAXROOMS; i++) + if (&rooms[i] == rp) + room = i; + + rs_write_int(savef, room); + + return(WRITESTAT); +} + +int +rs_read_room_reference(FILE *inf, struct room **rp) +{ + int i; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf, &i); + + *rp = &rooms[i]; + + return(READSTAT); +} + +int +rs_write_monsters(FILE *savef, struct monster *m, int count) +{ + int n; + + if (write_error) + return(WRITESTAT); + + rs_write_marker(savef, RSID_MONSTERS); + rs_write_int(savef, count); + + for(n=0;n ",ftell(savef)); + + rs_write_marker(savef, RSID_OBJECT); + rs_write_int(savef, o->_o._o_type); + rs_write_coord(savef, o->_o._o_pos); + rs_write_int(savef, o->_o._o_launch); + rs_write_char(savef, o->_o._o_packch); + rs_write_chars(savef, o->_o._o_damage, sizeof(o->_o._o_damage)); + rs_write_chars(savef, o->_o._o_hurldmg, sizeof(o->_o._o_hurldmg)); + rs_write_int(savef, o->_o._o_count); + rs_write_int(savef, o->_o._o_which); + rs_write_int(savef, o->_o._o_hplus); + rs_write_int(savef, o->_o._o_dplus); + rs_write_int(savef, o->_o._o_arm); + rs_write_int(savef, o->_o._o_flags); + rs_write_int(savef, o->_o._o_group); + rs_write_string(savef, o->_o._o_label); + //fprintf(stderr,"%ld\n",ftell(savef)); + return(WRITESTAT); +} + +int +rs_read_object(FILE *inf, THING *o) +{ + if (read_error || format_error) + return(READSTAT); + + rs_read_marker(inf, RSID_OBJECT); + rs_read_int(inf, &o->_o._o_type); + rs_read_coord(inf, &o->_o._o_pos); + rs_read_int(inf, &o->_o._o_launch); + rs_read_char(inf, &o->_o._o_packch); + rs_read_chars(inf, o->_o._o_damage, sizeof(o->_o._o_damage)); + rs_read_chars(inf, o->_o._o_hurldmg, sizeof(o->_o._o_hurldmg)); + rs_read_int(inf, &o->_o._o_count); + rs_read_int(inf, &o->_o._o_which); + rs_read_int(inf, &o->_o._o_hplus); + rs_read_int(inf, &o->_o._o_dplus); + rs_read_int(inf, &o->_o._o_arm); + rs_read_int(inf, &o->_o._o_flags); + rs_read_int(inf, &o->_o._o_group); + rs_read_new_string(inf, &o->_o._o_label); + + return(READSTAT); +} + +int +rs_write_object_list(FILE *savef, THING *l) +{ + if (write_error) + return(WRITESTAT); + //fprintf(stderr,"list %ld -> ",ftell(savef)); + + rs_write_marker(savef, RSID_OBJECTLIST); + rs_write_int(savef, list_size(l)); + + for( ;l != NULL; l = l->l_next) + rs_write_object(savef, l); + //fprintf(stderr,"%ld\n",ftell(savef)); + + return(WRITESTAT); +} + +int +rs_read_object_list(FILE *inf, THING **list) +{ + int i, cnt; + THING *l = NULL, *previous = NULL, *head = NULL; + + if (read_error || format_error) + return(READSTAT); + + rs_read_marker(inf, RSID_OBJECTLIST); + rs_read_int(inf, &cnt); + + for (i = 0; i < cnt; i++) + { + l = new_item();//,sizeof(THING)); + + memset(l,0,sizeof(THING)); + + l->l_prev = previous; + + if (previous != NULL) + previous->l_next = l; + + rs_read_object(inf,l); + + if (previous == NULL) + head = l; + + previous = l; + } + + if (l != NULL) + l->l_next = NULL; + + *list = head; + + return(READSTAT); +} + +int +rs_write_object_reference(FILE *savef, THING *list, THING *item) +{ + int i; + + if (write_error) + return(WRITESTAT); + + i = find_list_ptr(list, item); + + rs_write_int(savef, i); + + return(WRITESTAT); +} + +int +rs_read_object_reference(FILE *inf, THING *list, THING **item) +{ + int i; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf, &i); + + *item = get_list_item(list,i); + + return(READSTAT); +} + +int +find_room_coord(struct room *rmlist, coord *c, int n) +{ + int i = 0; + + for(i = 0; i < n; i++) + if(&rmlist[i].r_gold == c) + return(i); + + return(-1); +} + +int +find_thing_coord(THING *monlist, coord *c) +{ + THING *mitem; + THING *tp; + int i = 0; + + for(mitem = monlist; mitem != NULL; mitem = mitem->l_next) + { + tp = mitem; + + if (c == &tp->t_pos) + return(i); + + i++; + } + + return(-1); +} + +int +find_object_coord(THING *objlist, coord *c) +{ + THING *oitem; + THING *obj; + int i = 0; + + for(oitem = objlist; oitem != NULL; oitem = oitem->l_next) + { + obj = oitem; + + if (c == &obj->o_pos) + return(i); + + i++; + } + + return(-1); +} + +int +rs_write_thing(FILE *savef, THING *t) +{ + int i = -1; + + if (write_error) + return(WRITESTAT); + //fprintf(stderr,"thing %ld -> ",ftell(savef)); + + rs_write_marker(savef, RSID_THING); + + if (t == NULL) + { + rs_write_int(savef, 0); + return(WRITESTAT); + } + + rs_write_int(savef, 1); + rs_write_coord(savef, t->_t._t_pos); + rs_write_boolean(savef, t->_t._t_turn); + rs_write_char(savef, t->_t._t_type); + rs_write_char(savef, t->_t._t_disguise); + rs_write_char(savef, t->_t._t_oldch); + + /* + t_dest can be: + 0,0: NULL + 0,1: location of hero + 1,i: location of a thing (monster) + 2,i: location of an object + 3,i: location of gold in a room + + We need to remember what we are chasing rather than + the current location of what we are chasing. + */ + + if (t->t_dest == &hero) + { + rs_write_int(savef,0); + rs_write_int(savef,1); + } + else if (t->t_dest != NULL) + { + i = find_thing_coord(mlist, t->t_dest); + + if (i >=0 ) + { + rs_write_int(savef,1); + rs_write_int(savef,i); + } + else + { + i = find_object_coord(lvl_obj, t->t_dest); + + if (i >= 0) + { + rs_write_int(savef,2); + rs_write_int(savef,i); + } + else + { + i = find_room_coord(rooms, t->t_dest, MAXROOMS); + + if (i >= 0) + { + rs_write_int(savef,3); + rs_write_int(savef,i); + } + else + { + rs_write_int(savef, 0); + rs_write_int(savef,1); /* chase the hero anyway */ + } + } + } + } + else + { + rs_write_int(savef,0); + rs_write_int(savef,0); + } + + rs_write_short(savef, t->_t._t_flags); + rs_write_stats(savef, &t->_t._t_stats); + rs_write_room_reference(savef, t->_t._t_room); + rs_write_object_list(savef, t->_t._t_pack); + //fprintf(stderr,"%ld\n",ftell(savef)); + + return(WRITESTAT); +} + +int +rs_read_thing(FILE *inf, THING *t) +{ + int listid = 0, index = -1; + THING *item; + + if (read_error || format_error) + return(READSTAT); + + rs_read_marker(inf, RSID_THING); + + rs_read_int(inf, &index); + + if (index == 0) + return(READSTAT); + + rs_read_coord(inf,&t->_t._t_pos); + rs_read_boolean(inf,&t->_t._t_turn); + rs_read_char(inf,&t->_t._t_type); + rs_read_char(inf,&t->_t._t_disguise); + rs_read_char(inf,&t->_t._t_oldch); + + /* + t_dest can be (listid,index): + 0,0: NULL + 0,1: location of hero + 1,i: location of a thing (monster) + 2,i: location of an object + 3,i: location of gold in a room + + We need to remember what we are chasing rather than + the current location of what we are chasing. + */ + + rs_read_int(inf, &listid); + rs_read_int(inf, &index); + t->_t._t_reserved = -1; + + if (listid == 0) /* hero or NULL */ + { + if (index == 1) + t->_t._t_dest = &hero; + else + t->_t._t_dest = NULL; + } + else if (listid == 1) /* monster/thing */ + { + t->_t._t_dest = NULL; + t->_t._t_reserved = index; + } + else if (listid == 2) /* object */ + { + THING *obj; + + item = get_list_item(lvl_obj, index); + + if (item != NULL) + { + obj = item; + t->_t._t_dest = &obj->o_pos; + } + } + else if (listid == 3) /* gold */ + { + t->_t._t_dest = &rooms[index].r_gold; + } + else + t->_t._t_dest = NULL; + + rs_read_short(inf,&t->_t._t_flags); + rs_read_stats(inf,&t->_t._t_stats); + rs_read_room_reference(inf, &t->_t._t_room); + rs_read_object_list(inf,&t->_t._t_pack); + + return(READSTAT); +} + +void +rs_fix_thing(THING *t) +{ + THING *item; + THING *tp; + + if (t->t_reserved < 0) + return; + + item = get_list_item(mlist,t->t_reserved); + + if (item != NULL) + { + tp = item; + t->t_dest = &tp->t_pos; + } +} + +int +rs_write_thing_list(FILE *savef, THING *l) +{ + int cnt = 0; + + if (write_error) + return(WRITESTAT); + + rs_write_marker(savef, RSID_MONSTERLIST); + + cnt = list_size(l); + + rs_write_int(savef, cnt); + + if (cnt < 1) + return(WRITESTAT); + + while (l != NULL) { + rs_write_thing(savef, l); + l = l->l_next; + } + + return(WRITESTAT); +} + +int +rs_read_thing_list(FILE *inf, THING **list) +{ + int i, cnt; + THING *l = NULL, *previous = NULL, *head = NULL; + + if (read_error || format_error) + return(READSTAT); + + rs_read_marker(inf, RSID_MONSTERLIST); + + rs_read_int(inf, &cnt); + + for (i = 0; i < cnt; i++) + { + l = new_item(); + + l->l_prev = previous; + + if (previous != NULL) + previous->l_next = l; + + rs_read_thing(inf,l); + + if (previous == NULL) + head = l; + + previous = l; + } + + if (l != NULL) + l->l_next = NULL; + + *list = head; + + return(READSTAT); +} + +void +rs_fix_thing_list(THING *list) +{ + THING *item; + + for(item = list; item != NULL; item = item->l_next) + rs_fix_thing(item); +} + +int +rs_write_thing_reference(FILE *savef, THING *list, THING *item) +{ + int i; + + if (write_error) + return(WRITESTAT); + + if (item == NULL) + rs_write_int(savef,-1); + else + { + i = find_list_ptr(list, item); + + rs_write_int(savef, i); + } + + return(WRITESTAT); +} + +int +rs_read_thing_reference(FILE *inf, THING *list, THING **item) +{ + int i; + + if (read_error || format_error) + return(READSTAT); + + rs_read_int(inf, &i); + + if (i == -1) + *item = NULL; + else + *item = get_list_item(list,i); + + return(READSTAT); +} + +int +rs_write_thing_references(FILE *savef, THING *list, THING *items[], int count) +{ + int i; + + if (write_error) + return(WRITESTAT); + + for(i = 0; i < count; i++) + rs_write_thing_reference(savef,list,items[i]); + + return(WRITESTAT); +} + +int +rs_read_thing_references(FILE *inf, THING *list, THING *items[], int count) +{ + int i; + + if (read_error || format_error) + return(READSTAT); + + for(i = 0; i < count; i++) + rs_read_thing_reference(inf,list,&items[i]); + + return(WRITESTAT); +} + +int +rs_write_places(FILE *savef, PLACE *places, int count) +{ + int i = 0; + //fprintf(stderr,"places %ld -> ",ftell(savef)); + + if (write_error) + return(WRITESTAT); + + for(i = 0; i < count; i++) + { + rs_write_char(savef, places[i].p_ch); + rs_write_char(savef, places[i].p_flags); + rs_write_thing_reference(savef, mlist, places[i].p_monst); + } + //fprintf(stderr,"%ld\n",ftell(savef)); + + return(WRITESTAT); +} + +int +rs_read_places(FILE *inf, PLACE *places, int count) +{ + int i = 0; + + if (read_error || format_error) + return(READSTAT); + + for(i = 0; i < count; i++) + { + rs_read_char(inf,&places[i].p_ch); + rs_read_char(inf,&places[i].p_flags); + rs_read_thing_reference(inf, mlist, &places[i].p_monst); + } + + return(READSTAT); +} + +int +rs_save_file(FILE *savef) +{ + if (write_error) + return(WRITESTAT); + + rs_write_boolean(savef, after); /* 1 */ /* extern.c */ + rs_write_boolean(savef, again); /* 2 */ + rs_write_int(savef, noscore); /* 3 */ + rs_write_boolean(savef, seenstairs); /* 4 */ + rs_write_boolean(savef, amulet); /* 5 */ + rs_write_boolean(savef, door_stop); /* 6 */ + rs_write_boolean(savef, fight_flush); /* 7 */ + rs_write_boolean(savef, firstmove); /* 8 */ + rs_write_boolean(savef, got_ltc); /* 9 */ + rs_write_boolean(savef, has_hit); /* 10 */ + rs_write_boolean(savef, in_shell); /* 11 */ + rs_write_boolean(savef, inv_describe); /* 12 */ + rs_write_boolean(savef, jump); /* 13 */ + rs_write_boolean(savef, kamikaze); /* 14 */ + rs_write_boolean(savef, lower_msg); /* 15 */ + rs_write_boolean(savef, move_on); /* 16 */ + rs_write_boolean(savef, msg_esc); /* 17 */ + rs_write_boolean(savef, passgo); /* 18 */ + rs_write_boolean(savef, playing); /* 19 */ + rs_write_boolean(savef, q_comm); /* 20 */ + rs_write_boolean(savef, running); /* 21 */ + rs_write_boolean(savef, save_msg); /* 22 */ + rs_write_boolean(savef, see_floor); /* 23 */ + rs_write_boolean(savef, stat_msg); /* 24 */ + rs_write_boolean(savef, terse); /* 25 */ + rs_write_boolean(savef, to_death); /* 26 */ + rs_write_boolean(savef, tombstone); /* 27 */ +#ifdef MASTER + rs_write_int(savef, wizard); /* 28 */ +#else + rs_write_int(savef, 0); /* 28 */ +#endif + rs_write_booleans(savef, pack_used, 26); /* 29 */ + rs_write_char(savef, dir_ch); + //rs_write_chars(savef, file_name, MAXSTR); + //rs_write_chars(savef, huh, MAXSTR); + rs_write_potions(savef); + //rs_write_chars(savef,prbuf,2*MAXSTR); + rs_write_rings(savef); + rs_write_string(savef,release); + rs_write_char(savef, runch); + rs_write_scrolls(savef); + rs_write_char(savef, take); + //rs_write_chars(savef, whoami, MAXSTR); + rs_write_sticks(savef); + rs_write_int(savef,orig_dsusp); + rs_write_chars(savef, fruit, MAXSTR); + //rs_write_chars(savef, home, MAXSTR); + rs_write_strings(savef,inv_t_name,3); + rs_write_char(savef,l_last_comm); + rs_write_char(savef,l_last_dir); + rs_write_char(savef,last_comm); + rs_write_char(savef,last_dir); + rs_write_strings(savef,tr_name,8); + rs_write_int(savef,n_objs); + rs_write_int(savef, ntraps); + rs_write_int(savef, hungry_state); + rs_write_int(savef, inpack); + rs_write_int(savef, inv_type); + rs_write_int(savef, level); + rs_write_int(savef, max_level); + rs_write_int(savef, mpos); + rs_write_int(savef, no_food); + rs_write_ints(savef,a_class,MAXARMORS); + rs_write_int(savef, count); + rs_write_int(savef, food_left); + rs_write_int(savef, lastscore); + rs_write_int(savef, no_command); + rs_write_int(savef, no_move); + rs_write_int(savef, purse); + rs_write_int(savef, quiet); + rs_write_int(savef, vf_hit); + //rs_write_int(savef, dnum); + rs_write_int(savef, (int32_t)(seed&0xffffffff)); + rs_write_int(savef, (int32_t)((seed>>32)&0xffffffff)); + rs_write_ints(savef, e_levels, 21); + rs_write_coord(savef, delta); + rs_write_coord(savef, oldpos); + rs_write_coord(savef, stairs); + rs_write_thing(savef, &player); + rs_write_object_reference(savef, player.t_pack, cur_armor); + rs_write_object_reference(savef, player.t_pack, cur_ring[0]); + rs_write_object_reference(savef, player.t_pack, cur_ring[1]); + rs_write_object_reference(savef, player.t_pack, cur_weapon); + rs_write_object_reference(savef, player.t_pack, l_last_pick); + rs_write_object_reference(savef, player.t_pack, last_pick); + + rs_write_object_list(savef, lvl_obj); + rs_write_thing_list(savef, mlist); + + rs_write_places(savef,places,MAXLINES*MAXCOLS); + + rs_write_stats(savef,&max_stats); + rs_write_rooms(savef, rooms, MAXROOMS); + rs_write_room_reference(savef, oldrp); + rs_write_rooms(savef, passages, MAXPASS); + + rs_write_monsters(savef,monsters,26); + rs_write_obj_info(savef, things, NUMTHINGS); + rs_write_obj_info(savef, arm_info, MAXARMORS); + rs_write_obj_info(savef, pot_info, MAXPOTIONS); + rs_write_obj_info(savef, ring_info, MAXRINGS); + rs_write_obj_info(savef, scr_info, MAXSCROLLS); + rs_write_obj_info(savef, weap_info, MAXWEAPONS+1); + rs_write_obj_info(savef, ws_info, MAXSTICKS); + + + rs_write_daemons(savef, &d_list[0], 20); /* 5.4-daemon.c */ +#ifdef MASTER + rs_write_int(savef,total); /* 5.4-list.c */ +#else + rs_write_int(savef, 0); +#endif + rs_write_int(savef,between); /* 5.4-daemons.c*/ + rs_write_coord(savef, nh); /* 5.4-move.c */ + rs_write_int(savef, group); /* 5.4-weapons.c */ + //fprintf(stderr,"fifth %ld\n",ftell(savef)); + + rs_write_window(savef,stdscr); + //fprintf(stderr,"done %ld\n",ftell(savef)); + + return(WRITESTAT); +} + +int +rs_restore_file(FILE *inf) +{ + int dummyint; + + if (read_error || format_error) + return(READSTAT); + + rs_read_boolean(inf, &after); /* 1 */ /* extern.c */ + rs_read_boolean(inf, &again); /* 2 */ + rs_read_int(inf, &noscore); /* 3 */ + rs_read_boolean(inf, &seenstairs); /* 4 */ + rs_read_boolean(inf, &amulet); /* 5 */ + rs_read_boolean(inf, &door_stop); /* 6 */ + rs_read_boolean(inf, &fight_flush); /* 7 */ + rs_read_boolean(inf, &firstmove); /* 8 */ + rs_read_boolean(inf, &got_ltc); /* 9 */ + rs_read_boolean(inf, &has_hit); /* 10 */ + rs_read_boolean(inf, &in_shell); /* 11 */ + rs_read_boolean(inf, &inv_describe); /* 12 */ + rs_read_boolean(inf, &jump); /* 13 */ + rs_read_boolean(inf, &kamikaze); /* 14 */ + rs_read_boolean(inf, &lower_msg); /* 15 */ + rs_read_boolean(inf, &move_on); /* 16 */ + rs_read_boolean(inf, &msg_esc); /* 17 */ + rs_read_boolean(inf, &passgo); /* 18 */ + rs_read_boolean(inf, &playing); /* 19 */ + rs_read_boolean(inf, &q_comm); /* 20 */ + rs_read_boolean(inf, &running); /* 21 */ + rs_read_boolean(inf, &save_msg); /* 22 */ + rs_read_boolean(inf, &see_floor); /* 23 */ + rs_read_boolean(inf, &stat_msg); /* 24 */ + rs_read_boolean(inf, &terse); /* 25 */ + rs_read_boolean(inf, &to_death); /* 26 */ + rs_read_boolean(inf, &tombstone); /* 27 */ +#ifdef MASTER + rs_read_int(inf, &wizard); /* 28 */ +#else + rs_read_int(inf, &dummyint); /* 28 */ +#endif + rs_read_booleans(inf, pack_used, 26); /* 29 */ + rs_read_char(inf, &dir_ch); + //rs_read_chars(inf, file_name, MAXSTR); + //rs_read_chars(inf, huh, MAXSTR); + rs_read_potions(inf); + //rs_read_chars(inf, prbuf, 2*MAXSTR); + rs_read_rings(inf); + rs_read_new_string(inf,&release); + rs_read_char(inf, &runch); + rs_read_scrolls(inf); + rs_read_char(inf, &take); + //rs_read_chars(inf, whoami, MAXSTR); + rs_read_sticks(inf); + rs_read_int(inf,&orig_dsusp); + rs_read_chars(inf, fruit, MAXSTR); + //rs_read_chars(inf, home, MAXSTR); + rs_read_new_strings(inf,inv_t_name,3); + rs_read_char(inf, &l_last_comm); + rs_read_char(inf, &l_last_dir); + rs_read_char(inf, &last_comm); + rs_read_char(inf, &last_dir); + rs_read_new_strings(inf,tr_name,8); + rs_read_int(inf, &n_objs); + rs_read_int(inf, &ntraps); + rs_read_int(inf, &hungry_state); + rs_read_int(inf, &inpack); + rs_read_int(inf, &inv_type); + rs_read_int(inf, &level); + rs_read_int(inf, &max_level); + rs_read_int(inf, &mpos); + rs_read_int(inf, &no_food); + rs_read_ints(inf,a_class,MAXARMORS); + rs_read_int(inf, &count); + rs_read_int(inf, &food_left); + rs_read_int(inf, &lastscore); + rs_read_int(inf, &no_command); + rs_read_int(inf, &no_move); + rs_read_int(inf, &purse); + rs_read_int(inf, &quiet); + rs_read_int(inf, &vf_hit); + //rs_read_int(inf, &dnum); + int32_t lownum,highnum; + rs_read_int(inf, &lownum); + rs_read_int(inf, &highnum); + seed = ((uint64_t)highnum<<32) | (lownum&0xffffffff); + rs_read_ints(inf,e_levels,21); + rs_read_coord(inf, &delta); + rs_read_coord(inf, &oldpos); + rs_read_coord(inf, &stairs); + + rs_read_thing(inf, &player); + rs_read_object_reference(inf, player.t_pack, &cur_armor); + rs_read_object_reference(inf, player.t_pack, &cur_ring[0]); + rs_read_object_reference(inf, player.t_pack, &cur_ring[1]); + rs_read_object_reference(inf, player.t_pack, &cur_weapon); + rs_read_object_reference(inf, player.t_pack, &l_last_pick); + rs_read_object_reference(inf, player.t_pack, &last_pick); + + rs_read_object_list(inf, &lvl_obj); + rs_read_thing_list(inf, &mlist); + rs_fix_thing(&player); + rs_fix_thing_list(mlist); + + rs_read_places(inf,places,MAXLINES*MAXCOLS); + + rs_read_stats(inf, &max_stats); + rs_read_rooms(inf, rooms, MAXROOMS); + rs_read_room_reference(inf, &oldrp); + rs_read_rooms(inf, passages, MAXPASS); + + rs_read_monsters(inf,monsters,26); + rs_read_obj_info(inf, things, NUMTHINGS); + rs_read_obj_info(inf, arm_info, MAXARMORS); + rs_read_obj_info(inf, pot_info, MAXPOTIONS); + rs_read_obj_info(inf, ring_info, MAXRINGS); + rs_read_obj_info(inf, scr_info, MAXSCROLLS); + rs_read_obj_info(inf, weap_info, MAXWEAPONS+1); + rs_read_obj_info(inf, ws_info, MAXSTICKS); + + rs_read_daemons(inf, d_list, 20); /* 5.4-daemon.c */ + rs_read_int(inf,&dummyint); /* total */ /* 5.4-list.c */ + rs_read_int(inf,&between); /* 5.4-daemons.c */ + rs_read_coord(inf, &nh); /* 5.4-move.c */ + rs_read_int(inf,&group); /* 5.4-weapons.c */ + + rs_read_window(inf,stdscr); + + return(READSTAT); +} diff --git a/src/cc/rogue/sticks.c b/src/cc/rogue/sticks.c new file mode 100644 index 000000000..7b01fe34c --- /dev/null +++ b/src/cc/rogue/sticks.c @@ -0,0 +1,431 @@ +/* + * Functions to implement the various sticks one might find + * while wandering around the dungeon. + * + * @(#)sticks.c 4.39 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include +#include "rogue.h" + +/* + * fix_stick: + * Set up a new stick + */ + +void +fix_stick(THING *cur) +{ + if (strcmp(ws_type[cur->o_which], "staff") == 0) + strncpy(cur->o_damage,"2x3",sizeof(cur->o_damage)); + else + strncpy(cur->o_damage,"1x1",sizeof(cur->o_damage)); + strncpy(cur->o_hurldmg,"1x1",sizeof(cur->o_hurldmg)); + + switch (cur->o_which) + { + case WS_LIGHT: + cur->o_charges = rnd(10) + 10; + otherwise: + cur->o_charges = rnd(5) + 3; + } +} + +/* + * do_zap: + * Perform a zap with a wand + */ + +void +do_zap(struct rogue_state *rs) +{ + THING *obj, *tp; + int y, x; + char *name; + char monster, oldch; + static THING bolt; + + if ((obj = get_item(rs,"zap with", STICK)) == NULL) + return; + if (obj->o_type != STICK) + { + after = FALSE; + msg(rs,"you can't zap with that!"); + return; + } + if (obj->o_charges == 0) + { + msg(rs,"nothing happens"); + return; + } + switch (obj->o_which) + { + case WS_LIGHT: + /* + * Reddy Kilowat wand. Light up the room + */ + ws_info[WS_LIGHT].oi_know = TRUE; + if (proom->r_flags & ISGONE) + msg(rs,"the corridor glows and then fades"); + else + { + proom->r_flags &= ~ISDARK; + /* + * Light the room and put the player back up + */ + enter_room(rs,&hero); + addmsg(rs,"the room is lit"); + if (!terse) + addmsg(rs," by a shimmering %s light", pick_color("blue")); + endmsg(rs); + } + when WS_DRAIN: + /* + * take away 1/2 of hero's hit points, then take it away + * evenly from the monsters in the room (or next to hero + * if he is in a passage) + */ + if (pstats.s_hpt < 2) + { + msg(rs,"you are too weak to use it"); + return; + } + else + drain(rs); + when WS_INVIS: + case WS_POLYMORPH: + case WS_TELAWAY: + case WS_TELTO: + case WS_CANCEL: + y = hero.y; + x = hero.x; + while (step_ok(winat(y, x))) + { + y += delta.y; + x += delta.x; + } + if ((tp = moat(y, x)) != NULL) + { + monster = tp->t_type; + if (monster == 'F') + player.t_flags &= ~ISHELD; + switch (obj->o_which) { + case WS_INVIS: + tp->t_flags |= ISINVIS; + if (cansee(rs,y, x)) + mvaddch(y, x, tp->t_oldch); + break; + case WS_POLYMORPH: + { + THING *pp; + + pp = tp->t_pack; + detach(mlist, tp); + if (see_monst(tp)) + mvaddch(y, x, chat(y, x)); + oldch = tp->t_oldch; + delta.y = y; + delta.x = x; + new_monster(rs,tp, monster = (char)(rnd(26) + 'A'), &delta); + if (see_monst(tp)) + mvaddch(y, x, monster); + tp->t_oldch = oldch; + tp->t_pack = pp; + ws_info[WS_POLYMORPH].oi_know |= see_monst(tp); + break; + } + case WS_CANCEL: + tp->t_flags |= ISCANC; + tp->t_flags &= ~(ISINVIS|CANHUH); + tp->t_disguise = tp->t_type; + if (see_monst(tp)) + mvaddch(y, x, tp->t_disguise); + break; + case WS_TELAWAY: + case WS_TELTO: + { + coord new_pos; + + if (obj->o_which == WS_TELAWAY) + { + do + { + find_floor(NULL, &new_pos, FALSE, TRUE); + } while (ce(new_pos, hero)); + } + else + { + new_pos.y = hero.y + delta.y; + new_pos.x = hero.x + delta.x; + } + tp->t_dest = &hero; + tp->t_flags |= ISRUN; + relocate(rs,tp, &new_pos); + } + } + } + when WS_MISSILE: + ws_info[WS_MISSILE].oi_know = TRUE; + bolt.o_type = '*'; + strncpy(bolt.o_hurldmg,"1x4",sizeof(bolt.o_hurldmg)); + bolt.o_hplus = 100; + bolt.o_dplus = 1; + bolt.o_flags = ISMISL; + if (cur_weapon != NULL) + bolt.o_launch = cur_weapon->o_which; + do_motion(rs,&bolt, delta.y, delta.x); + if ((tp = moat(bolt.o_pos.y, bolt.o_pos.x)) != NULL + && !save_throw(VS_MAGIC, tp)) + hit_monster(rs,unc(bolt.o_pos), &bolt); + else if (terse) + msg(rs,"missle vanishes"); + else + msg(rs,"the missle vanishes with a puff of smoke"); + when WS_HASTE_M: + case WS_SLOW_M: + y = hero.y; + x = hero.x; + while (step_ok(winat(y, x))) + { + y += delta.y; + x += delta.x; + } + if ((tp = moat(y, x)) != NULL) + { + if (obj->o_which == WS_HASTE_M) + { + if (on(*tp, ISSLOW)) + tp->t_flags &= ~ISSLOW; + else + tp->t_flags |= ISHASTE; + } + else + { + if (on(*tp, ISHASTE)) + tp->t_flags &= ~ISHASTE; + else + tp->t_flags |= ISSLOW; + tp->t_turn = TRUE; + } + delta.y = y; + delta.x = x; + runto(rs,&delta); + } + when WS_ELECT: + case WS_FIRE: + case WS_COLD: + if (obj->o_which == WS_ELECT) + name = "bolt"; + else if (obj->o_which == WS_FIRE) + name = "flame"; + else + name = "ice"; + fire_bolt(rs,&hero, &delta, name); + ws_info[obj->o_which].oi_know = TRUE; + when WS_NOP: + break; +#ifdef MASTER + otherwise: + msg(rs,"what a bizarre schtick!"); +#endif + } + obj->o_charges--; +} + +/* + * drain: + * Do drain hit points from player shtick + */ + +void +drain(struct rogue_state *rs) +{ + THING *mp; + struct room *corp; + THING **dp; + int cnt; + bool inpass; + static THING *drainee[40]; + + /* + * First cnt how many things we need to spread the hit points among + */ + cnt = 0; + if (chat(hero.y, hero.x) == DOOR) + corp = &passages[flat(hero.y, hero.x) & F_PNUM]; + else + corp = NULL; + inpass = (bool)(proom->r_flags & ISGONE); + dp = drainee; + for (mp = mlist; mp != NULL; mp = next(mp)) + if (mp->t_room == proom || mp->t_room == corp || + (inpass && chat(mp->t_pos.y, mp->t_pos.x) == DOOR && + &passages[flat(mp->t_pos.y, mp->t_pos.x) & F_PNUM] == proom)) + *dp++ = mp; + if ((cnt = (int)(dp - drainee)) == 0) + { + msg(rs,"you have a tingling feeling"); + return; + } + *dp = NULL; + pstats.s_hpt /= 2; + cnt = pstats.s_hpt / cnt; + /* + * Now zot all of the monsters + */ + for (dp = drainee; *dp; dp++) + { + mp = *dp; + if ((mp->t_stats.s_hpt -= cnt) <= 0) + killed(rs,mp, see_monst(mp)); + else + runto(rs,&mp->t_pos); + } +} + +/* + * fire_bolt: + * Fire a bolt in a given direction from a specific starting place + */ + +void +fire_bolt(struct rogue_state *rs,coord *start, coord *dir, char *name) +{ + coord *c1, *c2; + THING *tp; + char dirch = 0, ch; + bool hit_hero, used, changed; + static coord pos; + static coord spotpos[BOLT_LENGTH]; + THING bolt; + + bolt.o_type = WEAPON; + bolt.o_which = FLAME; + strncpy(bolt.o_hurldmg,"6x6",sizeof(bolt.o_hurldmg)); + bolt.o_hplus = 100; + bolt.o_dplus = 0; + weap_info[FLAME].oi_name = name; + switch (dir->y + dir->x) + { + case 0: dirch = '/'; + when 1: case -1: dirch = (dir->y == 0 ? '-' : '|'); + when 2: case -2: dirch = '\\'; + } + pos = *start; + hit_hero = (bool)(start != &hero); + used = FALSE; + changed = FALSE; + for (c1 = spotpos; c1 <= &spotpos[BOLT_LENGTH-1] && !used; c1++) + { + pos.y += dir->y; + pos.x += dir->x; + *c1 = pos; + ch = winat(pos.y, pos.x); + switch (ch) + { + case DOOR: + /* + * this code is necessary if the hero is on a door + * and he fires at the wall the door is in, it would + * otherwise loop infinitely + */ + if (ce(hero, pos)) + goto def; + /* FALLTHROUGH */ + case '|': + case '-': + case ' ': + if (!changed) + hit_hero = !hit_hero; + changed = FALSE; + dir->y = -dir->y; + dir->x = -dir->x; + c1--; + msg(rs,"the %s bounces", name); + break; + default: +def: + if (!hit_hero && (tp = moat(pos.y, pos.x)) != NULL) + { + hit_hero = TRUE; + changed = !changed; + tp->t_oldch = chat(pos.y, pos.x); + if (!save_throw(VS_MAGIC, tp)) + { + bolt.o_pos = pos; + used = TRUE; + if (tp->t_type == 'D' && strcmp(name, "flame") == 0) + { + addmsg(rs,"the flame bounces"); + if (!terse) + addmsg(rs," off the dragon"); + endmsg(rs); + } + else + hit_monster(rs,unc(pos), &bolt); + } + else if (ch != 'M' || tp->t_disguise == 'M') + { + if (start == &hero) + runto(rs,&pos); + if (terse) + msg(rs,"%s misses", name); + else + msg(rs,"the %s whizzes past %s", name, set_mname(tp)); + } + } + else if (hit_hero && ce(pos, hero)) + { + hit_hero = FALSE; + changed = !changed; + if (!save(VS_MAGIC)) + { + if ((pstats.s_hpt -= roll(6, 6)) <= 0) + { + if (start == &hero) + death('b'); + else + death(moat(start->y, start->x)->t_type); + } + used = TRUE; + if (terse) + msg(rs,"the %s hits", name); + else + msg(rs,"you are hit by the %s", name); + } + else + msg(rs,"the %s whizzes by you", name); + } + mvaddch(pos.y, pos.x, dirch); + refresh(); + } + } + for (c2 = spotpos; c2 < c1; c2++) + mvaddch(c2->y, c2->x, chat(c2->y, c2->x)); +} + +/* + * charge_str: + * Return an appropriate string for a wand charge + */ +char * +charge_str(THING *obj) +{ + static char buf[20]; + + if (!(obj->o_flags & ISKNOW)) + buf[0] = '\0'; + else if (terse) + sprintf(buf, " [%d]", obj->o_charges); + else + sprintf(buf, " [%d charges]", obj->o_charges); + return buf; +} diff --git a/src/cc/rogue/test.zip b/src/cc/rogue/test.zip new file mode 100644 index 0000000000000000000000000000000000000000..b0c54f6d0403f64cc535b2bc756a3d75da122cae GIT binary patch literal 5451 zcmZ{oRa6uVw}yup7)lUH>FzFR0qI6M1VtEhC<%vdq@|JWmJZ3Gr3M(fO9|-~7zUX0 zedoVB>-_s>?|t#U@7>;OJ$jm0*kk|z00gjTk=Oa+dD9s8&+1tT0FVJ_0Y>h2Zten3 zZ*2wKT)>`o{O)f*+Zh?+0kGas8Cnuh8(MmL5dbi-uQ33C|8+UG!jmC$q7n#mAh7RfkNucsgzRU=kJ;{Y06`TD>HRzsviWuu-W! zTP)yVBg22!I}h1CBy-u>*r@9+jC6mX{E}cLpQgM{$WlY*@SN9l?=n7drAzva0TG3y zRE;w;ZO46X8U93to24b$i`9ft7|RlypFk}x68jI^i6<0J41(LitV=)N6rBgT&HNQG z@fP2!XZW+J?b!J^C@x>Or(U=)y!k6x#Qy^ODCiNyhfa`Hgi}a~Kf%Pfe=7ah zu{mP1!W%HG?VORivC!N>fN9h}p3Jc_q?PZcyLL7JU+RvVRZBNq(<@OwC#iS{BUlP$ zG}!-UJ~lBQojVNRC^tM)YOXXaMt@wKd3XpE`o*98?AF0j)KOHWh! z0-AR{R!qG%l-5-#6N0|YkCrQ#2|=A+9`Kg2{qdl1L#tI zga~+jy0(pi0?B(jvb+ab+2f>8a;6h5%iGfEq$7IrTW70JSw4fib5n439}IIPr3Gs- zajU|*PnD>u=y0J%^?_l3$$Hg~OU;i)63MqV{>M3&lG-|X{VvEY8v5FeKo+ezm9sG< zxpwYfPv>?NSb~Zq=gNg#3)UT!T;(UMMvbyAvBJ`FP z==0;jX7hYt*%tQ#ANP7RlaeNcb|h*3D%`?3Y4ytzh%gK0_~XoQ`K#@>5#Uswef#@k z$|LVmB&?YqE!q;a z)l>Sdmv}XIlVi+SC7pQ#KO8UA7wFSJQtd^Wb-is_lgQihW+s!?T2n5%0I*v@b?y9xl(&&#AY$RY{Cp_o$d4S ze49u1pgps27nP!l@_HJEU0AcPhXC_@jeRjN$<3czhpa%L4&nn$5IFGN4=ME7?bAc4 z3LMS`(HE@&M;G6Z0++0JiF3qiJQf#+pDDS^qzsYY9n;AD9wpFh-nY+McS3TwOru_? zB>ge$Wy_NjC&+fpRQ@2$uqS(Pn7!wD5jr=ZWhWk!K_(#|S#F6sDBLM!oPs3p7=w0G z<7(PvhhS`C4?mBbtKztyF}!JSIGh@~6TwE{)!w ztnPOVtdFL-mXwme{>XijLc{ONJdo^rHZ|>Cdx|;-a&PeIk5Ty1x^8wh4ZTR5G;s;Z zI#kY-5zXzkaiGh9?l--kZ+fvZD!sas8aDprnWv~Wd?!xCn;v()Pw?`Y^b04WE?k0Tv%htr=?1aTIqhmD?*uj($6XES*|MZr^|4bd=Tp4 z?w}Pivf^fWsu^2C*##4xdL4}F?G0)#ru_TVr^UbUvzPpgm~INmQ_iJ~TDa1P`-^n8|bH7Zzy9B4N6Z(tW_A~l^j zG+q>y_lu1(F0m4{TR7(uRb*aU-8?!OMV7e{w+`Wx5<;qt1f?Vo;} z9%GQBno1xMANkzztB++xqQ+F2_j$AXZ~*!EqGD0SH9K6g)^NeSeRsaLuB0_Hr_EkU zN=E+fJG_9T!KKgmH@G0tt-eU^WU;2R_bbQjgxc?Mk(%Re0`)xnY35z=df*PHv*wG} zQ0YgX=sA6E^qZvNCjW~YovN!OsGx>leYwy4`OJv~&w8pWKef@7qiw4B)htx85(5VU zCc&X}EHTxwXxwVVG&^{p%8c_-EV7AZx6-lHw8v{%(1$v&AODVj_ZbM9&&smuWVg@G z|1(+y{(JwEuFQ_+=aai5Gh1?S{jNd6)l7s5KPRyksT30zHwjFCtv^Xm*V|tbUSK}9 zul6&L2tk_+=wp@ti5z zn!2!R)A#ZdZybKe3HeQA2wyG>Cx#Jg4?gSDE_3SQItmom)tim+|FF7LHfL>FqH$Tq zTVo?3JZ|E>S6kr8S(Hd&A>cym?>o#_qS+#<$n8l$v(^0NFowr5CPwsAX9w8mQ#xD{ zwS6@G0n$QT=%raM)#+IitA|%?P^rjO8(;C}I$GNMux{q}(DmOb>L12Qq{X|wVvf$= zWk(VGYUpz55jW3CS0|#P<+vDz1Y{*tuIX3N#weg)fMq0bi5{nvB;3xbuL+rBM;UH&>yzU*d9MfSl zynl5#^8gOX+ELa9Z%~PRRCnUT4Yv5nx$#y2H9iyU11wGtUWYdEts|-QbBRRYsqA}U zlHj{kcR#Yl4o)XGyCma-$jHSwb%k#_@=5X&X1?E)ez{x9j@X|qb0qzgfX7~%h_c;j z#ip4Euxf1h+y~ur+A;q%=q>1{LEzBU(vnq;ws9@bN^Bvmm>vx%<9`Dt0-t%6(h|() zZhHOwS`knW(dgYm;5E3ez6{#JB;nXo(hIQ#kx1_;Oa|Ei6zIQl&DzA4yK{eQW_qsB z0Vw67P!Dd%6u-Qa1d&&Pp%BTJLvI6 z273`wr6H@#&3lfa+#Bp6YMqxg6ufli-7vY$JDN*%19c|x2OS-h4Wxw7rDrA0OcpSrvr#??V zuZ^URI(xu$wA=Lm;KdVf?i*5#-#Hi3^6|`=V*Q}c0@x~tS-kF0%)brIp21~BM(ibV z=DBuz$|{-XH*{Xu{mjKBf!M=YDJE^k^%Fd9PV2=HiiT3nty$Hw^61nFOyV;1!IDkx*5N2m;Yyuyhu8oQ`c54c0|dgP=q z-9CwIlTMESrkme#`ix}^Y~#wLV!xK5(4;TsvtlCR5K3E)P-eGKvA|$4aP1&7U)~$; zBXPP_B{Ua|8+%2az4TEJtN+3mC;0Jwl>%2f6Y<9yCMp6GMY(4-#(?ML{(=q~XL#NP z$AVIqm>(-}b(q!N9b}mrbb~mg-dR3%cPj?kP@GMzq><-5XMGG(5Kk|_S!SFjT9i9+ z)F>cwE3~+TDJY@Bz7mEgxQE7vJ~|0;4hmP>KNvE&DOfN_&2TjdA36NC<>6nN~CD}ji1Al1GZlRj2L z5T5?D^!1tgao-iArb7AFG^{ZVhLAf+++CW7p7i4#3yBk%)lqBLW%e zKWK<5N-^qk2zf(@#^7UXvy#jwK0~J=J|Oa7R!bfC(x;cXe>MVA0_Ov)H__79E0^H3 zZ1#uvz&~l99$%pIb~e@?yHU3{TK{@%-Dixo#rD`HJPzm0kfd}ops$Qa0`DXae&2UQ zqHCKATW(vryG3e49)-~z++BVD2-;ARfl~n!-RKF1nt%y3^sXD4cfWPNa(Oxe{;@XH z4bEMh+b)Pi(&%gX!OKi&^#iTKB%TLud`kkC1Eyi;^nPxqyf zpY<-<2{m9H&^0A-i^jWdyORuDm2+ljiC;lC9=l(;KeqZeJ)FFe|IC0s;qT}OJiE~4 z3*^4RRtqSNyz6biKe!ow$EOm6=P$)gtRV3c_Yv7d?`OY_dt}Kslqf4^`pltjMp}pE z>^l_(G>yWKo{0hn+Y~E{vyi9YN&JA014uyeCBsZUbir(DvrHrzenpR!aH-gCLd`g` z*XubI5D@ImsN|COshFo%8*IO-7f#K%&pvBG?K&wvF*0RD5{v-VsJQYmQj4-$P=jXl zxdhuW)O-dfJZ630%Xv%yZg~eJm~$(@)IlOFT~DdW-v@ZyXgM8X4bVVa;*Y*x0>D8c zJ=9l3I0N)=^FhERKJ)@zb_s5jWg_d#%@a0t_i{bM&tRODS1H0t)2ehOV@X_~YC;*Q zBr@U>%Yx#gK8OJ<*+{Y^o%&Q{0V7hF+TeOetWt;5R$qmK_l}<^L01=}Kcgc$rD!qn zVnI_2=;0DMMax5$Vztau)F@N%0;+|jp9DVs^EFk%+ScC5Scyw>%06JKh(x(tlCui- zYqs7ltOYaXV(e?`cN=97m)Jr{1=z1qNF<$t^Wp`u7|A}7*d4J)jukEo=XEvCXkT>I zYY*{s&*RjcUxW4Bi2X(3X@aW$<6EbRkH_rt?s7E7r|*o`LGf>d;M*<1DgKN*UdDE4 zzj?y-GmyBano{<9TJ}W;QB!`4UGu%Oyk@VlnX2oP0dHqtJF!-jDVWZ_)rir~_2Xua zX=j?Cu^=T6s1KjwEilbA7-$U8A--jjRJR}wnk%6&XAGYMjBE}T0x$F5(Wlvf%ixF&oZuDnSPiDZa>jyG5C}-7y&Cf@jP)5G$xnR0f<9Wlv(RYLrkEmlK&0+Xfz@}wv`a{@WW%Obqwuug= zxy|g9qiF=i**lBzC~`F$AoC&;6K8{(FFl^lPmm_8u91n9&otVJfL!`EzsPhqTa3=V z1jB$gSr2$Em|sLTiQCio(yZwvfCm7PPm3+E5wGLL^smQO$eKjHw8)%vR%`@C?h%7* z1^eylw1s+&ff>QFlQXYqcqV)Cd!jS#6hjI8`IgHCuX!0=D&*TWs0;~T5h&Ih^?1U_ zsxfeM@K=bI9f%~$=Z4WvVKNE8`dpk!)kMT_+v>g(6uj-#adHpu^}8P@+^1s%1OoXB z&Pmv3GNQaVUNR~OhTExyyh*^JTusk@i=_3+Bbo<#R&63S)2YL_NbLLWj_Twlv%;kq zp3uJVVZdsqg01Ct)4i9P`E%E2A=)aHz?8lb9J`9UeA$9Ut&6>h7wy2YwMcz-e&p}^ z_51iVT6O{joWSeKkiNRk4M2m{oWX`PM7w zCjLljv+tVj@!zzm)LRBUO$ +#include +#include +#include "rogue.h" + +/* + * inv_name: + * Return the name of something as it would appear in an + * inventory. + */ +char * +inv_name(THING *obj, bool drop) +{ + char *pb; + struct obj_info *op; + char *sp; + int which; + + pb = prbuf; + which = obj->o_which; + switch (obj->o_type) + { + case POTION: + nameit(obj, "potion", p_colors[which], &pot_info[which], nullstr); + when RING: + nameit(obj, "ring", r_stones[which], &ring_info[which], ring_num); + when STICK: + nameit(obj, ws_type[which], ws_made[which], &ws_info[which], charge_str); + when SCROLL: + if (obj->o_count == 1) + { + strcpy(pb, "A scroll "); + pb = &prbuf[9]; + } + else + { + sprintf(pb, "%d scrolls ", obj->o_count); + pb = &prbuf[strlen(prbuf)]; + } + op = &scr_info[which]; + if (op->oi_know) + sprintf(pb, "of %s", op->oi_name); + else if (op->oi_guess) + sprintf(pb, "called %s", op->oi_guess); + else + sprintf(pb, "titled '%s'", s_names[which]); + when FOOD: + if (which == 1) + if (obj->o_count == 1) + sprintf(pb, "A%s %s", vowelstr(fruit), fruit); + else + sprintf(pb, "%d %ss", obj->o_count, fruit); + else + if (obj->o_count == 1) + strcpy(pb, "Some food"); + else + sprintf(pb, "%d rations of food", obj->o_count); + when WEAPON: + sp = weap_info[which].oi_name; + if (obj->o_count > 1) + sprintf(pb, "%d ", obj->o_count); + else + sprintf(pb, "A%s ", vowelstr(sp)); + pb = &prbuf[strlen(prbuf)]; + if (obj->o_flags & ISKNOW) + sprintf(pb, "%s %s", num(obj->o_hplus,obj->o_dplus,WEAPON), sp); + else + sprintf(pb, "%s", sp); + if (obj->o_count > 1) + strcat(pb, "s"); + if (obj->o_label != NULL) + { + pb = &prbuf[strlen(prbuf)]; + sprintf(pb, " called %s", obj->o_label); + } + when ARMOR: + sp = arm_info[which].oi_name; + if (obj->o_flags & ISKNOW) + { + sprintf(pb, "%s %s [", + num(a_class[which] - obj->o_arm, 0, ARMOR), sp); + if (!terse) + strcat(pb, "protection "); + pb = &prbuf[strlen(prbuf)]; + sprintf(pb, "%d]", 10 - obj->o_arm); + } + else + sprintf(pb, "%s", sp); + if (obj->o_label != NULL) + { + pb = &prbuf[strlen(prbuf)]; + sprintf(pb, " called %s", obj->o_label); + } + when AMULET: + strcpy(pb, "The Amulet of Yendor"); + when GOLD: + sprintf(prbuf, "%d Gold pieces", obj->o_goldval); +#ifdef MASTER + otherwise: + debug("Picked up something funny %s", unctrl(obj->o_type)); + sprintf(pb, "Something bizarre %s", unctrl(obj->o_type)); +#endif + } + if (inv_describe) + { + if (obj == cur_armor) + strcat(pb, " (being worn)"); + if (obj == cur_weapon) + strcat(pb, " (weapon in hand)"); + if (obj == cur_ring[LEFT]) + strcat(pb, " (on left hand)"); + else if (obj == cur_ring[RIGHT]) + strcat(pb, " (on right hand)"); + } + if (drop && isupper(prbuf[0])) + prbuf[0] = (char) tolower(prbuf[0]); + else if (!drop && islower(*prbuf)) + *prbuf = (char) toupper(*prbuf); + prbuf[MAXSTR-1] = '\0'; + return prbuf; +} + +/* + * drop: + * Put something down + */ + +void +drop(struct rogue_state *rs) +{ + char ch; + THING *obj; + + ch = chat(hero.y, hero.x); + if (ch != FLOOR && ch != PASSAGE) + { + after = FALSE; + msg(rs,"there is something there already"); + return; + } + if ((obj = get_item(rs,"drop", 0)) == NULL) + return; + if (!dropcheck(rs,obj)) + return; + obj = leave_pack(rs,obj, TRUE, (bool)!ISMULT(obj->o_type)); + /* + * Link it into the level object list + */ + attach(lvl_obj, obj); + chat(hero.y, hero.x) = (char) obj->o_type; + flat(hero.y, hero.x) |= F_DROPPED; + obj->o_pos = hero; + if (obj->o_type == AMULET) + amulet = FALSE; + msg(rs,"dropped %s", inv_name(obj, TRUE)); +} + +/* + * dropcheck: + * Do special checks for dropping or unweilding|unwearing|unringing + */ +bool +dropcheck(struct rogue_state *rs,THING *obj) +{ + if (obj == NULL) + return TRUE; + if (obj != cur_armor && obj != cur_weapon + && obj != cur_ring[LEFT] && obj != cur_ring[RIGHT]) + return TRUE; + if (obj->o_flags & ISCURSED) + { + msg(rs,"you can't. It appears to be cursed"); + return FALSE; + } + if (obj == cur_weapon) + cur_weapon = NULL; + else if (obj == cur_armor) + { + waste_time(rs); + cur_armor = NULL; + } + else + { + cur_ring[obj == cur_ring[LEFT] ? LEFT : RIGHT] = NULL; + switch (obj->o_which) + { + case R_ADDSTR: + chg_str(-obj->o_arm); + break; + case R_SEEINVIS: + unsee(rs,0); + extinguish(unsee); + break; + } + } + return TRUE; +} + +/* + * new_thing: + * Return a new thing + */ +THING * +new_thing(struct rogue_state *rs) +{ + THING *cur; + int r; + + cur = new_item(); + cur->o_hplus = 0; + cur->o_dplus = 0; + strncpy(cur->o_damage, "0x0", sizeof(cur->o_damage)); + strncpy(cur->o_hurldmg, "0x0", sizeof(cur->o_hurldmg)); + cur->o_arm = 11; + cur->o_count = 1; + cur->o_group = 0; + cur->o_flags = 0; + /* + * Decide what kind of object it will be + * If we haven't had food for a while, let it be food. + */ + switch (no_food > 3 ? 2 : pick_one(rs,things, NUMTHINGS)) + { + case 0: + cur->o_type = POTION; + cur->o_which = pick_one(rs,pot_info, MAXPOTIONS); + when 1: + cur->o_type = SCROLL; + cur->o_which = pick_one(rs,scr_info, MAXSCROLLS); + when 2: + cur->o_type = FOOD; + no_food = 0; + if (rnd(10) != 0) + cur->o_which = 0; + else + cur->o_which = 1; + when 3: + init_weapon(cur, pick_one(rs,weap_info, MAXWEAPONS)); + if ((r = rnd(100)) < 10) + { + cur->o_flags |= ISCURSED; + cur->o_hplus -= rnd(3) + 1; + } + else if (r < 15) + cur->o_hplus += rnd(3) + 1; + when 4: + cur->o_type = ARMOR; + cur->o_which = pick_one(rs,arm_info, MAXARMORS); + cur->o_arm = a_class[cur->o_which]; + if ((r = rnd(100)) < 20) + { + cur->o_flags |= ISCURSED; + cur->o_arm += rnd(3) + 1; + } + else if (r < 28) + cur->o_arm -= rnd(3) + 1; + when 5: + cur->o_type = RING; + cur->o_which = pick_one(rs,ring_info, MAXRINGS); + switch (cur->o_which) + { + case R_ADDSTR: + case R_PROTECT: + case R_ADDHIT: + case R_ADDDAM: + if ((cur->o_arm = rnd(3)) == 0) + { + cur->o_arm = -1; + cur->o_flags |= ISCURSED; + } + when R_AGGR: + case R_TELEPORT: + cur->o_flags |= ISCURSED; + } + when 6: + cur->o_type = STICK; + cur->o_which = pick_one(rs,ws_info, MAXSTICKS); + fix_stick(cur); +#ifdef MASTER + otherwise: + debug("Picked a bad kind of object"); + wait_for(rs,' '); +#endif + } + return cur; +} + +/* + * pick_one: + * Pick an item out of a list of nitems possible objects + */ +int +pick_one(struct rogue_state *rs,struct obj_info *info, int nitems) +{ + struct obj_info *end; + struct obj_info *start; + int i; + + start = info; + for (end = &info[nitems], i = rnd(100); info < end; info++) + if (i < info->oi_prob) + break; + if (info == end) + { +#ifdef MASTER + if (wizard) + { + msg(rs,"bad pick_one: %d from %d items", i, nitems); + for (info = start; info < end; info++) + msg(rs,"%s: %d%%", info->oi_name, info->oi_prob); + } +#endif + info = start; + } + return (int)(info - start); +} + +/* + * discovered: + * list what the player has discovered in this game of a certain type + */ +static int line_cnt = 0; + +static bool newpage = FALSE; + +static char *lastfmt, *lastarg; + + +void +discovered(struct rogue_state *rs) +{ + char ch; + bool disc_list; + + do { + disc_list = FALSE; + if (!terse) + addmsg(rs,"for "); + addmsg(rs,"what type"); + if (!terse) + addmsg(rs," of object do you want a list"); + msg(rs,"? (* for all)"); + ch = readchar(rs); + switch (ch) + { + case ESCAPE: + msg(rs,""); + return; + case POTION: + case SCROLL: + case RING: + case STICK: + case '*': + disc_list = TRUE; + break; + default: + if (terse) + msg(rs,"Not a type"); + else + msg(rs,"Please type one of %c%c%c%c (ESCAPE to quit)", POTION, SCROLL, RING, STICK); + } + } while (!disc_list); + if (ch == '*') + { + print_disc(rs,POTION); + add_line(rs,"", NULL); + print_disc(rs,SCROLL); + add_line(rs,"", NULL); + print_disc(rs,RING); + add_line(rs,"", NULL); + print_disc(rs,STICK); + end_line(rs); + } + else + { + print_disc(rs,ch); + end_line(rs); + } +} + +/* + * print_disc: + * Print what we've discovered of type 'type' + */ + +#define MAX4(a,b,c,d) (a > b ? (a > c ? (a > d ? a : d) : (c > d ? c : d)) : (b > c ? (b > d ? b : d) : (c > d ? c : d))) + + +void +print_disc(struct rogue_state *rs,char type) +{ + struct obj_info *info = NULL; + int i, maxnum = 0, num_found; + static THING obj; + static int order[MAX4(MAXSCROLLS, MAXPOTIONS, MAXRINGS, MAXSTICKS)]; + + switch (type) + { + case SCROLL: + maxnum = MAXSCROLLS; + info = scr_info; + break; + case POTION: + maxnum = MAXPOTIONS; + info = pot_info; + break; + case RING: + maxnum = MAXRINGS; + info = ring_info; + break; + case STICK: + maxnum = MAXSTICKS; + info = ws_info; + break; + } + set_order(order, maxnum); + obj.o_count = 1; + obj.o_flags = 0; + num_found = 0; + for (i = 0; i < maxnum; i++) + if (info[order[i]].oi_know || info[order[i]].oi_guess) + { + obj.o_type = type; + obj.o_which = order[i]; + add_line(rs,"%s", inv_name(&obj, FALSE)); + num_found++; + } + if (num_found == 0) + add_line(rs,nothing(type), NULL); +} + +/* + * set_order: + * Set up order for list + */ + +void +set_order(int *order, int numthings) +{ + int i, r, t; + + for (i = 0; i< numthings; i++) + order[i] = i; + + for (i = numthings; i > 0; i--) + { + r = rnd(i); + t = order[i - 1]; + order[i - 1] = order[r]; + order[r] = t; + } +} + +/* + * add_line: + * Add a line to the list of discoveries + */ +/* VARARGS1 */ +char +add_line(struct rogue_state *rs,char *fmt, char *arg) +{ + WINDOW *tw, *sw; + int x, y; + char *prompt = "--Press space to continue--"; + static int maxlen = -1; + + if (line_cnt == 0) + { + wclear(hw); + if (inv_type == INV_SLOW) + mpos = 0; + } + if (inv_type == INV_SLOW) + { + if (*fmt != '\0') + if (msg(rs,fmt, arg) == ESCAPE) + return ESCAPE; + line_cnt++; + } + else + { + if (maxlen < 0) + maxlen = (int) strlen(prompt); + if (line_cnt >= LINES - 1 || fmt == NULL) + { + if (inv_type == INV_OVER && fmt == NULL && !newpage) + { + msg(rs,""); + refresh(); + tw = newwin(line_cnt + 1, maxlen + 2, 0, COLS - maxlen - 3); + sw = subwin(tw, line_cnt + 1, maxlen + 1, 0, COLS - maxlen - 2); + for (y = 0; y <= line_cnt; y++) + { + wmove(sw, y, 0); + for (x = 0; x <= maxlen; x++) + waddch(sw, mvwinch(hw, y, x)); + } + wmove(tw, line_cnt, 1); + waddstr(tw, prompt); + /* + * if there are lines below, use 'em + */ + if (LINES > NUMLINES) + { + if (NUMLINES + line_cnt > LINES) + mvwin(tw, LINES - (line_cnt + 1), COLS - maxlen - 3); + else + mvwin(tw, NUMLINES, 0); + } + touchwin(tw); + wrefresh(tw); + wait_for(rs,' '); + if (md_hasclreol()) + { + werase(tw); + leaveok(tw, TRUE); + wrefresh(tw); + } + delwin(tw); + touchwin(stdscr); + } + else + { + wmove(hw, LINES - 1, 0); + waddstr(hw, prompt); + wrefresh(hw); + wait_for(rs,' '); + clearok(curscr, TRUE); + wclear(hw); + touchwin(stdscr); + } + newpage = TRUE; + line_cnt = 0; + maxlen = (int) strlen(prompt); + } + if (fmt != NULL && !(line_cnt == 0 && *fmt == '\0')) + { + mvwprintw(hw, line_cnt++, 0, fmt, arg); + getyx(hw, y, x); + if (maxlen < x) + maxlen = x; + lastfmt = fmt; + lastarg = arg; + } + } + return ~ESCAPE; +} + +/* + * end_line: + * End the list of lines + */ + +void +end_line(struct rogue_state *rs) +{ + if (inv_type != INV_SLOW) + { + if (line_cnt == 1 && !newpage) + { + mpos = 0; + msg(rs,lastfmt, lastarg); + } + else + add_line(rs,(char *) NULL, NULL); + } + line_cnt = 0; + newpage = FALSE; +} + +/* + * nothing: + * Set up prbuf so that message for "nothing found" is there + */ +char * +nothing(char type) +{ + char *sp, *tystr = NULL; + + if (terse) + sprintf(prbuf, "Nothing"); + else + sprintf(prbuf, "Haven't discovered anything"); + if (type != '*') + { + sp = &prbuf[strlen(prbuf)]; + switch (type) + { + case POTION: tystr = "potion"; + when SCROLL: tystr = "scroll"; + when RING: tystr = "ring"; + when STICK: tystr = "stick"; + } + sprintf(sp, " about any %ss", tystr); + } + return prbuf; +} + +/* + * nameit: + * Give the proper name to a potion, stick, or ring + */ + +void +nameit(THING *obj, char *type, char *which, struct obj_info *op, + char *(*prfunc)(THING *)) +{ + char *pb; + + if (op->oi_know || op->oi_guess) + { + if (obj->o_count == 1) + sprintf(prbuf, "A %s ", type); + else + sprintf(prbuf, "%d %ss ", obj->o_count, type); + pb = &prbuf[strlen(prbuf)]; + if (op->oi_know) + sprintf(pb, "of %s%s(%s)", op->oi_name, (*prfunc)(obj), which); + else if (op->oi_guess) + sprintf(pb, "called %s%s(%s)", op->oi_guess, (*prfunc)(obj), which); + } + else if (obj->o_count == 1) + sprintf(prbuf, "A%s %s %s", vowelstr(which), which, type); + else + sprintf(prbuf, "%d %s %ss", obj->o_count, which, type); +} + +/* + * nullstr: + * Return a pointer to a null-length string + */ +char * +nullstr(THING *ignored) +{ + NOOP(ignored); + return ""; +} + +# ifdef MASTER +/* + * pr_list: + * List possible potions, scrolls, etc. for wizard. + */ + +void +pr_list(struct rogue_state *rs) +{ + int ch; + + if (!terse) + addmsg(rs,"for "); + addmsg(rs,"what type"); + if (!terse) + addmsg(rs," of object do you want a list"); + msg(rs,"? "); + ch = readchar(rs); + switch (ch) + { + case POTION: + pr_spec(pot_info, MAXPOTIONS); + when SCROLL: + pr_spec(scr_info, MAXSCROLLS); + when RING: + pr_spec(ring_info, MAXRINGS); + when STICK: + pr_spec(ws_info, MAXSTICKS); + when ARMOR: + pr_spec(arm_info, MAXARMORS); + when WEAPON: + pr_spec(weap_info, MAXWEAPONS); + otherwise: + return; + } +} + +/* + * pr_spec: + * Print specific list of possible items to choose from + */ + +void +pr_spec(struct rogue_state *rs,struct obj_info *info, int nitems) +{ + struct obj_info *endp; + int i, lastprob; + + endp = &info[nitems]; + lastprob = 0; + for (i = '0'; info < endp; i++) + { + if (i == '9' + 1) + i = 'a'; + sprintf(prbuf, "%c: %%s (%d%%%%)", i, info->oi_prob - lastprob); + lastprob = info->oi_prob; + add_line(rs,prbuf, info->oi_name); + info++; + } + end_line(rs); +} +# endif /* MASTER */ diff --git a/src/cc/rogue/vers.c b/src/cc/rogue/vers.c new file mode 100644 index 000000000..dcca986b1 --- /dev/null +++ b/src/cc/rogue/vers.c @@ -0,0 +1,17 @@ +/* + * Version number. Whenever a new version number is desired, use sccs + * to get vers.c. encstr is declared here to force it to be loaded + * before the version number, and therefore not to be written in saved + * games. + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +char *release = "5.4.4"; +char encstr[] = "\300k||`\251Y.'\305\321\201+\277~r\"]\240_\223=1\341)\222\212\241t;\t$\270\314/<#\201\254"; +char statlist[] = "\355kl{+\204\255\313idJ\361\214=4:\311\271\341wK<\312\321\213,,7\271/Rk%\b\312\f\246"; +char version[] = "rogue (rogueforge) 09/05/07"; diff --git a/src/cc/rogue/weapons.c b/src/cc/rogue/weapons.c new file mode 100644 index 000000000..51a4b7730 --- /dev/null +++ b/src/cc/rogue/weapons.c @@ -0,0 +1,288 @@ +/* + * Functions for dealing with problems brought about by weapons + * + * @(#)weapons.c 4.34 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include +#include "rogue.h" + +#define NO_WEAPON -1 + +int group = 2; + +static struct init_weaps { + char *iw_dam; /* Damage when wielded */ + char *iw_hrl; /* Damage when thrown */ + char iw_launch; /* Launching weapon */ + int iw_flags; /* Miscellaneous flags */ +} init_dam[MAXWEAPONS] = { + { "2x4", "1x3", NO_WEAPON, 0, }, /* Mace */ + { "3x4", "1x2", NO_WEAPON, 0, }, /* Long sword */ + { "1x1", "1x1", NO_WEAPON, 0, }, /* Bow */ + { "1x1", "2x3", BOW, ISMANY|ISMISL, }, /* Arrow */ + { "1x6", "1x4", NO_WEAPON, ISMISL|ISMISL, }, /* Dagger */ + { "4x4", "1x2", NO_WEAPON, 0, }, /* 2h sword */ + { "1x1", "1x3", NO_WEAPON, ISMANY|ISMISL, }, /* Dart */ + { "1x2", "2x4", NO_WEAPON, ISMANY|ISMISL, }, /* Shuriken */ + { "2x3", "1x6", NO_WEAPON, ISMISL, }, /* Spear */ +}; + +/* + * missile: + * Fire a missile in a given direction + */ + +void +missile(struct rogue_state *rs,int ydelta, int xdelta) +{ + THING *obj; + + /* + * Get which thing we are hurling + */ + if ((obj = get_item(rs,"throw", WEAPON)) == NULL) + return; + if (!dropcheck(rs,obj) || is_current(rs,obj)) + return; + obj = leave_pack(rs,obj, TRUE, FALSE); + do_motion(rs,obj, ydelta, xdelta); + /* + * AHA! Here it has hit something. If it is a wall or a door, + * or if it misses (combat) the monster, put it on the floor + */ + if (moat(obj->o_pos.y, obj->o_pos.x) == NULL || + !hit_monster(rs,unc(obj->o_pos), obj)) + fall(rs,obj, TRUE); +} + +/* + * do_motion: + * Do the actual motion on the screen done by an object traveling + * across the room + */ + +void +do_motion(struct rogue_state *rs,THING *obj, int ydelta, int xdelta) +{ + int ch; + + /* + * Come fly with us ... + */ + obj->o_pos = hero; + for (;;) + { + /* + * Erase the old one + */ + if (!ce(obj->o_pos, hero) && cansee(rs,unc(obj->o_pos)) && !terse) + { + ch = chat(obj->o_pos.y, obj->o_pos.x); + if (ch == FLOOR && !show_floor()) + ch = ' '; + mvaddch(obj->o_pos.y, obj->o_pos.x, ch); + } + /* + * Get the new position + */ + obj->o_pos.y += ydelta; + obj->o_pos.x += xdelta; + if (step_ok(ch = winat(obj->o_pos.y, obj->o_pos.x)) && ch != DOOR) + { + /* + * It hasn't hit anything yet, so display it + * If it alright. + */ + if (cansee(rs,unc(obj->o_pos)) && !terse) + { + mvaddch(obj->o_pos.y, obj->o_pos.x, obj->o_type); + refresh(); + } + continue; + } + break; + } +} + +/* + * fall: + * Drop an item someplace around here. + */ + +void +fall(struct rogue_state *rs,THING *obj, bool pr) +{ + PLACE *pp; + static coord fpos; + + if (fallpos(&obj->o_pos, &fpos)) + { + pp = INDEX(fpos.y, fpos.x); + pp->p_ch = (char) obj->o_type; + obj->o_pos = fpos; + if (cansee(rs,fpos.y, fpos.x)) + { + if (pp->p_monst != NULL) + pp->p_monst->t_oldch = (char) obj->o_type; + else + mvaddch(fpos.y, fpos.x, obj->o_type); + } + attach(lvl_obj, obj); + return; + } + if (pr) + { + if (has_hit) + { + endmsg(rs); + has_hit = FALSE; + } + msg(rs,"the %s vanishes as it hits the ground", + weap_info[obj->o_which].oi_name); + } + discard(obj); +} + +/* + * init_weapon: + * Set up the initial goodies for a weapon + */ + +void +init_weapon(THING *weap, int which) +{ + struct init_weaps *iwp; + + weap->o_type = WEAPON; + weap->o_which = which; + iwp = &init_dam[which]; + strncpy(weap->o_damage, iwp->iw_dam, sizeof(weap->o_damage)); + strncpy(weap->o_hurldmg,iwp->iw_hrl, sizeof(weap->o_hurldmg)); + weap->o_launch = iwp->iw_launch; + weap->o_flags = iwp->iw_flags; + weap->o_hplus = 0; + weap->o_dplus = 0; + if (which == DAGGER) + { + weap->o_count = rnd(4) + 2; + weap->o_group = group++; + } + else if (weap->o_flags & ISMANY) + { + weap->o_count = rnd(8) + 8; + weap->o_group = group++; + } + else + { + weap->o_count = 1; + weap->o_group = 0; + } +} + +/* + * hit_monster: + * Does the missile hit the monster? + */ +int +hit_monster(struct rogue_state *rs,int y, int x, THING *obj) +{ + static coord mp; + + mp.y = y; + mp.x = x; + return fight(rs,&mp, obj, TRUE); +} + +/* + * num: + * Figure out the plus number for armor/weapons + */ +char * +num(int n1, int n2, char type) +{ + static char numbuf[10]; + + sprintf(numbuf, n1 < 0 ? "%d" : "+%d", n1); + if (type == WEAPON) + sprintf(&numbuf[strlen(numbuf)], n2 < 0 ? ",%d" : ",+%d", n2); + return numbuf; +} + +/* + * wield: + * Pull out a certain weapon + */ + +void +wield(struct rogue_state *rs) +{ + THING *obj, *oweapon; + char *sp; + + oweapon = cur_weapon; + if (!dropcheck(rs,cur_weapon)) + { + cur_weapon = oweapon; + return; + } + cur_weapon = oweapon; + if ((obj = get_item(rs,"wield", WEAPON)) == NULL) + { +bad: + after = FALSE; + return; + } + + if (obj->o_type == ARMOR) + { + msg(rs,"you can't wield armor"); + goto bad; + } + if (is_current(rs,obj)) + goto bad; + + sp = inv_name(obj, TRUE); + cur_weapon = obj; + if (!terse) + addmsg(rs,"you are now "); + msg(rs,"wielding %s (%c)", sp, obj->o_packch); +} + +/* + * fallpos: + * Pick a random position around the give (y, x) coordinates + */ +bool +fallpos(coord *pos, coord *newpos) +{ + int y, x, cnt, ch; + + cnt = 0; + for (y = pos->y - 1; y <= pos->y + 1; y++) + for (x = pos->x - 1; x <= pos->x + 1; x++) + { + /* + * check to make certain the spot is empty, if it is, + * put the object there, set it in the level list + * and re-draw the room if he can see it + */ + if (y == hero.y && x == hero.x) + continue; + if (((ch = chat(y, x)) == FLOOR || ch == PASSAGE) + && rnd(++cnt) == 0) + { + newpos->y = y; + newpos->x = x; + } + } + return (bool)(cnt != 0); +} diff --git a/src/cc/rogue/wizard.c b/src/cc/rogue/wizard.c new file mode 100644 index 000000000..e56928d33 --- /dev/null +++ b/src/cc/rogue/wizard.c @@ -0,0 +1,284 @@ +/* + * Special wizard commands (some of which are also non-wizard commands + * under strange circumstances) + * + * @(#)wizard.c 4.30 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ + +#include +#include +#include +#include +#include "rogue.h" + +/* + * whatis: + * What a certin object is + */ + +void +whatis(struct rogue_state *rs,bool insist, int type) +{ + THING *obj; + + if (pack == NULL) + { + msg(rs,"you don't have anything in your pack to identify"); + return; + } + + for (;;) + { + obj = get_item(rs,"identify", type); + if (insist) + { + if (n_objs == 0) + return; + else if (obj == NULL) + msg(rs,"you must identify something"); + else if (type && obj->o_type != type && + !(type == R_OR_S && (obj->o_type == RING || obj->o_type == STICK)) ) + msg(rs,"you must identify a %s", type_name(type)); + else + break; + } + else + break; + } + + if (obj == NULL) + return; + + switch (obj->o_type) + { + case SCROLL: + set_know(obj, scr_info); + when POTION: + set_know(obj, pot_info); + when STICK: + set_know(obj, ws_info); + when WEAPON: + case ARMOR: + obj->o_flags |= ISKNOW; + when RING: + set_know(obj, ring_info); + } + msg(rs,inv_name(obj, FALSE)); +} + +/* + * set_know: + * Set things up when we really know what a thing is + */ + +void +set_know(THING *obj, struct obj_info *info) +{ + char **guess; + + info[obj->o_which].oi_know = TRUE; + obj->o_flags |= ISKNOW; + guess = &info[obj->o_which].oi_guess; + if (*guess) + { + free(*guess); + *guess = NULL; + } +} + +/* + * type_name: + * Return a pointer to the name of the type + */ +char * +type_name(int type) +{ + struct h_list *hp; + static struct h_list tlist[] = { + {POTION, "potion", FALSE}, + {SCROLL, "scroll", FALSE}, + {FOOD, "food", FALSE}, + {R_OR_S, "ring, wand or staff", FALSE}, + {RING, "ring", FALSE}, + {STICK, "wand or staff", FALSE}, + {WEAPON, "weapon", FALSE}, + {ARMOR, "suit of armor", FALSE}, + }; + + for (hp = tlist; hp->h_ch; hp++) + if (type == hp->h_ch) + return hp->h_desc; + /* NOTREACHED */ + return(0); +} + +#ifdef MASTER +/* + * create_obj: + * wizard command for getting anything he wants + */ + +void +create_obj(struct rogue_state *rs) +{ + THING *obj; + char ch, bless; + + obj = new_item(); + msg(rs,"type of item: "); + obj->o_type = readchar(rs); + mpos = 0; + msg(rs,"which %c do you want? (0-f)", obj->o_type); + obj->o_which = (isdigit((ch = readchar(rs))) ? ch - '0' : ch - 'a' + 10); + obj->o_group = 0; + obj->o_count = 1; + mpos = 0; + if (obj->o_type == WEAPON || obj->o_type == ARMOR) + { + msg(rs,"blessing? (+,-,n)"); + bless = readchar(rs); + mpos = 0; + if (bless == '-') + obj->o_flags |= ISCURSED; + if (obj->o_type == WEAPON) + { + init_weapon(obj, obj->o_which); + if (bless == '-') + obj->o_hplus -= rnd(3)+1; + if (bless == '+') + obj->o_hplus += rnd(3)+1; + } + else + { + obj->o_arm = a_class[obj->o_which]; + if (bless == '-') + obj->o_arm += rnd(3)+1; + if (bless == '+') + obj->o_arm -= rnd(3)+1; + } + } + else if (obj->o_type == RING) + switch (obj->o_which) + { + case R_PROTECT: + case R_ADDSTR: + case R_ADDHIT: + case R_ADDDAM: + msg(rs,"blessing? (+,-,n)"); + bless = readchar(rs); + mpos = 0; + if (bless == '-') + obj->o_flags |= ISCURSED; + obj->o_arm = (bless == '-' ? -1 : rnd(2) + 1); + when R_AGGR: + case R_TELEPORT: + obj->o_flags |= ISCURSED; + } + else if (obj->o_type == STICK) + fix_stick(obj); + else if (obj->o_type == GOLD) + { + msg(rs,"how much?"); + get_num(&obj->o_goldval, stdscr); + } + add_pack(rs,obj, FALSE); +} +#endif + +/* + * telport: + * Bamf the hero someplace else + */ + +void +teleport(struct rogue_state *rs) +{ + static coord c; + + mvaddch(hero.y, hero.x, floor_at()); + find_floor((struct room *) NULL, &c, FALSE, TRUE); + if (roomin(rs,&c) != proom) + { + leave_room(rs,&hero); + hero = c; + enter_room(rs,&hero); + } + else + { + hero = c; + look(rs,TRUE); + } + mvaddch(hero.y, hero.x, PLAYER); + /* + * turn off ISHELD in case teleportation was done while fighting + * a Flytrap + */ + if (on(player, ISHELD)) { + player.t_flags &= ~ISHELD; + vf_hit = 0; + strcpy(monsters['F'-'A'].m_stats.s_dmg, "000x0"); + } + no_move = 0; + count = 0; + running = FALSE; + flush_type(); +} + +#ifdef MASTER +/* + * passwd: + * See if user knows password + */ +int +passwd(struct rogue_state *rs) +{ + char *sp, c; + static char buf[MAXSTR]; + + msg(rs,"wizard's Password:"); + mpos = 0; + sp = buf; + while ((c = readchar(rs)) != '\n' && c != '\r' && c != ESCAPE) + if (c == md_killchar()) + sp = buf; + else if (c == md_erasechar() && sp > buf) + sp--; + else + *sp++ = c; + if (sp == buf) + return FALSE; + *sp = '\0'; + return (strcmp(PASSWD, md_crypt(buf, "mT")) == 0); +} + +/* + * show_map: + * Print out the map for the wizard + */ + +void +show_map(struct rogue_state *rs) +{ + int y, x, real; + + wclear(hw); + for (y = 1; y < NUMLINES - 1; y++) + for (x = 0; x < NUMCOLS; x++) + { + real = flat(y, x); + if (!(real & F_REAL)) + wstandout(hw); + wmove(hw, y, x); + waddch(hw, chat(y, x)); + if (!real) + wstandend(hw); + } + show_win(rs,"---More (level map)---"); +} +#endif diff --git a/src/cc/rogue/xcrypt.c b/src/cc/rogue/xcrypt.c new file mode 100644 index 000000000..bbf5d76ac --- /dev/null +++ b/src/cc/rogue/xcrypt.c @@ -0,0 +1,707 @@ +/* + * FreeSec: libcrypt + * + * Copyright (C) 1994 David Burren + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name(s) of the author(s) nor the names of other contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * + * This is an original implementation of the DES and the crypt(3) interfaces + * by David Burren . + * + * An excellent reference on the underlying algorithm (and related + * algorithms) is: + * + * B. Schneier, Applied Cryptography: protocols, algorithms, + * and source code in C, John Wiley & Sons, 1994. + * + * Note that in that book's description of DES the lookups for the initial, + * pbox, and final permutations are inverted (this has been brought to the + * attention of the author). A list of errata for this book has been + * posted to the sci.crypt newsgroup by the author and is available for FTP. + * + * NOTE: + * This file has a static version of des_setkey() so that crypt.o exports + * only the crypt() interface. This is required to make binaries linked + * against crypt.o exportable or re-exportable from the USA. + */ + +#include +#include + +unsigned int md_endian = 0x01020304; + +unsigned int +xntohl(unsigned int x) +{ + if ( *((char *)&md_endian) == 0x01 ) + return(x); + else + return( ((x & 0x000000ffU) << 24) | + ((x & 0x0000ff00U) << 8) | + ((x & 0x00ff0000U) >> 8) | + ((x & 0xff000000U) >> 24) ); +} + +unsigned +xhtonl(unsigned int x) +{ + if ( *((char *)&md_endian) == 0x01 ) + return(x); + else + return( ((x & 0x000000ffU) << 24) | + ((x & 0x0000ff00U) << 8) | + ((x & 0x00ff0000U) >> 8) | + ((x & 0xff000000U) >> 24) ); +} + +#define _PASSWORD_EFMT1 '_' + +static unsigned char IP[64] = { + 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, + 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, + 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, + 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 +}; + +static unsigned char inv_key_perm[64]; +static unsigned char key_perm[56] = { + 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, + 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, + 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, + 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 +}; + +static unsigned char key_shifts[16] = { + 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 +}; + +static unsigned char inv_comp_perm[56]; +static unsigned char comp_perm[48] = { + 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, + 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, + 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, + 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 +}; + +/* + * No E box is used, as it's replaced by some ANDs, shifts, and ORs. + */ + +static unsigned char u_sbox[8][64]; +static unsigned char sbox[8][64] = { + { + 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, + 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, + 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, + 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 + }, + { + 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, + 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, + 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, + 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 + }, + { + 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, + 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, + 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, + 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 + }, + { + 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, + 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, + 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, + 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 + }, + { + 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, + 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, + 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, + 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 + }, + { + 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, + 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, + 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, + 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 + }, + { + 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, + 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, + 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, + 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 + }, + { + 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, + 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, + 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, + 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 + } +}; + +static unsigned char un_pbox[32]; +static unsigned char pbox[32] = { + 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, + 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 +}; + +static unsigned int bits32[32] = +{ + 0x80000000, 0x40000000, 0x20000000, 0x10000000, + 0x08000000, 0x04000000, 0x02000000, 0x01000000, + 0x00800000, 0x00400000, 0x00200000, 0x00100000, + 0x00080000, 0x00040000, 0x00020000, 0x00010000, + 0x00008000, 0x00004000, 0x00002000, 0x00001000, + 0x00000800, 0x00000400, 0x00000200, 0x00000100, + 0x00000080, 0x00000040, 0x00000020, 0x00000010, + 0x00000008, 0x00000004, 0x00000002, 0x00000001 +}; + +static unsigned char bits8[8] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; + +static unsigned int saltbits; +static int old_salt; +static unsigned int *bits28, *bits24; +static unsigned char init_perm[64], final_perm[64]; +static unsigned int en_keysl[16], en_keysr[16]; +static unsigned int de_keysl[16], de_keysr[16]; +static int des_initialised = 0; +static unsigned char m_sbox[4][4096]; +static unsigned int psbox[4][256]; +static unsigned int ip_maskl[8][256], ip_maskr[8][256]; +static unsigned int fp_maskl[8][256], fp_maskr[8][256]; +static unsigned int key_perm_maskl[8][128], key_perm_maskr[8][128]; +static unsigned int comp_maskl[8][128], comp_maskr[8][128]; +static unsigned int old_rawkey0, old_rawkey1; + +static unsigned char ascii64[] = + "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; +/* 0000000000111111111122222222223333333333444444444455555555556666 */ +/* 0123456789012345678901234567890123456789012345678901234567890123 */ + +static __inline int +ascii_to_bin(char ch) +{ + if (ch > 'z') + return(0); + if (ch >= 'a') + return(ch - 'a' + 38); + if (ch > 'Z') + return(0); + if (ch >= 'A') + return(ch - 'A' + 12); + if (ch > '9') + return(0); + if (ch >= '.') + return(ch - '.'); + return(0); +} + +static void +des_init() +{ + int i, j, b, k, inbit, obit; + unsigned int *p, *il, *ir, *fl, *fr; + + old_rawkey0 = old_rawkey1 = 0; + saltbits = 0; + old_salt = 0; + bits24 = (bits28 = bits32 + 4) + 4; + + /* + * Invert the S-boxes, reordering the input bits. + */ + for (i = 0; i < 8; i++) + for (j = 0; j < 64; j++) { + b = (j & 0x20) | ((j & 1) << 4) | ((j >> 1) & 0xf); + u_sbox[i][j] = sbox[i][b]; + } + + /* + * Convert the inverted S-boxes into 4 arrays of 8 bits. + * Each will handle 12 bits of the S-box input. + */ + for (b = 0; b < 4; b++) + for (i = 0; i < 64; i++) + for (j = 0; j < 64; j++) + m_sbox[b][(i << 6) | j] = + (u_sbox[(b << 1)][i] << 4) | + u_sbox[(b << 1) + 1][j]; + + /* + * Set up the initial & final permutations into a useful form, and + * initialise the inverted key permutation. + */ + for (i = 0; i < 64; i++) { + init_perm[final_perm[i] = IP[i] - 1] = (unsigned char) i; + inv_key_perm[i] = 255; + } + + /* + * Invert the key permutation and initialise the inverted key + * compression permutation. + */ + for (i = 0; i < 56; i++) { + inv_key_perm[key_perm[i] - 1] = (unsigned char) i; + inv_comp_perm[i] = 255; + } + + /* + * Invert the key compression permutation. + */ + for (i = 0; i < 48; i++) { + inv_comp_perm[comp_perm[i] - 1] = (unsigned char) i; + } + + /* + * Set up the OR-mask arrays for the initial and final permutations, + * and for the key initial and compression permutations. + */ + for (k = 0; k < 8; k++) { + for (i = 0; i < 256; i++) { + *(il = &ip_maskl[k][i]) = 0; + *(ir = &ip_maskr[k][i]) = 0; + *(fl = &fp_maskl[k][i]) = 0; + *(fr = &fp_maskr[k][i]) = 0; + for (j = 0; j < 8; j++) { + inbit = 8 * k + j; + if (i & bits8[j]) { + if ((obit = init_perm[inbit]) < 32) + *il |= bits32[obit]; + else + *ir |= bits32[obit-32]; + if ((obit = final_perm[inbit]) < 32) + *fl |= bits32[obit]; + else + *fr |= bits32[obit - 32]; + } + } + } + for (i = 0; i < 128; i++) { + *(il = &key_perm_maskl[k][i]) = 0; + *(ir = &key_perm_maskr[k][i]) = 0; + for (j = 0; j < 7; j++) { + inbit = 8 * k + j; + if (i & bits8[j + 1]) { + if ((obit = inv_key_perm[inbit]) == 255) + continue; + if (obit < 28) + *il |= bits28[obit]; + else + *ir |= bits28[obit - 28]; + } + } + *(il = &comp_maskl[k][i]) = 0; + *(ir = &comp_maskr[k][i]) = 0; + for (j = 0; j < 7; j++) { + inbit = 7 * k + j; + if (i & bits8[j + 1]) { + if ((obit=inv_comp_perm[inbit]) == 255) + continue; + if (obit < 24) + *il |= bits24[obit]; + else + *ir |= bits24[obit - 24]; + } + } + } + } + + /* + * Invert the P-box permutation, and convert into OR-masks for + * handling the output of the S-box arrays setup above. + */ + for (i = 0; i < 32; i++) + un_pbox[pbox[i] - 1] = (unsigned char) i; + + for (b = 0; b < 4; b++) + for (i = 0; i < 256; i++) { + *(p = &psbox[b][i]) = 0; + for (j = 0; j < 8; j++) { + if (i & bits8[j]) + *p |= bits32[un_pbox[8 * b + j]]; + } + } + + des_initialised = 1; +} + +static void +setup_salt(int salt) +{ + unsigned int obit, saltbit; + int i; + + if (salt == old_salt) + return; + old_salt = salt; + + saltbits = 0; + saltbit = 1; + obit = 0x800000; + for (i = 0; i < 24; i++) { + if (salt & saltbit) + saltbits |= obit; + saltbit <<= 1; + obit >>= 1; + } +} + +static int +des_setkey(const char *key) +{ + unsigned int k0, k1, rawkey0, rawkey1; + int shifts, round; + + if (!des_initialised) + des_init(); + + rawkey0 = xntohl(*(unsigned int *) key); + rawkey1 = xntohl(*(unsigned int *) (key + 4)); + + if ((rawkey0 | rawkey1) + && rawkey0 == old_rawkey0 + && rawkey1 == old_rawkey1) { + /* + * Already setup for this key. + * This optimisation fails on a zero key (which is weak and + * has bad parity anyway) in order to simplify the starting + * conditions. + */ + return(0); + } + old_rawkey0 = rawkey0; + old_rawkey1 = rawkey1; + + /* + * Do key permutation and split into two 28-bit subkeys. + */ + k0 = key_perm_maskl[0][rawkey0 >> 25] + | key_perm_maskl[1][(rawkey0 >> 17) & 0x7f] + | key_perm_maskl[2][(rawkey0 >> 9) & 0x7f] + | key_perm_maskl[3][(rawkey0 >> 1) & 0x7f] + | key_perm_maskl[4][rawkey1 >> 25] + | key_perm_maskl[5][(rawkey1 >> 17) & 0x7f] + | key_perm_maskl[6][(rawkey1 >> 9) & 0x7f] + | key_perm_maskl[7][(rawkey1 >> 1) & 0x7f]; + k1 = key_perm_maskr[0][rawkey0 >> 25] + | key_perm_maskr[1][(rawkey0 >> 17) & 0x7f] + | key_perm_maskr[2][(rawkey0 >> 9) & 0x7f] + | key_perm_maskr[3][(rawkey0 >> 1) & 0x7f] + | key_perm_maskr[4][rawkey1 >> 25] + | key_perm_maskr[5][(rawkey1 >> 17) & 0x7f] + | key_perm_maskr[6][(rawkey1 >> 9) & 0x7f] + | key_perm_maskr[7][(rawkey1 >> 1) & 0x7f]; + /* + * Rotate subkeys and do compression permutation. + */ + shifts = 0; + for (round = 0; round < 16; round++) { + unsigned int t0, t1; + + shifts += key_shifts[round]; + + t0 = (k0 << shifts) | (k0 >> (28 - shifts)); + t1 = (k1 << shifts) | (k1 >> (28 - shifts)); + + de_keysl[15 - round] = + en_keysl[round] = comp_maskl[0][(t0 >> 21) & 0x7f] + | comp_maskl[1][(t0 >> 14) & 0x7f] + | comp_maskl[2][(t0 >> 7) & 0x7f] + | comp_maskl[3][t0 & 0x7f] + | comp_maskl[4][(t1 >> 21) & 0x7f] + | comp_maskl[5][(t1 >> 14) & 0x7f] + | comp_maskl[6][(t1 >> 7) & 0x7f] + | comp_maskl[7][t1 & 0x7f]; + + de_keysr[15 - round] = + en_keysr[round] = comp_maskr[0][(t0 >> 21) & 0x7f] + | comp_maskr[1][(t0 >> 14) & 0x7f] + | comp_maskr[2][(t0 >> 7) & 0x7f] + | comp_maskr[3][t0 & 0x7f] + | comp_maskr[4][(t1 >> 21) & 0x7f] + | comp_maskr[5][(t1 >> 14) & 0x7f] + | comp_maskr[6][(t1 >> 7) & 0x7f] + | comp_maskr[7][t1 & 0x7f]; + } + return(0); +} + +static int +do_des(unsigned int l_in, unsigned int r_in, unsigned int *l_out, + unsigned int *r_out, int count) +{ + /* + * l_in, r_in, l_out, and r_out are in pseudo-"big-endian" format. + */ + unsigned int l, r, *kl, *kr, *kl1, *kr1; + unsigned int f = 0, r48l, r48r; + int round; + + if (count == 0) { + return(1); + } else if (count > 0) { + /* + * Encrypting + */ + kl1 = en_keysl; + kr1 = en_keysr; + } else { + /* + * Decrypting + */ + count = -count; + kl1 = de_keysl; + kr1 = de_keysr; + } + + /* + * Do initial permutation (IP). + */ + l = ip_maskl[0][l_in >> 24] + | ip_maskl[1][(l_in >> 16) & 0xff] + | ip_maskl[2][(l_in >> 8) & 0xff] + | ip_maskl[3][l_in & 0xff] + | ip_maskl[4][r_in >> 24] + | ip_maskl[5][(r_in >> 16) & 0xff] + | ip_maskl[6][(r_in >> 8) & 0xff] + | ip_maskl[7][r_in & 0xff]; + r = ip_maskr[0][l_in >> 24] + | ip_maskr[1][(l_in >> 16) & 0xff] + | ip_maskr[2][(l_in >> 8) & 0xff] + | ip_maskr[3][l_in & 0xff] + | ip_maskr[4][r_in >> 24] + | ip_maskr[5][(r_in >> 16) & 0xff] + | ip_maskr[6][(r_in >> 8) & 0xff] + | ip_maskr[7][r_in & 0xff]; + + while (count--) { + /* + * Do each round. + */ + kl = kl1; + kr = kr1; + round = 16; + while (round--) { + /* + * Expand R to 48 bits (simulate the E-box). + */ + r48l = ((r & 0x00000001) << 23) + | ((r & 0xf8000000) >> 9) + | ((r & 0x1f800000) >> 11) + | ((r & 0x01f80000) >> 13) + | ((r & 0x001f8000) >> 15); + + r48r = ((r & 0x0001f800) << 7) + | ((r & 0x00001f80) << 5) + | ((r & 0x000001f8) << 3) + | ((r & 0x0000001f) << 1) + | ((r & 0x80000000) >> 31); + /* + * Do salting for crypt() and friends, and + * XOR with the permuted key. + */ + f = (r48l ^ r48r) & saltbits; + r48l ^= f ^ *kl++; + r48r ^= f ^ *kr++; + /* + * Do sbox lookups (which shrink it back to 32 bits) + * and do the pbox permutation at the same time. + */ + f = psbox[0][m_sbox[0][r48l >> 12]] + | psbox[1][m_sbox[1][r48l & 0xfff]] + | psbox[2][m_sbox[2][r48r >> 12]] + | psbox[3][m_sbox[3][r48r & 0xfff]]; + /* + * Now that we've permuted things, complete f(). + */ + f ^= l; + l = r; + r = f; + } + r = l; + l = f; + } + /* + * Do final permutation (inverse of IP). + */ + *l_out = fp_maskl[0][l >> 24] + | fp_maskl[1][(l >> 16) & 0xff] + | fp_maskl[2][(l >> 8) & 0xff] + | fp_maskl[3][l & 0xff] + | fp_maskl[4][r >> 24] + | fp_maskl[5][(r >> 16) & 0xff] + | fp_maskl[6][(r >> 8) & 0xff] + | fp_maskl[7][r & 0xff]; + *r_out = fp_maskr[0][l >> 24] + | fp_maskr[1][(l >> 16) & 0xff] + | fp_maskr[2][(l >> 8) & 0xff] + | fp_maskr[3][l & 0xff] + | fp_maskr[4][r >> 24] + | fp_maskr[5][(r >> 16) & 0xff] + | fp_maskr[6][(r >> 8) & 0xff] + | fp_maskr[7][r & 0xff]; + return(0); +} + +static int +des_cipher(const char *in, char *out, int salt, int count) +{ + unsigned int l_out, r_out, rawl, rawr; + unsigned int x[2]; + int retval; + + if (!des_initialised) + des_init(); + + setup_salt(salt); + + memcpy(x, in, sizeof x); + rawl = xntohl(x[0]); + rawr = xntohl(x[1]); + retval = do_des(rawl, rawr, &l_out, &r_out, count); + + x[0] = xhtonl(l_out); + x[1] = xhtonl(r_out); + memcpy(out, x, sizeof x); + return(retval); +} + +char * +xcrypt(const char *key, const char *setting) +{ + int i; + unsigned int count, salt, l, r0, r1, keybuf[2]; + unsigned char *p, *q; + static unsigned char output[21]; + + if (!des_initialised) + des_init(); + + /* + * Copy the key, shifting each character up by one bit + * and padding with zeros. + */ + q = (unsigned char *) keybuf; + while ((q - (unsigned char *) keybuf) < sizeof(keybuf)) { + if ((*q++ = *key << 1)) + key++; + } + if (des_setkey((const char *) keybuf)) + return(NULL); + + if (*setting == _PASSWORD_EFMT1) { + /* + * "new"-style: + * setting - underscore, 4 bytes of count, 4 bytes of salt + * key - unlimited characters + */ + for (i = 1, count = 0; i < 5; i++) + count |= ascii_to_bin(setting[i]) << (i - 1) * 6; + + for (i = 5, salt = 0; i < 9; i++) + salt |= ascii_to_bin(setting[i]) << (i - 5) * 6; + + while (*key) { + /* + * Encrypt the key with itself. + */ + if (des_cipher((const char*)keybuf, (char*)keybuf, 0, 1)) + return(NULL); + /* + * And XOR with the next 8 characters of the key. + */ + q = (unsigned char *) keybuf; + while (((q - (unsigned char *) keybuf) < sizeof(keybuf)) && + *key) + *q++ ^= *key++ << 1; + + if (des_setkey((const char *) keybuf)) + return(NULL); + } + strncpy((char *)output, setting, 9); + + /* + * Double check that we weren't given a short setting. + * If we were, the above code will probably have created + * wierd values for count and salt, but we don't really care. + * Just make sure the output string doesn't have an extra + * NUL in it. + */ + output[9] = '\0'; + p = output + strlen((const char *)output); + } else { + /* + * "old"-style: + * setting - 2 bytes of salt + * key - up to 8 characters + */ + count = 25; + + salt = (ascii_to_bin(setting[1]) << 6) + | ascii_to_bin(setting[0]); + + output[0] = setting[0]; + /* + * If the encrypted password that the salt was extracted from + * is only 1 character long, the salt will be corrupted. We + * need to ensure that the output string doesn't have an extra + * NUL in it! + */ + output[1] = setting[1] ? setting[1] : output[0]; + + p = output + 2; + } + setup_salt(salt); + /* + * Do it. + */ + if (do_des(0, 0, &r0, &r1, count)) + return(NULL); + /* + * Now encode the result... + */ + l = (r0 >> 8); + *p++ = ascii64[(l >> 18) & 0x3f]; + *p++ = ascii64[(l >> 12) & 0x3f]; + *p++ = ascii64[(l >> 6) & 0x3f]; + *p++ = ascii64[l & 0x3f]; + + l = (r0 << 16) | ((r1 >> 16) & 0xffff); + *p++ = ascii64[(l >> 18) & 0x3f]; + *p++ = ascii64[(l >> 12) & 0x3f]; + *p++ = ascii64[(l >> 6) & 0x3f]; + *p++ = ascii64[l & 0x3f]; + + l = r1 << 2; + *p++ = ascii64[(l >> 12) & 0x3f]; + *p++ = ascii64[(l >> 6) & 0x3f]; + *p++ = ascii64[l & 0x3f]; + *p = 0; + + return((char *)output); +} From 9b9bae114e2dae045b8402d7c93a7674b56d138c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 03:09:51 -1100 Subject: [PATCH 0233/1145] Configuration --- .gitignore | 4 +- src/cc/rogue/Makefile.in | 220 ++ src/cc/rogue/configure | 7511 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 7733 insertions(+), 2 deletions(-) create mode 100644 src/cc/rogue/Makefile.in create mode 100755 src/cc/rogue/configure diff --git a/.gitignore b/.gitignore index cd2641c22..47f490f20 100644 --- a/.gitignore +++ b/.gitignore @@ -11,7 +11,7 @@ src/test/test_bitcoin *zcashTest.vk # autoreconf -Makefile.in +#Makefile.in aclocal.m4 autom4te.cache/ build-aux/config.guess @@ -29,7 +29,7 @@ build-aux/compile build-aux/test-driver config.log config.status -configure +#configure libtool src/config/bitcoin-config.h src/config/bitcoin-config.h.in diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in new file mode 100644 index 000000000..c2f4e551a --- /dev/null +++ b/src/cc/rogue/Makefile.in @@ -0,0 +1,220 @@ +############################################################################### +# +# Makefile for rogue +# +# Rogue: Exploring the Dungeons of Doom +# Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman +# All rights reserved. +# +# See the file LICENSE.TXT for full copyright and licensing information. +# +############################################################################### + +############################################################################### +# Site configuration occurs beneath this comment +# Typically ./configure (autoconf tools) configures this section +# This section could be manually configured if autoconf/configure fails +############################################################################### + +DISTNAME=@PACKAGE_TARNAME@@PACKAGE_VERSION@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@-@PACKAGE_VERSION@ +PROGRAM=@PROGRAM@ + +O=o + +#CC=gcc +CC = @CC@ + +#CFLAGS=-O2 +CFLAGS= @CFLAGS@ -fPIC + +#LIBS=-lcurses +LIBS = @LIBS@ + +#RM=rm -f +RM = rm -f + +#GROFF=groff +GROFF = @GROFF@ + +#NROFF=nroff +NROFF = @NROFF@ + +#TBL=tbl +TBL = @TBL@ + +#COLCRT=colcrt +COLCRT = @COLCRT@ + +#SED=sed +SED = @SED@ + +#SCOREFILE=rogue54.scr +SCOREFILE = @SCOREFILE@ + +#LOCKFILE=rogue54.lck +LOCKFILE = @LOCKFILE@ + +#GROUPOWNER=games +GROUPOWNER = @GROUPOWNER@ + +#CPPFLAGS=-DHAVE_CONFIG_H +CPPFLAGS =@DEFS@ @CPPFLAGS@ + +#DISTFILE = $(PROGRAM) +DISTFILE = $(DISTNAME)-@TARGET@ + +INSTALL=./install-sh + +#INSTGROUP=-g games +INSTGROUP= +#INSTOWNER=-u root +INSTOWNER= + +CHGRP=chgrp + +MKDIR=mkdir + +TOUCH=touch + +RMDIR=rmdir + +CHMOD=chmod + +DESTDIR= + +prefix=@prefix@ +exec_prefix=@exec_prefix@ +datarootdir=@datarootdir@ +datadir=@datadir@ +bindir=@bindir@ +mandir=@mandir@ +docdir=@docdir@ +man6dir = $(mandir)/man6 + +############################################################################### +# Site configuration occurs above this comment +# It should not be necessary to change anything below this comment +############################################################################### + +HDRS = rogue.h extern.h score.h +OBJS1 = vers.$(O) extern.$(O) armor.$(O) chase.$(O) command.$(O) \ + daemon.$(O) daemons.$(O) fight.$(O) init.$(O) io.$(O) list.$(O) \ + mach_dep.$(O) rogue.$(O) mdport.$(O) misc.$(O) monsters.$(O) \ + move.$(O) new_level.$(O) +OBJS2 = options.$(O) pack.$(O) passages.$(O) potions.$(O) rings.$(O) \ + rip.$(O) rooms.$(O) save.$(O) scrolls.$(O) state.$(O) sticks.$(O) \ + things.$(O) weapons.$(O) wizard.$(O) xcrypt.$(O) +OBJS = main.$(O) $(OBJS1) $(OBJS2) +CFILES = vers.c extern.c armor.c chase.c command.c daemon.c \ + daemons.c fight.c init.c io.c list.c mach_dep.c \ + main.c mdport.c misc.c monsters.c move.c new_level.c \ + options.c pack.c passages.c potions.c rings.c rip.c \ + rooms.c save.c scrolls.c state.c sticks.c things.c \ + weapons.c wizard.c xcrypt.c +MISC_C = findpw.c scedit.c scmisc.c +DOCSRC = rogue.me.in rogue.6.in rogue.doc.in rogue.html.in rogue.cat.in +DOCS = $(PROGRAM).doc $(PROGRAM).html $(PROGRAM).cat $(PROGRAM).me \ + $(PROGRAM).6 +AFILES = configure Makefile.in configure.ac config.h.in config.sub config.guess \ + install-sh rogue.6.in rogue.me.in rogue.html.in rogue.doc.in rogue.cat.in +MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ + rogue.png rogue.desktop + +.SUFFIXES: .obj + +.c.obj: + $(CC) $(CFLAGS) $(CPPFLAGS) /c $*.c + +.c.o: + $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c + +$(PROGRAM): $(HDRS) $(OBJS) + $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2) -lcurses; $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + +clean: + $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so + $(RM) $(OBJS2) + $(RM) core a.exe a.out a.exe.stackdump $(PROGRAM) $(PROGRAM).exe + $(RM) $(PROGRAM).tar $(PROGRAM).tar.gz $(PROGRAM).zip + $(RM) $(DISTNAME)/* + -rmdir $(DISTNAME) + +maintainer-clean: + $(RM) config.h + $(RM) Makefile + $(RM) config.status + $(RM) -r autom4te.cache + $(RM) config.log + $(RM) $(PROGRAM).scr $(PROGRAM).lck + +stddocs: + sed -e 's/@PROGRAM@/rogue/' -e 's/@SCOREFILE@/rogue.scr/' rogue.6.in > rogue.6 + sed -e 's/@PROGRAM@/rogue/' -e 's/@SCOREFILE@/rogue.scr/' rogue.me.in > rogue.me + sed -e 's/@PROGRAM@/rogue/' -e 's/@SCOREFILE@/rogue.scr/' rogue.html.in > rogue,html + sed -e 's/@PROGRAM@/rogue/' -e 's/@SCOREFILE@/rogue.scr/' rogue.doc.in > rogue.doc + sed -e 's/@PROGRAM@/rogue/' -e 's/@SCOREFILE@/rogue.scr/' rogue.cat.in > rogue.cat + +dist.src: + $(MAKE) $(MAKEFILE) clean + mkdir $(DISTNAME) + cp $(CFILES) $(HDRS) $(MISC) $(AFILES) $(DISTNAME) + tar cf $(DISTNAME)-src.tar $(DISTNAME) + gzip -f $(DISTNAME)-src.tar + rm -fr $(DISTNAME) + +findpw: findpw.c xcrypt.o mdport.o xcrypt.o + $(CC) -s -o findpw findpw.c xcrypt.o mdport.o -lcurses + +scedit: scedit.o scmisc.o vers.o mdport.o xcrypt.o + $(CC) -s -o scedit vers.o scedit.o scmisc.o mdport.o xcrypt.o -lcurses + +scmisc.o scedit.o: + $(CC) -O -c $(SF) $*.c + +$(PROGRAM).doc: rogue.me + if test "x$(GROFF)" != "x" -a "x$(SED)" != "x" ; then \ + $(GROFF) -P-c -t -me -Tascii rogue.me | $(SED) -e 's/.\x08//g' > $(PROGRAM).doc ;\ + elif test "x$(NROFF)" != "x" -a "x$(TBL)" != "x" -a "x$(COLCRT)" != "x" ; then \ + tbl rogue.me | $(NROFF) -me | colcrt - > $(PROGRAM).doc ;\ + fi + +$(PROGRAM).cat: rogue.6 + if test "x$(GROFF)" != "x" -a "x$(SED)" != "x" ; then \ + $(GROFF) -Tascii -man rogue.6 | $(SED) -e 's/.\x08//g' > $(PROGRAM).cat ;\ + elif test "x$(NROFF)" != "x" -a "x$(TBL)" != "x" -a "x$(COLCRT)" != "x" ; then \ + $(NROFF) -man rogue.6 | $(COLCRT) - > $(PROGRAM).cat ;\ + fi + +dist: clean $(PROGRAM) + tar cf $(DISTFILE).tar $(PROGRAM) LICENSE.TXT $(DOCS) + gzip -f $(DISTFILE).tar + +install: $(PROGRAM) + -$(TOUCH) test + -if test ! -f $(DESTDIR)$(SCOREFILE) ; then $(INSTALL) -m 0664 test $(DESTDIR)$(SCOREFILE) ; fi + -$(INSTALL) -m 0755 $(PROGRAM) $(DESTDIR)$(bindir)/$(PROGRAM) + -if test "x$(GROUPOWNER)" != "x" ; then \ + $(CHGRP) $(GROUPOWNER) $(DESTDIR)$(SCOREFILE) ; \ + $(CHGRP) $(GROUPOWNER) $(DESTDIR)$(bindir)/$(PROGRAM) ; \ + $(CHMOD) 02755 $(DESTDIR)$(bindir)/$(PROGRAM) ; \ + $(CHMOD) 0464 $(DESTDIR)$(SCOREFILE) ; \ + fi + -if test -d $(man6dir) ; then $(INSTALL) -m 0644 rogue.6 $(DESTDIR)$(man6dir)/$(PROGRAM).6 ; fi + -if test ! -d $(man6dir) ; then $(INSTALL) -m 0644 rogue.6 $(DESTDIR)$(mandir)/$(PROGRAM).6 ; fi + -$(INSTALL) -m 0644 rogue.doc $(DESTDIR)$(docdir)/$(PROGRAM).doc + -$(INSTALL) -m 0644 rogue.html $(DESTDIR)$(docdir)/$(PROGRAM).html + -$(INSTALL) -m 0644 rogue.cat $(DESTDIR)$(docdir)/$(PROGRAM).cat + -$(INSTALL) -m 0644 LICENSE.TXT $(DESTDIR)$(docdir)/LICENSE.TXT + -$(INSTALL) -m 0644 rogue.me $(DESTDIR)$(docdir)/$(PROGRAM).me + -if test ! -f $(DESTDIR)$(LOCKFILE) ; then $(INSTALL) -m 0666 test $(DESTDIR)$(LOCKFILE) ; $(RM) $(DESTDIR)$(LOCKFILE) ; fi + -$(RM) test + +uninstall: + -$(RM) $(DESTDIR)$(bindir)/$(PROGRAM) + -$(RM) $(DESTDIR)$(man6dir)/$(PROGRAM).6 + -$(RM) $(DESTDIR)$(docdir)$(PROGRAM)/$(PROGRAM).doc + -$(RM) $(DESTDIR)$(LOCKFILE) + -$(RMDIR) $(DESTDIR)$(docdir)$(PROGRAM) + +reinstall: uninstall install diff --git a/src/cc/rogue/configure b/src/cc/rogue/configure new file mode 100755 index 000000000..a7b95e78d --- /dev/null +++ b/src/cc/rogue/configure @@ -0,0 +1,7511 @@ +#! /bin/sh +# Guess values for system-dependent variables and create Makefiles. +# Generated by GNU Autoconf 2.61 for Rogue 5.4.4. +# +# Report bugs to . +# +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, +# 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +# This configure script is free software; the Free Software Foundation +# gives unlimited permission to copy, distribute and modify it. +## --------------------- ## +## M4sh Initialization. ## +## --------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + + + +# PATH needs CR +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + echo "#! /bin/sh" >conf$$.sh + echo "exit 0" >>conf$$.sh + chmod +x conf$$.sh + if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then + PATH_SEPARATOR=';' + else + PATH_SEPARATOR=: + fi + rm -f conf$$.sh +fi + +# Support unset when possible. +if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + as_unset=unset +else + as_unset=false +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +as_nl=' +' +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +case $0 in + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break +done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + { (exit 1); exit 1; } +fi + +# Work around bugs in pre-3.0 UWIN ksh. +for as_var in ENV MAIL MAILPATH +do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +for as_var in \ + LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ + LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ + LC_TELEPHONE LC_TIME +do + if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then + eval $as_var=C; export $as_var + else + ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var + fi +done + +# Required to use basename. +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + + +# Name of the executable. +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# CDPATH. +$as_unset CDPATH + + +if test "x$CONFIG_SHELL" = x; then + if (eval ":") 2>/dev/null; then + as_have_required=yes +else + as_have_required=no +fi + + if test $as_have_required = yes && (eval ": +(as_func_return () { + (exit \$1) +} +as_func_success () { + as_func_return 0 +} +as_func_failure () { + as_func_return 1 +} +as_func_ret_success () { + return 0 +} +as_func_ret_failure () { + return 1 +} + +exitcode=0 +if as_func_success; then + : +else + exitcode=1 + echo as_func_success failed. +fi + +if as_func_failure; then + exitcode=1 + echo as_func_failure succeeded. +fi + +if as_func_ret_success; then + : +else + exitcode=1 + echo as_func_ret_success failed. +fi + +if as_func_ret_failure; then + exitcode=1 + echo as_func_ret_failure succeeded. +fi + +if ( set x; as_func_ret_success y && test x = \"\$1\" ); then + : +else + exitcode=1 + echo positional parameters were not saved. +fi + +test \$exitcode = 0) || { (exit 1); exit 1; } + +( + as_lineno_1=\$LINENO + as_lineno_2=\$LINENO + test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" && + test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; } +") 2> /dev/null; then + : +else + as_candidate_shells= + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + case $as_dir in + /*) + for as_base in sh bash ksh sh5; do + as_candidate_shells="$as_candidate_shells $as_dir/$as_base" + done;; + esac +done +IFS=$as_save_IFS + + + for as_shell in $as_candidate_shells $SHELL; do + # Try only shells that exist, to save several forks. + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { ("$as_shell") 2> /dev/null <<\_ASEOF +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + +: +_ASEOF +}; then + CONFIG_SHELL=$as_shell + as_have_required=yes + if { "$as_shell" 2> /dev/null <<\_ASEOF +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + +: +(as_func_return () { + (exit $1) +} +as_func_success () { + as_func_return 0 +} +as_func_failure () { + as_func_return 1 +} +as_func_ret_success () { + return 0 +} +as_func_ret_failure () { + return 1 +} + +exitcode=0 +if as_func_success; then + : +else + exitcode=1 + echo as_func_success failed. +fi + +if as_func_failure; then + exitcode=1 + echo as_func_failure succeeded. +fi + +if as_func_ret_success; then + : +else + exitcode=1 + echo as_func_ret_success failed. +fi + +if as_func_ret_failure; then + exitcode=1 + echo as_func_ret_failure succeeded. +fi + +if ( set x; as_func_ret_success y && test x = "$1" ); then + : +else + exitcode=1 + echo positional parameters were not saved. +fi + +test $exitcode = 0) || { (exit 1); exit 1; } + +( + as_lineno_1=$LINENO + as_lineno_2=$LINENO + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; } + +_ASEOF +}; then + break +fi + +fi + + done + + if test "x$CONFIG_SHELL" != x; then + for as_var in BASH_ENV ENV + do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var + done + export CONFIG_SHELL + exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} +fi + + + if test $as_have_required = no; then + echo This script requires a shell more modern than all the + echo shells that I found on your system. Please install a + echo modern shell, or manually run the script under such a + echo shell if you do have one. + { (exit 1); exit 1; } +fi + + +fi + +fi + + + +(eval "as_func_return () { + (exit \$1) +} +as_func_success () { + as_func_return 0 +} +as_func_failure () { + as_func_return 1 +} +as_func_ret_success () { + return 0 +} +as_func_ret_failure () { + return 1 +} + +exitcode=0 +if as_func_success; then + : +else + exitcode=1 + echo as_func_success failed. +fi + +if as_func_failure; then + exitcode=1 + echo as_func_failure succeeded. +fi + +if as_func_ret_success; then + : +else + exitcode=1 + echo as_func_ret_success failed. +fi + +if as_func_ret_failure; then + exitcode=1 + echo as_func_ret_failure succeeded. +fi + +if ( set x; as_func_ret_success y && test x = \"\$1\" ); then + : +else + exitcode=1 + echo positional parameters were not saved. +fi + +test \$exitcode = 0") || { + echo No shell found that supports shell functions. + echo Please tell autoconf@gnu.org about your system, + echo including any error possibly output before this + echo message +} + + + + as_lineno_1=$LINENO + as_lineno_2=$LINENO + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { + + # Create $as_me.lineno as a copy of $as_myself, but with $LINENO + # uniformly replaced by the line number. The first 'sed' inserts a + # line-number line after each line using $LINENO; the second 'sed' + # does the real work. The second script uses 'N' to pair each + # line-number line with the line containing $LINENO, and appends + # trailing '-' during substitution so that $LINENO is not a special + # case at line end. + # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the + # scripts with optimization help from Paolo Bonzini. Blame Lee + # E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 + { (exit 1); exit 1; }; } + + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in +-n*) + case `echo 'x\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + *) ECHO_C='\c';; + esac;; +*) + ECHO_N='-n';; +esac + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir +fi +echo >conf$$.file +if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' +elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln +else + as_ln_s='cp -p' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p=: +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +if test -x / >/dev/null 2>&1; then + as_test_x='test -x' +else + if ls -dL / >/dev/null 2>&1; then + as_ls_L_option=L + else + as_ls_L_option= + fi + as_test_x=' + eval sh -c '\'' + if test -d "$1"; then + test -d "$1/."; + else + case $1 in + -*)set "./$1";; + esac; + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + ???[sx]*):;;*)false;;esac;fi + '\'' sh + ' +fi +as_executable_p=$as_test_x + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + + +exec 7<&0 &1 + +# Name of the host. +# hostname on some systems (SVR3.2, Linux) returns a bogus exit status, +# so uname gets run too. +ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` + +# +# Initializations. +# +ac_default_prefix=/usr/local +ac_clean_files= +ac_config_libobj_dir=. +LIBOBJS= +cross_compiling=no +subdirs= +MFLAGS= +MAKEFLAGS= +SHELL=${CONFIG_SHELL-/bin/sh} + +# Identity of this package. +PACKAGE_NAME='Rogue' +PACKAGE_TARNAME='rogue' +PACKAGE_VERSION='5.4.4' +PACKAGE_STRING='Rogue 5.4.4' +PACKAGE_BUGREPORT='yendor@rogueforge.net' + +ac_unique_file="armor.c" +# Factoring default headers for most tests. +ac_includes_default="\ +#include +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_STAT_H +# include +#endif +#ifdef STDC_HEADERS +# include +# include +#else +# ifdef HAVE_STDLIB_H +# include +# endif +#endif +#ifdef HAVE_STRING_H +# if !defined STDC_HEADERS && defined HAVE_MEMORY_H +# include +# endif +# include +#endif +#ifdef HAVE_STRINGS_H +# include +#endif +#ifdef HAVE_INTTYPES_H +# include +#endif +#ifdef HAVE_STDINT_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif" + +ac_subst_vars='SHELL +PATH_SEPARATOR +PACKAGE_NAME +PACKAGE_TARNAME +PACKAGE_VERSION +PACKAGE_STRING +PACKAGE_BUGREPORT +exec_prefix +prefix +program_transform_name +bindir +sbindir +libexecdir +datarootdir +datadir +sysconfdir +sharedstatedir +localstatedir +includedir +oldincludedir +docdir +infodir +htmldir +dvidir +pdfdir +psdir +libdir +localedir +mandir +DEFS +ECHO_C +ECHO_N +ECHO_T +LIBS +build_alias +host_alias +target_alias +build +build_cpu +build_vendor +build_os +host +host_cpu +host_vendor +host_os +target +target_cpu +target_vendor +target_os +CC +CFLAGS +LDFLAGS +CPPFLAGS +ac_ct_CC +EXEEXT +OBJEXT +CPP +GREP +EGREP +LIBOBJS +NROFF +GROFF +COLCRT +TBL +SED +PROGRAM +GROUPOWNER +SCOREFILE +LOCKFILE +TARGET +LTLIBOBJS' +ac_subst_files='' + ac_precious_vars='build_alias +host_alias +target_alias +CC +CFLAGS +LDFLAGS +LIBS +CPPFLAGS +CPP' + + +# Initialize some variables set by options. +ac_init_help= +ac_init_version=false +# The variables have the same names as the options, with +# dashes changed to underlines. +cache_file=/dev/null +exec_prefix=NONE +no_create= +no_recursion= +prefix=NONE +program_prefix=NONE +program_suffix=NONE +program_transform_name=s,x,x, +silent= +site= +srcdir= +verbose= +x_includes=NONE +x_libraries=NONE + +# Installation directory options. +# These are left unexpanded so users can "make install exec_prefix=/foo" +# and all the variables that are supposed to be based on exec_prefix +# by default will actually change. +# Use braces instead of parens because sh, perl, etc. also accept them. +# (The list follows the same order as the GNU Coding Standards.) +bindir='${exec_prefix}/bin' +sbindir='${exec_prefix}/sbin' +libexecdir='${exec_prefix}/libexec' +datarootdir='${prefix}/share' +datadir='${datarootdir}' +sysconfdir='${prefix}/etc' +sharedstatedir='${prefix}/com' +localstatedir='${prefix}/var' +includedir='${prefix}/include' +oldincludedir='/usr/include' +docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' +infodir='${datarootdir}/info' +htmldir='${docdir}' +dvidir='${docdir}' +pdfdir='${docdir}' +psdir='${docdir}' +libdir='${exec_prefix}/lib' +localedir='${datarootdir}/locale' +mandir='${datarootdir}/man' + +ac_prev= +ac_dashdash= +for ac_option +do + # If the previous option needs an argument, assign it. + if test -n "$ac_prev"; then + eval $ac_prev=\$ac_option + ac_prev= + continue + fi + + case $ac_option in + *=*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *) ac_optarg=yes ;; + esac + + # Accept the important Cygnus configure options, so we can diagnose typos. + + case $ac_dashdash$ac_option in + --) + ac_dashdash=yes ;; + + -bindir | --bindir | --bindi | --bind | --bin | --bi) + ac_prev=bindir ;; + -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) + bindir=$ac_optarg ;; + + -build | --build | --buil | --bui | --bu) + ac_prev=build_alias ;; + -build=* | --build=* | --buil=* | --bui=* | --bu=*) + build_alias=$ac_optarg ;; + + -cache-file | --cache-file | --cache-fil | --cache-fi \ + | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) + ac_prev=cache_file ;; + -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ + | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) + cache_file=$ac_optarg ;; + + --config-cache | -C) + cache_file=config.cache ;; + + -datadir | --datadir | --datadi | --datad) + ac_prev=datadir ;; + -datadir=* | --datadir=* | --datadi=* | --datad=*) + datadir=$ac_optarg ;; + + -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ + | --dataroo | --dataro | --datar) + ac_prev=datarootdir ;; + -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ + | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) + datarootdir=$ac_optarg ;; + + -disable-* | --disable-*) + ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && + { echo "$as_me: error: invalid feature name: $ac_feature" >&2 + { (exit 1); exit 1; }; } + ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` + eval enable_$ac_feature=no ;; + + -docdir | --docdir | --docdi | --doc | --do) + ac_prev=docdir ;; + -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) + docdir=$ac_optarg ;; + + -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) + ac_prev=dvidir ;; + -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) + dvidir=$ac_optarg ;; + + -enable-* | --enable-*) + ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && + { echo "$as_me: error: invalid feature name: $ac_feature" >&2 + { (exit 1); exit 1; }; } + ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` + eval enable_$ac_feature=\$ac_optarg ;; + + -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ + | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ + | --exec | --exe | --ex) + ac_prev=exec_prefix ;; + -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ + | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ + | --exec=* | --exe=* | --ex=*) + exec_prefix=$ac_optarg ;; + + -gas | --gas | --ga | --g) + # Obsolete; use --with-gas. + with_gas=yes ;; + + -help | --help | --hel | --he | -h) + ac_init_help=long ;; + -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) + ac_init_help=recursive ;; + -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) + ac_init_help=short ;; + + -host | --host | --hos | --ho) + ac_prev=host_alias ;; + -host=* | --host=* | --hos=* | --ho=*) + host_alias=$ac_optarg ;; + + -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) + ac_prev=htmldir ;; + -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ + | --ht=*) + htmldir=$ac_optarg ;; + + -includedir | --includedir | --includedi | --included | --include \ + | --includ | --inclu | --incl | --inc) + ac_prev=includedir ;; + -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ + | --includ=* | --inclu=* | --incl=* | --inc=*) + includedir=$ac_optarg ;; + + -infodir | --infodir | --infodi | --infod | --info | --inf) + ac_prev=infodir ;; + -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) + infodir=$ac_optarg ;; + + -libdir | --libdir | --libdi | --libd) + ac_prev=libdir ;; + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir=$ac_optarg ;; + + -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ + | --libexe | --libex | --libe) + ac_prev=libexecdir ;; + -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ + | --libexe=* | --libex=* | --libe=*) + libexecdir=$ac_optarg ;; + + -localedir | --localedir | --localedi | --localed | --locale) + ac_prev=localedir ;; + -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) + localedir=$ac_optarg ;; + + -localstatedir | --localstatedir | --localstatedi | --localstated \ + | --localstate | --localstat | --localsta | --localst | --locals) + ac_prev=localstatedir ;; + -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ + | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) + localstatedir=$ac_optarg ;; + + -mandir | --mandir | --mandi | --mand | --man | --ma | --m) + ac_prev=mandir ;; + -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) + mandir=$ac_optarg ;; + + -nfp | --nfp | --nf) + # Obsolete; use --without-fp. + with_fp=no ;; + + -no-create | --no-create | --no-creat | --no-crea | --no-cre \ + | --no-cr | --no-c | -n) + no_create=yes ;; + + -no-recursion | --no-recursion | --no-recursio | --no-recursi \ + | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) + no_recursion=yes ;; + + -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ + | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ + | --oldin | --oldi | --old | --ol | --o) + ac_prev=oldincludedir ;; + -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ + | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ + | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) + oldincludedir=$ac_optarg ;; + + -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) + ac_prev=prefix ;; + -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) + prefix=$ac_optarg ;; + + -program-prefix | --program-prefix | --program-prefi | --program-pref \ + | --program-pre | --program-pr | --program-p) + ac_prev=program_prefix ;; + -program-prefix=* | --program-prefix=* | --program-prefi=* \ + | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) + program_prefix=$ac_optarg ;; + + -program-suffix | --program-suffix | --program-suffi | --program-suff \ + | --program-suf | --program-su | --program-s) + ac_prev=program_suffix ;; + -program-suffix=* | --program-suffix=* | --program-suffi=* \ + | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) + program_suffix=$ac_optarg ;; + + -program-transform-name | --program-transform-name \ + | --program-transform-nam | --program-transform-na \ + | --program-transform-n | --program-transform- \ + | --program-transform | --program-transfor \ + | --program-transfo | --program-transf \ + | --program-trans | --program-tran \ + | --progr-tra | --program-tr | --program-t) + ac_prev=program_transform_name ;; + -program-transform-name=* | --program-transform-name=* \ + | --program-transform-nam=* | --program-transform-na=* \ + | --program-transform-n=* | --program-transform-=* \ + | --program-transform=* | --program-transfor=* \ + | --program-transfo=* | --program-transf=* \ + | --program-trans=* | --program-tran=* \ + | --progr-tra=* | --program-tr=* | --program-t=*) + program_transform_name=$ac_optarg ;; + + -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) + ac_prev=pdfdir ;; + -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) + pdfdir=$ac_optarg ;; + + -psdir | --psdir | --psdi | --psd | --ps) + ac_prev=psdir ;; + -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) + psdir=$ac_optarg ;; + + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + silent=yes ;; + + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) + ac_prev=sbindir ;; + -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ + | --sbi=* | --sb=*) + sbindir=$ac_optarg ;; + + -sharedstatedir | --sharedstatedir | --sharedstatedi \ + | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ + | --sharedst | --shareds | --shared | --share | --shar \ + | --sha | --sh) + ac_prev=sharedstatedir ;; + -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ + | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ + | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ + | --sha=* | --sh=*) + sharedstatedir=$ac_optarg ;; + + -site | --site | --sit) + ac_prev=site ;; + -site=* | --site=* | --sit=*) + site=$ac_optarg ;; + + -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) + ac_prev=srcdir ;; + -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) + srcdir=$ac_optarg ;; + + -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ + | --syscon | --sysco | --sysc | --sys | --sy) + ac_prev=sysconfdir ;; + -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ + | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) + sysconfdir=$ac_optarg ;; + + -target | --target | --targe | --targ | --tar | --ta | --t) + ac_prev=target_alias ;; + -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) + target_alias=$ac_optarg ;; + + -v | -verbose | --verbose | --verbos | --verbo | --verb) + verbose=yes ;; + + -version | --version | --versio | --versi | --vers | -V) + ac_init_version=: ;; + + -with-* | --with-*) + ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && + { echo "$as_me: error: invalid package name: $ac_package" >&2 + { (exit 1); exit 1; }; } + ac_package=`echo $ac_package | sed 's/[-.]/_/g'` + eval with_$ac_package=\$ac_optarg ;; + + -without-* | --without-*) + ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && + { echo "$as_me: error: invalid package name: $ac_package" >&2 + { (exit 1); exit 1; }; } + ac_package=`echo $ac_package | sed 's/[-.]/_/g'` + eval with_$ac_package=no ;; + + --x) + # Obsolete; use --with-x. + with_x=yes ;; + + -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ + | --x-incl | --x-inc | --x-in | --x-i) + ac_prev=x_includes ;; + -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ + | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) + x_includes=$ac_optarg ;; + + -x-libraries | --x-libraries | --x-librarie | --x-librari \ + | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) + ac_prev=x_libraries ;; + -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ + | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) + x_libraries=$ac_optarg ;; + + -*) { echo "$as_me: error: unrecognized option: $ac_option +Try \`$0 --help' for more information." >&2 + { (exit 1); exit 1; }; } + ;; + + *=*) + ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` + # Reject names that are not valid shell variable names. + expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && + { echo "$as_me: error: invalid variable name: $ac_envvar" >&2 + { (exit 1); exit 1; }; } + eval $ac_envvar=\$ac_optarg + export $ac_envvar ;; + + *) + # FIXME: should be removed in autoconf 3.0. + echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && + echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} + ;; + + esac +done + +if test -n "$ac_prev"; then + ac_option=--`echo $ac_prev | sed 's/_/-/g'` + { echo "$as_me: error: missing argument to $ac_option" >&2 + { (exit 1); exit 1; }; } +fi + +# Be sure to have absolute directory names. +for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ + datadir sysconfdir sharedstatedir localstatedir includedir \ + oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ + libdir localedir mandir +do + eval ac_val=\$$ac_var + case $ac_val in + [\\/$]* | ?:[\\/]* ) continue;; + NONE | '' ) case $ac_var in *prefix ) continue;; esac;; + esac + { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 + { (exit 1); exit 1; }; } +done + +# There might be people who depend on the old broken behavior: `$host' +# used to hold the argument of --host etc. +# FIXME: To remove some day. +build=$build_alias +host=$host_alias +target=$target_alias + +# FIXME: To remove some day. +if test "x$host_alias" != x; then + if test "x$build_alias" = x; then + cross_compiling=maybe + echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. + If a cross compiler is detected then cross compile mode will be used." >&2 + elif test "x$build_alias" != "x$host_alias"; then + cross_compiling=yes + fi +fi + +ac_tool_prefix= +test -n "$host_alias" && ac_tool_prefix=$host_alias- + +test "$silent" = yes && exec 6>/dev/null + + +ac_pwd=`pwd` && test -n "$ac_pwd" && +ac_ls_di=`ls -di .` && +ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || + { echo "$as_me: error: Working directory cannot be determined" >&2 + { (exit 1); exit 1; }; } +test "X$ac_ls_di" = "X$ac_pwd_ls_di" || + { echo "$as_me: error: pwd does not report name of working directory" >&2 + { (exit 1); exit 1; }; } + + +# Find the source files, if location was not specified. +if test -z "$srcdir"; then + ac_srcdir_defaulted=yes + # Try the directory containing this script, then the parent directory. + ac_confdir=`$as_dirname -- "$0" || +$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$0" : 'X\(//\)[^/]' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +echo X"$0" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + srcdir=$ac_confdir + if test ! -r "$srcdir/$ac_unique_file"; then + srcdir=.. + fi +else + ac_srcdir_defaulted=no +fi +if test ! -r "$srcdir/$ac_unique_file"; then + test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." + { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 + { (exit 1); exit 1; }; } +fi +ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" +ac_abs_confdir=`( + cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2 + { (exit 1); exit 1; }; } + pwd)` +# When building in place, set srcdir=. +if test "$ac_abs_confdir" = "$ac_pwd"; then + srcdir=. +fi +# Remove unnecessary trailing slashes from srcdir. +# Double slashes in file names in object file debugging info +# mess up M-x gdb in Emacs. +case $srcdir in +*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; +esac +for ac_var in $ac_precious_vars; do + eval ac_env_${ac_var}_set=\${${ac_var}+set} + eval ac_env_${ac_var}_value=\$${ac_var} + eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} + eval ac_cv_env_${ac_var}_value=\$${ac_var} +done + +# +# Report the --help message. +# +if test "$ac_init_help" = "long"; then + # Omit some internal or obsolete options to make the list less imposing. + # This message is too long to be a string in the A/UX 3.1 sh. + cat <<_ACEOF +\`configure' configures Rogue 5.4.4 to adapt to many kinds of systems. + +Usage: $0 [OPTION]... [VAR=VALUE]... + +To assign environment variables (e.g., CC, CFLAGS...), specify them as +VAR=VALUE. See below for descriptions of some of the useful variables. + +Defaults for the options are specified in brackets. + +Configuration: + -h, --help display this help and exit + --help=short display options specific to this package + --help=recursive display the short help of all the included packages + -V, --version display version information and exit + -q, --quiet, --silent do not print \`checking...' messages + --cache-file=FILE cache test results in FILE [disabled] + -C, --config-cache alias for \`--cache-file=config.cache' + -n, --no-create do not create output files + --srcdir=DIR find the sources in DIR [configure dir or \`..'] + +Installation directories: + --prefix=PREFIX install architecture-independent files in PREFIX + [$ac_default_prefix] + --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX + [PREFIX] + +By default, \`make install' will install all the files in +\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify +an installation prefix other than \`$ac_default_prefix' using \`--prefix', +for instance \`--prefix=\$HOME'. + +For better control, use the options below. + +Fine tuning of the installation directories: + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/rogue] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] +_ACEOF + + cat <<\_ACEOF + +System types: + --build=BUILD configure for building on BUILD [guessed] + --host=HOST cross-compile to build programs to run on HOST [BUILD] + --target=TARGET configure for building compilers for TARGET [HOST] +_ACEOF +fi + +if test -n "$ac_init_help"; then + case $ac_init_help in + short | recursive ) echo "Configuration of Rogue 5.4.4:";; + esac + cat <<\_ACEOF + +Optional Features: + --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) + --enable-FEATURE[=ARG] include FEATURE [ARG=yes] + --enable-setgid=NAME install executable as setgid with group ownership of + NAME [default=no]] + --enable-scorefile=SCOREFILE + enable scoreboard with given filename + --enable-lockfile=LOCKFILE + enable scoreboard lockfile with given filename + --enable-wizardmode enable availability of wizard mode [default=no] + --enable-allscores enable scoreboard to show top scores, not just top + players [default=yes] + --enable-checktime enable checktime [default=no] + --enable-maxload enable maxload [default=no] + --enable-maxusers enable maxuser [default=no] + --enable-numscores number of scores to store in scoreboard [default=10] + --enable-numname word for number of scores to store in scoreboard + [default=Ten] + --enable-loadav=NAMELIST + use program's load average function (unlikely to + work) [default=no] + --enable-ucount=UTMPFILE + use program's own function to count users (unlikely + to work) [default=no] + +Optional Packages: + --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] + --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) + --with-ncurses Force the use of ncurses over curses + --with-program-name=NAME + alternate executable name + +Some influential environment variables: + CC C compiler command + CFLAGS C compiler flags + LDFLAGS linker flags, e.g. -L if you have libraries in a + nonstandard directory + LIBS libraries to pass to the linker, e.g. -l + CPPFLAGS C/C++/Objective C preprocessor flags, e.g. -I if + you have headers in a nonstandard directory + CPP C preprocessor + +Use these variables to override the choices made by `configure' or to help +it to find libraries and programs with nonstandard names/locations. + +Report bugs to . +_ACEOF +ac_status=$? +fi + +if test "$ac_init_help" = "recursive"; then + # If there are subdirs, report their specific --help. + for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue + test -d "$ac_dir" || continue + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + cd "$ac_dir" || { ac_status=$?; continue; } + # Check for guested configure. + if test -f "$ac_srcdir/configure.gnu"; then + echo && + $SHELL "$ac_srcdir/configure.gnu" --help=recursive + elif test -f "$ac_srcdir/configure"; then + echo && + $SHELL "$ac_srcdir/configure" --help=recursive + else + echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + fi || ac_status=$? + cd "$ac_pwd" || { ac_status=$?; break; } + done +fi + +test -n "$ac_init_help" && exit $ac_status +if $ac_init_version; then + cat <<\_ACEOF +Rogue configure 5.4.4 +generated by GNU Autoconf 2.61 + +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, +2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +This configure script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it. +_ACEOF + exit +fi +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. + +It was created by Rogue $as_me 5.4.4, which was +generated by GNU Autoconf 2.61. Invocation command line was + + $ $0 $@ + +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## + +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` + +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` + +_ASUNAME + +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + echo "PATH: $as_dir" +done +IFS=$as_save_IFS + +} >&5 + +cat >&5 <<_ACEOF + + +## ----------- ## +## Core tests. ## +## ----------- ## + +_ACEOF + + +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;; + 2) + ac_configure_args1="$ac_configure_args1 '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; + esac + fi + ac_configure_args="$ac_configure_args '$ac_arg'" + ;; + esac + done +done +$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; } +$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; } + +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo + + cat <<\_ASBOX +## ---------------- ## +## Cache variables. ## +## ---------------- ## +_ASBOX + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 +echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + *) $as_unset $ac_var ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo + + cat <<\_ASBOX +## ----------------- ## +## Output variables. ## +## ----------------- ## +_ASBOX + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + echo "$ac_var='\''$ac_val'\''" + done | sort + echo + + if test -n "$ac_subst_files"; then + cat <<\_ASBOX +## ------------------- ## +## File substitutions. ## +## ------------------- ## +_ASBOX + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + echo "$ac_var='\''$ac_val'\''" + done | sort + echo + fi + + if test -s confdefs.h; then + cat <<\_ASBOX +## ----------- ## +## confdefs.h. ## +## ----------- ## +_ASBOX + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + echo "$as_me: caught signal $ac_signal" + echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal +done +ac_signal=0 + +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h + +# Predefined preprocessor variables. + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF + + +# Let the site file select an alternate cache file if it wants to. +# Prefer explicitly selected file to automatically selected ones. +if test -n "$CONFIG_SITE"; then + set x "$CONFIG_SITE" +elif test "x$prefix" != xNONE; then + set x "$prefix/share/config.site" "$prefix/etc/config.site" +else + set x "$ac_default_prefix/share/config.site" \ + "$ac_default_prefix/etc/config.site" +fi +shift +for ac_site_file +do + if test -r "$ac_site_file"; then + { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 +echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" + fi +done + +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special + # files actually), so we avoid doing that. + if test -f "$cache_file"; then + { echo "$as_me:$LINENO: loading cache $cache_file" >&5 +echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { echo "$as_me:$LINENO: creating cache $cache_file" >&5 +echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi + +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 +echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + { echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 +echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + { echo "$as_me:$LINENO: former value: $ac_old_val" >&5 +echo "$as_me: former value: $ac_old_val" >&2;} + { echo "$as_me:$LINENO: current value: $ac_new_val" >&5 +echo "$as_me: current value: $ac_new_val" >&2;} + ac_cache_corrupted=: + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) ac_configure_args="$ac_configure_args '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 +echo "$as_me: error: changes in the environment can compromise the build" >&2;} + { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 +echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} + { (exit 1); exit 1; }; } +fi + + + + + + + + + + + + + + + + + + + + + + + + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + +ac_config_headers="$ac_config_headers config.h" + +ac_config_files="$ac_config_files Makefile rogue.6 rogue.cat rogue.doc rogue.html rogue.me" + +ac_aux_dir= +for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do + if test -f "$ac_dir/install-sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install-sh -c" + break + elif test -f "$ac_dir/install.sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install.sh -c" + break + elif test -f "$ac_dir/shtool"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/shtool install -c" + break + fi +done +if test -z "$ac_aux_dir"; then + { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5 +echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;} + { (exit 1); exit 1; }; } +fi + +# These three variables are undocumented and unsupported, +# and are intended to be withdrawn in a future Autoconf release. +# They can cause serious problems if a builder's source tree is in a directory +# whose full name contains unusual characters. +ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. +ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. +ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. + + +# Make sure we can run config.sub. +$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || + { { echo "$as_me:$LINENO: error: cannot run $SHELL $ac_aux_dir/config.sub" >&5 +echo "$as_me: error: cannot run $SHELL $ac_aux_dir/config.sub" >&2;} + { (exit 1); exit 1; }; } + +{ echo "$as_me:$LINENO: checking build system type" >&5 +echo $ECHO_N "checking build system type... $ECHO_C" >&6; } +if test "${ac_cv_build+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_build_alias=$build_alias +test "x$ac_build_alias" = x && + ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` +test "x$ac_build_alias" = x && + { { echo "$as_me:$LINENO: error: cannot guess build type; you must specify one" >&5 +echo "$as_me: error: cannot guess build type; you must specify one" >&2;} + { (exit 1); exit 1; }; } +ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || + { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&5 +echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&2;} + { (exit 1); exit 1; }; } + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_build" >&5 +echo "${ECHO_T}$ac_cv_build" >&6; } +case $ac_cv_build in +*-*-*) ;; +*) { { echo "$as_me:$LINENO: error: invalid value of canonical build" >&5 +echo "$as_me: error: invalid value of canonical build" >&2;} + { (exit 1); exit 1; }; };; +esac +build=$ac_cv_build +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_build +shift +build_cpu=$1 +build_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +build_os=$* +IFS=$ac_save_IFS +case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac + + +{ echo "$as_me:$LINENO: checking host system type" >&5 +echo $ECHO_N "checking host system type... $ECHO_C" >&6; } +if test "${ac_cv_host+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "x$host_alias" = x; then + ac_cv_host=$ac_cv_build +else + ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || + { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&5 +echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&2;} + { (exit 1); exit 1; }; } +fi + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_host" >&5 +echo "${ECHO_T}$ac_cv_host" >&6; } +case $ac_cv_host in +*-*-*) ;; +*) { { echo "$as_me:$LINENO: error: invalid value of canonical host" >&5 +echo "$as_me: error: invalid value of canonical host" >&2;} + { (exit 1); exit 1; }; };; +esac +host=$ac_cv_host +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_host +shift +host_cpu=$1 +host_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +host_os=$* +IFS=$ac_save_IFS +case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac + + +{ echo "$as_me:$LINENO: checking target system type" >&5 +echo $ECHO_N "checking target system type... $ECHO_C" >&6; } +if test "${ac_cv_target+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "x$target_alias" = x; then + ac_cv_target=$ac_cv_host +else + ac_cv_target=`$SHELL "$ac_aux_dir/config.sub" $target_alias` || + { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $target_alias failed" >&5 +echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $target_alias failed" >&2;} + { (exit 1); exit 1; }; } +fi + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_target" >&5 +echo "${ECHO_T}$ac_cv_target" >&6; } +case $ac_cv_target in +*-*-*) ;; +*) { { echo "$as_me:$LINENO: error: invalid value of canonical target" >&5 +echo "$as_me: error: invalid value of canonical target" >&2;} + { (exit 1); exit 1; }; };; +esac +target=$ac_cv_target +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_target +shift +target_cpu=$1 +target_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +target_os=$* +IFS=$ac_save_IFS +case $target_os in *\ *) target_os=`echo "$target_os" | sed 's/ /-/g'`;; esac + + +# The aliases save the names the user supplied, while $host etc. +# will get canonicalized. +test -n "$target_alias" && + test "$program_prefix$program_suffix$program_transform_name" = \ + NONENONEs,x,x, && + program_prefix=${target_alias}- + +# Checks for programs. +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { echo "$as_me:$LINENO: result: $CC" >&5 +echo "${ECHO_T}$CC" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CC="gcc" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +echo "${ECHO_T}$ac_ct_CC" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { echo "$as_me:$LINENO: result: $CC" >&5 +echo "${ECHO_T}$CC" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { echo "$as_me:$LINENO: result: $CC" >&5 +echo "${ECHO_T}$CC" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { echo "$as_me:$LINENO: result: $CC" >&5 +echo "${ECHO_T}$CC" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CC="$ac_prog" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 +echo "${ECHO_T}$ac_ct_CC" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + + test -n "$ac_ct_CC" && break +done + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&5 +echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools +whose name does not start with the host triplet. If you think this +configuration is useful to you, please write to autoconf@gnu.org." >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +fi + +fi + + +test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH +See \`config.log' for more details." >&5 +echo "$as_me: error: no acceptable C compiler found in \$PATH +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } + +# Provide some information about the compiler. +echo "$as_me:$LINENO: checking for C compiler version" >&5 +ac_compiler=`set X $ac_compile; echo $2` +{ (ac_try="$ac_compiler --version >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compiler --version >&5") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (ac_try="$ac_compiler -v >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compiler -v >&5") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } +{ (ac_try="$ac_compiler -V >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compiler -V >&5") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 +echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6; } +ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` +# +# List of possible output files, starting from the most likely. +# The algorithm is not robust to junk in `.', hence go to wildcards (a.*) +# only as a last resort. b.out is created by i960 compilers. +ac_files='a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out' +# +# The IRIX 6 linker writes into existing files which may not be +# executable, retaining their permissions. Remove them first so a +# subsequent execution test works. +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { (ac_try="$ac_link_default" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link_default") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= + +else + ac_file='' +fi + +{ echo "$as_me:$LINENO: result: $ac_file" >&5 +echo "${ECHO_T}$ac_file" >&6; } +if test -z "$ac_file"; then + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { echo "$as_me:$LINENO: error: C compiler cannot create executables +See \`config.log' for more details." >&5 +echo "$as_me: error: C compiler cannot create executables +See \`config.log' for more details." >&2;} + { (exit 77); exit 77; }; } +fi + +ac_exeext=$ac_cv_exeext + +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ echo "$as_me:$LINENO: checking whether the C compiler works" >&5 +echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6; } +# FIXME: These cross compiler hacks should be removed for Autoconf 3.0 +# If not cross compiling, check that we can run a simple program. +if test "$cross_compiling" != yes; then + if { ac_try='./$ac_file' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { echo "$as_me:$LINENO: error: cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } + fi + fi +fi +{ echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6; } + +rm -f a.out a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 +echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6; } +{ echo "$as_me:$LINENO: result: $cross_compiling" >&5 +echo "${ECHO_T}$cross_compiling" >&6; } + +{ echo "$as_me:$LINENO: checking for suffix of executables" >&5 +echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6; } +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac +done +else + { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } +fi + +rm -f conftest$ac_cv_exeext +{ echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 +echo "${ECHO_T}$ac_cv_exeext" >&6; } + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +{ echo "$as_me:$LINENO: checking for suffix of object files" >&5 +echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6; } +if test "${ac_cv_objext+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.o conftest.obj +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; then + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile +See \`config.log' for more details." >&5 +echo "$as_me: error: cannot compute suffix of object files: cannot compile +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } +fi + +rm -f conftest.$ac_cv_objext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 +echo "${ECHO_T}$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 +echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6; } +if test "${ac_cv_c_compiler_gnu+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_compiler_gnu=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_compiler_gnu=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 +echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6; } +GCC=`test $ac_compiler_gnu = yes && echo yes` +ac_test_CFLAGS=${CFLAGS+set} +ac_save_CFLAGS=$CFLAGS +{ echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 +echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6; } +if test "${ac_cv_prog_cc_g+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_cc_g=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + CFLAGS="" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + : +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_cc_g=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag +fi +{ echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 +echo "${ECHO_T}$ac_cv_prog_cc_g" >&6; } +if test "$ac_test_CFLAGS" = set; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +{ echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5 +echo $ECHO_N "checking for $CC option to accept ISO C89... $ECHO_C" >&6; } +if test "${ac_cv_prog_cc_c89+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include +#include +#include +/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct buf { int x; }; +FILE * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} + +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not '\xHH' hex character constants. + These don't provoke an error unfortunately, instead are silently treated + as 'x'. The following induces an error, until -std is added to get + proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an + array size at least. It's necessary to write '\x00'==0 to get something + that's true only with -std. */ +int osf4_cc_array ['\x00' == 0 ? 1 : -1]; + +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) 'x' +int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; + +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); +int argc; +char **argv; +int +main () +{ +return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; + ; + return 0; +} +_ACEOF +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ + -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_prog_cc_c89=$ac_arg +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + +fi + +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC + +fi +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c89" in + x) + { echo "$as_me:$LINENO: result: none needed" >&5 +echo "${ECHO_T}none needed" >&6; } ;; + xno) + { echo "$as_me:$LINENO: result: unsupported" >&5 +echo "${ECHO_T}unsupported" >&6; } ;; + *) + CC="$CC $ac_cv_prog_cc_c89" + { echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5 +echo "${ECHO_T}$ac_cv_prog_cc_c89" >&6; } ;; +esac + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +# Checks for libraries. + +# Checks for header files. + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 +echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if test "${ac_cv_prog_CPP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + # Double quotes because CPP needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + : +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Broken: fails on valid input. +continue +fi + +rm -f conftest.err conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + # Broken: success on invalid input. +continue +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Passes both tests. +ac_preproc_ok=: +break +fi + +rm -f conftest.err conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then + break +fi + + done + ac_cv_prog_CPP=$CPP + +fi + CPP=$ac_cv_prog_CPP +else + ac_cv_prog_CPP=$CPP +fi +{ echo "$as_me:$LINENO: result: $CPP" >&5 +echo "${ECHO_T}$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + : +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Broken: fails on valid input. +continue +fi + +rm -f conftest.err conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + # Broken: success on invalid input. +continue +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + # Passes both tests. +ac_preproc_ok=: +break +fi + +rm -f conftest.err conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.err conftest.$ac_ext +if $ac_preproc_ok; then + : +else + { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details." >&5 +echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details." >&2;} + { (exit 1); exit 1; }; } +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +{ echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5 +echo $ECHO_N "checking for grep that handles long lines and -e... $ECHO_C" >&6; } +if test "${ac_cv_path_GREP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + # Extract the first word of "grep ggrep" to use in msg output +if test -z "$GREP"; then +set dummy grep ggrep; ac_prog_name=$2 +if test "${ac_cv_path_GREP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_path_GREP_found=false +# Loop through the user's path and test for each of PROGNAME-LIST +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in grep ggrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue + # Check for GNU ac_path_GREP and select it if it is found. + # Check for GNU $ac_path_GREP +case `"$ac_path_GREP" --version 2>&1` in +*GNU*) + ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +*) + ac_count=0 + echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + echo 'GREP' >> "conftest.nl" + "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + ac_count=`expr $ac_count + 1` + if test $ac_count -gt ${ac_path_GREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_GREP="$ac_path_GREP" + ac_path_GREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + + $ac_path_GREP_found && break 3 + done +done + +done +IFS=$as_save_IFS + + +fi + +GREP="$ac_cv_path_GREP" +if test -z "$GREP"; then + { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 +echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} + { (exit 1); exit 1; }; } +fi + +else + ac_cv_path_GREP=$GREP +fi + + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5 +echo "${ECHO_T}$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" + + +{ echo "$as_me:$LINENO: checking for egrep" >&5 +echo $ECHO_N "checking for egrep... $ECHO_C" >&6; } +if test "${ac_cv_path_EGREP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + # Extract the first word of "egrep" to use in msg output +if test -z "$EGREP"; then +set dummy egrep; ac_prog_name=$2 +if test "${ac_cv_path_EGREP+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_path_EGREP_found=false +# Loop through the user's path and test for each of PROGNAME-LIST +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue + # Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + ac_count=`expr $ac_count + 1` + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + + $ac_path_EGREP_found && break 3 + done +done + +done +IFS=$as_save_IFS + + +fi + +EGREP="$ac_cv_path_EGREP" +if test -z "$EGREP"; then + { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 +echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} + { (exit 1); exit 1; }; } +fi + +else + ac_cv_path_EGREP=$EGREP +fi + + + fi +fi +{ echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5 +echo "${ECHO_T}$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + + +{ echo "$as_me:$LINENO: checking for ANSI C header files" >&5 +echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6; } +if test "${ac_cv_header_stdc+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_header_stdc=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_header_stdc=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then + : +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then + : +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then + : +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + : +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + +fi +fi +{ echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 +echo "${ECHO_T}$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +cat >>confdefs.h <<\_ACEOF +#define STDC_HEADERS 1 +_ACEOF + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. + + + + + + + + + +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do +as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` +{ echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default + +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + eval "$as_ac_Header=yes" +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + eval "$as_ac_Header=no" +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +ac_res=`eval echo '${'$as_ac_Header'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } +if test `eval echo '${'$as_ac_Header'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + + + + + + + + + + + + + + + +for ac_header in arpa/inet.h sys/utsname.h pwd.h fcntl.h limits.h nlist.h stdlib.h string.h sys/ioctl.h termios.h unistd.h utmp.h term.h ncurses/term.h process.h +do +as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + { echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +fi +ac_res=`eval echo '${'$as_ac_Header'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } +else + # Is the header compilable? +{ echo "$as_me:$LINENO: checking $ac_header usability" >&5 +echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_header_compiler=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_compiler=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +echo "${ECHO_T}$ac_header_compiler" >&6; } + +# Is the header present? +{ echo "$as_me:$LINENO: checking $ac_header presence" >&5 +echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include <$ac_header> +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + ac_header_preproc=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_preproc=no +fi + +rm -f conftest.err conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +echo "${ECHO_T}$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in + yes:no: ) + { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 +echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 +echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 +echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 +echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 +echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 +echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} + ( cat <<\_ASBOX +## ------------------------------------ ## +## Report this to yendor@rogueforge.net ## +## ------------------------------------ ## +_ASBOX + ) | sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac +{ echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + eval "$as_ac_Header=\$ac_header_preproc" +fi +ac_res=`eval echo '${'$as_ac_Header'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } + +fi +if test `eval echo '${'$as_ac_Header'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + +# Checks for typedefs, structures, and compiler characteristics. +{ echo "$as_me:$LINENO: checking for stdbool.h that conforms to C99" >&5 +echo $ECHO_N "checking for stdbool.h that conforms to C99... $ECHO_C" >&6; } +if test "${ac_cv_header_stdbool_h+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +#include +#ifndef bool + "error: bool is not defined" +#endif +#ifndef false + "error: false is not defined" +#endif +#if false + "error: false is not 0" +#endif +#ifndef true + "error: true is not defined" +#endif +#if true != 1 + "error: true is not 1" +#endif +#ifndef __bool_true_false_are_defined + "error: __bool_true_false_are_defined is not defined" +#endif + + struct s { _Bool s: 1; _Bool t; } s; + + char a[true == 1 ? 1 : -1]; + char b[false == 0 ? 1 : -1]; + char c[__bool_true_false_are_defined == 1 ? 1 : -1]; + char d[(bool) 0.5 == true ? 1 : -1]; + bool e = &s; + char f[(_Bool) 0.0 == false ? 1 : -1]; + char g[true]; + char h[sizeof (_Bool)]; + char i[sizeof s.t]; + enum { j = false, k = true, l = false * true, m = true * 256 }; + _Bool n[m]; + char o[sizeof n == m * sizeof n[0] ? 1 : -1]; + char p[-1 - (_Bool) 0 < 0 && -1 - (bool) 0 < 0 ? 1 : -1]; +# if defined __xlc__ || defined __GNUC__ + /* Catch a bug in IBM AIX xlc compiler version 6.0.0.0 + reported by James Lemley on 2005-10-05; see + http://lists.gnu.org/archive/html/bug-coreutils/2005-10/msg00086.html + This test is not quite right, since xlc is allowed to + reject this program, as the initializer for xlcbug is + not one of the forms that C requires support for. + However, doing the test right would require a runtime + test, and that would make cross-compilation harder. + Let us hope that IBM fixes the xlc bug, and also adds + support for this kind of constant expression. In the + meantime, this test will reject xlc, which is OK, since + our stdbool.h substitute should suffice. We also test + this with GCC, where it should work, to detect more + quickly whether someone messes up the test in the + future. */ + char digs[] = "0123456789"; + int xlcbug = 1 / (&(digs + 5)[-2 + (bool) 1] == &digs[4] ? 1 : -1); +# endif + /* Catch a bug in an HP-UX C compiler. See + http://gcc.gnu.org/ml/gcc-patches/2003-12/msg02303.html + http://lists.gnu.org/archive/html/bug-coreutils/2005-11/msg00161.html + */ + _Bool q = true; + _Bool *pq = &q; + +int +main () +{ + + *pq |= q; + *pq |= ! q; + /* Refer to every declared value, to avoid compiler optimizations. */ + return (!a + !b + !c + !d + !e + !f + !g + !h + !i + !!j + !k + !!l + + !m + !n + !o + !p + !q + !pq); + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_header_stdbool_h=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_header_stdbool_h=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_header_stdbool_h" >&5 +echo "${ECHO_T}$ac_cv_header_stdbool_h" >&6; } +{ echo "$as_me:$LINENO: checking for _Bool" >&5 +echo $ECHO_N "checking for _Bool... $ECHO_C" >&6; } +if test "${ac_cv_type__Bool+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +typedef _Bool ac__type_new_; +int +main () +{ +if ((ac__type_new_ *) 0) + return 0; +if (sizeof (ac__type_new_)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_type__Bool=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type__Bool=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5 +echo "${ECHO_T}$ac_cv_type__Bool" >&6; } +if test $ac_cv_type__Bool = yes; then + +cat >>confdefs.h <<_ACEOF +#define HAVE__BOOL 1 +_ACEOF + + +fi + +if test $ac_cv_header_stdbool_h = yes; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_STDBOOL_H 1 +_ACEOF + +fi + +{ echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5 +echo $ECHO_N "checking for an ANSI C-conforming const... $ECHO_C" >&6; } +if test "${ac_cv_c_const+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ +/* FIXME: Include the comments suggested by Paul. */ +#ifndef __cplusplus + /* Ultrix mips cc rejects this. */ + typedef int charset[2]; + const charset cs; + /* SunOS 4.1.1 cc rejects this. */ + char const *const *pcpcc; + char **ppc; + /* NEC SVR4.0.2 mips cc rejects this. */ + struct point {int x, y;}; + static struct point const zero = {0,0}; + /* AIX XL C 1.02.0.0 rejects this. + It does not let you subtract one const X* pointer from another in + an arm of an if-expression whose if-part is not a constant + expression */ + const char *g = "string"; + pcpcc = &g + (g ? g-g : 0); + /* HPUX 7.0 cc rejects these. */ + ++pcpcc; + ppc = (char**) pcpcc; + pcpcc = (char const *const *) ppc; + { /* SCO 3.2v4 cc rejects this. */ + char *t; + char const *s = 0 ? (char *) 0 : (char const *) 0; + + *t++ = 0; + if (s) return 0; + } + { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ + int x[] = {25, 17}; + const int *foo = &x[0]; + ++foo; + } + { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ + typedef const int *iptr; + iptr p = 0; + ++p; + } + { /* AIX XL C 1.02.0.0 rejects this saying + "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ + struct s { int j; const int *ap[3]; }; + struct s *b; b->j = 5; + } + { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ + const int foo = 10; + if (!foo) return 0; + } + return !cs[0] && !zero.x; +#endif + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_c_const=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_c_const=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5 +echo "${ECHO_T}$ac_cv_c_const" >&6; } +if test $ac_cv_c_const = no; then + +cat >>confdefs.h <<\_ACEOF +#define const +_ACEOF + +fi + +{ echo "$as_me:$LINENO: checking for uid_t in sys/types.h" >&5 +echo $ECHO_N "checking for uid_t in sys/types.h... $ECHO_C" >&6; } +if test "${ac_cv_type_uid_t+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "uid_t" >/dev/null 2>&1; then + ac_cv_type_uid_t=yes +else + ac_cv_type_uid_t=no +fi +rm -f conftest* + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_type_uid_t" >&5 +echo "${ECHO_T}$ac_cv_type_uid_t" >&6; } +if test $ac_cv_type_uid_t = no; then + +cat >>confdefs.h <<\_ACEOF +#define uid_t int +_ACEOF + + +cat >>confdefs.h <<\_ACEOF +#define gid_t int +_ACEOF + +fi + +{ echo "$as_me:$LINENO: checking for size_t" >&5 +echo $ECHO_N "checking for size_t... $ECHO_C" >&6; } +if test "${ac_cv_type_size_t+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +typedef size_t ac__type_new_; +int +main () +{ +if ((ac__type_new_ *) 0) + return 0; +if (sizeof (ac__type_new_)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_type_size_t=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_size_t=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5 +echo "${ECHO_T}$ac_cv_type_size_t" >&6; } +if test $ac_cv_type_size_t = yes; then + : +else + +cat >>confdefs.h <<_ACEOF +#define size_t unsigned int +_ACEOF + +fi + +{ echo "$as_me:$LINENO: checking whether struct tm is in sys/time.h or time.h" >&5 +echo $ECHO_N "checking whether struct tm is in sys/time.h or time.h... $ECHO_C" >&6; } +if test "${ac_cv_struct_tm+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include + +int +main () +{ +struct tm tm; + int *p = &tm.tm_sec; + return !p; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_struct_tm=time.h +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_struct_tm=sys/time.h +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_struct_tm" >&5 +echo "${ECHO_T}$ac_cv_struct_tm" >&6; } +if test $ac_cv_struct_tm = sys/time.h; then + +cat >>confdefs.h <<\_ACEOF +#define TM_IN_SYS_TIME 1 +_ACEOF + +fi + + +# Check whether --with-ncurses was given. +if test "${with_ncurses+set}" = set; then + withval=$with_ncurses; +fi + + mp_save_LIBS="$LIBS" + CURSES_LIB="" + if test "$with_ncurses" != yes + then + { echo "$as_me:$LINENO: checking for working curses" >&5 +echo $ECHO_N "checking for working curses... $ECHO_C" >&6; } +if test "${mp_cv_curses+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + LIBS="$LIBS -lcurses" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +int +main () +{ +chtype a; int b=A_STANDOUT, c=KEY_LEFT; initscr(); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + mp_cv_curses=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + mp_cv_curses=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $mp_cv_curses" >&5 +echo "${ECHO_T}$mp_cv_curses" >&6; } + if test "$mp_cv_curses" = yes + then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_CURSES_H 1 +_ACEOF + + #AC_DEFINE(HAVE_CURSES_H) + CURSES_LIB="-lcurses" + fi + fi + if test ! "$CURSES_LIB" + then + { echo "$as_me:$LINENO: checking for working ncurses" >&5 +echo $ECHO_N "checking for working ncurses... $ECHO_C" >&6; } +if test "${mp_cv_ncurses+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + LIBS="$mp_save_LIBS -lncurses" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +int +main () +{ +chtype a; int b=A_STANDOUT, c=KEY_LEFT; initscr(); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + mp_cv_ncurses=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + mp_cv_ncurses=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $mp_cv_ncurses" >&5 +echo "${ECHO_T}$mp_cv_ncurses" >&6; } + if test "$mp_cv_ncurses" = yes + then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_NCURSES_H 1 +_ACEOF + + CURSES_LIB="-lncurses" + fi + fi + if test ! "$CURSES_LIB" + then + { echo "$as_me:$LINENO: checking for working pdcurses" >&5 +echo $ECHO_N "checking for working pdcurses... $ECHO_C" >&6; } +if test "${mp_cv_pdcurses+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + LIBS="$mp_save_LIBS -lpdcurses" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +int +main () +{ +chtype a; int b=A_STANDOUT, c=KEY_LEFT; initscr(); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + mp_cv_pdcurses=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + mp_cv_pdcurses=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $mp_cv_pdcurses" >&5 +echo "${ECHO_T}$mp_cv_pdcurses" >&6; } + if test "$mp_cv_pdcurses" = yes + then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_CURSES_H 1 +_ACEOF + + CURSES_LIB="-lpdcurses" + fi + fi + if test ! "$CURSES_LIB" + then + { echo "$as_me:$LINENO: checking for working pdcur" >&5 +echo $ECHO_N "checking for working pdcur... $ECHO_C" >&6; } +if test "${mp_cv_pdcur+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + LIBS="$mp_save_LIBS -lpdcur" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +int +main () +{ +chtype a; int b=A_STANDOUT, c=KEY_LEFT; initscr(); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + mp_cv_pdcur=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + mp_cv_pdcur=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $mp_cv_pdcur" >&5 +echo "${ECHO_T}$mp_cv_pdcur" >&6; } + if test "$mp_cv_pdcur" = yes + then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_CURSES_H 1 +_ACEOF + + CURSES_LIB="-lpdcur" + fi + fi + if test ! "$CURSES_LIB" + then + { echo "$as_me:$LINENO: checking for working peer pdcurses" >&5 +echo $ECHO_N "checking for working peer pdcurses... $ECHO_C" >&6; } +if test "${mp_cv_lpdcurses+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + LIBS="$mp_save_LIBS ../pdcurses/pdcurses.a" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include "../pdcurses/curses.h" +int +main () +{ +chtype a; int b=A_STANDOUT, c=KEY_LEFT; initscr(); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + mp_cv_lpdcurses=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + mp_cv_lpdcurses=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $mp_cv_lpdcurses" >&5 +echo "${ECHO_T}$mp_cv_lpdcurses" >&6; } + if test "$mp_cv_lpdcurses" = yes + then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_CURSES_H 1 +_ACEOF + + CURSES_LIB="../pdcurses/pdcurses.a" + + if test "x$CPPFLAGS" = "x"; then + test "x$silent" != "xyes" && echo " setting CPPFLAGS to \""-I../pdcurses"\"" + CPPFLAGS=""-I../pdcurses"" + else + apr_addto_bugger=""-I../pdcurses"" + for i in $apr_addto_bugger; do + apr_addto_duplicate="0" + for j in $CPPFLAGS; do + if test "x$i" = "x$j"; then + apr_addto_duplicate="1" + break + fi + done + if test $apr_addto_duplicate = "0"; then + test "x$silent" != "xyes" && echo " adding \"$i\" to CPPFLAGS" + CPPFLAGS="$CPPFLAGS $i" + fi + done + fi + + fi + fi + { echo "$as_me:$LINENO: checking for ESCDELAY variable" >&5 +echo $ECHO_N "checking for ESCDELAY variable... $ECHO_C" >&6; } +if test "${mc_cv_ncurses_escdelay+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +int +main () +{ + + extern int ESCDELAY; + ESCDELAY = 0; + + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + mc_cv_ncurses_escdelay=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + mc_cv_ncurses_escdelay=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext + +fi +{ echo "$as_me:$LINENO: result: $mc_cv_ncurses_escdelay" >&5 +echo "${ECHO_T}$mc_cv_ncurses_escdelay" >&6; } + if test "$mc_cv_ncurses_escdelay" = yes; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_ESCDELAY 1 +_ACEOF + + fi + if test ! "$CURSES_LIB" ; then + LIBS="$mp_save_LIBS" + fi + +# Checks for library functions. +{ echo "$as_me:$LINENO: checking for pid_t" >&5 +echo $ECHO_N "checking for pid_t... $ECHO_C" >&6; } +if test "${ac_cv_type_pid_t+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +typedef pid_t ac__type_new_; +int +main () +{ +if ((ac__type_new_ *) 0) + return 0; +if (sizeof (ac__type_new_)) + return 0; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_type_pid_t=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_pid_t=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 +echo "${ECHO_T}$ac_cv_type_pid_t" >&6; } +if test $ac_cv_type_pid_t = yes; then + : +else + +cat >>confdefs.h <<_ACEOF +#define pid_t int +_ACEOF + +fi + + +for ac_header in vfork.h +do +as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + { echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +fi +ac_res=`eval echo '${'$as_ac_Header'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } +else + # Is the header compilable? +{ echo "$as_me:$LINENO: checking $ac_header usability" >&5 +echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +#include <$ac_header> +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_header_compiler=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_compiler=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 +echo "${ECHO_T}$ac_header_compiler" >&6; } + +# Is the header present? +{ echo "$as_me:$LINENO: checking $ac_header presence" >&5 +echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; } +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include <$ac_header> +_ACEOF +if { (ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } >/dev/null && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then + ac_header_preproc=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_header_preproc=no +fi + +rm -f conftest.err conftest.$ac_ext +{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 +echo "${ECHO_T}$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in + yes:no: ) + { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 +echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} + ac_header_preproc=yes + ;; + no:yes:* ) + { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 +echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 +echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 +echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 +echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 +echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} + { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 +echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} + ( cat <<\_ASBOX +## ------------------------------------ ## +## Report this to yendor@rogueforge.net ## +## ------------------------------------ ## +_ASBOX + ) | sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac +{ echo "$as_me:$LINENO: checking for $ac_header" >&5 +echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } +if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + eval "$as_ac_Header=\$ac_header_preproc" +fi +ac_res=`eval echo '${'$as_ac_Header'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } + +fi +if test `eval echo '${'$as_ac_Header'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + +for ac_func in fork vfork +do +as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ echo "$as_me:$LINENO: checking for $ac_func" >&5 +echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define $ac_func to an innocuous variant, in case declares $ac_func. + For example, HP-UX 11i declares gettimeofday. */ +#define $ac_func innocuous_$ac_func + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $ac_func (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef $ac_func + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $ac_func (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$ac_func || defined __stub___$ac_func +choke me +#endif + +int +main () +{ +return $ac_func (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + eval "$as_ac_var=yes" +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + eval "$as_ac_var=no" +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +ac_res=`eval echo '${'$as_ac_var'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } +if test `eval echo '${'$as_ac_var'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + +if test "x$ac_cv_func_fork" = xyes; then + { echo "$as_me:$LINENO: checking for working fork" >&5 +echo $ECHO_N "checking for working fork... $ECHO_C" >&6; } +if test "${ac_cv_func_fork_works+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then + ac_cv_func_fork_works=cross +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ + + /* By Ruediger Kuhlmann. */ + return fork () < 0; + + ; + return 0; +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_func_fork_works=yes +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_func_fork_works=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func_fork_works" >&5 +echo "${ECHO_T}$ac_cv_func_fork_works" >&6; } + +else + ac_cv_func_fork_works=$ac_cv_func_fork +fi +if test "x$ac_cv_func_fork_works" = xcross; then + case $host in + *-*-amigaos* | *-*-msdosdjgpp*) + # Override, as these systems have only a dummy fork() stub + ac_cv_func_fork_works=no + ;; + *) + ac_cv_func_fork_works=yes + ;; + esac + { echo "$as_me:$LINENO: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&5 +echo "$as_me: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&2;} +fi +ac_cv_func_vfork_works=$ac_cv_func_vfork +if test "x$ac_cv_func_vfork" = xyes; then + { echo "$as_me:$LINENO: checking for working vfork" >&5 +echo $ECHO_N "checking for working vfork... $ECHO_C" >&6; } +if test "${ac_cv_func_vfork_works+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then + ac_cv_func_vfork_works=cross +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Thanks to Paul Eggert for this test. */ +$ac_includes_default +#include +#ifdef HAVE_VFORK_H +# include +#endif +/* On some sparc systems, changes by the child to local and incoming + argument registers are propagated back to the parent. The compiler + is told about this with #include , but some compilers + (e.g. gcc -O) don't grok . Test for this by using a + static variable whose address is put into a register that is + clobbered by the vfork. */ +static void +#ifdef __cplusplus +sparc_address_test (int arg) +# else +sparc_address_test (arg) int arg; +#endif +{ + static pid_t child; + if (!child) { + child = vfork (); + if (child < 0) { + perror ("vfork"); + _exit(2); + } + if (!child) { + arg = getpid(); + write(-1, "", 0); + _exit (arg); + } + } +} + +int +main () +{ + pid_t parent = getpid (); + pid_t child; + + sparc_address_test (0); + + child = vfork (); + + if (child == 0) { + /* Here is another test for sparc vfork register problems. This + test uses lots of local variables, at least as many local + variables as main has allocated so far including compiler + temporaries. 4 locals are enough for gcc 1.40.3 on a Solaris + 4.1.3 sparc, but we use 8 to be safe. A buggy compiler should + reuse the register of parent for one of the local variables, + since it will think that parent can't possibly be used any more + in this routine. Assigning to the local variable will thus + munge parent in the parent process. */ + pid_t + p = getpid(), p1 = getpid(), p2 = getpid(), p3 = getpid(), + p4 = getpid(), p5 = getpid(), p6 = getpid(), p7 = getpid(); + /* Convince the compiler that p..p7 are live; otherwise, it might + use the same hardware register for all 8 local variables. */ + if (p != p1 || p != p2 || p != p3 || p != p4 + || p != p5 || p != p6 || p != p7) + _exit(1); + + /* On some systems (e.g. IRIX 3.3), vfork doesn't separate parent + from child file descriptors. If the child closes a descriptor + before it execs or exits, this munges the parent's descriptor + as well. Test for this by closing stdout in the child. */ + _exit(close(fileno(stdout)) != 0); + } else { + int status; + struct stat st; + + while (wait(&status) != child) + ; + return ( + /* Was there some problem with vforking? */ + child < 0 + + /* Did the child fail? (This shouldn't happen.) */ + || status + + /* Did the vfork/compiler bug occur? */ + || parent != getpid() + + /* Did the file descriptor bug occur? */ + || fstat(fileno(stdout), &st) != 0 + ); + } +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_func_vfork_works=yes +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_func_vfork_works=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func_vfork_works" >&5 +echo "${ECHO_T}$ac_cv_func_vfork_works" >&6; } + +fi; +if test "x$ac_cv_func_fork_works" = xcross; then + ac_cv_func_vfork_works=$ac_cv_func_vfork + { echo "$as_me:$LINENO: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&5 +echo "$as_me: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&2;} +fi + +if test "x$ac_cv_func_vfork_works" = xyes; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_WORKING_VFORK 1 +_ACEOF + +else + +cat >>confdefs.h <<\_ACEOF +#define vfork fork +_ACEOF + +fi +if test "x$ac_cv_func_fork_works" = xyes; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_WORKING_FORK 1 +_ACEOF + +fi + +if test $ac_cv_c_compiler_gnu = yes; then + { echo "$as_me:$LINENO: checking whether $CC needs -traditional" >&5 +echo $ECHO_N "checking whether $CC needs -traditional... $ECHO_C" >&6; } +if test "${ac_cv_prog_gcc_traditional+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_pattern="Autoconf.*'x'" + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +Autoconf TIOCGETP +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "$ac_pattern" >/dev/null 2>&1; then + ac_cv_prog_gcc_traditional=yes +else + ac_cv_prog_gcc_traditional=no +fi +rm -f conftest* + + + if test $ac_cv_prog_gcc_traditional = no; then + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +Autoconf TCGETA +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "$ac_pattern" >/dev/null 2>&1; then + ac_cv_prog_gcc_traditional=yes +fi +rm -f conftest* + + fi +fi +{ echo "$as_me:$LINENO: result: $ac_cv_prog_gcc_traditional" >&5 +echo "${ECHO_T}$ac_cv_prog_gcc_traditional" >&6; } + if test $ac_cv_prog_gcc_traditional = yes; then + CC="$CC -traditional" + fi +fi + +{ echo "$as_me:$LINENO: checking whether lstat dereferences a symlink specified with a trailing slash" >&5 +echo $ECHO_N "checking whether lstat dereferences a symlink specified with a trailing slash... $ECHO_C" >&6; } +if test "${ac_cv_func_lstat_dereferences_slashed_symlink+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + rm -f conftest.sym conftest.file +echo >conftest.file +if test "$as_ln_s" = "ln -s" && ln -s conftest.file conftest.sym; then + if test "$cross_compiling" = yes; then + ac_cv_func_lstat_dereferences_slashed_symlink=no +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +struct stat sbuf; + /* Linux will dereference the symlink and fail. + That is better in the sense that it means we will not + have to compile and use the lstat wrapper. */ + return lstat ("conftest.sym/", &sbuf) == 0; + ; + return 0; +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_func_lstat_dereferences_slashed_symlink=yes +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_func_lstat_dereferences_slashed_symlink=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + +else + # If the `ln -s' command failed, then we probably don't even + # have an lstat function. + ac_cv_func_lstat_dereferences_slashed_symlink=no +fi +rm -f conftest.sym conftest.file + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func_lstat_dereferences_slashed_symlink" >&5 +echo "${ECHO_T}$ac_cv_func_lstat_dereferences_slashed_symlink" >&6; } + +test $ac_cv_func_lstat_dereferences_slashed_symlink = yes && + +cat >>confdefs.h <<_ACEOF +#define LSTAT_FOLLOWS_SLASHED_SYMLINK 1 +_ACEOF + + +if test $ac_cv_func_lstat_dereferences_slashed_symlink = no; then + case " $LIBOBJS " in + *" lstat.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS lstat.$ac_objext" + ;; +esac + +fi + +{ echo "$as_me:$LINENO: checking whether lstat accepts an empty string" >&5 +echo $ECHO_N "checking whether lstat accepts an empty string... $ECHO_C" >&6; } +if test "${ac_cv_func_lstat_empty_string_bug+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then + ac_cv_func_lstat_empty_string_bug=yes +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +struct stat sbuf; + return lstat ("", &sbuf) == 0; + ; + return 0; +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_func_lstat_empty_string_bug=no +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_func_lstat_empty_string_bug=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func_lstat_empty_string_bug" >&5 +echo "${ECHO_T}$ac_cv_func_lstat_empty_string_bug" >&6; } +if test $ac_cv_func_lstat_empty_string_bug = yes; then + case " $LIBOBJS " in + *" lstat.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS lstat.$ac_objext" + ;; +esac + + +cat >>confdefs.h <<_ACEOF +#define HAVE_LSTAT_EMPTY_STRING_BUG 1 +_ACEOF + +fi + +{ echo "$as_me:$LINENO: checking whether lstat dereferences a symlink specified with a trailing slash" >&5 +echo $ECHO_N "checking whether lstat dereferences a symlink specified with a trailing slash... $ECHO_C" >&6; } +if test "${ac_cv_func_lstat_dereferences_slashed_symlink+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + rm -f conftest.sym conftest.file +echo >conftest.file +if test "$as_ln_s" = "ln -s" && ln -s conftest.file conftest.sym; then + if test "$cross_compiling" = yes; then + ac_cv_func_lstat_dereferences_slashed_symlink=no +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +struct stat sbuf; + /* Linux will dereference the symlink and fail. + That is better in the sense that it means we will not + have to compile and use the lstat wrapper. */ + return lstat ("conftest.sym/", &sbuf) == 0; + ; + return 0; +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_func_lstat_dereferences_slashed_symlink=yes +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_func_lstat_dereferences_slashed_symlink=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + +else + # If the `ln -s' command failed, then we probably don't even + # have an lstat function. + ac_cv_func_lstat_dereferences_slashed_symlink=no +fi +rm -f conftest.sym conftest.file + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func_lstat_dereferences_slashed_symlink" >&5 +echo "${ECHO_T}$ac_cv_func_lstat_dereferences_slashed_symlink" >&6; } + +test $ac_cv_func_lstat_dereferences_slashed_symlink = yes && + +cat >>confdefs.h <<_ACEOF +#define LSTAT_FOLLOWS_SLASHED_SYMLINK 1 +_ACEOF + + +if test $ac_cv_func_lstat_dereferences_slashed_symlink = no; then + case " $LIBOBJS " in + *" lstat.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS lstat.$ac_objext" + ;; +esac + +fi + +{ echo "$as_me:$LINENO: checking return type of signal handlers" >&5 +echo $ECHO_N "checking return type of signal handlers... $ECHO_C" >&6; } +if test "${ac_cv_type_signal+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +#include +#include + +int +main () +{ +return *(signal (0, 0)) (0) == 1; + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext +if { (ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_compile") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then + ac_cv_type_signal=int +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_type_signal=void +fi + +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_type_signal" >&5 +echo "${ECHO_T}$ac_cv_type_signal" >&6; } + +cat >>confdefs.h <<_ACEOF +#define RETSIGTYPE $ac_cv_type_signal +_ACEOF + + +{ echo "$as_me:$LINENO: checking whether stat accepts an empty string" >&5 +echo $ECHO_N "checking whether stat accepts an empty string... $ECHO_C" >&6; } +if test "${ac_cv_func_stat_empty_string_bug+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test "$cross_compiling" = yes; then + ac_cv_func_stat_empty_string_bug=yes +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +struct stat sbuf; + return stat ("", &sbuf) == 0; + ; + return 0; +} +_ACEOF +rm -f conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { ac_try='./conftest$ac_exeext' + { (case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); }; }; then + ac_cv_func_stat_empty_string_bug=no +else + echo "$as_me: program exited with status $ac_status" >&5 +echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +( exit $ac_status ) +ac_cv_func_stat_empty_string_bug=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +fi + + +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func_stat_empty_string_bug" >&5 +echo "${ECHO_T}$ac_cv_func_stat_empty_string_bug" >&6; } +if test $ac_cv_func_stat_empty_string_bug = yes; then + case " $LIBOBJS " in + *" stat.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS stat.$ac_objext" + ;; +esac + + +cat >>confdefs.h <<_ACEOF +#define HAVE_STAT_EMPTY_STRING_BUG 1 +_ACEOF + +fi + + +for ac_func in vprintf +do +as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ echo "$as_me:$LINENO: checking for $ac_func" >&5 +echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define $ac_func to an innocuous variant, in case declares $ac_func. + For example, HP-UX 11i declares gettimeofday. */ +#define $ac_func innocuous_$ac_func + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $ac_func (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef $ac_func + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $ac_func (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$ac_func || defined __stub___$ac_func +choke me +#endif + +int +main () +{ +return $ac_func (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + eval "$as_ac_var=yes" +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + eval "$as_ac_var=no" +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +ac_res=`eval echo '${'$as_ac_var'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } +if test `eval echo '${'$as_ac_var'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +{ echo "$as_me:$LINENO: checking for _doprnt" >&5 +echo $ECHO_N "checking for _doprnt... $ECHO_C" >&6; } +if test "${ac_cv_func__doprnt+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define _doprnt to an innocuous variant, in case declares _doprnt. + For example, HP-UX 11i declares gettimeofday. */ +#define _doprnt innocuous__doprnt + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char _doprnt (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef _doprnt + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char _doprnt (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub__doprnt || defined __stub____doprnt +choke me +#endif + +int +main () +{ +return _doprnt (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + ac_cv_func__doprnt=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_func__doprnt=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +{ echo "$as_me:$LINENO: result: $ac_cv_func__doprnt" >&5 +echo "${ECHO_T}$ac_cv_func__doprnt" >&6; } +if test $ac_cv_func__doprnt = yes; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_DOPRNT 1 +_ACEOF + +fi + +fi +done + + + + + + + + + + + + + + + + + + + + + + + + +for ac_func in erasechar killchar alarm getpass memset setenv strchr nlist _spawnl spawnl getpwuid loadav getloadavg strerror setresgid setregid setgid setresuid setreuid setuid getuid getgid +do +as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` +{ echo "$as_me:$LINENO: checking for $ac_func" >&5 +echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } +if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ +/* Define $ac_func to an innocuous variant, in case declares $ac_func. + For example, HP-UX 11i declares gettimeofday. */ +#define $ac_func innocuous_$ac_func + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $ac_func (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef $ac_func + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $ac_func (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$ac_func || defined __stub___$ac_func +choke me +#endif + +int +main () +{ +return $ac_func (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + eval "$as_ac_var=yes" +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + eval "$as_ac_var=no" +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +fi +ac_res=`eval echo '${'$as_ac_var'}'` + { echo "$as_me:$LINENO: result: $ac_res" >&5 +echo "${ECHO_T}$ac_res" >&6; } +if test `eval echo '${'$as_ac_var'}'` = yes; then + cat >>confdefs.h <<_ACEOF +#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + + +# Extract the first word of "nroff", so it can be a program name with args. +set dummy nroff; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_NROFF+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$NROFF"; then + ac_cv_prog_NROFF="$NROFF" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_NROFF="nroff" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +NROFF=$ac_cv_prog_NROFF +if test -n "$NROFF"; then + { echo "$as_me:$LINENO: result: $NROFF" >&5 +echo "${ECHO_T}$NROFF" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + +# Extract the first word of "groff", so it can be a program name with args. +set dummy groff; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_GROFF+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$GROFF"; then + ac_cv_prog_GROFF="$GROFF" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_GROFF="groff" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +GROFF=$ac_cv_prog_GROFF +if test -n "$GROFF"; then + { echo "$as_me:$LINENO: result: $GROFF" >&5 +echo "${ECHO_T}$GROFF" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + +# Extract the first word of "colcrt", so it can be a program name with args. +set dummy colcrt; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_COLCRT+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$COLCRT"; then + ac_cv_prog_COLCRT="$COLCRT" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_COLCRT="colcrt" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +COLCRT=$ac_cv_prog_COLCRT +if test -n "$COLCRT"; then + { echo "$as_me:$LINENO: result: $COLCRT" >&5 +echo "${ECHO_T}$COLCRT" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + +# Extract the first word of "tbl", so it can be a program name with args. +set dummy tbl; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_TBL+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$TBL"; then + ac_cv_prog_TBL="$TBL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_TBL="tbl" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +TBL=$ac_cv_prog_TBL +if test -n "$TBL"; then + { echo "$as_me:$LINENO: result: $TBL" >&5 +echo "${ECHO_T}$TBL" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + +# Extract the first word of "sed", so it can be a program name with args. +set dummy sed; ac_word=$2 +{ echo "$as_me:$LINENO: checking for $ac_word" >&5 +echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } +if test "${ac_cv_prog_SED+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + if test -n "$SED"; then + ac_cv_prog_SED="$SED" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_SED="sed" + echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done +done +IFS=$as_save_IFS + +fi +fi +SED=$ac_cv_prog_SED +if test -n "$SED"; then + { echo "$as_me:$LINENO: result: $SED" >&5 +echo "${ECHO_T}$SED" >&6; } +else + { echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + + + +# Check whether --with-program-name was given. +if test "${with_program_name+set}" = set; then + withval=$with_program_name; progname="$withval" +else + progname="rogue" +fi + +PROGRAM=$progname + + +# Check whether --enable-setgid was given. +if test "${enable_setgid+set}" = set; then + enableval=$enable_setgid; +fi + +{ echo "$as_me:$LINENO: checking if using setgid execute bit" >&5 +echo $ECHO_N "checking if using setgid execute bit... $ECHO_C" >&6; } +if test "x$enable_setgid" = "xno" ; then +GROUPOWNER= +elif test "x$enable_setgid" = "xyes" ; then +GROUPOWNER=games +elif test "x$enable_setgid" = "x" ; then +GROUPOWNER= +else +GROUPOWNER=$enable_setgid +fi + +if test "x$GROUPOWNER" != "x" ; then + +cat >>confdefs.h <<_ACEOF +#define GROUPOWNER $GROUPOWNER +_ACEOF + +{ echo "$as_me:$LINENO: result: $GROUPOWNER" >&5 +echo "${ECHO_T}$GROUPOWNER" >&6; } +else +{ echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + + + +# Check whether --enable-scorefile was given. +if test "${enable_scorefile+set}" = set; then + enableval=$enable_scorefile; +fi + +{ echo "$as_me:$LINENO: checking for scoreboard file" >&5 +echo $ECHO_N "checking for scoreboard file... $ECHO_C" >&6; } +if test "x$enable_scorefile" = "xno" ; then +SCOREFILE= +elif test "x$enable_scorefile" = "xyes" ; then +SCOREFILE=$progname.scr +elif test "x$enable_scorefile" = "x" ; then +SCOREFILE=$progname.scr +else +SCOREFILE=$enable_scorefile +fi + +if test "x$SCOREFILE" != "x" ; then + +cat >>confdefs.h <<_ACEOF +#define SCOREFILE "$SCOREFILE" +_ACEOF + +{ echo "$as_me:$LINENO: result: $SCOREFILE" >&5 +echo "${ECHO_T}$SCOREFILE" >&6; } +else +{ echo "$as_me:$LINENO: result: disabled" >&5 +echo "${ECHO_T}disabled" >&6; } +fi + + + +# Check whether --enable-lockfile was given. +if test "${enable_lockfile+set}" = set; then + enableval=$enable_lockfile; +fi + +{ echo "$as_me:$LINENO: checking for scoreboard lockfile file" >&5 +echo $ECHO_N "checking for scoreboard lockfile file... $ECHO_C" >&6; } +if test "x$enable_lockfile" = "xno" ; then +LOCKFILE= +elif test "x$enable_lockfile" = "xyes" ; then +LOCKFILE=$progname.lck +elif test "x$enable_lockfile" = "x" ; then +LOCKFILE=$progname.lck +else +LOCKFILE=$enable_lockfile +fi + +if test "x$LOCKFILE" != "x" ; then + +cat >>confdefs.h <<_ACEOF +#define LOCKFILE "$LOCKFILE" +_ACEOF + +{ echo "$as_me:$LINENO: result: $LOCKFILE" >&5 +echo "${ECHO_T}$LOCKFILE" >&6; } +else +{ echo "$as_me:$LINENO: result: disabled" >&5 +echo "${ECHO_T}disabled" >&6; } +fi + + + +# Check whether --enable-wizardmode was given. +if test "${enable_wizardmode+set}" = set; then + enableval=$enable_wizardmode; +fi + +{ echo "$as_me:$LINENO: checking if wizard mode is enabled" >&5 +echo $ECHO_N "checking if wizard mode is enabled... $ECHO_C" >&6; } +if test "x$enable_wizardmode" = "xno" ; then +{ echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +elif test "x$enable_wizardmode" = "x" ; then +{ echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +else + +cat >>confdefs.h <<\_ACEOF +#define MASTER +_ACEOF + +if test "x$enable_wizardmode" != "xyes" ; then + +cat >>confdefs.h <<_ACEOF +#define PASSWD $enable_wizardmode +_ACEOF + +fi +{ echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6; } +fi + +# Check whether --enable-allscores was given. +if test "${enable_allscores+set}" = set; then + enableval=$enable_allscores; +else + enable_allscores=yes +fi + +{ echo "$as_me:$LINENO: checking if allscores is enabled" >&5 +echo $ECHO_N "checking if allscores is enabled... $ECHO_C" >&6; } +if test "x$enable_allscores" = "xyes" ; then + +cat >>confdefs.h <<\_ACEOF +#define ALLSCORES 1 +_ACEOF + +{ echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6; } +else +{ echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + +# Check whether --enable-checktime was given. +if test "${enable_checktime+set}" = set; then + enableval=$enable_checktime; +fi + +{ echo "$as_me:$LINENO: checking if checktime is enabled" >&5 +echo $ECHO_N "checking if checktime is enabled... $ECHO_C" >&6; } +if test "x$enable_checktime" = "xyes" ; then + +cat >>confdefs.h <<\_ACEOF +#define CHECKTIME 1 +_ACEOF + +{ echo "$as_me:$LINENO: result: yes" >&5 +echo "${ECHO_T}yes" >&6; } +else +{ echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +fi + +# Check whether --enable-maxload was given. +if test "${enable_maxload+set}" = set; then + enableval=$enable_maxload; +fi + +{ echo "$as_me:$LINENO: checking runtime execution limit (maximum system load average)" >&5 +echo $ECHO_N "checking runtime execution limit (maximum system load average)... $ECHO_C" >&6; } +if test "x$enable_maxload" = "xyes" ; then + +cat >>confdefs.h <<\_ACEOF +#define MAXLOAD 100 +_ACEOF + +{ echo "$as_me:$LINENO: result: 100" >&5 +echo "${ECHO_T}100" >&6; } +elif test "x$enable_maxload" = "x" ; then +{ echo "$as_me:$LINENO: result: unlimited" >&5 +echo "${ECHO_T}unlimited" >&6; } +elif test "x$enable_maxload" = "xno" ; then +{ echo "$as_me:$LINENO: result: unlimited" >&5 +echo "${ECHO_T}unlimited" >&6; } +else + +cat >>confdefs.h <<_ACEOF +#define MAXLOAD $enable_maxload +_ACEOF + +{ echo "$as_me:$LINENO: result: $enable_maxload" >&5 +echo "${ECHO_T}$enable_maxload" >&6; } +fi + +# Check whether --enable-maxusers was given. +if test "${enable_maxusers+set}" = set; then + enableval=$enable_maxusers; +fi + +{ echo "$as_me:$LINENO: checking runtime execution limit (maximum online system users)" >&5 +echo $ECHO_N "checking runtime execution limit (maximum online system users)... $ECHO_C" >&6; } +if test "x$enable_maxusers" = "xyes" ; then + +cat >>confdefs.h <<\_ACEOF +#define MAXUSERS 100 +_ACEOF + +{ echo "$as_me:$LINENO: result: 100" >&5 +echo "${ECHO_T}100" >&6; } +elif test "x$enable_maxusers" = "x" ; then +{ echo "$as_me:$LINENO: result: unlimited" >&5 +echo "${ECHO_T}unlimited" >&6; } +elif test "x$enable_maxload" = "xno" ; then +{ echo "$as_me:$LINENO: result: unlimited" >&5 +echo "${ECHO_T}unlimited" >&6; } +else + +cat >>confdefs.h <<_ACEOF +#define MAXLOAD $enable_maxusers +_ACEOF + +{ echo "$as_me:$LINENO: result: $enable_maxusers" >&5 +echo "${ECHO_T}$enable_maxusers" >&6; } +fi + +# Check whether --enable-numscores was given. +if test "${enable_numscores+set}" = set; then + enableval=$enable_numscores; +fi + +{ echo "$as_me:$LINENO: checking what the number of scores to store in scoreboard is" >&5 +echo $ECHO_N "checking what the number of scores to store in scoreboard is... $ECHO_C" >&6; } +if test "x$numscores" = "xyes" ; then + +cat >>confdefs.h <<\_ACEOF +#define NUMSCORES 10 +_ACEOF + +{ echo "$as_me:$LINENO: result: 10" >&5 +echo "${ECHO_T}10" >&6; } +elif test "x$enable_numscores" = "x" ; then + +cat >>confdefs.h <<\_ACEOF +#define NUMSCORES 10 +_ACEOF + +{ echo "$as_me:$LINENO: result: 10" >&5 +echo "${ECHO_T}10" >&6; } +elif test "x$enable_numscores" = "xno" ; then + +cat >>confdefs.h <<\_ACEOF +#define NUMSCORES 10 +_ACEOF + +{ echo "$as_me:$LINENO: result: 10" >&5 +echo "${ECHO_T}10" >&6; } +else + +cat >>confdefs.h <<_ACEOF +#define NUMSCORES $enable_numscores +_ACEOF + +{ echo "$as_me:$LINENO: result: $enable_numscores" >&5 +echo "${ECHO_T}$enable_numscores" >&6; } +fi + +# Check whether --enable-numname was given. +if test "${enable_numname+set}" = set; then + enableval=$enable_numname; +fi + +{ echo "$as_me:$LINENO: checking word for the number of scores to store in scoreboard is" >&5 +echo $ECHO_N "checking word for the number of scores to store in scoreboard is... $ECHO_C" >&6; } +if test "x$enable_numname" = "xyes" ; then + +cat >>confdefs.h <<\_ACEOF +#define NUMNAME "Ten" +_ACEOF + +{ echo "$as_me:$LINENO: result: Ten" >&5 +echo "${ECHO_T}Ten" >&6; } +elif test "x$enable_numname" = "x" ; then + +cat >>confdefs.h <<\_ACEOF +#define NUMNAME "Ten" +_ACEOF + +{ echo "$as_me:$LINENO: result: Ten" >&5 +echo "${ECHO_T}Ten" >&6; } +elif test "x$enable_numname" = "xno" ; then + +cat >>confdefs.h <<\_ACEOF +#define NUMNAME "Ten" +_ACEOF + +{ echo "$as_me:$LINENO: result: Ten" >&5 +echo "${ECHO_T}Ten" >&6; } +else + +cat >>confdefs.h <<_ACEOF +#define NUMNAME "$enable_numname" +_ACEOF + +{ echo "$as_me:$LINENO: result: $enable_numname" >&5 +echo "${ECHO_T}$enable_numname" >&6; } +fi + +# Check whether --enable-loadav was given. +if test "${enable_loadav+set}" = set; then + enableval=$enable_loadav; +fi + +{ echo "$as_me:$LINENO: checking whether to use program's built in load average function" >&5 +echo $ECHO_N "checking whether to use program's built in load average function... $ECHO_C" >&6; } +if test "x$enable_loadav" = "xyes" ; then + +cat >>confdefs.h <<\_ACEOF +#define LOADAV +_ACEOF + + +cat >>confdefs.h <<\_ACEOF +#define NAMELIST /vmunix +_ACEOF + +{ echo "$as_me:$LINENO: result: /vmunix" >&5 +echo "${ECHO_T}/vmunix" >&6; } +elif test "x$enable_loadav" = "x" ; then +{ echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +elif test "x$enable_loadav" = "xno" ; then +{ echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +else + +cat >>confdefs.h <<\_ACEOF +#define LOADAV +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define NAMELIST $enable_loadav +_ACEOF + +{ echo "$as_me:$LINENO: result: $enable_loadav" >&5 +echo "${ECHO_T}$enable_loadav" >&6; } +fi + +# Check whether --enable-ucount was given. +if test "${enable_ucount+set}" = set; then + enableval=$enable_ucount; +fi + +{ echo "$as_me:$LINENO: checking whether to use program's built in user counting function" >&5 +echo $ECHO_N "checking whether to use program's built in user counting function... $ECHO_C" >&6; } +if test "x$enable_ucount" = "xyes" ; then + +cat >>confdefs.h <<\_ACEOF +#define UCOUNT +_ACEOF + + +cat >>confdefs.h <<\_ACEOF +#define UTMP /etc/utmp +_ACEOF + +{ echo "$as_me:$LINENO: result: /etc/utmp" >&5 +echo "${ECHO_T}/etc/utmp" >&6; } +elif test "x$enable_ucount" = "x" ; then +{ echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +elif test "x$enable_count" = "xno" ; then +{ echo "$as_me:$LINENO: result: no" >&5 +echo "${ECHO_T}no" >&6; } +else + +cat >>confdefs.h <<\_ACEOF +#define UCOUNT +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define UTMP $enable_ucount +_ACEOF + +{ echo "$as_me:$LINENO: result: $enable_ucount" >&5 +echo "${ECHO_T}$enable_ucount" >&6; } +fi + +TARGET=$target + + +{ echo "$as_me:$LINENO: checking whether to docdir is defined" >&5 +echo $ECHO_N "checking whether to docdir is defined... $ECHO_C" >&6; } +if test "x$docdir" = "x" ; then +{ echo "$as_me:$LINENO: result: docdir undefined" >&5 +echo "${ECHO_T}docdir undefined" >&6; } +docdir=\${datadir}/doc/\${PACKAGE_TARNAME} + +else +{ echo "$as_me:$LINENO: result: docdir defined" >&5 +echo "${ECHO_T}docdir defined" >&6; } +fi + +cat >confcache <<\_ACEOF +# This file is a shell script that caches the results of configure +# tests run on this system so they can be shared between configure +# scripts and configure runs, see configure's option --config-cache. +# It is not useful on other systems. If it contains results you don't +# want to keep, you may remove or edit it. +# +# config.status only pays attention to the cache file if you give it +# the --recheck option to rerun configure. +# +# `ac_cv_env_foo' variables (set or unset) will be overridden when +# loading this file, other *unset* `ac_cv_foo' will be assigned the +# following values. + +_ACEOF + +# The following way of writing the cache mishandles newlines in values, +# but we know of no workaround that is simple, portable, and efficient. +# So, we kill variables containing newlines. +# Ultrix sh set writes to stderr and can't be redirected directly, +# and sets the high bit in the cache file unless we assign to the vars. +( + for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 +echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + *) $as_unset $ac_var ;; + esac ;; + esac + done + + (set) 2>&1 | + case $as_nl`(ac_space=' '; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + # `set' does not quote correctly, so add quotes (double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \). + sed -n \ + "s/'/'\\\\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" + ;; #( + *) + # `set' quotes correctly as required by POSIX, so do not add quotes. + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) | + sed ' + /^ac_cv_env_/b end + t clear + :clear + s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ + t end + s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ + :end' >>confcache +if diff "$cache_file" confcache >/dev/null 2>&1; then :; else + if test -w "$cache_file"; then + test "x$cache_file" != "x/dev/null" && + { echo "$as_me:$LINENO: updating cache $cache_file" >&5 +echo "$as_me: updating cache $cache_file" >&6;} + cat confcache >$cache_file + else + { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5 +echo "$as_me: not updating unwritable cache $cache_file" >&6;} + fi +fi +rm -f confcache + +test "x$prefix" = xNONE && prefix=$ac_default_prefix +# Let make expand exec_prefix. +test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' + +DEFS=-DHAVE_CONFIG_H + +ac_libobjs= +ac_ltlibobjs= +for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue + # 1. Remove the extension, and $U if already installed. + ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' + ac_i=`echo "$ac_i" | sed "$ac_script"` + # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR + # will be set to the directory where LIBOBJS objects are built. + ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext" + ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo' +done +LIBOBJS=$ac_libobjs + +LTLIBOBJS=$ac_ltlibobjs + + + +: ${CONFIG_STATUS=./config.status} +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files $CONFIG_STATUS" +{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 +echo "$as_me: creating $CONFIG_STATUS" >&6;} +cat >$CONFIG_STATUS <<_ACEOF +#! $SHELL +# Generated by $as_me. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false +SHELL=\${CONFIG_SHELL-$SHELL} +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF +## --------------------- ## +## M4sh Initialization. ## +## --------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in + *posix*) set -o posix ;; +esac + +fi + + + + +# PATH needs CR +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + echo "#! /bin/sh" >conf$$.sh + echo "exit 0" >>conf$$.sh + chmod +x conf$$.sh + if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then + PATH_SEPARATOR=';' + else + PATH_SEPARATOR=: + fi + rm -f conf$$.sh +fi + +# Support unset when possible. +if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then + as_unset=unset +else + as_unset=false +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +as_nl=' +' +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +case $0 in + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break +done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + { (exit 1); exit 1; } +fi + +# Work around bugs in pre-3.0 UWIN ksh. +for as_var in ENV MAIL MAILPATH +do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +for as_var in \ + LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ + LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ + LC_TELEPHONE LC_TIME +do + if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then + eval $as_var=C; export $as_var + else + ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var + fi +done + +# Required to use basename. +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + + +# Name of the executable. +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# CDPATH. +$as_unset CDPATH + + + + as_lineno_1=$LINENO + as_lineno_2=$LINENO + test "x$as_lineno_1" != "x$as_lineno_2" && + test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { + + # Create $as_me.lineno as a copy of $as_myself, but with $LINENO + # uniformly replaced by the line number. The first 'sed' inserts a + # line-number line after each line using $LINENO; the second 'sed' + # does the real work. The second script uses 'N' to pair each + # line-number line with the line containing $LINENO, and appends + # trailing '-' during substitution so that $LINENO is not a special + # case at line end. + # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the + # scripts with optimization help from Paolo Bonzini. Blame Lee + # E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 + { (exit 1); exit 1; }; } + + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in +-n*) + case `echo 'x\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + *) ECHO_C='\c';; + esac;; +*) + ECHO_N='-n';; +esac + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir +fi +echo >conf$$.file +if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' +elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln +else + as_ln_s='cp -p' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p=: +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +if test -x / >/dev/null 2>&1; then + as_test_x='test -x' +else + if ls -dL / >/dev/null 2>&1; then + as_ls_L_option=L + else + as_ls_L_option= + fi + as_test_x=' + eval sh -c '\'' + if test -d "$1"; then + test -d "$1/."; + else + case $1 in + -*)set "./$1";; + esac; + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in + ???[sx]*):;;*)false;;esac;fi + '\'' sh + ' +fi +as_executable_p=$as_test_x + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 + +# Save the log message, to keep $[0] and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by Rogue $as_me 5.4.4, which was +generated by GNU Autoconf 2.61. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +_ACEOF + +cat >>$CONFIG_STATUS <<_ACEOF +# Files that config.status was made for. +config_files="$ac_config_files" +config_headers="$ac_config_headers" + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF +ac_cs_usage="\ +\`$as_me' instantiates files from templates according to the +current configuration. + +Usage: $0 [OPTIONS] [FILE]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + -q, --quiet do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE + +Configuration files: +$config_files + +Configuration headers: +$config_headers + +Report bugs to ." + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF +ac_cs_version="\\ +Rogue config.status 5.4.4 +configured by $0, generated by GNU Autoconf 2.61, + with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" + +Copyright (C) 2006 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='$ac_pwd' +srcdir='$srcdir' +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF +# If no file are specified by the user, then we need to provide default +# value. By we need to know if files were specified by the user. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + echo "$ac_cs_version"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + CONFIG_FILES="$CONFIG_FILES $ac_optarg" + ac_need_defaults=false;; + --header | --heade | --head | --hea ) + $ac_shift + CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg" + ac_need_defaults=false;; + --he | --h) + # Conflict between --help and --header + { echo "$as_me: error: ambiguous option: $1 +Try \`$0 --help' for more information." >&2 + { (exit 1); exit 1; }; };; + --help | --hel | -h ) + echo "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) { echo "$as_me: error: unrecognized option: $1 +Try \`$0 --help' for more information." >&2 + { (exit 1); exit 1; }; } ;; + + *) ac_config_targets="$ac_config_targets $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF +if \$ac_cs_recheck; then + echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6 + CONFIG_SHELL=$SHELL + export CONFIG_SHELL + exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion +fi + +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + echo "$ac_log" +} >&5 + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "rogue.6") CONFIG_FILES="$CONFIG_FILES rogue.6" ;; + "rogue.cat") CONFIG_FILES="$CONFIG_FILES rogue.cat" ;; + "rogue.doc") CONFIG_FILES="$CONFIG_FILES rogue.doc" ;; + "rogue.html") CONFIG_FILES="$CONFIG_FILES rogue.html" ;; + "rogue.me") CONFIG_FILES="$CONFIG_FILES rogue.me" ;; + + *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 +echo "$as_me: error: invalid argument: $ac_config_target" >&2;} + { (exit 1); exit 1; }; };; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files + test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= + trap 'exit_status=$? + { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status +' 0 + trap '{ (exit 1); exit 1; }' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -n "$tmp" && test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || +{ + echo "$me: cannot create a temporary directory in ." >&2 + { (exit 1); exit 1; } +} + +# +# Set up the sed scripts for CONFIG_FILES section. +# + +# No need to generate the scripts if there are no CONFIG_FILES. +# This happens for instance when ./config.status config.h +if test -n "$CONFIG_FILES"; then + +_ACEOF + + + +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + cat >conf$$subs.sed <<_ACEOF +SHELL!$SHELL$ac_delim +PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim +PACKAGE_NAME!$PACKAGE_NAME$ac_delim +PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim +PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim +PACKAGE_STRING!$PACKAGE_STRING$ac_delim +PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim +exec_prefix!$exec_prefix$ac_delim +prefix!$prefix$ac_delim +program_transform_name!$program_transform_name$ac_delim +bindir!$bindir$ac_delim +sbindir!$sbindir$ac_delim +libexecdir!$libexecdir$ac_delim +datarootdir!$datarootdir$ac_delim +datadir!$datadir$ac_delim +sysconfdir!$sysconfdir$ac_delim +sharedstatedir!$sharedstatedir$ac_delim +localstatedir!$localstatedir$ac_delim +includedir!$includedir$ac_delim +oldincludedir!$oldincludedir$ac_delim +docdir!$docdir$ac_delim +infodir!$infodir$ac_delim +htmldir!$htmldir$ac_delim +dvidir!$dvidir$ac_delim +pdfdir!$pdfdir$ac_delim +psdir!$psdir$ac_delim +libdir!$libdir$ac_delim +localedir!$localedir$ac_delim +mandir!$mandir$ac_delim +DEFS!$DEFS$ac_delim +ECHO_C!$ECHO_C$ac_delim +ECHO_N!$ECHO_N$ac_delim +ECHO_T!$ECHO_T$ac_delim +LIBS!$LIBS$ac_delim +build_alias!$build_alias$ac_delim +host_alias!$host_alias$ac_delim +target_alias!$target_alias$ac_delim +build!$build$ac_delim +build_cpu!$build_cpu$ac_delim +build_vendor!$build_vendor$ac_delim +build_os!$build_os$ac_delim +host!$host$ac_delim +host_cpu!$host_cpu$ac_delim +host_vendor!$host_vendor$ac_delim +host_os!$host_os$ac_delim +target!$target$ac_delim +target_cpu!$target_cpu$ac_delim +target_vendor!$target_vendor$ac_delim +target_os!$target_os$ac_delim +CC!$CC$ac_delim +CFLAGS!$CFLAGS$ac_delim +LDFLAGS!$LDFLAGS$ac_delim +CPPFLAGS!$CPPFLAGS$ac_delim +ac_ct_CC!$ac_ct_CC$ac_delim +EXEEXT!$EXEEXT$ac_delim +OBJEXT!$OBJEXT$ac_delim +CPP!$CPP$ac_delim +GREP!$GREP$ac_delim +EGREP!$EGREP$ac_delim +LIBOBJS!$LIBOBJS$ac_delim +NROFF!$NROFF$ac_delim +GROFF!$GROFF$ac_delim +COLCRT!$COLCRT$ac_delim +TBL!$TBL$ac_delim +SED!$SED$ac_delim +PROGRAM!$PROGRAM$ac_delim +GROUPOWNER!$GROUPOWNER$ac_delim +SCOREFILE!$SCOREFILE$ac_delim +LOCKFILE!$LOCKFILE$ac_delim +TARGET!$TARGET$ac_delim +LTLIBOBJS!$LTLIBOBJS$ac_delim +_ACEOF + + if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 71; then + break + elif $ac_last_try; then + { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 +echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} + { (exit 1); exit 1; }; } + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed` +if test -n "$ac_eof"; then + ac_eof=`echo "$ac_eof" | sort -nru | sed 1q` + ac_eof=`expr $ac_eof + 1` +fi + +cat >>$CONFIG_STATUS <<_ACEOF +cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end +_ACEOF +sed ' +s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g +s/^/s,@/; s/!/@,|#_!!_#|/ +:n +t n +s/'"$ac_delim"'$/,g/; t +s/$/\\/; p +N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n +' >>$CONFIG_STATUS >$CONFIG_STATUS <<_ACEOF +:end +s/|#_!!_#|//g +CEOF$ac_eof +_ACEOF + + +# VPATH may cause trouble with some makes, so we remove $(srcdir), +# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=/{ +s/:*\$(srcdir):*/:/ +s/:*\${srcdir}:*/:/ +s/:*@srcdir@:*/:/ +s/^\([^=]*=[ ]*\):*/\1/ +s/:*$// +s/^[^=]*=[ ]*$// +}' +fi + +cat >>$CONFIG_STATUS <<\_ACEOF +fi # test -n "$CONFIG_FILES" + + +for ac_tag in :F $CONFIG_FILES :H $CONFIG_HEADERS +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5 +echo "$as_me: error: Invalid tag $ac_tag." >&2;} + { (exit 1); exit 1; }; };; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 +echo "$as_me: error: cannot find input file: $ac_f" >&2;} + { (exit 1); exit 1; }; };; + esac + ac_file_inputs="$ac_file_inputs $ac_f" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input="Generated from "`IFS=: + echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure." + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { echo "$as_me:$LINENO: creating $ac_file" >&5 +echo "$as_me: creating $ac_file" >&6;} + fi + + case $ac_tag in + *:-:* | *:-) cat >"$tmp/stdin";; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +echo X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + { as_dir="$ac_dir" + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 +echo "$as_me: error: cannot create directory $as_dir" >&2;} + { (exit 1); exit 1; }; }; } + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + + case $ac_mode in + :F) + # + # CONFIG_FILE + # + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= + +case `sed -n '/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p +' $ac_file_inputs` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF + ac_datarootdir_hack=' + s&@datadir@&$datadir&g + s&@docdir@&$docdir&g + s&@infodir@&$infodir&g + s&@localedir@&$localedir&g + s&@mandir@&$mandir&g + s&\\\${datarootdir}&$datarootdir&g' ;; +esac +_ACEOF + +# Neutralize VPATH when `$srcdir' = `.'. +# Shell code in configure.ac might set extrasub. +# FIXME: do we really want to maintain this feature? +cat >>$CONFIG_STATUS <<_ACEOF + sed "$ac_vpsub +$extrasub +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s&@configure_input@&$configure_input&;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +$ac_datarootdir_hack +" $ac_file_inputs | sed -f "$tmp/subs-1.sed" >$tmp/out + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && + { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined." >&5 +echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined." >&2;} + + rm -f "$tmp/stdin" + case $ac_file in + -) cat "$tmp/out"; rm -f "$tmp/out";; + *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;; + esac + ;; + :H) + # + # CONFIG_HEADER + # +_ACEOF + +# Transform confdefs.h into a sed script `conftest.defines', that +# substitutes the proper values into config.h.in to produce config.h. +rm -f conftest.defines conftest.tail +# First, append a space to every undef/define line, to ease matching. +echo 's/$/ /' >conftest.defines +# Then, protect against being on the right side of a sed subst, or in +# an unquoted here document, in config.status. If some macros were +# called several times there might be several #defines for the same +# symbol, which is useless. But do not sort them, since the last +# AC_DEFINE must be honored. +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +# These sed commands are passed to sed as "A NAME B PARAMS C VALUE D", where +# NAME is the cpp macro being defined, VALUE is the value it is being given. +# PARAMS is the parameter list in the macro definition--in most cases, it's +# just an empty string. +ac_dA='s,^\\([ #]*\\)[^ ]*\\([ ]*' +ac_dB='\\)[ (].*,\\1define\\2' +ac_dC=' ' +ac_dD=' ,' + +uniq confdefs.h | + sed -n ' + t rset + :rset + s/^[ ]*#[ ]*define[ ][ ]*// + t ok + d + :ok + s/[\\&,]/\\&/g + s/^\('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/ '"$ac_dA"'\1'"$ac_dB"'\2'"${ac_dC}"'\3'"$ac_dD"'/p + s/^\('"$ac_word_re"'\)[ ]*\(.*\)/'"$ac_dA"'\1'"$ac_dB$ac_dC"'\2'"$ac_dD"'/p + ' >>conftest.defines + +# Remove the space that was appended to ease matching. +# Then replace #undef with comments. This is necessary, for +# example, in the case of _POSIX_SOURCE, which is predefined and required +# on some systems where configure will not decide to define it. +# (The regexp can be short, since the line contains either #define or #undef.) +echo 's/ $// +s,^[ #]*u.*,/* & */,' >>conftest.defines + +# Break up conftest.defines: +ac_max_sed_lines=50 + +# First sed command is: sed -f defines.sed $ac_file_inputs >"$tmp/out1" +# Second one is: sed -f defines.sed "$tmp/out1" >"$tmp/out2" +# Third one will be: sed -f defines.sed "$tmp/out2" >"$tmp/out1" +# et cetera. +ac_in='$ac_file_inputs' +ac_out='"$tmp/out1"' +ac_nxt='"$tmp/out2"' + +while : +do + # Write a here document: + cat >>$CONFIG_STATUS <<_ACEOF + # First, check the format of the line: + cat >"\$tmp/defines.sed" <<\\CEOF +/^[ ]*#[ ]*undef[ ][ ]*$ac_word_re[ ]*\$/b def +/^[ ]*#[ ]*define[ ][ ]*$ac_word_re[( ]/b def +b +:def +_ACEOF + sed ${ac_max_sed_lines}q conftest.defines >>$CONFIG_STATUS + echo 'CEOF + sed -f "$tmp/defines.sed"' "$ac_in >$ac_out" >>$CONFIG_STATUS + ac_in=$ac_out; ac_out=$ac_nxt; ac_nxt=$ac_in + sed 1,${ac_max_sed_lines}d conftest.defines >conftest.tail + grep . conftest.tail >/dev/null || break + rm -f conftest.defines + mv conftest.tail conftest.defines +done +rm -f conftest.defines conftest.tail + +echo "ac_result=$ac_in" >>$CONFIG_STATUS +cat >>$CONFIG_STATUS <<\_ACEOF + if test x"$ac_file" != x-; then + echo "/* $configure_input */" >"$tmp/config.h" + cat "$ac_result" >>"$tmp/config.h" + if diff $ac_file "$tmp/config.h" >/dev/null 2>&1; then + { echo "$as_me:$LINENO: $ac_file is unchanged" >&5 +echo "$as_me: $ac_file is unchanged" >&6;} + else + rm -f $ac_file + mv "$tmp/config.h" $ac_file + fi + else + echo "/* $configure_input */" + cat "$ac_result" + fi + rm -f "$tmp/out12" + ;; + + + esac + +done # for ac_tag + + +{ (exit 0); exit 0; } +_ACEOF +chmod +x $CONFIG_STATUS +ac_clean_files=$ac_clean_files_save + + +# configure is writing to config.log, and then calls config.status. +# config.status does its own redirection, appending to config.log. +# Unfortunately, on DOS this fails, as config.log is still kept open +# by configure, so config.status won't be able to write to it; its +# output is simply discarded. So we exec the FD to /dev/null, +# effectively closing config.log, so it can be properly (re)opened and +# appended to by config.status. When coming back to configure, we +# need to make the FD available again. +if test "$no_create" != yes; then + ac_cs_success=: + ac_config_status_args= + test "$silent" = yes && + ac_config_status_args="$ac_config_status_args --quiet" + exec 5>/dev/null + $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false + exec 5>>config.log + # Use ||, not &&, to avoid exiting from the if with $? = 1, which + # would make configure fail if this is the last instruction. + $ac_cs_success || { (exit 1); exit 1; } +fi + From e25d05fd85ebda1e4e49990641899f147fe99e50 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 03:19:52 -1100 Subject: [PATCH 0234/1145] Fixes --- src/cc/rogue/mach_dep.c | 3 ++- src/cc/rogue/rip.c | 6 ++++-- src/cc/rogue/rogue.c | 1 - 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/mach_dep.c b/src/cc/rogue/mach_dep.c index 7f1af9c67..34e502816 100644 --- a/src/cc/rogue/mach_dep.c +++ b/src/cc/rogue/mach_dep.c @@ -403,7 +403,8 @@ over: printf("The score file is very busy. Do you want to wait longer\n"); printf("for it to become free so your score can get posted?\n"); printf("If so, type \"y\"\n"); - (void) fgets(prbuf, MAXSTR, stdin); + if (fgets(prbuf, MAXSTR, stdin) != 0 ) + ; if (prbuf[0] == 'y') for (;;) { diff --git a/src/cc/rogue/rip.c b/src/cc/rogue/rip.c index 6f2793615..dc22566e9 100644 --- a/src/cc/rogue/rip.c +++ b/src/cc/rogue/rip.c @@ -179,7 +179,8 @@ score(int amount, int flags, char monst) else if (prflags == 2) { fflush(stdout); - (void) fgets(prbuf,10,stdin); + if ( fgets(prbuf,10,stdin) != 0 ) + fprintf(stderr,"fgets error\n"); if (prbuf[0] == 'd') { for (sc2 = scp; sc2 < endp - 1; sc2++) @@ -270,7 +271,8 @@ death(char monst) score(purse, amulet ? 3 : 0, monst); printf("[Press return to continue]"); fflush(stdout); - (void) fgets(prbuf,10,stdin); + if ( fgets(prbuf,10,stdin) != 0 ) + ; my_exit(0); } diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index d463ddc49..a496426dd 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -147,7 +147,6 @@ int32_t rogue_replay(uint64_t seed) if ( (fp= fopen("checkfile","wb")) != 0 ) { save_file(fp,0); - fclose(fp); if ( 0 && (fp= fopen("checkfile","rb")) != 0 ) { for (i=0; i<0x150; i++) From d7da31e4d775ecfdd3d92cc6716b96cf3badcd72 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 03:30:41 -1100 Subject: [PATCH 0235/1145] Rogue rpc skeleton --- src/cc/cclib.cpp | 15 +++++++++++++-- src/cc/makerogue | 2 +- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 8a0f0aeca..c05fc11b9 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -47,11 +47,18 @@ struct CClib_rpcinfo int32_t numrequiredargs,maxargs; uint8_t funcid,evalcode; } +// creategame, register (inventory + baton + buyin), progress (events + statehash + [compr state]?), claimwin + CClib_methods[] = { { (char *)"faucet2", (char *)"fund", (char *)"amount", 1, 1, 'F', EVAL_FAUCET2 }, { (char *)"faucet2", (char *)"get", (char *)"", 0, 0, 'G', EVAL_FAUCET2 }, #ifdef BUILD_ROGUE + { (char *)"rogue", (char *)"newgame", (char *)"buyin", 0, 1, 'N', EVAL_ROGUE }, + { (char *)"rogue", (char *)"register", (char *)"txid [inventory]", 1, 2, 'R', EVAL_ROGUE }, + { (char *)"rogue", (char *)"progress", (char *)"txid fname", 2, 2, 'P', EVAL_ROGUE }, + { (char *)"rogue", (char *)"claimwin", (char *)"txid", 1, 1, 'W', EVAL_ROGUE }, + { (char *)"rogue", (char *)"extract", (char *)"txid item", 2, 2, 'X', EVAL_ROGUE }, #else { (char *)"sudoku", (char *)"gen", (char *)"", 0, 0, 'G', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, @@ -63,6 +70,11 @@ CClib_methods[] = std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *params); #ifdef BUILD_ROGUE +bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) +{ + return(true); +} + #else bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); @@ -216,8 +228,7 @@ bool CClib_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C if ( cp->evalcode != EVAL_FAUCET2 ) { #ifdef BUILD_ROGUE - //return(rogue_validate(cp,height,eval,tx)); - return(false); + return(rogue_validate(cp,height,eval,tx)); #else return(sudoku_validate(cp,height,eval,tx)); #endif diff --git a/src/cc/makerogue b/src/cc/makerogue index c9e55c28c..ea02e7fb1 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,2 +1,2 @@ cd rogue; make; cd .. -gcc -DROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp rogue/rogue.so +gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp rogue/rogue.so From ffc1aac7008841c8ca09bb05856537c14e6f421e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 03:32:08 -1100 Subject: [PATCH 0236/1145] Make rogue --- src/cc/makerogue | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/makerogue b/src/cc/makerogue index ea02e7fb1..f0e495014 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,2 +1,3 @@ cd rogue; make; cd .. gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp rogue/rogue.so +gcc -DROGUE -std=c++11 -fPIC -shared -o ../libcc.so cclib.o rogue/rogue.so From ad8e1789ed1f3a2dc91bb29afc93a8f726bc8bda Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 03:34:00 -1100 Subject: [PATCH 0237/1145] makecclib --- src/cc/makerogue | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index f0e495014..059b0ae4a 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,3 +1,4 @@ cd rogue; make; cd .. gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp rogue/rogue.so -gcc -DROGUE -std=c++11 -fPIC -shared -o ../libcc.so cclib.o rogue/rogue.so +gcc -fPIC -shared -o librogue.so cclib.o rogue/rogue.so +cp librogue.so ../libcc.so From 47c926b373552c6a6e1f79a0e74c5fa234412c38 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 03:35:01 -1100 Subject: [PATCH 0238/1145] Fix --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 059b0ae4a..651e3683a 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,4 +1,4 @@ cd rogue; make; cd .. -gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp rogue/rogue.so +gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp gcc -fPIC -shared -o librogue.so cclib.o rogue/rogue.so cp librogue.so ../libcc.so From a3745c01d47340dc8a6189d1fd3d7dcc1b55054c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 03:35:45 -1100 Subject: [PATCH 0239/1145] Fix --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 651e3683a..6882139ff 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,4 +1,4 @@ cd rogue; make; cd .. -gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp +gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c cclib.cpp gcc -fPIC -shared -o librogue.so cclib.o rogue/rogue.so cp librogue.so ../libcc.so From 779826611a2c2cc1358d69b5fb069171153a9de7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 03:40:28 -1100 Subject: [PATCH 0240/1145] Stdint --- src/cc/rogue/extern.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue/extern.h b/src/cc/rogue/extern.h index e8c13d27d..eb95789e3 100644 --- a/src/cc/rogue/extern.h +++ b/src/cc/rogue/extern.h @@ -18,6 +18,7 @@ #undef HAVE_MEMORY_H #undef HAVE_STRING_H #endif +#include "" #include "config.h" #elif defined(__DJGPP__) #define HAVE_SYS_TYPES_H 1 From d338544e8665e1a286ef1c5f9cd7fe668f5a6ece Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 03:41:03 -1100 Subject: [PATCH 0241/1145] Add confgure --- src/cc/makerogue | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 6882139ff..7bb1fb18a 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,4 +1,6 @@ -cd rogue; make; cd .. +cd rogue; +./configure # only need this first time +make; cd .. gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c cclib.cpp gcc -fPIC -shared -o librogue.so cclib.o rogue/rogue.so cp librogue.so ../libcc.so From 205ec791c5cf4b5a5bc5b65e5ea0cbf5776d735d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 03:42:27 -1100 Subject: [PATCH 0242/1145] -"" --- src/cc/rogue/extern.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/extern.h b/src/cc/rogue/extern.h index eb95789e3..2946c540f 100644 --- a/src/cc/rogue/extern.h +++ b/src/cc/rogue/extern.h @@ -18,7 +18,7 @@ #undef HAVE_MEMORY_H #undef HAVE_STRING_H #endif -#include "" +#include #include "config.h" #elif defined(__DJGPP__) #define HAVE_SYS_TYPES_H 1 From 791cfd2b701d18f74b469623b79c3a9583a1830e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 03:48:38 -1100 Subject: [PATCH 0243/1145] -std=c++11 --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 7bb1fb18a..cfd72fd3d 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -2,5 +2,5 @@ cd rogue; ./configure # only need this first time make; cd .. gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c cclib.cpp -gcc -fPIC -shared -o librogue.so cclib.o rogue/rogue.so +gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so cp librogue.so ../libcc.so From eaa3bcb4939ca06aa961aa5ccc6ed7ee3c46c9b2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 03:57:08 -1100 Subject: [PATCH 0244/1145] Directly link .so --- src/cc/makerogue | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index cfd72fd3d..1b9568265 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,6 +1,7 @@ cd rogue; ./configure # only need this first time make; cd .. -gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c cclib.cpp -gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so +gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp +#gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so cp librogue.so ../libcc.so + From 70664f4be5ac7258acb4d12370c9bfea734533a0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:13:53 -1100 Subject: [PATCH 0245/1145] Build via include --- src/cc/cclib.cpp | 34 ++++++++++++++++++++++++++++++++++ src/cc/rogue/extern.h | 3 +++ src/cc/rogue/rogue.h | 5 +++++ src/cc/rogue/score.h | 3 +++ 4 files changed, 45 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index c05fc11b9..a637de5f9 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -403,6 +403,40 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para } #ifdef BUILD_ROGUE +#include "rogue/vers.c" +#include "rogue/extern.c" +#include "rogue/armor.c" +#include "rogue/chase.c" +#include "rogue/command.c" +#include "rogue/daemon.c" +#include "rogue/daemons.c" +#include "rogue/fight.c" +#include "rogue/init.c" +#include "rogue/io.c" +#include "rogue/list.c" +#include "rogue/mach_dep.c" +#include "rogue/rogue.c" +#include "rogue/mdport.c" +#include "rogue/misc.c" +#include "rogue/monsters.c" +#include "rogue/move.c" +#include "rogue/new_level.c" +#include "rogue/options.c" +#include "rogue/pack.c" +#include "rogue/passages.c" +#include "rogue/potions.c" +#include "rogue/rings.c" +#include "rogue/rip.c" +#include "rogue/rooms.c" +#include "rogue/save.c" +#include "rogue/scrolls.c" +#include "rogue/state.c" +#include "rogue/sticks.c" +#include "rogue/things.c" +#include "rogue/weapons.c" +#include "rogue/wizard.c" +#include "rogue/xcrypt.c" + #else #include "sudoku.cpp" #endif diff --git a/src/cc/rogue/extern.h b/src/cc/rogue/extern.h index 2946c540f..1516ebb12 100644 --- a/src/cc/rogue/extern.h +++ b/src/cc/rogue/extern.h @@ -10,6 +10,8 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ +#ifndef H_EXTERN_ROGUE_H +#define H_EXTERN_ROGUE_H #ifdef HAVE_CONFIG_H #ifdef PDCURSES @@ -179,4 +181,5 @@ void md_onsignal_autosave(void); void md_onsignal_exit(void); void md_onsignal_default(void); int md_issymlink(char *sp); +#endif diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index ae834eb7a..040c9a97d 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -10,6 +10,9 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ +#ifndef H_ROGUE_H +#define H_ROGUE_H + #include "extern.h" #undef lines @@ -783,3 +786,5 @@ extern char *wood[]; extern int cNWOOD; extern char *metal[]; extern int cNMETAL; +#endif + diff --git a/src/cc/rogue/score.h b/src/cc/rogue/score.h index fb51bf8bc..a5897b482 100644 --- a/src/cc/rogue/score.h +++ b/src/cc/rogue/score.h @@ -9,6 +9,8 @@ * * See the file LICENSE.TXT for full copyright and licensing information. */ +#ifndef H_SCORE_H +#define H_SCORE_H struct sc_ent { unsigned int sc_uid; @@ -24,3 +26,4 @@ typedef struct sc_ent SCORE; void rd_score(SCORE *top_ten); void wr_score(SCORE *top_ten); +#endif From 53659cea89161f50bec232c98896dae0023c283b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:16:07 -1100 Subject: [PATCH 0246/1145] Make sure included --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index a637de5f9..d4a3ad74b 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -412,6 +412,7 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para #include "rogue/daemons.c" #include "rogue/fight.c" #include "rogue/init.c" +xx #include "rogue/io.c" #include "rogue/list.c" #include "rogue/mach_dep.c" From fac2456a5d872446cfb60a1e7496960448e6bb06 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:17:05 -1100 Subject: [PATCH 0247/1145] Revert --- src/cc/cclib.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index d4a3ad74b..a637de5f9 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -412,7 +412,6 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para #include "rogue/daemons.c" #include "rogue/fight.c" #include "rogue/init.c" -xx #include "rogue/io.c" #include "rogue/list.c" #include "rogue/mach_dep.c" From a3e938ac02512992c2d4df3c7b55758b5b2c37c9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:20:13 -1100 Subject: [PATCH 0248/1145] Test --- src/cc/cclib.cpp | 4 ++-- src/cc/makerogue | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index a637de5f9..982431c8c 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -403,7 +403,7 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para } #ifdef BUILD_ROGUE -#include "rogue/vers.c" +/*#include "rogue/vers.c" #include "rogue/extern.c" #include "rogue/armor.c" #include "rogue/chase.c" @@ -435,7 +435,7 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para #include "rogue/things.c" #include "rogue/weapons.c" #include "rogue/wizard.c" -#include "rogue/xcrypt.c" +#include "rogue/xcrypt.c"*/ #else #include "sudoku.cpp" diff --git a/src/cc/makerogue b/src/cc/makerogue index 1b9568265..a12acb7cd 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,7 +1,7 @@ cd rogue; -./configure # only need this first time +#./configure # only need this first time make; cd .. gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -#gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so +gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.o cp librogue.so ../libcc.so From bab1da339a9b0181ad433be6b963f80fef612221 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:21:16 -1100 Subject: [PATCH 0249/1145] Test --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index a12acb7cd..167c16700 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,7 +1,7 @@ cd rogue; #./configure # only need this first time make; cd .. -gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp +gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c cclib.cpp #-o librogue.so gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.o cp librogue.so ../libcc.so From 7df876952a9ebccf4a03d4e693b75e41718a6a21 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:22:05 -1100 Subject: [PATCH 0250/1145] Test --- src/cc/makerogue | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 167c16700..46c2141cb 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,7 +1,7 @@ cd rogue; #./configure # only need this first time make; cd .. -gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c cclib.cpp #-o librogue.so -gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.o +gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp rogue/rogue.o +//gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.o cp librogue.so ../libcc.so From 4b74b07b2f2db75bdb375f6d8666818ee2ba2253 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:23:45 -1100 Subject: [PATCH 0251/1145] rogue_replay --- src/cc/cclib.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 982431c8c..b3a95a418 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -70,6 +70,8 @@ CClib_methods[] = std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *params); #ifdef BUILD_ROGUE +extern "C" int32_t rogue_replay(uint64_t seed); + bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { return(true); @@ -89,6 +91,7 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) #ifdef BUILD_ROGUE if ( cp->evalcode == EVAL_ROGUE ) { + rogue_replay(777); } #else if ( cp->evalcode == EVAL_SUDOKU ) From 84622a7f931dd786188659baad20312fc9afeb9a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:25:48 -1100 Subject: [PATCH 0252/1145] rogue.so --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 46c2141cb..18f43591d 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,7 +1,7 @@ cd rogue; #./configure # only need this first time make; cd .. -gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp rogue/rogue.o +gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so cclib.cpp rogue/rogue.so //gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.o cp librogue.so ../libcc.so From 5603e44b65dfe56e2d8ca0abcebdbe5553667581 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:26:57 -1100 Subject: [PATCH 0253/1145] Test --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 18f43591d..bc5d9dd77 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -2,6 +2,6 @@ cd rogue; #./configure # only need this first time make; cd .. gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so cclib.cpp rogue/rogue.so -//gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.o +#gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.o cp librogue.so ../libcc.so From c99266e25773b19db796c5782cbd8418bdb36972 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:28:00 -1100 Subject: [PATCH 0254/1145] Need to include --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index bc5d9dd77..4c8fb7f2b 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,7 +1,7 @@ cd rogue; #./configure # only need this first time make; cd .. -gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so cclib.cpp rogue/rogue.so +gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so cclib.cpp #gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.o cp librogue.so ../libcc.so From c4ea0147a27195b4ac5bf8fe2fd37944c6687287 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:28:51 -1100 Subject: [PATCH 0255/1145] -c --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 4c8fb7f2b..30d3fe6a3 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,7 +1,7 @@ cd rogue; #./configure # only need this first time make; cd .. -gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so cclib.cpp +gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o -c librogue.so cclib.cpp #gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.o cp librogue.so ../libcc.so From da4ffad51987f855d0a0a7e58674d0b0075ba8b8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:29:45 -1100 Subject: [PATCH 0256/1145] Revert --- src/cc/makerogue | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 30d3fe6a3..4fcbee14f 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,7 +1,7 @@ cd rogue; #./configure # only need this first time make; cd .. -gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o -c librogue.so cclib.cpp -#gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.o +gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp +#gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so cp librogue.so ../libcc.so From eb0eeed0dd4d9ccd549e00bcd92f93b26f22545c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:31:00 -1100 Subject: [PATCH 0257/1145] Incremental c files --- src/cc/cclib.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index b3a95a418..7706058ba 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -70,7 +70,7 @@ CClib_methods[] = std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *params); #ifdef BUILD_ROGUE -extern "C" int32_t rogue_replay(uint64_t seed); +int32_t rogue_replay(uint64_t seed); bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { @@ -406,10 +406,10 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para } #ifdef BUILD_ROGUE -/*#include "rogue/vers.c" +#include "rogue/vers.c" #include "rogue/extern.c" #include "rogue/armor.c" -#include "rogue/chase.c" +/*#include "rogue/chase.c" #include "rogue/command.c" #include "rogue/daemon.c" #include "rogue/daemons.c" From 10f9393196f31a33b1960a223fcbd04f83dd7eb0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:33:21 -1100 Subject: [PATCH 0258/1145] -Wno --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 4fcbee14f..c7b62e259 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,7 +1,7 @@ cd rogue; #./configure # only need this first time make; cd .. -gcc -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp +gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp #gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so cp librogue.so ../libcc.so From 6d73c8c032e4e7e0c9e71b1835b47a068562704c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:34:07 -1100 Subject: [PATCH 0259/1145] More files --- src/cc/cclib.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 7706058ba..53add03be 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -409,7 +409,7 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para #include "rogue/vers.c" #include "rogue/extern.c" #include "rogue/armor.c" -/*#include "rogue/chase.c" +#include "rogue/chase.c" #include "rogue/command.c" #include "rogue/daemon.c" #include "rogue/daemons.c" @@ -417,7 +417,7 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para #include "rogue/init.c" #include "rogue/io.c" #include "rogue/list.c" -#include "rogue/mach_dep.c" +/*#include "rogue/mach_dep.c" #include "rogue/rogue.c" #include "rogue/mdport.c" #include "rogue/misc.c" From 046de189811c5dc130cd09c795889acbe11ed933 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:36:12 -1100 Subject: [PATCH 0260/1145] -this --- src/cc/rogue/chase.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue/chase.c b/src/cc/rogue/chase.c index 168993edb..73d53e1fd 100644 --- a/src/cc/rogue/chase.c +++ b/src/cc/rogue/chase.c @@ -120,7 +120,7 @@ do_chase(struct rogue_state *rs,THING *th) register bool stoprun = FALSE; /* TRUE means we are there */ register bool door; register THING *obj; - static coord this; /* Temporary destination for chaser */ + static coord DEST; /* Temporary destination for chaser */ rer = th->t_room; /* Find room of chaser */ if (on(*th, ISGREED) && rer->r_goldval == 0) @@ -146,7 +146,7 @@ over: curdist = dist_cp(th->t_dest, cp); if (curdist < mindist) { - this = *cp; + DEST = *cp; mindist = curdist; } } @@ -159,7 +159,7 @@ over: } else { - this = *th->t_dest; + DEST = *th->t_dest; /* * For dragons check and see if (a) the hero is on a straight * line from it, and (b) that it is within shooting distance, @@ -191,13 +191,13 @@ over: * so we run to it. If we hit it we either want to fight it * or stop running */ - if (!chase(th, &this)) + if (!chase(th, &DEST)) { - if (ce(this, hero)) + if (ce(DEST, hero)) { return( attack(rs,th) ); } - else if (ce(this, *th->t_dest)) + else if (ce(DEST, *th->t_dest)) { for (obj = lvl_obj; obj != NULL; obj = next(obj)) if (th->t_dest == &obj->o_pos) From 46b235b2cc38e72b4e063d66869f25ac13a391e1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:39:26 -1100 Subject: [PATCH 0261/1145] syntax --- src/cc/rogue/command.c | 6 +++--- src/cc/rogue/fight.c | 2 +- src/cc/rogue/list.c | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index ce02da076..34a49a70b 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -355,9 +355,9 @@ over: when ']': current(rs,cur_armor, "wearing", NULL); when '=': current(rs,cur_ring[LEFT], "wearing", - terse ? "(L)" : "on left hand"); + terse ? (char *)"(L)" : (char *)"on left hand"); current(rs,cur_ring[RIGHT], "wearing", - terse ? "(R)" : "on right hand"); + terse ? (char *)"(R)" : (char *)"on right hand"); when '@': stat_msg = TRUE; status(rs); @@ -784,7 +784,7 @@ norm: { if (*guess != NULL) free(*guess); - *guess = malloc((unsigned int) strlen(prbuf) + 1); + *guess = (char *)malloc((unsigned int) strlen(prbuf) + 1); strcpy(*guess, prbuf); } } diff --git a/src/cc/rogue/fight.c b/src/cc/rogue/fight.c index ba1c9112e..31c29c62c 100644 --- a/src/cc/rogue/fight.c +++ b/src/cc/rogue/fight.c @@ -353,7 +353,7 @@ set_mname(THING *tp) static char tbuf[MAXSTR] = { 't', 'h', 'e', ' ' }; if (!see_monst(tp) && !on(player, SEEMONST)) - return (terse ? "it" : "something"); + return (terse ? (char *)"it" : (char *)"something"); else if (on(player, ISHALU)) { move(tp->t_pos.y, tp->t_pos.x); diff --git a/src/cc/rogue/list.c b/src/cc/rogue/list.c index 6c069d06e..8dc5a5359 100644 --- a/src/cc/rogue/list.c +++ b/src/cc/rogue/list.c @@ -100,7 +100,7 @@ new_item(void) THING *item; #ifdef MASTER - if ((item = calloc(1, sizeof *item)) == NULL) + if ((item = (THING *)calloc(1, sizeof *item)) == NULL) msg(rs,"ran out of memory after %d items", total); else total++; From a55cc1761ece689ebd061cb9892afae4d3e7a280 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:40:48 -1100 Subject: [PATCH 0262/1145] More c files --- src/cc/cclib.cpp | 4 ++-- src/cc/rogue/list.c | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 53add03be..8d1d7d379 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -417,12 +417,12 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para #include "rogue/init.c" #include "rogue/io.c" #include "rogue/list.c" -/*#include "rogue/mach_dep.c" +#include "rogue/mach_dep.c" #include "rogue/rogue.c" #include "rogue/mdport.c" #include "rogue/misc.c" #include "rogue/monsters.c" -#include "rogue/move.c" +/*#include "rogue/move.c" #include "rogue/new_level.c" #include "rogue/options.c" #include "rogue/pack.c" diff --git a/src/cc/rogue/list.c b/src/cc/rogue/list.c index 8dc5a5359..f571be628 100644 --- a/src/cc/rogue/list.c +++ b/src/cc/rogue/list.c @@ -105,7 +105,7 @@ new_item(void) else total++; #else - item = calloc(1, sizeof *item); + item = (THING *)calloc(1, sizeof *item); #endif item->l_next = NULL; item->l_prev = NULL; From d9f3929917acf6571e0d20b6f5dc025cab313b73 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:43:54 -1100 Subject: [PATCH 0263/1145] Test --- src/cc/rogue/misc.c | 8 ++++---- src/cc/rogue/rogue.c | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue/misc.c b/src/cc/rogue/misc.c index 87bc40b4d..f3aadae73 100644 --- a/src/cc/rogue/misc.c +++ b/src/cc/rogue/misc.c @@ -348,10 +348,10 @@ check_level(struct rogue_state *rs) void chg_str(int amt) { - auto str_t comp; + auto str_t comp = 0; if (amt == 0) - return; + return; add_str(&pstats.s_str, amt); comp = pstats.s_str; if (ISRING(LEFT, R_ADDSTR)) @@ -555,12 +555,12 @@ call_it(struct rogue_state *rs,struct obj_info *info) } else if (!info->oi_guess) { - msg(rs,terse ? "call it: " : "what do you want to call it? "); + msg(rs,terse ? (char *)"call it: " : (char *)"what do you want to call it? "); if (get_str(rs,prbuf, stdscr) == NORM) { if (info->oi_guess != NULL) free(info->oi_guess); - info->oi_guess = malloc((unsigned int) strlen(prbuf) + 1); + info->oi_guess = (char *)malloc((unsigned int) strlen(prbuf) + 1); strcpy(info->oi_guess, prbuf); } } diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index a496426dd..902e71aeb 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -139,7 +139,7 @@ int32_t rogue_replay(uint64_t seed) } if ( num > 0 ) { - rs = calloc(1,sizeof(*rs)); + rs = (struct rogue_state *)calloc(1,sizeof(*rs)); rs->seed = seed; rs->keystrokes = keystrokes; rs->numkeys = num; From e968da8ecb421451284b4d5d05f368c02c308c87 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:46:14 -1100 Subject: [PATCH 0264/1145] -auto --- src/cc/rogue/misc.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/misc.c b/src/cc/rogue/misc.c index f3aadae73..21460dbde 100644 --- a/src/cc/rogue/misc.c +++ b/src/cc/rogue/misc.c @@ -348,7 +348,8 @@ check_level(struct rogue_state *rs) void chg_str(int amt) { - auto str_t comp = 0; + //auto + str_t comp; if (amt == 0) return; From 830ecc52b827d3e7588489f82a0b68a53b5bb98a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:47:42 -1100 Subject: [PATCH 0265/1145] More files --- src/cc/cclib.cpp | 4 ++-- src/cc/rogue/misc.c | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 8d1d7d379..e1bc4bea6 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -422,7 +422,7 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para #include "rogue/mdport.c" #include "rogue/misc.c" #include "rogue/monsters.c" -/*#include "rogue/move.c" +#include "rogue/move.c" #include "rogue/new_level.c" #include "rogue/options.c" #include "rogue/pack.c" @@ -431,7 +431,7 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para #include "rogue/rings.c" #include "rogue/rip.c" #include "rogue/rooms.c" -#include "rogue/save.c" +/*#include "rogue/save.c" #include "rogue/scrolls.c" #include "rogue/state.c" #include "rogue/sticks.c" diff --git a/src/cc/rogue/misc.c b/src/cc/rogue/misc.c index 21460dbde..775878450 100644 --- a/src/cc/rogue/misc.c +++ b/src/cc/rogue/misc.c @@ -348,7 +348,7 @@ check_level(struct rogue_state *rs) void chg_str(int amt) { - //auto + //auto jl777: strange compiler error str_t comp; if (amt == 0) From daf4cfbe0c3d685cd263af5b8a343952a3f7c417 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:51:07 -1100 Subject: [PATCH 0266/1145] Fix --- src/cc/rogue/fight.c | 2 +- src/cc/rogue/pack.c | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue/fight.c b/src/cc/rogue/fight.c index 31c29c62c..6985b6d35 100644 --- a/src/cc/rogue/fight.c +++ b/src/cc/rogue/fight.c @@ -16,7 +16,7 @@ #include #include "rogue.h" -#define EQSTR(a, b) (strcmp(a, b) == 0) +//#define EQSTR(a, b) (strcmp(a, b) == 0) char *h_names[] = { /* strings for hitting */ " scored an excellent hit on ", diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 8c92718b5..6776654fe 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -275,11 +275,9 @@ inventory(struct rogue_state *rs,THING *list, int type) if (n_objs == 0) { if (terse) - msg(rs,type == 0 ? "empty handed" : - "nothing appropriate"); + msg(rs,type == 0 ? (char *)"empty handed" : (char *)"nothing appropriate"); else - msg(rs,type == 0 ? "you are empty handed" : - "you don't have anything appropriate"); + msg(rs,type == 0 ? (char *)"you are empty handed" : (char *)"you don't have anything appropriate"); return FALSE; } end_line(rs); From 6c436c81c18b65b1b5eb05bcca05303d197b6284 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:52:03 -1100 Subject: [PATCH 0267/1145] Enable all files --- src/cc/cclib.cpp | 4 ++-- src/cc/rogue/pack.c | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index e1bc4bea6..d0365b18b 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -431,14 +431,14 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para #include "rogue/rings.c" #include "rogue/rip.c" #include "rogue/rooms.c" -/*#include "rogue/save.c" +#include "rogue/save.c" #include "rogue/scrolls.c" #include "rogue/state.c" #include "rogue/sticks.c" #include "rogue/things.c" #include "rogue/weapons.c" #include "rogue/wizard.c" -#include "rogue/xcrypt.c"*/ +#include "rogue/xcrypt.c" #else #include "sudoku.cpp" diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 6776654fe..8385f95dd 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -358,7 +358,7 @@ picky_inven(struct rogue_state *rs) msg(rs,"a) %s", inv_name(pack, FALSE)); else { - msg(rs,terse ? "item: " : "which item do you wish to inventory: "); + msg(rs,terse ? (char *)"item: " : (char *)"which item do you wish to inventory: "); mpos = 0; if ((mch = readchar(rs)) == ESCAPE) { From e838265e564f7b42ff0ff784a0014cfcb06ef408 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:53:36 -1100 Subject: [PATCH 0268/1145] -auto --- src/cc/rogue/save.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index e12d14ea9..4fdc1a495 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -36,7 +36,8 @@ save_game(struct rogue_state *rs) { FILE *savef; int c; - auto char buf[MAXSTR]; + //auto + char buf[MAXSTR]; /* * get file name @@ -169,8 +170,10 @@ restore(struct rogue_state *rs,char *file, char **envp) FILE *inf; int syml; extern char **environ; - auto char buf[MAXSTR]; - auto STAT sbuf2; + //auto + char buf[MAXSTR]; + //auto + STAT sbuf2; int lines, cols; if (strcmp(file, "-r") == 0) From 007271afc07e92718338f6682c55cf2ae883afa9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:56:02 -1100 Subject: [PATCH 0269/1145] Test --- src/cc/rogue/save.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index 4fdc1a495..50de2069a 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -168,13 +168,12 @@ bool restore(struct rogue_state *rs,char *file, char **envp) { FILE *inf; - int syml; + int syml,lines, cols; extern char **environ; //auto char buf[MAXSTR]; //auto STAT sbuf2; - int lines, cols; if (strcmp(file, "-r") == 0) file = file_name; From 5429a5057b18bcc1ed67e78763d8943e3a9a6741 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 04:57:26 -1100 Subject: [PATCH 0270/1145] L --- src/cc/rogue/save.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index 50de2069a..8dcb65194 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -168,7 +168,7 @@ bool restore(struct rogue_state *rs,char *file, char **envp) { FILE *inf; - int syml,lines, cols; + int syml,l, cols; extern char **environ; //auto char buf[MAXSTR]; @@ -196,15 +196,15 @@ restore(struct rogue_state *rs,char *file, char **envp) return FALSE; } encread(buf,80,inf); - sscanf(buf,"%d x %d\n", &lines, &cols); + sscanf(buf,"%d x %d\n", &l, &cols); initscr(); /* Start up cursor package */ keypad(stdscr, 1); - if (lines > LINES) + if (l > LINES) { endwin(); - printf("Sorry, original game was played on a screen with %d lines.\n",lines); + printf("Sorry, original game was played on a screen with %d lines.\n",l); printf("Current screen only has %d lines. Unable to restore game\n",LINES); return(FALSE); } From 4ccb3b5d9c365f1ec8ffc50eb1d7aeba794f3d87 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 05:02:03 -1100 Subject: [PATCH 0271/1145] THING * --- src/cc/rogue/state.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 60a83c333..f18ee1e5f 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -78,7 +78,7 @@ rs_write(FILE *savef, void *ptr, size_t size) if (write_error) return(WRITESTAT); - if (encwrite(ptr, size, savef) != size) + if (encwrite((char *)ptr, size, savef) != size) write_error = 1; return(WRITESTAT); @@ -90,7 +90,7 @@ rs_read(FILE *inf, void *ptr, size_t size) if (read_error || format_error) return(READSTAT); - if (encread(ptr, size, inf) != size) + if (encread((char *)ptr, size, inf) != size) read_error = 1; return(READSTAT); @@ -554,7 +554,7 @@ rs_read_new_string(FILE *inf, char **s) buf = NULL; else { - buf = malloc(len); + buf = (char *)malloc(len); if (buf == NULL) read_error = TRUE; @@ -1468,7 +1468,7 @@ rs_read_object_reference(FILE *inf, THING *list, THING **item) rs_read_int(inf, &i); - *item = get_list_item(list,i); + *item = (THING *)get_list_item(list,i); return(READSTAT); } @@ -1670,7 +1670,7 @@ rs_read_thing(FILE *inf, THING *t) { THING *obj; - item = get_list_item(lvl_obj, index); + item = (THING *)get_list_item(lvl_obj, index); if (item != NULL) { @@ -1702,7 +1702,7 @@ rs_fix_thing(THING *t) if (t->t_reserved < 0) return; - item = get_list_item(mlist,t->t_reserved); + item = (THING *)get_list_item(mlist,t->t_reserved); if (item != NULL) { @@ -1816,7 +1816,7 @@ rs_read_thing_reference(FILE *inf, THING *list, THING **item) if (i == -1) *item = NULL; else - *item = get_list_item(list,i); + *item = (THING *)get_list_item(list,i); return(READSTAT); } From 1b34dade6682612b9365e0d77e883ea35b281780 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 05:04:42 -1100 Subject: [PATCH 0272/1145] Lcurses --- src/Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index ad9842f09..303adf657 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -100,7 +100,7 @@ EXTRA_LIBRARIES += \ $(LIBBITCOIN_COMMON) \ $(LIBBITCOIN_SERVER) \ $(LIBBITCOIN_CLI) \ - libzcash.a + libzcash.a -lcurses if ENABLE_WALLET BITCOIN_INCLUDES += $(BDB_CPPFLAGS) EXTRA_LIBRARIES += $(LIBBITCOIN_WALLET) From cc89099ff7284677ac8fdbf1ba9157543f89bf5c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 05:08:52 -1100 Subject: [PATCH 0273/1145] libcurses.a --- src/Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index 303adf657..39844c80a 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -100,7 +100,7 @@ EXTRA_LIBRARIES += \ $(LIBBITCOIN_COMMON) \ $(LIBBITCOIN_SERVER) \ $(LIBBITCOIN_CLI) \ - libzcash.a -lcurses + libzcash.a libcurses.a if ENABLE_WALLET BITCOIN_INCLUDES += $(BDB_CPPFLAGS) EXTRA_LIBRARIES += $(LIBBITCOIN_WALLET) From 495c41f313100c3ac6a9a10280aac6c8dce577ed Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 05:11:37 -1100 Subject: [PATCH 0274/1145] -lcurses --- src/Makefile.am | 2 +- src/cc/makerogue | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index 39844c80a..ad9842f09 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -100,7 +100,7 @@ EXTRA_LIBRARIES += \ $(LIBBITCOIN_COMMON) \ $(LIBBITCOIN_SERVER) \ $(LIBBITCOIN_CLI) \ - libzcash.a libcurses.a + libzcash.a if ENABLE_WALLET BITCOIN_INCLUDES += $(BDB_CPPFLAGS) EXTRA_LIBRARIES += $(LIBBITCOIN_WALLET) diff --git a/src/cc/makerogue b/src/cc/makerogue index c7b62e259..2ac20e6e6 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,7 +1,7 @@ cd rogue; #./configure # only need this first time make; cd .. -gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp +gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -lcurses #gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so cp librogue.so ../libcc.so From 23408a86efcd71e6ee36c0ea14fb14f625c953b3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 05:15:40 -1100 Subject: [PATCH 0275/1145] Nurses --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 2ac20e6e6..f7ee26669 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,7 +1,7 @@ cd rogue; #./configure # only need this first time make; cd .. -gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -lcurses +gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -lncurses #gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so cp librogue.so ../libcc.so From fe86924f94239b1a983209a0348e622a021b0637 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 05:17:06 -1100 Subject: [PATCH 0276/1145] -lncurses --- src/Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index ad9842f09..8503ebb56 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -572,7 +572,7 @@ komodod_LDADD += \ $(LIBVERUS_CRYPTO) \ $(LIBVERUS_PORTABLE_CRYPTO) \ $(LIBZCASH_LIBS) \ - libcc.so + libcc.so -lncurses if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) From 00a3970bef861feaf1d5f7b34bf670a41b812038 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 05:19:46 -1100 Subject: [PATCH 0277/1145] #include "rogue/xcrypt.c" --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index d0365b18b..41dfe8cc1 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -419,6 +419,7 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para #include "rogue/list.c" #include "rogue/mach_dep.c" #include "rogue/rogue.c" +#include "rogue/xcrypt.c" #include "rogue/mdport.c" #include "rogue/misc.c" #include "rogue/monsters.c" @@ -438,7 +439,6 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para #include "rogue/things.c" #include "rogue/weapons.c" #include "rogue/wizard.c" -#include "rogue/xcrypt.c" #else #include "sudoku.cpp" From ff22edb4db7e716112d1db26cd1036d0c2194781 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 05:20:34 -1100 Subject: [PATCH 0278/1145] Test --- src/cc/rogue/xcrypt.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/xcrypt.c b/src/cc/rogue/xcrypt.c index bbf5d76ac..b8a1adc03 100644 --- a/src/cc/rogue/xcrypt.c +++ b/src/cc/rogue/xcrypt.c @@ -590,7 +590,7 @@ des_cipher(const char *in, char *out, int salt, int count) memcpy(out, x, sizeof x); return(retval); } - +xxxx char * xcrypt(const char *key, const char *setting) { From 9b5f5ca0ada6e4ad7ba55bc2697e9544beceb316 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 05:22:39 -1100 Subject: [PATCH 0279/1145] -const --- src/cc/rogue/xcrypt.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/xcrypt.c b/src/cc/rogue/xcrypt.c index b8a1adc03..671e20718 100644 --- a/src/cc/rogue/xcrypt.c +++ b/src/cc/rogue/xcrypt.c @@ -590,9 +590,9 @@ des_cipher(const char *in, char *out, int salt, int count) memcpy(out, x, sizeof x); return(retval); } -xxxx + char * -xcrypt(const char *key, const char *setting) +xcrypt( char *key, char *setting) { int i; unsigned int count, salt, l, r0, r1, keybuf[2]; From 171d73ed67486673520dd78cb9dff981237ebd4b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 05:28:39 -1100 Subject: [PATCH 0280/1145] Ignores --- .gitignore | 6 ++++++ src/cc/rogue/test.zip | Bin 5451 -> 0 bytes 2 files changed, 6 insertions(+) delete mode 100644 src/cc/rogue/test.zip diff --git a/.gitignore b/.gitignore index 47f490f20..ebaa71f4d 100644 --- a/.gitignore +++ b/.gitignore @@ -126,3 +126,9 @@ src/komodo-tx.exe src/cryptoconditions/compile + +src/cc/rogue/rogue + +src/cc/rogue/rogue.so + +src/cc/rogue/test.zip diff --git a/src/cc/rogue/test.zip b/src/cc/rogue/test.zip deleted file mode 100644 index b0c54f6d0403f64cc535b2bc756a3d75da122cae..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5451 zcmZ{oRa6uVw}yup7)lUH>FzFR0qI6M1VtEhC<%vdq@|JWmJZ3Gr3M(fO9|-~7zUX0 zedoVB>-_s>?|t#U@7>;OJ$jm0*kk|z00gjTk=Oa+dD9s8&+1tT0FVJ_0Y>h2Zten3 zZ*2wKT)>`o{O)f*+Zh?+0kGas8Cnuh8(MmL5dbi-uQ33C|8+UG!jmC$q7n#mAh7RfkNucsgzRU=kJ;{Y06`TD>HRzsviWuu-W! zTP)yVBg22!I}h1CBy-u>*r@9+jC6mX{E}cLpQgM{$WlY*@SN9l?=n7drAzva0TG3y zRE;w;ZO46X8U93to24b$i`9ft7|RlypFk}x68jI^i6<0J41(LitV=)N6rBgT&HNQG z@fP2!XZW+J?b!J^C@x>Or(U=)y!k6x#Qy^ODCiNyhfa`Hgi}a~Kf%Pfe=7ah zu{mP1!W%HG?VORivC!N>fN9h}p3Jc_q?PZcyLL7JU+RvVRZBNq(<@OwC#iS{BUlP$ zG}!-UJ~lBQojVNRC^tM)YOXXaMt@wKd3XpE`o*98?AF0j)KOHWh! z0-AR{R!qG%l-5-#6N0|YkCrQ#2|=A+9`Kg2{qdl1L#tI zga~+jy0(pi0?B(jvb+ab+2f>8a;6h5%iGfEq$7IrTW70JSw4fib5n439}IIPr3Gs- zajU|*PnD>u=y0J%^?_l3$$Hg~OU;i)63MqV{>M3&lG-|X{VvEY8v5FeKo+ezm9sG< zxpwYfPv>?NSb~Zq=gNg#3)UT!T;(UMMvbyAvBJ`FP z==0;jX7hYt*%tQ#ANP7RlaeNcb|h*3D%`?3Y4ytzh%gK0_~XoQ`K#@>5#Uswef#@k z$|LVmB&?YqE!q;a z)l>Sdmv}XIlVi+SC7pQ#KO8UA7wFSJQtd^Wb-is_lgQihW+s!?T2n5%0I*v@b?y9xl(&&#AY$RY{Cp_o$d4S ze49u1pgps27nP!l@_HJEU0AcPhXC_@jeRjN$<3czhpa%L4&nn$5IFGN4=ME7?bAc4 z3LMS`(HE@&M;G6Z0++0JiF3qiJQf#+pDDS^qzsYY9n;AD9wpFh-nY+McS3TwOru_? zB>ge$Wy_NjC&+fpRQ@2$uqS(Pn7!wD5jr=ZWhWk!K_(#|S#F6sDBLM!oPs3p7=w0G z<7(PvhhS`C4?mBbtKztyF}!JSIGh@~6TwE{)!w ztnPOVtdFL-mXwme{>XijLc{ONJdo^rHZ|>Cdx|;-a&PeIk5Ty1x^8wh4ZTR5G;s;Z zI#kY-5zXzkaiGh9?l--kZ+fvZD!sas8aDprnWv~Wd?!xCn;v()Pw?`Y^b04WE?k0Tv%htr=?1aTIqhmD?*uj($6XES*|MZr^|4bd=Tp4 z?w}Pivf^fWsu^2C*##4xdL4}F?G0)#ru_TVr^UbUvzPpgm~INmQ_iJ~TDa1P`-^n8|bH7Zzy9B4N6Z(tW_A~l^j zG+q>y_lu1(F0m4{TR7(uRb*aU-8?!OMV7e{w+`Wx5<;qt1f?Vo;} z9%GQBno1xMANkzztB++xqQ+F2_j$AXZ~*!EqGD0SH9K6g)^NeSeRsaLuB0_Hr_EkU zN=E+fJG_9T!KKgmH@G0tt-eU^WU;2R_bbQjgxc?Mk(%Re0`)xnY35z=df*PHv*wG} zQ0YgX=sA6E^qZvNCjW~YovN!OsGx>leYwy4`OJv~&w8pWKef@7qiw4B)htx85(5VU zCc&X}EHTxwXxwVVG&^{p%8c_-EV7AZx6-lHw8v{%(1$v&AODVj_ZbM9&&smuWVg@G z|1(+y{(JwEuFQ_+=aai5Gh1?S{jNd6)l7s5KPRyksT30zHwjFCtv^Xm*V|tbUSK}9 zul6&L2tk_+=wp@ti5z zn!2!R)A#ZdZybKe3HeQA2wyG>Cx#Jg4?gSDE_3SQItmom)tim+|FF7LHfL>FqH$Tq zTVo?3JZ|E>S6kr8S(Hd&A>cym?>o#_qS+#<$n8l$v(^0NFowr5CPwsAX9w8mQ#xD{ zwS6@G0n$QT=%raM)#+IitA|%?P^rjO8(;C}I$GNMux{q}(DmOb>L12Qq{X|wVvf$= zWk(VGYUpz55jW3CS0|#P<+vDz1Y{*tuIX3N#weg)fMq0bi5{nvB;3xbuL+rBM;UH&>yzU*d9MfSl zynl5#^8gOX+ELa9Z%~PRRCnUT4Yv5nx$#y2H9iyU11wGtUWYdEts|-QbBRRYsqA}U zlHj{kcR#Yl4o)XGyCma-$jHSwb%k#_@=5X&X1?E)ez{x9j@X|qb0qzgfX7~%h_c;j z#ip4Euxf1h+y~ur+A;q%=q>1{LEzBU(vnq;ws9@bN^Bvmm>vx%<9`Dt0-t%6(h|() zZhHOwS`knW(dgYm;5E3ez6{#JB;nXo(hIQ#kx1_;Oa|Ei6zIQl&DzA4yK{eQW_qsB z0Vw67P!Dd%6u-Qa1d&&Pp%BTJLvI6 z273`wr6H@#&3lfa+#Bp6YMqxg6ufli-7vY$JDN*%19c|x2OS-h4Wxw7rDrA0OcpSrvr#??V zuZ^URI(xu$wA=Lm;KdVf?i*5#-#Hi3^6|`=V*Q}c0@x~tS-kF0%)brIp21~BM(ibV z=DBuz$|{-XH*{Xu{mjKBf!M=YDJE^k^%Fd9PV2=HiiT3nty$Hw^61nFOyV;1!IDkx*5N2m;Yyuyhu8oQ`c54c0|dgP=q z-9CwIlTMESrkme#`ix}^Y~#wLV!xK5(4;TsvtlCR5K3E)P-eGKvA|$4aP1&7U)~$; zBXPP_B{Ua|8+%2az4TEJtN+3mC;0Jwl>%2f6Y<9yCMp6GMY(4-#(?ML{(=q~XL#NP z$AVIqm>(-}b(q!N9b}mrbb~mg-dR3%cPj?kP@GMzq><-5XMGG(5Kk|_S!SFjT9i9+ z)F>cwE3~+TDJY@Bz7mEgxQE7vJ~|0;4hmP>KNvE&DOfN_&2TjdA36NC<>6nN~CD}ji1Al1GZlRj2L z5T5?D^!1tgao-iArb7AFG^{ZVhLAf+++CW7p7i4#3yBk%)lqBLW%e zKWK<5N-^qk2zf(@#^7UXvy#jwK0~J=J|Oa7R!bfC(x;cXe>MVA0_Ov)H__79E0^H3 zZ1#uvz&~l99$%pIb~e@?yHU3{TK{@%-Dixo#rD`HJPzm0kfd}ops$Qa0`DXae&2UQ zqHCKATW(vryG3e49)-~z++BVD2-;ARfl~n!-RKF1nt%y3^sXD4cfWPNa(Oxe{;@XH z4bEMh+b)Pi(&%gX!OKi&^#iTKB%TLud`kkC1Eyi;^nPxqyf zpY<-<2{m9H&^0A-i^jWdyORuDm2+ljiC;lC9=l(;KeqZeJ)FFe|IC0s;qT}OJiE~4 z3*^4RRtqSNyz6biKe!ow$EOm6=P$)gtRV3c_Yv7d?`OY_dt}Kslqf4^`pltjMp}pE z>^l_(G>yWKo{0hn+Y~E{vyi9YN&JA014uyeCBsZUbir(DvrHrzenpR!aH-gCLd`g` z*XubI5D@ImsN|COshFo%8*IO-7f#K%&pvBG?K&wvF*0RD5{v-VsJQYmQj4-$P=jXl zxdhuW)O-dfJZ630%Xv%yZg~eJm~$(@)IlOFT~DdW-v@ZyXgM8X4bVVa;*Y*x0>D8c zJ=9l3I0N)=^FhERKJ)@zb_s5jWg_d#%@a0t_i{bM&tRODS1H0t)2ehOV@X_~YC;*Q zBr@U>%Yx#gK8OJ<*+{Y^o%&Q{0V7hF+TeOetWt;5R$qmK_l}<^L01=}Kcgc$rD!qn zVnI_2=;0DMMax5$Vztau)F@N%0;+|jp9DVs^EFk%+ScC5Scyw>%06JKh(x(tlCui- zYqs7ltOYaXV(e?`cN=97m)Jr{1=z1qNF<$t^Wp`u7|A}7*d4J)jukEo=XEvCXkT>I zYY*{s&*RjcUxW4Bi2X(3X@aW$<6EbRkH_rt?s7E7r|*o`LGf>d;M*<1DgKN*UdDE4 zzj?y-GmyBano{<9TJ}W;QB!`4UGu%Oyk@VlnX2oP0dHqtJF!-jDVWZ_)rir~_2Xua zX=j?Cu^=T6s1KjwEilbA7-$U8A--jjRJR}wnk%6&XAGYMjBE}T0x$F5(Wlvf%ixF&oZuDnSPiDZa>jyG5C}-7y&Cf@jP)5G$xnR0f<9Wlv(RYLrkEmlK&0+Xfz@}wv`a{@WW%Obqwuug= zxy|g9qiF=i**lBzC~`F$AoC&;6K8{(FFl^lPmm_8u91n9&otVJfL!`EzsPhqTa3=V z1jB$gSr2$Em|sLTiQCio(yZwvfCm7PPm3+E5wGLL^smQO$eKjHw8)%vR%`@C?h%7* z1^eylw1s+&ff>QFlQXYqcqV)Cd!jS#6hjI8`IgHCuX!0=D&*TWs0;~T5h&Ih^?1U_ zsxfeM@K=bI9f%~$=Z4WvVKNE8`dpk!)kMT_+v>g(6uj-#adHpu^}8P@+^1s%1OoXB z&Pmv3GNQaVUNR~OhTExyyh*^JTusk@i=_3+Bbo<#R&63S)2YL_NbLLWj_Twlv%;kq zp3uJVVZdsqg01Ct)4i9P`E%E2A=)aHz?8lb9J`9UeA$9Ut&6>h7wy2YwMcz-e&p}^ z_51iVT6O{joWSeKkiNRk4M2m{oWX`PM7w zCjLljv+tVj@!zzm)LRBUO$ Date: Sat, 2 Feb 2019 05:29:34 -1100 Subject: [PATCH 0281/1145] Delay replay --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 902e71aeb..c810a313d 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -399,7 +399,7 @@ playit(struct rogue_state *rs) //fprintf(stderr,"replaydone\n"); sleep(3); return; } - //usleep(100000); + usleep(50000); } else { From faf6323ad4c2e03d4f754b4784dc2c8b70a75a9d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 05:33:47 -1100 Subject: [PATCH 0282/1145] Bigger buffer --- src/cc/rogue/rogue.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 040c9a97d..fff9203a0 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -319,7 +319,7 @@ struct rogue_state char *keystrokes; uint32_t needflush,replaydone; int32_t numkeys,ind,num,guiflag,counter; - char buffered[64]; + char buffered[8192]; }; int rogue(int argc, char **argv, char **envp); From 405e1e0c1707665e7cfb8f7e4549e8ae92222974 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 05:39:05 -1100 Subject: [PATCH 0283/1145] Gui mode for seed --- src/cc/rogue/main.c | 2 +- src/cc/rogue/rogue.c | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 681d51e31..68dca0e98 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -32,7 +32,7 @@ int rogue(int argc, char **argv, char **envp); int main(int argc, char **argv, char **envp) { uint64_t seed; FILE *fp = 0; - if ( argc > 1 && (fp=fopen(argv[1],"rb")) == 0 ) + if ( argc == 2 && (fp=fopen(argv[1],"rb")) == 0 ) { seed = atol(argv[1]); fprintf(stderr,"replay %llu\n",(long long)seed); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index c810a313d..010b66c9f 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -166,7 +166,9 @@ int rogue(int argc, char **argv, char **envp) { char *env; int lowtime; struct rogue_state *rs = &globalR; memset(rs,0,sizeof(*rs)); - rs->seed = 777; + if ( argc == 3 && strcmp(argv[2],"gui") == 0 ) + rs->seed = atol(argv[1]); + else rs->seed = 777; rs->guiflag = 1; md_init(); From 6ecbc31948e3425f38b590981fbe7d6d0ff1890c Mon Sep 17 00:00:00 2001 From: dimxy Date: Sat, 2 Feb 2019 21:41:40 +0500 Subject: [PATCH 0284/1145] added skipping asset validation for SEC chain --- src/cc/assets.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index 2433473b9..968659470 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -146,6 +146,9 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti outputs = inputs = 0; preventCCvins = preventCCvouts = -1; + if (strcmp(ASSETCHAINS_SYMBOL, "SEC") == 0 && chainActive.Height() < 144073) + return true; + if (numvouts == 0) return eval->Invalid("AssetValidate: no vouts"); From 71225aaa3f0e8e3c5f1e4c03597ef817b89a230a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 05:43:37 -1100 Subject: [PATCH 0285/1145] Reduce buffer size --- src/cc/rogue/rogue.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index fff9203a0..472b2755a 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -319,7 +319,7 @@ struct rogue_state char *keystrokes; uint32_t needflush,replaydone; int32_t numkeys,ind,num,guiflag,counter; - char buffered[8192]; + char buffered[512]; }; int rogue(int argc, char **argv, char **envp); From 43f5b8c00fd74a9e733eb6710398466594233c03 Mon Sep 17 00:00:00 2001 From: dimxy Date: Sat, 2 Feb 2019 21:56:22 +0500 Subject: [PATCH 0286/1145] added MGNX chain old token support --- src/cc/assets.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index 968659470..6aae09dd3 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -146,7 +146,11 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti outputs = inputs = 0; preventCCvins = preventCCvouts = -1; - if (strcmp(ASSETCHAINS_SYMBOL, "SEC") == 0 && chainActive.Height() < 144073) + // add specific chains exceptions for old token support: + if (strcmp(ASSETCHAINS_SYMBOL, "SEC") == 0 && chainActive.Height() <= 144073) + return true; + + if (strcmp(ASSETCHAINS_SYMBOL, "MGNX") == 0 && chainActive.Height() <= 210190) return true; if (numvouts == 0) From dbc619112f89f3ecab70bac745bec8ac141a98b0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 06:43:40 -1100 Subject: [PATCH 0287/1145] rogue: newgame, txidinfo, pending roc --- src/cc/cclib.cpp | 25 +++ src/cc/rogue_rpc.cpp | 398 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 423 insertions(+) create mode 100644 src/cc/rogue_rpc.cpp diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 41dfe8cc1..b6ba2eb93 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -55,6 +55,8 @@ CClib_methods[] = { (char *)"faucet2", (char *)"get", (char *)"", 0, 0, 'G', EVAL_FAUCET2 }, #ifdef BUILD_ROGUE { (char *)"rogue", (char *)"newgame", (char *)"buyin", 0, 1, 'N', EVAL_ROGUE }, + { (char *)"rogue", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_ROGUE }, + { (char *)"rogue", (char *)"pending", (char *)"", 0, 0, 'U', EVAL_ROGUE }, { (char *)"rogue", (char *)"register", (char *)"txid [inventory]", 1, 2, 'R', EVAL_ROGUE }, { (char *)"rogue", (char *)"progress", (char *)"txid fname", 2, 2, 'P', EVAL_ROGUE }, { (char *)"rogue", (char *)"claimwin", (char *)"txid", 1, 1, 'W', EVAL_ROGUE }, @@ -76,6 +78,11 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { return(true); } +UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_progress(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_claimwin(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); #else bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); @@ -92,6 +99,23 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) if ( cp->evalcode == EVAL_ROGUE ) { rogue_replay(777); + if ( strcmp(method,"newgame") == 0 ) + return(rogue_newgame(txfee,cp,params)); + else if ( strcmp(method,"register") == 0 ) + return(rogue_register(txfee,cp,params)); + else if ( strcmp(method,"progress") == 0 ) + return(rogue_progress(txfee,cp,params)); + else if ( strcmp(method,"claimwin") == 0 ) + return(rogue_claimwin(txfee,cp,params)); + else if ( strcmp(method,"extract") == 0 ) + return(rogue_extract(txfee,cp,params)); + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","invalid rogue method")); + result.push_back(Pair("method",method)); + return(result); + } } #else if ( cp->evalcode == EVAL_SUDOKU ) @@ -406,6 +430,7 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para } #ifdef BUILD_ROGUE +#include "rogue_rpc.cpp" #include "rogue/vers.c" #include "rogue/extern.c" #include "rogue/armor.c" diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp new file mode 100644 index 000000000..536b6e590 --- /dev/null +++ b/src/cc/rogue_rpc.cpp @@ -0,0 +1,398 @@ + +/****************************************************************************** + * Copyright © 2014-2019 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. * + * * + ******************************************************************************/ + +#include "cJSON.h" + + +//////////////////////// start of CClib interface + + +CScript rogue_newgameopret(int64_t buyin) +{ + CScript opret; uint8_t evalcode = EVAL_ROGUE; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'G' << buyin); + return(opret); +} + +/*CScript rogue_solutionopret(char *solution,uint32_t timestamps[81]) +{ + CScript opret; uint8_t evalcode = EVAL_ROGUE; std::string str(solution); std::vector data; int32_t i; + for (i=0; i<81; i++) + { + data.push_back((timestamps[i] >> 24) & 0xff); + data.push_back((timestamps[i] >> 16) & 0xff); + data.push_back((timestamps[i] >> 8) & 0xff); + data.push_back(timestamps[i] & 0xff); + } + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'S' << str << data); + return(opret); +} + +uint8_t rogue_solutionopreturndecode(char solution[82],uint32_t timestamps[81],CScript scriptPubKey) +{ + std::vector vopret; uint8_t *script,e,f; std::string str; std::vector data; int32_t i,ind; uint32_t x; + GetOpReturnData(scriptPubKey,vopret); + script = (uint8_t *)vopret.data(); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> str; ss >> data) != 0 && e == EVAL_ROGUE && f == 'S' ) + { + if ( data.size() == 81*sizeof(uint32_t) && str.size() == 81 ) + { + strcpy(solution,str.c_str()); + for (i=ind=0; i<81; i++) + { + if ( solution[i] < '1' || solution[i] > '9' ) + break; + x = data[ind++]; + x <<= 8, x |= (data[ind++] & 0xff); + x <<= 8, x |= (data[ind++] & 0xff); + x <<= 8, x |= (data[ind++] & 0xff); + timestamps[i] = x; + } + if ( i == 81 ) + return(f); + } else fprintf(stderr,"datasize %d sol[%d]\n",(int32_t)data.size(),(int32_t)str.size()); + } + return(0); +}*/ + +uint8_t rogue_newgameopreturndecode(int64_t &buyin,CScript scriptPubKey) +{ + std::vector vopret; uint8_t *script,e,f; + GetOpReturnData(scriptPubKey,vopret); + script = (uint8_t *)vopret.data(); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> buyin) != 0 && e == EVAL_ROGUE && f == 'G' ) + { + return(f); + } + return(0); +} + +UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + CPubKey roguepk,mypk; char *jsonstr; uint64_t inputsum,amount = 0; + if ( params != 0 ) + { + if ( (jsonstr= jprint(params,0)) != 0 ) + { + if ( jsonstr[0] == '"' && jsonstr[strlen(jsonstr)-1] == '"' ) + { + jsonstr[strlen(jsonstr)-1] = 0; + jsonstr++; + } + amount = atof(jsonstr) * COIN + 0.0000000049; + free(jsonstr); + } + } + mypk = pubkey2pk(Mypubkey()); + roguepk = GetUnspendable(cp,0); + result.push_back(Pair("result","success")); + result.push_back(Pair("name","rogue")); + result.push_back(Pair("method","newgame")); + if ( amount == 0 ) + result.push_back(Pair("type","newbie")); + else result.push_back(Pair("type","buyin")); + result.push_back(Pair("amount",ValueFromAmount(amount))); + if ( (inputsum= AddCClibInputs(cp,mtx,roguepk,3*txfee,16,cp->unspendableCCaddr)) >= 3*txfee ) + { + mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,roguepk)); + mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,mypk)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_newgameopret(amount)); + if ( rawtx.size() > 0 ) + { + CTransaction tx; + result.push_back(Pair("hex",rawtx)); + if ( DecodeHexTx(tx,rawtx) != 0 ) + result.push_back(Pair("txid",tx.GetHash().ToString())); + } else result.push_back(Pair("error","couldnt finalize CCtx")); + } + return(result); +} + +UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + return(result); +} + +UniValue rogue_progress(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + return(result); +} + +UniValue rogue_claimwin(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + return(result); +} + +UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + return(result); +} + +UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); int32_t numvouts; char CCaddr[64],str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; uint64_t amount; CBlockIndex *pindex; + if ( params != 0 ) + { + result.push_back(Pair("result","success")); + if ( (txidstr= jprint(params,0)) != 0 ) + { + if ( txidstr[0] == '"' && txidstr[strlen(txidstr)-1] == '"' ) + { + txidstr[strlen(txidstr)-1] = 0; + txidstr++; + } + //printf("params -> (%s)\n",txidstr); + decode_hex((uint8_t *)&txid,32,txidstr); + txid = revuint256(txid); + result.push_back(Pair("txid",txid.GetHex())); + if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + { + if ( rogue_newgameopreturndecode(buyin,tx.vout[numvouts-1].scriptPubKey) == 'G' ) + { + result.push_back(Pair("result","success")); + if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) + result.push_back(Pair("height",pindex->GetHeight())); + Getscriptaddress(CCaddr,tx.vout[1].scriptPubKey); + result.push_back(Pair("rogueaddr",CCaddr)); + result.push_back(Pair("buyin",ValueFromAmount(buyin))); + } + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","couldnt extract rogue_generate opreturn")); + } + } + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","couldnt find txid")); + } + } + } + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","missing txid in params")); + } + result.push_back(Pair("name","rogue")); + result.push_back(Pair("method","txidinfo")); + return(result); +} + +UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ),a(UniValue::VARR); + char coinaddr[64]; uint64_t seed; int64_t nValue,total=0; uint256 txid,hashBlock; CTransaction tx; int32_t ht,vout,numvouts; CPubKey roguepk; CBlockIndex *pindex; + std::vector > unspentOutputs; + roguepk = GetUnspendable(cp,0); + GetCCaddress(cp,coinaddr,roguepk); + SetCCunspents(unspentOutputs,coinaddr); + for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) + { + txid = it->first.txhash; + vout = (int32_t)it->first.index; + //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); + if ( it->second.satoshis != txfee || vout != 0 ) + continue; + if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + { + if ( (nValue= IsCClibvout(cp,tx,vout,coinaddr)) == txfee && myIsutxo_spentinmempool(txid,vout) == 0 ) + { + if ( rogue_newgameopreturndecode(amount,tx.vout[numvouts-1].scriptPubKey) == 'G' ) + { + UniValue obj(UniValue::VOBJ); + if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) + { + ht = pindex->GetHeight(); + obj.push_back(Pair("height",ht)); + obj.push_back(Pair("start",ht+10)); + if ( komodo_nextheight() > ht+10 ) + { + if ( pindex= komodo_chainactive(ht+10)) != 0 ) + { + hashBlock = pindex->GetBlockHash(); + obj.push_back(Pair("starthash",hashBlock.ToString().c_str())); + memset(&seed,&hashBlock,sizeof(seed)); + seed &= (1LL << 63) - 1; + obj.push_back(Pair("seed",(int64_t)seed)); + } + } + } + obj.push_back(Pair("buyin",ValueFromAmount(amount))); + obj.push_back(Pair("txid",txid.GetHex())); + a.push_back(obj); + total += amount; + } + } + } + } + result.push_back(Pair("result","success")); + result.push_back(Pair("name","rogue")); + result.push_back(Pair("method","pending")); + result.push_back(Pair("pending",a)); + result.push_back(Pair("numpending",a.size())); + result.push_back(Pair("total",ValueFromAmount(total))); + return(result); +} + +#ifdef notyest +UniValue rogue_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + UniValue result(UniValue::VOBJ); int32_t i,j,good,ind,n,numvouts; uint256 txid; char *jsonstr,*newstr,*txidstr,coinaddr[64],checkaddr[64],CCaddr[64],*solution=0,unsolved[82]; CPubKey pk,mypk; uint8_t vals9[9][9],priv32[32],pub33[33]; uint32_t timestamps[81]; uint64_t balance,inputsum; std::string rawtx; CTransaction tx; uint256 hashBlock; + mypk = pubkey2pk(Mypubkey()); + memset(timestamps,0,sizeof(timestamps)); + result.push_back(Pair("name","rogue")); + result.push_back(Pair("method","solution")); + good = 0; + if ( params != 0 ) + { + if ( (jsonstr= jprint(params,0)) != 0 ) + { + if ( jsonstr[0] == '"' && jsonstr[strlen(jsonstr)-1] == '"' ) + { + jsonstr[strlen(jsonstr)-1] = 0; + jsonstr++; + } + newstr = (char *)malloc(strlen(jsonstr)+1); + for (i=j=0; jsonstr[i]!=0; i++) + { + if ( jsonstr[i] == '%' && jsonstr[i+1] == '2' && jsonstr[i+2] == '2' ) + { + newstr[j++] = '"'; + i += 2; + } else newstr[j++] = jsonstr[i]; + } + newstr[j] = 0; + params = cJSON_Parse(newstr); + } else params = 0; + if ( params != 0 ) + { + if ( (n= cJSON_GetArraySize(params)) > 2 && n <= (sizeof(timestamps)/sizeof(*timestamps))+2 ) + { + for (i=2; i '9' ) + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","illegal solution")); + return(result); + } + vals9[i][j] = solution[ind++] - '0'; + } + rogue_privkey(priv32,vals9); + priv2addr(coinaddr,pub33,priv32); + pk = buf2pk(pub33); + GetCCaddress(cp,CCaddr,pk); + result.push_back(Pair("rogueaddr",CCaddr)); + balance = CCaddress_balance(CCaddr); + result.push_back(Pair("amount",ValueFromAmount(balance))); + if ( rogue_captcha(1,timestamps,komodo_nextheight()) < 0 ) + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","captcha failure")); + return(result); + } + else + { + if ( (txidstr= jstri(params,0)) != 0 ) + { + decode_hex((uint8_t *)&txid,32,txidstr); + txid = revuint256(txid); + result.push_back(Pair("txid",txid.GetHex())); + if ( CCgettxout(txid,0,1) < 0 ) + result.push_back(Pair("error","already solved")); + else if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + { + Getscriptaddress(checkaddr,tx.vout[1].scriptPubKey); + if ( strcmp(checkaddr,CCaddr) != 0 ) + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","wrong solution")); + result.push_back(Pair("yours",CCaddr)); + return(result); + } + if ( rogue_genopreturndecode(unsolved,tx.vout[numvouts-1].scriptPubKey) == 'G' ) + { + for (i=0; i<81; i++) + { + if ( unsolved[i] < '1' || unsolved[i] > '9') + continue; + else if ( unsolved[i] != solution[i] ) + { + printf("i.%d [%c] != [%c]\n",i,unsolved[i],solution[i]); + result.push_back(Pair("error","wrong rogue solved")); + break; + } + } + if ( i == 81 ) + good = 1; + } else result.push_back(Pair("error","cant decode rogue")); + } else result.push_back(Pair("error","couldnt find rogue")); + } + if ( good != 0 ) + { + mtx.vin.push_back(CTxIn(txid,0,CScript())); + if ( (inputsum= AddCClibInputs(cp,mtx,pk,balance,16,CCaddr)) >= balance ) + { + mtx.vout.push_back(CTxOut(balance,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + CCaddr2set(cp,cp->evalcode,pk,priv32,CCaddr); + rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,rogue_solutionopret(solution,timestamps)); + if ( rawtx.size() > 0 ) + { + result.push_back(Pair("result","success")); + result.push_back(Pair("hex",rawtx)); + } + else result.push_back(Pair("error","couldnt finalize CCtx")); + } else result.push_back(Pair("error","couldnt find funds in solution address")); + } + } + } + } + else + { + printf("n.%d params.(%s)\n",n,jprint(params,0)); + result.push_back(Pair("error","couldnt get all params")); + } + return(result); + } + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","couldnt parse parameters")); + result.push_back(Pair("parameters",newstr)); + return(result); + } + } + result.push_back(Pair("result","error")); + result.push_back(Pair("error","missing parameters")); + return(result); +} +#endif + From 65c54049a915ea5db9a4f2b7dee0ae3b5172de35 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 06:44:41 -1100 Subject: [PATCH 0288/1145] Syntax --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 536b6e590..b3f13777c 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -83,7 +83,7 @@ uint8_t rogue_newgameopreturndecode(int64_t &buyin,CScript scriptPubKey) UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CPubKey roguepk,mypk; char *jsonstr; uint64_t inputsum,amount = 0; + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey roguepk,mypk; char *jsonstr; uint64_t inputsum,amount = 0; if ( params != 0 ) { if ( (jsonstr= jprint(params,0)) != 0 ) From 06d45f433b9b1e340b109cb7058b66e63a09da99 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 06:45:43 -1100 Subject: [PATCH 0289/1145] CBlockIndex *komodo_chainactive(int32_t height) --- src/cc/CCinclude.h | 1 + src/cc/rogue_rpc.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index 4da696547..07c5e9491 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -135,6 +135,7 @@ void CCclearvars(struct CCcontract_info *cp); UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params); UniValue CClib_info(struct CCcontract_info *cp); CBlockIndex *komodo_blockindex(uint256 hash); +CBlockIndex *komodo_chainactive(int32_t height); static const uint256 zeroid; bool myGetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b3f13777c..91429cafe 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -200,7 +200,7 @@ UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ),a(UniValue::VARR); - char coinaddr[64]; uint64_t seed; int64_t nValue,total=0; uint256 txid,hashBlock; CTransaction tx; int32_t ht,vout,numvouts; CPubKey roguepk; CBlockIndex *pindex; + char coinaddr[64]; uint64_t seed; int64_t amount,nValue,total=0; uint256 txid,hashBlock; CTransaction tx; int32_t ht,vout,numvouts; CPubKey roguepk; CBlockIndex *pindex; std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); GetCCaddress(cp,coinaddr,roguepk); From 73445259d1d556c064f0412df2d679d17726183b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 06:46:08 -1100 Subject: [PATCH 0290/1145] ( --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 91429cafe..c1a6102d0 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -226,7 +226,7 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) obj.push_back(Pair("start",ht+10)); if ( komodo_nextheight() > ht+10 ) { - if ( pindex= komodo_chainactive(ht+10)) != 0 ) + if ( (pindex= komodo_chainactive(ht+10)) != 0 ) { hashBlock = pindex->GetBlockHash(); obj.push_back(Pair("starthash",hashBlock.ToString().c_str())); From fa2851ccfabefb147e051841c5aff3f9055051b7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 06:47:56 -1100 Subject: [PATCH 0291/1145] Test --- src/cc/rogue_rpc.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c1a6102d0..50335be72 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -148,7 +148,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); int32_t numvouts; char CCaddr[64],str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; uint64_t amount; CBlockIndex *pindex; + UniValue result(UniValue::VOBJ); int32_t numvouts; char CCaddr[64],str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; uint64_t buyin; CBlockIndex *pindex; if ( params != 0 ) { result.push_back(Pair("result","success")); @@ -230,8 +230,8 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { hashBlock = pindex->GetBlockHash(); obj.push_back(Pair("starthash",hashBlock.ToString().c_str())); - memset(&seed,&hashBlock,sizeof(seed)); - seed &= (1LL << 63) - 1; + memcpy(&seed,&hashBlock,sizeof(seed)); + seed &= (1LL << 62) - 1; obj.push_back(Pair("seed",(int64_t)seed)); } } From 381c067e04488a647ffed45277b62426bfaa5af2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 06:49:07 -1100 Subject: [PATCH 0292/1145] U --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 50335be72..2ed5236b9 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -148,7 +148,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); int32_t numvouts; char CCaddr[64],str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; uint64_t buyin; CBlockIndex *pindex; + UniValue result(UniValue::VOBJ); int32_t numvouts; char CCaddr[64],str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; int64_t buyin; CBlockIndex *pindex; if ( params != 0 ) { result.push_back(Pair("result","success")); From 078f999bc462e7a70729ea842cac1649ccd9f548 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 06:54:25 -1100 Subject: [PATCH 0293/1145] Support txidinfo and pending --- src/cc/cclib.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index b6ba2eb93..2c20bfcc0 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -54,11 +54,11 @@ CClib_methods[] = { (char *)"faucet2", (char *)"fund", (char *)"amount", 1, 1, 'F', EVAL_FAUCET2 }, { (char *)"faucet2", (char *)"get", (char *)"", 0, 0, 'G', EVAL_FAUCET2 }, #ifdef BUILD_ROGUE - { (char *)"rogue", (char *)"newgame", (char *)"buyin", 0, 1, 'N', EVAL_ROGUE }, - { (char *)"rogue", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_ROGUE }, - { (char *)"rogue", (char *)"pending", (char *)"", 0, 0, 'U', EVAL_ROGUE }, + { (char *)"rogue", (char *)"newgame", (char *)"buyin", 0, 1, 'G', EVAL_ROGUE }, + { (char *)"rogue", (char *)"txidinfo", (char *)"txid", 1, 1, 'I', EVAL_ROGUE }, + { (char *)"rogue", (char *)"pending", (char *)"", 0, 0, 'P', EVAL_ROGUE }, { (char *)"rogue", (char *)"register", (char *)"txid [inventory]", 1, 2, 'R', EVAL_ROGUE }, - { (char *)"rogue", (char *)"progress", (char *)"txid fname", 2, 2, 'P', EVAL_ROGUE }, + { (char *)"rogue", (char *)"progress", (char *)"txid fname", 2, 2, 'K', EVAL_ROGUE }, { (char *)"rogue", (char *)"claimwin", (char *)"txid", 1, 1, 'W', EVAL_ROGUE }, { (char *)"rogue", (char *)"extract", (char *)"txid item", 2, 2, 'X', EVAL_ROGUE }, #else @@ -101,6 +101,10 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) rogue_replay(777); if ( strcmp(method,"newgame") == 0 ) return(rogue_newgame(txfee,cp,params)); + else if ( strcmp(method,"pending") == 0 ) + return(rogue_pending(txfee,cp,params)); + else if ( strcmp(method,"txidinfo") == 0 ) + return(rogue_txidinfo(txfee,cp,params)); else if ( strcmp(method,"register") == 0 ) return(rogue_register(txfee,cp,params)); else if ( strcmp(method,"progress") == 0 ) From 9e70589b1ec09f34e9fddae8813460e111eeee8c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 06:55:50 -1100 Subject: [PATCH 0294/1145] UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); --- src/cc/cclib.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 2c20bfcc0..549db5848 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -79,6 +79,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return(true); } UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_progress(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_claimwin(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); From 5683411a18af427b5607def39627817b66c06b1b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 06:58:35 -1100 Subject: [PATCH 0295/1145] More txidinfo --- src/cc/rogue_rpc.cpp | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 2ed5236b9..81c2b0ba1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -148,7 +148,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); int32_t numvouts; char CCaddr[64],str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; int64_t buyin; CBlockIndex *pindex; + UniValue result(UniValue::VOBJ); int32_t ht,numvouts; char CCaddr[64],str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; uint64_t seed; int64_t buyin; CBlockIndex *pindex; if ( params != 0 ) { result.push_back(Pair("result","success")); @@ -169,7 +169,22 @@ UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { result.push_back(Pair("result","success")); if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) - result.push_back(Pair("height",pindex->GetHeight())); + { + ht = pindex->GetHeight(); + obj.push_back(Pair("height",ht)); + obj.push_back(Pair("start",ht+10)); + if ( komodo_nextheight() > ht+10 ) + { + if ( (pindex= komodo_chainactive(ht+10)) != 0 ) + { + hashBlock = pindex->GetBlockHash(); + obj.push_back(Pair("starthash",hashBlock.ToString().c_str())); + memcpy(&seed,&hashBlock,sizeof(seed)); + seed &= (1LL << 62) - 1; + obj.push_back(Pair("seed",(int64_t)seed)); + } + } + } Getscriptaddress(CCaddr,tx.vout[1].scriptPubKey); result.push_back(Pair("rogueaddr",CCaddr)); result.push_back(Pair("buyin",ValueFromAmount(buyin))); From 5567a8498db410ad664cdf049c85d97928749c22 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 06:59:24 -1100 Subject: [PATCH 0296/1145] result --- src/cc/rogue_rpc.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 81c2b0ba1..b6b12f64b 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -171,17 +171,17 @@ UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) { ht = pindex->GetHeight(); - obj.push_back(Pair("height",ht)); - obj.push_back(Pair("start",ht+10)); + result.push_back(Pair("height",ht)); + result.push_back(Pair("start",ht+10)); if ( komodo_nextheight() > ht+10 ) { if ( (pindex= komodo_chainactive(ht+10)) != 0 ) { hashBlock = pindex->GetBlockHash(); - obj.push_back(Pair("starthash",hashBlock.ToString().c_str())); + result.push_back(Pair("starthash",hashBlock.ToString().c_str())); memcpy(&seed,&hashBlock,sizeof(seed)); seed &= (1LL << 62) - 1; - obj.push_back(Pair("seed",(int64_t)seed)); + result.push_back(Pair("seed",(int64_t)seed)); } } } From 98fc13a132d311e1f4efd65d669784e6d79e87f2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 07:01:24 -1100 Subject: [PATCH 0297/1145] Fix --- src/cc/rogue_rpc.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b6b12f64b..f9c05220c 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -18,6 +18,9 @@ //////////////////////// start of CClib interface +// cclib newgame 17 +// cclib pending 17 +// cclib txidinfo 17 \"35e99df53c981a937bfa2ce7bfb303cea0249dba34831592c140d1cb729cb19f\" CScript rogue_newgameopret(int64_t buyin) @@ -151,7 +154,6 @@ UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); int32_t ht,numvouts; char CCaddr[64],str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; uint64_t seed; int64_t buyin; CBlockIndex *pindex; if ( params != 0 ) { - result.push_back(Pair("result","success")); if ( (txidstr= jprint(params,0)) != 0 ) { if ( txidstr[0] == '"' && txidstr[strlen(txidstr)-1] == '"' ) From ec7419b6f9507e1a98c7f6d5eeb514268f931ce4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 07:11:33 -1100 Subject: [PATCH 0298/1145] ROGUE_REGISTRATION --- src/cc/rogue_rpc.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f9c05220c..763408258 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -16,12 +16,15 @@ #include "cJSON.h" +#define ROGUE_REGISTRATION 5 //////////////////////// start of CClib interface +//./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & + // cclib newgame 17 // cclib pending 17 // cclib txidinfo 17 \"35e99df53c981a937bfa2ce7bfb303cea0249dba34831592c140d1cb729cb19f\" - +// ./rogue gui -> creates keystroke files CScript rogue_newgameopret(int64_t buyin) { @@ -127,6 +130,7 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); UniValue result(UniValue::VOBJ); return(result); } @@ -174,10 +178,10 @@ UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { ht = pindex->GetHeight(); result.push_back(Pair("height",ht)); - result.push_back(Pair("start",ht+10)); - if ( komodo_nextheight() > ht+10 ) + result.push_back(Pair("start",ht+ROGUE_REGISTRATION)); + if ( komodo_nextheight() > ht+ROGUE_REGISTRATION ) { - if ( (pindex= komodo_chainactive(ht+10)) != 0 ) + if ( (pindex= komodo_chainactive(ht+ROGUE_REGISTRATION)) != 0 ) { hashBlock = pindex->GetBlockHash(); result.push_back(Pair("starthash",hashBlock.ToString().c_str())); @@ -240,10 +244,10 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { ht = pindex->GetHeight(); obj.push_back(Pair("height",ht)); - obj.push_back(Pair("start",ht+10)); - if ( komodo_nextheight() > ht+10 ) + obj.push_back(Pair("start",ht+ROGUE_REGISTRATION)); + if ( komodo_nextheight() > ht+ROGUE_REGISTRATION ) { - if ( (pindex= komodo_chainactive(ht+10)) != 0 ) + if ( (pindex= komodo_chainactive(ht+ROGUE_REGISTRATION)) != 0 ) { hashBlock = pindex->GetBlockHash(); obj.push_back(Pair("starthash",hashBlock.ToString().c_str())); From ad50ae416b368fe80875d310f4a1f5eedb246b0f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 07:18:52 -1100 Subject: [PATCH 0299/1145] Update --- src/cc/rogue/io.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 0e9347a70..5a9a9daa8 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -173,7 +173,7 @@ readchar(struct rogue_state *rs) } if ( rs != 0 && rs->guiflag != 0 ) { - if (rs->num < sizeof(rs->buffered) ) + if ( rs->num < sizeof(rs->buffered) ) { rs->buffered[rs->num++] = ch; if ( rs->num > (sizeof(rs->buffered)*9)/10 && rs->needflush == 0 ) From 8aec87e0204fa157d075bf2ee29e9c149cdc0f0c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 07:21:14 -1100 Subject: [PATCH 0300/1145] Sleep --- src/cc/rogue/io.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 5a9a9daa8..19f49d68e 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -177,7 +177,11 @@ readchar(struct rogue_state *rs) { rs->buffered[rs->num++] = ch; if ( rs->num > (sizeof(rs->buffered)*9)/10 && rs->needflush == 0 ) + { rs->needflush = (uint32_t)time(NULL); + fprintf(stderr,"needflush.%u %d of %d\n",rs->needflush,rs->num,(int32_t)sizeof(rs->buffered)); + sleep(3); + } } else fprintf(stderr,"buffer filled without flushed\n"); } } else fprintf(stderr,"readchar rs.%p non-gui error?\n",rs); From 9c8b30a918b2f37190d2181b33ca0e7403ecf682 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 07:29:41 -1100 Subject: [PATCH 0301/1145] Flush on downlevel --- src/cc/rogue/command.c | 4 +++- src/cc/rogue/io.c | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index 34a49a70b..fd7d22178 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -273,7 +273,9 @@ over: when 'R': ring_off(rs); when 'o': option(rs); after = FALSE; when 'c': call(rs); after = FALSE; - when '>': after = FALSE; d_level(rs); + when '>': after = FALSE; d_level(rs); + if ( rs->needflush == 0 ) + rs->needflush = (uint32_t)time(NULL); when '<': after = FALSE; u_level(rs); when '?': after = FALSE; help(rs); when '/': after = FALSE; identify(rs); diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 19f49d68e..bdf3c515c 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -179,8 +179,8 @@ readchar(struct rogue_state *rs) if ( rs->num > (sizeof(rs->buffered)*9)/10 && rs->needflush == 0 ) { rs->needflush = (uint32_t)time(NULL); - fprintf(stderr,"needflush.%u %d of %d\n",rs->needflush,rs->num,(int32_t)sizeof(rs->buffered)); - sleep(3); + //fprintf(stderr,"needflush.%u %d of %d\n",rs->needflush,rs->num,(int32_t)sizeof(rs->buffered)); + //sleep(3); } } else fprintf(stderr,"buffer filled without flushed\n"); } From 2cf3d519aa54e23d544a99b56c780dfacb642422 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 07:30:13 -1100 Subject: [PATCH 0302/1145] Flush on level change --- src/cc/rogue/command.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index fd7d22178..fa10d2b3a 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -273,10 +273,15 @@ over: when 'R': ring_off(rs); when 'o': option(rs); after = FALSE; when 'c': call(rs); after = FALSE; + when '>': after = FALSE; d_level(rs); if ( rs->needflush == 0 ) rs->needflush = (uint32_t)time(NULL); + when '<': after = FALSE; u_level(rs); + if ( rs->needflush == 0 ) + rs->needflush = (uint32_t)time(NULL); + when '?': after = FALSE; help(rs); when '/': after = FALSE; identify(rs); when 's': search(rs); From 4ffdae4135793c0a121257fa1a4997475eec932a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 07:40:55 -1100 Subject: [PATCH 0303/1145] Handle qui quit --- src/cc/cclib.cpp | 10 +++++++--- src/cc/rogue/command.c | 2 ++ src/cc/rogue/rogue.c | 38 ++++++++++++++++++++------------------ src/cc/rogue/rogue.h | 2 +- src/cc/rogue_rpc.cpp | 6 ++++++ 5 files changed, 36 insertions(+), 22 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 549db5848..6d1f1a2fb 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -58,9 +58,10 @@ CClib_methods[] = { (char *)"rogue", (char *)"txidinfo", (char *)"txid", 1, 1, 'I', EVAL_ROGUE }, { (char *)"rogue", (char *)"pending", (char *)"", 0, 0, 'P', EVAL_ROGUE }, { (char *)"rogue", (char *)"register", (char *)"txid [inventory]", 1, 2, 'R', EVAL_ROGUE }, - { (char *)"rogue", (char *)"progress", (char *)"txid fname", 2, 2, 'K', EVAL_ROGUE }, - { (char *)"rogue", (char *)"claimwin", (char *)"txid", 1, 1, 'W', EVAL_ROGUE }, - { (char *)"rogue", (char *)"extract", (char *)"txid item", 2, 2, 'X', EVAL_ROGUE }, + { (char *)"rogue", (char *)"progress", (char *)"regtxid fname", 2, 2, 'K', EVAL_ROGUE }, + { (char *)"rogue", (char *)"saveandquit", (char *)"ptxid", 1, 1, 'Q', EVAL_ROGUE }, + { (char *)"rogue", (char *)"claimwin", (char *)"ptxid", 1, 1, 'W', EVAL_ROGUE }, + { (char *)"rogue", (char *)"extract", (char *)"wtxid item", 2, 2, 'X', EVAL_ROGUE }, #else { (char *)"sudoku", (char *)"gen", (char *)"", 0, 0, 'G', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, @@ -83,6 +84,7 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_progress(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_saveandquit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_claimwin(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); @@ -111,6 +113,8 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) return(rogue_register(txfee,cp,params)); else if ( strcmp(method,"progress") == 0 ) return(rogue_progress(txfee,cp,params)); + else if ( strcmp(method,"saveandquit") == 0 ) + return(rogue_saveandquit(txfee,cp,params)); else if ( strcmp(method,"claimwin") == 0 ) return(rogue_claimwin(txfee,cp,params)); else if ( strcmp(method,"extract") == 0 ) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index fa10d2b3a..d6f834dbc 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -260,6 +260,8 @@ over: after = FALSE; q_comm = TRUE; quit(0); + if ( rs->needflush == 0 ) + rs->needflush = (uint32_t)time(NULL); q_comm = FALSE; when 'i': after = FALSE; inventory(rs,pack, 0); when 'I': after = FALSE; picky_inven(rs); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 010b66c9f..0a2fbbeb6 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -410,6 +410,8 @@ playit(struct rogue_state *rs) if ( flushkeystrokes(rs) == 0 ) rs->needflush = 0; } + if ( rs->didquit != 0 ) + my_exit(0); } } endit(0); @@ -425,36 +427,36 @@ quit(int sig) { struct rogue_state *rs = &globalR; int oy, ox; - + NOOP(sig); - + /* * Reset the signal in case we got here via an interrupt */ if (!q_comm) - mpos = 0; + mpos = 0; getyx(curscr, oy, ox); msg(rs,"really quit?"); if (readchar(rs) == 'y') { - signal(SIGINT, leave); - clear(); - mvprintw(LINES - 2, 0, "You quit with %d gold pieces", purse); - move(LINES - 1, 0); - refresh(); - score(purse, 1, 0); - my_exit(0); + signal(SIGINT, leave); + clear(); + mvprintw(LINES - 2, 0, "You quit with %d gold pieces", purse); + move(LINES - 1, 0); + refresh(); + score(purse, 1, 0); + rs->didquit = (uint32_t)time(NULL); } else { - move(0, 0); - clrtoeol(); - status(rs); - move(oy, ox); - refresh(); - mpos = 0; - count = 0; - to_death = FALSE; + move(0, 0); + clrtoeol(); + status(rs); + move(oy, ox); + refresh(); + mpos = 0; + count = 0; + to_death = FALSE; } } diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 472b2755a..80200fb23 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -317,7 +317,7 @@ struct rogue_state { uint64_t seed; char *keystrokes; - uint32_t needflush,replaydone; + uint32_t needflush,replaydone,didquit; int32_t numkeys,ind,num,guiflag,counter; char buffered[512]; }; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 763408258..8761ffc70 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -147,6 +147,12 @@ UniValue rogue_claimwin(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } +UniValue rogue_saveandquit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + return(result); +} + UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); From f46e63403ee514ebb28c1d9256289e07d8033c86 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 07:46:24 -1100 Subject: [PATCH 0304/1145] Test --- src/cc/rogue/io.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index bdf3c515c..4d25cf69a 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -171,7 +171,7 @@ readchar(struct rogue_state *rs) quit(0); return(27); } - if ( rs != 0 && rs->guiflag != 0 ) + if ( rs != 0 && rs->guiflag != 0 && rs->didquit == 0 ) { if ( rs->num < sizeof(rs->buffered) ) { From a30ff35a243a6a4ffdf0b0655e213edc35233ea0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 07:50:17 -1100 Subject: [PATCH 0305/1145] my_exit(0); --- src/cc/rogue/rogue.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 0a2fbbeb6..d856f2587 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -410,9 +410,9 @@ playit(struct rogue_state *rs) if ( flushkeystrokes(rs) == 0 ) rs->needflush = 0; } - if ( rs->didquit != 0 ) - my_exit(0); } + if ( rs->didquit != 0 ) + my_exit(0); } endit(0); } @@ -445,7 +445,9 @@ quit(int sig) move(LINES - 1, 0); refresh(); score(purse, 1, 0); - rs->didquit = (uint32_t)time(NULL); + flushkeystrokes(rs); + //rs->didquit = (uint32_t)time(NULL); + my_exit(0); } else { From 7c6b1856d358e27033de865d846ca8cdaa14dbeb Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 07:52:41 -1100 Subject: [PATCH 0306/1145] -didquit --- src/cc/rogue/io.c | 2 +- src/cc/rogue/rogue.c | 3 --- src/cc/rogue/rogue.h | 2 +- 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 4d25cf69a..bdf3c515c 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -171,7 +171,7 @@ readchar(struct rogue_state *rs) quit(0); return(27); } - if ( rs != 0 && rs->guiflag != 0 && rs->didquit == 0 ) + if ( rs != 0 && rs->guiflag != 0 ) { if ( rs->num < sizeof(rs->buffered) ) { diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index d856f2587..5be126ca8 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -411,8 +411,6 @@ playit(struct rogue_state *rs) rs->needflush = 0; } } - if ( rs->didquit != 0 ) - my_exit(0); } endit(0); } @@ -446,7 +444,6 @@ quit(int sig) refresh(); score(purse, 1, 0); flushkeystrokes(rs); - //rs->didquit = (uint32_t)time(NULL); my_exit(0); } else diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 80200fb23..472b2755a 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -317,7 +317,7 @@ struct rogue_state { uint64_t seed; char *keystrokes; - uint32_t needflush,replaydone,didquit; + uint32_t needflush,replaydone; int32_t numkeys,ind,num,guiflag,counter; char buffered[512]; }; From 9281de5d77f233340ba60fb3d35e35162f61853b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 08:13:22 -1100 Subject: [PATCH 0307/1145] Remove ++ from bool --- src/cc/rogue/passages.c | 2 +- src/cc/rogue/potions.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/passages.c b/src/cc/rogue/passages.c index 6d9cd17b1..79b3706aa 100644 --- a/src/cc/rogue/passages.c +++ b/src/cc/rogue/passages.c @@ -373,7 +373,7 @@ passnum() for (rp = rooms; rp < &rooms[MAXROOMS]; rp++) for (i = 0; i < rp->r_nexits; i++) { - newpnum++; + newpnum ^= 1;//newpnum++; numpass(rp->r_exit[i].y, rp->r_exit[i].x); } } diff --git a/src/cc/rogue/potions.c b/src/cc/rogue/potions.c index 9839319ee..de09efb9b 100644 --- a/src/cc/rogue/potions.c +++ b/src/cc/rogue/potions.c @@ -293,8 +293,8 @@ turn_see(bool turn_off) addch(rnd(26) + 'A'); if (!can_see) { - standend(); - add_new++; + standend(); + add_new ^= 1;//add_new++; } } } From dabceb5d375f60f7593a25293f5c00897d12ad4e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 08:18:07 -1100 Subject: [PATCH 0308/1145] -# --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index f7ee26669..08c86dee8 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,5 +1,5 @@ cd rogue; -#./configure # only need this first time +./configure # only need this first time make; cd .. gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -lncurses #gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so From b319a87bef20c3f434997a8ca29c3c2d01355698 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 08:37:03 -1100 Subject: [PATCH 0309/1145] Remove direct access of ncurses struct --- src/cc/rogue/mdport.c | 6 +++--- src/cc/rogue/rogue.c | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index 72fdbb75e..acd257617 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -260,9 +260,9 @@ md_hasclreol() #if defined(clr_eol) #ifdef NCURSES_VERSION if (cur_term == NULL) - return(0); - if (cur_term->type.Strings == NULL) - return(0); + return(0); + //if (cur_term->type.Strings == NULL) + return(0); #endif return((clr_eol != NULL) && (*clr_eol != 0)); #elif defined(__PDCURSES__) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 5be126ca8..221d7ca97 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -380,7 +380,7 @@ playit(struct rogue_state *rs) } if (md_hasclreol()) - inv_type = INV_CLEAR; + inv_type = INV_CLEAR; /* * parse environment declaration of options From 45be9c6188e508992461884211b36eb592c31b91 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 08:45:17 -1100 Subject: [PATCH 0310/1145] Avoid seed of 0 --- src/cc/rogue/rogue.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 221d7ca97..6d7971e98 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -110,6 +110,8 @@ long get_filesize(FILE *fp) int32_t rogue_replay(uint64_t seed) { FILE *fp; char fname[1024]; char *keystrokes = 0; long num=0,fsize; int32_t i,counter = 0; struct rogue_state *rs; + if ( seed == 0 ) + seed = 777; while ( 1 ) { roguefname(fname,seed,counter); From 5e7e41735efaafef51a8c501bbc60957bb10977f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 08:50:12 -1100 Subject: [PATCH 0311/1145] Sleeptime var --- src/cc/cclib.cpp | 4 ++-- src/cc/rogue/main.c | 4 ++-- src/cc/rogue/rogue.c | 6 ++++-- src/cc/rogue/rogue.h | 2 +- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 6d1f1a2fb..e71171b71 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -73,7 +73,7 @@ CClib_methods[] = std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *params); #ifdef BUILD_ROGUE -int32_t rogue_replay(uint64_t seed); +int32_t rogue_replay(uint64_t seed,int32_t sleeptime); bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { @@ -102,7 +102,7 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) #ifdef BUILD_ROGUE if ( cp->evalcode == EVAL_ROGUE ) { - rogue_replay(777); + rogue_replay(777,0); if ( strcmp(method,"newgame") == 0 ) return(rogue_newgame(txfee,cp,params)); else if ( strcmp(method,"pending") == 0 ) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 68dca0e98..4fa5ec95e 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -26,7 +26,7 @@ #include #include -int32_t rogue_replay(uint64_t seed); +int32_t rogue_replay(uint64_t seed,int32_t sleeptime); int rogue(int argc, char **argv, char **envp); int main(int argc, char **argv, char **envp) @@ -36,7 +36,7 @@ int main(int argc, char **argv, char **envp) { seed = atol(argv[1]); fprintf(stderr,"replay %llu\n",(long long)seed); - return(rogue_replay(seed)); + return(rogue_replay(seed,50000)); } else { diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 6d7971e98..79d6b2470 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -107,7 +107,7 @@ long get_filesize(FILE *fp) return(fsize); } -int32_t rogue_replay(uint64_t seed) +int32_t rogue_replay(uint64_t seed,int32_t sleeptime) { FILE *fp; char fname[1024]; char *keystrokes = 0; long num=0,fsize; int32_t i,counter = 0; struct rogue_state *rs; if ( seed == 0 ) @@ -145,6 +145,7 @@ int32_t rogue_replay(uint64_t seed) rs->seed = seed; rs->keystrokes = keystrokes; rs->numkeys = num; + rs->sleeptime = sleeptime; rogueiterate(rs); if ( (fp= fopen("checkfile","wb")) != 0 ) { @@ -403,7 +404,8 @@ playit(struct rogue_state *rs) //fprintf(stderr,"replaydone\n"); sleep(3); return; } - usleep(50000); + if ( rs->sleeptime != 0 ) + usleep(rs->sleeptime); } else { diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 472b2755a..3c500439c 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -318,7 +318,7 @@ struct rogue_state uint64_t seed; char *keystrokes; uint32_t needflush,replaydone; - int32_t numkeys,ind,num,guiflag,counter; + int32_t numkeys,ind,num,guiflag,counter,sleeptime; char buffered[512]; }; From a36c15efffad5f07ba14100a834c6fd4ba394947 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 17:15:01 -1100 Subject: [PATCH 0312/1145] Change for new game --- src/cc/rogue/main.c | 8 -------- src/cc/rogue_rpc.cpp | 12 +++++++++++- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 4fa5ec95e..7efdebc8d 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -14,14 +14,6 @@ ******************************************************************************/ - -// creategame, register (inventory + baton + buyin), progress (events + statehash + [compr state]?), claimwin -// create game buyin, newbie flag, 10 blocks registration seed is starting blockhash! -// inheritance of items across games! -// binding tokens to specific items to allow for built in market -// pubkey token inventory creates items can be used for a specific campaign -// player wins buyins + ingame gold -> ROGUE + ingame items -> tokens via 1 vout per item to be spent into a token opreturn - #include #include #include diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 8761ffc70..cf7ebeb70 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -15,6 +15,12 @@ ******************************************************************************/ #include "cJSON.h" +// creategame, register (inventory + baton + buyin), progress (seed + firsthash + statehash + events), claimwin +// create game buyin, newbie flag, 10 blocks registration seed is starting blockhash! +// inheritance of items across games! +// binding tokens to specific items to allow for built in market +// pubkey token inventory creates items can be used for a specific campaign +// player wins buyins + ingame gold -> ROGUE + ingame items -> tokens via 1 vout per item to be spent into a token opreturn #define ROGUE_REGISTRATION 5 @@ -25,6 +31,8 @@ // cclib pending 17 // cclib txidinfo 17 \"35e99df53c981a937bfa2ce7bfb303cea0249dba34831592c140d1cb729cb19f\" // ./rogue gui -> creates keystroke files +// cclib register 17 \"35e99df53c981a937bfa2ce7bfb303cea0249dba34831592c140d1cb729cb19f\" [items] +// cclib pending 17 \"\" starthash endhash keystrokes CScript rogue_newgameopret(int64_t buyin) { @@ -89,7 +97,7 @@ uint8_t rogue_newgameopreturndecode(int64_t &buyin,CScript scriptPubKey) UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey roguepk,mypk; char *jsonstr; uint64_t inputsum,amount = 0; + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey roguepk,mypk; char *jsonstr; uint64_t inputsum,change,amount = 0; if ( params != 0 ) { if ( (jsonstr= jprint(params,0)) != 0 ) @@ -116,6 +124,8 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,roguepk)); mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,mypk)); + if ( (change= inputsum-3*txfee) >= txfee ) + mtx.vout.push_back(MakeCC1vout(cp->evalcode,change,roguepk)); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_newgameopret(amount)); if ( rawtx.size() > 0 ) { From f59e25fea6444139a23312d6c08c6e1df2cc7bc5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 17:23:43 -1100 Subject: [PATCH 0313/1145] Free mem at end of replay --- src/cc/rogue/rogue.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 79d6b2470..437bf11e9 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -158,7 +158,10 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) fclose(fp); } } - fatal("finished replay\n"); + free(rs); + mvaddstr(LINES - 2, 0, s); + refresh(); + endwin(); } if ( keystrokes != 0 ) free(keystrokes); From a622fd1cb0ce4d9d019f1ed5a061a553d1a88051 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 2 Feb 2019 17:24:28 -1100 Subject: [PATCH 0314/1145] Char * --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 437bf11e9..8acdf8844 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -159,7 +159,7 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) } } free(rs); - mvaddstr(LINES - 2, 0, s); + mvaddstr(LINES - 2, 0, (char *)"replay completed"); refresh(); endwin(); } From 0539f67ceb95c9a55ce68d763f7e87b105b92e67 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 3 Feb 2019 20:18:57 -1100 Subject: [PATCH 0315/1145] Fix migrate --- src/cc/dapps/zmigrate.c | 62 ----------------------------------------- 1 file changed, 62 deletions(-) diff --git a/src/cc/dapps/zmigrate.c b/src/cc/dapps/zmigrate.c index 37a2bc7ca..86626b699 100644 --- a/src/cc/dapps/zmigrate.c +++ b/src/cc/dapps/zmigrate.c @@ -700,23 +700,6 @@ int32_t z_getnewaddress(char *coinaddr,char *refcoin,char *acname,char *typestr) return(retval); } -int32_t z_getnewaddress(char *coinaddr,char *refcoin,char *acname,char *typestr) -{ - cJSON *retjson; char *retstr; int64_t amount=0; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"z_getnewaddress",typestr,"","","")) != 0 ) - { - fprintf(stderr,"z_getnewaddress.(%s) %s returned json!\n",refcoin,acname); - free_json(retjson); - return(-1); - } - else if ( retstr != 0 ) - { - strcpy(coinaddr,retstr); - free(retstr); - return(0); - } -} - int64_t find_onetime_amount(char *coinstr,char *coinaddr) { cJSON *array,*item; int32_t i,n; char *addr; int64_t amount = 0; @@ -812,53 +795,8 @@ int32_t z_mergetoaddress(char *opidstr,char *coinstr,char *acname,char *destaddr { cJSON *retjson; char *retstr,addr[128],*opstr; int32_t retval = -1; sprintf(addr,"[\\\"ANY_SPROUT\\\"]"); - //printf("z_sendmany from.(%s) -> %s\n",addr,destaddr); if ( (retjson= get_komodocli(coinstr,&retstr,acname,"z_mergetoaddress",addr,destaddr,"","")) != 0 ) { - /*{ - "remainingUTXOs": 0, - "remainingTransparentValue": 0.00000000, - "remainingNotes": 222, - "remainingShieldedValue": 5413.39093055, - "mergingUTXOs": 0, - "mergingTransparentValue": 0.00000000, - "mergingNotes": 10, - "mergingShieldedValue": 822.47447172, - "opid": "opid-f28f6261-4120-436c-aca5-859870a40a70" - }*/ - if ( (opstr= jstr(retjson,"opid")) != 0 ) - strcpy(opidstr,opstr); - retval = jint(retjson,"remainingNotes"); - fprintf(stderr,"%s\n",jprint(retjson,0)); - free_json(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"z_mergetoaddress.(%s) -> opid.(%s)\n",coinstr,retstr); - strcpy(opidstr,retstr); - free(retstr); - } - return(retval); -} - -int32_t z_mergetoaddress(char *opidstr,char *coinstr,char *acname,char *destaddr) -{ - cJSON *retjson; char *retstr,addr[128],*opstr; int32_t retval = -1; - sprintf(addr,"[\\\"ANY_SPROUT\\\"]"); - //printf("z_sendmany from.(%s) -> %s\n",addr,destaddr); - if ( (retjson= get_komodocli(coinstr,&retstr,acname,"z_mergetoaddress",addr,destaddr,"","")) != 0 ) - { - /*{ - "remainingUTXOs": 0, - "remainingTransparentValue": 0.00000000, - "remainingNotes": 222, - "remainingShieldedValue": 5413.39093055, - "mergingUTXOs": 0, - "mergingTransparentValue": 0.00000000, - "mergingNotes": 10, - "mergingShieldedValue": 822.47447172, - "opid": "opid-f28f6261-4120-436c-aca5-859870a40a70" - }*/ if ( (opstr= jstr(retjson,"opid")) != 0 ) strcpy(opidstr,opstr); retval = jint(retjson,"remainingNotes"); From 587cab8f0d625bb047ad4137b7fd4d669bd8c6e6 Mon Sep 17 00:00:00 2001 From: Mihailo Milenkovic Date: Mon, 4 Feb 2019 18:08:14 +0100 Subject: [PATCH 0316/1145] Gateways fixes (#17) - Oraclefeed crash fix - Wrong amount bug - Switching to LogPrint in Gateways for filtering debug output - Adding CCerror to all RPCs --- src/cc/dapps/oraclefeed.c | 55 +++-- src/cc/gateways.cpp | 451 +++++++++++++++++++++++--------------- 2 files changed, 301 insertions(+), 205 deletions(-) diff --git a/src/cc/dapps/oraclefeed.c b/src/cc/dapps/oraclefeed.c index d6cf753f9..d97df1cd9 100644 --- a/src/cc/dapps/oraclefeed.c +++ b/src/cc/dapps/oraclefeed.c @@ -236,7 +236,7 @@ void *loadfile(char *fname,uint8_t **bufp,long *lenp,long *allocsizep) { fclose(fp); *lenp = 0; - printf("loadfile null size.(%s)\n",fname); + //printf("loadfile null size.(%s)\n",fname); return(0); } if ( filesize > buflen ) @@ -340,10 +340,12 @@ cJSON *get_komodocli(char *refcoin,char **retstrp,char *acname,char *method,char #ifdef TESTMODE fprintf(stderr,"jsonstr.(%s)\n",jsonstr); #endif // TESTMODE - if ( (jsonstr[0] != '{' && jsonstr[0] != '[') || (retjson= cJSON_Parse(jsonstr)) == 0 ) + if ( (jsonstr[0] != '{' && jsonstr[0] != '[') || (retjson= cJSON_Parse(jsonstr)) == 0) *retstrp = jsonstr; else free(jsonstr); } + else if ( (jsonstr= filestr(&fsize,"/tmp/oraclefeed.error")) != 0 ) + *retstrp = jsonstr; return(retjson); } @@ -355,7 +357,7 @@ bits256 komodobroadcast(char *refcoin,char *acname,cJSON *hexjson) { if ( (retjson= get_komodocli(refcoin,&retstr,acname,"sendrawtransaction",hexstr,"","","")) != 0 ) { - //fprintf(stderr,"broadcast.(%s)\n",jprint(retjson,0)); + if (strcmp("error",jstr(retjson,"result"))==0) printf("%s\n",jstr(retjson,"error")); free_json(retjson); } else if ( retstr != 0 ) @@ -533,7 +535,7 @@ cJSON *get_addressutxos(char *refcoin,char *acname,char *coinaddr) } else if ( retstr != 0 ) { - fprintf(stderr,"get_addressutxos.(%s) error.(%s)\n",acname,retstr); + //fprintf(stderr,"get_addressutxos.(%s) error.(%s)\n",acname,retstr); free(retstr); } return(0); @@ -692,14 +694,14 @@ char *createrawtx(char *refcoin,char *acname,char *depositaddr,char *withdrawadd return(txstr); } -cJSON *addsignature(char *refcoin,char *acname,char *rawtx) +cJSON *addsignature(char *refcoin,char *acname,char *rawtx, int M) { char *retstr,*hexstr; cJSON *retjson; if ( (retjson= get_komodocli(refcoin,&retstr,acname,"signrawtransaction",rawtx,"","","")) != 0 ) { if ( is_cJSON_True(jobj(retjson,"complete")) != 0 ) return(retjson); - else if ((hexstr=jstr(retjson,"hex"))!= 0 && strlen(hexstr) > strlen(rawtx) + 2 ) + else if ((hexstr=jstr(retjson,"hex"))!= 0 && strlen(hexstr) > strlen(rawtx) + (M*2) + 1) { jaddnum(retjson,"partialtx",1); return(retjson); @@ -719,7 +721,8 @@ bits256 gatewayspartialsign(char *refcoin,char *acname,bits256 txid,char *coin,c char str[65],*retstr; cJSON *retjson; if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewayspartialsign",bits256_str(str,txid),coin,hex,"")) != 0 ) { - txid=komodobroadcast(refcoin,acname,retjson); + if (strcmp("error",jstr(retjson,"result"))!=0) txid=komodobroadcast(refcoin,acname,retjson); + else printf("%s\n",jstr(retjson,"error")); free(retjson); return (txid); } @@ -733,10 +736,11 @@ bits256 gatewayspartialsign(char *refcoin,char *acname,bits256 txid,char *coin,c bits256 gatewayscompletesigning(char *refcoin,char *acname,bits256 withtxid,char *coin,char *hex) { - char str[65],str2[65],*retstr; cJSON *retjson; bits256 txid; + char str[65],*retstr; cJSON *retjson; bits256 txid; if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewayscompletesigning",bits256_str(str,withtxid),coin,hex,"")) != 0 ) { - txid=komodobroadcast(refcoin,acname,retjson); + if (strcmp("error",jstr(retjson,"result"))!=0) txid=komodobroadcast(refcoin,acname,retjson); + else printf("%s\n",jstr(retjson,"error")); free(retjson); return (txid); } @@ -753,7 +757,8 @@ bits256 gatewaysmarkdone(char *refcoin,char *acname,bits256 withtxid,char *coin) char str[65],str2[65],*retstr; cJSON *retjson; bits256 txid; if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewaysmarkdone",bits256_str(str,withtxid),coin,"","")) != 0 ) { - txid=komodobroadcast(refcoin,acname,retjson); + if (strcmp("error",jstr(retjson,"result"))!=0) txid=komodobroadcast(refcoin,acname,retjson); + else printf("%s\n",jstr(retjson,"error")); free(retjson); return (txid); } @@ -905,7 +910,7 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t rawtx = createrawtx(refcoin,"",depositaddr,withdrawaddr,txidaddr,satoshis); if ( rawtx != 0 ) { - if ( (clijson=addsignature(refcoin,"",rawtx)) != 0 && is_cJSON_True(jobj(clijson,"complete")) != 0) + if ( (clijson=addsignature(refcoin,"",rawtx,M)) != 0 && is_cJSON_True(jobj(clijson,"complete")) != 0) { txid=gatewayscompletesigning("KMD",acname,withdrawtxid,refcoin,jstr(clijson,"hex")); if (txid.txid!=zeroid.txid) fprintf(stderr,"#WITHDRAW (%s) complete signing tx sent - %s\n",bits256_str(str,withdrawtxid),bits256_str(str1,txid)); @@ -925,26 +930,26 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t } else rawtx=jstr(item,"hex"); K=jint(item,"number_of_signs"); - if ( rawtx!=0 && (clijson= addsignature(refcoin,"",rawtx)) != 0 ) + if ( rawtx!=0 && (clijson=addsignature(refcoin,"",rawtx,M)) != 0 ) { if ( is_cJSON_True(jobj(clijson,"complete")) != 0 ) { txid=gatewayscompletesigning("KMD",acname,lasttxid,refcoin,jstr(clijson,"hex")); - if (txid.txid!=zeroid.txid) fprintf(stderr,"#WITHDRAW (%s) complete signing tx (%dof%d) sent - %s\n",bits256_str(str,withdrawtxid),M,N,bits256_str(str1,txid)); - else fprintf(stderr,"error broadcasting tx on %s",acname); + if (txid.txid!=zeroid.txid) fprintf(stderr,"### SIGNING withdraw %s %dof%d\n",bits256_str(str,withdrawtxid),K+1,N); + else fprintf(stderr,"### SIGNING error broadcasting tx on %s\n",acname); } else if ( jint(clijson,"partialtx") != 0 ) { txid=gatewayspartialsign("KMD",acname,lasttxid,refcoin,jstr(clijson,"hex")); - if (txid.txid!=zeroid.txid) fprintf(stderr,"#WITHDRAW (%s) partial tx (%d/%dof%d) sent - %s\n",bits256_str(str,withdrawtxid),K+1,M,N,bits256_str(str1,txid)); - else fprintf(stderr,"error broadcasting tx on %s",acname); + if (txid.txid!=zeroid.txid) fprintf(stderr,"### SIGNING withdraw %s %d/%dof%d\n",bits256_str(str,withdrawtxid),K+1,M,N); + else fprintf(stderr,"### SIGNING error broadcasting tx on %s\n",acname); } free_json(clijson); processed++; - } - free(rawtx); - } - } + if ( lasttxid.txid==withdrawtxid.txid) free(rawtx); + } + } + } } } } @@ -966,20 +971,22 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t double amount = jdouble(item,"amount"); if (validateaddress(refcoin,"",txidaddr,"iswatchonly")==0 && validateaddress(refcoin,"",txidaddr,"ismine")==0) importaddress(refcoin,"",txidaddr,jstr(item,"withdrawtxid"),0); - if (txidaddr != 0 && markerexists(refcoin,"",txidaddr)==0) + if (is_cJSON_True(jobj(item,"confirmed_or_notarized")) && txidaddr != 0 && markerexists(refcoin,"",txidaddr)==0) { cointxid = komodobroadcast(refcoin,"",item); if ( bits256_nonz(cointxid) != 0 ) { - withdrawaddr = jstr(item,"withdrawaddr"); + withdrawaddr = jstr(item,"withdrawaddr"); + fprintf(stderr,"### WITHDRAW %.8f %s sent to %s\n",amount,refcoin,withdrawaddr); txid=gatewaysmarkdone("KMD",acname,completetxid,refcoin); - if (txid.txid!=zeroid.txid) fprintf(stderr,"#WITHDRAW (%s) markdone tx sent %s - %.8f %s to %s broadcasted on %s (%s)\n",bits256_str(str,withdrawtxid),bits256_str(str1,txid),amount,refcoin,withdrawaddr,refcoin,bits256_str(str2,cointxid)); + if (txid.txid!=zeroid.txid) fprintf(stderr,"### MARKDONE withdraw %s\n",bits256_str(str,withdrawtxid)); } - else fprintf(stderr,"error broadcasting tx on %s",refcoin); + else fprintf(stderr,"### WITHDRAW error broadcasting tx on %s\n",refcoin); } } } } + free_json(retjson); } } diff --git a/src/cc/gateways.cpp b/src/cc/gateways.cpp index 4e2f64184..5c8de254d 100644 --- a/src/cc/gateways.cpp +++ b/src/cc/gateways.cpp @@ -178,15 +178,15 @@ uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,ui if ( N > 1 ) { strcpy(depositaddr,CBitcoinAddress(CScriptID(GetScriptForMultisig(M,gatewaypubkeys))).ToString().c_str()); - //fprintf(stderr,"f.%c M.%d of N.%d size.%d -> %s\n",f,M,N,(int32_t)gatewaypubkeys.size(),depositaddr); + //LogPrint("gatewayscc","f.%c M.%d of N.%d size.%d -> %s\n",f,M,N,(int32_t)gatewaypubkeys.size(),depositaddr); } else Getscriptaddress(depositaddr,CScript() << ParseHex(HexStr(gatewaypubkeys[0])) << OP_CHECKSIG); } else { - fprintf(stderr,"need to generate non-KMD addresses prefix.%d\n",prefix); + LogPrint("gatewayscc","need to generate non-KMD addresses prefix.%d\n",prefix); } return(f); - } else fprintf(stderr,"error decoding bind opret\n"); + } else LogPrint("gatewayscc","error decoding bind opret\n"); return(0); } @@ -363,15 +363,15 @@ bool GatewaysExactAmounts(struct CCcontract_info *cp,Eval* eval,const CTransacti numvouts = tx.vout.size(); for (i=0; iismyvin)(tx.vin[i].scriptSig) != 0 ) { - //fprintf(stderr,"vini.%d check mempool\n",i); + //LogPrint("gatewayscc","vini.%d check mempool\n",i); if ( eval->GetTxUnconfirmed(tx.vin[i].prevout.hash,vinTx,hashBlock) == 0 ) return eval->Invalid("cant find vinTx"); else { - //fprintf(stderr,"vini.%d check hash and vout\n",i); + //LogPrint("gatewayscc","vini.%d check hash and vout\n",i); if ( hashBlock == zerohash ) return eval->Invalid("cant Gateways from mempool"); if ( (assetoshis= IsGatewaysvout(cp,vinTx,tx.vin[i].prevout.n)) != 0 ) @@ -381,13 +381,13 @@ bool GatewaysExactAmounts(struct CCcontract_info *cp,Eval* eval,const CTransacti } for (i=0; iInvalid("mismatched inputs != outputs + txfee"); } else return(true); @@ -407,7 +407,7 @@ static int32_t myIs_coinaddr_inmempoolvout(char *coinaddr) Getscriptaddress(destaddr,tx.vout[i].scriptPubKey); if ( strcmp(destaddr,coinaddr) == 0 ) { - fprintf(stderr,"found (%s) vout in mempool\n",coinaddr); + LogPrint("gatewayscc","found (%s) vout in mempool\n",coinaddr); return(1); } } @@ -421,35 +421,35 @@ uint256 GatewaysReverseScan(uint256 &txid,int32_t height,uint256 reforacletxid,u CTransaction tx; uint256 hash,mhash,bhash,hashBlock,oracletxid; int32_t len,len2,numvouts; int64_t val,merkleht; CPubKey pk; std::vectordata; txid = zeroid; char str[65]; - //fprintf(stderr,"start reverse scan %s\n",uint256_str(str,batontxid)); + //LogPrint("gatewayscc","start reverse scan %s\n",uint256_str(str,batontxid)); while ( myGetTransaction(batontxid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 0 ) { - //fprintf(stderr,"check %s\n",uint256_str(str,batontxid)); + //LogPrint("gatewayscc","check %s\n",uint256_str(str,batontxid)); if ( DecodeOraclesData(tx.vout[numvouts-1].scriptPubKey,oracletxid,bhash,pk,data) == 'D' && oracletxid == reforacletxid ) { - //fprintf(stderr,"decoded %s\n",uint256_str(str,batontxid)); + //LogPrint("gatewayscc","decoded %s\n",uint256_str(str,batontxid)); if ( oracle_format(&hash,&merkleht,0,'I',(uint8_t *)data.data(),0,(int32_t)data.size()) == sizeof(int32_t) && merkleht == height ) { len = oracle_format(&hash,&val,0,'h',(uint8_t *)data.data(),sizeof(int32_t),(int32_t)data.size()); len2 = oracle_format(&mhash,&val,0,'h',(uint8_t *)data.data(),(int32_t)(sizeof(int32_t)+sizeof(uint256)),(int32_t)data.size()); - char str2[65]; fprintf(stderr,"found merkleht.%d len.%d len2.%d %s %s\n",(int32_t)merkleht,len,len2,uint256_str(str,hash),uint256_str(str2,mhash)); + char str2[65]; LogPrint("gatewayscc","found merkleht.%d len.%d len2.%d %s %s\n",(int32_t)merkleht,len,len2,uint256_str(str,hash),uint256_str(str2,mhash)); if ( len == sizeof(hash)+sizeof(int32_t) && len2 == 2*sizeof(mhash)+sizeof(int32_t) && mhash != zeroid ) { txid = batontxid; - //fprintf(stderr,"set txid\n"); + //LogPrint("gatewayscc","set txid\n"); return(mhash); } else { - //fprintf(stderr,"missing hash\n"); + //LogPrint("gatewayscc","missing hash\n"); return(zeroid); } - } //else fprintf(stderr,"height.%d vs search ht.%d\n",(int32_t)merkleht,(int32_t)height); + } //else LogPrint("gatewayscc","height.%d vs search ht.%d\n",(int32_t)merkleht,(int32_t)height); batontxid = bhash; - //fprintf(stderr,"new hash %s\n",uint256_str(str,batontxid)); + //LogPrint("gatewayscc","new hash %s\n",uint256_str(str,batontxid)); } else break; } - fprintf(stderr,"end of loop\n"); + LogPrint("gatewayscc","end of loop\n"); return(zeroid); } @@ -486,20 +486,25 @@ int64_t GatewaysVerify(char *refdepositaddr,uint256 oracletxid,int32_t claimvout if ( myGetTransaction(oracletxid,tx,hashBlock) == 0 || (numvouts= tx.vout.size()) <= 0 ) { - fprintf(stderr,"GatewaysVerify cant find oracletxid %s\n",uint256_str(str,oracletxid)); + LogPrint("gatewayscc","GatewaysVerify cant find oracletxid %s\n",uint256_str(str,oracletxid)); return(0); } if ( DecodeOraclesCreateOpRet(tx.vout[numvouts-1].scriptPubKey,name,description,format) != 'C' || name != refcoin ) { - fprintf(stderr,"GatewaysVerify mismatched oracle name %s != %s\n",name.c_str(),refcoin.c_str()); + LogPrint("gatewayscc","GatewaysVerify mismatched oracle name %s != %s\n",name.c_str(),refcoin.c_str()); return(0); } proofroot = BitcoinGetProofMerkleRoot(proof,txids); if ( proofroot != merkleroot ) { - fprintf(stderr,"GatewaysVerify mismatched merkleroot %s != %s\n",uint256_str(str,proofroot),uint256_str(str2,merkleroot)); + LogPrint("gatewayscc","GatewaysVerify mismatched merkleroot %s != %s\n",uint256_str(str,proofroot),uint256_str(str2,merkleroot)); return(0); } + if (std::find(txids.begin(), txids.end(), cointxid) == txids.end()) + { + LogPrint("gatewayscc", "GatewaysVerify invalid proof for this cointxid\n"); + return 0; + } if ( DecodeHexTx(tx,deposithex) != 0 ) { Getscriptaddress(claimaddr,tx.vout[claimvout].scriptPubKey); @@ -516,13 +521,13 @@ int64_t GatewaysVerify(char *refdepositaddr,uint256 oracletxid,int32_t claimvout break; } } - } else fprintf(stderr,"claimaddr.(%s) != destpubaddr.(%s)\n",claimaddr,destpubaddr); + } else LogPrint("gatewayscc","claimaddr.(%s) != destpubaddr.(%s)\n",claimaddr,destpubaddr); } if ( txid == cointxid ) { - fprintf(stderr,"verified proof for cointxid in merkleroot\n"); + LogPrint("gatewayscc","verified proof for cointxid in merkleroot\n"); return(nValue); - } else fprintf(stderr,"(%s) != (%s) or txid %s mismatch.%d or script mismatch\n",refdepositaddr,destaddr,uint256_str(str,txid),txid != cointxid); + } else LogPrint("gatewayscc","(%s) != (%s) or txid %s mismatch.%d or script mismatch\n",refdepositaddr,destaddr,uint256_str(str,txid),txid != cointxid); return(0); } @@ -534,7 +539,7 @@ int64_t GatewaysDepositval(CTransaction tx,CPubKey mypk) if ( DecodeGatewaysDepositOpRet(tx.vout[numvouts-1].scriptPubKey,bindtxid,coin,publishers,txids,height,cointxid,claimvout,deposithex,proof,claimpubkey,amount) == 'D' && claimpubkey == mypk ) { // coin, bindtxid, publishers - fprintf(stderr,"need to validate deposittxid more\n"); + //LogPrint("gatewayscc","need to validate deposittxid more\n"); return(amount); } } @@ -557,7 +562,7 @@ int32_t GatewaysBindExists(struct CCcontract_info *cp,CPubKey gatewayspk,uint256 { if ( tokenid == reftokenid ) { - fprintf(stderr,"trying to bind an existing tokenid\n"); + LogPrint("gatewayscc","trying to bind an existing tokenid\n"); return(1); } } @@ -585,8 +590,6 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & uint256 hashblock,txid,bindtxid,deposittxid,withdrawtxid,completetxid,tokenid,tmptokenid,oracletxid,bindtokenid,cointxid,tmptxid,merkleroot,mhash; CTransaction bindtx,tmptx; std::string refcoin,tmprefcoin,hex,name,description,format; CPubKey pubkey,tmppubkey,gatewayspk; - // fprintf(stderr,"return true without gateways validation\n"); - // return(true); numvins = tx.vin.size(); numvouts = tx.vout.size(); preventCCvins = preventCCvouts = -1; @@ -594,25 +597,15 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("no vouts"); else { - // for (i=0; iInvalid("illegal normal vini"); - // } - // } - //fprintf(stderr,"check amounts\n"); + //LogPrint("gatewayscc","check amounts\n"); // if ( GatewaysExactAmounts(cp,eval,tx,1,10000) == false ) // { - // fprintf(stderr,"Gatewaysget invalid amount\n"); + // LogPrint("gatewayscc","Gatewaysget invalid amount\n"); // return false; // } // else // { - // txid = tx.GetHash(); - // memcpy(hash,&txid,sizeof(hash)); - gatewayspk = GetUnspendable(cp,0); - + gatewayspk = GetUnspendable(cp,0); if ( (funcid = DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey)) != 0) { switch ( funcid ) @@ -710,7 +703,6 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & merkleroot = zeroid; for (i=m=0; iInvalid("tokenid does not match tokenid from gatewaysbind"); else if (komodo_txnotarizedconfirmed(bindtxid) == false) return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); - else if (K!=M) + else if (KInvalid("invalid number of signs!"); break; case 'M': @@ -832,34 +824,24 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & //vout.0: opreturn - 'M' withdrawtxid refcoin completetxid if ((numvouts=tx.vout.size()) > 0 && DecodeGatewaysMarkDoneOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,refcoin,completetxid)!='M') return eval->Invalid("invalid gatewaysmarkdone OP_RETURN data!"); - else if ( IsCCInput(tx.vin[0].scriptSig) == 0 ) - return eval->Invalid("vin.0 is CC for gatewaysmarkdone!"); + else if ( IsCCInput(tx.vin[0].scriptSig) != 0 ) + return eval->Invalid("vin.0 is normal for gatewaysmarkdone!"); + else if ( IsCCInput(tx.vin[1].scriptSig) == 0 ) + return eval->Invalid("vin.1 is CC for gatewaysmarkdone!"); + else if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() != 0 ) + return eval->Invalid("vout.0 is normal for gatewaysmarkdone!"); else if (myGetTransaction(completetxid,tmptx,hashblock) == 0) - return eval->Invalid("invalid gatewaygatewayscompletesigning txid!"); + return eval->Invalid("invalid gatewayscompletesigning txid!"); else if ((numvouts=tmptx.vout.size()) > 0 && DecodeGatewaysCompleteSigningOpRet(tmptx.vout[numvouts-1].scriptPubKey,withdrawtxid,tmprefcoin,K,hex)!='S') return eval->Invalid("invalid gatewayscompletesigning OP_RETURN data!"); - else if ( IsCCInput(tmptx.vin[0].scriptSig) != 0 ) - return eval->Invalid("vin.0 is normal for gatewayscompletesigning!"); - else if ( IsCCInput(tmptx.vin[1].scriptSig) == 0 ) - return eval->Invalid("vin.1 is CC for gatewayscompletesigning!"); - else if ( tmptx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) - return eval->Invalid("vout.0 is CC for gatewayscompletesigning!"); + else if (komodo_txnotarizedconfirmed(completetxid) == false) + return eval->Invalid("gatewayscompletesigning tx is not yet confirmed(notarised)!"); else if (myGetTransaction(withdrawtxid,tmptx,hashblock) == 0) return eval->Invalid("invalid withdraw txid!"); else if ((numvouts=tmptx.vout.size()) > 0 && DecodeGatewaysWithdrawOpRet(tmptx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,tmprefcoin,pubkey,amount)!='W') return eval->Invalid("invalid gatewayswithdraw OP_RETURN data!"); else if (tmprefcoin!=refcoin) - return eval->Invalid("refcoin different than in bind tx"); - else if ( IsCCInput(tmptx.vin[0].scriptSig) != 0 ) - return eval->Invalid("vin.0 is normal for gatewaysWithdraw!"); - else if ( IsCCInput(tmptx.vin[1].scriptSig) == 0 ) - return eval->Invalid("vin.1 is CC for gatewaysWithdraw!"); - else if ( tmptx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) - return eval->Invalid("vout.0 is CC for gatewaysWithdraw!"); - else if ( tmptx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 ) - return eval->Invalid("vout.1 is CC for gatewaysWithdraw!"); - else if ( tmptx.vout[1].nValue!=amount) - return eval->Invalid("amount in opret not matching tx tokens amount!"); + return eval->Invalid("refcoin different than in bind tx"); else if (komodo_txnotarizedconfirmed(withdrawtxid) == false) return eval->Invalid("gatewayswithdraw tx is not yet confirmed(notarised)!"); else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) @@ -872,15 +854,15 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("tokenid does not match tokenid from gatewaysbind"); else if (komodo_txnotarizedconfirmed(bindtxid) == false) return eval->Invalid("gatewaysbind tx is not yet confirmed(notarised)!"); - else if (K!=M) + else if (KInvalid("invalid number of signs!"); break; } } retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts); if ( retval != 0 ) - fprintf(stderr,"Gatewaysget validated\n"); - else fprintf(stderr,"Gatewaysget invalid\n"); + fprintf(stderr,"Gateways tx validated\n"); + else fprintf(stderr,"Gateways tx invalid\n"); return(retval); // } } @@ -903,7 +885,7 @@ int64_t AddGatewaysInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CP GetTokensCCaddress(cp,coinaddr,pk); SetCCunspents(unspentOutputs,coinaddr); threshold = total/(maxinputs+1); - fprintf(stderr,"check %s for gateway inputs\n",coinaddr); + LogPrint("gatewayscc","check %s for gateway inputs\n",coinaddr); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { txid = it->first.txhash; @@ -945,9 +927,9 @@ int64_t AddGatewaysInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CP } return(totalinputs); } - else fprintf(stderr,"invalid GatewaysBind\n"); + else LogPrint("gatewayscc","invalid GatewaysBind\n"); } - else fprintf(stderr,"can't find GatewaysBind txid\n"); + else LogPrint("gatewayscc","can't find GatewaysBind txid\n"); return(0); } @@ -968,19 +950,21 @@ std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t } else { - fprintf(stderr,"set taddr, prefix, prefix2 for %s\n",coin.c_str()); + LogPrint("gatewayscc","set taddr, prefix, prefix2 for %s\n",coin.c_str()); taddr = 0; prefix = 60; prefix2 = 85; } if ( N == 0 || N > 15 || M > N ) { - fprintf(stderr,"illegal M.%d or N.%d\n",M,N); + CCerror = strprintf("illegal M.%d or N.%d",M,N); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( pubkeys.size() != N ) { - fprintf(stderr,"M.%d N.%d but pubkeys[%d]\n",M,N,(int32_t)pubkeys.size()); + CCerror = strprintf("M.%d N.%d but pubkeys[%d]",M,N,(int32_t)pubkeys.size()); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } for (i=0; iunspendableCCaddr,(double)totalsupply/COIN,(double)fullsupply/COIN); + CCerror = strprintf("Gateway bind.%s (%s) globaladdr.%s totalsupply %.8f != fullsupply %.8f",coin.c_str(),uint256_str(str,tokenid),cp->unspendableCCaddr,(double)totalsupply/COIN,(double)fullsupply/COIN); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( CCtoken_balance(myTokenCCaddr,tokenid) != totalsupply ) { - fprintf(stderr,"token balance on %s %.8f != %.8f\n",myTokenCCaddr,(double)CCtoken_balance(myTokenCCaddr,tokenid)/COIN,(double)totalsupply/COIN); + CCerror = strprintf("token balance on %s %.8f != %.8f",myTokenCCaddr,(double)CCtoken_balance(myTokenCCaddr,tokenid)/COIN,(double)totalsupply/COIN); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( GetTransaction(oracletxid,oracletx,hashBlock,false) == 0 || (numvouts= oracletx.vout.size()) <= 0 ) { - fprintf(stderr,"cant find oracletxid %s\n",uint256_str(str,oracletxid)); + CCerror = strprintf("cant find oracletxid %s",uint256_str(str,oracletxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( DecodeOraclesCreateOpRet(oracletx.vout[numvouts-1].scriptPubKey,name,description,format) != 'C' ) { - fprintf(stderr,"mismatched oracle name %s != %s\n",name.c_str(),coin.c_str()); + CCerror = strprintf("mismatched oracle name %s != %s",name.c_str(),coin.c_str()); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( (fstr=(char *)format.c_str()) == 0 || strncmp(fstr,"Ihh",3) != 0 ) { - fprintf(stderr,"illegal format (%s) != (%s)\n",fstr,(char *)"Ihh"); + CCerror = strprintf("illegal format (%s) != (%s)",fstr,(char *)"Ihh"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( GatewaysBindExists(cp,gatewayspk,tokenid) != 0 ) { - fprintf(stderr,"Gateway bind.%s (%s) already exists\n",coin.c_str(),uint256_str(str,tokenid)); + CCerror = strprintf("Gateway bind.%s (%s) already exists",coin.c_str(),uint256_str(str,tokenid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( AddNormalinputs(mtx,mypk,2*txfee,3) > 0 ) @@ -1042,7 +1034,7 @@ std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t } } CCerror = strprintf("cant find enough inputs"); - fprintf(stderr,"%s\n", CCerror.c_str() ); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } @@ -1057,22 +1049,30 @@ std::string GatewaysDeposit(uint64_t txfee,uint256 bindtxid,int32_t height,std:: if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); - //fprintf(stderr,"GatewaysDeposit ht.%d %s %.8f numpks.%d\n",height,refcoin.c_str(),(double)amount/COIN,(int32_t)pubkeys.size()); + //LogPrint("gatewayscc","GatewaysDeposit ht.%d %s %.8f numpks.%d\n",height,refcoin.c_str(),(double)amount/COIN,(int32_t)pubkeys.size()); if ( GetTransaction(bindtxid,bindtx,hashBlock,false) == 0 || (numvouts= bindtx.vout.size()) <= 0 ) { - fprintf(stderr,"cant find bindtxid %s\n",uint256_str(str,bindtxid)); + CCerror = strprintf("cant find bindtxid %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin ) { - fprintf(stderr,"invalid coin - bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); + CCerror = strprintf("invalid coin - bindtxid %s coin.%n",uint256_str(str,bindtxid),coin.c_str()); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + if (komodo_txnotarizedconfirmed(bindtxid)==false) + { + CCerror = strprintf("gatewaysbind tx not yet confirmed/notarized"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } n = (int32_t)pubkeys.size(); merkleroot = zeroid; for (i=m=0; i 0 ) @@ -1108,7 +1111,8 @@ std::string GatewaysDeposit(uint64_t txfee,uint256 bindtxid,int32_t height,std:: mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(HexStr(CCtxidaddr(txidaddr,cointxid))) << OP_CHECKSIG)); return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysDepositOpRet('D',bindtxid,coin,publishers,txids,height,cointxid,claimvout,deposithex,proof,destpub,amount))); } - fprintf(stderr,"cant find enough inputs\n"); + CCerror = strprintf("cant find enough inputs"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } @@ -1127,32 +1131,50 @@ std::string GatewaysClaim(uint64_t txfee,uint256 bindtxid,std::string refcoin,ui gatewayspk = GetUnspendable(cp,0); if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 ) { - fprintf(stderr,"cant find bindtxid %s\n",uint256_str(str,bindtxid)); + CCerror = strprintf("cant find bindtxid %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || coin != refcoin ) { - fprintf(stderr,"invalid coin - bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); + CCerror = strprintf("invalid coin - bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + if (komodo_txnotarizedconfirmed(bindtxid)==false) + { + CCerror = strprintf("gatewaysbind tx not yet confirmed/notarized"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( GetTransaction(deposittxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 ) { - fprintf(stderr,"cant find deposittxid %s\n",uint256_str(str,bindtxid)); + CCerror = strprintf("cant find deposittxid %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if (DecodeGatewaysDepositOpRet(tx.vout[numvouts-1].scriptPubKey,tmptxid,coin,publishers,txids,height,cointxid,claimvout,deposithex,proof,tmpdestpub,tmpamount) != 'D' || coin != refcoin) { - fprintf(stderr,"invalid coin - deposittxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); + CCerror = strprintf("invalid coin - deposittxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + if (komodo_txnotarizedconfirmed(deposittxid)==false) + { + CCerror = strprintf("gatewaysdeposit tx not yet confirmed/notarized"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if (tmpdestpub!=destpub) { - fprintf(stderr,"different destination pubkey from desdeposittxid\n"); + CCerror = strprintf("different destination pubkey from desdeposit tx"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( (depositamount=GatewaysDepositval(tx,mypk)) != amount ) { - fprintf(stderr,"invalid Gateways deposittxid %s %.8f != %.8f\n",uint256_str(str,deposittxid),(double)depositamount/COIN,(double)amount/COIN); + CCerror = strprintf("invalid Gateways deposittxid %s %.8f != %.8f",uint256_str(str,deposittxid),(double)depositamount/COIN,(double)amount/COIN); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( AddNormalinputs(mtx,mypk,txfee,3) > 0 ) @@ -1167,7 +1189,7 @@ std::string GatewaysClaim(uint64_t txfee,uint256 bindtxid,std::string refcoin,ui } } CCerror = strprintf("cant find enough inputs or mismatched total"); - fprintf(stderr,"%s\n", CCerror.c_str() ); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } @@ -1175,7 +1197,7 @@ std::string GatewaysWithdraw(uint64_t txfee,uint256 bindtxid,std::string refcoin { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); CTransaction tx; CPubKey mypk,gatewayspk,signerpk; uint256 txid,tokenid,hashBlock,oracletxid,tmptokenid,tmpbindtxid,withdrawtxid; int32_t vout,numvouts; - int64_t nValue,totalsupply,inputs,CCchange=0; uint8_t funcid,K,M,N,taddr,prefix,prefix2; std::string coin,hex; + int64_t nValue,totalsupply,inputs,CCchange=0,tmpamount; uint8_t funcid,K,M,N,taddr,prefix,prefix2; std::string coin,hex; std::vector msigpubkeys; char depositaddr[64],str[65],coinaddr[64]; struct CCcontract_info *cp,C,*cpTokens,CTokens; std::vector > unspentOutputs; @@ -1188,12 +1210,20 @@ std::string GatewaysWithdraw(uint64_t txfee,uint256 bindtxid,std::string refcoin if( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 ) { - fprintf(stderr,"cant find bindtxid %s\n",uint256_str(str,bindtxid)); + CCerror = strprintf("cant find bindtxid %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || coin != refcoin ) { - fprintf(stderr,"invalid bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); + CCerror = strprintf("invalid bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + if (komodo_txnotarizedconfirmed(bindtxid)==false) + { + CCerror = strprintf("gatewaysbind tx not yet confirmed/notarized"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } _GetCCaddress(coinaddr,EVAL_GATEWAYS,gatewayspk); @@ -1207,20 +1237,20 @@ std::string GatewaysWithdraw(uint64_t txfee,uint256 bindtxid,std::string refcoin if ( vout == 0 && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 && (funcid=DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey))!=0 && (funcid=='W' || funcid=='P')) { - if (funcid=='W' && DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,tmpbindtxid,coin,withdrawpub,amount)=='W' + if (funcid=='W' && DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,tmpbindtxid,coin,withdrawpub,tmpamount)=='W' && refcoin==coin && tmptokenid==tokenid && tmpbindtxid==bindtxid) { - CCerror = strprintf("unable to create withdraw, another withdraw pending\n"); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("unable to create withdraw, another withdraw pending"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (funcid=='P' && DecodeGatewaysPartialOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,K,signerpk,hex)=='P' && - GetTransaction(withdrawtxid,tx,hashBlock,false)!=0 && (numvouts=tx.vout.size())>0 && DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,tmpbindtxid,coin,withdrawpub,amount)=='W' + GetTransaction(withdrawtxid,tx,hashBlock,false)!=0 && (numvouts=tx.vout.size())>0 && DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,tmpbindtxid,coin,withdrawpub,tmpamount)=='W' && refcoin==coin && tmptokenid==tokenid && tmpbindtxid==bindtxid) { - CCerror = strprintf("unable to create withdraw, another withdraw pending\n"); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("unable to create withdraw, another withdraw pending"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } } @@ -1238,12 +1268,12 @@ std::string GatewaysWithdraw(uint64_t txfee,uint256 bindtxid,std::string refcoin else { CCerror = strprintf("not enough balance of tokens for withdraw"); - fprintf(stderr,"%s\n", CCerror.c_str() ); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } } CCerror = strprintf("cant find enough normal inputs"); - fprintf(stderr,"%s\n", CCerror.c_str() ); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } @@ -1263,8 +1293,8 @@ std::string GatewaysPartialSign(uint64_t txfee,uint256 lasttxid,std::string refc if (GetTransaction(lasttxid,tx,hashBlock,false)==0 || (numvouts= tx.vout.size())<=0 || (funcid=DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey))==0 || (funcid!='W' && funcid!='P')) { - CCerror = strprintf("can't find last tx %s\n",uint256_str(str,lasttxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("can't find last tx %s",uint256_str(str,lasttxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if (funcid=='W') @@ -1272,21 +1302,27 @@ std::string GatewaysPartialSign(uint64_t txfee,uint256 lasttxid,std::string refc withdrawtxid=lasttxid; if (DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) { - CCerror = strprintf("invalid withdraw tx %s\n",uint256_str(str,lasttxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid withdraw tx %s",uint256_str(str,lasttxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + else if (komodo_txnotarizedconfirmed(withdrawtxid)==false) + { + CCerror = strprintf("gatewayswithdraw tx not yet confirmed/notarized"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (GetTransaction(bindtxid,tmptx,hashBlock,false)==0 || (numvouts=tmptx.vout.size())<=0) { - CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("can't find bind tx %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { - CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid bind tx %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } } @@ -1294,41 +1330,52 @@ std::string GatewaysPartialSign(uint64_t txfee,uint256 lasttxid,std::string refc { if (DecodeGatewaysPartialOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,K,signerpk,tmphex)!='P' || refcoin!=coin) { - CCerror = strprintf("cannot decode partialsign tx opret %s\n",uint256_str(str,lasttxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("cannot decode partialsign tx opret %s",uint256_str(str,lasttxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (GetTransaction(withdrawtxid,tmptx,hashBlock,false)==0 || (numvouts= tmptx.vout.size())<=0) { - CCerror = strprintf("can't find withdraw tx %s\n",uint256_str(str,withdrawtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("can't find withdraw tx %s",uint256_str(str,withdrawtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (DecodeGatewaysWithdrawOpRet(tmptx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) { - CCerror = strprintf("invalid withdraw tx %s\n",uint256_str(str,lasttxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid withdraw tx %s",uint256_str(str,lasttxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + else if (komodo_txnotarizedconfirmed(withdrawtxid)==false) + { + CCerror = strprintf("gatewayswithdraw tx not yet confirmed/notarized"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (GetTransaction(bindtxid,tmptx,hashBlock,false)==0 || (numvouts=tmptx.vout.size())<=0) { - CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("can't find bind tx %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { - CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid bind tx %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } } - if (AddNormalinputs(mtx,mypk,txfee,3)==0) fprintf(stderr,"error adding funds for partialsign\n"); - mtx.vin.push_back(CTxIn(tx.GetHash(),0,CScript())); - mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,txfee,gatewayspk)); - return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysPartialOpRet('P',withdrawtxid,refcoin,K+1,mypk,hex))); + if (AddNormalinputs(mtx,mypk,txfee,3)!=0) + { + mtx.vin.push_back(CTxIn(tx.GetHash(),0,CScript())); + mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,txfee,gatewayspk)); + return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysPartialOpRet('P',withdrawtxid,refcoin,K+1,mypk,hex))); + } + CCerror = strprintf("error adding funds for partialsign"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); } std::string GatewaysCompleteSigning(uint64_t txfee,uint256 lasttxid,std::string refcoin,std::string hex) @@ -1346,8 +1393,8 @@ std::string GatewaysCompleteSigning(uint64_t txfee,uint256 lasttxid,std::string if (GetTransaction(lasttxid,tx,hashBlock,false)==0 || (numvouts= tx.vout.size())<=0 || (funcid=DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey))==0 || (funcid!='W' && funcid!='P')) { - CCerror = strprintf("invalid last txid %s\n",uint256_str(str,lasttxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid last txid %s",uint256_str(str,lasttxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if (funcid=='W') @@ -1355,21 +1402,27 @@ std::string GatewaysCompleteSigning(uint64_t txfee,uint256 lasttxid,std::string withdrawtxid=lasttxid; if (DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) { - CCerror = strprintf("cannot decode withdraw tx opret %s\n",uint256_str(str,lasttxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("cannot decode withdraw tx opret %s",uint256_str(str,lasttxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (GetTransaction(bindtxid,tmptx,hashBlock,false)==0 || (numvouts=tmptx.vout.size())<=0) { - CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("can't find bind tx %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + else if (komodo_txnotarizedconfirmed(withdrawtxid)==false) + { + CCerror = strprintf("gatewayswithdraw tx not yet confirmed/notarized"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { - CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid bind tx %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } } @@ -1377,41 +1430,51 @@ std::string GatewaysCompleteSigning(uint64_t txfee,uint256 lasttxid,std::string { if (DecodeGatewaysPartialOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,K,signerpk,tmphex)!='P' || refcoin!=coin) { - CCerror = strprintf("cannot decode partialsign tx opret %s\n",uint256_str(str,lasttxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("cannot decode partialsign tx opret %s",uint256_str(str,lasttxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (GetTransaction(withdrawtxid,tmptx,hashBlock,false)==0 || (numvouts=tmptx.vout.size())==0) { - CCerror = strprintf("invalid withdraw txid %s\n",uint256_str(str,withdrawtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid withdraw txid %s",uint256_str(str,withdrawtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (DecodeGatewaysWithdrawOpRet(tmptx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) { - printf("aaaaaaaaaaa\n"); - CCerror = strprintf("cannot decode withdraw tx opret %s\n",uint256_str(str,withdrawtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("cannot decode withdraw tx opret %s",uint256_str(str,withdrawtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + else if (komodo_txnotarizedconfirmed(withdrawtxid)==false) + { + CCerror = strprintf("gatewayswithdraw tx not yet confirmed/notarized"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (GetTransaction(bindtxid,tmptx,hashBlock,false)==0 || (numvouts=tmptx.vout.size())<=0) { - CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("can't find bind tx %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { - CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid bind tx %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } } - if (AddNormalinputs(mtx,mypk,txfee,3)==0) fprintf(stderr,"error adding funds for completesigning\n"); - mtx.vin.push_back(CTxIn(lasttxid,0,CScript())); - mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,txfee,gatewayspk)); - return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysCompleteSigningOpRet('S',withdrawtxid,refcoin,K+1,hex))); + if (AddNormalinputs(mtx,mypk,txfee,3)!=0) + { + mtx.vin.push_back(CTxIn(lasttxid,0,CScript())); + mtx.vout.push_back(MakeCC1vout(EVAL_GATEWAYS,txfee,gatewayspk)); + return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysCompleteSigningOpRet('S',withdrawtxid,refcoin,K+1,hex))); + } + CCerror = strprintf("error adding funds for completesigning"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); } std::string GatewaysMarkDone(uint64_t txfee,uint256 completetxid,std::string refcoin) @@ -1427,43 +1490,56 @@ std::string GatewaysMarkDone(uint64_t txfee,uint256 completetxid,std::string ref txfee = 10000; if (GetTransaction(completetxid,tx,hashBlock,false)==0 || (numvouts= tx.vout.size())<=0) { - CCerror = strprintf("invalid completesigning txid %s\n",uint256_str(str,completetxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid completesigning txid %s",uint256_str(str,completetxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (DecodeGatewaysCompleteSigningOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,K,hex)!='S' || refcoin!=coin) { - CCerror = strprintf("cannot decode completesigning tx opret %s\n",uint256_str(str,completetxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("cannot decode completesigning tx opret %s",uint256_str(str,completetxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + if (komodo_txnotarizedconfirmed(completetxid)==false) + { + CCerror = strprintf("gatewayscompletesigning tx not yet confirmed/notarized"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (GetTransaction(withdrawtxid,tx,hashBlock,false)==0 || (numvouts= tx.vout.size())==0) { - CCerror = strprintf("invalid withdraw txid %s\n",uint256_str(str,withdrawtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid withdraw txid %s",uint256_str(str,withdrawtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount)!='W' || refcoin!=coin) { CCerror = strprintf("cannot decode withdraw tx opret %s\n",uint256_str(str,withdrawtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (GetTransaction(bindtxid,tx,hashBlock,false)==0 || (numvouts=tx.vout.size())<=0) { - CCerror = strprintf("can't find bind tx %s\n",uint256_str(str,bindtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("can't find bind tx %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } else if (DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { - CCerror = strprintf("invalid bind tx %s\n",uint256_str(str,bindtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid bind tx %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - mtx.vin.push_back(CTxIn(completetxid,0,CScript())); - return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysMarkDoneOpRet('M',withdrawtxid,refcoin,completetxid))); + if (AddNormalinputs(mtx,mypk,txfee,3)!=0) + { + mtx.vin.push_back(CTxIn(completetxid,0,CScript())); + mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysMarkDoneOpRet('M',withdrawtxid,refcoin,completetxid))); + } + CCerror = strprintf("error adding funds for markdone"); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); } UniValue GatewaysPendingDeposits(uint256 bindtxid,std::string refcoin) @@ -1481,14 +1557,14 @@ UniValue GatewaysPendingDeposits(uint256 bindtxid,std::string refcoin) _GetCCaddress(coinaddr,EVAL_GATEWAYS,mypk); if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 ) { - CCerror = strprintf("cant find bindtxid %s\n",uint256_str(str,bindtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("cant find bindtxid %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin) { - CCerror = strprintf("invalid bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } SetCCunspents(unspentOutputs,coinaddr); @@ -1535,14 +1611,14 @@ UniValue GatewaysPendingWithdraws(uint256 bindtxid,std::string refcoin) GetTokensCCaddress(cp,tokensaddr,gatewayspk); if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 ) { - CCerror = strprintf("cant find bindtxid %s\n",uint256_str(str,bindtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("cant find bindtxid %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin ) { - CCerror = strprintf("invalid bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } n = msigpubkeys.size(); @@ -1623,14 +1699,14 @@ UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin) _GetCCaddress(coinaddr,EVAL_GATEWAYS,gatewayspk); if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 ) { - CCerror = strprintf("cant find bindtxid %s\n",uint256_str(str,bindtxid)); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("cant find bindtxid %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin) { - CCerror = strprintf("invalid bindtxid %s coin.%s\n",uint256_str(str,bindtxid),coin.c_str()); - fprintf(stderr,"%s\n", CCerror.c_str() ); + CCerror = strprintf("invalid bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } n = msigpubkeys.size(); @@ -1660,6 +1736,7 @@ UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin) obj.push_back(Pair("withdrawtxidaddr",txidaddr)); Getscriptaddress(withaddr,CScript() << ParseHex(HexStr(withdrawpub)) << OP_CHECKSIG); obj.push_back(Pair("withdrawaddr",withaddr)); + obj.push_back(Pair("confirmed_or_notarized",komodo_txnotarizedconfirmed(txid))); sprintf(numstr,"%.8f",(double)tx.vout[1].nValue/COIN); obj.push_back(Pair("amount",numstr)); obj.push_back(Pair("hex",hex)); @@ -1697,15 +1774,27 @@ UniValue GatewaysInfo(uint256 bindtxid) CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); UniValue result(UniValue::VOBJ),a(UniValue::VARR); std::string coin; char str[67],numstr[65],depositaddr[64],gatewaystokens[64]; uint8_t M,N; std::vector pubkeys; uint8_t taddr,prefix,prefix2; uint256 tokenid,oracletxid,hashBlock; CTransaction tx; - CPubKey Gatewayspk; struct CCcontract_info *cp,C; int32_t i; int64_t totalsupply,remaining; + CPubKey Gatewayspk; struct CCcontract_info *cp,C; int32_t i; int64_t numvouts,totalsupply,remaining; std::vector msigpubkeys; - result.push_back(Pair("result","success")); - result.push_back(Pair("name","Gateways")); cp = CCinit(&C,EVAL_GATEWAYS); Gatewayspk = GetUnspendable(cp,0); GetTokensCCaddress(cp,gatewaystokens,Gatewayspk); + if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 ) + { + CCerror = strprintf("cant find bindtxid %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B') + { + CCerror = strprintf("invalid bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } if ( GetTransaction(bindtxid,tx,hashBlock,false) != 0 ) { + result.push_back(Pair("result","success")); + result.push_back(Pair("name","Gateways")); depositaddr[0] = 0; if ( tx.vout.size() > 0 && DecodeGatewaysBindOpRet(depositaddr,tx.vout[tx.vout.size()-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 0 && M <= N && N > 0 ) { From dd8f2697b7200077b228b74742200ace828ab682 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 19:25:32 -1100 Subject: [PATCH 0317/1145] Many changes --- src/cc/CCassetstx.cpp | 2 +- src/cc/CCinclude.h | 4 +- src/cc/CCtokens.cpp | 2 +- src/cc/CCtx.cpp | 6 +- src/cc/cclib.cpp | 83 ++-- src/cc/channels.cpp | 2 +- src/cc/dice.cpp | 10 +- src/cc/faucet.cpp | 2 +- src/cc/gateways.cpp | 6 +- src/cc/heir.cpp | 4 +- src/cc/marmara.cpp | 6 +- src/cc/oracles.cpp | 4 +- src/cc/payments.cpp | 2 +- src/cc/pegs.cpp | 2 +- src/cc/prices.cpp | 2 +- src/cc/rewards.cpp | 4 +- src/cc/rogue/main.c | 1 - src/cc/rogue_rpc.cpp | 890 ++++++++++++++++++++++++--------------- src/cc/sudoku.cpp | 27 +- src/komodo_bitcoind.h | 2 +- src/komodo_utils.h | 10 +- src/rpc/blockchain.cpp | 8 +- src/wallet/rpcwallet.cpp | 207 ++++----- 23 files changed, 759 insertions(+), 527 deletions(-) diff --git a/src/cc/CCassetstx.cpp b/src/cc/CCassetstx.cpp index 9d83beb2c..1ed43eb28 100644 --- a/src/cc/CCassetstx.cpp +++ b/src/cc/CCassetstx.cpp @@ -47,7 +47,7 @@ int64_t AddAssetInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK if( strcmp(destaddr,coinaddr) != 0 && strcmp(destaddr,cp->unspendableCCaddr) != 0 && strcmp(destaddr,cp->unspendableaddr2) != 0 ) continue; fprintf(stderr,"AddAssetInputs() check destaddress=%s vout amount=%.8f\n",destaddr,(double)vintx.vout[vout].nValue/COIN); - if( (nValue = IsAssetvout(cp, price, origpubkey, vintx, vout, assetid)) > 0 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if( (nValue = IsAssetvout(cp, price, origpubkey, vintx, vout, assetid)) > 0 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { if ( total != 0 && maxinputs != 0 ) mtx.vin.push_back(CTxIn(txid,vout,CScript())); diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index 07c5e9491..52f2d7c1f 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -138,11 +138,13 @@ CBlockIndex *komodo_blockindex(uint256 hash); CBlockIndex *komodo_chainactive(int32_t height); static const uint256 zeroid; +static uint256 ignoretxid; +static int32_t ignorevin; bool myGetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock); int32_t is_hexstr(char *str,int32_t n); bool myAddtomempool(CTransaction &tx, CValidationState *pstate = NULL, bool fSkipExpiry = false); int32_t CCgettxout(uint256 txid,int32_t vout,int32_t mempoolflag); -bool myIsutxo_spentinmempool(uint256 txid,int32_t vout); +bool myIsutxo_spentinmempool(uint256 &spenttxid,int32_t &spentvini,uint256 txid,int32_t vout); bool mytxid_inmempool(uint256 txid); int32_t myIsutxo_spent(uint256 &spenttxid,uint256 txid,int32_t vout); int32_t decode_hex(uint8_t *bytes,int32_t n,char *hex); diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index d7db32b99..61b8d6dd1 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -594,7 +594,7 @@ int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, C std::vector vinPubkeys; - if ((nValue = IsTokensvout(true, true/*<--add only checked token uxtos */, cp, NULL, vintx, vout, tokenid)) > 0 && myIsutxo_spentinmempool(txid, vout) == 0) + if ((nValue = IsTokensvout(true, true/*<--add only checked token uxtos */, cp, NULL, vintx, vout, tokenid)) > 0 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid, vout) == 0) { if (total != 0 && maxinputs != 0) mtx.vin.push_back(CTxIn(txid, vout, CScript())); diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index d93185ca4..630c887f0 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -341,7 +341,7 @@ int32_t CCgettxout(uint256 txid,int32_t vout,int32_t mempoolflag) CCoinsViewMemPool view(pcoinsTip, mempool); if (!view.GetCoins(txid, coins)) return(-1); - if ( myIsutxo_spentinmempool(txid,vout) != 0 ) + if ( myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) != 0 ) return(-1); } else @@ -507,7 +507,7 @@ int64_t AddNormalinputs(CMutableTransaction &mtx,CPubKey mypk,int64_t total,int3 if ( i != n ) continue; } - if ( myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { up = &utxos[n++]; up->txid = txid; @@ -598,7 +598,7 @@ int64_t AddNormalinputs2(CMutableTransaction &mtx,int64_t total,int32_t maxinput if ( i != n ) continue; } - if ( myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { up = &utxos[n++]; up->txid = txid; diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index e71171b71..aa7a9e1ff 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -47,21 +47,20 @@ struct CClib_rpcinfo int32_t numrequiredargs,maxargs; uint8_t funcid,evalcode; } -// creategame, register (inventory + baton + buyin), progress (events + statehash + [compr state]?), claimwin CClib_methods[] = { { (char *)"faucet2", (char *)"fund", (char *)"amount", 1, 1, 'F', EVAL_FAUCET2 }, { (char *)"faucet2", (char *)"get", (char *)"", 0, 0, 'G', EVAL_FAUCET2 }, #ifdef BUILD_ROGUE - { (char *)"rogue", (char *)"newgame", (char *)"buyin", 0, 1, 'G', EVAL_ROGUE }, - { (char *)"rogue", (char *)"txidinfo", (char *)"txid", 1, 1, 'I', EVAL_ROGUE }, + { (char *)"rogue", (char *)"newgame", (char *)"maxplayers buyin", 0, 2, 'G', EVAL_ROGUE }, + { (char *)"rogue", (char *)"gameinfo", (char *)"gametxid", 1, 1, 'T', EVAL_ROGUE }, { (char *)"rogue", (char *)"pending", (char *)"", 0, 0, 'P', EVAL_ROGUE }, - { (char *)"rogue", (char *)"register", (char *)"txid [inventory]", 1, 2, 'R', EVAL_ROGUE }, - { (char *)"rogue", (char *)"progress", (char *)"regtxid fname", 2, 2, 'K', EVAL_ROGUE }, - { (char *)"rogue", (char *)"saveandquit", (char *)"ptxid", 1, 1, 'Q', EVAL_ROGUE }, - { (char *)"rogue", (char *)"claimwin", (char *)"ptxid", 1, 1, 'W', EVAL_ROGUE }, - { (char *)"rogue", (char *)"extract", (char *)"wtxid item", 2, 2, 'X', EVAL_ROGUE }, + { (char *)"rogue", (char *)"register", (char *)"gametxid [playertxid]", 1, 2, 'R', EVAL_ROGUE }, + { (char *)"rogue", (char *)"keystrokes", (char *)"gametxid keystrokes", 2, 2, 'K', EVAL_ROGUE }, + { (char *)"rogue", (char *)"bailout", (char *)"baton finalhash", 2, 2, 'Q', EVAL_ROGUE }, + { (char *)"rogue", (char *)"highlander", (char *)"baton finalhash", 2, 2, 'H', EVAL_ROGUE }, + { (char *)"rogue", (char *)"playerinfo", (char *)"playertxid", 1, 1, 'I', EVAL_ROGUE }, #else { (char *)"sudoku", (char *)"gen", (char *)"", 0, 0, 'G', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, @@ -81,12 +80,12 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); -UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); -UniValue rogue_progress(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); -UniValue rogue_saveandquit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); -UniValue rogue_claimwin(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); -UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); #else bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); @@ -102,23 +101,22 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) #ifdef BUILD_ROGUE if ( cp->evalcode == EVAL_ROGUE ) { - rogue_replay(777,0); if ( strcmp(method,"newgame") == 0 ) return(rogue_newgame(txfee,cp,params)); else if ( strcmp(method,"pending") == 0 ) return(rogue_pending(txfee,cp,params)); - else if ( strcmp(method,"txidinfo") == 0 ) - return(rogue_txidinfo(txfee,cp,params)); + else if ( strcmp(method,"gameinfo") == 0 ) + return(rogue_gameinfo(txfee,cp,params)); else if ( strcmp(method,"register") == 0 ) return(rogue_register(txfee,cp,params)); - else if ( strcmp(method,"progress") == 0 ) - return(rogue_progress(txfee,cp,params)); - else if ( strcmp(method,"saveandquit") == 0 ) + else if ( strcmp(method,"keystrokes") == 0 ) + return(rogue_keystrokes(txfee,cp,params)); + else if ( strcmp(method,"bailout") == 0 ) return(rogue_saveandquit(txfee,cp,params)); - else if ( strcmp(method,"claimwin") == 0 ) + else if ( strcmp(method,"highlander") == 0 ) + return(rogue_claimwin(txfee,cp,params)); + else if ( strcmp(method,"playerinfo") == 0 ) return(rogue_claimwin(txfee,cp,params)); - else if ( strcmp(method,"extract") == 0 ) - return(rogue_extract(txfee,cp,params)); else { result.push_back(Pair("result","error")); @@ -328,7 +326,7 @@ bool CClib_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,int64_t total,int32_t maxinputs,char *cmpaddr) { - char coinaddr[64]; int64_t threshold,nValue,price,totalinputs = 0; uint256 txid,hashBlock; std::vector origpubkey; CTransaction vintx; int32_t vout,n = 0; + char coinaddr[64]; int64_t threshold,nValue,price,totalinputs = 0,txfee = 10000; uint256 txid,hashBlock; std::vector origpubkey; CTransaction vintx; int32_t vout,n = 0; std::vector > unspentOutputs; GetCCaddress(cp,coinaddr,pk); SetCCunspents(unspentOutputs,coinaddr); @@ -338,12 +336,12 @@ int64_t AddCClibInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK txid = it->first.txhash; vout = (int32_t)it->first.index; //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f vs %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN,(double)threshold/COIN); - if ( it->second.satoshis < threshold ) + if ( it->second.satoshis < threshold || it->second.satoshis == txfee ) continue; // no need to prevent dup if ( GetTransaction(txid,vintx,hashBlock,false) != 0 ) { - if ( (nValue= IsCClibvout(cp,vintx,vout,cmpaddr)) > 1000000 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( (nValue= IsCClibvout(cp,vintx,vout,cmpaddr)) >= 1000000 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { if ( total != 0 && maxinputs != 0 ) mtx.vin.push_back(CTxIn(txid,vout,CScript())); @@ -439,6 +437,41 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para return(""); } +UniValue cclib_error(UniValue &result,const char *errorstr) +{ + result.push_back(Pair("status","error")); + result.push_back(Pair("error",errorstr)); + return(result); +} + +cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will be freed by caller +{ + cJSON *params; char *jsonstr,*newstr; int32_t i,j; + if ( (jsonstr= jprint(origparams,0)) != 0 ) + { + if ( jsonstr[0] == '"' && jsonstr[strlen(jsonstr)-1] == '"' ) + { + jsonstr[strlen(jsonstr)-1] = 0; + jsonstr++; + } + newstr = (char *)malloc(strlen(jsonstr)+1); + for (i=j=0; jsonstr[i]!=0; i++) + { + if ( jsonstr[i] == '%' && jsonstr[i+1] == '2' && jsonstr[i+2] == '2' ) + { + newstr[j++] = '"'; + i += 2; + } else newstr[j++] = jsonstr[i]; + } + newstr[j] = 0; + params = cJSON_Parse(newstr); + free(newstr); + *nump = cJSON_GetArraySize(params); + //free(origparams); + } else params = 0; + return(params); +} + #ifdef BUILD_ROGUE #include "rogue_rpc.cpp" #include "rogue/vers.c" diff --git a/src/cc/channels.cpp b/src/cc/channels.cpp index 6cd379eed..e6f4b48c6 100644 --- a/src/cc/channels.cpp +++ b/src/cc/channels.cpp @@ -430,7 +430,7 @@ int64_t AddChannelsInputs(struct CCcontract_info *cp,CMutableTransaction &mtx, C } } } - if (txid!=zeroid && myIsutxo_spentinmempool(txid,0) != 0) + if (txid!=zeroid && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,0) != 0) { txid=zeroid; int32_t mindepth=CHANNELS_MAXPAYMENTS; diff --git a/src/cc/dice.cpp b/src/cc/dice.cpp index 05dad9bf6..1bb44af18 100644 --- a/src/cc/dice.cpp +++ b/src/cc/dice.cpp @@ -269,7 +269,7 @@ int32_t dicefinish_utxosget(int32_t &total,struct dicefinish_utxo *utxos,int32_t LOCK(mempool.cs); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { - if ( myIsutxo_spentinmempool(it->first.txhash,(int32_t)it->first.index) == 0 ) + if ( myIsutxo_spentinmempool(ignoretxid,ignorevin,it->first.txhash,(int32_t)it->first.index) == 0 ) { if ( it->second.satoshis < threshold || it->second.satoshis > 10*threshold ) continue; @@ -302,7 +302,7 @@ int32_t dice_betspent(char *debugstr,uint256 bettxid) } { //LOCK(mempool.cs); - if ( myIsutxo_spentinmempool(bettxid,0) != 0 || myIsutxo_spentinmempool(bettxid,1) != 0 ) + if ( myIsutxo_spentinmempool(ignoretxid,ignorevin,bettxid,0) != 0 || myIsutxo_spentinmempool(ignoretxid,ignorevin,bettxid,1) != 0 ) { fprintf(stderr,"%s bettxid.%s already spent in mempool\n",debugstr,bettxid.GetHex().c_str()); return(-1); @@ -1067,7 +1067,7 @@ uint64_t AddDiceInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK break; if ( j != mtx.vin.size() ) continue; - if ( myGetTransaction(txid,tx,hashBlock) != 0 && tx.vout.size() > 0 && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( myGetTransaction(txid,tx,hashBlock) != 0 && tx.vout.size() > 0 && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { if ( (funcid= DecodeDiceOpRet(txid,tx.vout[tx.vout.size()-1].scriptPubKey,sbits,fundingtxid,hash,proof)) != 0 ) { @@ -1176,7 +1176,7 @@ int64_t DicePlanFunds(uint64_t &entropyval,uint256 &entropytxid,uint64_t refsbit continue; } } - if ( myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { entropytxid = txid; entropyval = tx.vout[0].nValue; @@ -1447,7 +1447,7 @@ std::string DiceBet(uint64_t txfee,char *planstr,uint256 fundingtxid,int64_t bet CCerror = "Your dealer is broke, find a new casino."; return(""); } - if ( myIsutxo_spentinmempool(entropytxid,0) != 0 ) + if ( myIsutxo_spentinmempool(ignoretxid,ignorevin,entropytxid,0) != 0 ) { CCerror = "entropy txid is spent"; return(""); diff --git a/src/cc/faucet.cpp b/src/cc/faucet.cpp index 6e59b6c1a..b44337461 100644 --- a/src/cc/faucet.cpp +++ b/src/cc/faucet.cpp @@ -157,7 +157,7 @@ int64_t AddFaucetInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPub // no need to prevent dup if ( GetTransaction(txid,vintx,hashBlock,false) != 0 ) { - if ( (nValue= IsFaucetvout(cp,vintx,vout)) > 1000000 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( (nValue= IsFaucetvout(cp,vintx,vout)) > 1000000 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { if ( total != 0 && maxinputs != 0 ) mtx.vin.push_back(CTxIn(txid,vout,CScript())); diff --git a/src/cc/gateways.cpp b/src/cc/gateways.cpp index 4e2f64184..cc7e062dc 100644 --- a/src/cc/gateways.cpp +++ b/src/cc/gateways.cpp @@ -1499,7 +1499,7 @@ UniValue GatewaysPendingDeposits(uint256 bindtxid,std::string refcoin) nValue = (int64_t)it->second.satoshis; if ( vout == 0 && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts=tx.vout.size())>0 && DecodeGatewaysDepositOpRet(tx.vout[numvouts-1].scriptPubKey,tmpbindtxid,coin,publishers,txids,height,cointxid,claimvout,hex,proof,destpub,amount) == 'D' - && tmpbindtxid==bindtxid && refcoin == coin && myIsutxo_spentinmempool(txid,vout) == 0) + && tmpbindtxid==bindtxid && refcoin == coin && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("cointxid",uint256_str(str,cointxid))); @@ -1561,7 +1561,7 @@ UniValue GatewaysPendingWithdraws(uint256 bindtxid,std::string refcoin) nValue = (int64_t)it->second.satoshis; K=0; if ( vout == 0 && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 && - (funcid=DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey))!=0 && (funcid=='W' || funcid=='P') && myIsutxo_spentinmempool(txid,vout) == 0) + (funcid=DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey))!=0 && (funcid=='W' || funcid=='P') && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0) { if (funcid=='W') { @@ -1648,7 +1648,7 @@ UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin) vout = (int32_t)it->first.index; nValue = (int64_t)it->second.satoshis; if ( vout == 0 && nValue == 10000 && GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 && - DecodeGatewaysCompleteSigningOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,K,hex) == 'S' && refcoin == coin && myIsutxo_spentinmempool(txid,vout) == 0) + DecodeGatewaysCompleteSigningOpRet(tx.vout[numvouts-1].scriptPubKey,withdrawtxid,coin,K,hex) == 'S' && refcoin == coin && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0) { if (GetTransaction(withdrawtxid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size())>0 && DecodeGatewaysWithdrawOpRet(tx.vout[numvouts-1].scriptPubKey,tmptokenid,bindtxid,coin,withdrawpub,amount) == 'W' || refcoin!=coin || tmptokenid!=tokenid) diff --git a/src/cc/heir.cpp b/src/cc/heir.cpp index 04866594d..4fea0be1e 100644 --- a/src/cc/heir.cpp +++ b/src/cc/heir.cpp @@ -541,7 +541,7 @@ template int64_t Add1of2AddressInputs(struct CCcontract_info* cp, isMyFuncId(funcId) && (typeid(Helper) != typeid(TokenHelper) || IsTokensvout(true, true, cp, nullptr, heirtx, voutIndex, tokenid) > 0) && // token validation logic //(voutValue = IsHeirFundingVout(cp, heirtx, voutIndex, ownerPubkey, heirPubkey)) > 0 && // heir contract vout validation logic - not used since we moved to 2-eval vouts - !myIsutxo_spentinmempool(txid, voutIndex)) + !myIsutxo_spentinmempool(ignoretxid,ignorevin,txid, voutIndex)) { std::cerr << "Add1of2AddressInputs() satoshis=" << it->second.satoshis << std::endl; if (total != 0 && maxinputs != 0) @@ -591,7 +591,7 @@ template int64_t LifetimeHeirContractFunds(struct CCcontract_info (txid == fundingtxid || fundingTxidInOpret == fundingtxid) && isMyFuncId(funcId) && !isSpendingTx(funcId) && (typeid(Helper) != typeid(TokenHelper) || IsTokensvout(true, true, cp, nullptr, heirtx, ivout, tokenid) > 0) && - !myIsutxo_spentinmempool(txid, ivout)) // exclude tx in mempool + !myIsutxo_spentinmempool(ignoretxid,ignorevin,txid, ivout)) // exclude tx in mempool { total += it->second; // dont do this: tx.vout[ivout].nValue; // in vin[0] always is the pay to 1of2 addr (funding or change) //std::cerr << "LifetimeHeirContractFunds() added tx=" << txid.GetHex() << " it->second=" << it->second << " vout[0].nValue=" << tx.vout[ivout].nValue << " opreturn=" << (char)funcId << '\n'; diff --git a/src/cc/marmara.cpp b/src/cc/marmara.cpp index 0e301ba97..8bb306d9b 100644 --- a/src/cc/marmara.cpp +++ b/src/cc/marmara.cpp @@ -366,7 +366,7 @@ int64_t AddMarmaraCoinbases(struct CCcontract_info *cp,CMutableTransaction &mtx, { if ( DecodeMaramaraCoinbaseOpRet(vintx.vout[1].scriptPubKey,pk,ht,unlockht) == 'C' && unlockht == unlocks && pk == poolpk && ht >= firstheight ) { - if ( (nValue= vintx.vout[vout].nValue) > 0 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( (nValue= vintx.vout[vout].nValue) > 0 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { if ( maxinputs != 0 ) mtx.vin.push_back(CTxIn(txid,vout,CScript())); @@ -395,7 +395,7 @@ int64_t AddMarmarainputs(CMutableTransaction &mtx,std::vector &pubkeys, vout = (int32_t)it->first.index; if ( it->second.satoshis < threshold ) continue; - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 && vout < numvouts && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 && vout < numvouts && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { if ( (funcid= DecodeMaramaraCoinbaseOpRet(tx.vout[numvouts-1].scriptPubKey,pk,ht,unlockht)) == 'C' || funcid == 'P' || funcid == 'L' ) { @@ -462,7 +462,7 @@ UniValue MarmaraLock(uint64_t txfee,int64_t amount,int32_t height) vout = (int32_t)it->first.index; if ( (nValue= it->second.satoshis) < threshold ) continue; - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 && vout < numvouts && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 0 && vout < numvouts && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { if ( (funcid= DecodeMaramaraCoinbaseOpRet(tx.vout[numvouts-1].scriptPubKey,pk,ht,unlockht)) == 'C' || funcid == 'P' || funcid == 'L' ) { diff --git a/src/cc/oracles.cpp b/src/cc/oracles.cpp index 66c0e1b9a..bf3bf444a 100644 --- a/src/cc/oracles.cpp +++ b/src/cc/oracles.cpp @@ -294,7 +294,7 @@ uint256 OracleBatonUtxo(uint64_t txfee,struct CCcontract_info *cp,uint256 refora } } } - while ( myIsutxo_spentinmempool(batontxid,1) != 0 ) + while ( myIsutxo_spentinmempool(ignoretxid,ignorevin,batontxid,1) != 0 ) batontxid = myIs_baton_spentinmempool(batontxid,1); return(batontxid); } @@ -724,7 +724,7 @@ int64_t AddOracleInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,uint else if (tmporacletxid==oracletxid) { // get valid CC payments - if ( (nValue= IsOraclesvout(cp,vintx,vout)) >= 10000 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( (nValue= IsOraclesvout(cp,vintx,vout)) >= 10000 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { if ( total != 0 && maxinputs != 0 ) mtx.vin.push_back(CTxIn(txid,vout,CScript())); diff --git a/src/cc/payments.cpp b/src/cc/payments.cpp index 859a5ba3f..c4f476cfb 100644 --- a/src/cc/payments.cpp +++ b/src/cc/payments.cpp @@ -127,7 +127,7 @@ int64_t AddPaymentsInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CP // no need to prevent dup if ( GetTransaction(txid,vintx,hashBlock,false) != 0 ) { - if ( (nValue= IsPaymentsvout(cp,vintx,vout)) > 1000000 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( (nValue= IsPaymentsvout(cp,vintx,vout)) > 1000000 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { if ( total != 0 && maxinputs != 0 ) mtx.vin.push_back(CTxIn(txid,vout,CScript())); diff --git a/src/cc/pegs.cpp b/src/cc/pegs.cpp index e2893bec8..c435d9920 100644 --- a/src/cc/pegs.cpp +++ b/src/cc/pegs.cpp @@ -134,7 +134,7 @@ int64_t AddPegsInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKe // no need to prevent dup if ( GetTransaction(txid,vintx,hashBlock,false) != 0 ) { - if ( (nValue= IsPegsvout(cp,vintx,vout)) > 1000000 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( (nValue= IsPegsvout(cp,vintx,vout)) > 1000000 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { if ( total != 0 && maxinputs != 0 ) mtx.vin.push_back(CTxIn(txid,vout,CScript())); diff --git a/src/cc/prices.cpp b/src/cc/prices.cpp index 369495b1a..df1b5e18e 100644 --- a/src/cc/prices.cpp +++ b/src/cc/prices.cpp @@ -141,7 +141,7 @@ int64_t AddTokensInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,char if ( GetTransaction(txid,vintx,hashBlock,false) != 0 && vout < vintx.vout.size() ) { // need to verify assetid - if ( (nValue= vintx.vout[vout].nValue) >= 10000 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( (nValue= vintx.vout[vout].nValue) >= 10000 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { if ( total != 0 && maxinputs != 0 ) mtx.vin.push_back(CTxIn(txid,vout,CScript())); diff --git a/src/cc/rewards.cpp b/src/cc/rewards.cpp index b9f4677be..c201869b0 100644 --- a/src/cc/rewards.cpp +++ b/src/cc/rewards.cpp @@ -310,7 +310,7 @@ static uint64_t myIs_unlockedtx_inmempool(uint256 &txid,int32_t &vout,uint64_t r if ( tx.vout.size() > 0 && tx.vout[0].nValue >= needed ) { const uint256 &hash = tx.GetHash(); - if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() != 0 && myIsutxo_spentinmempool(hash,0) == 0 ) + if ( tx.vout[0].scriptPubKey.IsPayToCryptoCondition() != 0 && myIsutxo_spentinmempool(ignoretxid,ignorevin,hash,0) == 0 ) { if ( (funcid= DecodeRewardsOpRet(hash,tx.vout[tx.vout.size()-1].scriptPubKey,sbits,fundingtxid)) == 'U' && sbits == refsbits && fundingtxid == reffundingtxid ) { @@ -346,7 +346,7 @@ int64_t AddRewardsInputs(CScript &scriptPubKey,uint64_t maxseconds,struct CCcont break; if ( j != mtx.vin.size() ) continue; - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && tx.vout.size() > 0 && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( GetTransaction(txid,tx,hashBlock,false) != 0 && tx.vout.size() > 0 && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { if ( (funcid= DecodeRewardsOpRet(txid,tx.vout[tx.vout.size()-1].scriptPubKey,sbits,fundingtxid)) != 0 ) { diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 7efdebc8d..d2805ed73 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -13,7 +13,6 @@ * * ******************************************************************************/ - #include #include #include diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index cf7ebeb70..4fb850ef0 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -15,229 +15,600 @@ ******************************************************************************/ #include "cJSON.h" -// creategame, register (inventory + baton + buyin), progress (seed + firsthash + statehash + events), claimwin -// create game buyin, newbie flag, 10 blocks registration seed is starting blockhash! -// inheritance of items across games! -// binding tokens to specific items to allow for built in market -// pubkey token inventory creates items can be used for a specific campaign -// player wins buyins + ingame gold -> ROGUE + ingame items -> tokens via 1 vout per item to be spent into a token opreturn #define ROGUE_REGISTRATION 5 +#define ROGUE_REGISTRATIONSIZE (100 * 10000) +#define ROGUE_MAXPLAYERS 64 // need to send unused fees back to globalCC address to prevent leeching +#defein ROGUE_MAXKEYSTROKESGAP 60 + +/* + the idea is that you creategame and get a txid, you specify the maxplayers and buyin for the game. the tx will have maxplayers of vouts. You must have a non-zero buyin to be able to use a preexisting character. + + creategame + vout0 -> txfee highlander vout TCBOO creation + vout1 -> txfee highlander vout TCBOO playerdata used + vout2 to vout.maxplayers -> 1of2 registration ROGUE_REGISTRATIONSIZE batons + + registration + vin0 -> ROGUE_REGISTRATIONSIZE 1of2 registration baton from creategame + vin1 -> optional nonfungible character vout @ + vin2 -> original creation TCBOO playerdata used + vin3+ -> buyin + vout0 -> keystrokes/completion baton + + keystrokes + vin0 -> txfee 1of2 baton from registration or previous keystrokes + opret -> user input chars + + bailout: must be within 777 blocks of last keystrokes + vin0 -> keystrokes baton of completed game with Q + vout0 -> 1% ingame gold + + highlander + vin0 -> txfee highlander vout from creategame TCBOO creation + vin1 -> keystrokes baton of completed game, must be last to quit or first to win, only spent registration batons matter. If more than 777 blocks since last keystrokes, it is forfeit + vins -> rest of unspent registration utxo so all newgame vouts are spent + vout0 -> nonfungible character with pack @ + vout1 -> 1% ingame gold and all the buyins + + + then to register you need to spend one of the vouts and also provide the buyin + once you register the gui mode is making automatic keystrokes tx with the raw chars in opreturn. + if during the registration, you provide a character as an input, your gameplay starts with that character instead of the default + + each keystrokes tx spends a baton vout that you had in your register tx + + so from the creategame tx, you can trace the maxplayers vouts to find all the registrations and all the keystrokes to get the keyboard events + + If you quit out of the game, then the in game gold that you earned can be converted to ROGUE coins, but unless you are the last one remaining, any character you input, is permanently spent + + so you can win a multiplayer by being the last player to quit or the first one to win. In either case, you would need to spend a special highlander vout in the original creategame tx. having this as an input allows to create a tx that has the character as the nonfungible token, collect all the buyin and of course the ingame gold + + once you have a non-fungible token, ownership of it can be transferred or traded or spent in a game + */ + //////////////////////// start of CClib interface //./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & -// cclib newgame 17 +// cclib newgame 17 \"[maxplayers,buyin]\" // cclib pending 17 -// cclib txidinfo 17 \"35e99df53c981a937bfa2ce7bfb303cea0249dba34831592c140d1cb729cb19f\" +// cclib txidinfo 17 \"[%2235e99df53c981a937bfa2ce7bfb303cea0249dba34831592c140d1cb729cb19f%22]\" // ./rogue gui -> creates keystroke files -// cclib register 17 \"35e99df53c981a937bfa2ce7bfb303cea0249dba34831592c140d1cb729cb19f\" [items] -// cclib pending 17 \"\" starthash endhash keystrokes +// cclib register 17 \"[%2235e99df53c981a937bfa2ce7bfb303cea0249dba34831592c140d1cb729cb19f%22,%22%22]\" +// cclib keystrokes 17 \"[]\" -CScript rogue_newgameopret(int64_t buyin) +CScript rogue_newgameopret(int64_t buyin,int32_t maxplayers) { CScript opret; uint8_t evalcode = EVAL_ROGUE; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'G' << buyin); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'G' << buyin << maxplayers); return(opret); } -/*CScript rogue_solutionopret(char *solution,uint32_t timestamps[81]) +CScript rogue_registeropret(uint256 gametxid,uint256 playertxid) { - CScript opret; uint8_t evalcode = EVAL_ROGUE; std::string str(solution); std::vector data; int32_t i; - for (i=0; i<81; i++) - { - data.push_back((timestamps[i] >> 24) & 0xff); - data.push_back((timestamps[i] >> 16) & 0xff); - data.push_back((timestamps[i] >> 8) & 0xff); - data.push_back(timestamps[i] & 0xff); - } - opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'S' << str << data); + CScript opret; uint8_t evalcode = EVAL_ROGUE; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'R' << gametxid << playertxid); return(opret); } -uint8_t rogue_solutionopreturndecode(char solution[82],uint32_t timestamps[81],CScript scriptPubKey) +CScript rogue_keystrokesopret(uint256 gametxid,uint256 batontxid,CPubKey pk,std::vectorkeystrokes) { - std::vector vopret; uint8_t *script,e,f; std::string str; std::vector data; int32_t i,ind; uint32_t x; - GetOpReturnData(scriptPubKey,vopret); - script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> str; ss >> data) != 0 && e == EVAL_ROGUE && f == 'S' ) - { - if ( data.size() == 81*sizeof(uint32_t) && str.size() == 81 ) - { - strcpy(solution,str.c_str()); - for (i=ind=0; i<81; i++) - { - if ( solution[i] < '1' || solution[i] > '9' ) - break; - x = data[ind++]; - x <<= 8, x |= (data[ind++] & 0xff); - x <<= 8, x |= (data[ind++] & 0xff); - x <<= 8, x |= (data[ind++] & 0xff); - timestamps[i] = x; - } - if ( i == 81 ) - return(f); - } else fprintf(stderr,"datasize %d sol[%d]\n",(int32_t)data.size(),(int32_t)str.size()); - } - return(0); -}*/ + CScript opret; uint8_t evalcode = EVAL_ROGUE; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'K' << gametxid << batontxid << pk << keystrokes); + return(opret); +} -uint8_t rogue_newgameopreturndecode(int64_t &buyin,CScript scriptPubKey) +CScript rogue_highlanderopret(uint256 gametxid,uint256 registertxid,CPubKey pk,std::vectorplayerdata) +{ + CScript opret; uint8_t evalcode = EVAL_ROGUE; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'K' << gametxid << registertxid << pk << playerdata); + return(opret); +} + +uint8_t rogue_highlanderopretdecode(uint256 &gametxid,uint256 ®istertxid,CPubKey &pk,std::vector &playerdata,CSript scriptPubKey) { std::vector vopret; uint8_t *script,e,f; GetOpReturnData(scriptPubKey,vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> buyin) != 0 && e == EVAL_ROGUE && f == 'G' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> registertxid; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && f == 'H' ) { return(f); } return(0); } +uint8_t rogue_keystrokesopretdecode(uint256 &gametxid,uint256 &batontxid,CPubKey &pk,std::vector &keystrokes,CScript scriptPubKey) +{ + std::vector vopret; uint8_t *script,e,f; + GetOpReturnData(scriptPubKey,vopret); + script = (uint8_t *)vopret.data(); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> batontxid; ss >> pk; ss >> keystrokes) != 0 && e == EVAL_ROGUE && f == 'K' ) + { + return(f); + } + return(0); +} + +uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &playertxid,CScript scriptPubKey) +{ + std::vector vopret; uint8_t *script,e,f; + GetOpReturnData(scriptPubKey,vopret); + script = (uint8_t *)vopret.data(); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) + { + return(f); + } + return(0); +} + +uint8_t rogue_newgameopreturndecode(int64_t &buyin,int32_t &maxplayers,CScript scriptPubKey) +{ + std::vector vopret; uint8_t *script,e,f; + GetOpReturnData(scriptPubKey,vopret); + script = (uint8_t *)vopret.data(); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> buyin; ss >> mayplayers) != 0 && e == EVAL_ROGUE && f == 'G' ) + { + return(f); + } + return(0); +} + +void rogue_univalue(UniValue &result,const char *method,int64_t maxplayers,int64_t buyin) +{ + if ( method != 0 ) + { + result.push_back(Pair("name","rogue")); + result.push_back(Pair("method",method)); + } + if ( maxplayers > 0 ) + result.push_back(Pair("maxplayers",maxplayers)); + if ( buyin >= 0 ) + { + result.push_back(Pair("buyin",ValueFromAmount(buyin))); + if ( buyin == 0 ) + result.push_back(Pair("type","newbie")); + else result.push_back(Pair("type","buyin")); + } +} + +void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin) +{ + CBlockIndex *pindex; int32_t ht; uint64_t seed; char cmd[512]; + if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) + { + ht = pindex->GetHeight(); + obj.push_back(Pair("height",ht)); + obj.push_back(Pair("start",ht+ROGUE_REGISTRATION)); + if ( komodo_nextheight() > ht+ROGUE_REGISTRATION ) + { + if ( (pindex= komodo_chainactive(ht+ROGUE_REGISTRATION)) != 0 ) + { + hashBlock = pindex->GetBlockHash(); + obj.push_back(Pair("starthash",hashBlock.ToString())); + memcpy(&seed,&hashBlock,sizeof(seed)); + seed &= (1LL << 62) - 1; + obj.push_back(Pair("seed",(int64_t)seed)); + sprintf(cmd,"./rogue %llu gui",(long long)seed); + obj.push_back(Pair("run",cmd)); + } + } + } + obj.push_back(Pair("maxplayers",maxplayers)); + obj.push_back(Pair("buyin",ValueFromAmount(buyin))); +} + +int32_t rogue_isvalidgame(struct CCcontract_info *cp,CTransaction &tx,int64_t &buyin,int32_t &maxplayers,uint256 txid) +{ + uint256 hashBlock; int32_t i,numvouts; char coinaddr[64]; CPubKey roguepk; + buyin = maxplayers = 0; + if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + { + if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,0) == 0 ) + { + if ( rogue_newgameopreturndecode(buyin,maxplayers,tx.vout[numvouts-1].scriptPubKey) == 'G' ) + { + if ( numvouts > maxplayers+2 ) + { + for (i=0; i playerdata) +{ + obj.push_back("raw",playerdata.ToString()); + // convert to scrolls, etc. + return(obj); +} + +int32_t rogue_iterateplayer(uint256 firsttxid,uint256 lasttxid) // retrace playertxid vins to reach highlander <- this verifies player is valid and rogue_playerdataspend makes sure it can only be used once +{ + uint256 spenttxid,txid = firsttxid; int32_t spentvini,vout = 0; + while ( (spentvini= myIsutxo_spent(spenttxid,txid,vout)) == 0 ) + { + txid = spenttxid; + } + if ( txid == lasttxid ) + return(0); + else + { + fprintf(stderr,"firsttxid.%s -> %s != last.%s\n",firsttxid.ToString(),txid.ToString(),lasttxid.ToString()); + return(-1); + } +} + +/* + playertxid is whoever owns the nonfungible satoshi and it might have been bought and sold many times. + highlander is the game winning tx with the player data and is the only place where the unique player data exists + origplayergame is the gametxid that ends up being won by the highlander and they are linked directly as the highlander tx spends gametxid.vout0 + 'S' is for sell, but will need to change to accomodate assets + */ + +int32_t rogue_playerdata(uint256 &origplayergame,CPubKey &pk,std::vector &playerdata,uint256 playertxid) +{ + uint256 origplayertxid,hashBlock,highlander,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,maxplayers; int64_t buyin; + if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) + { + GetOpReturnData(scriptPubKey,vopret); + script = (uint8_t *)vopret.data(); + if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'S') ) + { + memcpy(&highlander,script+2,sizeof(highlander)); + highlander = revuint256(highlander); + fprintf(stderr,"got highlander.%s\n",highlander.ToString().c_str()); + if ( rogue_iterateplayer(highlander,playertxid) == 0 ) + { + if ( GetTransaction(highlander,highlandertx,hashBlock,false) != 0 && (numvouts= highlandertx.vout.size()) > 0 ) + { + if ( rogue_highlanderopretdecode(origplayergame,registertxid,pk,playerdata,highlandertx.vout[numvouts-1].scriptPubKey) == 'H' ) + { + if ( highlandertx.vin[0].prev.hash == prigplayergame && highlandertx.vin[0].prev.n == 0 && rogue_isvalidgame(cp,gametx,buyin,maxplayers,origplayergame) == 0 && maxplayers > 1 ) + return(0); + else return(-3); + } + } + } else return(-2); + } + } + return(-1); +} + +int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,uint256 origplayergame) +{ + int64_t txfee = 10000; + if ( CCgettxout(playertxid,0,1) == txfee && CCgettxout(origplayergame,1,1) == txfee ) + { + mtx.vin.push_back(playertxid,0,CScript()); + mtx.vin.push_back(origplayergame,1,CScript()); + return(0); + } else return(-1); +} + +int32_t rogue_findbaton(std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,CScript scriptPubKey) +{ + int32_t i,numvouts,spentvini,matches = 0; uint256 spenttxid,hashBlock,txid,playertxid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; + for (i=0; i= 0 ) + { + if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && tx.vout.size() > 0 ) + { + if ( spenttx.vout[0].scriptPubKey == scriptPubKey ) + { + matches++; + matchtx = spenttx; + } + } + } + } + if ( matches == 1 ) + { + numvouts = matchtx.vout.size(); + if ( rogue_registeropretdecode(txid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) + { + if ( playertxid == zeroid || rogue_playerdata(origplayergame,playerdata,playertxid) == 0 ) + { + txid = spenttxid; + while ( CCgettxout(txid,0,1) > 0 ) + { + spenttxid = zeroid; + spentvinit = -1; + if ( (spentvini= myIsutxo_spent(spenttxid,txid,0)) >= 0 ) + txid = spenttxid; + else if ( myIsutxo_spentinmempool(spenttxid,spentvin,txid,0) == 0 || spenttxid == zeroid ) + { + fprintf(stderr,"mempool tracking error %s/v0\n",txid.ToString().c_str()); + return(-2); + } + if ( spentvini != 0 ) + return(-3); + } + batontxid = txid; + batonvout = 0; // not vini + // how to detect timeout, bailedout, highlander + hashBlock = zeroid; + if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 0 ) + { + if ( hashBlock == zeroid ) + batonht = komodo_nextheight(); + else if ( (pindex= komodo_blockindex(hashBlock)) == 0 ) + return(-4); + else batonht = pindex->nHeight; + return(0); + } + } + } + } + return(-1); +} + +void rogue_gameplayerinfo(UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers) +{ + // identify if bailout or quit or timed out + uint256 batontxid; int32_t batonvout,batonht; int64_t batonvalue; std::vector playerdata; + obj.push_back(Pair("slot",(int64_t)vout-2)); + if ( rogue_findbaton(playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,gametx.vout[vout].scriptPubKey) == 0 ) + { + obj.push_back(Pair("baton",batontxid.ToString())); + obj.push_back(Pair("batonvout",(int64_t)batonvout)); + obj.push_back(Pair("batonvalue",ValueFromAmount(batonvalue))); + obj.push_back(Pair("batonht",(int64_t)batonht)); + if ( playerdata.size() > 0 ) + { + UniValue pobj(UniValue:VOBJ); + obj.push_back(Pair("rogue",rogue_playerobj(pobj,playerdata))); + } + } +} + +int64_t rogue_registrationbaton(CMutableTransaction &mtx,uint256 gametxid,CTransaction gametx,int32_t maxplayers) +{ + int32_t vout,j,r; int64_t nValue; + if ( tx.vout.size() > maxplayers+2 ) + { + r = rand() % maxplayers; + for (j=0; j 0 ) + { + result.push_back(Pair("hex",rawtx)); + if ( DecodeHexTx(tx,rawtx) != 0 ) + { + if ( broadcastflag != 0 && myAddtomempool(tx) != 0 ) + RelayTransaction(tx); + result.push_back(Pair("txid",tx.GetHash().ToString())); + result.push_back(Pair("result","success")); + } else result.push_back(Pair("error","decode hex")); + } else result.push_back(Pair("error","couldnt finalize CCtx")); + return(result); +} + UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey roguepk,mypk; char *jsonstr; uint64_t inputsum,change,amount = 0; - if ( params != 0 ) + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey roguepk,mypk; char *jsonstr; uint64_t inputsum,change,required,buyin=0,amount = 0; int32_t i,n,maxplayers = 1; + if ( txfee == 0 ) + txfee = 10000; + if ( (params= cclib_reparse(&n,params)) != 0 ) { - if ( (jsonstr= jprint(params,0)) != 0 ) + if ( n > 1 ) { - if ( jsonstr[0] == '"' && jsonstr[strlen(jsonstr)-1] == '"' ) - { - jsonstr[strlen(jsonstr)-1] = 0; - jsonstr++; - } - amount = atof(jsonstr) * COIN + 0.0000000049; - free(jsonstr); + maxplayers = juint(jitem(params,0),0); + if ( n > 2 ) + buyin = jdouble(jitem(params,1),0) * COIN + 0.0000000049; } } + if ( maxplayers < 1 || maxplayers > ROGUE_MAXPLAYERS ) + return(cclib_error(result,"illegal maxplayers")); mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); - result.push_back(Pair("result","success")); - result.push_back(Pair("name","rogue")); - result.push_back(Pair("method","newgame")); - if ( amount == 0 ) - result.push_back(Pair("type","newbie")); - else result.push_back(Pair("type","buyin")); - result.push_back(Pair("amount",ValueFromAmount(amount))); - if ( (inputsum= AddCClibInputs(cp,mtx,roguepk,3*txfee,16,cp->unspendableCCaddr)) >= 3*txfee ) + rogue_univalue(result,"newgame",maxplayers,buyin); + required = (3*txfee + maxplayers*ROGUE_REGISTRATIONSIZE); + if ( (inputsum= AddCClibInputs(cp,mtx,roguepk,required,16,cp->unspendableCCaddr)) >= required ) { - mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,roguepk)); - mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,mypk)); - if ( (change= inputsum-3*txfee) >= txfee ) + mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,roguepk)); // for highlander TCBOO creation + mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,roguepk)); // for highlander TCBOO used + for (i=0; ievalcode,ROGUE_REGISTRATIONSIZE,roguepk,roguepk)); + if ( (change= inputsum - required) >= txfee ) mtx.vout.push_back(MakeCC1vout(cp->evalcode,change,roguepk)); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_newgameopret(amount)); - if ( rawtx.size() > 0 ) - { - CTransaction tx; - result.push_back(Pair("hex",rawtx)); - if ( DecodeHexTx(tx,rawtx) != 0 ) - result.push_back(Pair("txid",tx.GetHash().ToString())); - } else result.push_back(Pair("error","couldnt finalize CCtx")); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_newgameopret(amount,maxplayers)); + return(rogue_rawtxresult(result,rawtx,0)); } + else return(cclib_error(result,"illegal maxplayers")); return(result); } +UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); std::vector playerdata; uint256 playertxid,origplayergame;std::vector playerdata; int32_t n; + result.push_back(Pair("result","success")); + rogue_univalue(result,"playerinfo",-1,-1); + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n > 0 ) + { + UniValue pobj(UniValue:VOBJ); + playertxid = jbits256(jitem(params,0),0); + if ( rogue_playerdata(origplayergame,playerdata,playertxid) < 0 ) + return(cclib_error(result,"invalid playerdata")); + result.push_back(Pair("rogue",rogue_playerobj(pobj,playerdata))); + } else return(cclib_error(result,"no playertxid")); + return(result); + } else return(cclib_error(result,"couldnt reparse params")); +} + UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { + // vin0 -> ROGUE_REGISTRATIONSIZE 1of2 registration baton from creategame + // vin1 -> optional nonfungible character vout @ + // vin2 -> original creation TCBOO playerdata used + // vin3+ -> buyin + // vout0 -> keystrokes/completion baton + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + UniValue result(UniValue::VOBJ); uint256 gametxid,playertxid,hashBlock; int32_t maxplayers,n,numvouts; int64_t inputsum,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx; std::vector playerdata; + if ( txfee == 0 ) + txfee = 10000; + mypk = pubkey2pk(Mypubkey()); + roguepk = GetUnspendable(cp,0); + rogue_univalue(result,"register",-1,-1); + playertxid = zeroid; + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n > 0 ) + { + gametxid = jbits256(jitem(params,0),0); + if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,gametxid) == 0 ) + { + if ( n > 1 && maxplayers > 1 ) + { + playertxid = jbits256(jitem(params,0),0); + if ( rogue_playerdata(origplayergame,playerdata,playertxid) < 0 ) + return(cclib_error(result,"couldnt extract valid playerdata")); + } + rogue_univalue(result,0,maxplayers,buyin); + if ( (inputsum= rogue_registrationbaton(mtx,gametxid,tx,maxplayers)) != ROGUE_REGISTRATIONSIZE ) + return(cclib_error(result,"couldnt find available registration baton")); + else if ( playertxid != zeroid && rogue_playerdataspend(mtx,playertxid,origplayergame) < 0 ) + return(cclib_error(result,"couldnt find playerdata to spend")); + else if ( buyin > 0 && AddNormalInputs(mtx,mypk,buyin,64) < buyin ) + return(cclib_error(result,"couldnt find enough normal funds for buyin")); + mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,inputsum-txfee,roguepk,mypk)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_registeropret(gametxid,playertxid)); + return(rogue_rawtxresult(result,rawtx,0)); + } else return(cclib_error(result,"invalid gametxid")); + } else return(cclib_error(result,"no gametxid")); + } else return(cclib_error(result,"couldnt reparse params")); +} + +UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + // vin0 -> baton from registration or previous keystrokes + // vout0 -> new baton + // opret -> user input chars + // being killed should auto broadcast (possible to be suppressed?) + // respawn to be prevented by including timestamps + int32_t nextheight = komodo_nextheight(); + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(),nextheight); + UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr; + if ( txfee == 0 ) + txfee = 10000; + rogue_univalue(result,"keystrokes",-1,-1); + if ( (params= cclib_reparse(&n,params)) != 0 && n == 2 && (keystrokestr= jstr(jitem(params,1),0)) != 0 ) + { + gametxid = jbits256(jitem(params,0),0); + keystrokes = ParseHex(keystrokestr); + mypk = pubkey2pk(Mypubkey()); + roguepk = GetUnspendable(cp,0); + txout = MakeCC1of2vout(cp->evalcode,0,roguepk,mypk); + if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,gametxid) == 0 ) + { + if ( rogue_findbaton(playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,txout.scriptPubKey) == 0 ) + { + if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) + { + mtx.vin.push_back(batontxid,batonvout,CScript()); + mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,batonvalue-txfee,roguepk,mypk)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_keystrokesopret(gametxid,batontxid,mypk,keystrokes)); + return(rogue_rawtxresult(result,rawtx,1)); + } else return(cclib_error(result,"keystrokes tx was too late")); + } else return(cclib_error(result,"couldnt find batontxid")); + } else return(cclib_error(result,"invalid gametxid")); + } else return(cclib_error(result,"couldnt reparse params")); +} + +UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + //vin0 -> highlander vout from creategame TCBOO + //vin1 -> keystrokes baton of completed game, must be last to quit or first to win, only spent registration batons matter. If more than 60 blocks since last keystrokes, it is forfeit + //vins2+ -> rest of unspent registration utxo so all newgame vouts are spent + //vout0 -> nonfungible character with pack @ + //vout1 -> 1% ingame gold and all the buyins CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); UniValue result(UniValue::VOBJ); - return(result); -} - -UniValue rogue_progress(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - return(result); -} - -UniValue rogue_claimwin(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - return(result); -} - -UniValue rogue_saveandquit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - return(result); -} - -UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - return(result); -} - -UniValue rogue_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); int32_t ht,numvouts; char CCaddr[64],str[65],*txidstr; uint256 txid,hashBlock; CTransaction tx; uint64_t seed; int64_t buyin; CBlockIndex *pindex; - if ( params != 0 ) - { - if ( (txidstr= jprint(params,0)) != 0 ) - { - if ( txidstr[0] == '"' && txidstr[strlen(txidstr)-1] == '"' ) - { - txidstr[strlen(txidstr)-1] = 0; - txidstr++; - } - //printf("params -> (%s)\n",txidstr); - decode_hex((uint8_t *)&txid,32,txidstr); - txid = revuint256(txid); - result.push_back(Pair("txid",txid.GetHex())); - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) - { - if ( rogue_newgameopreturndecode(buyin,tx.vout[numvouts-1].scriptPubKey) == 'G' ) - { - result.push_back(Pair("result","success")); - if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) - { - ht = pindex->GetHeight(); - result.push_back(Pair("height",ht)); - result.push_back(Pair("start",ht+ROGUE_REGISTRATION)); - if ( komodo_nextheight() > ht+ROGUE_REGISTRATION ) - { - if ( (pindex= komodo_chainactive(ht+ROGUE_REGISTRATION)) != 0 ) - { - hashBlock = pindex->GetBlockHash(); - result.push_back(Pair("starthash",hashBlock.ToString().c_str())); - memcpy(&seed,&hashBlock,sizeof(seed)); - seed &= (1LL << 62) - 1; - result.push_back(Pair("seed",(int64_t)seed)); - } - } - } - Getscriptaddress(CCaddr,tx.vout[1].scriptPubKey); - result.push_back(Pair("rogueaddr",CCaddr)); - result.push_back(Pair("buyin",ValueFromAmount(buyin))); - } - else - { - result.push_back(Pair("result","error")); - result.push_back(Pair("error","couldnt extract rogue_generate opreturn")); - } - } - else - { - result.push_back(Pair("result","error")); - result.push_back(Pair("error","couldnt find txid")); - } - } - } - else - { - result.push_back(Pair("result","error")); - result.push_back(Pair("error","missing txid in params")); - } + if ( txfee == 0 ) + txfee = 10000; + // make sure no highlander and it is an actual ingame win + result.push_back(Pair("result","success")); result.push_back(Pair("name","rogue")); - result.push_back(Pair("method","txidinfo")); + result.push_back(Pair("method","highlander")); + return(result); +} + +UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + // detect if last to bailout + // vin0 -> kestrokes baton of completed game with Q + // vout0 -> 1% ingame gold + // get any playerdata, get all keystrokes, replay game and compare final state + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + UniValue result(UniValue::VOBJ); + if ( txfee == 0 ) + txfee = 10000; + // make sure no highlander yet + result.push_back(Pair("result","success")); + result.push_back(Pair("name","rogue")); + result.push_back(Pair("method","bailout")); + return(result); +} + +UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; + result.push_back(Pair("name","rogue")); + result.push_back(Pair("method","gameinfo")); + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n > 0 ) + { + txid = jbits256(jitem(params,0),0); + result.push_back(Pair("txid",txid.GetHex())); + if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,txid) == 0 ) + { + result.push_back(Pair("result","success")); + rogue_gamefields(result,maxplayers,buyin); + for (i=0; i > unspentOutputs; roguepk = GetUnspendable(cp,0); GetCCaddress(cp,coinaddr,roguepk); @@ -247,189 +618,14 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) txid = it->first.txhash; vout = (int32_t)it->first.index; //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); - if ( it->second.satoshis != txfee || vout != 0 ) + if ( it->second.satoshis != txfee || vout != 0 ) // reject any that are not highlander markers continue; - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) - { - if ( (nValue= IsCClibvout(cp,tx,vout,coinaddr)) == txfee && myIsutxo_spentinmempool(txid,vout) == 0 ) - { - if ( rogue_newgameopreturndecode(amount,tx.vout[numvouts-1].scriptPubKey) == 'G' ) - { - UniValue obj(UniValue::VOBJ); - if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) - { - ht = pindex->GetHeight(); - obj.push_back(Pair("height",ht)); - obj.push_back(Pair("start",ht+ROGUE_REGISTRATION)); - if ( komodo_nextheight() > ht+ROGUE_REGISTRATION ) - { - if ( (pindex= komodo_chainactive(ht+ROGUE_REGISTRATION)) != 0 ) - { - hashBlock = pindex->GetBlockHash(); - obj.push_back(Pair("starthash",hashBlock.ToString().c_str())); - memcpy(&seed,&hashBlock,sizeof(seed)); - seed &= (1LL << 62) - 1; - obj.push_back(Pair("seed",(int64_t)seed)); - } - } - } - obj.push_back(Pair("buyin",ValueFromAmount(amount))); - obj.push_back(Pair("txid",txid.GetHex())); - a.push_back(obj); - total += amount; - } - } - } + if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,txid) == 0 ) + a.push_back(txid.GetHex()); } result.push_back(Pair("result","success")); - result.push_back(Pair("name","rogue")); - result.push_back(Pair("method","pending")); + rogue_univalue(result,"pending",-1,-1); result.push_back(Pair("pending",a)); result.push_back(Pair("numpending",a.size())); - result.push_back(Pair("total",ValueFromAmount(total))); return(result); } - -#ifdef notyest -UniValue rogue_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); int32_t i,j,good,ind,n,numvouts; uint256 txid; char *jsonstr,*newstr,*txidstr,coinaddr[64],checkaddr[64],CCaddr[64],*solution=0,unsolved[82]; CPubKey pk,mypk; uint8_t vals9[9][9],priv32[32],pub33[33]; uint32_t timestamps[81]; uint64_t balance,inputsum; std::string rawtx; CTransaction tx; uint256 hashBlock; - mypk = pubkey2pk(Mypubkey()); - memset(timestamps,0,sizeof(timestamps)); - result.push_back(Pair("name","rogue")); - result.push_back(Pair("method","solution")); - good = 0; - if ( params != 0 ) - { - if ( (jsonstr= jprint(params,0)) != 0 ) - { - if ( jsonstr[0] == '"' && jsonstr[strlen(jsonstr)-1] == '"' ) - { - jsonstr[strlen(jsonstr)-1] = 0; - jsonstr++; - } - newstr = (char *)malloc(strlen(jsonstr)+1); - for (i=j=0; jsonstr[i]!=0; i++) - { - if ( jsonstr[i] == '%' && jsonstr[i+1] == '2' && jsonstr[i+2] == '2' ) - { - newstr[j++] = '"'; - i += 2; - } else newstr[j++] = jsonstr[i]; - } - newstr[j] = 0; - params = cJSON_Parse(newstr); - } else params = 0; - if ( params != 0 ) - { - if ( (n= cJSON_GetArraySize(params)) > 2 && n <= (sizeof(timestamps)/sizeof(*timestamps))+2 ) - { - for (i=2; i '9' ) - { - result.push_back(Pair("result","error")); - result.push_back(Pair("error","illegal solution")); - return(result); - } - vals9[i][j] = solution[ind++] - '0'; - } - rogue_privkey(priv32,vals9); - priv2addr(coinaddr,pub33,priv32); - pk = buf2pk(pub33); - GetCCaddress(cp,CCaddr,pk); - result.push_back(Pair("rogueaddr",CCaddr)); - balance = CCaddress_balance(CCaddr); - result.push_back(Pair("amount",ValueFromAmount(balance))); - if ( rogue_captcha(1,timestamps,komodo_nextheight()) < 0 ) - { - result.push_back(Pair("result","error")); - result.push_back(Pair("error","captcha failure")); - return(result); - } - else - { - if ( (txidstr= jstri(params,0)) != 0 ) - { - decode_hex((uint8_t *)&txid,32,txidstr); - txid = revuint256(txid); - result.push_back(Pair("txid",txid.GetHex())); - if ( CCgettxout(txid,0,1) < 0 ) - result.push_back(Pair("error","already solved")); - else if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) - { - Getscriptaddress(checkaddr,tx.vout[1].scriptPubKey); - if ( strcmp(checkaddr,CCaddr) != 0 ) - { - result.push_back(Pair("result","error")); - result.push_back(Pair("error","wrong solution")); - result.push_back(Pair("yours",CCaddr)); - return(result); - } - if ( rogue_genopreturndecode(unsolved,tx.vout[numvouts-1].scriptPubKey) == 'G' ) - { - for (i=0; i<81; i++) - { - if ( unsolved[i] < '1' || unsolved[i] > '9') - continue; - else if ( unsolved[i] != solution[i] ) - { - printf("i.%d [%c] != [%c]\n",i,unsolved[i],solution[i]); - result.push_back(Pair("error","wrong rogue solved")); - break; - } - } - if ( i == 81 ) - good = 1; - } else result.push_back(Pair("error","cant decode rogue")); - } else result.push_back(Pair("error","couldnt find rogue")); - } - if ( good != 0 ) - { - mtx.vin.push_back(CTxIn(txid,0,CScript())); - if ( (inputsum= AddCClibInputs(cp,mtx,pk,balance,16,CCaddr)) >= balance ) - { - mtx.vout.push_back(CTxOut(balance,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); - CCaddr2set(cp,cp->evalcode,pk,priv32,CCaddr); - rawtx = FinalizeCCTx(0,cp,mtx,pubkey2pk(Mypubkey()),txfee,rogue_solutionopret(solution,timestamps)); - if ( rawtx.size() > 0 ) - { - result.push_back(Pair("result","success")); - result.push_back(Pair("hex",rawtx)); - } - else result.push_back(Pair("error","couldnt finalize CCtx")); - } else result.push_back(Pair("error","couldnt find funds in solution address")); - } - } - } - } - else - { - printf("n.%d params.(%s)\n",n,jprint(params,0)); - result.push_back(Pair("error","couldnt get all params")); - } - return(result); - } - else - { - result.push_back(Pair("result","error")); - result.push_back(Pair("error","couldnt parse parameters")); - result.push_back(Pair("parameters",newstr)); - return(result); - } - } - result.push_back(Pair("result","error")); - result.push_back(Pair("error","missing parameters")); - return(result); -} -#endif - diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 7cff6b280..7571d22e4 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2782,7 +2782,7 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) continue; if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) { - if ( (nValue= IsCClibvout(cp,tx,vout,coinaddr)) == txfee && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( (nValue= IsCClibvout(cp,tx,vout,coinaddr)) == txfee && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { if ( sudoku_genopreturndecode(unsolved,tx.vout[numvouts-1].scriptPubKey) == 'G' ) { @@ -2801,7 +2801,7 @@ UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("name","sudoku")); result.push_back(Pair("method","pending")); result.push_back(Pair("pending",a)); - result.push_back(Pair("numpending",a.size())); + result.push_back(Pair("numpending",(int64_t)a.size())); result.push_back(Pair("total",ValueFromAmount(total))); return(result); } @@ -2817,28 +2817,9 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params good = 0; if ( params != 0 ) { - if ( (jsonstr= jprint(params,0)) != 0 ) + if ( (params= cclib_reparse(&n,params)) != 0 ) { - if ( jsonstr[0] == '"' && jsonstr[strlen(jsonstr)-1] == '"' ) - { - jsonstr[strlen(jsonstr)-1] = 0; - jsonstr++; - } - newstr = (char *)malloc(strlen(jsonstr)+1); - for (i=j=0; jsonstr[i]!=0; i++) - { - if ( jsonstr[i] == '%' && jsonstr[i+1] == '2' && jsonstr[i+2] == '2' ) - { - newstr[j++] = '"'; - i += 2; - } else newstr[j++] = jsonstr[i]; - } - newstr[j] = 0; - params = cJSON_Parse(newstr); - } else params = 0; - if ( params != 0 ) - { - if ( (n= cJSON_GetArraySize(params)) > 2 && n <= (sizeof(timestamps)/sizeof(*timestamps))+2 ) + if ( n > 2 && n <= (sizeof(timestamps)/sizeof(*timestamps))+2 ) { for (i=2; ifirst.index; if ( (nValue= it->second.satoshis) < COIN ) continue; - if ( GetTransaction(txid,tx,hashBlock,true) != 0 && (pindex= komodo_getblockindex(hashBlock)) != 0 && myIsutxo_spentinmempool(txid,vout) == 0 ) + if ( GetTransaction(txid,tx,hashBlock,true) != 0 && (pindex= komodo_getblockindex(hashBlock)) != 0 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,vout) == 0 ) { const CScript &scriptPubKey = tx.vout[vout].scriptPubKey; if ( DecodeMaramaraCoinbaseOpRet(tx.vout[tx.vout.size()-1].scriptPubKey,pk,ht,unlockht) != 0 && pk == mypk ) diff --git a/src/komodo_utils.h b/src/komodo_utils.h index 862f0c6b0..f492173a7 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1782,7 +1782,6 @@ void komodo_args(char *argv0) ASSETCHAINS_MARMARA = GetArg("-ac_marmara",0); if ( ASSETCHAINS_CC != 0 ) { - ASSETCHAINS_CCLIB = GetArg("-ac_cclib",""); Split(GetArg("-ac_ccenable",""), ccenables, 0); for (i=nonz=0; i<0x100; i++) { @@ -1806,6 +1805,15 @@ void komodo_args(char *argv0) ASSETCHAINS_CCDISABLES[ccenables[i] & 0xff] = 0; } } + ASSETCHAINS_CCLIB = GetArg("-ac_cclib",""); + /*if ( ASSETCHAINS_CCLIB.size() > 0 ) + { + for (i=first; i<=last; i++) + { + CLEARBIT(disablebits,i); + ASSETCHAINS_CCDISABLES[i] = 0; + } + }*/ } if ( ASSETCHAINS_BEAMPORT != 0 && ASSETCHAINS_CODAPORT != 0 ) { diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index c210e3099..cf324d1f1 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -380,10 +380,11 @@ UniValue getdifficulty(const UniValue& params, bool fHelp) return GetNetworkDifficulty(); } -bool myIsutxo_spentinmempool(uint256 txid,int32_t vout) +bool myIsutxo_spentinmempool(uint256 &spenttxid,int32_t &spentvini,uint256 txid,int32_t vout) { //char *uint256_str(char *str,uint256); char str[65]; //LOCK(mempool.cs); + int32_t vini = 0; BOOST_FOREACH(const CTxMemPoolEntry &e,mempool.mapTx) { const CTransaction &tx = e.GetTx(); @@ -392,7 +393,12 @@ bool myIsutxo_spentinmempool(uint256 txid,int32_t vout) { //fprintf(stderr,"%s/v%d ",uint256_str(str,txin.prevout.hash),txin.prevout.n); if ( txin.prevout.n == vout && txin.prevout.hash == txid ) + { + spenttxid = hash; + spentvini = vini; return(true); + } + vini++; } //fprintf(stderr,"are vins for %s\n",uint256_str(str,hash)); } diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index f8fe7de20..12a4b47db 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5170,9 +5170,14 @@ int32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits return pwalletMain->VerusStakeTransaction(pBlock, txNew, nBits, hashResult, utxosig, pk); } -int32_t ensure_CCrequirements() +int32_t ensure_CCrequirements(uint8_t evalcode) { CCerror = ""; + if ( ASSETCHAINS_CCDISABLES[evalcode] != 0 || evalcode == EVAL_MARMARA && ASSETCHAINS_MARMARA == 0 ) + { + fprintf(stderr,"evalcode %d disabled\n",evalcode); + return(-1); + } if ( NOTARY_PUBKEY33[0] == 0 ) { fprintf(stderr,"no -pubkey set\n"); @@ -5345,7 +5350,7 @@ UniValue channelsaddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_CHANNELS); if ( fHelp || params.size() != 1 ) throw runtime_error("channelsaddress pubkey\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); pubkey = ParseHex(params[0].get_str().c_str()); return(CCaddress(cp,(char *)"Channels",pubkey)); @@ -5356,7 +5361,7 @@ UniValue cclibaddress(const UniValue& params, bool fHelp) struct CCcontract_info *cp,C; std::vector pubkey; uint8_t evalcode = EVAL_FIRSTUSER; if ( fHelp || params.size() > 2 ) throw runtime_error("cclibaddress [evalcode] [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if ( params.size() >= 1 ) { @@ -5377,7 +5382,7 @@ UniValue cclibinfo(const UniValue& params, bool fHelp) struct CCcontract_info *cp,C; uint8_t evalcode = EVAL_FIRSTUSER; if ( fHelp || params.size() > 0 ) throw runtime_error("cclibinfo\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); cp = CCinit(&C,evalcode); return(CClib_info(cp)); @@ -5388,7 +5393,9 @@ UniValue cclib(const UniValue& params, bool fHelp) struct CCcontract_info *cp,C; char *method; cJSON *jsonparams=0; uint8_t evalcode = EVAL_FIRSTUSER; if ( fHelp || params.size() > 3 ) throw runtime_error("cclib method [evalcode] [JSON params]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ASSETCHAINS_CCLIB.size() == 0 ) + throw runtime_error("no -ac_cclib= specified\n"); + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -5416,7 +5423,7 @@ UniValue oraclesaddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_ORACLES); if ( fHelp || params.size() > 1 ) throw runtime_error("oraclesaddress [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if ( params.size() == 1 ) pubkey = ParseHex(params[0].get_str().c_str()); @@ -5430,7 +5437,7 @@ UniValue pricesaddress(const UniValue& params, bool fHelp) assetscp = CCinit(&C2,EVAL_PRICES); if ( fHelp || params.size() > 1 ) throw runtime_error("pricesaddress [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if ( params.size() == 1 ) pubkey = ParseHex(params[0].get_str().c_str()); @@ -5452,7 +5459,7 @@ UniValue pegsaddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_PEGS); if ( fHelp || params.size() > 1 ) throw runtime_error("pegssaddress [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if ( params.size() == 1 ) pubkey = ParseHex(params[0].get_str().c_str()); @@ -5465,7 +5472,7 @@ UniValue marmaraaddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_MARMARA); if ( fHelp || params.size() > 1 ) throw runtime_error("Marmaraaddress [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if ( params.size() == 1 ) pubkey = ParseHex(params[0].get_str().c_str()); @@ -5478,7 +5485,7 @@ UniValue paymentsaddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_PAYMENTS); if ( fHelp || params.size() > 1 ) throw runtime_error("paymentsaddress [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if ( params.size() == 1 ) pubkey = ParseHex(params[0].get_str().c_str()); @@ -5491,7 +5498,7 @@ UniValue gatewaysaddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_GATEWAYS); if ( fHelp || params.size() > 1 ) throw runtime_error("gatewaysaddress [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if ( params.size() == 1 ) pubkey = ParseHex(params[0].get_str().c_str()); @@ -5504,7 +5511,7 @@ UniValue heiraddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_HEIR); if ( fHelp || params.size() > 1 ) throw runtime_error("heiraddress pubkey\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); pubkey = ParseHex(params[0].get_str().c_str()); return(CCaddress(cp,(char *)"Heir",pubkey)); @@ -5516,7 +5523,7 @@ UniValue lottoaddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_LOTTO); if ( fHelp || params.size() > 1 ) throw runtime_error("lottoaddress [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if ( params.size() == 1 ) pubkey = ParseHex(params[0].get_str().c_str()); @@ -5529,7 +5536,7 @@ UniValue FSMaddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_FSM); if ( fHelp || params.size() > 1 ) throw runtime_error("FSMaddress [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if ( params.size() == 1 ) pubkey = ParseHex(params[0].get_str().c_str()); @@ -5542,7 +5549,7 @@ UniValue auctionaddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_AUCTION); if ( fHelp || params.size() > 1 ) throw runtime_error("auctionaddress [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if ( params.size() == 1 ) pubkey = ParseHex(params[0].get_str().c_str()); @@ -5555,7 +5562,7 @@ UniValue diceaddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_DICE); if ( fHelp || params.size() > 1 ) throw runtime_error("diceaddress [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if ( params.size() == 1 ) pubkey = ParseHex(params[0].get_str().c_str()); @@ -5569,7 +5576,7 @@ UniValue faucetaddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_FAUCET); if ( fHelp || params.size() > 1 ) throw runtime_error("faucetaddress [pubkey]\n"); - error = ensure_CCrequirements(); + error = ensure_CCrequirements(0); if ( error < 0 ) throw runtime_error(strprintf("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet. ERR=%d\n", error)); if ( params.size() == 1 ) @@ -5583,7 +5590,7 @@ UniValue rewardsaddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_REWARDS); if ( fHelp || params.size() > 1 ) throw runtime_error("rewardsaddress [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if ( params.size() == 1 ) pubkey = ParseHex(params[0].get_str().c_str()); @@ -5596,7 +5603,7 @@ UniValue assetsaddress(const UniValue& params, bool fHelp) cp = CCinit(&C, EVAL_ASSETS); if (fHelp || params.size() > 1) throw runtime_error("assetsaddress [pubkey]\n"); - if (ensure_CCrequirements() < 0) + if (ensure_CCrequirements(0) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if (params.size() == 1) pubkey = ParseHex(params[0].get_str().c_str()); @@ -5609,7 +5616,7 @@ UniValue tokenaddress(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_TOKENS); if ( fHelp || params.size() > 1 ) throw runtime_error("tokenaddress [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(0) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); if ( params.size() == 1 ) pubkey = ParseHex(params[0].get_str().c_str()); @@ -5625,7 +5632,7 @@ UniValue marmara_poolpayout(const UniValue& params, bool fHelp) //marmarapoolpayout 0 2 '[["024131032ed90941e714db8e6dd176fe5a86c9d873d279edecf005c06f773da686",1000]]' throw runtime_error("marmarapoolpayout perc firstheight \"[[\\\"pubkey\\\":shares], ...]\"\n"); } - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_MARMARA) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -5645,7 +5652,7 @@ UniValue marmara_receive(const UniValue& params, bool fHelp) // after marmarareceive 039433dc3749aece1bd568f374a45da3b0bc6856990d7da3cd175399577940a775 7.5 MARMARA 1168 d72d87aa0d50436de695c93e2bf3d7273c63c92ef6307913aa01a6ee6a16548b throw runtime_error("marmarareceive senderpk amount currency matures batontxid\n"); } - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_MARMARA) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -5676,7 +5683,7 @@ UniValue marmara_issue(const UniValue& params, bool fHelp) throw runtime_error("marmaraissue receiverpk amount currency matures approvaltxid\n"); } - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_MARMARA) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -5701,7 +5708,7 @@ UniValue marmara_transfer(const UniValue& params, bool fHelp) // marmaratransfer 028076d42eb20efc10007fafb5ca66a2052523c0d2221e607adf958d1a332159f6 7.5 MARMARA 1168 1506c774e4b2804a6e25260920840f4cfca8d1fb400e69fe6b74b8e593dbedc5 throw runtime_error("marmaratransfer receiverpk amount currency matures approvaltxid\n"); } - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_MARMARA) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); receiverpub = ParseHex(params[0].get_str().c_str()); if (receiverpub.size()!= 33) @@ -5727,7 +5734,7 @@ UniValue marmara_info(const UniValue& params, bool fHelp) { throw runtime_error("marmarainfo firstheight lastheight minamount maxamount [currency issuerpk]\n"); } - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_MARMARA) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -5759,7 +5766,7 @@ UniValue marmara_creditloop(const UniValue& params, bool fHelp) // marmaracreditloop 010ff7f9256cefe3b5dee3d72c0eeae9fc6f34884e6f32ffe5b60916df54a9be throw runtime_error("marmaracreditloop txid\n"); } - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_MARMARA) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -5777,7 +5784,7 @@ UniValue marmara_settlement(const UniValue& params, bool fHelp) // marmarasettlement ff3e259869196f3da9b5ea3f9e088a76c4fc063cf36ab586b652e121d441a603 throw runtime_error("marmarasettlement batontxid\n"); } - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_MARMARA) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -5806,7 +5813,7 @@ UniValue channelslist(const UniValue& params, bool fHelp) { if ( fHelp || params.size() > 0 ) throw runtime_error("channelsinfo\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_MARMARA) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -5818,7 +5825,7 @@ UniValue channelsinfo(const UniValue& params, bool fHelp) uint256 opentxid; if ( fHelp || params.size() > 1 ) throw runtime_error("channelsinfo [opentxid]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_CHANNELS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -5836,7 +5843,7 @@ UniValue channelsopen(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_CHANNELS); if ( fHelp || params.size() < 3 || params.size() > 4) throw runtime_error("channelsopen destpubkey numpayments payment\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_CHANNELS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -5877,7 +5884,7 @@ UniValue channelspayment(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_CHANNELS); if ( fHelp || params.size() < 2 || params.size() >3 ) throw runtime_error("channelspayment opentxid amount [secret]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_CHANNELS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -5907,7 +5914,7 @@ UniValue channelsclose(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_CHANNELS); if ( fHelp || params.size() != 1 ) throw runtime_error("channelsclose opentxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_CHANNELS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -5927,7 +5934,7 @@ UniValue channelsrefund(const UniValue& params, bool fHelp) cp = CCinit(&C,EVAL_CHANNELS); if ( fHelp || params.size() != 2 ) throw runtime_error("channelsrefund opentxid closetxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_CHANNELS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -5947,7 +5954,7 @@ UniValue rewardscreatefunding(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); char *name; int64_t funds,APR,minseconds,maxseconds,mindeposit; std::string hex; if ( fHelp || params.size() > 6 || params.size() < 2 ) throw runtime_error("rewardscreatefunding name amount APR mindays maxdays mindeposit\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_REWARDS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6016,7 +6023,7 @@ UniValue rewardslock(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); char *name; uint256 fundingtxid; int64_t amount; std::string hex; if ( fHelp || params.size() != 3 ) throw runtime_error("rewardslock name fundingtxid amount\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_REWARDS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6046,7 +6053,7 @@ UniValue rewardsaddfunding(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); char *name; uint256 fundingtxid; int64_t amount; std::string hex; if ( fHelp || params.size() != 3 ) throw runtime_error("rewardsaddfunding name fundingtxid amount\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_REWARDS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6081,7 +6088,7 @@ UniValue rewardsunlock(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string hex; char *name; uint256 fundingtxid,txid; if ( fHelp || params.size() > 3 || params.size() < 2 ) throw runtime_error("rewardsunlock name fundingtxid [txid]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_REWARDS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6109,7 +6116,7 @@ UniValue rewardslist(const UniValue& params, bool fHelp) { if ( fHelp || params.size() > 0 ) throw runtime_error("rewardslist\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_REWARDS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6121,7 +6128,7 @@ UniValue rewardsinfo(const UniValue& params, bool fHelp) uint256 fundingtxid; if ( fHelp || params.size() != 1 ) throw runtime_error("rewardsinfo fundingtxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_REWARDS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6133,7 +6140,7 @@ UniValue gatewayslist(const UniValue& params, bool fHelp) { if ( fHelp || params.size() > 0 ) throw runtime_error("gatewayslist\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6145,7 +6152,7 @@ UniValue gatewaysinfo(const UniValue& params, bool fHelp) uint256 txid; if ( fHelp || params.size() != 1 ) throw runtime_error("gatewaysinfo bindtxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6158,7 +6165,7 @@ UniValue gatewaysbind(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); uint256 tokenid,oracletxid; int32_t i; int64_t totalsupply; std::vector pubkeys; uint8_t M,N; std::string hex,coin; std::vector pubkey; if ( fHelp || params.size() < 6 ) throw runtime_error("gatewaysbind tokenid oracletxid coin tokensupply M N pubkey(s)\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6194,7 +6201,7 @@ UniValue gatewaysdeposit(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); int32_t i,claimvout,height; int64_t amount; std::string hex,coin,deposithex; uint256 bindtxid,cointxid; std::vectorproof,destpub,pubkey; if ( fHelp || params.size() != 9 ) throw runtime_error("gatewaysdeposit bindtxid height coin cointxid claimvout deposithex proof destpub amount\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6227,7 +6234,7 @@ UniValue gatewaysclaim(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string hex,coin; uint256 bindtxid,deposittxid; std::vectordestpub; int64_t amount; if ( fHelp || params.size() != 5 ) throw runtime_error("gatewaysclaim bindtxid coin deposittxid destpub amount\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6253,7 +6260,7 @@ UniValue gatewayswithdraw(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); uint256 bindtxid; int64_t amount; std::string hex,coin; std::vector withdrawpub; if ( fHelp || params.size() != 4 ) throw runtime_error("gatewayswithdraw bindtxid coin withdrawpub amount\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6278,7 +6285,7 @@ UniValue gatewayspartialsign(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string coin,parthex,hex; uint256 txid; if ( fHelp || params.size() != 3 ) throw runtime_error("gatewayspartialsign txidaddr refcoin hex\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6299,7 +6306,7 @@ UniValue gatewayscompletesigning(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); uint256 withdrawtxid; std::string txhex,hex,coin; if ( fHelp || params.size() != 3 ) throw runtime_error("gatewayscompletesigning withdrawtxid coin hex\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6321,7 +6328,7 @@ UniValue gatewaysmarkdone(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); uint256 completetxid; std::string hex,coin; if ( fHelp || params.size() != 2 ) throw runtime_error("gatewaysmarkdone completesigningtx coin\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6342,7 +6349,7 @@ UniValue gatewayspendingdeposits(const UniValue& params, bool fHelp) uint256 bindtxid; std::string coin; if ( fHelp || params.size() != 2 ) throw runtime_error("gatewayspendingdeposits bindtxid coin\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6356,7 +6363,7 @@ UniValue gatewayspendingwithdraws(const UniValue& params, bool fHelp) uint256 bindtxid; std::string coin; if ( fHelp || params.size() != 2 ) throw runtime_error("gatewayspendingwithdraws bindtxid coin\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6370,7 +6377,7 @@ UniValue gatewaysprocessed(const UniValue& params, bool fHelp) uint256 bindtxid; std::string coin; if ( fHelp || params.size() != 2 ) throw runtime_error("gatewaysprocessed bindtxid coin\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6383,7 +6390,7 @@ UniValue oracleslist(const UniValue& params, bool fHelp) { if ( fHelp || params.size() > 0 ) throw runtime_error("oracleslist\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ORACLES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6395,7 +6402,7 @@ UniValue oraclesinfo(const UniValue& params, bool fHelp) uint256 txid; if ( fHelp || params.size() != 1 ) throw runtime_error("oraclesinfo oracletxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ORACLES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6408,7 +6415,7 @@ UniValue oraclesregister(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); uint256 txid; int64_t datafee; std::string hex; if ( fHelp || params.size() != 2 ) throw runtime_error("oraclesregister oracletxid datafee\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ORACLES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6430,7 +6437,7 @@ UniValue oraclessubscribe(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); uint256 txid; int64_t amount; std::string hex; std::vector pubkey; if ( fHelp || params.size() != 3 ) throw runtime_error("oraclessubscribe oracletxid publisher amount\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ORACLES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6452,7 +6459,7 @@ UniValue oraclessamples(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); uint256 txid,batontxid; int32_t num; if ( fHelp || params.size() != 3 ) throw runtime_error("oraclessamples oracletxid batonutxo num\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ORACLES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6467,7 +6474,7 @@ UniValue oraclesdata(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); uint256 txid; std::vector data; std::string hex; if ( fHelp || params.size() != 2 ) throw runtime_error("oraclesdata oracletxid hexstr\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ORACLES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6488,7 +6495,7 @@ UniValue oraclescreate(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string name,description,format,hex; if ( fHelp || params.size() != 3 ) throw runtime_error("oraclescreate name description format\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ORACLES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6525,7 +6532,7 @@ UniValue FSMcreate(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string name,states,hex; if ( fHelp || params.size() != 2 ) throw runtime_error("FSMcreate name states\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_FSM) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6545,7 +6552,7 @@ UniValue FSMlist(const UniValue& params, bool fHelp) uint256 tokenid; if ( fHelp || params.size() > 0 ) throw runtime_error("FSMlist\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_FSM) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); return(FSMList()); } @@ -6555,7 +6562,7 @@ UniValue FSMinfo(const UniValue& params, bool fHelp) uint256 FSMtxid; if ( fHelp || params.size() != 1 ) throw runtime_error("FSMinfo fundingtxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_FSM) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); FSMtxid = Parseuint256((char *)params[0].get_str().c_str()); return(FSMInfo(FSMtxid)); @@ -6566,7 +6573,7 @@ UniValue faucetinfo(const UniValue& params, bool fHelp) uint256 fundingtxid; if ( fHelp || params.size() != 0 ) throw runtime_error("faucetinfo\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_FAUCET) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); return(FaucetInfo()); } @@ -6576,7 +6583,7 @@ UniValue faucetfund(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); int64_t funds; std::string hex; if ( fHelp || params.size() > 1 ) throw runtime_error("faucetfund amount\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_FAUCET) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6597,7 +6604,7 @@ UniValue faucetget(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string hex; if ( fHelp || params.size() > 0 ) throw runtime_error("faucetget\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_FAUCET) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6613,7 +6620,7 @@ UniValue priceslist(const UniValue& params, bool fHelp) { if ( fHelp || params.size() > 0 ) throw runtime_error("priceslist\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_PRICES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); return(PricesList()); } @@ -6623,7 +6630,7 @@ UniValue pricesinfo(const UniValue& params, bool fHelp) uint256 fundingtxid; if ( fHelp || params.size() != 1 ) throw runtime_error("pricesinfo fundingtxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_PRICES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); fundingtxid = Parseuint256((char *)params[0].get_str().c_str()); return(PricesInfo(fundingtxid)); @@ -6634,7 +6641,7 @@ UniValue pricescreate(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); uint64_t mode; int64_t funding; int32_t i,n,margin,maxleverage; std::string hex; uint256 oracletxid,longtoken,shorttoken,bettoken; std::vector pubkeys; std::vectorpubkey; if ( fHelp || params.size() < 8 ) throw runtime_error("pricescreate bettoken oracletxid margin mode longtoken shorttoken maxleverage funding N [pubkeys]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_PRICES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6675,7 +6682,7 @@ UniValue pricesaddfunding(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string hex; uint256 fundingtxid,bettoken; int64_t amount; if ( fHelp || params.size() != 3 ) throw runtime_error("pricesaddfunding fundingtxid bettoken amount\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_PRICES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6700,7 +6707,7 @@ UniValue pricesbet(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string hex; uint256 fundingtxid,bettoken; int64_t amount; int32_t leverage; if ( fHelp || params.size() != 4 ) throw runtime_error("pricesbet fundingtxid bettoken amount leverage\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_PRICES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6726,7 +6733,7 @@ UniValue pricesstatus(const UniValue& params, bool fHelp) uint256 fundingtxid,bettxid,bettoken; if ( fHelp || params.size() != 3 ) throw runtime_error("pricesstatus fundingtxid bettoken bettxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_PRICES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); fundingtxid = Parseuint256((char *)params[0].get_str().c_str()); bettoken = Parseuint256((char *)params[1].get_str().c_str()); @@ -6739,7 +6746,7 @@ UniValue pricesfinish(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); uint256 fundingtxid,bettxid,bettoken; std::string hex; if ( fHelp || params.size() != 3 ) throw runtime_error("pricesfinish fundingtxid bettoken bettxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_PRICES) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6764,7 +6771,7 @@ UniValue dicefund(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); int64_t funds,minbet,maxbet,maxodds,timeoutblocks; std::string hex; char *name; if ( fHelp || params.size() != 6 ) throw runtime_error("dicefund name funds minbet maxbet maxodds timeoutblocks\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_DICE) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6797,7 +6804,7 @@ UniValue diceaddfunds(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); char *name; uint256 fundingtxid; int64_t amount; std::string hex; if ( fHelp || params.size() != 3 ) throw runtime_error("diceaddfunds name fundingtxid amount\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_DICE) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6825,7 +6832,7 @@ UniValue dicebet(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string hex,error; uint256 fundingtxid; int64_t amount,odds; char *name; if ( fHelp || params.size() != 4 ) throw runtime_error("dicebet name fundingtxid amount odds\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_DICE) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6857,7 +6864,7 @@ UniValue dicefinish(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); uint8_t funcid; char *name; uint256 entropyused,fundingtxid,bettxid; std::string hex; int32_t r,entropyvout; if ( fHelp || params.size() != 3 ) throw runtime_error("dicefinish name fundingtxid bettxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_DICE) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6892,7 +6899,7 @@ UniValue dicestatus(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); char *name; uint256 fundingtxid,bettxid; std::string status,error; double winnings; if ( fHelp || (params.size() != 2 && params.size() != 3) ) throw runtime_error("dicestatus name fundingtxid bettxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_DICE) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6940,7 +6947,7 @@ UniValue dicelist(const UniValue& params, bool fHelp) { if ( fHelp || params.size() > 0 ) throw runtime_error("dicelist\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_DICE) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); return(DiceList()); } @@ -6950,7 +6957,7 @@ UniValue diceinfo(const UniValue& params, bool fHelp) uint256 fundingtxid; if ( fHelp || params.size() != 1 ) throw runtime_error("diceinfo fundingtxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_DICE) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); fundingtxid = Parseuint256((char *)params[0].get_str().c_str()); return(DiceInfo(fundingtxid)); @@ -6961,7 +6968,7 @@ UniValue tokenlist(const UniValue& params, bool fHelp) uint256 tokenid; if ( fHelp || params.size() > 0 ) throw runtime_error("tokenlist\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); return(TokenList()); } @@ -6971,7 +6978,7 @@ UniValue tokeninfo(const UniValue& params, bool fHelp) uint256 tokenid; if ( fHelp || params.size() != 1 ) throw runtime_error("tokeninfo tokenid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6984,7 +6991,7 @@ UniValue tokenorders(const UniValue& params, bool fHelp) uint256 tokenid; if ( fHelp || params.size() > 1 ) throw runtime_error("tokenorders [tokenid]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7005,7 +7012,7 @@ UniValue tokenbalance(const UniValue& params, bool fHelp) if ( fHelp || params.size() > 2 ) throw runtime_error("tokenbalance tokenid [pubkey]\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); LOCK(cs_main); @@ -7041,7 +7048,7 @@ UniValue tokencreate(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string name,description,hex; uint64_t supply; if ( fHelp || params.size() > 3 || params.size() < 2 ) throw runtime_error("tokencreate name supply description\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7080,7 +7087,7 @@ UniValue tokentransfer(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string hex; int64_t amount; uint256 tokenid; if ( fHelp || params.size() != 3 ) throw runtime_error("tokentransfer tokenid destpubkey amount\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7116,7 +7123,7 @@ UniValue tokenconvert(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string hex; int32_t evalcode; int64_t amount; uint256 tokenid; if ( fHelp || params.size() != 4 ) throw runtime_error("tokenconvert evalcode tokenid pubkey amount\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7157,7 +7164,7 @@ UniValue tokenbid(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); int64_t bidamount,numtokens; std::string hex; double price; uint256 tokenid; if ( fHelp || params.size() != 3 ) throw runtime_error("tokenbid numtokens tokenid price\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7199,7 +7206,7 @@ UniValue tokencancelbid(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string hex; int32_t i; uint256 tokenid,bidtxid; if ( fHelp || params.size() != 2 ) throw runtime_error("tokencancelbid tokenid bidtxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7224,7 +7231,7 @@ UniValue tokenfillbid(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); int64_t fillamount; std::string hex; uint256 tokenid,bidtxid; if ( fHelp || params.size() != 3 ) throw runtime_error("tokenfillbid tokenid bidtxid fillamount\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7256,7 +7263,7 @@ UniValue tokenask(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); int64_t askamount,numtokens; std::string hex; double price; uint256 tokenid; if ( fHelp || params.size() != 3 ) throw runtime_error("tokenask numtokens tokenid price\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7290,7 +7297,7 @@ UniValue tokenswapask(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); int64_t askamount,numtokens; std::string hex; double price; uint256 tokenid,otherid; if ( fHelp || params.size() != 4 ) throw runtime_error("tokenswapask numtokens tokenid otherid price\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7318,7 +7325,7 @@ UniValue tokencancelask(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string hex; int32_t i; uint256 tokenid,asktxid; if ( fHelp || params.size() != 2 ) throw runtime_error("tokencancelask tokenid asktxid\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7343,7 +7350,7 @@ UniValue tokenfillask(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); int64_t fillunits; std::string hex; uint256 tokenid,asktxid; if ( fHelp || params.size() != 3 ) throw runtime_error("tokenfillask tokenid asktxid fillunits\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7383,7 +7390,7 @@ UniValue tokenfillswap(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); int64_t fillunits; std::string hex; uint256 tokenid,otherid,asktxid; if ( fHelp || params.size() != 4 ) throw runtime_error("tokenfillswap tokenid otherid asktxid fillunits\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7464,7 +7471,7 @@ UniValue heirfund(const UniValue& params, bool fHelp) if (fHelp || params.size() != 6 && params.size() != 7) throw runtime_error("heirfund txfee funds heirname heirpubkey inactivitytime memo [tokenid]\n"); - if (ensure_CCrequirements() < 0) + if (ensure_CCrequirements(EVAL_HEIR) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; @@ -7538,7 +7545,7 @@ UniValue heiradd(const UniValue& params, bool fHelp) if (fHelp || params.size() != 3) throw runtime_error("heiradd txfee funds fundingtxid\n"); - if (ensure_CCrequirements() < 0) + if (ensure_CCrequirements(EVAL_HEIR) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; @@ -7572,7 +7579,7 @@ UniValue heirclaim(const UniValue& params, bool fHelp) if (fHelp || params.size() != 3) throw runtime_error("heirclaim txfee funds fundingtxid\n"); - if (ensure_CCrequirements() < 0) + if (ensure_CCrequirements(EVAL_HEIR) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; @@ -7597,7 +7604,7 @@ UniValue heirinfo(const UniValue& params, bool fHelp) if (fHelp || params.size() != 1) throw runtime_error("heirinfo fundingtxid\n"); - // if ( ensure_CCrequirements() < 0 ) + // if ( ensure_CCrequirements(EVAL_HEIR) < 0 ) // throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); fundingtxid = Parseuint256((char*)params[0].get_str().c_str()); @@ -7609,7 +7616,7 @@ UniValue heirlist(const UniValue& params, bool fHelp) if (fHelp || params.size() != 0) throw runtime_error("heirlist\n"); - // if ( ensure_CCrequirements() < 0 ) + // if ( ensure_CCrequirements(EVAL_HEIR) < 0 ) // throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); return (HeirList()); @@ -7718,7 +7725,7 @@ UniValue test_ac(const UniValue& params, bool fHelp) if (fHelp || (params.size() != 4)) throw runtime_error("incorrect params\n"); - if (ensure_CCrequirements() < 0) + if (ensure_CCrequirements(EVAL_HEIR) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); std::vector pubkey1; @@ -7763,7 +7770,7 @@ UniValue test_heirmarker(const UniValue& params, bool fHelp) if (fHelp || (params.size() != 1)) throw runtime_error("incorrect params\n"); - if (ensure_CCrequirements() < 0) + if (ensure_CCrequirements(EVAL_HEIR) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); uint256 fundingtxid = Parseuint256((char *)params[0].get_str().c_str()); From db37d3c6e9b6035ec3576d421a6de0e7ed3c26f8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 19:34:53 -1100 Subject: [PATCH 0318/1145] 0xef --- src/cc/CCMarmara.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/CCMarmara.h b/src/cc/CCMarmara.h index 65269df77..208c370d4 100644 --- a/src/cc/CCMarmara.h +++ b/src/cc/CCMarmara.h @@ -24,6 +24,7 @@ #define MARMARA_MINLOCK (1440 * 3 * 30) #define MARMARA_MAXLOCK (1440 * 24 * 30) #define MARMARA_VINS 16 +#define EVAL_MARMARA 0xef extern uint8_t ASSETCHAINS_MARMARA; uint64_t komodo_block_prg(uint32_t nHeight); From 2465250ba081145b610bfadef536f963b6c3f245 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 19:37:47 -1100 Subject: [PATCH 0319/1145] EVAL_MARMARA --- src/wallet/rpcwallet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 12a4b47db..3fadd3859 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5173,7 +5173,7 @@ int32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits int32_t ensure_CCrequirements(uint8_t evalcode) { CCerror = ""; - if ( ASSETCHAINS_CCDISABLES[evalcode] != 0 || evalcode == EVAL_MARMARA && ASSETCHAINS_MARMARA == 0 ) + if ( ASSETCHAINS_CCDISABLES[evalcode] != 0 || (evalcode == EVAL_MARMARA && ASSETCHAINS_MARMARA == 0) ) { fprintf(stderr,"evalcode %d disabled\n",evalcode); return(-1); From 99ff6ff5ec91b7c2907a8a3f44112ccad4b69f18 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 19:40:19 -1100 Subject: [PATCH 0320/1145] Fix include file --- src/cc/CCMarmara.h | 4 ++-- src/wallet/rpcwallet.cpp | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/cc/CCMarmara.h b/src/cc/CCMarmara.h index 208c370d4..85f9175d1 100644 --- a/src/cc/CCMarmara.h +++ b/src/cc/CCMarmara.h @@ -14,8 +14,8 @@ ******************************************************************************/ -#ifndef CC_TRIGGERS_H -#define CC_TRIGGERS_H +#ifndef CC_MARMARA_H +#define CC_MARMARA_H #include "CCinclude.h" #include "../komodo_cJSON.h" diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 3fadd3859..7523738ca 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -6968,7 +6968,7 @@ UniValue tokenlist(const UniValue& params, bool fHelp) uint256 tokenid; if ( fHelp || params.size() > 0 ) throw runtime_error("tokenlist\n"); - if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) + if ( ensure_CCrequirements(EVAL_TOKENS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); return(TokenList()); } @@ -6978,7 +6978,7 @@ UniValue tokeninfo(const UniValue& params, bool fHelp) uint256 tokenid; if ( fHelp || params.size() != 1 ) throw runtime_error("tokeninfo tokenid\n"); - if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) + if ( ensure_CCrequirements(EVAL_TOKENS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7012,7 +7012,7 @@ UniValue tokenbalance(const UniValue& params, bool fHelp) if ( fHelp || params.size() > 2 ) throw runtime_error("tokenbalance tokenid [pubkey]\n"); - if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) + if ( ensure_CCrequirements(EVAL_TOKENS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); LOCK(cs_main); @@ -7048,7 +7048,7 @@ UniValue tokencreate(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string name,description,hex; uint64_t supply; if ( fHelp || params.size() > 3 || params.size() < 2 ) throw runtime_error("tokencreate name supply description\n"); - if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) + if ( ensure_CCrequirements(EVAL_TOKENS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7087,7 +7087,7 @@ UniValue tokentransfer(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string hex; int64_t amount; uint256 tokenid; if ( fHelp || params.size() != 3 ) throw runtime_error("tokentransfer tokenid destpubkey amount\n"); - if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) + if ( ensure_CCrequirements(EVAL_TOKENS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); From 19cfdd02f9d253062a6d24f78e97bd215b3113fb Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 19:42:21 -1100 Subject: [PATCH 0321/1145] Reorder code --- src/wallet/rpcwallet.cpp | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 7523738ca..8fe4c669a 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5170,6 +5170,21 @@ int32_t verus_staked(CBlock *pBlock, CMutableTransaction &txNew, uint32_t &nBits return pwalletMain->VerusStakeTransaction(pBlock, txNew, nBits, hashResult, utxosig, pk); } + +#include "../cc/CCfaucet.h" +#include "../cc/CCassets.h" +#include "../cc/CCrewards.h" +#include "../cc/CCdice.h" +#include "../cc/CCfsm.h" +#include "../cc/CCauction.h" +#include "../cc/CClotto.h" +#include "../cc/CCchannels.h" +#include "../cc/CCOracles.h" +#include "../cc/CCGateways.h" +#include "../cc/CCPrices.h" +#include "../cc/CCHeir.h" +#include "../cc/CCMarmara.h" + int32_t ensure_CCrequirements(uint8_t evalcode) { CCerror = ""; @@ -5196,20 +5211,6 @@ int32_t ensure_CCrequirements(uint8_t evalcode) else return(0); } -#include "../cc/CCfaucet.h" -#include "../cc/CCassets.h" -#include "../cc/CCrewards.h" -#include "../cc/CCdice.h" -#include "../cc/CCfsm.h" -#include "../cc/CCauction.h" -#include "../cc/CClotto.h" -#include "../cc/CCchannels.h" -#include "../cc/CCOracles.h" -#include "../cc/CCGateways.h" -#include "../cc/CCPrices.h" -#include "../cc/CCHeir.h" -#include "../cc/CCMarmara.h" - UniValue CCaddress(struct CCcontract_info *cp,char *name,std::vector &pubkey) { UniValue result(UniValue::VOBJ); char destaddr[64],str[64]; CPubKey mypk,pk; From 47615e789795095e5c2ff9128fa8e501cd05a0ba Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 19:50:06 -1100 Subject: [PATCH 0322/1145] playerinfo --- src/cc/cclib.cpp | 6 +++--- src/cc/rogue_rpc.cpp | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index aa7a9e1ff..cede1a450 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -112,11 +112,11 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) else if ( strcmp(method,"keystrokes") == 0 ) return(rogue_keystrokes(txfee,cp,params)); else if ( strcmp(method,"bailout") == 0 ) - return(rogue_saveandquit(txfee,cp,params)); + return(rogue_bailout(txfee,cp,params)); else if ( strcmp(method,"highlander") == 0 ) - return(rogue_claimwin(txfee,cp,params)); + return(rogue_highlander(txfee,cp,params)); else if ( strcmp(method,"playerinfo") == 0 ) - return(rogue_claimwin(txfee,cp,params)); + return(rogue_playerinfo(txfee,cp,params)); else { result.push_back(Pair("result","error")); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 4fb850ef0..7aef339f0 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -92,14 +92,14 @@ CScript rogue_registeropret(uint256 gametxid,uint256 playertxid) return(opret); } -CScript rogue_keystrokesopret(uint256 gametxid,uint256 batontxid,CPubKey pk,std::vectorkeystrokes) +CScript rogue_keystrokesopret(uint256 gametxid,uint256 batontxid,CPubKey pk,std::vectorkeystrokes) { CScript opret; uint8_t evalcode = EVAL_ROGUE; opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'K' << gametxid << batontxid << pk << keystrokes); return(opret); } -CScript rogue_highlanderopret(uint256 gametxid,uint256 registertxid,CPubKey pk,std::vectorplayerdata) +CScript rogue_highlanderopret(uint256 gametxid,uint256 registertxid,CPubKey pk,std::vectorplayerdata) { CScript opret; uint8_t evalcode = EVAL_ROGUE; opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'K' << gametxid << registertxid << pk << playerdata); From f3c01d0a81ed08a67558fbc69dd18297f0a4d968 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 19:55:03 -1100 Subject: [PATCH 0323/1145] Syntax --- src/cc/rogue_rpc.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 7aef339f0..ec4e56aee 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -19,7 +19,7 @@ #define ROGUE_REGISTRATION 5 #define ROGUE_REGISTRATIONSIZE (100 * 10000) #define ROGUE_MAXPLAYERS 64 // need to send unused fees back to globalCC address to prevent leeching -#defein ROGUE_MAXKEYSTROKESGAP 60 +#define ROGUE_MAXKEYSTROKESGAP 60 /* the idea is that you creategame and get a txid, you specify the maxplayers and buyin for the game. the tx will have maxplayers of vouts. You must have a non-zero buyin to be able to use a preexisting character. @@ -106,7 +106,7 @@ CScript rogue_highlanderopret(uint256 gametxid,uint256 registertxid,CPubKey pk,s return(opret); } -uint8_t rogue_highlanderopretdecode(uint256 &gametxid,uint256 ®istertxid,CPubKey &pk,std::vector &playerdata,CSript scriptPubKey) +uint8_t rogue_highlanderopretdecode(uint256 &gametxid,uint256 ®istertxid,CPubKey &pk,std::vector &playerdata,CScript scriptPubKey) { std::vector vopret; uint8_t *script,e,f; GetOpReturnData(scriptPubKey,vopret); @@ -147,7 +147,7 @@ uint8_t rogue_newgameopreturndecode(int64_t &buyin,int32_t &maxplayers,CScript s std::vector vopret; uint8_t *script,e,f; GetOpReturnData(scriptPubKey,vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> buyin; ss >> mayplayers) != 0 && e == EVAL_ROGUE && f == 'G' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> buyin; ss >> maxplayers) != 0 && e == EVAL_ROGUE && f == 'G' ) { return(f); } @@ -174,7 +174,7 @@ void rogue_univalue(UniValue &result,const char *method,int64_t maxplayers,int64 void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin) { - CBlockIndex *pindex; int32_t ht; uint64_t seed; char cmd[512]; + CBlockIndex *pindex; int32_t ht; uint256 hashBlock; uint64_t seed; char cmd[512]; if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) { ht = pindex->GetHeight(); @@ -200,7 +200,7 @@ void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin) int32_t rogue_isvalidgame(struct CCcontract_info *cp,CTransaction &tx,int64_t &buyin,int32_t &maxplayers,uint256 txid) { - uint256 hashBlock; int32_t i,numvouts; char coinaddr[64]; CPubKey roguepk; + uint256 hashBlock; int32_t i,numvouts; char coinaddr[64]; CPubKey roguepk; uint64_t txfee = 10000; buyin = maxplayers = 0; if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) { @@ -241,7 +241,7 @@ int32_t rogue_iterateplayer(uint256 firsttxid,uint256 lasttxid) // retrace p return(0); else { - fprintf(stderr,"firsttxid.%s -> %s != last.%s\n",firsttxid.ToString(),txid.ToString(),lasttxid.ToString()); + fprintf(stderr,"firsttxid.%s -> %s != last.%s\n",firsttxid.ToString().c_str(),txid.ToString().c_str(),lasttxid.ToString().c_str()); return(-1); } } @@ -253,12 +253,12 @@ int32_t rogue_iterateplayer(uint256 firsttxid,uint256 lasttxid) // retrace p 'S' is for sell, but will need to change to accomodate assets */ -int32_t rogue_playerdata(uint256 &origplayergame,CPubKey &pk,std::vector &playerdata,uint256 playertxid) +int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPubKey &pk,std::vector &playerdata,uint256 playertxid) { uint256 origplayertxid,hashBlock,highlander,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,maxplayers; int64_t buyin; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) { - GetOpReturnData(scriptPubKey,vopret); + GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); script = (uint8_t *)vopret.data(); if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'S') ) { @@ -271,7 +271,7 @@ int32_t rogue_playerdata(uint256 &origplayergame,CPubKey &pk,std::vector 1 ) + if ( highlandertx.vin[0].prevout.hash == prigplayergame && highlandertx.vin[0].prevout.n == 0 && rogue_isvalidgame(cp,gametx,buyin,maxplayers,origplayergame) == 0 && maxplayers > 1 ) return(0); else return(-3); } @@ -315,7 +315,7 @@ int32_t rogue_findbaton(std::vector &playerdata,uint256 &batontxid,int3 numvouts = matchtx.vout.size(); if ( rogue_registeropretdecode(txid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) { - if ( playertxid == zeroid || rogue_playerdata(origplayergame,playerdata,playertxid) == 0 ) + if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,playerdata,playertxid) == 0 ) { txid = spenttxid; while ( CCgettxout(txid,0,1) > 0 ) @@ -453,7 +453,7 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { UniValue pobj(UniValue:VOBJ); playertxid = jbits256(jitem(params,0),0); - if ( rogue_playerdata(origplayergame,playerdata,playertxid) < 0 ) + if ( rogue_playerdata(cp,origplayergame,playerdata,playertxid) < 0 ) return(cclib_error(result,"invalid playerdata")); result.push_back(Pair("rogue",rogue_playerobj(pobj,playerdata))); } else return(cclib_error(result,"no playertxid")); @@ -486,7 +486,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( n > 1 && maxplayers > 1 ) { playertxid = jbits256(jitem(params,0),0); - if ( rogue_playerdata(origplayergame,playerdata,playertxid) < 0 ) + if ( rogue_playerdata(cp,origplayergame,playerdata,playertxid) < 0 ) return(cclib_error(result,"couldnt extract valid playerdata")); } rogue_univalue(result,0,maxplayers,buyin); From 5e5f9d0054cc56c0167a5674eb63f37001dab9d3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 19:57:15 -1100 Subject: [PATCH 0324/1145] CTxIn( --- src/cc/rogue_rpc.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ec4e56aee..418c5100c 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -225,7 +225,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,CTransaction &tx,int64_t &b UniValue rogue_playerobj(UniValue &obj,std::vector playerdata) { - obj.push_back("raw",playerdata.ToString()); + obj.push_back("raw",playerdata.GetHex().ToString()); // convert to scrolls, etc. return(obj); } @@ -255,7 +255,7 @@ int32_t rogue_iterateplayer(uint256 firsttxid,uint256 lasttxid) // retrace p int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPubKey &pk,std::vector &playerdata,uint256 playertxid) { - uint256 origplayertxid,hashBlock,highlander,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,maxplayers; int64_t buyin; + uint256 origplayertxid,hashBlock,highlander,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,numvouts,maxplayers; int64_t buyin; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) { GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); @@ -271,7 +271,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub { if ( rogue_highlanderopretdecode(origplayergame,registertxid,pk,playerdata,highlandertx.vout[numvouts-1].scriptPubKey) == 'H' ) { - if ( highlandertx.vin[0].prevout.hash == prigplayergame && highlandertx.vin[0].prevout.n == 0 && rogue_isvalidgame(cp,gametx,buyin,maxplayers,origplayergame) == 0 && maxplayers > 1 ) + if ( highlandertx.vin[0].prevout.hash == origplayergame && highlandertx.vin[0].prevout.n == 0 && rogue_isvalidgame(cp,gametx,buyin,maxplayers,origplayergame) == 0 && maxplayers > 1 ) return(0); else return(-3); } @@ -287,8 +287,8 @@ int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,uint25 int64_t txfee = 10000; if ( CCgettxout(playertxid,0,1) == txfee && CCgettxout(origplayergame,1,1) == txfee ) { - mtx.vin.push_back(playertxid,0,CScript()); - mtx.vin.push_back(origplayergame,1,CScript()); + mtx.vin.push_back(CTxIn(playertxid,0,CScript())); + mtx.vin.push_back(CTxIn(origplayergame,1,CScript())); return(0); } else return(-1); } @@ -381,7 +381,7 @@ int64_t rogue_registrationbaton(CMutableTransaction &mtx,uint256 gametxid,CTrans vout = (r + j) % maxplayers; if ( CCgettxout(gametxid,vout,1) == ROGUE_REGISTRATIONSIZE ) { - mtx.vin.push_back(gametxid,vout,CScript()); + mtx.vin.push_back(CTxIn(gametxid,vout,CScript())); return(ROGUE_REGISTRATIONSIZE); } } @@ -530,7 +530,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) { - mtx.vin.push_back(batontxid,batonvout,CScript()); + mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,batonvalue-txfee,roguepk,mypk)); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_keystrokesopret(gametxid,batontxid,mypk,keystrokes)); return(rogue_rawtxresult(result,rawtx,1)); From dcfd8c570536675942d487e82253619d3ca4360c Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 20:03:48 -1100 Subject: [PATCH 0325/1145] struct CCcontract_info *cp, --- src/cc/rogue_rpc.cpp | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 418c5100c..ec914a4d2 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -225,7 +225,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,CTransaction &tx,int64_t &b UniValue rogue_playerobj(UniValue &obj,std::vector playerdata) { - obj.push_back("raw",playerdata.GetHex().ToString()); + obj.push_back("raw",""); // convert to scrolls, etc. return(obj); } @@ -293,14 +293,14 @@ int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,uint25 } else return(-1); } -int32_t rogue_findbaton(std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,CScript scriptPubKey) +int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,CScript scriptPubKey) { int32_t i,numvouts,spentvini,matches = 0; uint256 spenttxid,hashBlock,txid,playertxid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; for (i=0; i= 0 ) { - if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && tx.vout.size() > 0 ) + if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) { if ( spenttx.vout[0].scriptPubKey == scriptPubKey ) { @@ -321,10 +321,10 @@ int32_t rogue_findbaton(std::vector &playerdata,uint256 &batontxid,int3 while ( CCgettxout(txid,0,1) > 0 ) { spenttxid = zeroid; - spentvinit = -1; + spentvini = -1; if ( (spentvini= myIsutxo_spent(spenttxid,txid,0)) >= 0 ) txid = spenttxid; - else if ( myIsutxo_spentinmempool(spenttxid,spentvin,txid,0) == 0 || spenttxid == zeroid ) + else if ( myIsutxo_spentinmempool(spenttxid,spentvini,txid,0) == 0 || spenttxid == zeroid ) { fprintf(stderr,"mempool tracking error %s/v0\n",txid.ToString().c_str()); return(-2); @@ -342,7 +342,7 @@ int32_t rogue_findbaton(std::vector &playerdata,uint256 &batontxid,int3 batonht = komodo_nextheight(); else if ( (pindex= komodo_blockindex(hashBlock)) == 0 ) return(-4); - else batonht = pindex->nHeight; + else batonht = pindex->GetHeight(); return(0); } } @@ -351,12 +351,12 @@ int32_t rogue_findbaton(std::vector &playerdata,uint256 &batontxid,int3 return(-1); } -void rogue_gameplayerinfo(UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers) +void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers) { // identify if bailout or quit or timed out uint256 batontxid; int32_t batonvout,batonht; int64_t batonvalue; std::vector playerdata; obj.push_back(Pair("slot",(int64_t)vout-2)); - if ( rogue_findbaton(playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,gametx.vout[vout].scriptPubKey) == 0 ) + if ( rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,gametx.vout[vout].scriptPubKey) == 0 ) { obj.push_back(Pair("baton",batontxid.ToString())); obj.push_back(Pair("batonvout",(int64_t)batonvout)); @@ -364,7 +364,7 @@ void rogue_gameplayerinfo(UniValue &obj,uint256 gametxid,CTransaction gametx,int obj.push_back(Pair("batonht",(int64_t)batonht)); if ( playerdata.size() > 0 ) { - UniValue pobj(UniValue:VOBJ); + UniValue pobj(UniValue::VOBJ); obj.push_back(Pair("rogue",rogue_playerobj(pobj,playerdata))); } } @@ -373,7 +373,7 @@ void rogue_gameplayerinfo(UniValue &obj,uint256 gametxid,CTransaction gametx,int int64_t rogue_registrationbaton(CMutableTransaction &mtx,uint256 gametxid,CTransaction gametx,int32_t maxplayers) { int32_t vout,j,r; int64_t nValue; - if ( tx.vout.size() > maxplayers+2 ) + if ( gametx.vout.size() > maxplayers+2 ) { r = rand() % maxplayers; for (j=0; j 0 ) { - UniValue pobj(UniValue:VOBJ); + UniValue pobj(UniValue::VOBJ); playertxid = jbits256(jitem(params,0),0); if ( rogue_playerdata(cp,origplayergame,playerdata,playertxid) < 0 ) return(cclib_error(result,"invalid playerdata")); @@ -469,7 +469,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vin3+ -> buyin // vout0 -> keystrokes/completion baton CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); uint256 gametxid,playertxid,hashBlock; int32_t maxplayers,n,numvouts; int64_t inputsum,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx; std::vector playerdata; + UniValue result(UniValue::VOBJ); uint256 gametxid,playertxid,hashBlock; int32_t maxplayers,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx; std::vector playerdata; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -526,7 +526,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param txout = MakeCC1of2vout(cp->evalcode,0,roguepk,mypk); if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,gametxid) == 0 ) { - if ( rogue_findbaton(playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,txout.scriptPubKey) == 0 ) + if ( rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,txout.scriptPubKey) == 0 ) { if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) { @@ -595,7 +595,7 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( CCgettxout(txid,i+2,1) == 0 ) { UniValue obj(UniValue::VOBJ); - rogue_gameplayerinfo(obj,txid,tx,i+2,maxplayers); + rogue_gameplayerinfo(cp,obj,txid,tx,i+2,maxplayers); a.push_back(obj); } } From 0c8f7886af5c297cd0ba49efc564e5eb621ec68d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 20:06:21 -1100 Subject: [PATCH 0326/1145] struct CCcontract_info *cp, --- src/cc/rogue_rpc.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ec914a4d2..0146775dd 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -225,7 +225,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,CTransaction &tx,int64_t &b UniValue rogue_playerobj(UniValue &obj,std::vector playerdata) { - obj.push_back("raw",""); + obj.push_back(Pair("raw",playerdata.ToString())); // convert to scrolls, etc. return(obj); } @@ -295,7 +295,7 @@ int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,uint25 int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,CScript scriptPubKey) { - int32_t i,numvouts,spentvini,matches = 0; uint256 spenttxid,hashBlock,txid,playertxid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; + int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 spenttxid,hashBlock,txid,playertxid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; for (i=0; i= 0 ) @@ -315,7 +315,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd numvouts = matchtx.vout.size(); if ( rogue_registeropretdecode(txid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) { - if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,playerdata,playertxid) == 0 ) + if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) == 0 ) { txid = spenttxid; while ( CCgettxout(txid,0,1) > 0 ) @@ -444,7 +444,7 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); std::vector playerdata; uint256 playertxid,origplayergame;std::vector playerdata; int32_t n; + UniValue result(UniValue::VOBJ); std::vector playerdata; uint256 playertxid,origplayergame;std::vector playerdata; int32_t n; CPubKey pk; result.push_back(Pair("result","success")); rogue_univalue(result,"playerinfo",-1,-1); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -453,7 +453,7 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { UniValue pobj(UniValue::VOBJ); playertxid = jbits256(jitem(params,0),0); - if ( rogue_playerdata(cp,origplayergame,playerdata,playertxid) < 0 ) + if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"invalid playerdata")); result.push_back(Pair("rogue",rogue_playerobj(pobj,playerdata))); } else return(cclib_error(result,"no playertxid")); @@ -486,7 +486,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( n > 1 && maxplayers > 1 ) { playertxid = jbits256(jitem(params,0),0); - if ( rogue_playerdata(cp,origplayergame,playerdata,playertxid) < 0 ) + if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"couldnt extract valid playerdata")); } rogue_univalue(result,0,maxplayers,buyin); From afd20ae4c12c2381fdf27f90dfd0378880f69555 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 20:14:18 -1100 Subject: [PATCH 0327/1145] Bits256 --- src/cc/rogue_rpc.cpp | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 0146775dd..8ed303582 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -225,7 +225,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,CTransaction &tx,int64_t &b UniValue rogue_playerobj(UniValue &obj,std::vector playerdata) { - obj.push_back(Pair("raw",playerdata.ToString())); + obj.push_back(Pair("raw","")); // convert to scrolls, etc. return(obj); } @@ -285,7 +285,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,uint256 origplayergame) { int64_t txfee = 10000; - if ( CCgettxout(playertxid,0,1) == txfee && CCgettxout(origplayergame,1,1) == txfee ) + if ( CCgettxout(playertxid,0,1) == txfee && CCgettxout(origplayergame,1,1) == txfee ) // not sure if this is enough validation { mtx.vin.push_back(CTxIn(playertxid,0,CScript())); mtx.vin.push_back(CTxIn(origplayergame,1,CScript())); @@ -444,7 +444,7 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); std::vector playerdata; uint256 playertxid,origplayergame;std::vector playerdata; int32_t n; CPubKey pk; + UniValue result(UniValue::VOBJ); std::vector playerdata; uint256 playertxid,origplayergame;int32_t n; CPubKey pk; bits256 t; result.push_back(Pair("result","success")); rogue_univalue(result,"playerinfo",-1,-1); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -452,7 +452,8 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( n > 0 ) { UniValue pobj(UniValue::VOBJ); - playertxid = jbits256(jitem(params,0),0); + t = jbits256(jitem(params,0),0); + memcpy(&playertxid,t,sizeof(playertxid));; if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"invalid playerdata")); result.push_back(Pair("rogue",rogue_playerobj(pobj,playerdata))); @@ -469,7 +470,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vin3+ -> buyin // vout0 -> keystrokes/completion baton CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); uint256 gametxid,playertxid,hashBlock; int32_t maxplayers,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx; std::vector playerdata; + UniValue result(UniValue::VOBJ); uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t maxplayers,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx; std::vector playerdata; std::string rawtx; bits256 t; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -480,12 +481,14 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( n > 0 ) { - gametxid = jbits256(jitem(params,0),0); + t = jbits256(jitem(params,0),0); + memcpy(&gametxid,t,sizeof(gametxid)); if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,gametxid) == 0 ) { if ( n > 1 && maxplayers > 1 ) { - playertxid = jbits256(jitem(params,0),0); + t = jbits256(jitem(params,0),0); + memcpy(&playertxid,t,sizeof(playertxid)); if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"couldnt extract valid playerdata")); } @@ -513,13 +516,14 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // respawn to be prevented by including timestamps int32_t nextheight = komodo_nextheight(); CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(),nextheight); - UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr; + UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr; std::string rawtx; bits256 t; if ( txfee == 0 ) txfee = 10000; rogue_univalue(result,"keystrokes",-1,-1); if ( (params= cclib_reparse(&n,params)) != 0 && n == 2 && (keystrokestr= jstr(jitem(params,1),0)) != 0 ) { - gametxid = jbits256(jitem(params,0),0); + t = jbits256(jitem(params,0),0); + memcpy(&gametxid,t,sizeof(gametxid)); keystrokes = ParseHex(keystrokestr); mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); @@ -577,14 +581,15 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; bits256 t; result.push_back(Pair("name","rogue")); result.push_back(Pair("method","gameinfo")); if ( (params= cclib_reparse(&n,params)) != 0 ) { if ( n > 0 ) { - txid = jbits256(jitem(params,0),0); + t = jbits256(jitem(params,0),0); + memcpy(&txid,t,sizeof(txid)); result.push_back(Pair("txid",txid.GetHex())); if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,txid) == 0 ) { From 5754d4cca6377debcfc2922b278f25d8f5b5e2ee Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 20:16:01 -1100 Subject: [PATCH 0328/1145] & --- src/cc/rogue_rpc.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 8ed303582..446701ca3 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -453,7 +453,7 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { UniValue pobj(UniValue::VOBJ); t = jbits256(jitem(params,0),0); - memcpy(&playertxid,t,sizeof(playertxid));; + memcpy(&playertxid,&t,sizeof(playertxid));; if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"invalid playerdata")); result.push_back(Pair("rogue",rogue_playerobj(pobj,playerdata))); @@ -482,13 +482,13 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( n > 0 ) { t = jbits256(jitem(params,0),0); - memcpy(&gametxid,t,sizeof(gametxid)); + memcpy(&gametxid,&t,sizeof(gametxid)); if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,gametxid) == 0 ) { if ( n > 1 && maxplayers > 1 ) { t = jbits256(jitem(params,0),0); - memcpy(&playertxid,t,sizeof(playertxid)); + memcpy(&playertxid,&t,sizeof(playertxid)); if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"couldnt extract valid playerdata")); } @@ -497,7 +497,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"couldnt find available registration baton")); else if ( playertxid != zeroid && rogue_playerdataspend(mtx,playertxid,origplayergame) < 0 ) return(cclib_error(result,"couldnt find playerdata to spend")); - else if ( buyin > 0 && AddNormalInputs(mtx,mypk,buyin,64) < buyin ) + else if ( buyin > 0 && AddNormalinputs(mtx,mypk,buyin,64) < buyin ) return(cclib_error(result,"couldnt find enough normal funds for buyin")); mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,inputsum-txfee,roguepk,mypk)); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_registeropret(gametxid,playertxid)); @@ -523,7 +523,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( (params= cclib_reparse(&n,params)) != 0 && n == 2 && (keystrokestr= jstr(jitem(params,1),0)) != 0 ) { t = jbits256(jitem(params,0),0); - memcpy(&gametxid,t,sizeof(gametxid)); + memcpy(&gametxid,&t,sizeof(gametxid)); keystrokes = ParseHex(keystrokestr); mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); @@ -589,7 +589,7 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( n > 0 ) { t = jbits256(jitem(params,0),0); - memcpy(&txid,t,sizeof(txid)); + memcpy(&txid,&t,sizeof(txid)); result.push_back(Pair("txid",txid.GetHex())); if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,txid) == 0 ) { From 64b55a0891dedae251dd57d76cdc6900707d56de Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 20:39:47 -1100 Subject: [PATCH 0329/1145] Print --- src/cc/cclib.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index cede1a450..c72074717 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -465,6 +465,8 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will } newstr[j] = 0; params = cJSON_Parse(newstr); + if ( params != 0 ) + printf("new.(%s) -> %s\n",newstr,jprint(params,0)); free(newstr); *nump = cJSON_GetArraySize(params); //free(origparams); From ef94a1d13d0ea7813153ea5d45b8525268c0e7db Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 20:43:16 -1100 Subject: [PATCH 0330/1145] Off by 1 in parsing --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 446701ca3..499b4d48c 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -414,10 +414,10 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) txfee = 10000; if ( (params= cclib_reparse(&n,params)) != 0 ) { - if ( n > 1 ) + if ( n > 0 ) { maxplayers = juint(jitem(params,0),0); - if ( n > 2 ) + if ( n > 1 ) buyin = jdouble(jitem(params,1),0) * COIN + 0.0000000049; } } From 022a5903b8ce9ae49ccf3761e7184ad4012f7e98 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 21:04:19 -1100 Subject: [PATCH 0331/1145] juint256 --- src/cc/cclib.cpp | 7 + src/cc/rogue/command.c | 177 +++++++++++------------ src/cc/rogue/extern.c | 295 ++++++++++++++++++++++++++++----------- src/cc/rogue/extern.h | 1 + src/cc/rogue/fight.c | 17 +-- src/cc/rogue/init.c | 225 ++++++++++++++++------------- src/cc/rogue/io.c | 81 ++++------- src/cc/rogue/list.c | 38 +++++ src/cc/rogue/main.c | 1 + src/cc/rogue/misc.c | 8 +- src/cc/rogue/monsters.c | 5 +- src/cc/rogue/move.c | 3 +- src/cc/rogue/new_level.c | 67 ++++----- src/cc/rogue/options.c | 2 +- src/cc/rogue/pack.c | 34 ++--- src/cc/rogue/rip.c | 1 + src/cc/rogue/rogue.c | 81 +++++++++-- src/cc/rogue/rogue.h | 58 +++++--- src/cc/rogue/rooms.c | 170 +++++++++++----------- src/cc/rogue/save.c | 62 +++++++- src/cc/rogue/state.c | 145 ++++++++++++------- src/cc/rogue/sticks.c | 3 +- src/cc/rogue/things.c | 8 +- src/cc/rogue/weapons.c | 4 +- src/cc/rogue_rpc.cpp | 19 +-- 25 files changed, 933 insertions(+), 579 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index c72074717..f192fc20a 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -444,6 +444,13 @@ UniValue cclib_error(UniValue &result,const char *errorstr) return(result); } +uint256 juint256(cJSON *obj) +{ + uint256 tmp; bits256 t = jbits256(obj,0); + memcpy(&tmp,&t,sizeof(tmp)); + return(revuint256(tmp)); +} + cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will be freed by caller { cJSON *params; char *jsonstr,*newstr; int32_t i,j; diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index d6f834dbc..bdbf37b76 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -28,9 +28,9 @@ command(struct rogue_state *rs) char *fp; THING *mp; static char countch, direction, newcount = FALSE; - + if (on(player, ISHASTE)) - ntimes++; + ntimes++; /* * Let the daemons start up */ @@ -38,82 +38,85 @@ command(struct rogue_state *rs) do_fuses(rs,BEFORE); while (ntimes--) { - again = FALSE; - if (has_hit) - { - endmsg(rs); - has_hit = FALSE; - } - /* - * these are illegal things for the player to be, so if any are - * set, someone's been poking in memeory - */ - if (on(player, ISSLOW|ISGREED|ISINVIS|ISREGEN|ISTARGET)) - exit(1); - - look(rs,TRUE); - if (!running) - door_stop = FALSE; - status(rs); - lastscore = purse; - move(hero.y, hero.x); - if (!((running || count) && jump)) - refresh(); /* Draw screen */ - take = 0; - after = TRUE; - /* - * Read command or continue run - */ + again = FALSE; + if (has_hit) + { + endmsg(rs); + has_hit = FALSE; + } + /* + * these are illegal things for the player to be, so if any are + * set, someone's been poking in memeory + */ + if (on(player, ISSLOW|ISGREED|ISINVIS|ISREGEN|ISTARGET)) + exit(1); + + look(rs,TRUE); + if (!running) + door_stop = FALSE; + status(rs); + lastscore = purse; + move(hero.y, hero.x); + if ( rs->sleeptime != 0 ) + { + if (!((running || count) && jump)) + refresh(); /* Draw screen */ + } + take = 0; + after = TRUE; + /* + * Read command or continue run + */ #ifdef MASTER - if (wizard) - noscore = TRUE; + if (wizard) + noscore = TRUE; #endif - if (!no_command) - { - if (running || to_death) - ch = runch; - else if (count) - ch = countch; - else - { - ch = readchar(rs); - move_on = FALSE; - if (mpos != 0) /* Erase message if its there */ - msg(rs,""); - } - } - else - ch = '.'; - if (no_command) - { - if (--no_command == 0) - { - player.t_flags |= ISRUN; - msg(rs,"you can move again"); - } - } - else - { - /* - * check for prefixes - */ - newcount = FALSE; - if (isdigit(ch)) - { - count = 0; - newcount = TRUE; - while (isdigit(ch)) - { - count = count * 10 + (ch - '0'); - if (count > 255) - count = 255; - ch = readchar(rs); - } - countch = ch; - /* - * turn off count for commands which don't make sense - * to repeat - */ + if (!no_command) + { + if (running || to_death) + ch = runch; + else if (count) + ch = countch; + else + { + ch = readchar(rs); + move_on = FALSE; + if (mpos != 0) /* Erase message if its there */ + msg(rs,""); + } + } + else + ch = '.'; + if (no_command) + { + if (--no_command == 0) + { + player.t_flags |= ISRUN; + msg(rs,"you can move again"); + } + } + else + { + /* + * check for prefixes + */ + newcount = FALSE; + if (isdigit(ch)) + { + count = 0; + newcount = TRUE; + while (isdigit(ch)) + { + count = count * 10 + (ch - '0'); + if (count > 255) + count = 255; + ch = readchar(rs); + } + countch = ch; + /* + * turn off count for commands which don't make sense + * to repeat + */ switch (ch) { case CTRL('B'): case CTRL('H'): case CTRL('J'): @@ -317,9 +320,9 @@ over: if (chat(delta.y, delta.x) != TRAP) msg(rs,"no trap there"); else if (on(player, ISHALU)) - msg(rs,tr_name[rnd(NTRAPS)]); + msg(rs,(char *)tr_name[rnd(NTRAPS)]); else { - msg(rs,tr_name[*fp & F_TMASK]); + msg(rs,(char *)tr_name[*fp & F_TMASK]); *fp |= F_SEEN; } } @@ -521,9 +524,9 @@ foundone: if (!terse) addmsg(rs,"you found "); if (on(player, ISHALU)) - msg(rs,tr_name[rnd(NTRAPS)]); + msg(rs,(char *)tr_name[rnd(NTRAPS)]); else { - msg(rs,tr_name[*fp & F_TMASK]); + msg(rs,(char *)tr_name[*fp & F_TMASK]); *fp |= F_SEEN; } goto foundone; @@ -546,7 +549,7 @@ foundone: void help(struct rogue_state *rs) { - register struct h_list *strp; + register const struct h_list *strp; register char helpch; register int numprint, cnt; msg(rs,"character you want help for (* for all): "); @@ -617,9 +620,9 @@ void identify(struct rogue_state *rs) { register int ch; - register struct h_list *hp; + register const struct h_list *hp; register char *str; - static struct h_list ident_list[] = { + static const struct h_list ident_list[] = { {'|', "wall of a room", FALSE}, {'-', "wall of a room", FALSE}, {GOLD, "gold", FALSE}, @@ -729,9 +732,9 @@ void call(struct rogue_state *rs) { register THING *obj; - register struct obj_info *op = NULL; - register char **guess, *elsewise = NULL; - register bool *know; + register const struct obj_info *op = NULL; + register char **guess; const char *elsewise = NULL; + register const bool *know; obj = get_item(rs,"call", CALLABLE); /* @@ -758,7 +761,7 @@ call(struct rogue_state *rs) elsewise = ws_made[obj->o_which]; norm: know = &op->oi_know; - guess = &op->oi_guess; + guess = (char **)&op->oi_guess; if (*guess != NULL) elsewise = *guess; when FOOD: diff --git a/src/cc/rogue/extern.c b/src/cc/rogue/extern.c index fb732dfde..b84e6fa7b 100644 --- a/src/cc/rogue/extern.c +++ b/src/cc/rogue/extern.c @@ -13,6 +13,8 @@ #include #include "rogue.h" + + bool after; /* True if we want after daemons */ bool again; /* Repeating the last command */ int noscore; /* Was a wizard sometime */ @@ -50,41 +52,21 @@ bool pack_used[26] = { /* Is the character used in the pack? */ }; char dir_ch; /* Direction from last get_dir() call */ +char runch; /* Direction player is running */ +char take; /* Thing she is taking */ + +int orig_dsusp; /* Original dsusp char */ char file_name[MAXSTR]; /* Save file name */ char huh[MAXSTR]; /* The last message printed */ -char *p_colors[MAXPOTIONS]; /* Colors of the potions */ char prbuf[2*MAXSTR]; /* buffer for sprintfs */ -char *r_stones[MAXRINGS]; /* Stone settings of the rings */ -char runch; /* Direction player is running */ -char *s_names[MAXSCROLLS]; /* Names of the scrolls */ -char take; /* Thing she is taking */ char whoami[MAXSTR]; /* Name of player */ -char *ws_made[MAXSTICKS]; /* What sticks are made of */ -char *ws_type[MAXSTICKS]; /* Is it a wand or a staff */ -int orig_dsusp; /* Original dsusp char */ char fruit[MAXSTR] = /* Favorite fruit */ { 's', 'l', 'i', 'm', 'e', '-', 'm', 'o', 'l', 'd', '\0' }; char home[MAXSTR] = { '\0' }; /* User's home directory */ -char *inv_t_name[] = { - "Overwrite", - "Slow", - "Clear" -}; char l_last_comm = '\0'; /* Last last_comm */ char l_last_dir = '\0'; /* Last last_dir */ char last_comm = '\0'; /* Last command typed */ char last_dir = '\0'; /* Last direction given */ -char *tr_name[] = { /* Names of the traps */ - "a trapdoor", - "an arrow trap", - "a sleeping gas trap", - "a beartrap", - "a teleport trap", - "a poison dart trap", - "a rust trap", - "a mysterious trap" -}; - int n_objs; /* # items listed in inventory() call */ int ntraps; /* Number of traps on this level */ @@ -96,19 +78,8 @@ int max_hit; /* Max damage done to her in to_death */ int max_level; /* Deepest player has gone */ int mpos = 0; /* Where cursor is on top line */ int no_food = 0; /* Number of levels without food */ -int a_class[MAXARMORS] = { /* Armor class for each armor type */ - 8, /* LEATHER */ - 7, /* RING_MAIL */ - 7, /* STUDDED_LEATHER */ - 6, /* SCALE_MAIL */ - 5, /* CHAIN_MAIL */ - 4, /* SPLINT_MAIL */ - 4, /* BANDED_MAIL */ - 3, /* PLATE_MAIL */ -}; int count = 0; /* Number of times to repeat command */ -FILE *scoreboard = NULL; /* File descriptor for score file */ int food_left; /* Amount of food in hero's stomach */ int lastscore = -1; /* Score before this turn */ int no_command = 0; /* Number of turns asleep */ @@ -117,31 +88,9 @@ int purse = 0; /* How much gold he has */ int quiet = 0; /* Number of quiet turns */ int vf_hit = 0; /* Number of time flytrap has hit */ -int dnum; /* Dungeon number */ + +//int dnum; /* Dungeon number */ uint64_t seed; /* Random number seed */ -int e_levels[] = { - 10L, - 20L, - 40L, - 80L, - 160L, - 320L, - 640L, - 1300L, - 2600L, - 5200L, - 13000L, - 26000L, - 50000L, - 100000L, - 200000L, - 400000L, - 800000L, - 2000000L, - 4000000L, - 8000000L, - 0L -}; coord delta; /* Change indicated to get_dir() */ coord oldpos; /* Position before last look() call */ @@ -149,6 +98,11 @@ coord stairs; /* Location of staircase */ PLACE places[MAXLINES*MAXCOLS]; /* level map */ +const char *p_colors[MAXPOTIONS]; /* Colors of the potions */ +const char *r_stones[MAXRINGS]; /* Stone settings of the rings */ +const char *ws_made[MAXSTICKS]; /* What sticks are made of */ +const char *ws_type[MAXSTICKS]; /* Is it a wand or a staff */ + THING *cur_armor; /* What he is wearing */ THING *cur_ring[2]; /* Which rings are being worn */ THING *cur_weapon; /* Which weapon he is weilding */ @@ -156,18 +110,36 @@ THING *l_last_pick = NULL; /* Last last_pick */ THING *last_pick = NULL; /* Last object picked in get_item() */ THING *lvl_obj = NULL; /* List of objects on this level */ THING *mlist = NULL; /* List of monsters on the level */ +struct room *oldrp; /* Roomin(&oldpos) */ THING player; /* His stats */ - /* restart of game */ - WINDOW *hw = NULL; /* used as a scratch window */ +char *s_names[MAXSCROLLS]; /* Names of the scrolls */ +FILE *scoreboard = NULL; /* File descriptor for score file */ #define INIT_STATS { 16, 0, 1, 10, 12, "1x4", 12 } struct stats max_stats = INIT_STATS; /* The maximum for the player */ +struct stats orig_max_stats = INIT_STATS; -struct room *oldrp; /* Roomin(&oldpos) */ -struct room rooms[MAXROOMS]; /* One for each room -- A level */ -struct room passages[MAXPASS] = /* One for each passage */ +struct monster monsters[26]; +struct room passages[MAXPASS],rooms[MAXROOMS]; /* One for each room -- A level */ +struct obj_info things[NUMTHINGS],ring_info[MAXRINGS],pot_info[MAXPOTIONS],arm_info[MAXARMORS],scr_info[MAXSCROLLS],weap_info[MAXWEAPONS + 1],ws_info[MAXSTICKS]; + +////////////// constants +#define ___ 1 +#define XX 10 + +const struct obj_info origthings[NUMTHINGS] = { + { 0, 26 }, /* potion */ + { 0, 36 }, /* scroll */ + { 0, 16 }, /* food */ + { 0, 7 }, /* weapon */ + { 0, 7 }, /* armor */ + { 0, 4 }, /* ring */ + { 0, 4 }, /* stick */ +}; + +const struct room origpassages[MAXPASS] = /* One for each passage */ { { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, @@ -182,10 +154,7 @@ struct room passages[MAXPASS] = /* One for each passage */ { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} }, { {0, 0}, {0, 0}, {0, 0}, 0, ISGONE|ISDARK, 0, {{0,0}} } }; - -#define ___ 1 -#define XX 10 -struct monster monsters[26] = +const struct monster origmonsters[26] = { /* Name CARRY FLAG str, exp, lvl, amr, hpt, dmg */ { "aquator", 0, ISMEAN, { XX, 20, 5, 2, ___, "0x0/0x0" } }, @@ -220,17 +189,7 @@ struct monster monsters[26] = #undef ___ #undef XX -struct obj_info things[NUMTHINGS] = { - { 0, 26 }, /* potion */ - { 0, 36 }, /* scroll */ - { 0, 16 }, /* food */ - { 0, 7 }, /* weapon */ - { 0, 7 }, /* armor */ - { 0, 4 }, /* ring */ - { 0, 4 }, /* stick */ -}; - -struct obj_info arm_info[MAXARMORS] = { +const struct obj_info origarm_info[MAXARMORS] = { { "leather armor", 20, 20, NULL, FALSE }, { "ring mail", 15, 25, NULL, FALSE }, { "studded leather armor", 15, 20, NULL, FALSE }, @@ -240,7 +199,7 @@ struct obj_info arm_info[MAXARMORS] = { { "banded mail", 10, 90, NULL, FALSE }, { "plate mail", 5, 150, NULL, FALSE }, }; -struct obj_info pot_info[MAXPOTIONS] = { +const struct obj_info origpot_info[MAXPOTIONS] = { { "confusion", 7, 5, NULL, FALSE }, { "hallucination", 8, 5, NULL, FALSE }, { "poison", 8, 5, NULL, FALSE }, @@ -256,7 +215,7 @@ struct obj_info pot_info[MAXPOTIONS] = { { "blindness", 5, 5, NULL, FALSE }, { "levitation", 6, 75, NULL, FALSE }, }; -struct obj_info ring_info[MAXRINGS] = { +const struct obj_info origring_info[MAXRINGS] = { { "protection", 9, 400, NULL, FALSE }, { "add strength", 9, 400, NULL, FALSE }, { "sustain strength", 5, 280, NULL, FALSE }, @@ -272,7 +231,7 @@ struct obj_info ring_info[MAXRINGS] = { { "stealth", 7, 470, NULL, FALSE }, { "maintain armor", 5, 380, NULL, FALSE }, }; -struct obj_info scr_info[MAXSCROLLS] = { +const struct obj_info origscr_info[MAXSCROLLS] = { { "monster confusion", 7, 140, NULL, FALSE }, { "magic mapping", 4, 150, NULL, FALSE }, { "hold monster", 2, 180, NULL, FALSE }, @@ -292,7 +251,7 @@ struct obj_info scr_info[MAXSCROLLS] = { { "aggravate monsters", 3, 20, NULL, FALSE }, { "protect armor", 2, 250, NULL, FALSE }, }; -struct obj_info weap_info[MAXWEAPONS + 1] = { +const struct obj_info origweap_info[MAXWEAPONS + 1] = { { "mace", 11, 8, NULL, FALSE }, { "long sword", 11, 15, NULL, FALSE }, { "short bow", 12, 15, NULL, FALSE }, @@ -304,7 +263,7 @@ struct obj_info weap_info[MAXWEAPONS + 1] = { { "spear", 12, 5, NULL, FALSE }, { NULL, 0 }, /* DO NOT REMOVE: fake entry for dragon's breath */ }; -struct obj_info ws_info[MAXSTICKS] = { +const struct obj_info origws_info[MAXSTICKS] = { { "light", 12, 250, NULL, FALSE }, { "invisibility", 6, 5, NULL, FALSE }, { "lightning", 3, 330, NULL, FALSE }, @@ -321,7 +280,7 @@ struct obj_info ws_info[MAXSTICKS] = { { "cancellation", 5, 280, NULL, FALSE }, }; -struct h_list helpstr[] = { +const struct h_list helpstr[] = { {'?', " prints help", TRUE}, {'/', " identify object", TRUE}, {'h', " left", TRUE}, @@ -389,3 +348,169 @@ struct h_list helpstr[] = { {'v', " print version number", TRUE}, {0, NULL } }; + +const char *inv_t_name[] = { + "Overwrite", + "Slow", + "Clear" +}; + +const char *tr_name[] = { /* Names of the traps */ + "a trapdoor", + "an arrow trap", + "a sleeping gas trap", + "a beartrap", + "a teleport trap", + "a poison dart trap", + "a rust trap", + "a mysterious trap" +}; + +const int32_t a_class[MAXARMORS] = { /* Armor class for each armor type */ + 8, /* LEATHER */ + 7, /* RING_MAIL */ + 7, /* STUDDED_LEATHER */ + 6, /* SCALE_MAIL */ + 5, /* CHAIN_MAIL */ + 4, /* SPLINT_MAIL */ + 4, /* BANDED_MAIL */ + 3, /* PLATE_MAIL */ +}; + +const int32_t e_levels[] = { + 10L, + 20L, + 40L, + 80L, + 160L, + 320L, + 640L, + 1300L, + 2600L, + 5200L, + 13000L, + 26000L, + 50000L, + 100000L, + 200000L, + 400000L, + 800000L, + 2000000L, + 4000000L, + 8000000L, + 0L +}; + +#include +extern int between; +extern int group; +extern coord nh; + +void externs_clear() +{ + int i; + after = 0; /* True if we want after daemons */ + again = 0; /* Repeating the last command */ + noscore = 0; /* Was a wizard sometime */ + seenstairs = 0; /* Have seen the stairs (for lsd) */ + amulet = FALSE; /* He found the amulet */ + door_stop = FALSE; /* Stop running when we pass a door */ + fight_flush = FALSE; /* True if toilet input */ + firstmove = FALSE; /* First move after setting door_stop */ + got_ltc = FALSE; /* We have gotten the local tty chars */ + has_hit = FALSE; /* Has a "hit" message pending in msg */ + in_shell = FALSE; /* True if executing a shell */ + inv_describe = TRUE; /* Say which way items are being used */ + jump = FALSE; /* Show running as series of jumps */ + kamikaze = FALSE; /* to_death really to DEATH */ + lower_msg = FALSE; /* Messages should start w/lower case */ + move_on = FALSE; /* Next move shouldn't pick up items */ + msg_esc = FALSE; /* Check for ESC from msg's --More-- */ + passgo = FALSE; /* Follow passages */ + playing = TRUE; /* True until he quits */ + q_comm = FALSE; /* Are we executing a 'Q' command? */ + running = FALSE; /* True if player is running */ + save_msg = TRUE; /* Remember last msg */ + see_floor = TRUE; /* Show the lamp illuminated floor */ + stat_msg = FALSE; /* Should status() print as a msg() */ + terse = FALSE; /* True if we should be short */ + to_death = FALSE; /* Fighting is to the death! */ + tombstone = TRUE; /* Print out tombstone at end */ +#ifdef MASTER + int wizard = FALSE; /* True if allows wizard commands */ +#endif + for (i=0; i<26; i++) + pack_used[i] = FALSE; + for (i=0; io_type = FOOD; - obj->o_count = 1; - add_pack(rs,obj, TRUE); - /* - * And his suit of armor - */ - obj = new_item(); - obj->o_type = ARMOR; - obj->o_which = RING_MAIL; - obj->o_arm = a_class[RING_MAIL] - 1; - obj->o_flags |= ISKNOW; - obj->o_count = 1; - cur_armor = obj; - add_pack(rs,obj, TRUE); - /* - * Give him his weaponry. First a mace. - */ - obj = new_item(); - init_weapon(obj, MACE); - obj->o_hplus = 1; - obj->o_dplus = 1; - obj->o_flags |= ISKNOW; - add_pack(rs,obj, TRUE); - cur_weapon = obj; - /* - * Now a +1 bow - */ - obj = new_item(); - init_weapon(obj, BOW); - obj->o_hplus = 1; - obj->o_flags |= ISKNOW; - add_pack(rs,obj, TRUE); - /* - * Now some arrows - */ - obj = new_item(); - init_weapon(obj, ARROW); - obj->o_count = rnd(15) + 25; - obj->o_flags |= ISKNOW; - add_pack(rs,obj, TRUE); + + if ( 0 && rogue_restorepack(rs) == 0 ) + { + //rs->P.gold = purse; + max_hp = rs->P.hitpoints; + max_stats.s_str = rs->P.strength; + pstats.s_lvl = rs->P.level; + pstats.s_exp = rs->P.experience; + for (i=0; iP.packsize; i++) + { + obj = new_item(); + rogue_restoreobject(obj,&rs->P.roguepack[i]); + add_pack(rs,obj,TRUE); + } + // duplicate rng usage of normal case + obj = new_item(); + init_weapon(obj, MACE); + init_weapon(obj, BOW); + init_weapon(obj, ARROW); + obj->o_count = rnd(15) + 25; + free(obj); + } + else + { + /* + * Give him some food + */ + obj = new_item(); + obj->o_type = FOOD; + obj->o_count = 1; + add_pack(rs,obj, TRUE); + /* + * And his suit of armor + */ + obj = new_item(); + obj->o_type = ARMOR; + obj->o_which = RING_MAIL; + obj->o_arm = a_class[RING_MAIL] - 1; + obj->o_flags |= ISKNOW; + obj->o_count = 1; + cur_armor = obj; + add_pack(rs,obj, TRUE); + /* + * Give him his weaponry. First a mace. + */ + obj = new_item(); + init_weapon(obj, MACE); + obj->o_hplus = 1; + obj->o_dplus = 1; + obj->o_flags |= ISKNOW; + add_pack(rs,obj, TRUE); + cur_weapon = obj; + /* + * Now a +1 bow + */ + obj = new_item(); + init_weapon(obj, BOW); + obj->o_hplus = 1; + obj->o_flags |= ISKNOW; + add_pack(rs,obj, TRUE); + /* + * Now some arrows + */ + obj = new_item(); + init_weapon(obj, ARROW); + obj->o_count = rnd(15) + 25; + obj->o_flags |= ISKNOW; + add_pack(rs,obj, TRUE); + //fprintf(stderr,"initial o_count.%d\n",obj->o_count); sleep(3); + } } /* @@ -78,7 +105,7 @@ init_player(struct rogue_state *rs) * potions and scrolls */ -char *rainbow[] = { +const char *rainbow[] = { "amber", "aquamarine", "black", @@ -111,7 +138,7 @@ char *rainbow[] = { #define NCOLORS (sizeof rainbow / sizeof (char *)) int cNCOLORS = NCOLORS; -static char *sylls[] = { +static const char *sylls[] = { "a", "ab", "ag", "aks", "ala", "an", "app", "arg", "arze", "ash", "bek", "bie", "bit", "bjor", "blu", "bot", "bu", "byt", "comp", "con", "cos", "cre", "dalf", "dan", "den", "do", "e", "eep", "el", @@ -130,7 +157,7 @@ static char *sylls[] = { "zok", "zon", "zum", }; -STONE stones[] = { +const STONE stones[] = { { "agate", 25}, { "alexandrite", 40}, { "amethyst", 50}, @@ -162,7 +189,7 @@ STONE stones[] = { #define NSTONES (sizeof stones / sizeof (STONE)) int cNSTONES = NSTONES; -char *wood[] = { +const char *wood[] = { "avocado wood", "balsa", "bamboo", @@ -201,7 +228,7 @@ char *wood[] = { #define NWOOD (sizeof wood / sizeof (char *)) int cNWOOD = NWOOD; -char *metal[] = { +const char *metal[] = { "aluminum", "beryllium", "bone", @@ -240,16 +267,16 @@ void init_colors() { register int i, j; - + memset(used,0,sizeof(used)); for (i = 0; i < NCOLORS; i++) - used[i] = FALSE; + used[i] = FALSE; for (i = 0; i < MAXPOTIONS; i++) { - do - j = rnd(NCOLORS); - until (!used[j]); - used[j] = TRUE; - p_colors[i] = rainbow[j]; + do + j = rnd(NCOLORS); + until (!used[j]); + used[j] = TRUE; + p_colors[i] = rainbow[j]; } } @@ -263,7 +290,7 @@ void init_names() { register int nsyl; - register char *cp, *sp; + register char *cp; const char *sp; register int i, nwords; for (i = 0; i < MAXSCROLLS; i++) @@ -297,17 +324,16 @@ void init_stones() { register int i, j; - for (i = 0; i < NSTONES; i++) - used[i] = FALSE; + used[i] = FALSE; for (i = 0; i < MAXRINGS; i++) { - do - j = rnd(NSTONES); - until (!used[j]); - used[j] = TRUE; - r_stones[i] = stones[j].st_name; - ring_info[i].oi_worth += stones[j].st_value; + do + j = rnd(NSTONES); + until (!used[j]); + used[j] = TRUE; + r_stones[i] = stones[j].st_name; + ring_info[i].oi_worth += stones[j].st_value; } } @@ -319,39 +345,39 @@ void init_materials() { register int i, j; - register char *str; + register const char *str; static bool metused[NMETAL]; - + memset(metused,0,sizeof(metused)); for (i = 0; i < NWOOD; i++) - used[i] = FALSE; + used[i] = FALSE; for (i = 0; i < NMETAL; i++) - metused[i] = FALSE; + metused[i] = FALSE; for (i = 0; i < MAXSTICKS; i++) { - for (;;) - if (rnd(2) == 0) - { - j = rnd(NMETAL); - if (!metused[j]) - { - ws_type[i] = "wand"; - str = metal[j]; - metused[j] = TRUE; - break; - } - } - else - { - j = rnd(NWOOD); - if (!used[j]) - { - ws_type[i] = "staff"; - str = wood[j]; - used[j] = TRUE; - break; - } - } - ws_made[i] = str; + for (;;) + if (rnd(2) == 0) + { + j = rnd(NMETAL); + if (!metused[j]) + { + ws_type[i] = "wand"; + str = metal[j]; + metused[j] = TRUE; + break; + } + } + else + { + j = rnd(NWOOD); + if (!used[j]) + { + ws_type[i] = "staff"; + str = wood[j]; + used[j] = TRUE; + break; + } + } + ws_made[i] = str; } } @@ -380,18 +406,17 @@ init_materials() void sumprobs(struct obj_info *info, int bound #ifdef MASTER - , char *name + , char *name #endif ) { #ifdef MASTER - struct obj_info *start = info; + struct obj_info *start = info; #endif struct obj_info *endp; - endp = info + bound; while (++info < endp) - info->oi_prob += (info - 1)->oi_prob; + info->oi_prob += (info - 1)->oi_prob; #ifdef MASTER badcheck(name, start, bound); #endif @@ -443,5 +468,5 @@ badcheck(char *name, struct obj_info *info, int bound) char * pick_color(char *col) { - return (on(player, ISHALU) ? rainbow[rnd(NCOLORS)] : col); + return (on(player, ISHALU) ? (char *)rainbow[rnd(NCOLORS)] : col); } diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index bdf3c515c..f4a859b38 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -24,16 +24,16 @@ int msg(struct rogue_state *rs,char *fmt, ...) { va_list args; - + /* * if the string is "", just clear the line */ if (*fmt == '\0') { - move(0, 0); - clrtoeol(); - mpos = 0; - return ~ESCAPE; + move(0, 0); + clrtoeol(); + mpos = 0; + return ~ESCAPE; } /* * otherwise add to the message and flush it out @@ -70,39 +70,41 @@ endmsg(struct rogue_state *rs) char ch; if (save_msg) - strcpy(huh, msgbuf); + strcpy(huh, msgbuf); if (mpos) { - look(rs,FALSE); - mvaddstr(0, mpos, "--More--"); - refresh(); - if (!msg_esc) - wait_for(rs,' '); - else - { - while ((ch = readchar(rs)) != ' ') - if (ch == ESCAPE) - { - msgbuf[0] = '\0'; - mpos = 0; - newpos = 0; - msgbuf[0] = '\0'; - return ESCAPE; - } - } + look(rs,FALSE); + mvaddstr(0, mpos, "--More--"); + if ( rs->sleeptime != 0 ) + refresh(); + if (!msg_esc) + wait_for(rs,' '); + else + { + while ((ch = readchar(rs)) != ' ') + if (ch == ESCAPE) + { + msgbuf[0] = '\0'; + mpos = 0; + newpos = 0; + msgbuf[0] = '\0'; + return ESCAPE; + } + } } /* * All messages should start with uppercase, except ones that * start with a pack addressing character */ if (islower(msgbuf[0]) && !lower_msg && msgbuf[1] != ')') - msgbuf[0] = (char) toupper(msgbuf[0]); + msgbuf[0] = (char) toupper(msgbuf[0]); mvaddstr(0, 0, msgbuf); clrtoeol(); mpos = newpos; newpos = 0; msgbuf[0] = '\0'; - refresh(); + if ( rs->sleeptime != 0 ) + refresh(); return ~ESCAPE; } @@ -188,35 +190,6 @@ readchar(struct rogue_state *rs) return(ch); } -/*char readchar() -{ - static FILE *keystrokefp; int c; - - if ( keystrokefp == 0 ) - keystrokefp = fopen("keystrokes","rb"); - if ( keystrokefp != 0 ) - { - if ( (c= fgetc(keystrokefp)) == EOF ) - eofflag = 1; - else return(c); - } else eofflag = 1; - ch = (char) md_readchar(); - - if (ch == 3) - { - quit(0); - return(27); - } - { - static FILE *replayfp; - if ( replayfp == 0 ) - replayfp = fopen("replay","wb"); - if ( replayfp != 0 ) - fputc(ch,replayfp), fflush(replayfp); - } - return(ch); -}*/ - /* * status: * Display the important stats line. Keep the cursor where it was. diff --git a/src/cc/rogue/list.c b/src/cc/rogue/list.c index f571be628..6affc662c 100644 --- a/src/cc/rogue/list.c +++ b/src/cc/rogue/list.c @@ -12,6 +12,7 @@ #include #include +#include #include "rogue.h" #ifdef MASTER @@ -81,19 +82,50 @@ _free_list(THING **ptr) * Free up an item */ +int32_t itemcounter; +THING *thingptrs[100000]; +int32_t numptrs; + void discard(THING *item) { #ifdef MASTER total--; #endif + if ( 0 ) + { + int32_t i; + for (i=0; i_t._t_type,thingptrs[i]->o_type,thingptrs[i]->o_type); + free(thingptrs[i]); + } + memset(thingptrs,0,sizeof(thingptrs)); + numptrs = 0; +} + /* * new_item * Get a new item with a specified size */ + THING * new_item(void) { @@ -107,6 +139,12 @@ new_item(void) #else item = (THING *)calloc(1, sizeof *item); #endif + if ( 0 ) + { + thingptrs[numptrs++] = item; + if ( (++itemcounter % 100) == 0 ) + fprintf(stderr,"itemcounter.%d\n",itemcounter); + } item->l_next = NULL; item->l_prev = NULL; return item; diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index d2805ed73..7efdebc8d 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -13,6 +13,7 @@ * * ******************************************************************************/ + #include #include #include diff --git a/src/cc/rogue/misc.c b/src/cc/rogue/misc.c index 775878450..168886b6b 100644 --- a/src/cc/rogue/misc.c +++ b/src/cc/rogue/misc.c @@ -350,17 +350,17 @@ chg_str(int amt) { //auto jl777: strange compiler error str_t comp; - + if (amt == 0) return; add_str(&pstats.s_str, amt); comp = pstats.s_str; if (ISRING(LEFT, R_ADDSTR)) - add_str(&comp, -cur_ring[LEFT]->o_arm); + add_str(&comp, -cur_ring[LEFT]->o_arm); if (ISRING(RIGHT, R_ADDSTR)) - add_str(&comp, -cur_ring[RIGHT]->o_arm); + add_str(&comp, -cur_ring[RIGHT]->o_arm); if (comp > max_stats.s_str) - max_stats.s_str = comp; + max_stats.s_str = comp; } /* diff --git a/src/cc/rogue/monsters.c b/src/cc/rogue/monsters.c index c9441efa3..4649de9a2 100644 --- a/src/cc/rogue/monsters.c +++ b/src/cc/rogue/monsters.c @@ -218,7 +218,10 @@ void give_pack(struct rogue_state *rs,THING *tp) { if (level >= max_level && rnd(100) < monsters[tp->t_type-'A'].m_carry) - attach(tp->t_pack, new_thing(rs)); + { + //fprintf(stderr,"give_pack\n"); + attach(tp->t_pack, new_thing(rs)); + } } /* diff --git a/src/cc/rogue/move.c b/src/cc/rogue/move.c index b402f4fa1..87276e8e2 100644 --- a/src/cc/rogue/move.c +++ b/src/cc/rogue/move.c @@ -230,7 +230,8 @@ turnref() if (jump) { leaveok(stdscr, TRUE); - refresh(); + if ( globalR.sleeptime != 0 ) + refresh(); leaveok(stdscr, FALSE); } pp->p_flags |= F_SEEN; diff --git a/src/cc/rogue/new_level.c b/src/cc/rogue/new_level.c index 2c0ae7b51..9b2348b3f 100644 --- a/src/cc/rogue/new_level.c +++ b/src/cc/rogue/new_level.c @@ -26,25 +26,25 @@ new_level(struct rogue_state *rs) PLACE *pp; char *sp; int i; - + player.t_flags &= ~ISHELD; /* unhold when you go down just in case */ if (level > max_level) - max_level = level; + max_level = level; /* * Clean things off from last level */ for (pp = places; pp < &places[MAXCOLS*MAXLINES]; pp++) { - pp->p_ch = ' '; - pp->p_flags = F_REAL; - pp->p_monst = NULL; + pp->p_ch = ' '; + pp->p_flags = F_REAL; + pp->p_monst = NULL; } clear(); /* * Free up the monsters on the last level */ for (tp = mlist; tp != NULL; tp = next(tp)) - free_list(tp->t_pack); + free_list(tp->t_pack); free_list(mlist); /* * Throw away stuff left on the previous level (if anything) @@ -53,32 +53,33 @@ new_level(struct rogue_state *rs) do_rooms(rs); /* Draw rooms */ do_passages(rs); /* Draw passages */ no_food++; + //fprintf(stderr,"new_level.%d\n",level); put_things(rs); /* Place objects (if any) */ /* * Place the traps */ if (rnd(10) < level) { - ntraps = rnd(level / 4) + 1; - if (ntraps > MAXTRAPS) - ntraps = MAXTRAPS; - i = ntraps; - while (i--) - { - /* - * not only wouldn't it be NICE to have traps in mazes - * (not that we care about being nice), since the trap - * number is stored where the passage number is, we - * can't actually do it. - */ - do - { - find_floor((struct room *) NULL, &stairs, FALSE, FALSE); - } while (chat(stairs.y, stairs.x) != FLOOR); - sp = &flat(stairs.y, stairs.x); - *sp &= ~F_REAL; - *sp |= rnd(NTRAPS); - } + ntraps = rnd(level / 4) + 1; + if (ntraps > MAXTRAPS) + ntraps = MAXTRAPS; + i = ntraps; + while (i--) + { + /* + * not only wouldn't it be NICE to have traps in mazes + * (not that we care about being nice), since the trap + * number is stored where the passage number is, we + * can't actually do it. + */ + do + { + find_floor((struct room *) NULL, &stairs, FALSE, FALSE); + } while (chat(stairs.y, stairs.x) != FLOOR); + sp = &flat(stairs.y, stairs.x); + *sp &= ~F_REAL; + *sp |= rnd(NTRAPS); + } } /* * Place the staircase down. @@ -86,17 +87,17 @@ new_level(struct rogue_state *rs) find_floor((struct room *) NULL, &stairs, FALSE, FALSE); chat(stairs.y, stairs.x) = STAIRS; seenstairs = FALSE; - + for (tp = mlist; tp != NULL; tp = next(tp)) - tp->t_room = roomin(rs,&tp->t_pos); - + tp->t_room = roomin(rs,&tp->t_pos); + find_floor((struct room *) NULL, &hero, FALSE, TRUE); enter_room(rs,&hero); mvaddch(hero.y, hero.x, PLAYER); if (on(player, SEEMONST)) - turn_see(FALSE); + turn_see(FALSE); if (on(player, ISHALU)) - visuals(rs,0); + visuals(rs,0); } /* @@ -147,7 +148,8 @@ put_things(struct rogue_state *rs) * Pick a new object and link it in the list */ obj = new_thing(rs); - attach(lvl_obj, obj); + //fprintf(stderr,"put_things i.%d obj.%p\n",i,obj); + attach(lvl_obj, obj); /* * Put it somewhere */ @@ -200,6 +202,7 @@ treas_room(struct rogue_state *rs) while (nm--) { find_floor(rp, &mp, 2 * MAXTRIES, FALSE); + //fprintf(stderr,"treas_room\n"); tp = new_thing(rs); tp->o_pos = mp; attach(lvl_obj, tp); diff --git a/src/cc/rogue/options.c b/src/cc/rogue/options.c index 667d83248..6907da598 100644 --- a/src/cc/rogue/options.c +++ b/src/cc/rogue/options.c @@ -403,7 +403,7 @@ parse_opts(char *str) char *sp; OPTION *op; int len; - char **i; + const char **i; char *start; while (*str) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 8385f95dd..ee628b4f0 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -252,25 +252,25 @@ inventory(struct rogue_state *rs,THING *list, int type) n_objs = 0; for (; list != NULL; list = next(list)) { - if (type && type != list->o_type && !(type == CALLABLE && - list->o_type != FOOD && list->o_type != AMULET) && - !(type == R_OR_S && (list->o_type == RING || list->o_type == STICK))) - continue; - n_objs++; + if (type && type != list->o_type && !(type == CALLABLE && + list->o_type != FOOD && list->o_type != AMULET) && + !(type == R_OR_S && (list->o_type == RING || list->o_type == STICK))) + continue; + n_objs++; #ifdef MASTER - if (!list->o_packch) - strcpy(inv_temp, "%s"); - else + if (!list->o_packch) + strcpy(inv_temp, "%s"); + else #endif - sprintf(inv_temp, "%c) %%s", list->o_packch); - msg_esc = TRUE; - if (add_line(rs,inv_temp, inv_name(list, FALSE)) == ESCAPE) - { - msg_esc = FALSE; - msg(rs,""); - return TRUE; - } - msg_esc = FALSE; + sprintf(inv_temp, "%c) %%s", list->o_packch); + msg_esc = TRUE; + if (add_line(rs,inv_temp, inv_name(list, FALSE)) == ESCAPE) + { + msg_esc = FALSE; + msg(rs,""); + return TRUE; + } + msg_esc = FALSE; } if (n_objs == 0) { diff --git a/src/cc/rogue/rip.c b/src/cc/rogue/rip.c index dc22566e9..69eb89751 100644 --- a/src/cc/rogue/rip.c +++ b/src/cc/rogue/rip.c @@ -218,6 +218,7 @@ score(int amount, int flags, char monst) signal(SIGINT, fp); } } + free(top_ten); } /* diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 8acdf8844..554c0ae4e 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -21,10 +21,48 @@ * The main program, of course */ struct rogue_state globalR; +void garbage_collect(); + +void purge_obj_guess(struct obj_info *array,int32_t n) +{ + int32_t i; + for (i=0; iseed; + //clear(); + purge_obj_guess(things,NUMTHINGS); + purge_obj_guess(ring_info,MAXRINGS); + purge_obj_guess(pot_info,MAXPOTIONS); + purge_obj_guess(arm_info,MAXARMORS); + purge_obj_guess(scr_info,MAXSCROLLS); + purge_obj_guess(weap_info,MAXWEAPONS + 1); + purge_obj_guess(ws_info,MAXSTICKS); + free_list(player._t._t_pack); + for (tp = mlist; tp != NULL; tp = next(tp)) + free_list(tp->t_pack); + free_list(mlist); + free_list(lvl_obj); + garbage_collect(); + + externs_clear(); + memset(d_list,0,sizeof(d_list)); + + memcpy(passages,origpassages,sizeof(passages)); + memcpy(monsters,origmonsters,sizeof(monsters)); + memcpy(things,origthings,sizeof(things)); + + memcpy(ring_info,origring_info,sizeof(ring_info)); + memcpy(pot_info,origpot_info,sizeof(pot_info)); + memcpy(arm_info,origarm_info,sizeof(arm_info)); + memcpy(scr_info,origscr_info,sizeof(scr_info)); + memcpy(weap_info,origweap_info,sizeof(weap_info)); + memcpy(ws_info,origws_info,sizeof(ws_info)); initscr(); /* Start up cursor package */ init_probs(); /* Set up prob tables for objects */ @@ -45,7 +83,8 @@ void rogueiterate(struct rogue_state *rs) my_exit(1); } // Set up windows - hw = newwin(LINES, COLS, 0, 0); + if ( hw == NULL ) + hw = newwin(LINES, COLS, 0, 0); idlok(stdscr, TRUE); idlok(hw, TRUE); #ifdef MASTER @@ -80,7 +119,7 @@ int32_t flushkeystrokes(struct rogue_state *rs) fclose(fp); if ( (fp= fopen("savefile","wb")) != 0 ) { - save_file(fp,0); + save_file(rs,fp,0); if ( 0 && (fp= fopen("savefile","rb")) != 0 ) { for (i=0; i<0x150; i++) @@ -145,11 +184,27 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) rs->seed = seed; rs->keystrokes = keystrokes; rs->numkeys = num; - rs->sleeptime = sleeptime; + rs->sleeptime = 1; + uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); + fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL) - starttime); + sleep(2); + + starttime = (uint32_t)time(NULL); + for (i=0; i<2000; i++) + { + memset(rs,0,sizeof(*rs)); + rs->seed = seed; + rs->keystrokes = keystrokes; + rs->numkeys = num; + rs->sleeptime = 0; + rogueiterate(rs); + } + fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL)-starttime); + sleep(1); if ( (fp= fopen("checkfile","wb")) != 0 ) { - save_file(fp,0); + save_file(rs,fp,0); if ( 0 && (fp= fopen("checkfile","rb")) != 0 ) { for (i=0; i<0x150; i++) @@ -160,7 +215,6 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) } free(rs); mvaddstr(LINES - 2, 0, (char *)"replay completed"); - refresh(); endwin(); } if ( keystrokes != 0 ) @@ -176,6 +230,7 @@ int rogue(int argc, char **argv, char **envp) rs->seed = atol(argv[1]); else rs->seed = 777; rs->guiflag = 1; + rs->sleeptime = 1; // non-zero to allow refresh() md_init(); #ifdef MASTER @@ -209,14 +264,14 @@ int rogue(int argc, char **argv, char **envp) lowtime = (int) time(NULL); #ifdef MASTER if (wizard && getenv("SEED") != NULL) - dnum = atoi(getenv("SEED")); + rs->seed = atoi(getenv("SEED")); else #endif - dnum = lowtime + md_getpid(); + //dnum = lowtime + md_getpid(); if ( rs != 0 ) seed = rs->seed; else seed = 777; - dnum = (int)seed; + //dnum = (int)seed; open_score(); @@ -242,8 +297,8 @@ int rogue(int argc, char **argv, char **envp) } else if (strcmp(argv[1], "-d") == 0) { - dnum = rnd(100); /* throw away some rnd()s to break patterns */ - while (--dnum) + rs->seed = rnd(100); /* throw away some rnd()s to break patterns */ + while (--rs->seed) rnd(100); purse = rnd(100) + 1; level = rnd(100) + 1; @@ -448,7 +503,8 @@ quit(int sig) clear(); mvprintw(LINES - 2, 0, "You quit with %d gold pieces", purse); move(LINES - 1, 0); - refresh(); + if ( rs->sleeptime != 0 ) + refresh(); score(purse, 1, 0); flushkeystrokes(rs); my_exit(0); @@ -459,7 +515,8 @@ quit(int sig) clrtoeol(); status(rs); move(oy, ox); - refresh(); + if ( rs->sleeptime != 0 ) + refresh(); mpos = 0; count = 0; to_death = FALSE; diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 3c500439c..e66362a10 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -313,19 +313,35 @@ /* * Now we define the structures and types */ +struct rogue_packitem +{ + int32_t type,launch,count,which,hplus,dplus,arm,flags,group; + char damage[8],hurldmg[8]; +}; + +struct rogue_player +{ + int32_t gold,hitpoints,strength,level,experience,packsize; + struct rogue_packitem roguepack[MAXPACK]; +}; + struct rogue_state { uint64_t seed; char *keystrokes; uint32_t needflush,replaydone; int32_t numkeys,ind,num,guiflag,counter,sleeptime; + struct rogue_player P; char buffered[512]; }; +extern struct rogue_state globalR; + int rogue(int argc, char **argv, char **envp); void rogueiterate(struct rogue_state *rs); int32_t roguefname(char *fname,uint64_t seed,int32_t counter); int32_t flushkeystrokes(struct rogue_state *rs); +int32_t rogue_restorepack(struct rogue_state *rs); /* * Help list @@ -476,6 +492,18 @@ struct monster { /* * External variables */ +extern const char *tr_name[],*inv_t_name[]; +extern const int32_t a_class[], e_levels[]; +extern const struct h_list helpstr[]; +extern const char *h_names[],*m_names[]; + + +extern const struct monster origmonsters[26]; +extern const struct room origpassages[MAXPASS]; +extern const struct obj_info origthings[NUMTHINGS],origring_info[MAXRINGS],origpot_info[MAXPOTIONS],origarm_info[MAXARMORS],origscr_info[MAXSCROLLS],origws_info[MAXSTICKS],origweap_info[MAXWEAPONS + 1]; +extern struct monster monsters[26]; +extern struct room passages[MAXPASS]; +extern struct obj_info things[NUMTHINGS],ring_info[MAXRINGS],pot_info[MAXPOTIONS],arm_info[MAXARMORS],scr_info[MAXSCROLLS],weap_info[MAXWEAPONS + 1],ws_info[MAXSTICKS]; extern bool after, again, allscore, amulet, door_stop, fight_flush, firstmove, has_hit, inv_describe, jump, kamikaze, @@ -483,19 +511,18 @@ extern bool after, again, allscore, amulet, door_stop, fight_flush, passgo, playing, q_comm, running, save_msg, see_floor, seenstairs, stat_msg, terse, to_death, tombstone; -extern char dir_ch, file_name[], home[], huh[], *inv_t_name[], +extern char dir_ch, file_name[], home[], huh[], l_last_comm, l_last_dir, last_comm, last_dir, *Numname, - outbuf[], *p_colors[], *r_stones[], *release, runch, - *s_names[], take, *tr_name[], *ws_made[], *ws_type[]; + outbuf[], *release, *s_names[], runch, take; +extern const char *ws_made[], *r_stones[], *p_colors[], *ws_type[]; -extern int a_class[], count, food_left, hungry_state, inpack, +extern int count, food_left, hungry_state, inpack, inv_type, lastscore, level, max_hit, max_level, mpos, n_objs, no_command, no_food, no_move, noscore, ntraps, purse, quiet, vf_hit; extern unsigned int numscores; -extern int dnum, e_levels[]; extern uint64_t seed; extern WINDOW *hw; @@ -507,16 +534,11 @@ extern PLACE places[]; extern THING *cur_armor, *cur_ring[], *cur_weapon, *l_last_pick, *last_pick, *lvl_obj, *mlist, player; -extern struct h_list helpstr[]; -extern struct room *oldrp, passages[], rooms[]; +extern struct room *oldrp, rooms[]; extern struct stats max_stats; -extern struct monster monsters[]; - -extern struct obj_info arm_info[], pot_info[], ring_info[], - scr_info[], things[], ws_info[], weap_info[]; /* * Function types @@ -617,7 +639,7 @@ void money(struct rogue_state *rs,int value); int move_monst(struct rogue_state *rs,THING *tp); void move_msg(struct rogue_state *rs,THING *obj); int msg(struct rogue_state *rs,char *fmt, ...); -void nameit(THING *obj, char *type, char *which, struct obj_info *op, char *(*prfunc)(THING *)); +void nameit(THING *obj, const char *type, const char *which, struct obj_info *op, char *(*prfunc)(THING *)); void new_level(struct rogue_state *rs); void new_monster(struct rogue_state *rs,THING *tp, char type, coord *cp); void numpass(int y, int x); @@ -651,12 +673,12 @@ void ring_off(struct rogue_state *rs); int rnd(int range); int rnd_room(void); int roll(int number, int sides); -int rs_save_file(FILE *savef); +int rs_save_file(struct rogue_state *rs,FILE *savef); int rs_restore_file(FILE *inf); void runto(struct rogue_state *rs,coord *runner); void rust_armor(struct rogue_state *rs,THING *arm); int save(int which); -void save_file(FILE *savef,int32_t guiflag); +void save_file(struct rogue_state *rs,FILE *savef,int32_t guiflag); void save_game(struct rogue_state *rs); int save_throw(int which, THING *tp); void score(int amount, int flags, char monst); @@ -778,13 +800,13 @@ extern int total; extern int between; extern int group; extern coord nh; -extern char *rainbow[]; +extern const char *rainbow[]; extern int cNCOLORS; -extern STONE stones[]; +extern const STONE stones[]; extern int cNSTONES; -extern char *wood[]; +extern const char *wood[]; extern int cNWOOD; -extern char *metal[]; +extern const char *metal[]; extern int cNMETAL; #endif diff --git a/src/cc/rogue/rooms.c b/src/cc/rogue/rooms.c index 1dcf3019a..31991b08f 100644 --- a/src/cc/rogue/rooms.c +++ b/src/cc/rogue/rooms.c @@ -37,7 +37,7 @@ do_rooms(struct rogue_state *rs) static coord top; coord bsze; /* maximum room size */ coord mp; - + bsze.x = NUMCOLS / 3; bsze.y = NUMLINES / 3; /* @@ -45,101 +45,101 @@ do_rooms(struct rogue_state *rs) */ for (rp = rooms; rp < &rooms[MAXROOMS]; rp++) { - rp->r_goldval = 0; - rp->r_nexits = 0; - rp->r_flags = 0; + rp->r_goldval = 0; + rp->r_nexits = 0; + rp->r_flags = 0; } /* * Put the gone rooms, if any, on the level */ left_out = rnd(4); for (i = 0; i < left_out; i++) - rooms[rnd_room()].r_flags |= ISGONE; + rooms[rnd_room()].r_flags |= ISGONE; /* * dig and populate all the rooms on the level */ for (i = 0, rp = rooms; i < MAXROOMS; rp++, i++) { - /* - * Find upper left corner of box that this room goes in - */ - top.x = (i % 3) * bsze.x + 1; - top.y = (i / 3) * bsze.y; - if (rp->r_flags & ISGONE) - { - /* - * Place a gone room. Make certain that there is a blank line - * for passage drawing. - */ - do - { - rp->r_pos.x = top.x + rnd(bsze.x - 2) + 1; - rp->r_pos.y = top.y + rnd(bsze.y - 2) + 1; - rp->r_max.x = -NUMCOLS; - rp->r_max.y = -NUMLINES; - } until (rp->r_pos.y > 0 && rp->r_pos.y < NUMLINES-1); - continue; - } - /* - * set room type - */ - if (rnd(10) < level - 1) - { - rp->r_flags |= ISDARK; /* dark room */ - if (rnd(15) == 0) - rp->r_flags = ISMAZE; /* maze room */ - } - /* - * Find a place and size for a random room - */ - if (rp->r_flags & ISMAZE) - { - rp->r_max.x = bsze.x - 1; - rp->r_max.y = bsze.y - 1; - if ((rp->r_pos.x = top.x) == 1) - rp->r_pos.x = 0; - if ((rp->r_pos.y = top.y) == 0) - { - rp->r_pos.y++; - rp->r_max.y--; - } - } - else - do - { - rp->r_max.x = rnd(bsze.x - 4) + 4; - rp->r_max.y = rnd(bsze.y - 4) + 4; - rp->r_pos.x = top.x + rnd(bsze.x - rp->r_max.x); - rp->r_pos.y = top.y + rnd(bsze.y - rp->r_max.y); - } until (rp->r_pos.y != 0); - draw_room(rp); - /* - * Put the gold in - */ - if (rnd(2) == 0 && (!amulet || level >= max_level)) - { - THING *gold; - - gold = new_item(); - gold->o_goldval = rp->r_goldval = GOLDCALC; - find_floor(rp, &rp->r_gold, FALSE, FALSE); - gold->o_pos = rp->r_gold; - chat(rp->r_gold.y, rp->r_gold.x) = GOLD; - gold->o_flags = ISMANY; - gold->o_group = GOLDGRP; - gold->o_type = GOLD; - attach(lvl_obj, gold); - } - /* - * Put the monster in - */ - if (rnd(100) < (rp->r_goldval > 0 ? 80 : 25)) - { - tp = new_item(); - find_floor(rp, &mp, FALSE, TRUE); - new_monster(rs,tp, randmonster(FALSE), &mp); - give_pack(rs,tp); - } + /* + * Find upper left corner of box that this room goes in + */ + top.x = (i % 3) * bsze.x + 1; + top.y = (i / 3) * bsze.y; + if (rp->r_flags & ISGONE) + { + /* + * Place a gone room. Make certain that there is a blank line + * for passage drawing. + */ + do + { + rp->r_pos.x = top.x + rnd(bsze.x - 2) + 1; + rp->r_pos.y = top.y + rnd(bsze.y - 2) + 1; + rp->r_max.x = -NUMCOLS; + rp->r_max.y = -NUMLINES; + } until (rp->r_pos.y > 0 && rp->r_pos.y < NUMLINES-1); + continue; + } + /* + * set room type + */ + if (rnd(10) < level - 1) + { + rp->r_flags |= ISDARK; /* dark room */ + if (rnd(15) == 0) + rp->r_flags = ISMAZE; /* maze room */ + } + /* + * Find a place and size for a random room + */ + if (rp->r_flags & ISMAZE) + { + rp->r_max.x = bsze.x - 1; + rp->r_max.y = bsze.y - 1; + if ((rp->r_pos.x = top.x) == 1) + rp->r_pos.x = 0; + if ((rp->r_pos.y = top.y) == 0) + { + rp->r_pos.y++; + rp->r_max.y--; + } + } + else + do + { + rp->r_max.x = rnd(bsze.x - 4) + 4; + rp->r_max.y = rnd(bsze.y - 4) + 4; + rp->r_pos.x = top.x + rnd(bsze.x - rp->r_max.x); + rp->r_pos.y = top.y + rnd(bsze.y - rp->r_max.y); + } until (rp->r_pos.y != 0); + draw_room(rp); + /* + * Put the gold in + */ + if (rnd(2) == 0 && (!amulet || level >= max_level)) + { + THING *gold; + + gold = new_item(); + gold->o_goldval = rp->r_goldval = GOLDCALC; + find_floor(rp, &rp->r_gold, FALSE, FALSE); + gold->o_pos = rp->r_gold; + chat(rp->r_gold.y, rp->r_gold.x) = GOLD; + gold->o_flags = ISMANY; + gold->o_group = GOLDGRP; + gold->o_type = GOLD; + attach(lvl_obj, gold); + } + /* + * Put the monster in + */ + if (rnd(100) < (rp->r_goldval > 0 ? 80 : 25)) + { + tp = new_item(); + find_floor(rp, &mp, FALSE, TRUE); + new_monster(rs,tp, randmonster(FALSE), &mp); + give_pack(rs,tp); + } } } diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index 8dcb65194..eec85b930 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -64,7 +64,8 @@ over: if (c == 'y' || c == 'Y') { addstr("Yes\n"); - refresh(); + if ( rs->sleeptime != 0 ) + refresh(); strcpy(buf, file_name); goto gotfile; } @@ -109,7 +110,7 @@ gotfile: msg(rs,strerror(errno)); } while (savef == NULL); - save_file(savef,1); + save_file(rs,savef,1); /* NOTREACHED */ } @@ -128,7 +129,7 @@ auto_save(int sig) md_ignoreallsignals(); if (file_name[0] != '\0' && ((savef = fopen(file_name, "w")) != NULL || (md_unlink_open_file(file_name, savef) >= 0 && (savef = fopen(file_name, "w")) != NULL))) - save_file(savef,1); + save_file(&globalR,savef,1); exit(0); } @@ -137,10 +138,17 @@ auto_save(int sig) * Write the saved game on the file */ -void -save_file(FILE *savef,int32_t guiflag) +char *rogue_packfname(struct rogue_state *rs,char *fname) { - char buf[80]; + sprintf(fname,"rogue.%llu.pack",(long long)rs->seed); + return(fname); +} + +void +save_file(struct rogue_state *rs,FILE *savef,int32_t guiflag) +{ + char buf[80],fname[512]; int32_t i,n,nonz,histo[0x100]; FILE *fp; + memset(&rs->P,0,sizeof(rs->P)); mvcur(0, COLS - 1, LINES - 1, 0); putchar('\n'); endwin(); @@ -152,13 +160,53 @@ save_file(FILE *savef,int32_t guiflag) sprintf(buf,"%d x %d\n", LINES, COLS); encwrite(buf,80,savef); } - rs_save_file(savef); + rs_save_file(rs,savef); + n = sizeof(rs->P) - sizeof(rs->P.roguepack) + sizeof(rs->P.roguepack[0])*rs->P.packsize; + memset(histo,0,sizeof(histo)); + for (i=0; iP)[i]); + histo[((uint8_t *)&rs->P)[i]]++; + } + fprintf(stderr," packsize.%d n.%d\n",rs->P.packsize,n); + if ( (fp= fopen(rogue_packfname(rs,fname),"wb")) != 0 ) + { + fwrite(&rs->P,1,n,fp); + fclose(fp); + } + for (i=nonz=0; i<0x100; i++) + if ( histo[i] != 0 ) + fprintf(stderr,"(%d %d) ",i,histo[i]), nonz++; + fprintf(stderr,"nonz.%d\n",nonz); fflush(savef); fclose(savef); if ( guiflag != 0 ) exit(0); } +int32_t rogue_restorepack(struct rogue_state *rs) +{ + FILE *fp; char fname[512]; int32_t retflag = -1; + memset(&rs->P,0,sizeof(rs->P)); + if ( (fp= fopen(rogue_packfname(rs,fname),"rb")) != 0 ) + { + if ( fread(&rs->P,1,sizeof(rs->P) - sizeof(rs->P.roguepack),fp) == sizeof(rs->P) - sizeof(rs->P.roguepack) ) + { + if ( rs->P.packsize > 0 && rs->P.packsize <= MAXPACK ) + { + if ( fread(&rs->P.roguepack,1,rs->P.packsize*sizeof(rs->P.roguepack[0]),fp) == rs->P.packsize*sizeof(rs->P.roguepack[0]) ) + { + fprintf(stderr,"roguepack[%d] restored\n",rs->P.packsize); + retflag = 0; + } + } + } + } + if ( retflag < 0 ) + memset(&rs->P,0,sizeof(rs->P)); + return(retflag); +} + /* * restore: * Restore a saved game from a file with elaborate checks for file diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index f18ee1e5f..d99f1b0dc 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -97,7 +97,7 @@ rs_read(FILE *inf, void *ptr, size_t size) } int -rs_write_int(FILE *savef, int c) +rs_write_int(FILE *savef, int32_t c) { unsigned char bytes[4]; unsigned char *buf = (unsigned char *) &c; @@ -120,7 +120,7 @@ rs_write_int(FILE *savef, int c) } int -rs_read_int(FILE *inf, int *i) +rs_read_int(FILE *inf, int32_t *i) { unsigned char bytes[4]; int input = 0; @@ -198,7 +198,7 @@ rs_read_chars(FILE *inf, char *i, int count) } int -rs_write_ints(FILE *savef, int *c, int count) +rs_write_ints(FILE *savef, int32_t *c, int count) { int n = 0; @@ -215,7 +215,7 @@ rs_write_ints(FILE *savef, int *c, int count) } int -rs_read_ints(FILE *inf, int *i, int count) +rs_read_ints(FILE *inf, int32_t *i, int count) { int n, value; @@ -300,7 +300,7 @@ rs_read_booleans(FILE *inf, bool *i, int count) } int -rs_write_short(FILE *savef, short c) +rs_write_short(FILE *savef, int16_t c) { unsigned char bytes[2]; unsigned char *buf = (unsigned char *) &c; @@ -321,7 +321,7 @@ rs_write_short(FILE *savef, short c) } int -rs_read_short(FILE *inf, short *i) +rs_read_short(FILE *inf, int16_t *i) { unsigned char bytes[2]; short input; @@ -345,7 +345,7 @@ rs_read_short(FILE *inf, short *i) } int -rs_write_shorts(FILE *savef, short *c, int count) +rs_write_shorts(FILE *savef, int16_t *c, int count) { int n = 0; @@ -362,7 +362,7 @@ rs_write_shorts(FILE *savef, short *c, int count) } int -rs_read_shorts(FILE *inf, short *i, int count) +rs_read_shorts(FILE *inf, int16_t *i, int count) { int n = 0, value = 0; @@ -382,7 +382,7 @@ rs_read_shorts(FILE *inf, short *i, int count) } int -rs_write_ushort(FILE *savef, unsigned short c) +rs_write_ushort(FILE *savef, uint16_t c) { unsigned char bytes[2]; unsigned char *buf = (unsigned char *) &c; @@ -403,7 +403,7 @@ rs_write_ushort(FILE *savef, unsigned short c) } int -rs_read_ushort(FILE *inf, unsigned short *i) +rs_read_ushort(FILE *inf, uint16_t *i) { unsigned char bytes[2]; unsigned short input; @@ -427,7 +427,7 @@ rs_read_ushort(FILE *inf, unsigned short *i) } int -rs_write_uint(FILE *savef, unsigned int c) +rs_write_uint(FILE *savef, uint32_t c) { unsigned char bytes[4]; unsigned char *buf = (unsigned char *) &c; @@ -450,7 +450,7 @@ rs_write_uint(FILE *savef, unsigned int c) } int -rs_read_uint(FILE *inf, unsigned int *i) +rs_read_uint(FILE *inf, uint32_t *i) { unsigned char bytes[4]; int input; @@ -476,7 +476,7 @@ rs_read_uint(FILE *inf, unsigned int *i) } int -rs_write_marker(FILE *savef, int id) +rs_write_marker(FILE *savef, int32_t id) { if (write_error) return(WRITESTAT); @@ -487,7 +487,7 @@ rs_write_marker(FILE *savef, int id) } int -rs_read_marker(FILE *inf, int id) +rs_read_marker(FILE *inf, int32_t id) { int nid; @@ -891,7 +891,7 @@ rs_write_scrolls(FILE *savef) return(WRITESTAT); for(i = 0; i < MAXSCROLLS; i++) - rs_write_string(savef, s_names[i]); + rs_write_string(savef, (char *)s_names[i]); return(READSTAT); } @@ -905,7 +905,7 @@ rs_read_scrolls(FILE *inf) return(READSTAT); for(i = 0; i < MAXSCROLLS; i++) - rs_read_new_string(inf, &s_names[i]); + rs_read_new_string(inf, (char **)&s_names[i]); return(READSTAT); } @@ -919,7 +919,7 @@ rs_write_potions(FILE *savef) return(WRITESTAT); for(i = 0; i < MAXPOTIONS; i++) - rs_write_string_index(savef, rainbow, cNCOLORS, p_colors[i]); + rs_write_string_index(savef, (char **)rainbow, cNCOLORS, (char *)p_colors[i]); return(WRITESTAT); } @@ -933,7 +933,7 @@ rs_read_potions(FILE *inf) return(READSTAT); for(i = 0; i < MAXPOTIONS; i++) - rs_read_string_index(inf, rainbow, cNCOLORS, &p_colors[i]); + rs_read_string_index(inf, (char **)rainbow, cNCOLORS, (char **)&p_colors[i]); return(READSTAT); } @@ -947,7 +947,7 @@ rs_write_rings(FILE *savef) return(WRITESTAT); for(i = 0; i < MAXRINGS; i++) - rs_write_stone_index(savef, stones, cNSTONES, r_stones[i]); + rs_write_stone_index(savef, (STONE *)stones, cNSTONES, (char *)r_stones[i]); return(WRITESTAT); } @@ -961,7 +961,7 @@ rs_read_rings(FILE *inf) return(READSTAT); for(i = 0; i < MAXRINGS; i++) - rs_read_stone_index(inf, stones, cNSTONES, &r_stones[i]); + rs_read_stone_index(inf, (STONE *)stones, cNSTONES, (char **)&r_stones[i]); return(READSTAT); } @@ -979,12 +979,12 @@ rs_write_sticks(FILE *savef) if (strcmp(ws_type[i],"staff") == 0) { rs_write_int(savef,0); - rs_write_string_index(savef, wood, cNWOOD, ws_made[i]); + rs_write_string_index(savef, (char **)wood, cNWOOD, (char *)ws_made[i]); } else { rs_write_int(savef,1); - rs_write_string_index(savef, metal, cNMETAL, ws_made[i]); + rs_write_string_index(savef, (char **)metal, cNMETAL, (char *)ws_made[i]); } } @@ -1005,12 +1005,12 @@ rs_read_sticks(FILE *inf) if (list == 0) { - rs_read_string_index(inf, wood, cNWOOD, &ws_made[i]); + rs_read_string_index(inf, (char **)wood, cNWOOD, (char **)&ws_made[i]); ws_type[i] = "staff"; } else { - rs_read_string_index(inf, metal, cNMETAL, &ws_made[i]); + rs_read_string_index(inf, (char **)metal, cNMETAL, (char **)&ws_made[i]); ws_type[i] = "wand"; } } @@ -1336,13 +1336,65 @@ rs_read_monsters(FILE *inf, struct monster *m, int count) return(READSTAT); } -int -rs_write_object(FILE *savef, THING *o) +void rogue_restoreobject(THING *o,struct rogue_packitem *item) { + o->_o._o_type = item->type; + o->_o._o_launch = item->launch; + memcpy(o->_o._o_damage,item->damage,sizeof(item->damage)); + memcpy(o->_o._o_hurldmg,item->hurldmg,sizeof(item->hurldmg)); + o->_o._o_count = item->count; + o->_o._o_which = item->which; + o->_o._o_hplus = item->hplus; + o->_o._o_dplus = item->dplus; + o->_o._o_arm = item->arm; + o->_o._o_flags = item->flags; + o->_o._o_group = item->group; +} + +int32_t packsave(struct rogue_packitem *item,int32_t type,int32_t launch,char *damage,int32_t damagesize,char *hurldmg,int32_t hurlsize,int32_t count,int32_t which,int32_t hplus,int32_t dplus,int32_t arm,int32_t flags,int32_t group) +{ + if ( damagesize != 8 || hurlsize != 8 ) + { + fprintf(stderr,"unexpected damagesize.%d or hurlsize.%d != 8\n",damagesize,hurlsize); + return(-1); + } + item->type = type; + item->launch = launch; + memcpy(item->damage,damage,damagesize); + memcpy(item->hurldmg,hurldmg,hurlsize); + item->count = count; + item->which = which; + item->hplus = hplus; + item->dplus = dplus; + item->arm = arm; + item->flags = flags; + item->group = group; + return(0); +} + +int +rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) +{ + struct rogue_packitem *item; if (write_error) return(WRITESTAT); - //fprintf(stderr,"object %ld -> ",ftell(savef)); - + if ( o->_o._o_packch != 0 ) + { + item = &rs->P.roguepack[rs->P.packsize]; + if ( rs->P.packsize++ == 0 ) + { + rs->P.gold = purse; + rs->P.hitpoints = max_hp; + rs->P.strength = max_stats.s_str; + rs->P.level = pstats.s_lvl; + rs->P.experience = pstats.s_exp; + fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d\n",ftell(savef),purse,max_hp,max_stats.s_str,pstats.s_lvl,pstats.s_exp); + }; + fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); + if ( rs->P.packsize < MAXPACK ) + packsave(item,o->_o._o_type,o->_o._o_launch,o->_o._o_damage,sizeof(o->_o._o_damage),o->_o._o_hurldmg,sizeof(o->_o._o_hurldmg),o->_o._o_count,o->_o._o_which,o->_o._o_hplus,o->_o._o_dplus,o->_o._o_arm,o->_o._o_flags,o->_o._o_group); + } + rs_write_marker(savef, RSID_OBJECT); rs_write_int(savef, o->_o._o_type); rs_write_coord(savef, o->_o._o_pos); @@ -1358,7 +1410,6 @@ rs_write_object(FILE *savef, THING *o) rs_write_int(savef, o->_o._o_flags); rs_write_int(savef, o->_o._o_group); rs_write_string(savef, o->_o._o_label); - //fprintf(stderr,"%ld\n",ftell(savef)); return(WRITESTAT); } @@ -1388,7 +1439,7 @@ rs_read_object(FILE *inf, THING *o) } int -rs_write_object_list(FILE *savef, THING *l) +rs_write_object_list(struct rogue_state *rs,FILE *savef, THING *l) { if (write_error) return(WRITESTAT); @@ -1398,7 +1449,7 @@ rs_write_object_list(FILE *savef, THING *l) rs_write_int(savef, list_size(l)); for( ;l != NULL; l = l->l_next) - rs_write_object(savef, l); + rs_write_object(rs,savef, l); //fprintf(stderr,"%ld\n",ftell(savef)); return(WRITESTAT); @@ -1526,7 +1577,7 @@ find_object_coord(THING *objlist, coord *c) } int -rs_write_thing(FILE *savef, THING *t) +rs_write_thing(struct rogue_state *rs,FILE *savef, THING *t) { int i = -1; @@ -1610,7 +1661,7 @@ rs_write_thing(FILE *savef, THING *t) rs_write_short(savef, t->_t._t_flags); rs_write_stats(savef, &t->_t._t_stats); rs_write_room_reference(savef, t->_t._t_room); - rs_write_object_list(savef, t->_t._t_pack); + rs_write_object_list(rs,savef, t->_t._t_pack); //fprintf(stderr,"%ld\n",ftell(savef)); return(WRITESTAT); @@ -1712,7 +1763,7 @@ rs_fix_thing(THING *t) } int -rs_write_thing_list(FILE *savef, THING *l) +rs_write_thing_list(struct rogue_state *rs,FILE *savef, THING *l) { int cnt = 0; @@ -1729,7 +1780,7 @@ rs_write_thing_list(FILE *savef, THING *l) return(WRITESTAT); while (l != NULL) { - rs_write_thing(savef, l); + rs_write_thing(rs,savef, l); l = l->l_next; } @@ -1888,7 +1939,7 @@ rs_read_places(FILE *inf, PLACE *places, int count) } int -rs_save_file(FILE *savef) +rs_save_file(struct rogue_state *rs,FILE *savef) { if (write_error) return(WRITESTAT); @@ -1941,12 +1992,12 @@ rs_save_file(FILE *savef) rs_write_int(savef,orig_dsusp); rs_write_chars(savef, fruit, MAXSTR); //rs_write_chars(savef, home, MAXSTR); - rs_write_strings(savef,inv_t_name,3); + rs_write_strings(savef,(char **)inv_t_name,3); rs_write_char(savef,l_last_comm); rs_write_char(savef,l_last_dir); rs_write_char(savef,last_comm); rs_write_char(savef,last_dir); - rs_write_strings(savef,tr_name,8); + rs_write_strings(savef,(char **)tr_name,8); rs_write_int(savef,n_objs); rs_write_int(savef, ntraps); rs_write_int(savef, hungry_state); @@ -1956,7 +2007,7 @@ rs_save_file(FILE *savef) rs_write_int(savef, max_level); rs_write_int(savef, mpos); rs_write_int(savef, no_food); - rs_write_ints(savef,a_class,MAXARMORS); + rs_write_ints(savef,(int32_t *)a_class,MAXARMORS); rs_write_int(savef, count); rs_write_int(savef, food_left); rs_write_int(savef, lastscore); @@ -1968,11 +2019,11 @@ rs_save_file(FILE *savef) //rs_write_int(savef, dnum); rs_write_int(savef, (int32_t)(seed&0xffffffff)); rs_write_int(savef, (int32_t)((seed>>32)&0xffffffff)); - rs_write_ints(savef, e_levels, 21); + rs_write_ints(savef, (int32_t *)e_levels, 21); rs_write_coord(savef, delta); rs_write_coord(savef, oldpos); rs_write_coord(savef, stairs); - rs_write_thing(savef, &player); + rs_write_thing(rs,savef, &player); rs_write_object_reference(savef, player.t_pack, cur_armor); rs_write_object_reference(savef, player.t_pack, cur_ring[0]); rs_write_object_reference(savef, player.t_pack, cur_ring[1]); @@ -1980,8 +2031,8 @@ rs_save_file(FILE *savef) rs_write_object_reference(savef, player.t_pack, l_last_pick); rs_write_object_reference(savef, player.t_pack, last_pick); - rs_write_object_list(savef, lvl_obj); - rs_write_thing_list(savef, mlist); + rs_write_object_list(rs,savef, lvl_obj); + rs_write_thing_list(rs,savef, mlist); rs_write_places(savef,places,MAXLINES*MAXCOLS); @@ -2073,12 +2124,12 @@ rs_restore_file(FILE *inf) rs_read_int(inf,&orig_dsusp); rs_read_chars(inf, fruit, MAXSTR); //rs_read_chars(inf, home, MAXSTR); - rs_read_new_strings(inf,inv_t_name,3); + rs_read_new_strings(inf,(char **)inv_t_name,3); rs_read_char(inf, &l_last_comm); rs_read_char(inf, &l_last_dir); rs_read_char(inf, &last_comm); rs_read_char(inf, &last_dir); - rs_read_new_strings(inf,tr_name,8); + rs_read_new_strings(inf,(char **)tr_name,8); rs_read_int(inf, &n_objs); rs_read_int(inf, &ntraps); rs_read_int(inf, &hungry_state); @@ -2088,7 +2139,7 @@ rs_restore_file(FILE *inf) rs_read_int(inf, &max_level); rs_read_int(inf, &mpos); rs_read_int(inf, &no_food); - rs_read_ints(inf,a_class,MAXARMORS); + rs_read_ints(inf,(int32_t *)a_class,MAXARMORS); rs_read_int(inf, &count); rs_read_int(inf, &food_left); rs_read_int(inf, &lastscore); @@ -2102,7 +2153,7 @@ rs_restore_file(FILE *inf) rs_read_int(inf, &lownum); rs_read_int(inf, &highnum); seed = ((uint64_t)highnum<<32) | (lownum&0xffffffff); - rs_read_ints(inf,e_levels,21); + rs_read_ints(inf,(int32_t *)e_levels,21); rs_read_coord(inf, &delta); rs_read_coord(inf, &oldpos); rs_read_coord(inf, &stairs); diff --git a/src/cc/rogue/sticks.c b/src/cc/rogue/sticks.c index 7b01fe34c..7f9dc6ec2 100644 --- a/src/cc/rogue/sticks.c +++ b/src/cc/rogue/sticks.c @@ -405,7 +405,8 @@ def: msg(rs,"the %s whizzes by you", name); } mvaddch(pos.y, pos.x, dirch); - refresh(); + if ( rs->sleeptime != 0 ) + refresh(); } } for (c2 = spotpos; c2 < c1; c2++) diff --git a/src/cc/rogue/things.c b/src/cc/rogue/things.c index 2247c67e8..660e0720e 100644 --- a/src/cc/rogue/things.c +++ b/src/cc/rogue/things.c @@ -220,6 +220,7 @@ new_thing(struct rogue_state *rs) int r; cur = new_item(); + // 7th new_thing orphaned fprintf(stderr,"new_thing.%p\n",cur); cur->o_hplus = 0; cur->o_dplus = 0; strncpy(cur->o_damage, "0x0", sizeof(cur->o_damage)); @@ -499,7 +500,8 @@ add_line(struct rogue_state *rs,char *fmt, char *arg) if (inv_type == INV_OVER && fmt == NULL && !newpage) { msg(rs,""); - refresh(); + if ( rs->sleeptime != 0 ) + refresh(); tw = newwin(line_cnt + 1, maxlen + 2, 0, COLS - maxlen - 3); sw = subwin(tw, line_cnt + 1, maxlen + 1, 0, COLS - maxlen - 2); for (y = 0; y <= line_cnt; y++) @@ -615,7 +617,7 @@ nothing(char type) */ void -nameit(THING *obj, char *type, char *which, struct obj_info *op, +nameit(THING *obj, const char *type,const char *which, struct obj_info *op, char *(*prfunc)(THING *)) { char *pb; @@ -633,7 +635,7 @@ nameit(THING *obj, char *type, char *which, struct obj_info *op, sprintf(pb, "called %s%s(%s)", op->oi_guess, (*prfunc)(obj), which); } else if (obj->o_count == 1) - sprintf(prbuf, "A%s %s %s", vowelstr(which), which, type); + sprintf(prbuf, "A%s %s %s", vowelstr((char *)which), which, type); else sprintf(prbuf, "%d %s %ss", obj->o_count, which, type); } diff --git a/src/cc/rogue/weapons.c b/src/cc/rogue/weapons.c index 51a4b7730..6693f0814 100644 --- a/src/cc/rogue/weapons.c +++ b/src/cc/rogue/weapons.c @@ -105,7 +105,8 @@ do_motion(struct rogue_state *rs,THING *obj, int ydelta, int xdelta) if (cansee(rs,unc(obj->o_pos)) && !terse) { mvaddch(obj->o_pos.y, obj->o_pos.x, obj->o_type); - refresh(); + if ( rs->sleeptime != 0 ) + refresh(); } continue; } @@ -161,7 +162,6 @@ void init_weapon(THING *weap, int which) { struct init_weaps *iwp; - weap->o_type = WEAPON; weap->o_which = which; iwp = &init_dam[which]; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 499b4d48c..b5538d87a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -71,9 +71,9 @@ //////////////////////// start of CClib interface //./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & -// cclib newgame 17 \"[maxplayers,buyin]\" +// cclib newgame 17 \"[3,100]\" // cclib pending 17 -// cclib txidinfo 17 \"[%2235e99df53c981a937bfa2ce7bfb303cea0249dba34831592c140d1cb729cb19f%22]\" +// cclib gameinfo 17 \"[%22783369750c2c7003d3dcee327b830025c560b594f65648c0abbac733a661ea39%22]\" // ./rogue gui -> creates keystroke files // cclib register 17 \"[%2235e99df53c981a937bfa2ce7bfb303cea0249dba34831592c140d1cb729cb19f%22,%22%22]\" // cclib keystrokes 17 \"[]\" @@ -452,8 +452,7 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( n > 0 ) { UniValue pobj(UniValue::VOBJ); - t = jbits256(jitem(params,0),0); - memcpy(&playertxid,&t,sizeof(playertxid));; + playertxid = juint256(jitem(params,0)); if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"invalid playerdata")); result.push_back(Pair("rogue",rogue_playerobj(pobj,playerdata))); @@ -481,14 +480,12 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( n > 0 ) { - t = jbits256(jitem(params,0),0); - memcpy(&gametxid,&t,sizeof(gametxid)); + gametxid = juint256(jitem(params,0)); if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,gametxid) == 0 ) { if ( n > 1 && maxplayers > 1 ) { - t = jbits256(jitem(params,0),0); - memcpy(&playertxid,&t,sizeof(playertxid)); + playertxid = juint256(jitem(params,1)); if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"couldnt extract valid playerdata")); } @@ -522,8 +519,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param rogue_univalue(result,"keystrokes",-1,-1); if ( (params= cclib_reparse(&n,params)) != 0 && n == 2 && (keystrokestr= jstr(jitem(params,1),0)) != 0 ) { - t = jbits256(jitem(params,0),0); - memcpy(&gametxid,&t,sizeof(gametxid)); + gametxid = juint256(jitem(params,0)); keystrokes = ParseHex(keystrokestr); mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); @@ -588,8 +584,7 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( n > 0 ) { - t = jbits256(jitem(params,0),0); - memcpy(&txid,&t,sizeof(txid)); + txid = juint256(jitem(params,0)); result.push_back(Pair("txid",txid.GetHex())); if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,txid) == 0 ) { From afc2af57d59fdf795f35fae029c2b76aa7c0d2d5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 21:11:29 -1100 Subject: [PATCH 0332/1145] Txid for gameinfo --- src/cc/rogue_rpc.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b5538d87a..3470a36c7 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -74,6 +74,7 @@ // cclib newgame 17 \"[3,100]\" // cclib pending 17 // cclib gameinfo 17 \"[%22783369750c2c7003d3dcee327b830025c560b594f65648c0abbac733a661ea39%22]\" +// cclib register 17 \"[%22783369750c2c7003d3dcee327b830025c560b594f65648c0abbac733a661ea39%22]\" // ./rogue gui -> creates keystroke files // cclib register 17 \"[%2235e99df53c981a937bfa2ce7bfb303cea0249dba34831592c140d1cb729cb19f%22,%22%22]\" // cclib keystrokes 17 \"[]\" @@ -172,10 +173,10 @@ void rogue_univalue(UniValue &result,const char *method,int64_t maxplayers,int64 } } -void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin) +void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 txid) { CBlockIndex *pindex; int32_t ht; uint256 hashBlock; uint64_t seed; char cmd[512]; - if ( (pindex= komodo_blockindex(hashBlock)) != 0 ) + if ( (pindex= komodo_blockindex(txid)) != 0 ) { ht = pindex->GetHeight(); obj.push_back(Pair("height",ht)); @@ -409,7 +410,7 @@ UniValue rogue_rawtxresult(UniValue &result,std::string rawtx,int32_t broadcastf UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey roguepk,mypk; char *jsonstr; uint64_t inputsum,change,required,buyin=0,amount = 0; int32_t i,n,maxplayers = 1; + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey roguepk,mypk; char *jsonstr; uint64_t inputsum,change,required,buyin=0; int32_t i,n,maxplayers = 1; if ( txfee == 0 ) txfee = 10000; if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -435,7 +436,7 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,ROGUE_REGISTRATIONSIZE,roguepk,roguepk)); if ( (change= inputsum - required) >= txfee ) mtx.vout.push_back(MakeCC1vout(cp->evalcode,change,roguepk)); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_newgameopret(amount,maxplayers)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_newgameopret(buyin,maxplayers)); return(rogue_rawtxresult(result,rawtx,0)); } else return(cclib_error(result,"illegal maxplayers")); @@ -589,7 +590,7 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,txid) == 0 ) { result.push_back(Pair("result","success")); - rogue_gamefields(result,maxplayers,buyin); + rogue_gamefields(result,maxplayers,buyin,txid); for (i=0; i Date: Tue, 5 Feb 2019 21:13:36 -1100 Subject: [PATCH 0333/1145] Get hashBlock --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3470a36c7..0c9b9d70a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -175,8 +175,8 @@ void rogue_univalue(UniValue &result,const char *method,int64_t maxplayers,int64 void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 txid) { - CBlockIndex *pindex; int32_t ht; uint256 hashBlock; uint64_t seed; char cmd[512]; - if ( (pindex= komodo_blockindex(txid)) != 0 ) + CBlockIndex *pindex; int32_t ht; uint256 hashBlock; uint64_t seed; char cmd[512]; CTransaction tx; + if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) { ht = pindex->GetHeight(); obj.push_back(Pair("height",ht)); From 2fcf3f3f0f7c05a7fa285b22f90ffab140f1be43 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 21:29:18 -1100 Subject: [PATCH 0334/1145] 1of2 signing --- src/cc/CCinclude.h | 4 ++-- src/cc/CCtx.cpp | 2 +- src/cc/CCutils.cpp | 5 +++-- src/cc/channels.cpp | 2 +- src/cc/heir_validate.h | 7 +++++-- src/cc/marmara.cpp | 4 +++- src/cc/rogue_rpc.cpp | 17 +++++++++++++---- 7 files changed, 28 insertions(+), 13 deletions(-) diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index 52f2d7c1f..bc5ed20ed 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -95,7 +95,7 @@ struct CCcontract_info // this for 1of2 keys coins cryptocondition (for this evalcode) // NOTE: only one evalcode is allowed at this time char coins1of2addr[64]; - CPubKey coins1of2pk[2]; + CPubKey coins1of2pk[2]; uint8_t coins1of2priv[32]; // the same for tokens 1of2 keys cc char tokens1of2addr[64]; @@ -195,7 +195,7 @@ CC *MakeCCcond1of2(uint8_t evalcode,CPubKey pk1,CPubKey pk2); CC* GetCryptoCondition(CScript const& scriptSig); void CCaddr2set(struct CCcontract_info *cp,uint8_t evalcode,CPubKey pk,uint8_t *priv,char *coinaddr); void CCaddr3set(struct CCcontract_info *cp,uint8_t evalcode,CPubKey pk,uint8_t *priv,char *coinaddr); -void CCaddr1of2set(struct CCcontract_info *cp, CPubKey pk1, CPubKey pk2, char *coinaddr); +void CCaddr1of2set(struct CCcontract_info *cp, CPubKey pk1, CPubKey pk2,uint8_t *priv,char *coinaddr); CTxOut MakeTokensCC1of2vout(uint8_t evalcode, CAmount nValue, CPubKey pk1, CPubKey pk2); CTxOut MakeTokensCC1vout(uint8_t evalcode, CAmount nValue, CPubKey pk); diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index 630c887f0..932677e20 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -207,7 +207,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran else if (strcmp(cp->coins1of2addr, destaddr) == 0) { //fprintf(stderr,"FinalizeCCTx() matched %s unspendable1of2!\n",cp->coins1of2addr); - privkey = myprivkey; + privkey = cp->coins1of2priv;//myprivkey; if (othercond1of2 == 0) othercond1of2 = MakeCCcond1of2(cp->evalcode, cp->coins1of2pk[0], cp->coins1of2pk[1]); cond = othercond1of2; diff --git a/src/cc/CCutils.cpp b/src/cc/CCutils.cpp index 6dff5d3cd..88231fcd9 100644 --- a/src/cc/CCutils.cpp +++ b/src/cc/CCutils.cpp @@ -244,11 +244,12 @@ void CCaddr3set(struct CCcontract_info *cp,uint8_t evalcode,CPubKey pk,uint8_t * } // set pubkeys, myprivkey and 1of2 cc addr for spending from 1of2 cryptocondition vout: -void CCaddr1of2set(struct CCcontract_info *cp, CPubKey pk1, CPubKey pk2, char *coinaddr) +void CCaddr1of2set(struct CCcontract_info *cp, CPubKey pk1, CPubKey pk2,uint8_t *priv,char *coinaddr) { cp->coins1of2pk[0] = pk1; cp->coins1of2pk[1] = pk2; - strcpy(cp->coins1of2addr, coinaddr); + memcpy(cp->coins1of2priv,priv,32); + strcpy(cp->coins1of2addr,coinaddr); } // set pubkeys, myprivkey and 1of2 cc addr for spending from 1of2 tokens cryptocondition vout: diff --git a/src/cc/channels.cpp b/src/cc/channels.cpp index e6f4b48c6..ca069ee57 100644 --- a/src/cc/channels.cpp +++ b/src/cc/channels.cpp @@ -455,7 +455,7 @@ int64_t AddChannelsInputs(struct CCcontract_info *cp,CMutableTransaction &mtx, C mtx.vin.push_back(CTxIn(txid,marker,CScript())); Myprivkey(myprivkey); if (tokenid!=zeroid) CCaddrTokens1of2set(cp,srcpub,destpub,coinaddr); - else CCaddr1of2set(cp,srcpub,destpub,coinaddr); + else CCaddr1of2set(cp,srcpub,destpub,myprivkey,coinaddr); return totalinputs; } else return 0; diff --git a/src/cc/heir_validate.h b/src/cc/heir_validate.h index 15ab133e4..890e2b710 100644 --- a/src/cc/heir_validate.h +++ b/src/cc/heir_validate.h @@ -51,8 +51,11 @@ public: cpHeir = CCinit(&heirC, EVAL_HEIR); return GetCCaddress1of2(cpHeir, coinaddr, ownerPubkey, heirPubkey); } - static void CCaddrCoinsOrTokens1of2set(struct CCcontract_info *cp, CPubKey ownerPubkey, CPubKey heirPubkey, char *coinaddr) { - CCaddr1of2set(cp, ownerPubkey, heirPubkey, coinaddr); + static void CCaddrCoinsOrTokens1of2set(struct CCcontract_info *cp, CPubKey ownerPubkey, CPubKey heirPubkey, char *coinaddr) + { + uint8_t mypriv[32]; + Myprivkey(mypriv); + CCaddr1of2set(cp, ownerPubkey, heirPubkey,mypriv, coinaddr); } }; diff --git a/src/cc/marmara.cpp b/src/cc/marmara.cpp index 8bb306d9b..f43f3a559 100644 --- a/src/cc/marmara.cpp +++ b/src/cc/marmara.cpp @@ -455,7 +455,9 @@ UniValue MarmaraLock(uint64_t txfee,int64_t amount,int32_t height) GetCCaddress1of2(cp,coinaddr,Marmarapk,mypk); SetCCunspents(unspentOutputs,coinaddr); threshold = remains / (MARMARA_VINS+1); - CCaddr1of2set(cp,Marmarapk,mypk,coinaddr); + uint8_t mypriv[32]; + Myprivkey(mypriv); + CCaddr1of2set(cp,Marmarapk,mypk,mypriv,coinaddr); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { txid = it->first.txhash; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 0c9b9d70a..9ef8e7814 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -173,10 +173,15 @@ void rogue_univalue(UniValue &result,const char *method,int64_t maxplayers,int64 } } -void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 txid) +int32_t rogue_iamregistered(CTransaction tx) +{ + return(0); +} + +void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gametxid) { CBlockIndex *pindex; int32_t ht; uint256 hashBlock; uint64_t seed; char cmd[512]; CTransaction tx; - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) + if ( GetTransaction(gametxid,tx,hashBlock,false) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) { ht = pindex->GetHeight(); obj.push_back(Pair("height",ht)); @@ -190,7 +195,9 @@ void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 txi memcpy(&seed,&hashBlock,sizeof(seed)); seed &= (1LL << 62) - 1; obj.push_back(Pair("seed",(int64_t)seed)); - sprintf(cmd,"./rogue %llu gui",(long long)seed); + if ( rogue_iamregistered(tx) > 0 ) + sprintf(cmd,"./rogue %llu gui",(long long)seed); + else sprintf(cmd,"./komodo-cli -ac_name=%s cclib register \\\"[%22%s%22]\\\" %d",ASSETCHAINS_SYMBOL,gametxid.ToString().c_str(),EVAL_ROGUE); obj.push_back(Pair("run",cmd)); } } @@ -470,7 +477,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vin3+ -> buyin // vout0 -> keystrokes/completion baton CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t maxplayers,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx; std::vector playerdata; std::string rawtx; bits256 t; + UniValue result(UniValue::VOBJ); char destaddr[64]; uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t maxplayers,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx; std::vector playerdata; std::string rawtx; bits256 t; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -498,6 +505,8 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) else if ( buyin > 0 && AddNormalinputs(mtx,mypk,buyin,64) < buyin ) return(cclib_error(result,"couldnt find enough normal funds for buyin")); mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,inputsum-txfee,roguepk,mypk)); + GetCCaddress1of2(cp,destaddr,roguepk,roguepk); + CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_registeropret(gametxid,playertxid)); return(rogue_rawtxresult(result,rawtx,0)); } else return(cclib_error(result,"invalid gametxid")); From 0314166aebe24921267ea8d40ccedfcbf86157f2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 21:31:03 -1100 Subject: [PATCH 0335/1145] %% --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9ef8e7814..89e2f451e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -197,7 +197,7 @@ void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gam obj.push_back(Pair("seed",(int64_t)seed)); if ( rogue_iamregistered(tx) > 0 ) sprintf(cmd,"./rogue %llu gui",(long long)seed); - else sprintf(cmd,"./komodo-cli -ac_name=%s cclib register \\\"[%22%s%22]\\\" %d",ASSETCHAINS_SYMBOL,gametxid.ToString().c_str(),EVAL_ROGUE); + else sprintf(cmd,"./komodo-cli -ac_name=%s cclib register \\\"[%%22%s%%22]\\\" %d",ASSETCHAINS_SYMBOL,gametxid.ToString().c_str(),EVAL_ROGUE); obj.push_back(Pair("run",cmd)); } } From 06260a75e9aadf49ffdb37be49dde3f15be1b365 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 21:47:57 -1100 Subject: [PATCH 0336/1145] Fast registration for single player --- src/cc/rogue_rpc.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 89e2f451e..3d487d456 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -180,15 +180,16 @@ int32_t rogue_iamregistered(CTransaction tx) void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gametxid) { - CBlockIndex *pindex; int32_t ht; uint256 hashBlock; uint64_t seed; char cmd[512]; CTransaction tx; + CBlockIndex *pindex; int32_t ht,delay; uint256 hashBlock; uint64_t seed; char cmd[512]; CTransaction tx; if ( GetTransaction(gametxid,tx,hashBlock,false) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) { ht = pindex->GetHeight(); + delay = ROGUE_REGISTRATION * (maxplayers > 1); obj.push_back(Pair("height",ht)); - obj.push_back(Pair("start",ht+ROGUE_REGISTRATION)); - if ( komodo_nextheight() > ht+ROGUE_REGISTRATION ) + obj.push_back(Pair("start",ht+delay)); + if ( komodo_nextheight() > ht+delay ) { - if ( (pindex= komodo_chainactive(ht+ROGUE_REGISTRATION)) != 0 ) + if ( (pindex= komodo_chainactive(ht+delay)) != 0 ) { hashBlock = pindex->GetBlockHash(); obj.push_back(Pair("starthash",hashBlock.ToString())); @@ -197,7 +198,7 @@ void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gam obj.push_back(Pair("seed",(int64_t)seed)); if ( rogue_iamregistered(tx) > 0 ) sprintf(cmd,"./rogue %llu gui",(long long)seed); - else sprintf(cmd,"./komodo-cli -ac_name=%s cclib register \\\"[%%22%s%%22]\\\" %d",ASSETCHAINS_SYMBOL,gametxid.ToString().c_str(),EVAL_ROGUE); + else sprintf(cmd,"./komodo-cli -ac_name=%s cclib register %d \"[%%22%s%%22]\"",ASSETCHAINS_SYMBOL,gametxid.ToString().c_str(),EVAL_ROGUE); obj.push_back(Pair("run",cmd)); } } @@ -602,7 +603,7 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) rogue_gamefields(result,maxplayers,buyin,txid); for (i=0; i Date: Tue, 5 Feb 2019 21:49:25 -1100 Subject: [PATCH 0337/1145] Switch order --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3d487d456..b59efef81 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -198,7 +198,7 @@ void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gam obj.push_back(Pair("seed",(int64_t)seed)); if ( rogue_iamregistered(tx) > 0 ) sprintf(cmd,"./rogue %llu gui",(long long)seed); - else sprintf(cmd,"./komodo-cli -ac_name=%s cclib register %d \"[%%22%s%%22]\"",ASSETCHAINS_SYMBOL,gametxid.ToString().c_str(),EVAL_ROGUE); + else sprintf(cmd,"./komodo-cli -ac_name=%s cclib register %d \"[%%22%s%%22]\"",ASSETCHAINS_SYMBOL,EVAL_ROGUE,gametxid.ToString().c_str()); obj.push_back(Pair("run",cmd)); } } From 7c4b531e65f5a30b24a3d0c89242579889b88c65 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 21:51:07 -1100 Subject: [PATCH 0338/1145] Offset by 2 --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b59efef81..0770edd72 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -387,7 +387,7 @@ int64_t rogue_registrationbaton(CMutableTransaction &mtx,uint256 gametxid,CTrans r = rand() % maxplayers; for (j=0; j Date: Tue, 5 Feb 2019 22:06:47 -1100 Subject: [PATCH 0339/1145] +prints --- src/cc/rogue_rpc.cpp | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 0770edd72..5a1721018 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -173,12 +173,12 @@ void rogue_univalue(UniValue &result,const char *method,int64_t maxplayers,int64 } } -int32_t rogue_iamregistered(CTransaction tx) +int32_t rogue_iamregistered(CTransaction tx,char *myrogueaddr) { return(0); } -void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gametxid) +void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gametxid,char *myrogueaddr) { CBlockIndex *pindex; int32_t ht,delay; uint256 hashBlock; uint64_t seed; char cmd[512]; CTransaction tx; if ( GetTransaction(gametxid,tx,hashBlock,false) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) @@ -196,7 +196,7 @@ void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gam memcpy(&seed,&hashBlock,sizeof(seed)); seed &= (1LL << 62) - 1; obj.push_back(Pair("seed",(int64_t)seed)); - if ( rogue_iamregistered(tx) > 0 ) + if ( rogue_iamregistered(tx,myrogueaddr) > 0 ) sprintf(cmd,"./rogue %llu gui",(long long)seed); else sprintf(cmd,"./komodo-cli -ac_name=%s cclib register %d \"[%%22%s%%22]\"",ASSETCHAINS_SYMBOL,EVAL_ROGUE,gametxid.ToString().c_str()); obj.push_back(Pair("run",cmd)); @@ -315,18 +315,20 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd { matches++; matchtx = spenttx; - } - } - } + } else fprintf(stderr,"%d+2 doesnt match scriptPubKey\n",i); + } else fprintf(stderr,"%d+2 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); + } else fprintf(stderr,"%d+2 unspent\n",i); } if ( matches == 1 ) { numvouts = matchtx.vout.size(); + fprintf(stderr,"matches.%d numvouts.%d\n",matches,numvouts); if ( rogue_registeropretdecode(txid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) { if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) == 0 ) { txid = spenttxid; + fprintf(stderr,"scan forward\n"); while ( CCgettxout(txid,0,1) > 0 ) { spenttxid = zeroid; @@ -341,6 +343,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd if ( spentvini != 0 ) return(-3); } + fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); batontxid = txid; batonvout = 0; // not vini // how to detect timeout, bailedout, highlander @@ -355,7 +358,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd return(0); } } - } + }else fprintf(stderr,"opret erro\n"); } return(-1); } @@ -363,9 +366,9 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers) { // identify if bailout or quit or timed out - uint256 batontxid; int32_t batonvout,batonht; int64_t batonvalue; std::vector playerdata; + uint256 batontxid; int32_t batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; obj.push_back(Pair("slot",(int64_t)vout-2)); - if ( rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,gametx.vout[vout].scriptPubKey) == 0 ) + if ( (retval= rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,gametx.vout[vout].scriptPubKey)) == 0 ) { obj.push_back(Pair("baton",batontxid.ToString())); obj.push_back(Pair("batonvout",(int64_t)batonvout)); @@ -376,7 +379,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet UniValue pobj(UniValue::VOBJ); obj.push_back(Pair("rogue",rogue_playerobj(pobj,playerdata))); } - } + } else fprintf(stderr,"findbaton err.%d\n",retval); } int64_t rogue_registrationbaton(CMutableTransaction &mtx,uint256 gametxid,CTransaction gametx,int32_t maxplayers) @@ -478,7 +481,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vin3+ -> buyin // vout0 -> keystrokes/completion baton CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); char destaddr[64]; uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t maxplayers,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx; std::vector playerdata; std::string rawtx; bits256 t; + UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t maxplayers,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx; std::vector playerdata; std::string rawtx; bits256 t; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -499,6 +502,10 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"couldnt extract valid playerdata")); } rogue_univalue(result,0,maxplayers,buyin); + GetCCaddress1of2(cp,coinaddr,roguepk,mypk); + fprintf(stderr,"check %s\n",coinaddr); + if ( rogue_iamregistered(tx,coinaddr) > 1 ) + return(cclib_error(result,"already registered")); if ( (inputsum= rogue_registrationbaton(mtx,gametxid,tx,maxplayers)) != ROGUE_REGISTRATIONSIZE ) return(cclib_error(result,"couldnt find available registration baton")); else if ( playertxid != zeroid && rogue_playerdataspend(mtx,playertxid,origplayergame) < 0 ) @@ -588,7 +595,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; bits256 t; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; bits256 t; char myrogueaddr[64]; CPubKey mypk,roguepk; result.push_back(Pair("name","rogue")); result.push_back(Pair("method","gameinfo")); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -600,7 +607,11 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,txid) == 0 ) { result.push_back(Pair("result","success")); - rogue_gamefields(result,maxplayers,buyin,txid); + mypk = pubkey2pk(Mypubkey()); + roguepk = GetUnspendable(cp,0); + GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); + fprintf(stderr,"myrogueaddr.%s\n",myrogueaddr); + rogue_gamefields(result,maxplayers,buyin,txid,myrogueaddr); for (i=0; i Date: Tue, 5 Feb 2019 22:16:32 -1100 Subject: [PATCH 0340/1145] gametx.vout[vout].scriptPubKey --- src/cc/rogue_rpc.cpp | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5a1721018..8f751e15f 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -302,20 +302,21 @@ int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,uint25 } else return(-1); } -int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,CScript scriptPubKey) +int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr) { - int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 spenttxid,hashBlock,txid,playertxid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; + int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 spenttxid,hashBlock,txid,playertxid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64]; for (i=0; i= 0 ) { if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) { - if ( spenttx.vout[0].scriptPubKey == scriptPubKey ) + GetScriptaddress(ccaddr,spenttx.vout[0].scriptPubKey); + if ( strcmp(destaddr,ccaddr) == 0 ) { matches++; matchtx = spenttx; - } else fprintf(stderr,"%d+2 doesnt match scriptPubKey\n",i); + } else fprintf(stderr,"%d+2 doesnt match %s vs %s\n",i,ccaddr,destaddr); } else fprintf(stderr,"%d+2 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); } else fprintf(stderr,"%d+2 unspent\n",i); } @@ -366,9 +367,10 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers) { // identify if bailout or quit or timed out - uint256 batontxid; int32_t batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; + uint256 batontxid; int32_t batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; + GetScriptaddress(destaddr,gametx.vout[vout].scriptPubKey); obj.push_back(Pair("slot",(int64_t)vout-2)); - if ( (retval= rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,gametx.vout[vout].scriptPubKey)) == 0 ) + if ( (retval= rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr)) == 0 ) { obj.push_back(Pair("baton",batontxid.ToString())); obj.push_back(Pair("batonvout",(int64_t)batonvout)); @@ -531,7 +533,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // respawn to be prevented by including timestamps int32_t nextheight = komodo_nextheight(); CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(),nextheight); - UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr; std::string rawtx; bits256 t; + UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; if ( txfee == 0 ) txfee = 10000; rogue_univalue(result,"keystrokes",-1,-1); @@ -541,10 +543,10 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param keystrokes = ParseHex(keystrokestr); mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); - txout = MakeCC1of2vout(cp->evalcode,0,roguepk,mypk); + GetCCaddress1of2(cp,destaddr,roguepk,mypk); if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,gametxid) == 0 ) { - if ( rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,txout.scriptPubKey) == 0 ) + if ( rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr) == 0 ) { if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) { From 27bb4fd785c1d2aa44b3957ed31d146871ac8332 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 22:19:41 -1100 Subject: [PATCH 0341/1145] Getscriptaddress --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 8f751e15f..8d84ea754 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -311,7 +311,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd { if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) { - GetScriptaddress(ccaddr,spenttx.vout[0].scriptPubKey); + Getscriptaddress(ccaddr,spenttx.vout[0].scriptPubKey); if ( strcmp(destaddr,ccaddr) == 0 ) { matches++; @@ -368,7 +368,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet { // identify if bailout or quit or timed out uint256 batontxid; int32_t batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; - GetScriptaddress(destaddr,gametx.vout[vout].scriptPubKey); + Getscriptaddress(destaddr,gametx.vout[vout].scriptPubKey); obj.push_back(Pair("slot",(int64_t)vout-2)); if ( (retval= rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr)) == 0 ) { From 2fc422528b13e767dedfeb942b2c9793e2499754 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 22:27:54 -1100 Subject: [PATCH 0342/1145] Recall destaddr --- src/cc/rogue_rpc.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 8d84ea754..c1afabaae 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -367,8 +367,13 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers) { // identify if bailout or quit or timed out - uint256 batontxid; int32_t batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; - Getscriptaddress(destaddr,gametx.vout[vout].scriptPubKey); + uint256 batontxid,spenttxid,hashBlock; CTransaction spenttx; int32_t batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; + destaddr[0] = 0; + if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) + { + if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + Getscriptaddress(ccaddr,spenttx.vout[0].scriptPubKey); + } obj.push_back(Pair("slot",(int64_t)vout-2)); if ( (retval= rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr)) == 0 ) { From 4ddcfc2a041f83fb436614e11fded8024b1b1f8d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 22:36:10 -1100 Subject: [PATCH 0343/1145] Destaddr --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c1afabaae..89c4547e8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -372,7 +372,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) - Getscriptaddress(ccaddr,spenttx.vout[0].scriptPubKey); + Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); } obj.push_back(Pair("slot",(int64_t)vout-2)); if ( (retval= rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr)) == 0 ) From 6e8418cf0331dccc2af5ea01f3213542f9ed96c1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 22:40:50 -1100 Subject: [PATCH 0344/1145] Reverse polarity --- src/cc/rogue_rpc.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 89c4547e8..b372bd0a7 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -317,20 +317,20 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd matches++; matchtx = spenttx; } else fprintf(stderr,"%d+2 doesnt match %s vs %s\n",i,ccaddr,destaddr); - } else fprintf(stderr,"%d+2 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); - } else fprintf(stderr,"%d+2 unspent\n",i); + } //else fprintf(stderr,"%d+2 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); + } //else fprintf(stderr,"%d+2 unspent\n",i); } if ( matches == 1 ) { numvouts = matchtx.vout.size(); - fprintf(stderr,"matches.%d numvouts.%d\n",matches,numvouts); + //fprintf(stderr,"matches.%d numvouts.%d\n",matches,numvouts); if ( rogue_registeropretdecode(txid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) { if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) == 0 ) { txid = spenttxid; - fprintf(stderr,"scan forward\n"); - while ( CCgettxout(txid,0,1) > 0 ) + fprintf(stderr,"scan forward playertxid.%s spenttxid.%s\n",playertxid.GetHex().c_str(),spenttxid.GetHex().c_str()); + while ( CCgettxout(txid,0,1) < 0 ) { spenttxid = zeroid; spentvini = -1; From 895825f3db3a9a16b24cc1dc586f17eb3675fc3b Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 22:46:10 -1100 Subject: [PATCH 0345/1145] Test --- src/cc/makerogue | 2 +- src/cc/rogue_rpc.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 08c86dee8..f7ee26669 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,5 +1,5 @@ cd rogue; -./configure # only need this first time +#./configure # only need this first time make; cd .. gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -lncurses #gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b372bd0a7..5d5c1bd00 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -328,8 +328,8 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd { if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) == 0 ) { - txid = spenttxid; - fprintf(stderr,"scan forward playertxid.%s spenttxid.%s\n",playertxid.GetHex().c_str(),spenttxid.GetHex().c_str()); + txid = matchtx.GetHash(); + fprintf(stderr,"scan forward playertxid.%s spenttxid.%s\n",playertxid.GetHex().c_str(),txid.GetHex().c_str()); while ( CCgettxout(txid,0,1) < 0 ) { spenttxid = zeroid; From d14201d023e8445952c5589f74eab9486fe4f6ae Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 22:59:21 -1100 Subject: [PATCH 0346/1145] rogue_iamregistered --- src/cc/rogue_rpc.cpp | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5d5c1bd00..ff6de1971 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -173,8 +173,23 @@ void rogue_univalue(UniValue &result,const char *method,int64_t maxplayers,int64 } } -int32_t rogue_iamregistered(CTransaction tx,char *myrogueaddr) +int32_t rogue_iamregistered(int32_t maxplayers,uint256 gametxid,CTransaction tx,char *myrogueaddr) { + int32_t i,vout; uint256 spenttxid,hashBlock; CTransaction spenttx; char destaddr[64]; + for (i=0; i= 0 ) + { + if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + { + Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); + if ( strcmp(myrogueaddr,destaddr) == 0 ) + return(1); + } + } + } return(0); } @@ -196,7 +211,7 @@ void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gam memcpy(&seed,&hashBlock,sizeof(seed)); seed &= (1LL << 62) - 1; obj.push_back(Pair("seed",(int64_t)seed)); - if ( rogue_iamregistered(tx,myrogueaddr) > 0 ) + if ( rogue_iamregistered(maxplayers,gametxid,tx,myrogueaddr) > 0 ) sprintf(cmd,"./rogue %llu gui",(long long)seed); else sprintf(cmd,"./komodo-cli -ac_name=%s cclib register %d \"[%%22%s%%22]\"",ASSETCHAINS_SYMBOL,EVAL_ROGUE,gametxid.ToString().c_str()); obj.push_back(Pair("run",cmd)); @@ -356,6 +371,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd else if ( (pindex= komodo_blockindex(hashBlock)) == 0 ) return(-4); else batonht = pindex->GetHeight(); + batonvalue = batontx.vout[0].nValue; return(0); } } @@ -378,6 +394,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet if ( (retval= rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr)) == 0 ) { obj.push_back(Pair("baton",batontxid.ToString())); + obj.push_back(Pair("batonaddr",destaddr)); obj.push_back(Pair("batonvout",(int64_t)batonvout)); obj.push_back(Pair("batonvalue",ValueFromAmount(batonvalue))); obj.push_back(Pair("batonht",(int64_t)batonht)); @@ -511,7 +528,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) rogue_univalue(result,0,maxplayers,buyin); GetCCaddress1of2(cp,coinaddr,roguepk,mypk); fprintf(stderr,"check %s\n",coinaddr); - if ( rogue_iamregistered(tx,coinaddr) > 1 ) + if ( rogue_iamregistered(maxplayers,gametxid,tx,coinaddr) > 1 ) return(cclib_error(result,"already registered")); if ( (inputsum= rogue_registrationbaton(mtx,gametxid,tx,maxplayers)) != ROGUE_REGISTRATIONSIZE ) return(cclib_error(result,"couldnt find available registration baton")); From e28b2d84b7c0e4a0d5d28545ef36f239a159a768 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 23:18:50 -1100 Subject: [PATCH 0347/1145] Off by 1 --- src/cc/rogue_rpc.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ff6de1971..f9a3e7904 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -187,8 +187,9 @@ int32_t rogue_iamregistered(int32_t maxplayers,uint256 gametxid,CTransaction tx, Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); if ( strcmp(myrogueaddr,destaddr) == 0 ) return(1); - } - } + else fprintf(stderr,"myaddr.%s vs %s\n",myrogueaddr,destaddr); + } else fprintf(stderr,"cant find spenttxid.%s\n",spenttxid.GetHex().c_str()); + } else fprintf(stderr,"vout %d is unspent\n",vout); } return(0); } @@ -528,7 +529,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) rogue_univalue(result,0,maxplayers,buyin); GetCCaddress1of2(cp,coinaddr,roguepk,mypk); fprintf(stderr,"check %s\n",coinaddr); - if ( rogue_iamregistered(maxplayers,gametxid,tx,coinaddr) > 1 ) + if ( rogue_iamregistered(maxplayers,gametxid,tx,coinaddr) > 0 ) return(cclib_error(result,"already registered")); if ( (inputsum= rogue_registrationbaton(mtx,gametxid,tx,maxplayers)) != ROGUE_REGISTRATIONSIZE ) return(cclib_error(result,"couldnt find available registration baton")); From 406a017b2bdce93251dc6162de2aa59f677c441c Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 23:42:01 -1100 Subject: [PATCH 0348/1145] Flush keystrokes --- src/cc/rogue/rogue.c | 12 ++++++++++++ src/cc/rogue/rogue.h | 2 +- src/cc/rogue_rpc.cpp | 34 ++++++++++++++++++++++++++-------- 3 files changed, 39 insertions(+), 9 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 554c0ae4e..56316808c 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -105,6 +105,7 @@ int32_t roguefname(char *fname,uint64_t seed,int32_t counter) return(0); } +#ifdef test int32_t flushkeystrokes(struct rogue_state *rs) { char fname[1024]; FILE *fp; int32_t i,retflag = -1; @@ -136,6 +137,17 @@ int32_t flushkeystrokes(struct rogue_state *rs) } else fprintf(stderr,"error creating (%s)\n",fname); return(retflag); } +#else + +int32_t flushkeystrokes(struct rogue_state *rs) +{ + rogue_progress(rs->seed,rs->buffered,rs->num); + memset(rs->buffered,0,sizeof(rs->buffered)); + rs->counter++; + rs->num = 0; + return(0); +} +#endif long get_filesize(FILE *fp) { diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index e66362a10..6502ed775 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -332,7 +332,7 @@ struct rogue_state uint32_t needflush,replaydone; int32_t numkeys,ind,num,guiflag,counter,sleeptime; struct rogue_player P; - char buffered[512]; + char buffered[8192]; }; extern struct rogue_state globalR; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f9a3e7904..f8c575c4c 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -21,6 +21,8 @@ #define ROGUE_MAXPLAYERS 64 // need to send unused fees back to globalCC address to prevent leeching #define ROGUE_MAXKEYSTROKESGAP 60 +uint256 Gametxid; + /* the idea is that you creategame and get a txid, you specify the maxplayers and buyin for the game. the tx will have maxplayers of vouts. You must have a non-zero buyin to be able to use a preexisting character. @@ -76,8 +78,8 @@ // cclib gameinfo 17 \"[%22783369750c2c7003d3dcee327b830025c560b594f65648c0abbac733a661ea39%22]\" // cclib register 17 \"[%22783369750c2c7003d3dcee327b830025c560b594f65648c0abbac733a661ea39%22]\" // ./rogue gui -> creates keystroke files -// cclib register 17 \"[%2235e99df53c981a937bfa2ce7bfb303cea0249dba34831592c140d1cb729cb19f%22,%22%22]\" -// cclib keystrokes 17 \"[]\" +// cclib register 17 \"[%22783369750c2c7003d3dcee327b830025c560b594f65648c0abbac733a661ea39%22,%22%22]\" +// cclib keystrokes 17 \"[%22783369750c2c7003d3dcee327b830025c560b594f65648c0abbac733a661ea39%22,%22deadbeef%22]\" CScript rogue_newgameopret(int64_t buyin,int32_t maxplayers) { @@ -186,10 +188,13 @@ int32_t rogue_iamregistered(int32_t maxplayers,uint256 gametxid,CTransaction tx, { Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); if ( strcmp(myrogueaddr,destaddr) == 0 ) + { + Gametxid = gametxid; return(1); - else fprintf(stderr,"myaddr.%s vs %s\n",myrogueaddr,destaddr); - } else fprintf(stderr,"cant find spenttxid.%s\n",spenttxid.GetHex().c_str()); - } else fprintf(stderr,"vout %d is unspent\n",vout); + } + //else fprintf(stderr,"myaddr.%s vs %s\n",myrogueaddr,destaddr); + } //else fprintf(stderr,"cant find spenttxid.%s\n",spenttxid.GetHex().c_str()); + } //else fprintf(stderr,"vout %d is unspent\n",vout); } return(0); } @@ -528,7 +533,6 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } rogue_univalue(result,0,maxplayers,buyin); GetCCaddress1of2(cp,coinaddr,roguepk,mypk); - fprintf(stderr,"check %s\n",coinaddr); if ( rogue_iamregistered(maxplayers,gametxid,tx,coinaddr) > 0 ) return(cclib_error(result,"already registered")); if ( (inputsum= rogue_registrationbaton(mtx,gametxid,tx,maxplayers)) != ROGUE_REGISTRATIONSIZE ) @@ -556,7 +560,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // respawn to be prevented by including timestamps int32_t nextheight = komodo_nextheight(); CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(),nextheight); - UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; + UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; uint8_t mypriv[32]; if ( txfee == 0 ) txfee = 10000; rogue_univalue(result,"keystrokes",-1,-1); @@ -575,14 +579,28 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,batonvalue-txfee,roguepk,mypk)); + Myprivkey(mypriv); + CCaddr1of2set(cp,roguepk,mypk,mypriv,destaddr); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_keystrokesopret(gametxid,batontxid,mypk,keystrokes)); - return(rogue_rawtxresult(result,rawtx,1)); + fprintf(stderr,"KEYSTROKES.(%s)\n",rawtx.c_str()); + return(rogue_rawtxresult(result,rawtx,0)); } else return(cclib_error(result,"keystrokes tx was too late")); } else return(cclib_error(result,"couldnt find batontxid")); } else return(cclib_error(result,"invalid gametxid")); } else return(cclib_error(result,"couldnt reparse params")); } +void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) +{ + char cmd[32768],hexstr[32768]; int32_t i; + for (i=0; i highlander vout from creategame TCBOO From 1a6dcc079fb03e8a6e83b24062d1d689e8227196 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 23:50:34 -1100 Subject: [PATCH 0349/1145] -gametxid --- src/cc/rogue/rogue.c | 18 ++++++++++++++++-- src/cc/rogue_rpc.cpp | 15 +-------------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 56316808c..f43b81a68 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -22,6 +22,7 @@ */ struct rogue_state globalR; void garbage_collect(); +char Gametxidstr[67]; void purge_obj_guess(struct obj_info *array,int32_t n) { @@ -139,6 +140,17 @@ int32_t flushkeystrokes(struct rogue_state *rs) } #else +void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) // use seed to lookup gametxid +{ + char cmd[32768],hexstr[32768]; int32_t i; + for (i=0; iseed,rs->buffered,rs->num); @@ -238,9 +250,11 @@ int rogue(int argc, char **argv, char **envp) { char *env; int lowtime; struct rogue_state *rs = &globalR; memset(rs,0,sizeof(*rs)); - if ( argc == 3 && strcmp(argv[2],"gui") == 0 ) + if ( argc == 3 && strlen(argv[2]) == 64 ) + { rs->seed = atol(argv[1]); - else rs->seed = 777; + strcpy(Gametxidstr,argv[2]); + } else rs->seed = 777; rs->guiflag = 1; rs->sleeptime = 1; // non-zero to allow refresh() md_init(); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f8c575c4c..10d509b9b 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -21,8 +21,6 @@ #define ROGUE_MAXPLAYERS 64 // need to send unused fees back to globalCC address to prevent leeching #define ROGUE_MAXKEYSTROKESGAP 60 -uint256 Gametxid; - /* the idea is that you creategame and get a txid, you specify the maxplayers and buyin for the game. the tx will have maxplayers of vouts. You must have a non-zero buyin to be able to use a preexisting character. @@ -218,7 +216,7 @@ void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gam seed &= (1LL << 62) - 1; obj.push_back(Pair("seed",(int64_t)seed)); if ( rogue_iamregistered(maxplayers,gametxid,tx,myrogueaddr) > 0 ) - sprintf(cmd,"./rogue %llu gui",(long long)seed); + sprintf(cmd,"./rogue %llu %s",(long long)seed,gametxid.ToString().c_str()); else sprintf(cmd,"./komodo-cli -ac_name=%s cclib register %d \"[%%22%s%%22]\"",ASSETCHAINS_SYMBOL,EVAL_ROGUE,gametxid.ToString().c_str()); obj.push_back(Pair("run",cmd)); } @@ -590,17 +588,6 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"couldnt reparse params")); } -void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) -{ - char cmd[32768],hexstr[32768]; int32_t i; - for (i=0; i highlander vout from creategame TCBOO From b103d5215256651b81a223fabe7fe80ac61cce3a Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 5 Feb 2019 23:52:04 -1100 Subject: [PATCH 0350/1145] Fix system call --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index f43b81a68..7b1c63ba5 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -146,7 +146,7 @@ void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) // use seed to l for (i=0; i Date: Tue, 5 Feb 2019 23:52:51 -1100 Subject: [PATCH 0351/1145] -Gametxid --- src/cc/rogue_rpc.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 10d509b9b..432c4ed1d 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -186,10 +186,7 @@ int32_t rogue_iamregistered(int32_t maxplayers,uint256 gametxid,CTransaction tx, { Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); if ( strcmp(myrogueaddr,destaddr) == 0 ) - { - Gametxid = gametxid; return(1); - } //else fprintf(stderr,"myaddr.%s vs %s\n",myrogueaddr,destaddr); } //else fprintf(stderr,"cant find spenttxid.%s\n",spenttxid.GetHex().c_str()); } //else fprintf(stderr,"vout %d is unspent\n",vout); From 20b1d0df88759c9b7c2e00d67946f7974d32884a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 00:01:30 -1100 Subject: [PATCH 0352/1145] Test keystrokes --- src/cc/rogue/rogue.c | 2 +- src/cc/rogue_rpc.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 7b1c63ba5..1a09d13b9 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -146,7 +146,7 @@ void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) // use seed to l for (i=0; i Date: Wed, 6 Feb 2019 01:05:04 -1100 Subject: [PATCH 0353/1145] Test --- src/cc/cclib.cpp | 2 +- src/cc/rogue_rpc.cpp | 70 +++++++++++++++++++++++++++++++------------- 2 files changed, 51 insertions(+), 21 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index f192fc20a..dd0aef00f 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -472,7 +472,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will } newstr[j] = 0; params = cJSON_Parse(newstr); - if ( params != 0 ) + if ( 0 && params != 0 ) printf("new.(%s) -> %s\n",newstr,jprint(params,0)); free(newstr); *nump = cJSON_GetArraySize(params); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b2b4dbc71..0d415f4cb 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -19,7 +19,7 @@ #define ROGUE_REGISTRATION 5 #define ROGUE_REGISTRATIONSIZE (100 * 10000) #define ROGUE_MAXPLAYERS 64 // need to send unused fees back to globalCC address to prevent leeching -#define ROGUE_MAXKEYSTROKESGAP 777 +#define ROGUE_MAXKEYSTROKESGAP 60 /* the idea is that you creategame and get a txid, you specify the maxplayers and buyin for the game. the tx will have maxplayers of vouts. You must have a non-zero buyin to be able to use a preexisting character. @@ -71,13 +71,13 @@ //////////////////////// start of CClib interface //./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & -// cclib newgame 17 \"[3,100]\" +// cclib newgame 17 \"[3,10]\" // cclib pending 17 -// cclib gameinfo 17 \"[%22783369750c2c7003d3dcee327b830025c560b594f65648c0abbac733a661ea39%22]\" -// cclib register 17 \"[%22783369750c2c7003d3dcee327b830025c560b594f65648c0abbac733a661ea39%22]\" +// cclib gameinfo 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" +// cclib register 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" // ./rogue gui -> creates keystroke files -// cclib register 17 \"[%22783369750c2c7003d3dcee327b830025c560b594f65648c0abbac733a661ea39%22,%22%22]\" -// cclib keystrokes 17 \"[%22783369750c2c7003d3dcee327b830025c560b594f65648c0abbac733a661ea39%22,%22deadbeef%22]\" +// cclib register 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22,%22%22]\" +// cclib keystrokes 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22,%22deadbeef%22]\" CScript rogue_newgameopret(int64_t buyin,int32_t maxplayers) { @@ -213,7 +213,7 @@ void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gam seed &= (1LL << 62) - 1; obj.push_back(Pair("seed",(int64_t)seed)); if ( rogue_iamregistered(maxplayers,gametxid,tx,myrogueaddr) > 0 ) - sprintf(cmd,"./rogue %llu %s",(long long)seed,gametxid.ToString().c_str()); + sprintf(cmd,"cc/rogue/rogue %llu %s",(long long)seed,gametxid.ToString().c_str()); else sprintf(cmd,"./komodo-cli -ac_name=%s cclib register %d \"[%%22%s%%22]\"",ASSETCHAINS_SYMBOL,EVAL_ROGUE,gametxid.ToString().c_str()); obj.push_back(Pair("run",cmd)); } @@ -318,9 +318,10 @@ int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,uint25 } else return(-1); } -int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr) +int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &numkeys,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr) { int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 spenttxid,hashBlock,txid,playertxid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64]; + numkeys = 0; for (i=0; i= 0 ) @@ -345,7 +346,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) == 0 ) { txid = matchtx.GetHash(); - fprintf(stderr,"scan forward playertxid.%s spenttxid.%s\n",playertxid.GetHex().c_str(),txid.GetHex().c_str()); + //fprintf(stderr,"scan forward playertxid.%s spenttxid.%s\n",playertxid.GetHex().c_str(),txid.GetHex().c_str()); while ( CCgettxout(txid,0,1) < 0 ) { spenttxid = zeroid; @@ -359,8 +360,19 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd } if ( spentvini != 0 ) return(-3); + if ( keystrokesp != 0 && GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() == 2 ) + { + uint256 g,b; CPubKey p; std::vector k; + if ( rogue_keystrokesopretdecode(g,b,p,k,spenttx.vout[1].scriptPubKey) == 'K' ) + { + keystrokes = (char *)realloc(keystrokes,numkeys + (int32_t)k.size()/2); + decode_hex((uint8_t *)&keystrokes[numkeys],(int32_t)k.size()/2,&k[0]); + numkeys += (int32_t)k.size()/2; + (*keystrokesp) = keystrokes; + } + } } - fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); + //fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); batontxid = txid; batonvout = 0; // not vini // how to detect timeout, bailedout, highlander @@ -373,10 +385,11 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd return(-4); else batonht = pindex->GetHeight(); batonvalue = batontx.vout[0].nValue; + printf("keystrokes[%d]\n",numkeys); return(0); } } - }else fprintf(stderr,"opret erro\n"); + } else fprintf(stderr,"findbaton opret error\n"); } return(-1); } @@ -384,7 +397,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,std::vector &playerd void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers) { // identify if bailout or quit or timed out - uint256 batontxid,spenttxid,hashBlock; CTransaction spenttx; int32_t batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; + uint256 batontxid,spenttxid,hashBlock; CTransaction spenttx; int32_t numkeys,batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; destaddr[0] = 0; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { @@ -392,7 +405,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); } obj.push_back(Pair("slot",(int64_t)vout-2)); - if ( (retval= rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr)) == 0 ) + if ( (retval= rogue_findbaton(cp,0,numkeys,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr)) == 0 ) { obj.push_back(Pair("baton",batontxid.ToString())); obj.push_back(Pair("batonaddr",destaddr)); @@ -555,7 +568,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // respawn to be prevented by including timestamps int32_t nextheight = komodo_nextheight(); CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(),nextheight); - UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; uint8_t mypriv[32]; + UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t numkeys,batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; uint8_t mypriv[32]; if ( txfee == 0 ) txfee = 10000; rogue_univalue(result,"keystrokes",-1,-1); @@ -568,7 +581,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param GetCCaddress1of2(cp,destaddr,roguepk,mypk); if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,gametxid) == 0 ) { - if ( rogue_findbaton(cp,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr) == 0 ) + if ( rogue_findbaton(cp,0,numkeys,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr) == 0 ) { if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) { @@ -610,13 +623,30 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); + UniValue result(UniValue::VOBJ); CTransaction gametx; int64_t batonvalue; int32_t n,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; if ( txfee == 0 ) txfee = 10000; - // make sure no highlander yet - result.push_back(Pair("result","success")); + mypk = pubkey2pk(Mypubkey()); + roguepk = GetUnspendable(cp,0); + GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); result.push_back(Pair("name","rogue")); result.push_back(Pair("method","bailout")); + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n > 0 ) + { + gametxid = juint256(jitem(params,0)); + result.push_back(Pair("gametxid",txid.GetHex())); + if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,txid) == 0 ) + { + if ( rogue_findbaton(cp,&keystrokes,numkeys,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr) == 0 ) + { + + } + result.push_back(Pair("result","success")); + } + } + } return(result); } @@ -630,14 +660,14 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( n > 0 ) { txid = juint256(jitem(params,0)); - result.push_back(Pair("txid",txid.GetHex())); + result.push_back(Pair("gametxid",txid.GetHex())); if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,txid) == 0 ) { result.push_back(Pair("result","success")); mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); - fprintf(stderr,"myrogueaddr.%s\n",myrogueaddr); + //fprintf(stderr,"myrogueaddr.%s\n",myrogueaddr); rogue_gamefields(result,maxplayers,buyin,txid,myrogueaddr); for (i=0; i Date: Wed, 6 Feb 2019 01:06:34 -1100 Subject: [PATCH 0354/1145] Keystrokes --- src/cc/rogue_rpc.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 0d415f4cb..770ea058b 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -320,7 +320,7 @@ int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,uint25 int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &numkeys,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr) { - int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 spenttxid,hashBlock,txid,playertxid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64]; + int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 spenttxid,hashBlock,txid,playertxid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; numkeys = 0; for (i=0; i 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); CTransaction gametx; int64_t batonvalue; int32_t n,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; + UniValue result(UniValue::VOBJ); CTransaction gametx; int64_t buyin,batonvalue; int32_t n,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -636,8 +636,8 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( n > 0 ) { gametxid = juint256(jitem(params,0)); - result.push_back(Pair("gametxid",txid.GetHex())); - if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,txid) == 0 ) + result.push_back(Pair("gametxid",gametxid.GetHex())); + if ( rogue_isvalidgame(cp,gametx,buyin,maxplayers,gametxid) == 0 ) { if ( rogue_findbaton(cp,&keystrokes,numkeys,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr) == 0 ) { From 94f104121e09c12e8e3d89e251952c3713758e7c Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 01:09:47 -1100 Subject: [PATCH 0355/1145] +print --- src/cc/rogue_rpc.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 770ea058b..d00d48fb1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -78,6 +78,7 @@ // ./rogue gui -> creates keystroke files // cclib register 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22,%22%22]\" // cclib keystrokes 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22,%22deadbeef%22]\" +// cclib bailout 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" CScript rogue_newgameopret(int64_t buyin,int32_t maxplayers) { @@ -366,7 +367,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &n if ( rogue_keystrokesopretdecode(g,b,p,k,spenttx.vout[1].scriptPubKey) == 'K' ) { keystrokes = (char *)realloc(keystrokes,numkeys + (int32_t)k.size()/2); - decode_hex((uint8_t *)&keystrokes[numkeys],(int32_t)k.size()/2,&k[0]); + decode_hex((uint8_t *)&keystrokes[numkeys],(int32_t)k.size()/2,(char *)&k[0]); numkeys += (int32_t)k.size()/2; (*keystrokesp) = keystrokes; } @@ -641,7 +642,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( rogue_findbaton(cp,&keystrokes,numkeys,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr) == 0 ) { - + fprintf(stderr,"found baton %s numkeys.%d\n",batontxid.ToString().c_str(),numkeys); } result.push_back(Pair("result","success")); } From 694ba9a62943f85a3c59e048354987ab8a4e4cc3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 01:20:44 -1100 Subject: [PATCH 0356/1145] Replay2 --- src/cc/rogue/rogue.c | 66 +++++++++++++++++++++----------------------- src/cc/rogue_rpc.cpp | 6 +++- 2 files changed, 37 insertions(+), 35 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 1a09d13b9..073dbf3cd 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -159,6 +159,37 @@ int32_t flushkeystrokes(struct rogue_state *rs) rs->num = 0; return(0); } + +int32_t rogue_replay2(uint64_t seed,char *keystrokes,int32_t num) +{ + struct rogue_state *rs; FILE *fp; int32_t i; + rs = (struct rogue_state *)calloc(1,sizeof(*rs)); + rs->seed = seed; + rs->keystrokes = keystrokes; + rs->numkeys = num; + rs->sleeptime = 1; + uint32_t starttime = (uint32_t)time(NULL); + rogueiterate(rs); + fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL) - starttime); + sleep(2); + + starttime = (uint32_t)time(NULL); + for (i=0; i<100; i++) + { + memset(rs,0,sizeof(*rs)); + rs->seed = seed; + rs->keystrokes = keystrokes; + rs->numkeys = num; + rs->sleeptime = 0; + rogueiterate(rs); + } + fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL)-starttime); + sleep(1); + if ( (fp= fopen("checkfile","wb")) != 0 ) + save_file(rs,fp,0); + free(rs); + return(0); +} #endif long get_filesize(FILE *fp) @@ -204,40 +235,7 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) } if ( num > 0 ) { - rs = (struct rogue_state *)calloc(1,sizeof(*rs)); - rs->seed = seed; - rs->keystrokes = keystrokes; - rs->numkeys = num; - rs->sleeptime = 1; - uint32_t starttime = (uint32_t)time(NULL); - rogueiterate(rs); - fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL) - starttime); - sleep(2); - - starttime = (uint32_t)time(NULL); - for (i=0; i<2000; i++) - { - memset(rs,0,sizeof(*rs)); - rs->seed = seed; - rs->keystrokes = keystrokes; - rs->numkeys = num; - rs->sleeptime = 0; - rogueiterate(rs); - } - fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL)-starttime); - sleep(1); - if ( (fp= fopen("checkfile","wb")) != 0 ) - { - save_file(rs,fp,0); - if ( 0 && (fp= fopen("checkfile","rb")) != 0 ) - { - for (i=0; i<0x150; i++) - fprintf(stderr,"%02x",fgetc(fp)); - fprintf(stderr," first part rnd.%d\n",rnd(1000)); - fclose(fp); - } - } - free(rs); + rogue_replay2(seed,keystrokes,num); mvaddstr(LINES - 2, 0, (char *)"replay completed"); endwin(); } diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d00d48fb1..019e0c728 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -617,6 +617,8 @@ UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(result); } +int32_t rogue_replay2(uint64_t seed,char *keystrokes,int32_t num); + UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { // detect if last to bailout @@ -640,9 +642,11 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("gametxid",gametxid.GetHex())); if ( rogue_isvalidgame(cp,gametx,buyin,maxplayers,gametxid) == 0 ) { - if ( rogue_findbaton(cp,&keystrokes,numkeys,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr) == 0 ) + if ( rogue_findbaton(cp,&keystrokes,numkeys,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr) == 0 && keystrokes != 0 ) { fprintf(stderr,"found baton %s numkeys.%d\n",batontxid.ToString().c_str(),numkeys); + rogue_replay2(4419709268196762041,keystrokes,numkeys); + free(keystrokes); } result.push_back(Pair("result","success")); } From ba6a35728361ac6577de20d9b5585adabd96e3a5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 01:31:25 -1100 Subject: [PATCH 0357/1145] Suppress exit --- src/cc/rogue/rogue.c | 10 ++++++---- src/cc/rogue/save.c | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 073dbf3cd..1927f159b 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -167,10 +167,10 @@ int32_t rogue_replay2(uint64_t seed,char *keystrokes,int32_t num) rs->seed = seed; rs->keystrokes = keystrokes; rs->numkeys = num; - rs->sleeptime = 1; + rs->sleeptime = 0; uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); - fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL) - starttime); + /*fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL) - starttime); sleep(2); starttime = (uint32_t)time(NULL); @@ -184,7 +184,7 @@ int32_t rogue_replay2(uint64_t seed,char *keystrokes,int32_t num) rogueiterate(rs); } fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL)-starttime); - sleep(1); + sleep(1);*/ if ( (fp= fopen("checkfile","wb")) != 0 ) save_file(rs,fp,0); free(rs); @@ -619,6 +619,8 @@ void my_exit(int st) { resetltchars(); - exit(st); + if ( globalR.guiflag != 0 ) + exit(st); + else fprintf(stderr,"would have exit.(%d)\n",st); } diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index eec85b930..57811176a 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -130,7 +130,7 @@ auto_save(int sig) if (file_name[0] != '\0' && ((savef = fopen(file_name, "w")) != NULL || (md_unlink_open_file(file_name, savef) >= 0 && (savef = fopen(file_name, "w")) != NULL))) save_file(&globalR,savef,1); - exit(0); + my_exit(0); } /* @@ -181,7 +181,7 @@ save_file(struct rogue_state *rs,FILE *savef,int32_t guiflag) fflush(savef); fclose(savef); if ( guiflag != 0 ) - exit(0); + my_exit(0); } int32_t rogue_restorepack(struct rogue_state *rs) From dc7bc76dd626fdac4805ab3a1d1592a37d7d60f5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 01:36:09 -1100 Subject: [PATCH 0358/1145] Test --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 1927f159b..aeb509832 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -167,7 +167,7 @@ int32_t rogue_replay2(uint64_t seed,char *keystrokes,int32_t num) rs->seed = seed; rs->keystrokes = keystrokes; rs->numkeys = num; - rs->sleeptime = 0; + rs->sleeptime = 50000; uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); /*fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL) - starttime); From fde8e549a3047df05bc2f2ea22ae398ec293af3a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 01:46:55 -1100 Subject: [PATCH 0359/1145] Dont decode keystrokes --- src/cc/rogue_rpc.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 019e0c728..b39845c81 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -366,9 +366,10 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &n uint256 g,b; CPubKey p; std::vector k; if ( rogue_keystrokesopretdecode(g,b,p,k,spenttx.vout[1].scriptPubKey) == 'K' ) { - keystrokes = (char *)realloc(keystrokes,numkeys + (int32_t)k.size()/2); - decode_hex((uint8_t *)&keystrokes[numkeys],(int32_t)k.size()/2,(char *)&k[0]); - numkeys += (int32_t)k.size()/2; + keystrokes = (char *)realloc(keystrokes,numkeys + (int32_t)k.size()); + for (i=0; i Date: Wed, 6 Feb 2019 02:25:28 -1100 Subject: [PATCH 0360/1145] Opreturn player data --- src/cc/rogue/rogue.c | 8 ++++++-- src/cc/rogue/rogue.h | 5 +++-- src/cc/rogue/save.c | 2 ++ src/cc/rogue/state.c | 3 ++- src/cc/rogue_rpc.cpp | 41 +++++++++++++++++++++++++++-------------- 5 files changed, 40 insertions(+), 19 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index aeb509832..6ea858493 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -160,7 +160,7 @@ int32_t flushkeystrokes(struct rogue_state *rs) return(0); } -int32_t rogue_replay2(uint64_t seed,char *keystrokes,int32_t num) +int32_t rogue_replay2(uint8_t *player,uint64_t seed,char *keystrokes,int32_t num) { struct rogue_state *rs; FILE *fp; int32_t i; rs = (struct rogue_state *)calloc(1,sizeof(*rs)); @@ -186,9 +186,13 @@ int32_t rogue_replay2(uint64_t seed,char *keystrokes,int32_t num) fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL)-starttime); sleep(1);*/ if ( (fp= fopen("checkfile","wb")) != 0 ) + { save_file(rs,fp,0); + if ( rs->playersize > 0 ) + memcpy(player,rs->playerdata,rs->playersize); + } free(rs); - return(0); + return(rs->playersize); } #endif diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 6502ed775..4dcee238d 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -321,7 +321,7 @@ struct rogue_packitem struct rogue_player { - int32_t gold,hitpoints,strength,level,experience,packsize; + int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; struct rogue_packitem roguepack[MAXPACK]; }; @@ -330,9 +330,10 @@ struct rogue_state uint64_t seed; char *keystrokes; uint32_t needflush,replaydone; - int32_t numkeys,ind,num,guiflag,counter,sleeptime; + int32_t numkeys,ind,num,guiflag,counter,sleeptime,playersize; struct rogue_player P; char buffered[8192]; + uint8_t playerdata[10000]; }; extern struct rogue_state globalR; diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index 57811176a..8a40a9fb8 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -167,7 +167,9 @@ save_file(struct rogue_state *rs,FILE *savef,int32_t guiflag) { fprintf(stderr,"%02x",((uint8_t *)&rs->P)[i]); histo[((uint8_t *)&rs->P)[i]]++; + rs->playerdata[i] = ((uint8_t *)&rs->P)[i]; } + rs->playersize = n; fprintf(stderr," packsize.%d n.%d\n",rs->P.packsize,n); if ( (fp= fopen(rogue_packfname(rs,fname),"wb")) != 0 ) { diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index d99f1b0dc..226392e83 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1388,7 +1388,8 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) rs->P.strength = max_stats.s_str; rs->P.level = pstats.s_lvl; rs->P.experience = pstats.s_exp; - fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d\n",ftell(savef),purse,max_hp,max_stats.s_str,pstats.s_lvl,pstats.s_exp); + rs->P.dungeonlevel = level; + fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,max_stats.s_str,pstats.s_lvl,pstats.s_exp,level); }; fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); if ( rs->P.packsize < MAXPACK ) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b39845c81..c2afade28 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -101,19 +101,19 @@ CScript rogue_keystrokesopret(uint256 gametxid,uint256 batontxid,CPubKey pk,std: return(opret); } -CScript rogue_highlanderopret(uint256 gametxid,uint256 registertxid,CPubKey pk,std::vectorplayerdata) +CScript rogue_highlanderopret(uint256 gametxid,CPubKey pk,std::vectorplayerdata) { CScript opret; uint8_t evalcode = EVAL_ROGUE; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'K' << gametxid << registertxid << pk << playerdata); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'K' << gametxid << pk << playerdata); return(opret); } -uint8_t rogue_highlanderopretdecode(uint256 &gametxid,uint256 ®istertxid,CPubKey &pk,std::vector &playerdata,CScript scriptPubKey) +uint8_t rogue_highlanderopretdecode(uint256 &gametxid,CPubKey &pk,std::vector &playerdata,CScript scriptPubKey) { std::vector vopret; uint8_t *script,e,f; GetOpReturnData(scriptPubKey,vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> registertxid; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && f == 'H' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) { return(f); } @@ -195,9 +195,9 @@ int32_t rogue_iamregistered(int32_t maxplayers,uint256 gametxid,CTransaction tx, return(0); } -void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gametxid,char *myrogueaddr) +uint64_t rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gametxid,char *myrogueaddr) { - CBlockIndex *pindex; int32_t ht,delay; uint256 hashBlock; uint64_t seed; char cmd[512]; CTransaction tx; + CBlockIndex *pindex; int32_t ht,delay; uint256 hashBlock; uint64_t seed=0; char cmd[512]; CTransaction tx; if ( GetTransaction(gametxid,tx,hashBlock,false) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) { ht = pindex->GetHeight(); @@ -222,6 +222,7 @@ void rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gam } obj.push_back(Pair("maxplayers",maxplayers)); obj.push_back(Pair("buyin",ValueFromAmount(buyin))); + return(seed); } int32_t rogue_isvalidgame(struct CCcontract_info *cp,CTransaction &tx,int64_t &buyin,int32_t &maxplayers,uint256 txid) @@ -286,7 +287,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub { GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'S') ) + if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'Q' || script[1] == 'S') ) { memcpy(&highlander,script+2,sizeof(highlander)); highlander = revuint256(highlander); @@ -295,7 +296,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub { if ( GetTransaction(highlander,highlandertx,hashBlock,false) != 0 && (numvouts= highlandertx.vout.size()) > 0 ) { - if ( rogue_highlanderopretdecode(origplayergame,registertxid,pk,playerdata,highlandertx.vout[numvouts-1].scriptPubKey) == 'H' ) + if ( (f= rogue_highlanderopretdecode(origplayergame,registertxid,pk,playerdata,highlandertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { if ( highlandertx.vin[0].prevout.hash == origplayergame && highlandertx.vin[0].prevout.n == 0 && rogue_isvalidgame(cp,gametx,buyin,maxplayers,origplayergame) == 0 && maxplayers > 1 ) return(0); @@ -592,8 +593,8 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,destaddr); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_keystrokesopret(gametxid,batontxid,mypk,keystrokes)); - fprintf(stderr,"KEYSTROKES.(%s)\n",rawtx.c_str()); - return(rogue_rawtxresult(result,rawtx,0)); + //fprintf(stderr,"KEYSTROKES.(%s)\n",rawtx.c_str()); + return(rogue_rawtxresult(result,rawtx,1)); } else return(cclib_error(result,"keystrokes tx was too late")); } else return(cclib_error(result,"couldnt find batontxid")); } else return(cclib_error(result,"invalid gametxid")); @@ -618,7 +619,7 @@ UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(result); } -int32_t rogue_replay2(uint64_t seed,char *keystrokes,int32_t num); +int32_t rogue_replay2(uint8_t *player,uint64_t seed,char *keystrokes,int32_t num); UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { @@ -627,7 +628,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); CTransaction gametx; int64_t buyin,batonvalue; int32_t n,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; + UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; int64_t buyin,batonvalue; int32_t n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -645,9 +646,21 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( rogue_findbaton(cp,&keystrokes,numkeys,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr) == 0 && keystrokes != 0 ) { - fprintf(stderr,"found baton %s numkeys.%d\n",batontxid.ToString().c_str(),numkeys); - rogue_replay2(4419709268196762041,keystrokes,numkeys); + UniValue obj; + seed = uint64_t rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); + fprintf(stderr,"found baton %s numkeys.%d seed.%llu\n",batontxid.ToString().c_str(),numkeys,(long long)seed); + num = rogue_replay2(player,seed,keystrokes,numkeys); //4419709268196762041 free(keystrokes); + newdata.resize(num); + for (i=0; ievalcode,batonvalue-txfee,roguepk)); + Myprivkey(mypriv); + CCaddr1of2set(cp,roguepk,mypk,mypriv,destaddr); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_highlanderopret(gametxid,mypk,newdata)); + return(rogue_rawtxresult(result,rawtx,0)); } result.push_back(Pair("result","success")); } From acb3d796abd0a4fc4cd4c0f84edb50a647ac9398 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 02:54:46 -1100 Subject: [PATCH 0361/1145] Player data --- src/cc/rogue/init.c | 32 ++++++++++++++++++-------------- src/cc/rogue/rogue.c | 12 ++++++++---- src/cc/rogue/rogue.h | 4 +++- src/cc/rogue_rpc.cpp | 29 ++++++++++++++++++++++------- 4 files changed, 51 insertions(+), 26 deletions(-) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index ff3243ae8..9635ab37b 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -22,26 +22,30 @@ */ void rogue_restoreobject(THING *o,struct rogue_packitem *item); -void -init_player(struct rogue_state *rs) +void restore_player(struct rogue_state *rs) +{ + int32_t i; + //rs->P.gold = purse; + max_hp = rs->P.hitpoints; + max_stats.s_str = rs->P.strength; + pstats.s_lvl = rs->P.level; + pstats.s_exp = rs->P.experience; + for (i=0; iP.packsize; i++) + { + obj = new_item(); + rogue_restoreobject(obj,&rs->P.roguepack[i]); + add_pack(rs,obj,TRUE); + } +} + +void init_player(struct rogue_state *rs) { register THING *obj; int32_t i; pstats = max_stats; food_left = HUNGERTIME; - if ( 0 && rogue_restorepack(rs) == 0 ) + if ( rs->restoring != 0 ) { - //rs->P.gold = purse; - max_hp = rs->P.hitpoints; - max_stats.s_str = rs->P.strength; - pstats.s_lvl = rs->P.level; - pstats.s_exp = rs->P.experience; - for (i=0; iP.packsize; i++) - { - obj = new_item(); - rogue_restoreobject(obj,&rs->P.roguepack[i]); - add_pack(rs,obj,TRUE); - } // duplicate rng usage of normal case obj = new_item(); init_weapon(obj, MACE); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 6ea858493..68f77a0cb 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -97,6 +97,8 @@ void rogueiterate(struct rogue_state *rs) start_daemon(doctor, 0, AFTER); fuse(swander, 0, WANDERTIME, AFTER); start_daemon(stomach, 0, AFTER); + if ( rs->restoring != 0 ) + restore_player(rs); playit(rs); } @@ -160,7 +162,7 @@ int32_t flushkeystrokes(struct rogue_state *rs) return(0); } -int32_t rogue_replay2(uint8_t *player,uint64_t seed,char *keystrokes,int32_t num) +int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player) { struct rogue_state *rs; FILE *fp; int32_t i; rs = (struct rogue_state *)calloc(1,sizeof(*rs)); @@ -168,6 +170,8 @@ int32_t rogue_replay2(uint8_t *player,uint64_t seed,char *keystrokes,int32_t num rs->keystrokes = keystrokes; rs->numkeys = num; rs->sleeptime = 50000; + if ( player != 0 ) + rs->P = *player; uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); /*fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL) - starttime); @@ -188,8 +192,8 @@ int32_t rogue_replay2(uint8_t *player,uint64_t seed,char *keystrokes,int32_t num if ( (fp= fopen("checkfile","wb")) != 0 ) { save_file(rs,fp,0); - if ( rs->playersize > 0 ) - memcpy(player,rs->playerdata,rs->playersize); + if ( newdata != 0 && rs->playersize > 0 ) + memcpy(newdata,rs->playerdata,rs->playersize); } free(rs); return(rs->playersize); @@ -239,7 +243,7 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) } if ( num > 0 ) { - rogue_replay2(seed,keystrokes,num); + rogue_replay2(0,seed,keystrokes,num,0); mvaddstr(LINES - 2, 0, (char *)"replay completed"); endwin(); } diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 4dcee238d..34df75058 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -330,7 +330,7 @@ struct rogue_state uint64_t seed; char *keystrokes; uint32_t needflush,replaydone; - int32_t numkeys,ind,num,guiflag,counter,sleeptime,playersize; + int32_t numkeys,ind,num,guiflag,counter,sleeptime,playersize,restoring; struct rogue_player P; char buffered[8192]; uint8_t playerdata[10000]; @@ -343,6 +343,8 @@ void rogueiterate(struct rogue_state *rs); int32_t roguefname(char *fname,uint64_t seed,int32_t counter); int32_t flushkeystrokes(struct rogue_state *rs); int32_t rogue_restorepack(struct rogue_state *rs); +void restore_player(struct rogue_state *rs); +int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player); /* * Help list diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c2afade28..5298c1354 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -69,7 +69,7 @@ //////////////////////// start of CClib interface -//./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc & +//./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc > /dev/null & // cclib newgame 17 \"[3,10]\" // cclib pending 17 @@ -619,7 +619,7 @@ UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(result); } -int32_t rogue_replay2(uint8_t *player,uint64_t seed,char *keystrokes,int32_t num); +#include "rogue/rogue.h" UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { @@ -646,17 +646,32 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( rogue_findbaton(cp,&keystrokes,numkeys,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr) == 0 && keystrokes != 0 ) { - UniValue obj; + UniValue obj; struct rogue_player P; seed = uint64_t rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); fprintf(stderr,"found baton %s numkeys.%d seed.%llu\n",batontxid.ToString().c_str(),numkeys,(long long)seed); - num = rogue_replay2(player,seed,keystrokes,numkeys); //4419709268196762041 + if ( playerdata.size() > 0 ) + { + for (i=0; ievalcode,batonvalue-txfee,roguepk)); + if ( num == sizeof(P) ) + { + newdata.resize(num); + for (i=0; i_o._o_type,o->_o._o_packch,o->_o._o_packch); + } Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,destaddr); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_highlanderopret(gametxid,mypk,newdata)); From f68beb7072880d28b80ec0b783cf3d3b57f67e19 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 02:56:45 -1100 Subject: [PATCH 0362/1145] Simplify --- src/cc/rogue/init.c | 2 +- src/cc/rogue_rpc.cpp | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index 9635ab37b..1f63e1d51 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -24,7 +24,7 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item); void restore_player(struct rogue_state *rs) { - int32_t i; + int32_t i; THING *obj; //rs->P.gold = purse; max_hp = rs->P.hitpoints; max_stats.s_str = rs->P.strength; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5298c1354..61441d31a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -619,7 +619,18 @@ UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(result); } -#include "rogue/rogue.h" +#define MAXPACK 23 +struct rogue_packitem +{ + int32_t type,launch,count,which,hplus,dplus,arm,flags,group; + char damage[8],hurldmg[8]; +}; +struct rogue_player +{ + int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; + struct rogue_packitem roguepack[MAXPACK]; +}; +int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player); UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { @@ -647,7 +658,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( rogue_findbaton(cp,&keystrokes,numkeys,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr) == 0 && keystrokes != 0 ) { UniValue obj; struct rogue_player P; - seed = uint64_t rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); + seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); fprintf(stderr,"found baton %s numkeys.%d seed.%llu\n",batontxid.ToString().c_str(),numkeys,(long long)seed); if ( playerdata.size() > 0 ) { From 5ffb4153f7573e32b2f9c31c3e3d0f1139a84964 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 02:57:07 -1100 Subject: [PATCH 0363/1145] I --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 61441d31a..823d374b5 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -639,7 +639,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; int64_t buyin,batonvalue; int32_t n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; + UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; int64_t buyin,batonvalue; int32_t i,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); From 125dee848047d36e26db49b74909637de1f9ad37 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:00:52 -1100 Subject: [PATCH 0364/1145] Fixes --- src/cc/rogue/rogue.h | 5 ++++- src/cc/rogue_rpc.cpp | 8 ++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 34df75058..189884f26 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -313,17 +313,20 @@ /* * Now we define the structures and types */ +#ifndef rogue_packitem struct rogue_packitem { int32_t type,launch,count,which,hplus,dplus,arm,flags,group; char damage[8],hurldmg[8]; }; - +#endif +#ifndef rogue_player struct rogue_player { int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; struct rogue_packitem roguepack[MAXPACK]; }; +#endif struct rogue_state { diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 823d374b5..28cdf7964 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -282,7 +282,7 @@ int32_t rogue_iterateplayer(uint256 firsttxid,uint256 lasttxid) // retrace p int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPubKey &pk,std::vector &playerdata,uint256 playertxid) { - uint256 origplayertxid,hashBlock,highlander,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,numvouts,maxplayers; int64_t buyin; + uint256 origplayertxid,hashBlock,highlander; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,numvouts,maxplayers; int64_t buyin; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) { GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); @@ -296,7 +296,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub { if ( GetTransaction(highlander,highlandertx,hashBlock,false) != 0 && (numvouts= highlandertx.vout.size()) > 0 ) { - if ( (f= rogue_highlanderopretdecode(origplayergame,registertxid,pk,playerdata,highlandertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) + if ( (f= rogue_highlanderopretdecode(origplayergame,pk,playerdata,highlandertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { if ( highlandertx.vin[0].prevout.hash == origplayergame && highlandertx.vin[0].prevout.n == 0 && rogue_isvalidgame(cp,gametx,buyin,maxplayers,origplayergame) == 0 && maxplayers > 1 ) return(0); @@ -639,7 +639,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; int64_t buyin,batonvalue; int32_t i,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; + UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed; int64_t buyin,batonvalue; int32_t i,n,num,numkeys,maxplayers,batonht,batonvout; char destaddr[64],myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -678,7 +678,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) newdata[i] = player[i]; ((uint8_t *)&P)[i] = player[i]; } - fprintf(stderr,"gold.%d hp.%d strength.%d level.%d exp.%d %d dl.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel); + fprintf(stderr,"gold.%d hp.%d strength.%d level.%d exp.%d dl.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel); mtx.vout.push_back(CTxOut(P.gold*1000000,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); //for (i=0; i_o._o_type,o->_o._o_packch,o->_o._o_packch); From c72396684216faa146a853f02e7c9d0acce30e67 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:01:54 -1100 Subject: [PATCH 0365/1145] Ifdef --- src/cc/rogue/rogue.h | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 189884f26..32bd608d4 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -313,14 +313,12 @@ /* * Now we define the structures and types */ -#ifndef rogue_packitem +#ifndef ROGUE struct rogue_packitem { int32_t type,launch,count,which,hplus,dplus,arm,flags,group; char damage[8],hurldmg[8]; }; -#endif -#ifndef rogue_player struct rogue_player { int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; From 4fe5b4096f5f9044e2184106f3bf91d15e466fe1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:03:02 -1100 Subject: [PATCH 0366/1145] BUILD_ROGUE --- src/cc/rogue/rogue.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 32bd608d4..24c3a4546 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -313,7 +313,7 @@ /* * Now we define the structures and types */ -#ifndef ROGUE +#ifdef BUILD_ROGUE struct rogue_packitem { int32_t type,launch,count,which,hplus,dplus,arm,flags,group; From 6e7fb4b198ae0fbc52588b13f388b05fbf2390da Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:04:21 -1100 Subject: [PATCH 0367/1145] Test --- src/cc/rogue/extern.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/extern.c b/src/cc/rogue/extern.c index b84e6fa7b..1205b8407 100644 --- a/src/cc/rogue/extern.c +++ b/src/cc/rogue/extern.c @@ -11,7 +11,7 @@ */ #include -#include "rogue.h" +//#include "rogue.h" From 919cf02a5cdfea70dbcda44c2adacda09a829af5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:05:56 -1100 Subject: [PATCH 0368/1145] ROGUE_DECLARED_PACK --- src/cc/rogue/extern.c | 2 +- src/cc/rogue/rogue.h | 3 ++- src/cc/rogue_rpc.cpp | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/extern.c b/src/cc/rogue/extern.c index 1205b8407..b84e6fa7b 100644 --- a/src/cc/rogue/extern.c +++ b/src/cc/rogue/extern.c @@ -11,7 +11,7 @@ */ #include -//#include "rogue.h" +#include "rogue.h" diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 24c3a4546..fa18c424f 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -313,7 +313,7 @@ /* * Now we define the structures and types */ -#ifdef BUILD_ROGUE +#ifndef ROGUE_DECLARED_PACK struct rogue_packitem { int32_t type,launch,count,which,hplus,dplus,arm,flags,group; @@ -324,6 +324,7 @@ struct rogue_player int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; struct rogue_packitem roguepack[MAXPACK]; }; +#define ROGUE_DECLARED_PACK #endif struct rogue_state diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 28cdf7964..d51cd8335 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -631,6 +631,7 @@ struct rogue_player struct rogue_packitem roguepack[MAXPACK]; }; int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player); +#define ROGUE_DECLARED_PACK UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { From b02bc22f4fc11999006661a5b4631954f7a62193 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:10:38 -1100 Subject: [PATCH 0369/1145] extraction --- src/cc/rogue/rogue.c | 2 +- src/cc/rogue_rpc.cpp | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 68f77a0cb..62a8a2e1c 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -169,7 +169,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu rs->seed = seed; rs->keystrokes = keystrokes; rs->numkeys = num; - rs->sleeptime = 50000; + rs->sleeptime = 0; if ( player != 0 ) rs->P = *player; uint32_t starttime = (uint32_t)time(NULL); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d51cd8335..7c01a7439 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -679,7 +679,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) newdata[i] = player[i]; ((uint8_t *)&P)[i] = player[i]; } - fprintf(stderr,"gold.%d hp.%d strength.%d level.%d exp.%d dl.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel); + fprintf(stderr,"\n$$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel); mtx.vout.push_back(CTxOut(P.gold*1000000,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); //for (i=0; i_o._o_type,o->_o._o_packch,o->_o._o_packch); @@ -687,6 +687,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,destaddr); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_highlanderopret(gametxid,mypk,newdata)); + fprintf(stderr,"bailout.(%s)\n",rawtx.c_str()); return(rogue_rawtxresult(result,rawtx,0)); } result.push_back(Pair("result","success")); From 7d0d4ab892bf28a45164c2cef3b3ade88faf94d4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:12:49 -1100 Subject: [PATCH 0370/1145] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 7c01a7439..5b21348b7 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -680,7 +680,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ((uint8_t *)&P)[i] = player[i]; } fprintf(stderr,"\n$$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel); - mtx.vout.push_back(CTxOut(P.gold*1000000,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + //mtx.vout.push_back(CTxOut(P.gold*1000000,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); //for (i=0; i_o._o_type,o->_o._o_packch,o->_o._o_packch); } From 4970ed8a70f3ddb123ae59206e486298a9840153 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:15:03 -1100 Subject: [PATCH 0371/1145] Test --- src/cc/rogue_rpc.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5b21348b7..ef1ad7d92 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -640,7 +640,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed; int64_t buyin,batonvalue; int32_t i,n,num,numkeys,maxplayers,batonht,batonvout; char destaddr[64],myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; + UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed; int64_t buyin,batonvalue; int32_t i,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -680,12 +680,12 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ((uint8_t *)&P)[i] = player[i]; } fprintf(stderr,"\n$$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel); - //mtx.vout.push_back(CTxOut(P.gold*1000000,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + mtx.vout.push_back(CTxOut(P.gold*1000000,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); //for (i=0; i_o._o_type,o->_o._o_packch,o->_o._o_packch); } Myprivkey(mypriv); - CCaddr1of2set(cp,roguepk,mypk,mypriv,destaddr); + CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_highlanderopret(gametxid,mypk,newdata)); fprintf(stderr,"bailout.(%s)\n",rawtx.c_str()); return(rogue_rawtxresult(result,rawtx,0)); From f657ea839fab50f4659188386380f2009204e622 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:17:37 -1100 Subject: [PATCH 0372/1145] Resize --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ef1ad7d92..810aed574 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -671,7 +671,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); // also need a vin from gametx mtx.vout.push_back(MakeCC1vout(cp->evalcode,batonvalue-txfee,roguepk)); - if ( num == sizeof(P) ) + if ( num > 0 ) { newdata.resize(num); for (i=0; i_o._o_type,o->_o._o_packch,o->_o._o_packch); From 7fca64253c863dbef4cb3b6e6da9b559486741eb Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:24:51 -1100 Subject: [PATCH 0373/1145] Fund gold extraction --- src/cc/rogue_rpc.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 810aed574..3cbe37de1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -640,7 +640,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed; int64_t buyin,batonvalue; int32_t i,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; + UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed; int64_t buyin,batonvalue,CCchange=0; int32_t i,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -670,7 +670,6 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) free(keystrokes); mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); // also need a vin from gametx - mtx.vout.push_back(MakeCC1vout(cp->evalcode,batonvalue-txfee,roguepk)); if ( num > 0 ) { newdata.resize(num); @@ -679,15 +678,17 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) newdata[i] = player[i]; ((uint8_t *)&P)[i] = player[i]; } + if ( (inputsum= AddCClibInputs(cp,mtx,roguepk,(uint64_t)P.gold*1000000,16,cp->unspendableCCaddr)) >= (uint64_t)P.gold*1000000+txfee ) + CCchange = (inputsum - (uint64_t)P.gold*1000000 - txfee); fprintf(stderr,"\n$$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); mtx.vout.push_back(CTxOut(P.gold*1000000,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); //for (i=0; i_o._o_type,o->_o._o_packch,o->_o._o_packch); } + mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-txfee),roguepk)); Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_highlanderopret(gametxid,mypk,newdata)); - fprintf(stderr,"bailout.(%s)\n",rawtx.c_str()); return(rogue_rawtxresult(result,rawtx,0)); } result.push_back(Pair("result","success")); From f31e50fdc4bdfbbf0a642aaf5e9c208828d021af Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:25:45 -1100 Subject: [PATCH 0374/1145] Inputs --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3cbe37de1..e7b0c1541 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -640,7 +640,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed; int64_t buyin,batonvalue,CCchange=0; int32_t i,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; + UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed; int64_t buyin,batonvalue,inputsum,CCchange=0; int32_t i,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); From 60b2785c9c3bef31fc0402364e764e4ff2419d40 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:29:09 -1100 Subject: [PATCH 0375/1145] Extraction --- src/cc/rogue_rpc.cpp | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e7b0c1541..d2bbcd356 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -79,6 +79,19 @@ // cclib register 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22,%22%22]\" // cclib keystrokes 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22,%22deadbeef%22]\" // cclib bailout 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" +/* + gold.218 hp.20 strength.16 level.3 exp.22 2 +object (Some food) x.0 y.0 type.58 pack.(a:97) +object (+1 ring mail [protection 4] (being worn)) x.0 y.0 type.93 pack.(b:98) +object (A +1,+1 mace (weapon in hand)) x.0 y.0 type.41 pack.(c:99) +object (A +1,+0 short bow) x.0 y.0 type.41 pack.(d:100) +object (28 +0,+0 arrows) x.0 y.0 type.41 pack.(e:101) +object (A scroll titled 'eeptanelg eep agitwhon wunayot') x.9 y.13 type.63 pack.(f:102) +object (A scroll titled 'aks snodo') x.13 y.3 type.63 pack.(g:103) +object (A scroll titled 'itenejbot lechlech') x.35 y.13 type.63 pack.(h:104) +da000000140000001000000003000000160000000800000002000000000000003a0000000000000001000000000000000000000000000000000000001000000000000000000000000000000000000000000000005d00000000000000010000000100000000000000000000000600000012000000000000000000000000000000000000000000000029000000ffffffff010000000000000001000000010000000000000012000000000000003278340000000000317833000000000029000000ffffffff010000000200000001000000000000000000000012000000000000003178310000000000317831000000000029000000020000001c000000030000000000000000000000000000001e00000000000000317831000000000032783300000000003f00000000000000010000000c00000000000000000000000b0000001000000000000000307830000000000030783000000000003f00000000000000010000000300000000000000000000000b0000001000000000000000307830000000000030783000000000003f00000000000000010000000000000000000000000000000b000000100000000000000030783000000000003078300000000000 packsize.8 n.448 + +$$$gold.218 hp.20 strength.16 level.3 exp.22 dl.2 n.1 size.1228*/ CScript rogue_newgameopret(int64_t buyin,int32_t maxplayers) { @@ -678,9 +691,9 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) newdata[i] = player[i]; ((uint8_t *)&P)[i] = player[i]; } - if ( (inputsum= AddCClibInputs(cp,mtx,roguepk,(uint64_t)P.gold*1000000,16,cp->unspendableCCaddr)) >= (uint64_t)P.gold*1000000+txfee ) - CCchange = (inputsum - (uint64_t)P.gold*1000000 - txfee); - fprintf(stderr,"\n$$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); + if ( (inputsum= AddCClibInputs(cp,mtx,roguepk,(uint64_t)P.gold*1000000,16,cp->unspendableCCaddr)) > (uint64_t)P.gold*1000000 ) + CCchange = (inputsum - (uint64_t)P.gold*1000000); + fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); mtx.vout.push_back(CTxOut(P.gold*1000000,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); //for (i=0; i_o._o_type,o->_o._o_packch,o->_o._o_packch); From 3ac7cbd35c3eabf536c40f696c1fc25e637bee49 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:42:54 -1100 Subject: [PATCH 0376/1145] Marker for all registrations --- src/cc/rogue_rpc.cpp | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d2bbcd356..071287fb0 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -91,7 +91,9 @@ object (A scroll titled 'aks snodo') x.13 y.3 type.63 pack.(g:103) object (A scroll titled 'itenejbot lechlech') x.35 y.13 type.63 pack.(h:104) da000000140000001000000003000000160000000800000002000000000000003a0000000000000001000000000000000000000000000000000000001000000000000000000000000000000000000000000000005d00000000000000010000000100000000000000000000000600000012000000000000000000000000000000000000000000000029000000ffffffff010000000000000001000000010000000000000012000000000000003278340000000000317833000000000029000000ffffffff010000000200000001000000000000000000000012000000000000003178310000000000317831000000000029000000020000001c000000030000000000000000000000000000001e00000000000000317831000000000032783300000000003f00000000000000010000000c00000000000000000000000b0000001000000000000000307830000000000030783000000000003f00000000000000010000000300000000000000000000000b0000001000000000000000307830000000000030783000000000003f00000000000000010000000000000000000000000000000b000000100000000000000030783000000000003078300000000000 packsize.8 n.448 -$$$gold.218 hp.20 strength.16 level.3 exp.22 dl.2 n.1 size.1228*/ +$$$gold.218 hp.20 strength.16 level.3 exp.22 dl.2 n.1 size.1228 + ca995aa934b5365e9b86d3db97919e3c26ea03ee6e3045bfc9b05a079ab8b130 + */ CScript rogue_newgameopret(int64_t buyin,int32_t maxplayers) { @@ -251,8 +253,12 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,CTransaction &tx,int64_t &b if ( numvouts > maxplayers+2 ) { for (i=0; i &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr) +int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &numkeys,int32_t ®slot,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr) { int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 spenttxid,hashBlock,txid,playertxid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; numkeys = 0; @@ -347,6 +353,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &n if ( strcmp(destaddr,ccaddr) == 0 ) { matches++; + regslot = i; matchtx = spenttx; } else fprintf(stderr,"%d+2 doesnt match %s vs %s\n",i,ccaddr,destaddr); } //else fprintf(stderr,"%d+2 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); @@ -413,7 +420,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &n void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers) { // identify if bailout or quit or timed out - uint256 batontxid,spenttxid,hashBlock; CTransaction spenttx; int32_t numkeys,batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; + uint256 batontxid,spenttxid,hashBlock; CTransaction spenttx; int32_t regslot,numkeys,batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; destaddr[0] = 0; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { @@ -421,7 +428,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); } obj.push_back(Pair("slot",(int64_t)vout-2)); - if ( (retval= rogue_findbaton(cp,0,numkeys,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr)) == 0 ) + if ( (retval= rogue_findbaton(cp,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr)) == 0 ) { obj.push_back(Pair("baton",batontxid.ToString())); obj.push_back(Pair("batonaddr",destaddr)); @@ -499,6 +506,8 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,roguepk)); // for highlander TCBOO used for (i=0; ievalcode,ROGUE_REGISTRATIONSIZE,roguepk,roguepk)); + for (i=0; ievalcode,txfee,roguepk,roguepk)); if ( (change= inputsum - required) >= txfee ) mtx.vout.push_back(MakeCC1vout(cp->evalcode,change,roguepk)); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_newgameopret(buyin,maxplayers)); @@ -584,7 +593,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // respawn to be prevented by including timestamps int32_t nextheight = komodo_nextheight(); CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(),nextheight); - UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t numkeys,batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; uint8_t mypriv[32]; + UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t regslot,numkeys,batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; uint8_t mypriv[32]; if ( txfee == 0 ) txfee = 10000; rogue_univalue(result,"keystrokes",-1,-1); @@ -597,7 +606,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param GetCCaddress1of2(cp,destaddr,roguepk,mypk); if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,gametxid) == 0 ) { - if ( rogue_findbaton(cp,0,numkeys,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr) == 0 ) + if ( rogue_findbaton(cp,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr) == 0 ) { if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) { @@ -650,10 +659,11 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { // detect if last to bailout // vin0 -> kestrokes baton of completed game with Q + // vout0 -> playerdata marker // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed; int64_t buyin,batonvalue,inputsum,CCchange=0; int32_t i,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; + UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed; int64_t buyin,batonvalue,inputsum,CCchange=0; int32_t i,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -669,7 +679,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("gametxid",gametxid.GetHex())); if ( rogue_isvalidgame(cp,gametx,buyin,maxplayers,gametxid) == 0 ) { - if ( rogue_findbaton(cp,&keystrokes,numkeys,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr) == 0 && keystrokes != 0 ) + if ( rogue_findbaton(cp,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr) == 0 && keystrokes != 0 ) { UniValue obj; struct rogue_player P; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); @@ -682,7 +692,8 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) num = rogue_replay2(player,seed,keystrokes,numkeys,playerdata.size()==0?0:&P); //4419709268196762041 free(keystrokes); mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); - // also need a vin from gametx + mtx.vin.push_back(CTxIn(gametxid,2+maxplayers+slot,CScript())); + mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,mypk)); if ( num > 0 ) { newdata.resize(num); @@ -698,7 +709,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //for (i=0; i_o._o_type,o->_o._o_packch,o->_o._o_packch); } - mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-txfee),roguepk)); + mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-2*txfee),roguepk)); Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_highlanderopret(gametxid,mypk,newdata)); From 3369acbc7d2382be15dca4d650ed3a7aadbbbc46 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 03:51:10 -1100 Subject: [PATCH 0377/1145] Set of gametxid vouts for bailouts --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 071287fb0..f5745c314 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -692,7 +692,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) num = rogue_replay2(player,seed,keystrokes,numkeys,playerdata.size()==0?0:&P); //4419709268196762041 free(keystrokes); mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); - mtx.vin.push_back(CTxIn(gametxid,2+maxplayers+slot,CScript())); + mtx.vin.push_back(CTxIn(gametxid,2+maxplayers+regslot,CScript())); mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,mypk)); if ( num > 0 ) { From d7338fa770d6a385def8f75cc1ab0ac0ea645f67 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 06:29:43 -1100 Subject: [PATCH 0378/1145] 'H' command --- src/cc/rogue_rpc.cpp | 166 ++++++++++++++++++++++++++++++++----------- 1 file changed, 125 insertions(+), 41 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f5745c314..5c1fa9cba 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -22,14 +22,61 @@ #define ROGUE_MAXKEYSTROKESGAP 60 /* - the idea is that you creategame and get a txid, you specify the maxplayers and buyin for the game. the tx will have maxplayers of vouts. You must have a non-zero buyin to be able to use a preexisting character. + Roguelander - using highlander competition between rogue players + + anybody can create a game by specifying maxplayers and buyin. Buyin of 0.00 ROGUE is for newbies and a good way to get experience. All players will start in the identical level, but each level after that will be unique to each player. + There are two different modes that is based on the maxplayers. If maxplayers is one, then it is basically a practice/farming game where there are no time limits. Also, the gold -> ROGUE conversion rate is cut in half. You can start a single player game as soon as the newgame tx is confirmed. + + If maxplayers is more than one, then it goes into highlander mode. There can only be one winner. Additionally, multiplayer mode adds a timelimit of ROGUE_MAXKEYSTROKESGAP (60) blocks between keystrokes updates. That is approx. one hour and every level it does an automatic update, so as long as you are actively playing, it wont be a problem. The is ROGUE_REGISTRATION blocks waiting period before any of the players can start. The random seed for the game is based on the future blockhash so that way, nobody is able to start before the others. + + rogue is not an easy game to win, so it could be that the winner for a specific group is simply the last one standing. If you bailout of a game you cant win, but you can convert all the ingame gold you gathered at 0.001 ROGUE each. [In the event that there arent enough globally locked funds to payout the ROGUE, you will have to wait until there is. Since 10% of all economic activity creates more globally locked funds, it is just a matter of time before there will be enough funds to payout. Also, you can help speed this up by encouraging others to transact in ROGUE] + + Of course, the most direct way to win, is to get the amulet and come back out of the dungeon. The winner will get all of the buyins from all the players in addition to 0.01 ROGUE for every ingame gold. + + The above alone is enough to make the timeless classic solitaire game into a captivating multiplayer game, where real coins are at stake. However, there is an even better aspect to ROGUE! Whenever your player survives a game, even when you bailout, the entire player and his pack is preserved on the blockchain and becomes a nonfungible asset that you can trade for ROGUE. + + Additionally, instead of just being a collectors item with unique characteristics, the rogue playerdata can be used in any ROGUE game. Just specify the txid that created your character when you register and your character is restored. The better your characteristics your playerdata has, the more likely you are to win in multiplayer mode to win all the buyins. So there is definite economic value to a strong playerdata. + + You can farm characters in single player mode to earn ROGUE or to make competitive playerdata sets. You can purchase existing playerdata for collecting, or for using in battle. + + Here is how to play: + + ./komodo-cli -ac_name=ROGUE cclib newgame 17 \"[3,10]\" -> this will create a hex transaction that when broadcast with sendrawtransaction will get a gametxid onto the blockchain. This specific command was for 3 players and a buyin of 10 ROGUE. Lets assume the gametxid is 4fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a, most all the other commands will need the gametxid. + + you can always find all the existing games with: + + ./komodo-cli -ac_name=ROGUE cclib pending 17 + + and info about a specific game with: + + ./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" + + due to quirks of various parsing at the shell, rpc and internal level, the above convention is used where %22 is added where " should be. also all fields are separated by , without any space. + + When you do a gameinfo command it will show a "run" field and that will tell you if you are registered for the game or not. If not, the "run" field shows the register syntax you need to do, if you are registered, it will show the command line to start the rogue game that is playing the registered game. + +./komodo-cli -ac_name=ROGUE cclib register 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22,%22playerdata_txid%22]\" + + If you want to cash in your ingame gold and preserve your character for another battle, do the bailout: + +./komodo-cli -ac_name=ROGUE cclib bailout 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" + + If you won your game before anybody else did or if you are the last one left who didnt bailout, you can claim the prize: + + ./komodo-cli -ac_name=ROGUE cclib highlander 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" + + The txid you get from the bailout or highlander transactions is the "playerdata_txid" that you can use in future games. + + + Transaction details creategame vout0 -> txfee highlander vout TCBOO creation - vout1 -> txfee highlander vout TCBOO playerdata used - vout2 to vout.maxplayers -> 1of2 registration ROGUE_REGISTRATIONSIZE batons + vout1 -> txfee highlander vout TCBOO playerdata used (deprecated) + vout2 to vout.maxplayers+2 -> 1of2 registration ROGUE_REGISTRATIONSIZE batons + vout2+maxplayers to vout.2*maxplayers+2 -> 1of2 registration txfee batons for game completion - registration + register vin0 -> ROGUE_REGISTRATIONSIZE 1of2 registration baton from creategame vin1 -> optional nonfungible character vout @ vin2 -> original creation TCBOO playerdata used @@ -40,13 +87,13 @@ vin0 -> txfee 1of2 baton from registration or previous keystrokes opret -> user input chars - bailout: must be within 777 blocks of last keystrokes + bailout: must be within ROGUE_MAXKEYSTROKESGAP blocks of last keystrokes vin0 -> keystrokes baton of completed game with Q vout0 -> 1% ingame gold highlander vin0 -> txfee highlander vout from creategame TCBOO creation - vin1 -> keystrokes baton of completed game, must be last to quit or first to win, only spent registration batons matter. If more than 777 blocks since last keystrokes, it is forfeit + vin1 -> keystrokes baton of completed game, must be last to quit or first to win, only spent registration batons matter. If more than ROGUE_MAXKEYSTROKESGAP blocks since last keystrokes, it is forfeit vins -> rest of unspent registration utxo so all newgame vouts are spent vout0 -> nonfungible character with pack @ vout1 -> 1% ingame gold and all the buyins @@ -235,6 +282,8 @@ uint64_t rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 } } } + obj.push_back(Pair("alive",rogue_playersalive(numplayers,gametxid,maxplayers))); + obj.push_back(Pair("numplayers",numplayers)); obj.push_back(Pair("maxplayers",maxplayers)); obj.push_back(Pair("buyin",ValueFromAmount(buyin))); return(seed); @@ -328,6 +377,23 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub return(-1); } +int32_t rogue_playersalive(int32_t &numplayers,uint256 gametxid,int32_t maxplayers) +{ + int32_t i,alive = 0; + numplayers = 0; + for (i=0; i &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr) +int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &numkeys,int32_t ®slot,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr,int32_t &numplayers) { int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 spenttxid,hashBlock,txid,playertxid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; - numkeys = 0; + numkeys = numplayers = 0; for (i=0; i= 0 ) { if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) { + numplayers++; Getscriptaddress(ccaddr,spenttx.vout[0].scriptPubKey); if ( strcmp(destaddr,ccaddr) == 0 ) { matches++; regslot = i; matchtx = spenttx; - } else fprintf(stderr,"%d+2 doesnt match %s vs %s\n",i,ccaddr,destaddr); + } //else fprintf(stderr,"%d+2 doesnt match %s vs %s\n",i,ccaddr,destaddr); } //else fprintf(stderr,"%d+2 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); } //else fprintf(stderr,"%d+2 unspent\n",i); } @@ -420,7 +487,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &n void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers) { // identify if bailout or quit or timed out - uint256 batontxid,spenttxid,hashBlock; CTransaction spenttx; int32_t regslot,numkeys,batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; + uint256 batontxid,spenttxid,hashBlock; CTransaction spenttx; int32_t numplayers,regslot,numkeys,batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; destaddr[0] = 0; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { @@ -428,7 +495,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); } obj.push_back(Pair("slot",(int64_t)vout-2)); - if ( (retval= rogue_findbaton(cp,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr)) == 0 ) + if ( (retval= rogue_findbaton(cp,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr,numplayers)) == 0 ) { obj.push_back(Pair("baton",batontxid.ToString())); obj.push_back(Pair("batonaddr",destaddr)); @@ -574,7 +641,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"couldnt find playerdata to spend")); else if ( buyin > 0 && AddNormalinputs(mtx,mypk,buyin,64) < buyin ) return(cclib_error(result,"couldnt find enough normal funds for buyin")); - mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,inputsum-txfee,roguepk,mypk)); + mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_registeropret(gametxid,playertxid)); @@ -593,7 +660,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // respawn to be prevented by including timestamps int32_t nextheight = komodo_nextheight(); CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(),nextheight); - UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t regslot,numkeys,batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; uint8_t mypriv[32]; + UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t numplayers,regslot,numkeys,batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; uint8_t mypriv[32]; if ( txfee == 0 ) txfee = 10000; rogue_univalue(result,"keystrokes",-1,-1); @@ -606,7 +673,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param GetCCaddress1of2(cp,destaddr,roguepk,mypk); if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,gametxid) == 0 ) { - if ( rogue_findbaton(cp,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr) == 0 ) + if ( rogue_findbaton(cp,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr,numplayers) == 0 ) { if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) { @@ -623,24 +690,6 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"couldnt reparse params")); } -UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - //vin0 -> highlander vout from creategame TCBOO - //vin1 -> keystrokes baton of completed game, must be last to quit or first to win, only spent registration batons matter. If more than 60 blocks since last keystrokes, it is forfeit - //vins2+ -> rest of unspent registration utxo so all newgame vouts are spent - //vout0 -> nonfungible character with pack @ - //vout1 -> 1% ingame gold and all the buyins - CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); - if ( txfee == 0 ) - txfee = 10000; - // make sure no highlander and it is an actual ingame win - result.push_back(Pair("result","success")); - result.push_back(Pair("name","rogue")); - result.push_back(Pair("method","highlander")); - return(result); -} - #define MAXPACK 23 struct rogue_packitem { @@ -655,22 +704,38 @@ struct rogue_player int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player); #define ROGUE_DECLARED_PACK -UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params,char *method) { + //vin0 -> highlander vout from creategame TCBOO + //vin1 -> keystrokes baton of completed game, must be last to quit or first to win, only spent registration batons matter. If more than 60 blocks since last keystrokes, it is forfeit + //vins2+ -> rest of unspent registration utxo so all newgame vouts are spent + //vout0 -> nonfungible character with pack @ + //vout1 -> 1% ingame gold and all the buyins + // detect if last to bailout // vin0 -> kestrokes baton of completed game with Q // vout0 -> playerdata marker // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed; int64_t buyin,batonvalue,inputsum,CCchange=0; int32_t i,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32]; + UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); result.push_back(Pair("name","rogue")); - result.push_back(Pair("method","bailout")); + result.push_back(Pair("method",method)); + if ( strcmp(method,"bailout") == 0 ) + { + funcid = 'Q'; + mult = 100000; + } + else + { + funcid = 'H'; + mult = 1000000; + } if ( (params= cclib_reparse(&n,params)) != 0 ) { if ( n > 0 ) @@ -679,7 +744,9 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("gametxid",gametxid.GetHex())); if ( rogue_isvalidgame(cp,gametx,buyin,maxplayers,gametxid) == 0 ) { - if ( rogue_findbaton(cp,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr) == 0 && keystrokes != 0 ) + if ( maxplayers == 1 ) + mult /= 2; + if ( rogue_findbaton(cp,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers) == 0 && keystrokes != 0 ) { UniValue obj; struct rogue_player P; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); @@ -689,7 +756,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) for (i=0; iunspendableCCaddr)) > (uint64_t)P.gold*1000000 ) - CCchange = (inputsum - (uint64_t)P.gold*1000000); fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); - mtx.vout.push_back(CTxOut(P.gold*1000000,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + cashout = (uint64_t)P.gold * mult; + if ( funcid == 'H' ) + { + if ( (numplayers - rogue_playersalive(tmp,gametxid,maxplayers)) > 1 && (P.dungeonlevel > 1 || P.gold < 10000 || P.level < 20) ) + return(cclib_error(result,"highlander must be a winner or last one standing")); + cashout += numplayers * buyin; + } + if ( (inputsum= AddCClibInputs(cp,mtx,roguepk,cashout,16,cp->unspendableCCaddr)) > (uint64_t)P.gold*mult ) + CCchange = (inputsum - cashout); + mtx.vout.push_back(CTxOut(cashout,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); //for (i=0; i_o._o_type,o->_o._o_packch,o->_o._o_packch); } mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-2*txfee),roguepk)); Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_highlanderopret(gametxid,mypk,newdata)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_highlanderopret(funcid,gametxid,mypk,newdata)); return(rogue_rawtxresult(result,rawtx,0)); } result.push_back(Pair("result","success")); @@ -722,6 +796,16 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } +UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + return(rogue_finishgame(txfee,cp,params,"bailout")); +} + +UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + return(rogue_finishgame(txfee,cp,params,"highlander")); +} + UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; bits256 t; char myrogueaddr[64]; CPubKey mypk,roguepk; From c48d0cabcaf57ff3613911e245a4b124e7314710 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 06:40:01 -1100 Subject: [PATCH 0379/1145] Syntax --- src/cc/rogue_rpc.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5c1fa9cba..d647163bc 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -163,10 +163,10 @@ CScript rogue_keystrokesopret(uint256 gametxid,uint256 batontxid,CPubKey pk,std: return(opret); } -CScript rogue_highlanderopret(uint256 gametxid,CPubKey pk,std::vectorplayerdata) +CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,CPubKey pk,std::vectorplayerdata) { CScript opret; uint8_t evalcode = EVAL_ROGUE; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'K' << gametxid << pk << playerdata); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << gametxid << pk << playerdata); return(opret); } @@ -259,7 +259,7 @@ int32_t rogue_iamregistered(int32_t maxplayers,uint256 gametxid,CTransaction tx, uint64_t rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gametxid,char *myrogueaddr) { - CBlockIndex *pindex; int32_t ht,delay; uint256 hashBlock; uint64_t seed=0; char cmd[512]; CTransaction tx; + CBlockIndex *pindex; int32_t ht,delay,numplayers; uint256 hashBlock; uint64_t seed=0; char cmd[512]; CTransaction tx; if ( GetTransaction(gametxid,tx,hashBlock,false) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) { ht = pindex->GetHeight(); @@ -379,7 +379,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub int32_t rogue_playersalive(int32_t &numplayers,uint256 gametxid,int32_t maxplayers) { - int32_t i,alive = 0; + int32_t i,alive = 0; uint64_t txfee = 10000; numplayers = 0; for (i=0; i Date: Wed, 6 Feb 2019 06:40:52 -1100 Subject: [PATCH 0380/1145] Reorder --- src/cc/rogue_rpc.cpp | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d647163bc..f6fd057a0 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -257,6 +257,22 @@ int32_t rogue_iamregistered(int32_t maxplayers,uint256 gametxid,CTransaction tx, return(0); } +int32_t rogue_playersalive(int32_t &numplayers,uint256 gametxid,int32_t maxplayers) +{ + int32_t i,alive = 0; uint64_t txfee = 10000; + numplayers = 0; + for (i=0; i Date: Wed, 6 Feb 2019 06:44:00 -1100 Subject: [PATCH 0381/1145] Allocate enough for new game --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f6fd057a0..5501c2a1e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -565,7 +565,7 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); rogue_univalue(result,"newgame",maxplayers,buyin); - required = (3*txfee + maxplayers*ROGUE_REGISTRATIONSIZE); + required = (3*txfee + maxplayers*(ROGUE_REGISTRATIONSIZE+txfee)); if ( (inputsum= AddCClibInputs(cp,mtx,roguepk,required,16,cp->unspendableCCaddr)) >= required ) { mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,roguepk)); // for highlander TCBOO creation From 22d3a27d5e12e1a4668f2357ebe29f2220b89311 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 07:01:17 -1100 Subject: [PATCH 0382/1145] [] -> * --- src/cc/rogue/save.c | 2 +- src/cc/rogue_rpc.cpp | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index 8a40a9fb8..c96aa6b13 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -22,7 +22,7 @@ typedef struct stat STAT; -extern char version[], encstr[]; +extern char *version, *encstr; static STAT sbuf; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5501c2a1e..7a54366ae 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -120,12 +120,12 @@ // cclib newgame 17 \"[3,10]\" // cclib pending 17 -// cclib gameinfo 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" -// cclib register 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" +// cclib gameinfo 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22]\" +// cclib register 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22]\" // ./rogue gui -> creates keystroke files -// cclib register 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22,%22%22]\" -// cclib keystrokes 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22,%22deadbeef%22]\" -// cclib bailout 17 \"[%224fd6f5cad0fac455e5989ca6eef111b00292845447075a802e9335879146ad5a%22]\" +// cclib register 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22,%22%22]\" +// cclib keystrokes 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22,%22deadbeef%22]\" +// cclib bailout 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22]\" /* gold.218 hp.20 strength.16 level.3 exp.22 2 object (Some food) x.0 y.0 type.58 pack.(a:97) From fee10112f01153b1ef542357c034e0f5ff746a29 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 07:02:11 -1100 Subject: [PATCH 0383/1145] * --- src/cc/rogue/vers.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/vers.c b/src/cc/rogue/vers.c index dcca986b1..b6c5237d1 100644 --- a/src/cc/rogue/vers.c +++ b/src/cc/rogue/vers.c @@ -12,6 +12,6 @@ */ char *release = "5.4.4"; -char encstr[] = "\300k||`\251Y.'\305\321\201+\277~r\"]\240_\223=1\341)\222\212\241t;\t$\270\314/<#\201\254"; +char *encstr = "\300k||`\251Y.'\305\321\201+\277~r\"]\240_\223=1\341)\222\212\241t;\t$\270\314/<#\201\254"; char statlist[] = "\355kl{+\204\255\313idJ\361\214=4:\311\271\341wK<\312\321\213,,7\271/Rk%\b\312\f\246"; -char version[] = "rogue (rogueforge) 09/05/07"; +char *version = "rogue (rogueforge) 09/05/07"; From 518f11f77d83880cdac383aa623eb97bcbf9f8c2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 07:02:48 -1100 Subject: [PATCH 0384/1145] Statlist --- src/cc/rogue/save.c | 4 ++-- src/cc/rogue/vers.c | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index c96aa6b13..adec30e2e 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -333,7 +333,7 @@ encwrite(char *start, size_t size, FILE *outf) { char *e1, *e2, fb; int temp; - extern char statlist[]; + extern char *statlist; size_t o_size = size; e1 = encstr; e2 = statlist; @@ -371,7 +371,7 @@ encread(char *start, size_t size, FILE *inf) char *e1, *e2, fb; int temp; size_t read_size; - extern char statlist[]; + extern char *statlist; fb = 0; diff --git a/src/cc/rogue/vers.c b/src/cc/rogue/vers.c index b6c5237d1..6fbf7be87 100644 --- a/src/cc/rogue/vers.c +++ b/src/cc/rogue/vers.c @@ -13,5 +13,5 @@ char *release = "5.4.4"; char *encstr = "\300k||`\251Y.'\305\321\201+\277~r\"]\240_\223=1\341)\222\212\241t;\t$\270\314/<#\201\254"; -char statlist[] = "\355kl{+\204\255\313idJ\361\214=4:\311\271\341wK<\312\321\213,,7\271/Rk%\b\312\f\246"; +char *statlist = "\355kl{+\204\255\313idJ\361\214=4:\311\271\341wK<\312\321\213,,7\271/Rk%\b\312\f\246"; char *version = "rogue (rogueforge) 09/05/07"; From fdec90dc57e09df4a21a28e6e43d22fe225eb135 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 07:41:13 -1100 Subject: [PATCH 0385/1145] condCC2 --- src/cc/CCtx.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index 932677e20..111fc11ad 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -46,9 +46,9 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran CTransaction vintx; std::string hex; CPubKey globalpk; uint256 hashBlock; uint64_t mask=0,nmask=0,vinimask=0; int64_t utxovalues[CC_MAXVINS],change,normalinputs=0,totaloutputs=0,normaloutputs=0,totalinputs=0,normalvins=0,ccvins=0; int32_t i,flag,utxovout,n,err = 0; - char myaddr[64], destaddr[64], unspendable[64], mytokensaddr[64], mysingletokensaddr[64], tokensunspendable[64]; + char myaddr[64], destaddr[64], unspendable[64], mytokensaddr[64], mysingletokensaddr[64], tokensunspendable[64],CC1of2CCaddr[64]; uint8_t *privkey, myprivkey[32], unspendablepriv[32], tokensunspendablepriv[32], *msg32 = 0; - CC *mycond=0, *othercond=0, *othercond2=0,*othercond4=0, *othercond3=0, *othercond1of2=NULL, *othercond1of2tokens = NULL, *cond, *mytokenscond = NULL, *mysingletokenscond = NULL, *othertokenscond = NULL; + CC *mycond=0, *othercond=0, *othercond2=0,*othercond4=0, *othercond3=0, *othercond1of2=NULL, *othercond1of2tokens = NULL, *cond, *condCC2=0,*mytokenscond = NULL, *mysingletokenscond = NULL, *othertokenscond = NULL; CPubKey unspendablepk /*, tokensunspendablepk*/; struct CCcontract_info *cpTokens, tokensC; globalpk = GetUnspendable(cp,0); @@ -73,6 +73,9 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran unspendablepk = GetUnspendable(cp, unspendablepriv); GetCCaddress(cp, unspendable, unspendablepk); othercond = MakeCCcond1(cp->evalcode, unspendablepk); + + CCaddr1of2set(cp,unspendablepk,unspendablepk,unspendablepriv,CC1of2CCaddr); + //printf("evalcode.%d (%s)\n",cp->evalcode,unspendable); // tokens support: @@ -212,6 +215,13 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran othercond1of2 = MakeCCcond1of2(cp->evalcode, cp->coins1of2pk[0], cp->coins1of2pk[1]); cond = othercond1of2; } + else if ( strcmp(CC1of2CCaddr,destaddr) == 0 ) + { + privkey = unspendablepriv; + if (condCC2 == 0) + condCC2 = MakeCCcond1of2(cp->evalcode,unspendablepk,unspendablepk); + cond = condCC2; + } // check if this is spending from 1of2 cc tokens addr: else if (strcmp(cp->tokens1of2addr, destaddr) == 0) { @@ -267,6 +277,8 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran } if ( mycond != 0 ) cc_free(mycond); + if ( condCC2 != 0 ) + cc_free(condCC2); if ( othercond != 0 ) cc_free(othercond); if ( othercond2 != 0 ) From da2b3e31f80b98108bd69b7b79957c9079a3619a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 07:45:01 -1100 Subject: [PATCH 0386/1145] +print --- src/cc/CCtx.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index 111fc11ad..cd78ef045 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -209,7 +209,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran // check if this is spending from 1of2 cc coins addr: else if (strcmp(cp->coins1of2addr, destaddr) == 0) { - //fprintf(stderr,"FinalizeCCTx() matched %s unspendable1of2!\n",cp->coins1of2addr); + fprintf(stderr,"FinalizeCCTx() matched %s unspendable1of2!\n",cp->coins1of2addr); privkey = cp->coins1of2priv;//myprivkey; if (othercond1of2 == 0) othercond1of2 = MakeCCcond1of2(cp->evalcode, cp->coins1of2pk[0], cp->coins1of2pk[1]); @@ -217,6 +217,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran } else if ( strcmp(CC1of2CCaddr,destaddr) == 0 ) { + fprintf(stderr,"FinalizeCCTx() matched %s CC1of2CCaddr!\n",CC1of2CCaddr); privkey = unspendablepriv; if (condCC2 == 0) condCC2 = MakeCCcond1of2(cp->evalcode,unspendablepk,unspendablepk); From 373fd28f64ccc1a1bfffd1594957cc8e1dc9b2ca Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 07:48:37 -1100 Subject: [PATCH 0387/1145] +print --- src/cc/rogue_rpc.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 7a54366ae..46df85078 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -725,6 +725,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); result.push_back(Pair("name","rogue")); result.push_back(Pair("method",method)); + result.push_back(Pair("myrogueaddr",myrogueaddr)); if ( strcmp(method,"bailout") == 0 ) { funcid = 'Q'; From b70e4824481c26947065cac5bac851caac4dc50b Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 07:51:16 -1100 Subject: [PATCH 0388/1145] Fix condCC2 --- src/cc/CCtx.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index cd78ef045..b0cea19e1 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -73,8 +73,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran unspendablepk = GetUnspendable(cp, unspendablepriv); GetCCaddress(cp, unspendable, unspendablepk); othercond = MakeCCcond1(cp->evalcode, unspendablepk); - - CCaddr1of2set(cp,unspendablepk,unspendablepk,unspendablepriv,CC1of2CCaddr); + GetCCaddress1of2(cp,CC1of2CCaddr,unspendablepk,unspendablepk); //printf("evalcode.%d (%s)\n",cp->evalcode,unspendable); // tokens support: From 0abced67cab4d3fc912fbe4169c4873e5a54f497 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 07:56:57 -1100 Subject: [PATCH 0389/1145] Fix 'H' edgewise --- src/cc/rogue_rpc.cpp | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 46df85078..d48a50b65 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -114,6 +114,9 @@ once you have a non-fungible token, ownership of it can be transferred or traded or spent in a game */ +// todo: +// verify playerdata is usable +// verify keystrokes tx is confirmed //////////////////////// start of CClib interface //./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc > /dev/null & @@ -126,19 +129,20 @@ // cclib register 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22,%22%22]\" // cclib keystrokes 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22,%22deadbeef%22]\" // cclib bailout 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22]\" +// eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd /* - gold.218 hp.20 strength.16 level.3 exp.22 2 -object (Some food) x.0 y.0 type.58 pack.(a:97) -object (+1 ring mail [protection 4] (being worn)) x.0 y.0 type.93 pack.(b:98) -object (A +1,+1 mace (weapon in hand)) x.0 y.0 type.41 pack.(c:99) -object (A +1,+0 short bow) x.0 y.0 type.41 pack.(d:100) -object (28 +0,+0 arrows) x.0 y.0 type.41 pack.(e:101) -object (A scroll titled 'eeptanelg eep agitwhon wunayot') x.9 y.13 type.63 pack.(f:102) -object (A scroll titled 'aks snodo') x.13 y.3 type.63 pack.(g:103) -object (A scroll titled 'itenejbot lechlech') x.35 y.13 type.63 pack.(h:104) -da000000140000001000000003000000160000000800000002000000000000003a0000000000000001000000000000000000000000000000000000001000000000000000000000000000000000000000000000005d00000000000000010000000100000000000000000000000600000012000000000000000000000000000000000000000000000029000000ffffffff010000000000000001000000010000000000000012000000000000003278340000000000317833000000000029000000ffffffff010000000200000001000000000000000000000012000000000000003178310000000000317831000000000029000000020000001c000000030000000000000000000000000000001e00000000000000317831000000000032783300000000003f00000000000000010000000c00000000000000000000000b0000001000000000000000307830000000000030783000000000003f00000000000000010000000300000000000000000000000b0000001000000000000000307830000000000030783000000000003f00000000000000010000000000000000000000000000000b000000100000000000000030783000000000003078300000000000 packsize.8 n.448 - -$$$gold.218 hp.20 strength.16 level.3 exp.22 dl.2 n.1 size.1228 + 2409 gold.209 hp.17 strength.16 level.3 exp.22 3 + object (2 rations of food) x.0 y.0 type.58 pack.(a:97) + object (+1 ring mail [protection 4] (being worn)) x.0 y.0 type.93 pack.(b:98) + object (A +1,+1 mace (weapon in hand)) x.0 y.0 type.41 pack.(c:99) + object (A +1,+0 short bow) x.0 y.0 type.41 pack.(d:100) + object (25 +0,+0 arrows) x.0 y.0 type.41 pack.(e:101) + object (A scroll titled 'zokkli ta grebot sristael') x.61 y.12 type.63 pack.(f:102) + object (A scroll titled 'val riip') x.42 y.18 type.63 pack.(g:103) + d1000000110000001000000003000000160000000700000003000000000000003a0000000000000002000000000000000000000000000000000000001000000000000000000000000000000000000000000000005d00000000000000010000000100000000000000000000000600000012000000000000000000000000000000000000000000000029000000ffffffff010000000000000001000000010000000000000012000000000000003278340000000000317833000000000029000000ffffffff0100000002000000010000000000000000000000120000000000000031783100000000003178310000000000290000000200000019000000030000000000000000000000000000001e00000000000000317831000000000032783300000000003f00000000000000010000000000000000000000000000000b0000001000000000000000307830000000000030783000000000003f00000000000000010000000800000000000000000000000b000000100000000000000030783000000000003078300000000000 packsize.7 n.396 + (0 319) (1 9) (2 3) (3 3) (6 1) (7 1) (8 1) (11 2) (16 4) (17 1) (18 3) (22 1) (25 1) (30 1) (41 3) (48 8) (49 7) (50 2) (51 2) (52 1) (58 1) (63 2) (93 1) (120 10) (209 1) (255 8) nonz.26 + + extracted $$$gold.209 hp.17 strength.16 level.3 exp.22 dl.3 n.1 size.1228 ca995aa934b5365e9b86d3db97919e3c26ea03ee6e3045bfc9b05a079ab8b130 */ @@ -771,9 +775,9 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); cashout = (uint64_t)P.gold * mult; - if ( funcid == 'H' ) + if ( funcid == 'H' && maxplayers > 1 ) { - if ( (numplayers - rogue_playersalive(tmp,gametxid,maxplayers)) > 1 && (P.dungeonlevel > 1 || P.gold < 10000 || P.level < 20) ) + if ( numplayers != maxplayers || (numplayers - rogue_playersalive(tmp,gametxid,maxplayers)) > 1 && (P.dungeonlevel > 1 || P.gold < 10000 || P.level < 20) ) return(cclib_error(result,"highlander must be a winner or last one standing")); cashout += numplayers * buyin; } From 0b96f2004aae5e7bf491bfc8256dba9345e15758 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 08:01:04 -1100 Subject: [PATCH 0390/1145] Alive/finished status --- src/cc/rogue_rpc.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d48a50b65..25aeca57a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -143,7 +143,7 @@ (0 319) (1 9) (2 3) (3 3) (6 1) (7 1) (8 1) (11 2) (16 4) (17 1) (18 3) (22 1) (25 1) (30 1) (41 3) (48 8) (49 7) (50 2) (51 2) (52 1) (58 1) (63 2) (93 1) (120 10) (209 1) (255 8) nonz.26 extracted $$$gold.209 hp.17 strength.16 level.3 exp.22 dl.3 n.1 size.1228 - ca995aa934b5365e9b86d3db97919e3c26ea03ee6e3045bfc9b05a079ab8b130 + */ CScript rogue_newgameopret(int64_t buyin,int32_t maxplayers) @@ -500,6 +500,9 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet obj.push_back(Pair("slot",(int64_t)vout-2)); if ( (retval= rogue_findbaton(cp,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr,numplayers)) == 0 ) { + if ( CCgettxout(gametxid,2+maxplayers+i,1) == txfee ) + obj.push_back(Pair("status","alive")); + else obj.push_back(Pair("status","finished")); obj.push_back(Pair("baton",batontxid.ToString())); obj.push_back(Pair("batonaddr",destaddr)); obj.push_back(Pair("batonvout",(int64_t)batonvout)); From 47bf729f9caa3fb7a4018cb03a64cb526d2032da Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 08:02:46 -1100 Subject: [PATCH 0391/1145] Fix --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 25aeca57a..aef95c041 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -500,7 +500,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet obj.push_back(Pair("slot",(int64_t)vout-2)); if ( (retval= rogue_findbaton(cp,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr,numplayers)) == 0 ) { - if ( CCgettxout(gametxid,2+maxplayers+i,1) == txfee ) + if ( CCgettxout(gametxid,maxplayers+vout,1) == txfee ) obj.push_back(Pair("status","alive")); else obj.push_back(Pair("status","finished")); obj.push_back(Pair("baton",batontxid.ToString())); From 0166734f1dc78ba284947ac773cea16708d21591 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 08:03:44 -1100 Subject: [PATCH 0392/1145] Three --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index aef95c041..1fb00530c 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -500,7 +500,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet obj.push_back(Pair("slot",(int64_t)vout-2)); if ( (retval= rogue_findbaton(cp,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr,numplayers)) == 0 ) { - if ( CCgettxout(gametxid,maxplayers+vout,1) == txfee ) + if ( CCgettxout(gametxid,maxplayers+vout,1) == 10000 ) obj.push_back(Pair("status","alive")); else obj.push_back(Pair("status","finished")); obj.push_back(Pair("baton",batontxid.ToString())); From 5df7d49d5c3403c588aa0ee4e68386d26a83e39a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 6 Feb 2019 19:08:49 -1100 Subject: [PATCH 0393/1145] Enable ./configure --- src/cc/makerogue | 2 +- src/cc/rogue_rpc.cpp | 9 +++++++-- src/komodo_utils.h | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index f7ee26669..08c86dee8 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,5 +1,5 @@ cd rogue; -#./configure # only need this first time +./configure # only need this first time make; cd .. gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -lncurses #gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1fb00530c..777b02f80 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -116,10 +116,15 @@ // todo: // verify playerdata is usable -// verify keystrokes tx is confirmed +// verify keystrokes tx is in mempool and confirmed +// check that bailout is legal, ie. proper gametxid vin +// verify amulet possession in pack +// display playerdata (user comments?, or fully decode) +// verify playerdata can be used and has same initial level +// prevent running gui mode when keystrokes txid already there //////////////////////// start of CClib interface -//./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey= -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc > /dev/null & +//./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey=03951a6f7967ad784453116bc55cd30c54f91ea8a5b1e9b04d6b29cfd6b395ba6c -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc > /dev/null & // cclib newgame 17 \"[3,10]\" // cclib pending 17 diff --git a/src/komodo_utils.h b/src/komodo_utils.h index f492173a7..f5c92cf84 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1782,6 +1782,7 @@ void komodo_args(char *argv0) ASSETCHAINS_MARMARA = GetArg("-ac_marmara",0); if ( ASSETCHAINS_CC != 0 ) { + ASSETCHAINS_CCLIB = GetArg("-ac_cclib",""); Split(GetArg("-ac_ccenable",""), ccenables, 0); for (i=nonz=0; i<0x100; i++) { @@ -1805,7 +1806,6 @@ void komodo_args(char *argv0) ASSETCHAINS_CCDISABLES[ccenables[i] & 0xff] = 0; } } - ASSETCHAINS_CCLIB = GetArg("-ac_cclib",""); /*if ( ASSETCHAINS_CCLIB.size() > 0 ) { for (i=first; i<=last; i++) From f40a353e088d1191265a7bc722e6528c660eb3d0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 7 Feb 2019 07:27:00 -1100 Subject: [PATCH 0394/1145] >> keystrokes.log --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 62a8a2e1c..c52002447 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -148,7 +148,7 @@ void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) // use seed to l for (i=0; i> keystrokes.log",Gametxidstr,hexstr); if ( system(cmd) != 0 ) fprintf(stderr,"error issuing (%s)\n",cmd); } From e5198d57b2ca8a68ca67c3cde35c255a9ba0ed55 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 7 Feb 2019 07:31:00 -1100 Subject: [PATCH 0395/1145] -print --- src/cc/CCtx.cpp | 4 ++-- src/cc/rogue_rpc.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index b0cea19e1..93bed32f7 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -208,7 +208,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran // check if this is spending from 1of2 cc coins addr: else if (strcmp(cp->coins1of2addr, destaddr) == 0) { - fprintf(stderr,"FinalizeCCTx() matched %s unspendable1of2!\n",cp->coins1of2addr); + //fprintf(stderr,"FinalizeCCTx() matched %s unspendable1of2!\n",cp->coins1of2addr); privkey = cp->coins1of2priv;//myprivkey; if (othercond1of2 == 0) othercond1of2 = MakeCCcond1of2(cp->evalcode, cp->coins1of2pk[0], cp->coins1of2pk[1]); @@ -216,7 +216,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran } else if ( strcmp(CC1of2CCaddr,destaddr) == 0 ) { - fprintf(stderr,"FinalizeCCTx() matched %s CC1of2CCaddr!\n",CC1of2CCaddr); + //fprintf(stderr,"FinalizeCCTx() matched %s CC1of2CCaddr!\n",CC1of2CCaddr); privkey = unspendablepriv; if (condCC2 == 0) condCC2 = MakeCCcond1of2(cp->evalcode,unspendablepk,unspendablepk); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 777b02f80..1c149e9b1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -483,7 +483,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &n return(-4); else batonht = pindex->GetHeight(); batonvalue = batontx.vout[0].nValue; - printf("keystrokes[%d]\n",numkeys); + //printf("keystrokes[%d]\n",numkeys); return(0); } } From 35daec70b12fddc51aa752f9ec5539b31d32085d Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 8 Feb 2019 01:20:00 -1100 Subject: [PATCH 0396/1145] ReacceptWalletTransactions don't remove from wallet if initial block download --- src/cc/rogue_rpc.cpp | 1 + src/wallet/wallet.cpp | 7 +++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1c149e9b1..a7702d244 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -116,6 +116,7 @@ // todo: // verify playerdata is usable +// detect playerdeath/quit to prevent illegal keystrokes vector // verify keystrokes tx is in mempool and confirmed // check that bailout is legal, ie. proper gametxid vin // verify amulet possession in pack diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index d171812c4..47b6e6df4 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -2810,9 +2810,12 @@ void CWallet::ReacceptWalletTransactions() } } } - for (auto hash : vwtxh) + if ( IsInitialBlockDownload() == 0 ) { - EraseFromWallet(hash); + for (auto hash : vwtxh) + { + EraseFromWallet(hash); + } } } From 54c02fe3abcdf89c369e3d26714b512f8c5d30b2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 8 Feb 2019 01:59:53 -1100 Subject: [PATCH 0397/1145] +print --- src/cc/rogue_rpc.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index a7702d244..20c2a077e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -129,12 +129,12 @@ // cclib newgame 17 \"[3,10]\" // cclib pending 17 -// cclib gameinfo 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22]\" -// cclib register 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22]\" +// cclib gameinfo 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22]\" +// cclib register 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22]\" // ./rogue gui -> creates keystroke files -// cclib register 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22,%22%22]\" -// cclib keystrokes 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22,%22deadbeef%22]\" -// cclib bailout 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22]\" +// cclib register 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22,%22eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd%22]\" +// cclib keystrokes 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22deadbeef%22]\" +// cclib bailout 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22]\" // eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd /* 2409 gold.209 hp.17 strength.16 level.3 exp.22 3 @@ -381,6 +381,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub { GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); script = (uint8_t *)vopret.data(); + fprintf(stderr,"player data [%d] [%c]\n",script[0],script[1]); if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'Q' || script[1] == 'S') ) { memcpy(&highlander,script+2,sizeof(highlander)); From 652f1dc199b3d2d89bf6e788b098339ab35c18bd Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 8 Feb 2019 02:09:22 -1100 Subject: [PATCH 0398/1145] Skip rev --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 20c2a077e..08a5351d7 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -385,7 +385,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'Q' || script[1] == 'S') ) { memcpy(&highlander,script+2,sizeof(highlander)); - highlander = revuint256(highlander); + //highlander = revuint256(highlander); fprintf(stderr,"got highlander.%s\n",highlander.ToString().c_str()); if ( rogue_iterateplayer(highlander,playertxid) == 0 ) { From 4fa5d896590d4ab3e63cb19a1f1934b175d008c6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 8 Feb 2019 02:23:39 -1100 Subject: [PATCH 0399/1145] Test --- src/cc/rogue_rpc.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 08a5351d7..53288ffe0 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -386,8 +386,10 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub { memcpy(&highlander,script+2,sizeof(highlander)); //highlander = revuint256(highlander); - fprintf(stderr,"got highlander.%s\n",highlander.ToString().c_str()); - if ( rogue_iterateplayer(highlander,playertxid) == 0 ) + fprintf(stderr,"got vin.%s \n",playertx.vin[1].prevout.hash.ToString().c_str()); + // verify highlander is a valid gametxid, verify playertxid is linked to it + //if ( rogue_iterateplayer(highlander,playertx.vin[1].prevout.n,playertxid) == 0 ) + if ( playertx.vin[1].prevout.hash == highlander ) { if ( GetTransaction(highlander,highlandertx,hashBlock,false) != 0 && (numvouts= highlandertx.vout.size()) > 0 ) { From 97bc919d2fabffe0623d29af352dae82c4be843a Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 8 Feb 2019 02:26:11 -1100 Subject: [PATCH 0400/1145] Test --- src/cc/rogue_rpc.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 53288ffe0..5dbf3d860 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -381,7 +381,6 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub { GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); script = (uint8_t *)vopret.data(); - fprintf(stderr,"player data [%d] [%c]\n",script[0],script[1]); if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'Q' || script[1] == 'S') ) { memcpy(&highlander,script+2,sizeof(highlander)); @@ -389,7 +388,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub fprintf(stderr,"got vin.%s \n",playertx.vin[1].prevout.hash.ToString().c_str()); // verify highlander is a valid gametxid, verify playertxid is linked to it //if ( rogue_iterateplayer(highlander,playertx.vin[1].prevout.n,playertxid) == 0 ) - if ( playertx.vin[1].prevout.hash == highlander ) + //if ( playertx.vin[1].prevout.hash == highlander ) { if ( GetTransaction(highlander,highlandertx,hashBlock,false) != 0 && (numvouts= highlandertx.vout.size()) > 0 ) { From c71dc476b552f01a95552645a7387b5c707d9524 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 8 Feb 2019 02:26:41 -1100 Subject: [PATCH 0401/1145] - --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5dbf3d860..13128d3c3 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -399,7 +399,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub else return(-3); } } - } else return(-2); + } //else return(-2); } } return(-1); From edd1b42590e98e96246e947b30894f69de45e594 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 8 Feb 2019 02:29:46 -1100 Subject: [PATCH 0402/1145] Test --- src/cc/rogue_rpc.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 13128d3c3..342379036 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -390,13 +390,13 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub //if ( rogue_iterateplayer(highlander,playertx.vin[1].prevout.n,playertxid) == 0 ) //if ( playertx.vin[1].prevout.hash == highlander ) { - if ( GetTransaction(highlander,highlandertx,hashBlock,false) != 0 && (numvouts= highlandertx.vout.size()) > 0 ) + //if ( GetTransaction(highlander,highlandertx,hashBlock,false) != 0 && (numvouts= highlandertx.vout.size()) > 0 ) { - if ( (f= rogue_highlanderopretdecode(origplayergame,pk,playerdata,highlandertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) + if ( (f= rogue_highlanderopretdecode(origplayergame,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { - if ( highlandertx.vin[0].prevout.hash == origplayergame && highlandertx.vin[0].prevout.n == 0 && rogue_isvalidgame(cp,gametx,buyin,maxplayers,origplayergame) == 0 && maxplayers > 1 ) + //if ( highlandertx.vin[0].prevout.hash == origplayergame && highlandertx.vin[0].prevout.n == 0 && rogue_isvalidgame(cp,gametx,buyin,maxplayers,origplayergame) == 0 && maxplayers > 1 ) return(0); - else return(-3); + //else return(-3); } } } //else return(-2); From 411df1eb9f73906148289603c182279649cd32f6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 8 Feb 2019 02:35:00 -1100 Subject: [PATCH 0403/1145] test --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 342379036..5ca5a069a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -132,7 +132,7 @@ // cclib gameinfo 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22]\" // cclib register 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22]\" // ./rogue gui -> creates keystroke files -// cclib register 17 \"[%22e7d75f0b2bf0716ad0df87ee331bf52b41e0823e126654c7ec8bac5a15f6d869%22,%22eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd%22]\" +// cclib register 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd%22]\" // cclib keystrokes 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22deadbeef%22]\" // cclib bailout 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22]\" // eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd @@ -639,7 +639,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) gametxid = juint256(jitem(params,0)); if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,gametxid) == 0 ) { - if ( n > 1 && maxplayers > 1 ) + if ( n > 1 ) { playertxid = juint256(jitem(params,1)); if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) From be6279d62dec354a3105ec4cab60c995cfc82047 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 03:44:03 -1100 Subject: [PATCH 0404/1145] ASSETCHAINS_BLOCKTIME --- src/chainparams.cpp | 5 +++++ src/komodo_defs.h | 2 +- src/komodo_globals.h | 2 +- src/komodo_utils.h | 5 ++++- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 5c9efb276..177d7604f 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -276,6 +276,11 @@ void *chainparams_commandline(void *ptr) //fprintf(stderr,">>>>>>>> port.%u\n",ASSETCHAINS_P2PPORT); if ( ASSETCHAINS_SYMBOL[0] != 0 ) { + if ( ASSETCHAINS_BLOCKTIME != 60 ) + { + consensus.nMaxFutureBlockTime = 7 * ASSETCHAINS_BLOCKTIME; // 7 blocks + consensus.nPowTargetSpacing = ASSETCHAINS_BLOCKTIME; + } mainParams.SetDefaultPort(ASSETCHAINS_P2PPORT); if ( ASSETCHAINS_RPCPORT == 0 ) ASSETCHAINS_RPCPORT = ASSETCHAINS_P2PPORT + 1; diff --git a/src/komodo_defs.h b/src/komodo_defs.h index 0ea97d6db..9f33c6036 100644 --- a/src/komodo_defs.h +++ b/src/komodo_defs.h @@ -38,7 +38,7 @@ extern uint8_t ASSETCHAINS_TXPOW,ASSETCHAINS_PUBLIC; int32_t MAX_BLOCK_SIZE(int32_t height); extern char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; extern uint16_t ASSETCHAINS_P2PPORT,ASSETCHAINS_RPCPORT; -extern uint32_t ASSETCHAIN_INIT, ASSETCHAINS_MAGIC; +extern uint32_t ASSETCHAIN_INIT, ASSETCHAINS_MAGIC,ASSETCHAINS_BLOCKTIME; extern int32_t VERUS_BLOCK_POSUNITS, ASSETCHAINS_LWMAPOS, ASSETCHAINS_SAPLING, ASSETCHAINS_OVERWINTER; extern uint64_t ASSETCHAINS_SUPPLY; diff --git a/src/komodo_globals.h b/src/komodo_globals.h index c85c68451..8215a6b6e 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -69,7 +69,7 @@ int64_t MAX_MONEY = 200000000 * 100000000LL; uint64_t ASSETCHAINS_TIMELOCKGTE = _ASSETCHAINS_TIMELOCKOFF; uint64_t ASSETCHAINS_TIMEUNLOCKFROM = 0, ASSETCHAINS_TIMEUNLOCKTO = 0; -uint32_t ASSETCHAINS_LASTERA = 1; +uint32_t ASSETCHAINS_BLOCKTIME = 60,ASSETCHAINS_LASTERA = 1; uint64_t ASSETCHAINS_ENDSUBSIDY[ASSETCHAINS_MAX_ERAS],ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS],ASSETCHAINS_HALVING[ASSETCHAINS_MAX_ERAS],ASSETCHAINS_DECAY[ASSETCHAINS_MAX_ERAS]; uint8_t ASSETCHAINS_CCDISABLES[256]; diff --git a/src/komodo_utils.h b/src/komodo_utils.h index f5c92cf84..469cbd21b 100644 --- a/src/komodo_utils.h +++ b/src/komodo_utils.h @@ -1707,6 +1707,7 @@ void komodo_args(char *argv0) WITNESS_CACHE_SIZE = MAX_REORG_LENGTH+10; ASSETCHAINS_CC = GetArg("-ac_cc",0); KOMODO_CCACTIVATE = GetArg("-ac_ccactivate",0); + ASSETCHAINS_BLOCKTIME = GetArg("-ac_blocktime",60); ASSETCHAINS_PUBLIC = GetArg("-ac_public",0); ASSETCHAINS_PRIVATE = GetArg("-ac_private",0); if ( (KOMODO_REWIND= GetArg("-rewind",0)) != 0 ) @@ -1899,7 +1900,7 @@ void komodo_args(char *argv0) fprintf(stderr,"-ac_script and -ac_marmara are mutually exclusive\n"); exit(0); } - if ( ASSETCHAINS_ENDSUBSIDY[0] != 0 || ASSETCHAINS_REWARD[0] != 0 || ASSETCHAINS_HALVING[0] != 0 || ASSETCHAINS_DECAY[0] != 0 || ASSETCHAINS_COMMISSION != 0 || ASSETCHAINS_PUBLIC != 0 || ASSETCHAINS_PRIVATE != 0 || ASSETCHAINS_TXPOW != 0 || ASSETCHAINS_FOUNDERS != 0 || ASSETCHAINS_SCRIPTPUB.size() > 1 || ASSETCHAINS_SELFIMPORT.size() > 0 || ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 || ASSETCHAINS_TIMELOCKGTE != _ASSETCHAINS_TIMELOCKOFF|| ASSETCHAINS_ALGO != ASSETCHAINS_EQUIHASH || ASSETCHAINS_LWMAPOS != 0 || ASSETCHAINS_LASTERA > 0 || ASSETCHAINS_BEAMPORT != 0 || ASSETCHAINS_CODAPORT != 0 || ASSETCHAINS_MARMARA != 0 || nonz > 0 || ASSETCHAINS_CCLIB.size() > 0 ) + if ( ASSETCHAINS_ENDSUBSIDY[0] != 0 || ASSETCHAINS_REWARD[0] != 0 || ASSETCHAINS_HALVING[0] != 0 || ASSETCHAINS_DECAY[0] != 0 || ASSETCHAINS_COMMISSION != 0 || ASSETCHAINS_PUBLIC != 0 || ASSETCHAINS_PRIVATE != 0 || ASSETCHAINS_TXPOW != 0 || ASSETCHAINS_FOUNDERS != 0 || ASSETCHAINS_SCRIPTPUB.size() > 1 || ASSETCHAINS_SELFIMPORT.size() > 0 || ASSETCHAINS_OVERRIDE_PUBKEY33[0] != 0 || ASSETCHAINS_TIMELOCKGTE != _ASSETCHAINS_TIMELOCKOFF|| ASSETCHAINS_ALGO != ASSETCHAINS_EQUIHASH || ASSETCHAINS_LWMAPOS != 0 || ASSETCHAINS_LASTERA > 0 || ASSETCHAINS_BEAMPORT != 0 || ASSETCHAINS_CODAPORT != 0 || ASSETCHAINS_MARMARA != 0 || nonz > 0 || ASSETCHAINS_CCLIB.size() > 0 || ASSETCHAINS_BLOCKTIME != 60 ) { fprintf(stderr,"perc %.4f%% ac_pub=[%02x%02x%02x...] acsize.%d\n",dstr(ASSETCHAINS_COMMISSION)*100,ASSETCHAINS_OVERRIDE_PUBKEY33[0],ASSETCHAINS_OVERRIDE_PUBKEY33[1],ASSETCHAINS_OVERRIDE_PUBKEY33[2],(int32_t)ASSETCHAINS_SCRIPTPUB.size()); extraptr = extrabuf; @@ -1989,6 +1990,8 @@ void komodo_args(char *argv0) } fprintf(stderr," <- CCLIB name\n"); } + if ( ASSETCHAINS_BLOCKTIME != 60 ) + extralen += iguana_rwnum(1,&extraptr[extralen],sizeof(ASSETCHAINS_BLOCKTIME),(void *)&ASSETCHAINS_BLOCKTIME); } addn = GetArg("-seednode",""); From cec11785df0b14d7404e5fa9cc3a66efa48dcec7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 03:50:42 -1100 Subject: [PATCH 0405/1145] consensusParams --- src/chainparams.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 177d7604f..785ff412c 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -278,8 +278,8 @@ void *chainparams_commandline(void *ptr) { if ( ASSETCHAINS_BLOCKTIME != 60 ) { - consensus.nMaxFutureBlockTime = 7 * ASSETCHAINS_BLOCKTIME; // 7 blocks - consensus.nPowTargetSpacing = ASSETCHAINS_BLOCKTIME; + consensusParams.nMaxFutureBlockTime = 7 * ASSETCHAINS_BLOCKTIME; // 7 blocks + consensusParams.nPowTargetSpacing = ASSETCHAINS_BLOCKTIME; } mainParams.SetDefaultPort(ASSETCHAINS_P2PPORT); if ( ASSETCHAINS_RPCPORT == 0 ) From d103970fedbce5210809f4719b3e268cbdd9ad04 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 03:51:36 -1100 Subject: [PATCH 0406/1145] mainParams --- src/chainparams.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 785ff412c..655dc8e87 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -278,8 +278,8 @@ void *chainparams_commandline(void *ptr) { if ( ASSETCHAINS_BLOCKTIME != 60 ) { - consensusParams.nMaxFutureBlockTime = 7 * ASSETCHAINS_BLOCKTIME; // 7 blocks - consensusParams.nPowTargetSpacing = ASSETCHAINS_BLOCKTIME; + mainParams.nMaxFutureBlockTime = 7 * ASSETCHAINS_BLOCKTIME; // 7 blocks + mainParams.nPowTargetSpacing = ASSETCHAINS_BLOCKTIME; } mainParams.SetDefaultPort(ASSETCHAINS_P2PPORT); if ( ASSETCHAINS_RPCPORT == 0 ) From eae8207fe870adea099f9e1ecb31ef2fa3d6fedb Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 03:56:03 -1100 Subject: [PATCH 0407/1145] mainParams.consensus. --- src/chainparams.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 655dc8e87..4c307a6b8 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -278,8 +278,8 @@ void *chainparams_commandline(void *ptr) { if ( ASSETCHAINS_BLOCKTIME != 60 ) { - mainParams.nMaxFutureBlockTime = 7 * ASSETCHAINS_BLOCKTIME; // 7 blocks - mainParams.nPowTargetSpacing = ASSETCHAINS_BLOCKTIME; + mainParams.consensus.nMaxFutureBlockTime = 7 * ASSETCHAINS_BLOCKTIME; // 7 blocks + mainParams.consensus.nPowTargetSpacing = ASSETCHAINS_BLOCKTIME; } mainParams.SetDefaultPort(ASSETCHAINS_P2PPORT); if ( ASSETCHAINS_RPCPORT == 0 ) From a68d3a00a2394e007b5bfdcc8305ae10ecc54f1a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 04:01:39 -1100 Subject: [PATCH 0408/1145] Move to chainparams.cpp --- src/chainparams.cpp | 2 +- src/komodo_globals.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 4c307a6b8..a47c7fea3 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -91,7 +91,7 @@ static CBlock CreateGenesisBlock(uint32_t nTime, const uint256& nNonce, const st */ void *chainparams_commandline(void *ptr); #include "komodo_defs.h" - +uint32_t ASSETCHAINS_BLOCKTIME = 60; const arith_uint256 maxUint = UintToArith256(uint256S("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")); diff --git a/src/komodo_globals.h b/src/komodo_globals.h index 8215a6b6e..c85c68451 100644 --- a/src/komodo_globals.h +++ b/src/komodo_globals.h @@ -69,7 +69,7 @@ int64_t MAX_MONEY = 200000000 * 100000000LL; uint64_t ASSETCHAINS_TIMELOCKGTE = _ASSETCHAINS_TIMELOCKOFF; uint64_t ASSETCHAINS_TIMEUNLOCKFROM = 0, ASSETCHAINS_TIMEUNLOCKTO = 0; -uint32_t ASSETCHAINS_BLOCKTIME = 60,ASSETCHAINS_LASTERA = 1; +uint32_t ASSETCHAINS_LASTERA = 1; uint64_t ASSETCHAINS_ENDSUBSIDY[ASSETCHAINS_MAX_ERAS],ASSETCHAINS_REWARD[ASSETCHAINS_MAX_ERAS],ASSETCHAINS_HALVING[ASSETCHAINS_MAX_ERAS],ASSETCHAINS_DECAY[ASSETCHAINS_MAX_ERAS]; uint8_t ASSETCHAINS_CCDISABLES[256]; From 1f5b5b739458e43bfce8b229c35cbf14575b2a27 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 20:25:52 -1100 Subject: [PATCH 0409/1145] Player data extraction --- src/cc/rogue_rpc.cpp | 101 +++++++++++++++++++++++-------------------- 1 file changed, 55 insertions(+), 46 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5ca5a069a..18e312aa5 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -384,7 +384,6 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'Q' || script[1] == 'S') ) { memcpy(&highlander,script+2,sizeof(highlander)); - //highlander = revuint256(highlander); fprintf(stderr,"got vin.%s \n",playertx.vin[1].prevout.hash.ToString().c_str()); // verify highlander is a valid gametxid, verify playertxid is linked to it //if ( rogue_iterateplayer(highlander,playertx.vin[1].prevout.n,playertxid) == 0 ) @@ -392,7 +391,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub { //if ( GetTransaction(highlander,highlandertx,hashBlock,false) != 0 && (numvouts= highlandertx.vout.size()) > 0 ) { - if ( (f= rogue_highlanderopretdecode(origplayergame,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) + if ( (f= rogue_highlanderopretdecode(origplayergame,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' || f == 'S' ) { //if ( highlandertx.vin[0].prevout.hash == origplayergame && highlandertx.vin[0].prevout.n == 0 && rogue_isvalidgame(cp,gametx,buyin,maxplayers,origplayergame) == 0 && maxplayers > 1 ) return(0); @@ -439,58 +438,67 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &n } if ( matches == 1 ) { - numvouts = matchtx.vout.size(); - //fprintf(stderr,"matches.%d numvouts.%d\n",matches,numvouts); - if ( rogue_registeropretdecode(txid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) + if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+2) < 0 ) { - if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) == 0 ) + numvouts = matchtx.vout.size(); + //fprintf(stderr,"matches.%d numvouts.%d\n",matches,numvouts); + if ( rogue_registeropretdecode(txid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) { - txid = matchtx.GetHash(); - //fprintf(stderr,"scan forward playertxid.%s spenttxid.%s\n",playertxid.GetHex().c_str(),txid.GetHex().c_str()); - while ( CCgettxout(txid,0,1) < 0 ) + fprintf(stderr,"playertxid.%s\n",playertxid.ToString().c_str()); + if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) == 0 ) { - spenttxid = zeroid; - spentvini = -1; - if ( (spentvini= myIsutxo_spent(spenttxid,txid,0)) >= 0 ) - txid = spenttxid; - else if ( myIsutxo_spentinmempool(spenttxid,spentvini,txid,0) == 0 || spenttxid == zeroid ) + txid = matchtx.GetHash(); + //fprintf(stderr,"scan forward playertxid.%s spenttxid.%s\n",playertxid.GetHex().c_str(),txid.GetHex().c_str()); + while ( CCgettxout(txid,0,1) < 0 ) { - fprintf(stderr,"mempool tracking error %s/v0\n",txid.ToString().c_str()); - return(-2); - } - if ( spentvini != 0 ) - return(-3); - if ( keystrokesp != 0 && GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() == 2 ) - { - uint256 g,b; CPubKey p; std::vector k; - if ( rogue_keystrokesopretdecode(g,b,p,k,spenttx.vout[1].scriptPubKey) == 'K' ) + spenttxid = zeroid; + spentvini = -1; + if ( (spentvini= myIsutxo_spent(spenttxid,txid,0)) >= 0 ) + txid = spenttxid; + else if ( myIsutxo_spentinmempool(spenttxid,spentvini,txid,0) == 0 || spenttxid == zeroid ) { - keystrokes = (char *)realloc(keystrokes,numkeys + (int32_t)k.size()); - for (i=0; i k; + if ( rogue_keystrokesopretdecode(g,b,p,k,spenttx.vout[1].scriptPubKey) == 'K' ) + { + keystrokes = (char *)realloc(keystrokes,numkeys + (int32_t)k.size()); + for (i=0; i 0 ) + { + if ( hashBlock == zeroid ) + batonht = komodo_nextheight(); + else if ( (pindex= komodo_blockindex(hashBlock)) == 0 ) + return(-4); + else batonht = pindex->GetHeight(); + batonvalue = batontx.vout[0].nValue; + //printf("keystrokes[%d]\n",numkeys); + return(0); + } } - //fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); - batontxid = txid; - batonvout = 0; // not vini - // how to detect timeout, bailedout, highlander - hashBlock = zeroid; - if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 0 ) - { - if ( hashBlock == zeroid ) - batonht = komodo_nextheight(); - else if ( (pindex= komodo_blockindex(hashBlock)) == 0 ) - return(-4); - else batonht = pindex->GetHeight(); - batonvalue = batontx.vout[0].nValue; - //printf("keystrokes[%d]\n",numkeys); - return(0); - } - } - } else fprintf(stderr,"findbaton opret error\n"); + } else fprintf(stderr,"findbaton opret error\n"); + } + else + { + fprintf(stderr,"already played\n"); + return(-5); + } } return(-1); } @@ -775,6 +783,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param free(keystrokes); mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); mtx.vin.push_back(CTxIn(gametxid,2+maxplayers+regslot,CScript())); + mtx.vout.push_back(MakeCC1vout(cp->evalcode,1,mypk)); mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,mypk)); if ( num > 0 ) { From defb298184ff3c481d3d52b7f2662de775e69572 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 21:34:30 -1100 Subject: [PATCH 0410/1145] Players rpc call --- src/cc/cclib.cpp | 4 +++ src/cc/rogue/state.c | 9 +++++ src/cc/rogue_rpc.cpp | 85 ++++++++++++++++++++++++++++++++++---------- 3 files changed, 79 insertions(+), 19 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index dd0aef00f..78332c576 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -61,6 +61,7 @@ CClib_methods[] = { (char *)"rogue", (char *)"bailout", (char *)"baton finalhash", 2, 2, 'Q', EVAL_ROGUE }, { (char *)"rogue", (char *)"highlander", (char *)"baton finalhash", 2, 2, 'H', EVAL_ROGUE }, { (char *)"rogue", (char *)"playerinfo", (char *)"playertxid", 1, 1, 'I', EVAL_ROGUE }, + { (char *)"rogue", (char *)"players", (char *)"playertxid", 1, 1, 'D', EVAL_ROGUE }, #else { (char *)"sudoku", (char *)"gen", (char *)"", 0, 0, 'G', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, @@ -86,6 +87,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); #else bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); @@ -117,6 +119,8 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) return(rogue_highlander(txfee,cp,params)); else if ( strcmp(method,"playerinfo") == 0 ) return(rogue_playerinfo(txfee,cp,params)); + else if ( strcmp(method,"players") == 0 ) + return(rogue_players(txfee,cp,params)); else { result.push_back(Pair("result","error")); diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 226392e83..60d8648bd 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1349,6 +1349,15 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item) o->_o._o_arm = item->arm; o->_o._o_flags = item->flags; o->_o._o_group = item->group; + o->o_flags |= ISKNOW; +} + +void rogue_packitemstr(*packitemstr,struct rogue_packitem *item); +{ + THING *obj = new_item(); + rogue_restoreobject(obj,item); + strcpy(packitemstr,inv_name(o,FALSE)); + free(obj); } int32_t packsave(struct rogue_packitem *item,int32_t type,int32_t launch,char *damage,int32_t damagesize,char *hurldmg,int32_t hurlsize,int32_t count,int32_t which,int32_t hplus,int32_t dplus,int32_t arm,int32_t flags,int32_t group) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 18e312aa5..cff2aafc0 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -152,6 +152,22 @@ */ + +#define MAXPACK 23 +struct rogue_packitem +{ + int32_t type,launch,count,which,hplus,dplus,arm,flags,group; + char damage[8],hurldmg[8]; +}; +struct rogue_player +{ + int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; + struct rogue_packitem roguepack[MAXPACK]; +}; +int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player); +#define ROGUE_DECLARED_PACK +void rogue_packitemstr(*packitemstr,struct rogue_packitem *item); + CScript rogue_newgameopret(int64_t buyin,int32_t maxplayers) { CScript opret; uint8_t evalcode = EVAL_ROGUE; @@ -185,7 +201,7 @@ uint8_t rogue_highlanderopretdecode(uint256 &gametxid,CPubKey &pk,std::vector vopret; uint8_t *script,e,f; GetOpReturnData(scriptPubKey,vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q' || f == 'S') ) { return(f); } @@ -346,7 +362,26 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,CTransaction &tx,int64_t &b UniValue rogue_playerobj(UniValue &obj,std::vector playerdata) { - obj.push_back(Pair("raw","")); + int32_t i; struct rogue_player P; char packitemstr[512]; UniValue a(UniValue::VARR); + memset(&P,0,sizeof(P)); + if ( playerdata.size() > 0 ) + { + for (i=0; i 0 ) { UniValue pobj(UniValue::VOBJ); - obj.push_back(Pair("rogue",rogue_playerobj(pobj,playerdata))); + obj.push_back(Pair("player",rogue_playerobj(pobj,playerdata))); } } else fprintf(stderr,"findbaton err.%d\n",retval); } @@ -619,7 +654,7 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param playertxid = juint256(jitem(params,0)); if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"invalid playerdata")); - result.push_back(Pair("rogue",rogue_playerobj(pobj,playerdata))); + result.push_back(Pair("player",rogue_playerobj(pobj,playerdata))); } else return(cclib_error(result,"no playertxid")); return(result); } else return(cclib_error(result,"couldnt reparse params")); @@ -712,20 +747,6 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"couldnt reparse params")); } -#define MAXPACK 23 -struct rogue_packitem -{ - int32_t type,launch,count,which,hplus,dplus,arm,flags,group; - char damage[8],hurldmg[8]; -}; -struct rogue_player -{ - int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; - struct rogue_packitem roguepack[MAXPACK]; -}; -int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player); -#define ROGUE_DECLARED_PACK - UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params,char *method) { //vin0 -> highlander vout from creategame TCBOO @@ -774,13 +795,15 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue obj; struct rogue_player P; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); fprintf(stderr,"found baton %s numkeys.%d seed.%llu\n",batontxid.ToString().c_str(),numkeys,(long long)seed); + memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { for (i=0; ievalcode,1,mypk)); @@ -888,3 +911,27 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("numpending",a.size())); return(result); } + +UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ),a(UniValue::VARR); int64_t buyin; uint256 gametxid,txid,hashBlock; CTransaction playertx,tx; int32_t maxplayers,vout,numvouts; std::vector playerdata; CPubKey roguepk,mypk,pk; char coinaddr[64]; + std::vector > unspentOutputs; + roguepk = GetUnspendable(cp,0); + GetCCaddress(cp,coinaddr,mypk); + SetCCunspents(unspentOutputs,coinaddr); + for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) + { + txid = it->first.txhash; + vout = (int32_t)it->first.index; + //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); + if ( it->second.satoshis != 1 || vout != 0 ) + continue; + if ( rogue_playerdata(cp,gametxid,pk,playerdata,playertxid) == 0 && pk == mypk ) + a.push_back(Pair("player",rogue_playerobj(pobj,playerdata))); + } + result.push_back(Pair("result","success")); + rogue_univalue(result,"players",-1,-1); + result.push_back(Pair("players",a)); + result.push_back(Pair("numpending",a.size())); + return(result); +} From 7c68ae4363df1c1a39165ae850402bd57b2208a0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 21:35:43 -1100 Subject: [PATCH 0411/1145] Char --- src/cc/rogue/state.c | 2 +- src/cc/rogue_rpc.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 60d8648bd..777981ae3 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1352,7 +1352,7 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item) o->o_flags |= ISKNOW; } -void rogue_packitemstr(*packitemstr,struct rogue_packitem *item); +void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item); { THING *obj = new_item(); rogue_restoreobject(obj,item); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index cff2aafc0..e51c47442 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -166,7 +166,7 @@ struct rogue_player }; int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player); #define ROGUE_DECLARED_PACK -void rogue_packitemstr(*packitemstr,struct rogue_packitem *item); +void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item); CScript rogue_newgameopret(int64_t buyin,int32_t maxplayers) { From 6584d3c4773b5b5ab5358a3b463b803326870457 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 21:36:24 -1100 Subject: [PATCH 0412/1145] - ; --- src/cc/rogue/state.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 777981ae3..861aceadd 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1352,7 +1352,7 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item) o->o_flags |= ISKNOW; } -void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item); +void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) { THING *obj = new_item(); rogue_restoreobject(obj,item); From dbb7d7f6e7354c063b56fe523ebd5c0a3bffea57 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 21:38:43 -1100 Subject: [PATCH 0413/1145] syntax --- src/cc/rogue/state.c | 2 +- src/cc/rogue_rpc.cpp | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 861aceadd..20288f59a 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1356,7 +1356,7 @@ void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) { THING *obj = new_item(); rogue_restoreobject(obj,item); - strcpy(packitemstr,inv_name(o,FALSE)); + strcpy(packitemstr,inv_name(obj,FALSE)); free(obj); } diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e51c47442..18be911f8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -926,8 +926,11 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( it->second.satoshis != 1 || vout != 0 ) continue; - if ( rogue_playerdata(cp,gametxid,pk,playerdata,playertxid) == 0 && pk == mypk ) - a.push_back(Pair("player",rogue_playerobj(pobj,playerdata))); + if ( rogue_playerdata(cp,gametxid,pk,playerdata,txid) == 0 && pk == mypk ) + { + UniValue obj(UniValue::VOBJ); + a.push_back(Pair("player",rogue_playerobj(obj,playerdata))); + } } result.push_back(Pair("result","success")); rogue_univalue(result,"players",-1,-1); From cb5f7eaaa1d68577b5cf81c480425f2d01e878bf Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 21:55:50 -1100 Subject: [PATCH 0414/1145] Auto broadcast rogue rpc tx --- src/cc/CCinclude.h | 1 + src/cc/rogue_rpc.cpp | 39 +++++++++++++++++++++------------------ src/komodo_bitcoind.h | 11 +++++++++++ 3 files changed, 33 insertions(+), 18 deletions(-) diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index bc5ed20ed..948a5c1ae 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -136,6 +136,7 @@ UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params); UniValue CClib_info(struct CCcontract_info *cp); CBlockIndex *komodo_blockindex(uint256 hash); CBlockIndex *komodo_chainactive(int32_t height); +int32_t komodo_blockheight(uint256 hash); static const uint256 zeroid; static uint256 ignoretxid; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 18be911f8..c8af82062 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -129,8 +129,8 @@ // cclib newgame 17 \"[3,10]\" // cclib pending 17 -// cclib gameinfo 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22]\" -// cclib register 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22]\" +// cclib gameinfo 17 \"[%22d8bc6445bfec15ea761c8e91e26d162f47856dba1fc8c8ec508cac83b95d7433%22]\" +// cclib register 17 \"[%22d8bc6445bfec15ea761c8e91e26d162f47856dba1fc8c8ec508cac83b95d7433%22]\" // ./rogue gui -> creates keystroke files // cclib register 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd%22]\" // cclib keystrokes 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22deadbeef%22]\" @@ -331,12 +331,13 @@ uint64_t rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 return(seed); } -int32_t rogue_isvalidgame(struct CCcontract_info *cp,CTransaction &tx,int64_t &buyin,int32_t &maxplayers,uint256 txid) +int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransaction &tx,int64_t &buyin,int32_t &maxplayers,uint256 txid) { uint256 hashBlock; int32_t i,numvouts; char coinaddr[64]; CPubKey roguepk; uint64_t txfee = 10000; buyin = maxplayers = 0; if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) { + gameheight = komodo_blockheight(hashBlock); if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,0) == 0 ) { if ( rogue_newgameopreturndecode(buyin,maxplayers,tx.vout[numvouts-1].scriptPubKey) == 'G' ) @@ -635,7 +636,7 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( (change= inputsum - required) >= txfee ) mtx.vout.push_back(MakeCC1vout(cp->evalcode,change,roguepk)); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_newgameopret(buyin,maxplayers)); - return(rogue_rawtxresult(result,rawtx,0)); + return(rogue_rawtxresult(result,rawtx,1)); } else return(cclib_error(result,"illegal maxplayers")); return(result); @@ -668,7 +669,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vin3+ -> buyin // vout0 -> keystrokes/completion baton CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t maxplayers,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx; std::vector playerdata; std::string rawtx; bits256 t; + UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t maxplayers,gameheight,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx; std::vector playerdata; std::string rawtx; bits256 t; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -680,7 +681,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( n > 0 ) { gametxid = juint256(jitem(params,0)); - if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,gametxid) == 0 ) + if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid) == 0 ) { if ( n > 1 ) { @@ -702,7 +703,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_registeropret(gametxid,playertxid)); - return(rogue_rawtxresult(result,rawtx,0)); + return(rogue_rawtxresult(result,rawtx,1)); } else return(cclib_error(result,"invalid gametxid")); } else return(cclib_error(result,"no gametxid")); } else return(cclib_error(result,"couldnt reparse params")); @@ -717,7 +718,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // respawn to be prevented by including timestamps int32_t nextheight = komodo_nextheight(); CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(),nextheight); - UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t numplayers,regslot,numkeys,batonht,batonvout,n,elapsed,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; uint8_t mypriv[32]; + UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t numplayers,regslot,numkeys,batonht,batonvout,n,elapsed,gameheight,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; uint8_t mypriv[32]; if ( txfee == 0 ) txfee = 10000; rogue_univalue(result,"keystrokes",-1,-1); @@ -728,7 +729,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,destaddr,roguepk,mypk); - if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,gametxid) == 0 ) + if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid) == 0 ) { if ( rogue_findbaton(cp,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr,numplayers) == 0 ) { @@ -761,7 +762,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; + UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,gameheight,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -786,7 +787,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { gametxid = juint256(jitem(params,0)); result.push_back(Pair("gametxid",gametxid.GetHex())); - if ( rogue_isvalidgame(cp,gametx,buyin,maxplayers,gametxid) == 0 ) + if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { if ( maxplayers == 1 ) mult /= 2; @@ -834,7 +835,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_highlanderopret(funcid,gametxid,mypk,newdata)); - return(rogue_rawtxresult(result,rawtx,0)); + return(rogue_rawtxresult(result,rawtx,1)); } result.push_back(Pair("result","success")); } @@ -855,7 +856,7 @@ UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; bits256 t; char myrogueaddr[64]; CPubKey mypk,roguepk; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,gameheight,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; bits256 t; char myrogueaddr[64]; CPubKey mypk,roguepk; result.push_back(Pair("name","rogue")); result.push_back(Pair("method","gameinfo")); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -864,9 +865,10 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { txid = juint256(jitem(params,0)); result.push_back(Pair("gametxid",txid.GetHex())); - if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,txid) == 0 ) + if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,txid) == 0 ) { result.push_back(Pair("result","success")); + result.push_back(Pair("gameheight",(int64_t)gameheight)); mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); @@ -890,11 +892,12 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR); int64_t buyin; uint256 txid,hashBlock; CTransaction tx; int32_t maxplayers,vout,numvouts; CPubKey roguepk; char coinaddr[64]; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); int64_t buyin; uint256 txid,hashBlock; CTransaction tx; int32_t maxplayers,gameheight,nextheight,vout,numvouts; CPubKey roguepk; char coinaddr[64]; std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); GetCCaddress(cp,coinaddr,roguepk); SetCCunspents(unspentOutputs,coinaddr); + nextheight = komodo_nextheight(); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { txid = it->first.txhash; @@ -902,7 +905,7 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( it->second.satoshis != txfee || vout != 0 ) // reject any that are not highlander markers continue; - if ( rogue_isvalidgame(cp,tx,buyin,maxplayers,txid) == 0 ) + if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,txid) == 0 && gameheight > nextheight-777 ) a.push_back(txid.GetHex()); } result.push_back(Pair("result","success")); @@ -934,7 +937,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } result.push_back(Pair("result","success")); rogue_univalue(result,"players",-1,-1); - result.push_back(Pair("players",a)); - result.push_back(Pair("numpending",a.size())); + result.push_back(Pair("playerdata",a)); + result.push_back(Pair("numplayerdata",a.size())); return(result); } diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index f6dcc0efe..68250e6cf 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1041,6 +1041,17 @@ CBlockIndex *komodo_blockindex(uint256 hash) return(pindex); } +int32_t komodo_blockheight(uint256 hash) +{ + BlockMap::const_iterator it; CBlockIndex *pindex = 0; + if ( (it = mapBlockIndex.find(hash)) != mapBlockIndex.end() ) + { + if ( (pindex= it->second) != 0 ) + return(pindex->GetHeight()); + } + return(0); +} + int32_t komodo_checkpoint(int32_t *notarized_heightp,int32_t nHeight,uint256 hash) { int32_t notarized_height,MoMdepth; uint256 MoM,notarized_hash,notarized_desttxid; CBlockIndex *notary,*pindex; From 5cda0241b45284cfa811c4d795ed36c4c3d7e840 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 22:07:32 -1100 Subject: [PATCH 0415/1145] +print --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c8af82062..ef5949042 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -134,7 +134,7 @@ // ./rogue gui -> creates keystroke files // cclib register 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd%22]\" // cclib keystrokes 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22deadbeef%22]\" -// cclib bailout 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22]\" +// cclib bailout 17 \"[%22d8bc6445bfec15ea761c8e91e26d162f47856dba1fc8c8ec508cac83b95d7433%22]\" // eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd /* 2409 gold.209 hp.17 strength.16 level.3 exp.22 3 @@ -921,6 +921,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); GetCCaddress(cp,coinaddr,mypk); + fprintf(stderr,"search (%s)\n",coinaddr); SetCCunspents(unspentOutputs,coinaddr); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { From d5db98b42c51fdf6ba2b9707d4d1d46e785dfc04 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 22:14:53 -1100 Subject: [PATCH 0416/1145] mypk = pubkey2pk(Mypubkey()); --- src/cc/rogue_rpc.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ef5949042..b631c1956 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -920,6 +920,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ),a(UniValue::VARR); int64_t buyin; uint256 gametxid,txid,hashBlock; CTransaction playertx,tx; int32_t maxplayers,vout,numvouts; std::vector playerdata; CPubKey roguepk,mypk,pk; char coinaddr[64]; std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); + mypk = pubkey2pk(Mypubkey()); GetCCaddress(cp,coinaddr,mypk); fprintf(stderr,"search (%s)\n",coinaddr); SetCCunspents(unspentOutputs,coinaddr); From 564a7aece8231396482431498d4287a600a18d34 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 22:25:09 -1100 Subject: [PATCH 0417/1145] Make sure item strings are there --- src/cc/rogue/state.c | 9 +++++++++ src/cc/rogue_rpc.cpp | 7 +++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 20288f59a..67be65430 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1354,6 +1354,15 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item) void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) { + static int32_t didinit; + if ( didinit == 0 ) + { + init_names(); /* Set up names of scrolls */ + init_colors(); /* Set up colors of potions */ + init_stones(); /* Set up stone settings of rings */ + init_materials(); /* Set up materials of wands */ + didinit = 1; + } THING *obj = new_item(); rogue_restoreobject(obj,item); strcpy(packitemstr,inv_name(obj,FALSE)); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b631c1956..d51c0c399 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -412,15 +412,15 @@ int32_t rogue_iterateplayer(uint256 firsttxid,uint256 lasttxid) // retrace p int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPubKey &pk,std::vector &playerdata,uint256 playertxid) { - uint256 origplayertxid,hashBlock,highlander; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,numvouts,maxplayers; int64_t buyin; + uint256 origplayertxid,hashBlock,gametxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,numvouts,maxplayers; int64_t buyin; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) { GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); script = (uint8_t *)vopret.data(); if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'Q' || script[1] == 'S') ) { - memcpy(&highlander,script+2,sizeof(highlander)); - fprintf(stderr,"got vin.%s \n",playertx.vin[1].prevout.hash.ToString().c_str()); + memcpy(&gametxid,script+2,sizeof(gametxid)); + fprintf(stderr,"got vin.%s gametxid.%s\n",playertx.vin[1].prevout.hash.ToString().c_str(),gametxid.ToString().c_str()); // verify highlander is a valid gametxid, verify playertxid is linked to it //if ( rogue_iterateplayer(highlander,playertx.vin[1].prevout.n,playertxid) == 0 ) //if ( playertx.vin[1].prevout.hash == highlander ) @@ -922,7 +922,6 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) roguepk = GetUnspendable(cp,0); mypk = pubkey2pk(Mypubkey()); GetCCaddress(cp,coinaddr,mypk); - fprintf(stderr,"search (%s)\n",coinaddr); SetCCunspents(unspentOutputs,coinaddr); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { From f16510e7c2b3069f062cf5a221730f3de31f4baf Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 22:32:55 -1100 Subject: [PATCH 0418/1145] Rogue iterate --- src/cc/rogue/state.c | 7 +++---- src/cc/rogue_rpc.cpp | 4 ++-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 67be65430..23b6d7b27 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1357,10 +1357,9 @@ void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) static int32_t didinit; if ( didinit == 0 ) { - init_names(); /* Set up names of scrolls */ - init_colors(); /* Set up colors of potions */ - init_stones(); /* Set up stone settings of rings */ - init_materials(); /* Set up materials of wands */ + struct rogue_state R; + memset(&R,0,sizeof(R)); + rogueiterate(&R); didinit = 1; } THING *obj = new_item(); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d51c0c399..85c050ec8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -420,10 +420,10 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'Q' || script[1] == 'S') ) { memcpy(&gametxid,script+2,sizeof(gametxid)); - fprintf(stderr,"got vin.%s gametxid.%s\n",playertx.vin[1].prevout.hash.ToString().c_str(),gametxid.ToString().c_str()); + fprintf(stderr,"got vin.%s gametxid.%s iterate.%d valid.%d\n",playertx.vin[1].prevout.hash.ToString().c_str(),gametxid.ToString().c_str(),rogue_iterateplayer(gametxid,playertx.vin[1].prevout.n,playertxid),rogue_isvalidgame(cp,gametx,buyin,maxplayers,gametxid)); // verify highlander is a valid gametxid, verify playertxid is linked to it //if ( rogue_iterateplayer(highlander,playertx.vin[1].prevout.n,playertxid) == 0 ) - //if ( playertx.vin[1].prevout.hash == highlander ) + if ( playertx.vin[1].prevout.hash == gametxid ) { //if ( GetTransaction(highlander,highlandertx,hashBlock,false) != 0 && (numvouts= highlandertx.vout.size()) > 0 ) { From ddf8f6a0dd8cf33fac9faf672885cbaa93b49d1e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 22:34:43 -1100 Subject: [PATCH 0419/1145] Syntax --- src/cc/rogue_rpc.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 85c050ec8..8e9cee736 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -387,12 +387,13 @@ UniValue rogue_playerobj(UniValue &obj,std::vector playerdata) return(obj); } -int32_t rogue_iterateplayer(uint256 firsttxid,uint256 lasttxid) // retrace playertxid vins to reach highlander <- this verifies player is valid and rogue_playerdataspend makes sure it can only be used once +int32_t rogue_iterateplayer(uint256 firsttxid,int32_t firstvout,uint256 lasttxid) // retrace playertxid vins to reach highlander <- this verifies player is valid and rogue_playerdataspend makes sure it can only be used once { - uint256 spenttxid,txid = firsttxid; int32_t spentvini,vout = 0; + uint256 spenttxid,txid = firsttxid; int32_t spentvini,vout = firstvout; while ( (spentvini= myIsutxo_spent(spenttxid,txid,vout)) == 0 ) { txid = spenttxid; + vout = spentvini; } if ( txid == lasttxid ) return(0); @@ -412,7 +413,7 @@ int32_t rogue_iterateplayer(uint256 firsttxid,uint256 lasttxid) // retrace p int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPubKey &pk,std::vector &playerdata,uint256 playertxid) { - uint256 origplayertxid,hashBlock,gametxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,numvouts,maxplayers; int64_t buyin; + uint256 origplayertxid,hashBlock,gametxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,gameheight,numvouts,maxplayers; int64_t buyin; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) { GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); @@ -420,7 +421,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'Q' || script[1] == 'S') ) { memcpy(&gametxid,script+2,sizeof(gametxid)); - fprintf(stderr,"got vin.%s gametxid.%s iterate.%d valid.%d\n",playertx.vin[1].prevout.hash.ToString().c_str(),gametxid.ToString().c_str(),rogue_iterateplayer(gametxid,playertx.vin[1].prevout.n,playertxid),rogue_isvalidgame(cp,gametx,buyin,maxplayers,gametxid)); + fprintf(stderr,"got vin.%s gametxid.%s iterate.%d valid.%d\n",playertx.vin[1].prevout.hash.ToString().c_str(),gametxid.ToString().c_str(),rogue_iterateplayer(gametxid,playertx.vin[1].prevout.n,playertxid),rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)); // verify highlander is a valid gametxid, verify playertxid is linked to it //if ( rogue_iterateplayer(highlander,playertx.vin[1].prevout.n,playertxid) == 0 ) if ( playertx.vin[1].prevout.hash == gametxid ) From 612cabbfea4e712c01be7cb8b4c6f0868458dca5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 22:38:02 -1100 Subject: [PATCH 0420/1145] 'Q' 'y' --- src/cc/rogue/state.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 23b6d7b27..a9aa109f0 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1357,8 +1357,13 @@ void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) static int32_t didinit; if ( didinit == 0 ) { - struct rogue_state R; + struct rogue_state R; char keystrokes[3]; memset(&R,0,sizeof(R)); + keystrokes[0] = 'Q'; + keystrokes[1] = 'y'; + keystrokes[2] = 0; + R.keystrokes = keystrokes; + R.numkeys = 2; rogueiterate(&R); didinit = 1; } From 3cc3c3abedbab6f93f9db4d00dafb36d470d3ff4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 22:48:41 -1100 Subject: [PATCH 0421/1145] Details print --- src/cc/rogue/state.c | 1 + src/cc/rogue_rpc.cpp | 23 ++++++++++------------- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index a9aa109f0..50d995c79 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1370,6 +1370,7 @@ void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) THING *obj = new_item(); rogue_restoreobject(obj,item); strcpy(packitemstr,inv_name(obj,FALSE)); + fprintf(stderr,"packitem.(%s)\n",packitemstr); free(obj); } diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 8e9cee736..83a556a80 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -390,6 +390,8 @@ UniValue rogue_playerobj(UniValue &obj,std::vector playerdata) int32_t rogue_iterateplayer(uint256 firsttxid,int32_t firstvout,uint256 lasttxid) // retrace playertxid vins to reach highlander <- this verifies player is valid and rogue_playerdataspend makes sure it can only be used once { uint256 spenttxid,txid = firsttxid; int32_t spentvini,vout = firstvout; + if ( vout < 0 ) + return(-1); while ( (spentvini= myIsutxo_spent(spenttxid,txid,vout)) == 0 ) { txid = spenttxid; @@ -399,7 +401,7 @@ int32_t rogue_iterateplayer(uint256 firsttxid,int32_t firstvout,uint256 lasttxid return(0); else { - fprintf(stderr,"firsttxid.%s -> %s != last.%s\n",firsttxid.ToString().c_str(),txid.ToString().c_str(),lasttxid.ToString().c_str()); + fprintf(stderr,"firsttxid.%s/v%d -> %s != last.%s\n",firsttxid.ToString().c_str(),firstvout,txid.ToString().c_str(),lasttxid.ToString().c_str()); return(-1); } } @@ -421,21 +423,16 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'Q' || script[1] == 'S') ) { memcpy(&gametxid,script+2,sizeof(gametxid)); - fprintf(stderr,"got vin.%s gametxid.%s iterate.%d valid.%d\n",playertx.vin[1].prevout.hash.ToString().c_str(),gametxid.ToString().c_str(),rogue_iterateplayer(gametxid,playertx.vin[1].prevout.n,playertxid),rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)); - // verify highlander is a valid gametxid, verify playertxid is linked to it - //if ( rogue_iterateplayer(highlander,playertx.vin[1].prevout.n,playertxid) == 0 ) - if ( playertx.vin[1].prevout.hash == gametxid ) + if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { - //if ( GetTransaction(highlander,highlandertx,hashBlock,false) != 0 && (numvouts= highlandertx.vout.size()) > 0 ) + fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d valid.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); + if ( playertx.vin[1].prevout.hash == gametxid ) { if ( (f= rogue_highlanderopretdecode(origplayergame,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' || f == 'S' ) - { - //if ( highlandertx.vin[0].prevout.hash == origplayergame && highlandertx.vin[0].prevout.n == 0 && rogue_isvalidgame(cp,gametx,buyin,maxplayers,origplayergame) == 0 && maxplayers > 1 ) - return(0); - //else return(-3); - } - } - } //else return(-2); + return(0); + else fprintf(stderr,"f is %c/%d\n",f,f); + } else fprintf(stderr,"hash mismatch or illegale gametxid\n"); + } } } return(-1); From 3c5c8f35999ffc2874dde51b68c388d9d26ee2a4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 23:06:57 -1100 Subject: [PATCH 0422/1145] oi_know --- src/cc/rogue/state.c | 20 +++++++++++++++++ src/cc/rogue/things.c | 52 +++++++++++++++++++++---------------------- src/cc/rogue_rpc.cpp | 24 +++++++------------- 3 files changed, 54 insertions(+), 42 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 50d995c79..def3fb859 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1338,6 +1338,7 @@ rs_read_monsters(FILE *inf, struct monster *m, int count) void rogue_restoreobject(THING *o,struct rogue_packitem *item) { + int32_t i; o->_o._o_type = item->type; o->_o._o_launch = item->launch; memcpy(o->_o._o_damage,item->damage,sizeof(item->damage)); @@ -1350,6 +1351,25 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item) o->_o._o_flags = item->flags; o->_o._o_group = item->group; o->o_flags |= ISKNOW; + switch ( item->type ) + { + case SCROLL: + if ( item->which < MAXSCROLLS ) + scr_info[item->which].oi_know = TRUE; + break; + case POTION: + if ( item->which < MAXPOTIONS ) + pot_info[item->which].oi_know = TRUE; + break; + case RING: + if ( item->which < MAXRINGS ) + ring_info[item->which].oi_know = TRUE; + break; + case STICK: + if ( item->which < MAXSTICKS ) + ws_info[item->which].oi_know = TRUE; + break; + } } void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) diff --git a/src/cc/rogue/things.c b/src/cc/rogue/things.c index 660e0720e..4e572c60b 100644 --- a/src/cc/rogue/things.c +++ b/src/cc/rogue/things.c @@ -432,15 +432,15 @@ print_disc(struct rogue_state *rs,char type) obj.o_flags = 0; num_found = 0; for (i = 0; i < maxnum; i++) - if (info[order[i]].oi_know || info[order[i]].oi_guess) - { - obj.o_type = type; - obj.o_which = order[i]; - add_line(rs,"%s", inv_name(&obj, FALSE)); - num_found++; - } + if (info[order[i]].oi_know || info[order[i]].oi_guess) + { + obj.o_type = type; + obj.o_which = order[i]; + add_line(rs,"%s", inv_name(&obj, FALSE)); + num_found++; + } if (num_found == 0) - add_line(rs,nothing(type), NULL); + add_line(rs,nothing(type), NULL); } /* @@ -452,16 +452,16 @@ void set_order(int *order, int numthings) { int i, r, t; - + for (i = 0; i< numthings; i++) - order[i] = i; - + order[i] = i; + for (i = numthings; i > 0; i--) { - r = rnd(i); - t = order[i - 1]; - order[i - 1] = order[r]; - order[r] = t; + r = rnd(i); + t = order[i - 1]; + order[i - 1] = order[r]; + order[r] = t; } } @@ -624,20 +624,20 @@ nameit(THING *obj, const char *type,const char *which, struct obj_info *op, if (op->oi_know || op->oi_guess) { - if (obj->o_count == 1) - sprintf(prbuf, "A %s ", type); - else - sprintf(prbuf, "%d %ss ", obj->o_count, type); - pb = &prbuf[strlen(prbuf)]; - if (op->oi_know) - sprintf(pb, "of %s%s(%s)", op->oi_name, (*prfunc)(obj), which); - else if (op->oi_guess) - sprintf(pb, "called %s%s(%s)", op->oi_guess, (*prfunc)(obj), which); + if (obj->o_count == 1) + sprintf(prbuf, "A %s ", type); + else + sprintf(prbuf, "%d %ss ", obj->o_count, type); + pb = &prbuf[strlen(prbuf)]; + if (op->oi_know) + sprintf(pb, "of %s%s(%s)", op->oi_name, (*prfunc)(obj), which); + else if (op->oi_guess) + sprintf(pb, "called %s%s(%s)", op->oi_guess, (*prfunc)(obj), which); } else if (obj->o_count == 1) - sprintf(prbuf, "A%s %s %s", vowelstr((char *)which), which, type); + sprintf(prbuf, "A%s %s %s", vowelstr((char *)which), which, type); else - sprintf(prbuf, "%d %s %ss", obj->o_count, which, type); + sprintf(prbuf, "%d %s %ss", obj->o_count, which, type); } /* diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 83a556a80..b15925869 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -361,9 +361,9 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa } else return(-1); } -UniValue rogue_playerobj(UniValue &obj,std::vector playerdata) +UniValue rogue_playerobj(std::vector playerdata) { - int32_t i; struct rogue_player P; char packitemstr[512]; UniValue a(UniValue::VARR); + int32_t i; struct rogue_player P; char packitemstr[512]; UniValue obj(UniValue:VOBJ),a(UniValue::VARR); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -383,7 +383,6 @@ UniValue rogue_playerobj(UniValue &obj,std::vector playerdata) obj.push_back(Pair("level",(int64_t)P.level)); obj.push_back(Pair("experience",(int64_t)P.experience)); obj.push_back(Pair("dungeonlevel",(int64_t)P.dungeonlevel)); - // convert to scrolls, etc. return(obj); } @@ -425,13 +424,13 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub memcpy(&gametxid,script+2,sizeof(gametxid)); if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { - fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d valid.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); - if ( playertx.vin[1].prevout.hash == gametxid ) + fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); + if ( playertx.vin[1].prevout.hash == gametxid && rogue_iterateplayer(gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid) == 0 ) { if ( (f= rogue_highlanderopretdecode(origplayergame,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' || f == 'S' ) return(0); else fprintf(stderr,"f is %c/%d\n",f,f); - } else fprintf(stderr,"hash mismatch or illegale gametxid\n"); + } else fprintf(stderr,"hash mismatch or illegal gametxid\n"); } } } @@ -559,10 +558,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet obj.push_back(Pair("batonvalue",ValueFromAmount(batonvalue))); obj.push_back(Pair("batonht",(int64_t)batonht)); if ( playerdata.size() > 0 ) - { - UniValue pobj(UniValue::VOBJ); - obj.push_back(Pair("player",rogue_playerobj(pobj,playerdata))); - } + obj.push_back(Pair("player",rogue_playerobj(playerdata))); } else fprintf(stderr,"findbaton err.%d\n",retval); } @@ -649,11 +645,10 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { if ( n > 0 ) { - UniValue pobj(UniValue::VOBJ); playertxid = juint256(jitem(params,0)); if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"invalid playerdata")); - result.push_back(Pair("player",rogue_playerobj(pobj,playerdata))); + result.push_back(Pair("player",rogue_playerobj(playerdata))); } else return(cclib_error(result,"no playertxid")); return(result); } else return(cclib_error(result,"couldnt reparse params")); @@ -929,10 +924,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( it->second.satoshis != 1 || vout != 0 ) continue; if ( rogue_playerdata(cp,gametxid,pk,playerdata,txid) == 0 && pk == mypk ) - { - UniValue obj(UniValue::VOBJ); - a.push_back(Pair("player",rogue_playerobj(obj,playerdata))); - } + a.push_back(Pair("player",rogue_playerobj(playerdata))); } result.push_back(Pair("result","success")); rogue_univalue(result,"players",-1,-1); From 5e21713f8f0ae651899972a6916e9db67230dff9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 23:08:31 -1100 Subject: [PATCH 0423/1145] :: --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b15925869..3dcfa820a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -363,7 +363,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa UniValue rogue_playerobj(std::vector playerdata) { - int32_t i; struct rogue_player P; char packitemstr[512]; UniValue obj(UniValue:VOBJ),a(UniValue::VARR); + int32_t i; struct rogue_player P; char packitemstr[512]; UniValue obj(UniValue::VOBJ),a(UniValue::VARR); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { From e34d070c2984b4a85dafd63987f8b9b34ee7663c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 23:11:49 -1100 Subject: [PATCH 0424/1145] Double print --- src/cc/rogue_rpc.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3dcfa820a..424c958e0 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -916,6 +916,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) mypk = pubkey2pk(Mypubkey()); GetCCaddress(cp,coinaddr,mypk); SetCCunspents(unspentOutputs,coinaddr); + rogue_univalue(result,"players",-1,-1); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { txid = it->first.txhash; @@ -924,10 +925,11 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( it->second.satoshis != 1 || vout != 0 ) continue; if ( rogue_playerdata(cp,gametxid,pk,playerdata,txid) == 0 && pk == mypk ) + { a.push_back(Pair("player",rogue_playerobj(playerdata))); + result.push_back(Pair("playerdata",rogue_playerobj(playerdata))); + } } - result.push_back(Pair("result","success")); - rogue_univalue(result,"players",-1,-1); result.push_back(Pair("playerdata",a)); result.push_back(Pair("numplayerdata",a.size())); return(result); From b94b392d05e8b9ef3f030be89ce106e175358a70 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 23:14:31 -1100 Subject: [PATCH 0425/1145] Test --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 424c958e0..e0edb1658 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -926,8 +926,8 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) continue; if ( rogue_playerdata(cp,gametxid,pk,playerdata,txid) == 0 && pk == mypk ) { - a.push_back(Pair("player",rogue_playerobj(playerdata))); - result.push_back(Pair("playerdata",rogue_playerobj(playerdata))); + a.push_back(rogue_playerobj(playerdata)); + //result.push_back(Pair("playerdata",rogue_playerobj(playerdata))); } } result.push_back(Pair("playerdata",a)); From de6477bd52a8ddf31b15c0765dcfe49e8d995b68 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 23:18:21 -1100 Subject: [PATCH 0426/1145] Playertxid --- src/cc/rogue_rpc.cpp | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e0edb1658..1a4ffab13 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -361,7 +361,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa } else return(-1); } -UniValue rogue_playerobj(std::vector playerdata) +UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid) { int32_t i; struct rogue_player P; char packitemstr[512]; UniValue obj(UniValue::VOBJ),a(UniValue::VARR); memset(&P,0,sizeof(P)); @@ -376,6 +376,7 @@ UniValue rogue_playerobj(std::vector playerdata) rogue_packitemstr(packitemstr,&P.roguepack[i]); a.push_back(packitemstr); } + obj.push_back(Pair("playertxid",playertxid.GetHex())); obj.push_back(Pair("pack",a)); obj.push_back(Pair("packsize",(int64_t)P.packsize)); obj.push_back(Pair("hitpoints",(int64_t)P.hitpoints)); @@ -448,10 +449,11 @@ int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,uint25 } else return(-1); } -int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &numkeys,int32_t ®slot,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr,int32_t &numplayers) +int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **keystrokesp,int32_t &numkeys,int32_t ®slot,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr,int32_t &numplayers) { - int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 spenttxid,hashBlock,txid,playertxid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; + int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 spenttxid,hashBlock,txid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; numkeys = numplayers = 0; + playertxid = zeroid; for (i=0; i= 0 ) @@ -477,7 +479,6 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &n //fprintf(stderr,"matches.%d numvouts.%d\n",matches,numvouts); if ( rogue_registeropretdecode(txid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) { - fprintf(stderr,"playertxid.%s\n",playertxid.ToString().c_str()); if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) == 0 ) { txid = matchtx.GetHash(); @@ -539,7 +540,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,char **keystrokesp,int32_t &n void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers) { // identify if bailout or quit or timed out - uint256 batontxid,spenttxid,hashBlock; CTransaction spenttx; int32_t numplayers,regslot,numkeys,batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; + uint256 batontxid,spenttxid,hashBlock,playertxid; CTransaction spenttx; int32_t numplayers,regslot,numkeys,batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; destaddr[0] = 0; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { @@ -547,7 +548,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); } obj.push_back(Pair("slot",(int64_t)vout-2)); - if ( (retval= rogue_findbaton(cp,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr,numplayers)) == 0 ) + if ( (retval= rogue_findbaton(cp,playertxid,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr,numplayers)) == 0 ) { if ( CCgettxout(gametxid,maxplayers+vout,1) == 10000 ) obj.push_back(Pair("status","alive")); @@ -558,7 +559,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet obj.push_back(Pair("batonvalue",ValueFromAmount(batonvalue))); obj.push_back(Pair("batonht",(int64_t)batonht)); if ( playerdata.size() > 0 ) - obj.push_back(Pair("player",rogue_playerobj(playerdata))); + obj.push_back(Pair("player",rogue_playerobj(playerdata,playertxid))); } else fprintf(stderr,"findbaton err.%d\n",retval); } @@ -648,7 +649,7 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param playertxid = juint256(jitem(params,0)); if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"invalid playerdata")); - result.push_back(Pair("player",rogue_playerobj(playerdata))); + result.push_back(Pair("player",rogue_playerobj(playerdata,playertxid))); } else return(cclib_error(result,"no playertxid")); return(result); } else return(cclib_error(result,"couldnt reparse params")); @@ -711,7 +712,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // respawn to be prevented by including timestamps int32_t nextheight = komodo_nextheight(); CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(),nextheight); - UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t numplayers,regslot,numkeys,batonht,batonvout,n,elapsed,gameheight,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; uint8_t mypriv[32]; + UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,playertxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t numplayers,regslot,numkeys,batonht,batonvout,n,elapsed,gameheight,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; uint8_t mypriv[32]; if ( txfee == 0 ) txfee = 10000; rogue_univalue(result,"keystrokes",-1,-1); @@ -724,7 +725,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param GetCCaddress1of2(cp,destaddr,roguepk,mypk); if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid) == 0 ) { - if ( rogue_findbaton(cp,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr,numplayers) == 0 ) + if ( rogue_findbaton(cp,playertxid,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr,numplayers) == 0 ) { if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) { @@ -755,7 +756,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,gameheight,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; + UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,gameheight,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,playertxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -784,7 +785,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { if ( maxplayers == 1 ) mult /= 2; - if ( rogue_findbaton(cp,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers) == 0 && keystrokes != 0 ) + if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers) == 0 && keystrokes != 0 ) { UniValue obj; struct rogue_player P; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); @@ -926,7 +927,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) continue; if ( rogue_playerdata(cp,gametxid,pk,playerdata,txid) == 0 && pk == mypk ) { - a.push_back(rogue_playerobj(playerdata)); + a.push_back(rogue_playerobj(playerdata,txid)); //result.push_back(Pair("playerdata",rogue_playerobj(playerdata))); } } From 071e83e28b16d67c345c20869d0d21f485bba82d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 9 Feb 2019 23:26:31 -1100 Subject: [PATCH 0427/1145] Remove second vout for new game --- src/cc/rogue_rpc.cpp | 41 +++++++++++++++++++---------------------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1a4ffab13..e69fb75a9 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -72,9 +72,8 @@ Transaction details creategame vout0 -> txfee highlander vout TCBOO creation - vout1 -> txfee highlander vout TCBOO playerdata used (deprecated) - vout2 to vout.maxplayers+2 -> 1of2 registration ROGUE_REGISTRATIONSIZE batons - vout2+maxplayers to vout.2*maxplayers+2 -> 1of2 registration txfee batons for game completion + vout1 to vout.maxplayers+1 -> 1of2 registration ROGUE_REGISTRATIONSIZE batons + vout2+maxplayers to vout.2*maxplayers+1 -> 1of2 registration txfee batons for game completion register vin0 -> ROGUE_REGISTRATIONSIZE 1of2 registration baton from creategame @@ -268,7 +267,7 @@ int32_t rogue_iamregistered(int32_t maxplayers,uint256 gametxid,CTransaction tx, for (i=0; i= 0 ) { if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) @@ -289,10 +288,10 @@ int32_t rogue_playersalive(int32_t &numplayers,uint256 gametxid,int32_t maxplaye numplayers = 0; for (i=0; i maxplayers+2 ) + if ( numvouts > maxplayers+1 ) { for (i=0; i= 0 ) + if ( myIsutxo_spent(spenttxid,gametxid,i+1) >= 0 ) { if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) { @@ -467,13 +466,13 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke matches++; regslot = i; matchtx = spenttx; - } //else fprintf(stderr,"%d+2 doesnt match %s vs %s\n",i,ccaddr,destaddr); - } //else fprintf(stderr,"%d+2 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); - } //else fprintf(stderr,"%d+2 unspent\n",i); + } //else fprintf(stderr,"%d+1 doesnt match %s vs %s\n",i,ccaddr,destaddr); + } //else fprintf(stderr,"%d+1 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); + } //else fprintf(stderr,"%d+1 unspent\n",i); } if ( matches == 1 ) { - if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+2) < 0 ) + if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); //fprintf(stderr,"matches.%d numvouts.%d\n",matches,numvouts); @@ -547,7 +546,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); } - obj.push_back(Pair("slot",(int64_t)vout-2)); + obj.push_back(Pair("slot",(int64_t)vout-1)); if ( (retval= rogue_findbaton(cp,playertxid,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr,numplayers)) == 0 ) { if ( CCgettxout(gametxid,maxplayers+vout,1) == 10000 ) @@ -566,12 +565,12 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet int64_t rogue_registrationbaton(CMutableTransaction &mtx,uint256 gametxid,CTransaction gametx,int32_t maxplayers) { int32_t vout,j,r; int64_t nValue; - if ( gametx.vout.size() > maxplayers+2 ) + if ( gametx.vout.size() > maxplayers+1 ) { r = rand() % maxplayers; for (j=0; junspendableCCaddr)) >= required ) { mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,roguepk)); // for highlander TCBOO creation - mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,roguepk)); // for highlander TCBOO used for (i=0; ievalcode,ROGUE_REGISTRATIONSIZE,roguepk,roguepk)); for (i=0; ievalcode,1,mypk)); - mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,mypk)); if ( num > 0 ) { newdata.resize(num); @@ -870,10 +867,10 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) rogue_gamefields(result,maxplayers,buyin,txid,myrogueaddr); for (i=0; i Date: Sun, 10 Feb 2019 00:13:42 -1100 Subject: [PATCH 0428/1145] Not pending if all slots filled --- src/cc/rogue_rpc.cpp | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e69fb75a9..d8f003651 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -128,12 +128,12 @@ // cclib newgame 17 \"[3,10]\" // cclib pending 17 -// cclib gameinfo 17 \"[%22d8bc6445bfec15ea761c8e91e26d162f47856dba1fc8c8ec508cac83b95d7433%22]\" -// cclib register 17 \"[%22d8bc6445bfec15ea761c8e91e26d162f47856dba1fc8c8ec508cac83b95d7433%22]\" +// cclib gameinfo 17 \"[%2284d3c1b598c9e2b3891a6b33468ec526cfaa9c7024c578025cdaff24b5ea3d20%22]\" +// cclib register 17 \"[%2284d3c1b598c9e2b3891a6b33468ec526cfaa9c7024c578025cdaff24b5ea3d20%22]\" // ./rogue gui -> creates keystroke files // cclib register 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd%22]\" // cclib keystrokes 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22deadbeef%22]\" -// cclib bailout 17 \"[%22d8bc6445bfec15ea761c8e91e26d162f47856dba1fc8c8ec508cac83b95d7433%22]\" +// cclib bailout 17 \"[%2284d3c1b598c9e2b3891a6b33468ec526cfaa9c7024c578025cdaff24b5ea3d20%22]\" // eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd /* 2409 gold.209 hp.17 strength.16 level.3 exp.22 3 @@ -799,6 +799,8 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param free(keystrokes); mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); mtx.vin.push_back(CTxIn(gametxid,1+maxplayers+regslot,CScript())); + if ( funcid == 'H' ) + mtx.vin.push_back(CTxIn(gametxid,0,CScript())); mtx.vout.push_back(MakeCC1vout(cp->evalcode,1,mypk)); if ( num > 0 ) { @@ -883,7 +885,7 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR); int64_t buyin; uint256 txid,hashBlock; CTransaction tx; int32_t maxplayers,gameheight,nextheight,vout,numvouts; CPubKey roguepk; char coinaddr[64]; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); int64_t buyin; uint256 txid,hashBlock; CTransaction tx; int32_t maxplayers,numplayers,gameheight,nextheight,vout,numvouts; CPubKey roguepk; char coinaddr[64]; std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); GetCCaddress(cp,coinaddr,roguepk); @@ -897,7 +899,11 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( it->second.satoshis != txfee || vout != 0 ) // reject any that are not highlander markers continue; if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,txid) == 0 && gameheight > nextheight-777 ) - a.push_back(txid.GetHex()); + { + rogue_playersalive(numplayers,txid,maxplayers); + if ( numplayers < maxplayers ) + a.push_back(txid.GetHex()); + } } result.push_back(Pair("result","success")); rogue_univalue(result,"pending",-1,-1); From 3bf01610b98bb7e63212c95cb5e652086e7bf0cc Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 00:23:10 -1100 Subject: [PATCH 0429/1145] Registered state --- src/cc/rogue_rpc.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d8f003651..b85df7966 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -539,7 +539,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers) { // identify if bailout or quit or timed out - uint256 batontxid,spenttxid,hashBlock,playertxid; CTransaction spenttx; int32_t numplayers,regslot,numkeys,batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; + uint256 batontxid,spenttxid,gtxid,ptxid,hashBlock,playertxid; CTransaction spenttx,batontx; int32_t numplayers,regslot,numkeys,batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; destaddr[0] = 0; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { @@ -550,8 +550,14 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet if ( (retval= rogue_findbaton(cp,playertxid,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr,numplayers)) == 0 ) { if ( CCgettxout(gametxid,maxplayers+vout,1) == 10000 ) - obj.push_back(Pair("status","alive")); - else obj.push_back(Pair("status","finished")); + { + if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.size() > 1 ) + { + if ( rogue_registeropretdecode(gtxid,ptxid,batontx.vout[batontx.size()-1].scriptPubKey) == 'R' && gtxid == gametxid && ptxid == playertxid ) + obj.push_back(Pair("status","registered")); + else obj.push_back(Pair("status","alive")); + } else obj.push_back(Pair("status","error")); + } else obj.push_back(Pair("status","finished")); obj.push_back(Pair("baton",batontxid.ToString())); obj.push_back(Pair("batonaddr",destaddr)); obj.push_back(Pair("batonvout",(int64_t)batonvout)); From 2e9f18d3dcbb87c7a00647ad8225c90eaa69ec52 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 00:25:30 -1100 Subject: [PATCH 0430/1145] vout.size() --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b85df7966..24d6a87fc 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -551,9 +551,9 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet { if ( CCgettxout(gametxid,maxplayers+vout,1) == 10000 ) { - if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.size() > 1 ) + if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 1 ) { - if ( rogue_registeropretdecode(gtxid,ptxid,batontx.vout[batontx.size()-1].scriptPubKey) == 'R' && gtxid == gametxid && ptxid == playertxid ) + if ( rogue_registeropretdecode(gtxid,ptxid,batontx.vout[batontx.vout.size()-1].scriptPubKey) == 'R' && gtxid == gametxid && ptxid == playertxid ) obj.push_back(Pair("status","registered")); else obj.push_back(Pair("status","alive")); } else obj.push_back(Pair("status","error")); From 666935b93692860407228c05e667cf5253818f4d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 00:28:01 -1100 Subject: [PATCH 0431/1145] Add normal input to use playerdata --- src/cc/rogue_rpc.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 24d6a87fc..bc6580a29 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -697,6 +697,8 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"couldnt find playerdata to spend")); else if ( buyin > 0 && AddNormalinputs(mtx,mypk,buyin,64) < buyin ) return(cclib_error(result,"couldnt find enough normal funds for buyin")); + if ( playertxid != zeroid ) + AddNormalInputs2(mtx,txfee,10); mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); From 144b37028a0d1677c9779661700b5e9dbba36276 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 00:31:31 -1100 Subject: [PATCH 0432/1145] Fix --- src/cc/rogue_rpc.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index bc6580a29..800337827 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -386,15 +386,18 @@ UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid) return(obj); } -int32_t rogue_iterateplayer(uint256 firsttxid,int32_t firstvout,uint256 lasttxid) // retrace playertxid vins to reach highlander <- this verifies player is valid and rogue_playerdataspend makes sure it can only be used once +int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firstvout,uint256 lasttxid) // retrace playertxid vins to reach highlander <- this verifies player is valid and rogue_playerdataspend makes sure it can only be used once { uint256 spenttxid,txid = firsttxid; int32_t spentvini,vout = firstvout; + registertxid = zeroid; if ( vout < 0 ) return(-1); while ( (spentvini= myIsutxo_spent(spenttxid,txid,vout)) == 0 ) { txid = spenttxid; vout = spentvini; + if ( registertxid == zeroid ) + registertxid = txid; } if ( txid == lasttxid ) return(0); @@ -414,7 +417,7 @@ int32_t rogue_iterateplayer(uint256 firsttxid,int32_t firstvout,uint256 lasttxid int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPubKey &pk,std::vector &playerdata,uint256 playertxid) { - uint256 origplayertxid,hashBlock,gametxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,gameheight,numvouts,maxplayers; int64_t buyin; + uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,gameheight,numvouts,maxplayers; int64_t buyin; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) { GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); @@ -425,10 +428,13 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); - if ( playertx.vin[1].prevout.hash == gametxid && rogue_iterateplayer(gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid) == 0 ) + if ( playertx.vin[1].prevout.hash == gametxid && rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid) == 0 ) { if ( (f= rogue_highlanderopretdecode(origplayergame,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' || f == 'S' ) + { + // if registertxid has vin from pk, it can be used return(0); + } else fprintf(stderr,"f is %c/%d\n",f,f); } else fprintf(stderr,"hash mismatch or illegal gametxid\n"); } From 5e6c99ebeca5893d687674cbe894d98485a5db83 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 00:32:33 -1100 Subject: [PATCH 0433/1145] Test --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 800337827..5489b75f6 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -427,7 +427,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub memcpy(&gametxid,script+2,sizeof(gametxid)); if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { - fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); + fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); if ( playertx.vin[1].prevout.hash == gametxid && rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid) == 0 ) { if ( (f= rogue_highlanderopretdecode(origplayergame,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' || f == 'S' ) @@ -704,7 +704,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) else if ( buyin > 0 && AddNormalinputs(mtx,mypk,buyin,64) < buyin ) return(cclib_error(result,"couldnt find enough normal funds for buyin")); if ( playertxid != zeroid ) - AddNormalInputs2(mtx,txfee,10); + AddNormalinputs2(mtx,txfee,10); mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); From 14f1da959c1c0e79f21a0e895e85af04b045a86d Mon Sep 17 00:00:00 2001 From: dimxy Date: Thu, 7 Feb 2019 11:34:26 +0500 Subject: [PATCH 0434/1145] non-fungible tokens support (three-eval token vouts) added in CCtokens (additional opret data) non-fungible tokens support added in assets logging changed in CCtokens.cpp for bitcon LogPrintStr with -debug= support --- src/cc/CCassets.h | 7 +- src/cc/CCassetsCore.cpp | 244 +++++++++-------- src/cc/CCassetstx.cpp | 191 +++++++------ src/cc/CCcustom.cpp | 3 + src/cc/CCinclude.h | 44 ++- src/cc/CCtokens.cpp | 563 +++++++++++++++++++++++++-------------- src/cc/CCtokens.h | 5 +- src/cc/CCtx.cpp | 57 ++-- src/cc/CCutils.cpp | 74 +++-- src/cc/assets.cpp | 97 ++++--- src/cc/oracles.cpp | 2 +- src/cc/prices.cpp | 4 + src/wallet/rpcwallet.cpp | 88 +++--- 13 files changed, 851 insertions(+), 528 deletions(-) diff --git a/src/cc/CCassets.h b/src/cc/CCassets.h index 69fcfacbb..c4623ccbb 100644 --- a/src/cc/CCassets.h +++ b/src/cc/CCassets.h @@ -29,11 +29,8 @@ bool AssetsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx, uint32_t nIn); // CCassetsCore -//CTxOut MakeAssetsVout(CAmount nValue,CPubKey pk); -//CScript EncodeAssetCreateOpRet(uint8_t funcid,std::vector origpubkey,std::string name,std::string description); -//CScript EncodeAssetOpRet(uint8_t assetFuncId, uint256 tokenid, uint256 assetid2, int64_t price, std::vector origpubkey); -//bool DecodeAssetCreateOpRet(const CScript &scriptPubKey,std::vector &origpubkey,std::string &name,std::string &description); -//uint8_t DecodeAssetOpRet(const CScript &scriptPubKey, uint8_t &evalCode, uint256 &assetid, uint256 &assetid2, int64_t &price, std::vector &origpubkey); +CScript EncodeAssetOpRet(uint8_t assetFuncId, uint256 assetid2, int64_t price, std::vector origpubkey); +uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCode, uint256 &tokenid, uint256 &assetid2, int64_t &price, std::vector &origpubkey, std::vector &vopretNonfungible); bool SetAssetOrigpubkey(std::vector &origpubkey,int64_t &price,const CTransaction &tx); int64_t IsAssetvout(struct CCcontract_info *cp, int64_t &price, std::vector &origpubkey, const CTransaction& tx, int32_t v, uint256 refassetid); bool ValidateBidRemainder(int64_t remaining_price,int64_t remaining_nValue,int64_t orig_nValue,int64_t received_nValue,int64_t paidprice,int64_t totalprice); diff --git a/src/cc/CCassetsCore.cpp b/src/cc/CCassetsCore.cpp index 1b8e46189..f14de3956 100644 --- a/src/cc/CCassetsCore.cpp +++ b/src/cc/CCassetsCore.cpp @@ -43,17 +43,17 @@ bool ValidateBidRemainder(int64_t remaining_units,int64_t remaining_nValue,int64 int64_t unitprice,recvunitprice,newunitprice=0; if ( orig_nValue == 0 || received_nValue == 0 || paidunits == 0 || totalunits == 0 ) { - fprintf(stderr,"ValidateAssetRemainder: orig_nValue == %llu || received_nValue == %llu || paidunits == %llu || totalunits == %llu\n",(long long)orig_nValue,(long long)received_nValue,(long long)paidunits,(long long)totalunits); + fprintf(stderr,"ValidateAssetRemainder() orig_nValue == %llu || received_nValue == %llu || paidunits == %llu || totalunits == %llu\n",(long long)orig_nValue,(long long)received_nValue,(long long)paidunits,(long long)totalunits); return(false); } else if ( totalunits != (remaining_units + paidunits) ) { - fprintf(stderr,"ValidateAssetRemainder: totalunits %llu != %llu (remaining_units %llu + %llu paidunits)\n",(long long)totalunits,(long long)(remaining_units + paidunits),(long long)remaining_units,(long long)paidunits); + fprintf(stderr,"ValidateAssetRemainder() totalunits %llu != %llu (remaining_units %llu + %llu paidunits)\n",(long long)totalunits,(long long)(remaining_units + paidunits),(long long)remaining_units,(long long)paidunits); return(false); } else if ( orig_nValue != (remaining_nValue + received_nValue) ) { - fprintf(stderr,"ValidateAssetRemainder: orig_nValue %llu != %llu (remaining_nValue %llu + %llu received_nValue)\n",(long long)orig_nValue,(long long)(remaining_nValue - received_nValue),(long long)remaining_nValue,(long long)received_nValue); + fprintf(stderr,"ValidateAssetRemainder() orig_nValue %llu != %llu (remaining_nValue %llu + %llu received_nValue)\n",(long long)orig_nValue,(long long)(remaining_nValue - received_nValue),(long long)remaining_nValue,(long long)received_nValue); return(false); } else @@ -68,10 +68,10 @@ bool ValidateBidRemainder(int64_t remaining_units,int64_t remaining_nValue,int64 newunitprice = (remaining_nValue / remaining_units); if ( recvunitprice < unitprice ) { - fprintf(stderr,"error recvunitprice %.8f < %.8f unitprice, new unitprice %.8f\n",(double)recvunitprice/(COIN),(double)unitprice/(COIN),(double)newunitprice/(COIN)); + fprintf(stderr,"ValidateAssetRemainder() error recvunitprice %.8f < %.8f unitprice, new unitprice %.8f\n",(double)recvunitprice/(COIN),(double)unitprice/(COIN),(double)newunitprice/(COIN)); return(false); } - fprintf(stderr,"orig %llu total %llu, recv %llu paid %llu,recvunitprice %.8f >= %.8f unitprice, new unitprice %.8f\n",(long long)orig_nValue,(long long)totalunits,(long long)received_nValue,(long long)paidunits,(double)recvunitprice/(COIN),(double)unitprice/(COIN),(double)newunitprice/(COIN)); + fprintf(stderr,"ValidateAssetRemainder() orig %llu total %llu, recv %llu paid %llu,recvunitprice %.8f >= %.8f unitprice, new unitprice %.8f\n",(long long)orig_nValue,(long long)totalunits,(long long)received_nValue,(long long)paidunits,(double)recvunitprice/(COIN),(double)unitprice/(COIN),(double)newunitprice/(COIN)); } return(true); } @@ -89,7 +89,7 @@ bool SetBidFillamounts(int64_t &received_nValue,int64_t &remaining_units,int64_t paidunits = totalunits; received_nValue = orig_nValue; remaining_units = 0; - fprintf(stderr,"totally filled!\n"); + fprintf(stderr,"SetBidFillamounts() bid order totally filled!\n"); return(true); } remaining_units = (totalunits - paidunits); @@ -100,7 +100,7 @@ bool SetBidFillamounts(int64_t &received_nValue,int64_t &remaining_units,int64_t if ( unitprice > 0 && received_nValue > 0 && received_nValue <= orig_nValue ) { remaining_nValue = (orig_nValue - received_nValue); - printf("total.%llu - paid.%llu, remaining %llu <- %llu (%llu - %llu)\n",(long long)totalunits,(long long)paidunits,(long long)remaining_nValue,(long long)(orig_nValue - received_nValue),(long long)orig_nValue,(long long)received_nValue); + printf("SetBidFillamounts() total.%llu - paid.%llu, remaining %llu <- %llu (%llu - %llu)\n",(long long)totalunits,(long long)paidunits,(long long)remaining_nValue,(long long)(orig_nValue - received_nValue),(long long)orig_nValue,(long long)received_nValue); return(ValidateBidRemainder(remaining_units,remaining_nValue,orig_nValue,received_nValue,paidunits,totalunits)); } else return(false); } @@ -118,14 +118,14 @@ bool SetAskFillamounts(int64_t &received_assetoshis,int64_t &remaining_nValue,in paid_nValue = total_nValue; received_assetoshis = orig_assetoshis; remaining_nValue = 0; - fprintf(stderr,"totally filled!\n"); + fprintf(stderr,"SetAskFillamounts() ask order totally filled!\n"); return(true); } remaining_nValue = (total_nValue - paid_nValue); dunitprice = ((double)total_nValue / orig_assetoshis); received_assetoshis = (paid_nValue / dunitprice); - fprintf(stderr,"remaining_nValue %.8f (%.8f - %.8f)\n",(double)remaining_nValue/COIN,(double)total_nValue/COIN,(double)paid_nValue/COIN); - fprintf(stderr,"unitprice %.8f received_assetoshis %llu orig %llu\n",dunitprice/COIN,(long long)received_assetoshis,(long long)orig_assetoshis); + fprintf(stderr,"SetAskFillamounts() remaining_nValue %.8f (%.8f - %.8f)\n",(double)remaining_nValue/COIN,(double)total_nValue/COIN,(double)paid_nValue/COIN); + fprintf(stderr,"SetAskFillamounts() unitprice %.8f received_assetoshis %llu orig %llu\n",dunitprice/COIN,(long long)received_assetoshis,(long long)orig_assetoshis); if ( fabs(dunitprice) > SMALLVAL && received_assetoshis > 0 && received_assetoshis <= orig_assetoshis ) { remaining_assetoshis = (orig_assetoshis - received_assetoshis); @@ -138,17 +138,17 @@ bool ValidateAskRemainder(int64_t remaining_nValue,int64_t remaining_assetoshis, int64_t unitprice,recvunitprice,newunitprice=0; if ( orig_assetoshis == 0 || received_assetoshis == 0 || paid_nValue == 0 || total_nValue == 0 ) { - fprintf(stderr,"ValidateAssetRemainder: orig_assetoshis == %llu || received_assetoshis == %llu || paid_nValue == %llu || total_nValue == %llu\n",(long long)orig_assetoshis,(long long)received_assetoshis,(long long)paid_nValue,(long long)total_nValue); + fprintf(stderr,"ValidateAssetRemainder() orig_assetoshis == %llu || received_assetoshis == %llu || paid_nValue == %llu || total_nValue == %llu\n",(long long)orig_assetoshis,(long long)received_assetoshis,(long long)paid_nValue,(long long)total_nValue); return(false); } else if ( total_nValue != (remaining_nValue + paid_nValue) ) { - fprintf(stderr,"ValidateAssetRemainder: total_nValue %llu != %llu (remaining_nValue %llu + %llu paid_nValue)\n",(long long)total_nValue,(long long)(remaining_nValue + paid_nValue),(long long)remaining_nValue,(long long)paid_nValue); + fprintf(stderr,"ValidateAssetRemainder() total_nValue %llu != %llu (remaining_nValue %llu + %llu paid_nValue)\n",(long long)total_nValue,(long long)(remaining_nValue + paid_nValue),(long long)remaining_nValue,(long long)paid_nValue); return(false); } else if ( orig_assetoshis != (remaining_assetoshis + received_assetoshis) ) { - fprintf(stderr,"ValidateAssetRemainder: orig_assetoshis %llu != %llu (remaining_nValue %llu + %llu received_nValue)\n",(long long)orig_assetoshis,(long long)(remaining_assetoshis - received_assetoshis),(long long)remaining_assetoshis,(long long)received_assetoshis); + fprintf(stderr,"ValidateAssetRemainder() orig_assetoshis %llu != %llu (remaining_nValue %llu + %llu received_nValue)\n",(long long)orig_assetoshis,(long long)(remaining_assetoshis - received_assetoshis),(long long)remaining_assetoshis,(long long)received_assetoshis); return(false); } else @@ -159,10 +159,10 @@ bool ValidateAskRemainder(int64_t remaining_nValue,int64_t remaining_assetoshis, newunitprice = (remaining_nValue / remaining_assetoshis); if ( recvunitprice < unitprice ) { - fprintf(stderr,"error recvunitprice %.8f < %.8f unitprice, new unitprice %.8f\n",(double)recvunitprice/COIN,(double)unitprice/COIN,(double)newunitprice/COIN); + fprintf(stderr,"ValidateAskRemainder() error recvunitprice %.8f < %.8f unitprice, new unitprice %.8f\n",(double)recvunitprice/COIN,(double)unitprice/COIN,(double)newunitprice/COIN); return(false); } - fprintf(stderr,"got recvunitprice %.8f >= %.8f unitprice, new unitprice %.8f\n",(double)recvunitprice/COIN,(double)unitprice/COIN,(double)newunitprice/COIN); + fprintf(stderr,"ValidateAskRemainder() got recvunitprice %.8f >= %.8f unitprice, new unitprice %.8f\n",(double)recvunitprice/COIN,(double)unitprice/COIN,(double)newunitprice/COIN); } return(true); } @@ -172,7 +172,7 @@ bool SetSwapFillamounts(int64_t &received_assetoshis,int64_t &remaining_assetosh int64_t remaining_assetoshis; double dunitprice; if ( total_assetoshis2 == 0 ) { - fprintf(stderr,"total_assetoshis2.0 origsatoshis.%llu paid_assetoshis2.%llu\n",(long long)orig_assetoshis,(long long)paid_assetoshis2); + fprintf(stderr,"SetSwapFillamounts() total_assetoshis2.0 origsatoshis.%llu paid_assetoshis2.%llu\n",(long long)orig_assetoshis,(long long)paid_assetoshis2); received_assetoshis = remaining_assetoshis2 = paid_assetoshis2 = 0; return(false); } @@ -181,14 +181,14 @@ bool SetSwapFillamounts(int64_t &received_assetoshis,int64_t &remaining_assetosh paid_assetoshis2 = total_assetoshis2; received_assetoshis = orig_assetoshis; remaining_assetoshis2 = 0; - fprintf(stderr,"totally filled!\n"); + fprintf(stderr,"SetSwapFillamounts() swap order totally filled!\n"); return(true); } remaining_assetoshis2 = (total_assetoshis2 - paid_assetoshis2); dunitprice = ((double)total_assetoshis2 / orig_assetoshis); received_assetoshis = (paid_assetoshis2 / dunitprice); - fprintf(stderr,"remaining_assetoshis2 %llu (%llu - %llu)\n",(long long)remaining_assetoshis2/COIN,(long long)total_assetoshis2/COIN,(long long)paid_assetoshis2/COIN); - fprintf(stderr,"unitprice %.8f received_assetoshis %llu orig %llu\n",dunitprice/COIN,(long long)received_assetoshis,(long long)orig_assetoshis); + fprintf(stderr,"SetSwapFillamounts() remaining_assetoshis2 %llu (%llu - %llu)\n",(long long)remaining_assetoshis2/COIN,(long long)total_assetoshis2/COIN,(long long)paid_assetoshis2/COIN); + fprintf(stderr,"SetSwapFillamounts() unitprice %.8f received_assetoshis %llu orig %llu\n",dunitprice/COIN,(long long)received_assetoshis,(long long)orig_assetoshis); if ( fabs(dunitprice) > SMALLVAL && received_assetoshis > 0 && received_assetoshis <= orig_assetoshis ) { remaining_assetoshis = (orig_assetoshis - received_assetoshis); @@ -201,17 +201,17 @@ bool ValidateSwapRemainder(int64_t remaining_price,int64_t remaining_nValue,int6 int64_t unitprice,recvunitprice,newunitprice=0; if ( orig_nValue == 0 || received_nValue == 0 || paidunits == 0 || totalunits == 0 ) { - fprintf(stderr,"ValidateAssetRemainder: orig_nValue == %llu || received_nValue == %llu || paidunits == %llu || totalunits == %llu\n",(long long)orig_nValue,(long long)received_nValue,(long long)paidunits,(long long)totalunits); + fprintf(stderr,"ValidateAssetRemainder() orig_nValue == %llu || received_nValue == %llu || paidunits == %llu || totalunits == %llu\n",(long long)orig_nValue,(long long)received_nValue,(long long)paidunits,(long long)totalunits); return(false); } else if ( totalunits != (remaining_price + paidunits) ) { - fprintf(stderr,"ValidateAssetRemainder: totalunits %llu != %llu (remaining_price %llu + %llu paidunits)\n",(long long)totalunits,(long long)(remaining_price + paidunits),(long long)remaining_price,(long long)paidunits); + fprintf(stderr,"ValidateAssetRemainder() totalunits %llu != %llu (remaining_price %llu + %llu paidunits)\n",(long long)totalunits,(long long)(remaining_price + paidunits),(long long)remaining_price,(long long)paidunits); return(false); } else if ( orig_nValue != (remaining_nValue + received_nValue) ) { - fprintf(stderr,"ValidateAssetRemainder: orig_nValue %llu != %llu (remaining_nValue %llu + %llu received_nValue)\n",(long long)orig_nValue,(long long)(remaining_nValue - received_nValue),(long long)remaining_nValue,(long long)received_nValue); + fprintf(stderr,"ValidateAssetRemainder() orig_nValue %llu != %llu (remaining_nValue %llu + %llu received_nValue)\n",(long long)orig_nValue,(long long)(remaining_nValue - received_nValue),(long long)remaining_nValue,(long long)received_nValue); return(false); } else @@ -222,10 +222,10 @@ bool ValidateSwapRemainder(int64_t remaining_price,int64_t remaining_nValue,int6 newunitprice = (remaining_nValue * COIN) / remaining_price; if ( recvunitprice < unitprice ) { - fprintf(stderr,"error recvunitprice %.8f < %.8f unitprice, new unitprice %.8f\n",(double)recvunitprice/(COIN*COIN),(double)unitprice/(COIN*COIN),(double)newunitprice/(COIN*COIN)); + fprintf(stderr,"ValidateAssetRemainder() error recvunitprice %.8f < %.8f unitprice, new unitprice %.8f\n",(double)recvunitprice/(COIN*COIN),(double)unitprice/(COIN*COIN),(double)newunitprice/(COIN*COIN)); return(false); } - fprintf(stderr,"recvunitprice %.8f >= %.8f unitprice, new unitprice %.8f\n",(double)recvunitprice/(COIN*COIN),(double)unitprice/(COIN*COIN),(double)newunitprice/(COIN*COIN)); + fprintf(stderr,"ValidateAssetRemainder() recvunitprice %.8f >= %.8f unitprice, new unitprice %.8f\n",(double)recvunitprice/(COIN*COIN),(double)unitprice/(COIN*COIN),(double)newunitprice/(COIN*COIN)); } return(true); } @@ -279,19 +279,35 @@ bool DecodeAssetCreateOpRet(const CScript &scriptPubKey, std::vector &o return(0); } */ -uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &evalCodeInOpret, uint256 &tokenid, uint256 &assetid2, int64_t &price, std::vector &origpubkey) +uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCode, uint256 &tokenid, uint256 &assetid2, int64_t &price, std::vector &origpubkey, std::vector &vopretNonfungible) { - std::vector vopretExtra, vopretStripped; - uint8_t *script, funcId = 0, assetFuncId = 0, dummyEvalCode, dummyAssetFuncId; + std::vector vopret1, vopret2; + std::vector vopretAssets; //, vopretAssetsStripped; + uint8_t *script, funcId = 0, assetsFuncId = 0, dummyEvalCode, dummyAssetFuncId; uint256 dummyTokenid; std::vector voutPubkeysDummy; tokenid = zeroid; assetid2 = zeroid; price = 0; + assetsEvalCode = 0; + assetsFuncId = 0; // First - decode token opret: - funcId = DecodeTokenOpRet(scriptPubKey, evalCodeInOpret, tokenid, voutPubkeysDummy, vopretExtra); + funcId = DecodeTokenOpRet(scriptPubKey, dummyEvalCode, tokenid, voutPubkeysDummy, vopret1, vopret2); + std::cerr << "DecodeAssetTokenOpRet() from DecodeTokenOpRet returned funcId=" << (int)funcId << std::endl; + + if (!vopret2.empty()) { + // if there are both oprets then order is like this: + vopretNonfungible = vopret1; + vopretAssets = vopret2; + } + else { + // if only one opret - it is assets opret: + vopretNonfungible.clear(); + vopretAssets = vopret1; + } + /*GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); @@ -302,54 +318,59 @@ uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &evalCodeInOp //bool isEof = true; // NOTE: if parse error occures, parse might not be able to set error. It is safer to treat that it was eof if it is not set! //bool result = E_UNMARSHAL(vopret, ss >> evalCodeInOpret; ss >> funcId; ss >> tokenid; ss >> assetFuncId; isEof = ss.eof()); - if (funcId == 0 || vopretExtra.size() < 2) { - std::cerr << "DecodeAssetOpRet() incorrect opret or no asset's payload" << " funcId=" << (int)funcId << " vopretExtra.size()=" << vopretExtra.size() << std::endl; + if (funcId == 0 || vopretAssets.size() < 2) { + std::cerr << "DecodeAssetTokenOpRet() incorrect opret or no asset's payload" << " funcId=" << (int)funcId << " vopretAssets.size()=" << vopretAssets.size() << std::endl; return (uint8_t)0; } - if (!E_UNMARSHAL(vopretExtra, { ss >> vopretStripped; })) { //strip string size - std::cerr << "DecodeAssetTokenOpRet() could not unmarshal vopretStripped" << std::endl; - return (uint8_t)0; - } + //if (!E_UNMARSHAL(vopretAssets, { ss >> vopretAssetsStripped; })) { //strip string size + // std::cerr << "DecodeAssetTokenOpRet() could not unmarshal vopretAssetsStripped" << std::endl; + // return (uint8_t)0; + //} - ////tokenid = revuint256(tokenid); already done in DecodeToken! - evalCodeInOpret = vopretStripped.begin()[0]; - assetFuncId = vopretStripped.begin()[1]; + // additional check to prevent crash + if (vopretAssets.size() >= 2) { - //std::cerr << "DecodeAssetOpRet() evalCodeInOpret=" << (int)evalCodeInOpret << " funcId=" << (char)(funcId ? funcId : ' ') << " assetFuncId=" << (char)(assetFuncId ? assetFuncId : ' ') << std::endl; + assetsEvalCode = vopretAssets.begin()[0]; + assetsFuncId = vopretAssets.begin()[1]; - if(evalCodeInOpret == EVAL_ASSETS) - { - //fprintf(stderr,"decode.[%c] assetFuncId.[%c]\n", funcId, assetFuncId); - switch( assetFuncId ) + //std::cerr << "DecodeAssetTokenOpRet() evalCodeInOpret=" << (int)evalCodeInOpret << " funcId=" << (char)(funcId ? funcId : ' ') << " assetFuncId=" << (char)(assetFuncId ? assetFuncId : ' ') << std::endl; + + if (assetsEvalCode == EVAL_ASSETS) { - case 'x': case 'o': - if (vopretStripped.size() == 2) // no data after 'evalcode assetFuncId' allowed + //fprintf(stderr,"DecodeAssetTokenOpRet() decode.[%c] assetFuncId.[%c]\n", funcId, assetFuncId); + switch (assetsFuncId) + { + case 'x': case 'o': + if (vopretAssets.size() == 2) // no data after 'evalcode assetFuncId' allowed { - return(assetFuncId); + return(assetsFuncId); } break; case 's': case 'b': case 'S': case 'B': - if (E_UNMARSHAL(vopretStripped, ss >> dummyEvalCode; ss >> dummyAssetFuncId; ss >> price; ss >> origpubkey) != 0) + if (E_UNMARSHAL(vopretAssets, ss >> dummyEvalCode; ss >> dummyAssetFuncId; ss >> price; ss >> origpubkey) != 0) { - //fprintf(stderr,"DecodeAssetTokenOpRet got price %llu\n",(long long)price); - return(assetFuncId); + //fprintf(stderr,"DecodeAssetTokenOpRet() got price %llu\n",(long long)price); + return(assetsFuncId); } break; case 'E': case 'e': - if ( E_UNMARSHAL(vopretStripped, ss >> dummyEvalCode; ss >> dummyAssetFuncId; ss >> assetid2; ss >> price; ss >> origpubkey) != 0 ) + if (E_UNMARSHAL(vopretAssets, ss >> dummyEvalCode; ss >> dummyAssetFuncId; ss >> assetid2; ss >> price; ss >> origpubkey) != 0) { - //fprintf(stderr,"DecodeAssetTokenOpRet got price %llu\n",(long long)price); + //fprintf(stderr,"DecodeAssetTokenOpRet() got price %llu\n",(long long)price); assetid2 = revuint256(assetid2); - return(assetFuncId); + return(assetsFuncId); } break; default: - fprintf(stderr,"DecodeAssetTokenOpRet: illegal assetFuncId.%02x\n", assetFuncId); + fprintf(stderr, "DecodeAssetTokenOpRet() illegal assetFuncId.%02x\n", assetsFuncId); //funcId = 0; break; + } } } + + std::cerr << "DecodeAssetTokenOpRet() no asset's payload or incorrect assets evalcode" << " funcId=" << (int)funcId << " vopretAssets.size()=" << vopretAssets.size() << " assetsEvalCode=" << assetsEvalCode << " assetsFuncId=" << assetsFuncId << std::endl; return (uint8_t)0; } @@ -358,49 +379,55 @@ bool SetAssetOrigpubkey(std::vector &origpubkey,int64_t &price,const CT { uint256 assetid,assetid2; uint8_t evalCode; - if ( tx.vout.size() > 0 && DecodeAssetTokenOpRet(tx.vout[tx.vout.size()-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey) != 0 ) + std::vector vopretNonfungibleDummy; + + if ( tx.vout.size() > 0 && DecodeAssetTokenOpRet(tx.vout[tx.vout.size()-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey, vopretNonfungibleDummy) != 0 ) return(true); else return(false); } -// Calculate sell/buy owner's source token/asset address from ask/bid tx -bool GetAssetorigaddrs(struct CCcontract_info *cp, char *userCCaddr, char *destaddr, const CTransaction& tx) +// Calculate seller/buyer's dest cc address from ask/bid tx funcid +bool GetAssetorigaddrs(struct CCcontract_info *cp, char *origCCaddr, char *origNormalAddr, const CTransaction& vintx) { - uint256 assetid,assetid2; int64_t price,nValue=0; int32_t n; uint8_t funcid; + uint256 assetid, assetid2; + int64_t price,nValue=0; + int32_t n; + uint8_t vintxFuncId; std::vector origpubkey; CScript script; uint8_t evalCode; + std::vector vopretNonfungibleDummy; - n = tx.vout.size(); - if( n == 0 || (funcid = DecodeAssetTokenOpRet(tx.vout[n-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey)) == 0 ) + n = vintx.vout.size(); + if( n == 0 || (vintxFuncId = DecodeAssetTokenOpRet(vintx.vout[n-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey, vopretNonfungibleDummy)) == 0 ) return(false); bool bGetCCaddr = false; - if (funcid == 's' || funcid == 'S') { - struct CCcontract_info *cpTokens, tokensC; - cpTokens = CCinit(&tokensC, EVAL_TOKENS); - bGetCCaddr = GetCCaddress(cpTokens, userCCaddr, pubkey2pk(origpubkey)); - //bGetCCaddr = GetTokensCCaddress(cp, CCaddr, pubkey2pk(origpubkey)); + struct CCcontract_info *cpTokens, tokensC; + cpTokens = CCinit(&tokensC, EVAL_TOKENS); + + if (vintxFuncId == 's' || vintxFuncId == 'S') { + // bGetCCaddr = GetCCaddress(cpTokens, origCCaddr, pubkey2pk(origpubkey)); + cpTokens->additionalTokensEvalcode2 = cp->additionalTokensEvalcode2; // add non-fungible if present + bGetCCaddr = GetTokensCCaddress(cpTokens, origCCaddr, pubkey2pk(origpubkey)); // tokens to single-eval token or token+nonfungible } - else if (funcid == 'b' || funcid == 'B') { - struct CCcontract_info *cpTokens, tokensC; - cpTokens = CCinit(&tokensC, EVAL_TOKENS); - bGetCCaddr = GetCCaddress(cpTokens, userCCaddr, pubkey2pk(origpubkey)); + else if (vintxFuncId == 'b' || vintxFuncId == 'B') { + cpTokens->additionalTokensEvalcode2 = cp->additionalTokensEvalcode2; // add non-fungible if present + bGetCCaddr = GetTokensCCaddress(cpTokens, origCCaddr, pubkey2pk(origpubkey)); // tokens to single-eval token or token+nonfungible } else { - std::cerr << "GetAssetorigaddrs incorrect funcid=" << (char)(funcid?funcid:' ') << std::endl; + std::cerr << "GetAssetorigaddrs incorrect vintx funcid=" << (char)(vintxFuncId?vintxFuncId:' ') << std::endl; return false; } - - if( bGetCCaddr && Getscriptaddress(destaddr, CScript() << origpubkey << OP_CHECKSIG)) + if( bGetCCaddr && Getscriptaddress(origNormalAddr, CScript() << origpubkey << OP_CHECKSIG)) return(true); else return(false); } -int64_t AssetValidateCCvin(struct CCcontract_info *cp,Eval* eval,char *CCaddr,char *origaddr,const CTransaction &tx,int32_t vini,CTransaction &vinTx) +int64_t AssetValidateCCvin(struct CCcontract_info *cp,Eval* eval,char *origCCaddr,char *origaddr,const CTransaction &tx,int32_t vini,CTransaction &vinTx) { uint256 hashBlock; uint256 assetid, assetid2; @@ -410,7 +437,7 @@ int64_t AssetValidateCCvin(struct CCcontract_info *cp,Eval* eval,char *CCaddr,ch char destaddr[64], unspendableAddr[64]; - origaddr[0] = destaddr[0] = CCaddr[0] = 0; + origaddr[0] = destaddr[0] = origCCaddr[0] = 0; uint8_t funcid = 0; if (tx.vout.size() > 0) { @@ -418,7 +445,9 @@ int64_t AssetValidateCCvin(struct CCcontract_info *cp,Eval* eval,char *CCaddr,ch int64_t tmpprice; std::vector tmporigpubkey; uint8_t evalCode; - funcid = DecodeAssetTokenOpRet(tx.vout[tx.vout.size() - 1].scriptPubKey, evalCode, assetid, assetid2, tmpprice, tmporigpubkey); + std::vector vopretNonfungibleDummy; + + funcid = DecodeAssetTokenOpRet(tx.vout[tx.vout.size() - 1].scriptPubKey, evalCode, assetid, assetid2, tmpprice, tmporigpubkey, vopretNonfungibleDummy); } if( tx.vin.size() < 2 ) @@ -427,45 +456,48 @@ int64_t AssetValidateCCvin(struct CCcontract_info *cp,Eval* eval,char *CCaddr,ch return eval->Invalid("vin1 needs to be buyvin.vout[0]"); else if( eval->GetTxUnconfirmed(tx.vin[vini].prevout.hash, vinTx,hashBlock) == 0 ) { - /* int32_t z; - for (z=31; z>=0; z--) - fprintf(stderr,"%02x",((uint8_t *)&tx.vin[vini].prevout.hash)[z]); - fprintf(stderr," vini.%d\n",vini); */ - std::cerr << "AssetValidateCCvin cannot load vintx for vin=" << vini << " vintx id=" << tx.vin[vini].prevout.hash.GetHex() << std::endl; + std::cerr << "AssetValidateCCvin() cannot load vintx for vin=" << vini << " vintx id=" << tx.vin[vini].prevout.hash.GetHex() << std::endl; return eval->Invalid("always should find CCvin, but didnt"); } - // if fillSell or cancelSell --> to spend tokens from dual-eval token-assets unspendable addr + // check source cc unspendable cc address: + // if fillSell or cancelSell --> should spend tokens from dual-eval token-assets unspendable addr else if( (funcid == 'S' || funcid == 'x') && (Getscriptaddress(destaddr, vinTx.vout[tx.vin[vini].prevout.n].scriptPubKey) == 0 || !GetTokensCCaddress(cp, unspendableAddr, GetUnspendable(cp, NULL)) || strcmp(destaddr, unspendableAddr) != 0)) { - fprintf(stderr,"AssetValidateCCvin cc addr %s is not dual token-evalcode=0x%02x asset unspendable addr %s\n", destaddr, (int)cp->evalcode, unspendableAddr); - return eval->Invalid("invalid vin AssetsCCaddr"); + fprintf(stderr,"AssetValidateCCvin() cc addr %s is not dual token-evalcode=0x%02x asset unspendable addr %s\n", destaddr, (int)cp->evalcode, unspendableAddr); + return eval->Invalid("invalid vin assets CCaddr"); } - // if fillBuy or cancelBuy --> to spend coins from asset unspendable addr + // if fillBuy or cancelBuy --> should spend coins from asset unspendable addr else if ((funcid == 'B' || funcid == 'o') && (Getscriptaddress(destaddr, vinTx.vout[tx.vin[vini].prevout.n].scriptPubKey) == 0 || !GetCCaddress(cp, unspendableAddr, GetUnspendable(cp, NULL)) || strcmp(destaddr, unspendableAddr) != 0)) { - fprintf(stderr, "AssetValidateCCvin cc addr %s is not evalcode=0x%02x asset unspendable addr %s\n", destaddr, (int)cp->evalcode, unspendableAddr); - return eval->Invalid("invalid vin AssetsCCaddr"); + fprintf(stderr, "AssetValidateCCvin() cc addr %s is not evalcode=0x%02x asset unspendable addr %s\n", destaddr, (int)cp->evalcode, unspendableAddr); + return eval->Invalid("invalid vin assets CCaddr"); } - + // end of check source unspendable cc address //else if ( vinTx.vout[0].nValue < 10000 ) // return eval->Invalid("invalid dust for buyvin"); - else if( GetAssetorigaddrs(cp, CCaddr, origaddr, vinTx) == 0 ) + // get user dest cc and normal addresses: + else if( GetAssetorigaddrs(cp, origCCaddr, origaddr, vinTx) == 0 ) return eval->Invalid("couldnt get origaddr for buyvin"); - fprintf(stderr,"AssetValidateCCvin got %.8f to origaddr.(%s)\n",(double)vinTx.vout[tx.vin[vini].prevout.n].nValue/COIN,origaddr); + + fprintf(stderr,"AssetValidateCCvin() got %.8f to origaddr.(%s)\n", (double)vinTx.vout[tx.vin[vini].prevout.n].nValue/COIN,origaddr); + if ( vinTx.vout[0].nValue == 0 ) return eval->Invalid("null value CCvin"); + return(vinTx.vout[0].nValue); } int64_t AssetValidateBuyvin(struct CCcontract_info *cp,Eval* eval,int64_t &tmpprice,std::vector &tmporigpubkey,char *CCaddr,char *origaddr,const CTransaction &tx,uint256 refassetid) { CTransaction vinTx; int64_t nValue; uint256 assetid,assetid2; uint8_t funcid, evalCode; + std::vector vopretNonfungibleDummy; + CCaddr[0] = origaddr[0] = 0; // validate locked coins on Assets vin[1] @@ -473,7 +505,7 @@ int64_t AssetValidateBuyvin(struct CCcontract_info *cp,Eval* eval,int64_t &tmppr return(0); else if ( vinTx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) return eval->Invalid("invalid normal vout0 for buyvin"); - else if ((funcid = DecodeAssetTokenOpRet(vinTx.vout[vinTx.vout.size() - 1].scriptPubKey, evalCode, assetid, assetid2, tmpprice, tmporigpubkey)) == 'b' && + else if ((funcid = DecodeAssetTokenOpRet(vinTx.vout[vinTx.vout.size() - 1].scriptPubKey, evalCode, assetid, assetid2, tmpprice, tmporigpubkey, vopretNonfungibleDummy)) == 'b' && vinTx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 ) // marker is only in 'b'? return eval->Invalid("invalid normal vout1 for buyvin"); else @@ -493,7 +525,7 @@ int64_t AssetValidateBuyvin(struct CCcontract_info *cp,Eval* eval,int64_t &tmppr int64_t AssetValidateSellvin(struct CCcontract_info *cp,Eval* eval,int64_t &tmpprice,std::vector &tmporigpubkey,char *CCaddr,char *origaddr,const CTransaction &tx,uint256 assetid) { CTransaction vinTx; int64_t nValue,assetoshis; - //fprintf(stderr,"AssetValidateSellvin\n"); + //fprintf(stderr,"AssetValidateSellvin()\n"); if ( (nValue = AssetValidateCCvin(cp, eval, CCaddr, origaddr, tx, 1, vinTx)) == 0 ) return(0); if ( (assetoshis= IsAssetvout(cp, tmpprice, tmporigpubkey, vinTx, 0, assetid)) == 0 ) @@ -508,13 +540,14 @@ bool ValidateAssetOpret(CTransaction tx, int32_t v, uint256 assetid, int64_t &pr uint256 assetidOpret, assetidOpret2; uint8_t funcid, evalCode; + std::vector vopretNonfungibleDummy; // this is just for log messages indentation fur debugging recursive calls: int32_t n = tx.vout.size(); - if ((funcid = DecodeAssetTokenOpRet(tx.vout[n - 1].scriptPubKey, evalCode, assetidOpret, assetidOpret2, price, origpubkey)) == 0) + if ((funcid = DecodeAssetTokenOpRet(tx.vout[n - 1].scriptPubKey, evalCode, assetidOpret, assetidOpret2, price, origpubkey, vopretNonfungibleDummy)) == 0) { - std::cerr << "ValidateAssetOpret() DecodeAssetTokenOpRet returned null for the opret for txid=" << tx.GetHash().GetHex() << std::endl; + std::cerr << "ValidateAssetOpret() DecodeAssetTokenOpRet returned funcId=0 for opret from txid=" << tx.GetHash().GetHex() << std::endl; return(false); } /* it is now on token level: @@ -556,22 +589,20 @@ bool ValidateAssetOpret(CTransaction tx, int32_t v, uint256 assetid, int64_t &pr } // Checks if the vout is a really Asset CC vout -// compareTotals == true, the func also validates the passed transaction itself: -// it should be either sum(cc vins) == sum(cc vouts) or the transaction is the 'tokenbase' ('c') tx int64_t IsAssetvout(struct CCcontract_info *cp, int64_t &price, std::vector &origpubkey, const CTransaction& tx, int32_t v, uint256 refassetid) { //std::cerr << "IsAssetvout() entered for txid=" << tx.GetHash().GetHex() << " v=" << v << " for assetid=" << refassetid.GetHex() << std::endl; + int32_t n = tx.vout.size(); + // just check boundaries: + if (v >= n - 1) { // just moved this up (dimxy) + std::cerr << "isAssetVout() internal err: (v >= n - 1), returning 0" << std::endl; + return(0); + } + if (tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0) // maybe check address too? dimxy: possibly no, because there are too many cases with different addresses here { - int32_t n = tx.vout.size(); - // just check boundaries: - if (v >= n - 1) { // just moved this up (dimxy) - std::cerr << "isAssetVout() internal err: (v >= n - 1), returning 0" << std::endl; - return(0); - } - // moved opret checking to this new reusable func (dimxy): const bool valOpret = ValidateAssetOpret(tx, v, refassetid, price, origpubkey); //std::cerr << "IsAssetvout() ValidateAssetOpret returned=" << std::boolalpha << valOpret << " for txid=" << tx.GetHash().GetHex() << " for assetid=" << refassetid.GetHex() << std::endl; @@ -627,12 +658,9 @@ bool AssetCalcAmounts(struct CCcontract_info *cpAssets, int64_t &inputs, int64_t } } - for (int32_t i = 0; i < numvouts; i++) + for (int32_t i = 0; i < numvouts-1; i++) { - // Note: we pass in here 'false' because we don't need to call AssetExactAmounts() recursively from IsAssetvout - // indeed, in this case we'll be checking this tx again assetoshis = IsAssetvout(cpAssets, tmpprice, tmporigpubkey, tx, i, assetid); - if (assetoshis != 0) { std::cerr << "AssetCalcAmounts() vout i=" << i << " assetoshis=" << assetoshis << std::endl; @@ -643,12 +671,6 @@ bool AssetCalcAmounts(struct CCcontract_info *cpAssets, int64_t &inputs, int64_t //std::cerr << "AssetCalcAmounts() inputs=" << inputs << " outputs=" << outputs << " for txid=" << tx.GetHash().GetHex() << std::endl; /* we do not verify inputs == outputs here, - it's done in Tokens: - if (inputs != outputs) { - if (tx.GetHash() != assetid) { - std::cerr << "AssetCalcAmounts() unequal inputs=" << inputs << " vs outputs=" << outputs << " for txid=" << tx.GetHash().GetHex() << std::endl; - return (!eval) ? false : eval->Invalid("assets cc inputs != cc outputs"); - } - } */ + it's now done in Tokens */ return(true); } diff --git a/src/cc/CCassetstx.cpp b/src/cc/CCassetstx.cpp index 9d83beb2c..c057237f9 100644 --- a/src/cc/CCassetstx.cpp +++ b/src/cc/CCassetstx.cpp @@ -14,9 +14,9 @@ ******************************************************************************/ #include "CCassets.h" -//#include "CCtokens.h" - +#include "CCtokens.h" +/* use AddTokenCCInputs instead int64_t AddAssetInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,uint256 assetid,int64_t total,int32_t maxinputs) { char coinaddr[64],destaddr[64]; int64_t threshold,nValue,price,totalinputs = 0; uint256 txid,hashBlock; std::vector origpubkey; CTransaction vintx; int32_t j,vout,n = 0; @@ -64,25 +64,19 @@ int64_t AddAssetInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK //std::cerr << "AddAssetInputs() found totalinputs=" << totalinputs << std::endl; return(totalinputs); } - +*/ UniValue AssetOrders(uint256 refassetid) { static uint256 zero; UniValue result(UniValue::VARR); - std::vector > unspentOutputsTokens, unspentOutputsAssets; - - struct CCcontract_info *cpTokens, tokensC; - struct CCcontract_info *cpAssets, assetsC; - - cpTokens = CCinit(&tokensC, EVAL_TOKENS); - cpAssets = CCinit(&assetsC, EVAL_ASSETS); auto addOrders = [&](struct CCcontract_info *cp, std::vector >::const_iterator it) { uint256 txid, hashBlock, assetid, assetid2; int64_t price; std::vector origpubkey; + std::vector vopretNonfungible; CTransaction vintx; uint8_t funcid, evalCode; char numstr[32], funcidstr[16], origaddr[64], assetidstr[65]; @@ -93,7 +87,7 @@ UniValue AssetOrders(uint256 refassetid) { // for logging: funcid = DecodeAssetOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey); //std::cerr << "addOrders() vintx.vout.size()=" << vintx.vout.size() << " funcid=" << (char)(funcid ? funcid : ' ') << " assetid=" << assetid.GetHex() << std::endl; - if (vintx.vout.size() > 0 && (funcid = DecodeAssetTokenOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey)) != 0) + if (vintx.vout.size() > 0 && (funcid = DecodeAssetTokenOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey, vopretNonfungible)) != 0) { if (refassetid != zero && assetid != refassetid) { @@ -163,25 +157,35 @@ UniValue AssetOrders(uint256 refassetid) } }; + std::vector > unspentOutputsTokens, unspentOutputsCoins; + struct CCcontract_info *cpAssets, assetsC; + + cpAssets = CCinit(&assetsC, EVAL_ASSETS); char assetsUnspendableAddr[64]; GetCCaddress(cpAssets, assetsUnspendableAddr, GetUnspendable(cpAssets, NULL)); - SetCCunspents(unspentOutputsAssets, assetsUnspendableAddr /*(char *)cpTokens->unspendableCCaddr*/); + SetCCunspents(unspentOutputsCoins, assetsUnspendableAddr); - char tokensUnspendableAddr[64]; - GetTokensCCaddress(cpAssets, tokensUnspendableAddr, GetUnspendable(cpAssets, NULL)); - SetCCunspents(unspentOutputsAssets, tokensUnspendableAddr /*(char *)cpAssets->unspendableCCaddr*/); + char assetsTokensUnspendableAddr[64]; + std::vector vopretNonfungible; + GetNonfungibleData(refassetid, vopretNonfungible); + if (vopretNonfungible.size() > 0) + cpAssets->additionalTokensEvalcode2 = vopretNonfungible.begin()[0]; + GetTokensCCaddress(cpAssets, assetsTokensUnspendableAddr, GetUnspendable(cpAssets, NULL)); + SetCCunspents(unspentOutputsTokens, assetsTokensUnspendableAddr); - for (std::vector >::const_iterator itTokens = unspentOutputsTokens.begin(); + // tokenasks: + for (std::vector >::const_iterator itCoins = unspentOutputsCoins.begin(); + itCoins != unspentOutputsCoins.end(); + itCoins++) + addOrders(cpAssets, itCoins); + + // tokenbids: + for (std::vector >::const_iterator itTokens = unspentOutputsTokens.begin(); itTokens != unspentOutputsTokens.end(); itTokens++) - addOrders(cpTokens, itTokens); + addOrders(cpAssets, itTokens); - for (std::vector >::const_iterator itAssets = unspentOutputsAssets.begin(); - itAssets != unspentOutputsAssets.end(); - itAssets++) - addOrders(cpAssets, itAssets); - return(result); } @@ -328,14 +332,14 @@ std::string CreateBuyOffer(int64_t txfee, int64_t bidamount, uint256 assetid, in return (""); } - CPubKey unspendablePubkey = GetUnspendable(cpAssets, 0); - mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS, bidamount, unspendablePubkey)); + CPubKey unspendableAssetsPubkey = GetUnspendable(cpAssets, 0); + mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS, bidamount, unspendableAssetsPubkey)); mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS, txfee, mypk)); std::vector voutTokenPubkeys; // should be empty - no token vouts return(FinalizeCCTx(0, cpAssets, mtx, mypk, txfee, - EncodeTokenOpRet(assetid, voutTokenPubkeys, - EncodeAssetOpRet('b', zeroid, pricetotal, Mypubkey())))); + EncodeTokenOpRet(assetid, voutTokenPubkeys, // TODO: actually this tx is not 'tokens', maybe it is better not to have token opret here but only asset opret. + EncodeAssetOpRet('b', zeroid, pricetotal, Mypubkey())))); // But still such token opret should not make problems because no token eval in these vouts } CCerror = strprintf("no coins found to make buy offer"); return(""); @@ -348,7 +352,6 @@ std::string CreateSell(int64_t txfee,int64_t askamount,uint256 assetid,int64_t p CPubKey mypk; uint64_t mask; int64_t inputs, CCchange; - CScript opret; struct CCcontract_info *cpAssets, assetsC; struct CCcontract_info *cpTokens, tokensC; @@ -359,7 +362,8 @@ std::string CreateSell(int64_t txfee,int64_t askamount,uint256 assetid,int64_t p return(""); } - cpAssets = CCinit(&assetsC, EVAL_ASSETS); // NOTE: this is for signing + cpAssets = CCinit(&assetsC, EVAL_ASSETS); // NOTE: for signing + if (txfee == 0) txfee = 10000; @@ -367,10 +371,11 @@ std::string CreateSell(int64_t txfee,int64_t askamount,uint256 assetid,int64_t p mypk = pubkey2pk(Mypubkey()); if (AddNormalinputs(mtx, mypk, 2*txfee, 3) > 0) { + std::vector vopretNonfungible; mask = ~((1LL << mtx.vin.size()) - 1); - // add single-eval tokens: - cpTokens = CCinit(&tokensC, EVAL_TOKENS); // NOTE: tokens is here - if ((inputs = AddTokenCCInputs(cpTokens, mtx, mypk, assetid, askamount, 60)) > 0) + // add single-eval tokens (or non-fungible tokens): + cpTokens = CCinit(&tokensC, EVAL_TOKENS); // NOTE: adding inputs only from EVAL_TOKENS cc + if ((inputs = AddTokenCCInputs(cpTokens, mtx, mypk, assetid, askamount, 60, vopretNonfungible)) > 0) { if (inputs < askamount) { //was: askamount = inputs; @@ -379,20 +384,26 @@ std::string CreateSell(int64_t txfee,int64_t askamount,uint256 assetid,int64_t p return (""); } - CPubKey unspendablePubkey = GetUnspendable(cpAssets, NULL); - mtx.vout.push_back(MakeTokensCC1vout(EVAL_ASSETS, askamount, unspendablePubkey)); - mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS, txfee, mypk)); //marker + // if this is non-fungible tokens: + if( !vopretNonfungible.empty() ) + // set its evalcode + cpAssets->additionalTokensEvalcode2 = vopretNonfungible.begin()[0]; + + CPubKey unspendableAssetsPubkey = GetUnspendable(cpAssets, NULL); + mtx.vout.push_back(MakeTokensCC1vout(EVAL_ASSETS, cpAssets->additionalTokensEvalcode2, askamount, unspendableAssetsPubkey)); + mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS, txfee, mypk)); //marker (seems, it is not for tokenorders) if (inputs > askamount) CCchange = (inputs - askamount); if (CCchange != 0) - mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, CCchange, mypk)); // change to single-eval token vout + // change to single-eval or non-fungible token vout (although for non-fungible token change currently is not possible) + mtx.vout.push_back(MakeTokensCC1vout((cpAssets->additionalTokensEvalcode2) ? cpAssets->additionalTokensEvalcode2 : EVAL_TOKENS, CCchange, mypk)); std::vector voutTokenPubkeys; - voutTokenPubkeys.push_back(unspendablePubkey); + voutTokenPubkeys.push_back(unspendableAssetsPubkey); - opret = EncodeTokenOpRet(assetid, voutTokenPubkeys, - EncodeAssetOpRet('s', zeroid, pricetotal, Mypubkey())); - return(FinalizeCCTx(mask,cpAssets, mtx, mypk, txfee, opret)); + return FinalizeCCTx(mask, cpTokens, mtx, mypk, txfee, + EncodeTokenOpRet(assetid, voutTokenPubkeys, vopretNonfungible, + EncodeAssetOpRet('s', zeroid, pricetotal, Mypubkey()))); } else { fprintf(stderr, "need some tokens to place ask\n"); @@ -430,7 +441,7 @@ std::string CreateSwap(int64_t txfee,int64_t askamount,uint256 assetid,uint256 a if (AddNormalinputs(mtx, mypk, txfee, 3) > 0) { mask = ~((1LL << mtx.vin.size()) - 1); - if ((inputs = AddAssetInputs(cp, mtx, mypk, assetid, askamount, 60)) > 0) + /*if ((inputs = AddAssetInputs(cp, mtx, mypk, assetid, askamount, 60)) > 0) { ////////////////////////// NOT IMPLEMENTED YET///////////////////////////////// if (inputs < askamount) { @@ -458,13 +469,13 @@ std::string CreateSwap(int64_t txfee,int64_t askamount,uint256 assetid,uint256 a else { opret = EncodeTokenOpRet(assetid, voutTokenPubkeys, EncodeAssetOpRet('e', assetid2, pricetotal, Mypubkey())); - } + } ////////////////////////// NOT IMPLEMENTED YET///////////////////////////////// return(FinalizeCCTx(mask,cp,mtx,mypk,txfee,opret)); } else { fprintf(stderr, "need some assets to place ask\n"); - } + } */ } else { // dimxy added 'else', because it was misleading message before fprintf(stderr,"need some native coins to place ask\n"); @@ -494,12 +505,13 @@ std::string CancelBuyOffer(int64_t txfee,uint256 assetid,uint256 bidtxid) mask = ~((1LL << mtx.vin.size()) - 1); if (GetTransaction(bidtxid, vintx, hashBlock, false) != 0) { + std::vector vopretNonfungible; + bidamount = vintx.vout[0].nValue; mtx.vin.push_back(CTxIn(bidtxid, 0, CScript())); // coins in Assets - if((funcid=DecodeAssetTokenOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, dummyEvalCode, dummyAssetid, dummyAssetid2, dummyPrice, dummyOrigpubkey))!=0) + if((funcid=DecodeAssetTokenOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, dummyEvalCode, dummyAssetid, dummyAssetid2, dummyPrice, dummyOrigpubkey, vopretNonfungible))!=0) { - if (funcid == 's') mtx.vin.push_back(CTxIn(bidtxid, 1, CScript())); // spend marker if funcid='b' else if (funcid=='S') mtx.vin.push_back(CTxIn(bidtxid, 3, CScript())); // spend marker if funcid='B' } @@ -510,7 +522,7 @@ std::string CancelBuyOffer(int64_t txfee,uint256 assetid,uint256 bidtxid) std::vector voutTokenPubkeys; // should be empty, no token vouts return(FinalizeCCTx(mask, cpAssets, mtx, mypk, txfee, - EncodeTokenOpRet(assetid, voutTokenPubkeys, + EncodeTokenOpRet(assetid, voutTokenPubkeys, vopretNonfungible, EncodeAssetOpRet('o', zeroid, 0, Mypubkey())))); } } @@ -523,8 +535,12 @@ std::string CancelSell(int64_t txfee,uint256 assetid,uint256 asktxid) CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); CTransaction vintx; uint64_t mask; uint256 hashBlock; int64_t askamount; - CPubKey mypk; struct CCcontract_info *cpTokens, *cpAssets, tokensC, assetsC; - uint8_t funcid,dummyEvalCode; uint256 dummyAssetid, dummyAssetid2; int64_t dummyPrice; std::vector dummyOrigpubkey; + CPubKey mypk; + struct CCcontract_info *cpTokens, *cpAssets, tokensC, assetsC; + uint8_t funcid, dummyEvalCode; + uint256 dummyAssetid, dummyAssetid2; + int64_t dummyPrice; + std::vector dummyOrigpubkey; cpAssets = CCinit(&assetsC, EVAL_ASSETS); @@ -538,27 +554,27 @@ std::string CancelSell(int64_t txfee,uint256 assetid,uint256 asktxid) mask = ~((1LL << mtx.vin.size()) - 1); if (GetTransaction(asktxid, vintx, hashBlock, false) != 0) { + std::vector vopretNonfungible; askamount = vintx.vout[0].nValue; mtx.vin.push_back(CTxIn(asktxid, 0, CScript())); - if ((funcid=DecodeAssetTokenOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, dummyEvalCode, dummyAssetid, dummyAssetid2, dummyPrice, dummyOrigpubkey))!=0) + if ((funcid=DecodeAssetTokenOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, dummyEvalCode, dummyAssetid, dummyAssetid2, dummyPrice, dummyOrigpubkey, vopretNonfungible))!=0) { - if (funcid == 's') mtx.vin.push_back(CTxIn(asktxid, 1, CScript())); // marker if funcid='s' - else if (funcid=='S') mtx.vin.push_back(CTxIn(asktxid, 3, CScript())); // marker if funcid='S' + if (funcid == 's') + mtx.vin.push_back(CTxIn(asktxid, 1, CScript())); // marker if funcid='s' + else if (funcid=='S') + mtx.vin.push_back(CTxIn(asktxid, 3, CScript())); // marker if funcid='S' } - mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, askamount, mypk)); // one-eval token vout + if (vopretNonfungible.size() > 0) + cpAssets->additionalTokensEvalcode2 = vopretNonfungible.begin()[0]; + + mtx.vout.push_back(MakeTokensCC1vout(cpAssets->additionalTokensEvalcode2 == 0 ? EVAL_TOKENS : cpAssets->additionalTokensEvalcode2, askamount, mypk)); // one-eval token vout mtx.vout.push_back(CTxOut(txfee,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); std::vector voutTokenPubkeys; voutTokenPubkeys.push_back(mypk); - /* char myCCaddr[65]; - uint8_t myPrivkey[32]; - Myprivkey(myPrivkey); - cpAssets = CCinit(&assetsC, EVAL_ASSETS); - GetCCaddress(cpAssets, myCCaddr, mypk); */ - // this is only for unspendable addresses: //CCaddr2set(cpTokens, EVAL_ASSETS, mypk, myPrivkey, myCCaddr); //do we need this? Seems FinalizeCCTx can attach to any evalcode cc addr by calling Getscriptaddress @@ -572,7 +588,7 @@ std::string CancelSell(int64_t txfee,uint256 assetid,uint256 asktxid) CCaddr2set(cpAssets, EVAL_TOKENS, unspendableAssetsPk, unspendableAssetsPrivkey, unspendableAssetsAddr); return(FinalizeCCTx(mask, cpAssets, mtx, mypk, txfee, - EncodeTokenOpRet(assetid, voutTokenPubkeys, + EncodeTokenOpRet(assetid, voutTokenPubkeys, vopretNonfungible, EncodeAssetOpRet('x', zeroid, 0, Mypubkey())))); } } @@ -614,8 +630,9 @@ std::string FillBuyOffer(int64_t txfee,uint256 assetid,uint256 bidtxid,int64_t f SetAssetOrigpubkey(origpubkey, origprice, vintx); mtx.vin.push_back(CTxIn(bidtxid, bidvout, CScript())); // Coins on Assets unspendable - - if ((inputs = AddTokenCCInputs(cpTokens, mtx, mypk, assetid, fillamount, 60)) > 0) + + std::vector vopretNonfungible; + if ((inputs = AddTokenCCInputs(cpTokens, mtx, mypk, assetid, fillamount, 60, vopretNonfungible)) > 0) { if (inputs < fillamount) { std::cerr << "FillBuyOffer(): insufficient tokens to fill buy offer" << std::endl; @@ -624,6 +641,10 @@ std::string FillBuyOffer(int64_t txfee,uint256 assetid,uint256 bidtxid,int64_t f } SetBidFillamounts(paid_amount, remaining_required, bidamount, fillamount, origprice); + + uint8_t additionalTokensEvalcode2 = 0; + if (vopretNonfungible.size() > 0) + additionalTokensEvalcode2 = vopretNonfungible.begin()[0]; if (inputs > fillamount) CCchange = (inputs - fillamount); @@ -634,13 +655,13 @@ std::string FillBuyOffer(int64_t txfee,uint256 assetid,uint256 bidtxid,int64_t f mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS, bidamount - paid_amount, unspendableAssetsPk)); // vout0 coins remainder mtx.vout.push_back(CTxOut(paid_amount,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); // vout1 coins to normal - mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, fillamount, pubkey2pk(origpubkey))); // vout2 single-eval tokens sent to the buyer - mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS,txfee,origpubkey)); // vout3 marker to origpubkey + mtx.vout.push_back(MakeTokensCC1vout(additionalTokensEvalcode2 == 0 ? EVAL_TOKENS : additionalTokensEvalcode2, fillamount, pubkey2pk(origpubkey))); // vout2 single-eval tokens sent to the originator + mtx.vout.push_back(MakeCC1vout(EVAL_ASSETS, txfee, origpubkey)); // vout3 marker to origpubkey if (CCchange != 0) mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, CCchange, mypk)); // vout4 change in single-eval tokens - fprintf(stderr,"FillBuyOffer remaining %llu -> origpubkey\n", (long long)remaining_required); + fprintf(stderr,"FillBuyOffer() remaining %llu -> origpubkey\n", (long long)remaining_required); char unspendableAssetsAddr[64]; cpAssets = CCinit(&assetsC, EVAL_ASSETS); @@ -653,8 +674,8 @@ std::string FillBuyOffer(int64_t txfee,uint256 assetid,uint256 bidtxid,int64_t f std::vector voutTokenPubkeys; voutTokenPubkeys.push_back(pubkey2pk(origpubkey)); - return(FinalizeCCTx(mask,cpTokens,mtx,mypk,txfee, - EncodeTokenOpRet(assetid, voutTokenPubkeys, + return(FinalizeCCTx(mask, cpTokens, mtx, mypk, txfee, + EncodeTokenOpRet(assetid, voutTokenPubkeys, vopretNonfungible, EncodeAssetOpRet('B', zeroid, remaining_required, origpubkey)))); } else return("dont have any assets to fill bid"); } @@ -691,15 +712,21 @@ std::string FillSell(int64_t txfee, uint256 assetid, uint256 assetid2, uint256 a return(""); } + std::vector vopretNonfungible; + uint8_t additionalTokensEvalcode2 = 0; + GetNonfungibleData(assetid, vopretNonfungible); + if (vopretNonfungible.size() > 0) + additionalTokensEvalcode2 = vopretNonfungible.begin()[0]; + cpAssets = CCinit(&assetsC, EVAL_ASSETS); if (txfee == 0) txfee = 10000; mypk = pubkey2pk(Mypubkey()); - if (AddNormalinputs(mtx, mypk, 2*txfee, 3) > 0) - { - mask = ~((1LL << mtx.vin.size()) - 1); + //if (AddNormalinputs(mtx, mypk, 2*txfee, 3) > 0) + //{ + //mask = ~((1LL << mtx.vin.size()) - 1); if (GetTransaction(asktxid, vintx, hashBlock, false) != 0) { orig_assetoshis = vintx.vout[askvout].nValue; @@ -707,13 +734,12 @@ std::string FillSell(int64_t txfee, uint256 assetid, uint256 assetid2, uint256 a dprice = (double)total_nValue / orig_assetoshis; paid_nValue = dprice * fillunits; - mtx.vin.push_back(CTxIn(asktxid, askvout, CScript())); // NOTE: this is the reference to tokens -> send cpTokens for signing into FinalizeCCTx! - - if (assetid2 != zeroid) - inputs = AddAssetInputs(cpAssets, mtx, mypk, assetid2, paid_nValue, 60); // not implemented yet + if (assetid2 != zeroid) { + inputs = 0; // = AddAssetInputs(cpAssets, mtx, mypk, assetid2, paid_nValue, 60); // not implemented yet + } else { - inputs = AddNormalinputs(mtx, mypk, paid_nValue, 60); + inputs = AddNormalinputs(mtx, mypk, 2 * txfee + paid_nValue, 60); // Better to use single AddNormalinputs() to allow payment if user has only single utxo with normal funds mask = ~((1LL << mtx.vin.size()) - 1); } if (inputs > 0) @@ -723,7 +749,10 @@ std::string FillSell(int64_t txfee, uint256 assetid, uint256 assetid2, uint256 a CCerror = strprintf("insufficient coins to fill sell"); return (""); } - + + // cc vin should be after normal vin + mtx.vin.push_back(CTxIn(asktxid, askvout, CScript())); + if (assetid2 != zeroid) SetSwapFillamounts(received_assetoshis, remaining_nValue, orig_assetoshis, paid_nValue, total_nValue); //not implemented correctly yet else @@ -732,11 +761,11 @@ std::string FillSell(int64_t txfee, uint256 assetid, uint256 assetid2, uint256 a if (assetid2 != zeroid && inputs > paid_nValue) CCchange = (inputs - paid_nValue); - mtx.vout.push_back(MakeTokensCC1vout(EVAL_ASSETS, orig_assetoshis - received_assetoshis, GetUnspendable(cpAssets, NULL))); // vout.0 tokens remainder to unspendable cc addr - mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, received_assetoshis, mypk)); //vout.1 purchased tokens to self single-eval addr + // vout.0 tokens remainder to unspendable cc addr: + mtx.vout.push_back(MakeTokensCC1vout(EVAL_ASSETS, additionalTokensEvalcode2, orig_assetoshis - received_assetoshis, GetUnspendable(cpAssets, NULL))); + //vout.1 purchased tokens to self token single-eval or dual-eval token+nonfungible cc addr: + mtx.vout.push_back(MakeTokensCC1vout(additionalTokensEvalcode2 == 0 ? EVAL_TOKENS : additionalTokensEvalcode2, received_assetoshis, mypk)); - // NOTE: no marker here - if (assetid2 != zeroid) { std::cerr << "FillSell() WARNING: asset swap not implemented yet! (paid_nValue)" << std::endl; // TODO: change MakeCC1vout appropriately when implementing: @@ -768,14 +797,16 @@ std::string FillSell(int64_t txfee, uint256 assetid, uint256 assetid2, uint256 a std::vector voutTokenPubkeys; voutTokenPubkeys.push_back(mypk); + cpAssets->additionalTokensEvalcode2 = additionalTokensEvalcode2; + return(FinalizeCCTx(mask, cpAssets, mtx, mypk, txfee, - EncodeTokenOpRet(assetid, voutTokenPubkeys, + EncodeTokenOpRet(assetid, voutTokenPubkeys, vopretNonfungible, EncodeAssetOpRet(assetid2 != zeroid ? 'E' : 'S', assetid2, remaining_nValue, origpubkey)))); } else { CCerror = strprintf("filltx not enough utxos"); fprintf(stderr,"%s\n", CCerror.c_str()); } } - } + //} return(""); } diff --git a/src/cc/CCcustom.cpp b/src/cc/CCcustom.cpp index 8e878d37d..d2cb811cd 100644 --- a/src/cc/CCcustom.cpp +++ b/src/cc/CCcustom.cpp @@ -290,6 +290,9 @@ int32_t CClib_initcp(struct CCcontract_info *cp,uint8_t evalcode) struct CCcontract_info *CCinit(struct CCcontract_info *cp, uint8_t evalcode) { + // important to clear because not all members are always initialized! + memset(cp, '\0', sizeof(*cp)); + cp->evalcode = evalcode; switch ( evalcode ) { diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index 4da696547..1cb141a16 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -89,6 +89,7 @@ struct CCcontract_info { // this is for spending from 'unspendable' CC address uint8_t evalcode; + uint8_t additionalTokensEvalcode2; // this is for making three-eval-token vouts (EVAL_TOKENS + evalcode + additionalEvalcode2) char unspendableCCaddr[64], CChexstr[72], normaladdr[64]; uint8_t CCpriv[32]; @@ -103,7 +104,7 @@ struct CCcontract_info // this is for spending from two additional 'unspendable' CC addresses of other eval codes // (that is, for spending from several cc contract 'unspendable' addresses): - uint8_t evalcode2, evalcode3; + uint8_t unspendableEvalcode2, unspendableEvalcode3; // changed evalcodeN to unspendableEvalcodeN for not mixing up with additionalEvalcodeN char unspendableaddr2[64], unspendableaddr3[64]; uint8_t unspendablepriv2[32], unspendablepriv3[32]; CPubKey unspendablepk2, unspendablepk3; @@ -160,17 +161,19 @@ uint256 OraclesBatontxid(uint256 oracletxid,CPubKey pk); //int64_t AddAssetInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,uint256 assetid,int64_t total,int32_t maxinputs); int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, CPubKey pk, uint256 tokenid, int64_t total, int32_t maxinputs); +int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, CPubKey pk, uint256 tokenid, int64_t total, int32_t maxinputs, std::vector &vopretNonfungible); int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *cp, Eval* eval, const CTransaction& tx, int32_t v, uint256 reftokenid); bool DecodeHexTx(CTransaction& tx, const std::string& strHexTx); -CScript EncodeAssetOpRet(uint8_t assetFuncId, uint256 assetid2, int64_t price, std::vector origpubkey); -//bool DecodeAssetCreateOpRet(const CScript &scriptPubKey, std::vector &origpubkey, std::string &name, std::string &description); -uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &evalCodeInOpret, uint256 &tokenid, uint256 &assetid2, int64_t &price, std::vector &origpubkey); +CScript EncodeTokenCreateOpRet(uint8_t funcid, std::vector origpubkey, std::string name, std::string description, std::vector vopretNonfungible); +CScript EncodeTokenOpRet(uint8_t tokenFuncId, uint8_t evalCodeInOpret, uint256 tokenid, std::vector voutPubkeys, CScript payload); //old version CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, CScript payload); -CScript EncodeTokenOpRet(uint8_t tokenFuncId, uint8_t evalCodeInOpret, uint256 tokenid, std::vector voutPubkeys, CScript payload); +CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, std::vector vpayloadNonfungible, CScript payload); uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey, std::vector &origpubkey, std::string &name, std::string &description); +uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey, std::vector &origpubkey, std::string &name, std::string &description, std::vector &vopretNonfungible); uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCode, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopretExtra); +uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCode, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopret1, std::vector &vopret2); uint8_t DecodeOraclesData(const CScript &scriptPubKey,uint256 &oracletxid,uint256 &batontxid,CPubKey &pk,std::vector &data); int32_t oracle_format(uint256 *hashp,int64_t *valp,char *str,uint8_t fmt,uint8_t *data,int32_t offset,int32_t datalen); @@ -193,12 +196,14 @@ CC* GetCryptoCondition(CScript const& scriptSig); void CCaddr2set(struct CCcontract_info *cp,uint8_t evalcode,CPubKey pk,uint8_t *priv,char *coinaddr); void CCaddr3set(struct CCcontract_info *cp,uint8_t evalcode,CPubKey pk,uint8_t *priv,char *coinaddr); void CCaddr1of2set(struct CCcontract_info *cp, CPubKey pk1, CPubKey pk2, char *coinaddr); - CTxOut MakeTokensCC1of2vout(uint8_t evalcode, CAmount nValue, CPubKey pk1, CPubKey pk2); +CTxOut MakeTokensCC1of2vout(uint8_t evalcode, uint8_t evalcode2, CAmount nValue, CPubKey pk1, CPubKey pk2); CTxOut MakeTokensCC1vout(uint8_t evalcode, CAmount nValue, CPubKey pk); +CTxOut MakeTokensCC1vout(uint8_t evalcode, uint8_t evalcode2, CAmount nValue, CPubKey pk); +CC *MakeTokensCCcond1of2(uint8_t evalcode, uint8_t evalcode2, CPubKey pk1, CPubKey pk2); CC *MakeTokensCCcond1of2(uint8_t evalcode, CPubKey pk1, CPubKey pk2); CC *MakeTokensCCcond1(uint8_t evalcode, CPubKey pk); - +CC *MakeTokensCCcond1(uint8_t evalcode, uint8_t evalcode2, CPubKey pk); bool GetTokensCCaddress(struct CCcontract_info *cp, char *destaddr, CPubKey pk); bool GetTokensCCaddress1of2(struct CCcontract_info *cp, char *destaddr, CPubKey pk, CPubKey pk2); void CCaddrTokens1of2set(struct CCcontract_info *cp, CPubKey pk1, CPubKey pk2, char *coinaddr); @@ -245,4 +250,29 @@ void vcalc_sha256(char deprecated[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uin bits256 bits256_doublesha256(char *deprecated,uint8_t *data,int32_t datalen); UniValue ValueFromAmount(const CAmount& amount); + +// bitcoin LogPrintStr with category "-debug" cmdarg support for C++ ostringstream: +#define CCLOG_INFO 0 +#define CCLOG_DEBUG1 1 +#define CCLOG_DEBUG2 2 +#define CCLOG_DEBUG3 3 +template +inline void CCLogPrintStream(char *category, int level, T print_to_stream) +{ + std::ostringstream stream; + print_to_stream(stream); + if (level < 0) + level = 0; + if (level > 3) + level = 3; + for (int i = 0; i < level; i++) + if (LogAcceptCategory((std::string(category) + (level > 0 ? std::string("-") + std::to_string(level) : std::string(""))).c_str())) { + LogPrintStr(stream.str()); + break; + } +} + +#define LOGSTREAM(category, level, logoperator) CCLogPrintStream( category, level, [=](std::ostringstream &stream) {logoperator;} ) + + #endif diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index d7db32b99..23a4fda50 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -43,15 +43,25 @@ // NOTE: this inital tx won't be used by other contract // for tokens to be used there should be at least one 't' tx with other contract's custom opret -CScript EncodeTokenCreateOpRet(uint8_t funcid,std::vector origpubkey,std::string name,std::string description) +CScript EncodeTokenCreateOpRet(uint8_t funcid, std::vector origpubkey, std::string name, std::string description, std::vector vopretNonfungible ) { - CScript opret; uint8_t evalcode = EVAL_TOKENS; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << origpubkey << name << description); + CScript opret; + uint8_t evalcode = EVAL_TOKENS; + funcid = 'c'; // override the param + + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << origpubkey << name << description; \ + if(!vopretNonfungible.empty()) ss << vopretNonfungible ); return(opret); } // this is for other contracts which use tokens and build customized extra payloads to token's opret: CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, CScript payload) +{ + std::vector vpayloadNonfungibleEmpty; + return EncodeTokenOpRet(tokenid, voutPubkeys, vpayloadNonfungibleEmpty, payload); +} + +CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, std::vector vpayloadNonfungible, CScript payload) { CScript opret; uint8_t tokenFuncId = 't'; @@ -60,17 +70,20 @@ CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, CScr tokenid = revuint256(tokenid); uint8_t ccType = 0; - if (voutPubkeys.size() >= 1 && voutPubkeys.size() <= 2) + if (voutPubkeys.size() >= 0 && voutPubkeys.size() <= 2) ccType = voutPubkeys.size(); + else { + LOGSTREAM("tokens", CCLOG_INFO, stream << "EncodeTokenOpRet voutPubkeys.size()=" << voutPubkeys.size() << " not supported" << std::endl); + } std::vector vpayload; GetOpReturnData(payload, vpayload); - opret << OP_RETURN << E_MARSHAL(ss << evalCodeInOpret << tokenFuncId << tokenid << ccType; \ - if (ccType >= 1) ss << voutPubkeys[0]; \ - if (ccType == 2) ss << voutPubkeys[1]; \ - if (vpayload.size() > 0) ss << vpayload;); - + opret << OP_RETURN << E_MARSHAL(ss << evalCodeInOpret << tokenFuncId << tokenid << ccType; \ + if (ccType >= 1) ss << voutPubkeys[0]; \ + if (ccType == 2) ss << voutPubkeys[1]; \ + if (vpayloadNonfungible.size() > 0) ss << vpayloadNonfungible; \ + if (vpayload.size() > 0) ss << vpayload); // "error 64: scriptpubkey": // if (payload.size() > 0) @@ -96,21 +109,50 @@ CScript EncodeTokenOpRet(uint8_t tokenFuncId, uint8_t evalCodeInOpret, uint256 t return EncodeTokenOpRet(tokenid, voutPubkeys, payload); } -uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey,std::vector &origpubkey,std::string &name,std::string &description) +// overload for fungible: +uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey, std::vector &origpubkey, std::string &name, std::string &description) { + std::vector vopretNonfungibleDummy; + return DecodeTokenCreateOpRet(scriptPubKey, origpubkey, name, description, vopretNonfungibleDummy); +} + +uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey,std::vector &origpubkey,std::string &name,std::string &description, std::vector &vopretNonfungible) { std::vector vopret; uint8_t dummyEvalcode, funcid, *script; GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); + if ( script != 0 && vopret.size() > 2 && script[0] == EVAL_TOKENS && script[1] == 'c' ) { - if ( E_UNMARSHAL(vopret, ss >> dummyEvalcode; ss >> funcid; ss >> origpubkey; ss >> name; ss >> description) != 0 ) + if( E_UNMARSHAL(vopret, ss >> dummyEvalcode; ss >> funcid; ss >> origpubkey; ss >> name; ss >> description; \ + // we suppose in 'c' opret it might be only non-fungible payload and not any assets/heir/etc payloads + if(!ss.eof()) ss >> vopretNonfungible ) ) return(funcid); } return (uint8_t)0; } -uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCode, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopretExtra) +// overload for compatibility allows only usual fungible tokens: +// warning: it makes vopret marshalling to CScript because this is what caller would expect +uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCode, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopretExtra) { + std::vector vopret1, vopret2; + uint8_t funcId = DecodeTokenOpRet(scriptPubKey, evalCode, tokenid, voutPubkeys, vopret1, vopret2); + + CScript opretExtra; + vopretExtra.clear(); + + // make marshalling for compatibility + // callers of this func expect length of full array at the beginning (and they will make 'vopretStripped' from vopretExtra) + if (vopret2.empty()) + opretExtra << OP_RETURN << E_MARSHAL(ss << vopret1); // if first opret (or no oprets) + else + opretExtra << OP_RETURN << E_MARSHAL(ss << vopret2); // if both oprets present, return assets/heir/gateways/... opret (dump non-fungible opret) + + GetOpReturnData(opretExtra, vopretExtra); + return funcId; +} + +uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopret1, std::vector &vopret2) { std::vector vopret, extra, dummyPubkey; uint8_t funcId=0, *script, dummyEvalCode, dummyFuncId, ccType; @@ -121,32 +163,39 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCode, uint256 script = (uint8_t *)vopret.data(); tokenid = zeroid; - if (script != 0 && vopret.size() > 2) + if (script != NULL && vopret.size() > 2) { // NOTE: if parse error occures, parse might not be able to set error. It is safer to treat that it was eof if it is not set! bool isEof = true; - evalCode = script[0]; - if (evalCode != EVAL_TOKENS) + evalCodeTokens = script[0]; + if (evalCodeTokens != EVAL_TOKENS) return (uint8_t)0; funcId = script[1]; - //fprintf(stderr,"decode.[%c]\n",funcId); + LOGSTREAM("tokens", CCLOG_DEBUG1, stream << "DecodeTokenOpRet decoded funcId=" << (char)(funcId?funcId:' ')); switch( funcId ) { case 'c': - return DecodeTokenCreateOpRet(scriptPubKey, dummyPubkey, dummyName, dummyDescription); + return DecodeTokenCreateOpRet(scriptPubKey, dummyPubkey, dummyName, dummyDescription, vopret1); //break; case 't': //not used yet: case 'l': // NOTE: 'E_UNMARSHAL result==false' means 'parse error' OR 'not eof state'. Consequently, 'result==false' but 'isEof==true' means just 'parse error' - if (E_UNMARSHAL(vopret, ss >> dummyEvalCode; ss >> dummyFuncId; ss >> tokenid; ss >> ccType; if (ccType >= 1) ss >> voutPubkey1; if (ccType == 2) ss >> voutPubkey2; isEof = ss.eof(); vopretExtra = std::vector(ss.begin(), ss.end())) - || !isEof) + if (E_UNMARSHAL(vopret, ss >> dummyEvalCode; ss >> dummyFuncId; ss >> tokenid; ss >> ccType; \ + if (ccType >= 1) ss >> voutPubkey1; \ + if (ccType == 2) ss >> voutPubkey2; \ + isEof = ss.eof(); \ + if (!isEof) ss >> vopret1; \ + isEof = ss.eof(); \ + if (!isEof) { ss >> vopret2; } \ + // if something else remains -> bad format + isEof = ss.eof()) || !isEof) { if (!(ccType >= 0 && ccType <= 2)) { //incorrect ccType - std::cerr << "DecodeTokenOpRet() incorrect ccType=" << (int)ccType << " tokenid=" << revuint256(tokenid).GetHex() << std::endl; + LOGSTREAM("tokens", CCLOG_INFO, stream << "DecodeTokenOpRet() incorrect ccType=" << (int)ccType << " tokenid=" << revuint256(tokenid).GetHex() << std::endl); return (uint8_t)0; } @@ -160,22 +209,20 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCode, uint256 tokenid = revuint256(tokenid); return(funcId); } - std::cerr << "DecodeTokenOpRet() bad opret format, isEof=" << isEof << " ccType=" << ccType << " tokenid=" << revuint256(tokenid).GetHex() << std::endl; + LOGSTREAM("tokens", CCLOG_INFO, stream << "DecodeTokenOpRet() bad opret format, isEof=" << isEof << " ccType=" << ccType << " tokenid=" << revuint256(tokenid).GetHex() << std::endl); return (uint8_t)0; default: - std::cerr << "DecodeTokenOpRet() illegal funcid=" << (int)funcId << std::endl; + LOGSTREAM("tokens", CCLOG_INFO, stream << "DecodeTokenOpRet() illegal funcid=" << (int)funcId << std::endl); return (uint8_t)0; } } else { - std::cerr << "DecodeTokenOpRet() empty opret, could not parse" << std::endl; + LOGSTREAM("tokens", CCLOG_INFO, stream << "DecodeTokenOpRet() empty opret, could not parse" << std::endl); } return (uint8_t)0; } - - // tx validation bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn) { @@ -183,7 +230,7 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & CTxDestination address; CTransaction vinTx, createTx; uint256 hashBlock, tokenid, tokenid2; int32_t i, starti, numvins, numvouts, preventCCvins, preventCCvouts; int64_t remaining_price, nValue, tokenoshis, outputs, inputs, tmpprice, totalunits, ignore; - std::vector vopretExtra, tmporigpubkey, ignorepubkey; + std::vector vopret1, vopret2, tmporigpubkey, ignorepubkey; uint8_t funcid, evalCodeInOpret; char destaddr[64], origaddr[64], CCaddr[64]; std::vector voutTokenPubkeys; @@ -195,10 +242,10 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & outputs = inputs = 0; preventCCvins = preventCCvouts = -1; - if ((funcid = DecodeTokenOpRet(tx.vout[numvouts - 1].scriptPubKey, evalCodeInOpret, tokenid, voutTokenPubkeys, vopretExtra)) == 0) + if ((funcid = DecodeTokenOpRet(tx.vout[numvouts - 1].scriptPubKey, evalCodeInOpret, tokenid, voutTokenPubkeys, vopret1, vopret2)) == 0) return eval->Invalid("TokenValidate: invalid opreturn payload"); - fprintf(stderr, "TokensValidate (%c) evalcode=0x%0x\n", funcid, cp->evalcode); + LOGSTREAM("tokens", CCLOG_INFO, stream << "TokensValidate funcId=" << (char)(funcid?funcid:' ') << " evalcode=" << cp->evalcode); if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) return eval->Invalid("cant find token create txid"); @@ -218,6 +265,12 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & } } + // non-fungible tokens validation: + std::vector vopretNonfungible; + GetNonfungibleData(tokenid, vopretNonfungible); + if (vopretNonfungible.size() > 0 && vopretNonfungible != vopret1) // assuming tx vopretNonfungible in vopret1 + return eval->Invalid("incorrect or empty non-fungible data"); + switch (funcid) { @@ -240,11 +293,11 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & if (inputs == 0) return eval->Invalid("no token inputs for transfer"); - fprintf(stderr, "token transfer preliminarily validated %.8f -> %.8f (%d %d)\n", (double)inputs / COIN, (double)outputs / COIN, preventCCvins, preventCCvouts); + LOGSTREAM("tokens", CCLOG_INFO, stream << "token transfer preliminarily validated inputs=" << inputs << "->outputs=" << outputs << " preventCCvins=" << preventCCvins<< " preventCCvouts=" << preventCCvouts << std::endl); break; // breaking to other contract validation... default: - fprintf(stderr, "illegal tokens funcid.(%c)\n", funcid); + LOGSTREAM("tokens", CCLOG_INFO, stream << "illegal tokens funcid=" << (char)(funcid?funcid:' ') << std::endl); return eval->Invalid("unexpected token funcid"); } @@ -266,7 +319,7 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & // helper funcs: -// extract my vins pubkeys: +// extract cc token vins' pubkeys: bool ExtractTokensVinPubkeys(CTransaction tx, std::vector &vinPubkeys) { bool found = false; @@ -276,12 +329,13 @@ bool ExtractTokensVinPubkeys(CTransaction tx, std::vector &vinPubkeys) cpTokens = CCinit(&tokensC, EVAL_TOKENS); for (int32_t i = 0; i < tx.vin.size(); i++) - { // check for additional contracts which may send tokens to the Tokens contract + { + // check for cc token vins: if( (*cpTokens->ismyvin)(tx.vin[i].scriptSig) ) { auto findEval = [](CC *cond, struct CCVisitor _) { - bool r = false; //cc_typeId(cond) == CC_Eval && cond->codeLength == 1 && cond->code[0] == EVAL_TOKENS; + bool r = false; if (cc_typeId(cond) == CC_Secp256k1) { *(CPubKey*)_.context = buf2pk(cond->publicKey); @@ -313,38 +367,49 @@ bool ExtractTokensVinPubkeys(CTransaction tx, std::vector &vinPubkeys) thread_local uint32_t tokenValIndentSize = 0; // validates opret for token tx: -uint8_t ValidateTokenOpret(CTransaction tx, int32_t v, uint256 tokenid, std::vector &voutPubkeys, std::vector &vopretExtra) { +uint8_t ValidateTokenOpret(CTransaction tx, uint256 tokenid) { - uint256 tokenidOpret, tokenidOpret2; + uint256 tokenidOpret = zeroid; uint8_t funcid; uint8_t dummyEvalCode; + std::vector voutPubkeysDummy; + std::vector vopretExtraDummy; // this is just for log messages indentation fur debugging recursive calls: std::string indentStr = std::string().append(tokenValIndentSize, '.'); - int32_t n = tx.vout.size(); + if (tx.vout.size() == 0) + return (uint8_t)0; - if ((funcid = DecodeTokenOpRet(tx.vout[n - 1].scriptPubKey, dummyEvalCode, tokenidOpret, voutPubkeys, vopretExtra)) == 0) + if ((funcid = DecodeTokenOpRet(tx.vout.back().scriptPubKey, dummyEvalCode, tokenidOpret, voutPubkeysDummy, vopretExtraDummy)) == 0) { - std::cerr << indentStr << "ValidateTokenOpret() DecodeTokenOpret could not parse opret for txid=" << tx.GetHash().GetHex() << std::endl; - return(false); + LOGSTREAM("tokens", CCLOG_INFO, stream << indentStr << "ValidateTokenOpret() DecodeTokenOpret could not parse opret for txid=" << tx.GetHash().GetHex() << std::endl); + return (uint8_t)0; } else if (funcid == 'c') { - if (tokenid != zeroid && tokenid == tx.GetHash() && v == 0) { - //std::cerr << indentStr << "ValidateTokenOpret() this is the tokenbase 'c' tx, txid=" << tx.GetHash().GetHex() << " vout=" << v << " returning true" << std::endl; + if (tokenid != zeroid && tokenid == tx.GetHash()) { + LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() this is the tokenbase 'c' tx, txid=" << tx.GetHash().GetHex() << " returning true" << std::endl); return funcid; } + else { + LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not my tokenbase txid=" << tx.GetHash().GetHex() << std::endl); + } } else if (funcid == 't') { //std::cerr << indentStr << "ValidateTokenOpret() tokenid=" << tokenid.GetHex() << " tokenIdOpret=" << tokenidOpret.GetHex() << " txid=" << tx.GetHash().GetHex() << std::endl; if (tokenid != zeroid && tokenid == tokenidOpret) { - //std::cerr << indentStr << "ValidateTokenOpret() this is a transfer 't' tx, txid=" << tx.GetHash().GetHex() << " vout=" << v << " returning true" << std::endl; + LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() this is a transfer 't' tx, txid=" << tx.GetHash().GetHex() << " returning true" << std::endl); return funcid; } + else { + LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not my tokenid=" << tokenidOpret.GetHex() << std::endl); + } } - //std::cerr << indentStr << "ValidateTokenOpret() return false funcid=" << (char)funcid << " tokenid=" << tokenid.GetHex() << " tokenIdOpret=" << tokenidOpret.GetHex() << " txid=" << tx.GetHash().GetHex() << std::endl; + else { + LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not supported funcid=" << (char)funcid << " tokenIdOpret=" << tokenidOpret.GetHex() << " txid=" << tx.GetHash().GetHex() << std::endl); + } return (uint8_t)0; } @@ -358,20 +423,20 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c // this is just for log messages indentation fur debugging recursive calls: std::string indentStr = std::string().append(tokenValIndentSize, '.'); - //std::cerr << indentStr << "IsTokensvout() entered for txid=" << tx.GetHash().GetHex() << " v=" << v << " for tokenid=" << reftokenid.GetHex() << std::endl; + + LOGSTREAM("tokens", CCLOG_DEBUG2, stream << indentStr << "IsTokensvout() entered for txid=" << tx.GetHash().GetHex() << " v=" << v << " for tokenid=" << reftokenid.GetHex() << std::endl); + + int32_t n = tx.vout.size(); + // just check boundaries: + if (n == 0 || v < 0 || v >= n-1) { + LOGSTREAM("tokens", CCLOG_INFO, stream << indentStr << "isTokensvout() incorrect params: (n == 0 or v < 0 or v >= n-1)" << " v=" << v << " n=" << n << " returning 0" << std::endl); + return(0); + } //TODO: validate cc vouts are EVAL_TOKENS! if (tx.vout[v].scriptPubKey.IsPayToCryptoCondition()) // maybe check address too? dimxy: possibly no, because there are too many cases with different addresses here { - int32_t n = tx.vout.size(); - // just check boundaries: - if (v >= n - 1) { // just moved this up (dimxy) - std::cerr << indentStr << "isTokensvout() internal err: (v >= n - 1), returning 0" << std::endl; - return(0); - } - if (goDeeper) { - //std::cerr << indentStr << "IsTokensvout() maxTokenExactAmountDepth=" << maxTokenExactAmountDepth << std::endl; //validate all tx int64_t myCCVinsAmount = 0, myCCVoutsAmount = 0; @@ -384,98 +449,109 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c // if ccInputs != ccOutputs and it is not the tokenbase tx // this means it is possibly a fake tx (dimxy): if (reftokenid != tx.GetHash()) { // checking that this is the true tokenbase tx, by verifying that funcid=c, is done further in this function (dimxy) - std::cerr << indentStr << "IsTokensvout() warning: for the verified tx detected a bad vintx=" << tx.GetHash().GetHex() << ": cc inputs != cc outputs and not the 'tokenbase' tx, skipping the verified tx" << std::endl; + LOGSTREAM("tokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() warning: for the verified tx detected a bad vintx=" << tx.GetHash().GetHex() << ": cc inputs != cc outputs and not the 'tokenbase' tx, skipping the verified tx" << std::endl); return 0; } } } - // moved opret checking to this new reusable func (dimxy): - std::vector voutPubkeys; - std::vector vopretExtra; - const uint8_t funcId = ValidateTokenOpret(tx, v, reftokenid, voutPubkeys, vopretExtra); + // token opret most important checks (tokenid == reftokenid, tokenid is non-zero, tx is 'tokenbase'): + const uint8_t funcId = ValidateTokenOpret(tx, reftokenid); //std::cerr << indentStr << "IsTokensvout() ValidateTokenOpret returned=" << (char)(funcId?funcId:' ') << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl; if (funcId != 0) { - //std::cerr << indentStr << "IsTokensvout() ValidateTokenOpret returned not-null" << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl; + LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() ValidateTokenOpret returned not-null funcId=" << (char)(funcId?funcId:' ') << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); - if (checkPubkeys && funcId != 'c') { // verify that the vout is token's (for 'c' there is no pubkeys!): + uint8_t dummyEvalCode; + uint256 tokenIdOpret; + std::vector voutPubkeys; + std::vector vopret1; + std::vector vopret2; + DecodeTokenOpRet(tx.vout.back().scriptPubKey, dummyEvalCode, tokenIdOpret, voutPubkeys, vopret1, vopret2); - //std::cerr << "IsTokensvout() vopretExtra=" << HexStr(vopretExtra) << std::endl; - - uint8_t evalCodeInOpret; - if (vopretExtra.size() >= 2 /*|| vopretExtra.size() != vopretExtra.begin()[0] <-- shold we check this?*/) { - evalCodeInOpret = vopretExtra.begin()[1]; - } - else { - // if payload is empty maybe it is a claim to non-payload-one-token-eval vout? - evalCodeInOpret = EVAL_TOKENS; - } + if (checkPubkeys && funcId != 'c') { // for 'c' there is no pubkeys + // verify that the vout is token by constructing vouts with the pubkeys in the opret: + LOGSTREAM("tokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopret1=" << HexStr(vopret1) << std::endl); + LOGSTREAM("tokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopret2=" << HexStr(vopret2) << std::endl); + + uint8_t evalCode = EVAL_TOKENS; // if both payloads are empty maybe it is a transfer to non-payload-one-eval-token vout like GatewaysClaim + uint8_t evalCode2 = 0; // will be checked if zero or not + + // NOTE: evalcode order in vouts is important: + // non-fungible-eval -> EVAL_TOKENS -> assets-eval + if (vopret1.size() > 0) { + evalCode = vopret1.begin()[0]; + } + if (vopret2.size() > 0) { + evalCode2 = vopret2.begin()[0]; + } + + // checking vouts for possible token use-cases: + std::vector> testVouts; // maybe this is dual-eval 1 pubkey or 1of2 pubkey vout? if (voutPubkeys.size() >= 1 && voutPubkeys.size() <= 2) { - CTxOut testDualVout; - // check dual-eval 1 pubkey vout with the first pubkey - testDualVout = MakeTokensCC1vout(evalCodeInOpret, tx.vout[v].nValue, voutPubkeys[0]); - if (tx.vout[v].scriptPubKey == testDualVout.scriptPubKey) { - //std::cerr << indentStr << "IsTokensvout() this is dual-eval token vout (i=0), eval2=" << (int)evalCodeInOpret << ", returning nValue=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl; - return tx.vout[v].nValue; - } - - if(voutPubkeys.size() == 2) { - // check dual eval 1of2 pubkeys vout - testDualVout = MakeTokensCC1of2vout(evalCodeInOpret, tx.vout[v].nValue, voutPubkeys[0], voutPubkeys[1]); - if (tx.vout[v].scriptPubKey == testDualVout.scriptPubKey) { - //std::cerr << indentStr << "IsTokensvout() this is dual-eval token 1of2 vout, eval2=" << (int)evalCodeInOpret << ", returning nValue=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl; - return tx.vout[v].nValue; - } + // check dual/three-eval 1 pubkey vout with the first pubkey + testVouts.push_back( std::make_pair(MakeTokensCC1vout(evalCode, evalCode2, tx.vout[v].nValue, voutPubkeys[0]), std::string("three-eval cc1 pk[0]")) ); + if (evalCode2 != 0) + // also check in backward evalcode order + testVouts.push_back( std::make_pair(MakeTokensCC1vout(evalCode2, evalCode, tx.vout[v].nValue, voutPubkeys[0]), std::string("three-eval cc1 pk[0] backward-eval")) ); - // check dual eval 1 pubkey vout with the second pubkey - testDualVout = MakeTokensCC1vout(evalCodeInOpret, tx.vout[v].nValue, voutPubkeys[1]); - if (tx.vout[v].scriptPubKey == testDualVout.scriptPubKey) { - //std::cerr << indentStr << "IsTokensvout() this is dual-eval token vout (i=1), eval2=" << (int)evalCodeInOpret << ", returning nValue=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl; - return tx.vout[v].nValue; - } + if(voutPubkeys.size() == 2) { + // check dual/three eval 1of2 pubkeys vout + testVouts.push_back( std::make_pair(MakeTokensCC1of2vout(evalCode, evalCode2, tx.vout[v].nValue, voutPubkeys[0], voutPubkeys[1]), std::string("three-eval cc1of2")) ); + // check dual/three eval 1 pubkey vout with the second pubkey + testVouts.push_back(std::make_pair(MakeTokensCC1vout(evalCode, evalCode2, tx.vout[v].nValue, voutPubkeys[1]), std::string("three-eval cc1 pk[1]"))); + if (evalCode2 != 0) { + // also check in backward evalcode order: + // check dual/three eval 1of2 pubkeys vout + testVouts.push_back(std::make_pair(MakeTokensCC1of2vout(evalCode2, evalCode, tx.vout[v].nValue, voutPubkeys[0], voutPubkeys[1]), std::string("three-eval cc1of2 backward-eval"))); + // check dual/three eval 1 pubkey vout with the second pubkey + testVouts.push_back(std::make_pair(MakeTokensCC1vout(evalCode2, evalCode, tx.vout[v].nValue, voutPubkeys[1]), std::string("three-eval cc1 pk[1] backward-eval"))); + } } - // maybe this is claim to single-eval token? - CTxOut testTokenVout1; - testTokenVout1 = MakeCC1vout(EVAL_TOKENS, tx.vout[v].nValue, voutPubkeys[0]); - if (tx.vout[v].scriptPubKey == testTokenVout1.scriptPubKey) { - //std::cerr << indentStr << "IsTokensvout() this is single-eval token vout (i=0), returning nValue=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl; - return tx.vout[v].nValue; - } + // maybe this is like gatewayclaim to single-eval token? + testVouts.push_back(std::make_pair(MakeCC1vout(EVAL_TOKENS, tx.vout[v].nValue, voutPubkeys[0]), std::string("single-eval cc1 pk[0]"))); + // maybe this is like FillSell for non-fungible token? + if( evalCode != 0 ) + testVouts.push_back(std::make_pair(MakeTokensCC1vout(evalCode, tx.vout[v].nValue, voutPubkeys[0]), std::string("dual-eval-token cc1 pk[0]"))); + if( evalCode2 != 0 ) + testVouts.push_back(std::make_pair(MakeTokensCC1vout(evalCode2, tx.vout[v].nValue, voutPubkeys[0]), std::string("dual-eval2-token cc1 pk[0]"))); if (voutPubkeys.size() == 2) { - testTokenVout1 = MakeCC1vout(EVAL_TOKENS, tx.vout[v].nValue, voutPubkeys[1]); - if (tx.vout[v].scriptPubKey == testTokenVout1.scriptPubKey) { - //std::cerr << indentStr << "IsTokensvout() this is single-eval token vout (i=1), returning nValue=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl; - return tx.vout[v].nValue; - } + // the same for pk[1]: + testVouts.push_back(std::make_pair(MakeCC1vout(EVAL_TOKENS, tx.vout[v].nValue, voutPubkeys[1]), std::string("single-eval cc1 pk[1]"))); + if (evalCode != 0) + testVouts.push_back(std::make_pair(MakeTokensCC1vout(evalCode, tx.vout[v].nValue, voutPubkeys[1]), std::string("dual-eval-token cc1 pk[1]"))); + if (evalCode2 != 0) + testVouts.push_back(std::make_pair(MakeTokensCC1vout(evalCode2, tx.vout[v].nValue, voutPubkeys[1]), std::string("dual-eval2-token cc1 pk[1]"))); } } - // maybe it is single-eval or dual-eval token change? + // maybe it is single-eval or dual/three-eval token change? std::vector vinPubkeys; ExtractTokensVinPubkeys(tx, vinPubkeys); - for(std::vector::iterator it = vinPubkeys.begin(); it != vinPubkeys.end(); it++) { - CTxOut testTokenVout1 = MakeCC1vout(EVAL_TOKENS, tx.vout[v].nValue, *it); - CTxOut testDualVout1 = MakeTokensCC1vout(evalCodeInOpret, tx.vout[v].nValue, *it); + testVouts.push_back(std::make_pair(MakeCC1vout(EVAL_TOKENS, tx.vout[v].nValue, *it), std::string("single-eval cc1 self vin pk"))); + testVouts.push_back(std::make_pair(MakeTokensCC1vout(evalCode, evalCode2, tx.vout[v].nValue, *it), std::string("three-eval cc1 self vin pk"))); - if (tx.vout[v].scriptPubKey == testTokenVout1.scriptPubKey) { - //std::cerr << indentStr << "IsTokensvout() this is single-eval token change, returning nValue=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl; - return tx.vout[v].nValue; - } - - if (tx.vout[v].scriptPubKey == testDualVout1.scriptPubKey) { - //std::cerr << indentStr << "IsTokensvout() this is dual-eval token change, vout eval2=" << (int)evalCodeInOpret << ", returning nValue=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl; - return tx.vout[v].nValue; - } + if (evalCode2 != 0) + // also check in backward evalcode order: + testVouts.push_back(std::make_pair(MakeTokensCC1vout(evalCode2, evalCode, tx.vout[v].nValue, *it), std::string("three-eval cc1 self vin pk backward-eval"))); } + + // try all test vouts: + for (auto t : testVouts) { + if (t.first == tx.vout[v]) { + LOGSTREAM("tokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() valid amount=" << tx.vout[v].nValue << " msg=" << t.second << " evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " txid=" << tx.GetHash().GetHex() << " tokenid=" << reftokenid.GetHex() << std::endl); + return tx.vout[v].nValue; + } + } + LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() no valid vouts evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); } else { - //std::cerr << indentStr << "IsTokensvout() returns without pubkey check value=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl; + LOGSTREAM("tokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() returns without pubkey check value=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); return tx.vout[v].nValue; } } @@ -487,7 +563,7 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c } // compares cc inputs vs cc outputs (to prevent feeding vouts from normal inputs) -bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inputs, int64_t &outputs, Eval* eval, const CTransaction &tx, uint256 tokenid) +bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inputs, int64_t &outputs, Eval* eval, const CTransaction &tx, uint256 reftokenid) { CTransaction vinTx; uint256 hashBlock; @@ -503,6 +579,8 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu // this is just for log messages indentation for debugging recursive calls: std::string indentStr = std::string().append(tokenValIndentSize, '.'); + LOGSTREAM("tokens", CCLOG_DEBUG2, stream << indentStr << "TokensExactAmounts() entered for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); + for (int32_t i = 0; iismyvin)(tx.vin[i].scriptSig) /*|| IsVinAllowed(tx.vin[i].scriptSig) != 0*/) @@ -511,37 +589,38 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu // we are not inside the validation code -- dimxy if ((eval && eval->GetTxUnconfirmed(tx.vin[i].prevout.hash, vinTx, hashBlock) == 0) || (!eval && !myGetTransaction(tx.vin[i].prevout.hash, vinTx, hashBlock))) { - std::cerr << indentStr << "TokensExactAmounts() cannot read vintx for i." << i << " numvins." << numvins << std::endl; + LOGSTREAM("tokens", CCLOG_INFO, stream << indentStr << "TokensExactAmounts() cannot read vintx for i." << i << " numvins." << numvins << std::endl); return (!eval) ? false : eval->Invalid("always should find vin tx, but didnt"); } else { - tokenValIndentSize++; - // validate vouts of vintx - //std::cerr << indentStr << "TokenExactAmounts() check vin i=" << i << " nValue=" << vinTx.vout[tx.vin[i].prevout.n].nValue << std::endl; - tokenoshis = IsTokensvout(goDeeper, true, cpTokens, eval, vinTx, tx.vin[i].prevout.n, tokenid); + LOGSTREAM("tokens", CCLOG_DEBUG2, stream << indentStr << "TokenExactAmounts() checking vintx.vout for tx.vin[" << i << "] nValue=" << vinTx.vout[tx.vin[i].prevout.n].nValue << std::endl); + + // validate vouts of vintx + tokenValIndentSize++; + tokenoshis = IsTokensvout(goDeeper, true, cpTokens, eval, vinTx, tx.vin[i].prevout.n, reftokenid); tokenValIndentSize--; if (tokenoshis != 0) { - std::cerr << indentStr << "TokensExactAmounts() vin i=" << i << " tokenoshis=" << tokenoshis << std::endl; + LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "TokensExactAmounts() adding vintx.vout for tx.vin[" << i << "] tokenoshis=" << tokenoshis << std::endl); inputs += tokenoshis; } } } } - - for (int32_t i = 0; iInvalid() here! } else return true; } -// add inputs from token cc addr -int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, CPubKey pk, uint256 tokenid, int64_t total, int32_t maxinputs) +// get non-fungible data from 'tokenbase' tx (the data might be empty) +void GetNonfungibleData(uint256 tokenid, std::vector &vopretNonfungible) +{ + CTransaction tokenbasetx; + uint256 hashBlock; + + if (!myGetTransaction(tokenid, tokenbasetx, hashBlock)) { + LOGSTREAM("tokens", CCLOG_INFO, stream << "SetNonfungibleEvalCode() cound not load token creation tx=" << tokenid.GetHex() << std::endl); + return; + } + + vopretNonfungible.clear(); + // check if it is non-fungible tx and get its second evalcode from non-fungible payload + if (tokenbasetx.vout.size() > 0) { + uint8_t dummyEvalCode; + uint256 tokenIdOpret; + std::vector voutPubkeys; + std::vector vopretExtra; + DecodeTokenOpRet(tokenbasetx.vout.back().scriptPubKey, dummyEvalCode, tokenIdOpret, voutPubkeys, vopretNonfungible, vopretExtra); + } +} + + +// overload, adds inputs from token cc addr +int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, CPubKey pk, uint256 tokenid, int64_t total, int32_t maxinputs) { + std::vector vopretNonfungibleDummy; + return AddTokenCCInputs(cp, mtx, pk, tokenid, total, maxinputs, vopretNonfungibleDummy); +} + +// adds inputs from token cc addr and returns non-fungible opret payload if present +// also sets evalcode in cp, if needed +int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, CPubKey pk, uint256 tokenid, int64_t total, int32_t maxinputs, std::vector &vopretNonfungible) { char tokenaddr[64], destaddr[64]; - int64_t threshold, nValue, price, totalinputs = 0; - uint256 txid, hashBlock; - //std::vector vopretExtra; - CTransaction vintx; - int32_t j, vout, n = 0; + int64_t threshold, nValue, price, totalinputs = 0; + int32_t n = 0; std::vector > unspentOutputs; + GetNonfungibleData(tokenid, vopretNonfungible); + if (vopretNonfungible.size() > 0) + cp->additionalTokensEvalcode2 = vopretNonfungible.begin()[0]; + GetTokensCCaddress(cp, tokenaddr, pk); SetCCunspents(unspentOutputs, tokenaddr); - threshold = total / (maxinputs != 0 ? maxinputs : 64); // TODO: is maxinputs really could not be over 64? what if i want to calc total balance? + if (unspentOutputs.empty()) { + LOGSTREAM("tokens", CCLOG_INFO, stream << "AddTokenCCInputs() no utxos for token dual/three eval addr=" << tokenaddr << " evalcode=" << (int)cp->evalcode << " additionalTokensEvalcode2=" << (int)cp->additionalTokensEvalcode2 << std::endl); + } + + threshold = total / (maxinputs != 0 ? maxinputs : 64); // TODO: maxinputs really could not be over 64? what if i want to calc total balance for all available uxtos? + // maybe it is better to add all uxtos if maxinputs == 0 for (std::vector >::const_iterator it = unspentOutputs.begin(); it != unspentOutputs.end(); it++) { - txid = it->first.txhash; - vout = (int32_t)it->first.index; - if (it->second.satoshis < threshold) - continue; - for (j = 0; jfirst.txhash; + int32_t vout = (int32_t)it->first.index; + + if (it->second.satoshis < threshold) // this should work also for non-fungible tokens (there should be only 1 satoshi for non-fungible token issue) continue; - if (GetTransaction(txid, vintx, hashBlock, false) != 0) + int32_t ivin; + for (ivin = 0; ivin < mtx.vin.size(); ivin ++) + if (vintxid == mtx.vin[ivin].prevout.hash && vout == mtx.vin[ivin].prevout.n) + break; + if (ivin != mtx.vin.size()) // that is, the tx.vout is already added to mtx.vin (in some previous calls) + continue; + + if (GetTransaction(vintxid, vintx, hashBlock, false) != 0) { Getscriptaddress(destaddr, vintx.vout[vout].scriptPubKey); - if (strcmp(destaddr, tokenaddr) != 0 && strcmp(destaddr, cp->unspendableCCaddr) != 0 && strcmp(destaddr, cp->unspendableaddr2) != 0) + if (strcmp(destaddr, tokenaddr) != 0 && + strcmp(destaddr, cp->unspendableCCaddr) != 0 && // TODO: check why this. Should not we add token inputs from unspendable cc addr if mypubkey is used? + strcmp(destaddr, cp->unspendableaddr2) != 0) // or the logic is to allow to spend all available tokens (what about unspendableaddr3)? continue; - //fprintf(stderr, "AddTokenCCInputs() check destaddress=%s vout amount=%.8f\n", destaddr, (double)vintx.vout[vout].nValue / COIN); - - std::vector vinPubkeys; - if ((nValue = IsTokensvout(true, true/*<--add only checked token uxtos */, cp, NULL, vintx, vout, tokenid)) > 0 && myIsutxo_spentinmempool(txid, vout) == 0) + LOGSTREAM("tokens", CCLOG_DEBUG1, stream << "AddTokenCCInputs() check vintx vout destaddress=" << destaddr << " amount=" << vintx.vout[vout].nValue << std::endl); + + if ((nValue = IsTokensvout(true, true/*<--add only valid token uxtos */, cp, NULL, vintx, vout, tokenid)) > 0 && myIsutxo_spentinmempool(vintxid, vout) == 0) { - if (total != 0 && maxinputs != 0) - mtx.vin.push_back(CTxIn(txid, vout, CScript())); + //for non-fungible tokens check payload: + if (!vopretNonfungible.empty()) { + std::vector vopret; + + // check if it is non-fungible token: + GetNonfungibleData(tokenid, vopret); + if (vopret != vopretNonfungible) { + LOGSTREAM("tokens", CCLOG_INFO, stream << "AddTokenCCInputs() found incorrect non-fungible opret payload for vintxid=" << vintxid.GetHex() << std::endl); + continue; + } + + // non-fungible evalCode2 cc contract should also check if there exists only one non-fungible vout with amount = 1 + } + + + if (total != 0 && maxinputs != 0) // if it is not just to calc amount... + mtx.vin.push_back(CTxIn(vintxid, vout, CScript())); + nValue = it->second.satoshis; totalinputs += nValue; - std::cerr << "AddTokenInputs() adding input nValue=" << nValue << std::endl; + LOGSTREAM("tokens", CCLOG_DEBUG1, stream << "AddTokenCCInputs() adding input nValue=" << nValue << std::endl); n++; + if ((total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs)) break; } } } - //std::cerr << "AddTokenInputs() found totalinputs=" << totalinputs << std::endl; + //std::cerr << "AddTokenCCInputs() found totalinputs=" << totalinputs << std::endl; return(totalinputs); } -std::string CreateToken(int64_t txfee, int64_t assetsupply, std::string name, std::string description) +std::string CreateToken(int64_t txfee, int64_t tokensupply, std::string name, std::string description, std::vector nonfungibleData) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); CPubKey mypk; struct CCcontract_info *cp, C; - if (assetsupply < 0) + if (tokensupply < 0) { - fprintf(stderr, "negative assetsupply %lld\n", (long long)assetsupply); - return(""); + LOGSTREAM("tokens", CCLOG_INFO, stream << "CreateToken() negative tokensupply=" << tokensupply << std::endl); + return std::string(""); } + if (!nonfungibleData.empty() && tokensupply != 1) { + LOGSTREAM("tokens", CCLOG_INFO, stream << "CreateToken() for non-fungible tokens tokensupply should be equal to 1" << std::endl); + CCerror = "for non-fungible tokens tokensupply should be equal to 1"; + return std::string(""); + } + cp = CCinit(&C, EVAL_TOKENS); - if (name.size() > 32 || description.size() > 4096) + if (name.size() > 32 || description.size() > 4096) // this is also checked on rpc level { - fprintf(stderr, "name.%d or description.%d is too big\n", (int32_t)name.size(), (int32_t)description.size()); + LOGSTREAM("tokens", CCLOG_INFO, stream << "name of=" << name.size() << " or description of=" << description.size() << " is too big" << std::endl); + CCerror = "name should be < 32, description should be < 4096"; return(""); } if (txfee == 0) txfee = 10000; mypk = pubkey2pk(Mypubkey()); - if (AddNormalinputs(mtx, mypk, assetsupply + 2 * txfee, 64) > 0) + if (AddNormalinputs(mtx, mypk, tokensupply + 2 * txfee, 64) > 0) { - mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, assetsupply, mypk)); + uint8_t destEvalCode = EVAL_TOKENS; + if( nonfungibleData.size() > 0 ) + destEvalCode = nonfungibleData.begin()[0]; + + mtx.vout.push_back(MakeTokensCC1vout(destEvalCode, tokensupply, mypk)); mtx.vout.push_back(CTxOut(txfee, CScript() << ParseHex(cp->CChexstr) << OP_CHECKSIG)); - return(FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenCreateOpRet('c', Mypubkey(), name, description))); + return(FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenCreateOpRet('c', Mypubkey(), name, description, nonfungibleData))); } - return(""); + + LOGSTREAM("tokens", CCLOG_INFO, stream << "cant find normal inputs" << std::endl); + CCerror = "cant find normal inputs"; + return std::string(""); } - -std::string TokenTransfer(int64_t txfee, uint256 assetid, std::vector destpubkey, int64_t total) +// transfer tokens to another pubkey +// param additionalEvalCode allows transfer of dual-eval non-fungible tokens +std::string TokenTransfer(int64_t txfee, uint256 tokenid, std::vector destpubkey, int64_t total) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); CPubKey mypk; uint64_t mask; int64_t CCchange = 0, inputs = 0; struct CCcontract_info *cp, C; - std::vector emptyExtraOpret; + std::vector vopretNonfungible; - if (total < 0) - { - fprintf(stderr, "negative total %lld\n", (long long)total); + if (total < 0) { + LOGSTREAM("tokens", CCLOG_INFO, stream << "negative total=" << total << std::endl); return(""); } + cp = CCinit(&C, EVAL_TOKENS); + if (txfee == 0) txfee = 10000; mypk = pubkey2pk(Mypubkey()); if (AddNormalinputs(mtx, mypk, txfee, 3) > 0) { - //n = outputs.size(); - //if ( n == amounts.size() ) - //{ - // for (i=0; i 0) + mask = ~((1LL << mtx.vin.size()) - 1); // seems, mask is not used anymore + + if ((inputs = AddTokenCCInputs(cp, mtx, mypk, tokenid, total, 60, vopretNonfungible)) > 0) // NOTE: AddTokenCCInputs might set cp->additionalEvalCode which is used in FinalizeCCtx! { - if (inputs < total) { //added dimxy - std::cerr << "AssetTransfer(): insufficient funds" << std::endl; - return (""); + LOGSTREAM("tokens", CCLOG_INFO, stream << "TokenTransfer(): insufficient token funds" << std::endl); + CCerror = strprintf("insufficient token inputs"); + return std::string(""); } + + uint8_t destEvalCode = EVAL_TOKENS; + if (vopretNonfungible.size() > 0) + destEvalCode = vopretNonfungible.begin()[0]; + if (inputs > total) CCchange = (inputs - total); - //for (i=0; i voutTokenPubkeys; voutTokenPubkeys.push_back(pubkey2pk(destpubkey)); // dest pubkey for validating vout - return(FinalizeCCTx(mask, cp, mtx, mypk, txfee, EncodeTokenOpRet('t', EVAL_TOKENS, assetid, voutTokenPubkeys, CScript()))); // By setting EVAL_TOKENS we're getting out from assets validation code + return(FinalizeCCTx(mask, cp, mtx, mypk, txfee, EncodeTokenOpRet(tokenid, voutTokenPubkeys, vopretNonfungible, CScript()))); } else { - fprintf(stderr, "not enough CC token inputs for %.8f\n", (double)total / COIN); + LOGSTREAM("tokens", CCLOG_INFO, stream << "not enough CC token inputs for amount=" << total << std::endl); + CCerror = strprintf("no token inputs"); } //} else fprintf(stderr,"numoutputs.%d != numamounts.%d\n",n,(int32_t)amounts.size()); } else { - fprintf(stderr, "not enough normal inputs for txfee\n"); + LOGSTREAM("tokens", CCLOG_INFO, stream << "not enough normal inputs for txfee" << std::endl); + CCerror = strprintf("insufficient normal inputs"); } return(""); } @@ -708,7 +864,7 @@ int64_t GetTokenBalance(CPubKey pk, uint256 tokenid) if (GetTransaction(tokenid, tokentx, hashBlock, false) == 0) { - fprintf(stderr, "cant find tokenid\n"); + LOGSTREAM("tokens", CCLOG_INFO, stream << "cant find tokenid" << std::endl); CCerror = strprintf("cant find tokenid"); return 0; } @@ -720,26 +876,35 @@ int64_t GetTokenBalance(CPubKey pk, uint256 tokenid) UniValue TokenInfo(uint256 tokenid) { - UniValue result(UniValue::VOBJ); uint256 hashBlock; CTransaction vintx; std::vector origpubkey; std::string name, description; char str[67], numstr[65]; + UniValue result(UniValue::VOBJ); + uint256 hashBlock; + CTransaction vintx; + std::vector origpubkey; + std::vector vopretNonfungible; + std::string name, description; + if (GetTransaction(tokenid, vintx, hashBlock, false) == 0) { - fprintf(stderr, "cant find assetid\n"); + fprintf(stderr, "TokenInfo() cant find tokenid\n"); result.push_back(Pair("result", "error")); result.push_back(Pair("error", "cant find tokenid")); return(result); } - if (vintx.vout.size() > 0 && DecodeTokenCreateOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, origpubkey, name, description) == 0) + if (vintx.vout.size() > 0 && DecodeTokenCreateOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, origpubkey, name, description, vopretNonfungible) == 0) { - fprintf(stderr, "assetid isnt token creation txid\n"); + LOGSTREAM("tokens", CCLOG_INFO, stream << "TokenInfo() passed tokenid isnt token creation txid" << std::endl); result.push_back(Pair("result", "error")); - result.push_back(Pair("error", "assetid isnt token creation txid")); + result.push_back(Pair("error", "tokenid isnt token creation txid")); } result.push_back(Pair("result", "success")); - result.push_back(Pair("tokenid", uint256_str(str, tokenid))); - result.push_back(Pair("owner", pubkey33_str(str, origpubkey.data()))); + result.push_back(Pair("tokenid", tokenid.GetHex())); + result.push_back(Pair("owner", HexStr(origpubkey))); result.push_back(Pair("name", name)); result.push_back(Pair("supply", vintx.vout[0].nValue)); result.push_back(Pair("description", description)); + if( !vopretNonfungible.empty() ) + result.push_back(Pair("data", HexStr(vopretNonfungible))); + return(result); } diff --git a/src/cc/CCtokens.h b/src/cc/CCtokens.h index e7bb62101..4637ba6c9 100644 --- a/src/cc/CCtokens.h +++ b/src/cc/CCtokens.h @@ -28,14 +28,15 @@ // CCcustom bool TokensValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx, uint32_t nIn); bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cpTokens, int64_t &inputs, int64_t &outputs, Eval* eval, const CTransaction &tx, uint256 tokenid); -//int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *cp, Eval* eval, std::vector &origpubkey, const CTransaction& tx, int32_t v, uint256 reftokenid, std::vector vinPubkeys); -std::string CreateToken(int64_t txfee, int64_t assetsupply, std::string name, std::string description); +std::string CreateToken(int64_t txfee, int64_t assetsupply, std::string name, std::string description, std::vector nonfungibleData); std::string TokenTransfer(int64_t txfee, uint256 assetid, std::vector destpubkey, int64_t total); int64_t GetTokenBalance(CPubKey pk, uint256 tokenid); UniValue TokenInfo(uint256 tokenid); UniValue TokenList(); +void GetNonfungibleData(uint256 tokenid, std::vector &vopretNonfungible); + //this is in CCinclude.h int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, CPubKey pk, uint256 tokenid, int64_t total, int32_t maxinputs); //this is in CCinclude.h uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey,std::vector &origpubkey,std::string &name,std::string &description); diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index d93185ca4..6536fdee3 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -46,8 +46,8 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran CTransaction vintx; std::string hex; CPubKey globalpk; uint256 hashBlock; uint64_t mask=0,nmask=0,vinimask=0; int64_t utxovalues[CC_MAXVINS],change,normalinputs=0,totaloutputs=0,normaloutputs=0,totalinputs=0,normalvins=0,ccvins=0; int32_t i,flag,utxovout,n,err = 0; - char myaddr[64], destaddr[64], unspendable[64], mytokensaddr[64], mysingletokensaddr[64], tokensunspendable[64]; - uint8_t *privkey, myprivkey[32], unspendablepriv[32], tokensunspendablepriv[32], *msg32 = 0; + char myaddr[64], destaddr[64], unspendable[64], mytokensaddr[64], mysingletokensaddr[64], unspendabletokensaddr[64]; + uint8_t *privkey, myprivkey[32], unspendablepriv[32], /*tokensunspendablepriv[32],*/ *msg32 = 0; CC *mycond=0, *othercond=0, *othercond2=0,*othercond4=0, *othercond3=0, *othercond1of2=NULL, *othercond1of2tokens = NULL, *cond, *mytokenscond = NULL, *mysingletokenscond = NULL, *othertokenscond = NULL; CPubKey unspendablepk /*, tokensunspendablepk*/; struct CCcontract_info *cpTokens, tokensC; @@ -69,26 +69,26 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran GetCCaddress(cp,myaddr,mypk); mycond = MakeCCcond1(cp->evalcode,mypk); - // to spend from single-eval evalcode 'unspendable' + // to spend from single-eval evalcode 'unspendable' cc addr unspendablepk = GetUnspendable(cp, unspendablepriv); GetCCaddress(cp, unspendable, unspendablepk); othercond = MakeCCcond1(cp->evalcode, unspendablepk); //printf("evalcode.%d (%s)\n",cp->evalcode,unspendable); - // tokens support: - // to spend from dual-eval mypk vout + // tokens support: + // to spend from dual/three-eval mypk vout GetTokensCCaddress(cp, mytokensaddr, mypk); - mytokenscond = MakeTokensCCcond1(cp->evalcode, mypk); + // NOTE: if additionalEvalcode2 is not set it is a dual-eval (not three-eval) cc cond: + mytokenscond = MakeTokensCCcond1(cp->evalcode, cp->additionalTokensEvalcode2, mypk); // to spend from single-eval EVAL_TOKENS mypk cpTokens = CCinit(&tokensC, EVAL_TOKENS); GetCCaddress(cpTokens, mysingletokensaddr, mypk); mysingletokenscond = MakeCCcond1(EVAL_TOKENS, mypk); - // to spend from dual-eval EVAL_TOKEN+evalcode 'unspendable' pk - //tokensunspendablepk = GetUnspendable(cpTokens, tokensunspendablepriv); - GetTokensCCaddress(cp, tokensunspendable, unspendablepk); - othertokenscond = MakeTokensCCcond1(cp->evalcode, unspendablepk); + // to spend from dual/three-eval EVAL_TOKEN+evalcode 'unspendable' pk: + GetTokensCCaddress(cp, unspendabletokensaddr, unspendablepk); // it may be a three-eval cc, if cp->additionalEvalcode2 is set + othertokenscond = MakeTokensCCcond1(cp->evalcode, cp->additionalTokensEvalcode2, unspendablepk); //Reorder vins so that for multiple normal vins all other except vin0 goes to the end //This is a must to avoid hardfork change of validation in every CC, because there could be maximum one normal vin at the begining with current validation. @@ -155,9 +155,10 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran { Getscriptaddress(destaddr,vintx.vout[utxovout].scriptPubKey); //fprintf(stderr,"FinalizeCCTx() vin.%d is CC %.8f -> (%s)\n",i,(double)utxovalues[i]/COIN,destaddr); - //std::cerr << "FinalizeCCtx() searching destaddr=" << destaddr << " myaddr=" << myaddr << std::endl; - if( strcmp(destaddr,myaddr) == 0 ) + std::cerr << "FinalizeCCtx() searching destaddr=" << destaddr << " for vin[" << i << "] satoshis=" << utxovalues[i] << std::endl; + if( strcmp(destaddr, myaddr) == 0 ) { + fprintf(stderr, "FinalizeCCTx() matched cc myaddr (%s)\n", myaddr); privkey = myprivkey; cond = mycond; } @@ -165,48 +166,48 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran { privkey = myprivkey; cond = mytokenscond; - //fprintf(stderr,"FinalizeCCTx() matched dual-eval TokensCC1vout CC addr.(%s)\n",mytokensaddr); + fprintf(stderr,"FinalizeCCTx() matched dual-eval TokensCC1vout my token addr.(%s)\n",mytokensaddr); } else if (strcmp(destaddr, mysingletokensaddr) == 0) // if this is TokensCC1vout { privkey = myprivkey; cond = mysingletokenscond; - //fprintf(stderr, "FinalizeCCTx() matched single-eval token CC1vout CC addr.(%s)\n", mytokensaddr); + fprintf(stderr, "FinalizeCCTx() matched single-eval token CC1vout my token addr.(%s)\n", mytokensaddr); } else if ( strcmp(destaddr,unspendable) == 0 ) { privkey = unspendablepriv; cond = othercond; - //fprintf(stderr,"FinalizeCCTx(%d) matched unspendable CC addr.(%s)\n",cp->evalcode,unspendable); + fprintf(stderr,"FinalizeCCTx evalcode(%d) matched unspendable CC addr.(%s)\n",cp->evalcode,unspendable); } - else if (strcmp(destaddr, tokensunspendable) == 0) + else if (strcmp(destaddr, unspendabletokensaddr) == 0) { privkey = unspendablepriv; cond = othertokenscond; - //fprintf(stderr,"FinalizeCCTx() matched tokensunspendable CC addr.(%s)\n",unspendable); + fprintf(stderr,"FinalizeCCTx() matched unspendabletokensaddr dual/three-eval CC addr.(%s)\n",unspendabletokensaddr); } // check if this is the 2nd additional evalcode + 'unspendable' cc addr: - else if ( strcmp(destaddr,cp->unspendableaddr2) == 0) + else if ( strcmp(destaddr, cp->unspendableaddr2) == 0) { - //fprintf(stderr,"FinalizeCCTx() matched %s unspendable2!\n",cp->unspendableaddr2); + fprintf(stderr,"FinalizeCCTx() matched %s unspendable2!\n",cp->unspendableaddr2); privkey = cp->unspendablepriv2; - if ( othercond2 == 0 ) - othercond2 = MakeCCcond1(cp->evalcode2, cp->unspendablepk2); + if( othercond2 == 0 ) + othercond2 = MakeCCcond1(cp->unspendableEvalcode2, cp->unspendablepk2); cond = othercond2; } // check if this is 3rd additional evalcode + 'unspendable' cc addr: else if ( strcmp(destaddr,cp->unspendableaddr3) == 0 ) { - //fprintf(stderr,"FinalizeCCTx() matched %s unspendable3!\n",cp->unspendableaddr3); + fprintf(stderr,"FinalizeCCTx() matched %s unspendable3!\n",cp->unspendableaddr3); privkey = cp->unspendablepriv3; - if ( othercond3 == 0 ) - othercond3 = MakeCCcond1(cp->evalcode3,cp->unspendablepk3); + if( othercond3 == 0 ) + othercond3 = MakeCCcond1(cp->unspendableEvalcode3, cp->unspendablepk3); cond = othercond3; } // check if this is spending from 1of2 cc coins addr: else if (strcmp(cp->coins1of2addr, destaddr) == 0) { - //fprintf(stderr,"FinalizeCCTx() matched %s unspendable1of2!\n",cp->coins1of2addr); + fprintf(stderr,"FinalizeCCTx() matched %s unspendable1of2!\n",cp->coins1of2addr); privkey = myprivkey; if (othercond1of2 == 0) othercond1of2 = MakeCCcond1of2(cp->evalcode, cp->coins1of2pk[0], cp->coins1of2pk[1]); @@ -215,10 +216,12 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran // check if this is spending from 1of2 cc tokens addr: else if (strcmp(cp->tokens1of2addr, destaddr) == 0) { - //fprintf(stderr,"FinalizeCCTx() matched %s cp->tokens1of2addr!\n", cp->tokens1of2addr); + fprintf(stderr,"FinalizeCCTx() matched %s cp->tokens1of2addr!\n", cp->tokens1of2addr); privkey = myprivkey; if (othercond1of2tokens == 0) - othercond1of2tokens = MakeTokensCCcond1of2(cp->evalcode, cp->tokens1of2pk[0], cp->tokens1of2pk[1]); + // NOTE: if additionalEvalcode2 is not set then it is dual-eval cc else three-eval cc + // TODO: verify evalcodes order if additionalEvalcode2 is not 0 + othercond1of2tokens = MakeTokensCCcond1of2(cp->evalcode, cp->additionalTokensEvalcode2, cp->tokens1of2pk[0], cp->tokens1of2pk[1]); cond = othercond1of2tokens; } else diff --git a/src/cc/CCutils.cpp b/src/cc/CCutils.cpp index 6dff5d3cd..6892f6fab 100644 --- a/src/cc/CCutils.cpp +++ b/src/cc/CCutils.cpp @@ -76,7 +76,8 @@ CTxOut MakeCC1of2vout(uint8_t evalcode,CAmount nValue,CPubKey pk1,CPubKey pk2) return(vout); } -CC *MakeTokensCCcond1of2(uint8_t evalcode, CPubKey pk1, CPubKey pk2) +// make three-eval (token+evalcode+evalcode2) 1of2 cryptocondition: +CC *MakeTokensCCcond1of2(uint8_t evalcode, uint8_t evalcode2, CPubKey pk1, CPubKey pk2) { // make 1of2 sigs cond std::vector pks; @@ -85,44 +86,68 @@ CC *MakeTokensCCcond1of2(uint8_t evalcode, CPubKey pk1, CPubKey pk2) std::vector thresholds; thresholds.push_back( CCNewEval(E_MARSHAL(ss << evalcode)) ); - if( evalcode != EVAL_TOKENS ) // if evalCode == EVAL_TOKENS, it is actually MakeCCcond1of2()! - thresholds.push_back(CCNewEval(E_MARSHAL(ss << (uint8_t)EVAL_TOKENS))); // this is eval token cc - thresholds.push_back(CCNewThreshold(1, pks)); // this is 1 of 2 sigs cc + if( evalcode != EVAL_TOKENS ) // if evalCode == EVAL_TOKENS, it is actually MakeCCcond1of2()! + thresholds.push_back(CCNewEval(E_MARSHAL(ss << (uint8_t)EVAL_TOKENS))); // this is eval token cc + if( evalcode2 != 0 ) + thresholds.push_back(CCNewEval(E_MARSHAL(ss << evalcode2))); // add optional additional evalcode + thresholds.push_back(CCNewThreshold(1, pks)); // this is 1 of 2 sigs cc return CCNewThreshold(thresholds.size(), thresholds); } +// overload to make two-eval (token+evalcode) 1of2 cryptocondition: +CC *MakeTokensCCcond1of2(uint8_t evalcode, CPubKey pk1, CPubKey pk2) { + return MakeTokensCCcond1of2(evalcode, 0, pk1, pk2); +} -CC *MakeTokensCCcond1(uint8_t evalcode, CPubKey pk) +// make three-eval (token+evalcode+evalcode2) cryptocondition: +CC *MakeTokensCCcond1(uint8_t evalcode, uint8_t evalcode2, CPubKey pk) { std::vector pks; pks.push_back(CCNewSecp256k1(pk)); std::vector thresholds; thresholds.push_back(CCNewEval(E_MARSHAL(ss << evalcode))); - if (evalcode != EVAL_TOKENS) // if evalCode == EVAL_TOKENS, it is actually MakeCCcond1()! - thresholds.push_back(CCNewEval(E_MARSHAL(ss << (uint8_t)EVAL_TOKENS))); // this is eval token cc - thresholds.push_back(CCNewThreshold(1, pks)); // signature + if (evalcode != EVAL_TOKENS) // if evalCode == EVAL_TOKENS, it is actually MakeCCcond1()! + thresholds.push_back(CCNewEval(E_MARSHAL(ss << (uint8_t)EVAL_TOKENS))); // this is eval token cc + if (evalcode2 != 0) + thresholds.push_back(CCNewEval(E_MARSHAL(ss << evalcode2))); // add optional additional evalcode + thresholds.push_back(CCNewThreshold(1, pks)); // signature return CCNewThreshold(thresholds.size(), thresholds); } +// overload to make two-eval (token+evalcode) cryptocondition: +CC *MakeTokensCCcond1(uint8_t evalcode, CPubKey pk) { + return MakeTokensCCcond1(evalcode, 0, pk); +} -CTxOut MakeTokensCC1of2vout(uint8_t evalcode, CAmount nValue, CPubKey pk1, CPubKey pk2) +// make three-eval (token+evalcode+evalcode2) 1of2 cc vout: +CTxOut MakeTokensCC1of2vout(uint8_t evalcode, uint8_t evalcode2, CAmount nValue, CPubKey pk1, CPubKey pk2) { CTxOut vout; - CC *payoutCond = MakeTokensCCcond1of2(evalcode, pk1, pk2); + CC *payoutCond = MakeTokensCCcond1of2(evalcode, evalcode2, pk1, pk2); vout = CTxOut(nValue, CCPubKey(payoutCond)); cc_free(payoutCond); return(vout); } +// overload to make two-eval (token+evalcode) 1of2 cc vout: +CTxOut MakeTokensCC1of2vout(uint8_t evalcode, CAmount nValue, CPubKey pk1, CPubKey pk2) { + return MakeTokensCC1of2vout(evalcode, 0, nValue, pk1, pk2); +} -CTxOut MakeTokensCC1vout(uint8_t evalcode, CAmount nValue, CPubKey pk) +// make three-eval (token+evalcode+evalcode2) cc vout: +CTxOut MakeTokensCC1vout(uint8_t evalcode, uint8_t evalcode2, CAmount nValue, CPubKey pk) { CTxOut vout; - CC *payoutCond = MakeTokensCCcond1(evalcode, pk); + CC *payoutCond = MakeTokensCCcond1(evalcode, evalcode2, pk); vout = CTxOut(nValue, CCPubKey(payoutCond)); cc_free(payoutCond); return(vout); } +// overload to make two-eval (token+evalcode) cc vout: +CTxOut MakeTokensCC1vout(uint8_t evalcode, CAmount nValue, CPubKey pk) { + return MakeTokensCC1vout(evalcode, 0, nValue, pk); +} + CC* GetCryptoCondition(CScript const& scriptSig) { @@ -227,17 +252,19 @@ CPubKey pubkey2pk(std::vector pubkey) return(pk); } +// set additional 'unspendable' addr void CCaddr2set(struct CCcontract_info *cp,uint8_t evalcode,CPubKey pk,uint8_t *priv,char *coinaddr) { - cp->evalcode2 = evalcode; + cp->unspendableEvalcode2 = evalcode; cp->unspendablepk2 = pk; memcpy(cp->unspendablepriv2,priv,32); strcpy(cp->unspendableaddr2,coinaddr); } +// set yet another additional 'unspendable' addr void CCaddr3set(struct CCcontract_info *cp,uint8_t evalcode,CPubKey pk,uint8_t *priv,char *coinaddr) { - cp->evalcode3 = evalcode; + cp->unspendableEvalcode3 = evalcode; cp->unspendablepk3 = pk; memcpy(cp->unspendablepriv3,priv,32); strcpy(cp->unspendableaddr3,coinaddr); @@ -251,12 +278,13 @@ void CCaddr1of2set(struct CCcontract_info *cp, CPubKey pk1, CPubKey pk2, char *c strcpy(cp->coins1of2addr, coinaddr); } -// set pubkeys, myprivkey and 1of2 cc addr for spending from 1of2 tokens cryptocondition vout: -void CCaddrTokens1of2set(struct CCcontract_info *cp, CPubKey pk1, CPubKey pk2, char *coinaddr) +// set pubkeys, myprivkey and 1of2 cc addr for spending from 1of2 token cryptocondition vout +// to get tokenaddr use GetTokensCCaddress() +void CCaddrTokens1of2set(struct CCcontract_info *cp, CPubKey pk1, CPubKey pk2, char *tokenaddr) { cp->tokens1of2pk[0] = pk1; cp->tokens1of2pk[1] = pk2; - strcpy(cp->tokens1of2addr, coinaddr); + strcpy(cp->tokens1of2addr, tokenaddr); } bool Getscriptaddress(char *destaddr,const CScript &scriptPubKey) @@ -351,11 +379,11 @@ bool GetCCaddress(struct CCcontract_info *cp,char *destaddr,CPubKey pk) return(_GetCCaddress(destaddr,cp->evalcode,pk)); } -bool _GetTokensCCaddress(char *destaddr, uint8_t evalcode, CPubKey pk) +bool _GetTokensCCaddress(char *destaddr, uint8_t evalcode, uint8_t evalcode2, CPubKey pk) { CC *payoutCond; destaddr[0] = 0; - if ((payoutCond = MakeTokensCCcond1(evalcode, pk)) != 0) + if ((payoutCond = MakeTokensCCcond1(evalcode, evalcode2, pk)) != 0) { Getscriptaddress(destaddr, CCPubKey(payoutCond)); cc_free(payoutCond); @@ -363,12 +391,13 @@ bool _GetTokensCCaddress(char *destaddr, uint8_t evalcode, CPubKey pk) return(destaddr[0] != 0); } +// get scriptPubKey adddress for three/dual eval token cc vout bool GetTokensCCaddress(struct CCcontract_info *cp, char *destaddr, CPubKey pk) { destaddr[0] = 0; if (pk.size() == 0) pk = GetUnspendable(cp, 0); - return(_GetTokensCCaddress(destaddr, cp->evalcode, pk)); + return(_GetTokensCCaddress(destaddr, cp->evalcode, cp->additionalTokensEvalcode2, pk)); } @@ -384,11 +413,12 @@ bool GetCCaddress1of2(struct CCcontract_info *cp,char *destaddr,CPubKey pk,CPubK return(destaddr[0] != 0); } +// get scriptPubKey adddress for three/dual eval token 1of2 cc vout bool GetTokensCCaddress1of2(struct CCcontract_info *cp, char *destaddr, CPubKey pk, CPubKey pk2) { CC *payoutCond; destaddr[0] = 0; - if ((payoutCond = MakeTokensCCcond1of2(cp->evalcode, pk, pk2)) != 0) + if ((payoutCond = MakeTokensCCcond1of2(cp->evalcode, cp->additionalTokensEvalcode2, pk, pk2)) != 0) // if additionalTokensEvalcode2 not set then it is dual-eval cc else three-eval cc { Getscriptaddress(destaddr, CCPubKey(payoutCond)); cc_free(payoutCond); @@ -515,7 +545,7 @@ CPubKey GetUnspendable(struct CCcontract_info *cp,uint8_t *unspendablepriv) void CCclearvars(struct CCcontract_info *cp) { - cp->evalcode2 = cp->evalcode3 = 0; + cp->unspendableEvalcode2 = cp->unspendableEvalcode3 = 0; cp->unspendableaddr2[0] = cp->unspendableaddr3[0] = 0; } diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index 6aae09dd3..97b01302c 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -14,6 +14,7 @@ ******************************************************************************/ #include "CCassets.h" +#include "CCtokens.h" /* Assets can be created or transferred. @@ -129,21 +130,21 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransaction &tx, uint32_t nIn) { static uint256 zero; - CTxDestination address; CTransaction vinTx,createTx; uint256 hashBlock,assetid,assetid2; - int32_t i,starti,numvins,numvouts,preventCCvins,preventCCvouts; - int64_t remaining_price,nValue,assetoshis,outputs,inputs,tmpprice,totalunits,ignore; std::vector origpubkey,tmporigpubkey,ignorepubkey; + CTxDestination address; + CTransaction vinTx, createTx; + uint256 hashBlock, assetid, assetid2; + int32_t i,starti, numvins, numvouts, preventCCvins, preventCCvouts; + int64_t remaining_price, nValue, assetoshis, outputsDummy,inputs,tmpprice,totalunits,ignore; + std::vector origpubkey, tmporigpubkey, ignorepubkey, vopretNonfungible, vopretNonfungibleDummy; uint8_t funcid, evalCodeInOpret; - char destaddr[64], origaddr[64], assetsCCaddr[64], userTokensCCaddr[64]; //, signleEvalTokensCCaddr[64]; + char destaddr[64], origNormalAddr[64], origTokensCCaddr[64], origCCaddrDummy[64]; + char tokensDualEvalUnspendableCCaddr[64], origAssetsCCaddr[64]; //return true; - //CPubKey unspendableTokensPk = GetUnspendable(cpTokens, NULL); - //CPubKey unspendableAssetsPk = GetUnspendable(cpAssets, NULL); - //GetCCaddress(cpTokens, tokensUnspendableCCaddr, unspendableTokensPk); - numvins = tx.vin.size(); numvouts = tx.vout.size(); - outputs = inputs = 0; + outputsDummy = inputs = 0; preventCCvins = preventCCvouts = -1; // add specific chains exceptions for old token support: @@ -156,13 +157,18 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti if (numvouts == 0) return eval->Invalid("AssetValidate: no vouts"); - if((funcid = DecodeAssetTokenOpRet(tx.vout[numvouts-1].scriptPubKey, evalCodeInOpret, assetid, assetid2, remaining_price, origpubkey)) == 0 ) + if((funcid = DecodeAssetTokenOpRet(tx.vout[numvouts-1].scriptPubKey, evalCodeInOpret, assetid, assetid2, remaining_price, origpubkey, vopretNonfungibleDummy)) == 0 ) return eval->Invalid("AssetValidate: invalid opreturn payload"); + // non-fungible tokens support: + GetNonfungibleData(assetid, vopretNonfungible); + if (vopretNonfungible.size() > 0) + cpAssets->additionalTokensEvalcode2 = vopretNonfungible.begin()[0]; + // find dual-eval tokens unspendable addr: - char tokensUnspendableAddr[64],origpubkeyCCaddr[64]; - GetTokensCCaddress(cpAssets, tokensUnspendableAddr, GetUnspendable(cpAssets, NULL)); - GetCCaddress(cpAssets, origpubkeyCCaddr, origpubkey); + GetTokensCCaddress(cpAssets, tokensDualEvalUnspendableCCaddr, GetUnspendable(cpAssets, NULL)); + // this is for marker validation: + GetCCaddress(cpAssets, origAssetsCCaddr, origpubkey); // we need this for validating single-eval tokens' vins/vous: struct CCcontract_info *cpTokens, tokensC; @@ -177,7 +183,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti return eval->Invalid("cant find asset create txid"); else if( funcid != 'o' && funcid != 'x' && assetid2 != zero && eval->GetTxUnconfirmed(assetid2, createTx, hashBlock) == 0 ) return eval->Invalid("cant find asset2 create txid"); - else if( IsCCInput(tx.vin[0].scriptSig) != 0 ) + else if( IsCCInput(tx.vin[0].scriptSig) != 0 ) // vin0 should be normal vin return eval->Invalid("illegal asset vin0"); else if( numvouts < 2 ) return eval->Invalid("too few vouts"); // it was if(numvouts < 1) but it refers at least to vout[1] below @@ -191,7 +197,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti if( assetid == zero ) return eval->Invalid("illegal assetid"); - else if (!AssetCalcAmounts(cpAssets, inputs, outputs, eval, tx, assetid)) { // Only set inputs and outputs. NOTE: we do not need to check cc inputs == cc outputs + else if (!AssetCalcAmounts(cpAssets, inputs, outputsDummy/*outputsDummy is calculated incorrectly but not used*/, eval, tx, assetid)) { // Only set inputs and outputs. NOTE: we do not need to check cc inputs == cc outputs return false; // returns false if some problems with reading vintxes } } @@ -226,9 +232,13 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti //vout.1: CC output for marker //vout.2: normal output for change (if any) // vout.n-1: opreturn [EVAL_ASSETS] ['b'] [assetid] [amount of asset required] [origpubkey] + + // as we don't use tokenconvert we should not be here: + return eval->Invalid("invalid asset funcid (b)"); + if( remaining_price == 0 ) return eval->Invalid("illegal null amount for buyoffer"); - else if( ConstrainVout(tx.vout[0],1,cpAssets->unspendableCCaddr,0) == 0 ) + else if( ConstrainVout(tx.vout[0], 1, cpAssets->unspendableCCaddr,0) == 0 ) // coins to assets unspendable cc addr return eval->Invalid("invalid vout for buyoffer"); preventCCvins = 1; preventCCvouts = 1; @@ -243,13 +253,13 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti //vout.1: vin.2 back to users pubkey //vout.2: normal output for change (if any) //vout.n-1: opreturn [EVAL_ASSETS] ['o'] - if( (nValue= AssetValidateBuyvin(cpAssets, eval, tmpprice, tmporigpubkey, assetsCCaddr, origaddr, tx, assetid)) == 0 ) + if( (nValue= AssetValidateBuyvin(cpAssets, eval, tmpprice, tmporigpubkey, origCCaddrDummy, origNormalAddr, tx, assetid)) == 0 ) return(false); - else if( ConstrainVout(tx.vout[0],0, origaddr, nValue) == 0 ) + else if( ConstrainVout(tx.vout[0],0, origNormalAddr, nValue) == 0 ) return eval->Invalid("invalid refund for cancelbuy"); preventCCvins = 3; preventCCvouts = 0; - fprintf(stderr,"cancelbuy validated to origaddr.(%s)\n",origaddr); + fprintf(stderr,"cancelbuy validated to origaddr.(%s)\n",origNormalAddr); break; case 'B': // fillbuy: @@ -264,7 +274,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti //vout.n-1: opreturn [EVAL_ASSETS] ['B'] [assetid] [remaining asset required] [origpubkey] preventCCvouts = 4; - if( (nValue = AssetValidateBuyvin(cpAssets, eval, totalunits, tmporigpubkey, assetsCCaddr, origaddr, tx, assetid)) == 0 ) + if( (nValue = AssetValidateBuyvin(cpAssets, eval, totalunits, tmporigpubkey, origTokensCCaddr, origNormalAddr, tx, assetid)) == 0 ) return(false); else if( numvouts < 4 ) return eval->Invalid("not enough vouts for fillbuy"); @@ -274,24 +284,24 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti { if( nValue != tx.vout[0].nValue + tx.vout[1].nValue ) return eval->Invalid("locked value doesnt match vout0+1 fillbuy"); - else if( tx.vout[4].scriptPubKey.IsPayToCryptoCondition() != 0 ) + else if( tx.vout[4].scriptPubKey.IsPayToCryptoCondition() != 0 ) // if cc change present { - if( ConstrainVout(tx.vout[2], 1, assetsCCaddr, 0) == 0 ) // tokens on user cc addr + if( ConstrainVout(tx.vout[2], 1, origTokensCCaddr, 0) == 0 ) // tokens to originator cc addr (tokens+nonfungible evals) return eval->Invalid("vout2 doesnt go to origpubkey fillbuy"); else if ( inputs != tx.vout[2].nValue + tx.vout[4].nValue ) return eval->Invalid("asset inputs doesnt match vout2+3 fillbuy"); } - else if( ConstrainVout(tx.vout[2], 1, assetsCCaddr, inputs) == 0 ) // tokens on user cc addr + else if( ConstrainVout(tx.vout[2], 1, origTokensCCaddr, inputs) == 0 ) // tokens to originator cc addr (tokens+nonfungible evals) return eval->Invalid("vout2 doesnt match inputs fillbuy"); - else if( ConstrainVout(tx.vout[1],0,0,0) == 0 ) + else if( ConstrainVout(tx.vout[1], 0, NULL, 0) == 0 ) return eval->Invalid("vout1 is CC for fillbuy"); - else if( ConstrainVout(tx.vout[3], 1, origpubkeyCCaddr, 10000) == 0 ) + else if( ConstrainVout(tx.vout[3], 1, origAssetsCCaddr, 10000) == 0 ) // marker to asset cc addr return eval->Invalid("invalid marker for original pubkey"); else if( ValidateBidRemainder(remaining_price, tx.vout[0].nValue, nValue, tx.vout[1].nValue, tx.vout[2].nValue, totalunits) == false ) return eval->Invalid("mismatched remainder for fillbuy"); else if( remaining_price != 0 ) { - if( ConstrainVout(tx.vout[0], 1, cpAssets->unspendableCCaddr, 0) == 0 ) // coins on asset unspendable cc addr + if( ConstrainVout(tx.vout[0], 1, cpAssets->unspendableCCaddr, 0) == 0 ) // coins to asset unspendable cc addr return eval->Invalid("mismatched vout0 AssetsCCaddr for fillbuy"); } } @@ -308,25 +318,30 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti //vout.3: normal output for change (if any) //'s'.vout.n-1: opreturn [EVAL_ASSETS] ['s'] [assetid] [amount of native coin required] [origpubkey] //'e'.vout.n-1: opreturn [EVAL_ASSETS] ['e'] [assetid] [assetid2] [amount of asset2 required] [origpubkey] + + // as we don't use tokenconvert we should not be here: + return eval->Invalid("invalid asset funcid (s)"); + preventCCvouts = 2; if( remaining_price == 0 ) return eval->Invalid("illegal null remaining_price for selloffer"); if ( tx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 ) return eval->Invalid("invalid normal vout1 for sellvin"); - if( tx.vout[2].scriptPubKey.IsPayToCryptoCondition() != 0 ) // cc change + if( tx.vout[2].scriptPubKey.IsPayToCryptoCondition() != 0 ) // if cc change presents { preventCCvouts++; - if( ConstrainVout(tx.vout[0], 1, (char *)cpTokens->unspendableCCaddr, 0) == 0 ) // check also cc vout[0] + if( ConstrainVout(tx.vout[0], 1, (char *)cpTokens->unspendableCCaddr, 0) == 0 ) // tokens to tokens unspendable cc addr. TODO: this in incorrect, should be assets if we got here! return eval->Invalid("mismatched vout0 TokensCCaddr for selloffer"); else if( tx.vout[0].nValue + tx.vout[2].nValue != inputs ) return eval->Invalid("mismatched vout0+vout2 total for selloffer"); } - else if( ConstrainVout(tx.vout[0], 1, (char *)cpTokens->unspendableCCaddr, inputs) == 0 ) // no cc change, just vout[0] + // no cc change: + else if( ConstrainVout(tx.vout[0], 1, (char *)cpTokens->unspendableCCaddr, inputs) == 0 ) // tokens to tokens unspendable cc addr TODO: this in incorrect, should be assets if got here! return eval->Invalid("mismatched vout0 TokensCCaddr for selloffer"); //fprintf(stderr,"remaining.%d for sell\n",(int32_t)remaining_price); break; - case 'x': // cancel + case 'x': // cancel sell //vin.0: normal input //vin.1: unspendable.(vout.0 from exchange or selloffer) sellTx/exchangeTx.vout[0] inputTx //vin.2: CC marker from selloffer for txfee @@ -335,9 +350,9 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti //vout.2: normal output for change (if any) //vout.n-1: opreturn [EVAL_ASSETS] ['x'] [assetid] - if( (assetoshis = AssetValidateSellvin(cpAssets, eval, tmpprice, tmporigpubkey, userTokensCCaddr, origaddr, tx, assetid)) == 0 ) // NOTE: + if( (assetoshis = AssetValidateSellvin(cpAssets, eval, tmpprice, tmporigpubkey, origTokensCCaddr, origNormalAddr, tx, assetid)) == 0 ) // NOTE: return(false); - else if( ConstrainVout(tx.vout[0], 1, userTokensCCaddr, assetoshis) == 0 ) + else if( ConstrainVout(tx.vout[0], 1, origTokensCCaddr, assetoshis) == 0 ) // tokens returning to originator cc addr return eval->Invalid("invalid vout for cancel"); preventCCvins = 3; preventCCvouts = 1; @@ -353,7 +368,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti //vout.3: normal output for change (if any) //'S'.vout.n-1: opreturn [EVAL_ASSETS] ['S'] [assetid] [amount of coin still required] [origpubkey] - if( (assetoshis = AssetValidateSellvin(cpAssets, eval, totalunits, tmporigpubkey, userTokensCCaddr, origaddr, tx, assetid)) == 0 ) + if( (assetoshis = AssetValidateSellvin(cpAssets, eval, totalunits, tmporigpubkey, origTokensCCaddr, origNormalAddr, tx, assetid)) == 0 ) return(false); else if( numvouts < 4 ) return eval->Invalid("not enough vouts for fillask"); @@ -365,17 +380,15 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti return eval->Invalid("locked value doesnt match vout0+1 fillask"); if( ValidateAskRemainder(remaining_price, tx.vout[0].nValue, assetoshis, tx.vout[1].nValue, tx.vout[2].nValue, totalunits) == false ) return eval->Invalid("mismatched remainder for fillask"); - else if( ConstrainVout(tx.vout[1], 1, 0, 0) == 0 ) + else if( ConstrainVout(tx.vout[1], 1, NULL, 0) == 0 ) // do not check token buyer's cc addr return eval->Invalid("normal vout1 for fillask"); - else if( ConstrainVout(tx.vout[2], 0, origaddr, 0) == 0 ) + else if( ConstrainVout(tx.vout[2], 0, origNormalAddr, 0) == 0 ) // coins to originator normal addr return eval->Invalid("normal vout1 for fillask"); - else if( ConstrainVout(tx.vout[3], 1, origpubkeyCCaddr, 10000) == 0 ) + else if( ConstrainVout(tx.vout[3], 1, origAssetsCCaddr, 10000) == 0 ) // marker to originator asset cc addr return eval->Invalid("invalid marker for original pubkey"); else if( remaining_price != 0 ) { - //char tokensUnspendableAddr[64]; - //GetTokensCCaddress(cpAssets, tokensUnspendableAddr, GetUnspendable(cpAssets, NULL)); - if ( ConstrainVout(tx.vout[0], 1, tokensUnspendableAddr /*(char *)cpAssets->unspendableCCaddr*/, 0) == 0 ) + if ( ConstrainVout(tx.vout[0], 1, tokensDualEvalUnspendableCCaddr, 0) == 0 ) return eval->Invalid("mismatched vout0 assets dual unspendable CCaddr for fill sell"); } } @@ -399,7 +412,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti // eval->Invalid("asset2 inputs != outputs"); ////////// not implemented yet //////////// - if( (assetoshis= AssetValidateSellvin(cpTokens, eval, totalunits, tmporigpubkey, userTokensCCaddr, origaddr, tx, assetid)) == 0 ) + if( (assetoshis= AssetValidateSellvin(cpTokens, eval, totalunits, tmporigpubkey, origTokensCCaddr, origNormalAddr, tx, assetid)) == 0 ) return(false); else if( numvouts < 3 ) return eval->Invalid("not enough vouts for fillex"); @@ -412,7 +425,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti else if( tx.vout[3].scriptPubKey.IsPayToCryptoCondition() != 0 ) ////////// not implemented yet //////////// { - if( ConstrainVout(tx.vout[2], 1, userTokensCCaddr, 0) == 0 ) + if( ConstrainVout(tx.vout[2], 1, origTokensCCaddr, 0) == 0 ) return eval->Invalid("vout2 doesnt go to origpubkey fillex"); else if( inputs != tx.vout[2].nValue + tx.vout[3].nValue ) { @@ -421,7 +434,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti } } ////////// not implemented yet //////////// - else if( ConstrainVout(tx.vout[2], 1, userTokensCCaddr, inputs) == 0 ) + else if( ConstrainVout(tx.vout[2], 1, origTokensCCaddr, inputs) == 0 ) return eval->Invalid("vout2 doesnt match inputs fillex"); else if( ConstrainVout(tx.vout[1], 0, 0, 0) == 0 ) return eval->Invalid("vout1 is CC for fillex"); diff --git a/src/cc/oracles.cpp b/src/cc/oracles.cpp index 66c0e1b9a..a1d349c12 100644 --- a/src/cc/oracles.cpp +++ b/src/cc/oracles.cpp @@ -171,7 +171,7 @@ CPubKey OracleBatonPk(char *batonaddr,struct CCcontract_info *cp) if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); Myprivkey(priv); - cp->evalcode2 = EVAL_ORACLES; + cp->unspendableEvalcode2 = EVAL_ORACLES; for (i=0; i<32; i++) cp->unspendablepriv2[i] = (priv[i] ^ cp->CCpriv[i]); while ( secp256k1_ec_seckey_verify(ctx,cp->unspendablepriv2) == 0 ) diff --git a/src/cc/prices.cpp b/src/cc/prices.cpp index 369495b1a..03a4d2b9c 100644 --- a/src/cc/prices.cpp +++ b/src/cc/prices.cpp @@ -13,6 +13,7 @@ * * ******************************************************************************/ +#include "CCassets.h" #include "CCPrices.h" /* @@ -89,6 +90,9 @@ uint8_t DecodePricesFundingOpRet(CScript scriptPubKey,CPubKey &planpk,uint256 &o bool PricesValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx, uint32_t nIn) { int32_t numvins,numvouts,preventCCvins,preventCCvouts,i,numblocks; bool retval; uint256 txid; uint8_t hash[32]; char str[65],destaddr[64]; + + return true; // TODO remove, for test dual-evals + return eval->Invalid("no validation yet"); std::vector > txids; numvins = tx.vin.size(); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index f8fe7de20..abd0b9696 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -7038,75 +7038,98 @@ UniValue tokenbalance(const UniValue& params, bool fHelp) UniValue tokencreate(const UniValue& params, bool fHelp) { - UniValue result(UniValue::VOBJ); std::string name,description,hex; uint64_t supply; - if ( fHelp || params.size() > 3 || params.size() < 2 ) - throw runtime_error("tokencreate name supply description\n"); + UniValue result(UniValue::VOBJ); + std::string name, description, hextx; + std::vector nonfungibleData; + int64_t supply; // changed from uin64_t to int64_t for this 'if ( supply <= 0 )' to work as expected + + CCerror.clear(); + + if ( fHelp || params.size() > 4 || params.size() < 2 ) + throw runtime_error("tokencreate name supply [description][data]\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); + name = params[0].get_str(); - supply = atof(params[1].get_str().c_str()) * COIN + 0.00000000499999; // what for is this '+0.00000000499999'? it will be lost while converting double to int64_t (dimxy) - if ( name.size() == 0 || name.size() > 32) - { + if (name.size() == 0 || name.size() > 32) { ERR_RESULT("Token name must not be empty and up to 32 characters"); return(result); } - if ( supply <= 0 ) - { + + supply = atof(params[1].get_str().c_str()) * COIN + 0.00000000499999; // what for is this '+0.00000000499999'? it will be lost while converting double to int64_t (dimxy) + if (supply <= 0) { ERR_RESULT("Token supply must be positive"); return(result); } - if ( params.size() == 3 ) - { + + if (params.size() >= 3) { description = params[2].get_str(); - if ( description.size() > 4096 ) - { + if (description.size() > 4096) { ERR_RESULT("Token description must be <= 4096 characters"); return(result); } } - hex = CreateToken(0,supply,name,description); - if ( hex.size() > 0 ) - { + + if (params.size() == 4) { + nonfungibleData = ParseHex(params[3].get_str()); + if (nonfungibleData.size() > 10000) // opret limit + { + ERR_RESULT("Non-fungible data must be <= 10000"); + return(result); + } + } + + hextx = CreateToken(0, supply, name, description, nonfungibleData); + if( hextx.size() > 0 ) { result.push_back(Pair("result", "success")); - result.push_back(Pair("hex", hex)); - } else ERR_RESULT("couldnt create transaction"); + result.push_back(Pair("hex", hextx)); + } + else + ERR_RESULT(CCerror); return(result); } UniValue tokentransfer(const UniValue& params, bool fHelp) { - UniValue result(UniValue::VOBJ); std::string hex; int64_t amount; uint256 tokenid; - if ( fHelp || params.size() != 3 ) + UniValue result(UniValue::VOBJ); + std::string hex; + int64_t amount; + uint256 tokenid; + + CCerror.clear(); + + if ( fHelp || params.size() != 3) throw runtime_error("tokentransfer tokenid destpubkey amount\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); + tokenid = Parseuint256((char *)params[0].get_str().c_str()); std::vector pubkey(ParseHex(params[1].get_str().c_str())); //amount = atol(params[2].get_str().c_str()); amount = atoll(params[2].get_str().c_str()); // dimxy changed to prevent loss of significance - if ( tokenid == zeroid ) - { + if( tokenid == zeroid ) { ERR_RESULT("invalid tokenid"); return(result); } - if ( amount <= 0 ) - { + if( amount <= 0 ) { ERR_RESULT("amount must be positive"); return(result); } - hex = TokenTransfer(0,tokenid,pubkey,amount); - if (amount > 0) { - if ( hex.size() > 0 ) - { - result.push_back(Pair("result", "success")); - result.push_back(Pair("hex", hex)); - } else ERR_RESULT("couldnt transfer assets"); - } else { - ERR_RESULT("amount must be positive"); + + hex = TokenTransfer(0, tokenid, pubkey, amount); + + if( !CCerror.empty() ) { + ERR_RESULT(CCerror); + } + else { + result.push_back(Pair("result", "success")); + result.push_back(Pair("hex", hex)); } return(result); } @@ -7786,3 +7809,4 @@ UniValue test_heirmarker(const UniValue& params, bool fHelp) cp = CCinit(&C, EVAL_HEIR); return(FinalizeCCTx(0, cp, mtx, myPubkey, 10000, opret)); } + From 9919b39bce506841dc71b6068949d91733e25bc2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 01:15:06 -1100 Subject: [PATCH 0435/1145] Remove gametxid.vout[1] usage --- src/cc/rogue/new_level.c | 2 +- src/cc/rogue_rpc.cpp | 11 +++++------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/cc/rogue/new_level.c b/src/cc/rogue/new_level.c index 9b2348b3f..9dc0d761f 100644 --- a/src/cc/rogue/new_level.c +++ b/src/cc/rogue/new_level.c @@ -167,7 +167,7 @@ put_things(struct rogue_state *rs) obj->o_hplus = 0; obj->o_dplus = 0; strncpy(obj->o_damage,"0x0",sizeof(obj->o_damage)); - strncpy(obj->o_hurldmg,"0x0",sizeof(obj->o_hurldmg)); + strncpy(obj->o_hurldmg,"0x0",sizeof(obj->o_hurldmg)); obj->o_arm = 11; obj->o_type = AMULET; /* diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5489b75f6..59f3beee6 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -128,12 +128,12 @@ // cclib newgame 17 \"[3,10]\" // cclib pending 17 -// cclib gameinfo 17 \"[%2284d3c1b598c9e2b3891a6b33468ec526cfaa9c7024c578025cdaff24b5ea3d20%22]\" -// cclib register 17 \"[%2284d3c1b598c9e2b3891a6b33468ec526cfaa9c7024c578025cdaff24b5ea3d20%22]\" +// cclib gameinfo 17 \"[%2250ad0155ea102f94949d51cc911e1d41ac03d24caf1a79cf5e0a4d9cc05ed836%22]\" +// cclib register 17 \"[%2250ad0155ea102f94949d51cc911e1d41ac03d24caf1a79cf5e0a4d9cc05ed836%22]\" // ./rogue gui -> creates keystroke files -// cclib register 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd%22]\" +// cclib register 17 \"[%2250ad0155ea102f94949d51cc911e1d41ac03d24caf1a79cf5e0a4d9cc05ed836%22,%2233d52f92980ceaa81556093171ee224e085fd384690d83460d6fbbad96fe0e7e%22]\" // cclib keystrokes 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22deadbeef%22]\" -// cclib bailout 17 \"[%2284d3c1b598c9e2b3891a6b33468ec526cfaa9c7024c578025cdaff24b5ea3d20%22]\" +// cclib bailout 17 \"[%2250ad0155ea102f94949d51cc911e1d41ac03d24caf1a79cf5e0a4d9cc05ed836%22]\" // eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd /* 2409 gold.209 hp.17 strength.16 level.3 exp.22 3 @@ -446,10 +446,9 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,uint256 origplayergame) { int64_t txfee = 10000; - if ( CCgettxout(playertxid,0,1) == txfee && CCgettxout(origplayergame,1,1) == txfee ) // not sure if this is enough validation + if ( CCgettxout(playertxid,0,1) == 1 ) // not sure if this is enough validation { mtx.vin.push_back(CTxIn(playertxid,0,CScript())); - mtx.vin.push_back(CTxIn(origplayergame,1,CScript())); return(0); } else return(-1); } From a98a2413e88d462c065c15f395683e0b28a8e07a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 01:24:51 -1100 Subject: [PATCH 0436/1145] Ismine and datastr --- src/cc/rogue_rpc.cpp | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 59f3beee6..47b166ce2 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -362,12 +362,17 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid) { - int32_t i; struct rogue_player P; char packitemstr[512]; UniValue obj(UniValue::VOBJ),a(UniValue::VARR); + int32_t i; struct rogue_player P; char packitemstr[512],*datastr; UniValue obj(UniValue::VOBJ),a(UniValue::VARR); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { + datastr = (char *)malloc(playerdata.size()*2+1); for (i=0; i playerdata,uint256 playertxid) a.push_back(packitemstr); } obj.push_back(Pair("playertxid",playertxid.GetHex())); + obj.push_back(Pair("data",datastr)); + free(datastr); obj.push_back(Pair("pack",a)); obj.push_back(Pair("packsize",(int64_t)P.packsize)); obj.push_back(Pair("hitpoints",(int64_t)P.hitpoints)); @@ -541,7 +548,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke return(-1); } -void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers) +void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers,char *myrogueaddr) { // identify if bailout or quit or timed out uint256 batontxid,spenttxid,gtxid,ptxid,hashBlock,playertxid; CTransaction spenttx,batontx; int32_t numplayers,regslot,numkeys,batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; @@ -565,6 +572,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet } else obj.push_back(Pair("status","finished")); obj.push_back(Pair("baton",batontxid.ToString())); obj.push_back(Pair("batonaddr",destaddr)); + obj.push_back(Pair("ismine",strcmp(myrogueaddr,destaddr)==0)); obj.push_back(Pair("batonvout",(int64_t)batonvout)); obj.push_back(Pair("batonvalue",ValueFromAmount(batonvalue))); obj.push_back(Pair("batonht",(int64_t)batonht)); @@ -885,7 +893,7 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( CCgettxout(txid,i+1,1) < 0 ) { UniValue obj(UniValue::VOBJ); - rogue_gameplayerinfo(cp,obj,txid,tx,i+1,maxplayers); + rogue_gameplayerinfo(cp,obj,txid,tx,i+1,maxplayers,myrogueaddr); a.push_back(obj); } } From a42b9198df6654ffa4381b2b52d9c5e64bd587b6 Mon Sep 17 00:00:00 2001 From: dimxy Date: Sun, 10 Feb 2019 17:48:24 +0500 Subject: [PATCH 0437/1145] logging param changed to "cctokens" "ccassets" --- src/cc/CCassetsCore.cpp | 11 +++-- src/cc/CCtokens.cpp | 92 ++++++++++++++++++++--------------------- 2 files changed, 51 insertions(+), 52 deletions(-) diff --git a/src/cc/CCassetsCore.cpp b/src/cc/CCassetsCore.cpp index f14de3956..1aa654a89 100644 --- a/src/cc/CCassetsCore.cpp +++ b/src/cc/CCassetsCore.cpp @@ -295,7 +295,7 @@ uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCo // First - decode token opret: funcId = DecodeTokenOpRet(scriptPubKey, dummyEvalCode, tokenid, voutPubkeysDummy, vopret1, vopret2); - std::cerr << "DecodeAssetTokenOpRet() from DecodeTokenOpRet returned funcId=" << (int)funcId << std::endl; + LOGSTREAM("ccassets", CCLOG_DEBUG2, stream << "DecodeAssetTokenOpRet() from DecodeTokenOpRet returned funcId=" << (int)funcId << std::endl); if (!vopret2.empty()) { // if there are both oprets then order is like this: @@ -319,7 +319,7 @@ uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCo //bool result = E_UNMARSHAL(vopret, ss >> evalCodeInOpret; ss >> funcId; ss >> tokenid; ss >> assetFuncId; isEof = ss.eof()); if (funcId == 0 || vopretAssets.size() < 2) { - std::cerr << "DecodeAssetTokenOpRet() incorrect opret or no asset's payload" << " funcId=" << (int)funcId << " vopretAssets.size()=" << vopretAssets.size() << std::endl; + LOGSTREAM("ccassets", CCLOG_INFO, stream << "DecodeAssetTokenOpRet() incorrect opret or no asset's payload" << " funcId=" << (int)funcId << " vopretAssets.size()=" << vopretAssets.size() << std::endl); return (uint8_t)0; } @@ -334,7 +334,7 @@ uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCo assetsEvalCode = vopretAssets.begin()[0]; assetsFuncId = vopretAssets.begin()[1]; - //std::cerr << "DecodeAssetTokenOpRet() evalCodeInOpret=" << (int)evalCodeInOpret << " funcId=" << (char)(funcId ? funcId : ' ') << " assetFuncId=" << (char)(assetFuncId ? assetFuncId : ' ') << std::endl; + LOGSTREAM("ccassets", CCLOG_DEBUG2, stream << "DecodeAssetTokenOpRet() assetsEvalCode=" << (int)assetsEvalCode << " funcId=" << (char)(funcId ? funcId : ' ') << " assetsFuncId=" << (char)(assetsFuncId ? assetsFuncId : ' ') << std::endl); if (assetsEvalCode == EVAL_ASSETS) { @@ -363,14 +363,13 @@ uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCo } break; default: - fprintf(stderr, "DecodeAssetTokenOpRet() illegal assetFuncId.%02x\n", assetsFuncId); - //funcId = 0; + LOGSTREAM("ccassets", CCLOG_INFO, stream << "DecodeAssetTokenOpRet() illegal assetFuncId=" << (int)funcId << std::endl); break; } } } - std::cerr << "DecodeAssetTokenOpRet() no asset's payload or incorrect assets evalcode" << " funcId=" << (int)funcId << " vopretAssets.size()=" << vopretAssets.size() << " assetsEvalCode=" << assetsEvalCode << " assetsFuncId=" << assetsFuncId << std::endl; + LOGSTREAM("ccassets", CCLOG_INFO, stream << "DecodeAssetTokenOpRet() no asset's payload or incorrect assets evalcode" << " funcId=" << (int)funcId << " vopretAssets.size()=" << vopretAssets.size() << " assetsEvalCode=" << assetsEvalCode << " assetsFuncId=" << assetsFuncId << std::endl); return (uint8_t)0; } diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index 23a4fda50..6cbe9496f 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -73,7 +73,7 @@ CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, std: if (voutPubkeys.size() >= 0 && voutPubkeys.size() <= 2) ccType = voutPubkeys.size(); else { - LOGSTREAM("tokens", CCLOG_INFO, stream << "EncodeTokenOpRet voutPubkeys.size()=" << voutPubkeys.size() << " not supported" << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "EncodeTokenOpRet voutPubkeys.size()=" << voutPubkeys.size() << " not supported" << std::endl); } std::vector vpayload; @@ -173,7 +173,7 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, ui return (uint8_t)0; funcId = script[1]; - LOGSTREAM("tokens", CCLOG_DEBUG1, stream << "DecodeTokenOpRet decoded funcId=" << (char)(funcId?funcId:' ')); + LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << "DecodeTokenOpRet decoded funcId=" << (char)(funcId?funcId:' ')); switch( funcId ) { @@ -195,7 +195,7 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, ui { if (!(ccType >= 0 && ccType <= 2)) { //incorrect ccType - LOGSTREAM("tokens", CCLOG_INFO, stream << "DecodeTokenOpRet() incorrect ccType=" << (int)ccType << " tokenid=" << revuint256(tokenid).GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "DecodeTokenOpRet() incorrect ccType=" << (int)ccType << " tokenid=" << revuint256(tokenid).GetHex() << std::endl); return (uint8_t)0; } @@ -209,16 +209,16 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, ui tokenid = revuint256(tokenid); return(funcId); } - LOGSTREAM("tokens", CCLOG_INFO, stream << "DecodeTokenOpRet() bad opret format, isEof=" << isEof << " ccType=" << ccType << " tokenid=" << revuint256(tokenid).GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "DecodeTokenOpRet() bad opret format, isEof=" << isEof << " ccType=" << ccType << " tokenid=" << revuint256(tokenid).GetHex() << std::endl); return (uint8_t)0; default: - LOGSTREAM("tokens", CCLOG_INFO, stream << "DecodeTokenOpRet() illegal funcid=" << (int)funcId << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "DecodeTokenOpRet() illegal funcid=" << (int)funcId << std::endl); return (uint8_t)0; } } else { - LOGSTREAM("tokens", CCLOG_INFO, stream << "DecodeTokenOpRet() empty opret, could not parse" << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "DecodeTokenOpRet() empty opret, could not parse" << std::endl); } return (uint8_t)0; } @@ -245,7 +245,7 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & if ((funcid = DecodeTokenOpRet(tx.vout[numvouts - 1].scriptPubKey, evalCodeInOpret, tokenid, voutTokenPubkeys, vopret1, vopret2)) == 0) return eval->Invalid("TokenValidate: invalid opreturn payload"); - LOGSTREAM("tokens", CCLOG_INFO, stream << "TokensValidate funcId=" << (char)(funcid?funcid:' ') << " evalcode=" << cp->evalcode); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "TokensValidate funcId=" << (char)(funcid?funcid:' ') << " evalcode=" << cp->evalcode << std::endl); if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) return eval->Invalid("cant find token create txid"); @@ -293,11 +293,11 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & if (inputs == 0) return eval->Invalid("no token inputs for transfer"); - LOGSTREAM("tokens", CCLOG_INFO, stream << "token transfer preliminarily validated inputs=" << inputs << "->outputs=" << outputs << " preventCCvins=" << preventCCvins<< " preventCCvouts=" << preventCCvouts << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "token transfer preliminarily validated inputs=" << inputs << "->outputs=" << outputs << " preventCCvins=" << preventCCvins<< " preventCCvouts=" << preventCCvouts << std::endl); break; // breaking to other contract validation... default: - LOGSTREAM("tokens", CCLOG_INFO, stream << "illegal tokens funcid=" << (char)(funcid?funcid:' ') << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "illegal tokens funcid=" << (char)(funcid?funcid:' ') << std::endl); return eval->Invalid("unexpected token funcid"); } @@ -383,32 +383,32 @@ uint8_t ValidateTokenOpret(CTransaction tx, uint256 tokenid) { if ((funcid = DecodeTokenOpRet(tx.vout.back().scriptPubKey, dummyEvalCode, tokenidOpret, voutPubkeysDummy, vopretExtraDummy)) == 0) { - LOGSTREAM("tokens", CCLOG_INFO, stream << indentStr << "ValidateTokenOpret() DecodeTokenOpret could not parse opret for txid=" << tx.GetHash().GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << indentStr << "ValidateTokenOpret() DecodeTokenOpret could not parse opret for txid=" << tx.GetHash().GetHex() << std::endl); return (uint8_t)0; } else if (funcid == 'c') { if (tokenid != zeroid && tokenid == tx.GetHash()) { - LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() this is the tokenbase 'c' tx, txid=" << tx.GetHash().GetHex() << " returning true" << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() this is the tokenbase 'c' tx, txid=" << tx.GetHash().GetHex() << " returning true" << std::endl); return funcid; } else { - LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not my tokenbase txid=" << tx.GetHash().GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not my tokenbase txid=" << tx.GetHash().GetHex() << std::endl); } } else if (funcid == 't') { //std::cerr << indentStr << "ValidateTokenOpret() tokenid=" << tokenid.GetHex() << " tokenIdOpret=" << tokenidOpret.GetHex() << " txid=" << tx.GetHash().GetHex() << std::endl; if (tokenid != zeroid && tokenid == tokenidOpret) { - LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() this is a transfer 't' tx, txid=" << tx.GetHash().GetHex() << " returning true" << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() this is a transfer 't' tx, txid=" << tx.GetHash().GetHex() << " returning true" << std::endl); return funcid; } else { - LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not my tokenid=" << tokenidOpret.GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not my tokenid=" << tokenidOpret.GetHex() << std::endl); } } else { - LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not supported funcid=" << (char)funcid << " tokenIdOpret=" << tokenidOpret.GetHex() << " txid=" << tx.GetHash().GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not supported funcid=" << (char)funcid << " tokenIdOpret=" << tokenidOpret.GetHex() << " txid=" << tx.GetHash().GetHex() << std::endl); } return (uint8_t)0; } @@ -424,12 +424,12 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c // this is just for log messages indentation fur debugging recursive calls: std::string indentStr = std::string().append(tokenValIndentSize, '.'); - LOGSTREAM("tokens", CCLOG_DEBUG2, stream << indentStr << "IsTokensvout() entered for txid=" << tx.GetHash().GetHex() << " v=" << v << " for tokenid=" << reftokenid.GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG2, stream << indentStr << "IsTokensvout() entered for txid=" << tx.GetHash().GetHex() << " v=" << v << " for tokenid=" << reftokenid.GetHex() << std::endl); int32_t n = tx.vout.size(); // just check boundaries: if (n == 0 || v < 0 || v >= n-1) { - LOGSTREAM("tokens", CCLOG_INFO, stream << indentStr << "isTokensvout() incorrect params: (n == 0 or v < 0 or v >= n-1)" << " v=" << v << " n=" << n << " returning 0" << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << indentStr << "isTokensvout() incorrect params: (n == 0 or v < 0 or v >= n-1)" << " v=" << v << " n=" << n << " returning 0" << std::endl); return(0); } @@ -449,7 +449,7 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c // if ccInputs != ccOutputs and it is not the tokenbase tx // this means it is possibly a fake tx (dimxy): if (reftokenid != tx.GetHash()) { // checking that this is the true tokenbase tx, by verifying that funcid=c, is done further in this function (dimxy) - LOGSTREAM("tokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() warning: for the verified tx detected a bad vintx=" << tx.GetHash().GetHex() << ": cc inputs != cc outputs and not the 'tokenbase' tx, skipping the verified tx" << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() warning: for the verified tx detected a bad vintx=" << tx.GetHash().GetHex() << ": cc inputs != cc outputs and not the 'tokenbase' tx, skipping the verified tx" << std::endl); return 0; } } @@ -459,7 +459,7 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c const uint8_t funcId = ValidateTokenOpret(tx, reftokenid); //std::cerr << indentStr << "IsTokensvout() ValidateTokenOpret returned=" << (char)(funcId?funcId:' ') << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl; if (funcId != 0) { - LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() ValidateTokenOpret returned not-null funcId=" << (char)(funcId?funcId:' ') << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() ValidateTokenOpret returned not-null funcId=" << (char)(funcId?funcId:' ') << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); uint8_t dummyEvalCode; uint256 tokenIdOpret; @@ -471,8 +471,8 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c if (checkPubkeys && funcId != 'c') { // for 'c' there is no pubkeys // verify that the vout is token by constructing vouts with the pubkeys in the opret: - LOGSTREAM("tokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopret1=" << HexStr(vopret1) << std::endl); - LOGSTREAM("tokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopret2=" << HexStr(vopret2) << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopret1=" << HexStr(vopret1) << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopret2=" << HexStr(vopret2) << std::endl); uint8_t evalCode = EVAL_TOKENS; // if both payloads are empty maybe it is a transfer to non-payload-one-eval-token vout like GatewaysClaim uint8_t evalCode2 = 0; // will be checked if zero or not @@ -544,14 +544,14 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c // try all test vouts: for (auto t : testVouts) { if (t.first == tx.vout[v]) { - LOGSTREAM("tokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() valid amount=" << tx.vout[v].nValue << " msg=" << t.second << " evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " txid=" << tx.GetHash().GetHex() << " tokenid=" << reftokenid.GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() valid amount=" << tx.vout[v].nValue << " msg=" << t.second << " evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " txid=" << tx.GetHash().GetHex() << " tokenid=" << reftokenid.GetHex() << std::endl); return tx.vout[v].nValue; } } - LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() no valid vouts evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() no valid vouts evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); } else { - LOGSTREAM("tokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() returns without pubkey check value=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() returns without pubkey check value=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); return tx.vout[v].nValue; } } @@ -579,7 +579,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu // this is just for log messages indentation for debugging recursive calls: std::string indentStr = std::string().append(tokenValIndentSize, '.'); - LOGSTREAM("tokens", CCLOG_DEBUG2, stream << indentStr << "TokensExactAmounts() entered for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG2, stream << indentStr << "TokensExactAmounts() entered for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); for (int32_t i = 0; iGetTxUnconfirmed(tx.vin[i].prevout.hash, vinTx, hashBlock) == 0) || (!eval && !myGetTransaction(tx.vin[i].prevout.hash, vinTx, hashBlock))) { - LOGSTREAM("tokens", CCLOG_INFO, stream << indentStr << "TokensExactAmounts() cannot read vintx for i." << i << " numvins." << numvins << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << indentStr << "TokensExactAmounts() cannot read vintx for i." << i << " numvins." << numvins << std::endl); return (!eval) ? false : eval->Invalid("always should find vin tx, but didnt"); } else { - LOGSTREAM("tokens", CCLOG_DEBUG2, stream << indentStr << "TokenExactAmounts() checking vintx.vout for tx.vin[" << i << "] nValue=" << vinTx.vout[tx.vin[i].prevout.n].nValue << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG2, stream << indentStr << "TokenExactAmounts() checking vintx.vout for tx.vin[" << i << "] nValue=" << vinTx.vout[tx.vin[i].prevout.n].nValue << std::endl); // validate vouts of vintx tokenValIndentSize++; @@ -601,7 +601,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu tokenValIndentSize--; if (tokenoshis != 0) { - LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "TokensExactAmounts() adding vintx.vout for tx.vin[" << i << "] tokenoshis=" << tokenoshis << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "TokensExactAmounts() adding vintx.vout for tx.vin[" << i << "] tokenoshis=" << tokenoshis << std::endl); inputs += tokenoshis; } } @@ -610,7 +610,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu for (int32_t i = 0; i < numvouts-1; i ++) // 'numvouts-1' <-- do not check opret { - LOGSTREAM("tokens", CCLOG_DEBUG2, stream << indentStr << "TokenExactAmounts() recursively checking tx.vout[" << i << "] nValue=" << tx.vout[i].nValue << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG2, stream << indentStr << "TokenExactAmounts() recursively checking tx.vout[" << i << "] nValue=" << tx.vout[i].nValue << std::endl); // Note: we pass in here IsTokenvout(false,...) because we don't need to call TokenExactAmounts() recursively from IsTokensvout here // indeed, if we pass 'true' we'll be checking this tx vout again @@ -620,7 +620,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu if (tokenoshis != 0) { - LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "TokensExactAmounts() adding tx.vout[" << i << "] tokenoshis=" << tokenoshis << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "TokensExactAmounts() adding tx.vout[" << i << "] tokenoshis=" << tokenoshis << std::endl); outputs += tokenoshis; } } @@ -629,7 +629,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu if (inputs != outputs) { if (tx.GetHash() != reftokenid) - LOGSTREAM("tokens", CCLOG_DEBUG1, stream << indentStr << "TokenExactAmounts() found unequal token cc inputs=" << inputs << " vs cc outputs=" << outputs << " for txid=" << tx.GetHash().GetHex() << " and this is not the create tx" << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "TokenExactAmounts() found unequal token cc inputs=" << inputs << " vs cc outputs=" << outputs << " for txid=" << tx.GetHash().GetHex() << " and this is not the create tx" << std::endl); return false; // do not call eval->Invalid() here! } else @@ -643,7 +643,7 @@ void GetNonfungibleData(uint256 tokenid, std::vector &vopretNonfungible uint256 hashBlock; if (!myGetTransaction(tokenid, tokenbasetx, hashBlock)) { - LOGSTREAM("tokens", CCLOG_INFO, stream << "SetNonfungibleEvalCode() cound not load token creation tx=" << tokenid.GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "SetNonfungibleEvalCode() cound not load token creation tx=" << tokenid.GetHex() << std::endl); return; } @@ -682,7 +682,7 @@ int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, C SetCCunspents(unspentOutputs, tokenaddr); if (unspentOutputs.empty()) { - LOGSTREAM("tokens", CCLOG_INFO, stream << "AddTokenCCInputs() no utxos for token dual/three eval addr=" << tokenaddr << " evalcode=" << (int)cp->evalcode << " additionalTokensEvalcode2=" << (int)cp->additionalTokensEvalcode2 << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "AddTokenCCInputs() no utxos for token dual/three eval addr=" << tokenaddr << " evalcode=" << (int)cp->evalcode << " additionalTokensEvalcode2=" << (int)cp->additionalTokensEvalcode2 << std::endl); } threshold = total / (maxinputs != 0 ? maxinputs : 64); // TODO: maxinputs really could not be over 64? what if i want to calc total balance for all available uxtos? @@ -713,7 +713,7 @@ int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, C strcmp(destaddr, cp->unspendableaddr2) != 0) // or the logic is to allow to spend all available tokens (what about unspendableaddr3)? continue; - LOGSTREAM("tokens", CCLOG_DEBUG1, stream << "AddTokenCCInputs() check vintx vout destaddress=" << destaddr << " amount=" << vintx.vout[vout].nValue << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << "AddTokenCCInputs() check vintx vout destaddress=" << destaddr << " amount=" << vintx.vout[vout].nValue << std::endl); if ((nValue = IsTokensvout(true, true/*<--add only valid token uxtos */, cp, NULL, vintx, vout, tokenid)) > 0 && myIsutxo_spentinmempool(vintxid, vout) == 0) { @@ -724,7 +724,7 @@ int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, C // check if it is non-fungible token: GetNonfungibleData(tokenid, vopret); if (vopret != vopretNonfungible) { - LOGSTREAM("tokens", CCLOG_INFO, stream << "AddTokenCCInputs() found incorrect non-fungible opret payload for vintxid=" << vintxid.GetHex() << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "AddTokenCCInputs() found incorrect non-fungible opret payload for vintxid=" << vintxid.GetHex() << std::endl); continue; } @@ -737,7 +737,7 @@ int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, C nValue = it->second.satoshis; totalinputs += nValue; - LOGSTREAM("tokens", CCLOG_DEBUG1, stream << "AddTokenCCInputs() adding input nValue=" << nValue << std::endl); + LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << "AddTokenCCInputs() adding input nValue=" << nValue << std::endl); n++; if ((total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs)) @@ -757,11 +757,11 @@ std::string CreateToken(int64_t txfee, int64_t tokensupply, std::string name, st CPubKey mypk; struct CCcontract_info *cp, C; if (tokensupply < 0) { - LOGSTREAM("tokens", CCLOG_INFO, stream << "CreateToken() negative tokensupply=" << tokensupply << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "CreateToken() negative tokensupply=" << tokensupply << std::endl); return std::string(""); } if (!nonfungibleData.empty() && tokensupply != 1) { - LOGSTREAM("tokens", CCLOG_INFO, stream << "CreateToken() for non-fungible tokens tokensupply should be equal to 1" << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "CreateToken() for non-fungible tokens tokensupply should be equal to 1" << std::endl); CCerror = "for non-fungible tokens tokensupply should be equal to 1"; return std::string(""); } @@ -770,7 +770,7 @@ std::string CreateToken(int64_t txfee, int64_t tokensupply, std::string name, st cp = CCinit(&C, EVAL_TOKENS); if (name.size() > 32 || description.size() > 4096) // this is also checked on rpc level { - LOGSTREAM("tokens", CCLOG_INFO, stream << "name of=" << name.size() << " or description of=" << description.size() << " is too big" << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "name of=" << name.size() << " or description of=" << description.size() << " is too big" << std::endl); CCerror = "name should be < 32, description should be < 4096"; return(""); } @@ -789,7 +789,7 @@ std::string CreateToken(int64_t txfee, int64_t tokensupply, std::string name, st return(FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenCreateOpRet('c', Mypubkey(), name, description, nonfungibleData))); } - LOGSTREAM("tokens", CCLOG_INFO, stream << "cant find normal inputs" << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "cant find normal inputs" << std::endl); CCerror = "cant find normal inputs"; return std::string(""); } @@ -803,7 +803,7 @@ std::string TokenTransfer(int64_t txfee, uint256 tokenid, std::vector d std::vector vopretNonfungible; if (total < 0) { - LOGSTREAM("tokens", CCLOG_INFO, stream << "negative total=" << total << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "negative total=" << total << std::endl); return(""); } @@ -819,7 +819,7 @@ std::string TokenTransfer(int64_t txfee, uint256 tokenid, std::vector d if ((inputs = AddTokenCCInputs(cp, mtx, mypk, tokenid, total, 60, vopretNonfungible)) > 0) // NOTE: AddTokenCCInputs might set cp->additionalEvalCode which is used in FinalizeCCtx! { if (inputs < total) { //added dimxy - LOGSTREAM("tokens", CCLOG_INFO, stream << "TokenTransfer(): insufficient token funds" << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "TokenTransfer(): insufficient token funds" << std::endl); CCerror = strprintf("insufficient token inputs"); return std::string(""); } @@ -840,13 +840,13 @@ std::string TokenTransfer(int64_t txfee, uint256 tokenid, std::vector d return(FinalizeCCTx(mask, cp, mtx, mypk, txfee, EncodeTokenOpRet(tokenid, voutTokenPubkeys, vopretNonfungible, CScript()))); } else { - LOGSTREAM("tokens", CCLOG_INFO, stream << "not enough CC token inputs for amount=" << total << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "not enough CC token inputs for amount=" << total << std::endl); CCerror = strprintf("no token inputs"); } //} else fprintf(stderr,"numoutputs.%d != numamounts.%d\n",n,(int32_t)amounts.size()); } else { - LOGSTREAM("tokens", CCLOG_INFO, stream << "not enough normal inputs for txfee" << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "not enough normal inputs for txfee" << std::endl); CCerror = strprintf("insufficient normal inputs"); } return(""); @@ -864,7 +864,7 @@ int64_t GetTokenBalance(CPubKey pk, uint256 tokenid) if (GetTransaction(tokenid, tokentx, hashBlock, false) == 0) { - LOGSTREAM("tokens", CCLOG_INFO, stream << "cant find tokenid" << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "cant find tokenid" << std::endl); CCerror = strprintf("cant find tokenid"); return 0; } @@ -892,7 +892,7 @@ UniValue TokenInfo(uint256 tokenid) } if (vintx.vout.size() > 0 && DecodeTokenCreateOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, origpubkey, name, description, vopretNonfungible) == 0) { - LOGSTREAM("tokens", CCLOG_INFO, stream << "TokenInfo() passed tokenid isnt token creation txid" << std::endl); + LOGSTREAM("cctokens", CCLOG_INFO, stream << "TokenInfo() passed tokenid isnt token creation txid" << std::endl); result.push_back(Pair("result", "error")); result.push_back(Pair("error", "tokenid isnt token creation txid")); } From fdd1d04b1065e7f76634819206b919f6d9a93ab2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:17:59 -1100 Subject: [PATCH 0438/1145] dapp loading player data --- src/cc/rogue/rogue.c | 38 ++++++++++++++++++++++++++++++++++++++ src/cc/rogue/state.c | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index c52002447..91d638e12 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -142,6 +142,43 @@ int32_t flushkeystrokes(struct rogue_state *rs) } #else +uint8_t *OS_fileptr(long *allocsizep,char *fname); + +void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) +{ + char cmd[32768]; int32_t i,n; char *filestr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; + sprintf(fname,"%s.gameinfo",gametxidstr); + sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); + if ( system(cmd) != 0 ) + fprintf(stderr,"error issuing (%s)\n",cmd); + else + { + filestr = (char *)OS_fileptr(&allocsize,fname); + if ( (retjson= cJSON_Parse(filestr)) != 0 ) + { + if ( (array= jarray(&n,retjson,"players")) != 0 ) + { + for (i=0; iP,(int32_t)strlen(datastr)/2,datastr); + fprintf(stderr,"set datastr[%d]\n",(int32_t)strlen(datastr)); + rs->restoring = 1; + } + } + } + } + free_json(retjson); + } + free(filestr); + } +} + void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) // use seed to lookup gametxid { char cmd[32768],hexstr[32768]; int32_t i; @@ -260,6 +297,7 @@ int rogue(int argc, char **argv, char **envp) { rs->seed = atol(argv[1]); strcpy(Gametxidstr,argv[2]); + rogue_setplayerdata(rs,Gametxidstr); } else rs->seed = 777; rs->guiflag = 1; rs->sleeptime = 1; // non-zero to allow refresh() diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index def3fb859..68686b255 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1390,7 +1390,7 @@ void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) THING *obj = new_item(); rogue_restoreobject(obj,item); strcpy(packitemstr,inv_name(obj,FALSE)); - fprintf(stderr,"packitem.(%s)\n",packitemstr); + //fprintf(stderr,"packitem.(%s)\n",packitemstr); free(obj); } From 366ade08a03369e6fc10262d5d41359ba2d5aca8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:28:14 -1100 Subject: [PATCH 0439/1145] Merge nonfungible --- src/cc/CCinclude.h | 5 ----- src/cc/CCtokens.cpp | 6 +----- src/cc/CCtx.cpp | 15 ++------------- src/wallet/rpcwallet.cpp | 11 ++--------- 4 files changed, 5 insertions(+), 32 deletions(-) diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index 87813c8fd..89e6343b9 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -199,12 +199,7 @@ CC *MakeCCcond1of2(uint8_t evalcode,CPubKey pk1,CPubKey pk2); CC* GetCryptoCondition(CScript const& scriptSig); void CCaddr2set(struct CCcontract_info *cp,uint8_t evalcode,CPubKey pk,uint8_t *priv,char *coinaddr); void CCaddr3set(struct CCcontract_info *cp,uint8_t evalcode,CPubKey pk,uint8_t *priv,char *coinaddr); -<<<<<<< HEAD void CCaddr1of2set(struct CCcontract_info *cp, CPubKey pk1, CPubKey pk2,uint8_t *priv,char *coinaddr); - -======= -void CCaddr1of2set(struct CCcontract_info *cp, CPubKey pk1, CPubKey pk2, char *coinaddr); ->>>>>>> FSM CTxOut MakeTokensCC1of2vout(uint8_t evalcode, CAmount nValue, CPubKey pk1, CPubKey pk2); CTxOut MakeTokensCC1of2vout(uint8_t evalcode, uint8_t evalcode2, CAmount nValue, CPubKey pk1, CPubKey pk2); CTxOut MakeTokensCC1vout(uint8_t evalcode, CAmount nValue, CPubKey pk); diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index 98c92e674..499d9e7b0 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -713,13 +713,9 @@ int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, C strcmp(destaddr, cp->unspendableaddr2) != 0) // or the logic is to allow to spend all available tokens (what about unspendableaddr3)? continue; -<<<<<<< HEAD - if ((nValue = IsTokensvout(true, true/*<--add only checked token uxtos */, cp, NULL, vintx, vout, tokenid)) > 0 && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid, vout) == 0) -======= LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << "AddTokenCCInputs() check vintx vout destaddress=" << destaddr << " amount=" << vintx.vout[vout].nValue << std::endl); - if ((nValue = IsTokensvout(true, true/*<--add only valid token uxtos */, cp, NULL, vintx, vout, tokenid)) > 0 && myIsutxo_spentinmempool(vintxid, vout) == 0) ->>>>>>> FSM + if ((nValue = IsTokensvout(true, true/*<--add only valid token uxtos */, cp, NULL, vintx, vout, tokenid)) > 0 && myIsutxo_spentinmempool(ignoretxid,ignorevin,vintxid, vout) == 0) { //for non-fungible tokens check payload: if (!vopretNonfungible.empty()) { diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index d2a040412..af5535591 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -46,15 +46,9 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran CTransaction vintx; std::string hex; CPubKey globalpk; uint256 hashBlock; uint64_t mask=0,nmask=0,vinimask=0; int64_t utxovalues[CC_MAXVINS],change,normalinputs=0,totaloutputs=0,normaloutputs=0,totalinputs=0,normalvins=0,ccvins=0; int32_t i,flag,utxovout,n,err = 0; -<<<<<<< HEAD - char myaddr[64], destaddr[64], unspendable[64], mytokensaddr[64], mysingletokensaddr[64], tokensunspendable[64],CC1of2CCaddr[64]; - uint8_t *privkey, myprivkey[32], unspendablepriv[32], tokensunspendablepriv[32], *msg32 = 0; - CC *mycond=0, *othercond=0, *othercond2=0,*othercond4=0, *othercond3=0, *othercond1of2=NULL, *othercond1of2tokens = NULL, *cond, *condCC2=0,*mytokenscond = NULL, *mysingletokenscond = NULL, *othertokenscond = NULL; -======= - char myaddr[64], destaddr[64], unspendable[64], mytokensaddr[64], mysingletokensaddr[64], unspendabletokensaddr[64]; + char myaddr[64], destaddr[64], unspendable[64], mytokensaddr[64], mysingletokensaddr[64], unspendabletokensaddr[64],CC1of2CCaddr[64]; uint8_t *privkey, myprivkey[32], unspendablepriv[32], /*tokensunspendablepriv[32],*/ *msg32 = 0; - CC *mycond=0, *othercond=0, *othercond2=0,*othercond4=0, *othercond3=0, *othercond1of2=NULL, *othercond1of2tokens = NULL, *cond, *mytokenscond = NULL, *mysingletokenscond = NULL, *othertokenscond = NULL; ->>>>>>> FSM + CC *mycond=0, *othercond=0, *othercond2=0,*othercond4=0, *othercond3=0, *othercond1of2=NULL, *othercond1of2tokens = NULL, *cond, *condCC2=0,*mytokenscond = NULL, *mysingletokenscond = NULL, *othertokenscond = NULL; CPubKey unspendablepk /*, tokensunspendablepk*/; struct CCcontract_info *cpTokens, tokensC; globalpk = GetUnspendable(cp,0); @@ -215,13 +209,8 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran // check if this is spending from 1of2 cc coins addr: else if (strcmp(cp->coins1of2addr, destaddr) == 0) { -<<<<<<< HEAD //fprintf(stderr,"FinalizeCCTx() matched %s unspendable1of2!\n",cp->coins1of2addr); privkey = cp->coins1of2priv;//myprivkey; -======= - fprintf(stderr,"FinalizeCCTx() matched %s unspendable1of2!\n",cp->coins1of2addr); - privkey = myprivkey; ->>>>>>> FSM if (othercond1of2 == 0) othercond1of2 = MakeCCcond1of2(cp->evalcode, cp->coins1of2pk[0], cp->coins1of2pk[1]); cond = othercond1of2; diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 8cc051a44..0087abf58 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -7046,13 +7046,7 @@ UniValue tokenbalance(const UniValue& params, bool fHelp) UniValue tokencreate(const UniValue& params, bool fHelp) { -<<<<<<< HEAD - UniValue result(UniValue::VOBJ); std::string name,description,hex; uint64_t supply; - if ( fHelp || params.size() > 3 || params.size() < 2 ) - throw runtime_error("tokencreate name supply description\n"); - if ( ensure_CCrequirements(EVAL_TOKENS) < 0 ) -======= - UniValue result(UniValue::VOBJ); + UniValue result(UniValue::VOBJ); std::string name, description, hextx; std::vector nonfungibleData; int64_t supply; // changed from uin64_t to int64_t for this 'if ( supply <= 0 )' to work as expected @@ -7061,8 +7055,7 @@ UniValue tokencreate(const UniValue& params, bool fHelp) if ( fHelp || params.size() > 4 || params.size() < 2 ) throw runtime_error("tokencreate name supply [description][data]\n"); - if ( ensure_CCrequirements() < 0 ) ->>>>>>> FSM + if ( ensure_CCrequirements(EVAL_TOKENS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; From 26adb60f2a2edea4adccc10fff9edc9c6e22cd66 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:29:25 -1100 Subject: [PATCH 0440/1145] Missing funds --- src/cc/rogue/rogue.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 91d638e12..4f66c770f 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -154,7 +154,7 @@ void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) else { filestr = (char *)OS_fileptr(&allocsize,fname); - if ( (retjson= cJSON_Parse(filestr)) != 0 ) + /*if ( (retjson= cJSON_Parse(filestr)) != 0 ) { if ( (array= jarray(&n,retjson,"players")) != 0 ) { @@ -174,7 +174,7 @@ void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } } free_json(retjson); - } + }*/ free(filestr); } } From 1ae1b3953c0a4d78de4ad81a0564e6a1c2d47800 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:30:03 -1100 Subject: [PATCH 0441/1145] -cJSON --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 4f66c770f..970844da0 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -146,7 +146,7 @@ uint8_t *OS_fileptr(long *allocsizep,char *fname); void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) { - char cmd[32768]; int32_t i,n; char *filestr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; + char cmd[32768]; int32_t i,n; char *filestr,*datastr,fname[128]; long allocsize; //cJSON *retjson,*array,*item; sprintf(fname,"%s.gameinfo",gametxidstr); sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); if ( system(cmd) != 0 ) From ffc96c9674c3d29b1ed7e9f7763f1c14cf4c5f73 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:36:32 -1100 Subject: [PATCH 0442/1145] (char *) --- src/cc/CCassetsCore.cpp | 10 ++--- src/cc/CCtokens.cpp | 92 ++++++++++++++++++++--------------------- src/cc/rogue/main.c | 47 +++++++++++++++++++++ 3 files changed, 98 insertions(+), 51 deletions(-) diff --git a/src/cc/CCassetsCore.cpp b/src/cc/CCassetsCore.cpp index 1aa654a89..fa8b1df71 100644 --- a/src/cc/CCassetsCore.cpp +++ b/src/cc/CCassetsCore.cpp @@ -295,7 +295,7 @@ uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCo // First - decode token opret: funcId = DecodeTokenOpRet(scriptPubKey, dummyEvalCode, tokenid, voutPubkeysDummy, vopret1, vopret2); - LOGSTREAM("ccassets", CCLOG_DEBUG2, stream << "DecodeAssetTokenOpRet() from DecodeTokenOpRet returned funcId=" << (int)funcId << std::endl); + LOGSTREAM((char *)"ccassets", CCLOG_DEBUG2, stream << "DecodeAssetTokenOpRet() from DecodeTokenOpRet returned funcId=" << (int)funcId << std::endl); if (!vopret2.empty()) { // if there are both oprets then order is like this: @@ -319,7 +319,7 @@ uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCo //bool result = E_UNMARSHAL(vopret, ss >> evalCodeInOpret; ss >> funcId; ss >> tokenid; ss >> assetFuncId; isEof = ss.eof()); if (funcId == 0 || vopretAssets.size() < 2) { - LOGSTREAM("ccassets", CCLOG_INFO, stream << "DecodeAssetTokenOpRet() incorrect opret or no asset's payload" << " funcId=" << (int)funcId << " vopretAssets.size()=" << vopretAssets.size() << std::endl); + LOGSTREAM((char *)"ccassets", CCLOG_INFO, stream << "DecodeAssetTokenOpRet() incorrect opret or no asset's payload" << " funcId=" << (int)funcId << " vopretAssets.size()=" << vopretAssets.size() << std::endl); return (uint8_t)0; } @@ -334,7 +334,7 @@ uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCo assetsEvalCode = vopretAssets.begin()[0]; assetsFuncId = vopretAssets.begin()[1]; - LOGSTREAM("ccassets", CCLOG_DEBUG2, stream << "DecodeAssetTokenOpRet() assetsEvalCode=" << (int)assetsEvalCode << " funcId=" << (char)(funcId ? funcId : ' ') << " assetsFuncId=" << (char)(assetsFuncId ? assetsFuncId : ' ') << std::endl); + LOGSTREAM((char *)"ccassets", CCLOG_DEBUG2, stream << "DecodeAssetTokenOpRet() assetsEvalCode=" << (int)assetsEvalCode << " funcId=" << (char)(funcId ? funcId : ' ') << " assetsFuncId=" << (char)(assetsFuncId ? assetsFuncId : ' ') << std::endl); if (assetsEvalCode == EVAL_ASSETS) { @@ -363,13 +363,13 @@ uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCo } break; default: - LOGSTREAM("ccassets", CCLOG_INFO, stream << "DecodeAssetTokenOpRet() illegal assetFuncId=" << (int)funcId << std::endl); + LOGSTREAM((char *)"ccassets", CCLOG_INFO, stream << "DecodeAssetTokenOpRet() illegal assetFuncId=" << (int)funcId << std::endl); break; } } } - LOGSTREAM("ccassets", CCLOG_INFO, stream << "DecodeAssetTokenOpRet() no asset's payload or incorrect assets evalcode" << " funcId=" << (int)funcId << " vopretAssets.size()=" << vopretAssets.size() << " assetsEvalCode=" << assetsEvalCode << " assetsFuncId=" << assetsFuncId << std::endl); + LOGSTREAM((char *)"ccassets", CCLOG_INFO, stream << "DecodeAssetTokenOpRet() no asset's payload or incorrect assets evalcode" << " funcId=" << (int)funcId << " vopretAssets.size()=" << vopretAssets.size() << " assetsEvalCode=" << assetsEvalCode << " assetsFuncId=" << assetsFuncId << std::endl); return (uint8_t)0; } diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index 499d9e7b0..df1733173 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -73,7 +73,7 @@ CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, std: if (voutPubkeys.size() >= 0 && voutPubkeys.size() <= 2) ccType = voutPubkeys.size(); else { - LOGSTREAM("cctokens", CCLOG_INFO, stream << "EncodeTokenOpRet voutPubkeys.size()=" << voutPubkeys.size() << " not supported" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "EncodeTokenOpRet voutPubkeys.size()=" << voutPubkeys.size() << " not supported" << std::endl); } std::vector vpayload; @@ -173,7 +173,7 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, ui return (uint8_t)0; funcId = script[1]; - LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << "DecodeTokenOpRet decoded funcId=" << (char)(funcId?funcId:' ')); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << "DecodeTokenOpRet decoded funcId=" << (char)(funcId?funcId:' ')); switch( funcId ) { @@ -195,7 +195,7 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, ui { if (!(ccType >= 0 && ccType <= 2)) { //incorrect ccType - LOGSTREAM("cctokens", CCLOG_INFO, stream << "DecodeTokenOpRet() incorrect ccType=" << (int)ccType << " tokenid=" << revuint256(tokenid).GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "DecodeTokenOpRet() incorrect ccType=" << (int)ccType << " tokenid=" << revuint256(tokenid).GetHex() << std::endl); return (uint8_t)0; } @@ -209,16 +209,16 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, ui tokenid = revuint256(tokenid); return(funcId); } - LOGSTREAM("cctokens", CCLOG_INFO, stream << "DecodeTokenOpRet() bad opret format, isEof=" << isEof << " ccType=" << ccType << " tokenid=" << revuint256(tokenid).GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "DecodeTokenOpRet() bad opret format, isEof=" << isEof << " ccType=" << ccType << " tokenid=" << revuint256(tokenid).GetHex() << std::endl); return (uint8_t)0; default: - LOGSTREAM("cctokens", CCLOG_INFO, stream << "DecodeTokenOpRet() illegal funcid=" << (int)funcId << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "DecodeTokenOpRet() illegal funcid=" << (int)funcId << std::endl); return (uint8_t)0; } } else { - LOGSTREAM("cctokens", CCLOG_INFO, stream << "DecodeTokenOpRet() empty opret, could not parse" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "DecodeTokenOpRet() empty opret, could not parse" << std::endl); } return (uint8_t)0; } @@ -245,7 +245,7 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & if ((funcid = DecodeTokenOpRet(tx.vout[numvouts - 1].scriptPubKey, evalCodeInOpret, tokenid, voutTokenPubkeys, vopret1, vopret2)) == 0) return eval->Invalid("TokenValidate: invalid opreturn payload"); - LOGSTREAM("cctokens", CCLOG_INFO, stream << "TokensValidate funcId=" << (char)(funcid?funcid:' ') << " evalcode=" << cp->evalcode << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "TokensValidate funcId=" << (char)(funcid?funcid:' ') << " evalcode=" << cp->evalcode << std::endl); if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) return eval->Invalid("cant find token create txid"); @@ -293,11 +293,11 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & if (inputs == 0) return eval->Invalid("no token inputs for transfer"); - LOGSTREAM("cctokens", CCLOG_INFO, stream << "token transfer preliminarily validated inputs=" << inputs << "->outputs=" << outputs << " preventCCvins=" << preventCCvins<< " preventCCvouts=" << preventCCvouts << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "token transfer preliminarily validated inputs=" << inputs << "->outputs=" << outputs << " preventCCvins=" << preventCCvins<< " preventCCvouts=" << preventCCvouts << std::endl); break; // breaking to other contract validation... default: - LOGSTREAM("cctokens", CCLOG_INFO, stream << "illegal tokens funcid=" << (char)(funcid?funcid:' ') << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "illegal tokens funcid=" << (char)(funcid?funcid:' ') << std::endl); return eval->Invalid("unexpected token funcid"); } @@ -383,32 +383,32 @@ uint8_t ValidateTokenOpret(CTransaction tx, uint256 tokenid) { if ((funcid = DecodeTokenOpRet(tx.vout.back().scriptPubKey, dummyEvalCode, tokenidOpret, voutPubkeysDummy, vopretExtraDummy)) == 0) { - LOGSTREAM("cctokens", CCLOG_INFO, stream << indentStr << "ValidateTokenOpret() DecodeTokenOpret could not parse opret for txid=" << tx.GetHash().GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << indentStr << "ValidateTokenOpret() DecodeTokenOpret could not parse opret for txid=" << tx.GetHash().GetHex() << std::endl); return (uint8_t)0; } else if (funcid == 'c') { if (tokenid != zeroid && tokenid == tx.GetHash()) { - LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() this is the tokenbase 'c' tx, txid=" << tx.GetHash().GetHex() << " returning true" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() this is the tokenbase 'c' tx, txid=" << tx.GetHash().GetHex() << " returning true" << std::endl); return funcid; } else { - LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not my tokenbase txid=" << tx.GetHash().GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not my tokenbase txid=" << tx.GetHash().GetHex() << std::endl); } } else if (funcid == 't') { //std::cerr << indentStr << "ValidateTokenOpret() tokenid=" << tokenid.GetHex() << " tokenIdOpret=" << tokenidOpret.GetHex() << " txid=" << tx.GetHash().GetHex() << std::endl; if (tokenid != zeroid && tokenid == tokenidOpret) { - LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() this is a transfer 't' tx, txid=" << tx.GetHash().GetHex() << " returning true" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() this is a transfer 't' tx, txid=" << tx.GetHash().GetHex() << " returning true" << std::endl); return funcid; } else { - LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not my tokenid=" << tokenidOpret.GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not my tokenid=" << tokenidOpret.GetHex() << std::endl); } } else { - LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not supported funcid=" << (char)funcid << " tokenIdOpret=" << tokenidOpret.GetHex() << " txid=" << tx.GetHash().GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "ValidateTokenOpret() not supported funcid=" << (char)funcid << " tokenIdOpret=" << tokenidOpret.GetHex() << " txid=" << tx.GetHash().GetHex() << std::endl); } return (uint8_t)0; } @@ -424,12 +424,12 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c // this is just for log messages indentation fur debugging recursive calls: std::string indentStr = std::string().append(tokenValIndentSize, '.'); - LOGSTREAM("cctokens", CCLOG_DEBUG2, stream << indentStr << "IsTokensvout() entered for txid=" << tx.GetHash().GetHex() << " v=" << v << " for tokenid=" << reftokenid.GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << indentStr << "IsTokensvout() entered for txid=" << tx.GetHash().GetHex() << " v=" << v << " for tokenid=" << reftokenid.GetHex() << std::endl); int32_t n = tx.vout.size(); // just check boundaries: if (n == 0 || v < 0 || v >= n-1) { - LOGSTREAM("cctokens", CCLOG_INFO, stream << indentStr << "isTokensvout() incorrect params: (n == 0 or v < 0 or v >= n-1)" << " v=" << v << " n=" << n << " returning 0" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << indentStr << "isTokensvout() incorrect params: (n == 0 or v < 0 or v >= n-1)" << " v=" << v << " n=" << n << " returning 0" << std::endl); return(0); } @@ -449,7 +449,7 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c // if ccInputs != ccOutputs and it is not the tokenbase tx // this means it is possibly a fake tx (dimxy): if (reftokenid != tx.GetHash()) { // checking that this is the true tokenbase tx, by verifying that funcid=c, is done further in this function (dimxy) - LOGSTREAM("cctokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() warning: for the verified tx detected a bad vintx=" << tx.GetHash().GetHex() << ": cc inputs != cc outputs and not the 'tokenbase' tx, skipping the verified tx" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() warning: for the verified tx detected a bad vintx=" << tx.GetHash().GetHex() << ": cc inputs != cc outputs and not the 'tokenbase' tx, skipping the verified tx" << std::endl); return 0; } } @@ -459,7 +459,7 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c const uint8_t funcId = ValidateTokenOpret(tx, reftokenid); //std::cerr << indentStr << "IsTokensvout() ValidateTokenOpret returned=" << (char)(funcId?funcId:' ') << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl; if (funcId != 0) { - LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() ValidateTokenOpret returned not-null funcId=" << (char)(funcId?funcId:' ') << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() ValidateTokenOpret returned not-null funcId=" << (char)(funcId?funcId:' ') << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); uint8_t dummyEvalCode; uint256 tokenIdOpret; @@ -471,8 +471,8 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c if (checkPubkeys && funcId != 'c') { // for 'c' there is no pubkeys // verify that the vout is token by constructing vouts with the pubkeys in the opret: - LOGSTREAM("cctokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopret1=" << HexStr(vopret1) << std::endl); - LOGSTREAM("cctokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopret2=" << HexStr(vopret2) << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopret1=" << HexStr(vopret1) << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopret2=" << HexStr(vopret2) << std::endl); uint8_t evalCode = EVAL_TOKENS; // if both payloads are empty maybe it is a transfer to non-payload-one-eval-token vout like GatewaysClaim uint8_t evalCode2 = 0; // will be checked if zero or not @@ -544,14 +544,14 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c // try all test vouts: for (auto t : testVouts) { if (t.first == tx.vout[v]) { - LOGSTREAM("cctokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() valid amount=" << tx.vout[v].nValue << " msg=" << t.second << " evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " txid=" << tx.GetHash().GetHex() << " tokenid=" << reftokenid.GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() valid amount=" << tx.vout[v].nValue << " msg=" << t.second << " evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " txid=" << tx.GetHash().GetHex() << " tokenid=" << reftokenid.GetHex() << std::endl); return tx.vout[v].nValue; } } - LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() no valid vouts evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() no valid vouts evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); } else { - LOGSTREAM("cctokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() returns without pubkey check value=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() returns without pubkey check value=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); return tx.vout[v].nValue; } } @@ -579,7 +579,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu // this is just for log messages indentation for debugging recursive calls: std::string indentStr = std::string().append(tokenValIndentSize, '.'); - LOGSTREAM("cctokens", CCLOG_DEBUG2, stream << indentStr << "TokensExactAmounts() entered for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << indentStr << "TokensExactAmounts() entered for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); for (int32_t i = 0; iGetTxUnconfirmed(tx.vin[i].prevout.hash, vinTx, hashBlock) == 0) || (!eval && !myGetTransaction(tx.vin[i].prevout.hash, vinTx, hashBlock))) { - LOGSTREAM("cctokens", CCLOG_INFO, stream << indentStr << "TokensExactAmounts() cannot read vintx for i." << i << " numvins." << numvins << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << indentStr << "TokensExactAmounts() cannot read vintx for i." << i << " numvins." << numvins << std::endl); return (!eval) ? false : eval->Invalid("always should find vin tx, but didnt"); } else { - LOGSTREAM("cctokens", CCLOG_DEBUG2, stream << indentStr << "TokenExactAmounts() checking vintx.vout for tx.vin[" << i << "] nValue=" << vinTx.vout[tx.vin[i].prevout.n].nValue << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << indentStr << "TokenExactAmounts() checking vintx.vout for tx.vin[" << i << "] nValue=" << vinTx.vout[tx.vin[i].prevout.n].nValue << std::endl); // validate vouts of vintx tokenValIndentSize++; @@ -601,7 +601,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu tokenValIndentSize--; if (tokenoshis != 0) { - LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "TokensExactAmounts() adding vintx.vout for tx.vin[" << i << "] tokenoshis=" << tokenoshis << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "TokensExactAmounts() adding vintx.vout for tx.vin[" << i << "] tokenoshis=" << tokenoshis << std::endl); inputs += tokenoshis; } } @@ -610,7 +610,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu for (int32_t i = 0; i < numvouts-1; i ++) // 'numvouts-1' <-- do not check opret { - LOGSTREAM("cctokens", CCLOG_DEBUG2, stream << indentStr << "TokenExactAmounts() recursively checking tx.vout[" << i << "] nValue=" << tx.vout[i].nValue << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << indentStr << "TokenExactAmounts() recursively checking tx.vout[" << i << "] nValue=" << tx.vout[i].nValue << std::endl); // Note: we pass in here IsTokenvout(false,...) because we don't need to call TokenExactAmounts() recursively from IsTokensvout here // indeed, if we pass 'true' we'll be checking this tx vout again @@ -620,7 +620,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu if (tokenoshis != 0) { - LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "TokensExactAmounts() adding tx.vout[" << i << "] tokenoshis=" << tokenoshis << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "TokensExactAmounts() adding tx.vout[" << i << "] tokenoshis=" << tokenoshis << std::endl); outputs += tokenoshis; } } @@ -629,7 +629,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu if (inputs != outputs) { if (tx.GetHash() != reftokenid) - LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << indentStr << "TokenExactAmounts() found unequal token cc inputs=" << inputs << " vs cc outputs=" << outputs << " for txid=" << tx.GetHash().GetHex() << " and this is not the create tx" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "TokenExactAmounts() found unequal token cc inputs=" << inputs << " vs cc outputs=" << outputs << " for txid=" << tx.GetHash().GetHex() << " and this is not the create tx" << std::endl); return false; // do not call eval->Invalid() here! } else @@ -643,7 +643,7 @@ void GetNonfungibleData(uint256 tokenid, std::vector &vopretNonfungible uint256 hashBlock; if (!myGetTransaction(tokenid, tokenbasetx, hashBlock)) { - LOGSTREAM("cctokens", CCLOG_INFO, stream << "SetNonfungibleEvalCode() cound not load token creation tx=" << tokenid.GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "SetNonfungibleEvalCode() cound not load token creation tx=" << tokenid.GetHex() << std::endl); return; } @@ -682,7 +682,7 @@ int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, C SetCCunspents(unspentOutputs, tokenaddr); if (unspentOutputs.empty()) { - LOGSTREAM("cctokens", CCLOG_INFO, stream << "AddTokenCCInputs() no utxos for token dual/three eval addr=" << tokenaddr << " evalcode=" << (int)cp->evalcode << " additionalTokensEvalcode2=" << (int)cp->additionalTokensEvalcode2 << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "AddTokenCCInputs() no utxos for token dual/three eval addr=" << tokenaddr << " evalcode=" << (int)cp->evalcode << " additionalTokensEvalcode2=" << (int)cp->additionalTokensEvalcode2 << std::endl); } threshold = total / (maxinputs != 0 ? maxinputs : 64); // TODO: maxinputs really could not be over 64? what if i want to calc total balance for all available uxtos? @@ -713,7 +713,7 @@ int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, C strcmp(destaddr, cp->unspendableaddr2) != 0) // or the logic is to allow to spend all available tokens (what about unspendableaddr3)? continue; - LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << "AddTokenCCInputs() check vintx vout destaddress=" << destaddr << " amount=" << vintx.vout[vout].nValue << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << "AddTokenCCInputs() check vintx vout destaddress=" << destaddr << " amount=" << vintx.vout[vout].nValue << std::endl); if ((nValue = IsTokensvout(true, true/*<--add only valid token uxtos */, cp, NULL, vintx, vout, tokenid)) > 0 && myIsutxo_spentinmempool(ignoretxid,ignorevin,vintxid, vout) == 0) { @@ -724,7 +724,7 @@ int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, C // check if it is non-fungible token: GetNonfungibleData(tokenid, vopret); if (vopret != vopretNonfungible) { - LOGSTREAM("cctokens", CCLOG_INFO, stream << "AddTokenCCInputs() found incorrect non-fungible opret payload for vintxid=" << vintxid.GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "AddTokenCCInputs() found incorrect non-fungible opret payload for vintxid=" << vintxid.GetHex() << std::endl); continue; } @@ -737,7 +737,7 @@ int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, C nValue = it->second.satoshis; totalinputs += nValue; - LOGSTREAM("cctokens", CCLOG_DEBUG1, stream << "AddTokenCCInputs() adding input nValue=" << nValue << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << "AddTokenCCInputs() adding input nValue=" << nValue << std::endl); n++; if ((total > 0 && totalinputs >= total) || (maxinputs > 0 && n >= maxinputs)) @@ -757,11 +757,11 @@ std::string CreateToken(int64_t txfee, int64_t tokensupply, std::string name, st CPubKey mypk; struct CCcontract_info *cp, C; if (tokensupply < 0) { - LOGSTREAM("cctokens", CCLOG_INFO, stream << "CreateToken() negative tokensupply=" << tokensupply << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "CreateToken() negative tokensupply=" << tokensupply << std::endl); return std::string(""); } if (!nonfungibleData.empty() && tokensupply != 1) { - LOGSTREAM("cctokens", CCLOG_INFO, stream << "CreateToken() for non-fungible tokens tokensupply should be equal to 1" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "CreateToken() for non-fungible tokens tokensupply should be equal to 1" << std::endl); CCerror = "for non-fungible tokens tokensupply should be equal to 1"; return std::string(""); } @@ -770,7 +770,7 @@ std::string CreateToken(int64_t txfee, int64_t tokensupply, std::string name, st cp = CCinit(&C, EVAL_TOKENS); if (name.size() > 32 || description.size() > 4096) // this is also checked on rpc level { - LOGSTREAM("cctokens", CCLOG_INFO, stream << "name of=" << name.size() << " or description of=" << description.size() << " is too big" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "name of=" << name.size() << " or description of=" << description.size() << " is too big" << std::endl); CCerror = "name should be < 32, description should be < 4096"; return(""); } @@ -789,7 +789,7 @@ std::string CreateToken(int64_t txfee, int64_t tokensupply, std::string name, st return(FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenCreateOpRet('c', Mypubkey(), name, description, nonfungibleData))); } - LOGSTREAM("cctokens", CCLOG_INFO, stream << "cant find normal inputs" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "cant find normal inputs" << std::endl); CCerror = "cant find normal inputs"; return std::string(""); } @@ -803,7 +803,7 @@ std::string TokenTransfer(int64_t txfee, uint256 tokenid, std::vector d std::vector vopretNonfungible; if (total < 0) { - LOGSTREAM("cctokens", CCLOG_INFO, stream << "negative total=" << total << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "negative total=" << total << std::endl); return(""); } @@ -819,7 +819,7 @@ std::string TokenTransfer(int64_t txfee, uint256 tokenid, std::vector d if ((inputs = AddTokenCCInputs(cp, mtx, mypk, tokenid, total, 60, vopretNonfungible)) > 0) // NOTE: AddTokenCCInputs might set cp->additionalEvalCode which is used in FinalizeCCtx! { if (inputs < total) { //added dimxy - LOGSTREAM("cctokens", CCLOG_INFO, stream << "TokenTransfer(): insufficient token funds" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "TokenTransfer(): insufficient token funds" << std::endl); CCerror = strprintf("insufficient token inputs"); return std::string(""); } @@ -840,13 +840,13 @@ std::string TokenTransfer(int64_t txfee, uint256 tokenid, std::vector d return(FinalizeCCTx(mask, cp, mtx, mypk, txfee, EncodeTokenOpRet(tokenid, voutTokenPubkeys, vopretNonfungible, CScript()))); } else { - LOGSTREAM("cctokens", CCLOG_INFO, stream << "not enough CC token inputs for amount=" << total << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "not enough CC token inputs for amount=" << total << std::endl); CCerror = strprintf("no token inputs"); } //} else fprintf(stderr,"numoutputs.%d != numamounts.%d\n",n,(int32_t)amounts.size()); } else { - LOGSTREAM("cctokens", CCLOG_INFO, stream << "not enough normal inputs for txfee" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "not enough normal inputs for txfee" << std::endl); CCerror = strprintf("insufficient normal inputs"); } return(""); @@ -864,7 +864,7 @@ int64_t GetTokenBalance(CPubKey pk, uint256 tokenid) if (GetTransaction(tokenid, tokentx, hashBlock, false) == 0) { - LOGSTREAM("cctokens", CCLOG_INFO, stream << "cant find tokenid" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "cant find tokenid" << std::endl); CCerror = strprintf("cant find tokenid"); return 0; } @@ -892,7 +892,7 @@ UniValue TokenInfo(uint256 tokenid) } if (vintx.vout.size() > 0 && DecodeTokenCreateOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, origpubkey, name, description, vopretNonfungible) == 0) { - LOGSTREAM("cctokens", CCLOG_INFO, stream << "TokenInfo() passed tokenid isnt token creation txid" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "TokenInfo() passed tokenid isnt token creation txid" << std::endl); result.push_back(Pair("result", "error")); result.push_back(Pair("error", "tokenid isnt token creation txid")); } diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 7efdebc8d..95d4fea72 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -17,10 +17,57 @@ #include #include #include +#include "../../cJSON.c" int32_t rogue_replay(uint64_t seed,int32_t sleeptime); int rogue(int argc, char **argv, char **envp); +void *OS_loadfile(char *fname,uint8_t **bufp,long *lenp,long *allocsizep) +{ + FILE *fp; + long filesize,buflen = *allocsizep; + uint8_t *buf = *bufp; + *lenp = 0; + if ( (fp= fopen(fname,"rb")) != 0 ) + { + fseek(fp,0,SEEK_END); + filesize = ftell(fp); + if ( filesize == 0 ) + { + fclose(fp); + *lenp = 0; + printf("OS_loadfile null size.(%s)\n",fname); + return(0); + } + if ( filesize > buflen ) + { + *allocsizep = filesize; + *bufp = buf = (uint8_t *)realloc(buf,(long)*allocsizep+64); + } + rewind(fp); + if ( buf == 0 ) + printf("Null buf ???\n"); + else + { + if ( fread(buf,1,(long)filesize,fp) != (unsigned long)filesize ) + printf("error reading filesize.%ld\n",(long)filesize); + buf[filesize] = 0; + } + fclose(fp); + *lenp = filesize; + //printf("loaded.(%s)\n",buf); + } //else printf("OS_loadfile couldnt load.(%s)\n",fname); + return(buf); +} + +uint8_t *OS_fileptr(long *allocsizep,char *fname) +{ + long filesize = 0; uint8_t *buf = 0; void *retptr; + *allocsizep = 0; + retptr = OS_loadfile(fname,&buf,&filesize,allocsizep); + return((uint8_t *)retptr); +} + int main(int argc, char **argv, char **envp) { uint64_t seed; FILE *fp = 0; From 263b0e09ed3d2895b653f49ed26decf35de7e23e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:39:36 -1100 Subject: [PATCH 0443/1145] Boolean --- src/cc/rogue/main.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 95d4fea72..7e7e0209c 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -17,6 +17,9 @@ #include #include #include + +#define true 1 +#define false 0 #include "../../cJSON.c" int32_t rogue_replay(uint64_t seed,int32_t sleeptime); From 53ac13e3f0f68eb1c8b897638be27da4bf9bf872 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:41:10 -1100 Subject: [PATCH 0444/1145] komodo_cJSON.h --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 7e7e0209c..df04da7c6 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -20,7 +20,7 @@ #define true 1 #define false 0 -#include "../../cJSON.c" +#include "../../komodo_cJSON.c" int32_t rogue_replay(uint64_t seed,int32_t sleeptime); int rogue(int argc, char **argv, char **envp); From 14570c6eb3f3cbd0e0fa352084b10793e9c01d02 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:43:20 -1100 Subject: [PATCH 0445/1145] Compact --- src/cc/rogue/main.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index df04da7c6..426a69b40 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -18,6 +18,16 @@ #include #include +#define SMALLVAL 0.000000000000001 +#define SATOSHIDEN ((uint64_t)100000000L) +#define dstr(x) ((double)(x) / SATOSHIDEN) + +#ifndef _BITS256 +#define _BITS256 +union _bits256 { uint8_t bytes[32]; uint16_t ushorts[16]; uint32_t uints[8]; uint64_t ulongs[4]; uint64_t txid; }; +typedef union _bits256 bits256; +#endif + #define true 1 #define false 0 #include "../../komodo_cJSON.c" From 1c41e45351dd3997a265521d8b86602b84eaff9b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:45:47 -1100 Subject: [PATCH 0446/1145] Utils --- src/cc/rogue/main.c | 137 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 426a69b40..00d31fde4 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -28,6 +28,143 @@ union _bits256 { uint8_t bytes[32]; uint16_t ushorts[16]; uint32_t uints[8]; uin typedef union _bits256 bits256; #endif +int32_t _unhex(char c) +{ + if ( c >= '0' && c <= '9' ) + return(c - '0'); + else if ( c >= 'a' && c <= 'f' ) + return(c - 'a' + 10); + else if ( c >= 'A' && c <= 'F' ) + return(c - 'A' + 10); + return(-1); +} + +int32_t is_hexstr(char *str,int32_t n) +{ + int32_t i; + if ( str == 0 || str[0] == 0 ) + return(0); + for (i=0; str[i]!=0; i++) + { + if ( n > 0 && i >= n ) + break; + if ( _unhex(str[i]) < 0 ) + break; + } + if ( n == 0 ) + return(i); + return(i == n); +} + +int32_t unhex(char c) +{ + int32_t hex; + if ( (hex= _unhex(c)) < 0 ) + { + //printf("unhex: illegal hexchar.(%c)\n",c); + } + return(hex); +} + +unsigned char _decode_hex(char *hex) { return((unhex(hex[0])<<4) | unhex(hex[1])); } + +int32_t decode_hex(uint8_t *bytes,int32_t n,char *hex) +{ + int32_t adjust,i = 0; + //printf("decode.(%s)\n",hex); + if ( is_hexstr(hex,n) <= 0 ) + { + memset(bytes,0,n); + return(n); + } + if ( hex[n-1] == '\n' || hex[n-1] == '\r' ) + hex[--n] = 0; + if ( n == 0 || (hex[n*2+1] == 0 && hex[n*2] != 0) ) + { + if ( n > 0 ) + { + bytes[0] = unhex(hex[0]); + printf("decode_hex n.%d hex[0] (%c) -> %d hex.(%s) [n*2+1: %d] [n*2: %d %c] len.%ld\n",n,hex[0],bytes[0],hex,hex[n*2+1],hex[n*2],hex[n*2],(long)strlen(hex)); + } + bytes++; + hex++; + adjust = 1; + } else adjust = 0; + if ( n > 0 ) + { + for (i=0; i>4) & 0xf); + hexbytes[i*2 + 1] = hexbyte(message[i] & 0xf); + //printf("i.%d (%02x) [%c%c]\n",i,message[i],hexbytes[i*2],hexbytes[i*2+1]); + } + hexbytes[len*2] = 0; + //printf("len.%ld\n",len*2+1); + return((int32_t)len*2+1); +} + +char *bits256_str(char hexstr[65],bits256 x) +{ + init_hexbytes_noT(hexstr,x.bytes,sizeof(x)); + return(hexstr); +} + +long _stripwhite(char *buf,int accept) +{ + int32_t i,j,c; + if ( buf == 0 || buf[0] == 0 ) + return(0); + for (i=j=0; buf[i]!=0; i++) + { + buf[j] = c = buf[i]; + if ( c == accept || (c != ' ' && c != '\n' && c != '\r' && c != '\t' && c != '\b') ) + j++; + } + buf[j] = 0; + return(j); +} + +char *clonestr(char *str) +{ + char *clone; + if ( str == 0 || str[0] == 0 ) + { + printf("warning cloning nullstr.%p\n",str); +#ifdef __APPLE__ + while ( 1 ) sleep(1); +#endif + str = (char *)""; + } + clone = (char *)malloc(strlen(str)+16); + strcpy(clone,str); + return(clone); +} + #define true 1 #define false 0 #include "../../komodo_cJSON.c" From 6a71231e174f1131c259794544b9c62aff0a5f84 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:46:25 -1100 Subject: [PATCH 0447/1145] Memory and string --- src/cc/rogue/main.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 00d31fde4..aabb2562a 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -17,6 +17,8 @@ #include #include #include +#include +#include #define SMALLVAL 0.000000000000001 #define SATOSHIDEN ((uint64_t)100000000L) From 4a30b0a8bc99dffef69a451d756f5c8571102742 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:47:56 -1100 Subject: [PATCH 0448/1145] Safecopy --- src/cc/rogue/main.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index aabb2562a..a41e51dc3 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -166,6 +166,27 @@ char *clonestr(char *str) strcpy(clone,str); return(clone); } +int32_t safecopy(char *dest,char *src,long len) +{ + int32_t i = -1; + if ( src != 0 && dest != 0 && src != dest ) + { + if ( dest != 0 ) + memset(dest,0,len); + for (i=0; i Date: Sun, 10 Feb 2019 02:50:08 -1100 Subject: [PATCH 0449/1145] int32_t decode_hex(uint8_t *bytes,int32_t n,char *hex) --- src/cc/rogue/extern.h | 3 +++ src/cc/rogue/rogue.c | 7 ++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/extern.h b/src/cc/rogue/extern.h index 109ea0d49..486d85ff1 100644 --- a/src/cc/rogue/extern.h +++ b/src/cc/rogue/extern.h @@ -182,5 +182,8 @@ void md_onsignal_autosave(void); void md_onsignal_exit(void); void md_onsignal_default(void); int md_issymlink(char *sp); + +int32_t decode_hex(uint8_t *bytes,int32_t n,char *hex); + #endif diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 970844da0..e49163f74 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -15,6 +15,7 @@ #include #include #include "rogue.h" +#include "../../komodo_cJSON.h" /* * main: @@ -146,7 +147,7 @@ uint8_t *OS_fileptr(long *allocsizep,char *fname); void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) { - char cmd[32768]; int32_t i,n; char *filestr,*datastr,fname[128]; long allocsize; //cJSON *retjson,*array,*item; + char cmd[32768]; int32_t i,n; char *filestr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; sprintf(fname,"%s.gameinfo",gametxidstr); sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); if ( system(cmd) != 0 ) @@ -154,7 +155,7 @@ void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) else { filestr = (char *)OS_fileptr(&allocsize,fname); - /*if ( (retjson= cJSON_Parse(filestr)) != 0 ) + if ( (retjson= cJSON_Parse(filestr)) != 0 ) { if ( (array= jarray(&n,retjson,"players")) != 0 ) { @@ -174,7 +175,7 @@ void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } } free_json(retjson); - }*/ + } free(filestr); } } From a15a77963dd8e8b37c542cedb0fb19a9e32c8138 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:51:06 -1100 Subject: [PATCH 0450/1145] Bits256 --- src/cc/rogue/main.c | 9 --------- src/cc/rogue/rogue.h | 12 ++++++++++++ 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index a41e51dc3..98cf4c304 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -20,15 +20,6 @@ #include #include -#define SMALLVAL 0.000000000000001 -#define SATOSHIDEN ((uint64_t)100000000L) -#define dstr(x) ((double)(x) / SATOSHIDEN) - -#ifndef _BITS256 -#define _BITS256 -union _bits256 { uint8_t bytes[32]; uint16_t ushorts[16]; uint32_t uints[8]; uint64_t ulongs[4]; uint64_t txid; }; -typedef union _bits256 bits256; -#endif int32_t _unhex(char c) { diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index fa18c424f..ab7eba4b3 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -313,6 +313,18 @@ /* * Now we define the structures and types */ + +#define SMALLVAL 0.000000000000001 +#define SATOSHIDEN ((uint64_t)100000000L) +#define dstr(x) ((double)(x) / SATOSHIDEN) + +#ifndef _BITS256 +#define _BITS256 +union _bits256 { uint8_t bytes[32]; uint16_t ushorts[16]; uint32_t uints[8]; uint64_t ulongs[4]; uint64_t txid; }; +typedef union _bits256 bits256; +#endif + + #ifndef ROGUE_DECLARED_PACK struct rogue_packitem { From 841588a109cec749bfb70b1b41a27e9f7067fa75 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:52:21 -1100 Subject: [PATCH 0451/1145] is --- src/cc/rogue/main.c | 9 +++++++++ src/cc/rogue/rogue.c | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 98cf4c304..a41e51dc3 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -20,6 +20,15 @@ #include #include +#define SMALLVAL 0.000000000000001 +#define SATOSHIDEN ((uint64_t)100000000L) +#define dstr(x) ((double)(x) / SATOSHIDEN) + +#ifndef _BITS256 +#define _BITS256 +union _bits256 { uint8_t bytes[32]; uint16_t ushorts[16]; uint32_t uints[8]; uint64_t ulongs[4]; uint64_t txid; }; +typedef union _bits256 bits256; +#endif int32_t _unhex(char c) { diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index e49163f74..f7a4a8da0 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -162,7 +162,7 @@ void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) for (i=0; i Date: Sun, 10 Feb 2019 02:53:45 -1100 Subject: [PATCH 0452/1145] is_cJSON_True --- src/cc/rogue/rogue.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index f7a4a8da0..6bb9d8f83 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -144,6 +144,7 @@ int32_t flushkeystrokes(struct rogue_state *rs) #else uint8_t *OS_fileptr(long *allocsizep,char *fname); +#define is_cJSON_True(json) ((json) != 0 && ((json)->type & 0xff) == cJSON_True) void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) { @@ -167,7 +168,7 @@ void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) fprintf(stderr,"found ismine:true\n"); if ( (item= jobj(item,"player")) != 0 && (datastr= jstr(item,"data")) != 0 ) { - decode_hex(&rs->P,(int32_t)strlen(datastr)/2,datastr); + decode_hex((uint8_t *)&rs->P,(int32_t)strlen(datastr)/2,datastr); fprintf(stderr,"set datastr[%d]\n",(int32_t)strlen(datastr)); rs->restoring = 1; } From 175ac9275dc0715c231f78fc0f5329d09a04e33e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 02:56:19 -1100 Subject: [PATCH 0453/1145] Delay to see --- src/cc/rogue/rogue.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 6bb9d8f83..5fc5bd7a9 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -166,11 +166,13 @@ void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) if ( is_cJSON_True(jobj(item,"ismine")) != 0 ) { fprintf(stderr,"found ismine:true\n"); + sleep(2); if ( (item= jobj(item,"player")) != 0 && (datastr= jstr(item,"data")) != 0 ) { decode_hex((uint8_t *)&rs->P,(int32_t)strlen(datastr)/2,datastr); fprintf(stderr,"set datastr[%d]\n",(int32_t)strlen(datastr)); rs->restoring = 1; + sleep(5); } } } From 8737db6f84116e86e653a79b0f6914d7b62a5e95 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 03:00:42 -1100 Subject: [PATCH 0454/1145] +print --- src/cc/rogue/rogue.c | 4 ++++ src/cc/rogue/state.c | 3 +++ 2 files changed, 7 insertions(+) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 5fc5bd7a9..27c4a9b20 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -99,7 +99,11 @@ void rogueiterate(struct rogue_state *rs) fuse(swander, 0, WANDERTIME, AFTER); start_daemon(stomach, 0, AFTER); if ( rs->restoring != 0 ) + { + fprintf(stderr,"restore player\n"); restore_player(rs); + sleep(3); + } playit(rs); } diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 68686b255..250010fe4 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1370,6 +1370,9 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item) ws_info[item->which].oi_know = TRUE; break; } + char packitemstr[256]; + strcpy(packitemstr,inv_name(obj,FALSE)); + fprintf(stderr,"packitem.(%s)\n",packitemstr); } void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) From 7ac4a4f99fcb9cea61a46d7003692901890ec208 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 03:01:18 -1100 Subject: [PATCH 0455/1145] Obj -> o --- src/cc/rogue/state.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 250010fe4..abbcdbdb7 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1371,7 +1371,7 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item) break; } char packitemstr[256]; - strcpy(packitemstr,inv_name(obj,FALSE)); + strcpy(packitemstr,inv_name(o,FALSE)); fprintf(stderr,"packitem.(%s)\n",packitemstr); } From 59b2c324d5ec92a37fc43fcadb8b8b90f7be12af Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 03:06:17 -1100 Subject: [PATCH 0456/1145] Test --- src/cc/rogue/state.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index abbcdbdb7..46d789f87 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1351,6 +1351,7 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item) o->_o._o_flags = item->flags; o->_o._o_group = item->group; o->o_flags |= ISKNOW; + o->o_flags &= ~ISFOUND; switch ( item->type ) { case SCROLL: @@ -1370,9 +1371,9 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item) ws_info[item->which].oi_know = TRUE; break; } - char packitemstr[256]; - strcpy(packitemstr,inv_name(o,FALSE)); - fprintf(stderr,"packitem.(%s)\n",packitemstr); + //char packitemstr[256]; + //strcpy(packitemstr,inv_name(o,FALSE)); + //fprintf(stderr,"packitem.(%s)\n",packitemstr); } void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) From 37dfb49e4ebb90f2d42d6e929a0d3ff4f39edba9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 03:08:32 -1100 Subject: [PATCH 0457/1145] -prints -sleeps --- src/cc/rogue/rogue.c | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 27c4a9b20..c2f8c667b 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -99,11 +99,7 @@ void rogueiterate(struct rogue_state *rs) fuse(swander, 0, WANDERTIME, AFTER); start_daemon(stomach, 0, AFTER); if ( rs->restoring != 0 ) - { - fprintf(stderr,"restore player\n"); restore_player(rs); - sleep(3); - } playit(rs); } @@ -169,14 +165,11 @@ void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) item = jitem(array,i); if ( is_cJSON_True(jobj(item,"ismine")) != 0 ) { - fprintf(stderr,"found ismine:true\n"); - sleep(2); if ( (item= jobj(item,"player")) != 0 && (datastr= jstr(item,"data")) != 0 ) { decode_hex((uint8_t *)&rs->P,(int32_t)strlen(datastr)/2,datastr); - fprintf(stderr,"set datastr[%d]\n",(int32_t)strlen(datastr)); + //fprintf(stderr,"set datastr[%d]\n",(int32_t)strlen(datastr)); rs->restoring = 1; - sleep(5); } } } From b50a9670ce7cdaa6cb927cf48706b4b316ae760a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 03:21:25 -1100 Subject: [PATCH 0458/1145] Restore --- src/cc/rogue/rogue.c | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index c2f8c667b..4aaab985c 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -146,9 +146,9 @@ int32_t flushkeystrokes(struct rogue_state *rs) uint8_t *OS_fileptr(long *allocsizep,char *fname); #define is_cJSON_True(json) ((json) != 0 && ((json)->type & 0xff) == cJSON_True) -void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) +int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) { - char cmd[32768]; int32_t i,n; char *filestr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; + char cmd[32768]; int32_t i,n,retval=-1; char *filestr,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; sprintf(fname,"%s.gameinfo",gametxidstr); sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); if ( system(cmd) != 0 ) @@ -163,13 +163,17 @@ void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) for (i=0; iP,(int32_t)strlen(datastr)/2,datastr); - //fprintf(stderr,"set datastr[%d]\n",(int32_t)strlen(datastr)); - rs->restoring = 1; + retval = 0; + if ( (item= jobj(item,"player")) != 0 && (datastr= jstr(item,"data")) != 0 ) + { + decode_hex((uint8_t *)&rs->P,(int32_t)strlen(datastr)/2,datastr); + //fprintf(stderr,"set datastr[%d]\n",(int32_t)strlen(datastr)); + rs->restoring = 1; + } } } } @@ -178,6 +182,7 @@ void rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } free(filestr); } + return(retval); } void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) // use seed to lookup gametxid @@ -209,7 +214,11 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu rs->numkeys = num; rs->sleeptime = 0; if ( player != 0 ) + { rs->P = *player; + rs->restoring = 1; + fprintf(stderr,"restore player\n"); + } uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); /*fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL) - starttime); @@ -298,7 +307,11 @@ int rogue(int argc, char **argv, char **envp) { rs->seed = atol(argv[1]); strcpy(Gametxidstr,argv[2]); - rogue_setplayerdata(rs,Gametxidstr); + if ( rogue_setplayerdata(rs,Gametxidstr) < 0 ) + { + fprintf(stderr,"invalid gametxid, or already started\n"); + return(-1); + } } else rs->seed = 777; rs->guiflag = 1; rs->sleeptime = 1; // non-zero to allow refresh() From 3b32174da75cee49d66c15b961cfd305f6f832d6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 03:29:02 -1100 Subject: [PATCH 0459/1145] Test --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 47b166ce2..ebfd32620 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -808,8 +808,9 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { UniValue obj; struct rogue_player P; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); - fprintf(stderr,"found baton %s numkeys.%d seed.%llu\n",batontxid.ToString().c_str(),numkeys,(long long)seed); + fprintf(stderr,"found baton %s numkeys.%d seed.%llu playerdata.%d\n",batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); + sleep(60); if ( playerdata.size() > 0 ) { for (i=0; i Date: Sun, 10 Feb 2019 03:32:42 -1100 Subject: [PATCH 0460/1145] +prints --- src/cc/rogue/rogue.c | 2 +- src/cc/rogue/state.c | 6 +++--- src/cc/rogue_rpc.cpp | 1 - 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 4aaab985c..65a6ae605 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -217,7 +217,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu { rs->P = *player; rs->restoring = 1; - fprintf(stderr,"restore player\n"); + fprintf(stderr,"restore player packsize.%d\n",rp->P.packsize); } uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 46d789f87..b97c5035f 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1371,9 +1371,9 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item) ws_info[item->which].oi_know = TRUE; break; } - //char packitemstr[256]; - //strcpy(packitemstr,inv_name(o,FALSE)); - //fprintf(stderr,"packitem.(%s)\n",packitemstr); + char packitemstr[256]; + strcpy(packitemstr,inv_name(o,FALSE)); + fprintf(stderr,"packitem.(%s)\n",packitemstr); } void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ebfd32620..28fd07f6a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -810,7 +810,6 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); fprintf(stderr,"found baton %s numkeys.%d seed.%llu playerdata.%d\n",batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); - sleep(60); if ( playerdata.size() > 0 ) { for (i=0; i Date: Sun, 10 Feb 2019 03:34:08 -1100 Subject: [PATCH 0461/1145] Rs --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 65a6ae605..d7bc45fb6 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -217,7 +217,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu { rs->P = *player; rs->restoring = 1; - fprintf(stderr,"restore player packsize.%d\n",rp->P.packsize); + fprintf(stderr,"restore player packsize.%d\n",rs->P.packsize); } uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); From 502195f02dfc87698342b8d2db9796420acdac30 Mon Sep 17 00:00:00 2001 From: dimxy Date: Sun, 10 Feb 2019 19:37:01 +0500 Subject: [PATCH 0462/1145] changed vout0 for tokens, added token opret with non-fungible data --- src/cc/rogue_rpc.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 47b166ce2..6923d5a56 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -822,7 +822,8 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param mtx.vin.push_back(CTxIn(gametxid,1+maxplayers+regslot,CScript())); if ( funcid == 'H' ) mtx.vin.push_back(CTxIn(gametxid,0,CScript())); - mtx.vout.push_back(MakeCC1vout(cp->evalcode,1,mypk)); + //mtx.vout.push_back(MakeCC1vout(cp->evalcode,1,mypk)); + mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, mypk)); if ( num > 0 ) { newdata.resize(num); @@ -848,7 +849,14 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-2*txfee),roguepk)); Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_highlanderopret(funcid,gametxid,mypk,newdata)); + //rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_highlanderopret(funcid,gametxid,mypk,newdata)); + + CScript opret = rogue_highlanderopret(funcid, gametxid, mypk, newdata); + + std::vector vopretNonfungible; + GetOpReturnData(opret, vopretNonfungible); + rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenCreateOpRet('c', Mypubkey(), std::string("???"), std::string("??????"), vopretNonfungible)); + return(rogue_rawtxresult(result,rawtx,1)); } result.push_back(Pair("result","success")); From 91d0ed149b5c8427b6a39f2633cad62f6b0e0459 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 03:37:46 -1100 Subject: [PATCH 0463/1145] Sleeps --- src/cc/rogue/rogue.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index d7bc45fb6..002912509 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -99,7 +99,10 @@ void rogueiterate(struct rogue_state *rs) fuse(swander, 0, WANDERTIME, AFTER); start_daemon(stomach, 0, AFTER); if ( rs->restoring != 0 ) + { restore_player(rs); + sleep(3); + } playit(rs); } @@ -218,6 +221,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu rs->P = *player; rs->restoring = 1; fprintf(stderr,"restore player packsize.%d\n",rs->P.packsize); + sleep(3); } uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); From 1c1ae17c10f85ebca93094364d5d638fdda3d3f3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 03:42:35 -1100 Subject: [PATCH 0464/1145] replaydone --- src/cc/rogue/rogue.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 002912509..91b09b0a3 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -99,10 +99,7 @@ void rogueiterate(struct rogue_state *rs) fuse(swander, 0, WANDERTIME, AFTER); start_daemon(stomach, 0, AFTER); if ( rs->restoring != 0 ) - { restore_player(rs); - sleep(3); - } playit(rs); } @@ -221,7 +218,6 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu rs->P = *player; rs->restoring = 1; fprintf(stderr,"restore player packsize.%d\n",rs->P.packsize); - sleep(3); } uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); @@ -682,9 +678,14 @@ shell(struct rogue_state *rs) void my_exit(int st) { + uint32_t counter; resetltchars(); if ( globalR.guiflag != 0 ) exit(st); - else fprintf(stderr,"would have exit.(%d)\n",st); + else if ( counter++ < 10 ) + { + fprintf(stderr,"would have exit.(%d)\n",st); + rs->replaydone = 1; + } } From 8f9182c45e58413dc62ef62103681838cf889155 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 03:43:20 -1100 Subject: [PATCH 0465/1145] globalR. --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 91b09b0a3..f56371815 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -685,7 +685,7 @@ my_exit(int st) else if ( counter++ < 10 ) { fprintf(stderr,"would have exit.(%d)\n",st); - rs->replaydone = 1; + globalR.replaydone = 1; } } From ff50eb0c7c1d7b7d9325db89780c1fe042db577e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 03:54:53 -1100 Subject: [PATCH 0466/1145] ESCAPE --- src/cc/rogue/io.c | 17 +++++++++++++---- src/cc/rogue/rogue.c | 2 +- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index f4a859b38..f52b206ce 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -161,8 +161,9 @@ readchar(struct rogue_state *rs) rs->replaydone = (uint32_t)time(NULL); return(rs->keystrokes[rs->ind++]); } - fatal("replay finished but readchar called\n"); - return(' '); + //fatal("replay finished but readchar called\n"); + rs->replaydone = (uint32_t)time(NULL); + return(ESCAPE); } if ( rs == 0 || rs->guiflag != 0 ) { @@ -277,10 +278,18 @@ wait_for(struct rogue_state *rs,int ch) if (ch == '\n') while ((c = readchar(rs)) != '\n' && c != '\r') - continue; + { + if ( rs->replaydone != 0 ) + return; + continue; + } else while (readchar(rs) != ch) - continue; + { + if ( rs->replaydone != 0 ) + return; + continue; + } } /* diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index f56371815..3d4e012ac 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -543,7 +543,7 @@ playit(struct rogue_state *rs) { if ( rs->replaydone != 0 ) { - //fprintf(stderr,"replaydone\n"); sleep(3); + fprintf(stderr,"replaydone\n"); sleep(3); return; } if ( rs->sleeptime != 0 ) From 2297cbdfac40207204c0a551d357c72fb398086c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 04:00:02 -1100 Subject: [PATCH 0467/1145] Test --- src/cc/rogue/io.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index f52b206ce..ee8aaebbb 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -159,9 +159,10 @@ readchar(struct rogue_state *rs) { if ( rs->ind == rs->numkeys-1 ) rs->replaydone = (uint32_t)time(NULL); + fprintf(stderr,"(%c) ",rs->keystrokes[rs->ind]); return(rs->keystrokes[rs->ind++]); } - //fatal("replay finished but readchar called\n"); + fprintf(stderr,"replay finished but readchar called\n"); rs->replaydone = (uint32_t)time(NULL); return(ESCAPE); } From 9ea6248655d51434880cbbb62967c52cbaf8bcd7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 04:08:13 -1100 Subject: [PATCH 0468/1145] Test --- src/cc/rogue/command.c | 2 ++ src/cc/rogue/io.c | 6 +++--- src/cc/rogue/rogue.c | 48 +++++++++++++++++++++++++----------------- 3 files changed, 34 insertions(+), 22 deletions(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index bdbf37b76..3414bfe3b 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -117,6 +117,8 @@ command(struct rogue_state *rs) * turn off count for commands which don't make sense * to repeat */ + if ( rs->guiflag == 0 && rs->replaydone != 0 ) + ch = 'Q'; switch (ch) { case CTRL('B'): case CTRL('H'): case CTRL('J'): diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index ee8aaebbb..c64b9c8b0 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -157,14 +157,14 @@ readchar(struct rogue_state *rs) { if ( rs->ind < rs->numkeys ) { - if ( rs->ind == rs->numkeys-1 ) - rs->replaydone = (uint32_t)time(NULL); + //if ( rs->ind == rs->numkeys-1 ) + // rs->replaydone = (uint32_t)time(NULL); fprintf(stderr,"(%c) ",rs->keystrokes[rs->ind]); return(rs->keystrokes[rs->ind++]); } fprintf(stderr,"replay finished but readchar called\n"); rs->replaydone = (uint32_t)time(NULL); - return(ESCAPE); + return('y'); } if ( rs == 0 || rs->guiflag != 0 ) { diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 3d4e012ac..cbabaff3b 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -571,27 +571,37 @@ quit(int sig) { struct rogue_state *rs = &globalR; int oy, ox; - - NOOP(sig); - - /* - * Reset the signal in case we got here via an interrupt - */ - if (!q_comm) - mpos = 0; - getyx(curscr, oy, ox); - msg(rs,"really quit?"); + fprintf(stder,"inside quit(%d)\n",sig); + if ( rs->guiflag != 0 ) + { + NOOP(sig); + + /* + * Reset the signal in case we got here via an interrupt + */ + if (!q_comm) + mpos = 0; + getyx(curscr, oy, ox); + msg(rs,"really quit?"); + } if (readchar(rs) == 'y') { - signal(SIGINT, leave); - clear(); - mvprintw(LINES - 2, 0, "You quit with %d gold pieces", purse); - move(LINES - 1, 0); - if ( rs->sleeptime != 0 ) - refresh(); - score(purse, 1, 0); - flushkeystrokes(rs); - my_exit(0); + if ( rs->guiflag != 0 ) + { + signal(SIGINT, leave); + clear(); + mvprintw(LINES - 2, 0, "You quit with %d gold pieces", purse); + move(LINES - 1, 0); + if ( rs->sleeptime != 0 ) + refresh(); + score(purse, 1, 0); + flushkeystrokes(rs); + my_exit(0); + } + else + { + score(purse, 1, 0); + } } else { From 4680ae91da1338da41820c965bcddfe5574554b8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 04:08:42 -1100 Subject: [PATCH 0469/1145] Stderr --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index cbabaff3b..46b3f5c33 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -571,7 +571,7 @@ quit(int sig) { struct rogue_state *rs = &globalR; int oy, ox; - fprintf(stder,"inside quit(%d)\n",sig); + fprintf(stderr,"inside quit(%d)\n",sig); if ( rs->guiflag != 0 ) { NOOP(sig); From 92ba9815e8beaa063fb3aca589814e4b4adc24c4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 04:14:17 -1100 Subject: [PATCH 0470/1145] Prints --- src/cc/rogue/command.c | 6 +++--- src/cc/rogue/rogue.c | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index 3414bfe3b..6d1520321 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -265,7 +265,7 @@ over: after = FALSE; q_comm = TRUE; quit(0); - if ( rs->needflush == 0 ) + if ( rs->guiflag != 0 && rs->needflush == 0 ) rs->needflush = (uint32_t)time(NULL); q_comm = FALSE; when 'i': after = FALSE; inventory(rs,pack, 0); @@ -282,11 +282,11 @@ over: when 'c': call(rs); after = FALSE; when '>': after = FALSE; d_level(rs); - if ( rs->needflush == 0 ) + if ( rs->guiflag != 0 && rs->needflush == 0 ) rs->needflush = (uint32_t)time(NULL); when '<': after = FALSE; u_level(rs); - if ( rs->needflush == 0 ) + if ( rs->guiflag != 0 && rs->needflush == 0 ) rs->needflush = (uint32_t)time(NULL); when '?': after = FALSE; help(rs); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 46b3f5c33..b2bd485b2 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -600,6 +600,7 @@ quit(int sig) } else { + fprintf(stderr,"done!\n"); score(purse, 1, 0); } } From a4a93eb86284fbc81ae664263281b122e776dd8f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 04:19:02 -1100 Subject: [PATCH 0471/1145] Hard return --- src/cc/rogue/command.c | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index 6d1520321..0b7618df6 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -38,6 +38,8 @@ command(struct rogue_state *rs) do_fuses(rs,BEFORE); while (ntimes--) { + if ( rs->replaydone != 0 ) + return; again = FALSE; if (has_hit) { @@ -268,6 +270,7 @@ over: if ( rs->guiflag != 0 && rs->needflush == 0 ) rs->needflush = (uint32_t)time(NULL); q_comm = FALSE; + return; when 'i': after = FALSE; inventory(rs,pack, 0); when 'I': after = FALSE; picky_inven(rs); when 'd': drop(rs); @@ -448,23 +451,23 @@ over: /* * If he ran into something to take, let him pick it up. */ - if (take != 0) - pick_up(rs,take); - if (!running) - door_stop = FALSE; - if (!after) - ntimes++; + if (take != 0) + pick_up(rs,take); + if (!running) + door_stop = FALSE; + if (!after) + ntimes++; } do_daemons(rs,AFTER); do_fuses(rs,AFTER); if (ISRING(LEFT, R_SEARCH)) - search(rs); + search(rs); else if (ISRING(LEFT, R_TELEPORT) && rnd(50) == 0) - teleport(rs); + teleport(rs); if (ISRING(RIGHT, R_SEARCH)) - search(rs); + search(rs); else if (ISRING(RIGHT, R_TELEPORT) && rnd(50) == 0) - teleport(rs); + teleport(rs); } /* From 73a696f00835a5f3be2812bc44f5cd138e8a63ab Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 04:23:23 -1100 Subject: [PATCH 0472/1145] Test --- src/cc/CCtx.cpp | 2 +- src/cc/rogue/io.c | 6 ++++-- src/cc/rogue_rpc.cpp | 11 +++++++---- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index af5535591..3e36c681a 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -157,7 +157,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran { Getscriptaddress(destaddr,vintx.vout[utxovout].scriptPubKey); //fprintf(stderr,"FinalizeCCTx() vin.%d is CC %.8f -> (%s)\n",i,(double)utxovalues[i]/COIN,destaddr); - std::cerr << "FinalizeCCtx() searching destaddr=" << destaddr << " for vin[" << i << "] satoshis=" << utxovalues[i] << std::endl; + //std::cerr << "FinalizeCCtx() searching destaddr=" << destaddr << " for vin[" << i << "] satoshis=" << utxovalues[i] << std::endl; if( strcmp(destaddr, myaddr) == 0 ) { fprintf(stderr, "FinalizeCCTx() matched cc myaddr (%s)\n", myaddr); diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index c64b9c8b0..38252fafd 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -159,12 +159,14 @@ readchar(struct rogue_state *rs) { //if ( rs->ind == rs->numkeys-1 ) // rs->replaydone = (uint32_t)time(NULL); - fprintf(stderr,"(%c) ",rs->keystrokes[rs->ind]); + //fprintf(stderr,"(%c) ",rs->keystrokes[rs->ind]); return(rs->keystrokes[rs->ind++]); } fprintf(stderr,"replay finished but readchar called\n"); rs->replaydone = (uint32_t)time(NULL); - return('y'); + if ( (rand() & 1) == 0 ) + return(ESCAPE); + else return('y'); } if ( rs == 0 || rs->guiflag != 0 ) { diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 28fd07f6a..ff8ab88c2 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -839,9 +839,12 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(cclib_error(result,"highlander must be a winner or last one standing")); cashout += numplayers * buyin; } - if ( (inputsum= AddCClibInputs(cp,mtx,roguepk,cashout,16,cp->unspendableCCaddr)) > (uint64_t)P.gold*mult ) - CCchange = (inputsum - cashout); - mtx.vout.push_back(CTxOut(cashout,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + if ( cashout >= txfee ) + { + if ( (inputsum= AddCClibInputs(cp,mtx,roguepk,cashout,16,cp->unspendableCCaddr)) > (uint64_t)P.gold*mult ) + CCchange = (inputsum - cashout); + mtx.vout.push_back(CTxOut(cashout,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + } //for (i=0; i_o._o_type,o->_o._o_packch,o->_o._o_packch); } @@ -849,7 +852,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_highlanderopret(funcid,gametxid,mypk,newdata)); - return(rogue_rawtxresult(result,rawtx,1)); + return(rogue_rawtxresult(result,rawtx,0)); } result.push_back(Pair("result","success")); } From 9342d3f7429351bddf5e5f5ec4a70d270e8e71fc Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 04:40:58 -1100 Subject: [PATCH 0473/1145] Token support --- src/cc/CCinclude.h | 1 + src/cc/rogue_rpc.cpp | 19 ++++++++++--------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index 89e6343b9..70069cad8 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -186,6 +186,7 @@ int32_t oracle_format(uint256 *hashp,int64_t *valp,char *str,uint8_t fmt,uint8_t // CCcustom CPubKey GetUnspendable(struct CCcontract_info *cp,uint8_t *unspendablepriv); +uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopret1, std::vector &vopret2); // CCutils bool priv2addr(char *coinaddr,uint8_t buf33[33],uint8_t priv32[32]); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f4bf294ee..f35ad1629 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -197,12 +197,14 @@ CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,CPubKey pk,std::ve uint8_t rogue_highlanderopretdecode(uint256 &gametxid,CPubKey &pk,std::vector &playerdata,CScript scriptPubKey) { - std::vector vopret; uint8_t *script,e,f; - GetOpReturnData(scriptPubKey,vopret); - script = (uint8_t *)vopret.data(); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q' || f == 'S') ) + std::vector vopret,vpopret2; uint8_t *script,e,f; uint256 tokenid; std::vector voutPubkeys + if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) { - return(f); + script = (uint8_t *)vopret.data(); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) + { + return(f); + } } return(0); } @@ -419,7 +421,6 @@ int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firs playertxid is whoever owns the nonfungible satoshi and it might have been bought and sold many times. highlander is the game winning tx with the player data and is the only place where the unique player data exists origplayergame is the gametxid that ends up being won by the highlander and they are linked directly as the highlander tx spends gametxid.vout0 - 'S' is for sell, but will need to change to accomodate assets */ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPubKey &pk,std::vector &playerdata,uint256 playertxid) @@ -429,7 +430,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub { GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); script = (uint8_t *)vopret.data(); - if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'Q' || script[1] == 'S') ) + if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'Q') ) { memcpy(&gametxid,script+2,sizeof(gametxid)); if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) @@ -437,7 +438,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); if ( playertx.vin[1].prevout.hash == gametxid && rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid) == 0 ) { - if ( (f= rogue_highlanderopretdecode(origplayergame,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' || f == 'S' ) + if ( (f= rogue_highlanderopretdecode(origplayergame,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { // if registertxid has vin from pk, it can be used return(0); @@ -860,7 +861,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param GetOpReturnData(opret, vopretNonfungible); rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenCreateOpRet('c', Mypubkey(), std::string("???"), std::string("??????"), vopretNonfungible)); - return(rogue_rawtxresult(result,rawtx,1)); + return(rogue_rawtxresult(result,rawtx,0)); } result.push_back(Pair("result","success")); } From 544bc5c89a37464dce19a98ca949d6ca2c457b74 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 04:42:01 -1100 Subject: [PATCH 0474/1145] ; --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f35ad1629..2a3f2dd3a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -197,7 +197,7 @@ CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,CPubKey pk,std::ve uint8_t rogue_highlanderopretdecode(uint256 &gametxid,CPubKey &pk,std::vector &playerdata,CScript scriptPubKey) { - std::vector vopret,vpopret2; uint8_t *script,e,f; uint256 tokenid; std::vector voutPubkeys + std::vector vopret,vpopret2; uint8_t *script,e,f; uint256 tokenid; std::vector voutPubkeys; if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) { script = (uint8_t *)vopret.data(); From be683c1f1302422a602634558787bbc923275e30 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 04:44:08 -1100 Subject: [PATCH 0475/1145] Vopret2 --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 2a3f2dd3a..79d47f647 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -197,7 +197,7 @@ CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,CPubKey pk,std::ve uint8_t rogue_highlanderopretdecode(uint256 &gametxid,CPubKey &pk,std::vector &playerdata,CScript scriptPubKey) { - std::vector vopret,vpopret2; uint8_t *script,e,f; uint256 tokenid; std::vector voutPubkeys; + std::vector vopret,vopret2; uint8_t *script,e,f; uint256 tokenid; std::vector voutPubkeys; if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) { script = (uint8_t *)vopret.data(); From 43f0a2ba92d2a976aaf2cbe762ddd959465f8445 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 05:03:39 -1100 Subject: [PATCH 0476/1145] Hardcode address --- src/cc/CCtx.cpp | 16 ++++++++-------- src/cc/rogue_rpc.cpp | 10 +++++----- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index 3e36c681a..63f104896 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -160,7 +160,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran //std::cerr << "FinalizeCCtx() searching destaddr=" << destaddr << " for vin[" << i << "] satoshis=" << utxovalues[i] << std::endl; if( strcmp(destaddr, myaddr) == 0 ) { - fprintf(stderr, "FinalizeCCTx() matched cc myaddr (%s)\n", myaddr); + //fprintf(stderr, "FinalizeCCTx() matched cc myaddr (%s)\n", myaddr); privkey = myprivkey; cond = mycond; } @@ -168,30 +168,30 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran { privkey = myprivkey; cond = mytokenscond; - fprintf(stderr,"FinalizeCCTx() matched dual-eval TokensCC1vout my token addr.(%s)\n",mytokensaddr); + //fprintf(stderr,"FinalizeCCTx() matched dual-eval TokensCC1vout my token addr.(%s)\n",mytokensaddr); } else if (strcmp(destaddr, mysingletokensaddr) == 0) // if this is TokensCC1vout { privkey = myprivkey; cond = mysingletokenscond; - fprintf(stderr, "FinalizeCCTx() matched single-eval token CC1vout my token addr.(%s)\n", mytokensaddr); + //fprintf(stderr, "FinalizeCCTx() matched single-eval token CC1vout my token addr.(%s)\n", mytokensaddr); } else if ( strcmp(destaddr,unspendable) == 0 ) { privkey = unspendablepriv; cond = othercond; - fprintf(stderr,"FinalizeCCTx evalcode(%d) matched unspendable CC addr.(%s)\n",cp->evalcode,unspendable); + //fprintf(stderr,"FinalizeCCTx evalcode(%d) matched unspendable CC addr.(%s)\n",cp->evalcode,unspendable); } else if (strcmp(destaddr, unspendabletokensaddr) == 0) { privkey = unspendablepriv; cond = othertokenscond; - fprintf(stderr,"FinalizeCCTx() matched unspendabletokensaddr dual/three-eval CC addr.(%s)\n",unspendabletokensaddr); + //fprintf(stderr,"FinalizeCCTx() matched unspendabletokensaddr dual/three-eval CC addr.(%s)\n",unspendabletokensaddr); } // check if this is the 2nd additional evalcode + 'unspendable' cc addr: else if ( strcmp(destaddr, cp->unspendableaddr2) == 0) { - fprintf(stderr,"FinalizeCCTx() matched %s unspendable2!\n",cp->unspendableaddr2); + //fprintf(stderr,"FinalizeCCTx() matched %s unspendable2!\n",cp->unspendableaddr2); privkey = cp->unspendablepriv2; if( othercond2 == 0 ) othercond2 = MakeCCcond1(cp->unspendableEvalcode2, cp->unspendablepk2); @@ -200,7 +200,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran // check if this is 3rd additional evalcode + 'unspendable' cc addr: else if ( strcmp(destaddr,cp->unspendableaddr3) == 0 ) { - fprintf(stderr,"FinalizeCCTx() matched %s unspendable3!\n",cp->unspendableaddr3); + //fprintf(stderr,"FinalizeCCTx() matched %s unspendable3!\n",cp->unspendableaddr3); privkey = cp->unspendablepriv3; if( othercond3 == 0 ) othercond3 = MakeCCcond1(cp->unspendableEvalcode3, cp->unspendablepk3); @@ -226,7 +226,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran // check if this is spending from 1of2 cc tokens addr: else if (strcmp(cp->tokens1of2addr, destaddr) == 0) { - fprintf(stderr,"FinalizeCCTx() matched %s cp->tokens1of2addr!\n", cp->tokens1of2addr); + //fprintf(stderr,"FinalizeCCTx() matched %s cp->tokens1of2addr!\n", cp->tokens1of2addr); privkey = myprivkey; if (othercond1of2tokens == 0) // NOTE: if additionalEvalcode2 is not set then it is dual-eval cc else three-eval cc diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 79d47f647..981de91ae 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -128,12 +128,12 @@ // cclib newgame 17 \"[3,10]\" // cclib pending 17 -// cclib gameinfo 17 \"[%2250ad0155ea102f94949d51cc911e1d41ac03d24caf1a79cf5e0a4d9cc05ed836%22]\" -// cclib register 17 \"[%2250ad0155ea102f94949d51cc911e1d41ac03d24caf1a79cf5e0a4d9cc05ed836%22]\" +// cclib gameinfo 17 \"[%22f60167a973fc4a5ff08b378bff78bfbfa2f7fae04d603e8deb9acdb1551e0d10%22]\" +// cclib register 17 \"[%22f60167a973fc4a5ff08b378bff78bfbfa2f7fae04d603e8deb9acdb1551e0d10%22]\" // ./rogue gui -> creates keystroke files -// cclib register 17 \"[%2250ad0155ea102f94949d51cc911e1d41ac03d24caf1a79cf5e0a4d9cc05ed836%22,%2233d52f92980ceaa81556093171ee224e085fd384690d83460d6fbbad96fe0e7e%22]\" +// cclib register 17 \"[%22f60167a973fc4a5ff08b378bff78bfbfa2f7fae04d603e8deb9acdb1551e0d10%22,%2233d52f92980ceaa81556093171ee224e085fd384690d83460d6fbbad96fe0e7e%22]\" // cclib keystrokes 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22deadbeef%22]\" -// cclib bailout 17 \"[%2250ad0155ea102f94949d51cc911e1d41ac03d24caf1a79cf5e0a4d9cc05ed836%22]\" +// cclib bailout 17 \"[%22f60167a973fc4a5ff08b378bff78bfbfa2f7fae04d603e8deb9acdb1551e0d10%22]\" // eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd /* 2409 gold.209 hp.17 strength.16 level.3 exp.22 3 @@ -952,7 +952,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) roguepk = GetUnspendable(cp,0); mypk = pubkey2pk(Mypubkey()); GetCCaddress(cp,coinaddr,mypk); - SetCCunspents(unspentOutputs,coinaddr); + SetCCunspents(unspentOutputs,"RLxgD7gu5XEbzPkFWVLDV38CrfXwqfz73z");//coinaddr); rogue_univalue(result,"players",-1,-1); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { From 3b9b9191f3f12cdddde25fd739298ea416ccba88 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 05:08:45 -1100 Subject: [PATCH 0477/1145] Dont do raw data access --- src/cc/rogue_rpc.cpp | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 981de91ae..7c2869fc6 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -428,22 +428,19 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,gameheight,numvouts,maxplayers; int64_t buyin; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) { - GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); - script = (uint8_t *)vopret.data(); - if ( vopret.size() > 34 && script[0] == EVAL_ROGUE && (script[1] == 'H' || script[1] == 'Q') ) + //GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); + //script = (uint8_t *)vopret.data(); + if ( (f= rogue_highlanderopretdecode(gametxid,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { - memcpy(&gametxid,script+2,sizeof(gametxid)); + fprintf(stderr,"gametxid.%s\n",gametxid.GetHex().c_str()); + //memcpy(&gametxid,script+2,sizeof(gametxid)); if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); if ( playertx.vin[1].prevout.hash == gametxid && rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid) == 0 ) { - if ( (f= rogue_highlanderopretdecode(origplayergame,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) - { - // if registertxid has vin from pk, it can be used - return(0); - } - else fprintf(stderr,"f is %c/%d\n",f,f); + // if registertxid has vin from pk, it can be used + return(0); } else fprintf(stderr,"hash mismatch or illegal gametxid\n"); } } @@ -958,7 +955,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { txid = it->first.txhash; vout = (int32_t)it->first.index; - //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); + char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( it->second.satoshis != 1 || vout != 0 ) continue; if ( rogue_playerdata(cp,gametxid,pk,playerdata,txid) == 0 && pk == mypk ) From 24c390a0cda4bd6d36fec262927e29010c2f08a4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 05:15:22 -1100 Subject: [PATCH 0478/1145] -sleep --- src/cc/rogue/rogue.c | 2 +- src/cc/rogue_rpc.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index b2bd485b2..0d7c47fda 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -543,7 +543,7 @@ playit(struct rogue_state *rs) { if ( rs->replaydone != 0 ) { - fprintf(stderr,"replaydone\n"); sleep(3); + //fprintf(stderr,"replaydone\n"); sleep(3); return; } if ( rs->sleeptime != 0 ) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 7c2869fc6..0421ed8d1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -948,8 +948,8 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); mypk = pubkey2pk(Mypubkey()); - GetCCaddress(cp,coinaddr,mypk); - SetCCunspents(unspentOutputs,"RLxgD7gu5XEbzPkFWVLDV38CrfXwqfz73z");//coinaddr); + GetTokensCCaddress(cp,coinaddr,mypk); + SetCCunspents(unspentOutputs,coinaddr); rogue_univalue(result,"players",-1,-1); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { From 6fdf25af762fb3975b5b6608a2864080241f7015 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 07:11:30 -1100 Subject: [PATCH 0479/1145] Fix cclibinfo for rogue --- src/cc/CCcustom.cpp | 2 +- src/cc/cclib.cpp | 6 +++--- src/cc/rogue/daemons.c | 2 +- src/cc/rogue/fight.c | 12 ++++++------ src/cc/rogue/move.c | 4 ++-- src/cc/rogue/rip.c | 9 +++++++-- src/cc/rogue/rogue.c | 2 +- src/cc/rogue/rogue.h | 2 +- src/cc/rogue/sticks.c | 4 ++-- src/cc/rogue_rpc.cpp | 15 ++++++--------- 10 files changed, 30 insertions(+), 28 deletions(-) diff --git a/src/cc/CCcustom.cpp b/src/cc/CCcustom.cpp index d2cb811cd..3a00e0c98 100644 --- a/src/cc/CCcustom.cpp +++ b/src/cc/CCcustom.cpp @@ -262,7 +262,7 @@ int32_t CClib_initcp(struct CCcontract_info *cp,uint8_t evalcode) { if ( buf2pk(check33) == pk && strcmp(checkaddr,cp->normaladdr) == 0 ) { - fprintf(stderr,"verified evalcode.%d %s %s\n",cp->evalcode,checkaddr,pubkey33_str(str,pub33)); + //fprintf(stderr,"verified evalcode.%d %s %s\n",cp->evalcode,checkaddr,pubkey33_str(str,pub33)); return(0); } else fprintf(stderr,"CClib_initcp mismatched privkey -> addr %s vs %s\n",checkaddr,cp->normaladdr); } diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 78332c576..ea39bbc41 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -58,10 +58,10 @@ CClib_methods[] = { (char *)"rogue", (char *)"pending", (char *)"", 0, 0, 'P', EVAL_ROGUE }, { (char *)"rogue", (char *)"register", (char *)"gametxid [playertxid]", 1, 2, 'R', EVAL_ROGUE }, { (char *)"rogue", (char *)"keystrokes", (char *)"gametxid keystrokes", 2, 2, 'K', EVAL_ROGUE }, - { (char *)"rogue", (char *)"bailout", (char *)"baton finalhash", 2, 2, 'Q', EVAL_ROGUE }, - { (char *)"rogue", (char *)"highlander", (char *)"baton finalhash", 2, 2, 'H', EVAL_ROGUE }, + { (char *)"rogue", (char *)"bailout", (char *)"gametxid", 1, 1, 'Q', EVAL_ROGUE }, + { (char *)"rogue", (char *)"highlander", (char *)"gametxid", 1, 1, 'H', EVAL_ROGUE }, { (char *)"rogue", (char *)"playerinfo", (char *)"playertxid", 1, 1, 'I', EVAL_ROGUE }, - { (char *)"rogue", (char *)"players", (char *)"playertxid", 1, 1, 'D', EVAL_ROGUE }, + { (char *)"rogue", (char *)"players", (char *)"", 0, 0, 'D', EVAL_ROGUE }, #else { (char *)"sudoku", (char *)"gen", (char *)"", 0, 0, 'G', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, diff --git a/src/cc/rogue/daemons.c b/src/cc/rogue/daemons.c index 75d544cda..436aa004d 100644 --- a/src/cc/rogue/daemons.c +++ b/src/cc/rogue/daemons.c @@ -143,7 +143,7 @@ stomach(struct rogue_state *rs,int arg) if (food_left <= 0) { if (food_left-- < -STARVETIME) - death('s'); + death(rs,'s'); /* * the hero is fainting */ diff --git a/src/cc/rogue/fight.c b/src/cc/rogue/fight.c index 6f5fc00b4..7f4aad587 100644 --- a/src/cc/rogue/fight.c +++ b/src/cc/rogue/fight.c @@ -175,7 +175,7 @@ attack(struct rogue_state *rs,THING *mp) endmsg(rs); has_hit = FALSE; if (pstats.s_hpt <= 0) - death(mp->t_type); /* Bye bye life ... */ + death(rs,mp->t_type); /* Bye bye life ... */ else if (!kamikaze) { oldhp -= pstats.s_hpt; @@ -206,7 +206,7 @@ attack(struct rogue_state *rs,THING *mp) } no_command += rnd(2) + 2; if (no_command > BORE_LEVEL) - death('h'); + death(rs,'h'); when 'R': /* * Rattlesnakes have poisonous bites @@ -242,7 +242,7 @@ attack(struct rogue_state *rs,THING *mp) if (mp->t_type == 'W') { if (pstats.s_exp == 0) - death('W'); /* All levels gone */ + death(rs,'W'); /* All levels gone */ if (--pstats.s_lvl == 0) { pstats.s_exp = 0; @@ -259,7 +259,7 @@ attack(struct rogue_state *rs,THING *mp) if (pstats.s_hpt <= 0) pstats.s_hpt = 1; if (max_hp <= 0) - death(mp->t_type); + death(rs,mp->t_type); msg(rs,"you suddenly feel weaker"); } when 'F': @@ -269,7 +269,7 @@ attack(struct rogue_state *rs,THING *mp) player.t_flags |= ISHELD; sprintf(monsters['F'-'A'].m_stats.s_dmg,"%dx1", ++vf_hit); if (--pstats.s_hpt <= 0) - death('F'); + death(rs,'F'); when 'L': { /* @@ -327,7 +327,7 @@ attack(struct rogue_state *rs,THING *mp) { pstats.s_hpt -= vf_hit; if (pstats.s_hpt <= 0) - death(mp->t_type); /* Bye bye life ... */ + death(rs,mp->t_type); /* Bye bye life ... */ } miss(rs,mname, (char *) NULL, FALSE); } diff --git a/src/cc/rogue/move.c b/src/cc/rogue/move.c index 87276e8e2..3bdf90d37 100644 --- a/src/cc/rogue/move.c +++ b/src/cc/rogue/move.c @@ -310,7 +310,7 @@ be_trapped(struct rogue_state *rs,coord *tc) if (pstats.s_hpt <= 0) { msg(rs,"an arrow killed you"); - death('a'); + death(rs,'a'); } else msg(rs,"oh no! An arrow shot you"); @@ -340,7 +340,7 @@ be_trapped(struct rogue_state *rs,coord *tc) if (pstats.s_hpt <= 0) { msg(rs,"a poisoned dart killed you"); - death('d'); + death(rs,'d'); } if (!ISWEARING(R_SUSTSTR) && !save(VS_POISON)) chg_str(-1); diff --git a/src/cc/rogue/rip.c b/src/cc/rogue/rip.c index 69eb89751..4e3a349a8 100644 --- a/src/cc/rogue/rip.c +++ b/src/cc/rogue/rip.c @@ -227,13 +227,18 @@ score(int amount, int flags, char monst) */ void -death(char monst) +death(struct rogue_state *rs,char monst) { char **dp, *killer; struct tm *lt; static time_t date; //struct tm *localtime(const time_t *); - + if ( rs->guiflag == 0 ) + { + fprintf(stderr,"death during replay\n"); + rs->replaydone = (uint32_t)time(NULL); + return; + } signal(SIGINT, SIG_IGN); purse -= purse / 10; signal(SIGINT, leave); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 0d7c47fda..57b63eb25 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -388,7 +388,7 @@ int rogue(int argc, char **argv, char **envp) level = rnd(100) + 1; initscr(); getltchars(); - death(death_monst()); + death(rs,death_monst()); exit(0); } } diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index ab7eba4b3..6543976da 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -586,7 +586,7 @@ void create_obj(struct rogue_state *rs); void current(struct rogue_state *rs,THING *cur, char *how, char *where); void d_level(struct rogue_state *rs); -void death(char monst); +void death(struct rogue_state *rs,char monst); char death_monst(void); void dig(int y, int x); void discard(THING *item); diff --git a/src/cc/rogue/sticks.c b/src/cc/rogue/sticks.c index 7f9dc6ec2..39e098339 100644 --- a/src/cc/rogue/sticks.c +++ b/src/cc/rogue/sticks.c @@ -391,9 +391,9 @@ def: if ((pstats.s_hpt -= roll(6, 6)) <= 0) { if (start == &hero) - death('b'); + death(rs,'b'); else - death(moat(start->y, start->x)->t_type); + death(rs,moat(start->y, start->x)->t_type); } used = TRUE; if (terse) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 0421ed8d1..0ba5bc6ae 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -114,26 +114,23 @@ */ // todo: -// verify playerdata is usable -// detect playerdeath/quit to prevent illegal keystrokes vector +// -detect playerdeath/quit to prevent illegal keystrokes vector // verify keystrokes tx is in mempool and confirmed // check that bailout is legal, ie. proper gametxid vin // verify amulet possession in pack -// display playerdata (user comments?, or fully decode) -// verify playerdata can be used and has same initial level -// prevent running gui mode when keystrokes txid already there +// -verify playerdata can be used and has same initial level //////////////////////// start of CClib interface //./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey=03951a6f7967ad784453116bc55cd30c54f91ea8a5b1e9b04d6b29cfd6b395ba6c -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc > /dev/null & // cclib newgame 17 \"[3,10]\" // cclib pending 17 -// cclib gameinfo 17 \"[%22f60167a973fc4a5ff08b378bff78bfbfa2f7fae04d603e8deb9acdb1551e0d10%22]\" -// cclib register 17 \"[%22f60167a973fc4a5ff08b378bff78bfbfa2f7fae04d603e8deb9acdb1551e0d10%22]\" +// cclib gameinfo 17 \"[%22a49f90d6b5a226132a8615c9b55b254629611565c69246ea58f7a02059b847bf%22]\" +// cclib register 17 \"[%22a49f90d6b5a226132a8615c9b55b254629611565c69246ea58f7a02059b847bf%22]\" // ./rogue gui -> creates keystroke files -// cclib register 17 \"[%22f60167a973fc4a5ff08b378bff78bfbfa2f7fae04d603e8deb9acdb1551e0d10%22,%2233d52f92980ceaa81556093171ee224e085fd384690d83460d6fbbad96fe0e7e%22]\" +// cclib register 17 \"[%22a49f90d6b5a226132a8615c9b55b254629611565c69246ea58f7a02059b847bf%22,%22f3a4a61cfa0dd43733b06d1368c199594258e0f3db983dc1b9b10768a5671909%22]\" // cclib keystrokes 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22deadbeef%22]\" -// cclib bailout 17 \"[%22f60167a973fc4a5ff08b378bff78bfbfa2f7fae04d603e8deb9acdb1551e0d10%22]\" +// cclib bailout 17 \"[%22a49f90d6b5a226132a8615c9b55b254629611565c69246ea58f7a02059b847bf%22]\" // eef1d0091a88d85bdac1ede9d31db8504bc466a6695fdf259dac623fce09e0dd /* 2409 gold.209 hp.17 strength.16 level.3 exp.22 3 From 82b8ae689a41b3ec32708a15a6a79b1de49b6a3a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 07:33:44 -1100 Subject: [PATCH 0480/1145] Player death -> loss of player data --- src/cc/rogue/state.c | 38 +++++++++++++++++--------- src/cc/rogue_rpc.cpp | 63 +++++++++++++++++++++++++------------------- 2 files changed, 61 insertions(+), 40 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index b97c5035f..b47b83faf 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1428,21 +1428,33 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) if ( o->_o._o_packch != 0 ) { item = &rs->P.roguepack[rs->P.packsize]; - if ( rs->P.packsize++ == 0 ) + if ( pstats.s_hpt <= 0 ) { - rs->P.gold = purse; - rs->P.hitpoints = max_hp; - rs->P.strength = max_stats.s_str; - rs->P.level = pstats.s_lvl; - rs->P.experience = pstats.s_exp; - rs->P.dungeonlevel = level; - fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,max_stats.s_str,pstats.s_lvl,pstats.s_exp,level); - }; - fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); - if ( rs->P.packsize < MAXPACK ) - packsave(item,o->_o._o_type,o->_o._o_launch,o->_o._o_damage,sizeof(o->_o._o_damage),o->_o._o_hurldmg,sizeof(o->_o._o_hurldmg),o->_o._o_count,o->_o._o_which,o->_o._o_hplus,o->_o._o_dplus,o->_o._o_arm,o->_o._o_flags,o->_o._o_group); + fprintf(stderr,"KILLED\n"); + rs->P.gold = -1; + rs->P.hitpoints = -1; + rs->P.strength = -1; + rs->P.level = -1; + rs->P.experience = -1; + rs->P.dungeonlevel = -1; + } + else + { + if ( rs->P.packsize++ == 0 ) + { + rs->P.gold = purse; + rs->P.hitpoints = max_hp; + rs->P.strength = max_stats.s_str; + rs->P.level = pstats.s_lvl; + rs->P.experience = pstats.s_exp; + rs->P.dungeonlevel = level; + fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,max_stats.s_str,pstats.s_lvl,pstats.s_exp,level); + } + fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); + if ( rs->P.packsize < MAXPACK ) + packsave(item,o->_o._o_type,o->_o._o_launch,o->_o._o_damage,sizeof(o->_o._o_damage),o->_o._o_hurldmg,sizeof(o->_o._o_hurldmg),o->_o._o_count,o->_o._o_which,o->_o._o_hplus,o->_o._o_dplus,o->_o._o_arm,o->_o._o_flags,o->_o._o_group); + } } - rs_write_marker(savef, RSID_OBJECT); rs_write_int(savef, o->_o._o_type); rs_write_coord(savef, o->_o._o_pos); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 0ba5bc6ae..11c2d28ae 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -194,10 +194,12 @@ CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,CPubKey pk,std::ve uint8_t rogue_highlanderopretdecode(uint256 &gametxid,CPubKey &pk,std::vector &playerdata,CScript scriptPubKey) { - std::vector vopret,vopret2; uint8_t *script,e,f; uint256 tokenid; std::vector voutPubkeys; - if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) + std::vector vopret,vopret2; uint8_t e,f; uint256 tokenid; std::vector voutPubkeys; + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) + return(f); + else if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) { - script = (uint8_t *)vopret.data(); if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) { return(f); @@ -208,9 +210,8 @@ uint8_t rogue_highlanderopretdecode(uint256 &gametxid,CPubKey &pk,std::vector &keystrokes,CScript scriptPubKey) { - std::vector vopret; uint8_t *script,e,f; + std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); - script = (uint8_t *)vopret.data(); if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> batontxid; ss >> pk; ss >> keystrokes) != 0 && e == EVAL_ROGUE && f == 'K' ) { return(f); @@ -220,9 +221,8 @@ uint8_t rogue_keystrokesopretdecode(uint256 &gametxid,uint256 &batontxid,CPubKey uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &playertxid,CScript scriptPubKey) { - std::vector vopret; uint8_t *script,e,f; + std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); - script = (uint8_t *)vopret.data(); if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) { return(f); @@ -232,9 +232,8 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &playertxid,CScript uint8_t rogue_newgameopreturndecode(int64_t &buyin,int32_t &maxplayers,CScript scriptPubKey) { - std::vector vopret; uint8_t *script,e,f; + std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); - script = (uint8_t *)vopret.data(); if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> buyin; ss >> maxplayers) != 0 && e == EVAL_ROGUE && f == 'G' ) { return(f); @@ -817,7 +816,6 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param mtx.vin.push_back(CTxIn(gametxid,1+maxplayers+regslot,CScript())); if ( funcid == 'H' ) mtx.vin.push_back(CTxIn(gametxid,0,CScript())); - //mtx.vout.push_back(MakeCC1vout(cp->evalcode,1,mypk)); mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, mypk)); if ( num > 0 ) { @@ -827,19 +825,27 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param newdata[i] = player[i]; ((uint8_t *)&P)[i] = player[i]; } - fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); - cashout = (uint64_t)P.gold * mult; - if ( funcid == 'H' && maxplayers > 1 ) + if ( P.gold < 0 || P.hitpoints < 0 || P.strength < 0 || P.level < 0 || P.experience < 0 || P.dungeonlevel < 0 ) { - if ( numplayers != maxplayers || (numplayers - rogue_playersalive(tmp,gametxid,maxplayers)) > 1 && (P.dungeonlevel > 1 || P.gold < 10000 || P.level < 20) ) - return(cclib_error(result,"highlander must be a winner or last one standing")); - cashout += numplayers * buyin; + fprintf(stderr,"was killed -> no playerdata\n"); + newdata.resize(0); } - if ( cashout >= txfee ) + else { - if ( (inputsum= AddCClibInputs(cp,mtx,roguepk,cashout,16,cp->unspendableCCaddr)) > (uint64_t)P.gold*mult ) - CCchange = (inputsum - cashout); - mtx.vout.push_back(CTxOut(cashout,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); + cashout = (uint64_t)P.gold * mult; + if ( funcid == 'H' && maxplayers > 1 ) + { + if ( numplayers != maxplayers || (numplayers - rogue_playersalive(tmp,gametxid,maxplayers)) > 1 && (P.dungeonlevel > 1 || P.gold < 10000 || P.level < 20) ) + return(cclib_error(result,"highlander must be a winner or last one standing")); + cashout += numplayers * buyin; + } + if ( cashout >= txfee ) + { + if ( (inputsum= AddCClibInputs(cp,mtx,roguepk,cashout,16,cp->unspendableCCaddr)) > (uint64_t)P.gold*mult ) + CCchange = (inputsum - cashout); + mtx.vout.push_back(CTxOut(cashout,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); + } } //for (i=0; i_o._o_type,o->_o._o_packch,o->_o._o_packch); @@ -847,14 +853,17 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-2*txfee),roguepk)); Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); - //rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_highlanderopret(funcid,gametxid,mypk,newdata)); - CScript opret = rogue_highlanderopret(funcid, gametxid, mypk, newdata); - - std::vector vopretNonfungible; - GetOpReturnData(opret, vopretNonfungible); - rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenCreateOpRet('c', Mypubkey(), std::string("???"), std::string("??????"), vopretNonfungible)); - + if ( newdata.size() == 0 ) + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,opret); + else + { + char seedstr[32]; + sprintf(seedstr,"%llu",(long long)seed); + std::vector vopretNonfungible; + GetOpReturnData(opret, vopretNonfungible); + rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenCreateOpRet('c', Mypubkey(), std::string(seedstr), gametxid.GetHex(), vopretNonfungible)); + } return(rogue_rawtxresult(result,rawtx,0)); } result.push_back(Pair("result","success")); From 8919dd65236a41f976919fb1f2e097d75276d3f5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 07:42:52 -1100 Subject: [PATCH 0481/1145] Auto bailout on quit or death --- src/cc/rogue/command.c | 1 + src/cc/rogue/extern.h | 1 + src/cc/rogue/rip.c | 1 + src/cc/rogue/rogue.c | 13 ++++++++++++- src/cc/rogue_rpc.cpp | 16 ---------------- 5 files changed, 15 insertions(+), 17 deletions(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index 0b7618df6..a6cf50724 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -270,6 +270,7 @@ over: if ( rs->guiflag != 0 && rs->needflush == 0 ) rs->needflush = (uint32_t)time(NULL); q_comm = FALSE; + rogue_bailout(); return; when 'i': after = FALSE; inventory(rs,pack, 0); when 'I': after = FALSE; picky_inven(rs); diff --git a/src/cc/rogue/extern.h b/src/cc/rogue/extern.h index 486d85ff1..0791702d6 100644 --- a/src/cc/rogue/extern.h +++ b/src/cc/rogue/extern.h @@ -184,6 +184,7 @@ void md_onsignal_default(void); int md_issymlink(char *sp); int32_t decode_hex(uint8_t *bytes,int32_t n,char *hex); +void rogue_bailout(void); #endif diff --git a/src/cc/rogue/rip.c b/src/cc/rogue/rip.c index 4e3a349a8..56f2453a4 100644 --- a/src/cc/rogue/rip.c +++ b/src/cc/rogue/rip.c @@ -275,6 +275,7 @@ death(struct rogue_state *rs,char monst) move(LINES - 1, 0); refresh(); score(purse, amulet ? 3 : 0, monst); + rogue_bailout(); printf("[Press return to continue]"); fflush(stdout); if ( fgets(prbuf,10,stdin) != 0 ) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 57b63eb25..2d89cbc67 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -185,7 +185,18 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) return(retval); } -void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) // use seed to lookup gametxid +void rogue_bailout() +{ + char cmd[32768],hexstr[32768]; int32_t i; + for (i=0; i> keystrokes.log",Gametxidstr); + if ( system(cmd) != 0 ) + fprintf(stderr,"error issuing (%s)\n",cmd); +} + +void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) { char cmd[32768],hexstr[32768]; int32_t i; for (i=0; i Date: Sun, 10 Feb 2019 07:44:17 -1100 Subject: [PATCH 0482/1145] Zero value character --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e80635ba9..6e2c1b1b5 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -809,9 +809,9 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param newdata[i] = player[i]; ((uint8_t *)&P)[i] = player[i]; } - if ( P.gold < 0 || P.hitpoints < 0 || P.strength < 0 || P.level < 0 || P.experience < 0 || P.dungeonlevel < 0 ) + if ( P.gold <= 0 || P.hitpoints <= 0 || P.strength <= 0 || P.level <= 0 || P.experience <= 0 || P.dungeonlevel <= 0 ) { - fprintf(stderr,"was killed -> no playerdata\n"); + fprintf(stderr,"zero value character was killed -> no playerdata\n"); newdata.resize(0); } else From 8ac5fd8e8e49f8c58f79639056eaaeb01f4ba163 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 07:45:31 -1100 Subject: [PATCH 0483/1145] Bailout --- src/cc/rogue/rogue.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 2d89cbc67..e6ae6bc8c 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -187,10 +187,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) void rogue_bailout() { - char cmd[32768],hexstr[32768]; int32_t i; - for (i=0; i> keystrokes.log",Gametxidstr); if ( system(cmd) != 0 ) fprintf(stderr,"error issuing (%s)\n",cmd); From 55a946be4bbc75ba56770a7717853d6e363d68dd Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 07:54:02 -1100 Subject: [PATCH 0484/1145] Regslot saved --- src/cc/rogue/rogue.c | 2 +- src/cc/rogue_rpc.cpp | 27 +++++++++++++++------------ 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index e6ae6bc8c..0eca62c7f 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -188,7 +188,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) void rogue_bailout() { char cmd[512]; - sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib bailout 17 \\\"[%%22%s%%22]\\\" >> keystrokes.log",Gametxidstr); + sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib bailout 17 \\\"[%%22%s%%22]\\\" >> bailout.log",Gametxidstr); if ( system(cmd) != 0 ) fprintf(stderr,"error issuing (%s)\n",cmd); } diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 6e2c1b1b5..a80ac3b79 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -169,22 +169,22 @@ CScript rogue_keystrokesopret(uint256 gametxid,uint256 batontxid,CPubKey pk,std: return(opret); } -CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,CPubKey pk,std::vectorplayerdata) +CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,int32_t regslot,CPubKey pk,std::vectorplayerdata) { CScript opret; uint8_t evalcode = EVAL_ROGUE; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << gametxid << pk << playerdata); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << gametxid << regslot << pk << playerdata); return(opret); } -uint8_t rogue_highlanderopretdecode(uint256 &gametxid,CPubKey &pk,std::vector &playerdata,CScript scriptPubKey) +uint8_t rogue_highlanderopretdecode(uint256 &gametxid,int32_t ®slot,CPubKey &pk,std::vector &playerdata,CScript scriptPubKey) { std::vector vopret,vopret2; uint8_t e,f; uint256 tokenid; std::vector voutPubkeys; GetOpReturnData(scriptPubKey,vopret); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) return(f); else if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) { - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) { return(f); } @@ -405,12 +405,12 @@ int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firs int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPubKey &pk,std::vector &playerdata,uint256 playertxid) { - uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,gameheight,numvouts,maxplayers; int64_t buyin; + uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) { //GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); //script = (uint8_t *)vopret.data(); - if ( (f= rogue_highlanderopretdecode(gametxid,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) + if ( (f= rogue_highlanderopretdecode(gametxid,regslot,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { fprintf(stderr,"gametxid.%s\n",gametxid.GetHex().c_str()); //memcpy(&gametxid,script+2,sizeof(gametxid)); @@ -782,7 +782,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { if ( maxplayers == 1 ) mult /= 2; - if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers) == 0 && keystrokes != 0 ) + if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers) == 0 ) { UniValue obj; struct rogue_player P; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); @@ -793,14 +793,16 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param for (i=0; ievalcode, 1, mypk)); if ( num > 0 ) { newdata.resize(num); @@ -816,6 +818,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else { + mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,1,mypk)); fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); cashout = (uint64_t)P.gold * mult; if ( funcid == 'H' && maxplayers > 1 ) @@ -837,7 +840,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-2*txfee),roguepk)); Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); - CScript opret = rogue_highlanderopret(funcid, gametxid, mypk, newdata); + CScript opret = rogue_highlanderopret(funcid, gametxid, regslot,mypk, newdata); if ( newdata.size() == 0 ) rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,opret); else From f86c6a07e82a57ad0334df0c66360f2c7812e1d1 Mon Sep 17 00:00:00 2001 From: dimxy Date: Sun, 10 Feb 2019 23:54:08 +0500 Subject: [PATCH 0485/1145] added token support in register tx --- src/cc/rogue_rpc.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 0ba5bc6ae..9605d721e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -710,7 +710,13 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,rogue_registeropret(gametxid,playertxid)); + + std::vector vopretFinish, vopret2; uint8_t e, f; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; + DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretFinish, vopret2); + + CScript opretRegister = rogue_registeropret(gametxid, playertxid); + rawtx = FinalizeCCTx(0,cp,mtx,CPubKey()/*=null pubkey*/,txfee, + EncodeTokenOpRet(tokenid, voutPubkeysEmpty, vopretFinish /*=non-fungible*/, opretRegister)); return(rogue_rawtxresult(result,rawtx,1)); } else return(cclib_error(result,"invalid gametxid")); } else return(cclib_error(result,"no gametxid")); From 4c3e9226b63042d89f3442a21d723f248f0f3bee Mon Sep 17 00:00:00 2001 From: dimxy Date: Mon, 11 Feb 2019 00:16:53 +0500 Subject: [PATCH 0486/1145] corrected for both token and no token vintx --- src/cc/rogue_rpc.cpp | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9605d721e..fe886e745 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -711,12 +711,18 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); + mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, mypk)); + std::vector vopretFinish, vopret2; uint8_t e, f; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; - DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretFinish, vopret2); - CScript opretRegister = rogue_registeropret(gametxid, playertxid); - rawtx = FinalizeCCTx(0,cp,mtx,CPubKey()/*=null pubkey*/,txfee, - EncodeTokenOpRet(tokenid, voutPubkeysEmpty, vopretFinish /*=non-fungible*/, opretRegister)); + if (DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretFinish, vopret2) != 0) { // if token in the opret + rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, + EncodeTokenOpRet(tokenid, voutPubkeysEmpty /*=never spent*/, vopretFinish /*=non-fungible*/, opretRegister)); + } + else { + rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, opretRegister); + } + return(rogue_rawtxresult(result,rawtx,1)); } else return(cclib_error(result,"invalid gametxid")); } else return(cclib_error(result,"no gametxid")); From 917501e7c027187fece95cca66e7b1c76b1b5e1b Mon Sep 17 00:00:00 2001 From: dimxy Date: Mon, 11 Feb 2019 00:19:29 +0500 Subject: [PATCH 0487/1145] token vout changed to empty pk --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index fe886e745..d6eb540a8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -711,7 +711,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); - mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, mypk)); + mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, CPubKey() /*nullpk*/)); std::vector vopretFinish, vopret2; uint8_t e, f; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; CScript opretRegister = rogue_registeropret(gametxid, playertxid); From 3483c0ac9ab77616960fc850e7b1fb96dcade2b1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 08:28:43 -1100 Subject: [PATCH 0488/1145] Prevent restoring amulet --- src/cc/rogue/state.c | 76 ++++++++++++++++++++++++-------------------- src/cc/rogue_rpc.cpp | 5 ++- 2 files changed, 43 insertions(+), 38 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index b47b83faf..dd54afe25 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1339,41 +1339,44 @@ rs_read_monsters(FILE *inf, struct monster *m, int count) void rogue_restoreobject(THING *o,struct rogue_packitem *item) { int32_t i; - o->_o._o_type = item->type; - o->_o._o_launch = item->launch; - memcpy(o->_o._o_damage,item->damage,sizeof(item->damage)); - memcpy(o->_o._o_hurldmg,item->hurldmg,sizeof(item->hurldmg)); - o->_o._o_count = item->count; - o->_o._o_which = item->which; - o->_o._o_hplus = item->hplus; - o->_o._o_dplus = item->dplus; - o->_o._o_arm = item->arm; - o->_o._o_flags = item->flags; - o->_o._o_group = item->group; - o->o_flags |= ISKNOW; - o->o_flags &= ~ISFOUND; - switch ( item->type ) + if ( item->type != AMULET ) { - case SCROLL: - if ( item->which < MAXSCROLLS ) - scr_info[item->which].oi_know = TRUE; - break; - case POTION: - if ( item->which < MAXPOTIONS ) - pot_info[item->which].oi_know = TRUE; - break; - case RING: - if ( item->which < MAXRINGS ) - ring_info[item->which].oi_know = TRUE; - break; - case STICK: - if ( item->which < MAXSTICKS ) - ws_info[item->which].oi_know = TRUE; - break; + o->_o._o_type = item->type; + o->_o._o_launch = item->launch; + memcpy(o->_o._o_damage,item->damage,sizeof(item->damage)); + memcpy(o->_o._o_hurldmg,item->hurldmg,sizeof(item->hurldmg)); + o->_o._o_count = item->count; + o->_o._o_which = item->which; + o->_o._o_hplus = item->hplus; + o->_o._o_dplus = item->dplus; + o->_o._o_arm = item->arm; + o->_o._o_flags = item->flags; + o->_o._o_group = item->group; + o->o_flags |= ISKNOW; + o->o_flags &= ~ISFOUND; + switch ( item->type ) + { + case SCROLL: + if ( item->which < MAXSCROLLS ) + scr_info[item->which].oi_know = TRUE; + break; + case POTION: + if ( item->which < MAXPOTIONS ) + pot_info[item->which].oi_know = TRUE; + break; + case RING: + if ( item->which < MAXRINGS ) + ring_info[item->which].oi_know = TRUE; + break; + case STICK: + if ( item->which < MAXSTICKS ) + ws_info[item->which].oi_know = TRUE; + break; + } + char packitemstr[256]; + strcpy(packitemstr,inv_name(o,FALSE)); + fprintf(stderr,"packitem.(%s)\n",packitemstr); } - char packitemstr[256]; - strcpy(packitemstr,inv_name(o,FALSE)); - fprintf(stderr,"packitem.(%s)\n",packitemstr); } void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) @@ -1440,7 +1443,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) } else { - if ( rs->P.packsize++ == 0 ) + if ( rs->P.packsize == 0 ) { rs->P.gold = purse; rs->P.hitpoints = max_hp; @@ -1451,8 +1454,11 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,max_stats.s_str,pstats.s_lvl,pstats.s_exp,level); } fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); - if ( rs->P.packsize < MAXPACK ) + if ( rs->P.packsize < MAXPACK && o->o_type != AMULET ) + { packsave(item,o->_o._o_type,o->_o._o_launch,o->_o._o_damage,sizeof(o->_o._o_damage),o->_o._o_hurldmg,sizeof(o->_o._o_hurldmg),o->_o._o_count,o->_o._o_which,o->_o._o_hplus,o->_o._o_dplus,o->_o._o_arm,o->_o._o_flags,o->_o._o_group); + rs->P.packsize++; + } } } rs_write_marker(savef, RSID_OBJECT); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 988df05eb..66326b20d 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -114,11 +114,10 @@ */ // todo: -// -detect playerdeath/quit to prevent illegal keystrokes vector +// make register a token burn +// convert playertxid to the original playertxid // verify keystrokes tx is in mempool and confirmed -// check that bailout is legal, ie. proper gametxid vin // verify amulet possession in pack -// -verify playerdata can be used and has same initial level //////////////////////// start of CClib interface //./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey=03951a6f7967ad784453116bc55cd30c54f91ea8a5b1e9b04d6b29cfd6b395ba6c -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc > /dev/null & From a6d1adbc2336d12acba909514c80ed461b142f80 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 08:34:16 -1100 Subject: [PATCH 0489/1145] +print --- src/cc/rogue/rogue.c | 2 +- src/cc/rogue_rpc.cpp | 15 ++++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 0eca62c7f..f6bc9b727 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -579,7 +579,7 @@ quit(int sig) { struct rogue_state *rs = &globalR; int oy, ox; - fprintf(stderr,"inside quit(%d)\n",sig); + //fprintf(stderr,"inside quit(%d)\n",sig); if ( rs->guiflag != 0 ) { NOOP(sig); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 66326b20d..b0161180e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -129,7 +129,7 @@ // ./rogue gui -> creates keystroke files // cclib register 17 \"[%22a49f90d6b5a226132a8615c9b55b254629611565c69246ea58f7a02059b847bf%22,%22f3a4a61cfa0dd43733b06d1368c199594258e0f3db983dc1b9b10768a5671909%22]\" // cclib keystrokes 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22deadbeef%22]\" -// cclib bailout 17 \"[%22a49f90d6b5a226132a8615c9b55b254629611565c69246ea58f7a02059b847bf%22]\" +// ./c cclib bailout 17 \"[%226de8a1650bf696aaa515e38a858bd0f40eab8c02bcb75169b2cfe99b8a2ce1f0%22]\" #define MAXPACK 23 @@ -455,22 +455,22 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke matches++; regslot = i; matchtx = spenttx; - } //else fprintf(stderr,"%d+1 doesnt match %s vs %s\n",i,ccaddr,destaddr); - } //else fprintf(stderr,"%d+1 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); - } //else fprintf(stderr,"%d+1 unspent\n",i); + } else fprintf(stderr,"%d+1 doesnt match %s vs %s\n",i,ccaddr,destaddr); + } else fprintf(stderr,"%d+1 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); + } else fprintf(stderr,"%d+1 unspent\n",i); } if ( matches == 1 ) { if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); - //fprintf(stderr,"matches.%d numvouts.%d\n",matches,numvouts); + fprintf(stderr,"matches.%d numvouts.%d\n",matches,numvouts); if ( rogue_registeropretdecode(txid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) { if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) == 0 ) { txid = matchtx.GetHash(); - //fprintf(stderr,"scan forward playertxid.%s spenttxid.%s\n",playertxid.GetHex().c_str(),txid.GetHex().c_str()); + fprintf(stderr,"scan forward playertxid.%s spenttxid.%s\n",playertxid.GetHex().c_str(),txid.GetHex().c_str()); while ( CCgettxout(txid,0,1) < 0 ) { spenttxid = zeroid; @@ -497,7 +497,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke } } } - //fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); + fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); batontxid = txid; batonvout = 0; // not vini // how to detect timeout, bailedout, highlander @@ -791,6 +791,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param result.push_back(Pair("gametxid",gametxid.GetHex())); if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { + fprintf(stderr,"validgame\n"); if ( maxplayers == 1 ) mult /= 2; if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers) == 0 ) From 553e49207d30036b6cf888751b4e407b25d4f239 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 08:39:46 -1100 Subject: [PATCH 0490/1145] Set players --- src/cc/rogue_rpc.cpp | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b0161180e..847528e65 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -657,7 +657,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vin3+ -> buyin // vout0 -> keystrokes/completion baton CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t maxplayers,gameheight,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx; std::vector playerdata; std::string rawtx; bits256 t; + UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t maxplayers,gameheight,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx; bits256 t; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -692,18 +692,24 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); - mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, CPubKey() /*nullpk*/)); - std::vector vopretFinish, vopret2; uint8_t e, f; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; + std::vector vopretFinish, vopret2; uint8_t e, f; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; int32_t didtx = 0; CScript opretRegister = rogue_registeropret(gametxid, playertxid); - if (DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretFinish, vopret2) != 0) { // if token in the opret - rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, - EncodeTokenOpRet(tokenid, voutPubkeysEmpty /*=never spent*/, vopretFinish /*=non-fungible*/, opretRegister)); + if ( playertxid != zeroid ) + { + if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) + { + if ( DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretFinish, vopret2) != 0) + { // if token in the opret + didtx = 1; + rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, + EncodeTokenOpRet(tokenid, voutPubkeysEmpty /*=never spent*/, vopretFinish /*=non-fungible*/, opretRegister)); + } + } } - else { + if ( didtx == 0 ) rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, opretRegister); - } return(rogue_rawtxresult(result,rawtx,1)); } else return(cclib_error(result,"invalid gametxid")); From ca500eb217f684d0d59c5e23cd1b2c469478e354 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 08:43:09 -1100 Subject: [PATCH 0491/1145] +print --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 847528e65..c07508e47 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -872,8 +872,8 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(rogue_rawtxresult(result,rawtx,0)); } result.push_back(Pair("result","success")); - } - } + } else printf(stderr,"illegal game\n"); + } else printf(stderr,"n.%d\n",n); } return(result); } From fcbd4d53c051e1df2a319ede0298c9d04d5d02a7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 08:43:39 -1100 Subject: [PATCH 0492/1145] fprintf --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c07508e47..36853e95c 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -872,8 +872,8 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(rogue_rawtxresult(result,rawtx,0)); } result.push_back(Pair("result","success")); - } else printf(stderr,"illegal game\n"); - } else printf(stderr,"n.%d\n",n); + } else fprintf(stderr,"illegal game\n"); + } else fprintf(stderr,"n.%d\n",n); } return(result); } From c8f901bfbf8b77a210995df6ff0d9109c396cc32 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 08:46:43 -1100 Subject: [PATCH 0493/1145] Err --- src/cc/rogue_rpc.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 36853e95c..b8651a0f1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -657,7 +657,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vin3+ -> buyin // vout0 -> keystrokes/completion baton CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t maxplayers,gameheight,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx; bits256 t; + UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t err,maxplayers,gameheight,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx; bits256 t; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -669,7 +669,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( n > 0 ) { gametxid = juint256(jitem(params,0)); - if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid) == 0 ) + if ( (err= rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid)) == 0 ) { if ( n > 1 ) { @@ -770,7 +770,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,gameheight,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,playertxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; + UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,err,gameheight,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,playertxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -795,7 +795,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { gametxid = juint256(jitem(params,0)); result.push_back(Pair("gametxid",gametxid.GetHex())); - if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) + if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) { fprintf(stderr,"validgame\n"); if ( maxplayers == 1 ) @@ -872,7 +872,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(rogue_rawtxresult(result,rawtx,0)); } result.push_back(Pair("result","success")); - } else fprintf(stderr,"illegal game\n"); + } else fprintf(stderr,"illegal game err.%d\n",err); } else fprintf(stderr,"n.%d\n",n); } return(result); From 280bc8b88c11202e3613eaea8879f6ef6853afa9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 08:56:24 -1100 Subject: [PATCH 0494/1145] Look at replay --- src/cc/rogue/rogue.c | 2 +- src/cc/rogue_rpc.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index f6bc9b727..79b2c1956 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -220,7 +220,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu rs->seed = seed; rs->keystrokes = keystrokes; rs->numkeys = num; - rs->sleeptime = 0; + rs->sleeptime = 50000; if ( player != 0 ) { rs->P = *player; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b8651a0f1..446b3f224 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -129,7 +129,7 @@ // ./rogue gui -> creates keystroke files // cclib register 17 \"[%22a49f90d6b5a226132a8615c9b55b254629611565c69246ea58f7a02059b847bf%22,%22f3a4a61cfa0dd43733b06d1368c199594258e0f3db983dc1b9b10768a5671909%22]\" // cclib keystrokes 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22deadbeef%22]\" -// ./c cclib bailout 17 \"[%226de8a1650bf696aaa515e38a858bd0f40eab8c02bcb75169b2cfe99b8a2ce1f0%22]\" +// ./c cclib bailout 17 \"[%228fd5b29b77ef90d7b7747c779530a8b005f7c236ea0ddb1fe68a392ea3b6cdf1%22]\" #define MAXPACK 23 @@ -318,7 +318,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) { gameheight = komodo_blockheight(hashBlock); - if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,0) == 0 ) + if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) >= txfee && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,0) == 0 ) { if ( rogue_newgameopreturndecode(buyin,maxplayers,tx.vout[numvouts-1].scriptPubKey) == 'G' ) { From e084210351e9a3788f3eca5e3cf1ab8d86d024c9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 09:01:36 -1100 Subject: [PATCH 0495/1145] Test --- src/cc/rogue/io.c | 7 ++++--- src/cc/rogue/rogue.c | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 38252fafd..30795f2ad 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -164,9 +164,10 @@ readchar(struct rogue_state *rs) } fprintf(stderr,"replay finished but readchar called\n"); rs->replaydone = (uint32_t)time(NULL); - if ( (rand() & 1) == 0 ) - return(ESCAPE); - else return('y'); + //if ( (rand() & 1) == 0 ) + // return(ESCAPE); + //else + return('y'); } if ( rs == 0 || rs->guiflag != 0 ) { diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 79b2c1956..a0278f38a 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -220,7 +220,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu rs->seed = seed; rs->keystrokes = keystrokes; rs->numkeys = num; - rs->sleeptime = 50000; + rs->sleeptime = 0*50000; if ( player != 0 ) { rs->P = *player; From 80a610cdaa53487f5a0d7effab8a87ec817bf1f1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 09:07:44 -1100 Subject: [PATCH 0496/1145] -score --- src/cc/rogue/rip.c | 8 +++++--- src/cc/rogue/rogue.c | 6 +++--- src/cc/rogue/rogue.h | 2 +- src/cc/rogue_rpc.cpp | 7 +++---- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/cc/rogue/rip.c b/src/cc/rogue/rip.c index 56f2453a4..032cc1b6d 100644 --- a/src/cc/rogue/rip.c +++ b/src/cc/rogue/rip.c @@ -46,12 +46,14 @@ static char *rip[] = { /* VARARGS2 */ void -score(int amount, int flags, char monst) +score(struct rogue_state *rs,int amount, int flags, char monst) { SCORE *scp; int i; SCORE *sc2; SCORE *top_ten, *endp; + if ( rs->guiflag == 0 ) + return; # ifdef MASTER int prflags = 0; # endif @@ -274,7 +276,7 @@ death(struct rogue_state *rs,char monst) } move(LINES - 1, 0); refresh(); - score(purse, amulet ? 3 : 0, monst); + score(rs,purse, amulet ? 3 : 0, monst); rogue_bailout(); printf("[Press return to continue]"); fflush(stdout); @@ -390,7 +392,7 @@ total_winner(struct rogue_state *rs) } printw(" %5d Gold Pieces ", oldpurse); refresh(); - score(purse, 2, ' '); + score(rs,purse, 2, ' '); my_exit(0); } diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index a0278f38a..8db8cabca 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -384,7 +384,7 @@ int rogue(int argc, char **argv, char **envp) if (strcmp(argv[1], "-s") == 0) { noscore = TRUE; - score(0, -1, 0); + score(rs,0, -1, 0); exit(0); } else if (strcmp(argv[1], "-d") == 0) @@ -602,14 +602,14 @@ quit(int sig) move(LINES - 1, 0); if ( rs->sleeptime != 0 ) refresh(); - score(purse, 1, 0); + score(rs,purse, 1, 0); flushkeystrokes(rs); my_exit(0); } else { fprintf(stderr,"done!\n"); - score(purse, 1, 0); + score(rs,purse, 1, 0); } } else diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 6543976da..6e9a6600f 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -698,7 +698,7 @@ int save(int which); void save_file(struct rogue_state *rs,FILE *savef,int32_t guiflag); void save_game(struct rogue_state *rs); int save_throw(int which, THING *tp); -void score(int amount, int flags, char monst); +void score(struct rogue_state *rs,int amount, int flags, char monst); void search(struct rogue_state *rs); void set_know(THING *obj, struct obj_info *info); void set_oldch(THING *tp, coord *cp); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 446b3f224..fe898e363 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -464,13 +464,13 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); - fprintf(stderr,"matches.%d numvouts.%d\n",matches,numvouts); + //fprintf(stderr,"matches.%d numvouts.%d\n",matches,numvouts); if ( rogue_registeropretdecode(txid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) { if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) == 0 ) { txid = matchtx.GetHash(); - fprintf(stderr,"scan forward playertxid.%s spenttxid.%s\n",playertxid.GetHex().c_str(),txid.GetHex().c_str()); + //fprintf(stderr,"scan forward playertxid.%s spenttxid.%s\n",playertxid.GetHex().c_str(),txid.GetHex().c_str()); while ( CCgettxout(txid,0,1) < 0 ) { spenttxid = zeroid; @@ -497,7 +497,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke } } } - fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); + //fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); batontxid = txid; batonvout = 0; // not vini // how to detect timeout, bailedout, highlander @@ -797,7 +797,6 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param result.push_back(Pair("gametxid",gametxid.GetHex())); if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) { - fprintf(stderr,"validgame\n"); if ( maxplayers == 1 ) mult /= 2; if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers) == 0 ) From cf3a8e6e9a2e89e8540fa0c8453c01bb86184c0b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 09:10:40 -1100 Subject: [PATCH 0497/1145] Skip bailout for replay --- src/cc/rogue/command.c | 3 ++- src/cc/rogue/rogue.c | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index a6cf50724..b2ce396ab 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -270,7 +270,8 @@ over: if ( rs->guiflag != 0 && rs->needflush == 0 ) rs->needflush = (uint32_t)time(NULL); q_comm = FALSE; - rogue_bailout(); + if ( rs->guiflag != 0 ) + rogue_bailout(); return; when 'i': after = FALSE; inventory(rs,pack, 0); when 'I': after = FALSE; picky_inven(rs); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 8db8cabca..307baab5f 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -608,8 +608,8 @@ quit(int sig) } else { - fprintf(stderr,"done!\n"); score(rs,purse, 1, 0); + fprintf(stderr,"done!\n"); } } else From 505dc7520dd20e2bf78bf875053508294d38417f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 09:27:26 -1100 Subject: [PATCH 0498/1145] Change to myGetTransaction --- src/cc/CCtokens.cpp | 3 ++- src/cc/rogue_rpc.cpp | 9 +++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index df1733173..3ee2be457 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -247,7 +247,8 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "TokensValidate funcId=" << (char)(funcid?funcid:' ') << " evalcode=" << cp->evalcode << std::endl); - if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) + //if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) + if (myGetTransacton(tokenid, createTx, hashBlock) == 0) return eval->Invalid("cant find token create txid"); else if (IsCCInput(tx.vin[0].scriptSig) != 0) return eval->Invalid("illegal token vin0"); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index fe898e363..aa2920126 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -124,11 +124,12 @@ // cclib newgame 17 \"[3,10]\" // cclib pending 17 -// cclib gameinfo 17 \"[%22a49f90d6b5a226132a8615c9b55b254629611565c69246ea58f7a02059b847bf%22]\" -// cclib register 17 \"[%22a49f90d6b5a226132a8615c9b55b254629611565c69246ea58f7a02059b847bf%22]\" +// ./c cclib gameinfo 17 \"[%22aa81321d8889f881fe3d7c68c905b7447d9143832b0abbef6c2cab49dff8b0cc%22]\" +// cclib register 17 \"[%22aa81321d8889f881fe3d7c68c905b7447d9143832b0abbef6c2cab49dff8b0cc%22]\" // ./rogue gui -> creates keystroke files -// cclib register 17 \"[%22a49f90d6b5a226132a8615c9b55b254629611565c69246ea58f7a02059b847bf%22,%22f3a4a61cfa0dd43733b06d1368c199594258e0f3db983dc1b9b10768a5671909%22]\" -// cclib keystrokes 17 \"[%220a4ecb345ca3090f4acad63f889c3668e46e245cb00ca4b8b57c4677b1ee95b2%22,%22deadbeef%22]\" +// ./c cclib register 17 \"[%22aa81321d8889f881fe3d7c68c905b7447d9143832b0abbef6c2cab49dff8b0cc%22,%226c88eb35f1f9eadabb0fb00c5b25b44cc60e99013ec9ce6871acd8ed7541de93%22]\" +// cclib keystrokes 17 \"[%22./c cclib gameinfo 17 \"[%22aa81321d8889f881fe3d7c68c905b7447d9143832b0abbef6c2cab49dff8b0cc%22]\" +%22,%22deadbeef%22]\" // ./c cclib bailout 17 \"[%228fd5b29b77ef90d7b7747c779530a8b005f7c236ea0ddb1fe68a392ea3b6cdf1%22]\" From ee444194be91432f93e951186df40eae2797fed6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 09:28:36 -1100 Subject: [PATCH 0499/1145] -\ --- src/cc/rogue_rpc.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index aa2920126..f685fdc64 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -128,8 +128,6 @@ // cclib register 17 \"[%22aa81321d8889f881fe3d7c68c905b7447d9143832b0abbef6c2cab49dff8b0cc%22]\" // ./rogue gui -> creates keystroke files // ./c cclib register 17 \"[%22aa81321d8889f881fe3d7c68c905b7447d9143832b0abbef6c2cab49dff8b0cc%22,%226c88eb35f1f9eadabb0fb00c5b25b44cc60e99013ec9ce6871acd8ed7541de93%22]\" -// cclib keystrokes 17 \"[%22./c cclib gameinfo 17 \"[%22aa81321d8889f881fe3d7c68c905b7447d9143832b0abbef6c2cab49dff8b0cc%22]\" -%22,%22deadbeef%22]\" // ./c cclib bailout 17 \"[%228fd5b29b77ef90d7b7747c779530a8b005f7c236ea0ddb1fe68a392ea3b6cdf1%22]\" From abec8d30fb47fbee2f899652abb6e8bbb1d90467 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 09:29:58 -1100 Subject: [PATCH 0500/1145] Test --- src/cc/CCtokens.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index 3ee2be457..1318d8bc8 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -248,7 +248,7 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "TokensValidate funcId=" << (char)(funcid?funcid:' ') << " evalcode=" << cp->evalcode << std::endl); //if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) - if (myGetTransacton(tokenid, createTx, hashBlock) == 0) + if (myGetTransaction(tokenid, createTx, hashBlock) == 0) return eval->Invalid("cant find token create txid"); else if (IsCCInput(tx.vin[0].scriptSig) != 0) return eval->Invalid("illegal token vin0"); From b488b0b270e494bde65c99e926a9e3b63469e6ce Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 09:33:20 -1100 Subject: [PATCH 0501/1145] +print --- src/cc/CCtokens.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index 1318d8bc8..12f3f8d36 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -247,9 +247,12 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "TokensValidate funcId=" << (char)(funcid?funcid:' ') << " evalcode=" << cp->evalcode << std::endl); - //if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) - if (myGetTransaction(tokenid, createTx, hashBlock) == 0) + if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) + //if (myGetTransaction(tokenid, createTx, hashBlock) == 0) + { + fprintf(stderr,"tokenid.%s\n",tokenid.GetHex()); return eval->Invalid("cant find token create txid"); + } else if (IsCCInput(tx.vin[0].scriptSig) != 0) return eval->Invalid("illegal token vin0"); else if (numvouts < 1) From 012e7cdf83585e59a695b481ff9142d95daf1c8b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 09:37:43 -1100 Subject: [PATCH 0502/1145] 2 prints --- src/cc/CCtokens.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index 12f3f8d36..326a8c6b1 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -250,7 +250,9 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) //if (myGetTransaction(tokenid, createTx, hashBlock) == 0) { - fprintf(stderr,"tokenid.%s\n",tokenid.GetHex()); + fprintf(stderr,"tokenid.%s\n",tokenid.GetHex().c_str()); + fprintf(stderr,"tokenid.%s\n",tokenid.GetHex().c_str()); + fprintf(stderr,"tokenid.%s\n",tokenid.GetHex().c_str()); return eval->Invalid("cant find token create txid"); } else if (IsCCInput(tx.vin[0].scriptSig) != 0) From 9d00a3f5a8c084cb5148adffb9dcdb2b47e05ea3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 09:43:19 -1100 Subject: [PATCH 0503/1145] -print --- src/cc/CCtokens.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index 326a8c6b1..4e6906685 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -248,13 +248,7 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "TokensValidate funcId=" << (char)(funcid?funcid:' ') << " evalcode=" << cp->evalcode << std::endl); if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) - //if (myGetTransaction(tokenid, createTx, hashBlock) == 0) - { - fprintf(stderr,"tokenid.%s\n",tokenid.GetHex().c_str()); - fprintf(stderr,"tokenid.%s\n",tokenid.GetHex().c_str()); - fprintf(stderr,"tokenid.%s\n",tokenid.GetHex().c_str()); return eval->Invalid("cant find token create txid"); - } else if (IsCCInput(tx.vin[0].scriptSig) != 0) return eval->Invalid("illegal token vin0"); else if (numvouts < 1) From f5f11ea56d360d814ff0686346a9d7ec3d4e4cde Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 09:49:25 -1100 Subject: [PATCH 0504/1145] Set token --- src/cc/rogue_rpc.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f685fdc64..351304956 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -697,6 +697,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { + tokenid = playertxid; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) { if ( DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretFinish, vopret2) != 0) From 88eb8db62e926fd86aa909382275ea2b7583e03d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 09:51:18 -1100 Subject: [PATCH 0505/1145] Set tokenid in right place --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 351304956..7903d2929 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -697,12 +697,12 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { - tokenid = playertxid; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) { if ( DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretFinish, vopret2) != 0) { // if token in the opret didtx = 1; + tokenid = playertxid; rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenOpRet(tokenid, voutPubkeysEmpty /*=never spent*/, vopretFinish /*=non-fungible*/, opretRegister)); } From 365c053dc5e1569039e13896d586e748f1952865 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 10:02:52 -1100 Subject: [PATCH 0506/1145] Guard tokenid setting --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 7903d2929..43754edd4 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -702,7 +702,8 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretFinish, vopret2) != 0) { // if token in the opret didtx = 1; - tokenid = playertxid; + if ( tokenid == zeroid ) + tokenid = playertxid; rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenOpRet(tokenid, voutPubkeysEmpty /*=never spent*/, vopretFinish /*=non-fungible*/, opretRegister)); } From 68e95fde75febe68cd175686ff5901508cff1fd2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 10:05:55 -1100 Subject: [PATCH 0507/1145] Remove check for normal input --- src/cc/CCtokens.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index 4e6906685..c434b34fe 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -249,8 +249,8 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) return eval->Invalid("cant find token create txid"); - else if (IsCCInput(tx.vin[0].scriptSig) != 0) - return eval->Invalid("illegal token vin0"); + //else if (IsCCInput(tx.vin[0].scriptSig) != 0) + // return eval->Invalid("illegal token vin0"); else if (numvouts < 1) return eval->Invalid("no vouts"); else if (funcid != 'c') From 986fabaa3adbb9f3bc3cc1a0fff422aa1cb68c0a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 10:09:26 -1100 Subject: [PATCH 0508/1145] +print --- src/cc/CCtokens.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index c434b34fe..ce9d1f9b5 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -630,6 +630,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu if (inputs != outputs) { if (tx.GetHash() != reftokenid) LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "TokenExactAmounts() found unequal token cc inputs=" << inputs << " vs cc outputs=" << outputs << " for txid=" << tx.GetHash().GetHex() << " and this is not the create tx" << std::endl); + fprintf(stderr,"inputs %.8f vs outputs %.8f\n",(long long)inputs,(long long)outputs); return false; // do not call eval->Invalid() here! } else From 2c30681b73a03842e02ff8ca1a0511e17fe5d359 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 10:11:28 -1100 Subject: [PATCH 0509/1145] Flu --- src/cc/CCtokens.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index ce9d1f9b5..c6f493026 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -630,7 +630,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu if (inputs != outputs) { if (tx.GetHash() != reftokenid) LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "TokenExactAmounts() found unequal token cc inputs=" << inputs << " vs cc outputs=" << outputs << " for txid=" << tx.GetHash().GetHex() << " and this is not the create tx" << std::endl); - fprintf(stderr,"inputs %.8f vs outputs %.8f\n",(long long)inputs,(long long)outputs); + fprintf(stderr,"inputs %llu vs outputs %llu\n",(long long)inputs,(long long)outputs); return false; // do not call eval->Invalid() here! } else From b083d687d6f07a13f11256669528884d436a4cec Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 10:17:13 -1100 Subject: [PATCH 0510/1145] Test sending to self --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 43754edd4..3d17080b5 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -691,7 +691,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); - mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, CPubKey() /*nullpk*/)); + mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, mypk));//CPubKey() /*nullpk*/)); std::vector vopretFinish, vopret2; uint8_t e, f; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; int32_t didtx = 0; CScript opretRegister = rogue_registeropret(gametxid, playertxid); From 197ae4c0e9b43adc62682aa048965a7be7149159 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 10:19:54 -1100 Subject: [PATCH 0511/1145] voutpubkeysempty --- src/cc/rogue_rpc.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3d17080b5..1e52b8aa1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -697,6 +697,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { + voutPubkeysEmpty.push_back(mypk); if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) { if ( DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretFinish, vopret2) != 0) From 3795785a381299d69c218a018ae14d4effd71cd1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 10:37:55 -1100 Subject: [PATCH 0512/1145] -print --- src/cc/CCinclude.h | 2 +- src/cc/CCtokens.cpp | 2 +- src/cc/rogue_rpc.cpp | 7 ++++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index 70069cad8..57f42f064 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -52,7 +52,7 @@ one other technical note is that komodod has the insight-explorer extensions bui #include "../utlist.h" #include "../uthash.h" - +#define CC_BURNPUBKEY "02deaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddeaddead" #define CC_MAXVINS 1024 #define SMALLVAL 0.000000000000001 diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index c6f493026..fedc78151 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -630,7 +630,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu if (inputs != outputs) { if (tx.GetHash() != reftokenid) LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "TokenExactAmounts() found unequal token cc inputs=" << inputs << " vs cc outputs=" << outputs << " for txid=" << tx.GetHash().GetHex() << " and this is not the create tx" << std::endl); - fprintf(stderr,"inputs %llu vs outputs %llu\n",(long long)inputs,(long long)outputs); + //fprintf(stderr,"inputs %llu vs outputs %llu\n",(long long)inputs,(long long)outputs); return false; // do not call eval->Invalid() here! } else diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1e52b8aa1..f4a57dede 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -656,10 +656,11 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vin3+ -> buyin // vout0 -> keystrokes/completion baton CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t err,maxplayers,gameheight,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx; bits256 t; + UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t err,maxplayers,gameheight,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk,burnpk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx; bits256 t; if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); + burnpk = pubkey2pk(ParseHex(CC_BURNPUBKEY)); roguepk = GetUnspendable(cp,0); rogue_univalue(result,"register",-1,-1); playertxid = zeroid; @@ -691,13 +692,13 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); - mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, mypk));//CPubKey() /*nullpk*/)); + mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, burnpk)); std::vector vopretFinish, vopret2; uint8_t e, f; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; int32_t didtx = 0; CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { - voutPubkeysEmpty.push_back(mypk); + voutPubkeysEmpty.push_back(burnpk); if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) { if ( DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretFinish, vopret2) != 0) From 296cc4a243ec3b4d24ed5a0a0c200e76ff34a26f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 10:56:04 -1100 Subject: [PATCH 0513/1145] obj.push_back(Pair("baton",batontxid.ToString())); --- src/cc/rogue_rpc.cpp | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f4a57dede..3aa27fe42 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -201,14 +201,22 @@ uint8_t rogue_keystrokesopretdecode(uint256 &gametxid,uint256 &batontxid,CPubKey return(0); } -uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &playertxid,CScript scriptPubKey) +uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &playertxid,CScript scriptPubKey) { std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); + tokenid = zeroid; if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) { return(f); } + else if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) + { + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R') ) + { + return(f); + } + } return(0); } @@ -438,7 +446,7 @@ int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,uint25 int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **keystrokesp,int32_t &numkeys,int32_t ®slot,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr,int32_t &numplayers) { - int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 spenttxid,hashBlock,txid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; + int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 spenttxid,tokenid,hashBlock,txid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; numkeys = numplayers = 0; playertxid = zeroid; for (i=0; i playerdata; char destaddr[64]; + uint256 batontxid,spenttxid,gtxid,ptxid,tokenid,hashBlock,playertxid; CTransaction spenttx,batontx; int32_t numplayers,regslot,numkeys,batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; destaddr[0] = 0; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { @@ -541,12 +551,13 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet { if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 1 ) { - if ( rogue_registeropretdecode(gtxid,ptxid,batontx.vout[batontx.vout.size()-1].scriptPubKey) == 'R' && gtxid == gametxid && ptxid == playertxid ) + if ( rogue_registeropretdecode(gtxid,tokenid,ptxid,batontx.vout[batontx.vout.size()-1].scriptPubKey) == 'R' && gtxid == gametxid && ptxid == playertxid ) obj.push_back(Pair("status","registered")); else obj.push_back(Pair("status","alive")); } else obj.push_back(Pair("status","error")); } else obj.push_back(Pair("status","finished")); obj.push_back(Pair("baton",batontxid.ToString())); + obj.push_back(Pair("tokenid",tokenid.ToString())); obj.push_back(Pair("batonaddr",destaddr)); obj.push_back(Pair("ismine",strcmp(myrogueaddr,destaddr)==0)); obj.push_back(Pair("batonvout",(int64_t)batonvout)); From 2c02d35fb119d8cdb09ec6354166713d510f4b46 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 10:57:52 -1100 Subject: [PATCH 0514/1145] std::vector voutPubkeys; --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3aa27fe42..7015d52b1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -203,7 +203,7 @@ uint8_t rogue_keystrokesopretdecode(uint256 &gametxid,uint256 &batontxid,CPubKey uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &playertxid,CScript scriptPubKey) { - std::vector vopret; uint8_t e,f; + std::vector vopret,vopret2; uint8_t e,f; std::vector voutPubkeys; GetOpReturnData(scriptPubKey,vopret); tokenid = zeroid; if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) From 5ec161a477ed370f217e6ea5597398c1b6dfdbab Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 11:01:37 -1100 Subject: [PATCH 0515/1145] Test --- src/cc/rogue_rpc.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 7015d52b1..06fd2ed15 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -212,6 +212,7 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl } else if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) { + fprintf(stderr,"got valid token opret %s e.%d vs %d\n",tokenid.GetHex().c_str(),e,EVAL_TOKENS); if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R') ) { return(f); From d76a5c448a3b9465f77d8a460615be987d878b69 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 11:02:36 -1100 Subject: [PATCH 0516/1145] -) --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 06fd2ed15..e78132934 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -213,7 +213,7 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl else if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) { fprintf(stderr,"got valid token opret %s e.%d vs %d\n",tokenid.GetHex().c_str(),e,EVAL_TOKENS); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R') ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) { return(f); } From ce7900940563cfde7631971895ecb8b842b7f1ef Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 11:04:41 -1100 Subject: [PATCH 0517/1145] +priont --- src/cc/rogue_rpc.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e78132934..57fbf0db1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -217,6 +217,7 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl { return(f); } + fprintf(stderr,"e.%d vs %d, f %c, gametxid.%s player.%s\n",e,EVAL_ROGUE,f,gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); } return(0); } From a9a9a9723a1897b09e68606f07cdad87387c80d5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 11:14:42 -1100 Subject: [PATCH 0518/1145] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 57fbf0db1..f86897f04 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -473,7 +473,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); - //fprintf(stderr,"matches.%d numvouts.%d\n",matches,numvouts); + fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex(),c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) { if ( tokenid != zeroid ) From 5cad17c68b2dd2c98d14512cc72204316d3bfaff Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 11:15:25 -1100 Subject: [PATCH 0519/1145] . --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f86897f04..2cf292bf4 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -473,7 +473,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); - fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex(),c_str(),matches,numvouts); + fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) { if ( tokenid != zeroid ) From 5ae21d9b1f06db4abbd05f3ef6e629e03bc0e00e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 11:29:43 -1100 Subject: [PATCH 0520/1145] Test --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 2cf292bf4..3a3885250 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -711,6 +711,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { + fprintf(stderr,"playertxid.%s\n",playertxid.GetHex().c_str()); voutPubkeysEmpty.push_back(burnpk); if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) { @@ -727,7 +728,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( didtx == 0 ) rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, opretRegister); - return(rogue_rawtxresult(result,rawtx,1)); + return(rogue_rawtxresult(result,rawtx,0)); } else return(cclib_error(result,"invalid gametxid")); } else return(cclib_error(result,"no gametxid")); } else return(cclib_error(result,"couldnt reparse params")); From 6ccee6c03624def16dd9949b41e4b200d917d112 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 11:33:50 -1100 Subject: [PATCH 0521/1145] Test --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3a3885250..6016201f5 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -156,6 +156,7 @@ CScript rogue_newgameopret(int64_t buyin,int32_t maxplayers) CScript rogue_registeropret(uint256 gametxid,uint256 playertxid) { CScript opret; uint8_t evalcode = EVAL_ROGUE; + fprintf(stderr,"opret.(%s %s).R\n",gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'R' << gametxid << playertxid); return(opret); } @@ -692,6 +693,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } rogue_univalue(result,0,maxplayers,buyin); GetCCaddress1of2(cp,coinaddr,roguepk,mypk); + CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( rogue_iamregistered(maxplayers,gametxid,tx,coinaddr) > 0 ) return(cclib_error(result,"already registered")); if ( (inputsum= rogue_registrationbaton(mtx,gametxid,tx,maxplayers)) != ROGUE_REGISTRATIONSIZE ) @@ -708,7 +710,6 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, burnpk)); std::vector vopretFinish, vopret2; uint8_t e, f; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; int32_t didtx = 0; - CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { fprintf(stderr,"playertxid.%s\n",playertxid.GetHex().c_str()); From 79ce5721dd651d05ca709e21f46c93ecf881f50d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 11:42:26 -1100 Subject: [PATCH 0522/1145] Test --- src/cc/rogue_rpc.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 6016201f5..a9dccc911 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -156,7 +156,7 @@ CScript rogue_newgameopret(int64_t buyin,int32_t maxplayers) CScript rogue_registeropret(uint256 gametxid,uint256 playertxid) { CScript opret; uint8_t evalcode = EVAL_ROGUE; - fprintf(stderr,"opret.(%s %s).R\n",gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); + //fprintf(stderr,"opret.(%s %s).R\n",gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'R' << gametxid << playertxid); return(opret); } @@ -214,7 +214,8 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl else if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) { fprintf(stderr,"got valid token opret %s e.%d vs %d\n",tokenid.GetHex().c_str(),e,EVAL_TOKENS); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) + playertxid = tokenid; + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && (f == 'Q' || f == 'R') ) { return(f); } @@ -693,7 +694,6 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } rogue_univalue(result,0,maxplayers,buyin); GetCCaddress1of2(cp,coinaddr,roguepk,mypk); - CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( rogue_iamregistered(maxplayers,gametxid,tx,coinaddr) > 0 ) return(cclib_error(result,"already registered")); if ( (inputsum= rogue_registrationbaton(mtx,gametxid,tx,maxplayers)) != ROGUE_REGISTRATIONSIZE ) @@ -710,6 +710,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, burnpk)); std::vector vopretFinish, vopret2; uint8_t e, f; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; int32_t didtx = 0; + CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { fprintf(stderr,"playertxid.%s\n",playertxid.GetHex().c_str()); @@ -721,6 +722,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) didtx = 1; if ( tokenid == zeroid ) tokenid = playertxid; + vopretFinish.resize(0); rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenOpRet(tokenid, voutPubkeysEmpty /*=never spent*/, vopretFinish /*=non-fungible*/, opretRegister)); } From d4015ad408af3ae508f051ab9971de02bea74cbc Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 11:48:28 -1100 Subject: [PATCH 0523/1145] Qr --- src/cc/rogue_rpc.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index a9dccc911..d5fe86b1d 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -709,7 +709,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, burnpk)); - std::vector vopretFinish, vopret2; uint8_t e, f; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; int32_t didtx = 0; + std::vector vopretFinish, vopret2; uint8_t e, funcid; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; int32_t didtx = 0; CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { @@ -717,10 +717,10 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) voutPubkeysEmpty.push_back(burnpk); if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) { - if ( DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretFinish, vopret2) != 0) + if ( (funcid= DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretFinish, vopret2)) != 0) { // if token in the opret didtx = 1; - if ( tokenid == zeroid ) + if ( funcid == 'c' ) tokenid = playertxid; vopretFinish.resize(0); rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, From 6e131475ba8fc91d72a8177840374e52aad17c07 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 11:51:50 -1100 Subject: [PATCH 0524/1145] Test --- src/cc/rogue_rpc.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d5fe86b1d..06ec8ff59 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -214,12 +214,13 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl else if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) { fprintf(stderr,"got valid token opret %s e.%d vs %d\n",tokenid.GetHex().c_str(),e,EVAL_TOKENS); - playertxid = tokenid; - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && (f == 'Q' || f == 'R') ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) { return(f); } + playertxid = tokenid; fprintf(stderr,"e.%d vs %d, f %c, gametxid.%s player.%s\n",e,EVAL_ROGUE,f,gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); + return('R'); } return(0); } @@ -466,16 +467,16 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke matches++; regslot = i; matchtx = spenttx; - } else fprintf(stderr,"%d+1 doesnt match %s vs %s\n",i,ccaddr,destaddr); - } else fprintf(stderr,"%d+1 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); - } else fprintf(stderr,"%d+1 unspent\n",i); + } //else fprintf(stderr,"%d+1 doesnt match %s vs %s\n",i,ccaddr,destaddr); + } //else fprintf(stderr,"%d+1 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); + } //else fprintf(stderr,"%d+1 unspent\n",i); } if ( matches == 1 ) { if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); - fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); + //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) { if ( tokenid != zeroid ) From 55ef02f69cbee7864c608fd66fc28479fb74642f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 11:54:47 -1100 Subject: [PATCH 0525/1145] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 06ec8ff59..e348c7d6e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -477,7 +477,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke { numvouts = matchtx.vout.size(); //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); - if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) + if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { if ( tokenid != zeroid ) playertxid = tokenid; From bff1e7162b77318a3079642d0628db3abe717bd5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 12:00:42 -1100 Subject: [PATCH 0526/1145] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e348c7d6e..f4ba31ee9 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -556,7 +556,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet { if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 1 ) { - if ( rogue_registeropretdecode(gtxid,tokenid,ptxid,batontx.vout[batontx.vout.size()-1].scriptPubKey) == 'R' && gtxid == gametxid && ptxid == playertxid ) + if ( rogue_registeropretdecode(gtxid,tokenid,ptxid,batontx.vout[batontx.vout.size()-1].scriptPubKey) == 'R' && ptxid == playertxid )//&& gtxid == gametxid ) obj.push_back(Pair("status","registered")); else obj.push_back(Pair("status","alive")); } else obj.push_back(Pair("status","error")); From 937aaea32b280d6b40b06ae4649d446dc26458e7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 12:16:11 -1100 Subject: [PATCH 0527/1145] Add back nonfungible data --- src/cc/rogue_rpc.cpp | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f4ba31ee9..3e75fbbe5 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -124,11 +124,11 @@ // cclib newgame 17 \"[3,10]\" // cclib pending 17 -// ./c cclib gameinfo 17 \"[%22aa81321d8889f881fe3d7c68c905b7447d9143832b0abbef6c2cab49dff8b0cc%22]\" +// ./c cclib gameinfo 17 \"[%226d3243c6e5ab383898b28a87e01f6c00b5bdd9687020f17f5caacc8a61febd19%22]\" // cclib register 17 \"[%22aa81321d8889f881fe3d7c68c905b7447d9143832b0abbef6c2cab49dff8b0cc%22]\" // ./rogue gui -> creates keystroke files -// ./c cclib register 17 \"[%22aa81321d8889f881fe3d7c68c905b7447d9143832b0abbef6c2cab49dff8b0cc%22,%226c88eb35f1f9eadabb0fb00c5b25b44cc60e99013ec9ce6871acd8ed7541de93%22]\" -// ./c cclib bailout 17 \"[%228fd5b29b77ef90d7b7747c779530a8b005f7c236ea0ddb1fe68a392ea3b6cdf1%22]\" +// ./c cclib register 17 \"[%226d3243c6e5ab383898b28a87e01f6c00b5bdd9687020f17f5caacc8a61febd19%22,%222475182f9d5169d8a3249d17640e4eccd90f4ee43ab04791129b0fa3f177b14a%22]\" +// ./c cclib bailout 17 \"[%22aa81321d8889f881fe3d7c68c905b7447d9143832b0abbef6c2cab49dff8b0cc%22]\" #define MAXPACK 23 @@ -213,14 +213,14 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl } else if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) { - fprintf(stderr,"got valid token opret %s e.%d vs %d\n",tokenid.GetHex().c_str(),e,EVAL_TOKENS); + //fprintf(stderr,"got valid token opret %s e.%d vs %d\n",tokenid.GetHex().c_str(),e,EVAL_TOKENS); if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) { return(f); } playertxid = tokenid; fprintf(stderr,"e.%d vs %d, f %c, gametxid.%s player.%s\n",e,EVAL_ROGUE,f,gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); - return('R'); + return(0); } return(0); } @@ -423,11 +423,10 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub //script = (uint8_t *)vopret.data(); if ( (f= rogue_highlanderopretdecode(gametxid,regslot,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { - fprintf(stderr,"gametxid.%s\n",gametxid.GetHex().c_str()); //memcpy(&gametxid,script+2,sizeof(gametxid)); if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { - fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); + //fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); if ( playertx.vin[1].prevout.hash == gametxid && rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid) == 0 ) { // if registertxid has vin from pk, it can be used @@ -477,7 +476,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke { numvouts = matchtx.vout.size(); //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); - if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) + if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) { if ( tokenid != zeroid ) playertxid = tokenid; @@ -556,7 +555,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet { if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 1 ) { - if ( rogue_registeropretdecode(gtxid,tokenid,ptxid,batontx.vout[batontx.vout.size()-1].scriptPubKey) == 'R' && ptxid == playertxid )//&& gtxid == gametxid ) + if ( rogue_registeropretdecode(gtxid,tokenid,ptxid,batontx.vout[batontx.vout.size()-1].scriptPubKey) == 'R' && ptxid == playertxid && gtxid == gametxid ) obj.push_back(Pair("status","registered")); else obj.push_back(Pair("status","alive")); } else obj.push_back(Pair("status","error")); @@ -714,7 +713,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { - fprintf(stderr,"playertxid.%s\n",playertxid.GetHex().c_str()); + //fprintf(stderr,"playertxid.%s\n",playertxid.GetHex().c_str()); voutPubkeysEmpty.push_back(burnpk); if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) { @@ -723,7 +722,6 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) didtx = 1; if ( funcid == 'c' ) tokenid = playertxid; - vopretFinish.resize(0); rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenOpRet(tokenid, voutPubkeysEmpty /*=never spent*/, vopretFinish /*=non-fungible*/, opretRegister)); } From a515539d8499e477be187fc1174d6f2f49b16f60 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 12:18:04 -1100 Subject: [PATCH 0528/1145] Vopret2 --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3e75fbbe5..ead68eb73 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -214,7 +214,7 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl else if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) { //fprintf(stderr,"got valid token opret %s e.%d vs %d\n",tokenid.GetHex().c_str(),e,EVAL_TOKENS); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) + if ( vopret2.size() > 2 && E_UNMARSHAL(vopret2,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) { return(f); } From 7fbf26c93ed9d95f01f83be0e6b1a28bc6b7caab Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 12:29:27 -1100 Subject: [PATCH 0529/1145] Auto broadcast tx --- src/cc/rogue_rpc.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ead68eb73..be4435056 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -114,10 +114,8 @@ */ // todo: -// make register a token burn // convert playertxid to the original playertxid // verify keystrokes tx is in mempool and confirmed -// verify amulet possession in pack //////////////////////// start of CClib interface //./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey=03951a6f7967ad784453116bc55cd30c54f91ea8a5b1e9b04d6b29cfd6b395ba6c -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc > /dev/null & @@ -730,7 +728,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( didtx == 0 ) rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, opretRegister); - return(rogue_rawtxresult(result,rawtx,0)); + return(rogue_rawtxresult(result,rawtx,1)); } else return(cclib_error(result,"invalid gametxid")); } else return(cclib_error(result,"no gametxid")); } else return(cclib_error(result,"couldnt reparse params")); @@ -887,7 +885,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param GetOpReturnData(opret, vopretNonfungible); rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenCreateOpRet('c', Mypubkey(), std::string(seedstr), gametxid.GetHex(), vopretNonfungible)); } - return(rogue_rawtxresult(result,rawtx,0)); + return(rogue_rawtxresult(result,rawtx,1)); } result.push_back(Pair("result","success")); } else fprintf(stderr,"illegal game err.%d\n",err); From fdaca7e5e5d4929f2144447153e1a19591aa3032 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 19:28:32 -1100 Subject: [PATCH 0530/1145] Auto bailout --- src/cc/cclib.cpp | 4 ---- src/cc/rogue/command.c | 2 +- src/cc/rogue/extern.h | 1 - src/cc/rogue/rip.c | 2 +- src/cc/rogue/rogue.c | 30 ++++++++++++++++++------------ src/cc/rogue/rogue.h | 1 + src/cc/rogue_rpc.cpp | 10 +++++++--- 7 files changed, 28 insertions(+), 22 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index ea39bbc41..441b43ccf 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -75,10 +75,6 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para #ifdef BUILD_ROGUE int32_t rogue_replay(uint64_t seed,int32_t sleeptime); -bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) -{ - return(true); -} UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index b2ce396ab..e78e6b055 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -271,7 +271,7 @@ over: rs->needflush = (uint32_t)time(NULL); q_comm = FALSE; if ( rs->guiflag != 0 ) - rogue_bailout(); + rogue_bailout(rs); return; when 'i': after = FALSE; inventory(rs,pack, 0); when 'I': after = FALSE; picky_inven(rs); diff --git a/src/cc/rogue/extern.h b/src/cc/rogue/extern.h index 0791702d6..486d85ff1 100644 --- a/src/cc/rogue/extern.h +++ b/src/cc/rogue/extern.h @@ -184,7 +184,6 @@ void md_onsignal_default(void); int md_issymlink(char *sp); int32_t decode_hex(uint8_t *bytes,int32_t n,char *hex); -void rogue_bailout(void); #endif diff --git a/src/cc/rogue/rip.c b/src/cc/rogue/rip.c index 032cc1b6d..a5b3e7208 100644 --- a/src/cc/rogue/rip.c +++ b/src/cc/rogue/rip.c @@ -277,7 +277,7 @@ death(struct rogue_state *rs,char monst) move(LINES - 1, 0); refresh(); score(rs,purse, amulet ? 3 : 0, monst); - rogue_bailout(); + rogue_bailout(rs); printf("[Press return to continue]"); fflush(stdout); if ( fgets(prbuf,10,stdin) != 0 ) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 307baab5f..305ae2b64 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -185,14 +185,6 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) return(retval); } -void rogue_bailout() -{ - char cmd[512]; - sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib bailout 17 \\\"[%%22%s%%22]\\\" >> bailout.log",Gametxidstr); - if ( system(cmd) != 0 ) - fprintf(stderr,"error issuing (%s)\n",cmd); -} - void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) { char cmd[32768],hexstr[32768]; int32_t i; @@ -206,13 +198,27 @@ void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) int32_t flushkeystrokes(struct rogue_state *rs) { - rogue_progress(rs->seed,rs->buffered,rs->num); - memset(rs->buffered,0,sizeof(rs->buffered)); - rs->counter++; - rs->num = 0; + if ( rs->num > 0 ) + { + rogue_progress(rs->seed,rs->buffered,rs->num); + memset(rs->buffered,0,sizeof(rs->buffered)); + rs->counter++; + rs->num = 0; + } return(0); } +void rogue_bailout(struct rogue_state *rs) +{ + char cmd[512]; + flushkeystrokes(rs); + sleep(5); + fprintf(stderr,"bailing out\n"); + sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib bailout 17 \\\"[%%22%s%%22]\\\" >> bailout.log",Gametxidstr); + if ( system(cmd) != 0 ) + fprintf(stderr,"error issuing (%s)\n",cmd); +} + int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player) { struct rogue_state *rs; FILE *fp; int32_t i; diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 6e9a6600f..5eccb2e8c 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -359,6 +359,7 @@ int32_t flushkeystrokes(struct rogue_state *rs); int32_t rogue_restorepack(struct rogue_state *rs); void restore_player(struct rogue_state *rs); int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player); +void rogue_bailout(struct rogue_state *rs); /* * Help list diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index be4435056..9c7504e5f 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -126,7 +126,7 @@ // cclib register 17 \"[%22aa81321d8889f881fe3d7c68c905b7447d9143832b0abbef6c2cab49dff8b0cc%22]\" // ./rogue gui -> creates keystroke files // ./c cclib register 17 \"[%226d3243c6e5ab383898b28a87e01f6c00b5bdd9687020f17f5caacc8a61febd19%22,%222475182f9d5169d8a3249d17640e4eccd90f4ee43ab04791129b0fa3f177b14a%22]\" -// ./c cclib bailout 17 \"[%22aa81321d8889f881fe3d7c68c905b7447d9143832b0abbef6c2cab49dff8b0cc%22]\" +// ./c cclib bailout 17 \"[%226d3243c6e5ab383898b28a87e01f6c00b5bdd9687020f17f5caacc8a61febd19%22]\" #define MAXPACK 23 @@ -868,8 +868,6 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param mtx.vout.push_back(CTxOut(cashout,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG)); } } - //for (i=0; i_o._o_type,o->_o._o_packch,o->_o._o_packch); } mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-2*txfee),roguepk)); Myprivkey(mypriv); @@ -995,3 +993,9 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("numplayerdata",a.size())); return(result); } + +bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) +{ + return(true); +} + From c888efeef541011833a29cdf2b576f98f896ef62 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 10 Feb 2019 19:43:43 -1100 Subject: [PATCH 0531/1145] bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 441b43ccf..04ad7a66d 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -74,6 +74,7 @@ std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *para #ifdef BUILD_ROGUE int32_t rogue_replay(uint64_t seed,int32_t sleeptime); +bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); From d7f1ab8365df292153c133d826d825a3af18dfff Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 01:33:02 -1100 Subject: [PATCH 0532/1145] Remove flush from bailout --- src/cc/rogue/rogue.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 305ae2b64..f5003c78a 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -211,8 +211,8 @@ int32_t flushkeystrokes(struct rogue_state *rs) void rogue_bailout(struct rogue_state *rs) { char cmd[512]; - flushkeystrokes(rs); - sleep(5); + //flushkeystrokes(rs); + //sleep(5); fprintf(stderr,"bailing out\n"); sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib bailout 17 \\\"[%%22%s%%22]\\\" >> bailout.log",Gametxidstr); if ( system(cmd) != 0 ) From 7a05f1eef3d0482651e23e65505087f5a4d9bb3c Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 01:49:56 -1100 Subject: [PATCH 0533/1145] Disable auto bailout --- src/cc/rogue/rogue.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index f5003c78a..e82b514e0 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -213,6 +213,7 @@ void rogue_bailout(struct rogue_state *rs) char cmd[512]; //flushkeystrokes(rs); //sleep(5); + return; fprintf(stderr,"bailing out\n"); sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib bailout 17 \\\"[%%22%s%%22]\\\" >> bailout.log",Gametxidstr); if ( system(cmd) != 0 ) From e583658d144ae7b1fdcb9a64477f5760b169c860 Mon Sep 17 00:00:00 2001 From: dimxy Date: Mon, 11 Feb 2019 19:04:52 +0500 Subject: [PATCH 0534/1145] removed non-fungible data from 't' opret added fieldId for non-fungible data in 'c' opret changed to cc marker int tokencreate, added in rogue_finishgame (tokenlist supports old and new markers) --- src/cc/CCassets.h | 2 +- src/cc/CCassetsCore.cpp | 44 ++------- src/cc/CCassetstx.cpp | 24 ++--- src/cc/CCinclude.h | 17 ++-- src/cc/CCtokens.cpp | 214 +++++++++++++++++++++++----------------- src/cc/CCtokens.h | 7 -- src/cc/assets.cpp | 2 +- src/cc/rogue_rpc.cpp | 35 +++++-- 8 files changed, 180 insertions(+), 165 deletions(-) diff --git a/src/cc/CCassets.h b/src/cc/CCassets.h index c4623ccbb..82fbcb961 100644 --- a/src/cc/CCassets.h +++ b/src/cc/CCassets.h @@ -30,7 +30,7 @@ bool AssetsValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx // CCassetsCore CScript EncodeAssetOpRet(uint8_t assetFuncId, uint256 assetid2, int64_t price, std::vector origpubkey); -uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCode, uint256 &tokenid, uint256 &assetid2, int64_t &price, std::vector &origpubkey, std::vector &vopretNonfungible); +uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCode, uint256 &tokenid, uint256 &assetid2, int64_t &price, std::vector &origpubkey); bool SetAssetOrigpubkey(std::vector &origpubkey,int64_t &price,const CTransaction &tx); int64_t IsAssetvout(struct CCcontract_info *cp, int64_t &price, std::vector &origpubkey, const CTransaction& tx, int32_t v, uint256 refassetid); bool ValidateBidRemainder(int64_t remaining_price,int64_t remaining_nValue,int64_t orig_nValue,int64_t received_nValue,int64_t paidprice,int64_t totalprice); diff --git a/src/cc/CCassetsCore.cpp b/src/cc/CCassetsCore.cpp index fa8b1df71..62d57e71c 100644 --- a/src/cc/CCassetsCore.cpp +++ b/src/cc/CCassetsCore.cpp @@ -279,9 +279,8 @@ bool DecodeAssetCreateOpRet(const CScript &scriptPubKey, std::vector &o return(0); } */ -uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCode, uint256 &tokenid, uint256 &assetid2, int64_t &price, std::vector &origpubkey, std::vector &vopretNonfungible) +uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCode, uint256 &tokenid, uint256 &assetid2, int64_t &price, std::vector &origpubkey) { - std::vector vopret1, vopret2; std::vector vopretAssets; //, vopretAssetsStripped; uint8_t *script, funcId = 0, assetsFuncId = 0, dummyEvalCode, dummyAssetFuncId; uint256 dummyTokenid; @@ -294,30 +293,9 @@ uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCo assetsFuncId = 0; // First - decode token opret: - funcId = DecodeTokenOpRet(scriptPubKey, dummyEvalCode, tokenid, voutPubkeysDummy, vopret1, vopret2); + funcId = DecodeTokenOpRet(scriptPubKey, dummyEvalCode, tokenid, voutPubkeysDummy, vopretAssets); LOGSTREAM((char *)"ccassets", CCLOG_DEBUG2, stream << "DecodeAssetTokenOpRet() from DecodeTokenOpRet returned funcId=" << (int)funcId << std::endl); - if (!vopret2.empty()) { - // if there are both oprets then order is like this: - vopretNonfungible = vopret1; - vopretAssets = vopret2; - } - else { - // if only one opret - it is assets opret: - vopretNonfungible.clear(); - vopretAssets = vopret1; - } - - - /*GetOpReturnData(scriptPubKey, vopret); - script = (uint8_t *)vopret.data(); - if (script == 0) { - std::cerr << "DecodeAssetOpRet() script is empty" << std::endl; - return (uint8_t)0; - }*/ - //bool isEof = true; // NOTE: if parse error occures, parse might not be able to set error. It is safer to treat that it was eof if it is not set! - //bool result = E_UNMARSHAL(vopret, ss >> evalCodeInOpret; ss >> funcId; ss >> tokenid; ss >> assetFuncId; isEof = ss.eof()); - if (funcId == 0 || vopretAssets.size() < 2) { LOGSTREAM((char *)"ccassets", CCLOG_INFO, stream << "DecodeAssetTokenOpRet() incorrect opret or no asset's payload" << " funcId=" << (int)funcId << " vopretAssets.size()=" << vopretAssets.size() << std::endl); return (uint8_t)0; @@ -363,13 +341,12 @@ uint8_t DecodeAssetTokenOpRet(const CScript &scriptPubKey, uint8_t &assetsEvalCo } break; default: - LOGSTREAM((char *)"ccassets", CCLOG_INFO, stream << "DecodeAssetTokenOpRet() illegal assetFuncId=" << (int)funcId << std::endl); break; } } } - LOGSTREAM((char *)"ccassets", CCLOG_INFO, stream << "DecodeAssetTokenOpRet() no asset's payload or incorrect assets evalcode" << " funcId=" << (int)funcId << " vopretAssets.size()=" << vopretAssets.size() << " assetsEvalCode=" << assetsEvalCode << " assetsFuncId=" << assetsFuncId << std::endl); + LOGSTREAM((char *)"ccassets", CCLOG_INFO, stream << "DecodeAssetTokenOpRet() no asset's payload or incorrect assets funcId or evalcode" << " funcId=" << (int)funcId << " vopretAssets.size()=" << vopretAssets.size() << " assetsEvalCode=" << assetsEvalCode << " assetsFuncId=" << assetsFuncId << std::endl); return (uint8_t)0; } @@ -378,9 +355,8 @@ bool SetAssetOrigpubkey(std::vector &origpubkey,int64_t &price,const CT { uint256 assetid,assetid2; uint8_t evalCode; - std::vector vopretNonfungibleDummy; - if ( tx.vout.size() > 0 && DecodeAssetTokenOpRet(tx.vout[tx.vout.size()-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey, vopretNonfungibleDummy) != 0 ) + if ( tx.vout.size() > 0 && DecodeAssetTokenOpRet(tx.vout[tx.vout.size()-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey) != 0 ) return(true); else return(false); @@ -396,10 +372,9 @@ bool GetAssetorigaddrs(struct CCcontract_info *cp, char *origCCaddr, char *origN std::vector origpubkey; CScript script; uint8_t evalCode; - std::vector vopretNonfungibleDummy; n = vintx.vout.size(); - if( n == 0 || (vintxFuncId = DecodeAssetTokenOpRet(vintx.vout[n-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey, vopretNonfungibleDummy)) == 0 ) + if( n == 0 || (vintxFuncId = DecodeAssetTokenOpRet(vintx.vout[n-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey)) == 0 ) return(false); bool bGetCCaddr = false; @@ -444,9 +419,8 @@ int64_t AssetValidateCCvin(struct CCcontract_info *cp,Eval* eval,char *origCCadd int64_t tmpprice; std::vector tmporigpubkey; uint8_t evalCode; - std::vector vopretNonfungibleDummy; - funcid = DecodeAssetTokenOpRet(tx.vout[tx.vout.size() - 1].scriptPubKey, evalCode, assetid, assetid2, tmpprice, tmporigpubkey, vopretNonfungibleDummy); + funcid = DecodeAssetTokenOpRet(tx.vout[tx.vout.size() - 1].scriptPubKey, evalCode, assetid, assetid2, tmpprice, tmporigpubkey); } if( tx.vin.size() < 2 ) @@ -495,7 +469,6 @@ int64_t AssetValidateCCvin(struct CCcontract_info *cp,Eval* eval,char *origCCadd int64_t AssetValidateBuyvin(struct CCcontract_info *cp,Eval* eval,int64_t &tmpprice,std::vector &tmporigpubkey,char *CCaddr,char *origaddr,const CTransaction &tx,uint256 refassetid) { CTransaction vinTx; int64_t nValue; uint256 assetid,assetid2; uint8_t funcid, evalCode; - std::vector vopretNonfungibleDummy; CCaddr[0] = origaddr[0] = 0; @@ -504,7 +477,7 @@ int64_t AssetValidateBuyvin(struct CCcontract_info *cp,Eval* eval,int64_t &tmppr return(0); else if ( vinTx.vout[0].scriptPubKey.IsPayToCryptoCondition() == 0 ) return eval->Invalid("invalid normal vout0 for buyvin"); - else if ((funcid = DecodeAssetTokenOpRet(vinTx.vout[vinTx.vout.size() - 1].scriptPubKey, evalCode, assetid, assetid2, tmpprice, tmporigpubkey, vopretNonfungibleDummy)) == 'b' && + else if ((funcid = DecodeAssetTokenOpRet(vinTx.vout[vinTx.vout.size() - 1].scriptPubKey, evalCode, assetid, assetid2, tmpprice, tmporigpubkey)) == 'b' && vinTx.vout[1].scriptPubKey.IsPayToCryptoCondition() == 0 ) // marker is only in 'b'? return eval->Invalid("invalid normal vout1 for buyvin"); else @@ -539,12 +512,11 @@ bool ValidateAssetOpret(CTransaction tx, int32_t v, uint256 assetid, int64_t &pr uint256 assetidOpret, assetidOpret2; uint8_t funcid, evalCode; - std::vector vopretNonfungibleDummy; // this is just for log messages indentation fur debugging recursive calls: int32_t n = tx.vout.size(); - if ((funcid = DecodeAssetTokenOpRet(tx.vout[n - 1].scriptPubKey, evalCode, assetidOpret, assetidOpret2, price, origpubkey, vopretNonfungibleDummy)) == 0) + if ((funcid = DecodeAssetTokenOpRet(tx.vout[n - 1].scriptPubKey, evalCode, assetidOpret, assetidOpret2, price, origpubkey)) == 0) { std::cerr << "ValidateAssetOpret() DecodeAssetTokenOpRet returned funcId=0 for opret from txid=" << tx.GetHash().GetHex() << std::endl; return(false); diff --git a/src/cc/CCassetstx.cpp b/src/cc/CCassetstx.cpp index 79a8fb77a..7673724f1 100644 --- a/src/cc/CCassetstx.cpp +++ b/src/cc/CCassetstx.cpp @@ -76,18 +76,17 @@ UniValue AssetOrders(uint256 refassetid) uint256 txid, hashBlock, assetid, assetid2; int64_t price; std::vector origpubkey; - std::vector vopretNonfungible; CTransaction vintx; uint8_t funcid, evalCode; char numstr[32], funcidstr[16], origaddr[64], assetidstr[65]; txid = it->first.txhash; //std::cerr << "addOrders() txid=" << txid.GetHex() << std::endl; - if ( GetTransaction(txid,vintx,hashBlock,false) != 0 ) + if ( GetTransaction(txid, vintx, hashBlock, false) != 0 ) { // for logging: funcid = DecodeAssetOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey); //std::cerr << "addOrders() vintx.vout.size()=" << vintx.vout.size() << " funcid=" << (char)(funcid ? funcid : ' ') << " assetid=" << assetid.GetHex() << std::endl; - if (vintx.vout.size() > 0 && (funcid = DecodeAssetTokenOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey, vopretNonfungible)) != 0) + if (vintx.vout.size() > 0 && (funcid = DecodeAssetTokenOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey)) != 0) { if (refassetid != zero && assetid != refassetid) { @@ -402,7 +401,7 @@ std::string CreateSell(int64_t txfee,int64_t askamount,uint256 assetid,int64_t p voutTokenPubkeys.push_back(unspendableAssetsPubkey); return FinalizeCCTx(mask, cpTokens, mtx, mypk, txfee, - EncodeTokenOpRet(assetid, voutTokenPubkeys, vopretNonfungible, + EncodeTokenOpRet(assetid, voutTokenPubkeys, EncodeAssetOpRet('s', zeroid, pricetotal, Mypubkey()))); } else { @@ -506,11 +505,12 @@ std::string CancelBuyOffer(int64_t txfee,uint256 assetid,uint256 bidtxid) if (GetTransaction(bidtxid, vintx, hashBlock, false) != 0) { std::vector vopretNonfungible; + GetNonfungibleData(assetid, vopretNonfungible); bidamount = vintx.vout[0].nValue; mtx.vin.push_back(CTxIn(bidtxid, 0, CScript())); // coins in Assets - if((funcid=DecodeAssetTokenOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, dummyEvalCode, dummyAssetid, dummyAssetid2, dummyPrice, dummyOrigpubkey, vopretNonfungible))!=0) + if((funcid=DecodeAssetTokenOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, dummyEvalCode, dummyAssetid, dummyAssetid2, dummyPrice, dummyOrigpubkey))!=0) { if (funcid == 's') mtx.vin.push_back(CTxIn(bidtxid, 1, CScript())); // spend marker if funcid='b' else if (funcid=='S') mtx.vin.push_back(CTxIn(bidtxid, 3, CScript())); // spend marker if funcid='B' @@ -522,8 +522,8 @@ std::string CancelBuyOffer(int64_t txfee,uint256 assetid,uint256 bidtxid) std::vector voutTokenPubkeys; // should be empty, no token vouts return(FinalizeCCTx(mask, cpAssets, mtx, mypk, txfee, - EncodeTokenOpRet(assetid, voutTokenPubkeys, vopretNonfungible, - EncodeAssetOpRet('o', zeroid, 0, Mypubkey())))); + EncodeTokenOpRet(assetid, voutTokenPubkeys, + EncodeAssetOpRet('o', zeroid, 0, Mypubkey())))); } } return(""); @@ -555,10 +555,12 @@ std::string CancelSell(int64_t txfee,uint256 assetid,uint256 asktxid) if (GetTransaction(asktxid, vintx, hashBlock, false) != 0) { std::vector vopretNonfungible; + GetNonfungibleData(assetid, vopretNonfungible); + askamount = vintx.vout[0].nValue; mtx.vin.push_back(CTxIn(asktxid, 0, CScript())); - if ((funcid=DecodeAssetTokenOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, dummyEvalCode, dummyAssetid, dummyAssetid2, dummyPrice, dummyOrigpubkey, vopretNonfungible))!=0) + if ((funcid=DecodeAssetTokenOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, dummyEvalCode, dummyAssetid, dummyAssetid2, dummyPrice, dummyOrigpubkey))!=0) { if (funcid == 's') mtx.vin.push_back(CTxIn(asktxid, 1, CScript())); // marker if funcid='s' @@ -588,7 +590,7 @@ std::string CancelSell(int64_t txfee,uint256 assetid,uint256 asktxid) CCaddr2set(cpAssets, EVAL_TOKENS, unspendableAssetsPk, unspendableAssetsPrivkey, unspendableAssetsAddr); return(FinalizeCCTx(mask, cpAssets, mtx, mypk, txfee, - EncodeTokenOpRet(assetid, voutTokenPubkeys, vopretNonfungible, + EncodeTokenOpRet(assetid, voutTokenPubkeys, EncodeAssetOpRet('x', zeroid, 0, Mypubkey())))); } } @@ -675,7 +677,7 @@ std::string FillBuyOffer(int64_t txfee,uint256 assetid,uint256 bidtxid,int64_t f voutTokenPubkeys.push_back(pubkey2pk(origpubkey)); return(FinalizeCCTx(mask, cpTokens, mtx, mypk, txfee, - EncodeTokenOpRet(assetid, voutTokenPubkeys, vopretNonfungible, + EncodeTokenOpRet(assetid, voutTokenPubkeys, EncodeAssetOpRet('B', zeroid, remaining_required, origpubkey)))); } else return("dont have any assets to fill bid"); } @@ -800,7 +802,7 @@ std::string FillSell(int64_t txfee, uint256 assetid, uint256 assetid2, uint256 a cpAssets->additionalTokensEvalcode2 = additionalTokensEvalcode2; return(FinalizeCCTx(mask, cpAssets, mtx, mypk, txfee, - EncodeTokenOpRet(assetid, voutTokenPubkeys, vopretNonfungible, + EncodeTokenOpRet(assetid, voutTokenPubkeys, EncodeAssetOpRet(assetid2 != zeroid ? 'E' : 'S', assetid2, remaining_nValue, origpubkey)))); } else { CCerror = strprintf("filltx not enough utxos"); diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index 57f42f064..6018114a0 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -67,6 +67,12 @@ one other technical note is that komodod has the insight-explorer extensions bui #include "../komodo_cJSON.h" +// opret data block ids: + enum { + OPRETID_NONFUNGIBLEDATA = 0x11 + // TODO: OPRETID_ASSETSDATA = 0x12 +}; + struct CC_utxo { uint256 txid; @@ -173,11 +179,10 @@ bool DecodeHexTx(CTransaction& tx, const std::string& strHexTx); CScript EncodeTokenCreateOpRet(uint8_t funcid, std::vector origpubkey, std::string name, std::string description, std::vector vopretNonfungible); CScript EncodeTokenOpRet(uint8_t tokenFuncId, uint8_t evalCodeInOpret, uint256 tokenid, std::vector voutPubkeys, CScript payload); //old version CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, CScript payload); -CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, std::vector vpayloadNonfungible, CScript payload); uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey, std::vector &origpubkey, std::string &name, std::string &description); -uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey, std::vector &origpubkey, std::string &name, std::string &description, std::vector &vopretNonfungible); -uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCode, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopretExtra); -uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCode, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopret1, std::vector &vopret2); +uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey, std::vector &origpubkey, std::string &name, std::string &description, std::vector &vopretNonfungible); +uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopretExtra); +void GetNonfungibleData(uint256 tokenid, std::vector &vopretNonfungible); uint8_t DecodeOraclesData(const CScript &scriptPubKey,uint256 &oracletxid,uint256 &batontxid,CPubKey &pk,std::vector &data); int32_t oracle_format(uint256 *hashp,int64_t *valp,char *str,uint8_t fmt,uint8_t *data,int32_t offset,int32_t datalen); @@ -186,7 +191,7 @@ int32_t oracle_format(uint256 *hashp,int64_t *valp,char *str,uint8_t fmt,uint8_t // CCcustom CPubKey GetUnspendable(struct CCcontract_info *cp,uint8_t *unspendablepriv); -uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopret1, std::vector &vopret2); +//uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopret1, std::vector &vopret2); // CCutils bool priv2addr(char *coinaddr,uint8_t buf33[33],uint8_t priv32[32]); @@ -262,7 +267,7 @@ UniValue ValueFromAmount(const CAmount& amount); #define CCLOG_DEBUG2 2 #define CCLOG_DEBUG3 3 template -inline void CCLogPrintStream(char *category, int level, T print_to_stream) +inline void CCLogPrintStream(const char *category, int level, T print_to_stream) { std::ostringstream stream; print_to_stream(stream); diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index fedc78151..f5eda7d31 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -50,18 +50,15 @@ CScript EncodeTokenCreateOpRet(uint8_t funcid, std::vector origpubkey, funcid = 'c'; // override the param opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << origpubkey << name << description; \ - if(!vopretNonfungible.empty()) ss << vopretNonfungible ); + if (!vopretNonfungible.empty()) { \ + ss << (uint8_t)OPRETID_NONFUNGIBLEDATA; \ + ss << vopretNonfungible; \ + }); return(opret); } -// this is for other contracts which use tokens and build customized extra payloads to token's opret: -CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, CScript payload) -{ - std::vector vpayloadNonfungibleEmpty; - return EncodeTokenOpRet(tokenid, voutPubkeys, vpayloadNonfungibleEmpty, payload); -} -CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, std::vector vpayloadNonfungible, CScript payload) +CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, CScript payload) { CScript opret; uint8_t tokenFuncId = 't'; @@ -73,7 +70,7 @@ CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, std: if (voutPubkeys.size() >= 0 && voutPubkeys.size() <= 2) ccType = voutPubkeys.size(); else { - LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "EncodeTokenOpRet voutPubkeys.size()=" << voutPubkeys.size() << " not supported" << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "EncodeTokenOpRet voutPubkeys.size()=" << voutPubkeys.size() << " not supported" << std::endl); } std::vector vpayload; @@ -82,10 +79,11 @@ CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, std: opret << OP_RETURN << E_MARSHAL(ss << evalCodeInOpret << tokenFuncId << tokenid << ccType; \ if (ccType >= 1) ss << voutPubkeys[0]; \ if (ccType == 2) ss << voutPubkeys[1]; \ - if (vpayloadNonfungible.size() > 0) ss << vpayloadNonfungible; \ if (vpayload.size() > 0) ss << vpayload); - // "error 64: scriptpubkey": + // bad opret cases (retries to attach payload without re-serialization): + + // "error 64: scriptpubkey": // if (payload.size() > 0) // opret += payload; @@ -93,8 +91,7 @@ CScript EncodeTokenOpRet(uint256 tokenid, std::vector voutPubkeys, std: // CScript opretPayloadNoOpcode(vpayload); // return opret + opretPayloadNoOpcode; - // how to attach payload without re-serialization: - // sig_aborted: + // error sig_aborted: // opret.resize(opret.size() + vpayload.size()); // CScript::iterator it = opret.begin() + opret.size(); // for (int i = 0; i < vpayload.size(); i++, it++) @@ -117,16 +114,20 @@ uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey, std::vector uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey,std::vector &origpubkey,std::string &name,std::string &description, std::vector &vopretNonfungible) { - std::vector vopret; uint8_t dummyEvalcode, funcid, *script; + std::vector vopret; uint8_t dummyEvalcode, funcid, *script, fieldId = 0; GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); if ( script != 0 && vopret.size() > 2 && script[0] == EVAL_TOKENS && script[1] == 'c' ) { - if( E_UNMARSHAL(vopret, ss >> dummyEvalcode; ss >> funcid; ss >> origpubkey; ss >> name; ss >> description; \ + if (E_UNMARSHAL(vopret, ss >> dummyEvalcode; ss >> funcid; ss >> origpubkey; ss >> name; ss >> description; \ // we suppose in 'c' opret it might be only non-fungible payload and not any assets/heir/etc payloads - if(!ss.eof()) ss >> vopretNonfungible ) ) + if (!ss.eof()) { \ + ss >> fieldId; \ + if( fieldId == OPRETID_NONFUNGIBLEDATA) \ + ss >> vopretNonfungible; \ + })) return(funcid); } return (uint8_t)0; @@ -134,7 +135,7 @@ uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey,std::vector // overload for compatibility allows only usual fungible tokens: // warning: it makes vopret marshalling to CScript because this is what caller would expect -uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCode, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopretExtra) { +/*uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCode, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopretExtra) { std::vector vopret1, vopret2; uint8_t funcId = DecodeTokenOpRet(scriptPubKey, evalCode, tokenid, voutPubkeys, vopret1, vopret2); @@ -150,12 +151,12 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCode, uint256 GetOpReturnData(opretExtra, vopretExtra); return funcId; -} +} */ -uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopret1, std::vector &vopret2) +uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopretExtra) { - std::vector vopret, extra, dummyPubkey; - uint8_t funcId=0, *script, dummyEvalCode, dummyFuncId, ccType; + std::vector vopret, extra, dummyPubkey, vnonfungibleDummy; + uint8_t funcId=0, *script, dummyEvalCode, dummyFuncId, ccType, fieldId = 0; std::string dummyName; std::string dummyDescription; CPubKey voutPubkey1, voutPubkey2; @@ -178,7 +179,7 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, ui switch( funcId ) { case 'c': - return DecodeTokenCreateOpRet(scriptPubKey, dummyPubkey, dummyName, dummyDescription, vopret1); + return DecodeTokenCreateOpRet(scriptPubKey, dummyPubkey, dummyName, dummyDescription, vnonfungibleDummy); //break; case 't': //not used yet: case 'l': @@ -187,9 +188,7 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, ui if (ccType >= 1) ss >> voutPubkey1; \ if (ccType == 2) ss >> voutPubkey2; \ isEof = ss.eof(); \ - if (!isEof) ss >> vopret1; \ - isEof = ss.eof(); \ - if (!isEof) { ss >> vopret2; } \ + if (!isEof) ss >> vopretExtra; \ // if something else remains -> bad format isEof = ss.eof()) || !isEof) { @@ -230,7 +229,7 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & CTxDestination address; CTransaction vinTx, createTx; uint256 hashBlock, tokenid, tokenid2; int32_t i, starti, numvins, numvouts, preventCCvins, preventCCvouts; int64_t remaining_price, nValue, tokenoshis, outputs, inputs, tmpprice, totalunits, ignore; - std::vector vopret1, vopret2, tmporigpubkey, ignorepubkey; + std::vector vopretExtra, tmporigpubkey, ignorepubkey; uint8_t funcid, evalCodeInOpret; char destaddr[64], origaddr[64], CCaddr[64]; std::vector voutTokenPubkeys; @@ -242,7 +241,11 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & outputs = inputs = 0; preventCCvins = preventCCvouts = -1; - if ((funcid = DecodeTokenOpRet(tx.vout[numvouts - 1].scriptPubKey, evalCodeInOpret, tokenid, voutTokenPubkeys, vopret1, vopret2)) == 0) + // check boundaries: + if (numvouts < 1) + return eval->Invalid("no vouts"); + + if ((funcid = DecodeTokenOpRet(tx.vout[numvouts - 1].scriptPubKey, evalCodeInOpret, tokenid, voutTokenPubkeys, vopretExtra)) == 0) return eval->Invalid("TokenValidate: invalid opreturn payload"); LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "TokensValidate funcId=" << (char)(funcid?funcid:' ') << " evalcode=" << cp->evalcode << std::endl); @@ -250,13 +253,11 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) return eval->Invalid("cant find token create txid"); //else if (IsCCInput(tx.vin[0].scriptSig) != 0) - // return eval->Invalid("illegal token vin0"); - else if (numvouts < 1) - return eval->Invalid("no vouts"); + // return eval->Invalid("illegal token vin0"); // this validation was removed because some token tx might not have normal vins else if (funcid != 'c') { - if (tokenid == zeroid) - return eval->Invalid("illegal tokenid"); + if (tokenid == zeroid) + return eval->Invalid("illegal tokenid"); else if (!TokensExactAmounts(true, cp, inputs, outputs, eval, tx, tokenid)) { if (!eval->Valid()) return false; //TokenExactAmounts must call eval->Invalid()! @@ -265,14 +266,7 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & } } - // non-fungible tokens validation: - std::vector vopretNonfungible; - GetNonfungibleData(tokenid, vopretNonfungible); - if (vopretNonfungible.size() > 0 && vopretNonfungible != vopret1) // assuming tx vopretNonfungible in vopret1 - return eval->Invalid("incorrect or empty non-fungible data"); - - - switch (funcid) + switch (funcid) { case 'c': // create wont be called to be verified as it has no CC inputs //vin.0: normal input @@ -418,7 +412,7 @@ uint8_t ValidateTokenOpret(CTransaction tx, uint256 tokenid) { // goDeeper is true: the func also validates amounts of the passed transaction: // it should be either sum(cc vins) == sum(cc vouts) or the transaction is the 'tokenbase' ('c') tx // checkPubkeys is true: validates if the vout is token vout1 or token vout1of2. Should always be true! -int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *cp, Eval* eval, const CTransaction& tx, int32_t v, uint256 reftokenid) +int64_t IsTokensvout(bool goDeeper, bool checkPubkeys /*<--not used, always true*/, struct CCcontract_info *cp, Eval* eval, const CTransaction& tx, int32_t v, uint256 reftokenid) { // this is just for log messages indentation fur debugging recursive calls: @@ -458,36 +452,41 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c // token opret most important checks (tokenid == reftokenid, tokenid is non-zero, tx is 'tokenbase'): const uint8_t funcId = ValidateTokenOpret(tx, reftokenid); //std::cerr << indentStr << "IsTokensvout() ValidateTokenOpret returned=" << (char)(funcId?funcId:' ') << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl; - if (funcId != 0) { - LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() ValidateTokenOpret returned not-null funcId=" << (char)(funcId?funcId:' ') << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); + if (funcId != 0) { + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << indentStr << "IsTokensvout() ValidateTokenOpret returned not-null funcId=" << (char)(funcId ? funcId : ' ') << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); uint8_t dummyEvalCode; uint256 tokenIdOpret; std::vector voutPubkeys; - std::vector vopret1; - std::vector vopret2; - DecodeTokenOpRet(tx.vout.back().scriptPubKey, dummyEvalCode, tokenIdOpret, voutPubkeys, vopret1, vopret2); + std::vector vopretExtra, vopretNonfungible; - if (checkPubkeys && funcId != 'c') { // for 'c' there is no pubkeys + uint8_t evalCode = EVAL_TOKENS; // if both payloads are empty maybe it is a transfer to non-payload-one-eval-token vout like GatewaysClaim + uint8_t evalCode2 = 0; // will be checked if zero or not + + // test vouts for possible token use-cases: + std::vector> testVouts; + + DecodeTokenOpRet(tx.vout.back().scriptPubKey, dummyEvalCode, tokenIdOpret, voutPubkeys, vopretExtra); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopretExtra=" << HexStr(vopretExtra) << std::endl); + + GetNonfungibleData(reftokenid, vopretNonfungible); + + // NOTE: evalcode order in vouts is important: + // non-fungible-eval -> EVAL_TOKENS -> assets-eval + + if (vopretNonfungible.size() > 0) + evalCode = vopretNonfungible.begin()[0]; + if (vopretExtra.size() > 0) + evalCode2 = vopretExtra.begin()[0]; + + if (evalCode == EVAL_TOKENS && evalCode2 != 0) { + evalCode = evalCode2; + evalCode2 = 0; + } + + if( /*checkPubkeys &&*/ funcId != 'c' ) { // for 'c' there is no pubkeys // verify that the vout is token by constructing vouts with the pubkeys in the opret: - LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopret1=" << HexStr(vopret1) << std::endl); - LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopret2=" << HexStr(vopret2) << std::endl); - - uint8_t evalCode = EVAL_TOKENS; // if both payloads are empty maybe it is a transfer to non-payload-one-eval-token vout like GatewaysClaim - uint8_t evalCode2 = 0; // will be checked if zero or not - - // NOTE: evalcode order in vouts is important: - // non-fungible-eval -> EVAL_TOKENS -> assets-eval - if (vopret1.size() > 0) { - evalCode = vopret1.begin()[0]; - } - if (vopret2.size() > 0) { - evalCode2 = vopret2.begin()[0]; - } - - // checking vouts for possible token use-cases: - std::vector> testVouts; // maybe this is dual-eval 1 pubkey or 1of2 pubkey vout? if (voutPubkeys.size() >= 1 && voutPubkeys.size() <= 2) { // check dual/three-eval 1 pubkey vout with the first pubkey @@ -541,19 +540,36 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys, struct CCcontract_info *c testVouts.push_back(std::make_pair(MakeTokensCC1vout(evalCode2, evalCode, tx.vout[v].nValue, *it), std::string("three-eval cc1 self vin pk backward-eval"))); } - // try all test vouts: - for (auto t : testVouts) { - if (t.first == tx.vout[v]) { - LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() valid amount=" << tx.vout[v].nValue << " msg=" << t.second << " evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " txid=" << tx.GetHash().GetHex() << " tokenid=" << reftokenid.GetHex() << std::endl); - return tx.vout[v].nValue; - } - } - LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() no valid vouts evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); } else { - LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() returns without pubkey check value=" << tx.vout[v].nValue << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); - return tx.vout[v].nValue; + CPubKey origPubkey; + std::vector vorigPubkey; + std::string dummyName, dummyDescription; + std::vector vopret1; + + if (DecodeTokenCreateOpRet(tx.vout.back().scriptPubKey, vorigPubkey, dummyName, dummyDescription, vopret1) == 0) { + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << indentStr << "IsTokensvout() could not decode create opret" << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); + return 0; + } + + origPubkey = pubkey2pk(vorigPubkey); + + // for 'c' recognize the tokens only to token originator pubkey (but not to unspendable <-- closed sec violation) + // maybe this is like gatewayclaim to single-eval token? + testVouts.push_back(std::make_pair(MakeCC1vout(EVAL_TOKENS, tx.vout[v].nValue, origPubkey), std::string("single-eval cc1 orig-pk"))); + // maybe this is like FillSell for non-fungible token? + if (evalCode != 0) + testVouts.push_back(std::make_pair(MakeTokensCC1vout(evalCode, tx.vout[v].nValue, origPubkey), std::string("dual-eval-token cc1 orig-pk"))); } + + // try all test vouts: + for (auto t : testVouts) { + if (t.first == tx.vout[v]) { + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() valid amount=" << tx.vout[v].nValue << " msg=" << t.second << " evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " txid=" << tx.GetHash().GetHex() << " tokenid=" << reftokenid.GetHex() << std::endl); + return tx.vout[v].nValue; + } + } + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << indentStr << "IsTokensvout() no valid vouts evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); } //std::cerr << indentStr; fprintf(stderr,"IsTokensvout() CC vout v.%d of n=%d amount=%.8f txid=%s\n",v,n,(double)0/COIN, tx.GetHash().GetHex().c_str()); @@ -637,6 +653,7 @@ bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cp, int64_t &inpu return true; } + // get non-fungible data from 'tokenbase' tx (the data might be empty) void GetNonfungibleData(uint256 tokenid, std::vector &vopretNonfungible) { @@ -644,18 +661,18 @@ void GetNonfungibleData(uint256 tokenid, std::vector &vopretNonfungible uint256 hashBlock; if (!myGetTransaction(tokenid, tokenbasetx, hashBlock)) { - LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "SetNonfungibleEvalCode() cound not load token creation tx=" << tokenid.GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "GetNonfungibleData() cound not load token creation tx=" << tokenid.GetHex() << std::endl); return; } vopretNonfungible.clear(); // check if it is non-fungible tx and get its second evalcode from non-fungible payload if (tokenbasetx.vout.size() > 0) { - uint8_t dummyEvalCode; - uint256 tokenIdOpret; - std::vector voutPubkeys; + std::vector origpubkey; + std::string name, description; std::vector vopretExtra; - DecodeTokenOpRet(tokenbasetx.vout.back().scriptPubKey, dummyEvalCode, tokenIdOpret, voutPubkeys, vopretNonfungible, vopretExtra); + if (DecodeTokenCreateOpRet(tokenbasetx.vout.back().scriptPubKey, origpubkey, name, description, vopretExtra) == 'c') + vopretNonfungible = vopretExtra; } } @@ -786,7 +803,9 @@ std::string CreateToken(int64_t txfee, int64_t tokensupply, std::string name, st destEvalCode = nonfungibleData.begin()[0]; mtx.vout.push_back(MakeTokensCC1vout(destEvalCode, tokensupply, mypk)); - mtx.vout.push_back(CTxOut(txfee, CScript() << ParseHex(cp->CChexstr) << OP_CHECKSIG)); + //mtx.vout.push_back(CTxOut(txfee, CScript() << ParseHex(cp->CChexstr) << OP_CHECKSIG)); // old marker (non-burnable because spending could not be validated) + // NOTE: we should prevent spending fake-tokens from this marker in IsTokenvout(): + mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cp, NULL))); // new marker to cc addr, burnable and validated return(FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenCreateOpRet('c', Mypubkey(), name, description, nonfungibleData))); } @@ -838,7 +857,7 @@ std::string TokenTransfer(int64_t txfee, uint256 tokenid, std::vector d std::vector voutTokenPubkeys; voutTokenPubkeys.push_back(pubkey2pk(destpubkey)); // dest pubkey for validating vout - return(FinalizeCCTx(mask, cp, mtx, mypk, txfee, EncodeTokenOpRet(tokenid, voutTokenPubkeys, vopretNonfungible, CScript()))); + return(FinalizeCCTx(mask, cp, mtx, mypk, txfee, EncodeTokenOpRet(tokenid, voutTokenPubkeys, CScript()))); } else { LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "not enough CC token inputs for amount=" << total << std::endl); @@ -913,22 +932,31 @@ UniValue TokenList() { UniValue result(UniValue::VARR); std::vector > addressIndex; + std::vector > addressIndexCCMarker; + struct CCcontract_info *cp, C; uint256 txid, hashBlock; CTransaction vintx; std::vector origpubkey; - std::string name, description; char str[65]; + std::string name, description; cp = CCinit(&C, EVAL_TOKENS); - SetCCtxids(addressIndex, cp->normaladdr); - for (std::vector >::const_iterator it = addressIndex.begin(); it != addressIndex.end(); it++) - { - txid = it->first.txhash; - if (GetTransaction(txid, vintx, hashBlock, false) != 0) - { - if (vintx.vout.size() > 0 && DecodeTokenCreateOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, origpubkey, name, description) != 0) - { - result.push_back(uint256_str(str, txid)); - } - } + + auto addTokenId = [&](uint256 txid) { + if (GetTransaction(txid, vintx, hashBlock, false) != 0) { + if (vintx.vout.size() > 0 && DecodeTokenCreateOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, origpubkey, name, description) != 0) { + result.push_back(txid.GetHex()); + } + } + }; + + SetCCtxids(addressIndex, cp->normaladdr); // find by old normal addr marker + for (std::vector >::const_iterator it = addressIndex.begin(); it != addressIndex.end(); it++) { + addTokenId(it->first.txhash); } + + SetCCunspents(addressIndexCCMarker, cp->unspendableCCaddr); // find by burnable validated cc addr marker + for (std::vector >::const_iterator it = addressIndexCCMarker.begin(); it != addressIndexCCMarker.end(); it++) { + addTokenId(it->first.txhash); + } + return(result); } diff --git a/src/cc/CCtokens.h b/src/cc/CCtokens.h index 4637ba6c9..231b64ac9 100644 --- a/src/cc/CCtokens.h +++ b/src/cc/CCtokens.h @@ -35,11 +35,4 @@ int64_t GetTokenBalance(CPubKey pk, uint256 tokenid); UniValue TokenInfo(uint256 tokenid); UniValue TokenList(); -void GetNonfungibleData(uint256 tokenid, std::vector &vopretNonfungible); - -//this is in CCinclude.h int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, CPubKey pk, uint256 tokenid, int64_t total, int32_t maxinputs); - -//this is in CCinclude.h uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey,std::vector &origpubkey,std::string &name,std::string &description); - - #endif diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index 97b01302c..6f93da01b 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -157,7 +157,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti if (numvouts == 0) return eval->Invalid("AssetValidate: no vouts"); - if((funcid = DecodeAssetTokenOpRet(tx.vout[numvouts-1].scriptPubKey, evalCodeInOpret, assetid, assetid2, remaining_price, origpubkey, vopretNonfungibleDummy)) == 0 ) + if((funcid = DecodeAssetTokenOpRet(tx.vout[numvouts-1].scriptPubKey, evalCodeInOpret, assetid, assetid2, remaining_price, origpubkey)) == 0 ) return eval->Invalid("AssetValidate: invalid opreturn payload"); // non-fungible tokens support: diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9c7504e5f..5a1ef60b5 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -15,6 +15,7 @@ ******************************************************************************/ #include "cJSON.h" +#include "CCinclude.h" #define ROGUE_REGISTRATION 5 #define ROGUE_REGISTRATIONSIZE (100 * 10000) @@ -173,19 +174,27 @@ CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,int32_t regslot,CP return(opret); } -uint8_t rogue_highlanderopretdecode(uint256 &gametxid,int32_t ®slot,CPubKey &pk,std::vector &playerdata,CScript scriptPubKey) +uint8_t rogue_highlanderopretdecode(uint256 &gametxid, int32_t ®slot, CPubKey &pk, std::vector &playerdata, CScript scriptPubKey) { - std::vector vopret,vopret2; uint8_t e,f; uint256 tokenid; std::vector voutPubkeys; - GetOpReturnData(scriptPubKey,vopret); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) + std::string name, description; + std::vector vorigPubkey; + std::vector vopretNonfungible, vopret, vopretDummy; + uint8_t e, f; uint256 tokenid; std::vector voutPubkeys; + + GetOpReturnData(scriptPubKey, vopret); + // try no tokens case: + if (vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q')) return(f); - else if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) - { - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) + else if (f = DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy) != 0) { // it is tokens + if (f != 'c') + GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx + + if (vopretNonfungible.size() > 2 && E_UNMARSHAL(vopretNonfungible, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q')) { return(f); } } + return(0); } @@ -670,6 +679,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vout0 -> keystrokes/completion baton CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t err,maxplayers,gameheight,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk,burnpk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx; bits256 t; + if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -707,7 +717,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, burnpk)); - std::vector vopretFinish, vopret2; uint8_t e, funcid; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; int32_t didtx = 0; + std::vector vopretExtra; uint8_t e, funcid; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; int32_t didtx = 0; CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { @@ -715,13 +725,13 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) voutPubkeysEmpty.push_back(burnpk); if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) { - if ( (funcid= DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretFinish, vopret2)) != 0) + if ( (funcid= DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretExtra)) != 0) { // if token in the opret didtx = 1; if ( funcid == 'c' ) tokenid = playertxid; rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, - EncodeTokenOpRet(tokenid, voutPubkeysEmpty /*=never spent*/, vopretFinish /*=non-fungible*/, opretRegister)); + EncodeTokenOpRet(tokenid, voutPubkeysEmpty /*=never spent*/, opretRegister)); } } } @@ -788,6 +798,8 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,err,gameheight,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,playertxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; + struct CCcontract_info *cpTokens, tokensC; + if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); @@ -870,6 +882,9 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } } mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-2*txfee),roguepk)); + cpTokens = CCinit(&tokensC, EVAL_TOKENS); + mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cpTokens, NULL))); // marker to token cc addr, burnable and validated + Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); CScript opret = rogue_highlanderopret(funcid, gametxid, regslot,mypk, newdata); From e7516e10a98e0a18c2a5126bde306b4bca1158f6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 03:43:00 -1100 Subject: [PATCH 0535/1145] Flushkeystrokes every 4kb --- src/cc/rogue/rogue.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index e82b514e0..fffa6203d 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -187,7 +187,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) { - char cmd[32768],hexstr[32768]; int32_t i; + char cmd[16384],hexstr[16384]; int32_t i; for (i=0; ineedflush != 0 ) + if ( rs->needflush != 0 && rs->num > 4096 ) { if ( flushkeystrokes(rs) == 0 ) rs->needflush = 0; From 08be0457e6619121959b9d60cbcf54e3e3a9fdff Mon Sep 17 00:00:00 2001 From: dimxy Date: Mon, 11 Feb 2019 20:04:50 +0500 Subject: [PATCH 0536/1145] corr call to DecodeTokenOpRet --- src/cc/CCtokens.cpp | 36 +++++++++++++++++++++++++++++------- src/cc/rogue_rpc.cpp | 6 +++--- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index f5eda7d31..eb802b65d 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -125,7 +125,7 @@ uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey,std::vector // we suppose in 'c' opret it might be only non-fungible payload and not any assets/heir/etc payloads if (!ss.eof()) { \ ss >> fieldId; \ - if( fieldId == OPRETID_NONFUNGIBLEDATA) \ + if( fieldId == OPRETID_NONFUNGIBLEDATA ) \ ss >> vopretNonfungible; \ })) return(funcid); @@ -153,6 +153,9 @@ uint8_t DecodeTokenCreateOpRet(const CScript &scriptPubKey,std::vector return funcId; } */ +// decodes token opret: +// for 't' returns all data from opret, vopretExtra contains other contract's data (currently only assets'). +// for 'c' returns only funcid. NOTE: nonfungible data is not returned uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, uint256 &tokenid, std::vector &voutPubkeys, std::vector &vopretExtra) { std::vector vopret, extra, dummyPubkey, vnonfungibleDummy; @@ -163,6 +166,7 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, ui GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); tokenid = zeroid; + vopretExtra.clear(); if (script != NULL && vopret.size() > 2) { @@ -174,7 +178,7 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, ui return (uint8_t)0; funcId = script[1]; - LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << "DecodeTokenOpRet decoded funcId=" << (char)(funcId?funcId:' ')); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "DecodeTokenOpRet decoded funcId=" << (char)(funcId?funcId:' ')); switch( funcId ) { @@ -407,6 +411,20 @@ uint8_t ValidateTokenOpret(CTransaction tx, uint256 tokenid) { return (uint8_t)0; } +// remove token->unspendablePk (it is only for marker usage) +std::vector FilterOutTokensUnspendablePk(std::vector sourcePubkeys) { + struct CCcontract_info *cpTokens, tokensC; + cpTokens = CCinit(&tokensC, EVAL_TOKENS); + CPubKey tokensUnspendablePk = GetUnspendable(cpTokens, NULL); + std::vector destPubkeys; + + for (auto pk : sourcePubkeys) + if (pk != tokensUnspendablePk) + destPubkeys.push_back(pk); + + return destPubkeys; +} + // Checks if the vout is a really Tokens CC vout // also checks tokenid in opret or txid if this is 'c' tx // goDeeper is true: the func also validates amounts of the passed transaction: @@ -457,7 +475,7 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys /*<--not used, always true uint8_t dummyEvalCode; uint256 tokenIdOpret; - std::vector voutPubkeys; + std::vector voutPubkeys, voutPubkeysInOpret; std::vector vopretExtra, vopretNonfungible; uint8_t evalCode = EVAL_TOKENS; // if both payloads are empty maybe it is a transfer to non-payload-one-eval-token vout like GatewaysClaim @@ -466,11 +484,13 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys /*<--not used, always true // test vouts for possible token use-cases: std::vector> testVouts; - DecodeTokenOpRet(tx.vout.back().scriptPubKey, dummyEvalCode, tokenIdOpret, voutPubkeys, vopretExtra); + DecodeTokenOpRet(tx.vout.back().scriptPubKey, dummyEvalCode, tokenIdOpret, voutPubkeysInOpret, vopretExtra); LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "IsTokensvout() vopretExtra=" << HexStr(vopretExtra) << std::endl); GetNonfungibleData(reftokenid, vopretNonfungible); + voutPubkeys = FilterOutTokensUnspendablePk(voutPubkeysInOpret); + // NOTE: evalcode order in vouts is important: // non-fungible-eval -> EVAL_TOKENS -> assets-eval @@ -529,8 +549,10 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys /*<--not used, always true } // maybe it is single-eval or dual/three-eval token change? - std::vector vinPubkeys; - ExtractTokensVinPubkeys(tx, vinPubkeys); + std::vector vinPubkeys, vinPubkeysUnfiltered; + ExtractTokensVinPubkeys(tx, vinPubkeysUnfiltered); + vinPubkeys = FilterOutTokensUnspendablePk(vinPubkeysUnfiltered); + for(std::vector::iterator it = vinPubkeys.begin(); it != vinPubkeys.end(); it++) { testVouts.push_back(std::make_pair(MakeCC1vout(EVAL_TOKENS, tx.vout[v].nValue, *it), std::string("single-eval cc1 self vin pk"))); testVouts.push_back(std::make_pair(MakeTokensCC1vout(evalCode, evalCode2, tx.vout[v].nValue, *it), std::string("three-eval cc1 self vin pk"))); @@ -805,7 +827,7 @@ std::string CreateToken(int64_t txfee, int64_t tokensupply, std::string name, st mtx.vout.push_back(MakeTokensCC1vout(destEvalCode, tokensupply, mypk)); //mtx.vout.push_back(CTxOut(txfee, CScript() << ParseHex(cp->CChexstr) << OP_CHECKSIG)); // old marker (non-burnable because spending could not be validated) // NOTE: we should prevent spending fake-tokens from this marker in IsTokenvout(): - mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cp, NULL))); // new marker to cc addr, burnable and validated + mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cp, NULL))); // new marker to token cc addr, burnable and validated return(FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenCreateOpRet('c', Mypubkey(), name, description, nonfungibleData))); } diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5a1ef60b5..603e776b8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -218,7 +218,7 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl { return(f); } - else if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret,vopret2)) == 'c' || f == 't' ) + else if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret)) == 'c' || f == 't' ) { //fprintf(stderr,"got valid token opret %s e.%d vs %d\n",tokenid.GetHex().c_str(),e,EVAL_TOKENS); if ( vopret2.size() > 2 && E_UNMARSHAL(vopret2,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) @@ -731,7 +731,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( funcid == 'c' ) tokenid = playertxid; rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, - EncodeTokenOpRet(tokenid, voutPubkeysEmpty /*=never spent*/, opretRegister)); + EncodeTokenOpRet(tokenid, voutPubkeysEmpty /*=never spent*/, opretRegister)); } } } @@ -881,7 +881,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } } } - mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-2*txfee),roguepk)); + mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-3*txfee),roguepk)); cpTokens = CCinit(&tokensC, EVAL_TOKENS); mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cpTokens, NULL))); // marker to token cc addr, burnable and validated From 0edf474beb3ae206c0d6f03a2cb937768a023572 Mon Sep 17 00:00:00 2001 From: Mihailo Milenkovic Date: Mon, 11 Feb 2019 16:37:28 +0100 Subject: [PATCH 0537/1145] Multi coin support for GatewaysCC (#18) - Added support for other cions - New RPC for getting address for a pubkey on external chain and for dumping private key in external chain format --- src/base58.cpp | 78 ++++++++++++++++ src/base58.h | 31 +++++- src/cc/CCGateways.h | 4 +- src/cc/CCinclude.h | 2 + src/cc/CCutils.cpp | 22 +++++ src/cc/dapps/oraclefeed.c | 92 +++++++++--------- src/cc/gateways.cpp | 192 +++++++++++++++++++++++++------------- src/key_io.cpp | 13 +++ src/key_io.h | 1 + src/rpc/server.cpp | 2 + src/rpc/server.h | 2 + src/wallet/rpcwallet.cpp | 55 ++++++++++- 12 files changed, 372 insertions(+), 122 deletions(-) diff --git a/src/base58.cpp b/src/base58.cpp index 9d10b7e6a..33b43d745 100644 --- a/src/base58.cpp +++ b/src/base58.cpp @@ -336,6 +336,84 @@ bool CBitcoinAddress::IsScript() const return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS); } +bool CCustomBitcoinAddress::Set(const CKeyID& id) +{ + SetData(base58Prefixes[0], &id, 20); + return true; +} + +bool CCustomBitcoinAddress::Set(const CPubKey& key) +{ + CKeyID id = key.GetID(); + SetData(base58Prefixes[0], &id, 20); + return true; +} + +bool CCustomBitcoinAddress::Set(const CScriptID& id) +{ + SetData(base58Prefixes[1], &id, 20); + return true; +} + +bool CCustomBitcoinAddress::Set(const CTxDestination& dest) +{ + return boost::apply_visitor(CBitcoinAddressVisitor(this), dest); +} + +bool CCustomBitcoinAddress::IsValid() const +{ + bool fCorrectSize = vchData.size() == 20; + bool fKnownVersion = vchVersion == base58Prefixes[0] || + vchVersion == base58Prefixes[1]; + return fCorrectSize && fKnownVersion; +} + +bool CCustomBitcoinAddress::GetKeyID(CKeyID& keyID) const +{ + if (!IsValid() || vchVersion != base58Prefixes[0]) + return false; + uint160 id; + memcpy(&id, &vchData[0], 20); + keyID = CKeyID(id); + return true; +} + +CTxDestination CCustomBitcoinAddress::Get() const +{ + if (!IsValid()) + return CNoDestination(); + uint160 id; + memcpy(&id, &vchData[0], 20); + if (vchVersion == base58Prefixes[0]) + return CKeyID(id); + else if (vchVersion == base58Prefixes[1]) + return CScriptID(id); + else + return CNoDestination(); +} + +bool CCustomBitcoinAddress::GetIndexKey(uint160& hashBytes, int& type) const +{ + if (!IsValid()) { + return false; + } else if (vchVersion == base58Prefixes[0]) { + memcpy(&hashBytes, &vchData[0], 20); + type = 1; + return true; + } else if (vchVersion == base58Prefixes[1]) { + memcpy(&hashBytes, &vchData[0], 20); + type = 2; + return true; + } + + return false; +} + +bool CCustomBitcoinAddress::IsScript() const +{ + return IsValid() && vchVersion == base58Prefixes[1]; +} + void CBitcoinSecret::SetKey(const CKey& vchSecret) { assert(vchSecret.IsValid()); diff --git a/src/base58.h b/src/base58.h index 4decb4922..52b3ac5f3 100644 --- a/src/base58.h +++ b/src/base58.h @@ -130,9 +130,9 @@ public: */ class CBitcoinAddress : public CBase58Data { public: - bool Set(const CKeyID &id); - bool Set(const CPubKey &key); - bool Set(const CScriptID &id); + virtual bool Set(const CKeyID &id); + virtual bool Set(const CPubKey &key); + virtual bool Set(const CScriptID &id); bool Set(const CTxDestination &dest); bool IsValid() const; bool IsValid(const CChainParams ¶ms) const; @@ -151,6 +151,31 @@ public: bool IsScript() const; }; +class CCustomBitcoinAddress : public CBitcoinAddress { + std::vector base58Prefixes[2]; +public: + bool Set(const CKeyID &id); + bool Set(const CPubKey &key); + bool Set(const CScriptID &id); + bool Set(const CTxDestination &dest); + bool IsValid() const; + + CCustomBitcoinAddress() {} + CCustomBitcoinAddress(const CTxDestination &dest,uint8_t taddr,uint8_t pubkey_prefix,uint8_t script_prefix) + { + if (taddr!=0) base58Prefixes[0].push_back(taddr); + base58Prefixes[0].push_back(pubkey_prefix); + base58Prefixes[1].push_back(script_prefix); + Set(dest); + } + + CTxDestination Get() const; + bool GetKeyID(CKeyID &keyID) const; + bool GetKeyID_NoCheck(CKeyID& keyID) const; + bool GetIndexKey(uint160& hashBytes, int& type) const; + bool IsScript() const; +}; + /** * A base58-encoded secret key */ diff --git a/src/cc/CCGateways.h b/src/cc/CCGateways.h index 7ecae2228..1f594e38b 100644 --- a/src/cc/CCGateways.h +++ b/src/cc/CCGateways.h @@ -21,7 +21,7 @@ #include "../merkleblock.h" bool GatewaysValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx, uint32_t nIn); -std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t totalsupply,uint256 oracletxid,uint8_t M,uint8_t N,std::vector pubkeys); +std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t totalsupply,uint256 oracletxid,uint8_t M,uint8_t N,std::vector pubkeys,uint8_t p1,uint8_t p2,uint8_t p3,uint8_t p4); std::string GatewaysDeposit(uint64_t txfee,uint256 bindtxid,int32_t height,std::string refcoin,uint256 cointxid,int32_t claimvout,std::string deposithex,std::vectorproof,CPubKey destpub,int64_t amount); std::string GatewaysClaim(uint64_t txfee,uint256 bindtxid,std::string refcoin,uint256 deposittxid,CPubKey destpub,int64_t amount); std::string GatewaysWithdraw(uint64_t txfee,uint256 bindtxid,std::string refcoin,CPubKey withdrawpub,int64_t amount); @@ -34,6 +34,8 @@ UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin); // CCcustom UniValue GatewaysInfo(uint256 bindtxid); +UniValue GatewaysExternalAddress(uint256 bindtxid,CPubKey pubkey); +UniValue GatewaysDumpPrivKey(uint256 bindtxid,CKey privkey); UniValue GatewaysList(); #endif diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index 1cb141a16..11af54b66 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -151,6 +151,7 @@ int32_t iguana_rwbignum(int32_t rwflag,uint8_t *serialized,int32_t len,uint8_t * CScript GetScriptForMultisig(int nRequired, const std::vector& keys); int64_t CCaddress_balance(char *coinaddr); CPubKey CCtxidaddr(char *txidaddr,uint256 txid); +CPubKey CCCustomtxidaddr(char *txidaddr,uint256 txid,uint8_t taddr,uint8_t prefix,uint8_t prefix2); bool GetCCParams(Eval* eval, const CTransaction &tx, uint32_t nIn, CTransaction &txOut, std::vector> &preConditions, std::vector> ¶ms); @@ -227,6 +228,7 @@ bool GetCCaddress1of2(struct CCcontract_info *cp,char *destaddr,CPubKey pk,CPubK bool ConstrainVout(CTxOut vout,int32_t CCflag,char *cmpaddr,int64_t nValue); bool PreventCC(Eval* eval,const CTransaction &tx,int32_t preventCCvins,int32_t numvins,int32_t preventCCvouts,int32_t numvouts); bool Getscriptaddress(char *destaddr,const CScript &scriptPubKey); +bool GetCustomscriptaddress(char *destaddr,const CScript &scriptPubKey,uint8_t taddr,uint8_t prefix,uint8_t prefix2); std::vector Mypubkey(); bool Myprivkey(uint8_t myprivkey[]); int64_t CCduration(int32_t &numblocks,uint256 txid); diff --git a/src/cc/CCutils.cpp b/src/cc/CCutils.cpp index 6892f6fab..1ee191444 100644 --- a/src/cc/CCutils.cpp +++ b/src/cc/CCutils.cpp @@ -299,6 +299,18 @@ bool Getscriptaddress(char *destaddr,const CScript &scriptPubKey) return(false); } +bool GetCustomscriptaddress(char *destaddr,const CScript &scriptPubKey,uint8_t taddr,uint8_t prefix, uint8_t prefix2) +{ + CTxDestination address; txnouttype whichType; + if ( ExtractDestination(scriptPubKey,address) != 0 ) + { + strcpy(destaddr,(char *)CCustomBitcoinAddress(address,taddr,prefix,prefix2).ToString().c_str()); + return(true); + } + //fprintf(stderr,"ExtractDestination failed\n"); + return(false); +} + bool GetCCParams(Eval* eval, const CTransaction &tx, uint32_t nIn, CTransaction &txOut, std::vector> &preConditions, std::vector> ¶ms) { @@ -359,6 +371,16 @@ CPubKey CCtxidaddr(char *txidaddr,uint256 txid) return(pk); } +CPubKey CCCustomtxidaddr(char *txidaddr,uint256 txid,uint8_t taddr,uint8_t prefix,uint8_t prefix2) +{ + uint8_t buf33[33]; CPubKey pk; + buf33[0] = 0x02; + endiancpy(&buf33[1],(uint8_t *)&txid,32); + pk = buf2pk(buf33); + GetCustomscriptaddress(txidaddr,CScript() << ParseHex(HexStr(pk)) << OP_CHECKSIG,taddr,prefix,prefix2); + return(pk); +} + bool _GetCCaddress(char *destaddr,uint8_t evalcode,CPubKey pk) { CC *payoutCond; diff --git a/src/cc/dapps/oraclefeed.c b/src/cc/dapps/oraclefeed.c index d97df1cd9..cc6b45037 100644 --- a/src/cc/dapps/oraclefeed.c +++ b/src/cc/dapps/oraclefeed.c @@ -312,22 +312,20 @@ uint64_t get_btcusd() char *REFCOIN_CLI; -cJSON *get_komodocli(char *refcoin,char **retstrp,char *acname,char *method,char *arg0,char *arg1,char *arg2,char *arg3) +cJSON *get_cli(char *refcoin,char **retstrp,char *acname,char *method,char *arg0,char *arg1,char *arg2,char *arg3) { long fsize; cJSON *retjson = 0; char cmdstr[32768],*jsonstr,fname[256]; sprintf(fname,"/tmp/oraclefeed.%s",method); if ( acname[0] != 0 ) { - if ( refcoin[0] != 0 && strcmp(refcoin,"KMD") != 0 ) - printf("unexpected: refcoin.(%s) acname.(%s)\n",refcoin,acname); + if ( refcoin[0] == 0 ) + printf("must supply reference coin\n"); sprintf(cmdstr,"./komodo-cli -ac_name=%s %s %s %s %s %s > %s 2>/tmp/oraclefeed.error\n",acname,method,arg0,arg1,arg2,arg3,fname); } - else if ( strcmp(refcoin,"KMD") == 0 ) - sprintf(cmdstr,"./komodo-cli %s %s %s %s %s > %s 2>/tmp/oraclefeed.error\n",method,arg0,arg1,arg2,arg3,fname); else if ( REFCOIN_CLI != 0 && REFCOIN_CLI[0] != 0 ) { sprintf(cmdstr,"%s %s %s %s %s %s > %s 2>/tmp/oraclefeed.error\n",REFCOIN_CLI,method,arg0,arg1,arg2,arg3,fname); - printf("ref.(%s) REFCOIN_CLI (%s)\n",refcoin,cmdstr); + //printf("ref.(%s) REFCOIN_CLI (%s)\n",refcoin,cmdstr); } #ifdef TESTMODE fprintf(stderr,"cmd: %s\n",cmdstr); @@ -349,13 +347,13 @@ cJSON *get_komodocli(char *refcoin,char **retstrp,char *acname,char *method,char return(retjson); } -bits256 komodobroadcast(char *refcoin,char *acname,cJSON *hexjson) +bits256 broadcasttx(char *refcoin,char *acname,cJSON *hexjson) { char *hexstr,*retstr,str[65]; cJSON *retjson; bits256 txid; memset(txid.bytes,0,sizeof(txid)); if ( (hexstr= jstr(hexjson,"hex")) != 0 ) { - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"sendrawtransaction",hexstr,"","","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"sendrawtransaction",hexstr,"","","")) != 0 ) { if (strcmp("error",jstr(retjson,"result"))==0) printf("%s\n",jstr(retjson,"error")); free_json(retjson); @@ -379,9 +377,9 @@ bits256 sendtoaddress(char *refcoin,char *acname,char *destaddr,int64_t satoshis char numstr[32],*retstr,str[65]; cJSON *retjson; bits256 txid; memset(txid.bytes,0,sizeof(txid)); sprintf(numstr,"%.8f",(double)satoshis/SATOSHIDEN); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"sendtoaddress",destaddr,numstr,"","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"sendtoaddress",destaddr,numstr,"","")) != 0 ) { - fprintf(stderr,"unexpected sendrawtransaction json.(%s)\n",jprint(retjson,0)); + fprintf(stderr,"unexpected sendtoaddress json.(%s)\n",jprint(retjson,0)); free_json(retjson); } else if ( retstr != 0 ) @@ -400,10 +398,11 @@ bits256 sendtoaddress(char *refcoin,char *acname,char *destaddr,int64_t satoshis int32_t get_coinheight(char *refcoin,char *acname) { cJSON *retjson; char *retstr; int32_t height=0; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"getblockchaininfo","","","","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"getblockchaininfo","","","","")) != 0 ) { height = jint(retjson,"blocks"); free_json(retjson); + } else if ( retstr != 0 ) { @@ -418,7 +417,7 @@ bits256 get_coinblockhash(char *refcoin,char *acname,int32_t height) cJSON *retjson; char *retstr,heightstr[32]; bits256 hash; memset(hash.bytes,0,sizeof(hash)); sprintf(heightstr,"%d",height); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"getblockhash",heightstr,"","","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"getblockhash",heightstr,"","","")) != 0 ) { fprintf(stderr,"unexpected blockhash json.(%s)\n",jprint(retjson,0)); free_json(retjson); @@ -439,7 +438,7 @@ bits256 get_coinmerkleroot(char *refcoin,char *acname,bits256 blockhash) { cJSON *retjson; char *retstr,str[65]; bits256 merkleroot; memset(merkleroot.bytes,0,sizeof(merkleroot)); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"getblockheader",bits256_str(str,blockhash),"","","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"getblockheader",bits256_str(str,blockhash),"","","")) != 0 ) { merkleroot = jbits256(retjson,"merkleroot"); //fprintf(stderr,"got merkleroot.(%s)\n",bits256_str(str,merkleroot)); @@ -477,7 +476,7 @@ int32_t get_coinheader(char *refcoin,char *acname,bits256 *blockhashp,bits256 *m cJSON *get_gatewayspending(char *refcoin,char *acname,char *bindtxidstr) { cJSON *retjson; char *retstr; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewayspendingwithdraws",bindtxidstr,refcoin,"","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"gatewayspendingwithdraws",bindtxidstr,refcoin,"","")) != 0 ) { //printf("pending.(%s)\n",jprint(retjson,0)); return(retjson); @@ -493,7 +492,7 @@ cJSON *get_gatewayspending(char *refcoin,char *acname,char *bindtxidstr) cJSON *get_gatewaysprocessed(char *refcoin,char *acname,char *bindtxidstr) { cJSON *retjson; char *retstr; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewaysprocessed",bindtxidstr,refcoin,"","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"gatewaysprocessed",bindtxidstr,refcoin,"","")) != 0 ) { //printf("pending.(%s)\n",jprint(retjson,0)); return(retjson); @@ -509,7 +508,7 @@ cJSON *get_gatewaysprocessed(char *refcoin,char *acname,char *bindtxidstr) cJSON *get_rawmempool(char *refcoin,char *acname) { cJSON *retjson; char *retstr; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"getrawmempool","","","","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"getrawmempool","","","","")) != 0 ) { //printf("mempool.(%s)\n",jprint(retjson,0)); return(retjson); @@ -528,7 +527,7 @@ cJSON *get_addressutxos(char *refcoin,char *acname,char *coinaddr) if ( refcoin[0] != 0 && strcmp(refcoin,"KMD") != 0 ) printf("warning: assumes %s has addressindex enabled\n",refcoin); sprintf(jsonbuf,"{\\\"addresses\\\":[\\\"%s\\\"]}",coinaddr); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"getaddressutxos",jsonbuf,"","","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"getaddressutxos",jsonbuf,"","","")) != 0 ) { //printf("addressutxos.(%s)\n",jprint(retjson,0)); return(retjson); @@ -544,7 +543,7 @@ cJSON *get_addressutxos(char *refcoin,char *acname,char *coinaddr) cJSON *get_rawtransaction(char *refcoin,char *acname,bits256 txid) { cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"getrawtransaction",bits256_str(str,txid),"1","","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"getrawtransaction",bits256_str(str,txid),"1","","")) != 0 ) { return(retjson); } @@ -559,7 +558,7 @@ cJSON *get_rawtransaction(char *refcoin,char *acname,bits256 txid) int32_t validateaddress(char *refcoin,char *acname,char *depositaddr, char* compare) { cJSON *retjson; char *retstr; int32_t res=0; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"validateaddress",depositaddr,"","","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"validateaddress",depositaddr,"","","")) != 0 ) { if (is_cJSON_True(jobj(retjson,compare)) != 0 ) res=1; free_json(retjson); @@ -578,7 +577,7 @@ void importaddress(char *refcoin,char *acname,char *depositaddr, char *label,int cJSON *retjson; char *retstr; char rescanstr[10]; if (rescan) strcpy(rescanstr,"true"); else strcpy(rescanstr,"false"); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"importaddress",depositaddr,label,rescanstr,"")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"importaddress",depositaddr,label,rescanstr,"")) != 0 ) { printf("importaddress.(%s)\n",jprint(retjson,0)); free_json(retjson); @@ -595,7 +594,7 @@ void addmultisigaddress(char *refcoin,char *acname,int32_t M, char *pubkeys) cJSON *retjson; char *retstr,Mstr[10],addr[64]; sprintf(Mstr,"%d",M); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"addmultisigaddress",Mstr,pubkeys,"","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"addmultisigaddress",Mstr,pubkeys,"","")) != 0 ) { fprintf(stderr,"unexpected addmultisigaddress json.(%s)\n",jprint(retjson,0)); free(retstr); @@ -603,7 +602,7 @@ void addmultisigaddress(char *refcoin,char *acname,int32_t M, char *pubkeys) else if ( retstr != 0 ) { sprintf(addr,"\"%s\"",retstr); - get_komodocli(refcoin,&retstr,acname,"importaddress",addr,"\"\"","false",""); + get_cli(refcoin,&retstr,acname,"importaddress",addr,"\"\"","false",""); printf("addmultisigaddress.(%s)\n",retstr); free_json(retjson); } @@ -648,7 +647,7 @@ char *createrawtx(char *refcoin,char *acname,char *depositaddr,char *withdrawadd return(0); } sprintf(array,"\'[\"%s\"]\'",depositaddr); - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"listunspent","1","99999999",array,"")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"listunspent","1","99999999",array,"")) != 0 ) { //createrawtransaction [{"txid":"id","vout":n},...] {"address":amount,...} if ( (vins= getinputarray(&total,retjson,satoshis)) != 0 ) @@ -669,7 +668,7 @@ char *createrawtx(char *refcoin,char *acname,char *depositaddr,char *withdrawadd char *argB=malloc(sizeof(char) * (strlen(tmpB)+3)); sprintf(argA,"\'%s\'",tmpA); sprintf(argB,"\'%s\'",tmpB); - if ( (retjson2= get_komodocli(refcoin,&txstr,acname,"createrawtransaction",argA,argB,"","")) != 0 ) + if ( (retjson2= get_cli(refcoin,&txstr,acname,"createrawtransaction",argA,argB,"","")) != 0 ) { printf("createrawtx: unexpected JSON2.(%s)\n",jprint(retjson2,0)); free_json(retjson2); @@ -697,7 +696,7 @@ char *createrawtx(char *refcoin,char *acname,char *depositaddr,char *withdrawadd cJSON *addsignature(char *refcoin,char *acname,char *rawtx, int M) { char *retstr,*hexstr; cJSON *retjson; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"signrawtransaction",rawtx,"","","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"signrawtransaction",rawtx,"","","")) != 0 ) { if ( is_cJSON_True(jobj(retjson,"complete")) != 0 ) return(retjson); @@ -716,12 +715,12 @@ cJSON *addsignature(char *refcoin,char *acname,char *rawtx, int M) return(0); } -bits256 gatewayspartialsign(char *refcoin,char *acname,bits256 txid,char *coin,char *hex) +bits256 gatewayspartialsign(char *refcoin,char *acname,bits256 txid,char *hex) { char str[65],*retstr; cJSON *retjson; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewayspartialsign",bits256_str(str,txid),coin,hex,"")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"gatewayspartialsign",bits256_str(str,txid),refcoin,hex,"")) != 0 ) { - if (strcmp("error",jstr(retjson,"result"))!=0) txid=komodobroadcast(refcoin,acname,retjson); + if (strcmp("error",jstr(retjson,"result"))!=0) txid=broadcasttx(refcoin,acname,retjson); else printf("%s\n",jstr(retjson,"error")); free(retjson); return (txid); @@ -734,12 +733,12 @@ bits256 gatewayspartialsign(char *refcoin,char *acname,bits256 txid,char *coin,c return (zeroid); } -bits256 gatewayscompletesigning(char *refcoin,char *acname,bits256 withtxid,char *coin,char *hex) +bits256 gatewayscompletesigning(char *refcoin,char *acname,bits256 withtxid,char *hex) { char str[65],*retstr; cJSON *retjson; bits256 txid; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewayscompletesigning",bits256_str(str,withtxid),coin,hex,"")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"gatewayscompletesigning",bits256_str(str,withtxid),refcoin,hex,"")) != 0 ) { - if (strcmp("error",jstr(retjson,"result"))!=0) txid=komodobroadcast(refcoin,acname,retjson); + if (strcmp("error",jstr(retjson,"result"))!=0) txid=broadcasttx(refcoin,acname,retjson); else printf("%s\n",jstr(retjson,"error")); free(retjson); return (txid); @@ -752,12 +751,12 @@ bits256 gatewayscompletesigning(char *refcoin,char *acname,bits256 withtxid,char return (zeroid); } -bits256 gatewaysmarkdone(char *refcoin,char *acname,bits256 withtxid,char *coin) +bits256 gatewaysmarkdone(char *refcoin,char *acname,bits256 withtxid) { char str[65],str2[65],*retstr; cJSON *retjson; bits256 txid; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewaysmarkdone",bits256_str(str,withtxid),coin,"","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"gatewaysmarkdone",bits256_str(str,withtxid),refcoin,"","")) != 0 ) { - if (strcmp("error",jstr(retjson,"result"))!=0) txid=komodobroadcast(refcoin,acname,retjson); + if (strcmp("error",jstr(retjson,"result"))!=0) txid=broadcasttx(refcoin,acname,retjson); else printf("%s\n",jstr(retjson,"error")); free(retjson); return (txid); @@ -773,7 +772,7 @@ bits256 gatewaysmarkdone(char *refcoin,char *acname,bits256 withtxid,char *coin) int32_t get_gatewaysinfo(char *refcoin,char *acname,char *depositaddr,int32_t *Mp,int32_t *Np,char *bindtxidstr,char *coin,char *oraclestr, char **pubkeys) { char *oracle,*retstr,*name,*deposit,temp[128]; cJSON *retjson,*pubarray; int32_t n; - if ( (retjson= get_komodocli(refcoin,&retstr,acname,"gatewaysinfo",bindtxidstr,"","","")) != 0 ) + if ( (retjson= get_cli(refcoin,&retstr,acname,"gatewaysinfo",bindtxidstr,"","","")) != 0 ) { if ( (oracle= jstr(retjson,"oracletxid")) != 0 && strcmp(oracle,oraclestr) == 0 && (deposit= jstr(retjson,"deposit")) != 0 ) { @@ -888,7 +887,7 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t int32_t i,j,n,K,retval,processed = 0; bits256 txid,cointxid,withdrawtxid,lasttxid,completetxid; int64_t satoshis; memset(&zeroid,0,sizeof(zeroid)); - if ( (retjson= get_gatewayspending("KMD",acname,bindtxidstr)) != 0 ) + if ( (retjson= get_gatewayspending(refcoin,acname,bindtxidstr)) != 0 ) { if ( jint(retjson,"queueflag") != 0 && (coinstr= jstr(retjson,"coin")) != 0 && strcmp(coinstr,refcoin) == 0 ) { @@ -912,7 +911,7 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t { if ( (clijson=addsignature(refcoin,"",rawtx,M)) != 0 && is_cJSON_True(jobj(clijson,"complete")) != 0) { - txid=gatewayscompletesigning("KMD",acname,withdrawtxid,refcoin,jstr(clijson,"hex")); + txid=gatewayscompletesigning(refcoin,acname,withdrawtxid,jstr(clijson,"hex")); if (txid.txid!=zeroid.txid) fprintf(stderr,"#WITHDRAW (%s) complete signing tx sent - %s\n",bits256_str(str,withdrawtxid),bits256_str(str1,txid)); else fprintf(stderr,"error broadcasting tx on %s",acname); free_json(clijson); @@ -934,13 +933,13 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t { if ( is_cJSON_True(jobj(clijson,"complete")) != 0 ) { - txid=gatewayscompletesigning("KMD",acname,lasttxid,refcoin,jstr(clijson,"hex")); + txid=gatewayscompletesigning(refcoin,acname,lasttxid,jstr(clijson,"hex")); if (txid.txid!=zeroid.txid) fprintf(stderr,"### SIGNING withdraw %s %dof%d\n",bits256_str(str,withdrawtxid),K+1,N); else fprintf(stderr,"### SIGNING error broadcasting tx on %s\n",acname); } else if ( jint(clijson,"partialtx") != 0 ) { - txid=gatewayspartialsign("KMD",acname,lasttxid,refcoin,jstr(clijson,"hex")); + txid=gatewayspartialsign(refcoin,acname,lasttxid,jstr(clijson,"hex")); if (txid.txid!=zeroid.txid) fprintf(stderr,"### SIGNING withdraw %s %d/%dof%d\n",bits256_str(str,withdrawtxid),K+1,M,N); else fprintf(stderr,"### SIGNING error broadcasting tx on %s\n",acname); } @@ -956,7 +955,7 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t } free_json(retjson); } - if ( (retjson= get_gatewaysprocessed("KMD",acname,bindtxidstr)) != 0 ) + if ( (retjson= get_gatewaysprocessed(refcoin,acname,bindtxidstr)) != 0 ) { if ( jint(retjson,"queueflag") != 0 && (coinstr= jstr(retjson,"coin")) != 0 && strcmp(coinstr,refcoin) == 0 ) { @@ -973,12 +972,12 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t importaddress(refcoin,"",txidaddr,jstr(item,"withdrawtxid"),0); if (is_cJSON_True(jobj(item,"confirmed_or_notarized")) && txidaddr != 0 && markerexists(refcoin,"",txidaddr)==0) { - cointxid = komodobroadcast(refcoin,"",item); + cointxid = broadcasttx(refcoin,"",item); if ( bits256_nonz(cointxid) != 0 ) { withdrawaddr = jstr(item,"withdrawaddr"); fprintf(stderr,"### WITHDRAW %.8f %s sent to %s\n",amount,refcoin,withdrawaddr); - txid=gatewaysmarkdone("KMD",acname,completetxid,refcoin); + txid=gatewaysmarkdone(refcoin,acname,completetxid); if (txid.txid!=zeroid.txid) fprintf(stderr,"### MARKDONE withdraw %s\n",bits256_str(str,withdrawtxid)); } else fprintf(stderr,"### WITHDRAW error broadcasting tx on %s\n",refcoin); @@ -1073,7 +1072,7 @@ int32_t main(int32_t argc,char **argv) while ( 1 ) { retstr = 0; - if ( (refcoin[0] == 0 || prevheight < (get_coinheight(refcoin,"") - 10)) && (clijson= get_komodocli("KMD",&retstr,acname,"oraclesinfo",oraclestr,"","","")) != 0 ) + if ( (refcoin[0] == 0 || prevheight < (get_coinheight(refcoin,"") - 10)) && (clijson= get_cli(refcoin,&retstr,acname,"oraclesinfo",oraclestr,"","","")) != 0 ) { if ( refcoin[0] == 0 && jstr(clijson,"name") != 0 ) { @@ -1084,7 +1083,7 @@ int32_t main(int32_t argc,char **argv) exit(0); } pubkeys=0; - if ( get_gatewaysinfo("KMD",acname,depositaddr,&M,&N,bindtxidstr,refcoin,oraclestr,&pubkeys) < 0 ) + if ( get_gatewaysinfo(refcoin,acname,depositaddr,&M,&N,bindtxidstr,refcoin,oraclestr,&pubkeys) < 0 ) { printf("cant find bindtxid.(%s)\n",bindtxidstr); exit(0); @@ -1106,10 +1105,9 @@ int32_t main(int32_t argc,char **argv) { if ( (height= get_oracledata(refcoin,"",prevheight,hexstr,sizeof(hexstr),"Ihh")) != 0 ) { - if ( (clijson2= get_komodocli("KMD",&retstr2,acname,"oraclesdata",oraclestr,hexstr,"","")) != 0 ) + if ( (clijson2= get_cli(refcoin,&retstr2,acname,"oraclesdata",oraclestr,hexstr,"","")) != 0 ) { - //printf("data.(%s)\n",jprint(clijson2,0)); - txid = komodobroadcast("KMD",acname,clijson2); + txid = broadcasttx(refcoin,acname,clijson2); if ( bits256_nonz(txid) != 0 ) { prevheight = height; diff --git a/src/cc/gateways.cpp b/src/cc/gateways.cpp index 5c8de254d..af9038f81 100644 --- a/src/cc/gateways.cpp +++ b/src/cc/gateways.cpp @@ -14,6 +14,7 @@ ******************************************************************************/ #include "CCGateways.h" +#include "key_io.h" /* prevent duplicate bindtxid via mempool scan @@ -147,7 +148,7 @@ */ // start of consensus code -CScript EncodeGatewaysBindOpRet(uint8_t funcid,uint256 tokenid,std::string coin,int64_t totalsupply,uint256 oracletxid,uint8_t M,uint8_t N,std::vector gatewaypubkeys,uint8_t taddr,uint8_t prefix,uint8_t prefix2) +CScript EncodeGatewaysBindOpRet(uint8_t funcid,uint256 tokenid,std::string coin,int64_t totalsupply,uint256 oracletxid,uint8_t M,uint8_t N,std::vector gatewaypubkeys,uint8_t taddr,uint8_t prefix,uint8_t prefix2,uint8_t wiftype) { CScript opret; uint8_t evalcode = EVAL_GATEWAYS; struct CCcontract_info *cp,C; CPubKey gatewayspk; std::vector pubkeys; @@ -155,11 +156,11 @@ CScript EncodeGatewaysBindOpRet(uint8_t funcid,uint256 tokenid,std::string coin, cp = CCinit(&C,EVAL_GATEWAYS); gatewayspk = GetUnspendable(cp,0); pubkeys.push_back(gatewayspk); - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << coin << totalsupply << oracletxid << M << N << gatewaypubkeys << taddr << prefix << prefix2); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << coin << totalsupply << oracletxid << M << N << gatewaypubkeys << taddr << prefix << prefix2 << wiftype); return(EncodeTokenOpRet(tokenid,pubkeys,opret)); } -uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,uint256 &tokenid,std::string &coin,int64_t &totalsupply,uint256 &oracletxid,uint8_t &M,uint8_t &N,std::vector &gatewaypubkeys,uint8_t &taddr,uint8_t &prefix,uint8_t &prefix2) +uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,uint256 &tokenid,std::string &coin,int64_t &totalsupply,uint256 &oracletxid,uint8_t &M,uint8_t &N,std::vector &gatewaypubkeys,uint8_t &taddr,uint8_t &prefix,uint8_t &prefix2,uint8_t wiftype) { std::vector vopret; uint8_t *script,e,f,tokenevalcode; std::vector vOpretExtra; std::vector pubkeys; @@ -171,7 +172,7 @@ uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,ui else GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); depositaddr[0] = 0; - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> coin; ss >> totalsupply; ss >> oracletxid; ss >> M; ss >> N; ss >> gatewaypubkeys; ss >> taddr; ss >> prefix; ss >> prefix2;) != 0 ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> coin; ss >> totalsupply; ss >> oracletxid; ss >> M; ss >> N; ss >> gatewaypubkeys; ss >> taddr; ss >> prefix; ss >> prefix2; ss >> wiftype) != 0 ) { if ( prefix == 60 ) { @@ -181,6 +182,11 @@ uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,ui //LogPrint("gatewayscc","f.%c M.%d of N.%d size.%d -> %s\n",f,M,N,(int32_t)gatewaypubkeys.size(),depositaddr); } else Getscriptaddress(depositaddr,CScript() << ParseHex(HexStr(gatewaypubkeys[0])) << OP_CHECKSIG); } + else if (prefix == 28 && prefix2 == 50) + { + if ( N > 1 ) strcpy(depositaddr,CCustomBitcoinAddress(CScriptID(GetScriptForMultisig(M,gatewaypubkeys)),taddr,prefix,prefix2).ToString().c_str()); + else GetCustomscriptaddress(depositaddr,CScript() << ParseHex(HexStr(gatewaypubkeys[0])) << OP_CHECKSIG,taddr,prefix,prefix2); + } else { LogPrint("gatewayscc","need to generate non-KMD addresses prefix.%d\n",prefix); @@ -446,7 +452,7 @@ uint256 GatewaysReverseScan(uint256 &txid,int32_t height,uint256 reforacletxid,u } } //else LogPrint("gatewayscc","height.%d vs search ht.%d\n",(int32_t)merkleht,(int32_t)height); batontxid = bhash; - //LogPrint("gatewayscc","new hash %s\n",uint256_str(str,batontxid)); + // LogPrint("gatewayscc","new hash %s\n",uint256_str(str,batontxid)); } else break; } LogPrint("gatewayscc","end of loop\n"); @@ -479,7 +485,7 @@ uint256 BitcoinGetProofMerkleRoot(const std::vector &proofData, std::ve return merkleBlock.txn.ExtractMatches(txids); } -int64_t GatewaysVerify(char *refdepositaddr,uint256 oracletxid,int32_t claimvout,std::string refcoin,uint256 cointxid,const std::string deposithex,std::vectorproof,uint256 merkleroot,CPubKey destpub) +int64_t GatewaysVerify(char *refdepositaddr,uint256 oracletxid,int32_t claimvout,std::string refcoin,uint256 cointxid,const std::string deposithex,std::vectorproof,uint256 merkleroot,CPubKey destpub,uint8_t taddr,uint8_t prefix,uint8_t prefix2) { std::vector txids; uint256 proofroot,hashBlock,txid = zeroid; CTransaction tx; std::string name,description,format; char destaddr[64],destpubaddr[64],claimaddr[64],str[65],str2[65]; int32_t i,numvouts; int64_t nValue = 0; @@ -507,13 +513,13 @@ int64_t GatewaysVerify(char *refdepositaddr,uint256 oracletxid,int32_t claimvout } if ( DecodeHexTx(tx,deposithex) != 0 ) { - Getscriptaddress(claimaddr,tx.vout[claimvout].scriptPubKey); - Getscriptaddress(destpubaddr,CScript() << ParseHex(HexStr(destpub)) << OP_CHECKSIG); + GetCustomscriptaddress(claimaddr,tx.vout[claimvout].scriptPubKey,taddr,prefix,prefix2); + GetCustomscriptaddress(destpubaddr,CScript() << ParseHex(HexStr(destpub)) << OP_CHECKSIG,taddr,prefix,prefix2); if ( strcmp(claimaddr,destpubaddr) == 0 ) { for (i=0; i pubkeys; CTransaction tx; + uint8_t M,N,taddr,prefix,prefix2,wiftype; std::vector pubkeys; CTransaction tx; std::vector > addressIndex; _GetCCaddress(markeraddr,EVAL_GATEWAYS,gatewayspk); @@ -558,7 +564,7 @@ int32_t GatewaysBindExists(struct CCcontract_info *cp,CPubKey gatewayspk,uint256 { if ( myGetTransaction(it->first.txhash,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 0 && DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey)=='B' ) { - if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) == 'B' ) + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) == 'B' ) { if ( tokenid == reftokenid ) { @@ -574,7 +580,7 @@ int32_t GatewaysBindExists(struct CCcontract_info *cp,CPubKey gatewayspk,uint256 const uint256 &hash = txmempool.GetHash(); if ((numvouts=txmempool.vout.size()) > 0 && DecodeGatewaysOpRet(tx.vout[numvouts-1].scriptPubKey)=='B') - if (DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) == 'B' && + if (DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) == 'B' && tokenid == reftokenid) return(1); } @@ -584,7 +590,7 @@ int32_t GatewaysBindExists(struct CCcontract_info *cp,CPubKey gatewayspk,uint256 bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction &tx, uint32_t nIn) { - int32_t numvins,numvouts,preventCCvins,preventCCvouts,i,numblocks,height,claimvout; bool retval; uint8_t funcid,hash[32],K,M,N,taddr,prefix,prefix2; + int32_t numvins,numvouts,preventCCvins,preventCCvouts,i,numblocks,height,claimvout; bool retval; uint8_t funcid,hash[32],K,M,N,taddr,prefix,prefix2,wiftype; char str[65],destaddr[64],depositaddr[65],validationError[512]; std::vector txids; std::vector pubkeys,publishers,tmppublishers; std::vector proof; int64_t fullsupply,totalsupply,amount,tmpamount; uint256 hashblock,txid,bindtxid,deposittxid,withdrawtxid,completetxid,tokenid,tmptokenid,oracletxid,bindtokenid,cointxid,tmptxid,merkleroot,mhash; CTransaction bindtx,tmptx; @@ -615,7 +621,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & //vin.1: CC input of tokens //vout.0: CC vout of gateways tokens to gateways tokens CC address //vout.1: CC vout txfee marker - //vout.n-1: opreturn - 'B' tokenid coin totalsupply oracletxid M N pubkeys taddr prefix prefix2 + //vout.n-1: opreturn - 'B' tokenid coin totalsupply oracletxid M N pubkeys taddr prefix prefix2 wiftype return eval->Invalid("unexpected GatewaysValidate for gatewaysbind!"); break; case 'D': @@ -644,7 +650,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("vout.0 is CC for gatewaysClaim!"); else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) return eval->Invalid("invalid gatewaysbind txid!"); - else if ((numvouts=tmptx.vout.size()) < 1 || DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B') + else if ((numvouts=tmptx.vout.size()) < 1 || DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B') return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); else if (tmprefcoin!=refcoin) return eval->Invalid("refcoin different than in bind tx"); @@ -718,7 +724,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & sprintf(validationError,"couldnt find merkleroot for ht.%d %s oracle.%s m.%d vs n.%d\n",height,tmprefcoin.c_str(),uint256_str(str,oracletxid),m,N); return eval->Invalid(validationError); } - else if (GatewaysVerify(depositaddr,oracletxid,claimvout,tmprefcoin,cointxid,hex,proof,merkleroot,pubkey)!=amount) + else if (GatewaysVerify(depositaddr,oracletxid,claimvout,tmprefcoin,cointxid,hex,proof,merkleroot,pubkey,taddr,prefix,prefix2)!=amount) return eval->Invalid("external deposit not verified\n"); } break; @@ -764,7 +770,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("gatewayswithdraw tx is not yet confirmed(notarised)!"); else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) return eval->Invalid("invalid gatewaysbind txid!"); - else if ((numvouts=tmptx.vout.size()) < 1 || DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B') + else if ((numvouts=tmptx.vout.size()) < 1 || DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B') return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); else if (tmprefcoin!=refcoin) return eval->Invalid("refcoin different than in bind tx"); @@ -808,7 +814,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("gatewayswithdraw tx is not yet confirmed(notarised)!"); else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) return eval->Invalid("invalid gatewaysbind txid!"); - else if ((numvouts=tmptx.vout.size()) < 1 || DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B') + else if ((numvouts=tmptx.vout.size()) < 1 || DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B') return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); else if (tmprefcoin!=refcoin) return eval->Invalid("refcoin different than in bind tx"); @@ -846,7 +852,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("gatewayswithdraw tx is not yet confirmed(notarised)!"); else if (myGetTransaction(bindtxid,tmptx,hashblock) == 0) return eval->Invalid("invalid gatewaysbind txid!"); - else if ((numvouts=tmptx.vout.size()) < 1 || DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B') + else if ((numvouts=tmptx.vout.size()) < 1 || DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,tmprefcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B') return eval->Invalid("invalid gatewaysbind OP_RETURN data!"); else if (tmprefcoin!=refcoin) return eval->Invalid("refcoin different than in bind tx"); @@ -874,13 +880,13 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & int64_t AddGatewaysInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubKey pk,uint256 bindtxid,int64_t total,int32_t maxinputs) { char coinaddr[64],depositaddr[64]; int64_t threshold,nValue,price,totalinputs = 0,totalsupply,amount; - CTransaction vintx,bindtx; int32_t vout,numvouts,n = 0; uint8_t M,N,evalcode,funcid,taddr,prefix,prefix2; std::vector pubkeys; + CTransaction vintx,bindtx; int32_t vout,numvouts,n = 0; uint8_t M,N,evalcode,funcid,taddr,prefix,prefix2,wiftype; std::vector pubkeys; std::vector > unspentOutputs; std::string refcoin,tmprefcoin; CPubKey withdrawpub,destpub; uint256 tokenid,txid,oracletxid,tmpbindtxid,tmptokenid,deposittxid,hashBlock; if ( GetTransaction(bindtxid,bindtx,hashBlock,false) != 0 ) { - if ((numvouts=bindtx.vout.size())!=0 && DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,refcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) == 'B') + if ((numvouts=bindtx.vout.size())!=0 && DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,refcoin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) == 'B') { GetTokensCCaddress(cp,coinaddr,pk); SetCCunspents(unspentOutputs,coinaddr); @@ -933,10 +939,10 @@ int64_t AddGatewaysInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CP return(0); } -std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t totalsupply,uint256 oracletxid,uint8_t M,uint8_t N,std::vector pubkeys) +std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t totalsupply,uint256 oracletxid,uint8_t M,uint8_t N,std::vector pubkeys,uint8_t p1,uint8_t p2,uint8_t p3,uint8_t p4) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CTransaction oracletx; uint8_t taddr,prefix,prefix2; CPubKey mypk,gatewayspk; CScript opret; uint256 hashBlock; + CTransaction oracletx; uint8_t taddr,prefix,prefix2,wiftype; CPubKey mypk,gatewayspk; CScript opret; uint256 hashBlock; struct CCcontract_info *cp,*cpTokens,C,CTokens; std::string name,description,format; int32_t i,numvouts; int64_t fullsupply; char destaddr[64],coinaddr[64],myTokenCCaddr[64],str[65],*fstr; @@ -944,16 +950,18 @@ std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t cpTokens = CCinit(&CTokens,EVAL_TOKENS); if (coin=="KMD") { - taddr = 0; prefix = 60; prefix2 = 85; + wiftype = 188; + taddr = 0; } else { - LogPrint("gatewayscc","set taddr, prefix, prefix2 for %s\n",coin.c_str()); - taddr = 0; - prefix = 60; - prefix2 = 85; + prefix = p1; + prefix2 = p2; + wiftype = p3; + taddr = p4; + LogPrint("gatewayscc","set prefix %d, prefix2 %d, wiftype %d for %s\n",prefix,prefix2,wiftype,coin.c_str()); } if ( N == 0 || N > 15 || M > N ) { @@ -1030,7 +1038,7 @@ std::string GatewaysBind(uint64_t txfee,std::string coin,uint256 tokenid,int64_t { mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,totalsupply,gatewayspk)); mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,gatewayspk)); - return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysBindOpRet('B',tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2))); + return(FinalizeCCTx(0,cp,mtx,mypk,txfee,EncodeGatewaysBindOpRet('B',tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype))); } } CCerror = strprintf("cant find enough inputs"); @@ -1042,7 +1050,7 @@ std::string GatewaysDeposit(uint64_t txfee,uint256 bindtxid,int32_t height,std:: { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); CTransaction bindtx; CPubKey mypk; uint256 oracletxid,merkleroot,mhash,hashBlock,tokenid,txid; - int64_t totalsupply; int32_t i,m,n,numvouts; uint8_t M,N,taddr,prefix,prefix2; std::string coin; struct CCcontract_info *cp,C; + int64_t totalsupply; int32_t i,m,n,numvouts; uint8_t M,N,taddr,prefix,prefix2,wiftype; std::string coin; struct CCcontract_info *cp,C; std::vector pubkeys,publishers; std::vectortxids; char str[67],depositaddr[64],txidaddr[64]; cp = CCinit(&C,EVAL_GATEWAYS); @@ -1056,9 +1064,9 @@ std::string GatewaysDeposit(uint64_t txfee,uint256 bindtxid,int32_t height,std:: LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - if ( DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin ) + if ( DecodeGatewaysBindOpRet(depositaddr,bindtx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B' || refcoin != coin ) { - CCerror = strprintf("invalid coin - bindtxid %s coin.%n",uint256_str(str,bindtxid),coin.c_str()); + CCerror = strprintf("invalid coin - bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } @@ -1099,7 +1107,7 @@ std::string GatewaysDeposit(uint64_t txfee,uint256 bindtxid,int32_t height,std:: LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - if ( GatewaysVerify(depositaddr,oracletxid,claimvout,coin,cointxid,deposithex,proof,merkleroot,destpub) != amount ) + if ( GatewaysVerify(depositaddr,oracletxid,claimvout,coin,cointxid,deposithex,proof,merkleroot,destpub,taddr,prefix,prefix2) != amount ) { CCerror = strprintf("deposittxid didnt validate"); LogPrint("gatewayscc","%s\n", CCerror.c_str() ); @@ -1119,7 +1127,7 @@ std::string GatewaysDeposit(uint64_t txfee,uint256 bindtxid,int32_t height,std:: std::string GatewaysClaim(uint64_t txfee,uint256 bindtxid,std::string refcoin,uint256 deposittxid,CPubKey destpub,int64_t amount) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CTransaction tx; CPubKey mypk,gatewayspk,tmpdestpub; struct CCcontract_info *cp,C; uint8_t M,N,taddr,prefix,prefix2; + CTransaction tx; CPubKey mypk,gatewayspk,tmpdestpub; struct CCcontract_info *cp,C; uint8_t M,N,taddr,prefix,prefix2,wiftype; std::string coin, deposithex; std::vector msigpubkeys,publishers; int64_t totalsupply,depositamount,tmpamount,inputs,CCchange=0; int32_t numvouts,claimvout,height; std::vector proof; uint256 hashBlock,tokenid,oracletxid,tmptxid,cointxid; char str[65],depositaddr[64],coinaddr[64],destaddr[64]; std::vector txids; @@ -1135,7 +1143,7 @@ std::string GatewaysClaim(uint64_t txfee,uint256 bindtxid,std::string refcoin,ui LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || coin != refcoin ) + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2,wiftype) != 'B' || coin != refcoin ) { CCerror = strprintf("invalid coin - bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); LogPrint("gatewayscc","%s\n", CCerror.c_str() ); @@ -1197,7 +1205,7 @@ std::string GatewaysWithdraw(uint64_t txfee,uint256 bindtxid,std::string refcoin { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); CTransaction tx; CPubKey mypk,gatewayspk,signerpk; uint256 txid,tokenid,hashBlock,oracletxid,tmptokenid,tmpbindtxid,withdrawtxid; int32_t vout,numvouts; - int64_t nValue,totalsupply,inputs,CCchange=0,tmpamount; uint8_t funcid,K,M,N,taddr,prefix,prefix2; std::string coin,hex; + int64_t nValue,totalsupply,inputs,CCchange=0,tmpamount; uint8_t funcid,K,M,N,taddr,prefix,prefix2,wiftype; std::string coin,hex; std::vector msigpubkeys; char depositaddr[64],str[65],coinaddr[64]; struct CCcontract_info *cp,C,*cpTokens,CTokens; std::vector > unspentOutputs; @@ -1214,7 +1222,7 @@ std::string GatewaysWithdraw(uint64_t txfee,uint256 bindtxid,std::string refcoin LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - if( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || coin != refcoin ) + if( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2,wiftype) != 'B' || coin != refcoin ) { CCerror = strprintf("invalid bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); LogPrint("gatewayscc","%s\n", CCerror.c_str() ); @@ -1283,7 +1291,7 @@ std::string GatewaysPartialSign(uint64_t txfee,uint256 lasttxid,std::string refc CPubKey mypk,withdrawpub,signerpk,gatewayspk; struct CCcontract_info *cp,C; CTransaction tx,tmptx; std::vector > unspentOutputs; char funcid,str[65],depositaddr[64]; int32_t numvouts; uint256 withdrawtxid,hashBlock,bindtxid,tokenid,oracletxid,tmptokenid; std::string coin,tmphex; int64_t amount,totalsupply; - uint8_t K=0,M,N,taddr,prefix,prefix2; std::vector pubkeys; + uint8_t K=0,M,N,taddr,prefix,prefix2,wiftype; std::vector pubkeys; cp = CCinit(&C,EVAL_GATEWAYS); if ( txfee == 0 ) @@ -1318,7 +1326,7 @@ std::string GatewaysPartialSign(uint64_t txfee,uint256 lasttxid,std::string refc LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { CCerror = strprintf("invalid bind tx %s",uint256_str(str,bindtxid)); @@ -1359,7 +1367,7 @@ std::string GatewaysPartialSign(uint64_t txfee,uint256 lasttxid,std::string refc LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { CCerror = strprintf("invalid bind tx %s",uint256_str(str,bindtxid)); @@ -1383,7 +1391,7 @@ std::string GatewaysCompleteSigning(uint64_t txfee,uint256 lasttxid,std::string CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); CPubKey mypk,gatewayspk,signerpk,withdrawpub; struct CCcontract_info *cp,C; char funcid,str[65],depositaddr[64]; int64_t amount,totalsupply; std::string coin,tmphex; CTransaction tx,tmptx; uint256 withdrawtxid,hashBlock,tokenid,tmptokenid,bindtxid,oracletxid; int32_t numvouts; - uint8_t K=0,M,N,taddr,prefix,prefix2; std::vector pubkeys; + uint8_t K=0,M,N,taddr,prefix,prefix2,wiftype; std::vector pubkeys; cp = CCinit(&C,EVAL_GATEWAYS); mypk = pubkey2pk(Mypubkey()); @@ -1418,7 +1426,7 @@ std::string GatewaysCompleteSigning(uint64_t txfee,uint256 lasttxid,std::string LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { CCerror = strprintf("invalid bind tx %s",uint256_str(str,bindtxid)); @@ -1458,7 +1466,7 @@ std::string GatewaysCompleteSigning(uint64_t txfee,uint256 lasttxid,std::string LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + else if (DecodeGatewaysBindOpRet(depositaddr,tmptx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { CCerror = strprintf("invalid bind tx %s",uint256_str(str,bindtxid)); @@ -1482,7 +1490,7 @@ std::string GatewaysMarkDone(uint64_t txfee,uint256 completetxid,std::string ref CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); CPubKey mypk; struct CCcontract_info *cp,C; char str[65],depositaddr[64]; CTransaction tx; int32_t numvouts; uint256 withdrawtxid,bindtxid,oracletxid,tokenid,tmptokenid,hashBlock; std::string coin,hex; - uint8_t K,M,N,taddr,prefix,prefix2; std::vector pubkeys; int64_t amount,totalsupply; CPubKey withdrawpub; + uint8_t K,M,N,taddr,prefix,prefix2,wiftype; std::vector pubkeys; int64_t amount,totalsupply; CPubKey withdrawpub; cp = CCinit(&C,EVAL_GATEWAYS); mypk = pubkey2pk(Mypubkey()); @@ -1524,7 +1532,7 @@ std::string GatewaysMarkDone(uint64_t txfee,uint256 completetxid,std::string ref LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - else if (DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' + else if (DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B' || refcoin!=coin || tokenid!=tmptokenid) { CCerror = strprintf("invalid bind tx %s",uint256_str(str,bindtxid)); @@ -1546,7 +1554,7 @@ UniValue GatewaysPendingDeposits(uint256 bindtxid,std::string refcoin) { UniValue result(UniValue::VOBJ),pending(UniValue::VARR); CTransaction tx; std::string coin,hex,pub; CPubKey mypk,gatewayspk,destpub; std::vector pubkeys,publishers; std::vector txids; - uint256 tmpbindtxid,hashBlock,txid,tokenid,oracletxid,cointxid; uint8_t M,N,taddr,prefix,prefix2; + uint256 tmpbindtxid,hashBlock,txid,tokenid,oracletxid,cointxid; uint8_t M,N,taddr,prefix,prefix2,wiftype; char depositaddr[65],coinaddr[65],str[65],destaddr[65],txidaddr[65]; std::vector proof; int32_t numvouts,vout,claimvout,height; int64_t totalsupply,nValue,amount; struct CCcontract_info *cp,C; std::vector > unspentOutputs; @@ -1561,7 +1569,7 @@ UniValue GatewaysPendingDeposits(uint256 bindtxid,std::string refcoin) LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin) + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 'B' || refcoin != coin) { CCerror = strprintf("invalid bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); LogPrint("gatewayscc","%s\n", CCerror.c_str() ); @@ -1583,6 +1591,7 @@ UniValue GatewaysPendingDeposits(uint256 bindtxid,std::string refcoin) CCtxidaddr(txidaddr,txid); obj.push_back(Pair("deposittxidaddr",txidaddr)); _GetCCaddress(destaddr,EVAL_TOKENS,destpub); + obj.push_back(Pair("depositaddr",depositaddr)); obj.push_back(Pair("tokens_destination_address",destaddr)); pub=HexStr(destpub); obj.push_back(Pair("claim_pubkey",pub)); @@ -1599,7 +1608,7 @@ UniValue GatewaysPendingDeposits(uint256 bindtxid,std::string refcoin) UniValue GatewaysPendingWithdraws(uint256 bindtxid,std::string refcoin) { UniValue result(UniValue::VOBJ),pending(UniValue::VARR); CTransaction tx; std::string coin,hex; CPubKey mypk,gatewayspk,withdrawpub,signerpk; - std::vector msigpubkeys; uint256 hashBlock,tokenid,txid,tmpbindtxid,tmptokenid,oracletxid,withdrawtxid; uint8_t K,M,N,taddr,prefix,prefix2; + std::vector msigpubkeys; uint256 hashBlock,tokenid,txid,tmpbindtxid,tmptokenid,oracletxid,withdrawtxid; uint8_t K,M,N,taddr,prefix,prefix2,wiftype; char funcid,depositaddr[65],coinaddr[65],tokensaddr[65],destaddr[65],str[65],withaddr[65],numstr[32],signeraddr[65],txidaddr[65]; int32_t i,n,numvouts,vout,queueflag; int64_t totalsupply,amount,nValue; struct CCcontract_info *cp,C; std::vector > unspentOutputs; @@ -1615,7 +1624,7 @@ UniValue GatewaysPendingWithdraws(uint256 bindtxid,std::string refcoin) LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin ) + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2,wiftype) != 'B' || refcoin != coin ) { CCerror = strprintf("invalid bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); LogPrint("gatewayscc","%s\n", CCerror.c_str() ); @@ -1651,12 +1660,12 @@ UniValue GatewaysPendingWithdraws(uint256 bindtxid,std::string refcoin) continue; } Getscriptaddress(destaddr,tx.vout[1].scriptPubKey); - Getscriptaddress(withaddr,CScript() << ParseHex(HexStr(withdrawpub)) << OP_CHECKSIG); + GetCustomscriptaddress(withaddr,CScript() << ParseHex(HexStr(withdrawpub)) << OP_CHECKSIG,taddr,prefix,prefix2); if ( strcmp(destaddr,tokensaddr) == 0 ) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("withdrawtxid",uint256_str(str,tx.GetHash()))); - CCtxidaddr(txidaddr,tx.GetHash()); + CCCustomtxidaddr(txidaddr,tx.GetHash(),taddr,prefix,prefix2); obj.push_back(Pair("withdrawtxidaddr",txidaddr)); obj.push_back(Pair("withdrawaddr",withaddr)); sprintf(numstr,"%.8f",(double)tx.vout[1].nValue/COIN); @@ -1665,7 +1674,7 @@ UniValue GatewaysPendingWithdraws(uint256 bindtxid,std::string refcoin) if ( queueflag != 0 ) { obj.push_back(Pair("depositaddr",depositaddr)); - Getscriptaddress(signeraddr,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG); + GetCustomscriptaddress(signeraddr,CScript() << ParseHex(HexStr(mypk)) << OP_CHECKSIG,taddr,prefix,prefix2); obj.push_back(Pair("signeraddr",signeraddr)); } if (N>1) @@ -1688,7 +1697,7 @@ UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin) { UniValue result(UniValue::VOBJ),processed(UniValue::VARR); CTransaction tx; std::string coin,hex; CPubKey mypk,gatewayspk,withdrawpub; std::vector msigpubkeys; - uint256 withdrawtxid,hashBlock,txid,tokenid,tmptokenid,oracletxid; uint8_t K,M,N,taddr,prefix,prefix2; + uint256 withdrawtxid,hashBlock,txid,tokenid,tmptokenid,oracletxid; uint8_t K,M,N,taddr,prefix,prefix2,wiftype; char depositaddr[65],coinaddr[65],str[65],numstr[32],withaddr[65],txidaddr[65]; int32_t i,n,numvouts,vout,queueflag; int64_t totalsupply,nValue,amount; struct CCcontract_info *cp,C; std::vector > unspentOutputs; @@ -1703,7 +1712,7 @@ UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin) LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B' || refcoin != coin) + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2,wiftype) != 'B' || refcoin != coin) { CCerror = strprintf("invalid bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); LogPrint("gatewayscc","%s\n", CCerror.c_str() ); @@ -1732,9 +1741,9 @@ UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin) UniValue obj(UniValue::VOBJ); obj.push_back(Pair("completesigningtxid",uint256_str(str,txid))); obj.push_back(Pair("withdrawtxid",uint256_str(str,withdrawtxid))); - CCtxidaddr(txidaddr,withdrawtxid); + CCCustomtxidaddr(txidaddr,withdrawtxid,taddr,prefix,prefix2); obj.push_back(Pair("withdrawtxidaddr",txidaddr)); - Getscriptaddress(withaddr,CScript() << ParseHex(HexStr(withdrawpub)) << OP_CHECKSIG); + GetCustomscriptaddress(withaddr,CScript() << ParseHex(HexStr(withdrawpub)) << OP_CHECKSIG,taddr,prefix,prefix2); obj.push_back(Pair("withdrawaddr",withaddr)); obj.push_back(Pair("confirmed_or_notarized",komodo_txnotarizedconfirmed(txid))); sprintf(numstr,"%.8f",(double)tx.vout[1].nValue/COIN); @@ -1752,7 +1761,7 @@ UniValue GatewaysProcessedWithdraws(uint256 bindtxid,std::string refcoin) UniValue GatewaysList() { - UniValue result(UniValue::VARR); std::vector > addressIndex; struct CCcontract_info *cp,C; uint256 txid,hashBlock,oracletxid,tokenid; CTransaction vintx; std::string coin; int64_t totalsupply; char str[65],depositaddr[64]; uint8_t M,N,taddr,prefix,prefix2; std::vector pubkeys; + UniValue result(UniValue::VARR); std::vector > addressIndex; struct CCcontract_info *cp,C; uint256 txid,hashBlock,oracletxid,tokenid; CTransaction vintx; std::string coin; int64_t totalsupply; char str[65],depositaddr[64]; uint8_t M,N,taddr,prefix,prefix2,wiftype; std::vector pubkeys; cp = CCinit(&C,EVAL_GATEWAYS); SetCCtxids(addressIndex,cp->unspendableCCaddr); for (std::vector >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) @@ -1760,7 +1769,7 @@ UniValue GatewaysList() txid = it->first.txhash; if ( GetTransaction(txid,vintx,hashBlock,false) != 0 ) { - if ( vintx.vout.size() > 0 && DecodeGatewaysBindOpRet(depositaddr,vintx.vout[vintx.vout.size()-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 0 ) + if ( vintx.vout.size() > 0 && DecodeGatewaysBindOpRet(depositaddr,vintx.vout[vintx.vout.size()-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 0 ) { result.push_back(uint256_str(str,txid)); } @@ -1769,11 +1778,60 @@ UniValue GatewaysList() return(result); } +UniValue GatewaysExternalAddress(uint256 bindtxid,CPubKey pubkey) +{ + UniValue result(UniValue::VOBJ); struct CCcontract_info *cp,C; uint256 txid,hashBlock,oracletxid,tokenid; CTransaction tx; + std::string coin; int64_t numvouts,totalsupply; char str[65],addr[65],depositaddr[65]; uint8_t M,N,taddr,prefix,prefix2,wiftype; std::vector msigpubkeys; + + cp = CCinit(&C,EVAL_GATEWAYS); + if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 ) + { + CCerror = strprintf("cant find bindtxid %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2,wiftype) != 'B') + { + CCerror = strprintf("invalid bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + GetCustomscriptaddress(addr,CScript() << ParseHex(HexStr(pubkey)) << OP_CHECKSIG,taddr,prefix,prefix2); + result.push_back(Pair("result","success")); + result.push_back(Pair("address",addr)); + return(result); +} + +UniValue GatewaysDumpPrivKey(uint256 bindtxid,CKey key) +{ + UniValue result(UniValue::VOBJ); struct CCcontract_info *cp,C; uint256 txid,hashBlock,oracletxid,tokenid; CTransaction tx; + std::string coin,priv; int64_t numvouts,totalsupply; char str[65],addr[65],depositaddr[65]; uint8_t M,N,taddr,prefix,prefix2,wiftype; std::vector msigpubkeys; + + cp = CCinit(&C,EVAL_GATEWAYS); + if ( GetTransaction(bindtxid,tx,hashBlock,false) == 0 || (numvouts= tx.vout.size()) <= 0 ) + { + CCerror = strprintf("cant find bindtxid %s",uint256_str(str,bindtxid)); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2,wiftype) != 'B') + { + CCerror = strprintf("invalid bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); + LogPrint("gatewayscc","%s\n", CCerror.c_str() ); + return(""); + } + + priv=EncodeCustomSecret(key,wiftype); + result.push_back(Pair("result","success")); + result.push_back(Pair("address",priv.c_str())); + return(result); +} + UniValue GatewaysInfo(uint256 bindtxid) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); UniValue result(UniValue::VOBJ),a(UniValue::VARR); std::string coin; char str[67],numstr[65],depositaddr[64],gatewaystokens[64]; - uint8_t M,N; std::vector pubkeys; uint8_t taddr,prefix,prefix2; uint256 tokenid,oracletxid,hashBlock; CTransaction tx; + uint8_t M,N; std::vector pubkeys; uint8_t taddr,prefix,prefix2,wiftype; uint256 tokenid,oracletxid,hashBlock; CTransaction tx; CPubKey Gatewayspk; struct CCcontract_info *cp,C; int32_t i; int64_t numvouts,totalsupply,remaining; std::vector msigpubkeys; cp = CCinit(&C,EVAL_GATEWAYS); @@ -1785,7 +1843,7 @@ UniValue GatewaysInfo(uint256 bindtxid) LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); } - if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2) != 'B') + if ( DecodeGatewaysBindOpRet(depositaddr,tx.vout[numvouts-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,msigpubkeys,taddr,prefix,prefix2,wiftype) != 'B') { CCerror = strprintf("invalid bindtxid %s coin.%s",uint256_str(str,bindtxid),coin.c_str()); LogPrint("gatewayscc","%s\n", CCerror.c_str() ); @@ -1796,7 +1854,7 @@ UniValue GatewaysInfo(uint256 bindtxid) result.push_back(Pair("result","success")); result.push_back(Pair("name","Gateways")); depositaddr[0] = 0; - if ( tx.vout.size() > 0 && DecodeGatewaysBindOpRet(depositaddr,tx.vout[tx.vout.size()-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2) != 0 && M <= N && N > 0 ) + if ( tx.vout.size() > 0 && DecodeGatewaysBindOpRet(depositaddr,tx.vout[tx.vout.size()-1].scriptPubKey,tokenid,coin,totalsupply,oracletxid,M,N,pubkeys,taddr,prefix,prefix2,wiftype) != 0 && M <= N && N > 0 ) { if ( N > 1 ) { diff --git a/src/key_io.cpp b/src/key_io.cpp index f04c4da04..1953d9623 100644 --- a/src/key_io.cpp +++ b/src/key_io.cpp @@ -206,6 +206,19 @@ std::string EncodeSecret(const CKey& key) return ret; } +std::string EncodeCustomSecret(const CKey& key,uint8_t secret_key) +{ + assert(key.IsValid()); + std::vector data = std::vector(1,secret_key);; + data.insert(data.end(), key.begin(), key.end()); + if (key.IsCompressed()) { + data.push_back(1); + } + std::string ret = EncodeBase58Check(data); + memory_cleanse(data.data(), data.size()); + return ret; +} + CExtPubKey DecodeExtPubKey(const std::string& str) { CExtPubKey key; diff --git a/src/key_io.h b/src/key_io.h index 3606ad09f..72823d57e 100644 --- a/src/key_io.h +++ b/src/key_io.h @@ -18,6 +18,7 @@ CKey DecodeSecret(const std::string& str); std::string EncodeSecret(const CKey& key); +std::string EncodeCustomSecret(const CKey& key,uint8_t secret_key); CExtKey DecodeExtKey(const std::string& str); std::string EncodeExtKey(const CExtKey& extkey); diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index 208b3cf02..96e58b3af 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -470,6 +470,8 @@ static const CRPCCommand vRPCCommands[] = // Gateways { "gateways", "gatewaysaddress", &gatewaysaddress, true }, { "gateways", "gatewayslist", &gatewayslist, true }, + { "gateways", "gatewaysexternaladdress", &gatewaysexternaladdress, true }, + { "gateways", "gatewaysdumpprivkey", &gatewaysdumpprivkey, true }, { "gateways", "gatewaysinfo", &gatewaysinfo, true }, { "gateways", "gatewaysbind", &gatewaysbind, true }, { "gateways", "gatewaysdeposit", &gatewaysdeposit, true }, diff --git a/src/rpc/server.h b/src/rpc/server.h index b812ccc9d..3abc6748c 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -293,6 +293,8 @@ extern UniValue cclib(const UniValue& params, bool fHelp); extern UniValue gatewaysaddress(const UniValue& params, bool fHelp); extern UniValue gatewayslist(const UniValue& params, bool fHelp); extern UniValue gatewaysinfo(const UniValue& params, bool fHelp); +extern UniValue gatewaysdumpprivkey(const UniValue& params, bool fHelp); +extern UniValue gatewaysexternaladdress(const UniValue& params, bool fHelp); extern UniValue gatewaysbind(const UniValue& params, bool fHelp); extern UniValue gatewaysdeposit(const UniValue& params, bool fHelp); extern UniValue gatewaysclaim(const UniValue& params, bool fHelp); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index abd0b9696..b0bdd6bdd 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -6140,6 +6140,47 @@ UniValue gatewayslist(const UniValue& params, bool fHelp) return(GatewaysList()); } +UniValue gatewaysexternaladdress(const UniValue& params, bool fHelp) +{ + uint256 bindtxid; CPubKey pubkey; + + if ( fHelp || params.size() != 2) + throw runtime_error("gatewaysexternaladdress bindtxid pubkey\n"); + if ( ensure_CCrequirements() < 0 ) + throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); + bindtxid = Parseuint256((char *)params[0].get_str().c_str()); + pubkey = ParseHex(params[1].get_str().c_str()); + return(GatewaysExternalAddress(bindtxid,pubkey)); +} + +UniValue gatewaysdumpprivkey(const UniValue& params, bool fHelp) +{ + uint256 bindtxid; + + if ( fHelp || params.size() != 2) + throw runtime_error("gatewaysexternaladdress bindtxid address\n"); + if ( ensure_CCrequirements() < 0 ) + throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + LOCK2(cs_main, pwalletMain->cs_wallet); + bindtxid = Parseuint256((char *)params[0].get_str().c_str()); + std::string strAddress = params[1].get_str(); + CTxDestination dest = DecodeDestination(strAddress); + if (!IsValidDestination(dest)) { + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid transparent address"); + } + const CKeyID *keyID = boost::get(&dest); + if (!keyID) { + throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); + } + CKey vchSecret; + if (!pwalletMain->GetKey(*keyID, vchSecret)) { + throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); + } + return(GatewaysDumpPrivKey(bindtxid,vchSecret)); +} + UniValue gatewaysinfo(const UniValue& params, bool fHelp) { uint256 txid; @@ -6155,9 +6196,11 @@ UniValue gatewaysinfo(const UniValue& params, bool fHelp) UniValue gatewaysbind(const UniValue& params, bool fHelp) { - UniValue result(UniValue::VOBJ); uint256 tokenid,oracletxid; int32_t i; int64_t totalsupply; std::vector pubkeys; uint8_t M,N; std::string hex,coin; std::vector pubkey; - if ( fHelp || params.size() < 6 ) - throw runtime_error("gatewaysbind tokenid oracletxid coin tokensupply M N pubkey(s)\n"); + UniValue result(UniValue::VOBJ); uint256 tokenid,oracletxid; int32_t i; int64_t totalsupply; std::vector pubkeys; + uint8_t M,N,p1,p2,p3,p4=0; std::string hex,coin; std::vector pubkey; + + if ( fHelp || params.size() < 9 ) + throw runtime_error("gatewaysbind tokenid oracletxid coin tokensupply M N pubkey(s) pubtype p2shtype wiftype [taddr]\n"); if ( ensure_CCrequirements() < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; @@ -6179,7 +6222,11 @@ UniValue gatewaysbind(const UniValue& params, bool fHelp) throw runtime_error("invalid destination pubkey"); pubkeys.push_back(pubkey2pk(pubkey)); } - hex = GatewaysBind(0,coin,tokenid,totalsupply,oracletxid,M,N,pubkeys); + p1 = atoi((char *)params[6+N].get_str().c_str()); + p2 = atoi((char *)params[6+N+1].get_str().c_str()); + p3 = atoi((char *)params[6+N+2].get_str().c_str()); + if (params.size() == 9+N) p4 = atoi((char *)params[6+N+3].get_str().c_str()); + hex = GatewaysBind(0,coin,tokenid,totalsupply,oracletxid,M,N,pubkeys,p1,p2,p3,p4); RETURN_IF_ERROR(CCerror); if ( hex.size() > 0 ) { From af628f2706020eaaead58eb903d6f8178480e314 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 05:13:16 -1100 Subject: [PATCH 0538/1145] The owner doesn't need to be the creator --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 603e776b8..53a505a12 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -995,10 +995,10 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { txid = it->first.txhash; vout = (int32_t)it->first.index; - char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); + //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( it->second.satoshis != 1 || vout != 0 ) continue; - if ( rogue_playerdata(cp,gametxid,pk,playerdata,txid) == 0 && pk == mypk ) + if ( rogue_playerdata(cp,gametxid,pk,playerdata,txid) == 0 )//&& pk == mypk ) { a.push_back(rogue_playerobj(playerdata,txid)); //result.push_back(Pair("playerdata",rogue_playerobj(playerdata))); From ba863048dca89eb0e133857e0eef9815abc0a11b Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 05:17:47 -1100 Subject: [PATCH 0539/1145] Test --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 53a505a12..8a6f1530f 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -433,13 +433,13 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub //memcpy(&gametxid,script+2,sizeof(gametxid)); if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { - //fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); + fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); if ( playertx.vin[1].prevout.hash == gametxid && rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid) == 0 ) { // if registertxid has vin from pk, it can be used return(0); } else fprintf(stderr,"hash mismatch or illegal gametxid\n"); - } + } else fprintf(stderr,"invalid game %s\n",gametxid.GetHex().c_str()); } } return(-1); From 5ad59bf6146c75a3816c9632db991a67a69aa9af Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 05:22:24 -1100 Subject: [PATCH 0540/1145] Missing () --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 8a6f1530f..b9ea82d65 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -185,10 +185,10 @@ uint8_t rogue_highlanderopretdecode(uint256 &gametxid, int32_t ®slot, CPubKey // try no tokens case: if (vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q')) return(f); - else if (f = DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy) != 0) { // it is tokens + else if ( (f= DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy)) != 0) + { if (f != 'c') GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx - if (vopretNonfungible.size() > 2 && E_UNMARSHAL(vopretNonfungible, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q')) { return(f); From 17a8707c624f0c1b92e1f8878c17db476ab39929 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 05:26:44 -1100 Subject: [PATCH 0541/1145] Test --- src/cc/rogue_rpc.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b9ea82d65..42246f190 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -187,12 +187,14 @@ uint8_t rogue_highlanderopretdecode(uint256 &gametxid, int32_t ®slot, CPubKey return(f); else if ( (f= DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy)) != 0) { + fprintf(stderr,"f %c %d\n",f,f); if (f != 'c') GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx if (vopretNonfungible.size() > 2 && E_UNMARSHAL(vopretNonfungible, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q')) { return(f); } + fprintf(stderr,"e.%d f.%c game.%s slot.%dВыходи и жди ,ок\n",e,f,gametxid.GetHex().c_str(),regslot); } return(0); From 785b17d3991cec88a4169392e5f44cc88416ae90 Mon Sep 17 00:00:00 2001 From: Mihailo Milenkovic Date: Mon, 11 Feb 2019 17:42:34 +0100 Subject: [PATCH 0542/1145] GatewaysCC code cleanup --- src/cc/dapps/oraclefeed.c | 32 +++------------- src/cc/gateways.cpp | 78 +++++++++++++++++++-------------------- 2 files changed, 42 insertions(+), 68 deletions(-) diff --git a/src/cc/dapps/oraclefeed.c b/src/cc/dapps/oraclefeed.c index cc6b45037..cf7a2eacb 100644 --- a/src/cc/dapps/oraclefeed.c +++ b/src/cc/dapps/oraclefeed.c @@ -372,29 +372,6 @@ bits256 broadcasttx(char *refcoin,char *acname,cJSON *hexjson) return(txid); } -bits256 sendtoaddress(char *refcoin,char *acname,char *destaddr,int64_t satoshis) -{ - char numstr[32],*retstr,str[65]; cJSON *retjson; bits256 txid; - memset(txid.bytes,0,sizeof(txid)); - sprintf(numstr,"%.8f",(double)satoshis/SATOSHIDEN); - if ( (retjson= get_cli(refcoin,&retstr,acname,"sendtoaddress",destaddr,numstr,"","")) != 0 ) - { - fprintf(stderr,"unexpected sendtoaddress json.(%s)\n",jprint(retjson,0)); - free_json(retjson); - } - else if ( retstr != 0 ) - { - if ( strlen(retstr) >= 64 ) - { - retstr[64] = 0; - decode_hex(txid.bytes,32,retstr); - } - fprintf(stderr,"sendtoaddress %s %.8f txid.(%s)\n",destaddr,(double)satoshis/SATOSHIDEN,bits256_str(str,txid)); - free(retstr); - } - return(txid); -} - int32_t get_coinheight(char *refcoin,char *acname) { cJSON *retjson; char *retstr; int32_t height=0; @@ -643,7 +620,7 @@ char *createrawtx(char *refcoin,char *acname,char *depositaddr,char *withdrawadd else txfee = 10000; if ( satoshis < txfee ) { - printf("createrawtx satoshis %.8f < txfee %.8f\n",(double)satoshis/SATOSHIDEN,(double)txfee/SATOSHIDEN); + printf("createrawtx: satoshis %.8f < txfee %.8f\n",(double)satoshis/SATOSHIDEN,(double)txfee/SATOSHIDEN); return(0); } sprintf(array,"\'[\"%s\"]\'",depositaddr); @@ -912,8 +889,8 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t if ( (clijson=addsignature(refcoin,"",rawtx,M)) != 0 && is_cJSON_True(jobj(clijson,"complete")) != 0) { txid=gatewayscompletesigning(refcoin,acname,withdrawtxid,jstr(clijson,"hex")); - if (txid.txid!=zeroid.txid) fprintf(stderr,"#WITHDRAW (%s) complete signing tx sent - %s\n",bits256_str(str,withdrawtxid),bits256_str(str1,txid)); - else fprintf(stderr,"error broadcasting tx on %s",acname); + if (txid.txid!=zeroid.txid) fprintf(stderr,"### SIGNING withdraw %s 1of1\n",bits256_str(str,withdrawtxid)); + else fprintf(stderr,"### SIGNING error broadcasting tx on %s",acname); free_json(clijson); processed++; } @@ -978,7 +955,8 @@ void update_gatewayspending(char *refcoin,char *acname,char *bindtxidstr,int32_t withdrawaddr = jstr(item,"withdrawaddr"); fprintf(stderr,"### WITHDRAW %.8f %s sent to %s\n",amount,refcoin,withdrawaddr); txid=gatewaysmarkdone(refcoin,acname,completetxid); - if (txid.txid!=zeroid.txid) fprintf(stderr,"### MARKDONE withdraw %s\n",bits256_str(str,withdrawtxid)); + if (txid.txid!=zeroid.txid) fprintf(stderr,"### MARKDONE withdraw %s\n",bits256_str(str,withdrawtxid)); + else fprintf(stderr,"### MARKDONE error broadcasting tx on %s\n",refcoin); } else fprintf(stderr,"### WITHDRAW error broadcasting tx on %s\n",refcoin); } diff --git a/src/cc/gateways.cpp b/src/cc/gateways.cpp index af9038f81..02e30940f 100644 --- a/src/cc/gateways.cpp +++ b/src/cc/gateways.cpp @@ -148,6 +148,11 @@ */ // start of consensus code +#define KMD_PUBTYPE 60 +#define KMD_P2SHTYPE 85 +#define KMD_WIFTYPE 188 +#define KMD_TADDR 0 + CScript EncodeGatewaysBindOpRet(uint8_t funcid,uint256 tokenid,std::string coin,int64_t totalsupply,uint256 oracletxid,uint8_t M,uint8_t N,std::vector gatewaypubkeys,uint8_t taddr,uint8_t prefix,uint8_t prefix2,uint8_t wiftype) { CScript opret; uint8_t evalcode = EVAL_GATEWAYS; struct CCcontract_info *cp,C; CPubKey gatewayspk; @@ -174,31 +179,28 @@ uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,ui depositaddr[0] = 0; if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> coin; ss >> totalsupply; ss >> oracletxid; ss >> M; ss >> N; ss >> gatewaypubkeys; ss >> taddr; ss >> prefix; ss >> prefix2; ss >> wiftype) != 0 ) { - if ( prefix == 60 ) + if ( prefix == KMD_PUBTYPE && prefix2 == KMD_P2SHTYPE ) { if ( N > 1 ) { strcpy(depositaddr,CBitcoinAddress(CScriptID(GetScriptForMultisig(M,gatewaypubkeys))).ToString().c_str()); - //LogPrint("gatewayscc","f.%c M.%d of N.%d size.%d -> %s\n",f,M,N,(int32_t)gatewaypubkeys.size(),depositaddr); + LogPrint("gatewayscc-1","f.%c M.%d of N.%d size.%d -> %s\n",f,M,N,(int32_t)gatewaypubkeys.size(),depositaddr); } else Getscriptaddress(depositaddr,CScript() << ParseHex(HexStr(gatewaypubkeys[0])) << OP_CHECKSIG); } - else if (prefix == 28 && prefix2 == 50) + else { if ( N > 1 ) strcpy(depositaddr,CCustomBitcoinAddress(CScriptID(GetScriptForMultisig(M,gatewaypubkeys)),taddr,prefix,prefix2).ToString().c_str()); else GetCustomscriptaddress(depositaddr,CScript() << ParseHex(HexStr(gatewaypubkeys[0])) << OP_CHECKSIG,taddr,prefix,prefix2); } - else - { - LogPrint("gatewayscc","need to generate non-KMD addresses prefix.%d\n",prefix); - } return(f); - } else LogPrint("gatewayscc","error decoding bind opret\n"); + } else LogPrint("gatewayscc-1","error decoding bind opret\n"); return(0); } CScript EncodeGatewaysDepositOpRet(uint8_t funcid,uint256 bindtxid,std::string refcoin,std::vector publishers,std::vectortxids,int32_t height,uint256 cointxid,int32_t claimvout,std::string deposithex,std::vectorproof,CPubKey destpub,int64_t amount) { CScript opret; uint8_t evalcode = EVAL_GATEWAYS; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << refcoin << bindtxid << publishers << txids << height << cointxid << claimvout << deposithex << proof << destpub << amount); return(opret); } @@ -206,6 +208,7 @@ CScript EncodeGatewaysDepositOpRet(uint8_t funcid,uint256 bindtxid,std::string r uint8_t DecodeGatewaysDepositOpRet(const CScript &scriptPubKey,uint256 &bindtxid,std::string &refcoin,std::vector&publishers,std::vector&txids,int32_t &height,uint256 &cointxid, int32_t &claimvout,std::string &deposithex,std::vector &proof,CPubKey &destpub,int64_t &amount) { std::vector vopret; uint8_t *script,e,f; + GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> refcoin; ss >> bindtxid; ss >> publishers; ss >> txids; ss >> height; ss >> cointxid; ss >> claimvout; ss >> deposithex; ss >> proof; ss >> destpub; ss >> amount) != 0 ) @@ -276,6 +279,7 @@ uint8_t DecodeGatewaysWithdrawOpRet(const CScript &scriptPubKey, uint256& tokeni CScript EncodeGatewaysPartialOpRet(uint8_t funcid, uint256 withdrawtxid,std::string refcoin,uint8_t K, CPubKey signerpk,std::string hex) { CScript opret; uint8_t evalcode = EVAL_GATEWAYS; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << withdrawtxid << refcoin << K << signerpk << hex); return(opret); } @@ -302,6 +306,7 @@ CScript EncodeGatewaysCompleteSigningOpRet(uint8_t funcid,uint256 withdrawtxid,s uint8_t DecodeGatewaysCompleteSigningOpRet(const CScript &scriptPubKey,uint256 &withdrawtxid,std::string &refcoin,uint8_t &K,std::string &hex) { std::vector vopret; uint8_t *script,e,f; + GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> withdrawtxid; ss >> refcoin; ss >> K; ss >> hex) != 0 ) @@ -314,6 +319,7 @@ uint8_t DecodeGatewaysCompleteSigningOpRet(const CScript &scriptPubKey,uint256 & CScript EncodeGatewaysMarkDoneOpRet(uint8_t funcid,uint256 withdrawtxid,std::string refcoin,uint256 completetxid) { CScript opret; uint8_t evalcode = EVAL_GATEWAYS; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << withdrawtxid << refcoin << completetxid); return(opret); } @@ -321,6 +327,7 @@ CScript EncodeGatewaysMarkDoneOpRet(uint8_t funcid,uint256 withdrawtxid,std::str uint8_t DecodeGatewaysMarkDoneOpRet(const CScript &scriptPubKey, uint256 &withdrawtxid, std::string &refcoin, uint256 &completetxid) { std::vector vopret; uint8_t *script,e,f; + GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> withdrawtxid; ss >> refcoin; ss >> completetxid;) != 0 ) @@ -353,6 +360,7 @@ uint8_t DecodeGatewaysOpRet(const CScript &scriptPubKey) int64_t IsGatewaysvout(struct CCcontract_info *cp,const CTransaction& tx,int32_t v) { char destaddr[64]; + if ( tx.vout[v].scriptPubKey.IsPayToCryptoCondition() != 0 ) { if ( Getscriptaddress(destaddr,tx.vout[v].scriptPubKey) > 0 && strcmp(destaddr,cp->unspendableCCaddr) == 0 ) @@ -365,6 +373,7 @@ bool GatewaysExactAmounts(struct CCcontract_info *cp,Eval* eval,const CTransacti { static uint256 zerohash; CTransaction vinTx; uint256 hashBlock,activehash; int32_t i,numvins,numvouts; int64_t inputs=0,outputs=0,assetoshis; + numvins = tx.vin.size(); numvouts = tx.vout.size(); for (i=0; idata; txid = zeroid; char str[65]; - //LogPrint("gatewayscc","start reverse scan %s\n",uint256_str(str,batontxid)); + LogPrint("gatewayscc-2","start reverse scan %s\n",uint256_str(str,batontxid)); while ( myGetTransaction(batontxid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 0 ) { - //LogPrint("gatewayscc","check %s\n",uint256_str(str,batontxid)); + LogPrint("gatewayscc-2","check %s\n",uint256_str(str,batontxid)); if ( DecodeOraclesData(tx.vout[numvouts-1].scriptPubKey,oracletxid,bhash,pk,data) == 'D' && oracletxid == reforacletxid ) { - //LogPrint("gatewayscc","decoded %s\n",uint256_str(str,batontxid)); + LogPrint("gatewayscc-2","decoded %s\n",uint256_str(str,batontxid)); if ( oracle_format(&hash,&merkleht,0,'I',(uint8_t *)data.data(),0,(int32_t)data.size()) == sizeof(int32_t) && merkleht == height ) { len = oracle_format(&hash,&val,0,'h',(uint8_t *)data.data(),sizeof(int32_t),(int32_t)data.size()); @@ -442,20 +451,20 @@ uint256 GatewaysReverseScan(uint256 &txid,int32_t height,uint256 reforacletxid,u if ( len == sizeof(hash)+sizeof(int32_t) && len2 == 2*sizeof(mhash)+sizeof(int32_t) && mhash != zeroid ) { txid = batontxid; - //LogPrint("gatewayscc","set txid\n"); + LogPrint("gatewayscc-2","set txid\n"); return(mhash); } else { - //LogPrint("gatewayscc","missing hash\n"); + LogPrint("gatewayscc-2","missing hash\n"); return(zeroid); } - } //else LogPrint("gatewayscc","height.%d vs search ht.%d\n",(int32_t)merkleht,(int32_t)height); + } else LogPrint("gatewayscc-2","height.%d vs search ht.%d\n",(int32_t)merkleht,(int32_t)height); batontxid = bhash; - // LogPrint("gatewayscc","new hash %s\n",uint256_str(str,batontxid)); + LogPrint("gatewayscc-2","new hash %s\n",uint256_str(str,batontxid)); } else break; } - LogPrint("gatewayscc","end of loop\n"); + LogPrint("gatewayscc-2","end of loop\n"); return(zeroid); } @@ -529,7 +538,7 @@ int64_t GatewaysVerify(char *refdepositaddr,uint256 oracletxid,int32_t claimvout } if ( txid == cointxid ) { - LogPrint("gatewayscc","verified proof for cointxid in merkleroot\n"); + LogPrint("gatewayscc-1","verified proof for cointxid in merkleroot\n"); return(nValue); } else LogPrint("gatewayscc","(%s) != (%s) or txid %s mismatch.%d or script mismatch\n",refdepositaddr,destaddr,uint256_str(str,txid),txid != cointxid); } else LogPrint("gatewayscc","claimaddr.(%s) != destpubaddr.(%s)\n",claimaddr,destpubaddr); @@ -544,8 +553,6 @@ int64_t GatewaysDepositval(CTransaction tx,CPubKey mypk) { if ( DecodeGatewaysDepositOpRet(tx.vout[numvouts-1].scriptPubKey,bindtxid,coin,publishers,txids,height,cointxid,claimvout,deposithex,proof,claimpubkey,amount) == 'D' && claimpubkey == mypk ) { - // coin, bindtxid, publishers - //LogPrint("gatewayscc","need to validate deposittxid more\n"); return(amount); } } @@ -603,11 +610,10 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & return eval->Invalid("no vouts"); else { - //LogPrint("gatewayscc","check amounts\n"); + //LogPrint("gatewayscc-1","check amounts\n"); // if ( GatewaysExactAmounts(cp,eval,tx,1,10000) == false ) // { - // LogPrint("gatewayscc","Gatewaysget invalid amount\n"); - // return false; + // return eval->Invalid("invalid inputs vs. outputs!"); // } // else // { @@ -867,7 +873,7 @@ bool GatewaysValidate(struct CCcontract_info *cp,Eval *eval,const CTransaction & } retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts); if ( retval != 0 ) - fprintf(stderr,"Gateways tx validated\n"); + LogPrint("gatewayscc","Gateways tx validated\n"); else fprintf(stderr,"Gateways tx invalid\n"); return(retval); // } @@ -891,18 +897,11 @@ int64_t AddGatewaysInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CP GetTokensCCaddress(cp,coinaddr,pk); SetCCunspents(unspentOutputs,coinaddr); threshold = total/(maxinputs+1); - LogPrint("gatewayscc","check %s for gateway inputs\n",coinaddr); + LogPrint("gatewayscc-1","check %s for gateway inputs\n",coinaddr); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { txid = it->first.txhash; vout = (int32_t)it->first.index; - if ( it->second.satoshis < threshold ) - continue; - // for (j=0; j 15 || M > N ) { @@ -1057,7 +1056,7 @@ std::string GatewaysDeposit(uint64_t txfee,uint256 bindtxid,int32_t height,std:: if ( txfee == 0 ) txfee = 10000; mypk = pubkey2pk(Mypubkey()); - //LogPrint("gatewayscc","GatewaysDeposit ht.%d %s %.8f numpks.%d\n",height,refcoin.c_str(),(double)amount/COIN,(int32_t)pubkeys.size()); + LogPrint("gatewayscc-1","GatewaysDeposit ht.%d %s %.8f numpks.%d\n",height,refcoin.c_str(),(double)amount/COIN,(int32_t)pubkeys.size()); if ( GetTransaction(bindtxid,bindtx,hashBlock,false) == 0 || (numvouts= bindtx.vout.size()) <= 0 ) { CCerror = strprintf("cant find bindtxid %s",uint256_str(str,bindtxid)); @@ -1094,9 +1093,6 @@ std::string GatewaysDeposit(uint64_t txfee,uint256 bindtxid,int32_t height,std:: LogPrint("gatewayscc","cointxid.%s m.%d of n.%d\n",uint256_str(str,cointxid),m,n); if ( merkleroot == zeroid || m < n/2 ) { - //uint256 tmp; - //decode_hex((uint8_t *)&tmp,32,(char *)"90aedc2f19200afc9aca2e351438d011ebae8264a58469bf225883045f61917f"); - //merkleroot = revuint256(tmp); CCerror = strprintf("couldnt find merkleroot for ht.%d %s oracle.%s m.%d vs n.%d",height,coin.c_str(),uint256_str(str,oracletxid),m,n); LogPrint("gatewayscc","%s\n", CCerror.c_str() ); return(""); From 972618e4fdc987c888552de9f1a8022586280cf1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 06:14:18 -1100 Subject: [PATCH 0543/1145] Fix rogue_highlanderopretdecode --- src/cc/rogue_rpc.cpp | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 42246f190..e6ccc3352 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -176,27 +176,25 @@ CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,int32_t regslot,CP uint8_t rogue_highlanderopretdecode(uint256 &gametxid, int32_t ®slot, CPubKey &pk, std::vector &playerdata, CScript scriptPubKey) { - std::string name, description; - std::vector vorigPubkey; - std::vector vopretNonfungible, vopret, vopretDummy; - uint8_t e, f; uint256 tokenid; std::vector voutPubkeys; + std::string name, description; std::vector vorigPubkey; + std::vector vopretNonfungible, vopret, vopretDummy,origpubkey; + uint8_t e, f,*script; uint256 tokenid; std::vector voutPubkeys; GetOpReturnData(scriptPubKey, vopret); - // try no tokens case: - if (vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q')) - return(f); - else if ( (f= DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy)) != 0) + script = (uint8_t *)vopret.data(); + if ( script[1] == 'c' && (f= DecodeTokenCreateOpRet(scriptPubKey,origpubkey,name,description,vopretNonfungible)) == 'c' ) { - fprintf(stderr,"f %c %d\n",f,f); - if (f != 'c') - GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx - if (vopretNonfungible.size() > 2 && E_UNMARSHAL(vopretNonfungible, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q')) - { - return(f); - } - fprintf(stderr,"e.%d f.%c game.%s slot.%dВыходи и жди ,ок\n",e,f,gametxid.GetHex().c_str(),regslot); + vopret = vopretNonfungible; } - + else if ( script[1] == 't' && (f= DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy)) != 0 ) + { + GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx + } + if ( vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) + { + return(f); + } + fprintf(stderr,"e.%d f.%c game.%s regslot.%d psize.%d\n",e,f,gametxid.GetHex().c_str(),regslot,(int32_t)playerdata.size()); return(0); } @@ -889,7 +887,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); - CScript opret = rogue_highlanderopret(funcid, gametxid, regslot,mypk, newdata); + CScript opret = rogue_highlanderopret(funcid, gametxid, regslot, mypk, newdata); if ( newdata.size() == 0 ) rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,opret); else From 8537216d9ac5fab92a58270ca0a3ab6d3517048b Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 06:36:14 -1100 Subject: [PATCH 0544/1145] Suppress special chars --- src/cc/rogue/state.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index dd54afe25..96d576501 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1381,7 +1381,7 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item) void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) { - static int32_t didinit; + static int32_t didinit; int32_t i; if ( didinit == 0 ) { struct rogue_state R; char keystrokes[3]; @@ -1397,6 +1397,9 @@ void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) THING *obj = new_item(); rogue_restoreobject(obj,item); strcpy(packitemstr,inv_name(obj,FALSE)); + for (i=0; packitemstr[i]!=0; i++) + if ( packitemstr[i] < ' ' || (uint8_t)packitemstr[i] >= 0x80 ) + packitemstr[i] = ' '; //fprintf(stderr,"packitem.(%s)\n",packitemstr); free(obj); } From 7a48d681ed49a5c208fa0fc3522a0256e70fef18 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 07:11:17 -1100 Subject: [PATCH 0545/1145] vopret = vopretNonfungible; --- src/cc/rogue/state.c | 3 --- src/cc/rogue_rpc.cpp | 1 + 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 96d576501..817993c17 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1397,9 +1397,6 @@ void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item) THING *obj = new_item(); rogue_restoreobject(obj,item); strcpy(packitemstr,inv_name(obj,FALSE)); - for (i=0; packitemstr[i]!=0; i++) - if ( packitemstr[i] < ' ' || (uint8_t)packitemstr[i] >= 0x80 ) - packitemstr[i] = ' '; //fprintf(stderr,"packitem.(%s)\n",packitemstr); free(obj); } diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e6ccc3352..f33d4d583 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -189,6 +189,7 @@ uint8_t rogue_highlanderopretdecode(uint256 &gametxid, int32_t ®slot, CPubKey else if ( script[1] == 't' && (f= DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy)) != 0 ) { GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx + vopret = vopretNonfungible; } if ( vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) { From 73c33eb2a3e383f6b91f649aa5f8e2b037b19b17 Mon Sep 17 00:00:00 2001 From: dimxy Date: Mon, 11 Feb 2019 22:53:08 +0500 Subject: [PATCH 0546/1145] added burned non-fungible tokens validation --- src/cc/CCtokens.cpp | 96 +++++++++++++++++++++++++++++++++++++++++---- src/cc/CCtokens.h | 2 + 2 files changed, 91 insertions(+), 7 deletions(-) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index eb802b65d..bcebb1a09 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -236,7 +236,7 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & std::vector vopretExtra, tmporigpubkey, ignorepubkey; uint8_t funcid, evalCodeInOpret; char destaddr[64], origaddr[64], CCaddr[64]; - std::vector voutTokenPubkeys; + std::vector voutTokenPubkeys, vinTokenPubkeys; //return true; @@ -257,7 +257,7 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) return eval->Invalid("cant find token create txid"); //else if (IsCCInput(tx.vin[0].scriptSig) != 0) - // return eval->Invalid("illegal token vin0"); // this validation was removed because some token tx might not have normal vins + // return eval->Invalid("illegal token vin0"); // <-- this validation was removed because some token tx might not have normal vins else if (funcid != 'c') { if (tokenid == zeroid) @@ -270,6 +270,18 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & } } + // validate spending from token cc addr: allowed only for burned non-fungible tokens: + if (ExtractTokensVinPubkeys(tx, vinTokenPubkeys) && std::find(vinTokenPubkeys.begin(), vinTokenPubkeys.end(), GetUnspendable(cp, NULL)) != vinTokenPubkeys.end()) { + // validate spending from token unspendable cc addr: + int64_t burnedAmount = HasBurnedTokensvouts(cp, eval, tx, tokenid); + if (burnedAmount > 0) { + std::vector vopretNonfungible; + GetNonfungibleData(tokenid, vopretNonfungible); + if( vopretNonfungible.empty() ) + return eval->Invalid("spending cc marker not supported for fungible tokens"); + } + } + switch (funcid) { case 'c': // create wont be called to be verified as it has no CC inputs @@ -445,8 +457,7 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys /*<--not used, always true return(0); } - //TODO: validate cc vouts are EVAL_TOKENS! - if (tx.vout[v].scriptPubKey.IsPayToCryptoCondition()) // maybe check address too? dimxy: possibly no, because there are too many cases with different addresses here + if (tx.vout[v].scriptPubKey.IsPayToCryptoCondition()) { if (goDeeper) { //validate all tx @@ -489,7 +500,7 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys /*<--not used, always true GetNonfungibleData(reftokenid, vopretNonfungible); - voutPubkeys = FilterOutTokensUnspendablePk(voutPubkeysInOpret); + voutPubkeys = FilterOutTokensUnspendablePk(voutPubkeysInOpret); // cannot send tokens to token unspendable cc addr (only marker is allowed there) // NOTE: evalcode order in vouts is important: // non-fungible-eval -> EVAL_TOKENS -> assets-eval @@ -551,7 +562,7 @@ int64_t IsTokensvout(bool goDeeper, bool checkPubkeys /*<--not used, always true // maybe it is single-eval or dual/three-eval token change? std::vector vinPubkeys, vinPubkeysUnfiltered; ExtractTokensVinPubkeys(tx, vinPubkeysUnfiltered); - vinPubkeys = FilterOutTokensUnspendablePk(vinPubkeysUnfiltered); + vinPubkeys = FilterOutTokensUnspendablePk(vinPubkeysUnfiltered); // cannot send tokens to token unspendable cc addr (only marker is allowed there) for(std::vector::iterator it = vinPubkeys.begin(); it != vinPubkeys.end(); it++) { testVouts.push_back(std::make_pair(MakeCC1vout(EVAL_TOKENS, tx.vout[v].nValue, *it), std::string("single-eval cc1 self vin pk"))); @@ -767,7 +778,6 @@ int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, C LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "AddTokenCCInputs() found incorrect non-fungible opret payload for vintxid=" << vintxid.GetHex() << std::endl); continue; } - // non-fungible evalCode2 cc contract should also check if there exists only one non-fungible vout with amount = 1 } @@ -790,6 +800,78 @@ int64_t AddTokenCCInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, C return(totalinputs); } +// checks if any token vouts are sent to 'dead' pubkey +int64_t HasBurnedTokensvouts(struct CCcontract_info *cp, Eval* eval, const CTransaction& tx, uint256 reftokenid) +{ + uint8_t dummyEvalCode; + uint256 tokenIdOpret; + std::vector voutPubkeys, voutPubkeysDummy; + std::vector vopretExtra, vopretNonfungible; + + uint8_t evalCode = EVAL_TOKENS; // if both payloads are empty maybe it is a transfer to non-payload-one-eval-token vout like GatewaysClaim + uint8_t evalCode2 = 0; // will be checked if zero or not + + // test vouts for possible token use-cases: + std::vector> testVouts; + + int32_t n = tx.vout.size(); + // just check boundaries: + if (n == 0) { + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "HasBurnedTokensvouts() incorrect params: tx.vout.size() == 0, txid=" << tx.GetHash().GetHex() << std::endl); + return(0); + } + + + if (DecodeTokenOpRet(tx.vout.back().scriptPubKey, dummyEvalCode, tokenIdOpret, voutPubkeysDummy, vopretExtra) == 0) { + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "HasBurnedTokensvouts() cannot parse opret DecodeTokenOpRet returned 0, txid=" << tx.GetHash().GetHex() << std::endl); + return 0; + } + + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "HasBurnedTokensvouts() vopretExtra=" << HexStr(vopretExtra) << std::endl); + + GetNonfungibleData(reftokenid, vopretNonfungible); + + if (vopretNonfungible.size() > 0) + evalCode = vopretNonfungible.begin()[0]; + if (vopretExtra.size() > 0) + evalCode2 = vopretExtra.begin()[0]; + + if (evalCode == EVAL_TOKENS && evalCode2 != 0) { + evalCode = evalCode2; + evalCode2 = 0; + } + + voutPubkeys.push_back(pubkey2pk(ParseHex(CC_BURNPUBKEY))); + + int64_t burnedAmount = 0; + + for (int i = 0; i < tx.vout.size(); i++) { + + if (tx.vout[i].scriptPubKey.IsPayToCryptoCondition()) + { + // make all possible token vouts for dead pk: + for (std::vector::iterator it = voutPubkeys.begin(); it != voutPubkeys.end(); it++) { + testVouts.push_back(std::make_pair(MakeCC1vout(EVAL_TOKENS, tx.vout[i].nValue, *it), std::string("single-eval cc1 burn pk"))); + testVouts.push_back(std::make_pair(MakeTokensCC1vout(evalCode, evalCode2, tx.vout[i].nValue, *it), std::string("three-eval cc1 burn pk"))); + + if (evalCode2 != 0) + // also check in backward evalcode order: + testVouts.push_back(std::make_pair(MakeTokensCC1vout(evalCode2, evalCode, tx.vout[i].nValue, *it), std::string("three-eval cc1 burn pk backward-eval"))); + } + + // try all test vouts: + for (auto t : testVouts) { + if (t.first == tx.vout[i]) { + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG1, stream << "HasBurnedTokensvouts() burned amount=" << tx.vout[i].nValue << " msg=" << t.second << " evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " txid=" << tx.GetHash().GetHex() << " tokenid=" << reftokenid.GetHex() << std::endl); + burnedAmount += tx.vout[i].nValue; + } + } + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "HasBurnedTokensvouts() no burned vouts evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); + } + } + + return burnedAmount; +} std::string CreateToken(int64_t txfee, int64_t tokensupply, std::string name, std::string description, std::vector nonfungibleData) { diff --git a/src/cc/CCtokens.h b/src/cc/CCtokens.h index 231b64ac9..791107648 100644 --- a/src/cc/CCtokens.h +++ b/src/cc/CCtokens.h @@ -30,6 +30,8 @@ bool TokensValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx bool TokensExactAmounts(bool goDeeper, struct CCcontract_info *cpTokens, int64_t &inputs, int64_t &outputs, Eval* eval, const CTransaction &tx, uint256 tokenid); std::string CreateToken(int64_t txfee, int64_t assetsupply, std::string name, std::string description, std::vector nonfungibleData); std::string TokenTransfer(int64_t txfee, uint256 assetid, std::vector destpubkey, int64_t total); +bool ExtractTokensVinPubkeys(CTransaction tx, std::vector &vinPubkeys); +int64_t HasBurnedTokensvouts(struct CCcontract_info *cp, Eval* eval, const CTransaction& tx, uint256 reftokenid); int64_t GetTokenBalance(CPubKey pk, uint256 tokenid); UniValue TokenInfo(uint256 tokenid); From 672b3939f6eafed26ae00bf2047e603c88eb66a0 Mon Sep 17 00:00:00 2001 From: dimxy Date: Mon, 11 Feb 2019 23:27:39 +0500 Subject: [PATCH 0547/1145] added cc marker spending in rogue_register --- src/cc/CCtokens.cpp | 2 +- src/cc/rogue_rpc.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index bcebb1a09..cb8c65342 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -909,7 +909,7 @@ std::string CreateToken(int64_t txfee, int64_t tokensupply, std::string name, st mtx.vout.push_back(MakeTokensCC1vout(destEvalCode, tokensupply, mypk)); //mtx.vout.push_back(CTxOut(txfee, CScript() << ParseHex(cp->CChexstr) << OP_CHECKSIG)); // old marker (non-burnable because spending could not be validated) // NOTE: we should prevent spending fake-tokens from this marker in IsTokenvout(): - mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cp, NULL))); // new marker to token cc addr, burnable and validated + mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cp, NULL))); // new marker to token cc addr, burnable and validated, this vout must be=1 return(FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenCreateOpRet('c', Mypubkey(), name, description, nonfungibleData))); } diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e6ccc3352..14d6f4a09 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -712,6 +712,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"couldnt find enough normal funds for buyin")); if ( playertxid != zeroid ) AddNormalinputs2(mtx,txfee,10); + mtx.vin.push_back(CTxIn(playertxid, 1)); // spending cc marker as token is being burned mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); From cb0db91e9fbc4a327efd2f3f40ac987095c5aa30 Mon Sep 17 00:00:00 2001 From: dimxy Date: Mon, 11 Feb 2019 23:31:37 +0500 Subject: [PATCH 0548/1145] added playertxid check for non zero --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 14d6f4a09..8ee7a0528 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -712,7 +712,8 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"couldnt find enough normal funds for buyin")); if ( playertxid != zeroid ) AddNormalinputs2(mtx,txfee,10); - mtx.vin.push_back(CTxIn(playertxid, 1)); // spending cc marker as token is being burned + if (playertxid != zeroid) + mtx.vin.push_back(CTxIn(playertxid, 1)); // spending cc marker as token is being burned mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); From 9494baa69b1970fa4dde1cfcf1ae027bec2bee61 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 07:40:11 -1100 Subject: [PATCH 0549/1145] Tokens exemption --- src/cc/assets.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index 6f93da01b..9b859e54c 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -153,7 +153,10 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti if (strcmp(ASSETCHAINS_SYMBOL, "MGNX") == 0 && chainActive.Height() <= 210190) return true; - + + if (strcmp(ASSETCHAINS_SYMBOL, "ROGUE") == 0 && chainActive.Height() <= 12500) + return true; + if (numvouts == 0) return eval->Invalid("AssetValidate: no vouts"); From 9c47a23df909ec31b36289b193cdd4b539a2eae2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 08:03:28 -1100 Subject: [PATCH 0550/1145] Print --- src/cc/rogue_rpc.cpp | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f33d4d583..e8d6cd574 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -174,20 +174,21 @@ CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,int32_t regslot,CP return(opret); } -uint8_t rogue_highlanderopretdecode(uint256 &gametxid, int32_t ®slot, CPubKey &pk, std::vector &playerdata, CScript scriptPubKey) +uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t ®slot, CPubKey &pk, std::vector &playerdata, CScript scriptPubKey) { std::string name, description; std::vector vorigPubkey; std::vector vopretNonfungible, vopret, vopretDummy,origpubkey; - uint8_t e, f,*script; uint256 tokenid; std::vector voutPubkeys; - + uint8_t e, f,*script; std::vector voutPubkeys; + tokenid = zeroid; GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); if ( script[1] == 'c' && (f= DecodeTokenCreateOpRet(scriptPubKey,origpubkey,name,description,vopretNonfungible)) == 'c' ) { vopret = vopretNonfungible; } - else if ( script[1] == 't' && (f= DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy)) != 0 ) + else if ( script[1] != 'H' && script[1] != 'Q' && (f= DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy)) != 0 ) { + fprintf(stderr,"decode opret %c\n",script[1]); GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx vopret = vopretNonfungible; } @@ -424,14 +425,11 @@ int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firs int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPubKey &pk,std::vector &playerdata,uint256 playertxid) { - uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; + uint256 origplayertxid,tokenid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) { - //GetOpReturnData(playertx.vout[numvouts-1].scriptPubKey,vopret); - //script = (uint8_t *)vopret.data(); - if ( (f= rogue_highlanderopretdecode(gametxid,regslot,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) + if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { - //memcpy(&gametxid,script+2,sizeof(gametxid)); if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); @@ -442,7 +440,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub } else fprintf(stderr,"hash mismatch or illegal gametxid\n"); } else fprintf(stderr,"invalid game %s\n",gametxid.GetHex().c_str()); } - } + } else fprintf(stderr,"couldnt get playertxid.%s\n",playertxid.GetHex().c_str()); return(-1); } From 183a5e465bc5405136a0daf4de342d845b28ccd3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 08:06:53 -1100 Subject: [PATCH 0551/1145] +print --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e8d6cd574..776636e12 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -188,7 +188,7 @@ uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t } else if ( script[1] != 'H' && script[1] != 'Q' && (f= DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy)) != 0 ) { - fprintf(stderr,"decode opret %c\n",script[1]); + fprintf(stderr,"decode opret %c tokenid.%s\n",script[1],tokenid.GetHex().c_str()); GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx vopret = vopretNonfungible; } From 533d95de182391d72fa4d692990dcba957a4fe5e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 08:11:35 -1100 Subject: [PATCH 0552/1145] Test resin --- src/cc/assets.cpp | 4 ++-- src/cc/rogue_rpc.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index 9b859e54c..bba952782 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -154,8 +154,8 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti if (strcmp(ASSETCHAINS_SYMBOL, "MGNX") == 0 && chainActive.Height() <= 210190) return true; - if (strcmp(ASSETCHAINS_SYMBOL, "ROGUE") == 0 && chainActive.Height() <= 12500) - return true; + //if (strcmp(ASSETCHAINS_SYMBOL, "ROGUE") == 0 && chainActive.Height() <= 12500) + // return true; if (numvouts == 0) return eval->Invalid("AssetValidate: no vouts"); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 776636e12..09027d9f1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -433,7 +433,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); - if ( playertx.vin[1].prevout.hash == gametxid && rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid) == 0 ) + if ( (tokenid != zeroid || playertx.vin[1].prevout.hash == gametxid) && rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid) == 0 ) { // if registertxid has vin from pk, it can be used return(0); From 7a4072b4f1496f52f013d68d3ea1dd2a9679ba11 Mon Sep 17 00:00:00 2001 From: dimxy Date: Tue, 12 Feb 2019 00:14:08 +0500 Subject: [PATCH 0553/1145] test_burntx added --- src/rpc/server.cpp | 2 ++ src/rpc/server.h | 2 ++ src/wallet/rpcwallet.cpp | 30 ++++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+) diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index 208b3cf02..77c714531 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -539,6 +539,8 @@ static const CRPCCommand vRPCCommands[] = { "hidden", "setmocktime", &setmocktime, true }, { "hidden", "test_ac", &test_ac, true }, { "hidden", "test_heirmarker", &test_heirmarker, true }, + { "hidden", "test_burntx", &test_burntx, true }, + #ifdef ENABLE_WALLET /* Wallet */ diff --git a/src/rpc/server.h b/src/rpc/server.h index b812ccc9d..9682cbf5c 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -474,5 +474,7 @@ extern UniValue paxwithdraw(const UniValue& params, bool fHelp); // test rpc: extern UniValue test_ac(const UniValue& params, bool fHelp); extern UniValue test_heirmarker(const UniValue& params, bool fHelp); +extern UniValue test_burntx(const UniValue& params, bool fHelp); + #endif // BITCOIN_RPCSERVER_H diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 0087abf58..f20b1cb5c 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -7818,3 +7818,33 @@ UniValue test_heirmarker(const UniValue& params, bool fHelp) return(FinalizeCCTx(0, cp, mtx, myPubkey, 10000, opret)); } +UniValue test_burntx(const UniValue& params, bool fHelp) +{ + // make fake token tx: + struct CCcontract_info *cp, C; + + if (fHelp || (params.size() != 1)) + throw runtime_error("incorrect params\n"); + if (ensure_CCrequirements(EVAL_TOKENS) < 0) + throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + + uint256 tokenid = Parseuint256((char *)params[0].get_str().c_str()); + + CPubKey myPubkey = pubkey2pk(Mypubkey()); + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + + int64_t normalInputs = AddNormalinputs(mtx, myPubkey, 10000, 60); + if (normalInputs < 10000) + throw runtime_error("not enough normals\n"); + + CPubKey burnpk = pubkey2pk(ParseHex(CC_BURNPUBKEY)); + + mtx.vin.push_back(CTxIn(tokenid, 1)); + mtx.vout.push_back(MakeTokensCC1vout(EVAL_TOKENS, 1, burnpk)); + + std::vector voutPubkeys; + voutPubkeys.push_back(burnpk); + + cp = CCinit(&C, EVAL_TOKENS); + return(FinalizeCCTx(0, cp, mtx, myPubkey, 10000, EncodeTokenOpRet(tokenid, voutPubkeys, CScript()))); +} From 706d798676c223b72ca750d6b4e27fc41916ea5d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 08:18:26 -1100 Subject: [PATCH 0554/1145] Restore exemption --- src/cc/assets.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index bba952782..9b859e54c 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -154,8 +154,8 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti if (strcmp(ASSETCHAINS_SYMBOL, "MGNX") == 0 && chainActive.Height() <= 210190) return true; - //if (strcmp(ASSETCHAINS_SYMBOL, "ROGUE") == 0 && chainActive.Height() <= 12500) - // return true; + if (strcmp(ASSETCHAINS_SYMBOL, "ROGUE") == 0 && chainActive.Height() <= 12500) + return true; if (numvouts == 0) return eval->Invalid("AssetValidate: no vouts"); From 431562b77d4c76c0115035737474f4ee7682c767 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 08:24:41 -1100 Subject: [PATCH 0555/1145] Rogue exemption in tokens --- src/cc/CCtokens.cpp | 3 ++- src/cc/assets.cpp | 5 +---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index eb802b65d..e15cdbeb9 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -238,7 +238,8 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & char destaddr[64], origaddr[64], CCaddr[64]; std::vector voutTokenPubkeys; - //return true; + if (strcmp(ASSETCHAINS_SYMBOL, "ROGUE") == 0 && chainActive.Height() <= 12500) + return true; numvins = tx.vin.size(); numvouts = tx.vout.size(); diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index 9b859e54c..18f93f903 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -153,10 +153,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti if (strcmp(ASSETCHAINS_SYMBOL, "MGNX") == 0 && chainActive.Height() <= 210190) return true; - - if (strcmp(ASSETCHAINS_SYMBOL, "ROGUE") == 0 && chainActive.Height() <= 12500) - return true; - + if (numvouts == 0) return eval->Invalid("AssetValidate: no vouts"); From 1754fb8821a73fc057d000a9f1ca64b0a100315c Mon Sep 17 00:00:00 2001 From: dimxy Date: Tue, 12 Feb 2019 00:47:19 +0500 Subject: [PATCH 0556/1145] added CCaddr2set for test_burntx --- src/wallet/rpcwallet.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index f20b1cb5c..e10ba621c 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -7846,5 +7846,11 @@ UniValue test_burntx(const UniValue& params, bool fHelp) voutPubkeys.push_back(burnpk); cp = CCinit(&C, EVAL_TOKENS); + + uint8_t tokenpriv[33]; + char unspendableTokenAddr[64]; + CPubKey unspPk = GetUnspendable(cp, tokenpriv); + GetCCaddress(cp, unspendableTokenAddr, unspPk); + CCaddr2set(cp, EVAL_TOKENS, unspPk, tokenpriv, unspendableTokenAddr); return(FinalizeCCTx(0, cp, mtx, myPubkey, 10000, EncodeTokenOpRet(tokenid, voutPubkeys, CScript()))); } From 520074335a37b662d2ed03b2eb4885d0cd300b5a Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 08:47:53 -1100 Subject: [PATCH 0557/1145] 'T' in out 1 --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 09027d9f1..61e70547f 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -995,7 +995,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) txid = it->first.txhash; vout = (int32_t)it->first.index; //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); - if ( it->second.satoshis != 1 || vout != 0 ) + if ( it->second.satoshis != 1 || vout < 2 ) continue; if ( rogue_playerdata(cp,gametxid,pk,playerdata,txid) == 0 )//&& pk == mypk ) { From d4fd4ac5f1290f17f2ac125798adf199f619f15e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 08:49:47 -1100 Subject: [PATCH 0558/1145] >1 --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 61e70547f..be66eb4f8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -995,7 +995,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) txid = it->first.txhash; vout = (int32_t)it->first.index; //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); - if ( it->second.satoshis != 1 || vout < 2 ) + if ( it->second.satoshis != 1 || vout > 1 ) continue; if ( rogue_playerdata(cp,gametxid,pk,playerdata,txid) == 0 )//&& pk == mypk ) { From 5e6965b60ad848f233eca87071e7bf750bfae3d9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 08:56:03 -1100 Subject: [PATCH 0559/1145] Deference tokenid --- src/cc/rogue_rpc.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index be66eb4f8..68eed4439 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -430,6 +430,15 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPub { if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { + if ( tokenid != zeroid ) + { + playertxid = tokenid; + if ( GetTransaction(playertxid,playertx,hashBlock,false) == 0 || (numvouts= playertx.vout.size()) <= 0 ) + { + fprintf(stderr,"couldnt get tokenid.%s\n",playertxid.GetHex().c_str()); + return(-2); + } + } if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); From 34b91c2d43f5a8bf787a323553a68f6b70a6bf64 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 09:01:20 -1100 Subject: [PATCH 0560/1145] Tokenid --- src/cc/rogue_rpc.cpp | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 68eed4439..03f073ecb 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -362,7 +362,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa } else return(-1); } -UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid) +UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint256 tokenid) { int32_t i; struct rogue_player P; char packitemstr[512],*datastr; UniValue obj(UniValue::VOBJ),a(UniValue::VARR); memset(&P,0,sizeof(P)); @@ -383,6 +383,8 @@ UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid) a.push_back(packitemstr); } obj.push_back(Pair("playertxid",playertxid.GetHex())); + if ( tokenid != zeroid ) + obj.push_back(Pair("tokenid",tokenid.GetHex())); obj.push_back(Pair("data",datastr)); free(datastr); obj.push_back(Pair("pack",a)); @@ -423,9 +425,9 @@ int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firs origplayergame is the gametxid that ends up being won by the highlander and they are linked directly as the highlander tx spends gametxid.vout0 */ -int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,CPubKey &pk,std::vector &playerdata,uint256 playertxid) +int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint256 &tokenid,CPubKey &pk,std::vector &playerdata,uint256 playertxid) { - uint256 origplayertxid,tokenid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; + uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) { if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) @@ -465,7 +467,7 @@ int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,uint25 int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **keystrokesp,int32_t &numkeys,int32_t ®slot,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr,int32_t &numplayers) { - int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 spenttxid,tokenid,hashBlock,txid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; + int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 tid,spenttxid,tokenid,hashBlock,txid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; numkeys = numplayers = 0; playertxid = zeroid; for (i=0; i 0 ) - obj.push_back(Pair("player",rogue_playerobj(playerdata,playertxid))); + obj.push_back(Pair("player",rogue_playerobj(playerdata,playertxid,tokenid))); } else fprintf(stderr,"findbaton err.%d\n",retval); } @@ -662,7 +664,7 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); std::vector playerdata; uint256 playertxid,origplayergame;int32_t n; CPubKey pk; bits256 t; + UniValue result(UniValue::VOBJ); std::vector playerdata; uint256 playertxid,tokenid,origplayergame;int32_t n; CPubKey pk; bits256 t; result.push_back(Pair("result","success")); rogue_univalue(result,"playerinfo",-1,-1); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -670,9 +672,9 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( n > 0 ) { playertxid = juint256(jitem(params,0)); - if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) + if ( rogue_playerdata(cp,origplayergame,tokenid,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"invalid playerdata")); - result.push_back(Pair("player",rogue_playerobj(playerdata,playertxid))); + result.push_back(Pair("player",rogue_playerobj(playerdata,playertxid,tokenid))); } else return(cclib_error(result,"no playertxid")); return(result); } else return(cclib_error(result,"couldnt reparse params")); @@ -686,7 +688,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vin3+ -> buyin // vout0 -> keystrokes/completion baton CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 gametxid,origplayergame,playertxid,hashBlock; int32_t err,maxplayers,gameheight,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk,burnpk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx; bits256 t; + UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 tokenid,gametxid,origplayergame,playertxid,hashBlock; int32_t err,maxplayers,gameheight,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk,burnpk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx; bits256 t; if ( txfee == 0 ) txfee = 10000; @@ -705,7 +707,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( n > 1 ) { playertxid = juint256(jitem(params,1)); - if ( rogue_playerdata(cp,origplayergame,pk,playerdata,playertxid) < 0 ) + if ( rogue_playerdata(cp,origplayergame,tokenid,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"couldnt extract valid playerdata")); } rogue_univalue(result,0,maxplayers,buyin); @@ -992,7 +994,7 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR); int64_t buyin; uint256 gametxid,txid,hashBlock; CTransaction playertx,tx; int32_t maxplayers,vout,numvouts; std::vector playerdata; CPubKey roguepk,mypk,pk; char coinaddr[64]; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); int64_t buyin; uint256 tokenid,gametxid,txid,hashBlock; CTransaction playertx,tx; int32_t maxplayers,vout,numvouts; std::vector playerdata; CPubKey roguepk,mypk,pk; char coinaddr[64]; std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); mypk = pubkey2pk(Mypubkey()); @@ -1006,9 +1008,9 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( it->second.satoshis != 1 || vout > 1 ) continue; - if ( rogue_playerdata(cp,gametxid,pk,playerdata,txid) == 0 )//&& pk == mypk ) + if ( rogue_playerdata(cp,gametxid,tokenid,pk,playerdata,txid) == 0 )//&& pk == mypk ) { - a.push_back(rogue_playerobj(playerdata,txid)); + a.push_back(rogue_playerobj(playerdata,txid,tokenid)); //result.push_back(Pair("playerdata",rogue_playerobj(playerdata))); } } From e15764f36293ac7a1bdc8b92a86b7ab3bfeb0d24 Mon Sep 17 00:00:00 2001 From: dimxy Date: Tue, 12 Feb 2019 01:20:21 +0500 Subject: [PATCH 0561/1145] added vin for vout0 in test_burntx --- src/wallet/rpcwallet.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index e10ba621c..a8bcf2660 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -7839,6 +7839,7 @@ UniValue test_burntx(const UniValue& params, bool fHelp) CPubKey burnpk = pubkey2pk(ParseHex(CC_BURNPUBKEY)); + mtx.vin.push_back(CTxIn(tokenid, 0)); mtx.vin.push_back(CTxIn(tokenid, 1)); mtx.vout.push_back(MakeTokensCC1vout(EVAL_TOKENS, 1, burnpk)); From 1fce79e677c1a5c78a91d2d2abb4c356d3f815ad Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 09:20:22 -1100 Subject: [PATCH 0562/1145] Test --- src/cc/rogue_rpc.cpp | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 03f073ecb..cd035f6f7 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -115,8 +115,8 @@ */ // todo: -// convert playertxid to the original playertxid // verify keystrokes tx is in mempool and confirmed +// chaining when mempool tx sometimes infinite loops //////////////////////// start of CClib interface //./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey=03951a6f7967ad784453116bc55cd30c54f91ea8a5b1e9b04d6b29cfd6b395ba6c -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc > /dev/null & @@ -128,7 +128,7 @@ // ./rogue gui -> creates keystroke files // ./c cclib register 17 \"[%226d3243c6e5ab383898b28a87e01f6c00b5bdd9687020f17f5caacc8a61febd19%22,%222475182f9d5169d8a3249d17640e4eccd90f4ee43ab04791129b0fa3f177b14a%22]\" // ./c cclib bailout 17 \"[%226d3243c6e5ab383898b28a87e01f6c00b5bdd9687020f17f5caacc8a61febd19%22]\" - +// ./komodo-cli -ac_name=ROGUE cclib register 17 \"[%22a898f4ceef7647ba113b9f3c24ef045f5d134935a3b09bdd1a997b9d474f4c1b%22,%22f11d0cb4e2e4c21f029a1146f8e5926f11456885b7ab7d665096f5efedec8ea0%22]\" #define MAXPACK 23 struct rogue_packitem @@ -455,12 +455,12 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint return(-1); } -int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,uint256 origplayergame) +int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,int32_t vout,uint256 origplayergame) { int64_t txfee = 10000; - if ( CCgettxout(playertxid,0,1) == 1 ) // not sure if this is enough validation + if ( CCgettxout(playertxid,vout,1) == 1 ) // not sure if this is enough validation { - mtx.vin.push_back(CTxIn(playertxid,0,CScript())); + mtx.vin.push_back(CTxIn(playertxid,vout,CScript())); return(0); } else return(-1); } @@ -688,7 +688,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vin3+ -> buyin // vout0 -> keystrokes/completion baton CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 tokenid,gametxid,origplayergame,playertxid,hashBlock; int32_t err,maxplayers,gameheight,n,numvouts; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk,burnpk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx; bits256 t; + UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 tokenid,gametxid,origplayergame,playertxid,hashBlock; int32_t err,maxplayers,gameheight,n,numvouts,vout=0; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk,burnpk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx; bits256 t; if ( txfee == 0 ) txfee = 10000; @@ -696,7 +696,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) burnpk = pubkey2pk(ParseHex(CC_BURNPUBKEY)); roguepk = GetUnspendable(cp,0); rogue_univalue(result,"register",-1,-1); - playertxid = zeroid; + playertxid = tokenid = zeroid; if ( (params= cclib_reparse(&n,params)) != 0 ) { if ( n > 0 ) @@ -709,6 +709,8 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) playertxid = juint256(jitem(params,1)); if ( rogue_playerdata(cp,origplayergame,tokenid,pk,playerdata,playertxid) < 0 ) return(cclib_error(result,"couldnt extract valid playerdata")); + if ( tokenid != zeroid ) + vout = 1; } rogue_univalue(result,0,maxplayers,buyin); GetCCaddress1of2(cp,coinaddr,roguepk,mypk); @@ -716,7 +718,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"already registered")); if ( (inputsum= rogue_registrationbaton(mtx,gametxid,tx,maxplayers)) != ROGUE_REGISTRATIONSIZE ) return(cclib_error(result,"couldnt find available registration baton")); - else if ( playertxid != zeroid && rogue_playerdataspend(mtx,playertxid,origplayergame) < 0 ) + else if ( playertxid != zeroid && rogue_playerdataspend(mtx,playertxid,vout,origplayergame) < 0 ) return(cclib_error(result,"couldnt find playerdata to spend")); else if ( buyin > 0 && AddNormalinputs(mtx,mypk,buyin,64) < buyin ) return(cclib_error(result,"couldnt find enough normal funds for buyin")); @@ -727,21 +729,21 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode, 1, burnpk)); - std::vector vopretExtra; uint8_t e, funcid; uint256 tokenid; std::vector voutPubkeys, voutPubkeysEmpty; int32_t didtx = 0; + std::vector vopretExtra; uint8_t e, funcid; uint256 tid; std::vector voutPubkeys, voutPubkeysEmpty; int32_t didtx = 0; CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { //fprintf(stderr,"playertxid.%s\n",playertxid.GetHex().c_str()); voutPubkeysEmpty.push_back(burnpk); - if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) + if ( GetTransaction(tokenid == zeroid ? playertxid : tokenid,playertx,hashBlock,false) != 0 ) { - if ( (funcid= DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tokenid, voutPubkeys, vopretExtra)) != 0) + if ( (funcid= DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tid, voutPubkeys, vopretExtra)) != 0) { // if token in the opret didtx = 1; if ( funcid == 'c' ) - tokenid = playertxid; + tid = tokenid == zeroid ? playertxid : tokenid; rawtx = FinalizeCCTx(0, cp, mtx, mypk, txfee, - EncodeTokenOpRet(tokenid, voutPubkeysEmpty /*=never spent*/, opretRegister)); + EncodeTokenOpRet(tid, voutPubkeysEmpty /*=never spent*/, opretRegister)); } } } From 0a9f2e0b8e3ea2f41e0791fda7ffd285cb18c902 Mon Sep 17 00:00:00 2001 From: dimxy Date: Tue, 12 Feb 2019 01:29:49 +0500 Subject: [PATCH 0563/1145] added additionalEvalcode2 in test_burntx --- src/wallet/rpcwallet.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index a8bcf2660..51d7cb6ad 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -7848,6 +7848,11 @@ UniValue test_burntx(const UniValue& params, bool fHelp) cp = CCinit(&C, EVAL_TOKENS); + std::vector vopret; + GetNonfungibleData(tokenid, vopret); + if (vopret.size() > 0) + cp->additionalTokensEvalcode2 = vopret.begin()[0]; + uint8_t tokenpriv[33]; char unspendableTokenAddr[64]; CPubKey unspPk = GetUnspendable(cp, tokenpriv); From d889948d52be7f825d978cf8161b396ef21e4aa7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 09:31:07 -1100 Subject: [PATCH 0564/1145] Fix rogue_registeropretdecode --- src/cc/rogue_rpc.cpp | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index cd035f6f7..273042685 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -188,7 +188,7 @@ uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t } else if ( script[1] != 'H' && script[1] != 'Q' && (f= DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy)) != 0 ) { - fprintf(stderr,"decode opret %c tokenid.%s\n",script[1],tokenid.GetHex().c_str()); + //fprintf(stderr,"decode opret %c tokenid.%s\n",script[1],tokenid.GetHex().c_str()); GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx vopret = vopretNonfungible; } @@ -213,7 +213,29 @@ uint8_t rogue_keystrokesopretdecode(uint256 &gametxid,uint256 &batontxid,CPubKey uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &playertxid,CScript scriptPubKey) { - std::vector vopret,vopret2; uint8_t e,f; std::vector voutPubkeys; + std::string name, description; std::vector vorigPubkey; + std::vector vopretNonfungible, vopret, vopretDummy,origpubkey; + uint8_t e, f,*script; std::vector voutPubkeys; + tokenid = zeroid; + GetOpReturnData(scriptPubKey, vopret); + script = (uint8_t *)vopret.data(); + if ( script[1] == 'c' && (f= DecodeTokenCreateOpRet(scriptPubKey,origpubkey,name,description,vopretNonfungible)) == 'c' ) + { + vopret = vopretNonfungible; + } + else if ( script[1] != 'R' && (f= DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy)) != 0 ) + { + //fprintf(stderr,"decode opret %c tokenid.%s\n",script[1],tokenid.GetHex().c_str()); + GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx + vopret = vopretNonfungible; + } + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) + { + return(f); + } + fprintf(stderr,"e.%d f.%c game.%s playertxid.%s\n",e,f,gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); + + /*std::vector vopret,vopret2; uint8_t e,f; std::vector voutPubkeys; GetOpReturnData(scriptPubKey,vopret); tokenid = zeroid; if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) @@ -230,7 +252,7 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl playertxid = tokenid; fprintf(stderr,"e.%d vs %d, f %c, gametxid.%s player.%s\n",e,EVAL_ROGUE,f,gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); return(0); - } + }*/ return(0); } @@ -443,7 +465,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint } if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { - fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); + //fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); if ( (tokenid != zeroid || playertx.vin[1].prevout.hash == gametxid) && rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid) == 0 ) { // if registertxid has vin from pk, it can be used From d2e4067fad7c54c67316b6aab0e1521ddee7a27d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 09:36:11 -1100 Subject: [PATCH 0565/1145] Gametxid --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 273042685..b93e146ce 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -515,8 +515,9 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke { numvouts = matchtx.vout.size(); //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); - if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' && txid == gametxid ) + if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { + fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s\n",token.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str()); if ( tokenid != zeroid ) playertxid = tokenid; if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,tid,pk,playerdata,playertxid) == 0 ) From 70f6fe55d4eced7db597950f8e631a2ccaa9f615 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 09:37:23 -1100 Subject: [PATCH 0566/1145] Tokens --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b93e146ce..3b615aabf 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -517,7 +517,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { - fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s\n",token.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str()); + fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str()); if ( tokenid != zeroid ) playertxid = tokenid; if ( playertxid == zeroid || rogue_playerdata(cp,origplayergame,tid,pk,playerdata,playertxid) == 0 ) From 0b8fffc5010fbcb7b50cd2aca0c9d65dfd4ebda0 Mon Sep 17 00:00:00 2001 From: dimxy Date: Tue, 12 Feb 2019 01:40:59 +0500 Subject: [PATCH 0567/1145] logging corrected --- src/cc/CCtokens.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index cb8c65342..6e1afbf33 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -866,7 +866,7 @@ int64_t HasBurnedTokensvouts(struct CCcontract_info *cp, Eval* eval, const CTran burnedAmount += tx.vout[i].nValue; } } - LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "HasBurnedTokensvouts() no burned vouts evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "HasBurnedTokensvouts() total burned=" << burnedAmount << " evalCode=" << (int)evalCode << " evalCode2=" << (int)evalCode2 << " for txid=" << tx.GetHash().GetHex() << " for tokenid=" << reftokenid.GetHex() << std::endl); } } From 9fdb634a4ea378e4887cb73ea2b09c2e3c7dede5 Mon Sep 17 00:00:00 2001 From: dimxy Date: Tue, 12 Feb 2019 02:01:52 +0500 Subject: [PATCH 0568/1145] cc log levels corr --- src/cc/CCinclude.h | 9 +++++---- src/cc/CCtokens.cpp | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index 6018114a0..a2d782c3f 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -266,6 +266,7 @@ UniValue ValueFromAmount(const CAmount& amount); #define CCLOG_DEBUG1 1 #define CCLOG_DEBUG2 2 #define CCLOG_DEBUG3 3 +#define CCLOG_MAXLEVEL 3 template inline void CCLogPrintStream(const char *category, int level, T print_to_stream) { @@ -273,10 +274,10 @@ inline void CCLogPrintStream(const char *category, int level, T print_to_stream) print_to_stream(stream); if (level < 0) level = 0; - if (level > 3) - level = 3; - for (int i = 0; i < level; i++) - if (LogAcceptCategory((std::string(category) + (level > 0 ? std::string("-") + std::to_string(level) : std::string(""))).c_str())) { + if (level > CCLOG_MAXLEVEL) + level = CCLOG_MAXLEVEL; + for (int i = level; i <= CCLOG_MAXLEVEL; i++) + if (LogAcceptCategory((std::string(category) + (i > 0 ? std::string("-") + std::to_string(i) : std::string(""))).c_str())) { LogPrintStr(stream.str()); break; } diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index 6e1afbf33..c6e2498cf 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -178,7 +178,7 @@ uint8_t DecodeTokenOpRet(const CScript scriptPubKey, uint8_t &evalCodeTokens, ui return (uint8_t)0; funcId = script[1]; - LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "DecodeTokenOpRet decoded funcId=" << (char)(funcId?funcId:' ')); + LOGSTREAM((char *)"cctokens", CCLOG_DEBUG2, stream << "DecodeTokenOpRet decoded funcId=" << (char)(funcId?funcId:' ') << std::endl); switch( funcId ) { From f50b207e6203d0151740995f9fd4d502001e4c29 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 13:55:43 -1100 Subject: [PATCH 0569/1145] Spend right playertxid vout --- src/cc/rogue_rpc.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 75966ce70..f85c07319 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -225,7 +225,7 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl } else if ( script[1] != 'R' && (f= DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy)) != 0 ) { - //fprintf(stderr,"decode opret %c tokenid.%s\n",script[1],tokenid.GetHex().c_str()); + fprintf(stderr,"decode opret %c tokenid.%s\n",script[1],tokenid.GetHex().c_str()); GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx vopret = vopretNonfungible; } @@ -747,8 +747,8 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"couldnt find enough normal funds for buyin")); if ( playertxid != zeroid ) AddNormalinputs2(mtx,txfee,10); - if (playertxid != zeroid) - mtx.vin.push_back(CTxIn(playertxid, 1)); // spending cc marker as token is being burned + if (playertxid != zeroid ) + mtx.vin.push_back(CTxIn(playertxid, vout)); // spending cc marker as token is being burned mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); @@ -760,7 +760,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { //fprintf(stderr,"playertxid.%s\n",playertxid.GetHex().c_str()); voutPubkeysEmpty.push_back(burnpk); - if ( GetTransaction(tokenid == zeroid ? playertxid : tokenid,playertx,hashBlock,false) != 0 ) + if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) { if ( (funcid= DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tid, voutPubkeys, vopretExtra)) != 0) { // if token in the opret From be2a5fd6bc2f7381ddd9df1f0ef5fd5544138498 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 13:59:02 -1100 Subject: [PATCH 0570/1145] Resolve conflict --- src/wallet/rpcwallet.cpp | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 0077b198d..a2a66a610 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -6204,19 +6204,12 @@ UniValue gatewaysinfo(const UniValue& params, bool fHelp) UniValue gatewaysbind(const UniValue& params, bool fHelp) { -<<<<<<< HEAD - UniValue result(UniValue::VOBJ); uint256 tokenid,oracletxid; int32_t i; int64_t totalsupply; std::vector pubkeys; uint8_t M,N; std::string hex,coin; std::vector pubkey; - if ( fHelp || params.size() < 6 ) - throw runtime_error("gatewaysbind tokenid oracletxid coin tokensupply M N pubkey(s)\n"); - if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) -======= UniValue result(UniValue::VOBJ); uint256 tokenid,oracletxid; int32_t i; int64_t totalsupply; std::vector pubkeys; uint8_t M,N,p1,p2,p3,p4=0; std::string hex,coin; std::vector pubkey; if ( fHelp || params.size() < 9 ) throw runtime_error("gatewaysbind tokenid oracletxid coin tokensupply M N pubkey(s) pubtype p2shtype wiftype [taddr]\n"); - if ( ensure_CCrequirements() < 0 ) ->>>>>>> FSM + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); From 6c21d8affa6c20e0e953c65373639843f729e2c0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 14:08:52 -1100 Subject: [PATCH 0571/1145] EVAL_GATEWAYS --- src/wallet/rpcwallet.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index a2a66a610..c0f9dc297 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -6154,7 +6154,7 @@ UniValue gatewaysexternaladdress(const UniValue& params, bool fHelp) if ( fHelp || params.size() != 2) throw runtime_error("gatewaysexternaladdress bindtxid pubkey\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -6169,7 +6169,7 @@ UniValue gatewaysdumpprivkey(const UniValue& params, bool fHelp) if ( fHelp || params.size() != 2) throw runtime_error("gatewaysexternaladdress bindtxid address\n"); - if ( ensure_CCrequirements() < 0 ) + if ( ensure_CCrequirements(EVAL_GATEWAYS) < 0 ) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); LOCK2(cs_main, pwalletMain->cs_wallet); bindtxid = Parseuint256((char *)params[0].get_str().c_str()); From 10320c4db1cb864adfa000b481468abd6578464e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 14:46:32 -1100 Subject: [PATCH 0572/1145] Revert out change --- src/cc/rogue_rpc.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f85c07319..9dbd52070 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -746,9 +746,10 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) else if ( buyin > 0 && AddNormalinputs(mtx,mypk,buyin,64) < buyin ) return(cclib_error(result,"couldnt find enough normal funds for buyin")); if ( playertxid != zeroid ) - AddNormalinputs2(mtx,txfee,10); - if (playertxid != zeroid ) - mtx.vin.push_back(CTxIn(playertxid, vout)); // spending cc marker as token is being burned + { + // AddNormalinputs2(mtx,txfee,10); + mtx.vin.push_back(CTxIn(playertxid,1)); // spending cc marker as token is being burned + } mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); CCaddr1of2set(cp,roguepk,roguepk,cp->CCpriv,destaddr); From 510c6d807cc289f938c8521c68c03d71b891b074 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 14:52:32 -1100 Subject: [PATCH 0573/1145] Move around bouts --- src/cc/rogue_rpc.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9dbd52070..bf7ba7702 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -711,7 +711,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vin3+ -> buyin // vout0 -> keystrokes/completion baton CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 tokenid,gametxid,origplayergame,playertxid,hashBlock; int32_t err,maxplayers,gameheight,n,numvouts,vout=0; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk,burnpk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx; bits256 t; + UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 tokenid,gametxid,origplayergame,playertxid,hashBlock; int32_t err,maxplayers,gameheight,n,numvouts,vout=1; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk,burnpk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx; bits256 t; if ( txfee == 0 ) txfee = 10000; @@ -748,7 +748,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( playertxid != zeroid ) { // AddNormalinputs2(mtx,txfee,10); - mtx.vin.push_back(CTxIn(playertxid,1)); // spending cc marker as token is being burned + mtx.vin.push_back(CTxIn(playertxid,0)); // spending cc marker as token is being burned } mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); @@ -902,6 +902,8 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else { + cpTokens = CCinit(&tokensC, EVAL_TOKENS); + mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cpTokens, NULL))); // marker to token cc addr, burnable and validated mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,1,mypk)); fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); cashout = (uint64_t)P.gold * mult; @@ -920,8 +922,6 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } } mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-3*txfee),roguepk)); - cpTokens = CCinit(&tokensC, EVAL_TOKENS); - mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cpTokens, NULL))); // marker to token cc addr, burnable and validated Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); From 7bd0acd56c33ca45ec5b00e3e6680d9e3f8c7b3e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 15:13:16 -1100 Subject: [PATCH 0574/1145] Spend burn marker --- src/cc/rogue_rpc.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index bf7ba7702..03045a4b9 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -747,8 +747,13 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"couldnt find enough normal funds for buyin")); if ( playertxid != zeroid ) { - // AddNormalinputs2(mtx,txfee,10); - mtx.vin.push_back(CTxIn(playertxid,0)); // spending cc marker as token is being burned + mtx.vin.push_back(CTxIn(playertxid,0)); // spending cc marker as token is burned + char unspendableTokenAddr[64]; uint8_t tokenpriv[32]; struct CCcontract_info *cpTokens, tokensC; + cpTokens = CCinit(&tokensC, EVAL_TOKENS); + CPubKey unspPk = GetUnspendable(cpTokens, tokenpriv); + GetCCaddress(cpTokens, unspendableTokenAddr, unspPk); + CCaddr2set(cpTokens, EVAL_TOKENS, unspPk, tokenpriv, unspendableTokenAddr); + fprintf(stderr,"destaddr.(%s)\n",destaddr); } mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); @@ -903,7 +908,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param else { cpTokens = CCinit(&tokensC, EVAL_TOKENS); - mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cpTokens, NULL))); // marker to token cc addr, burnable and validated + mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cpTokens,NULL))); // marker to token cc addr, burnable and validated mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,1,mypk)); fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); cashout = (uint64_t)P.gold * mult; From ad65f834dd82b9fbf3ee2ca9fbd47003deb59584 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 15:15:51 -1100 Subject: [PATCH 0575/1145] +print --- src/cc/CCtx.cpp | 2 +- src/cc/rogue_rpc.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index 63f104896..82c12c37f 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -191,7 +191,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran // check if this is the 2nd additional evalcode + 'unspendable' cc addr: else if ( strcmp(destaddr, cp->unspendableaddr2) == 0) { - //fprintf(stderr,"FinalizeCCTx() matched %s unspendable2!\n",cp->unspendableaddr2); + fprintf(stderr,"FinalizeCCTx() matched %s unspendable2!\n",cp->unspendableaddr2); privkey = cp->unspendablepriv2; if( othercond2 == 0 ) othercond2 = MakeCCcond1(cp->unspendableEvalcode2, cp->unspendablepk2); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 03045a4b9..bf9611215 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -753,7 +753,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) CPubKey unspPk = GetUnspendable(cpTokens, tokenpriv); GetCCaddress(cpTokens, unspendableTokenAddr, unspPk); CCaddr2set(cpTokens, EVAL_TOKENS, unspPk, tokenpriv, unspendableTokenAddr); - fprintf(stderr,"destaddr.(%s)\n",destaddr); + fprintf(stderr,"destaddr.(%s)\n",unspendableTokenAddr); } mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); From 4ceb869bef508c61ab0abbb63ccbf979de14cdad Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 15:20:54 -1100 Subject: [PATCH 0576/1145] Test --- src/cc/CCtx.cpp | 2 +- src/cc/rogue_rpc.cpp | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index 82c12c37f..198fb0908 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -156,7 +156,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran else { Getscriptaddress(destaddr,vintx.vout[utxovout].scriptPubKey); - //fprintf(stderr,"FinalizeCCTx() vin.%d is CC %.8f -> (%s)\n",i,(double)utxovalues[i]/COIN,destaddr); + fprintf(stderr,"FinalizeCCTx() vin.%d is CC %.8f -> (%s) vs %s\n",i,(double)utxovalues[i]/COIN,destaddr,cp->unspendableaddr2); //std::cerr << "FinalizeCCtx() searching destaddr=" << destaddr << " for vin[" << i << "] satoshis=" << utxovalues[i] << std::endl; if( strcmp(destaddr, myaddr) == 0 ) { diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index bf9611215..9c99528ce 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -752,8 +752,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) cpTokens = CCinit(&tokensC, EVAL_TOKENS); CPubKey unspPk = GetUnspendable(cpTokens, tokenpriv); GetCCaddress(cpTokens, unspendableTokenAddr, unspPk); - CCaddr2set(cpTokens, EVAL_TOKENS, unspPk, tokenpriv, unspendableTokenAddr); - fprintf(stderr,"destaddr.(%s)\n",unspendableTokenAddr); + CCaddr2set(cp, EVAL_TOKENS, unspPk, tokenpriv, unspendableTokenAddr); } mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,buyin + inputsum - txfee,roguepk,mypk)); GetCCaddress1of2(cp,destaddr,roguepk,roguepk); From 5a8b054ede1fa4903c99387a378383c3ac45561c Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 15:27:49 -1100 Subject: [PATCH 0577/1145] Map R --- src/cc/CCtx.cpp | 4 ++-- src/cc/rogue_rpc.cpp | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/CCtx.cpp b/src/cc/CCtx.cpp index 198fb0908..0f7e103f9 100644 --- a/src/cc/CCtx.cpp +++ b/src/cc/CCtx.cpp @@ -156,7 +156,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran else { Getscriptaddress(destaddr,vintx.vout[utxovout].scriptPubKey); - fprintf(stderr,"FinalizeCCTx() vin.%d is CC %.8f -> (%s) vs %s\n",i,(double)utxovalues[i]/COIN,destaddr,cp->unspendableaddr2); + //fprintf(stderr,"FinalizeCCTx() vin.%d is CC %.8f -> (%s) vs %s\n",i,(double)utxovalues[i]/COIN,destaddr,cp->unspendableaddr2); //std::cerr << "FinalizeCCtx() searching destaddr=" << destaddr << " for vin[" << i << "] satoshis=" << utxovalues[i] << std::endl; if( strcmp(destaddr, myaddr) == 0 ) { @@ -191,7 +191,7 @@ std::string FinalizeCCTx(uint64_t CCmask,struct CCcontract_info *cp,CMutableTran // check if this is the 2nd additional evalcode + 'unspendable' cc addr: else if ( strcmp(destaddr, cp->unspendableaddr2) == 0) { - fprintf(stderr,"FinalizeCCTx() matched %s unspendable2!\n",cp->unspendableaddr2); + //fprintf(stderr,"FinalizeCCTx() matched %s unspendable2!\n",cp->unspendableaddr2); privkey = cp->unspendablepriv2; if( othercond2 == 0 ) othercond2 = MakeCCcond1(cp->unspendableEvalcode2, cp->unspendablepk2); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9c99528ce..d6660dbfa 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -215,7 +215,7 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl { std::string name, description; std::vector vorigPubkey; std::vector vopretNonfungible, vopret, vopretDummy,origpubkey; - uint8_t e, f,*script; std::vector voutPubkeys; + uint8_t e, f,*script,flag = 0; std::vector voutPubkeys; tokenid = zeroid; GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); @@ -228,8 +228,9 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl fprintf(stderr,"decode opret %c tokenid.%s\n",script[1],tokenid.GetHex().c_str()); GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx vopret = vopretNonfungible; + flag = 1; } - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && (flag != 0 || f == 'R') ) { return(f); } From 27341371d440dc468d538ad7649d00b2a111ec5c Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 15:36:12 -1100 Subject: [PATCH 0578/1145] Test --- src/cc/rogue_rpc.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d6660dbfa..53d18eff9 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -215,7 +215,7 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl { std::string name, description; std::vector vorigPubkey; std::vector vopretNonfungible, vopret, vopretDummy,origpubkey; - uint8_t e, f,*script,flag = 0; std::vector voutPubkeys; + uint8_t e, f,*script; std::vector voutPubkeys; tokenid = zeroid; GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); @@ -226,11 +226,10 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl else if ( script[1] != 'R' && (f= DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy)) != 0 ) { fprintf(stderr,"decode opret %c tokenid.%s\n",script[1],tokenid.GetHex().c_str()); - GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx - vopret = vopretNonfungible; - flag = 1; + //GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx + vopret = vopretDummy; } - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && (flag != 0 || f == 'R') ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) { return(f); } @@ -764,7 +763,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { - //fprintf(stderr,"playertxid.%s\n",playertxid.GetHex().c_str()); + fprintf(stderr,"gametxid.%s playertxid.%s opR.%d\n",gametxid.GetHex().c_str(),playertxid.GetHex().c_str(),(int32_t)opretRegister.size()); voutPubkeysEmpty.push_back(burnpk); if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) { From 2cdb6f10e76928223c2b231c34b6fad1ba0e5d7f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 15:50:11 -1100 Subject: [PATCH 0579/1145] -print --- src/cc/rogue/state.c | 1 + src/cc/rogue_rpc.cpp | 23 +---------------------- 2 files changed, 2 insertions(+), 22 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 817993c17..1779bcbcc 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1372,6 +1372,7 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item) if ( item->which < MAXSTICKS ) ws_info[item->which].oi_know = TRUE; break; + // cur_armor and cur_weapon should be set } char packitemstr[256]; strcpy(packitemstr,inv_name(o,FALSE)); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 53d18eff9..0b6a00c43 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -225,8 +225,6 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl } else if ( script[1] != 'R' && (f= DecodeTokenOpRet(scriptPubKey, e, tokenid, voutPubkeys, vopretDummy)) != 0 ) { - fprintf(stderr,"decode opret %c tokenid.%s\n",script[1],tokenid.GetHex().c_str()); - //GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx vopret = vopretDummy; } if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) @@ -234,25 +232,6 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl return(f); } fprintf(stderr,"e.%d f.%c game.%s playertxid.%s\n",e,f,gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); - - /*std::vector vopret,vopret2; uint8_t e,f; std::vector voutPubkeys; - GetOpReturnData(scriptPubKey,vopret); - tokenid = zeroid; - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) - { - return(f); - } - else if ( (f= DecodeTokenOpRet(scriptPubKey,e,tokenid,voutPubkeys,vopret)) == 'c' || f == 't' ) - { - //fprintf(stderr,"got valid token opret %s e.%d vs %d\n",tokenid.GetHex().c_str(),e,EVAL_TOKENS); - if ( vopret2.size() > 2 && E_UNMARSHAL(vopret2,ss >> e; ss >> f; ss >> gametxid; ss >> playertxid) != 0 && e == EVAL_ROGUE && f == 'R' ) - { - return(f); - } - playertxid = tokenid; - fprintf(stderr,"e.%d vs %d, f %c, gametxid.%s player.%s\n",e,EVAL_ROGUE,f,gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); - return(0); - }*/ return(0); } @@ -763,7 +742,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { - fprintf(stderr,"gametxid.%s playertxid.%s opR.%d\n",gametxid.GetHex().c_str(),playertxid.GetHex().c_str(),(int32_t)opretRegister.size()); + //fprintf(stderr,"gametxid.%s playertxid.%s opR.%d\n",gametxid.GetHex().c_str(),playertxid.GetHex().c_str(),(int32_t)opretRegister.size()); voutPubkeysEmpty.push_back(burnpk); if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) { From 00d27436f39c7d35e2c178d472c6d0250958806f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 15:54:11 -1100 Subject: [PATCH 0580/1145] +skip --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 0b6a00c43..0c29322ee 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -196,7 +196,7 @@ uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t { return(f); } - fprintf(stderr,"e.%d f.%c game.%s regslot.%d psize.%d\n",e,f,gametxid.GetHex().c_str(),regslot,(int32_t)playerdata.size()); + fprintf(stderr,"SKIP obsolete: e.%d f.%c game.%s regslot.%d psize.%d\n",e,f,gametxid.GetHex().c_str(),regslot,(int32_t)playerdata.size()); return(0); } From 5aee2381b08acc6b6deef21273813c63a8818bdf Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 11 Feb 2019 21:55:37 -1100 Subject: [PATCH 0581/1145] Disp playertxid for tokens for 'c' tx --- src/cc/rogue_rpc.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 0c29322ee..2ba2dd980 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -386,6 +386,7 @@ UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint obj.push_back(Pair("playertxid",playertxid.GetHex())); if ( tokenid != zeroid ) obj.push_back(Pair("tokenid",tokenid.GetHex())); + else obj.push_back(Pair("tokenid",playertxid.GetHex())); obj.push_back(Pair("data",datastr)); free(datastr); obj.push_back(Pair("pack",a)); From 9eed81089bf15c859f116fccdee32ae5193d82a3 Mon Sep 17 00:00:00 2001 From: dimxy Date: Tue, 12 Feb 2019 13:07:31 +0500 Subject: [PATCH 0582/1145] corr check for non-existing eval MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit in CCLogPrintStream -debug=cat-0 added declr corrected comment added to check for non supported eval added check if eval not supported СCLogPrintStream moved to CCutils.cpp --- src/cc/CCinclude.h | 13 +++++++------ src/cc/CCtokens.cpp | 2 +- src/cc/CCutils.cpp | 5 ++++- src/cc/eval.cpp | 1 + 4 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index e4d74ba76..eb9297a36 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -270,21 +270,22 @@ UniValue ValueFromAmount(const CAmount& amount); #define CCLOG_DEBUG3 3 #define CCLOG_MAXLEVEL 3 template -inline void CCLogPrintStream(const char *category, int level, T print_to_stream) +void CCLogPrintStream(const char *category, int level, T print_to_stream) { - std::ostringstream stream; + std::ostringstream stream; print_to_stream(stream); - if (level < 0) - level = 0; + if (level < 0) + level = 0; if (level > CCLOG_MAXLEVEL) level = CCLOG_MAXLEVEL; for (int i = level; i <= CCLOG_MAXLEVEL; i++) - if (LogAcceptCategory((std::string(category) + (i > 0 ? std::string("-") + std::to_string(i) : std::string(""))).c_str())) { + if( LogAcceptCategory((std::string(category) + std::string("-") + std::to_string(i)).c_str()) || // '-debug=cctokens-0', '-debug=cctokens-1',... + i == 0 && LogAcceptCategory(std::string(category).c_str()) ) { // also supporting '-debug=cctokens' for CCLOG_INFO LogPrintStr(stream.str()); break; } } - +// use: LOGSTREAM("yourcategory", your-debug-level, stream << "some log data" << data2 << data3 << ... << std::endl); #define LOGSTREAM(category, level, logoperator) CCLogPrintStream( category, level, [=](std::ostringstream &stream) {logoperator;} ) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index 5b6c148e8..e5b9eeb78 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -253,7 +253,7 @@ bool TokensValidate(struct CCcontract_info *cp, Eval* eval, const CTransaction & if ((funcid = DecodeTokenOpRet(tx.vout[numvouts - 1].scriptPubKey, evalCodeInOpret, tokenid, voutTokenPubkeys, vopretExtra)) == 0) return eval->Invalid("TokenValidate: invalid opreturn payload"); - LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "TokensValidate funcId=" << (char)(funcid?funcid:' ') << " evalcode=" << cp->evalcode << std::endl); + LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "TokensValidate funcId=" << (char)(funcid?funcid:' ') << " evalcode=" << std::hex << (int)cp->evalcode << std::endl); if (eval->GetTxUnconfirmed(tokenid, createTx, hashBlock) == 0) return eval->Invalid("cant find token create txid"); diff --git a/src/cc/CCutils.cpp b/src/cc/CCutils.cpp index a9e9b74c6..d79f1d7f6 100644 --- a/src/cc/CCutils.cpp +++ b/src/cc/CCutils.cpp @@ -687,6 +687,9 @@ bool ProcessCC(struct CCcontract_info *cp,Eval* eval, std::vector param from_mempool = 1; height &= ((1<<30) - 1); } + if (cp->validate == NULL) + return eval->Invalid("validation not supported for eval code"); + //fprintf(stderr,"KOMODO_CONNECTING.%d mempool.%d vs CCactive.%d\n",height,from_mempool,KOMODO_CCACTIVATE); // there is a chance CC tx is valid in mempool, but invalid when in block, so we cant filter duplicate requests. if any of the vins are spent, for example //txid = ctx.GetHash(); @@ -748,4 +751,4 @@ bool CClib_Dispatch(const CC *cond,Eval *eval,std::vector paramsNull,co return(false); //eval->Invalid("error in CClib_validate"); } return eval->Invalid("cclib CC must have evalcode between 16 and 127"); -} +} \ No newline at end of file diff --git a/src/cc/eval.cpp b/src/cc/eval.cpp index ca2703bff..405f02cc4 100644 --- a/src/cc/eval.cpp +++ b/src/cc/eval.cpp @@ -85,6 +85,7 @@ bool Eval::Dispatch(const CC *cond, const CTransaction &txTo, unsigned int nIn) CCinit(cp,ecode); cp->didinit = 1; } + switch ( ecode ) { case EVAL_IMPORTPAYOUT: From fb00eedf6c50f789d3e6e9ce2a1470c042f41aba Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 07:59:16 -1100 Subject: [PATCH 0583/1145] Two possible reasons for hang --- src/cc/rogue_rpc.cpp | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 2ba2dd980..ba0161faa 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -21,6 +21,7 @@ #define ROGUE_REGISTRATIONSIZE (100 * 10000) #define ROGUE_MAXPLAYERS 64 // need to send unused fees back to globalCC address to prevent leeching #define ROGUE_MAXKEYSTROKESGAP 60 +#define ROGUE_MAXLEN 777 /* Roguelander - using highlander competition between rogue players @@ -401,16 +402,22 @@ UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firstvout,uint256 lasttxid) // retrace playertxid vins to reach highlander <- this verifies player is valid and rogue_playerdataspend makes sure it can only be used once { - uint256 spenttxid,txid = firsttxid; int32_t spentvini,vout = firstvout; + uint256 spenttxid,txid = firsttxid; int32_t spentvini,n,vout = firstvout; registertxid = zeroid; if ( vout < 0 ) return(-1); + n = 0; while ( (spentvini= myIsutxo_spent(spenttxid,txid,vout)) == 0 ) { txid = spenttxid; vout = spentvini; if ( registertxid == zeroid ) registertxid = txid; + if ( ++n >= ROGUE_MAXLENGTH ) + { + fprintf(stderr,"rogue_iterateplayer n.%d, seems something is wrong\n",n); + break; + } } if ( txid == lasttxid ) return(0); @@ -469,7 +476,7 @@ int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,int32_ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **keystrokesp,int32_t &numkeys,int32_t ®slot,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr,int32_t &numplayers) { - int32_t i,numvouts,spentvini,matches = 0; CPubKey pk; uint256 tid,spenttxid,tokenid,hashBlock,txid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; + int32_t i,numvouts,spentvini,n,matches = 0; CPubKey pk; uint256 tid,spenttxid,tokenid,hashBlock,txid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; numkeys = numplayers = 0; playertxid = zeroid; for (i=0; i= 2 ) { uint256 g,b; CPubKey p; std::vector k; - if ( rogue_keystrokesopretdecode(g,b,p,k,spenttx.vout[1].scriptPubKey) == 'K' ) + if ( rogue_keystrokesopretdecode(g,b,p,k,spenttx.vout[spenttx.vout.size()-1].scriptPubKey) == 'K' ) { keystrokes = (char *)realloc(keystrokes,numkeys + (int32_t)k.size()); for (i=0; i= ROGUE_MAXLENGTH ) + { + fprintf(stderr,"rogue_findbaton n.%d, seems something is wrong\n",n); + break; + } } //fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); batontxid = txid; From 69ccb69983bd4fcd7b631145881dd96e4480eb1f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 08:00:26 -1100 Subject: [PATCH 0584/1145] ROGUE_MAXITERATIONS --- src/cc/rogue_rpc.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ba0161faa..d81755570 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -21,7 +21,7 @@ #define ROGUE_REGISTRATIONSIZE (100 * 10000) #define ROGUE_MAXPLAYERS 64 // need to send unused fees back to globalCC address to prevent leeching #define ROGUE_MAXKEYSTROKESGAP 60 -#define ROGUE_MAXLEN 777 +#define ROGUE_MAXITERATIONS 777 /* Roguelander - using highlander competition between rogue players @@ -413,7 +413,7 @@ int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firs vout = spentvini; if ( registertxid == zeroid ) registertxid = txid; - if ( ++n >= ROGUE_MAXLENGTH ) + if ( ++n >= ROGUE_MAXITERATIONS ) { fprintf(stderr,"rogue_iterateplayer n.%d, seems something is wrong\n",n); break; @@ -538,7 +538,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke (*keystrokesp) = keystrokes; } } - if ( ++n >= ROGUE_MAXLENGTH ) + if ( ++n >= ROGUE_MAXITERATIONS ) { fprintf(stderr,"rogue_findbaton n.%d, seems something is wrong\n",n); break; From 072093c628a7fb2f241ed52e14c029cd51835395 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 08:01:04 -1100 Subject: [PATCH 0585/1145] Return negative --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d81755570..6fceb497b 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -416,7 +416,7 @@ int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firs if ( ++n >= ROGUE_MAXITERATIONS ) { fprintf(stderr,"rogue_iterateplayer n.%d, seems something is wrong\n",n); - break; + return(-2); } } if ( txid == lasttxid ) @@ -541,7 +541,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( ++n >= ROGUE_MAXITERATIONS ) { fprintf(stderr,"rogue_findbaton n.%d, seems something is wrong\n",n); - break; + retyrn(-5); } } //fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); From 44b3739ae0f8fe8376f224dec3aeb184237ba417 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 08:01:55 -1100 Subject: [PATCH 0586/1145] Return --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 6fceb497b..526c48c6a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -541,7 +541,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( ++n >= ROGUE_MAXITERATIONS ) { fprintf(stderr,"rogue_findbaton n.%d, seems something is wrong\n",n); - retyrn(-5); + return(-5); } } //fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); From ded4d20f988864928a2420e5f226650192ba4596 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 08:44:20 -1100 Subject: [PATCH 0587/1145] Spend the tokenid v0 to burn it --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 526c48c6a..450e40470 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -739,9 +739,9 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"couldnt find playerdata to spend")); else if ( buyin > 0 && AddNormalinputs(mtx,mypk,buyin,64) < buyin ) return(cclib_error(result,"couldnt find enough normal funds for buyin")); - if ( playertxid != zeroid ) + if ( tokenid != zeroid ) { - mtx.vin.push_back(CTxIn(playertxid,0)); // spending cc marker as token is burned + mtx.vin.push_back(CTxIn(tokenid,0)); // spending cc marker as token is burned char unspendableTokenAddr[64]; uint8_t tokenpriv[32]; struct CCcontract_info *cpTokens, tokensC; cpTokens = CCinit(&tokensC, EVAL_TOKENS); CPubKey unspPk = GetUnspendable(cpTokens, tokenpriv); From c6e8ba4a71020d03a5759259d43e6d4d140296c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 09:02:42 -1100 Subject: [PATCH 0588/1145] Games rpc call --- src/cc/cclib.cpp | 4 ++++ src/cc/rogue_rpc.cpp | 23 ++++++++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 04ad7a66d..f5a3d092e 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -62,6 +62,7 @@ CClib_methods[] = { (char *)"rogue", (char *)"highlander", (char *)"gametxid", 1, 1, 'H', EVAL_ROGUE }, { (char *)"rogue", (char *)"playerinfo", (char *)"playertxid", 1, 1, 'I', EVAL_ROGUE }, { (char *)"rogue", (char *)"players", (char *)"", 0, 0, 'D', EVAL_ROGUE }, + { (char *)"rogue", (char *)"games", (char *)"", 0, 0, 'F', EVAL_ROGUE }, #else { (char *)"sudoku", (char *)"gen", (char *)"", 0, 0, 'G', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, @@ -85,6 +86,7 @@ UniValue rogue_bailout(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); #else bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); @@ -118,6 +120,8 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) return(rogue_playerinfo(txfee,cp,params)); else if ( strcmp(method,"players") == 0 ) return(rogue_players(txfee,cp,params)); + else if ( strcmp(method,"games") == 0 ) + return(rogue_games(txfee,cp,params)); else { result.push_back(Pair("result","error")); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 450e40470..f1b21598a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -757,7 +757,6 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) CScript opretRegister = rogue_registeropret(gametxid, playertxid); if ( playertxid != zeroid ) { - //fprintf(stderr,"gametxid.%s playertxid.%s opR.%d\n",gametxid.GetHex().c_str(),playertxid.GetHex().c_str(),(int32_t)opretRegister.size()); voutPubkeysEmpty.push_back(burnpk); if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) { @@ -1045,6 +1044,28 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } +UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ),a(UniValue::VARR); int64_t buyin; uint256 tokenid,gametxid,txid,hashBlock; CTransaction playertx,tx; int32_t maxplayers,vout,numvouts; std::vector playerdata; CPubKey roguepk,mypk,pk; char coinaddr[64]; + roguepk = GetUnspendable(cp,0); + mypk = pubkey2pk(Mypubkey()); + GetCCaddress1of2(cp,coinaddr,roguepk,mypk); + SetCCunspents(unspentOutputs,coinaddr); + rogue_univalue(result,"games",-1,-1); + for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) + { + txid = it->first.txhash; + vout = (int32_t)it->first.index; + //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); + if ( vout == 0 ) + { + a.push_back(txid.GetHex()); + } + } + result.push_back(Pair("games",a)); + result.push_back(Pair("numgames",a.size())); +} + bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { return(true); From 20d2b07d982529d84c540670e657c99048a40079 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 09:03:02 -1100 Subject: [PATCH 0589/1145] Return result --- src/cc/rogue_rpc.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f1b21598a..2fe2f6269 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1064,6 +1064,7 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } result.push_back(Pair("games",a)); result.push_back(Pair("numgames",a.size())); + return(result); } bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) From a757607bb75329fc7fe1b8f2ed5c82d6c0a2df65 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 09:16:29 -1100 Subject: [PATCH 0590/1145] +print --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 2fe2f6269..a3d0fda0c 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1052,11 +1052,12 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) GetCCaddress1of2(cp,coinaddr,roguepk,mypk); SetCCunspents(unspentOutputs,coinaddr); rogue_univalue(result,"games",-1,-1); + fprintf(stderr,"rogue_games\n"); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { txid = it->first.txhash; vout = (int32_t)it->first.index; - //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); + char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( vout == 0 ) { a.push_back(txid.GetHex()); From 60da8f511b1fdcb0893300303d4f128f87e76477 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 09:21:16 -1100 Subject: [PATCH 0591/1145] Declare inspects --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index a3d0fda0c..fbd512c5a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1046,13 +1046,13 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR); int64_t buyin; uint256 tokenid,gametxid,txid,hashBlock; CTransaction playertx,tx; int32_t maxplayers,vout,numvouts; std::vector playerdata; CPubKey roguepk,mypk,pk; char coinaddr[64]; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); uint256 txid; int32_t vout; CPubKey roguepk,mypk; char coinaddr[64]; + std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); mypk = pubkey2pk(Mypubkey()); GetCCaddress1of2(cp,coinaddr,roguepk,mypk); SetCCunspents(unspentOutputs,coinaddr); rogue_univalue(result,"games",-1,-1); - fprintf(stderr,"rogue_games\n"); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { txid = it->first.txhash; From 37eba17f16425ab6f16ac1b6b4765f0ec1f2b27c Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 09:30:31 -1100 Subject: [PATCH 0592/1145] Limit to 'R' --- src/cc/rogue_rpc.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index fbd512c5a..0e6c6011a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1046,7 +1046,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR); uint256 txid; int32_t vout; CPubKey roguepk,mypk; char coinaddr[64]; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); uint256 txid,gametxid,tokenid,playertxid; int32_t vout; CPubKey roguepk,mypk; char coinaddr[64]; CTransaction tx; std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); mypk = pubkey2pk(Mypubkey()); @@ -1057,10 +1057,16 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { txid = it->first.txhash; vout = (int32_t)it->first.index; - char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); + //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( vout == 0 ) { - a.push_back(txid.GetHex()); + if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + { + if ( rogue_registeropretdecode(gametxid,tokenid,playertxid,tx.vout[numvouts-1].scriptPubKey) == 'R' ) + { + a.push_back(gametxid.GetHex()); + } + } } } result.push_back(Pair("games",a)); From 891e89f4fd5e88eb21aa8aa9fa5038830b19954c Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 09:31:35 -1100 Subject: [PATCH 0593/1145] Vars --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 0e6c6011a..a9393af28 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1046,7 +1046,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR); uint256 txid,gametxid,tokenid,playertxid; int32_t vout; CPubKey roguepk,mypk; char coinaddr[64]; CTransaction tx; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); uint256 txid,hashBlock,gametxid,tokenid,playertxid; int32_t vout,numvouts; CPubKey roguepk,mypk; char coinaddr[64]; CTransaction tx; std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); mypk = pubkey2pk(Mypubkey()); From 5425e6a040f213079f9aa17b2268bd3941cc6d37 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 09:50:21 -1100 Subject: [PATCH 0594/1145] Prints --- src/cc/rogue_rpc.cpp | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index a9393af28..20418bb84 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -476,7 +476,7 @@ int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,int32_ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **keystrokesp,int32_t &numkeys,int32_t ®slot,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr,int32_t &numplayers) { - int32_t i,numvouts,spentvini,n,matches = 0; CPubKey pk; uint256 tid,spenttxid,tokenid,hashBlock,txid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; + int32_t i,numvouts,spentvini,n,matches = 0; CPubKey pk; uint256 tid,active,spenttxid,tokenid,hashBlock,txid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; numkeys = numplayers = 0; playertxid = zeroid; for (i=0; i 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,err,gameheight,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,playertxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; + UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,err,gameheight,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata,nodata; uint256 batontxid,playertxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; struct CCcontract_info *cpTokens, tokensC; if ( txfee == 0 ) @@ -922,11 +923,16 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); - CScript opret = rogue_highlanderopret(funcid, gametxid, regslot, mypk, newdata); + CScript opret; if ( newdata.size() == 0 ) + { + opret = rogue_highlanderopret(funcid, gametxid, regslot, mypk, nodata); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,opret); + fprintf(stderr,"nodata finalizetx.(%s)\n",rawtx); + } else { + opret = rogue_highlanderopret(funcid, gametxid, regslot, mypk, newdata); char seedstr[32]; sprintf(seedstr,"%llu",(long long)seed); std::vector vopretNonfungible; From 7d485369b27b4f202ec69f465587133312a3a9bd Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 10:07:35 -1100 Subject: [PATCH 0595/1145] All taxis for games --- src/cc/rogue/state.c | 6 +++--- src/cc/rogue_rpc.cpp | 10 ++++++---- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 1779bcbcc..3db54a319 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1374,9 +1374,9 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item) break; // cur_armor and cur_weapon should be set } - char packitemstr[256]; - strcpy(packitemstr,inv_name(o,FALSE)); - fprintf(stderr,"packitem.(%s)\n",packitemstr); + //char packitemstr[256]; + //strcpy(packitemstr,inv_name(o,FALSE)); + //fprintf(stderr,"packitem.(%s)\n",packitemstr); } } diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 20418bb84..2563b8e83 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -504,7 +504,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { - fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); + //fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); if ( tokenid != zeroid ) active = tokenid; else active = playertxid; @@ -928,7 +928,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { opret = rogue_highlanderopret(funcid, gametxid, regslot, mypk, nodata); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,opret); - fprintf(stderr,"nodata finalizetx.(%s)\n",rawtx); + fprintf(stderr,"nodata finalizetx.(%s)\n",rawtx.c_str()); } else { @@ -1053,11 +1053,13 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ),a(UniValue::VARR); uint256 txid,hashBlock,gametxid,tokenid,playertxid; int32_t vout,numvouts; CPubKey roguepk,mypk; char coinaddr[64]; CTransaction tx; - std::vector > unspentOutputs; + std::vector > &addressIndex; + //std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); mypk = pubkey2pk(Mypubkey()); GetCCaddress1of2(cp,coinaddr,roguepk,mypk); - SetCCunspents(unspentOutputs,coinaddr); + //SetCCunspents(unspentOutputs,coinaddr); + SetCCtxids(addressIndex,coinaddr); rogue_univalue(result,"games",-1,-1); for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { From e895ba68d23facc31a9ff9865695e058675399f7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 10:11:24 -1100 Subject: [PATCH 0596/1145] Fix --- src/cc/rogue_rpc.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 2563b8e83..a54f81036 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1053,7 +1053,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ),a(UniValue::VARR); uint256 txid,hashBlock,gametxid,tokenid,playertxid; int32_t vout,numvouts; CPubKey roguepk,mypk; char coinaddr[64]; CTransaction tx; - std::vector > &addressIndex; + std::vector > addressIndex; //std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); mypk = pubkey2pk(Mypubkey()); @@ -1061,7 +1061,8 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //SetCCunspents(unspentOutputs,coinaddr); SetCCtxids(addressIndex,coinaddr); rogue_univalue(result,"games",-1,-1); - for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) + for (std::vector >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) + //for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) { txid = it->first.txhash; vout = (int32_t)it->first.index; From b86fa74a48e647cd4316307dc234bf61d0bb95f8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 10:15:42 -1100 Subject: [PATCH 0597/1145] Pastgames --- src/cc/rogue_rpc.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index a54f81036..ec2f571ee 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -232,7 +232,7 @@ uint8_t rogue_registeropretdecode(uint256 &gametxid,uint256 &tokenid,uint256 &pl { return(f); } - fprintf(stderr,"e.%d f.%c game.%s playertxid.%s\n",e,f,gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); + //fprintf(stderr,"e.%d f.%c game.%s playertxid.%s\n",e,f,gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); return(0); } @@ -1052,7 +1052,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR); uint256 txid,hashBlock,gametxid,tokenid,playertxid; int32_t vout,numvouts; CPubKey roguepk,mypk; char coinaddr[64]; CTransaction tx; + UniValue result(UniValue::VOBJ),a(UniValue::VARR),b(UniValue::VARR); uint256 txid,hashBlock,gametxid,tokenid,playertxid; int32_t vout,numvouts; CPubKey roguepk,mypk; char coinaddr[64]; CTransaction tx; std::vector > addressIndex; //std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); @@ -1073,13 +1073,16 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( rogue_registeropretdecode(gametxid,tokenid,playertxid,tx.vout[numvouts-1].scriptPubKey) == 'R' ) { - a.push_back(gametxid.GetHex()); + if ( CCgettxout(txid,vout,1) < 0 ) + b.push_back(gametxid.GetHex()); + else a.push_back(gametxid.GetHex()); } } } } + result.push_back(Pair("pastgames",b)); result.push_back(Pair("games",a)); - result.push_back(Pair("numgames",a.size())); + result.push_back(Pair("numgames",a.size()+b.size())); return(result); } From f41d60a399eac2e6c9c2c9645c192d84ec05996d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 10:20:24 -1100 Subject: [PATCH 0598/1145] Filter out invalid games --- src/cc/rogue_rpc.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ec2f571ee..49a61bd67 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1052,7 +1052,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR),b(UniValue::VARR); uint256 txid,hashBlock,gametxid,tokenid,playertxid; int32_t vout,numvouts; CPubKey roguepk,mypk; char coinaddr[64]; CTransaction tx; + UniValue result(UniValue::VOBJ),a(UniValue::VARR),b(UniValue::VARR); uint256 txid,hashBlock,gametxid,tokenid,playertxid; int32_t vout,maxplayers,gameheight,numvouts; CPubKey roguepk,mypk; char coinaddr[64]; CTransaction tx,gametx; int64_t buyin; std::vector > addressIndex; //std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); @@ -1073,9 +1073,12 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( rogue_registeropretdecode(gametxid,tokenid,playertxid,tx.vout[numvouts-1].scriptPubKey) == 'R' ) { - if ( CCgettxout(txid,vout,1) < 0 ) - b.push_back(gametxid.GetHex()); - else a.push_back(gametxid.GetHex()); + if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) + { + if ( CCgettxout(txid,vout,1) < 0 ) + b.push_back(gametxid.GetHex()); + else a.push_back(gametxid.GetHex()); + } } } } From 06058a25ffc2be34327af04d1980d4e10ff91ccf Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 17:51:04 -1100 Subject: [PATCH 0599/1145] -prints --- src/cc/rogue/rogue.c | 17 +++++++++++------ src/cc/rogue_rpc.cpp | 7 ++++--- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index fffa6203d..8442e9997 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -149,6 +149,8 @@ uint8_t *OS_fileptr(long *allocsizep,char *fname); int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) { char cmd[32768]; int32_t i,n,retval=-1; char *filestr,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; + if ( gametxidstr == 0 || *gametxidstr == 0 ) + return(retval); sprintf(fname,"%s.gameinfo",gametxidstr); sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); if ( system(cmd) != 0 ) @@ -188,12 +190,15 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) { char cmd[16384],hexstr[16384]; int32_t i; - for (i=0; i> keystrokes.log",Gametxidstr,hexstr); - if ( system(cmd) != 0 ) - fprintf(stderr,"error issuing (%s)\n",cmd); + if ( Gametxidstr[0] != 0 ) + { + for (i=0; i> keystrokes.log",Gametxidstr,hexstr); + if ( system(cmd) != 0 ) + fprintf(stderr,"error issuing (%s)\n",cmd); + } } int32_t flushkeystrokes(struct rogue_state *rs) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 49a61bd67..e012746e4 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -117,7 +117,8 @@ // todo: // verify keystrokes tx is in mempool and confirmed -// chaining when mempool tx sometimes infinite loops +// chaining when mempool tx sometimes infinite loops? +// bailout stealing, is it possible? //////////////////////// start of CClib interface //./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey=03951a6f7967ad784453116bc55cd30c54f91ea8a5b1e9b04d6b29cfd6b395ba6c -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc > /dev/null & @@ -1041,8 +1042,8 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) continue; if ( rogue_playerdata(cp,gametxid,tokenid,pk,playerdata,txid) == 0 )//&& pk == mypk ) { - a.push_back(rogue_playerobj(playerdata,txid,tokenid)); - //result.push_back(Pair("playerdata",rogue_playerobj(playerdata))); + a.push_back(txid.GetHex()); + //a.push_back(Pair("playerdata",rogue_playerobj(playerdata))); } } result.push_back(Pair("playerdata",a)); From 12a4822a0b0dc45f2a4b5332b483496726a2c86d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 17:56:02 -1100 Subject: [PATCH 0600/1145] Add ASSETCHAINS_SYMBOL to player data --- src/cc/rogue_rpc.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e012746e4..40c5eab84 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -172,11 +172,11 @@ CScript rogue_keystrokesopret(uint256 gametxid,uint256 batontxid,CPubKey pk,std: CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,int32_t regslot,CPubKey pk,std::vectorplayerdata) { CScript opret; uint8_t evalcode = EVAL_ROGUE; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << gametxid << regslot << pk << playerdata); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << gametxid << regslot << pk << playerdata << ASSETCHAINS_SYMBOL); return(opret); } -uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t ®slot, CPubKey &pk, std::vector &playerdata, CScript scriptPubKey) +uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t ®slot, CPubKey &pk, std::vector &playerdata, std::string &symbol,CScript scriptPubKey) { std::string name, description; std::vector vorigPubkey; std::vector vopretNonfungible, vopret, vopretDummy,origpubkey; @@ -194,7 +194,7 @@ uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx vopret = vopretNonfungible; } - if ( vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata; ss >> symbol) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) { return(f); } @@ -437,10 +437,10 @@ int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firs int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint256 &tokenid,CPubKey &pk,std::vector &playerdata,uint256 playertxid) { - uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; + uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; std::string symbol; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) { - if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) + if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { if ( tokenid != zeroid ) { From cf92af5fcaff447426b5b6b9edf14a73f8549e9d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 17:57:15 -1100 Subject: [PATCH 0601/1145] Symbol --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 40c5eab84..b6635a016 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -171,8 +171,8 @@ CScript rogue_keystrokesopret(uint256 gametxid,uint256 batontxid,CPubKey pk,std: CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,int32_t regslot,CPubKey pk,std::vectorplayerdata) { - CScript opret; uint8_t evalcode = EVAL_ROGUE; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << gametxid << regslot << pk << playerdata << ASSETCHAINS_SYMBOL); + CScript opret; uint8_t evalcode = EVAL_ROGUE; std::string symbol(ASSETCHAINS_SYMBOL); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << gametxid << regslot << pk << playerdata << symbol); return(opret); } From e3b6e77eb6eab458cd077b4eaafd7038d573cb76 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 18:25:57 -1100 Subject: [PATCH 0602/1145] Fred --- src/cc/rogue_rpc.cpp | 56 ++++++++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 26 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b6635a016..ce6f0889f 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -169,14 +169,14 @@ CScript rogue_keystrokesopret(uint256 gametxid,uint256 batontxid,CPubKey pk,std: return(opret); } -CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,int32_t regslot,CPubKey pk,std::vectorplayerdata) +CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,int32_t regslot,CPubKey pk,std::vectorplayerdata,std::string pname) { CScript opret; uint8_t evalcode = EVAL_ROGUE; std::string symbol(ASSETCHAINS_SYMBOL); - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << gametxid << regslot << pk << playerdata << symbol); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << gametxid << regslot << pk << playerdata << symbol << pname); return(opret); } -uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t ®slot, CPubKey &pk, std::vector &playerdata, std::string &symbol,CScript scriptPubKey) +uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t ®slot, CPubKey &pk, std::vector &playerdata, std::string &symbol,std::string &pname,CScript scriptPubKey) { std::string name, description; std::vector vorigPubkey; std::vector vopretNonfungible, vopret, vopretDummy,origpubkey; @@ -194,7 +194,7 @@ uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx vopret = vopretNonfungible; } - if ( vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata; ss >> symbol) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata; ss >> symbol; ss >> pname) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) { return(f); } @@ -365,7 +365,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa } else return(-1); } -UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint256 tokenid) +UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint256 tokenid,std::string symbol,std::string pname) { int32_t i; struct rogue_player P; char packitemstr[512],*datastr; UniValue obj(UniValue::VOBJ),a(UniValue::VARR); memset(&P,0,sizeof(P)); @@ -398,6 +398,8 @@ UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint obj.push_back(Pair("level",(int64_t)P.level)); obj.push_back(Pair("experience",(int64_t)P.experience)); obj.push_back(Pair("dungeonlevel",(int64_t)P.dungeonlevel)); + obj.push_back(Pair("chain",symbol)); + obj.push_back(Pair("name",pname)); return(obj); } @@ -435,12 +437,12 @@ int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firs origplayergame is the gametxid that ends up being won by the highlander and they are linked directly as the highlander tx spends gametxid.vout0 */ -int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint256 &tokenid,CPubKey &pk,std::vector &playerdata,uint256 playertxid) +int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint256 &tokenid,CPubKey &pk,std::vector &playerdata,std::string &symbol,std::string &pname,uint256 playertxid) { - uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; std::string symbol; + uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) { - if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) + if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,pname,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { if ( tokenid != zeroid ) { @@ -475,7 +477,7 @@ int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,int32_ } else return(-1); } -int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **keystrokesp,int32_t &numkeys,int32_t ®slot,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr,int32_t &numplayers) +int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **keystrokesp,int32_t &numkeys,int32_t ®slot,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr,int32_t &numplayers,std::string &symbol,std::string &pname) { int32_t i,numvouts,spentvini,n,matches = 0; CPubKey pk; uint256 tid,active,spenttxid,tokenid,hashBlock,txid,origplayergame; CTransaction spenttx,matchtx,batontx; std::vector checkdata; CBlockIndex *pindex; char ccaddr[64],*keystrokes=0; numkeys = numplayers = 0; @@ -509,7 +511,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( tokenid != zeroid ) active = tokenid; else active = playertxid; - if ( active == zeroid || rogue_playerdata(cp,origplayergame,tid,pk,playerdata,active) == 0 ) + if ( active == zeroid || rogue_playerdata(cp,origplayergame,tid,pk,playerdata,symbol,pname,active) == 0 ) { txid = matchtx.GetHash(); //fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); @@ -577,7 +579,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gametxid,CTransaction gametx,int32_t vout,int32_t maxplayers,char *myrogueaddr) { // identify if bailout or quit or timed out - uint256 batontxid,spenttxid,gtxid,ptxid,tokenid,hashBlock,playertxid; CTransaction spenttx,batontx; int32_t numplayers,regslot,numkeys,batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; + uint256 batontxid,spenttxid,gtxid,ptxid,tokenid,hashBlock,playertxid; CTransaction spenttx,batontx; int32_t numplayers,regslot,numkeys,batonvout,batonht,retval; int64_t batonvalue; std::vector playerdata; char destaddr[64]; std::string symbol,pname; destaddr[0] = 0; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { @@ -585,7 +587,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); } obj.push_back(Pair("slot",(int64_t)vout-1)); - if ( (retval= rogue_findbaton(cp,playertxid,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr,numplayers)) == 0 ) + if ( (retval= rogue_findbaton(cp,playertxid,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,destaddr,numplayers,symbol,pname)) == 0 ) { if ( CCgettxout(gametxid,maxplayers+vout,1) == 10000 ) { @@ -604,7 +606,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet obj.push_back(Pair("batonvalue",ValueFromAmount(batonvalue))); obj.push_back(Pair("batonht",(int64_t)batonht)); if ( playerdata.size() > 0 ) - obj.push_back(Pair("player",rogue_playerobj(playerdata,playertxid,tokenid))); + obj.push_back(Pair("player",rogue_playerobj(playerdata,playertxid,tokenid,symbol,pname))); } else fprintf(stderr,"findbaton err.%d\n",retval); } @@ -683,7 +685,7 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); std::vector playerdata; uint256 playertxid,tokenid,origplayergame;int32_t n; CPubKey pk; bits256 t; + UniValue result(UniValue::VOBJ); std::vector playerdata; uint256 playertxid,tokenid,origplayergame;int32_t n; CPubKey pk; bits256 t; std::string symbol,pname; result.push_back(Pair("result","success")); rogue_univalue(result,"playerinfo",-1,-1); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -691,9 +693,9 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( n > 0 ) { playertxid = juint256(jitem(params,0)); - if ( rogue_playerdata(cp,origplayergame,tokenid,pk,playerdata,playertxid) < 0 ) + if ( rogue_playerdata(cp,origplayergame,tokenid,pk,playerdata,symbol,pname,playertxid) < 0 ) return(cclib_error(result,"invalid playerdata")); - result.push_back(Pair("player",rogue_playerobj(playerdata,playertxid,tokenid))); + result.push_back(Pair("player",rogue_playerobj(playerdata,playertxid,tokenid,symbol,pname))); } else return(cclib_error(result,"no playertxid")); return(result); } else return(cclib_error(result,"couldnt reparse params")); @@ -707,7 +709,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) // vin3+ -> buyin // vout0 -> keystrokes/completion baton CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 tokenid,gametxid,origplayergame,playertxid,hashBlock; int32_t err,maxplayers,gameheight,n,numvouts,vout=1; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk,burnpk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx; bits256 t; + UniValue result(UniValue::VOBJ); char destaddr[64],coinaddr[64]; uint256 tokenid,gametxid,origplayergame,playertxid,hashBlock; int32_t err,maxplayers,gameheight,n,numvouts,vout=1; int64_t inputsum,buyin,CCchange=0; CPubKey pk,mypk,roguepk,burnpk; CTransaction tx,playertx; std::vector playerdata; std::string rawtx,symbol,pname; bits256 t; if ( txfee == 0 ) txfee = 10000; @@ -726,7 +728,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( n > 1 ) { playertxid = juint256(jitem(params,1)); - if ( rogue_playerdata(cp,origplayergame,tokenid,pk,playerdata,playertxid) < 0 ) + if ( rogue_playerdata(cp,origplayergame,tokenid,pk,playerdata,symbol,pname,playertxid) < 0 ) return(cclib_error(result,"couldnt extract valid playerdata")); if ( tokenid != zeroid ) vout = 1; @@ -790,7 +792,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // respawn to be prevented by including timestamps int32_t nextheight = komodo_nextheight(); CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(),nextheight); - UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,playertxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t numplayers,regslot,numkeys,batonht,batonvout,n,elapsed,gameheight,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx; bits256 t; uint8_t mypriv[32]; + UniValue result(UniValue::VOBJ); CPubKey roguepk,mypk; uint256 gametxid,playertxid,batontxid; int64_t batonvalue,buyin; std::vector keystrokes,playerdata; int32_t numplayers,regslot,numkeys,batonht,batonvout,n,elapsed,gameheight,maxplayers; CTransaction tx; CTxOut txout; char *keystrokestr,destaddr[64]; std::string rawtx,symbol,pname; bits256 t; uint8_t mypriv[32]; if ( txfee == 0 ) txfee = 10000; rogue_univalue(result,"keystrokes",-1,-1); @@ -803,7 +805,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param GetCCaddress1of2(cp,destaddr,roguepk,mypk); if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid) == 0 ) { - if ( rogue_findbaton(cp,playertxid,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr,numplayers) == 0 ) + if ( rogue_findbaton(cp,playertxid,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr,numplayers,symbol,pname) == 0 ) { if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) { @@ -834,7 +836,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,err,gameheight,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata,nodata; uint256 batontxid,playertxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; + UniValue result(UniValue::VOBJ); std::string rawtx,symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,err,gameheight,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata,nodata; uint256 batontxid,playertxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; struct CCcontract_info *cpTokens, tokensC; if ( txfee == 0 ) @@ -865,9 +867,11 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { if ( maxplayers == 1 ) mult /= 2; - if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers) == 0 ) + if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers,symbol,pname) == 0 ) { UniValue obj; struct rogue_player P; + if ( pname.size() == 0 ) + pname = "fred"; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); fprintf(stderr,"found baton %s numkeys.%d seed.%llu playerdata.%d\n",batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); @@ -927,13 +931,13 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param CScript opret; if ( newdata.size() == 0 ) { - opret = rogue_highlanderopret(funcid, gametxid, regslot, mypk, nodata); + opret = rogue_highlanderopret(funcid, gametxid, regslot, mypk, nodata,pname); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,opret); fprintf(stderr,"nodata finalizetx.(%s)\n",rawtx.c_str()); } else { - opret = rogue_highlanderopret(funcid, gametxid, regslot, mypk, newdata); + opret = rogue_highlanderopret(funcid, gametxid, regslot, mypk, newdata,pname); char seedstr[32]; sprintf(seedstr,"%llu",(long long)seed); std::vector vopretNonfungible; @@ -1026,7 +1030,7 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR); int64_t buyin; uint256 tokenid,gametxid,txid,hashBlock; CTransaction playertx,tx; int32_t maxplayers,vout,numvouts; std::vector playerdata; CPubKey roguepk,mypk,pk; char coinaddr[64]; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); int64_t buyin; uint256 tokenid,gametxid,txid,hashBlock; CTransaction playertx,tx; int32_t maxplayers,vout,numvouts; std::vector playerdata; CPubKey roguepk,mypk,pk; std::string symbol,pname; char coinaddr[64]; std::vector > unspentOutputs; roguepk = GetUnspendable(cp,0); mypk = pubkey2pk(Mypubkey()); @@ -1040,7 +1044,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( it->second.satoshis != 1 || vout > 1 ) continue; - if ( rogue_playerdata(cp,gametxid,tokenid,pk,playerdata,txid) == 0 )//&& pk == mypk ) + if ( rogue_playerdata(cp,gametxid,tokenid,pk,playerdata,symbol,pname,txid) == 0 )//&& pk == mypk ) { a.push_back(txid.GetHex()); //a.push_back(Pair("playerdata",rogue_playerobj(playerdata))); From 382af721ebe0d270134d8f8441f7149378bec68c Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 18:27:00 -1100 Subject: [PATCH 0603/1145] Symbol --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ce6f0889f..328e2b628 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -442,7 +442,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) { - if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,pname,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) + if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { if ( tokenid != zeroid ) { From a672e859cf092e8b1458474cf3fe5752e18a8440 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 18:39:02 -1100 Subject: [PATCH 0604/1145] Test --- src/cc/CCassetsCore.cpp | 6 +++--- src/cc/assets.cpp | 6 +++--- src/cc/rogue/rogue.c | 4 +++- src/cc/rogue_rpc.cpp | 4 ++-- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/cc/CCassetsCore.cpp b/src/cc/CCassetsCore.cpp index 62d57e71c..63c94d920 100644 --- a/src/cc/CCassetsCore.cpp +++ b/src/cc/CCassetsCore.cpp @@ -458,7 +458,7 @@ int64_t AssetValidateCCvin(struct CCcontract_info *cp,Eval* eval,char *origCCadd else if( GetAssetorigaddrs(cp, origCCaddr, origaddr, vinTx) == 0 ) return eval->Invalid("couldnt get origaddr for buyvin"); - fprintf(stderr,"AssetValidateCCvin() got %.8f to origaddr.(%s)\n", (double)vinTx.vout[tx.vin[vini].prevout.n].nValue/COIN,origaddr); + //fprintf(stderr,"AssetValidateCCvin() got %.8f to origaddr.(%s)\n", (double)vinTx.vout[tx.vin[vini].prevout.n].nValue/COIN,origaddr); if ( vinTx.vout[0].nValue == 0 ) return eval->Invalid("null value CCvin"); @@ -622,7 +622,7 @@ bool AssetCalcAmounts(struct CCcontract_info *cpAssets, int64_t &inputs, int64_t assetoshis = IsTokensvout(false, false, cpTokens, NULL, vinTx, tx.vin[i].prevout.n, assetid); if (assetoshis != 0) { - std::cerr << "AssetCalcAmounts() vin i=" << i << " assetoshis=" << assetoshis << std::endl; + //std::cerr << "AssetCalcAmounts() vin i=" << i << " assetoshis=" << assetoshis << std::endl; inputs += assetoshis; } } @@ -634,7 +634,7 @@ bool AssetCalcAmounts(struct CCcontract_info *cpAssets, int64_t &inputs, int64_t assetoshis = IsAssetvout(cpAssets, tmpprice, tmporigpubkey, tx, i, assetid); if (assetoshis != 0) { - std::cerr << "AssetCalcAmounts() vout i=" << i << " assetoshis=" << assetoshis << std::endl; + //std::cerr << "AssetCalcAmounts() vout i=" << i << " assetoshis=" << assetoshis << std::endl; outputs += assetoshis; } } diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index 18f93f903..28adf9be6 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -392,7 +392,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti return eval->Invalid("mismatched vout0 assets dual unspendable CCaddr for fill sell"); } } - fprintf(stderr,"fill validated\n"); + //fprintf(stderr,"fill validated\n"); break; case 'E': // fillexchange ////////// not implemented yet //////////// @@ -451,7 +451,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti } } ////////// not implemented yet //////////// - fprintf(stderr,"fill validated\n"); + //fprintf(stderr,"fill validated\n"); break; default: @@ -462,7 +462,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti // what does this do? bool bPrevent = PreventCC(eval, tx, preventCCvins, numvins, preventCCvouts, numvouts); - std::cerr << "AssetsValidate() PreventCC returned=" << bPrevent << std::endl; + //std::cerr << "AssetsValidate() PreventCC returned=" << bPrevent << std::endl; return (bPrevent); } diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 8442e9997..b05992ac5 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -148,7 +148,7 @@ uint8_t *OS_fileptr(long *allocsizep,char *fname); int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) { - char cmd[32768]; int32_t i,n,retval=-1; char *filestr,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; + char cmd[32768]; int32_t i,n,retval=-1; char *filestr,*pname,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; if ( gametxidstr == 0 || *gametxidstr == 0 ) return(retval); sprintf(fname,"%s.gameinfo",gametxidstr); @@ -170,6 +170,8 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) if ( strcmp(statusstr,"registered") == 0 ) { retval = 0; + if ( (pname= jstr(item,"pname")) != 0 && strlen(pname) < MAXSTR-1 ) + strcpy(whoami,pname); if ( (item= jobj(item,"player")) != 0 && (datastr= jstr(item,"data")) != 0 ) { decode_hex((uint8_t *)&rs->P,(int32_t)strlen(datastr)/2,datastr); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 328e2b628..66e056b08 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -198,7 +198,7 @@ uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t { return(f); } - fprintf(stderr,"SKIP obsolete: e.%d f.%c game.%s regslot.%d psize.%d\n",e,f,gametxid.GetHex().c_str(),regslot,(int32_t)playerdata.size()); + fprintf(stderr,"SKIP obsolete: e.%d f.%c game.%s regslot.%d psize.%d (%s) (%s)\n",e,f,gametxid.GetHex().c_str(),regslot,(int32_t)playerdata.size(),symbol,pname); return(0); } @@ -462,7 +462,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint return(0); } else fprintf(stderr,"hash mismatch or illegal gametxid\n"); } else fprintf(stderr,"invalid game %s\n",gametxid.GetHex().c_str()); - } + } else fprintf(stderr,"invalid player funcid.%c\n",funcid); } else fprintf(stderr,"couldnt get playertxid.%s\n",playertxid.GetHex().c_str()); return(-1); } From 616989f8ada2c7019dffb55c96546fe861064736 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 18:40:05 -1100 Subject: [PATCH 0605/1145] Test --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 66e056b08..41b84ba27 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -198,7 +198,7 @@ uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t { return(f); } - fprintf(stderr,"SKIP obsolete: e.%d f.%c game.%s regslot.%d psize.%d (%s) (%s)\n",e,f,gametxid.GetHex().c_str(),regslot,(int32_t)playerdata.size(),symbol,pname); + fprintf(stderr,"SKIP obsolete: e.%d f.%c game.%s regslot.%d psize.%d (%s) (%s)\n",e,f,gametxid.GetHex().c_str(),regslot,(int32_t)playerdata.size(),symbol.c_str(),pname.c_str()); return(0); } @@ -462,7 +462,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint return(0); } else fprintf(stderr,"hash mismatch or illegal gametxid\n"); } else fprintf(stderr,"invalid game %s\n",gametxid.GetHex().c_str()); - } else fprintf(stderr,"invalid player funcid.%c\n",funcid); + } else fprintf(stderr,"invalid player funcid.%c\n",f); } else fprintf(stderr,"couldnt get playertxid.%s\n",playertxid.GetHex().c_str()); return(-1); } From 13a3898082917ed1ac28830e69b5886513e5a33d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 18:46:12 -1100 Subject: [PATCH 0606/1145] Test --- src/cc/rogue_rpc.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 41b84ba27..522ea842a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -172,11 +172,11 @@ CScript rogue_keystrokesopret(uint256 gametxid,uint256 batontxid,CPubKey pk,std: CScript rogue_highlanderopret(uint8_t funcid,uint256 gametxid,int32_t regslot,CPubKey pk,std::vectorplayerdata,std::string pname) { CScript opret; uint8_t evalcode = EVAL_ROGUE; std::string symbol(ASSETCHAINS_SYMBOL); - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << gametxid << regslot << pk << playerdata << symbol << pname); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << gametxid << symbol << pname << regslot << pk << playerdata ); return(opret); } -uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t ®slot, CPubKey &pk, std::vector &playerdata, std::string &symbol,std::string &pname,CScript scriptPubKey) +uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t ®slot, CPubKey &pk, std::vector &playerdata, std::string &symbol, std::string &pname,CScript scriptPubKey) { std::string name, description; std::vector vorigPubkey; std::vector vopretNonfungible, vopret, vopretDummy,origpubkey; @@ -194,11 +194,11 @@ uint8_t rogue_highlanderopretdecode(uint256 &gametxid, uint256 &tokenid, int32_t GetNonfungibleData(tokenid, vopretNonfungible); //load nonfungible data from the 'tokenbase' tx vopret = vopretNonfungible; } - if ( vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> gametxid; ss >> regslot; ss >> pk; ss >> playerdata; ss >> symbol; ss >> pname) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret, ss >> e; ss >> f; ss >> gametxid; ss >> symbol; ss >> pname; ss >> regslot; ss >> pk; ss >> playerdata) != 0 && e == EVAL_ROGUE && (f == 'H' || f == 'Q') ) { return(f); } - fprintf(stderr,"SKIP obsolete: e.%d f.%c game.%s regslot.%d psize.%d (%s) (%s)\n",e,f,gametxid.GetHex().c_str(),regslot,(int32_t)playerdata.size(),symbol.c_str(),pname.c_str()); + fprintf(stderr,"SKIP obsolete: e.%d f.%c game.%s regslot.%d psize.%d\n",e,f,gametxid.GetHex().c_str(),regslot,(int32_t)playerdata.size()); return(0); } From a12fe67278557f179395a97cf8f6ce87c422e17f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 19:11:09 -1100 Subject: [PATCH 0607/1145] Use name in game --- src/cc/rogue/rogue.c | 4 ++-- src/cc/rogue_rpc.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index b05992ac5..b4b1b7d15 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -170,10 +170,10 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) if ( strcmp(statusstr,"registered") == 0 ) { retval = 0; - if ( (pname= jstr(item,"pname")) != 0 && strlen(pname) < MAXSTR-1 ) - strcpy(whoami,pname); if ( (item= jobj(item,"player")) != 0 && (datastr= jstr(item,"data")) != 0 ) { + if ( (pname= jstr(item,"pname")) != 0 && strlen(pname) < MAXSTR-1 ) + strcpy(whoami,pname); decode_hex((uint8_t *)&rs->P,(int32_t)strlen(datastr)/2,datastr); //fprintf(stderr,"set datastr[%d]\n",(int32_t)strlen(datastr)); rs->restoring = 1; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 522ea842a..7fdc4f53a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -462,7 +462,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint return(0); } else fprintf(stderr,"hash mismatch or illegal gametxid\n"); } else fprintf(stderr,"invalid game %s\n",gametxid.GetHex().c_str()); - } else fprintf(stderr,"invalid player funcid.%c\n",f); + } //else fprintf(stderr,"invalid player funcid.%c\n",f); } else fprintf(stderr,"couldnt get playertxid.%s\n",playertxid.GetHex().c_str()); return(-1); } @@ -933,7 +933,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { opret = rogue_highlanderopret(funcid, gametxid, regslot, mypk, nodata,pname); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,opret); - fprintf(stderr,"nodata finalizetx.(%s)\n",rawtx.c_str()); + //fprintf(stderr,"nodata finalizetx.(%s)\n",rawtx.c_str()); } else { From 5eb4336781883f1367d02aa76871bc6e1d76eab1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 19:17:41 -1100 Subject: [PATCH 0608/1145] Set name roc --- src/cc/cclib.cpp | 4 ++++ src/cc/rogue_rpc.cpp | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index f5a3d092e..c13f55ce4 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -63,6 +63,7 @@ CClib_methods[] = { (char *)"rogue", (char *)"playerinfo", (char *)"playertxid", 1, 1, 'I', EVAL_ROGUE }, { (char *)"rogue", (char *)"players", (char *)"", 0, 0, 'D', EVAL_ROGUE }, { (char *)"rogue", (char *)"games", (char *)"", 0, 0, 'F', EVAL_ROGUE }, + { (char *)"rogue", (char *)"setname", (char *)"pname", 1, 1, 'N', EVAL_ROGUE }, #else { (char *)"sudoku", (char *)"gen", (char *)"", 0, 0, 'G', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, @@ -87,6 +88,7 @@ UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); #else bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); @@ -122,6 +124,8 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) return(rogue_players(txfee,cp,params)); else if ( strcmp(method,"games") == 0 ) return(rogue_games(txfee,cp,params)); + else if ( strcmp(method,"setname") == 0 ) + return(rogue_setname(txfee,cp,params)); else { result.push_back(Pair("result","error")); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 7fdc4f53a..4f287333e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1094,6 +1094,27 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } +UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); char *namestr = 0; + rogue_univalue(result,"setname",-1,-1); + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n > 0 ) + { + if ( (namestr= jstri(params,0)) != 0 ) + { + result.push_back(Pair("result","success")); + result.push_back(Pair("name",namestr)); + return(result); + } + } + } + result.push_back(Pair("result","error")); + result.push_back(Pair("error","couldnt get name")); + return(result); +} + bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { return(true); From e87a92b347eb24c902d79593d5b569f09f53bbdf Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 19:20:33 -1100 Subject: [PATCH 0609/1145] Rogue_pname --- src/cc/rogue_rpc.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 4f287333e..d19b24fd6 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -22,6 +22,7 @@ #define ROGUE_MAXPLAYERS 64 // need to send unused fees back to globalCC address to prevent leeching #define ROGUE_MAXKEYSTROKESGAP 60 #define ROGUE_MAXITERATIONS 777 +std::string Rogue_pname = "fred"; /* Roguelander - using highlander competition between rogue players @@ -871,9 +872,9 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { UniValue obj; struct rogue_player P; if ( pname.size() == 0 ) - pname = "fred"; + pname = Rogue_pname; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); - fprintf(stderr,"found baton %s numkeys.%d seed.%llu playerdata.%d\n",batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname,batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { From e543773eb1614c94d88cab67afad6fa4f0c8c8bf Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 19:21:45 -1100 Subject: [PATCH 0610/1145] Syntax --- src/cc/rogue_rpc.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d19b24fd6..f37d587ea 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -874,7 +874,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( pname.size() == 0 ) pname = Rogue_pname; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); - fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname,batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -1097,7 +1097,7 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); char *namestr = 0; + UniValue result(UniValue::VOBJ); int32_t n; char *namestr = 0; rogue_univalue(result,"setname",-1,-1); if ( (params= cclib_reparse(&n,params)) != 0 ) { @@ -1107,6 +1107,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { result.push_back(Pair("result","success")); result.push_back(Pair("name",namestr)); + Rogue_pname = namestr; return(result); } } From 25fc96b97fbc55a257fdced3cf37838e8894e464 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 19:38:13 -1100 Subject: [PATCH 0611/1145] In game whom --- src/cc/rogue/command.c | 5 +++-- src/cc/rogue/extern.c | 2 +- src/cc/rogue/rogue.c | 4 ++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index e78e6b055..9446d704f 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -312,8 +312,9 @@ over: after = FALSE; msg(rs,"version %s. (mctesq was here)", release); when 'S': - after = FALSE; - save_game(rs); + msg(rs,"Saving is disabled, use bailout rpc"); + after = FALSE; + //save_game(rs); when '.': ; /* Rest command */ when ' ': after = FALSE; /* "Legal" illegal command */ when '^': diff --git a/src/cc/rogue/extern.c b/src/cc/rogue/extern.c index b84e6fa7b..39a48b23f 100644 --- a/src/cc/rogue/extern.c +++ b/src/cc/rogue/extern.c @@ -452,7 +452,7 @@ void externs_clear() memset(p_colors,0,sizeof(p_colors)); memset(prbuf,0,sizeof(prbuf)); memset(r_stones,0,sizeof(r_stones)); - memset(whoami,0,sizeof(whoami)); + //memset(whoami,0,sizeof(whoami)); memset(ws_made,0,sizeof(ws_made)); memset(ws_type,0,sizeof(ws_type)); runch = 0; /* Direction player is running */ diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index b4b1b7d15..038ce3b0b 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -365,8 +365,8 @@ int rogue(int argc, char **argv, char **envp) if ((env = getenv("ROGUEOPTS")) != NULL) parse_opts(env); - if (env == NULL || whoami[0] == '\0') - strucpy(whoami, md_getusername(), (int) strlen(md_getusername())); + //if (env == NULL || whoami[0] == '\0') + // strucpy(whoami, md_getusername(), (int) strlen(md_getusername())); lowtime = (int) time(NULL); #ifdef MASTER if (wizard && getenv("SEED") != NULL) From 9db89931776503735286f012168f723f8e25151f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 12 Feb 2019 20:19:46 -1100 Subject: [PATCH 0612/1145] STANDALONE --- src/cc/rogue/main.c | 4 ++++ src/cc/rogue/rogue.c | 6 +++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index a41e51dc3..21c52deab 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -190,7 +190,11 @@ int32_t safecopy(char *dest,char *src,long len) #define true 1 #define false 0 +#ifdef STANDALONE +#include "../komodo/src/komodo_cJSON.c" +#else #include "../../komodo_cJSON.c" +#endif int32_t rogue_replay(uint64_t seed,int32_t sleeptime); int rogue(int argc, char **argv, char **envp); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 038ce3b0b..00cda9426 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -15,7 +15,11 @@ #include #include #include "rogue.h" +#ifdef STANDALONE +#include "../komodo/src/komodo_cJSON.h" +#else #include "../../komodo_cJSON.h" +#endif /* * main: @@ -175,7 +179,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) if ( (pname= jstr(item,"pname")) != 0 && strlen(pname) < MAXSTR-1 ) strcpy(whoami,pname); decode_hex((uint8_t *)&rs->P,(int32_t)strlen(datastr)/2,datastr); - //fprintf(stderr,"set datastr[%d]\n",(int32_t)strlen(datastr)); + fprintf(stderr,"set pname[%s] %s\n",pname==0?"":pname,jprint(item,0)); rs->restoring = 1; } } From 3774bde4bb8e15db494dc62c9949df257d2eea2c Mon Sep 17 00:00:00 2001 From: dimxy Date: Wed, 13 Feb 2019 13:15:10 +0500 Subject: [PATCH 0613/1145] added mytokenorders rpc --- src/cc/CCassets.h | 2 +- src/cc/CCassetstx.cpp | 130 ++++++++++++++++++++------------------- src/rpc/server.cpp | 1 + src/rpc/server.h | 1 + src/wallet/rpcwallet.cpp | 38 ++++++++---- 5 files changed, 96 insertions(+), 76 deletions(-) diff --git a/src/cc/CCassets.h b/src/cc/CCassets.h index 82fbcb961..036ba1340 100644 --- a/src/cc/CCassets.h +++ b/src/cc/CCassets.h @@ -47,7 +47,7 @@ bool AssetCalcAmounts(struct CCcontract_info *cpAssets, int64_t &inputs, int64_t //int64_t GetAssetBalance(CPubKey pk,uint256 tokenid); // --> GetTokenBalance() int64_t AddAssetInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, CPubKey pk, uint256 assetid, int64_t total, int32_t maxinputs); -UniValue AssetOrders(uint256 tokenid); +UniValue AssetOrders(uint256 tokenid, CPubKey pubkey); //UniValue AssetInfo(uint256 tokenid); //UniValue AssetList(); //std::string CreateAsset(int64_t txfee,int64_t assetsupply,std::string name,std::string description); diff --git a/src/cc/CCassetstx.cpp b/src/cc/CCassetstx.cpp index 7673724f1..2b77e99bb 100644 --- a/src/cc/CCassetstx.cpp +++ b/src/cc/CCassetstx.cpp @@ -66,100 +66,102 @@ int64_t AddAssetInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK } */ -UniValue AssetOrders(uint256 refassetid) +UniValue AssetOrders(uint256 refassetid, CPubKey pk) { static uint256 zero; UniValue result(UniValue::VARR); + struct CCcontract_info *cpAssets, assetsC; + struct CCcontract_info *cpTokens, tokensC; + + cpAssets = CCinit(&assetsC, EVAL_ASSETS); + cpTokens = CCinit(&assetsC, EVAL_TOKENS); + auto addOrders = [&](struct CCcontract_info *cp, std::vector >::const_iterator it) { uint256 txid, hashBlock, assetid, assetid2; int64_t price; std::vector origpubkey; - CTransaction vintx; + CTransaction ordertx; uint8_t funcid, evalCode; - char numstr[32], funcidstr[16], origaddr[64], assetidstr[65]; + char numstr[32], funcidstr[16], origaddr[64], origtokenaddr[64], assetidstr[65]; txid = it->first.txhash; //std::cerr << "addOrders() txid=" << txid.GetHex() << std::endl; - if ( GetTransaction(txid, vintx, hashBlock, false) != 0 ) + if ( GetTransaction(txid, ordertx, hashBlock, false) != 0 ) { // for logging: funcid = DecodeAssetOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey); - //std::cerr << "addOrders() vintx.vout.size()=" << vintx.vout.size() << " funcid=" << (char)(funcid ? funcid : ' ') << " assetid=" << assetid.GetHex() << std::endl; - if (vintx.vout.size() > 0 && (funcid = DecodeAssetTokenOpRet(vintx.vout[vintx.vout.size()-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey)) != 0) + if (ordertx.vout.size() > 0 && (funcid = DecodeAssetTokenOpRet(ordertx.vout[ordertx.vout.size()-1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey)) != 0) { - if (refassetid != zero && assetid != refassetid) - { - //int32_t z; - //for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&txid)[z]); - //fprintf(stderr," txid\n"); - //for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&assetid)[z]); - //fprintf(stderr," assetid\n"); - //for (z=31; z>=0; z--) fprintf(stderr,"%02x",((uint8_t *)&refassetid)[z]); - //fprintf(stderr," refassetid\n"); - return; - } + LOGSTREAM("ccassets", CCLOG_DEBUG2, stream << "addOrders() checking ordertx.vout.size()=" << ordertx.vout.size() << " funcid=" << (char)(funcid ? funcid : ' ') << " assetid=" << assetid.GetHex() << std::endl); - //std::cerr << "addOrders() it->first.index=" << it->first.index << " vintx.vout[it->first.index].nValue=" << vintx.vout[it->first.index].nValue << std::endl; - if (vintx.vout[it->first.index].nValue == 0) - return; + if (refassetid != zero && assetid != refassetid || + pk.IsValid() && pk == pubkey2pk(origpubkey) && (funcid == 'S' || funcid == 's')) + { - UniValue item(UniValue::VOBJ); + LOGSTREAM("ccassets", CCLOG_DEBUG2, stream << "addOrders() it->first.index=" << it->first.index << " ordertx.vout[it->first.index].nValue=" << ordertx.vout[it->first.index].nValue << std::endl); + if (ordertx.vout[it->first.index].nValue == 0) { + LOGSTREAM("ccassets", CCLOG_DEBUG2, stream << "addOrders() order with value=0 skipped" << std::endl); + return; + } - funcidstr[0] = funcid; - funcidstr[1] = 0; - item.push_back(Pair("funcid", funcidstr)); - item.push_back(Pair("txid", uint256_str(assetidstr,txid))); - item.push_back(Pair("vout", (int64_t)it->first.index)); - if ( funcid == 'b' || funcid == 'B' ) - { - sprintf(numstr,"%.8f",(double)vintx.vout[it->first.index].nValue/COIN); - item.push_back(Pair("amount",numstr)); - sprintf(numstr,"%.8f",(double)vintx.vout[0].nValue/COIN); - item.push_back(Pair("bidamount",numstr)); - } - else - { - sprintf(numstr,"%llu",(long long)vintx.vout[it->first.index].nValue); - item.push_back(Pair("amount",numstr)); - sprintf(numstr,"%llu",(long long)vintx.vout[0].nValue); - item.push_back(Pair("askamount",numstr)); - } - if ( origpubkey.size() == 33 ) - { - GetCCaddress(cp, origaddr, pubkey2pk(origpubkey)); // TODO: what is this? is it asset or token?? - item.push_back(Pair("origaddress", origaddr)); - } - if ( assetid != zeroid ) - item.push_back(Pair("tokenid",uint256_str(assetidstr,assetid))); - if ( assetid2 != zeroid ) - item.push_back(Pair("otherid",uint256_str(assetidstr,assetid2))); - if ( price > 0 ) - { - if ( funcid == 's' || funcid == 'S' || funcid == 'e' || funcid == 'e' ) + UniValue item(UniValue::VOBJ); + + funcidstr[0] = funcid; + funcidstr[1] = 0; + item.push_back(Pair("funcid", funcidstr)); + item.push_back(Pair("txid", uint256_str(assetidstr, txid))); + item.push_back(Pair("vout", (int64_t)it->first.index)); + if (funcid == 'b' || funcid == 'B') { - sprintf(numstr,"%.8f",(double)price / COIN); - item.push_back(Pair("totalrequired", numstr)); - sprintf(numstr,"%.8f",(double)price / (COIN * vintx.vout[0].nValue)); - item.push_back(Pair("price", numstr)); + sprintf(numstr, "%.8f", (double)ordertx.vout[it->first.index].nValue / COIN); + item.push_back(Pair("amount", numstr)); + sprintf(numstr, "%.8f", (double)ordertx.vout[0].nValue / COIN); + item.push_back(Pair("bidamount", numstr)); } else { - item.push_back(Pair("totalrequired", (int64_t)price)); - sprintf(numstr,"%.8f",(double)vintx.vout[0].nValue / (price * COIN)); - item.push_back(Pair("price",numstr)); + sprintf(numstr, "%llu", (long long)ordertx.vout[it->first.index].nValue); + item.push_back(Pair("amount", numstr)); + sprintf(numstr, "%llu", (long long)ordertx.vout[0].nValue); + item.push_back(Pair("askamount", numstr)); } + if (origpubkey.size() == 33) + { + GetCCaddress(cp, origaddr, pubkey2pk(origpubkey)); + item.push_back(Pair("origaddress", origaddr)); + GetTokensCCaddress(cpTokens, origtokenaddr, pubkey2pk(origpubkey)); + item.push_back(Pair("origtokenaddress", origtokenaddr)); + + } + if (assetid != zeroid) + item.push_back(Pair("tokenid", uint256_str(assetidstr, assetid))); + if (assetid2 != zeroid) + item.push_back(Pair("otherid", uint256_str(assetidstr, assetid2))); + if (price > 0) + { + if (funcid == 's' || funcid == 'S' || funcid == 'e' || funcid == 'e') + { + sprintf(numstr, "%.8f", (double)price / COIN); + item.push_back(Pair("totalrequired", numstr)); + sprintf(numstr, "%.8f", (double)price / (COIN * ordertx.vout[0].nValue)); + item.push_back(Pair("price", numstr)); + } + else + { + item.push_back(Pair("totalrequired", (int64_t)price)); + sprintf(numstr, "%.8f", (double)ordertx.vout[0].nValue / (price * COIN)); + item.push_back(Pair("price", numstr)); + } + } + result.push_back(item); + LOGSTREAM("ccassets", CCLOG_DEBUG1, stream << "addOrders() added order funcId=" << (char)(funcid ? funcid : ' ') << " it->first.index=" << it->first.index << " ordertx.vout[it->first.index].nValue=" << ordertx.vout[it->first.index].nValue << " tokenid=" << assetid.GetHex() << std::endl); } - result.push_back(item); - //fprintf(stderr,"addOrders() func.(%c) %s/v%d %.8f\n",funcid,uint256_str(assetidstr,txid),(int32_t)it->first.index,(double)vintx.vout[it->first.index].nValue/COIN); } } }; std::vector > unspentOutputsTokens, unspentOutputsCoins; - struct CCcontract_info *cpAssets, assetsC; - - cpAssets = CCinit(&assetsC, EVAL_ASSETS); char assetsUnspendableAddr[64]; GetCCaddress(cpAssets, assetsUnspendableAddr, GetUnspendable(cpAssets, NULL)); diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index d870e627c..98b5deccc 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -499,6 +499,7 @@ static const CRPCCommand vRPCCommands[] = { "tokens", "tokeninfo", &tokeninfo, true }, { "tokens", "tokenlist", &tokenlist, true }, { "tokens", "tokenorders", &tokenorders, true }, + { "tokens", "mytokenorders", &mytokenorders, true }, { "tokens", "tokenaddress", &tokenaddress, true }, { "tokens", "tokenbalance", &tokenbalance, true }, { "tokens", "tokencreate", &tokencreate, true }, diff --git a/src/rpc/server.h b/src/rpc/server.h index a2aba895b..9cacce8ac 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -241,6 +241,7 @@ extern UniValue coinsupply(const UniValue& params, bool fHelp); extern UniValue tokeninfo(const UniValue& params, bool fHelp); extern UniValue tokenlist(const UniValue& params, bool fHelp); extern UniValue tokenorders(const UniValue& params, bool fHelp); +extern UniValue mytokenorders(const UniValue& params, bool fHelp); extern UniValue tokenbalance(const UniValue& params, bool fHelp); extern UniValue assetsaddress(const UniValue& params, bool fHelp); extern UniValue tokenaddress(const UniValue& params, bool fHelp); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index c0f9dc297..643381648 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -7038,8 +7038,8 @@ UniValue tokenorders(const UniValue& params, bool fHelp) { uint256 tokenid; if ( fHelp || params.size() > 1 ) - throw runtime_error("tokenorders [tokenid]\n"); - if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) + throw runtime_error("tokenorders tokenid\n"); + if (ensure_CCrequirements(EVAL_ASSETS) < 0 || ensure_CCrequirements(EVAL_TOKENS) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7048,9 +7048,25 @@ UniValue tokenorders(const UniValue& params, bool fHelp) if (tokenid == zeroid) throw runtime_error("incorrect tokenid\n"); } - else - memset(&tokenid,0,sizeof(tokenid)); - return(AssetOrders(tokenid)); + else { + // memset(&tokenid, 0, sizeof(tokenid)); + throw runtime_error("no tokenid\n"); + } + return(AssetOrders(tokenid, CPubKey())); +} + + +UniValue mytokenorders(const UniValue& params, bool fHelp) +{ + uint256 tokenid; + if (fHelp || params.size() > 1) + throw runtime_error("mytokenorders\n"); + if (ensure_CCrequirements(EVAL_ASSETS) < 0 || ensure_CCrequirements(EVAL_TOKENS) < 0) + throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); + const CKeyStore& keystore = *pwalletMain; + LOCK2(cs_main, pwalletMain->cs_wallet); + + return(AssetOrders(zeroid, Mypubkey())); } UniValue tokenbalance(const UniValue& params, bool fHelp) @@ -7235,7 +7251,7 @@ UniValue tokenbid(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); int64_t bidamount,numtokens; std::string hex; double price; uint256 tokenid; if ( fHelp || params.size() != 3 ) throw runtime_error("tokenbid numtokens tokenid price\n"); - if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) + if (ensure_CCrequirements(EVAL_ASSETS) < 0 || ensure_CCrequirements(EVAL_TOKENS) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7277,7 +7293,7 @@ UniValue tokencancelbid(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string hex; int32_t i; uint256 tokenid,bidtxid; if ( fHelp || params.size() != 2 ) throw runtime_error("tokencancelbid tokenid bidtxid\n"); - if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) + if (ensure_CCrequirements(EVAL_ASSETS) < 0 || ensure_CCrequirements(EVAL_TOKENS) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7302,7 +7318,7 @@ UniValue tokenfillbid(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); int64_t fillamount; std::string hex; uint256 tokenid,bidtxid; if ( fHelp || params.size() != 3 ) throw runtime_error("tokenfillbid tokenid bidtxid fillamount\n"); - if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) + if (ensure_CCrequirements(EVAL_ASSETS) < 0 || ensure_CCrequirements(EVAL_TOKENS) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7334,7 +7350,7 @@ UniValue tokenask(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); int64_t askamount,numtokens; std::string hex; double price; uint256 tokenid; if ( fHelp || params.size() != 3 ) throw runtime_error("tokenask numtokens tokenid price\n"); - if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) + if (ensure_CCrequirements(EVAL_ASSETS) < 0 || ensure_CCrequirements(EVAL_TOKENS) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7396,7 +7412,7 @@ UniValue tokencancelask(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); std::string hex; int32_t i; uint256 tokenid,asktxid; if ( fHelp || params.size() != 2 ) throw runtime_error("tokencancelask tokenid asktxid\n"); - if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) + if (ensure_CCrequirements(EVAL_ASSETS) < 0 || ensure_CCrequirements(EVAL_TOKENS) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); @@ -7421,7 +7437,7 @@ UniValue tokenfillask(const UniValue& params, bool fHelp) UniValue result(UniValue::VOBJ); int64_t fillunits; std::string hex; uint256 tokenid,asktxid; if ( fHelp || params.size() != 3 ) throw runtime_error("tokenfillask tokenid asktxid fillunits\n"); - if ( ensure_CCrequirements(EVAL_ASSETS) < 0 ) + if (ensure_CCrequirements(EVAL_ASSETS) < 0 || ensure_CCrequirements(EVAL_TOKENS) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); From ea78447b3bd67821848a88016cabc533de403baa Mon Sep 17 00:00:00 2001 From: dimxy Date: Wed, 13 Feb 2019 13:49:04 +0500 Subject: [PATCH 0614/1145] corr if selecting ordertx --- src/cc/CCassetstx.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/CCassetstx.cpp b/src/cc/CCassetstx.cpp index 2b77e99bb..872fd1b72 100644 --- a/src/cc/CCassetstx.cpp +++ b/src/cc/CCassetstx.cpp @@ -87,7 +87,7 @@ UniValue AssetOrders(uint256 refassetid, CPubKey pk) char numstr[32], funcidstr[16], origaddr[64], origtokenaddr[64], assetidstr[65]; txid = it->first.txhash; - //std::cerr << "addOrders() txid=" << txid.GetHex() << std::endl; + LOGSTREAM("ccassets", CCLOG_DEBUG2, stream << "addOrders() checking txid=" << txid.GetHex() << std::endl); if ( GetTransaction(txid, ordertx, hashBlock, false) != 0 ) { // for logging: funcid = DecodeAssetOpRet(vintx.vout[vintx.vout.size() - 1].scriptPubKey, evalCode, assetid, assetid2, price, origpubkey); @@ -95,8 +95,8 @@ UniValue AssetOrders(uint256 refassetid, CPubKey pk) { LOGSTREAM("ccassets", CCLOG_DEBUG2, stream << "addOrders() checking ordertx.vout.size()=" << ordertx.vout.size() << " funcid=" << (char)(funcid ? funcid : ' ') << " assetid=" << assetid.GetHex() << std::endl); - if (refassetid != zero && assetid != refassetid || - pk.IsValid() && pk == pubkey2pk(origpubkey) && (funcid == 'S' || funcid == 's')) + if (refassetid != zero && assetid == refassetid || + pk != CPubKey() && pk == pubkey2pk(origpubkey) && (funcid == 'S' || funcid == 's')) { LOGSTREAM("ccassets", CCLOG_DEBUG2, stream << "addOrders() it->first.index=" << it->first.index << " ordertx.vout[it->first.index].nValue=" << ordertx.vout[it->first.index].nValue << std::endl); From 1446f33ba8e7692ca0f3692cc1a1695955e741c9 Mon Sep 17 00:00:00 2001 From: dimxy Date: Wed, 13 Feb 2019 14:36:15 +0500 Subject: [PATCH 0615/1145] corr cp init --- src/cc/CCassetstx.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/cc/CCassetstx.cpp b/src/cc/CCassetstx.cpp index 872fd1b72..dde7666ab 100644 --- a/src/cc/CCassetstx.cpp +++ b/src/cc/CCassetstx.cpp @@ -75,7 +75,7 @@ UniValue AssetOrders(uint256 refassetid, CPubKey pk) struct CCcontract_info *cpTokens, tokensC; cpAssets = CCinit(&assetsC, EVAL_ASSETS); - cpTokens = CCinit(&assetsC, EVAL_TOKENS); + cpTokens = CCinit(&tokensC, EVAL_TOKENS); auto addOrders = [&](struct CCcontract_info *cp, std::vector >::const_iterator it) { @@ -169,9 +169,11 @@ UniValue AssetOrders(uint256 refassetid, CPubKey pk) char assetsTokensUnspendableAddr[64]; std::vector vopretNonfungible; - GetNonfungibleData(refassetid, vopretNonfungible); - if (vopretNonfungible.size() > 0) - cpAssets->additionalTokensEvalcode2 = vopretNonfungible.begin()[0]; + if (refassetid != zeroid) { + GetNonfungibleData(refassetid, vopretNonfungible); + if (vopretNonfungible.size() > 0) + cpAssets->additionalTokensEvalcode2 = vopretNonfungible.begin()[0]; + } GetTokensCCaddress(cpAssets, assetsTokensUnspendableAddr, GetUnspendable(cpAssets, NULL)); SetCCunspents(unspentOutputsTokens, assetsTokensUnspendableAddr); From 0b16f3942c979e01593930ef822aeca1b6580dea Mon Sep 17 00:00:00 2001 From: dimxy Date: Wed, 13 Feb 2019 17:34:31 +0500 Subject: [PATCH 0616/1145] added non-fungible eval code param --- src/cc/CCassets.h | 2 +- src/cc/CCassetstx.cpp | 23 ++++++++++++++++++----- src/wallet/rpcwallet.cpp | 12 ++++++++---- 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/src/cc/CCassets.h b/src/cc/CCassets.h index 036ba1340..af9ec5bd1 100644 --- a/src/cc/CCassets.h +++ b/src/cc/CCassets.h @@ -47,7 +47,7 @@ bool AssetCalcAmounts(struct CCcontract_info *cpAssets, int64_t &inputs, int64_t //int64_t GetAssetBalance(CPubKey pk,uint256 tokenid); // --> GetTokenBalance() int64_t AddAssetInputs(struct CCcontract_info *cp, CMutableTransaction &mtx, CPubKey pk, uint256 assetid, int64_t total, int32_t maxinputs); -UniValue AssetOrders(uint256 tokenid, CPubKey pubkey); +UniValue AssetOrders(uint256 tokenid, CPubKey pubkey, uint8_t additionalEvalCode); //UniValue AssetInfo(uint256 tokenid); //UniValue AssetList(); //std::string CreateAsset(int64_t txfee,int64_t assetsupply,std::string name,std::string description); diff --git a/src/cc/CCassetstx.cpp b/src/cc/CCassetstx.cpp index dde7666ab..14be084b4 100644 --- a/src/cc/CCassetstx.cpp +++ b/src/cc/CCassetstx.cpp @@ -66,7 +66,7 @@ int64_t AddAssetInputs(struct CCcontract_info *cp,CMutableTransaction &mtx,CPubK } */ -UniValue AssetOrders(uint256 refassetid, CPubKey pk) +UniValue AssetOrders(uint256 refassetid, CPubKey pk, uint8_t additionalEvalCode) { static uint256 zero; UniValue result(UniValue::VARR); @@ -161,7 +161,7 @@ UniValue AssetOrders(uint256 refassetid, CPubKey pk) } }; - std::vector > unspentOutputsTokens, unspentOutputsCoins; + std::vector > unspentOutputsTokens, unspentOutputsDualEvalTokens, unspentOutputsCoins; char assetsUnspendableAddr[64]; GetCCaddress(cpAssets, assetsUnspendableAddr, GetUnspendable(cpAssets, NULL)); @@ -177,18 +177,31 @@ UniValue AssetOrders(uint256 refassetid, CPubKey pk) GetTokensCCaddress(cpAssets, assetsTokensUnspendableAddr, GetUnspendable(cpAssets, NULL)); SetCCunspents(unspentOutputsTokens, assetsTokensUnspendableAddr); - // tokenasks: + // tokenbids: for (std::vector >::const_iterator itCoins = unspentOutputsCoins.begin(); itCoins != unspentOutputsCoins.end(); itCoins++) addOrders(cpAssets, itCoins); - // tokenbids: + // tokenasks: for (std::vector >::const_iterator itTokens = unspentOutputsTokens.begin(); itTokens != unspentOutputsTokens.end(); itTokens++) addOrders(cpAssets, itTokens); - + + if (additionalEvalCode != 0) { //this would be mytokenorders + char assetsDualEvalTokensUnspendableAddr[64]; + + // try also dual eval tokenasks (and we do not need bids): + cpAssets->additionalTokensEvalcode2 = additionalEvalCode; + GetTokensCCaddress(cpAssets, assetsDualEvalTokensUnspendableAddr, GetUnspendable(cpAssets, NULL)); + SetCCunspents(unspentOutputsDualEvalTokens, assetsDualEvalTokensUnspendableAddr); + + for (std::vector >::const_iterator itDualEvalTokens = unspentOutputsDualEvalTokens.begin(); + itDualEvalTokens != unspentOutputsDualEvalTokens.end(); + itDualEvalTokens++) + addOrders(cpAssets, itDualEvalTokens); + } return(result); } diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 643381648..220b1e30d 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -7052,21 +7052,25 @@ UniValue tokenorders(const UniValue& params, bool fHelp) // memset(&tokenid, 0, sizeof(tokenid)); throw runtime_error("no tokenid\n"); } - return(AssetOrders(tokenid, CPubKey())); + return AssetOrders(tokenid, CPubKey(), 0); } UniValue mytokenorders(const UniValue& params, bool fHelp) { uint256 tokenid; - if (fHelp || params.size() > 1) - throw runtime_error("mytokenorders\n"); + if (fHelp || params.size() > 2) + throw runtime_error("mytokenorders [evalcode]\n"); if (ensure_CCrequirements(EVAL_ASSETS) < 0 || ensure_CCrequirements(EVAL_TOKENS) < 0) throw runtime_error("to use CC contracts, you need to launch daemon with valid -pubkey= for an address in your wallet\n"); const CKeyStore& keystore = *pwalletMain; LOCK2(cs_main, pwalletMain->cs_wallet); - return(AssetOrders(zeroid, Mypubkey())); + uint8_t additionalEvalCode = 0; + if (params.size() == 1) + additionalEvalCode = atoi(params[0].get_str().c_str()); + + return AssetOrders(zeroid, Mypubkey(), additionalEvalCode); } UniValue tokenbalance(const UniValue& params, bool fHelp) From 9e855f8224e50ef6989c0bbe552aa274bee68892 Mon Sep 17 00:00:00 2001 From: dimxy Date: Wed, 13 Feb 2019 17:57:22 +0500 Subject: [PATCH 0617/1145] changed to strtol in mytokenorders --- src/wallet/rpcwallet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 220b1e30d..5564c2000 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -7068,7 +7068,7 @@ UniValue mytokenorders(const UniValue& params, bool fHelp) uint8_t additionalEvalCode = 0; if (params.size() == 1) - additionalEvalCode = atoi(params[0].get_str().c_str()); + additionalEvalCode = strtol(params[0].get_str().c_str(), NULL, 0); // supports also 0xEE-like values return AssetOrders(zeroid, Mypubkey(), additionalEvalCode); } From 1917708467bb4fa454ae191596c3353a08791d41 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 13 Feb 2019 06:35:56 -1100 Subject: [PATCH 0618/1145] Fix edge case --- src/cc/rogue/command.c | 7 +++++-- src/cc/rogue/main.c | 1 + src/cc/rogue/rogue.h | 10 ++++++++++ src/cc/rogue_rpc.cpp | 31 +++++++++++++++++-------------- 4 files changed, 33 insertions(+), 16 deletions(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index 9446d704f..63aed25be 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -312,9 +312,12 @@ over: after = FALSE; msg(rs,"version %s. (mctesq was here)", release); when 'S': - msg(rs,"Saving is disabled, use bailout rpc"); after = FALSE; - //save_game(rs); +#ifdef STANDALONE + save_game(rs); +#else + msg(rs,"Saving is disabled, use bailout rpc"); +#endif when '.': ; /* Rest command */ when ' ': after = FALSE; /* "Legal" illegal command */ when '^': diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 21c52deab..c3484eafe 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -19,6 +19,7 @@ #include #include #include +#include #define SMALLVAL 0.000000000000001 #define SATOSHIDEN ((uint64_t)100000000L) diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 5eccb2e8c..a407ae8a6 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -17,6 +17,16 @@ #undef lines +#ifdef LINES +#undef LINES +#endif +#ifdef COLS +#undef COLS +#endif + +#define LINES 24 +#define COLS 80 + #define NOOP(x) (x += 0) #define CCHAR(x) ( (char) (x & A_CHARTEXT) ) /* diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f37d587ea..86a633212 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -22,6 +22,23 @@ #define ROGUE_MAXPLAYERS 64 // need to send unused fees back to globalCC address to prevent leeching #define ROGUE_MAXKEYSTROKESGAP 60 #define ROGUE_MAXITERATIONS 777 + +#define MAXPACK 23 +struct rogue_packitem +{ + int32_t type,launch,count,which,hplus,dplus,arm,flags,group; + char damage[8],hurldmg[8]; +}; +struct rogue_player +{ + int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; + struct rogue_packitem roguepack[MAXPACK]; +}; +int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player); +#define ROGUE_DECLARED_PACK +void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item); + + std::string Rogue_pname = "fred"; /* @@ -133,20 +150,6 @@ std::string Rogue_pname = "fred"; // ./c cclib bailout 17 \"[%226d3243c6e5ab383898b28a87e01f6c00b5bdd9687020f17f5caacc8a61febd19%22]\" // ./komodo-cli -ac_name=ROGUE cclib register 17 \"[%22a898f4ceef7647ba113b9f3c24ef045f5d134935a3b09bdd1a997b9d474f4c1b%22,%22f11d0cb4e2e4c21f029a1146f8e5926f11456885b7ab7d665096f5efedec8ea0%22]\" -#define MAXPACK 23 -struct rogue_packitem -{ - int32_t type,launch,count,which,hplus,dplus,arm,flags,group; - char damage[8],hurldmg[8]; -}; -struct rogue_player -{ - int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; - struct rogue_packitem roguepack[MAXPACK]; -}; -int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player); -#define ROGUE_DECLARED_PACK -void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item); CScript rogue_newgameopret(int64_t buyin,int32_t maxplayers) { From 5740e8605efb0ce939b0d5458f0a88ce6e2cc2ac Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 14 Feb 2019 12:01:18 +0100 Subject: [PATCH 0619/1145] add depends include os specific dependency headers --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 08c86dee8..c4fc45dd7 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,7 +1,7 @@ cd rogue; ./configure # only need this first time make; cd .. -gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -lncurses +gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -lncurses #gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so cp librogue.so ../libcc.so From a37e1ae63363c64f1503e9a7c9c306666d3b432c Mon Sep 17 00:00:00 2001 From: dimxy Date: Thu, 14 Feb 2019 23:02:38 +0500 Subject: [PATCH 0620/1145] vopretStripped eliminated in heir cc --- src/cc/heir.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/cc/heir.cpp b/src/cc/heir.cpp index 4fea0be1e..d90f87d07 100644 --- a/src/cc/heir.cpp +++ b/src/cc/heir.cpp @@ -327,16 +327,17 @@ uint8_t _DecodeHeirEitherOpRet(CScript scriptPubKey, uint256 &tokenid, CPubKey& { uint8_t evalCodeTokens = 0; std::vector voutPubkeysDummy; - std::vector vopretExtra, vopretStripped; + std::vector vopretExtra /*, vopretStripped*/; if (DecodeTokenOpRet(scriptPubKey, evalCodeTokens, tokenid, voutPubkeysDummy, vopretExtra) != 0) { if (vopretExtra.size() > 1) { // restore the second opret: - if (!E_UNMARSHAL(vopretExtra, { ss >> vopretStripped; })) { //strip string size + /* unmarshalled in DecodeTokenOpRet: + if (!E_UNMARSHAL(vopretExtra, { ss >> vopretStripped; })) { //strip string size if (!noLogging) std::cerr << "_DecodeHeirEitherOpret() could not unmarshal vopretStripped" << std::endl; return (uint8_t)0; - } + }*/ } else { if (!noLogging) std::cerr << "_DecodeHeirEitherOpret() empty vopretExtra" << std::endl; @@ -344,10 +345,10 @@ uint8_t _DecodeHeirEitherOpRet(CScript scriptPubKey, uint256 &tokenid, CPubKey& } } else { - GetOpReturnData(scriptPubKey, vopretStripped); + GetOpReturnData(scriptPubKey, vopretExtra); } - return _DecodeHeirOpRet(vopretStripped, ownerPubkey, heirPubkey, inactivityTime, heirName, memo, fundingTxidInOpret, hasHeirSpendingBegun, noLogging); + return _DecodeHeirOpRet(vopretExtra, ownerPubkey, heirPubkey, inactivityTime, heirName, memo, fundingTxidInOpret, hasHeirSpendingBegun, noLogging); } // overload to decode opret in fundingtxid: From dc739bc9daac0bff64c829adbe3de87018676f00 Mon Sep 17 00:00:00 2001 From: dimxy Date: Thu, 14 Feb 2019 23:33:34 +0500 Subject: [PATCH 0621/1145] empty if{} removed --- src/cc/heir.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/cc/heir.cpp b/src/cc/heir.cpp index d90f87d07..aca30208b 100644 --- a/src/cc/heir.cpp +++ b/src/cc/heir.cpp @@ -330,16 +330,16 @@ uint8_t _DecodeHeirEitherOpRet(CScript scriptPubKey, uint256 &tokenid, CPubKey& std::vector vopretExtra /*, vopretStripped*/; if (DecodeTokenOpRet(scriptPubKey, evalCodeTokens, tokenid, voutPubkeysDummy, vopretExtra) != 0) { - if (vopretExtra.size() > 1) { - // restore the second opret: + /* if (vopretExtra.size() > 1) { + // restore the second opret: - /* unmarshalled in DecodeTokenOpRet: + /* unmarshalled in DecodeTokenOpRet: if (!E_UNMARSHAL(vopretExtra, { ss >> vopretStripped; })) { //strip string size - if (!noLogging) std::cerr << "_DecodeHeirEitherOpret() could not unmarshal vopretStripped" << std::endl; - return (uint8_t)0; - }*/ - } - else { + if (!noLogging) std::cerr << "_DecodeHeirEitherOpret() could not unmarshal vopretStripped" << std::endl; + return (uint8_t)0; + } + } */ + if (vopretExtra.size() < 1) { if (!noLogging) std::cerr << "_DecodeHeirEitherOpret() empty vopretExtra" << std::endl; return (uint8_t)0; } From 28ee0fd7565a4ac9247be588e2af67af4c711b95 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 14 Feb 2019 20:24:44 -1100 Subject: [PATCH 0622/1145] -fred --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 86a633212..e2e427545 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -39,7 +39,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item); -std::string Rogue_pname = "fred"; +std::string Rogue_pname = ""; /* Roguelander - using highlander competition between rogue players @@ -403,7 +403,7 @@ UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint obj.push_back(Pair("experience",(int64_t)P.experience)); obj.push_back(Pair("dungeonlevel",(int64_t)P.dungeonlevel)); obj.push_back(Pair("chain",symbol)); - obj.push_back(Pair("name",pname)); + obj.push_back(Pair("pname",pname)); return(obj); } From b6e147e4d81b7aabbda58a0940ac1b7eb96ac243 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 14 Feb 2019 20:42:03 -1100 Subject: [PATCH 0623/1145] pname --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e2e427545..70a4b842e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1109,7 +1109,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( (namestr= jstri(params,0)) != 0 ) { result.push_back(Pair("result","success")); - result.push_back(Pair("name",namestr)); + result.push_back(Pair("pname",namestr)); Rogue_pname = namestr; return(result); } From b6f1f8cf13b52469f3be607b3bbe7de47b693e47 Mon Sep 17 00:00:00 2001 From: Mihailo Milenkovic Date: Fri, 15 Feb 2019 11:10:36 +0100 Subject: [PATCH 0624/1145] Fix for new DecodeTokenOpRet --- src/cc/channels.cpp | 6 +++--- src/cc/gateways.cpp | 20 ++++++++------------ 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/src/cc/channels.cpp b/src/cc/channels.cpp index ca069ee57..fd20314bb 100644 --- a/src/cc/channels.cpp +++ b/src/cc/channels.cpp @@ -106,12 +106,12 @@ CScript EncodeChannelsOpRet(uint8_t funcid,uint256 tokenid,uint256 opentxid,CPub uint8_t DecodeChannelsOpRet(const CScript &scriptPubKey, uint256 &tokenid, uint256 &opentxid, CPubKey &srcpub,CPubKey &destpub,int32_t &numpayments,int64_t &payment,uint256 &hashchain) { - std::vector vopret; uint8_t *script,e,f,tokenevalcode; - std::vector pubkeys; std::vector vOpretExtra; + std::vector vopret,vOpretExtra; uint8_t *script,e,f,tokenevalcode; + std::vector pubkeys; if (DecodeTokenOpRet(scriptPubKey,tokenevalcode,tokenid,pubkeys,vOpretExtra)!=0 && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) { - if (!E_UNMARSHAL(vOpretExtra, { ss >> vopret; })) return (0); + vopret=vOpretExtra; } else GetOpReturnData(scriptPubKey, vopret); if ( vopret.size() > 2 ) diff --git a/src/cc/gateways.cpp b/src/cc/gateways.cpp index 41cd37e3a..5d803a80e 100644 --- a/src/cc/gateways.cpp +++ b/src/cc/gateways.cpp @@ -167,12 +167,11 @@ CScript EncodeGatewaysBindOpRet(uint8_t funcid,uint256 tokenid,std::string coin, uint8_t DecodeGatewaysBindOpRet(char *depositaddr,const CScript &scriptPubKey,uint256 &tokenid,std::string &coin,int64_t &totalsupply,uint256 &oracletxid,uint8_t &M,uint8_t &N,std::vector &gatewaypubkeys,uint8_t &taddr,uint8_t &prefix,uint8_t &prefix2,uint8_t wiftype) { - std::vector vopret; uint8_t *script,e,f,tokenevalcode; - std::vector vOpretExtra; std::vector pubkeys; + std::vector vopret,vOpretExtra; uint8_t *script,e,f,tokenevalcode; std::vector pubkeys; if (DecodeTokenOpRet(scriptPubKey,tokenevalcode,tokenid,pubkeys,vOpretExtra)!=0 && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) { - if (!E_UNMARSHAL(vOpretExtra, { ss >> vopret; })) return (0); + vopret=vOpretExtra; } else GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); @@ -230,12 +229,11 @@ CScript EncodeGatewaysClaimOpRet(uint8_t funcid,uint256 tokenid,uint256 bindtxid uint8_t DecodeGatewaysClaimOpRet(const CScript &scriptPubKey,uint256 &tokenid,uint256 &bindtxid,std::string &refcoin,uint256 &deposittxid,CPubKey &destpub,int64_t &amount) { - std::vector vopret; uint8_t *script,e,f,tokenevalcode; - std::vector pubkeys; std::vector vOpretExtra; + std::vector vopret,vOpretExtra; uint8_t *script,e,f,tokenevalcode; std::vector pubkeys; if (DecodeTokenOpRet(scriptPubKey,tokenevalcode,tokenid,pubkeys,vOpretExtra)!=0 && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) { - if (!E_UNMARSHAL(vOpretExtra, { ss >> vopret; })) return (0); + vopret=vOpretExtra; } else GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); @@ -260,12 +258,11 @@ CScript EncodeGatewaysWithdrawOpRet(uint8_t funcid,uint256 tokenid,uint256 bindt uint8_t DecodeGatewaysWithdrawOpRet(const CScript &scriptPubKey, uint256& tokenid, uint256 &bindtxid, std::string &refcoin, CPubKey &withdrawpub, int64_t &amount) { - std::vector vopret; uint8_t *script,e,f,tokenevalcode; - std::vector pubkeys; std::vector vOpretExtra; + std::vector vopret,vOpretExtra; uint8_t *script,e,f,tokenevalcode; std::vector pubkeys; if (DecodeTokenOpRet(scriptPubKey,tokenevalcode,tokenid,pubkeys,vOpretExtra)!=0 && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) { - if (!E_UNMARSHAL(vOpretExtra, { ss >> vopret; })) return (0); + vopret=vOpretExtra; } else GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); @@ -339,12 +336,11 @@ uint8_t DecodeGatewaysMarkDoneOpRet(const CScript &scriptPubKey, uint256 &withdr uint8_t DecodeGatewaysOpRet(const CScript &scriptPubKey) { - std::vector vopret; uint8_t *script,e,f,tokenevalcode; - std::vector pubkeys; std::vector vOpretExtra; uint256 tokenid; + std::vector vopret,vOpretExtra; uint8_t *script,e,f,tokenevalcode; std::vector pubkeys; uint256 tokenid; if (DecodeTokenOpRet(scriptPubKey,tokenevalcode,tokenid,pubkeys,vOpretExtra)!=0 && tokenevalcode==EVAL_TOKENS && vOpretExtra.size()>0) { - if (!E_UNMARSHAL(vOpretExtra, { ss >> vopret; })) return (0); + vopret=vOpretExtra; } else GetOpReturnData(scriptPubKey, vopret); script = (uint8_t *)vopret.data(); From def8dd646268a81afd9a3cbf8db4dff4d2e488ab Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 15 Feb 2019 00:45:01 -1100 Subject: [PATCH 0625/1145] (int64_t) in Pair --- src/cc/makecclib | 1 + src/cc/makerogue | 1 + src/cc/rogue_rpc.cpp | 6 +++--- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/cc/makecclib b/src/cc/makecclib index 0aecab072..ea44acdae 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1 +1,2 @@ +#!/bin/sh gcc -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp diff --git a/src/cc/makerogue b/src/cc/makerogue index c4fc45dd7..490576bd1 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,3 +1,4 @@ +#!/bin/sh cd rogue; ./configure # only need this first time make; cd .. diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 70a4b842e..5daca5d1c 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1028,7 +1028,7 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("result","success")); rogue_univalue(result,"pending",-1,-1); result.push_back(Pair("pending",a)); - result.push_back(Pair("numpending",a.size())); + result.push_back(Pair("numpending",(int64_t)a.size())); return(result); } @@ -1055,7 +1055,7 @@ UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } } result.push_back(Pair("playerdata",a)); - result.push_back(Pair("numplayerdata",a.size())); + result.push_back(Pair("numplayerdata",(int64_t)a.size())); return(result); } @@ -1094,7 +1094,7 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } result.push_back(Pair("pastgames",b)); result.push_back(Pair("games",a)); - result.push_back(Pair("numgames",a.size()+b.size())); + result.push_back(Pair("numgames",(int64_t)(a.size()+b.size()))); return(result); } From c9b2389854e7872d2f90d77e40d887af60dd5dbe Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 15 Feb 2019 04:44:22 -1100 Subject: [PATCH 0626/1145] Gather curses dependencies --- src/cc/rogue/armor.c | 2 +- src/cc/rogue/chase.c | 4 +- src/cc/rogue/command.c | 5 +-- src/cc/rogue/daemon.c | 2 +- src/cc/rogue/daemons.c | 2 +- src/cc/rogue/extern.c | 2 +- src/cc/rogue/extern.h | 3 ++ src/cc/rogue/fight.c | 8 ++-- src/cc/rogue/init.c | 8 ++-- src/cc/rogue/io.c | 11 ++--- src/cc/rogue/list.c | 6 +-- src/cc/rogue/mach_dep.c | 3 +- src/cc/rogue/mdport.c | 2 +- src/cc/rogue/misc.c | 8 ++-- src/cc/rogue/monsters.c | 6 +-- src/cc/rogue/move.c | 4 +- src/cc/rogue/new_level.c | 4 +- src/cc/rogue/options.c | 8 ++-- src/cc/rogue/pack.c | 6 +-- src/cc/rogue/passages.c | 4 +- src/cc/rogue/potions.c | 4 +- src/cc/rogue/rings.c | 2 +- src/cc/rogue/rip.c | 14 +++--- src/cc/rogue/rogue.c | 40 +++++++++-------- src/cc/rogue/rogue.h | 91 +++++++++++++++++++++++++++++++++++++- src/cc/rogue/rooms.c | 4 +- src/cc/rogue/save.c | 14 +++--- src/cc/rogue/scrolls.c | 4 +- src/cc/rogue/state.c | 6 +-- src/cc/rogue/sticks.c | 6 +-- src/cc/rogue/things.c | 94 ++++++++++++++++++++-------------------- src/cc/rogue/weapons.c | 6 +-- src/cc/rogue/wizard.c | 8 ++-- 33 files changed, 242 insertions(+), 149 deletions(-) diff --git a/src/cc/rogue/armor.c b/src/cc/rogue/armor.c index 5244628b1..20c5704a8 100644 --- a/src/cc/rogue/armor.c +++ b/src/cc/rogue/armor.c @@ -9,7 +9,7 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include +//#include #include "rogue.h" /* diff --git a/src/cc/rogue/chase.c b/src/cc/rogue/chase.c index 73d53e1fd..059df470d 100644 --- a/src/cc/rogue/chase.c +++ b/src/cc/rogue/chase.c @@ -10,8 +10,8 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include +//#include +//#include #include "rogue.h" #define DRAGONSHOT 5 /* one chance in DRAGONSHOT that a dragon will flame */ diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index 63aed25be..1a32246bb 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -10,10 +10,7 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include -#include -#include +//#include #include "rogue.h" /* diff --git a/src/cc/rogue/daemon.c b/src/cc/rogue/daemon.c index 8309dc642..1da06d499 100644 --- a/src/cc/rogue/daemon.c +++ b/src/cc/rogue/daemon.c @@ -11,7 +11,7 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include +//#include #include "rogue.h" #define EMPTY 0 diff --git a/src/cc/rogue/daemons.c b/src/cc/rogue/daemons.c index 436aa004d..42e685320 100644 --- a/src/cc/rogue/daemons.c +++ b/src/cc/rogue/daemons.c @@ -10,7 +10,7 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include +//#include #include "rogue.h" /* diff --git a/src/cc/rogue/extern.c b/src/cc/rogue/extern.c index 39a48b23f..fdb77307c 100644 --- a/src/cc/rogue/extern.c +++ b/src/cc/rogue/extern.c @@ -10,7 +10,7 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include +//#include #include "rogue.h" diff --git a/src/cc/rogue/extern.h b/src/cc/rogue/extern.h index 486d85ff1..fc3454830 100644 --- a/src/cc/rogue/extern.h +++ b/src/cc/rogue/extern.h @@ -13,6 +13,9 @@ #ifndef H_EXTERN_ROGUE_H #define H_EXTERN_ROGUE_H +#include +#include + #ifdef HAVE_CONFIG_H #ifdef PDCURSES #undef HAVE_UNISTD_H diff --git a/src/cc/rogue/fight.c b/src/cc/rogue/fight.c index 7f4aad587..43474616e 100644 --- a/src/cc/rogue/fight.c +++ b/src/cc/rogue/fight.c @@ -10,10 +10,10 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include -#include -#include +//#include +//#include +//#include +//#include #include "rogue.h" //#define EQSTR(a, b) (strcmp(a, b) == 0) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index 1f63e1d51..1603474e2 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -10,10 +10,10 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include -#include -#include +//#include +//#include +//#include +//#include #include "rogue.h" /* diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 30795f2ad..6791c26a4 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -4,10 +4,10 @@ * @(#)io.c 4.32 (Berkeley) 02/05/99 */ -#include -#include -#include -#include +//#include +//#include +//#include +//#include #include "rogue.h" /* @@ -162,7 +162,8 @@ readchar(struct rogue_state *rs) //fprintf(stderr,"(%c) ",rs->keystrokes[rs->ind]); return(rs->keystrokes[rs->ind++]); } - fprintf(stderr,"replay finished but readchar called\n"); + if ( rs->replaydone != 0 ) + fprintf(stderr,"replay finished but readchar called\n"); rs->replaydone = (uint32_t)time(NULL); //if ( (rand() & 1) == 0 ) // return(ESCAPE); diff --git a/src/cc/rogue/list.c b/src/cc/rogue/list.c index 6affc662c..622af60cd 100644 --- a/src/cc/rogue/list.c +++ b/src/cc/rogue/list.c @@ -10,9 +10,9 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include -#include +//#include +//#include +//#include #include "rogue.h" #ifdef MASTER diff --git a/src/cc/rogue/mach_dep.c b/src/cc/rogue/mach_dep.c index 34e502816..6d0e1c66f 100644 --- a/src/cc/rogue/mach_dep.c +++ b/src/cc/rogue/mach_dep.c @@ -46,7 +46,8 @@ #include #include #include -#include +//#include +#include "rogue.h" #include "extern.h" #define NOOP(x) (x += 0) diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index acd257617..443ef1e60 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -44,7 +44,7 @@ #undef MOUSE_MOVED #endif -#include +//#include #include "extern.h" #if defined(HAVE_SYS_TYPES) diff --git a/src/cc/rogue/misc.c b/src/cc/rogue/misc.c index 168886b6b..7db9d073a 100644 --- a/src/cc/rogue/misc.c +++ b/src/cc/rogue/misc.c @@ -10,10 +10,10 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include -#include -#include +//#include +//#include +//#include +//#include #include "rogue.h" /* diff --git a/src/cc/rogue/monsters.c b/src/cc/rogue/monsters.c index 4649de9a2..2f6d68362 100644 --- a/src/cc/rogue/monsters.c +++ b/src/cc/rogue/monsters.c @@ -10,10 +10,10 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include +//#include +//#include #include "rogue.h" -#include +//#include /* * List of monsters in rough order of vorpalness diff --git a/src/cc/rogue/move.c b/src/cc/rogue/move.c index 3bdf90d37..c70d668ca 100644 --- a/src/cc/rogue/move.c +++ b/src/cc/rogue/move.c @@ -10,8 +10,8 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include +//#include +//#include #include "rogue.h" /* diff --git a/src/cc/rogue/new_level.c b/src/cc/rogue/new_level.c index 9dc0d761f..b55d3e42c 100644 --- a/src/cc/rogue/new_level.c +++ b/src/cc/rogue/new_level.c @@ -11,8 +11,8 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include +//#include +//#include #include "rogue.h" #define TREAS_ROOM 20 /* one chance in TREAS_ROOM for a treasure room */ diff --git a/src/cc/rogue/options.c b/src/cc/rogue/options.c index 6907da598..d74979365 100644 --- a/src/cc/rogue/options.c +++ b/src/cc/rogue/options.c @@ -12,10 +12,10 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include -#include -#include +//#include +//#include +//#include +//#include #include "rogue.h" #define EQSTR(a, b, c) (strncmp(a, b, c) == 0) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index ee628b4f0..b6debc966 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -10,9 +10,9 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include -#include +//#include +//#include +//#include #include "rogue.h" /* diff --git a/src/cc/rogue/passages.c b/src/cc/rogue/passages.c index 79b3706aa..5437f4972 100644 --- a/src/cc/rogue/passages.c +++ b/src/cc/rogue/passages.c @@ -10,8 +10,8 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include +//#include +//#include #include "rogue.h" /* diff --git a/src/cc/rogue/potions.c b/src/cc/rogue/potions.c index de09efb9b..00865b5dd 100644 --- a/src/cc/rogue/potions.c +++ b/src/cc/rogue/potions.c @@ -10,8 +10,8 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include +//#include +//#include #include "rogue.h" typedef struct diff --git a/src/cc/rogue/rings.c b/src/cc/rogue/rings.c index 56f7a0294..747da302a 100644 --- a/src/cc/rogue/rings.c +++ b/src/cc/rogue/rings.c @@ -10,7 +10,7 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include +//#include #include "rogue.h" /* diff --git a/src/cc/rogue/rip.c b/src/cc/rogue/rip.c index a5b3e7208..be97fb867 100644 --- a/src/cc/rogue/rip.c +++ b/src/cc/rogue/rip.c @@ -11,14 +11,14 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include -#include +//#include +//#include +//#include #include -#include -#include -#include -#include +//#include +//#include +//#include +//#include #include "rogue.h" #include "score.h" diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 00cda9426..be17b25be 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -8,12 +8,11 @@ * @(#)main.c 4.22 (Berkeley) 02/05/99 */ -#include -#include +//#include +//#include #include -#include -#include -#include +//#include +//#include #include "rogue.h" #ifdef STANDALONE #include "../komodo/src/komodo_cJSON.h" @@ -88,6 +87,8 @@ void rogueiterate(struct rogue_state *rs) endwin(); my_exit(1); } + //fprintf(stderr,"LINES %d, COLS %d\n",LINES,COLS); + // Set up windows if ( hw == NULL ) hw = newwin(LINES, COLS, 0, 0); @@ -247,21 +248,24 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu } uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); - /*fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL) - starttime); - sleep(2); - - starttime = (uint32_t)time(NULL); - for (i=0; i<100; i++) + if ( 0 ) { - memset(rs,0,sizeof(*rs)); - rs->seed = seed; - rs->keystrokes = keystrokes; - rs->numkeys = num; - rs->sleeptime = 0; - rogueiterate(rs); + fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL) - starttime); + sleep(2); + + starttime = (uint32_t)time(NULL); + for (i=0; i<10000; i++) + { + memset(rs,0,sizeof(*rs)); + rs->seed = seed; + rs->keystrokes = keystrokes; + rs->numkeys = num; + rs->sleeptime = 0; + rogueiterate(rs); + } + fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL)-starttime); + sleep(3); } - fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL)-starttime); - sleep(1);*/ if ( (fp= fopen("checkfile","wb")) != 0 ) { save_file(rs,fp,0); diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index a407ae8a6..419d5aa1b 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -12,10 +12,92 @@ #ifndef H_ROGUE_H #define H_ROGUE_H +#include +#include +#include +#include +#include +#include +#include /* we need va_list */ +#include /* we want wchar_t */ +#include +#include -#include "extern.h" +#include +#include +#include +#include +#include -#undef lines +#ifndef DONTUSEGUI +#include +#else + +#ifndef TRUE +#define TRUE 1 +#endif +#ifndef FALSE +#define FALSE 0 +#endif + +typedef void *WINDOW; +WINDOW stdscr; + +#define standout() +#define standend() +#define refresh() +#define raw() +#define noecho() +#define flushinp() +#define initscr() +#define clear() +#define clrtoeol() + +#define addch(a) +#define werase(a) +#define wclear(a) +#define delwin(a) +#define addstr(a) +#define touchwin(a) +#define idlok(a,b) +#define clearok(a,b) +#define keypad(a,b) +#define leaveok(a,b) +#define waddch(a,b) +#define waddstr(a,b) +#define move(a,b) +#define mvwin(a,b,c) +#define wmove(a,b,c) +#define mvaddch(a,b,c) +#define mvaddstr(a,b,c) +#define wgetnstr(a,b,c) +#define getyx(a,b,c) +#define mvcur(a,b,c,d) +#define mvwaddch(a,b,c,d) +#define mvprintw(...) +#define printw(...) +#define wprintw(...) +#define mvwprintw(...) + + +#define A_CHARTEXT 0xff +#define inch() 0 +#define endwin() 1 +#define isendwin() 0 +#define baudrate() 9600 +#define killchar() 3 +#define erasechar() 8 +#define wclrtoeol(a) 0 +#define wrefresh(a) 0 +#define unctrl(a) "^x" +#define getmaxx(a) COLS +#define getmaxy(a) LINES +#define mvinch(a,b) '.' +#define mvwinch(a,b,c) 0 +#define newwin(a,b,c,d) 0 +#define subwin(a,b,c,d,e) 0 + +#endif #ifdef LINES #undef LINES @@ -27,6 +109,11 @@ #define LINES 24 #define COLS 80 +#include "extern.h" + + +#undef lines + #define NOOP(x) (x += 0) #define CCHAR(x) ( (char) (x & A_CHARTEXT) ) /* diff --git a/src/cc/rogue/rooms.c b/src/cc/rogue/rooms.c index 31991b08f..41041d627 100644 --- a/src/cc/rogue/rooms.c +++ b/src/cc/rogue/rooms.c @@ -10,8 +10,8 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include +//#include +//#include #include "rogue.h" typedef struct spot { /* position matrix for maze positions */ diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index adec30e2e..718c5074b 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -10,13 +10,13 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include -#include -#include -#include -#include -#include +//#include +//#include +//#include +//#include +//#include +//#include +//#include #include "rogue.h" #include "score.h" diff --git a/src/cc/rogue/scrolls.c b/src/cc/rogue/scrolls.c index b6854ab07..5554a5701 100644 --- a/src/cc/rogue/scrolls.c +++ b/src/cc/rogue/scrolls.c @@ -10,8 +10,8 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include +//#include +//#include #include "rogue.h" /* diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 3db54a319..e034039a8 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -29,9 +29,9 @@ SUCH DAMAGE. */ -#include -#include -#include +//#include +//#include +//#include #include "rogue.h" /************************************************************************/ diff --git a/src/cc/rogue/sticks.c b/src/cc/rogue/sticks.c index 39e098339..f048f9423 100644 --- a/src/cc/rogue/sticks.c +++ b/src/cc/rogue/sticks.c @@ -11,9 +11,9 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include -#include +//#include +//#include +//#include #include "rogue.h" /* diff --git a/src/cc/rogue/things.c b/src/cc/rogue/things.c index 4e572c60b..29c51c4ed 100644 --- a/src/cc/rogue/things.c +++ b/src/cc/rogue/things.c @@ -11,9 +11,9 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include -#include +//#include +//#include +//#include #include "rogue.h" /* @@ -498,55 +498,55 @@ add_line(struct rogue_state *rs,char *fmt, char *arg) if (line_cnt >= LINES - 1 || fmt == NULL) { if (inv_type == INV_OVER && fmt == NULL && !newpage) - { - msg(rs,""); + { + msg(rs,""); if ( rs->sleeptime != 0 ) refresh(); - tw = newwin(line_cnt + 1, maxlen + 2, 0, COLS - maxlen - 3); - sw = subwin(tw, line_cnt + 1, maxlen + 1, 0, COLS - maxlen - 2); - for (y = 0; y <= line_cnt; y++) - { - wmove(sw, y, 0); - for (x = 0; x <= maxlen; x++) - waddch(sw, mvwinch(hw, y, x)); - } - wmove(tw, line_cnt, 1); - waddstr(tw, prompt); - /* - * if there are lines below, use 'em - */ - if (LINES > NUMLINES) - { - if (NUMLINES + line_cnt > LINES) - mvwin(tw, LINES - (line_cnt + 1), COLS - maxlen - 3); - else - mvwin(tw, NUMLINES, 0); - } - touchwin(tw); - wrefresh(tw); - wait_for(rs,' '); - if (md_hasclreol()) - { - werase(tw); - leaveok(tw, TRUE); - wrefresh(tw); - } - delwin(tw); - touchwin(stdscr); + tw = newwin(line_cnt + 1, maxlen + 2, 0, COLS - maxlen - 3); + sw = subwin(tw, line_cnt + 1, maxlen + 1, 0, COLS - maxlen - 2); + for (y = 0; y <= line_cnt; y++) + { + wmove(sw, y, 0); + for (x = 0; x <= maxlen; x++) + waddch(sw, mvwinch(hw, y, x)); + } + wmove(tw, line_cnt, 1); + waddstr(tw, prompt); + /* + * if there are lines below, use 'em + */ + if (LINES > NUMLINES) + { + if (NUMLINES + line_cnt > LINES) + mvwin(tw, LINES - (line_cnt + 1), COLS - maxlen - 3); + else + mvwin(tw, NUMLINES, 0); + } + touchwin(tw); + wrefresh(tw); + wait_for(rs,' '); + if (md_hasclreol()) + { + werase(tw); + leaveok(tw, TRUE); + wrefresh(tw); + } + delwin(tw); + touchwin(stdscr); } else { - wmove(hw, LINES - 1, 0); - waddstr(hw, prompt); - wrefresh(hw); - wait_for(rs,' '); - clearok(curscr, TRUE); - wclear(hw); - touchwin(stdscr); - } - newpage = TRUE; - line_cnt = 0; - maxlen = (int) strlen(prompt); + wmove(hw, LINES - 1, 0); + waddstr(hw, prompt); + wrefresh(hw); + wait_for(rs,' '); + clearok(curscr, TRUE); + wclear(hw); + touchwin(stdscr); + } + newpage = TRUE; + line_cnt = 0; + maxlen = (int) strlen(prompt); } if (fmt != NULL && !(line_cnt == 0 && *fmt == '\0')) { diff --git a/src/cc/rogue/weapons.c b/src/cc/rogue/weapons.c index 6693f0814..e5a5eacf6 100644 --- a/src/cc/rogue/weapons.c +++ b/src/cc/rogue/weapons.c @@ -10,9 +10,9 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include -#include +//#include +//#include +//#include #include "rogue.h" #define NO_WEAPON -1 diff --git a/src/cc/rogue/wizard.c b/src/cc/rogue/wizard.c index e56928d33..ee16b2d9b 100644 --- a/src/cc/rogue/wizard.c +++ b/src/cc/rogue/wizard.c @@ -11,10 +11,10 @@ * See the file LICENSE.TXT for full copyright and licensing information. */ -#include -#include -#include -#include +//#include +//#include +//#include +//#include #include "rogue.h" /* From 72a3a99eaacb877649e6a496b394a12335b80d26 Mon Sep 17 00:00:00 2001 From: "Jonathan \"Duke\" Leto" Date: Fri, 15 Feb 2019 15:52:15 -0800 Subject: [PATCH 0627/1145] quick hack to make things build on mac --- src/Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index 8503ebb56..84445f5be 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -572,7 +572,7 @@ komodod_LDADD += \ $(LIBVERUS_CRYPTO) \ $(LIBVERUS_PORTABLE_CRYPTO) \ $(LIBZCASH_LIBS) \ - libcc.so -lncurses + libcc.dylib -lncurses if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) From 88e7828253c341129c86047e4bcc32cd78c0f41a Mon Sep 17 00:00:00 2001 From: "Jonathan \"Duke\" Leto" Date: Fri, 15 Feb 2019 17:15:12 -0800 Subject: [PATCH 0628/1145] Fix building of libcc on darwin --- src/Makefile.am | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index 84445f5be..1881f0a90 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -571,8 +571,14 @@ komodod_LDADD += \ $(LIBBITCOIN_CRYPTO) \ $(LIBVERUS_CRYPTO) \ $(LIBVERUS_PORTABLE_CRYPTO) \ - $(LIBZCASH_LIBS) \ - libcc.dylib -lncurses + $(LIBZCASH_LIBS) + +if TARGET_DARWIN +komodod_LDADD += libcc.dylib -lncurses +else +komodod_LDADD += libcc.so -lncurses +endif + if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) From f3be53cbff1d35bdda82265915f6ce082db85878 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 00:20:39 -1100 Subject: [PATCH 0629/1145] +print --- src/cc/rogue/pack.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index b6debc966..ebc4c32f4 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -178,7 +178,8 @@ pack_room(struct rogue_state *rs,bool from_floor, THING *obj) inpack = MAXPACK; return FALSE; } - + fprintf(stderr,"inpack.%d vs MAX.%d\n",inpack,MAXPACK), sleep(2); + if (from_floor) { detach(lvl_obj, obj); From f5d952300c5bb614d417c7de99e560ec3480bc29 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 00:29:13 -1100 Subject: [PATCH 0630/1145] +/- print --- src/cc/rogue/pack.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index ebc4c32f4..bfe176dfa 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -178,7 +178,7 @@ pack_room(struct rogue_state *rs,bool from_floor, THING *obj) inpack = MAXPACK; return FALSE; } - fprintf(stderr,"inpack.%d vs MAX.%d\n",inpack,MAXPACK), sleep(2); + //fprintf(stderr,"inpack.%d vs MAX.%d\n",inpack,MAXPACK), sleep(2); if (from_floor) { @@ -273,6 +273,8 @@ inventory(struct rogue_state *rs,THING *list, int type) } msg_esc = FALSE; } + //if ( n_objs != numpack ) + fprintf(stderr,"n_objs.%d vs numpack.%d\n",n_objs,numpack), sleep(2); if (n_objs == 0) { if (terse) From e64329265c916dfa41c52e8e877691bdeb5e4e46 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 00:43:26 -1100 Subject: [PATCH 0631/1145] cursesd.h --- src/cc/rogue/cursesd.h | 79 ++++++++++++++++++++++++++++++++++++++++++ src/cc/rogue/rogue.h | 65 +--------------------------------- 2 files changed, 80 insertions(+), 64 deletions(-) create mode 100644 src/cc/rogue/cursesd.h diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h new file mode 100644 index 000000000..76e9b878e --- /dev/null +++ b/src/cc/rogue/cursesd.h @@ -0,0 +1,79 @@ +/* + * Score file structure + * + * @(#)score.h 4.6 (Berkeley) 02/05/99 + * + * Rogue: Exploring the Dungeons of Doom + * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman + * All rights reserved. + * + * See the file LICENSE.TXT for full copyright and licensing information. + */ +#ifndef H_CURSESD_H +#define H_CURSESD_H + +#ifndef TRUE +#define TRUE 1 +#endif +#ifndef FALSE +#define FALSE 0 +#endif + +typedef void *WINDOW; +WINDOW stdscr; + +#define standout() +#define standend() +#define refresh() +#define raw() +#define noecho() +#define flushinp() +#define initscr() +#define clear() +#define clrtoeol() + +#define addch(a) +#define werase(a) +#define wclear(a) +#define delwin(a) +#define addstr(a) +#define touchwin(a) +#define idlok(a,b) +#define clearok(a,b) +#define keypad(a,b) +#define leaveok(a,b) +#define waddch(a,b) +#define waddstr(a,b) +#define move(a,b) +#define mvwin(a,b,c) +#define wmove(a,b,c) +#define mvaddch(a,b,c) +#define mvaddstr(a,b,c) +#define wgetnstr(a,b,c) +#define getyx(a,b,c) +#define mvcur(a,b,c,d) +#define mvwaddch(a,b,c,d) +#define mvprintw(...) +#define printw(...) +#define wprintw(...) +#define mvwprintw(...) + + +#define A_CHARTEXT 0xff +#define inch() 0 +#define endwin() 1 +#define isendwin() 0 +#define baudrate() 9600 +#define killchar() 3 +#define erasechar() 8 +#define wclrtoeol(a) 0 +#define wrefresh(a) 0 +#define unctrl(a) "^x" +#define getmaxx(a) COLS +#define getmaxy(a) LINES +#define mvinch(a,b) '.' +#define mvwinch(a,b,c) 0 +#define newwin(a,b,c,d) 0 +#define subwin(a,b,c,d,e) 0 + +#endif diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 419d5aa1b..b83b1a3f5 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -33,70 +33,7 @@ #include #else -#ifndef TRUE -#define TRUE 1 -#endif -#ifndef FALSE -#define FALSE 0 -#endif - -typedef void *WINDOW; -WINDOW stdscr; - -#define standout() -#define standend() -#define refresh() -#define raw() -#define noecho() -#define flushinp() -#define initscr() -#define clear() -#define clrtoeol() - -#define addch(a) -#define werase(a) -#define wclear(a) -#define delwin(a) -#define addstr(a) -#define touchwin(a) -#define idlok(a,b) -#define clearok(a,b) -#define keypad(a,b) -#define leaveok(a,b) -#define waddch(a,b) -#define waddstr(a,b) -#define move(a,b) -#define mvwin(a,b,c) -#define wmove(a,b,c) -#define mvaddch(a,b,c) -#define mvaddstr(a,b,c) -#define wgetnstr(a,b,c) -#define getyx(a,b,c) -#define mvcur(a,b,c,d) -#define mvwaddch(a,b,c,d) -#define mvprintw(...) -#define printw(...) -#define wprintw(...) -#define mvwprintw(...) - - -#define A_CHARTEXT 0xff -#define inch() 0 -#define endwin() 1 -#define isendwin() 0 -#define baudrate() 9600 -#define killchar() 3 -#define erasechar() 8 -#define wclrtoeol(a) 0 -#define wrefresh(a) 0 -#define unctrl(a) "^x" -#define getmaxx(a) COLS -#define getmaxy(a) LINES -#define mvinch(a,b) '.' -#define mvwinch(a,b,c) 0 -#define newwin(a,b,c,d) 0 -#define subwin(a,b,c,d,e) 0 - +#include "cursesd.h" #endif #ifdef LINES From f341a6938ee2c4f84b633004f5f70826e5b34c81 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 00:44:29 -1100 Subject: [PATCH 0632/1145] Inpack --- src/cc/rogue/pack.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index bfe176dfa..1984a87a8 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -273,8 +273,8 @@ inventory(struct rogue_state *rs,THING *list, int type) } msg_esc = FALSE; } - //if ( n_objs != numpack ) - fprintf(stderr,"n_objs.%d vs numpack.%d\n",n_objs,numpack), sleep(2); + //if ( n_objs != inpack ) + fprintf(stderr,"n_objs.%d vs inpack.%d\n",n_objs,inpack), sleep(2); if (n_objs == 0) { if (terse) From 49e84c350ebb7c27b91030436753d380a9ade706 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 01:29:42 -1100 Subject: [PATCH 0633/1145] Calculate unpack --- src/cc/rogue/Makefile.in | 2 +- src/cc/rogue/cursesd.c | 22 ++++++++++++++++++++++ src/cc/rogue/cursesd.h | 38 ++++++++++++++++++++++++-------------- src/cc/rogue/pack.c | 11 +++++++++++ src/cc/rogue/rogue.h | 1 + 5 files changed, 59 insertions(+), 15 deletions(-) create mode 100644 src/cc/rogue/cursesd.c diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index c2f4e551a..e276584a9 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -101,7 +101,7 @@ HDRS = rogue.h extern.h score.h OBJS1 = vers.$(O) extern.$(O) armor.$(O) chase.$(O) command.$(O) \ daemon.$(O) daemons.$(O) fight.$(O) init.$(O) io.$(O) list.$(O) \ mach_dep.$(O) rogue.$(O) mdport.$(O) misc.$(O) monsters.$(O) \ - move.$(O) new_level.$(O) + move.$(O) new_level.$(O) cursesd.$(O) OBJS2 = options.$(O) pack.$(O) passages.$(O) potions.$(O) rings.$(O) \ rip.$(O) rooms.$(O) save.$(O) scrolls.$(O) state.$(O) sticks.$(O) \ things.$(O) weapons.$(O) wizard.$(O) xcrypt.$(O) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c new file mode 100644 index 000000000..71843d36d --- /dev/null +++ b/src/cc/rogue/cursesd.c @@ -0,0 +1,22 @@ +/****************************************************************************** + * Copyright © 2014-2019 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. * + * * + ******************************************************************************/ + +#include "cursesd.h" + +WINDOW *initscr() +{ + if ( stdscr == 0 ) + stdscr = (WINDOW)calloc(1,sizeof(*stdscr)); +} diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 76e9b878e..54c368220 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -1,17 +1,30 @@ -/* - * Score file structure - * - * @(#)score.h 4.6 (Berkeley) 02/05/99 - * - * Rogue: Exploring the Dungeons of Doom - * Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman - * All rights reserved. - * - * See the file LICENSE.TXT for full copyright and licensing information. - */ +/****************************************************************************** + * Copyright © 2014-2019 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_CURSESD_H #define H_CURSESD_H +#define LINES 24 +#define COLS 80 + +struct cursesd_info +{ + uint8_t screen[LINES][COLS]; +} *stdscr; +typedef struct cursesd_info WINDOW; + #ifndef TRUE #define TRUE 1 #endif @@ -19,8 +32,6 @@ #define FALSE 0 #endif -typedef void *WINDOW; -WINDOW stdscr; #define standout() #define standend() @@ -28,7 +39,6 @@ WINDOW stdscr; #define raw() #define noecho() #define flushinp() -#define initscr() #define clear() #define clrtoeol() diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 1984a87a8..1e308892e 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -165,6 +165,7 @@ out: bool pack_room(struct rogue_state *rs,bool from_floor, THING *obj) { + inpack = num_packitems(); if (++inpack > MAXPACK) { if (!terse) @@ -245,6 +246,16 @@ pack_char() * List what is in the pack. Return TRUE if there is something of * the given type. */ + +int32_t num_packitems() +{ + THING *list = pack; + int32_t type = 0,n = 0; + for (; list != NULL; list = next(list)) + n++; + return(n); +} + bool inventory(struct rogue_state *rs,THING *list, int type) { diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index b83b1a3f5..7d00bd8cf 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -816,6 +816,7 @@ THING *leave_pack(struct rogue_state *rs,THING *obj, bool newobj, bool all); THING *new_item(void); THING *new_thing(struct rogue_state *rs); void end_line(struct rogue_state *rs); +int32_t num_packitems(); void runners(struct rogue_state *rs,int); void land(struct rogue_state *rs,int); From 2fc5f85f0f920aaeaa641bee9fb416fff1321f20 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 01:33:36 -1100 Subject: [PATCH 0634/1145] Fix --- src/cc/rogue/cursesd.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 54c368220..db6c184b9 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -19,6 +19,8 @@ #define LINES 24 #define COLS 80 +#include + struct cursesd_info { uint8_t screen[LINES][COLS]; From 9da6a5c5d0972ccbbc52654743237d9570fc4fae Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 01:34:23 -1100 Subject: [PATCH 0635/1145] Test --- src/cc/rogue/cursesd.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 71843d36d..ff1e9a388 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -13,10 +13,10 @@ * * ******************************************************************************/ -#include "cursesd.h" +/*#include "cursesd.h" WINDOW *initscr() { if ( stdscr == 0 ) stdscr = (WINDOW)calloc(1,sizeof(*stdscr)); -} +}*/ From ffccabc6f288d1b8b43387e17df0646e6c851236 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 01:39:02 -1100 Subject: [PATCH 0636/1145] -print --- src/cc/rogue/cursesd.c | 7 ++++--- src/cc/rogue/pack.c | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index ff1e9a388..174ce89e7 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -13,10 +13,11 @@ * * ******************************************************************************/ -/*#include "cursesd.h" +#include "cursesd.h" WINDOW *initscr() { if ( stdscr == 0 ) - stdscr = (WINDOW)calloc(1,sizeof(*stdscr)); -}*/ + stdscr = (WINDOW *)calloc(1,sizeof(*stdscr)); + return(stdscr); +} diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 1e308892e..2f683441b 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -285,7 +285,7 @@ inventory(struct rogue_state *rs,THING *list, int type) msg_esc = FALSE; } //if ( n_objs != inpack ) - fprintf(stderr,"n_objs.%d vs inpack.%d\n",n_objs,inpack), sleep(2); + // fprintf(stderr,"n_objs.%d vs inpack.%d\n",n_objs,inpack), sleep(2); if (n_objs == 0) { if (terse) From 49593a055a48acde8f6ebf50b6e19971ebf89cae Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 01:41:22 -1100 Subject: [PATCH 0637/1145] -print --- src/cc/rogue/cursesd.h | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index db6c184b9..3df9a5a19 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -19,7 +19,22 @@ #define LINES 24 #define COLS 80 +#include #include +#include +#include +#include +#include +#include /* we need va_list */ +#include /* we want wchar_t */ +#include +#include + +#include +#include +#include +#include +#include struct cursesd_info { From eb2e0928c094ecba54298f15c96ffd1c92c6ba4e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 02:07:04 -1100 Subject: [PATCH 0638/1145] Test --- src/cc/rogue/Makefile.in | 2 +- src/cc/rogue/cursesd.c | 85 ++++++++++++++++++++++++++++++++++++++++ src/cc/rogue/cursesd.h | 22 +++++++++++ 3 files changed, 108 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index e276584a9..a6d410b23 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -101,7 +101,7 @@ HDRS = rogue.h extern.h score.h OBJS1 = vers.$(O) extern.$(O) armor.$(O) chase.$(O) command.$(O) \ daemon.$(O) daemons.$(O) fight.$(O) init.$(O) io.$(O) list.$(O) \ mach_dep.$(O) rogue.$(O) mdport.$(O) misc.$(O) monsters.$(O) \ - move.$(O) new_level.$(O) cursesd.$(O) + move.$(O) new_level.$(O) OBJS2 = options.$(O) pack.$(O) passages.$(O) potions.$(O) rings.$(O) \ rip.$(O) rooms.$(O) save.$(O) scrolls.$(O) state.$(O) sticks.$(O) \ things.$(O) weapons.$(O) wizard.$(O) xcrypt.$(O) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 174ce89e7..643ed87de 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -15,9 +15,94 @@ #include "cursesd.h" +static int32_t endwinflag; + WINDOW *initscr() { if ( stdscr == 0 ) stdscr = (WINDOW *)calloc(1,sizeof(*stdscr)); return(stdscr); } + +void endwin() +{ + if ( stdscr != 0 ) + free(stdscr), stdscr = 0; + endwinflag = 1; +} + +int isendwin(void) +{ + return(endwinflag); +} + +int wrefresh(WINDOW *win) +{ + return(0); +} + +int refresh(void) +{ + endwinflag = 0; + return(wrefresh(stdscr)); +} + +int wnoutrefresh(WINDOW *win) +{ + return(0); +} + +int doupdate(void) +{ + return(0); +} + +int redrawwin(WINDOW *win) +{ + return(wrefresh(win)); +} + +int wredrawln(WINDOW *win, int beg_line, int num_lines) +{ + return(wrefresh(win)); +} + +int werase(WINDOW *win) +{ + +} + +int erase(void) +{ + return(werase(stdscr)); +} + +int wclear(WINDOW *win) +{ + +} + +int clear(void) +{ + return(wclear(stdscr)); +} + +int wclrtobot(WINDOW *win) +{ + +} + +int clrtobot(void) +{ + return(wclrtobot(stdscr)); +} + +int wclrtoeol(WINDOW *win) +{ + +} + +int clrtoeol(void) +{ + return(wclrtoeol(stdscr)); +} diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 3df9a5a19..d01a9325d 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -49,6 +49,28 @@ typedef struct cursesd_info WINDOW; #define FALSE 0 #endif +WINDOW *initscr(void); +int endwin(void); +int isendwin(void); +//SCREEN *newterm(const char *type, FILE *outfd, FILE *infd); +//SCREEN *set_term(SCREEN *new); +//void delscreen(SCREEN* sp); + +int refresh(void); +int wrefresh(WINDOW *win); +//int wnoutrefresh(WINDOW *win); +//int doupdate(void); +int redrawwin(WINDOW *win); +int wredrawln(WINDOW *win, int beg_line, int num_lines); + +int erase(void); +int werase(WINDOW *win); +int clear(void); +int wclear(WINDOW *win); +int clrtobot(void); +int wclrtobot(WINDOW *win); +int clrtoeol(void); +int wclrtoeol(WINDOW *win); #define standout() #define standend() From 4c2dfcbc8e99720b979e5625c71512f654df9b41 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 02:08:09 -1100 Subject: [PATCH 0639/1145] Test --- src/cc/rogue/cursesd.h | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index d01a9325d..5e3d375ca 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -36,19 +36,14 @@ #include #include +#ifdef notyet + struct cursesd_info { uint8_t screen[LINES][COLS]; } *stdscr; typedef struct cursesd_info WINDOW; -#ifndef TRUE -#define TRUE 1 -#endif -#ifndef FALSE -#define FALSE 0 -#endif - WINDOW *initscr(void); int endwin(void); int isendwin(void); @@ -72,6 +67,16 @@ int wclrtobot(WINDOW *win); int clrtoeol(void); int wclrtoeol(WINDOW *win); +#endif + +#ifndef TRUE +#define TRUE 1 +#endif +#ifndef FALSE +#define FALSE 0 +#endif + + #define standout() #define standend() #define refresh() From a994a2c01504d44b7bcdf296ae87e71c58d83b7f Mon Sep 17 00:00:00 2001 From: dimxy Date: Sat, 16 Feb 2019 21:39:01 +0500 Subject: [PATCH 0640/1145] corrected invalid non-canonical corrected burntx nExpiryHeight to prevent duplication of importtx (malleability) added importcoin validation for amount, ac_pubkey added sourcetx creation with amount in opret --- src/cc/import.cpp | 369 ++++++++++++++++++++++++++++++++++----- src/importcoin.cpp | 7 +- src/importcoin.h | 2 +- src/rpc/crosschain.cpp | 144 ++++++++++++--- src/rpc/server.cpp | 3 +- src/rpc/server.h | 2 +- src/wallet/rpcwallet.cpp | 52 ++++++ 7 files changed, 505 insertions(+), 74 deletions(-) diff --git a/src/cc/import.cpp b/src/cc/import.cpp index ea69745b0..dbbf7832f 100644 --- a/src/cc/import.cpp +++ b/src/cc/import.cpp @@ -20,6 +20,10 @@ #include "primitives/transaction.h" #include "cc/CCinclude.h" +//#define LEV_INFO 0 +//#define LEV_DEBUG1 1 +//#define LOGSTREAM(category, level, logoperator) { std::ostringstream stream; logoperator; for(int i = 0; i < level; i ++) if( LogAcceptCategory( (std::string(category) + (level > 0 ? std::string("-")+std::to_string(level) : std::string("") )).c_str() ) ) LogPrintStr(stream.str()); } + /* * CC Eval method for import coin. * @@ -33,63 +37,299 @@ extern std::string ASSETCHAINS_SELFIMPORT; extern uint16_t ASSETCHAINS_CODAPORT,ASSETCHAINS_BEAMPORT; extern uint8_t ASSETCHAINS_OVERRIDE_PUBKEY33[33]; -int32_t GetSelfimportProof(std::string source,CMutableTransaction &mtx,CScript &scriptPubKey,TxProof &proof,uint64_t burnAmount,std::vector rawtx,uint256 txid,std::vector rawproof) // find burnTx with hash from "other" daemon +// utilities from gateways.cpp +uint256 BitcoinGetProofMerkleRoot(const std::vector &proofData, std::vector &txids); +uint256 GatewaysReverseScan(uint256 &txid, int32_t height, uint256 reforacletxid, uint256 batontxid); +int32_t GatewaysCointxidExists(struct CCcontract_info *cp, uint256 cointxid); +uint8_t DecodeGatewaysBindOpRet(char *depositaddr, const CScript &scriptPubKey, std::string &coin, uint256 &tokenid, int64_t &totalsupply, uint256 &oracletxid, uint8_t &M, uint8_t &N, std::vector &pubkeys, uint8_t &taddr, uint8_t &prefix, uint8_t &prefix2); + +// ac_import=chain support: +// encode opret for gateways import +CScript EncodeGatewaysImportTxOpRet(uint32_t targetCCid, std::string coin, uint256 bindtxid, std::vector publishers, std::vectortxids, int32_t height, uint256 cointxid, int32_t claimvout, std::string rawburntx, std::vectorproof, CPubKey destpub, int64_t amount) { - MerkleBranch newBranch; CMutableTransaction tmpmtx; CTransaction tx,vintx; uint256 blockHash; char destaddr[64],pkaddr[64]; - tmpmtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(),komodo_nextheight()); - if ( source == "BEAM" ) + CScript opret; + opret << OP_RETURN << E_MARSHAL(ss << targetCCid << coin << bindtxid << publishers << txids << height << cointxid << claimvout << rawburntx << proof << destpub << amount); + return(opret); +} + +bool ImportCoinGatewaysVerify(char *refdepositaddr, uint256 oracletxid, int32_t claimvout, std::string refcoin, uint256 burntxid, const std::string rawburntx, std::vectorproof, uint256 merkleroot) +{ + std::vector txids; + uint256 proofroot, hashBlock, foundtxid = zeroid; + CTransaction oracletx, burntx; + std::string name, description, format; + char destaddr[64], destpubaddr[64], claimaddr[64]; + int32_t i, numvouts; + int64_t nValue = 0; + + if (myGetTransaction(oracletxid, oracletx, hashBlock) == 0 || (numvouts = oracletx.vout.size()) <= 0) { - if ( ASSETCHAINS_BEAMPORT == 0 ) - return(-1); - // confirm via ASSETCHAINS_BEAMPORT that burnTx/hash is a valid BEAM burn - // return(0); + LOGSTREAM("importcoin", CCLOG_INFO, stream << "ImportCoinGatewaysVerify can't find oracletxid=" << oracletxid.GetHex() << std::endl); + return false; } - else if ( source == "CODA" ) + if (DecodeOraclesCreateOpRet(oracletx.vout[numvouts - 1].scriptPubKey, name, description, format) != 'C' || name != refcoin) { - if ( ASSETCHAINS_CODAPORT == 0 ) - return(-1); - // confirm via ASSETCHAINS_CODAPORT that burnTx/hash is a valid CODA burn - // return(0); + LOGSTREAM("importcoin", CCLOG_INFO, stream << "ImportCoinGatewaysVerify mismatched oracle name=" << name.c_str() << " != " << refcoin.c_str() << std::endl); + return false; } - else + proofroot = BitcoinGetProofMerkleRoot(proof, txids); + if (proofroot != merkleroot) { - if ( !E_UNMARSHAL(rawtx, ss >> tx) ) - return(-1); - scriptPubKey = tx.vout[0].scriptPubKey; - mtx = tx; - mtx.fOverwintered = tmpmtx.fOverwintered; - mtx.nExpiryHeight = tmpmtx.nExpiryHeight; - mtx.nVersionGroupId = tmpmtx.nVersionGroupId; - mtx.nVersion = tmpmtx.nVersion; - mtx.vout.clear(); - mtx.vout.resize(1); - mtx.vout[0].nValue = burnAmount; - mtx.vout[0].scriptPubKey = scriptPubKey; - if ( tx.GetHash() != txid ) - return(-1); - if ( source == "PUBKEY" ) + LOGSTREAM("importcoin", CCLOG_INFO, stream << "ImportCoinGatewaysVerify mismatched proof merkleroot=" << proofroot.GetHex() << " and oracles merkleroot=" << merkleroot.GetHex() << std::endl); + return false; + } + + // check the burntxid is in the proof: + if (std::find(txids.begin(), txids.end(), burntxid) == txids.end()) { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "ImportCoinGatewaysVerify invalid proof for this burntxid=" << burntxid.GetHex() << std::endl); + return false; + } + + /* + if (DecodeHexTx(burntx, rawburntx) != 0) + { + Getscriptaddress(claimaddr, burntx.vout[claimvout].scriptPubKey); + Getscriptaddress(destpubaddr, CScript() << ParseHex(HexStr(destpub)) << OP_CHECKSIG); + if (strcmp(claimaddr, destpubaddr) == 0) { - // make sure vin0 is signed by ASSETCHAINS_OVERRIDE_PUBKEY33 - if ( myGetTransaction(tx.vin[0].prevout.hash,vintx,blockHash) == 0 ) - return(-1); - if ( tx.vin[0].prevout.n < vintx.vout.size() && Getscriptaddress(destaddr,vintx.vout[tx.vin[0].prevout.n].scriptPubKey) != 0 ) + for (i = 0; i %s vs %s\n",tx.vin[0].prevout.n,destaddr,pkaddr); } } - else if ( source == ASSETCHAINS_SELFIMPORT ) + else fprintf(stderr, "claimaddr.(%s) != destpubaddr.(%s)\n", claimaddr, destpubaddr); + }*/ + + /* + if (foundtxid == burntxid) { + LOGSTREAM("importcoin", LEV_DEBUG1, stream << "verified proof for burntxid=" << burntxid.GetHex() << " in merkleroot merkleroot" << std::endl); + return(nValue); + } + else { + LOGSTREAM("importcoin", LEV_INFO, stream << "verified proof for burntxid=" << burntxid.GetHex() << " in merkleroot merkleroot" << std::endl); + + fprintf(stderr, "(%s) != (%s) or txid %s mismatch.%d or script mismatch\n", refdepositaddr, destaddr, uint256_str(str, foundtxid), foundtxid != burntxid); + */ + + LOGSTREAM("importcoin", CCLOG_DEBUG1, stream << "verified proof for burntxid=" << burntxid.GetHex() << " in trusted merkleroot" << std::endl); + return true; +} + + +// make import tx with burntx and its proof of existence +std::string MakeGatewaysImportTx(uint64_t txfee, uint256 bindtxid, int32_t height, std::string refcoin, std::vectorproof, std::string rawburntx, int32_t ivout, uint256 burntxid) +{ + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + CTransaction burntx, bindtx; + CPubKey mypk, gatewayspk; + uint256 oracletxid, merkleroot, mhash, hashBlock, tokenid, txid; + int64_t totalsupply; + int32_t i, m, n, numvouts; + uint8_t M, N, taddr, prefix, prefix2; + std::string coin; + struct CCcontract_info *cp, C; + std::vector pubkeys, publishers; + std::vectortxids; + char depositaddr[64], txidaddr[64]; + + cp = CCinit(&C, EVAL_GATEWAYS); + /*if (txfee == 0) + txfee = 10000; + mypk = pubkey2pk(Mypubkey()); + gatewayspk = GetUnspendable(cp, 0); */ + + if (!E_UNMARSHAL(ParseHex(rawburntx), ss >> burntx)) + return std::string(""); + + CAmount amount = GetCoinImportValue(burntx); // equal to int64_t + + LOGSTREAM("importcoin", CCLOG_DEBUG1, stream << "MakeGatewaysImportTx height=" << height << " coin=" << refcoin << " amount=" << (double)amount / COIN << " pubkeys num=" << pubkeys.size() << std::endl); + + if (GetTransaction(bindtxid, bindtx, hashBlock, false) == 0 || (numvouts = bindtx.vout.size()) <= 0) + { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "MakeGatewaysImportTx cant find bindtxid=" << bindtxid.GetHex() << std::endl); + return(""); + } +/* if (DecodeGatewaysBindOpRet(depositaddr, bindtx.vout[numvouts - 1].scriptPubKey, coin, tokenid, totalsupply, oracletxid, M, N, pubkeys, taddr, prefix, prefix2) != 'B' || refcoin != coin) + { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "MakeGatewaysImportTx invalid coin - bindtxid=" << bindtxid.GetHex() << " coin=" << coin.c_str() << std::endl); + return(""); + } eliminate link err */ + n = (int32_t)pubkeys.size(); + merkleroot = zeroid; + for (i = m = 0; i < n; i++) + { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "MakeGatewaysImportTx using pubkeys[" << i << "]=" << HexStr(pubkeys[i]) << std::endl); + if ((mhash = GatewaysReverseScan(txid, height, oracletxid, OraclesBatontxid(oracletxid, pubkeys[i]))) != zeroid) { - // source is external coin is the assetchains symbol in the burnTx OP_RETURN - // burnAmount, rawtx and rawproof should be enough for gatewaysdeposit equivalent + if (merkleroot == zeroid) + merkleroot = mhash, m = 1; + else if (mhash == merkleroot) + m ++; + publishers.push_back(pubkeys[i]); + txids.push_back(txid); } } - return(-1); + + LOGSTREAM("importcoin", CCLOG_DEBUG1, stream << "MakeGatewaysImportTx burntxid=" << burntxid.GetHex() << " nodes m=" << m << " of n=" << n << std::endl); + if (merkleroot == zeroid || m < n / 2) // none or less than half oracle nodes sent merkleroot + { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "MakeGatewaysImportTx couldnt find merkleroot for block height=" << height << "coin=" << coin.c_str() << " oracleid=" << oracletxid.GetHex() << " m=" << m << " vs n=" << n << std::endl ); + return(""); + } + if (GatewaysCointxidExists(cp, burntxid) != 0) + { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "MakeGatewaysImportTx burntxid=" << burntxid.GetHex() << " already exists" << std::endl); + return(""); + } + if (!ImportCoinGatewaysVerify(depositaddr, oracletxid, ivout, coin, burntxid, rawburntx, proof, merkleroot)) + { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "MakeGatewaysImportTx could not validate burntx, txid=" << burntxid.GetHex() << std::endl); + return(""); + } + + + std::vector leaftxids; + BitcoinGetProofMerkleRoot(proof, leaftxids); + MerkleBranch newBranch(0, leaftxids); + TxProof txProof = std::make_pair(burntxid, newBranch); + + std::vector vouts; + + + + return HexStr(E_MARSHAL(ss << MakeImportCoinTransaction(txProof, burntx, vouts))); + + /*if (AddNormalinputs(mtx, mypk, 3 * txfee, 4) > 0) + { + mtx.vout.push_back(MakeCC1vout(cp->evalcode, txfee, destpub)); + mtx.vout.push_back(CTxOut(txfee, CScript() << ParseHex(HexStr(CCtxidaddr(txidaddr, burntxid))) << OP_CHECKSIG)); + return(FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeGatewaysImportTxOpRet(0xFFFFFFFF, coin, bindtxid, publishers, txids, height, burntxid, ivout, rawburntx, proof, destpub, amount))); + } + LOGSTREAM("importcoin", LEV_INFO, stream << "MakeGatewaysImportTx coud not find normal imputs" << std::endl);*/ + return(""); +} + +// makes source tx for self import tx +std::string MakeSelfImportSourceTx(CTxDestination &dest, int64_t amount, CMutableTransaction &mtx) +{ + const int64_t txfee = 10000; + int64_t inputs, change; + CPubKey myPubKey = Mypubkey(); + struct CCcontract_info *cpDummy, C; + + cpDummy = CCinit(&C, EVAL_TOKENS); + + mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + + if( (inputs = AddNormalinputs(mtx, myPubKey, txfee, 4)) == 0 ) { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "MakeSelfImportSourceTx: cannot find normal imputs for txfee" << std::endl); + return std::string(""); + } + + CScript scriptPubKey = GetScriptForDestination(dest); + mtx.vout.push_back(CTxOut(txfee, scriptPubKey)); + change = inputs - txfee; + if( change != 0 ) + mtx.vout.push_back(CTxOut(change, CScript() << ParseHex(HexStr(myPubKey)) << OP_CHECKSIG)); + + //make opret with amount: + return FinalizeCCTx(0, cpDummy, mtx, myPubKey, txfee, CScript() << OP_RETURN << E_MARSHAL(ss << (uint8_t)EVAL_IMPORTCOIN << (uint8_t)'A' << amount)); +} + +// make sure vin0 is signed by ASSETCHAINS_OVERRIDE_PUBKEY33 +int32_t CheckVin0PubKey(const CTransaction &sourcetx) +{ + CTransaction vintx; + uint256 blockHash; + char destaddr[64], pkaddr[64]; + + if( !myGetTransaction(sourcetx.vin[0].prevout.hash, vintx, blockHash) ) { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "CheckVin0PubKey() could not load vintx" << sourcetx.vin[0].prevout.hash.GetHex() << std::endl); + return(-1); + } + if( sourcetx.vin[0].prevout.n < vintx.vout.size() && Getscriptaddress(destaddr, vintx.vout[sourcetx.vin[0].prevout.n].scriptPubKey) != 0 ) + { + pubkey2addr(pkaddr, ASSETCHAINS_OVERRIDE_PUBKEY33); + if (strcmp(pkaddr, destaddr) == 0) { + return(0); + } + LOGSTREAM("importcoin", CCLOG_INFO, stream << "CheckVin0PubKey() mismatched vin0[prevout.n=" << sourcetx.vin[0].prevout.n << "] -> destaddr=" << destaddr << " vs pkaddr=" << pkaddr << std::endl); + } + return -1; +} + +// ac_import=PUBKEY support: +// prepare a tx for creating import tx and quasi-burn tx +int32_t GetSelfimportProof(std::string source, CMutableTransaction &mtx, CScript &scriptPubKey, TxProof &proof, std::string rawsourcetx, int32_t &ivout, uint256 sourcetxid, uint64_t burnAmount) // find burnTx with hash from "other" daemon +{ + MerkleBranch newBranch; + CMutableTransaction tmpmtx; + CTransaction sourcetx; + + tmpmtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + + if (!E_UNMARSHAL(ParseHex(rawsourcetx), ss >> sourcetx)) { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "GetSelfimportProof: could not unmarshal source tx" << std::endl); + return(-1); + } + + if (sourcetx.vout.size() == 0) { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "GetSelfimportProof: vout size is 0" << std::endl); + return -1; + } + + if (ivout < 0) { // "ivout < 0" means "find" + // try to find vout + CPubKey myPubkey = Mypubkey(); + ivout = 0; + // skip change: + if (sourcetx.vout[ivout].scriptPubKey == (CScript() << ParseHex(HexStr(myPubkey)) << OP_CHECKSIG)) + ivout++; + } + + if (ivout >= sourcetx.vout.size()) { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "GetSelfimportProof: needed vout not found" << std::endl); + return -1; + } + + LOGSTREAM("importcoin", CCLOG_DEBUG1, stream << "GetSelfimportProof: using vout[" << ivout << "] of the passed rawtx" << std::endl); + + scriptPubKey = sourcetx.vout[ivout].scriptPubKey; + + //mtx is template for import tx + mtx = sourcetx; + mtx.fOverwintered = tmpmtx.fOverwintered; + + //malleability fix for burn tx: + //mtx.nExpiryHeight = tmpmtx.nExpiryHeight; + mtx.nExpiryHeight = sourcetx.nExpiryHeight; + + mtx.nVersionGroupId = tmpmtx.nVersionGroupId; + mtx.nVersion = tmpmtx.nVersion; + mtx.vout.clear(); + mtx.vout.resize(1); + mtx.vout[0].nValue = burnAmount; + mtx.vout[0].scriptPubKey = scriptPubKey; + + // not sure we need this now as we create sourcetx ourselves: + if (sourcetx.GetHash() != sourcetxid) { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "GetSelfimportProof: passed source txid incorrect" << std::endl); + return(-1); + } + + // check ac_pubkey: + if (CheckVin0PubKey(sourcetx) < 0) { + return -1; + } + proof = std::make_pair(sourcetxid, newBranch); + return 0; } // use proof from the above functions to validate the import @@ -116,9 +356,46 @@ int32_t CheckGATEWAYimport(TxProof proof,std::vector rawproof,CTransact int32_t CheckPUBKEYimport(TxProof proof,std::vector rawproof,CTransaction burnTx,std::vector payouts) { // if burnTx has ASSETCHAINS_PUBKEY vin, it is valid return(0); - fprintf(stderr,"proof txid.%s\n",proof.first.GetHex().c_str()); + LOGSTREAM("importcoin", CCLOG_DEBUG1, stream << "proof txid=" << proof.first.GetHex() << std::endl); + + uint256 sourcetxid = proof.first, hashBlock; + CTransaction sourcetx; + + if (!myGetTransaction(sourcetxid, sourcetx, hashBlock)) { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "could not load source txid=" << sourcetxid.GetHex() << std::endl); + return -1; + } + + if (sourcetx.vout.size() == 0) { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "no vouts in source txid=" << sourcetxid.GetHex() << std::endl); + return -1; + } + + //ac_pubkey check: + if (CheckVin0PubKey(sourcetx) < 0) { + return -1; + } + + // get source tx opret: + std::vector vopret; + uint8_t evalCode, funcId; + int64_t amount; + + GetOpReturnData(sourcetx.vout.back().scriptPubKey, vopret); + if (vopret.size() == 0 || !E_UNMARSHAL(vopret, ss >> evalCode; ss >> funcId; ss >> amount) || evalCode != EVAL_IMPORTCOIN || funcId != 'A') { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "no or incorrect opret to validate in source txid=" << sourcetxid.GetHex() << std::endl); + return -1; + } + + LOGSTREAM("importcoin", CCLOG_DEBUG1, stream << "importTx amount=" << payouts[0].nValue << " burnTx amount=" << burnTx.vout[0].nValue << " opret amount=" << amount << " source txid=" << sourcetxid.GetHex() << std::endl); + + // amount malleability check with the opret from the source tx: + if (payouts[0].nValue != amount) { // assume that burntx amount is checked in the common code in Eval::ImportCoin() + LOGSTREAM("importcoin", CCLOG_INFO, stream << "importTx amount != amount in the opret of source txid=" << sourcetxid.GetHex() << std::endl); + return -1; + } + return(0); - return(-1); } bool Eval::ImportCoin(const std::vector params,const CTransaction &importTx,unsigned int nIn) @@ -132,10 +409,10 @@ bool Eval::ImportCoin(const std::vector params,const CTransaction &impo return Invalid("invalid-params"); // Control all aspects of this transaction // It should not be at all malleable - if (MakeImportCoinTransaction(proof, burnTx, payouts).GetHash() != importTx.GetHash()) + if (MakeImportCoinTransaction(proof, burnTx, payouts, importTx.nExpiryHeight).GetHash() != importTx.GetHash()) return Invalid("non-canonical"); // burn params - if (!UnmarshalBurnTx(burnTx, targetSymbol, &targetCcid, payoutsHash,rawproof)) + if (!UnmarshalBurnTx(burnTx, targetSymbol, &targetCcid, payoutsHash, rawproof)) return Invalid("invalid-burn-tx"); // check burn amount { diff --git a/src/importcoin.cpp b/src/importcoin.cpp index 39ff01d68..381a52fb8 100644 --- a/src/importcoin.cpp +++ b/src/importcoin.cpp @@ -26,14 +26,17 @@ int32_t komodo_nextheight(); -CTransaction MakeImportCoinTransaction(const TxProof proof, const CTransaction burnTx, const std::vector payouts) +CTransaction MakeImportCoinTransaction(const TxProof proof, const CTransaction burnTx, const std::vector payouts, uint32_t nExpiryHeightOverride) { std::vector payload = E_MARSHAL(ss << EVAL_IMPORTCOIN); - CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); mtx.vin.push_back(CTxIn(COutPoint(burnTx.GetHash(), 10e8), CScript() << payload)); mtx.vout = payouts; auto importData = E_MARSHAL(ss << proof; ss << burnTx); mtx.vout.insert(mtx.vout.begin(), CTxOut(0, CScript() << OP_RETURN << importData)); + + if (nExpiryHeightOverride != 0) + mtx.nExpiryHeight = nExpiryHeightOverride; //this is for construction of the tx used for validating importtx return CTransaction(mtx); } diff --git a/src/importcoin.h b/src/importcoin.h index 64019ac8f..947debcd8 100644 --- a/src/importcoin.h +++ b/src/importcoin.h @@ -26,7 +26,7 @@ CAmount GetCoinImportValue(const CTransaction &tx); CTransaction MakeImportCoinTransaction(const TxProof proof, - const CTransaction burnTx, const std::vector payouts); + const CTransaction burnTx, const std::vector payouts, uint32_t nExpiryHeightOverride = 0); CTxOut MakeBurnOutput(CAmount value, uint32_t targetCCid, std::string targetSymbol, const std::vector payouts,std::vector rawproof); diff --git a/src/rpc/crosschain.cpp b/src/rpc/crosschain.cpp index a0a3b507f..1a6dc41ea 100644 --- a/src/rpc/crosschain.cpp +++ b/src/rpc/crosschain.cpp @@ -34,21 +34,27 @@ #include "script/sign.h" #include "script/standard.h" +#include "key_io.h" + #include #include #include - using namespace std; +extern std::string ASSETCHAINS_SELFIMPORT; +extern uint16_t ASSETCHAINS_CODAPORT, ASSETCHAINS_BEAMPORT; + 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,uint256 *MoMoMp,int32_t kmdstarti,int32_t kmdendi); uint256 komodo_calcMoM(int32_t height,int32_t MoMdepth); extern std::string ASSETCHAINS_SELFIMPORT; uint256 Parseuint256(char *hexstr); -int32_t GetSelfimportProof(std::string source,CMutableTransaction &mtx,CScript &scriptPubKey,TxProof &proof,uint64_t burnAmount,std::vector rawtx,uint256 txid,std::vector rawproof); +std::string MakeSelfImportSourceTx(CTxDestination &dest, int64_t amount, CMutableTransaction &mtx); +int32_t GetSelfimportProof(std::string source, CMutableTransaction &mtx, CScript &scriptPubKey, TxProof &proof, std::string rawsourcetx, int32_t &ivout, uint256 sourcetxid, uint64_t burnAmount); +std::string MakeGatewaysImportTx(uint64_t txfee, uint256 bindtxid, int32_t height, std::string refcoin, std::vectorproof, std::string rawburntx, int32_t ivout, uint256 burntxid); UniValue assetchainproof(const UniValue& params, bool fHelp) { @@ -256,6 +262,7 @@ UniValue migrate_createimporttransaction(const UniValue& params, bool fHelp) TxProof proof = GetAssetchainProof(burnTx.GetHash(),burnTx); CTransaction importTx = MakeImportCoinTransaction(proof, burnTx, payouts); + return HexStr(E_MARSHAL(ss << importTx)); } @@ -281,31 +288,122 @@ UniValue migrate_completeimporttransaction(const UniValue& params, bool fHelp) UniValue selfimport(const UniValue& params, bool fHelp) { - CMutableTransaction mtx; - std::string source; TxProof proof; CTransaction burnTx,tx; CTxOut burnOut; uint64_t burnAmount; uint256 txid,blockHash; std::vector vouts; std::vector rawtx,rawproof; CScript scriptPubKey; + UniValue result(UniValue::VOBJ); + CMutableTransaction sourceMtx, templateMtx; + std::string destaddr; + std::string source; + std::string rawsourcetx; + CTransaction burnTx; + CTxOut burnOut; + uint64_t burnAmount; + uint256 sourcetxid, blockHash; + std::vector vouts; + std::vector rawproof, rawproofEmpty; + int32_t ivout = 0; + CScript scriptPubKey; + TxProof proof; + if ( ASSETCHAINS_SELFIMPORT.size() == 0 ) throw runtime_error("selfimport only works on -ac_import chains"); - if (fHelp || params.size() < 3 || params.size() > 5 ) - throw runtime_error("selfimport rawtx txid burnamount [rawproof source]\n\n" - "creates signed selfimport transaction"); - rawtx = ParseHex(params[0].get_str().c_str()); - txid = Parseuint256((char *)params[1].get_str().c_str()); // allow for txid != hash(rawtx) - burnAmount = atof(params[2].get_str().c_str()) * COIN + 0.00000000499999; - source = ASSETCHAINS_SELFIMPORT; - if ( params.size() >= 4 ) + + if (fHelp || params.size() != 2) + throw runtime_error("selfimport destaddr amount\n" + //old: "selfimport rawsourcetx sourcetxid {nvout|\"find\"} amount \n" + //TODO: "or selfimport rawburntx burntxid {nvout|\"find\"} rawproof source bindtxid height} \n" + "\ncreates self import coin transaction"); + +/* OLD selfimport schema: + rawsourcetx = params[0].get_str(); + sourcetxid = Parseuint256((char *)params[1].get_str().c_str()); // allow for txid != hash(rawtx) + + int32_t ivout = -1; + if( params[2].get_str() != "find" ) { + if( !std::all_of(params[2].get_str().begin(), params[2].get_str().end(), ::isdigit) ) // check if not all chars are digit + throw std::runtime_error("incorrect nvout param"); + + ivout = atoi(params[2].get_str().c_str()); + } + + burnAmount = atof(params[3].get_str().c_str()) * COIN + 0.00000000499999; */ + + destaddr = params[0].get_str(); + burnAmount = atof(params[1].get_str().c_str()) * COIN + 0.00000000499999; + + source = ASSETCHAINS_SELFIMPORT; //defaults to -ac_import=... param + /* TODO for gateways: + if ( params.size() >= 5 ) { - rawproof = ParseHex(params[3].get_str().c_str()); - if ( params.size() == 5 ) - source = params[4].get_str(); + rawproof = ParseHex(params[4].get_str().c_str()); + if ( params.size() == 6 ) + source = params[5].get_str(); + } */ + + + if (source == "BEAM") + { + if (ASSETCHAINS_BEAMPORT == 0) + return(-1); + // confirm via ASSETCHAINS_BEAMPORT that burnTx/hash is a valid BEAM burn + // return(0); + return -1; } - if ( GetSelfimportProof(source,mtx,scriptPubKey,proof,burnAmount,rawtx,txid,rawproof) < 0 ) - throw std::runtime_error("Failed validating selfimport"); - vouts = mtx.vout; - burnOut = MakeBurnOutput(burnAmount,0xffffffff,ASSETCHAINS_SELFIMPORT,vouts,rawproof); - mtx.vout.clear(); - mtx.vout.push_back(burnOut); - burnTx = mtx; - return HexStr(E_MARSHAL(ss << MakeImportCoinTransaction(proof,burnTx,vouts))); + else if (source == "CODA") + { + if (ASSETCHAINS_CODAPORT == 0) + return(-1); + // confirm via ASSETCHAINS_CODAPORT that burnTx/hash is a valid CODA burn + // return(0); + return -1; + } + else if (source == "PUBKEY") + { + + CTxDestination dest = DecodeDestination(destaddr.c_str()); + rawsourcetx = MakeSelfImportSourceTx(dest, burnAmount, sourceMtx); + sourcetxid = sourceMtx.GetHash(); + + // prepare self-import 'quasi-burn' tx and also create vout for import tx (in mtx.vout): + if (GetSelfimportProof(source, templateMtx, scriptPubKey, proof, rawsourcetx, ivout, sourcetxid, burnAmount) < 0) + throw std::runtime_error("Failed validating selfimport"); + + vouts = templateMtx.vout; + burnOut = MakeBurnOutput(burnAmount, 0xffffffff, ASSETCHAINS_SELFIMPORT, vouts, rawproofEmpty); + templateMtx.vout.clear(); + templateMtx.vout.push_back(burnOut); // burn tx has only opret with vouts and optional proof + + burnTx = templateMtx; // complete the creation of 'quasi-burn' tx + + std::string hextx = HexStr(E_MARSHAL(ss << MakeImportCoinTransaction(proof, burnTx, vouts))); + + CTxDestination address; + bool fValidAddress = ExtractDestination(scriptPubKey, address); + + result.push_back(Pair("sourceTxHex", rawsourcetx)); + result.push_back(Pair("importTxHex", hextx)); + result.push_back(Pair("UsedRawtxVout", ivout)); // notify user about the used vout of rawtx + result.push_back(Pair("DestinationAddress", EncodeDestination(address))); // notify user about the address where the funds will be sent + + return result; + } + else if (source == ASSETCHAINS_SELFIMPORT) + { + throw std::runtime_error("not implemented yet\n"); + + if (params.size() != 8) + throw runtime_error("use \'selfimport rawburntx burntxid nvout rawproof source bindtxid height\' to import from a coin chain\n"); + + uint256 bindtxid = Parseuint256((char *)params[6].get_str().c_str()); + int32_t height = atoi((char *)params[7].get_str().c_str()); + + + // source is external coin is the assetchains symbol in the burnTx OP_RETURN + // burnAmount, rawtx and rawproof should be enough for gatewaysdeposit equivalent + std::string hextx = MakeGatewaysImportTx(0, bindtxid, height, source, rawproof, rawsourcetx, ivout, sourcetxid); + + result.push_back(Pair("hex", hextx)); + result.push_back(Pair("UsedRawtxVout", ivout)); // notify user about the used vout of rawtx + } + return result; } UniValue getNotarisationsForBlock(const UniValue& params, bool fHelp) diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index 98b5deccc..19ac60525 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -541,7 +541,8 @@ static const CRPCCommand vRPCCommands[] = /* Not shown in help */ { "hidden", "setmocktime", &setmocktime, true }, { "hidden", "test_ac", &test_ac, true }, - { "hidden", "test_heirmarker", &test_heirmarker, true }, + { "hidden", "test_heirmarker", &test_heirmarker, true }, + { "hidden", "test_proof", &test_proof, true }, { "hidden", "test_burntx", &test_burntx, true }, diff --git a/src/rpc/server.h b/src/rpc/server.h index 9cacce8ac..b41203df9 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -478,6 +478,6 @@ extern UniValue paxwithdraw(const UniValue& params, bool fHelp); extern UniValue test_ac(const UniValue& params, bool fHelp); extern UniValue test_heirmarker(const UniValue& params, bool fHelp); extern UniValue test_burntx(const UniValue& params, bool fHelp); - +extern UniValue test_proof(const UniValue& params, bool fHelp); #endif // BITCOIN_RPCSERVER_H diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 5564c2000..f945b82fc 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -7883,8 +7883,11 @@ UniValue test_heirmarker(const UniValue& params, bool fHelp) cp = CCinit(&C, EVAL_HEIR); return(FinalizeCCTx(0, cp, mtx, myPubkey, 10000, opret)); + + } + UniValue test_burntx(const UniValue& params, bool fHelp) { // make fake token tx: @@ -7927,3 +7930,52 @@ UniValue test_burntx(const UniValue& params, bool fHelp) CCaddr2set(cp, EVAL_TOKENS, unspPk, tokenpriv, unspendableTokenAddr); return(FinalizeCCTx(0, cp, mtx, myPubkey, 10000, EncodeTokenOpRet(tokenid, voutPubkeys, CScript()))); } + +UniValue test_proof(const UniValue& params, bool fHelp) +{ + UniValue result(UniValue::VOBJ); + std::vectorproof; + + if (fHelp || (params.size() != 2)) + throw runtime_error("incorrect params\n"); + + + proof = ParseHex(params[0].get_str()); + uint256 cointxid = Parseuint256((char *)params[1].get_str().c_str()); + + std::vector txids; + + CMerkleBlock merkleBlock; + if (!E_UNMARSHAL(proof, ss >> merkleBlock)) { + result.push_back(Pair("error", "could not unmarshal proof")); + return result; + } + uint256 merkleRoot = merkleBlock.txn.ExtractMatches(txids); + + result.push_back(Pair("source_root", merkleRoot.GetHex())); + + for (int i = 0; i < txids.size(); i++) + std::cerr << "merkle block txid=" << txids[0].GetHex() << std::endl; + + + std::vector vMatches(txids.size()); + for (auto v : vMatches) v = true; + CPartialMerkleTree verifTree(txids, vMatches); + + result.push_back(Pair("verif_root", verifTree.ExtractMatches(txids).GetHex())); + + if (std::find(txids.begin(), txids.end(), cointxid) == txids.end()) { + fprintf(stderr, "invalid proof for this cointxid\n"); + } + + std::vector vMerkleTree; + bool f; + ::BuildMerkleTree(&f, txids, vMerkleTree); + + std::vector vMerkleBranch = ::GetMerkleBranch(0, txids.size(), vMerkleTree); + + uint256 ourResult = SafeCheckMerkleBranch(zeroid, vMerkleBranch, 0); + result.push_back(Pair("SafeCheckMerkleBranch", ourResult.GetHex())); + + return result; +} From 7b312f6ce680977b12690fa11be83cfe9fd3c02b Mon Sep 17 00:00:00 2001 From: dimxy Date: Sat, 16 Feb 2019 21:59:21 +0500 Subject: [PATCH 0641/1145] added burn tx nExpiryHeight validation --- src/cc/import.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/cc/import.cpp b/src/cc/import.cpp index dbbf7832f..1b49f5c94 100644 --- a/src/cc/import.cpp +++ b/src/cc/import.cpp @@ -371,6 +371,12 @@ int32_t CheckPUBKEYimport(TxProof proof,std::vector rawproof,CTransacti return -1; } + // might be malleable: + if (burnTx.nExpiryHeight != sourcetx.nExpiryHeight) { + LOGSTREAM("importcoin", CCLOG_INFO, stream << "burntx nExpiryHeight incorrect for source txid=" << sourcetxid.GetHex() << std::endl); + return -1; + } + //ac_pubkey check: if (CheckVin0PubKey(sourcetx) < 0) { return -1; From 3c3531627f25c6a6d94fc6aef07dcbb6e4150b66 Mon Sep 17 00:00:00 2001 From: dimxy Date: Sat, 16 Feb 2019 22:15:55 +0500 Subject: [PATCH 0642/1145] comment added --- src/cc/import.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/import.cpp b/src/cc/import.cpp index 1b49f5c94..25bed49df 100644 --- a/src/cc/import.cpp +++ b/src/cc/import.cpp @@ -415,7 +415,7 @@ bool Eval::ImportCoin(const std::vector params,const CTransaction &impo return Invalid("invalid-params"); // Control all aspects of this transaction // It should not be at all malleable - if (MakeImportCoinTransaction(proof, burnTx, payouts, importTx.nExpiryHeight).GetHash() != importTx.GetHash()) + if (MakeImportCoinTransaction(proof, burnTx, payouts, importTx.nExpiryHeight).GetHash() != importTx.GetHash()) // ExistsImportTombstone prevents from duplication return Invalid("non-canonical"); // burn params if (!UnmarshalBurnTx(burnTx, targetSymbol, &targetCcid, payoutsHash, rawproof)) From ec0a203d88aa48031c2934d5eb3d12bb8bbf67fc Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 07:19:14 -1100 Subject: [PATCH 0643/1145] Extract roc --- src/cc/cclib.cpp | 3 +++ src/cc/rogue/rogue.c | 6 ++--- src/cc/rogue/rogue.h | 2 +- src/cc/rogue_rpc.cpp | 62 +++++++++++++++++++++++++++++++++++++++----- 4 files changed, 62 insertions(+), 11 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index c13f55ce4..be6f3a3fe 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -89,6 +89,7 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue rogue_players(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); #else bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); @@ -118,6 +119,8 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) return(rogue_bailout(txfee,cp,params)); else if ( strcmp(method,"highlander") == 0 ) return(rogue_highlander(txfee,cp,params)); + else if ( strcmp(method,"extract") == 0 ) + return(rogue_extract(txfee,cp,params)); else if ( strcmp(method,"playerinfo") == 0 ) return(rogue_playerinfo(txfee,cp,params)); else if ( strcmp(method,"players") == 0 ) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index be17b25be..0f53dfff2 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -232,14 +232,14 @@ void rogue_bailout(struct rogue_state *rs) fprintf(stderr,"error issuing (%s)\n",cmd); } -int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player) +int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis) { struct rogue_state *rs; FILE *fp; int32_t i; rs = (struct rogue_state *)calloc(1,sizeof(*rs)); rs->seed = seed; rs->keystrokes = keystrokes; rs->numkeys = num; - rs->sleeptime = 0*50000; + rs->sleeptime = sleepmillis * 1000; if ( player != 0 ) { rs->P = *player; @@ -320,7 +320,7 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) } if ( num > 0 ) { - rogue_replay2(0,seed,keystrokes,num,0); + rogue_replay2(0,seed,keystrokes,num,0,0); mvaddstr(LINES - 2, 0, (char *)"replay completed"); endwin(); } diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 7d00bd8cf..fac84d8b0 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -392,7 +392,7 @@ int32_t roguefname(char *fname,uint64_t seed,int32_t counter); int32_t flushkeystrokes(struct rogue_state *rs); int32_t rogue_restorepack(struct rogue_state *rs); void restore_player(struct rogue_state *rs); -int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player); +int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis); void rogue_bailout(struct rogue_state *rs); /* diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5daca5d1c..3597eab5a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -34,7 +34,7 @@ struct rogue_player int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; struct rogue_packitem roguepack[MAXPACK]; }; -int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player); +int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis); #define ROGUE_DECLARED_PACK void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item); @@ -826,6 +826,54 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"couldnt reparse params")); } +UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result; CPubKey mypk,roguepk; int32_t i,n,num,regslot,numkeys,err; std::string symbol,pname,maxplayers,batonht,batonvout; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char myrogueaddr[64],fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid,gametxid; FILE *fp; + mypk = pubkey2pk(Mypubkey()); + roguepk = GetUnspendable(cp,0); + GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); + result.push_back(Pair("name","rogue")); + result.push_back(Pair("method",method)); + result.push_back(Pair("myrogueaddr",myrogueaddr)); + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n > 0 ) + { + gametxid = juint256(jitem(params,0)); + result.push_back(Pair("gametxid",gametxid.GetHex())); + if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) + { + if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers,symbol,pname) == 0 ) + { + UniValue obj; struct rogue_player P; + seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); + fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname,batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + memset(&P,0,sizeof(P)); + if ( playerdata.size() > 0 ) + { + for (i=0; i highlander vout from creategame TCBOO @@ -869,15 +917,11 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param result.push_back(Pair("gametxid",gametxid.GetHex())); if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) { - if ( maxplayers == 1 ) - mult /= 2; if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers,symbol,pname) == 0 ) { UniValue obj; struct rogue_player P; - if ( pname.size() == 0 ) - pname = Rogue_pname; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); - fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname,batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -886,7 +930,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } if ( keystrokes != 0 ) { - num = rogue_replay2(player,seed,keystrokes,numkeys,playerdata.size()==0?0:&P); + num = rogue_replay2(player,seed,keystrokes,numkeys,playerdata.size()==0?0:&P,0); if ( keystrokes != 0 ) free(keystrokes); } else num = 0; @@ -909,6 +953,8 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else { + if ( maxplayers == 1 ) + mult /= 2; cpTokens = CCinit(&tokensC, EVAL_TOKENS); mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cpTokens,NULL))); // marker to token cc addr, burnable and validated mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,1,mypk)); @@ -933,6 +979,8 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); CScript opret; + if ( pname.size() == 0 ) + pname = Rogue_pname; if ( newdata.size() == 0 ) { opret = rogue_highlanderopret(funcid, gametxid, regslot, mypk, nodata,pname); From 466fdb06a7f198a884cfd521a19722bfc016786f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 07:20:36 -1100 Subject: [PATCH 0644/1145] syntax --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3597eab5a..0041a68c4 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -828,12 +828,12 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result; CPubKey mypk,roguepk; int32_t i,n,num,regslot,numkeys,err; std::string symbol,pname,maxplayers,batonht,batonvout; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char myrogueaddr[64],fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid,gametxid; FILE *fp; + UniValue result; CPubKey mypk,roguepk; int32_t i,n,num,gameheight,numplayers,regslot,numkeys,err; std::string symbol,pname,maxplayers,batonht,batonvout; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char myrogueaddr[64],fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000]; mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); result.push_back(Pair("name","rogue")); - result.push_back(Pair("method",method)); + result.push_back(Pair("method","extract")); result.push_back(Pair("myrogueaddr",myrogueaddr)); if ( (params= cclib_reparse(&n,params)) != 0 ) { From c501ef7e684a30bb6e894757f9b52597614c2587 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 07:22:12 -1100 Subject: [PATCH 0645/1145] Fix --- src/cc/rogue_rpc.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 0041a68c4..88e8a1749 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -828,7 +828,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result; CPubKey mypk,roguepk; int32_t i,n,num,gameheight,numplayers,regslot,numkeys,err; std::string symbol,pname,maxplayers,batonht,batonvout; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char myrogueaddr[64],fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000]; + UniValue result; CPubKey mypk,roguepk; int32_t i,n,num,maxplayers,gameheight,numplayers,regslot,numkeys,err; std::string symbol,pname,maxplayers,batonht,batonvout; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char myrogueaddr[64],fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000]; mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); @@ -847,7 +847,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue obj; struct rogue_player P; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); - fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname,batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -921,7 +921,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { UniValue obj; struct rogue_player P; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); - fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname,batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { From efbaeecaa39f4dca075edcf6236efdedeb738d7d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 07:23:08 -1100 Subject: [PATCH 0646/1145] ,batonht,batonvout --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 88e8a1749..b403acd1a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -828,7 +828,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result; CPubKey mypk,roguepk; int32_t i,n,num,maxplayers,gameheight,numplayers,regslot,numkeys,err; std::string symbol,pname,maxplayers,batonht,batonvout; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char myrogueaddr[64],fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000]; + UniValue result; CPubKey mypk,roguepk; int32_t i,n,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char myrogueaddr[64],fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000]; mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); From 3a93aa649c74b64efe411e6c4947ab8bea416044 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 07:39:28 -1100 Subject: [PATCH 0647/1145] Test --- src/cc/rogue_rpc.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b403acd1a..60e7fab35 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -832,6 +832,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); + result.push_back(Pair("status","success")); result.push_back(Pair("name","rogue")); result.push_back(Pair("method","extract")); result.push_back(Pair("myrogueaddr",myrogueaddr)); @@ -841,6 +842,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { gametxid = juint256(jitem(params,0)); result.push_back(Pair("gametxid",gametxid.GetHex())); + fprintf(stderr,"gametxid.%s\n",gametxid.GetHex().c_str()); if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) { if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers,symbol,pname) == 0 ) From 0871a2be6acec1b82bea5b057296bc988a23b106 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 07:41:24 -1100 Subject: [PATCH 0648/1145] Add to table --- src/cc/cclib.cpp | 1 + src/cc/rogue_rpc.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index be6f3a3fe..481dd81ce 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -64,6 +64,7 @@ CClib_methods[] = { (char *)"rogue", (char *)"players", (char *)"", 0, 0, 'D', EVAL_ROGUE }, { (char *)"rogue", (char *)"games", (char *)"", 0, 0, 'F', EVAL_ROGUE }, { (char *)"rogue", (char *)"setname", (char *)"pname", 1, 1, 'N', EVAL_ROGUE }, + { (char *)"rogue", (char *)"extract", (char *)"gametxid", 1, 1, 'X', EVAL_ROGUE }, #else { (char *)"sudoku", (char *)"gen", (char *)"", 0, 0, 'G', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 60e7fab35..36e770823 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -836,6 +836,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("name","rogue")); result.push_back(Pair("method","extract")); result.push_back(Pair("myrogueaddr",myrogueaddr)); + fprintf(stderr,"extract\n"); if ( (params= cclib_reparse(&n,params)) != 0 ) { if ( n > 0 ) From 0ddddd52f02fd25121a32f222b044430ae2703e9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 08:16:18 -1100 Subject: [PATCH 0649/1145] +prints --- src/cc/rogue/rogue.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 0f53dfff2..4b96026ef 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -294,11 +294,13 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) while ( 1 ) { roguefname(fname,seed,counter); + printf("check (%s)\n",fname); if ( (fp= fopen(fname,"rb")) == 0 ) break; if ( (fsize= get_filesize(fp)) <= 0 ) { fclose(fp); + printf("fsize.%ld\n",fsize); break; } if ( (keystrokes= (char *)realloc(keystrokes,num+fsize)) == 0 ) From a2da66be25e56359aee4d6a65edcd8950f0ce07a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 08:20:56 -1100 Subject: [PATCH 0650/1145] rogue.seed.0 --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 36e770823..ebef1f19d 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -859,7 +859,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } if ( keystrokes != 0 ) { - sprintf(fname,"%llu.0",(long long)seed); + sprintf(fname,"rogue.%llu.0",(long long)seed); if ( (fp= fopen(fname,"wb")) != 0 ) { if ( fwrite(keystrokes,1,numkeys,fp) != numkeys ) From 16e9d5e6b2086d4bcb09aec4738c2efed09c1bb4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 08:21:47 -1100 Subject: [PATCH 0651/1145] Slow down replay --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 4b96026ef..494e99b9c 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -322,7 +322,7 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) } if ( num > 0 ) { - rogue_replay2(0,seed,keystrokes,num,0,0); + rogue_replay2(0,seed,keystrokes,num,0,50); mvaddstr(LINES - 2, 0, (char *)"replay completed"); endwin(); } From 878db4d87968f5d81307b24910a691ac353b3ff2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 08:33:56 -1100 Subject: [PATCH 0652/1145] Pub key arg to extract --- src/cc/cclib.cpp | 2 +- src/cc/rogue_rpc.cpp | 23 +++++++++++++++-------- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 481dd81ce..8a5cd2185 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -64,7 +64,7 @@ CClib_methods[] = { (char *)"rogue", (char *)"players", (char *)"", 0, 0, 'D', EVAL_ROGUE }, { (char *)"rogue", (char *)"games", (char *)"", 0, 0, 'F', EVAL_ROGUE }, { (char *)"rogue", (char *)"setname", (char *)"pname", 1, 1, 'N', EVAL_ROGUE }, - { (char *)"rogue", (char *)"extract", (char *)"gametxid", 1, 1, 'X', EVAL_ROGUE }, + { (char *)"rogue", (char *)"extract", (char *)"gametxid [pubkey]", 1, 2, 'X', EVAL_ROGUE }, #else { (char *)"sudoku", (char *)"gen", (char *)"", 0, 0, 'G', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ebef1f19d..69e77f5d8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -828,28 +828,35 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result; CPubKey mypk,roguepk; int32_t i,n,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char myrogueaddr[64],fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000]; - mypk = pubkey2pk(Mypubkey()); + UniValue result; CPubKey mypk,roguepk; int32_t i,n,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char rogueaddr[64],fname[64],*pubstr,*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000],pub33[33]; + pk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); - GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); result.push_back(Pair("status","success")); result.push_back(Pair("name","rogue")); result.push_back(Pair("method","extract")); - result.push_back(Pair("myrogueaddr",myrogueaddr)); - fprintf(stderr,"extract\n"); if ( (params= cclib_reparse(&n,params)) != 0 ) { if ( n > 0 ) { gametxid = juint256(jitem(params,0)); result.push_back(Pair("gametxid",gametxid.GetHex())); - fprintf(stderr,"gametxid.%s\n",gametxid.GetHex().c_str()); + if ( n == 2 ) + { + if ( (pubstr= jstr(jitem(params,1),0)) != 0 && strlen(pubstr) == 66 ) + { + decode_hex(pub33,33,pubstr); + pk = buf2pk(pub33); + } + fprintf(stderr,"gametxid.%s %s\n",gametxid.GetHex().c_str(),pubstr); + } + GetCCaddress1of2(cp,myrogueaddr,roguepk,pk); + result.push_back(Pair("rogueaddr",rogueaddr)); if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) { - if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers,symbol,pname) == 0 ) + if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,rogueaddr,numplayers,symbol,pname) == 0 ) { UniValue obj; struct rogue_player P; - seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,myrogueaddr); + seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) From c7db40898ae5d4673bc60fff9c62be05e5870582 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 08:35:27 -1100 Subject: [PATCH 0653/1145] Fix --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 69e77f5d8..d9daf2187 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -828,7 +828,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result; CPubKey mypk,roguepk; int32_t i,n,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char rogueaddr[64],fname[64],*pubstr,*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000],pub33[33]; + UniValue result; CPubKey pk,roguepk; int32_t i,n,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char rogueaddr[64],fname[64],*pubstr,*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000],pub33[33]; pk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); result.push_back(Pair("status","success")); @@ -849,7 +849,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } fprintf(stderr,"gametxid.%s %s\n",gametxid.GetHex().c_str(),pubstr); } - GetCCaddress1of2(cp,myrogueaddr,roguepk,pk); + GetCCaddress1of2(cp,rogueaddr,roguepk,pk); result.push_back(Pair("rogueaddr",rogueaddr)); if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) { From e9bddb1ed175a33c22d5fc8d8908cf50f74daf33 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 08:53:22 -1100 Subject: [PATCH 0654/1145] Mark replay done on Q --- src/cc/rogue/command.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index 1a32246bb..6cc6b0763 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -269,6 +269,7 @@ over: q_comm = FALSE; if ( rs->guiflag != 0 ) rogue_bailout(rs); + else rs->replaydone = (uint32_t)time(NULL); return; when 'i': after = FALSE; inventory(rs,pack, 0); when 'I': after = FALSE; picky_inven(rs); From eba3ba86f637a4a932d028f0429381ddd08916ce Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 09:00:32 -1100 Subject: [PATCH 0655/1145] Alternate esc and y --- src/cc/rogue/io.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 6791c26a4..fbcddf5fa 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -155,6 +155,7 @@ readchar(struct rogue_state *rs) char ch = -1; if ( rs != 0 && rs->guiflag == 0 ) { + static uint32_t counter; if ( rs->ind < rs->numkeys ) { //if ( rs->ind == rs->numkeys-1 ) @@ -162,13 +163,15 @@ readchar(struct rogue_state *rs) //fprintf(stderr,"(%c) ",rs->keystrokes[rs->ind]); return(rs->keystrokes[rs->ind++]); } - if ( rs->replaydone != 0 ) + if ( rs->replaydone != 0 && counter++ < 3 ) fprintf(stderr,"replay finished but readchar called\n"); rs->replaydone = (uint32_t)time(NULL); //if ( (rand() & 1) == 0 ) // return(ESCAPE); //else - return('y'); + if ( counter < 3 || (counter & 1) == 0 ) + return('y'); + else return(ESCAPE); } if ( rs == 0 || rs->guiflag != 0 ) { From 139a7bdfec066e1c25cd6aedcd02dbbced2f1807 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 09:31:50 -1100 Subject: [PATCH 0656/1145] Extract player data --- src/cc/rogue/init.c | 4 ++++ src/cc/rogue/rogue.c | 4 +++- src/cc/rogue_rpc.cpp | 7 +++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index 1603474e2..dcbdb2f6d 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -49,7 +49,11 @@ void init_player(struct rogue_state *rs) // duplicate rng usage of normal case obj = new_item(); init_weapon(obj, MACE); + free(obj); + obj = new_item(); init_weapon(obj, BOW); + free(obj); + obj = new_item(); init_weapon(obj, ARROW); obj->o_count = rnd(15) + 25; free(obj); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 494e99b9c..43d230eec 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -104,7 +104,9 @@ void rogueiterate(struct rogue_state *rs) fuse(swander, 0, WANDERTIME, AFTER); start_daemon(stomach, 0, AFTER); if ( rs->restoring != 0 ) + { restore_player(rs); + } playit(rs); } @@ -244,7 +246,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu { rs->P = *player; rs->restoring = 1; - fprintf(stderr,"restore player packsize.%d\n",rs->P.packsize); + fprintf(stderr,"restore player packsize.%d HP.%d\n",rs->P.packsize,rs->P.hitpoints); } uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d9daf2187..143842007 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -873,6 +873,13 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) fprintf(stderr,"error writing %s\n",fname); fclose(fp); } + sprintf(fname,"rogue.%llu.player",(long long)seed); + if ( (fp= fopen(fname,"wb")) != 0 ) + { + if ( fwrite(playerdata,1,(int32_t)playerdata.size(),fp) != playerdata.size() ) + fprintf(stderr,"error writing %s\n",fname); + fclose(fp); + } num = rogue_replay2(player,seed,keystrokes,numkeys,playerdata.size()==0?0:&P,50); if ( keystrokes != 0 ) free(keystrokes); From d0090c3c881a237fe9db63a4fd7456c8c0c53d7c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 09:33:09 -1100 Subject: [PATCH 0657/1145] Syntax --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 143842007..65b8be53e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -876,7 +876,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) sprintf(fname,"rogue.%llu.player",(long long)seed); if ( (fp= fopen(fname,"wb")) != 0 ) { - if ( fwrite(playerdata,1,(int32_t)playerdata.size(),fp) != playerdata.size() ) + if ( fwrite(&playerdata[0],1,(int32_t)playerdata.size(),fp) != playerdata.size() ) fprintf(stderr,"error writing %s\n",fname); fclose(fp); } From eeee29d3ae81e1bf8ee157480a4d16764b11c82b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 09:39:28 -1100 Subject: [PATCH 0658/1145] Make app use player data --- src/cc/rogue/rogue.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 43d230eec..f8b645d91 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -290,7 +290,7 @@ long get_filesize(FILE *fp) int32_t rogue_replay(uint64_t seed,int32_t sleeptime) { - FILE *fp; char fname[1024]; char *keystrokes = 0; long num=0,fsize; int32_t i,counter = 0; struct rogue_state *rs; + FILE *fp; char fname[1024]; char *keystrokes = 0; long num=0,fsize; int32_t i,counter = 0; struct rogue_state *rs; struct rogue_player P,*player = 0; if ( seed == 0 ) seed = 777; while ( 1 ) @@ -324,7 +324,17 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) } if ( num > 0 ) { - rogue_replay2(0,seed,keystrokes,num,0,50); + sprintf(fname,"rogue.%llu.player",(long long)seed); + if ( (fp=fopen(fname,"rb")) != 0 ) + { + if ( fread(&P,1,sizeof(P),fp) > 0 ) + { + printf("max size player\n"); + player = &P; + } + fclose(fp); + } + rogue_replay2(0,seed,keystrokes,num,player,50); mvaddstr(LINES - 2, 0, (char *)"replay completed"); endwin(); } From ede1db736aa26d811fe889a11ecb80e5ed5009e7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 10:01:15 -1100 Subject: [PATCH 0659/1145] +print --- src/cc/rogue_rpc.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 65b8be53e..854f5f6e1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -828,7 +828,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result; CPubKey pk,roguepk; int32_t i,n,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char rogueaddr[64],fname[64],*pubstr,*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000],pub33[33]; + UniValue result; CPubKey pk,roguepk; int32_t i,n,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char rogueaddr[64],fname[64],*pubstr,*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000],pub33[33]; pk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); result.push_back(Pair("status","success")); @@ -881,6 +881,18 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) fclose(fp); } num = rogue_replay2(player,seed,keystrokes,numkeys,playerdata.size()==0?0:&P,50); + newdata.resize(num); + for (i=0; i no playerdata\n"); + newdata.resize(0); + } + else fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); if ( keystrokes != 0 ) free(keystrokes); } else num = 0; From 4f6cdb4b155b8c63c430a7c4275464a7bfb139f7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 10:02:42 -1100 Subject: [PATCH 0660/1145] +print --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 854f5f6e1..4d6167b3f 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -892,7 +892,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) fprintf(stderr,"zero value character was killed -> no playerdata\n"); newdata.resize(0); } - else fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); + fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); if ( keystrokes != 0 ) free(keystrokes); } else num = 0; From 8b6fe6bec71ff6f772d582949a7db23fb9dc2f08 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 10:19:22 -1100 Subject: [PATCH 0661/1145] -print --- src/cc/rogue/save.c | 15 +++++++++------ src/cc/rogue/state.c | 6 +++--- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index 718c5074b..7349c196a 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -165,21 +165,24 @@ save_file(struct rogue_state *rs,FILE *savef,int32_t guiflag) memset(histo,0,sizeof(histo)); for (i=0; iP)[i]); + //fprintf(stderr,"%02x",((uint8_t *)&rs->P)[i]); histo[((uint8_t *)&rs->P)[i]]++; rs->playerdata[i] = ((uint8_t *)&rs->P)[i]; } rs->playersize = n; - fprintf(stderr," packsize.%d n.%d\n",rs->P.packsize,n); + //fprintf(stderr," packsize.%d n.%d\n",rs->P.packsize,n); if ( (fp= fopen(rogue_packfname(rs,fname),"wb")) != 0 ) { fwrite(&rs->P,1,n,fp); fclose(fp); } - for (i=nonz=0; i<0x100; i++) - if ( histo[i] != 0 ) - fprintf(stderr,"(%d %d) ",i,histo[i]), nonz++; - fprintf(stderr,"nonz.%d\n",nonz); + if ( 0 ) + { + for (i=nonz=0; i<0x100; i++) + if ( histo[i] != 0 ) + fprintf(stderr,"(%d %d) ",i,histo[i]), nonz++; + fprintf(stderr,"nonz.%d\n",nonz); + } fflush(savef); fclose(savef); if ( guiflag != 0 ) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index e034039a8..36191d72c 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1434,7 +1434,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) item = &rs->P.roguepack[rs->P.packsize]; if ( pstats.s_hpt <= 0 ) { - fprintf(stderr,"KILLED\n"); + //fprintf(stderr,"KILLED\n"); rs->P.gold = -1; rs->P.hitpoints = -1; rs->P.strength = -1; @@ -1452,9 +1452,9 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) rs->P.level = pstats.s_lvl; rs->P.experience = pstats.s_exp; rs->P.dungeonlevel = level; - fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,max_stats.s_str,pstats.s_lvl,pstats.s_exp,level); + //fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,max_stats.s_str,pstats.s_lvl,pstats.s_exp,level); } - fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); + //fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); if ( rs->P.packsize < MAXPACK && o->o_type != AMULET ) { packsave(item,o->_o._o_type,o->_o._o_launch,o->_o._o_damage,sizeof(o->_o._o_damage),o->_o._o_hurldmg,sizeof(o->_o._o_hurldmg),o->_o._o_count,o->_o._o_which,o->_o._o_hplus,o->_o._o_dplus,o->_o._o_arm,o->_o._o_flags,o->_o._o_group); From 2f13dbdf4e30d5eb3b8949a4978022de4cc11ac5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 10:23:55 -1100 Subject: [PATCH 0662/1145] -print + delay --- src/cc/rogue/main.c | 2 +- src/cc/rogue/rogue.c | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index c3484eafe..12e6af368 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -252,7 +252,7 @@ int main(int argc, char **argv, char **envp) if ( argc == 2 && (fp=fopen(argv[1],"rb")) == 0 ) { seed = atol(argv[1]); - fprintf(stderr,"replay %llu\n",(long long)seed); + //fprintf(stderr,"replay %llu\n",(long long)seed); return(rogue_replay(seed,50000)); } else diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index f8b645d91..7f885e861 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -246,7 +246,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu { rs->P = *player; rs->restoring = 1; - fprintf(stderr,"restore player packsize.%d HP.%d\n",rs->P.packsize,rs->P.hitpoints); + //fprintf(stderr,"restore player packsize.%d HP.%d\n",rs->P.packsize,rs->P.hitpoints); } uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); @@ -296,7 +296,7 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) while ( 1 ) { roguefname(fname,seed,counter); - printf("check (%s)\n",fname); + //printf("check (%s)\n",fname); if ( (fp= fopen(fname,"rb")) == 0 ) break; if ( (fsize= get_filesize(fp)) <= 0 ) @@ -329,13 +329,14 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) { if ( fread(&P,1,sizeof(P),fp) > 0 ) { - printf("max size player\n"); + //printf("max size player\n"); player = &P; } fclose(fp); } rogue_replay2(0,seed,keystrokes,num,player,50); mvaddstr(LINES - 2, 0, (char *)"replay completed"); + sleep(4); endwin(); } if ( keystrokes != 0 ) From 593ec0e34092997f12d528d51f45882d057277c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 10:25:49 -1100 Subject: [PATCH 0663/1145] Pause --- src/cc/rogue/rogue.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 7f885e861..340fe94a8 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -335,8 +335,9 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) fclose(fp); } rogue_replay2(0,seed,keystrokes,num,player,50); - mvaddstr(LINES - 2, 0, (char *)"replay completed"); sleep(4); + + //mvaddstr(LINES - 2, 0, (char *)"replay completed"); endwin(); } if ( keystrokes != 0 ) From 40a2bb28df79dc4378058740e7fb2e1042017941 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 10:26:05 -1100 Subject: [PATCH 0664/1145] 150 --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 340fe94a8..4e9d9438e 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -334,7 +334,7 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) } fclose(fp); } - rogue_replay2(0,seed,keystrokes,num,player,50); + rogue_replay2(0,seed,keystrokes,num,player,150); sleep(4); //mvaddstr(LINES - 2, 0, (char *)"replay completed"); From bc71d62f820f415f55d1d9a802f218176b7a2aeb Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 10:29:29 -1100 Subject: [PATCH 0665/1145] -score --- src/cc/rogue/rogue.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 4e9d9438e..1e110ee12 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -646,8 +646,8 @@ quit(int sig) } else { - score(rs,purse, 1, 0); - fprintf(stderr,"done!\n"); + //score(rs,purse, 1, 0); + //fprintf(stderr,"done!\n"); } } else From 009b20d427f56e566744fe7fa617047e35f8e404 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 10:32:00 -1100 Subject: [PATCH 0666/1145] Test --- src/cc/rogue/rogue.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 1e110ee12..e288bcf1a 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -335,7 +335,6 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) fclose(fp); } rogue_replay2(0,seed,keystrokes,num,player,150); - sleep(4); //mvaddstr(LINES - 2, 0, (char *)"replay completed"); endwin(); @@ -589,7 +588,7 @@ playit(struct rogue_state *rs) { if ( rs->replaydone != 0 ) { - //fprintf(stderr,"replaydone\n"); sleep(3); + fprintf(stderr,"replaydone\n"); sleep(3); return; } if ( rs->sleeptime != 0 ) From 8c4226da9b970711352553cac62e03b2f38f8354 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 10:33:17 -1100 Subject: [PATCH 0667/1145] Sleeptime --- src/cc/rogue/rogue.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index e288bcf1a..63e699c30 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -588,7 +588,8 @@ playit(struct rogue_state *rs) { if ( rs->replaydone != 0 ) { - fprintf(stderr,"replaydone\n"); sleep(3); + if ( rs->sleeptime != 0 ) + sleep(3); return; } if ( rs->sleeptime != 0 ) From e225c54012f306294773afe8ba0fac4dd8859da0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 16 Feb 2019 20:32:20 -1100 Subject: [PATCH 0668/1145] Use current strength --- src/cc/rogue/init.c | 2 +- src/cc/rogue/state.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index dcbdb2f6d..f296d6182 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -27,7 +27,7 @@ void restore_player(struct rogue_state *rs) int32_t i; THING *obj; //rs->P.gold = purse; max_hp = rs->P.hitpoints; - max_stats.s_str = rs->P.strength; + pstats.s_str = max_stats.s_str = rs->P.strength; pstats.s_lvl = rs->P.level; pstats.s_exp = rs->P.experience; for (i=0; iP.packsize; i++) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 36191d72c..e738a9d16 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1448,7 +1448,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) { rs->P.gold = purse; rs->P.hitpoints = max_hp; - rs->P.strength = max_stats.s_str; + rs->P.strength = pstats.s_str; //max_stats.s_str; rs->P.level = pstats.s_lvl; rs->P.experience = pstats.s_exp; rs->P.dungeonlevel = level; From e3ccd36f0b325587acaf5a5c9affa36fb9190f9b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 00:46:28 -1100 Subject: [PATCH 0669/1145] Initial cursesd --- src/cc/makerogue | 2 +- src/cc/rogue/cursesd.c | 363 +++++++++++++++++++++++++++++++++++++---- src/cc/rogue/cursesd.h | 161 +++++++++--------- src/cc/rogue/options.c | 6 +- src/cc/rogue/rip.c | 1 + src/cc/rogue/rogue.c | 2 + src/cc/rogue/rogue.h | 2 +- src/cc/rogue/rogue.scr | 0 src/cc/rogue/save.c | 4 +- src/cc/rogue/things.c | 63 +++---- 10 files changed, 465 insertions(+), 139 deletions(-) create mode 100644 src/cc/rogue/rogue.scr diff --git a/src/cc/makerogue b/src/cc/makerogue index 490576bd1..249e646f5 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -2,7 +2,7 @@ cd rogue; ./configure # only need this first time make; cd .. -gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -lncurses +gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp #gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so cp librogue.so ../libcc.so diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 643ed87de..54f55c4f5 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -17,13 +17,268 @@ static int32_t endwinflag; +WINDOW *newwin(int32_t nlines,int32_t ncols,int32_t begin_y,int32_t begin_x) +{ + WINDOW *scr = 0; + if ( nlines == LINES && ncols == COLS && begin_y == 0 && begin_x == 0 ) + scr = (WINDOW *)calloc(1,sizeof(*stdscr)); + return(scr); +} + WINDOW *initscr() { if ( stdscr == 0 ) - stdscr = (WINDOW *)calloc(1,sizeof(*stdscr)); + stdscr = newwin(LINES,COLS,0,0); return(stdscr); } +int32_t delwin(WINDOW *win) +{ + free(win); + return(0); +} + +int32_t wmove(WINDOW *win, int32_t y, int32_t x) +{ + win->y = y; + win->x = x; + return(0); +} + +int32_t move(int32_t y, int32_t x) +{ + return(wmove(stdscr,y,x)); +} + +int werase(WINDOW *win) +{ + memset(win->screen,' ',sizeof(win->screen)); + return(0); +} + +int wclear(WINDOW *win) +{ + werase(win); + clearok(win,TRUE); + return(0); +} + +int wclrtoeol(WINDOW *win) +{ + if ( win->x < COLS-1 ) + memset(&win->screen[win->y][win->x],' ',COLS - win->x); + return(0); +} + +int wclrtobot(WINDOW *win) +{ + wclrtoeol(win); + if ( win->y < LINES-1 ) + memset(&win->screen[win->y+1][0],' ',COLS); + return(0); +} + +int erase(void) +{ + return(werase(stdscr)); +} + +int clear(void) +{ + return(wclear(stdscr)); +} + +int clrtobot(void) +{ + return(wclrtobot(stdscr)); +} + +int clrtoeol(void) +{ + return(wclrtoeol(stdscr)); +} + +int32_t waddch(WINDOW *win, chtype ch) +{ + int32_t t; + if ( ch == '\t' ) + { + for (i=0; i<8; i++) + { + if ( win->x >= COLS-1 ) + break; + win->x++; + if ( (win->x & 7) == 0 ) + break; + } + } + else if ( ch == '\n' ) + { + wclrtoeol(win); + win->x = 0; + win->y++; + if ( win->y >= LINES ) + win->y = 0; + } + else if ( ch == '\b' ) + { + if ( win->x > 0 ) + win->x--; + } + else + { + win->screen[win->y][win->x++] = ch; + if ( win->x >= COLS ) + { + win->x = 0; + win->y++; + if ( win->y >= LINES ) + win->y = 0; + } + } + reurn(0); +} + +int32_t mvwaddch(WINDOW *win, int32_t y, int32_t x, chtype ch) +{ + win->y = y; + win->x = x; + return(waddch(win,ch)); +} + +int32_t addch(chtype ch) +{ + return(waddch(stdscr,ch)); +} + +int32_t mvaddch(int32_t y, int32_t x, chtype ch) +{ + return(mvwaddch(stdscr,y,x,ch)); +} + +int32_t waddstr(WINDOW *win, const char *str) +{ + int32_t i; + for (i=0; str[i]!=0; i++) + waddch(win,str[i]); + return(0); +} + +int32_t waddnstr(WINDOW *win, const char *str, int32_t n) +{ + int32_t i; + for (i=0; str[i]!=0 && iy = y; + win->x = x; + return(waddstr(win,str)); +} + +int32_t mvwaddnstr(WINDOW *win, int32_t y, int32_t x, const char *str, int32_t n) +{ + win->y = y; + win->x = x; + return(waddnstr(win,str)); +} + +int32_t addstr(const char *str) +{ + return(waddstr(stdscr,str)); +} + +int32_t addnstr(const char *str, int32_t n) +{ + return(waddnstr(stdscr,str,n)); +} + +int32_t mvaddstr(int32_t y, int32_t x, const char *str) +{ + stdscr->y = y; + stdscr->x = x; + return(waddstr(stdscr,str)); +} + +int32_t mvaddnstr(int32_t y, int32_t x, const char *str, int32_t n) +{ + stdscr->y = y; + stdscr->x = x; + return(waddnstr(stdscr,str,n)); +} + +int32_t printw(char *fmt,...) +{ + char str[512]; int32_t ret; va_list myargs; // Declare a va_list type variable + va_start(myargs,fmt); // Initialise the va_list variable with the ... after fmt + ret = vsprintf(str,fmt,myargs); // Forward the '...' to vsprintf + va_end(myargs); // Clean up the va_list + return(addstr(str)); +} + +int32_t wprintw(WINDOW *win,char *fmt,...) +{ + char str[512]; int32_t ret; va_list myargs; // Declare a va_list type variable + va_start(myargs,fmt); // Initialise the va_list variable with the ... after fmt + ret = vsprintf(str,fmt,myargs); // Forward the '...' to vsprintf + va_end(myargs); // Clean up the va_list + return(waddstr(win,str)); +} + +int32_t mvprintw(int32_t y,int32_t x,char *fmt,...) +{ + char str[512]; int32_t ret; va_list myargs; // Declare a va_list type variable + va_start(myargs,fmt); // Initialise the va_list variable with the ... after fmt + ret = vsprintf(str,fmt,myargs); // Forward the '...' to vsprintf + va_end(myargs); // Clean up the va_list + stdscr->y = y; + stdscr->x = x; + return(addstr(str)); +} + +int32_t mvwprintw(WINDOW *win,int32_t y,int32_t x,char *fmt,...) +{ + char str[512]; int32_t ret; va_list myargs; // Declare a va_list type variable + va_start(myargs,fmt); // Initialise the va_list variable with the ... after fmt + ret = vsprintf(str,fmt,myargs); // Forward the '...' to vsprintf + va_end(myargs); // Clean up the va_list + win->y = y; + win->x = x; + return(waddstr(win,str)); +} + +chtype winch(WINDOW *win) +{ + return(win->screen[win->y][win->x]); +} + +chtype inch(void) +{ + return(winch(stdscr)); +} + +chtype mvwinch(WINDOW *win, int32_t y, int32_t x) +{ + win->y = y; + win->x = x; + return(win->screen[win->y][win->x]); +} + +chtype mvinch(int32_t y, int32_t x) +{ + return(mvwinch(stdscr,y,x)); +} + +int32_t mvcur(int32_t oldrow, int32_t oldcol, int32_t newrow, int32_t newcol) +{ + stdscr->y = newrow; + stdscr->x = newcol; + return(0); +} + void endwin() { if ( stdscr != 0 ) @@ -36,27 +291,12 @@ int isendwin(void) return(endwinflag); } -int wrefresh(WINDOW *win) -{ - return(0); -} - int refresh(void) { endwinflag = 0; return(wrefresh(stdscr)); } -int wnoutrefresh(WINDOW *win) -{ - return(0); -} - -int doupdate(void) -{ - return(0); -} - int redrawwin(WINDOW *win) { return(wrefresh(win)); @@ -67,42 +307,101 @@ int wredrawln(WINDOW *win, int beg_line, int num_lines) return(wrefresh(win)); } -int werase(WINDOW *win) +// functions with no data side effect +#ifdef they_are_macros +int wrefresh(WINDOW *win) { - + return(0); } -int erase(void) +int wnoutrefresh(WINDOW *win) { - return(werase(stdscr)); + return(0); } -int wclear(WINDOW *win) +int doupdate(void) { - + return(0); } -int clear(void) +int32_t touchwin(WINDOW *win) { - return(wclear(stdscr)); + return(0); } -int wclrtobot(WINDOW *win) +int standout(void) { - + return(0); } -int clrtobot(void) +int standend(void) { - return(wclrtobot(stdscr)); + return(0); } -int wclrtoeol(WINDOW *win) +int raw(void) { - + return(0); } -int clrtoeol(void) +int32_t keypad(WINDOW *win, bool bf) { - return(wclrtoeol(stdscr)); + return(0); } + +int noecho(void) +{ + return(0); +} + +int flushinp(void) +{ + return(0); +} + +int clearok(WINDOW *win, bool bf) +{ + return(0); +} + +int idlok(WINDOW *win, bool bf) +{ + return(0); +} + +int leaveok(WINDOW *win, bool bf) +{ + return(0); +} +#endif + +int32_t mvwin(WINDOW *win, int32_t y, int32_t x); // stub +{ + fprintf(stderr,"unexpected call to mvwin\n"); + return(0); +} + +WINDOW *subwin(WINDOW *orig, int nlines, int ncols, int begin_y, int begin_x) +{ + fprintf(stderr,"unexpected and unsupported call to subwin\n"); + return(0); +} + +char erasechar(void) +{ + fprintf(stderr,"unexpected and unsupported call to erasechar\n"); + return(8); +} + +char killchar(void) +{ + fprintf(stderr,"unexpected and unsupported call to erasechar\n"); + return(3); +} + +int32_t mvgetnstr(int32_t y, int32_t x, char *str, int32_t n) // stub +{ + fprintf(stderr,"unexpected and unsupported call to mvgetnstr\n"); + return(0); +} + diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 5e3d375ca..6d5944b75 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -36,38 +36,107 @@ #include #include -#ifdef notyet - struct cursesd_info { uint8_t screen[LINES][COLS]; + int32_t x,y; } *stdscr; typedef struct cursesd_info WINDOW; +typedef char chtype; WINDOW *initscr(void); -int endwin(void); -int isendwin(void); +int32_t endwin(void); +int32_t isendwin(void); //SCREEN *newterm(const char *type, FILE *outfd, FILE *infd); //SCREEN *set_term(SCREEN *new); //void delscreen(SCREEN* sp); -int refresh(void); -int wrefresh(WINDOW *win); -//int wnoutrefresh(WINDOW *win); -//int doupdate(void); -int redrawwin(WINDOW *win); -int wredrawln(WINDOW *win, int beg_line, int num_lines); +int32_t refresh(void); +int32_t wrefresh(WINDOW *win); +//int32_t wnoutrefresh(WINDOW *win); +//int32_t doupdate(void); +int32_t redrawwin(WINDOW *win); +int32_t wredrawln(WINDOW *win, int32_t beg_line, int32_t num_lines); -int erase(void); -int werase(WINDOW *win); -int clear(void); -int wclear(WINDOW *win); -int clrtobot(void); -int wclrtobot(WINDOW *win); -int clrtoeol(void); -int wclrtoeol(WINDOW *win); +int32_t erase(void); +int32_t werase(WINDOW *win); +int32_t clear(void); +int32_t wclear(WINDOW *win); +int32_t clrtobot(void); +int32_t wclrtobot(WINDOW *win); +int32_t clrtoeol(void); +int32_t wclrtoeol(WINDOW *win); -#endif +int32_t standout(void); +int32_t standend(void); +int32_t raw(void); +int32_t noecho(void); +int32_t flushinp(void); +int32_t keypad(WINDOW *win, bool bf); + +int32_t clearok(WINDOW *win, bool bf); +int32_t idlok(WINDOW *win, bool bf); +int32_t leaveok(WINDOW *win, bool bf); + +WINDOW *newwin(int32_t nlines,int32_t ncols,int32_t begin_y,int32_t begin_x); // only LINES,COLS,0,0 +int32_t delwin(WINDOW *win); +int32_t touchwin(WINDOW *win); // stub +WINDOW *subwin(WINDOW *orig, int32_t nlines, int32_t ncols, int32_t begin_y, int32_t begin_x); // stub +int32_t mvwin(WINDOW *win, int32_t y, int32_t x); // stub +int32_t mvcur(int32_t oldrow, int32_t oldcol, int32_t newrow, int32_t newcol); + +char erasechar(void); // stub +char killchar(void); // stub + +int32_t move(int32_t y, int32_t x); +int32_t wmove(WINDOW *win, int32_t y, int32_t x); + +chtype inch(void); +chtype winch(WINDOW *win); +chtype mvinch(int32_t y, int32_t x); +chtype mvwinch(WINDOW *win, int32_t y, int32_t x); + +int32_t addch(chtype ch); +int32_t waddch(WINDOW *win, chtype ch); +int32_t mvaddch(int32_t y, int32_t x, chtype ch); +int32_t mvwaddch(WINDOW *win, int32_t y, int32_t x, chtype ch); + +int32_t addstr(const char *str); +int32_t addnstr(const char *str, int32_t n); +int32_t waddstr(WINDOW *win, const char *str); +int32_t waddnstr(WINDOW *win, const char *str, int32_t n); +int32_t mvaddstr(int32_t y, int32_t x, const char *str); +int32_t mvaddnstr(int32_t y, int32_t x, const char *str, int32_t n); +int32_t mvwaddstr(WINDOW *win, int32_t y, int32_t x, const char *str); +int32_t mvwaddnstr(WINDOW *win, int32_t y, int32_t x, const char *str, int32_t n); + +int32_t mvgetnstr(int32_t y, int32_t x, char *str, int32_t n); // stub +int32_t printw(char *fmt,...); +int32_t wprintw(WINDOW *win,char *fmt,...); +int32_t mvprintw(int32_t y,int32_t x,char *fmt,...); +int32_t mvwprintw(WINDOW *win,int32_t y,int32_t x,char *fmt,...); + +#define A_CHARTEXT 0xff +#define baudrate() 9600 +#define unctrl(a) "^x" +#define getmaxx(a) COLS +#define getmaxy(a) LINES +#define getxy(win,y,x) y = win->y, x = win->x + +// functions with only visible effects +#define wrefresh(win) 0 +#define wnoutrefresh(win) 0 +#define doupdate() 0 +#define touchwin(win) 0 +#define standout() 0 +#define standend() 0 +#define raw() 0 +#define keypad(win,bf) 0 +#define noecho() 0 +#define flushinp() 0 +#define clearok(win,bf) 0 +#define idlok(win,bf) 0 +#define leaveok(win,bf) 0 #ifndef TRUE #define TRUE 1 @@ -77,57 +146,3 @@ int wclrtoeol(WINDOW *win); #endif -#define standout() -#define standend() -#define refresh() -#define raw() -#define noecho() -#define flushinp() -#define clear() -#define clrtoeol() - -#define addch(a) -#define werase(a) -#define wclear(a) -#define delwin(a) -#define addstr(a) -#define touchwin(a) -#define idlok(a,b) -#define clearok(a,b) -#define keypad(a,b) -#define leaveok(a,b) -#define waddch(a,b) -#define waddstr(a,b) -#define move(a,b) -#define mvwin(a,b,c) -#define wmove(a,b,c) -#define mvaddch(a,b,c) -#define mvaddstr(a,b,c) -#define wgetnstr(a,b,c) -#define getyx(a,b,c) -#define mvcur(a,b,c,d) -#define mvwaddch(a,b,c,d) -#define mvprintw(...) -#define printw(...) -#define wprintw(...) -#define mvwprintw(...) - - -#define A_CHARTEXT 0xff -#define inch() 0 -#define endwin() 1 -#define isendwin() 0 -#define baudrate() 9600 -#define killchar() 3 -#define erasechar() 8 -#define wclrtoeol(a) 0 -#define wrefresh(a) 0 -#define unctrl(a) "^x" -#define getmaxx(a) COLS -#define getmaxy(a) LINES -#define mvinch(a,b) '.' -#define mvwinch(a,b,c) 0 -#define newwin(a,b,c,d) 0 -#define subwin(a,b,c,d,e) 0 - -#endif diff --git a/src/cc/rogue/options.c b/src/cc/rogue/options.c index d74979365..258bd184f 100644 --- a/src/cc/rogue/options.c +++ b/src/cc/rogue/options.c @@ -266,7 +266,7 @@ get_str(struct rogue_state *rs,void *vopt, WINDOW *win) { if (c == -1) continue; - else if (c == erasechar()) /* process erase character */ + /*else if (c == erasechar()) // process erase character { if (sp > buf) { @@ -276,12 +276,12 @@ get_str(struct rogue_state *rs,void *vopt, WINDOW *win) } continue; } - else if (c == killchar()) /* process kill character */ + else if (c == killchar()) // process kill character { sp = buf; wmove(win, oy, ox); continue; - } + }*/ else if (sp == buf) { if (c == '-' && win != stdscr) diff --git a/src/cc/rogue/rip.c b/src/cc/rogue/rip.c index be97fb867..65be2e8fa 100644 --- a/src/cc/rogue/rip.c +++ b/src/cc/rogue/rip.c @@ -87,6 +87,7 @@ score(struct rogue_state *rs,int amount, int flags, char monst) delwin(curscr); if (hw != NULL) delwin(hw); + hw = NULL; } top_ten = (SCORE *) malloc(numscores * sizeof (SCORE)); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 63e699c30..eb605385d 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -91,7 +91,9 @@ void rogueiterate(struct rogue_state *rs) // Set up windows if ( hw == NULL ) + { hw = newwin(LINES, COLS, 0, 0); + } idlok(stdscr, TRUE); idlok(hw, TRUE); #ifdef MASTER diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index fac84d8b0..f8e5dd23b 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -29,7 +29,7 @@ #include #include -#ifndef DONTUSEGUI +#ifndef BUILD_ROGUE #include #else diff --git a/src/cc/rogue/rogue.scr b/src/cc/rogue/rogue.scr new file mode 100644 index 000000000..e69de29bb diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index 7349c196a..15dda401e 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -227,7 +227,9 @@ restore(struct rogue_state *rs,char *file, char **envp) char buf[MAXSTR]; //auto STAT sbuf2; - + if ( rs->guiflag == 0 ) + return(0); + if (strcmp(file, "-r") == 0) file = file_name; diff --git a/src/cc/rogue/things.c b/src/cc/rogue/things.c index 29c51c4ed..39c7b94b7 100644 --- a/src/cc/rogue/things.c +++ b/src/cc/rogue/things.c @@ -502,37 +502,44 @@ add_line(struct rogue_state *rs,char *fmt, char *arg) msg(rs,""); if ( rs->sleeptime != 0 ) refresh(); - tw = newwin(line_cnt + 1, maxlen + 2, 0, COLS - maxlen - 3); - sw = subwin(tw, line_cnt + 1, maxlen + 1, 0, COLS - maxlen - 2); - for (y = 0; y <= line_cnt; y++) + if ( rs->guiflag != 0 ) { - wmove(sw, y, 0); - for (x = 0; x <= maxlen; x++) - waddch(sw, mvwinch(hw, y, x)); - } - wmove(tw, line_cnt, 1); - waddstr(tw, prompt); - /* - * if there are lines below, use 'em - */ - if (LINES > NUMLINES) - { - if (NUMLINES + line_cnt > LINES) - mvwin(tw, LINES - (line_cnt + 1), COLS - maxlen - 3); - else - mvwin(tw, NUMLINES, 0); - } - touchwin(tw); - wrefresh(tw); - wait_for(rs,' '); - if (md_hasclreol()) - { - werase(tw); - leaveok(tw, TRUE); + tw = newwin(line_cnt + 1, maxlen + 2, 0, COLS - maxlen - 3); + sw = subwin(tw, line_cnt + 1, maxlen + 1, 0, COLS - maxlen - 2); + for (y = 0; y <= line_cnt; y++) + { + wmove(sw, y, 0); + for (x = 0; x <= maxlen; x++) + waddch(sw, mvwinch(hw, y, x)); + } + wmove(tw, line_cnt, 1); + waddstr(tw, prompt); + /* + * if there are lines below, use 'em + */ + if (LINES > NUMLINES) + { + if (NUMLINES + line_cnt > LINES) + mvwin(tw, LINES - (line_cnt + 1), COLS - maxlen - 3); + else + mvwin(tw, NUMLINES, 0); + } + touchwin(tw); wrefresh(tw); + wait_for(rs,' '); + if (md_hasclreol()) + { + werase(tw); + leaveok(tw, TRUE); + wrefresh(tw); + } + delwin(tw); + touchwin(stdscr); + } + else + { + wait_for(rs,' '); } - delwin(tw); - touchwin(stdscr); } else { From a6b024b5595f0a9e1c65217fc25b3cc32bee5fac Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 00:47:24 -1100 Subject: [PATCH 0670/1145] Delete rogue.scr --- src/cc/rogue/rogue.scr | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/cc/rogue/rogue.scr diff --git a/src/cc/rogue/rogue.scr b/src/cc/rogue/rogue.scr deleted file mode 100644 index e69de29bb..000000000 From 8d1a4eb532cc2ac86aa237be27af71e914a75ca6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 00:48:56 -1100 Subject: [PATCH 0671/1145] Terminate ifdef --- src/cc/rogue/cursesd.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 6d5944b75..8a2062a36 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -145,4 +145,5 @@ int32_t mvwprintw(WINDOW *win,int32_t y,int32_t x,char *fmt,...); #define FALSE 0 #endif +#endif From a76f1fd959472a54c7534ceca9a48287f42a3b40 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 00:51:28 -1100 Subject: [PATCH 0672/1145] Test --- src/cc/rogue/rogue.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index f8e5dd23b..8cf5f7d90 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -30,9 +30,10 @@ #include #ifndef BUILD_ROGUE +xxx #include #else - +yyy #include "cursesd.h" #endif From 360cb73281bddb712eeec96dbbe11dbd96d3bb23 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 00:53:51 -1100 Subject: [PATCH 0673/1145] Mdport -= curses.h --- src/cc/rogue/mdport.c | 5 +++++ src/cc/rogue/rogue.h | 2 -- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index 443ef1e60..899f5d9db 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -81,7 +81,12 @@ #endif #endif +#ifndef BUILD_ROGUE #include /* AIX requires curses.h be included before term.h */ +#else +#include "cursesd.h" +#endif + #if defined(HAVE_TERM_H) #include diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 8cf5f7d90..e99c0d5ff 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -30,10 +30,8 @@ #include #ifndef BUILD_ROGUE -xxx #include #else -yyy #include "cursesd.h" #endif From 413b477db0f6baba40e942d991cbcac87ac3983b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 00:55:09 -1100 Subject: [PATCH 0674/1145] io.c --- src/cc/rogue/io.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index fbcddf5fa..a5762adda 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -8,6 +8,12 @@ //#include //#include //#include +#ifndef BUILD_ROGUE +#include +#else +#include "cursesd.h" +#endif + #include "rogue.h" /* From bc1fc144ae51f30579e19e765737e5d9db511627 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 00:58:04 -1100 Subject: [PATCH 0675/1145] Stdscr --- src/cc/rogue/cursesd.c | 1 + src/cc/rogue/cursesd.h | 3 ++- src/cc/rogue/io.c | 5 ----- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 54f55c4f5..76760c3f9 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -16,6 +16,7 @@ #include "cursesd.h" static int32_t endwinflag; +WINDOW *stdscr; WINDOW *newwin(int32_t nlines,int32_t ncols,int32_t begin_y,int32_t begin_x) { diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 8a2062a36..0cbb2cc01 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -40,7 +40,8 @@ struct cursesd_info { uint8_t screen[LINES][COLS]; int32_t x,y; -} *stdscr; +}; +extern WINDOW *stdscr; typedef struct cursesd_info WINDOW; typedef char chtype; diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index a5762adda..c920ee411 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -8,11 +8,6 @@ //#include //#include //#include -#ifndef BUILD_ROGUE -#include -#else -#include "cursesd.h" -#endif #include "rogue.h" From da992ca886ca526d58536b91501581d89284e848 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 01:15:30 -1100 Subject: [PATCH 0676/1145] Fixes --- src/cc/rogue/cursesd.c | 3 ++- src/cc/rogue/cursesd.h | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 76760c3f9..8462532b9 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -23,6 +23,7 @@ WINDOW *newwin(int32_t nlines,int32_t ncols,int32_t begin_y,int32_t begin_x) WINDOW *scr = 0; if ( nlines == LINES && ncols == COLS && begin_y == 0 && begin_x == 0 ) scr = (WINDOW *)calloc(1,sizeof(*stdscr)); + curscr = scr; return(scr); } @@ -400,7 +401,7 @@ char killchar(void) return(3); } -int32_t mvgetnstr(int32_t y, int32_t x, char *str, int32_t n) // stub +int32_t wgetnstr(WINDOW *win, char *str, int32_t n) // stub { fprintf(stderr,"unexpected and unsupported call to mvgetnstr\n"); return(0); diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 0cbb2cc01..57cb51237 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -41,7 +41,7 @@ struct cursesd_info uint8_t screen[LINES][COLS]; int32_t x,y; }; -extern WINDOW *stdscr; +extern WINDOW *stdscr,*curscr; typedef struct cursesd_info WINDOW; typedef char chtype; @@ -111,7 +111,7 @@ int32_t mvaddnstr(int32_t y, int32_t x, const char *str, int32_t n); int32_t mvwaddstr(WINDOW *win, int32_t y, int32_t x, const char *str); int32_t mvwaddnstr(WINDOW *win, int32_t y, int32_t x, const char *str, int32_t n); -int32_t mvgetnstr(int32_t y, int32_t x, char *str, int32_t n); // stub +int32_t wgetnstr(WINDOW *win, char *str, int32_t n); // stub int32_t printw(char *fmt,...); int32_t wprintw(WINDOW *win,char *fmt,...); int32_t mvprintw(int32_t y,int32_t x,char *fmt,...); @@ -122,7 +122,7 @@ int32_t mvwprintw(WINDOW *win,int32_t y,int32_t x,char *fmt,...); #define unctrl(a) "^x" #define getmaxx(a) COLS #define getmaxy(a) LINES -#define getxy(win,y,x) y = win->y, x = win->x +#define getyx(win,y,x) y = win->y, x = win->x // functions with only visible effects #define wrefresh(win) 0 From 958365e987e02457d833e96b657c0e2406151d48 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 01:42:06 -1100 Subject: [PATCH 0677/1145] _argfory --- src/cc/rogue/cursesd.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 57cb51237..12ab8b2be 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -122,7 +122,7 @@ int32_t mvwprintw(WINDOW *win,int32_t y,int32_t x,char *fmt,...); #define unctrl(a) "^x" #define getmaxx(a) COLS #define getmaxy(a) LINES -#define getyx(win,y,x) y = win->y, x = win->x +#define getyx(win,_argfory,_argforx) _argfory = win->y, _argforx = win->x // functions with only visible effects #define wrefresh(win) 0 From 8824e836a700a03bdcc1265e1aa36cbd37e275f3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 01:44:12 -1100 Subject: [PATCH 0678/1145] extern WINDOW *stdscr,*curscr; --- src/cc/rogue/rogue.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index e99c0d5ff..f3f5572b2 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -860,5 +860,8 @@ extern const char *wood[]; extern int cNWOOD; extern const char *metal[]; extern int cNMETAL; + +extern WINDOW *stdscr,*curscr; + #endif From 43edfb4ae23abe6ce59ce2377f7329e78eb83e17 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 01:51:13 -1100 Subject: [PATCH 0679/1145] Stubs --- src/cc/rogue/cursesd.c | 6 ++++++ src/cc/rogue/cursesd.h | 6 +++++- src/cc/rogue/rogue.c | 2 ++ src/cc/rogue/rogue.h | 2 +- 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 8462532b9..c89a713ae 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -407,3 +407,9 @@ int32_t wgetnstr(WINDOW *win, char *str, int32_t n) // stub return(0); } +int32_t getch(void) +{ + fprintf(stderr,"unexpected and unsupported call to getch\n"); + return(0); +} + diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 12ab8b2be..53d928ad0 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -41,10 +41,12 @@ struct cursesd_info uint8_t screen[LINES][COLS]; int32_t x,y; }; -extern WINDOW *stdscr,*curscr; typedef struct cursesd_info WINDOW; +extern WINDOW *stdscr,*curscr; typedef char chtype; +int32_t getch(void); // stub + WINDOW *initscr(void); int32_t endwin(void); int32_t isendwin(void); @@ -138,6 +140,8 @@ int32_t mvwprintw(WINDOW *win,int32_t y,int32_t x,char *fmt,...); #define clearok(win,bf) 0 #define idlok(win,bf) 0 #define leaveok(win,bf) 0 +#define halfdelay(x) 0 +#define nocbreak() 0 #ifndef TRUE #define TRUE 1 diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index eb605385d..b709e8d3a 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -544,9 +544,11 @@ tstp(int ignored) fflush(stdout); //wmove(curscr,oy,ox); #ifndef __APPLE__ +#ifndef BUILD_ROGUE curscr->_cury = oy; curscr->_curx = ox; #endif +#endif } /* diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index f3f5572b2..a5ddf943f 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -861,7 +861,7 @@ extern int cNWOOD; extern const char *metal[]; extern int cNMETAL; -extern WINDOW *stdscr,*curscr; +//extern WINDOW *stdscr,*curscr; #endif From db50762b5cd84439904e55d0f1d8515b84b24653 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 01:59:19 -1100 Subject: [PATCH 0680/1145] md_readchar --- src/cc/rogue/cursesd.c | 7 +++++++ src/cc/rogue/cursesd.h | 4 ++++ src/cc/rogue/mdport.c | 4 +++- 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index c89a713ae..c7a28fc62 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -17,6 +17,7 @@ static int32_t endwinflag; WINDOW *stdscr; +int32_t ESCDELAY; WINDOW *newwin(int32_t nlines,int32_t ncols,int32_t begin_y,int32_t begin_x) { @@ -413,3 +414,9 @@ int32_t getch(void) return(0); } +int32_t md_readchar(void) +{ + fprintf(stderr,"unexpected and unsupported call to md_readchar\n"); + return(0); +} + diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 53d928ad0..4fa09e9d9 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -36,6 +36,8 @@ #include #include +#define ERR (-1) + struct cursesd_info { uint8_t screen[LINES][COLS]; @@ -43,9 +45,11 @@ struct cursesd_info }; typedef struct cursesd_info WINDOW; extern WINDOW *stdscr,*curscr; +extern int32_t ESCDELAY; typedef char chtype; int32_t getch(void); // stub +int32_t md_readchar(void); // stub WINDOW *initscr(void); int32_t endwin(void); diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index 899f5d9db..841dffbb8 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -1081,6 +1081,7 @@ md_setsuspchar(int c) #define M_KEYPAD 2 #define M_TRAIL 3 +#ifndef BUILD_ROGUE int md_readchar() { @@ -1320,7 +1321,8 @@ md_readchar() return(ch & 0x7F); } - +#endif + #if defined(LOADAV) && defined(HAVE_NLIST_H) && defined(HAVE_NLIST) /* * loadav: From 0e79c0002e61f8597ffd0e047ea14b0864859c04 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 02:03:09 -1100 Subject: [PATCH 0681/1145] Build cursesd.c --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 8a5cd2185..77f6a21ac 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -496,6 +496,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will #ifdef BUILD_ROGUE #include "rogue_rpc.cpp" +#include "rogue/cursesd.c" #include "rogue/vers.c" #include "rogue/extern.c" #include "rogue/armor.c" From 4a6e3550134ae0b1d04a86f4e2fdac2a9aa4b1f4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 02:05:20 -1100 Subject: [PATCH 0682/1145] syntax --- src/cc/rogue/cursesd.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index c7a28fc62..d1975624c 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -103,7 +103,7 @@ int clrtoeol(void) int32_t waddch(WINDOW *win, chtype ch) { - int32_t t; + int32_t i; if ( ch == '\t' ) { for (i=0; i<8; i++) @@ -139,7 +139,7 @@ int32_t waddch(WINDOW *win, chtype ch) win->y = 0; } } - reurn(0); + return(0); } int32_t mvwaddch(WINDOW *win, int32_t y, int32_t x, chtype ch) @@ -186,7 +186,7 @@ int32_t mvwaddnstr(WINDOW *win, int32_t y, int32_t x, const char *str, int32_t n { win->y = y; win->x = x; - return(waddnstr(win,str)); + return(waddnstr(win,str,n)); } int32_t addstr(const char *str) @@ -378,7 +378,7 @@ int leaveok(WINDOW *win, bool bf) } #endif -int32_t mvwin(WINDOW *win, int32_t y, int32_t x); // stub +int32_t mvwin(WINDOW *win, int32_t y, int32_t x) // stub { fprintf(stderr,"unexpected call to mvwin\n"); return(0); From 62e1966b14263fcb96ca95d36f4535bc70b514f7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 02:05:58 -1100 Subject: [PATCH 0683/1145] Void --- src/cc/rogue/cursesd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index d1975624c..5bba65c95 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -282,7 +282,7 @@ int32_t mvcur(int32_t oldrow, int32_t oldcol, int32_t newrow, int32_t newcol) return(0); } -void endwin() +void endwin(void) { if ( stdscr != 0 ) free(stdscr), stdscr = 0; From 3666f642e496ef9a2bc9d27e5514794bd19dcfc3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 02:07:34 -1100 Subject: [PATCH 0684/1145] int32_t --- src/cc/rogue/cursesd.c | 51 +++++++++++++++++++++--------------------- 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 5bba65c95..99274b86f 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -53,27 +53,27 @@ int32_t move(int32_t y, int32_t x) return(wmove(stdscr,y,x)); } -int werase(WINDOW *win) +int32_t werase(WINDOW *win) { memset(win->screen,' ',sizeof(win->screen)); return(0); } -int wclear(WINDOW *win) +int32_t wclear(WINDOW *win) { werase(win); clearok(win,TRUE); return(0); } -int wclrtoeol(WINDOW *win) +int32_t wclrtoeol(WINDOW *win) { if ( win->x < COLS-1 ) memset(&win->screen[win->y][win->x],' ',COLS - win->x); return(0); } -int wclrtobot(WINDOW *win) +int32_t wclrtobot(WINDOW *win) { wclrtoeol(win); if ( win->y < LINES-1 ) @@ -81,22 +81,22 @@ int wclrtobot(WINDOW *win) return(0); } -int erase(void) +int32_t erase(void) { return(werase(stdscr)); } -int clear(void) +int32_t clear(void) { return(wclear(stdscr)); } -int clrtobot(void) +int32_t clrtobot(void) { return(wclrtobot(stdscr)); } -int clrtoeol(void) +int32_t clrtoeol(void) { return(wclrtoeol(stdscr)); } @@ -282,47 +282,48 @@ int32_t mvcur(int32_t oldrow, int32_t oldcol, int32_t newrow, int32_t newcol) return(0); } -void endwin(void) +int32_t endwin(void) { if ( stdscr != 0 ) free(stdscr), stdscr = 0; endwinflag = 1; + return(0); } -int isendwin(void) +int32_t isendwin(void) { return(endwinflag); } -int refresh(void) +int32_t refresh(void) { endwinflag = 0; return(wrefresh(stdscr)); } -int redrawwin(WINDOW *win) +int32_t redrawwin(WINDOW *win) { return(wrefresh(win)); } -int wredrawln(WINDOW *win, int beg_line, int num_lines) +int32_t wredrawln(WINDOW *win, int32_t beg_line, int32_t num_lines) { return(wrefresh(win)); } // functions with no data side effect #ifdef they_are_macros -int wrefresh(WINDOW *win) +int32_t wrefresh(WINDOW *win) { return(0); } -int wnoutrefresh(WINDOW *win) +int32_t wnoutrefresh(WINDOW *win) { return(0); } -int doupdate(void) +int32_t doupdate(void) { return(0); } @@ -332,17 +333,17 @@ int32_t touchwin(WINDOW *win) return(0); } -int standout(void) +int32_t standout(void) { return(0); } -int standend(void) +int32_t standend(void) { return(0); } -int raw(void) +int32_t raw(void) { return(0); } @@ -352,27 +353,27 @@ int32_t keypad(WINDOW *win, bool bf) return(0); } -int noecho(void) +int32_t noecho(void) { return(0); } -int flushinp(void) +int32_t flushinp(void) { return(0); } -int clearok(WINDOW *win, bool bf) +int32_t clearok(WINDOW *win, bool bf) { return(0); } -int idlok(WINDOW *win, bool bf) +int32_t idlok(WINDOW *win, bool bf) { return(0); } -int leaveok(WINDOW *win, bool bf) +int32_t leaveok(WINDOW *win, bool bf) { return(0); } @@ -384,7 +385,7 @@ int32_t mvwin(WINDOW *win, int32_t y, int32_t x) // stub return(0); } -WINDOW *subwin(WINDOW *orig, int nlines, int ncols, int begin_y, int begin_x) +WINDOW *subwin(WINDOW *orig, int32_t nlines, int32_t ncols, int32_t begin_y, int32_t begin_x) { fprintf(stderr,"unexpected and unsupported call to subwin\n"); return(0); From d908ddc5a5bb97b63a62a8b6da45d3bebdf0ec58 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 02:34:50 -1100 Subject: [PATCH 0685/1145] +print --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 4d6167b3f..ed69b6bc2 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -459,7 +459,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint } if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { - //fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); + fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); if ( (tokenid != zeroid || playertx.vin[1].prevout.hash == gametxid) && rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid) == 0 ) { // if registertxid has vin from pk, it can be used From acedc0026123f41a35bfd577f767f8d13e22ce03 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 02:39:36 -1100 Subject: [PATCH 0686/1145] Dont save from daemon --- src/cc/rogue/save.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index 15dda401e..b1cac8f8f 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -148,7 +148,9 @@ void save_file(struct rogue_state *rs,FILE *savef,int32_t guiflag) { char buf[80],fname[512]; int32_t i,n,nonz,histo[0x100]; FILE *fp; - memset(&rs->P,0,sizeof(rs->P)); + if ( rs->guiflag == 0 ) + return; + //memset(&rs->P,0,sizeof(rs->P)); mvcur(0, COLS - 1, LINES - 1, 0); putchar('\n'); endwin(); From dd68e9cdfeac3b0b7ddd838bd008b22d9b0bea8b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 02:49:03 -1100 Subject: [PATCH 0687/1145] +print --- src/cc/rogue/cursesd.c | 1 + src/cc/rogue_rpc.cpp | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 99274b86f..e504a0ca4 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -162,6 +162,7 @@ int32_t mvaddch(int32_t y, int32_t x, chtype ch) int32_t waddstr(WINDOW *win, const char *str) { int32_t i; + fprintf(stderr,"%s\n",str); for (i=0; str[i]!=0; i++) waddch(win,str[i]); return(0); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ed69b6bc2..44d42dff8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -459,7 +459,7 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint } if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) { - fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); + //fprintf(stderr,"playertxid.%s got vin.%s/v%d gametxid.%s iterate.%d\n",playertxid.ToString().c_str(),playertx.vin[1].prevout.hash.ToString().c_str(),(int32_t)playertx.vin[1].prevout.n-maxplayers,gametxid.ToString().c_str(),rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid)); if ( (tokenid != zeroid || playertx.vin[1].prevout.hash == gametxid) && rogue_iterateplayer(registertxid,gametxid,playertx.vin[1].prevout.n-maxplayers,playertxid) == 0 ) { // if registertxid has vin from pk, it can be used @@ -880,7 +880,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) fprintf(stderr,"error writing %s\n",fname); fclose(fp); } - num = rogue_replay2(player,seed,keystrokes,numkeys,playerdata.size()==0?0:&P,50); + num = rogue_replay2(player,seed,keystrokes,numkeys,playerdata.size()==0?0:&P,0); newdata.resize(num); for (i=0; i Date: Sun, 17 Feb 2019 02:53:02 -1100 Subject: [PATCH 0688/1145] Test --- src/cc/rogue/save.c | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index b1cac8f8f..af0ed37b6 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -148,19 +148,20 @@ void save_file(struct rogue_state *rs,FILE *savef,int32_t guiflag) { char buf[80],fname[512]; int32_t i,n,nonz,histo[0x100]; FILE *fp; - if ( rs->guiflag == 0 ) - return; - //memset(&rs->P,0,sizeof(rs->P)); - mvcur(0, COLS - 1, LINES - 1, 0); - putchar('\n'); - endwin(); - resetltchars(); - md_chmod(file_name, 0400); - if ( guiflag != 0 ) + if ( rs->guiflag != 0 ) { - encwrite(version, strlen(version)+1, savef); - sprintf(buf,"%d x %d\n", LINES, COLS); - encwrite(buf,80,savef); + //memset(&rs->P,0,sizeof(rs->P)); + mvcur(0, COLS - 1, LINES - 1, 0); + putchar('\n'); + endwin(); + resetltchars(); + md_chmod(file_name, 0400); + if ( guiflag != 0 ) + { + encwrite(version, strlen(version)+1, savef); + sprintf(buf,"%d x %d\n", LINES, COLS); + encwrite(buf,80,savef); + } } rs_save_file(rs,savef); n = sizeof(rs->P) - sizeof(rs->P.roguepack) + sizeof(rs->P.roguepack[0])*rs->P.packsize; From 35eb8d347a2404e15b1187de9a344553fc63df6a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 02:57:06 -1100 Subject: [PATCH 0689/1145] Test speed --- src/cc/rogue/cursesd.c | 2 +- src/cc/rogue/rogue.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index e504a0ca4..c9785c0d1 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -162,7 +162,7 @@ int32_t mvaddch(int32_t y, int32_t x, chtype ch) int32_t waddstr(WINDOW *win, const char *str) { int32_t i; - fprintf(stderr,"%s\n",str); + //fprintf(stderr,"%s\n",str); for (i=0; str[i]!=0; i++) waddch(win,str[i]); return(0); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index b709e8d3a..ca2926c35 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -252,7 +252,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu } uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); - if ( 0 ) + if ( 1 ) { fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL) - starttime); sleep(2); From 4d1bfb8c862506993c14329f9fe5ff27b296d075 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 03:03:06 -1100 Subject: [PATCH 0690/1145] Test --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index ca2926c35..b709e8d3a 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -252,7 +252,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu } uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); - if ( 1 ) + if ( 0 ) { fprintf(stderr,"elapsed %d seconds\n",(uint32_t)time(NULL) - starttime); sleep(2); From bb03c1d872d6cb3a0174bb7bc8744d72b027938b Mon Sep 17 00:00:00 2001 From: "Jonathan \"Duke\" Leto" Date: Sun, 17 Feb 2019 06:03:35 -0800 Subject: [PATCH 0691/1145] Update zeromq to 4.3.1 --- depends/packages/zeromq.mk | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/depends/packages/zeromq.mk b/depends/packages/zeromq.mk index b9a57cba7..0cb256e81 100644 --- a/depends/packages/zeromq.mk +++ b/depends/packages/zeromq.mk @@ -14,10 +14,10 @@ define $(package)_set_vars endef else package=zeromq -$(package)_version=4.2.1 -$(package)_download_path=https://github.com/zeromq/libzmq/releases/download/v$($(package)_version) +$(package)_version=4.3.1 +$(package)_download_path=https://github.com/zeromq/libzmq/releases/download/v$($(package)_version)/ $(package)_file_name=$(package)-$($(package)_version).tar.gz -$(package)_sha256_hash=27d1e82a099228ee85a7ddb2260f40830212402c605a4a10b5e5498a7e0e9d03 +$(package)_sha256_hash=bcbabe1e2c7d0eec4ed612e10b94b112dd5f06fcefa994a0c79a45d835cd21eb define $(package)_set_vars $(package)_config_opts=--without-documentation --disable-shared --disable-curve From d16b2dd1bf68d50c69b497b8dda4b0a2fb1d0d05 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 05:56:17 -1100 Subject: [PATCH 0692/1145] Test --- src/cc/rogue/cursesd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index c9785c0d1..e504a0ca4 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -162,7 +162,7 @@ int32_t mvaddch(int32_t y, int32_t x, chtype ch) int32_t waddstr(WINDOW *win, const char *str) { int32_t i; - //fprintf(stderr,"%s\n",str); + fprintf(stderr,"%s\n",str); for (i=0; str[i]!=0; i++) waddch(win,str[i]); return(0); From 9c8ebf3f6279614516e32cbb5ee65c8a92aa2721 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 06:04:59 -1100 Subject: [PATCH 0693/1145] Flush always --- src/cc/rogue/rogue.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index b709e8d3a..f28d0df29 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -336,7 +336,7 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) } fclose(fp); } - rogue_replay2(0,seed,keystrokes,num,player,150); + rogue_replay2(0,seed,keystrokes,num,player,30); //mvaddstr(LINES - 2, 0, (char *)"replay completed"); endwin(); @@ -601,7 +601,7 @@ playit(struct rogue_state *rs) } else { - if ( rs->needflush != 0 && rs->num > 4096 ) + if ( rs->needflush != 0 )//&& rs->num > 4096 ) { if ( flushkeystrokes(rs) == 0 ) rs->needflush = 0; From e5865055252d9c5683e99de8d1bb81afd9f13052 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 06:18:52 -1100 Subject: [PATCH 0694/1145] +proint --- src/cc/rogue/state.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index e738a9d16..8b312ae5f 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1434,7 +1434,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) item = &rs->P.roguepack[rs->P.packsize]; if ( pstats.s_hpt <= 0 ) { - //fprintf(stderr,"KILLED\n"); + fprintf(stderr,"KILLED\n"); rs->P.gold = -1; rs->P.hitpoints = -1; rs->P.strength = -1; @@ -1452,9 +1452,9 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) rs->P.level = pstats.s_lvl; rs->P.experience = pstats.s_exp; rs->P.dungeonlevel = level; - //fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,max_stats.s_str,pstats.s_lvl,pstats.s_exp,level); + fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,max_stats.s_str,pstats.s_lvl,pstats.s_exp,level); } - //fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); + fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); if ( rs->P.packsize < MAXPACK && o->o_type != AMULET ) { packsave(item,o->_o._o_type,o->_o._o_launch,o->_o._o_damage,sizeof(o->_o._o_damage),o->_o._o_hurldmg,sizeof(o->_o._o_hurldmg),o->_o._o_count,o->_o._o_which,o->_o._o_hplus,o->_o._o_dplus,o->_o._o_arm,o->_o._o_flags,o->_o._o_group); @@ -2009,7 +2009,10 @@ int rs_save_file(struct rogue_state *rs,FILE *savef) { if (write_error) + { + fprintf(stderr,"write error\n"); return(WRITESTAT); + } rs_write_boolean(savef, after); /* 1 */ /* extern.c */ rs_write_boolean(savef, again); /* 2 */ From 9cec68f8c49833a6143eabf2a9b58858847321f1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 06:25:24 -1100 Subject: [PATCH 0695/1145] +prints --- src/cc/rogue/rogue.c | 1 + src/cc/rogue/rogue.h | 4 ++-- src/cc/rogue/save.c | 8 +++++--- src/cc/rogue/state.c | 3 ++- src/cc/rogue_rpc.cpp | 1 + 5 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index f28d0df29..2fd50607a 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -273,6 +273,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu if ( (fp= fopen("checkfile","wb")) != 0 ) { save_file(rs,fp,0); + fprintf(stderr,"gold.%d hp.%d strength.%d level.%d exp.%d dungeon.%d data[%d]\n",rs->P.gold,rs->P.hitpoints,rs->P.strength,rs->P.level,rs->P.experience,rs->P.dungeonlevel,rs->playersize); if ( newdata != 0 && rs->playersize > 0 ) memcpy(newdata,rs->playerdata,rs->playersize); } diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index a5ddf943f..20f32c6f2 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -358,7 +358,7 @@ typedef union _bits256 bits256; #endif -#ifndef ROGUE_DECLARED_PACK +/*#ifndef ROGUE_DECLARED_PACK struct rogue_packitem { int32_t type,launch,count,which,hplus,dplus,arm,flags,group; @@ -369,7 +369,7 @@ struct rogue_player int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; struct rogue_packitem roguepack[MAXPACK]; }; -#define ROGUE_DECLARED_PACK +#define ROGUE_DECLARED_PACK*/ #endif struct rogue_state diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index af0ed37b6..0496eaa73 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -150,7 +150,6 @@ save_file(struct rogue_state *rs,FILE *savef,int32_t guiflag) char buf[80],fname[512]; int32_t i,n,nonz,histo[0x100]; FILE *fp; if ( rs->guiflag != 0 ) { - //memset(&rs->P,0,sizeof(rs->P)); mvcur(0, COLS - 1, LINES - 1, 0); putchar('\n'); endwin(); @@ -163,7 +162,10 @@ save_file(struct rogue_state *rs,FILE *savef,int32_t guiflag) encwrite(buf,80,savef); } } - rs_save_file(rs,savef); + memset(&rs->P,0,sizeof(rs->P)); + rs_save_file(rs,savef); // sets rs->P + fprintf(stderr,"gold.%d hp.%d strength.%d level.%d exp.%d %d\n",rs->P.gold,rs->P.hitpoints,rs->P.strength,rs->P.level,rs->P.experience,rs->P.dungeonlevel); + n = sizeof(rs->P) - sizeof(rs->P.roguepack) + sizeof(rs->P.roguepack[0])*rs->P.packsize; memset(histo,0,sizeof(histo)); for (i=0; iplayerdata[i] = ((uint8_t *)&rs->P)[i]; } rs->playersize = n; - //fprintf(stderr," packsize.%d n.%d\n",rs->P.packsize,n); + fprintf(stderr," packsize.%d playersize.%d\n",rs->P.packsize,n); if ( (fp= fopen(rogue_packfname(rs,fname),"wb")) != 0 ) { fwrite(&rs->P,1,n,fp); diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 8b312ae5f..d1ceaaa2f 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1452,7 +1452,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) rs->P.level = pstats.s_lvl; rs->P.experience = pstats.s_exp; rs->P.dungeonlevel = level; - fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,max_stats.s_str,pstats.s_lvl,pstats.s_exp,level); + fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,pstats.s_str,pstats.s_lvl,pstats.s_exp,level); } fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); if ( rs->P.packsize < MAXPACK && o->o_type != AMULET ) @@ -1460,6 +1460,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) packsave(item,o->_o._o_type,o->_o._o_launch,o->_o._o_damage,sizeof(o->_o._o_damage),o->_o._o_hurldmg,sizeof(o->_o._o_hurldmg),o->_o._o_count,o->_o._o_which,o->_o._o_hplus,o->_o._o_dplus,o->_o._o_arm,o->_o._o_flags,o->_o._o_group); rs->P.packsize++; } + fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,pstats.s_str,pstats.s_lvl,pstats.s_exp,level); } } rs_write_marker(savef, RSID_OBJECT); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 44d42dff8..7b26ff572 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -23,6 +23,7 @@ #define ROGUE_MAXKEYSTROKESGAP 60 #define ROGUE_MAXITERATIONS 777 + #define MAXPACK 23 struct rogue_packitem { From 2ee3594c1b0da6c8596be7f7f37d5afd0e422ec4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 06:27:05 -1100 Subject: [PATCH 0696/1145] Test --- src/cc/rogue/rogue.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 20f32c6f2..a5ddf943f 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -358,7 +358,7 @@ typedef union _bits256 bits256; #endif -/*#ifndef ROGUE_DECLARED_PACK +#ifndef ROGUE_DECLARED_PACK struct rogue_packitem { int32_t type,launch,count,which,hplus,dplus,arm,flags,group; @@ -369,7 +369,7 @@ struct rogue_player int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; struct rogue_packitem roguepack[MAXPACK]; }; -#define ROGUE_DECLARED_PACK*/ +#define ROGUE_DECLARED_PACK #endif struct rogue_state From fa7ad1f44bbc418ac2644f589844fb1f329af368 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 06:32:17 -1100 Subject: [PATCH 0697/1145] Test --- src/cc/rogue/cursesd.c | 2 +- src/cc/rogue/save.c | 4 ++-- src/cc/rogue/state.c | 7 +++---- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index e504a0ca4..c9785c0d1 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -162,7 +162,7 @@ int32_t mvaddch(int32_t y, int32_t x, chtype ch) int32_t waddstr(WINDOW *win, const char *str) { int32_t i; - fprintf(stderr,"%s\n",str); + //fprintf(stderr,"%s\n",str); for (i=0; str[i]!=0; i++) waddch(win,str[i]); return(0); diff --git a/src/cc/rogue/save.c b/src/cc/rogue/save.c index 0496eaa73..4df79e150 100644 --- a/src/cc/rogue/save.c +++ b/src/cc/rogue/save.c @@ -164,7 +164,7 @@ save_file(struct rogue_state *rs,FILE *savef,int32_t guiflag) } memset(&rs->P,0,sizeof(rs->P)); rs_save_file(rs,savef); // sets rs->P - fprintf(stderr,"gold.%d hp.%d strength.%d level.%d exp.%d %d\n",rs->P.gold,rs->P.hitpoints,rs->P.strength,rs->P.level,rs->P.experience,rs->P.dungeonlevel); + //fprintf(stderr,"gold.%d hp.%d strength.%d level.%d exp.%d %d\n",rs->P.gold,rs->P.hitpoints,rs->P.strength,rs->P.level,rs->P.experience,rs->P.dungeonlevel); n = sizeof(rs->P) - sizeof(rs->P.roguepack) + sizeof(rs->P.roguepack[0])*rs->P.packsize; memset(histo,0,sizeof(histo)); @@ -175,7 +175,7 @@ save_file(struct rogue_state *rs,FILE *savef,int32_t guiflag) rs->playerdata[i] = ((uint8_t *)&rs->P)[i]; } rs->playersize = n; - fprintf(stderr," packsize.%d playersize.%d\n",rs->P.packsize,n); + //fprintf(stderr," packsize.%d playersize.%d\n",rs->P.packsize,n); if ( (fp= fopen(rogue_packfname(rs,fname),"wb")) != 0 ) { fwrite(&rs->P,1,n,fp); diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index d1ceaaa2f..800622444 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1434,7 +1434,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) item = &rs->P.roguepack[rs->P.packsize]; if ( pstats.s_hpt <= 0 ) { - fprintf(stderr,"KILLED\n"); + //fprintf(stderr,"KILLED\n"); rs->P.gold = -1; rs->P.hitpoints = -1; rs->P.strength = -1; @@ -1452,15 +1452,14 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) rs->P.level = pstats.s_lvl; rs->P.experience = pstats.s_exp; rs->P.dungeonlevel = level; - fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,pstats.s_str,pstats.s_lvl,pstats.s_exp,level); + //fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,pstats.s_str,pstats.s_lvl,pstats.s_exp,level); } - fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); + //fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); if ( rs->P.packsize < MAXPACK && o->o_type != AMULET ) { packsave(item,o->_o._o_type,o->_o._o_launch,o->_o._o_damage,sizeof(o->_o._o_damage),o->_o._o_hurldmg,sizeof(o->_o._o_hurldmg),o->_o._o_count,o->_o._o_which,o->_o._o_hplus,o->_o._o_dplus,o->_o._o_arm,o->_o._o_flags,o->_o._o_group); rs->P.packsize++; } - fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,pstats.s_str,pstats.s_lvl,pstats.s_exp,level); } } rs_write_marker(savef, RSID_OBJECT); From 64d18650222bff6079d0f8e1ddd36224225d7a60 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 06:34:57 -1100 Subject: [PATCH 0698/1145] rogue_player.h --- src/cc/rogue/rogue.h | 15 +-------------- src/cc/rogue/rogue_player.h | 35 +++++++++++++++++++++++++++++++++++ src/cc/rogue_rpc.cpp | 17 +---------------- 3 files changed, 37 insertions(+), 30 deletions(-) create mode 100644 src/cc/rogue/rogue_player.h diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index a5ddf943f..905a5ed36 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -357,20 +357,7 @@ union _bits256 { uint8_t bytes[32]; uint16_t ushorts[16]; uint32_t uints[8]; uin typedef union _bits256 bits256; #endif - -#ifndef ROGUE_DECLARED_PACK -struct rogue_packitem -{ - int32_t type,launch,count,which,hplus,dplus,arm,flags,group; - char damage[8],hurldmg[8]; -}; -struct rogue_player -{ - int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; - struct rogue_packitem roguepack[MAXPACK]; -}; -#define ROGUE_DECLARED_PACK -#endif +#include "rogue_player.h" // interface to rpc struct rogue_state { diff --git a/src/cc/rogue/rogue_player.h b/src/cc/rogue/rogue_player.h new file mode 100644 index 000000000..1319b3213 --- /dev/null +++ b/src/cc/rogue/rogue_player.h @@ -0,0 +1,35 @@ +/****************************************************************************** + * Copyright © 2014-2019 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 ROGUE_DECLARED_PACK +#define ROGUE_DECLARED_PACK + + +#define MAXPACK 23 +struct rogue_packitem +{ + int32_t type,launch,count,which,hplus,dplus,arm,flags,group; + char damage[8],hurldmg[8]; +}; +struct rogue_player +{ + int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; + struct rogue_packitem roguepack[MAXPACK]; +}; +int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis); +void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item); + +#endif + diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 7b26ff572..253f3ec89 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -23,22 +23,7 @@ #define ROGUE_MAXKEYSTROKESGAP 60 #define ROGUE_MAXITERATIONS 777 - -#define MAXPACK 23 -struct rogue_packitem -{ - int32_t type,launch,count,which,hplus,dplus,arm,flags,group; - char damage[8],hurldmg[8]; -}; -struct rogue_player -{ - int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; - struct rogue_packitem roguepack[MAXPACK]; -}; -int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis); -#define ROGUE_DECLARED_PACK -void rogue_packitemstr(char *packitemstr,struct rogue_packitem *item); - +#include "rogue/rogueplayer.h" std::string Rogue_pname = ""; From 0d022d48145c19964ea5889138934b824c2937f6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 06:35:36 -1100 Subject: [PATCH 0699/1145] _ --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 253f3ec89..e297f6a27 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -23,7 +23,7 @@ #define ROGUE_MAXKEYSTROKESGAP 60 #define ROGUE_MAXITERATIONS 777 -#include "rogue/rogueplayer.h" +#include "rogue/rogue_player.h" std::string Rogue_pname = ""; From 82a43da6ec36fceefce05a21872cd64d447e5680 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 07:17:08 -1100 Subject: [PATCH 0700/1145] Print extracted string --- src/cc/rogue_rpc.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e297f6a27..032a99ea9 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -720,7 +720,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) playertxid = juint256(jitem(params,1)); if ( rogue_playerdata(cp,origplayergame,tokenid,pk,playerdata,symbol,pname,playertxid) < 0 ) return(cclib_error(result,"couldnt extract valid playerdata")); - if ( tokenid != zeroid ) + if ( tokenid != zeroid ) // if it is tokentransfer this will be 0 vout = 1; } rogue_univalue(result,0,maxplayers,buyin); @@ -814,7 +814,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result; CPubKey pk,roguepk; int32_t i,n,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char rogueaddr[64],fname[64],*pubstr,*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000],pub33[33]; + UniValue result; CPubKey pk,roguepk; int32_t i,n,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char rogueaddr[64],fname[64],str[512],*pubstr,*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000],pub33[33]; pk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); result.push_back(Pair("status","success")); @@ -878,7 +878,8 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) fprintf(stderr,"zero value character was killed -> no playerdata\n"); newdata.resize(0); } - fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); + sprintf(str,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); + result.push_back(Pair("extracted",str)); if ( keystrokes != 0 ) free(keystrokes); } else num = 0; From 72e86ef16ef542b2e754aafd4011cf661d24166d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 07:23:10 -1100 Subject: [PATCH 0701/1145] Test --- src/cc/rogue_rpc.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 032a99ea9..25b279f61 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -812,6 +812,8 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"couldnt reparse params")); } +// change to subfunction without JSON to be used by other functions + UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result; CPubKey pk,roguepk; int32_t i,n,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char rogueaddr[64],fname[64],str[512],*pubstr,*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000],pub33[33]; @@ -878,8 +880,9 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) fprintf(stderr,"zero value character was killed -> no playerdata\n"); newdata.resize(0); } - sprintf(str,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); + sprintf(str,"extracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); result.push_back(Pair("extracted",str)); + fprintf(stderr,"%s\n",str); if ( keystrokes != 0 ) free(keystrokes); } else num = 0; From b95214f57e411a114322b251b17822be4c81de61 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 07:43:08 -1100 Subject: [PATCH 0702/1145] - -lncurses --- src/Makefile.am | 4 ++-- src/cc/rogue_rpc.cpp | 8 +++----- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index 1881f0a90..53331ee8f 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -574,9 +574,9 @@ komodod_LDADD += \ $(LIBZCASH_LIBS) if TARGET_DARWIN -komodod_LDADD += libcc.dylib -lncurses +komodod_LDADD += libcc.dylib # -lncurses else -komodod_LDADD += libcc.so -lncurses +komodod_LDADD += libcc.so # -lncurses endif diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 25b279f61..3ad5766a9 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -120,9 +120,9 @@ std::string Rogue_pname = ""; */ // todo: -// verify keystrokes tx is in mempool and confirmed -// chaining when mempool tx sometimes infinite loops? -// bailout stealing, is it possible? +// add some more conditions to multiplayer +// change rogue_extract to subfunction without JSON to be used by other functions +// how does it work with playertxid instead of pubkey //////////////////////// start of CClib interface //./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey=03951a6f7967ad784453116bc55cd30c54f91ea8a5b1e9b04d6b29cfd6b395ba6c -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc > /dev/null & @@ -812,8 +812,6 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"couldnt reparse params")); } -// change to subfunction without JSON to be used by other functions - UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result; CPubKey pk,roguepk; int32_t i,n,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char rogueaddr[64],fname[64],str[512],*pubstr,*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000],pub33[33]; From d41134cb97a1e00d0b81586eda74df5f8a0f7836 Mon Sep 17 00:00:00 2001 From: dimxy Date: Mon, 18 Feb 2019 00:03:48 +0500 Subject: [PATCH 0703/1145] token marker moved to vout tokeninfo validates vouts --- src/cc/CCtokens.cpp | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/cc/CCtokens.cpp b/src/cc/CCtokens.cpp index e5b9eeb78..d5fffdf5b 100644 --- a/src/cc/CCtokens.cpp +++ b/src/cc/CCtokens.cpp @@ -907,10 +907,12 @@ std::string CreateToken(int64_t txfee, int64_t tokensupply, std::string name, st if( nonfungibleData.size() > 0 ) destEvalCode = nonfungibleData.begin()[0]; + // NOTE: we should prevent spending fake-tokens from this marker in IsTokenvout(): + mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cp, NULL))); // new marker to token cc addr, burnable and validated, vout pos now changed to 0 (from 1) mtx.vout.push_back(MakeTokensCC1vout(destEvalCode, tokensupply, mypk)); //mtx.vout.push_back(CTxOut(txfee, CScript() << ParseHex(cp->CChexstr) << OP_CHECKSIG)); // old marker (non-burnable because spending could not be validated) - // NOTE: we should prevent spending fake-tokens from this marker in IsTokenvout(): - mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cp, NULL))); // new marker to token cc addr, burnable and validated, this vout must be=1 + //mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cp, NULL))); // ...moved to vout=0 for matching with rogue-game token + return(FinalizeCCTx(0, cp, mtx, mypk, txfee, EncodeTokenCreateOpRet('c', Mypubkey(), name, description, nonfungibleData))); } @@ -1007,8 +1009,11 @@ UniValue TokenInfo(uint256 tokenid) std::vector origpubkey; std::vector vopretNonfungible; std::string name, description; + struct CCcontract_info *cpTokens, tokensCCinfo; - if (GetTransaction(tokenid, vintx, hashBlock, false) == 0) + cpTokens = CCinit(&tokensCCinfo, EVAL_TOKENS); + + if( !GetTransaction(tokenid, vintx, hashBlock, false) ) { fprintf(stderr, "TokenInfo() cant find tokenid\n"); result.push_back(Pair("result", "error")); @@ -1020,17 +1025,23 @@ UniValue TokenInfo(uint256 tokenid) LOGSTREAM((char *)"cctokens", CCLOG_INFO, stream << "TokenInfo() passed tokenid isnt token creation txid" << std::endl); result.push_back(Pair("result", "error")); result.push_back(Pair("error", "tokenid isnt token creation txid")); + return result; } result.push_back(Pair("result", "success")); result.push_back(Pair("tokenid", tokenid.GetHex())); result.push_back(Pair("owner", HexStr(origpubkey))); result.push_back(Pair("name", name)); - result.push_back(Pair("supply", vintx.vout[0].nValue)); + + int64_t supply = 0, output; + for (int v = 0; v < vintx.vout.size() - 1; v++) + if ((output = IsTokensvout(false, true, cpTokens, NULL, vintx, v, tokenid)) > 0) + supply += output; + result.push_back(Pair("supply", supply)); result.push_back(Pair("description", description)); if( !vopretNonfungible.empty() ) result.push_back(Pair("data", HexStr(vopretNonfungible))); - return(result); + return result; } UniValue TokenList() From 2fc487d21339eeb8ba17a3022893bcffab06986e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 08:10:40 -1100 Subject: [PATCH 0704/1145] Fix undefined --- src/cc/rogue/cursesd.c | 2 +- src/cc/rogue/mdport.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index c9785c0d1..02a80c470 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -16,7 +16,7 @@ #include "cursesd.h" static int32_t endwinflag; -WINDOW *stdscr; +WINDOW *stdscr,*curscr; int32_t ESCDELAY; WINDOW *newwin(int32_t nlines,int32_t ncols,int32_t begin_y,int32_t begin_x) diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index 841dffbb8..d72c4097a 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -263,12 +263,12 @@ int md_hasclreol() { #if defined(clr_eol) -#ifdef NCURSES_VERSION +/*#ifdef NCURSES_VERSION if (cur_term == NULL) return(0); //if (cur_term->type.Strings == NULL) return(0); -#endif +#endif*/ return((clr_eol != NULL) && (*clr_eol != 0)); #elif defined(__PDCURSES__) return(TRUE); From 54c7943a38b43b37acd2f7fafa2a33a58a47d99c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 08:16:52 -1100 Subject: [PATCH 0705/1145] Return 0 --- src/cc/rogue/mdport.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index d72c4097a..9d6c7d2c6 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -262,19 +262,20 @@ md_onsignal_autosave() int md_hasclreol() { -#if defined(clr_eol) -/*#ifdef NCURSES_VERSION +/*#if defined(clr_eol) +#ifdef NCURSES_VERSION if (cur_term == NULL) return(0); //if (cur_term->type.Strings == NULL) return(0); -#endif*/ +#endif return((clr_eol != NULL) && (*clr_eol != 0)); #elif defined(__PDCURSES__) return(TRUE); #else return((CE != NULL) && (*CE != 0)); -#endif +#endif*/ + return(0); } void From f641b7c31d6603e597d8c3217d1b383ea3fb3edc Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 08:56:48 -1100 Subject: [PATCH 0706/1145] Guard null name --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3ad5766a9..309602c2c 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -389,7 +389,7 @@ UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint obj.push_back(Pair("experience",(int64_t)P.experience)); obj.push_back(Pair("dungeonlevel",(int64_t)P.dungeonlevel)); obj.push_back(Pair("chain",symbol)); - obj.push_back(Pair("pname",pname)); + obj.push_back(Pair("pname",pname.size() > 0 ? pname : "noname")); return(obj); } From 9fda3717842d971cbf444e2fa3114449da7c9869 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 09:00:14 -1100 Subject: [PATCH 0707/1145] Test --- src/cc/rogue_rpc.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 309602c2c..c9d873656 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -388,8 +388,10 @@ UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint obj.push_back(Pair("level",(int64_t)P.level)); obj.push_back(Pair("experience",(int64_t)P.experience)); obj.push_back(Pair("dungeonlevel",(int64_t)P.dungeonlevel)); - obj.push_back(Pair("chain",symbol)); - obj.push_back(Pair("pname",pname.size() > 0 ? pname : "noname")); + if ( symbol.c_str() != 0 ) + obj.push_back(Pair("chain",symbol.c_str())); + if ( pname.c_str() != 0 ) + obj.push_back(Pair("pname",pname._cstr())); return(obj); } From 5fd1874cb363d14383c88d4ad3a4af2568857590 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 09:00:51 -1100 Subject: [PATCH 0708/1145] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c9d873656..1db0d51f1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -391,7 +391,7 @@ UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint if ( symbol.c_str() != 0 ) obj.push_back(Pair("chain",symbol.c_str())); if ( pname.c_str() != 0 ) - obj.push_back(Pair("pname",pname._cstr())); + obj.push_back(Pair("pname",pname.c_str())); return(obj); } From 73fa543afa9495de92b250655def5c3613620134 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 09:04:16 -1100 Subject: [PATCH 0709/1145] Test --- src/cc/rogue_rpc.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1db0d51f1..41e40edb4 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -357,7 +357,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint256 tokenid,std::string symbol,std::string pname) { - int32_t i; struct rogue_player P; char packitemstr[512],*datastr; UniValue obj(UniValue::VOBJ),a(UniValue::VARR); + int32_t i; struct rogue_player P; char packitemstr[512],*datastr=0; UniValue obj(UniValue::VOBJ),a(UniValue::VARR); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -379,8 +379,11 @@ UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint if ( tokenid != zeroid ) obj.push_back(Pair("tokenid",tokenid.GetHex())); else obj.push_back(Pair("tokenid",playertxid.GetHex())); - obj.push_back(Pair("data",datastr)); - free(datastr); + if ( datastr != 0 ) + { + obj.push_back(Pair("data",datastr)); + free(datastr); + } obj.push_back(Pair("pack",a)); obj.push_back(Pair("packsize",(int64_t)P.packsize)); obj.push_back(Pair("hitpoints",(int64_t)P.hitpoints)); @@ -388,10 +391,8 @@ UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint obj.push_back(Pair("level",(int64_t)P.level)); obj.push_back(Pair("experience",(int64_t)P.experience)); obj.push_back(Pair("dungeonlevel",(int64_t)P.dungeonlevel)); - if ( symbol.c_str() != 0 ) - obj.push_back(Pair("chain",symbol.c_str())); - if ( pname.c_str() != 0 ) - obj.push_back(Pair("pname",pname.c_str())); + obj.push_back(Pair("chain",symbol)); + obj.push_back(Pair("pname",pname)); return(obj); } From 88fa8f223315f802c93cdf0025a09ad95d5204d9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 09:09:52 -1100 Subject: [PATCH 0710/1145] Test --- src/cc/rogue_rpc.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 41e40edb4..1e6d3111d 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -798,8 +798,11 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param GetCCaddress1of2(cp,destaddr,roguepk,mypk); if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid) == 0 ) { + result.push_back(Pair("gametxid",gametxid.GetHex())); if ( rogue_findbaton(cp,playertxid,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr,numplayers,symbol,pname) == 0 ) { + result.push_back(Pair("batontxid",batontxid.GetHex())); + result.push_back(Pair("playertxid",playertxid.GetHex())); if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) { mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); From 8a9687d2550cd1f46bb707fd2f23683a8a9ca0e6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 09:12:08 -1100 Subject: [PATCH 0711/1145] Dont keystrokes tx more than once per 1024 --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 2fd50607a..01c8b1873 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -602,7 +602,7 @@ playit(struct rogue_state *rs) } else { - if ( rs->needflush != 0 )//&& rs->num > 4096 ) + if ( rs->needflush != 0 && rs->num > 1024 ) { if ( flushkeystrokes(rs) == 0 ) rs->needflush = 0; From 5391c8ca87f3c5ff564c58ef31ec210fbdb383e3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 09:28:54 -1100 Subject: [PATCH 0712/1145] Keystrokesstr --- src/cc/rogue_rpc.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1e6d3111d..4fec21b5a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -123,6 +123,7 @@ std::string Rogue_pname = ""; // add some more conditions to multiplayer // change rogue_extract to subfunction without JSON to be used by other functions // how does it work with playertxid instead of pubkey +// keystrokes retry //////////////////////// start of CClib interface //./komodod -ac_name=ROGUE -ac_supply=1000000 -pubkey=03951a6f7967ad784453116bc55cd30c54f91ea8a5b1e9b04d6b29cfd6b395ba6c -addnode=5.9.102.210 -ac_cclib=rogue -ac_perc=10000000 -ac_reward=100000000 -ac_cc=60001 -ac_script=2ea22c80203d1579313abe7d8ea85f48c65ea66fc512c878c0d0e6f6d54036669de940febf8103120c008203000401cc > /dev/null & @@ -792,13 +793,14 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( (params= cclib_reparse(&n,params)) != 0 && n == 2 && (keystrokestr= jstr(jitem(params,1),0)) != 0 ) { gametxid = juint256(jitem(params,0)); + result.push_back(Pair("gametxid",gametxid.GetHex())); + result.push_back(Pair("keystrokes",keystrokestr)); keystrokes = ParseHex(keystrokestr); mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,destaddr,roguepk,mypk); if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid) == 0 ) { - result.push_back(Pair("gametxid",gametxid.GetHex())); if ( rogue_findbaton(cp,playertxid,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr,numplayers,symbol,pname) == 0 ) { result.push_back(Pair("batontxid",batontxid.GetHex())); From 5325bf6507ff34928a83193b128e26e4a33223e5 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 00:05:24 +0100 Subject: [PATCH 0713/1145] add Makefile for rogue multiOS supported Makefile --- src/cc/Makefile_rogue | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/cc/Makefile_rogue diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue new file mode 100644 index 000000000..7fb3f799f --- /dev/null +++ b/src/cc/Makefile_rogue @@ -0,0 +1,37 @@ +SHELL = /bin/sh +CC = gcc +CC_DARWIN = g++-6 +CC_WIN = x86_64-w64-mingw32-gcc-posix +CFLAGS_DARWIN = -DBUILD_ROGUE -std=c++11 -arch x86_64 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -Wl,-undefined -Wl,dynamic_lookup -Wno-write-strings -shared -dynamiclib +CFLAGS = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared +CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared +DEBUGFLAGS = -O0 -D _DEBUG +RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program +$(info $(OS)) +OS := $(shell uname -s) +$(info $(OS)) +TARGET = librogue.so +TARGET_DARWIN = librogue.dylib +TARGET_WIN = librogue.dll +SOURCES = cclib.cpp +#HEADERS = $(shell echo ../cryptoconditions/include/*.h) -I/usr/local/Cellar/gcc\@6/6.4.0_2/include/c++/6.4.0/ + +all: $(TARGET) + +$(TARGET): $(SOURCES) + $(info Building cclib to src/) +ifeq ($(OS),Darwin) + $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET_DARWIN) -c $(SOURCES) -lncurses + cp $(TARGET_DARWIN) ../libcc.dylib +else ifeq ($(OS),Linux) + $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) -lncurses + cp $(TARGET) ../libcc.so +#else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host +else + $(info WINDOWS) + $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses + cp $(TARGET_WIN) ../libcc.dll +endif + +clean: + rm -rf $(TARGET) From 9eb16504de6a35e5a31792954cb266bf96d37912 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 00:08:03 +0100 Subject: [PATCH 0714/1145] update makerogue --- src/cc/makerogue | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 249e646f5..3b47638e9 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,8 +1,5 @@ #!/bin/sh cd rogue; -./configure # only need this first time +./configure make; cd .. -gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -#gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so -cp librogue.so ../libcc.so - +make -f Makefile_rogue From c5b8640d9dde49a4b5b7706c545c1afb4eebb7ce Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 00:15:35 +0100 Subject: [PATCH 0715/1145] update OSX makefile --- zcutil/build-mac.sh | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/zcutil/build-mac.sh b/zcutil/build-mac.sh index a3619111f..df4efd05f 100755 --- a/zcutil/build-mac.sh +++ b/zcutil/build-mac.sh @@ -47,14 +47,7 @@ make "$@" -C ./depends/ V=1 NO_QT=1 NO_PROTON=1 WD=$PWD cd src/cc echo $PWD - -if make "$@"; then - echo CCLIB BUILD SUCCESSFUL -else - echo CCLIB BUILD FAILED - exit 1 -fi - +./makerogue cd $WD ./autogen.sh From cfa13caa4c1fe9cddc3c1b267d19e69da37257c1 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 00:16:20 +0100 Subject: [PATCH 0716/1145] update makerogue --- src/cc/makerogue | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 3b47638e9..a38eab6a4 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -2,4 +2,10 @@ cd rogue; ./configure make; cd .. -make -f Makefile_rogue + +if make -f Makefile_rogue "$@"; then + echo ROGUE BUILD SUCCESSFUL +else + echo ROGUE BUILD FAILED + exit 1 +fi From 6de80465b5dea552ac478a9162db961774d7726d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:06:22 -1100 Subject: [PATCH 0717/1145] Extract game function --- src/cc/rogue_rpc.cpp | 116 ++++++++++++++++++++++++------------------- 1 file changed, 66 insertions(+), 50 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 4fec21b5a..54aad1326 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -121,7 +121,6 @@ std::string Rogue_pname = ""; // todo: // add some more conditions to multiplayer -// change rogue_extract to subfunction without JSON to be used by other functions // how does it work with playertxid instead of pubkey // keystrokes retry @@ -820,12 +819,67 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"couldnt reparse params")); } +char *rogue_extractgame(char *str,int32_t *numkeysp,struct rogue_player &P,std::vector &newdata,struct rogue_player &endP,int64_t &seed,struct CCcontract_info *cp,uint256 gametxid,char *rogueaddr) +{ + CPubKey roguepk; int32_t i,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; int64_t buyin,batonvalue; char fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid; FILE *fp; uint8_t newplayer[10000]; + roguepk = GetUnspendable(cp,0); + *numkeysp = 0; + seed = 0; + if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) + { + if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,rogueaddr,numplayers,symbol,pname) == 0 ) + { + UniValue obj; + seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); + fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + memset(&P,0,sizeof(P)); + if ( playerdata.size() > 0 ) + { + for (i=0; i no playerdata\n"); + newdata.resize(0); + } + sprintf(str,"extracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",endP.gold,endP.hitpoints,endP.strength,endP.level,endP.experience,endP.dungeonlevel,n,(int32_t)sizeof(endP)); + fprintf(stderr,"%s\n",str); + } else num = 0; + } + } + *numkeysp = numkeys; + return(keystrokes); +} + UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result; CPubKey pk,roguepk; int32_t i,n,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue; char rogueaddr[64],fname[64],str[512],*pubstr,*keystrokes = 0; std::vector playerdata,newdata; uint256 batontxid,playertxid,gametxid; FILE *fp; uint8_t player[10000],pub33[33]; + UniValue result; CPubKey pk,roguepk; int32_t i,n,numkeys,flag = 0; uint64_t seed; char str[512],rogueaddr[64],*pubstr,*keystrokes = 0; std::vector newdata; uint256 gametxid; FILE *fp; uint8_t player[10000],pub33[33]; pk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); - result.push_back(Pair("status","success")); result.push_back(Pair("name","rogue")); result.push_back(Pair("method","extract")); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -845,57 +899,19 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } GetCCaddress1of2(cp,rogueaddr,roguepk,pk); result.push_back(Pair("rogueaddr",rogueaddr)); - if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) + if ( (keystrokes= rogue_extractgame(str,&numkeys,P,newdata,endP,seed,cp,gametxid,rogueaddr)) != 0 ) { - if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,rogueaddr,numplayers,symbol,pname) == 0 ) - { - UniValue obj; struct rogue_player P; - seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); - fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); - memset(&P,0,sizeof(P)); - if ( playerdata.size() > 0 ) - { - for (i=0; i no playerdata\n"); - newdata.resize(0); - } - sprintf(str,"extracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); - result.push_back(Pair("extracted",str)); - fprintf(stderr,"%s\n",str); - if ( keystrokes != 0 ) - free(keystrokes); - } else num = 0; - } + result.push_back(Pair("status","success")); + flag = 1; + result.push_back(Pair("extracted",str)); + result.push_back(Pair("numkeys",(int64_t)numkeys)); + result.push_back(Pair("seed",(int64_t)seed)); + free(keystrokes); } } } + if ( flag == 0 ) + result.push_back(Pair("status","error")); return(result); } From e06149dc5617971911651a796de137de3423ad22 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:08:12 -1100 Subject: [PATCH 0718/1145] Syntax --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 54aad1326..b8a816158 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -866,7 +866,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,struct rogue_player &P,std:: fprintf(stderr,"zero value character was killed -> no playerdata\n"); newdata.resize(0); } - sprintf(str,"extracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",endP.gold,endP.hitpoints,endP.strength,endP.level,endP.experience,endP.dungeonlevel,n,(int32_t)sizeof(endP)); + sprintf(str,"extracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength,endP.level,endP.experience,endP.dungeonlevel); fprintf(stderr,"%s\n",str); } else num = 0; } @@ -877,7 +877,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,struct rogue_player &P,std:: UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result; CPubKey pk,roguepk; int32_t i,n,numkeys,flag = 0; uint64_t seed; char str[512],rogueaddr[64],*pubstr,*keystrokes = 0; std::vector newdata; uint256 gametxid; FILE *fp; uint8_t player[10000],pub33[33]; + UniValue result; CPubKey pk,roguepk; int32_t i,n,numkeys,flag = 0; uint64_t seed; char str[512],rogueaddr[64],*pubstr,*keystrokes = 0; std::vector newdata; uint256 gametxid; FILE *fp; uint8_t player[10000],pub33[33]; struct rogue_player P,endP; pk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); result.push_back(Pair("name","rogue")); From 51e251ff220885c51c1a10536f9b56faf219bca3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:09:15 -1100 Subject: [PATCH 0719/1145] uint64_t seed --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b8a816158..087567df5 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -819,7 +819,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"couldnt reparse params")); } -char *rogue_extractgame(char *str,int32_t *numkeysp,struct rogue_player &P,std::vector &newdata,struct rogue_player &endP,int64_t &seed,struct CCcontract_info *cp,uint256 gametxid,char *rogueaddr) +char *rogue_extractgame(char *str,int32_t *numkeysp,struct rogue_player &P,std::vector &newdata,struct rogue_player &endP,uint64_t &seed,struct CCcontract_info *cp,uint256 gametxid,char *rogueaddr) { CPubKey roguepk; int32_t i,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; int64_t buyin,batonvalue; char fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid; FILE *fp; uint8_t newplayer[10000]; roguepk = GetUnspendable(cp,0); From 274bbfb0c8e8fa9e4e36ca139ac3b2f7164442e2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:12:42 -1100 Subject: [PATCH 0720/1145] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 087567df5..144692404 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -899,7 +899,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } GetCCaddress1of2(cp,rogueaddr,roguepk,pk); result.push_back(Pair("rogueaddr",rogueaddr)); - if ( (keystrokes= rogue_extractgame(str,&numkeys,P,newdata,endP,seed,cp,gametxid,rogueaddr)) != 0 ) + if ( 0 && (keystrokes= rogue_extractgame(str,&numkeys,P,newdata,endP,seed,cp,gametxid,rogueaddr)) != 0 ) { result.push_back(Pair("status","success")); flag = 1; From 99ea9f366ea5e7e90344376fa119148bc814163d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:14:29 -1100 Subject: [PATCH 0721/1145] Huh? --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 144692404..1a364dd53 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -877,12 +877,12 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,struct rogue_player &P,std:: UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result; CPubKey pk,roguepk; int32_t i,n,numkeys,flag = 0; uint64_t seed; char str[512],rogueaddr[64],*pubstr,*keystrokes = 0; std::vector newdata; uint256 gametxid; FILE *fp; uint8_t player[10000],pub33[33]; struct rogue_player P,endP; + UniValue result; CPubKey pk,roguepk; int32_t i,n,numkeys,flag = 0; uint64_t seed; char str[512],rogueaddr[64],*pubstr,*keystrokes = 0; std::vector newdata; uint256 gametxid; FILE *fp; uint8_t pub33[33]; struct rogue_player P,endP; pk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); result.push_back(Pair("name","rogue")); result.push_back(Pair("method","extract")); - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( 0 && (params= cclib_reparse(&n,params)) != 0 ) { if ( n > 0 ) { From 35110a993c489477b6a2ae148c08bb8f8b18d52c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:18:06 -1100 Subject: [PATCH 0722/1145] Test --- src/cc/rogue_rpc.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1a364dd53..eb13d0a41 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -819,9 +819,9 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"couldnt reparse params")); } -char *rogue_extractgame(char *str,int32_t *numkeysp,struct rogue_player &P,std::vector &newdata,struct rogue_player &endP,uint64_t &seed,struct CCcontract_info *cp,uint256 gametxid,char *rogueaddr) +char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdata,uint64_t &seed,struct CCcontract_info *cp,uint256 gametxid,char *rogueaddr) { - CPubKey roguepk; int32_t i,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; int64_t buyin,batonvalue; char fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid; FILE *fp; uint8_t newplayer[10000]; + CPubKey roguepk; int32_t i,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; int64_t buyin,batonvalue; char fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid; FILE *fp; uint8_t newplayer[10000]; struct rogue_player P,endP; roguepk = GetUnspendable(cp,0); *numkeysp = 0; seed = 0; @@ -877,11 +877,12 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,struct rogue_player &P,std:: UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result; CPubKey pk,roguepk; int32_t i,n,numkeys,flag = 0; uint64_t seed; char str[512],rogueaddr[64],*pubstr,*keystrokes = 0; std::vector newdata; uint256 gametxid; FILE *fp; uint8_t pub33[33]; struct rogue_player P,endP; + UniValue result; CPubKey pk,roguepk; int32_t i,n,numkeys,flag = 0; uint64_t seed; char str[512],rogueaddr[64],*pubstr,*keystrokes = 0; std::vector newdata; uint256 gametxid; FILE *fp; uint8_t pub33[33]; pk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); result.push_back(Pair("name","rogue")); result.push_back(Pair("method","extract")); + fprintf(stderr,"inside rogue extract\n"); if ( 0 && (params= cclib_reparse(&n,params)) != 0 ) { if ( n > 0 ) @@ -899,7 +900,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } GetCCaddress1of2(cp,rogueaddr,roguepk,pk); result.push_back(Pair("rogueaddr",rogueaddr)); - if ( 0 && (keystrokes= rogue_extractgame(str,&numkeys,P,newdata,endP,seed,cp,gametxid,rogueaddr)) != 0 ) + if ( 0 && (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,cp,gametxid,rogueaddr)) != 0 ) { result.push_back(Pair("status","success")); flag = 1; From 93f7c80bce2128f546a5320ac055b37c2c437e21 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:20:03 -1100 Subject: [PATCH 0723/1145] Test --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index eb13d0a41..5f7fb233f 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -883,7 +883,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("name","rogue")); result.push_back(Pair("method","extract")); fprintf(stderr,"inside rogue extract\n"); - if ( 0 && (params= cclib_reparse(&n,params)) != 0 ) + /* if ( 0 && (params= cclib_reparse(&n,params)) != 0 ) { if ( n > 0 ) { @@ -910,7 +910,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) free(keystrokes); } } - } + }*/ if ( flag == 0 ) result.push_back(Pair("status","error")); return(result); From 0ad53817bf541f2e3f2db081d4ac5bc75f035ec7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:22:29 -1100 Subject: [PATCH 0724/1145] Test --- src/cc/rogue_rpc.cpp | 45 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5f7fb233f..9c6ab7152 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -876,6 +876,45 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat } UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ),a(UniValue::VARR),b(UniValue::VARR); uint256 txid,hashBlock,gametxid,tokenid,playertxid; int32_t vout,maxplayers,gameheight,numvouts; CPubKey roguepk,mypk; char coinaddr[64]; CTransaction tx,gametx; int64_t buyin; + std::vector > addressIndex; + //std::vector > unspentOutputs; + roguepk = GetUnspendable(cp,0); + mypk = pubkey2pk(Mypubkey()); + GetCCaddress1of2(cp,coinaddr,roguepk,mypk); + //SetCCunspents(unspentOutputs,coinaddr); + SetCCtxids(addressIndex,coinaddr); + rogue_univalue(result,"extract",-1,-1); + for (std::vector >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) + //for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) + { + txid = it->first.txhash; + vout = (int32_t)it->first.index; + //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); + if ( vout == 0 ) + { + if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + { + if ( rogue_registeropretdecode(gametxid,tokenid,playertxid,tx.vout[numvouts-1].scriptPubKey) == 'R' ) + { + if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) + { + if ( CCgettxout(txid,vout,1) < 0 ) + b.push_back(gametxid.GetHex()); + else a.push_back(gametxid.GetHex()); + } + } + } + } + } + result.push_back(Pair("pastgames",b)); + result.push_back(Pair("games",a)); + result.push_back(Pair("numgames",(int64_t)(a.size()+b.size()))); + return(result); +} + +UniValue realrogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result; CPubKey pk,roguepk; int32_t i,n,numkeys,flag = 0; uint64_t seed; char str[512],rogueaddr[64],*pubstr,*keystrokes = 0; std::vector newdata; uint256 gametxid; FILE *fp; uint8_t pub33[33]; pk = pubkey2pk(Mypubkey()); @@ -883,7 +922,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("name","rogue")); result.push_back(Pair("method","extract")); fprintf(stderr,"inside rogue extract\n"); - /* if ( 0 && (params= cclib_reparse(&n,params)) != 0 ) + if ( (params= cclib_reparse(&n,params)) != 0 ) { if ( n > 0 ) { @@ -900,7 +939,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } GetCCaddress1of2(cp,rogueaddr,roguepk,pk); result.push_back(Pair("rogueaddr",rogueaddr)); - if ( 0 && (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,cp,gametxid,rogueaddr)) != 0 ) + if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,cp,gametxid,rogueaddr)) != 0 ) { result.push_back(Pair("status","success")); flag = 1; @@ -910,7 +949,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) free(keystrokes); } } - }*/ + } if ( flag == 0 ) result.push_back(Pair("status","error")); return(result); From 7572af1ac9e250c8e89bee702ae7e2c5dcef1165 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:24:45 -1100 Subject: [PATCH 0725/1145] (UniValue::VOBJ) --- src/cc/rogue_rpc.cpp | 42 +----------------------------------------- 1 file changed, 1 insertion(+), 41 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9c6ab7152..6101eead4 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -877,51 +877,11 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR),b(UniValue::VARR); uint256 txid,hashBlock,gametxid,tokenid,playertxid; int32_t vout,maxplayers,gameheight,numvouts; CPubKey roguepk,mypk; char coinaddr[64]; CTransaction tx,gametx; int64_t buyin; - std::vector > addressIndex; - //std::vector > unspentOutputs; - roguepk = GetUnspendable(cp,0); - mypk = pubkey2pk(Mypubkey()); - GetCCaddress1of2(cp,coinaddr,roguepk,mypk); - //SetCCunspents(unspentOutputs,coinaddr); - SetCCtxids(addressIndex,coinaddr); - rogue_univalue(result,"extract",-1,-1); - for (std::vector >::const_iterator it=addressIndex.begin(); it!=addressIndex.end(); it++) - //for (std::vector >::const_iterator it=unspentOutputs.begin(); it!=unspentOutputs.end(); it++) - { - txid = it->first.txhash; - vout = (int32_t)it->first.index; - //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); - if ( vout == 0 ) - { - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) - { - if ( rogue_registeropretdecode(gametxid,tokenid,playertxid,tx.vout[numvouts-1].scriptPubKey) == 'R' ) - { - if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) - { - if ( CCgettxout(txid,vout,1) < 0 ) - b.push_back(gametxid.GetHex()); - else a.push_back(gametxid.GetHex()); - } - } - } - } - } - result.push_back(Pair("pastgames",b)); - result.push_back(Pair("games",a)); - result.push_back(Pair("numgames",(int64_t)(a.size()+b.size()))); - return(result); -} - -UniValue realrogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result; CPubKey pk,roguepk; int32_t i,n,numkeys,flag = 0; uint64_t seed; char str[512],rogueaddr[64],*pubstr,*keystrokes = 0; std::vector newdata; uint256 gametxid; FILE *fp; uint8_t pub33[33]; + UniValue result(UniValue::VOBJ); CPubKey pk,roguepk; int32_t i,n,numkeys,flag = 0; uint64_t seed; char str[512],rogueaddr[64],*pubstr,*keystrokes = 0; std::vector newdata; uint256 gametxid; FILE *fp; uint8_t pub33[33]; pk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); result.push_back(Pair("name","rogue")); result.push_back(Pair("method","extract")); - fprintf(stderr,"inside rogue extract\n"); if ( (params= cclib_reparse(&n,params)) != 0 ) { if ( n > 0 ) From ca219e38ad00ea27912b998aff294b698c6042b0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:26:46 -1100 Subject: [PATCH 0726/1145] Test --- src/cc/rogue_rpc.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 6101eead4..240d74752 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -899,6 +899,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } GetCCaddress1of2(cp,rogueaddr,roguepk,pk); result.push_back(Pair("rogueaddr",rogueaddr)); + return(result); if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,cp,gametxid,rogueaddr)) != 0 ) { result.push_back(Pair("status","success")); From 98947db212f7fd17b59a5651d87dbc7361fa31e4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:28:34 -1100 Subject: [PATCH 0727/1145] Test --- src/cc/rogue_rpc.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 240d74752..8f39b3d5e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -899,14 +899,14 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } GetCCaddress1of2(cp,rogueaddr,roguepk,pk); result.push_back(Pair("rogueaddr",rogueaddr)); - return(result); + str[0] = 0; if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,cp,gametxid,rogueaddr)) != 0 ) { result.push_back(Pair("status","success")); flag = 1; result.push_back(Pair("extracted",str)); - result.push_back(Pair("numkeys",(int64_t)numkeys)); - result.push_back(Pair("seed",(int64_t)seed)); + //result.push_back(Pair("numkeys",(int64_t)numkeys)); + //result.push_back(Pair("seed",(int64_t)seed)); free(keystrokes); } } From 0a849f55b90626ffd9c3f376c3b961f4966e9bf0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:31:06 -1100 Subject: [PATCH 0728/1145] Test --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 8f39b3d5e..5fa964407 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -905,8 +905,8 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("status","success")); flag = 1; result.push_back(Pair("extracted",str)); - //result.push_back(Pair("numkeys",(int64_t)numkeys)); - //result.push_back(Pair("seed",(int64_t)seed)); + result.push_back(Pair("numkeys",(int64_t)numkeys)); + result.push_back(Pair("seed",(int64_t)seed)); free(keystrokes); } } From afc2c11591636aed86a9c3ab396b6f19a8a59592 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:39:10 -1100 Subject: [PATCH 0729/1145] Slseepmillis --- src/cc/cclib.cpp | 2 +- src/cc/rogue/main.c | 2 +- src/cc/rogue/rogue.c | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 77f6a21ac..f2f13837c 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -76,7 +76,7 @@ CClib_methods[] = std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *params); #ifdef BUILD_ROGUE -int32_t rogue_replay(uint64_t seed,int32_t sleeptime); +int32_t rogue_replay(uint64_t seed,int32_t sleepmillis); bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 12e6af368..c0fa36752 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -253,7 +253,7 @@ int main(int argc, char **argv, char **envp) { seed = atol(argv[1]); //fprintf(stderr,"replay %llu\n",(long long)seed); - return(rogue_replay(seed,50000)); + return(rogue_replay(seed,10)); } else { diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 01c8b1873..516100906 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -337,7 +337,7 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) } fclose(fp); } - rogue_replay2(0,seed,keystrokes,num,player,30); + rogue_replay2(0,seed,keystrokes,num,player,sleeptime); //mvaddstr(LINES - 2, 0, (char *)"replay completed"); endwin(); From 02794ea8641936484dd4df859524ba6886939d4b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:39:51 -1100 Subject: [PATCH 0730/1145] Replay --- src/cc/rogue_rpc.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5fa964407..318567383 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -907,6 +907,8 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("extracted",str)); result.push_back(Pair("numkeys",(int64_t)numkeys)); result.push_back(Pair("seed",(int64_t)seed)); + sprintf(str,"cc/rogue/rogue %llu",(long long)seed); + result.push_back(Pair("replay",str)); free(keystrokes); } } From 5793bef688561caa644d528e2830c88df4c149b9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:46:37 -1100 Subject: [PATCH 0731/1145] playertxid --- src/cc/rogue_rpc.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 318567383..93baaa44b 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -819,9 +819,9 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"couldnt reparse params")); } -char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdata,uint64_t &seed,struct CCcontract_info *cp,uint256 gametxid,char *rogueaddr) +char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdata,uint64_t &seed,uint256 &playertxid,struct CCcontract_info *cp,uint256 gametxid,char *rogueaddr) { - CPubKey roguepk; int32_t i,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; int64_t buyin,batonvalue; char fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid,playertxid; FILE *fp; uint8_t newplayer[10000]; struct rogue_player P,endP; + CPubKey roguepk; int32_t i,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; int64_t buyin,batonvalue; char fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid; FILE *fp; uint8_t newplayer[10000]; struct rogue_player P,endP; roguepk = GetUnspendable(cp,0); *numkeysp = 0; seed = 0; @@ -877,7 +877,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); CPubKey pk,roguepk; int32_t i,n,numkeys,flag = 0; uint64_t seed; char str[512],rogueaddr[64],*pubstr,*keystrokes = 0; std::vector newdata; uint256 gametxid; FILE *fp; uint8_t pub33[33]; + UniValue result(UniValue::VOBJ); CPubKey pk,roguepk; int32_t i,n,numkeys,flag = 0; uint64_t seed; char str[512],rogueaddr[64],*pubstr,*keystrokes = 0; std::vector newdata; uint256 gametxid,playertxid; FILE *fp; uint8_t pub33[33]; pk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); result.push_back(Pair("name","rogue")); @@ -900,10 +900,11 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) GetCCaddress1of2(cp,rogueaddr,roguepk,pk); result.push_back(Pair("rogueaddr",rogueaddr)); str[0] = 0; - if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,cp,gametxid,rogueaddr)) != 0 ) + if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) { result.push_back(Pair("status","success")); flag = 1; + result.push_back(Pair("playertxid",playertxid.GetHex())); result.push_back(Pair("extracted",str)); result.push_back(Pair("numkeys",(int64_t)numkeys)); result.push_back(Pair("seed",(int64_t)seed)); From 156e9057d088b127f10be4da2d99797840b017e9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:52:01 -1100 Subject: [PATCH 0732/1145] Require registration within ROGUE_MAXKEYSTROKESGAP --- src/cc/rogue_rpc.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 93baaa44b..de91eef19 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -726,6 +726,8 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( tokenid != zeroid ) // if it is tokentransfer this will be 0 vout = 1; } + if ( komodo_nextheight() > gameheight + ROGUE_MAXKEYSTROKESGAP ) + return(cclib_error(result,"didnt register in time, ROGUE_MAXKEYSTROKESGAP")); rogue_univalue(result,0,maxplayers,buyin); GetCCaddress1of2(cp,coinaddr,roguepk,mypk); if ( rogue_iamregistered(maxplayers,gametxid,tx,coinaddr) > 0 ) From 3549fd1c0fb49cc792dab85a847704b31fc48f31 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 20:53:53 -1100 Subject: [PATCH 0733/1145] Update pending valid filter --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index de91eef19..4a7ef705d 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1113,7 +1113,7 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( it->second.satoshis != txfee || vout != 0 ) // reject any that are not highlander markers continue; - if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,txid) == 0 && gameheight > nextheight-777 ) + if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,txid) == 0 && nextheight <= gameheight+ROGUE_MAXKEYSTROKESGAP ) { rogue_playersalive(numplayers,txid,maxplayers); if ( numplayers < maxplayers ) From 533c2e564dd06eb2c1203bc8807c5bd8d23b9bba Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 21:27:02 -1100 Subject: [PATCH 0734/1145] Exit from replay --- src/cc/rogue/rogue.c | 3 ++- src/cc/rogue_rpc.cpp | 43 ++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 516100906..d015be4a9 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -339,8 +339,9 @@ int32_t rogue_replay(uint64_t seed,int32_t sleeptime) } rogue_replay2(0,seed,keystrokes,num,player,sleeptime); - //mvaddstr(LINES - 2, 0, (char *)"replay completed"); + mvaddstr(LINES - 2, 0, (char *)"replay completed"); endwin(); + my_exit(0); } if ( keystrokes != 0 ) free(keystrokes); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 4a7ef705d..17d58a960 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -833,7 +833,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat { UniValue obj; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); - fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + //fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -897,7 +897,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) decode_hex(pub33,33,pubstr); pk = buf2pk(pub33); } - fprintf(stderr,"gametxid.%s %s\n",gametxid.GetHex().c_str(),pubstr); + //fprintf(stderr,"gametxid.%s %s\n",gametxid.GetHex().c_str(),pubstr); } GetCCaddress1of2(cp,rogueaddr,roguepk,pk); result.push_back(Pair("rogueaddr",rogueaddr)); @@ -1047,7 +1047,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } result.push_back(Pair("result","success")); } else fprintf(stderr,"illegal game err.%d\n",err); - } else fprintf(stderr,"n.%d\n",n); + } else fprintf(stderr,"parameters only n.%d\n",n); } return(result); } @@ -1217,6 +1217,43 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,ind,errflag,dispflag,score,numvouts; CTransaction vintx; uint256 hashBlock; + if ( (numvouts= tx.vout.size()) > 1 ) + { + scriptPubKey = tx.vout[numvouts-1].scriptPubKey; + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() > 2 ) + { + script = (uint8_t *)vopret.data(); + if ( script[0] == EVAL_ROGUE ) + { + switch ( script[1] ) + { + case 'G': // newgame + case 'R': // register + case 'K': // keystrokes + case 'H': // win + case 'Q': // bailout + return(true); + break; + default: + return eval->Invalid("illegal rogue funcid"); + break; + } + } + else if ( script[0] == EVAL_TOKENS ) + { + if ( script[1] == 'c' ) + { + + } + else + { + + } + } else return eval->Invalid("illegal evalcode"); + } else return eval->Invalid("opret too small"); + } else return eval->Invalid("not enough vouts"); return(true); } From 444a5de9bc9156dd9666bd5d303657e0f4005613 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 21:30:29 -1100 Subject: [PATCH 0735/1145] -print --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index d015be4a9..337592f86 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -743,7 +743,7 @@ my_exit(int st) { uint32_t counter; resetltchars(); - if ( globalR.guiflag != 0 ) + if ( globalR.guiflag != 0 || globalR.sleeptime != 0 ) exit(st); else if ( counter++ < 10 ) { From 9ecce2eb73035ce4bd640c5ffe2b78ff079998c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 21:43:20 -1100 Subject: [PATCH 0736/1145] Preserve both player strength and max strength --- src/cc/rogue/init.c | 7 ++++++- src/cc/rogue/rogue.c | 2 +- src/cc/rogue/state.c | 6 +++--- src/cc/rogue_rpc.cpp | 11 ++++++----- 4 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index f296d6182..6ff0a71c0 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -27,7 +27,12 @@ void restore_player(struct rogue_state *rs) int32_t i; THING *obj; //rs->P.gold = purse; max_hp = rs->P.hitpoints; - pstats.s_str = max_stats.s_str = rs->P.strength; + pstats.s_str = rs->P.strength & 0xffff; + max_stats.s_str = rs->P.strength >> 16; + if ( max_stats.s_str < 12 ) + max_stats.s_str = 12; + if ( pstats.s_str > max_stats.s_str ) + pstats.s_str = max_stats.s_str; pstats.s_lvl = rs->P.level; pstats.s_exp = rs->P.experience; for (i=0; iP.packsize; i++) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 337592f86..72fe07558 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -273,7 +273,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu if ( (fp= fopen("checkfile","wb")) != 0 ) { save_file(rs,fp,0); - fprintf(stderr,"gold.%d hp.%d strength.%d level.%d exp.%d dungeon.%d data[%d]\n",rs->P.gold,rs->P.hitpoints,rs->P.strength,rs->P.level,rs->P.experience,rs->P.dungeonlevel,rs->playersize); + fprintf(stderr,"gold.%d hp.%d strength.%d/%d level.%d exp.%d dungeon.%d data[%d]\n",rs->P.gold,rs->P.hitpoints,rs->P.strength&0xffff,rs->P.strength>>16,rs->P.level,rs->P.experience,rs->P.dungeonlevel,rs->playersize); if ( newdata != 0 && rs->playersize > 0 ) memcpy(newdata,rs->playerdata,rs->playersize); } diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 800622444..778540b68 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1437,7 +1437,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) //fprintf(stderr,"KILLED\n"); rs->P.gold = -1; rs->P.hitpoints = -1; - rs->P.strength = -1; + rs->P.strength = 0; rs->P.level = -1; rs->P.experience = -1; rs->P.dungeonlevel = -1; @@ -1448,11 +1448,11 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) { rs->P.gold = purse; rs->P.hitpoints = max_hp; - rs->P.strength = pstats.s_str; //max_stats.s_str; + rs->P.strength = (pstats.s_str & 0xffff) | (max_stats.s_str << 16); rs->P.level = pstats.s_lvl; rs->P.experience = pstats.s_exp; rs->P.dungeonlevel = level; - //fprintf(stderr,"%ld gold.%d hp.%d strength.%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,pstats.s_str,pstats.s_lvl,pstats.s_exp,level); + //fprintf(stderr,"%ld gold.%d hp.%d strength.%d/%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,pstats.s_str,max_stats.s_str,pstats.s_lvl,pstats.s_exp,level); } //fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); if ( rs->P.packsize < MAXPACK && o->o_type != AMULET ) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 17d58a960..b79d653d5 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -387,7 +387,8 @@ UniValue rogue_playerobj(std::vector playerdata,uint256 playertxid,uint obj.push_back(Pair("pack",a)); obj.push_back(Pair("packsize",(int64_t)P.packsize)); obj.push_back(Pair("hitpoints",(int64_t)P.hitpoints)); - obj.push_back(Pair("strength",(int64_t)P.strength)); + obj.push_back(Pair("strength",(int64_t)(P.strength&0xffff))); + obj.push_back(Pair("maxstrength",(int64_t)(P.strength>>16))); obj.push_back(Pair("level",(int64_t)P.level)); obj.push_back(Pair("experience",(int64_t)P.experience)); obj.push_back(Pair("dungeonlevel",(int64_t)P.dungeonlevel)); @@ -863,12 +864,12 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat newdata[i] = newplayer[i]; ((uint8_t *)&endP)[i] = newplayer[i]; } - if ( endP.gold <= 0 || endP.hitpoints <= 0 || endP.strength <= 0 || endP.level <= 0 || endP.experience <= 0 || endP.dungeonlevel <= 0 ) + if ( endP.gold <= 0 || endP.hitpoints <= 0 || (endP.strength&0xffff) <= 0 || endP.level <= 0 || endP.experience <= 0 || endP.dungeonlevel <= 0 ) { fprintf(stderr,"zero value character was killed -> no playerdata\n"); newdata.resize(0); } - sprintf(str,"extracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength,endP.level,endP.experience,endP.dungeonlevel); + sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); fprintf(stderr,"%s\n",str); } else num = 0; } @@ -993,7 +994,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param newdata[i] = player[i]; ((uint8_t *)&P)[i] = player[i]; } - if ( P.gold <= 0 || P.hitpoints <= 0 || P.strength <= 0 || P.level <= 0 || P.experience <= 0 || P.dungeonlevel <= 0 ) + if ( P.gold <= 0 || P.hitpoints <= 0 || (P.strength&0xffff) <= 0 || P.level <= 0 || P.experience <= 0 || P.dungeonlevel <= 0 ) { fprintf(stderr,"zero value character was killed -> no playerdata\n"); newdata.resize(0); @@ -1005,7 +1006,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param cpTokens = CCinit(&tokensC, EVAL_TOKENS); mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cpTokens,NULL))); // marker to token cc addr, burnable and validated mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,1,mypk)); - fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); + fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); cashout = (uint64_t)P.gold * mult; if ( funcid == 'H' && maxplayers > 1 ) { From 6224d87b12dd461382289b908ccc341ff40888ac Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 21:45:29 -1100 Subject: [PATCH 0737/1145] Validate bypass --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b79d653d5..62f653685 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1246,11 +1246,11 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( script[1] == 'c' ) { - + return(true); } else { - + return(true); } } else return eval->Invalid("illegal evalcode"); } else return eval->Invalid("opret too small"); From 31a369f9855b16d616ba69f7830791e09e96adf2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 21:49:08 -1100 Subject: [PATCH 0738/1145] +fprintf in cursesd --- src/cc/rogue/cursesd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 02a80c470..30cc54ec9 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -162,7 +162,7 @@ int32_t mvaddch(int32_t y, int32_t x, chtype ch) int32_t waddstr(WINDOW *win, const char *str) { int32_t i; - //fprintf(stderr,"%s\n",str); + fprintf(stderr,"%s\n",str); for (i=0; str[i]!=0; i++) waddch(win,str[i]); return(0); From ab28897a624d29b96d13d0ba5e493e257555c0ad Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 21:57:34 -1100 Subject: [PATCH 0739/1145] Redo chg_str --- src/cc/rogue/misc.c | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue/misc.c b/src/cc/rogue/misc.c index 7db9d073a..8a4d1df94 100644 --- a/src/cc/rogue/misc.c +++ b/src/cc/rogue/misc.c @@ -349,17 +349,36 @@ void chg_str(int amt) { //auto jl777: strange compiler error - str_t comp; + uint32_t comp; if (amt == 0) return; - add_str(&pstats.s_str, amt); + //add_str(&pstats.s_str, amt); + pstats.s_str += amt; + if ( pstats.s_str < 3 ) + pstats.s_str = 3; + else if ( pstats.s_str > 31 ) + pstats.s_str = 31; comp = pstats.s_str; if (ISRING(LEFT, R_ADDSTR)) - add_str(&comp, -cur_ring[LEFT]->o_arm); + { + // add_str(&comp, -cur_ring[LEFT]->o_arm); + comp += -cur_ring[LEFT]->o_arm; + if ( comp < 3 ) + comp = 3; + else if ( comp > 31 ) + comp = 31; + } if (ISRING(RIGHT, R_ADDSTR)) - add_str(&comp, -cur_ring[RIGHT]->o_arm); - if (comp > max_stats.s_str) + { + //add_str(&comp, -cur_ring[RIGHT]->o_arm); + comp += -cur_ring[RIGHT]->o_arm; + if ( comp < 3 ) + comp = 3; + else if ( comp > 31 ) + comp = 31; + } + if ( comp > max_stats.s_str ) max_stats.s_str = comp; } From 67879fb99208d901882322d83ef6a9416d9a5602 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 22:03:55 -1100 Subject: [PATCH 0740/1145] +chars print --- src/cc/rogue/io.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index c920ee411..7cfa7e59f 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -161,7 +161,7 @@ readchar(struct rogue_state *rs) { //if ( rs->ind == rs->numkeys-1 ) // rs->replaydone = (uint32_t)time(NULL); - //fprintf(stderr,"(%c) ",rs->keystrokes[rs->ind]); + fprintf(stderr,"(%c) ",rs->keystrokes[rs->ind]); return(rs->keystrokes[rs->ind++]); } if ( rs->replaydone != 0 && counter++ < 3 ) From 10ad979ac9fe8cdf4862358f4ced79e84c9e51e0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 22:08:13 -1100 Subject: [PATCH 0741/1145] Test --- src/cc/rogue/command.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index 6cc6b0763..22723b6c6 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -259,7 +259,8 @@ over: again = TRUE; goto over; } - when 'q': quaff(rs); + case 'q': quaff(rs); + break; when 'Q': after = FALSE; q_comm = TRUE; From fbdd8a6166c356655a87b0ea8d4cb2c41c742504 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 22:10:48 -1100 Subject: [PATCH 0742/1145] Test --- src/cc/rogue/command.c | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index 22723b6c6..5dbc97051 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -262,15 +262,18 @@ over: case 'q': quaff(rs); break; when 'Q': - after = FALSE; - q_comm = TRUE; - quit(0); - if ( rs->guiflag != 0 && rs->needflush == 0 ) - rs->needflush = (uint32_t)time(NULL); - q_comm = FALSE; - if ( rs->guiflag != 0 ) - rogue_bailout(rs); - else rs->replaydone = (uint32_t)time(NULL); + if ( rs->sleeptime == 1 ) + { + after = FALSE; + q_comm = TRUE; + quit(0); + if ( rs->guiflag != 0 && rs->needflush == 0 ) + rs->needflush = (uint32_t)time(NULL); + q_comm = FALSE; + if ( rs->guiflag != 0 ) + rogue_bailout(rs); + else rs->replaydone = (uint32_t)time(NULL); + } return; when 'i': after = FALSE; inventory(rs,pack, 0); when 'I': after = FALSE; picky_inven(rs); From da2234e121cc9649b367dc0cd18ad9f1e80b3e9c Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 22:15:25 -1100 Subject: [PATCH 0743/1145] Test --- src/cc/rogue/command.c | 21 +++++++++------------ src/cc/rogue/rogue.c | 6 +++--- 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index 5dbc97051..d13be4972 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -262,18 +262,15 @@ over: case 'q': quaff(rs); break; when 'Q': - if ( rs->sleeptime == 1 ) - { - after = FALSE; - q_comm = TRUE; - quit(0); - if ( rs->guiflag != 0 && rs->needflush == 0 ) - rs->needflush = (uint32_t)time(NULL); - q_comm = FALSE; - if ( rs->guiflag != 0 ) - rogue_bailout(rs); - else rs->replaydone = (uint32_t)time(NULL); - } + after = FALSE; + q_comm = TRUE; + quit(0); + if ( rs->guiflag != 0 && rs->needflush == 0 ) + rs->needflush = (uint32_t)time(NULL); + q_comm = FALSE; + if ( rs->guiflag != 0 ) + rogue_bailout(rs); + else rs->replaydone = (uint32_t)time(NULL); return; when 'i': after = FALSE; inventory(rs,pack, 0); when 'I': after = FALSE; picky_inven(rs); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 72fe07558..67a99aa14 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -633,9 +633,9 @@ quit(int sig) */ if (!q_comm) mpos = 0; - getyx(curscr, oy, ox); - msg(rs,"really quit?"); } + getyx(curscr, oy, ox); + msg(rs,"really quit?"); if (readchar(rs) == 'y') { if ( rs->guiflag != 0 ) @@ -653,7 +653,7 @@ quit(int sig) else { //score(rs,purse, 1, 0); - //fprintf(stderr,"done!\n"); + fprintf(stderr,"done!\n"); } } else From 0d262ff7e2e0a68520b6d59668fa3f7a9ae5d848 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 22:17:40 -1100 Subject: [PATCH 0744/1145] Test --- src/cc/rogue/io.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 7cfa7e59f..83e0c2ff6 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -161,7 +161,12 @@ readchar(struct rogue_state *rs) { //if ( rs->ind == rs->numkeys-1 ) // rs->replaydone = (uint32_t)time(NULL); - fprintf(stderr,"(%c) ",rs->keystrokes[rs->ind]); + if ( rs->keystrokes[rs->ind] == 'Q' ) + { + rs->ind++; + fprintf(stderr,"Q.(%c) ",rs->keystrokes[rs->ind]); + return('q'); + } return(rs->keystrokes[rs->ind++]); } if ( rs->replaydone != 0 && counter++ < 3 ) From ae05cc1f6816560481cabb33d2e38041a5ce8f8a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 22:22:50 -1100 Subject: [PATCH 0745/1145] Quit handling --- src/cc/rogue/command.c | 17 ++++++++++------- src/cc/rogue/extern.h | 2 +- src/cc/rogue/io.c | 13 ------------- src/cc/rogue/rogue.c | 7 ++++--- 4 files changed, 15 insertions(+), 24 deletions(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index d13be4972..d55b93a5b 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -264,14 +264,17 @@ over: when 'Q': after = FALSE; q_comm = TRUE; - quit(0); - if ( rs->guiflag != 0 && rs->needflush == 0 ) - rs->needflush = (uint32_t)time(NULL); + if ( quit(0) > 0 ) + { + if ( rs->guiflag != 0 ) + { + if (rs->needflush == 0 ) + rs->needflush = (uint32_t)time(NULL); + rogue_bailout(rs); + } else rs->replaydone = (uint32_t)time(NULL); + } q_comm = FALSE; - if ( rs->guiflag != 0 ) - rogue_bailout(rs); - else rs->replaydone = (uint32_t)time(NULL); - return; + return; when 'i': after = FALSE; inventory(rs,pack, 0); when 'I': after = FALSE; picky_inven(rs); when 'd': drop(rs); diff --git a/src/cc/rogue/extern.h b/src/cc/rogue/extern.h index fc3454830..ff45e0fee 100644 --- a/src/cc/rogue/extern.h +++ b/src/cc/rogue/extern.h @@ -141,7 +141,7 @@ void getltchars(void); void leave(int); void my_exit(int st); void playltchars(void); -void quit(int); +int32_t quit(int); void resetltchars(void); void set_order(int *order, int numthings); void tstp(int ignored); diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 83e0c2ff6..576314a42 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -158,23 +158,10 @@ readchar(struct rogue_state *rs) { static uint32_t counter; if ( rs->ind < rs->numkeys ) - { - //if ( rs->ind == rs->numkeys-1 ) - // rs->replaydone = (uint32_t)time(NULL); - if ( rs->keystrokes[rs->ind] == 'Q' ) - { - rs->ind++; - fprintf(stderr,"Q.(%c) ",rs->keystrokes[rs->ind]); - return('q'); - } return(rs->keystrokes[rs->ind++]); - } if ( rs->replaydone != 0 && counter++ < 3 ) fprintf(stderr,"replay finished but readchar called\n"); rs->replaydone = (uint32_t)time(NULL); - //if ( (rand() & 1) == 0 ) - // return(ESCAPE); - //else if ( counter < 3 || (counter & 1) == 0 ) return('y'); else return(ESCAPE); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 67a99aa14..bfb4e0277 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -618,8 +618,7 @@ playit(struct rogue_state *rs) * Have player make certain, then exit. */ -void -quit(int sig) +int32_t quit(int sig) { struct rogue_state *rs = &globalR; int oy, ox; @@ -653,8 +652,9 @@ quit(int sig) else { //score(rs,purse, 1, 0); - fprintf(stderr,"done!\n"); + //fprintf(stderr,"done!\n"); } + return(1); } else { @@ -667,6 +667,7 @@ quit(int sig) mpos = 0; count = 0; to_death = FALSE; + return(0); } } From f513e5d1f531de4760c41d09f9f0ece0069d00ae Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 22:26:03 -1100 Subject: [PATCH 0746/1145] Prints --- src/cc/rogue/io.c | 2 ++ src/cc/rogue/rogue.c | 8 +++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 576314a42..6e070b2a8 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -158,7 +158,9 @@ readchar(struct rogue_state *rs) { static uint32_t counter; if ( rs->ind < rs->numkeys ) + { return(rs->keystrokes[rs->ind++]); + } if ( rs->replaydone != 0 && counter++ < 3 ) fprintf(stderr,"replay finished but readchar called\n"); rs->replaydone = (uint32_t)time(NULL); diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index bfb4e0277..dafcf3f01 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -621,7 +621,7 @@ playit(struct rogue_state *rs) int32_t quit(int sig) { struct rogue_state *rs = &globalR; - int oy, ox; + int oy, ox, c; //fprintf(stderr,"inside quit(%d)\n",sig); if ( rs->guiflag != 0 ) { @@ -635,7 +635,8 @@ int32_t quit(int sig) } getyx(curscr, oy, ox); msg(rs,"really quit?"); - if (readchar(rs) == 'y') + sleep(1); + if ( (c= readchar(rs)) == 'y') { if ( rs->guiflag != 0 ) { @@ -652,12 +653,13 @@ int32_t quit(int sig) else { //score(rs,purse, 1, 0); - //fprintf(stderr,"done!\n"); + fprintf(stderr,"done!\n"); } return(1); } else { + fprintf(stderr,"'Q' answer (%c)\n",c); move(0, 0); clrtoeol(); status(rs); From ef4844d5a3538f097c7b81a311c7409172f46107 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 22:29:58 -1100 Subject: [PATCH 0747/1145] _quit --- src/cc/rogue/command.c | 2 +- src/cc/rogue/extern.h | 3 ++- src/cc/rogue/io.c | 2 +- src/cc/rogue/rogue.c | 40 +++++++++++++++++++++++++--------------- 4 files changed, 29 insertions(+), 18 deletions(-) diff --git a/src/cc/rogue/command.c b/src/cc/rogue/command.c index d55b93a5b..54d7beb99 100644 --- a/src/cc/rogue/command.c +++ b/src/cc/rogue/command.c @@ -264,7 +264,7 @@ over: when 'Q': after = FALSE; q_comm = TRUE; - if ( quit(0) > 0 ) + if ( _quit() > 0 ) { if ( rs->guiflag != 0 ) { diff --git a/src/cc/rogue/extern.h b/src/cc/rogue/extern.h index ff45e0fee..7fba842f3 100644 --- a/src/cc/rogue/extern.h +++ b/src/cc/rogue/extern.h @@ -141,7 +141,8 @@ void getltchars(void); void leave(int); void my_exit(int st); void playltchars(void); -int32_t quit(int); +void quit(int); +int32_t _quit(); void resetltchars(void); void set_order(int *order, int numthings); void tstp(int ignored); diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 6e070b2a8..79eadb571 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -174,7 +174,7 @@ readchar(struct rogue_state *rs) if (ch == 3) { - quit(0); + _quit(); return(27); } if ( rs != 0 && rs->guiflag != 0 ) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index dafcf3f01..02feef2ab 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -613,26 +613,13 @@ playit(struct rogue_state *rs) endit(0); } -/* - * quit: - * Have player make certain, then exit. - */ -int32_t quit(int sig) + +int32_t _quit() { struct rogue_state *rs = &globalR; int oy, ox, c; //fprintf(stderr,"inside quit(%d)\n",sig); - if ( rs->guiflag != 0 ) - { - NOOP(sig); - - /* - * Reset the signal in case we got here via an interrupt - */ - if (!q_comm) - mpos = 0; - } getyx(curscr, oy, ox); msg(rs,"really quit?"); sleep(1); @@ -673,6 +660,29 @@ int32_t quit(int sig) } } +/* + * quit: + * Have player make certain, then exit. + */ + +void quit(int sig) +{ + struct rogue_state *rs = &globalR; + int oy, ox, c; + //fprintf(stderr,"inside quit(%d)\n",sig); + if ( rs->guiflag != 0 ) + { + NOOP(sig); + + /* + * Reset the signal in case we got here via an interrupt + */ + if (!q_comm) + mpos = 0; + } + _quit(); +} + /* * leave: * Leave quickly, but curteously From 7be1c552280b7c4347306e064632bdebcf024dba Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 22:33:13 -1100 Subject: [PATCH 0748/1145] tst --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 02feef2ab..bc576dabf 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -640,7 +640,7 @@ int32_t _quit() else { //score(rs,purse, 1, 0); - fprintf(stderr,"done!\n"); + fprintf(stderr,"done! (%c)\n",c); } return(1); } From 0a11653334e01b49116a47003f57088d99fd5eac Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 22:38:44 -1100 Subject: [PATCH 0749/1145] test --- src/cc/rogue/io.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 79eadb571..525550e67 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -153,13 +153,22 @@ step_ok(int ch) char readchar(struct rogue_state *rs) { - char ch = -1; + char c,ch = -1; if ( rs != 0 && rs->guiflag == 0 ) { static uint32_t counter; if ( rs->ind < rs->numkeys ) { - return(rs->keystrokes[rs->ind++]); + c = rs->keystrokes[rs->ind++]; + while ( c == 'Q' && rs->ind < rs->numkeys ) + { + fprintf(stderr,"Got 'Q' next (%c)\n",rs->keystrokes[rs->ind]); sleep(2); + if ( rs->keystrokes[rs->ind] == 'y' ) + return(c); + rs->ind++; + c = rs->keystrokes[rs->ind++]; + } + return(c); } if ( rs->replaydone != 0 && counter++ < 3 ) fprintf(stderr,"replay finished but readchar called\n"); From 8ea12e7dde906edc9d0e4342929bc13c7eb70b92 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 23:02:10 -1100 Subject: [PATCH 0750/1145] Test --- src/cc/rogue/rogue.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index bc576dabf..6583725f4 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -250,6 +250,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu rs->restoring = 1; //fprintf(stderr,"restore player packsize.%d HP.%d\n",rs->P.packsize,rs->P.hitpoints); } + globalR = *rs; uint32_t starttime = (uint32_t)time(NULL); rogueiterate(rs); if ( 0 ) @@ -760,7 +761,7 @@ my_exit(int st) exit(st); else if ( counter++ < 10 ) { - fprintf(stderr,"would have exit.(%d)\n",st); + fprintf(stderr,"would have exit.(%d) sleeptime.%d\n",st,globalR.sleeptime); globalR.replaydone = 1; } } From ef554cc4744b53eda75dafeea3698e94328eb042 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 23:03:55 -1100 Subject: [PATCH 0751/1145] -print and pause --- src/cc/rogue/io.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 525550e67..9842ba353 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -162,7 +162,7 @@ readchar(struct rogue_state *rs) c = rs->keystrokes[rs->ind++]; while ( c == 'Q' && rs->ind < rs->numkeys ) { - fprintf(stderr,"Got 'Q' next (%c)\n",rs->keystrokes[rs->ind]); sleep(2); + //fprintf(stderr,"Got 'Q' next (%c)\n",rs->keystrokes[rs->ind]); sleep(2); if ( rs->keystrokes[rs->ind] == 'y' ) return(c); rs->ind++; From 85d4e67ea779ef417ffa07567d4639d10e897884 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 23:16:03 -1100 Subject: [PATCH 0752/1145] -print --- src/cc/rogue/cursesd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 30cc54ec9..02a80c470 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -162,7 +162,7 @@ int32_t mvaddch(int32_t y, int32_t x, chtype ch) int32_t waddstr(WINDOW *win, const char *str) { int32_t i; - fprintf(stderr,"%s\n",str); + //fprintf(stderr,"%s\n",str); for (i=0; str[i]!=0; i++) waddch(win,str[i]); return(0); From 26f77ab47dc2a66b9529921794bebadf9951ac5b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 23:29:45 -1100 Subject: [PATCH 0753/1145] -sleep --- src/cc/rogue/rogue.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 6583725f4..c2f1d9829 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -595,7 +595,7 @@ playit(struct rogue_state *rs) { if ( rs->replaydone != 0 ) { - if ( rs->sleeptime != 0 ) + if ( 0 && rs->sleeptime != 0 ) sleep(3); return; } @@ -623,7 +623,7 @@ int32_t _quit() //fprintf(stderr,"inside quit(%d)\n",sig); getyx(curscr, oy, ox); msg(rs,"really quit?"); - sleep(1); + //sleep(1); if ( (c= readchar(rs)) == 'y') { if ( rs->guiflag != 0 ) From 9ef4ca17230036e43607999f0f9d6f06ff3ee282 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 23:33:24 -1100 Subject: [PATCH 0754/1145] Validation prints --- src/cc/rogue_rpc.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 62f653685..d0ed66cbb 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1235,6 +1235,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'K': // keystrokes case 'H': // win case 'Q': // bailout + fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); return(true); break; default: @@ -1244,6 +1245,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } else if ( script[0] == EVAL_TOKENS ) { + fprintf(stderr,"ht.%d tokens.(%c)\n",height,script[1]); if ( script[1] == 'c' ) { return(true); From 9a48b245d436297903ae8f44292f9332deee427b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 23:46:14 -1100 Subject: [PATCH 0755/1145] Remove minstrength check --- src/cc/rogue/init.c | 4 +--- src/cc/rogue_rpc.cpp | 23 ++++++++++------------- 2 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index 6ff0a71c0..62998889d 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -28,9 +28,7 @@ void restore_player(struct rogue_state *rs) //rs->P.gold = purse; max_hp = rs->P.hitpoints; pstats.s_str = rs->P.strength & 0xffff; - max_stats.s_str = rs->P.strength >> 16; - if ( max_stats.s_str < 12 ) - max_stats.s_str = 12; + max_stats.s_str = (rs->P.strength >> 16) & 0xffff; if ( pstats.s_str > max_stats.s_str ) pstats.s_str = max_stats.s_str; pstats.s_lvl = rs->P.level; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d0ed66cbb..068847c93 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1226,9 +1226,18 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C if ( vopret.size() > 2 ) { script = (uint8_t *)vopret.data(); + if ( script[0] == EVAL_TOKENS ) + { + if ( script[1] == 'c' ) + { + } + else if ( script[1] == 't' ) + { + } else return eval->Invalid("illegal tokens funcid"); + } if ( script[0] == EVAL_ROGUE ) { - switch ( script[1] ) + switch ( funcid ) { case 'G': // newgame case 'R': // register @@ -1242,18 +1251,6 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return eval->Invalid("illegal rogue funcid"); break; } - } - else if ( script[0] == EVAL_TOKENS ) - { - fprintf(stderr,"ht.%d tokens.(%c)\n",height,script[1]); - if ( script[1] == 'c' ) - { - return(true); - } - else - { - return(true); - } } else return eval->Invalid("illegal evalcode"); } else return eval->Invalid("opret too small"); } else return eval->Invalid("not enough vouts"); From eff9ec93e24fbf2be824a4ef68e194933854de72 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 23:47:59 -1100 Subject: [PATCH 0756/1145] Backwards compatibility --- src/cc/rogue/init.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index 62998889d..1a5faa9ce 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -28,7 +28,8 @@ void restore_player(struct rogue_state *rs) //rs->P.gold = purse; max_hp = rs->P.hitpoints; pstats.s_str = rs->P.strength & 0xffff; - max_stats.s_str = (rs->P.strength >> 16) & 0xffff; + if ( (max_stats.s_str= (rs->P.strength >> 16) & 0xffff) == 0 ) + max_stats.s_str = 16; if ( pstats.s_str > max_stats.s_str ) pstats.s_str = max_stats.s_str; pstats.s_lvl = rs->P.level; From 2e1e7f8c7ba42670af2156759e38fc38fb0529aa Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 17 Feb 2019 23:52:07 -1100 Subject: [PATCH 0757/1145] Fix num_pack --- src/cc/rogue/pack.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 2f683441b..37072bf93 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -252,7 +252,10 @@ int32_t num_packitems() THING *list = pack; int32_t type = 0,n = 0; for (; list != NULL; list = next(list)) - n++; + { + if (!list->o_packch) + n++; + } return(n); } From 76c397d4d1137a44b6f7b8026cfa9c898222c101 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:00:06 -1100 Subject: [PATCH 0758/1145] Rework validation --- src/cc/rogue/pack.c | 16 ++++++++-------- src/cc/rogue_rpc.cpp | 9 +++++++-- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 37072bf93..392159fb5 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -52,9 +52,9 @@ add_pack(struct rogue_state *rs,THING *obj, bool silent) if (pack == NULL) { - pack = obj; - obj->o_packch = pack_char(); - inpack++; + pack = obj; + obj->o_packch = pack_char(); + inpack++; } else { @@ -291,11 +291,11 @@ inventory(struct rogue_state *rs,THING *list, int type) // fprintf(stderr,"n_objs.%d vs inpack.%d\n",n_objs,inpack), sleep(2); if (n_objs == 0) { - if (terse) - msg(rs,type == 0 ? (char *)"empty handed" : (char *)"nothing appropriate"); - else - msg(rs,type == 0 ? (char *)"you are empty handed" : (char *)"you don't have anything appropriate"); - return FALSE; + if (terse) + msg(rs,type == 0 ? (char *)"empty handed" : (char *)"nothing appropriate"); + else + msg(rs,type == 0 ? (char *)"you are empty handed" : (char *)"you don't have anything appropriate"); + return FALSE; } end_line(rs); return TRUE; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 068847c93..c4a142ba1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1226,16 +1226,21 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C if ( vopret.size() > 2 ) { script = (uint8_t *)vopret.data(); - if ( script[0] == EVAL_TOKENS ) + funcid = script[1]; + if ( (e= script[0]) == EVAL_TOKENS ) { if ( script[1] == 'c' ) { + e = EVAL_ROGUE; + funcid = 'Q'; } else if ( script[1] == 't' ) { + e = EVAL_ROGUE; + funcid = 'Q'; } else return eval->Invalid("illegal tokens funcid"); } - if ( script[0] == EVAL_ROGUE ) + if ( e == EVAL_ROGUE ) { switch ( funcid ) { From 27002ce1f2f10f12baef75e4fb30c898370c8d9b Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:07:45 -1100 Subject: [PATCH 0759/1145] -print --- src/cc/assets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index 28adf9be6..f42c4fda3 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -177,7 +177,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti // find single-eval token user cc addr: //GetCCaddress(cpTokens, signleEvalTokensCCaddr, pubkey2pk(origpubkey)); - fprintf(stderr,"AssetValidate (%c)\n",funcid); + //fprintf(stderr,"AssetValidate (%c)\n",funcid); if( funcid != 'o' && funcid != 'x' && eval->GetTxUnconfirmed(assetid, createTx, hashBlock) == 0 ) return eval->Invalid("cant find asset create txid"); From 553b54b61cb32f41a86281dd26fabe2ecce1363f Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 12:13:11 +0100 Subject: [PATCH 0760/1145] roguefy makefile 'roguefy' for komodo linux makefile --- zcutil/build.sh | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/zcutil/build.sh b/zcutil/build.sh index dc312c8e8..7b452a1fc 100755 --- a/zcutil/build.sh +++ b/zcutil/build.sh @@ -103,20 +103,12 @@ ld -v HOST="$HOST" BUILD="$BUILD" NO_PROTON="$PROTON_ARG" "$MAKE" "$@" -C ./depends/ V=1 - #BUILD CCLIB WD=$PWD cd src/cc echo $PWD - -if make "$@"; then - echo CCLIB BUILD SUCCESSFUL -else - echo CCLIB BUILD FAILED - exit 1 -fi - +./makerogue cd $WD ./autogen.sh From 2d98e3a0e58072fac0eb866dfbcf2c36d3c8bc2e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:39:21 -1100 Subject: [PATCH 0761/1145] Decode all ospreys --- src/cc/rogue_rpc.cpp | 69 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 53 insertions(+), 16 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c4a142ba1..ac63dea42 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1218,7 +1218,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,ind,errflag,dispflag,score,numvouts; CTransaction vintx; uint256 hashBlock; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -1229,30 +1229,67 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C funcid = script[1]; if ( (e= script[0]) == EVAL_TOKENS ) { - if ( script[1] == 'c' ) + if ( (funcid= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) == 0 ) { - e = EVAL_ROGUE; - funcid = 'Q'; - } - else if ( script[1] == 't' ) - { - e = EVAL_ROGUE; - funcid = 'Q'; - } else return eval->Invalid("illegal tokens funcid"); + if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) + { + funcid = 'Q'; + fprintf(stderr,"ht.%d couldnt decode tokens opret\n",height); + } else e = EVAL_ROGUE, decoded = 1; + } else e = EVAL_ROGUE, decoded = 1; } if ( e == EVAL_ROGUE ) { + if ( decoded == 0 ) + { + switch ( funcid ) + { + case 'G': + if ( (funcid= rogue_newgameopreturndecode(buyin,maxplayers,scriptPubKey)) != 'G' ) + return eval->Invalid("couldnt decode newgame opret"); + // validate newgame tx + return(true); + break; + case 'R': + if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) != 'R' ) + return eval->Invalid("couldnt decode register opret"); + break; + case 'K': + if ( (funcid= rogue_keystrokesopretdecode(gametxid,batontxid,pk,keystrokes,scriptPubKey)) != 'K' ) + return eval->Invalid("couldnt decode keystrokes opret"); + // validate keystrokes are from the correct pk. might need to add vin + return(true); + break; + case 'H': case 'Q': + if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) != funcid ) + return eval->Invalid("couldnt decode H/Q opret"); + break; + default: + return eval->Invalid("illegal rogue non-decoded funcid"); + break; + } + } switch ( funcid ) { - case 'G': // newgame - case 'R': // register - case 'K': // keystrokes - case 'H': // win - case 'Q': // bailout - fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); + case 'R': + // validate register: within 60 blocks, not duplicate, etc. + return(true); + break; + case 'H': // fall through + case 'Q': + // make sure any playerdata is reproduced via replay + if ( funcid == 'Q' ) + { + // validate bailout constraints + } + else // 'H' + { + // validate winner constraints + } return(true); break; default: + fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); return eval->Invalid("illegal rogue funcid"); break; } From bec0d4935f6227df401270e3cd779f05657fd65b Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:39:56 -1100 Subject: [PATCH 0762/1145] Playertxid --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ac63dea42..06d2b63b8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1218,7 +1218,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; From 0a59b078e15e4b4fb4a63caffc32531b6befb150 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:41:45 -1100 Subject: [PATCH 0763/1145] -proint --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c4a142ba1..451b3bedb 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1249,7 +1249,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'K': // keystrokes case 'H': // win case 'Q': // bailout - fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); + //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); return(true); break; default: From 562e99fc96d91c8d796580ca3d688d34d8aa6884 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:51:21 -1100 Subject: [PATCH 0764/1145] Do total items --- src/cc/rogue/pack.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 392159fb5..4858afcdd 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -250,12 +250,16 @@ pack_char() int32_t num_packitems() { THING *list = pack; - int32_t type = 0,n = 0; + int32_t type = 0,n = 0,total = 0; for (; list != NULL; list = next(list)) { - if (!list->o_packch) + if ( list->o_packch != 0 ) + { n++; + total += list->o_count; + } } + fprintf(stderr,"total.%d vs %d inventory letters\n",total,n); return(n); } From 437af05de66e9e0822c1472eef335425bcb49883 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:53:23 -1100 Subject: [PATCH 0765/1145] Test --- src/cc/rogue/pack.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 4858afcdd..8fc488389 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -259,7 +259,7 @@ int32_t num_packitems() total += list->o_count; } } - fprintf(stderr,"total.%d vs %d inventory letters\n",total,n); + fprintf(stderr,"total.%d vs %d inventory letters\n",total,n); sleep(1); return(n); } From dae06859f1803ad54733671a512c993cc34a5417 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 00:57:16 -1100 Subject: [PATCH 0766/1145] -sleep --- src/cc/rogue/pack.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 8fc488389..39dc163b1 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -259,7 +259,7 @@ int32_t num_packitems() total += list->o_count; } } - fprintf(stderr,"total.%d vs %d inventory letters\n",total,n); sleep(1); + fprintf(stderr,"total.%d vs %d inventory letters\n",total,n); return(n); } From 040d3f8bfeebe26f46104c6000efe8352e03a39d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:04:14 -1100 Subject: [PATCH 0767/1145] Print --- src/cc/rogue/pack.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 39dc163b1..1589d4d34 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -259,14 +259,17 @@ int32_t num_packitems() total += list->o_count; } } - fprintf(stderr,"total.%d vs %d inventory letters\n",total,n); + + char inv_temp[MAXSTR],str[MAXSTR]; + sprintf(str,"total.%d vs %d inventory letters\n",total,n); + add_line(rs,inv_temp,str); return(n); } bool inventory(struct rogue_state *rs,THING *list, int type) { - static char inv_temp[MAXSTR]; + char inv_temp[MAXSTR]; n_objs = 0; for (; list != NULL; list = next(list)) From e4c1ce63964d04147e20bcb4e4643a852ee38bbe Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:04:51 -1100 Subject: [PATCH 0768/1145] struct rogue_state *rs --- src/cc/rogue/pack.c | 4 ++-- src/cc/rogue/rogue.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 1589d4d34..0c967a85b 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -165,7 +165,7 @@ out: bool pack_room(struct rogue_state *rs,bool from_floor, THING *obj) { - inpack = num_packitems(); + inpack = num_packitems(rs); if (++inpack > MAXPACK) { if (!terse) @@ -247,7 +247,7 @@ pack_char() * the given type. */ -int32_t num_packitems() +int32_t num_packitems(struct rogue_state *rs) { THING *list = pack; int32_t type = 0,n = 0,total = 0; diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 905a5ed36..515c1d44a 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -802,7 +802,7 @@ THING *leave_pack(struct rogue_state *rs,THING *obj, bool newobj, bool all); THING *new_item(void); THING *new_thing(struct rogue_state *rs); void end_line(struct rogue_state *rs); -int32_t num_packitems(); +int32_t num_packitems(struct rogue_state *rs); void runners(struct rogue_state *rs,int); void land(struct rogue_state *rs,int); From 63bad40a584d5a8c6206219103960ddd68f21e53 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:07:59 -1100 Subject: [PATCH 0769/1145] Fat --- src/cc/rogue/pack.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 0c967a85b..7e93dd759 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -260,9 +260,9 @@ int32_t num_packitems(struct rogue_state *rs) } } - char inv_temp[MAXSTR],str[MAXSTR]; + char str[MAXSTR]; sprintf(str,"total.%d vs %d inventory letters\n",total,n); - add_line(rs,inv_temp,str); + add_line(rs,"%s",str); return(n); } From f9b288af4768d7f4f75a44da02ab1067accbed0a Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:11:53 -1100 Subject: [PATCH 0770/1145] Total < strength*3 --- src/cc/rogue/pack.c | 74 ++++++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index 7e93dd759..f8fc98175 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -157,37 +157,55 @@ out: } } +int32_t num_packitems(struct rogue_state *rs) +{ + THING *list = pack; + int32_t type = 0,n = 0,total = 0; + for (; list != NULL; list = next(list)) + { + if ( list->o_packch != 0 ) + { + n++; + total += list->o_count; + } + } + + char str[MAXSTR]; + sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); + add_line(rs,"%s",str); + if ( total > pstats.s_str*3 ) + return(MAXPACK); + return(n); +} + /* * pack_room: * See if there's room in the pack. If not, print out an * appropriate message */ -bool -pack_room(struct rogue_state *rs,bool from_floor, THING *obj) +bool pack_room(struct rogue_state *rs,bool from_floor, THING *obj) { inpack = num_packitems(rs); - if (++inpack > MAXPACK) + if ( ++inpack > MAXPACK ) { - if (!terse) - addmsg(rs,"there's "); - addmsg(rs,"no room"); - if (!terse) - addmsg(rs," in your pack"); - endmsg(rs); - if (from_floor) - move_msg(rs,obj); - inpack = MAXPACK; - return FALSE; + if (!terse) + addmsg(rs,"there's "); + addmsg(rs,"no room"); + if (!terse) + addmsg(rs," in your pack"); + endmsg(rs); + if (from_floor) + move_msg(rs,obj); + inpack = MAXPACK; + return FALSE; } //fprintf(stderr,"inpack.%d vs MAX.%d\n",inpack,MAXPACK), sleep(2); - - if (from_floor) + if ( from_floor != 0 ) { - detach(lvl_obj, obj); - mvaddch(hero.y, hero.x, floor_ch()); - chat(hero.y, hero.x) = (proom->r_flags & ISGONE) ? PASSAGE : FLOOR; + detach(lvl_obj, obj); + mvaddch(hero.y, hero.x, floor_ch()); + chat(hero.y, hero.x) = (proom->r_flags & ISGONE) ? PASSAGE : FLOOR; } - return TRUE; } @@ -247,24 +265,6 @@ pack_char() * the given type. */ -int32_t num_packitems(struct rogue_state *rs) -{ - THING *list = pack; - int32_t type = 0,n = 0,total = 0; - for (; list != NULL; list = next(list)) - { - if ( list->o_packch != 0 ) - { - n++; - total += list->o_count; - } - } - - char str[MAXSTR]; - sprintf(str,"total.%d vs %d inventory letters\n",total,n); - add_line(rs,"%s",str); - return(n); -} bool inventory(struct rogue_state *rs,THING *list, int type) From 575f5b4fd85d91560e6feb27a15934a6cbb51070 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:13:31 -1100 Subject: [PATCH 0771/1145] Disable --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 06d2b63b8..f4f45bf25 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1219,6 +1219,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + return(true); if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -1289,7 +1290,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return(true); break; default: - fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); + //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); return eval->Invalid("illegal rogue funcid"); break; } From 54319f4bb65ce2ff948b23d58247f15ca515b0d8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:20:28 -1100 Subject: [PATCH 0772/1145] Test opret validation --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 068a959cc..e5381a802 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1219,7 +1219,6 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; - return(true); if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -1254,6 +1253,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'R': if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) != 'R' ) return eval->Invalid("couldnt decode register opret"); + // validation is done below break; case 'K': if ( (funcid= rogue_keystrokesopretdecode(gametxid,batontxid,pk,keystrokes,scriptPubKey)) != 'K' ) @@ -1264,6 +1264,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'H': case 'Q': if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) != funcid ) return eval->Invalid("couldnt decode H/Q opret"); + // validation is done below break; default: return eval->Invalid("illegal rogue non-decoded funcid"); From c19cc548ad998128ea19628bcc9294e2746f8103 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:22:53 -1100 Subject: [PATCH 0773/1145] Height exemption --- src/cc/rogue_rpc.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index e5381a802..b1eb36e65 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1246,7 +1246,11 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { case 'G': if ( (funcid= rogue_newgameopreturndecode(buyin,maxplayers,scriptPubKey)) != 'G' ) - return eval->Invalid("couldnt decode newgame opret"); + { + fprintf(stderr,"height.%d couldnt decode newgame opret\n",height); + if ( height > 20000 ) + return eval->Invalid("couldnt decode newgame opret"); + } // validate newgame tx return(true); break; From 53c35e3c89c1ea5358e75ebf9a6069b5fac6a424 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:26:56 -1100 Subject: [PATCH 0774/1145] Test --- src/cc/rogue_rpc.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b1eb36e65..6e6da24f2 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1240,6 +1240,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } if ( e == EVAL_ROGUE ) { + fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); if ( decoded == 0 ) { switch ( funcid ) @@ -1261,7 +1262,11 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C break; case 'K': if ( (funcid= rogue_keystrokesopretdecode(gametxid,batontxid,pk,keystrokes,scriptPubKey)) != 'K' ) - return eval->Invalid("couldnt decode keystrokes opret"); + { + fprintf(stderr,"height.%d couldnt decode keystrokes opret\n",height); + if ( height > 20000 ) + return eval->Invalid("couldnt decode keystrokes opret"); + } // validate keystrokes are from the correct pk. might need to add vin return(true); break; @@ -1286,7 +1291,6 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return(true); break; default: - //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); return eval->Invalid("illegal rogue funcid"); break; } From aa26fa0a69c7ba92ab3b2a0ade2c5adf8eac2300 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:30:05 -1100 Subject: [PATCH 0775/1145] Bypass all --- src/cc/rogue_rpc.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 6e6da24f2..994cbe319 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1257,7 +1257,11 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C break; case 'R': if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) != 'R' ) - return eval->Invalid("couldnt decode register opret"); + { + fprintf(stderr,"height.%d couldnt decode register opret\n",height); + if ( height > 20000 ) + return eval->Invalid("couldnt decode register opret"); + } // validation is done below break; case 'K': @@ -1272,7 +1276,11 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C break; case 'H': case 'Q': if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) != funcid ) - return eval->Invalid("couldnt decode H/Q opret"); + { + fprintf(stderr,"height.%d couldnt decode H/Q opret\n",height); + if ( height > 20000 ) + return eval->Invalid("couldnt decode H/Q opret"); + } // validation is done below break; default: From 535741426479fc5d01d35ef90b74ed6fba2b880c Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 01:35:21 -1100 Subject: [PATCH 0776/1145] Test --- src/cc/rogue_rpc.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 994cbe319..ef24489ba 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1234,7 +1234,9 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) { funcid = 'Q'; - fprintf(stderr,"ht.%d couldnt decode tokens opret\n",height); + fprintf(stderr,"ht.%d couldnt decode tokens opret (%c)\n",height,script[1]); + if ( height < 20000 ) + e = EVAL_ROGUE; } else e = EVAL_ROGUE, decoded = 1; } else e = EVAL_ROGUE, decoded = 1; } From 49d8a2aa5d9b6306776650cfa3e9e3442d1716e6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 03:20:43 -1100 Subject: [PATCH 0777/1145] Disable --- src/cc/rogue/pack.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index f8fc98175..f28ef891d 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -169,12 +169,14 @@ int32_t num_packitems(struct rogue_state *rs) total += list->o_count; } } - - char str[MAXSTR]; - sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); - add_line(rs,"%s",str); - if ( total > pstats.s_str*3 ) - return(MAXPACK); + if ( 0 ) // crashes playerinfo + { + char str[MAXSTR]; + sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); + add_line(rs,"%s",str); + if ( total > pstats.s_str*3 ) + return(MAXPACK); + } return(n); } From f5af7f465f635877aafcea1bc630016e4d86114f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 03:23:15 -1100 Subject: [PATCH 0778/1145] Fix player info crash --- src/cc/rogue/pack.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index f8fc98175..7fae5452a 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -169,10 +169,12 @@ int32_t num_packitems(struct rogue_state *rs) total += list->o_count; } } - - char str[MAXSTR]; - sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); - add_line(rs,"%s",str); + if ( 0 ) + { + char str[MAXSTR]; + sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); + add_line(rs,"%s",str); + } if ( total > pstats.s_str*3 ) return(MAXPACK); return(n); From a4f241718bdec6e7312a479037eba3ad40daa0f9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 03:24:21 -1100 Subject: [PATCH 0779/1145] Test --- src/cc/rogue/pack.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index f28ef891d..d482a8a52 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -169,14 +169,14 @@ int32_t num_packitems(struct rogue_state *rs) total += list->o_count; } } - if ( 0 ) // crashes playerinfo + if ( rs->guiflag != 0 ) { char str[MAXSTR]; sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); add_line(rs,"%s",str); - if ( total > pstats.s_str*3 ) - return(MAXPACK); } + if ( total > pstats.s_str*3 ) + return(MAXPACK); return(n); } From 8b35141984d4a25ed761bdf23fb40a1772145b5e Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 15:29:59 +0100 Subject: [PATCH 0780/1145] roguefy WIN makefile --- zcutil/build-win.sh | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/zcutil/build-win.sh b/zcutil/build-win.sh index 5c12893fa..ef0c09549 100755 --- a/zcutil/build-win.sh +++ b/zcutil/build-win.sh @@ -11,6 +11,12 @@ cd "$(dirname "$(readlink -f "$0")")/.." cd depends/ && make HOST=$HOST V=1 NO_QT=1 cd ../ +WD=$PWD +cd src/cc +echo $PWD +./makerogue +cd $WD + ./autogen.sh CONFIG_SITE=$PWD/depends/x86_64-w64-mingw32/share/config.site CXXFLAGS="-DPTW32_STATIC_LIB -DCURL_STATICLIB -DCURVE_ALT_BN128 -fopenmp -pthread" ./configure --prefix="${PREFIX}" --host=x86_64-w64-mingw32 --enable-static --disable-shared sed -i 's/-lboost_system-mt /-lboost_system-mt-s /' configure From cbe32599e4cb46c06a97f8dca6e6cdcd96492573 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 03:35:29 -1100 Subject: [PATCH 0781/1145] Conditional validate --- src/cc/rogue_rpc.cpp | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ef24489ba..31336d8fb 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1219,6 +1219,8 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 20000 ) + return(true); if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -1231,12 +1233,9 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( (funcid= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) == 0 ) { - if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) + if ( (f= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) { - funcid = 'Q'; fprintf(stderr,"ht.%d couldnt decode tokens opret (%c)\n",height,script[1]); - if ( height < 20000 ) - e = EVAL_ROGUE; } else e = EVAL_ROGUE, decoded = 1; } else e = EVAL_ROGUE, decoded = 1; } @@ -1250,8 +1249,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'G': if ( (funcid= rogue_newgameopreturndecode(buyin,maxplayers,scriptPubKey)) != 'G' ) { - fprintf(stderr,"height.%d couldnt decode newgame opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode newgame opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode newgame opret"); } // validate newgame tx @@ -1260,8 +1259,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'R': if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) != 'R' ) { - fprintf(stderr,"height.%d couldnt decode register opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode register opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode register opret"); } // validation is done below @@ -1269,8 +1268,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'K': if ( (funcid= rogue_keystrokesopretdecode(gametxid,batontxid,pk,keystrokes,scriptPubKey)) != 'K' ) { - fprintf(stderr,"height.%d couldnt decode keystrokes opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode keystrokes opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode keystrokes opret"); } // validate keystrokes are from the correct pk. might need to add vin @@ -1279,8 +1278,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'H': case 'Q': if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) != funcid ) { - fprintf(stderr,"height.%d couldnt decode H/Q opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode H/Q opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode H/Q opret"); } // validation is done below @@ -1292,11 +1291,18 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } switch ( funcid ) { - case 'G': // newgame case 'R': // register - case 'K': // keystrokes + return(true); case 'H': // win case 'Q': // bailout + if ( funcid == 'Q' ) + { + + } + else + { + + } //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); return(true); break; From b4c9cbc661f35e298814b6b910c56583b421c966 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 03:59:54 -1100 Subject: [PATCH 0782/1145] Fix setpubkey crash --- src/wallet/rpcwallet.cpp | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index f945b82fc..47f7d3004 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5306,15 +5306,20 @@ UniValue setpubkey(const UniValue& params, bool fHelp) LOCK(cs_main); #endif - char Raddress[18]; + char Raddress[64]; uint8_t pubkey33[33]; - if ( NOTARY_PUBKEY33[0] == 0 ) { - if (strlen(params[0].get_str().c_str()) == 66) { + if ( NOTARY_PUBKEY33[0] == 0 ) + { + if (strlen(params[0].get_str().c_str()) == 66) + { decode_hex(pubkey33,33,(char *)params[0].get_str().c_str()); pubkey2addr((char *)Raddress,(uint8_t *)pubkey33); - if (strcmp("RRmWExvapDM9YbLT9X9xAyzDgxomYf63ng",Raddress) == 0) { + if ( 0 && strcmp("RRmWExvapDM9YbLT9X9xAyzDgxomYf63ng",Raddress) == 0) // no idea what this addr is + { result.push_back(Pair("error", "pubkey entered is invalid.")); - } else { + } + else + { CBitcoinAddress address(Raddress); bool isValid = address.IsValid(); if (isValid) @@ -5331,10 +5336,10 @@ UniValue setpubkey(const UniValue& params, bool fHelp) decode_hex(NOTARY_PUBKEY33,33,(char *)NOTARY_PUBKEY.c_str()); USE_EXTERNAL_PUBKEY = 1; } - } else { - result.push_back(Pair("error", "pubkey is wrong length, must be 66 char hex string.")); - } - } else { + } else result.push_back(Pair("error", "pubkey is wrong length, must be 66 char hex string.")); + } + else + { result.push_back(Pair("error", "Can only set pubkey once, to change it you need to restart your daemon, pubkey in use is below.")); pubkey2addr((char *)Raddress,(uint8_t *)NOTARY_PUBKEY33); std::string address_ret; address_ret.assign(Raddress); From 25acb3c52ca4246b79ddb1b3187491a8ce5d24dc Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:01:14 -1100 Subject: [PATCH 0783/1145] Fix setpubkey crash --- src/wallet/rpcwallet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index f945b82fc..6d37033d6 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5306,7 +5306,7 @@ UniValue setpubkey(const UniValue& params, bool fHelp) LOCK(cs_main); #endif - char Raddress[18]; + char Raddress[64]; uint8_t pubkey33[33]; if ( NOTARY_PUBKEY33[0] == 0 ) { if (strlen(params[0].get_str().c_str()) == 66) { From 50070c8c531bb802b58509c04b1b47882d324728 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:27:23 -1100 Subject: [PATCH 0784/1145] Verify player data --- src/cc/rogue_rpc.cpp | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 31336d8fb..08e3e27bc 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1216,6 +1216,20 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } +int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) +{ + char str[512],*keystrokes,rogueaddr[64]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 platertxid; CPubKey roguepk; + roguepk = GetUnspendable(cp,0); + GetCCaddress1of2(cp,rogueaddr,roguepk,pk); + if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) + { + if ( newdata == playerdata ) + return(0); + else fprintf(stderr,"newdata[%d] != playerdata[%d]\n",(int32_t)newdata.size(),(int32_t)playerdata.size()); + } + return(-1); +} + bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; @@ -1295,15 +1309,22 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return(true); case 'H': // win case 'Q': // bailout + // verify pk belongs to this tx + if ( playerdata.size() > 0 ) + { + if ( rogue_playerdata_validate(cp,playerdata,gametxid,pk) < 0 ) + { + fprintf(stderr,"ht.%d gametxid.%s player.%x invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),playertxid.GetHex().c_str(),(int32_t)playerdata.size()); + } else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,playertxid.GetHex().c_str()); + } if ( funcid == 'Q' ) { - + // verify vin/vout } - else + else // 'H' { - + // verify vin/vout } - //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); return(true); break; default: From f06745f9ee29533a70e19dcfac707360f0866ca3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:28:25 -1100 Subject: [PATCH 0785/1145] Formats --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 08e3e27bc..25d3c37ed 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1218,7 +1218,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { - char str[512],*keystrokes,rogueaddr[64]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 platertxid; CPubKey roguepk; + char str[512],*keystrokes,rogueaddr[64]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) @@ -1314,7 +1314,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( rogue_playerdata_validate(cp,playerdata,gametxid,pk) < 0 ) { - fprintf(stderr,"ht.%d gametxid.%s player.%x invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),playertxid.GetHex().c_str(),(int32_t)playerdata.size()); + fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),playertxid.GetHex().c_str(),(int32_t)playerdata.size()); } else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,playertxid.GetHex().c_str()); } if ( funcid == 'Q' ) From 1aae4fa9c53c6abc382182fcc96cb3e437fe49f7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:34:06 -1100 Subject: [PATCH 0786/1145] Dont deadlock in GetTransaction --- src/cc/assets.cpp | 2 +- src/cc/rogue_rpc.cpp | 24 ++++++++++++------------ 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index f42c4fda3..921d33d69 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -305,7 +305,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti return eval->Invalid("mismatched vout0 AssetsCCaddr for fillbuy"); } } - fprintf(stderr,"fillbuy validated\n"); + //fprintf(stderr,"fillbuy validated\n"); break; //case 'e': // selloffer // break; // disable swaps diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 25d3c37ed..aeb7d8228 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -265,7 +265,7 @@ int32_t rogue_iamregistered(int32_t maxplayers,uint256 gametxid,CTransaction tx, vout = i+1; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { - if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) { Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); if ( strcmp(myrogueaddr,destaddr) == 0 ) @@ -296,7 +296,7 @@ int32_t rogue_playersalive(int32_t &numplayers,uint256 gametxid,int32_t maxplaye uint64_t rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gametxid,char *myrogueaddr) { CBlockIndex *pindex; int32_t ht,delay,numplayers; uint256 hashBlock; uint64_t seed=0; char cmd[512]; CTransaction tx; - if ( GetTransaction(gametxid,tx,hashBlock,false) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) + if ( myGetTransaction(gametxid,tx,hashBlock) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) { ht = pindex->GetHeight(); delay = ROGUE_REGISTRATION * (maxplayers > 1); @@ -329,7 +329,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa { uint256 hashBlock; int32_t i,numvouts; char coinaddr[64]; CPubKey roguepk; uint64_t txfee = 10000; buyin = maxplayers = 0; - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) { gameheight = komodo_blockheight(hashBlock); if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) >= txfee && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,0) == 0 ) @@ -434,14 +434,14 @@ int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firs int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint256 &tokenid,CPubKey &pk,std::vector &playerdata,std::string &symbol,std::string &pname,uint256 playertxid) { uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; - if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) + if ( myGetTransaction(playertxid,playertx,hashBlock) != 0 && (numvouts= playertx.vout.size()) > 0 ) { if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { if ( tokenid != zeroid ) { playertxid = tokenid; - if ( GetTransaction(playertxid,playertx,hashBlock,false) == 0 || (numvouts= playertx.vout.size()) <= 0 ) + if ( myGetTransaction(playertxid,playertx,hashBlock) == 0 || (numvouts= playertx.vout.size()) <= 0 ) { fprintf(stderr,"couldnt get tokenid.%s\n",playertxid.GetHex().c_str()); return(-2); @@ -480,7 +480,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke { if ( myIsutxo_spent(spenttxid,gametxid,i+1) >= 0 ) { - if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) { numplayers++; Getscriptaddress(ccaddr,spenttx.vout[0].scriptPubKey); @@ -524,7 +524,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke txid = spenttxid; if ( spentvini != 0 ) return(-3); - if ( keystrokesp != 0 && GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() >= 2 ) + if ( keystrokesp != 0 && myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() >= 2 ) { uint256 g,b; CPubKey p; std::vector k; if ( rogue_keystrokesopretdecode(g,b,p,k,spenttx.vout[spenttx.vout.size()-1].scriptPubKey) == 'K' ) @@ -547,7 +547,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke batonvout = 0; // not vini // how to detect timeout, bailedout, highlander hashBlock = zeroid; - if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 0 ) + if ( myGetTransaction(batontxid,batontx,hashBlock) != 0 && batontx.vout.size() > 0 ) { if ( hashBlock == zeroid ) batonht = komodo_nextheight(); @@ -577,7 +577,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet destaddr[0] = 0; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { - if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); } obj.push_back(Pair("slot",(int64_t)vout-1)); @@ -585,7 +585,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet { if ( CCgettxout(gametxid,maxplayers+vout,1) == 10000 ) { - if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 1 ) + if ( myGetTransaction(batontxid,batontx,hashBlock) != 0 && batontx.vout.size() > 1 ) { if ( rogue_registeropretdecode(gtxid,tokenid,ptxid,batontx.vout[batontx.vout.size()-1].scriptPubKey) == 'R' && ptxid == playertxid && gtxid == gametxid ) obj.push_back(Pair("status","registered")); @@ -758,7 +758,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( playertxid != zeroid ) { voutPubkeysEmpty.push_back(burnpk); - if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) + if ( myGetTransaction(playertxid,playertx,hashBlock) != 0 ) { if ( (funcid= DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tid, voutPubkeys, vopretExtra)) != 0) { // if token in the opret @@ -1174,7 +1174,7 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( vout == 0 ) { - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) { if ( rogue_registeropretdecode(gametxid,tokenid,playertxid,tx.vout[numvouts-1].scriptPubKey) == 'R' ) { From bc1e1418ea44884427d17ebc86b3cc580f52f489 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:42:16 -1100 Subject: [PATCH 0787/1145] Set funcid --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index aeb7d8228..a932a8151 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1247,7 +1247,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( (funcid= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) == 0 ) { - if ( (f= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) + if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) { fprintf(stderr,"ht.%d couldnt decode tokens opret (%c)\n",height,script[1]); } else e = EVAL_ROGUE, decoded = 1; From 7d97a0ef0317130b4e4182a40fe4f058d563d818 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:45:44 -1100 Subject: [PATCH 0788/1145] +prints --- src/cc/rogue_rpc.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index a932a8151..ee67d04b6 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -828,13 +828,15 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat roguepk = GetUnspendable(cp,0); *numkeysp = 0; seed = 0; + fprintf(stderr,"calling validgame\n"); if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) { + fprintf(stderr,"calling baton\n"); if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,rogueaddr,numplayers,symbol,pname) == 0 ) { UniValue obj; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); - //fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -872,8 +874,8 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); fprintf(stderr,"%s\n",str); } else num = 0; - } - } + } else fprintf(stderr,"extractgame: couldnt find baton\n"); + } else fprintf(stderr,"extractgame: invalid game\n"); *numkeysp = numkeys; return(keystrokes); } @@ -1221,8 +1223,11 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); + fprintf(stderr,"call extractgame\n"); if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) { + free(keystrokes); + fprintf(stderr,"extracted.(%s)\n",str); if ( newdata == playerdata ) return(0); else fprintf(stderr,"newdata[%d] != playerdata[%d]\n",(int32_t)newdata.size(),(int32_t)playerdata.size()); From 667d50cea019a269a37df03137df3ed0b6312533 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 04:59:33 -1100 Subject: [PATCH 0789/1145] Prints --- src/cc/rogue_rpc.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ee67d04b6..46446a883 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -478,6 +478,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke playertxid = zeroid; for (i=0; i= 0 ) { if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) @@ -489,26 +490,26 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke matches++; regslot = i; matchtx = spenttx; - } //else fprintf(stderr,"%d+1 doesnt match %s vs %s\n",i,ccaddr,destaddr); - } //else fprintf(stderr,"%d+1 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); - } //else fprintf(stderr,"%d+1 unspent\n",i); + } else fprintf(stderr,"%d+1 doesnt match %s vs %s\n",i,ccaddr,destaddr); + } else fprintf(stderr,"%d+1 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); + } else fprintf(stderr,"%d+1 unspent\n",i); } if ( matches == 1 ) { if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); - //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); + fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { - //fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); + fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); if ( tokenid != zeroid ) active = tokenid; else active = playertxid; if ( active == zeroid || rogue_playerdata(cp,origplayergame,tid,pk,playerdata,symbol,pname,active) == 0 ) { txid = matchtx.GetHash(); - //fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); + fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); n = 0; while ( CCgettxout(txid,0,1) < 0 ) { @@ -541,8 +542,9 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke fprintf(stderr,"rogue_findbaton n.%d, seems something is wrong\n",n); return(-5); } + fprintf(stderr,"n.%d txid.%s\n",n,txid.GetHex().c_str()); } - //fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); + fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); batontxid = txid; batonvout = 0; // not vini // how to detect timeout, bailedout, highlander @@ -555,7 +557,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke return(-4); else batonht = pindex->GetHeight(); batonvalue = batontx.vout[0].nValue; - //printf("keystrokes[%d]\n",numkeys); + printf("keystrokes[%d]\n",numkeys); return(0); } } From 7cced97fb91e24a8e7016d926ec04b5288e1e775 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:08:49 -1100 Subject: [PATCH 0790/1145] +print --- src/cc/rogue_rpc.cpp | 5 +++-- src/komodo_bitcoind.h | 6 +++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 46446a883..b5e669237 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -557,9 +557,9 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke return(-4); else batonht = pindex->GetHeight(); batonvalue = batontx.vout[0].nValue; - printf("keystrokes[%d]\n",numkeys); + printf("batonht.%d keystrokes[%d]\n",batonht,numkeys); return(0); - } + } else fprintf(stderr,"couldnt find baton\n"); } } else fprintf(stderr,"findbaton opret error\n"); } @@ -837,6 +837,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,rogueaddr,numplayers,symbol,pname) == 0 ) { UniValue obj; + fprintf(stderr,"calling gamefields\n"); seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); diff --git a/src/komodo_bitcoind.h b/src/komodo_bitcoind.h index 68250e6cf..6cc7dc427 100644 --- a/src/komodo_bitcoind.h +++ b/src/komodo_bitcoind.h @@ -1127,10 +1127,10 @@ uint64_t komodo_accrued_interest(int32_t *txheightp,uint32_t *locktimep,uint256 int32_t komodo_nextheight() { - CBlockIndex *pindex; int32_t ht,longest = komodo_longestchain(); - if ( (pindex= chainActive.LastTip()) != 0 && (ht= pindex->GetHeight()) >= longest ) + CBlockIndex *pindex; int32_t ht; + if ( (pindex= chainActive.LastTip()) != 0 && (ht= pindex->GetHeight()) > 0 ) return(ht+1); - else return(longest + 1); + else return(komodo_longestchain() + 1); } int32_t komodo_isrealtime(int32_t *kmdheightp) From 726a46027aa156ba1a216f9650f24e49f55af031 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:27:51 -1100 Subject: [PATCH 0791/1145] Init pack --- src/cc/rogue/init.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index 1a5faa9ce..30370f958 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -24,7 +24,7 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item); void restore_player(struct rogue_state *rs) { - int32_t i; THING *obj; + int32_t i,total = 0; THING *obj; //rs->P.gold = purse; max_hp = rs->P.hitpoints; pstats.s_str = rs->P.strength & 0xffff; @@ -34,10 +34,13 @@ void restore_player(struct rogue_state *rs) pstats.s_str = max_stats.s_str; pstats.s_lvl = rs->P.level; pstats.s_exp = rs->P.experience; - for (i=0; iP.packsize; i++) + for (i=0; iP.packsize&&iP.roguepack[i]); + total += obj->o_count; + if ( total > pstats.s_str*3 ) + break; add_pack(rs,obj,TRUE); } } From a0e262832560685a38338834e3f28661c3813f82 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:29:01 -1100 Subject: [PATCH 0792/1145] Init pack with strength limit --- src/cc/rogue/init.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index 1a5faa9ce..30370f958 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -24,7 +24,7 @@ void rogue_restoreobject(THING *o,struct rogue_packitem *item); void restore_player(struct rogue_state *rs) { - int32_t i; THING *obj; + int32_t i,total = 0; THING *obj; //rs->P.gold = purse; max_hp = rs->P.hitpoints; pstats.s_str = rs->P.strength & 0xffff; @@ -34,10 +34,13 @@ void restore_player(struct rogue_state *rs) pstats.s_str = max_stats.s_str; pstats.s_lvl = rs->P.level; pstats.s_exp = rs->P.experience; - for (i=0; iP.packsize; i++) + for (i=0; iP.packsize&&iP.roguepack[i]); + total += obj->o_count; + if ( total > pstats.s_str*3 ) + break; add_pack(rs,obj,TRUE); } } From bda6c83b969400a9226288a3d33f008e31f8ec8d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:39:28 -1100 Subject: [PATCH 0793/1145] +print --- src/cc/rogue/cursesd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 02a80c470..30cc54ec9 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -162,7 +162,7 @@ int32_t mvaddch(int32_t y, int32_t x, chtype ch) int32_t waddstr(WINDOW *win, const char *str) { int32_t i; - //fprintf(stderr,"%s\n",str); + fprintf(stderr,"%s\n",str); for (i=0; str[i]!=0; i++) waddch(win,str[i]); return(0); From 4ba765895cb3a12e3e5dbc692616c12c7f0cb62a Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:42:02 -1100 Subject: [PATCH 0794/1145] Fix dereference --- src/cc/rogue/rogue.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index c2f1d9829..2393b0ced 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -238,7 +238,7 @@ void rogue_bailout(struct rogue_state *rs) int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis) { - struct rogue_state *rs; FILE *fp; int32_t i; + struct rogue_state *rs; FILE *fp; int32_t i,n; rs = (struct rogue_state *)calloc(1,sizeof(*rs)); rs->seed = seed; rs->keystrokes = keystrokes; @@ -248,7 +248,9 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu { rs->P = *player; rs->restoring = 1; - //fprintf(stderr,"restore player packsize.%d HP.%d\n",rs->P.packsize,rs->P.hitpoints); + fprintf(stderr,"restore player packsize.%d HP.%d\n",rs->P.packsize,rs->P.hitpoints); + if ( rs->P.packsize > MAXPACK ) + rs->P.packsize = MAXPACK; } globalR = *rs; uint32_t starttime = (uint32_t)time(NULL); @@ -278,8 +280,9 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu if ( newdata != 0 && rs->playersize > 0 ) memcpy(newdata,rs->playerdata,rs->playersize); } + n = rs->playsize; free(rs); - return(rs->playersize); + return(n); } #endif From c0bdecef07107470c479b7c3c8c9efbc67b18d0f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:42:57 -1100 Subject: [PATCH 0795/1145] Er --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 2393b0ced..cbcc67afd 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -280,7 +280,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu if ( newdata != 0 && rs->playersize > 0 ) memcpy(newdata,rs->playerdata,rs->playersize); } - n = rs->playsize; + n = rs->playersize; free(rs); return(n); } From 20402a3a01bb80098e5e600dfde91a90871ea99c Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 05:53:41 -1100 Subject: [PATCH 0796/1145] New unctrl --- src/cc/rogue/cursesd.c | 7 +++++++ src/cc/rogue/cursesd.h | 3 ++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 30cc54ec9..ab57e2107 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -422,3 +422,10 @@ int32_t md_readchar(void) return(0); } +char *unctrl(char c) +{ + static char ctrlstr[3]; + ctrlstr[0] = '^'; + ctrlstr[1] = 'a' + c; + return(ctrlstr); +} diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 4fa09e9d9..87304cfa6 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -123,9 +123,10 @@ int32_t wprintw(WINDOW *win,char *fmt,...); int32_t mvprintw(int32_t y,int32_t x,char *fmt,...); int32_t mvwprintw(WINDOW *win,int32_t y,int32_t x,char *fmt,...); +char *unctrl(char c); + #define A_CHARTEXT 0xff #define baudrate() 9600 -#define unctrl(a) "^x" #define getmaxx(a) COLS #define getmaxy(a) LINES #define getyx(win,_argfory,_argforx) _argfory = win->y, _argforx = win->x From 92e136108c905aa6f776f235f97849d20065a481 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:00:56 -1100 Subject: [PATCH 0797/1145] ^%% --- src/cc/rogue/cursesd.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index ab57e2107..102e2bd7b 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -424,8 +424,7 @@ int32_t md_readchar(void) char *unctrl(char c) { - static char ctrlstr[3]; - ctrlstr[0] = '^'; - ctrlstr[1] = 'a' + c; + static char ctrlstr[5]; + sprintf(ctrlstr,"^%%%02x",c); return(ctrlstr); } From 12c97d71a744c7d458815fcdafd326b14dabedf1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:06:47 -1100 Subject: [PATCH 0798/1145] Dont loop on bad item select --- src/cc/rogue/pack.c | 106 +++++++++++++++++++++++--------------------- 1 file changed, 55 insertions(+), 51 deletions(-) diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index d482a8a52..e4ceee689 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -410,59 +410,63 @@ get_item(struct rogue_state *rs,char *purpose, int type) { THING *obj; char ch; - + if (pack == NULL) - msg(rs,"you aren't carrying anything"); + msg(rs,"you aren't carrying anything"); else if (again) - if (last_pick) - return last_pick; - else - msg(rs,"you ran out"); - else - { - for (;;) - { - if (!terse) - addmsg(rs,"which object do you want to "); - addmsg(rs,purpose); - if (terse) - addmsg(rs," what"); - msg(rs,"? (* for list): "); - ch = readchar(rs); - mpos = 0; - /* - * Give the poor player a chance to abort the command - */ - if (ch == ESCAPE) - { - reset_last(); - after = FALSE; - msg(rs,""); - return NULL; - } - n_objs = 1; /* normal case: person types one char */ - if (ch == '*') - { - mpos = 0; - if (inventory(rs,pack, type) == 0) - { - after = FALSE; - return NULL; - } - continue; - } - for (obj = pack; obj != NULL; obj = next(obj)) - if (obj->o_packch == ch) - break; - if (obj == NULL) - { - msg(rs,"'%s' is not a valid item",unctrl(ch)); - continue; - } - else - return obj; - } - } + if (last_pick) + return last_pick; + else + msg(rs,"you ran out"); + else + { + for (;;) + { + if (!terse) + addmsg(rs,"which object do you want to "); + addmsg(rs,purpose); + if (terse) + addmsg(rs," what"); + msg(rs,"? (* for list): "); + ch = readchar(rs); + mpos = 0; + /* + * Give the poor player a chance to abort the command + */ + if (ch == ESCAPE) + { + reset_last(); + after = FALSE; + msg(rs,""); + return NULL; + } + n_objs = 1; /* normal case: person types one char */ + if (ch == '*') + { + mpos = 0; + if (inventory(rs,pack, type) == 0) + { + after = FALSE; + return NULL; + } + continue; + } + for (obj = pack; obj != NULL; obj = next(obj)) + if (obj->o_packch == ch) + break; + if (obj == NULL) + { + //msg(rs,"'%s' is not a valid item",unctrl(ch)); + //continue; + reset_last(); + after = FALSE; + msg(rs,"'%s' is not a valid item",unctrl(ch)); + return NULL; + } + else + return obj; + } + } return NULL; } From 5e543b34032b9d8e7a1833cf9ce9baf1e9e47001 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:12:46 -1100 Subject: [PATCH 0799/1145] <30000 --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b5e669237..499f7fcda 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1241,7 +1241,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; - if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 20000 ) + if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 30000 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) { From a9d9c7599dacc9fa962b33700cd84b47861a3537 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 18:14:32 +0100 Subject: [PATCH 0800/1145] Update Makefile_rogue --- src/cc/Makefile_rogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 7fb3f799f..543ab2895 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -4,7 +4,7 @@ CC_DARWIN = g++-6 CC_WIN = x86_64-w64-mingw32-gcc-posix CFLAGS_DARWIN = -DBUILD_ROGUE -std=c++11 -arch x86_64 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -Wl,-undefined -Wl,dynamic_lookup -Wno-write-strings -shared -dynamiclib CFLAGS = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared +CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/x86_64-w64-mingw32/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared DEBUGFLAGS = -O0 -D _DEBUG RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program $(info $(OS)) From beb670166961a6d7f5f55e07d952333d27ba2a27 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:17:07 -1100 Subject: [PATCH 0801/1145] -print --- src/cc/rogue/cursesd.c | 2 +- src/cc/rogue_rpc.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 102e2bd7b..202cc4acb 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -162,7 +162,7 @@ int32_t mvaddch(int32_t y, int32_t x, chtype ch) int32_t waddstr(WINDOW *win, const char *str) { int32_t i; - fprintf(stderr,"%s\n",str); + //fprintf(stderr,"%s\n",str); for (i=0; str[i]!=0; i++) waddch(win,str[i]); return(0); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 499f7fcda..b5e669237 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1241,7 +1241,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; - if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 30000 ) + if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 20000 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) { From 82f46bd36fbbdb16e0bb2718bb132ff3b02e5057 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:22:01 -1100 Subject: [PATCH 0802/1145] -print --- src/cc/rogue_rpc.cpp | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b5e669237..694464c05 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -478,7 +478,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke playertxid = zeroid; for (i=0; i= 0 ) { if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) @@ -490,26 +490,26 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke matches++; regslot = i; matchtx = spenttx; - } else fprintf(stderr,"%d+1 doesnt match %s vs %s\n",i,ccaddr,destaddr); - } else fprintf(stderr,"%d+1 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); - } else fprintf(stderr,"%d+1 unspent\n",i); + } //else fprintf(stderr,"%d+1 doesnt match %s vs %s\n",i,ccaddr,destaddr); + } //else fprintf(stderr,"%d+1 couldnt find spenttx.%s\n",i,spenttxid.GetHex().c_str()); + } //else fprintf(stderr,"%d+1 unspent\n",i); } if ( matches == 1 ) { if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); - fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); + //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { - fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); + //fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); if ( tokenid != zeroid ) active = tokenid; else active = playertxid; if ( active == zeroid || rogue_playerdata(cp,origplayergame,tid,pk,playerdata,symbol,pname,active) == 0 ) { txid = matchtx.GetHash(); - fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); + //fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); n = 0; while ( CCgettxout(txid,0,1) < 0 ) { @@ -542,9 +542,9 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke fprintf(stderr,"rogue_findbaton n.%d, seems something is wrong\n",n); return(-5); } - fprintf(stderr,"n.%d txid.%s\n",n,txid.GetHex().c_str()); + //fprintf(stderr,"n.%d txid.%s\n",n,txid.GetHex().c_str()); } - fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); + //fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); batontxid = txid; batonvout = 0; // not vini // how to detect timeout, bailedout, highlander @@ -557,7 +557,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke return(-4); else batonht = pindex->GetHeight(); batonvalue = batontx.vout[0].nValue; - printf("batonht.%d keystrokes[%d]\n",batonht,numkeys); + //printf("batonht.%d keystrokes[%d]\n",batonht,numkeys); return(0); } else fprintf(stderr,"couldnt find baton\n"); } @@ -830,16 +830,13 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat roguepk = GetUnspendable(cp,0); *numkeysp = 0; seed = 0; - fprintf(stderr,"calling validgame\n"); if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) { - fprintf(stderr,"calling baton\n"); if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,rogueaddr,numplayers,symbol,pname) == 0 ) { UniValue obj; - fprintf(stderr,"calling gamefields\n"); seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); - fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + //fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { From 4b966a1b3d3ca7f026b3255ed8ada2efb09a9ac6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:26:17 -1100 Subject: [PATCH 0803/1145] -print --- src/cc/rogue/rogue.c | 2 +- src/cc/rogue_rpc.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index cbcc67afd..21c229860 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -248,7 +248,7 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu { rs->P = *player; rs->restoring = 1; - fprintf(stderr,"restore player packsize.%d HP.%d\n",rs->P.packsize,rs->P.hitpoints); + //fprintf(stderr,"restore player packsize.%d HP.%d\n",rs->P.packsize,rs->P.hitpoints); if ( rs->P.packsize > MAXPACK ) rs->P.packsize = MAXPACK; } diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 694464c05..f4081330b 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1223,14 +1223,14 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); - fprintf(stderr,"call extractgame\n"); + //fprintf(stderr,"call extractgame\n"); if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) { free(keystrokes); - fprintf(stderr,"extracted.(%s)\n",str); + //fprintf(stderr,"extracted.(%s)\n",str); if ( newdata == playerdata ) return(0); - else fprintf(stderr,"newdata[%d] != playerdata[%d]\n",(int32_t)newdata.size(),(int32_t)playerdata.size()); + else fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys); } return(-1); } From 09e17f4c5fcbe21290b4d0a054a2d8f3146a2c85 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:35:52 -1100 Subject: [PATCH 0804/1145] Playertxid --- src/cc/rogue_rpc.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f4081330b..6618d62a8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -502,7 +502,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { - //fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); + fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); if ( tokenid != zeroid ) active = tokenid; else active = playertxid; @@ -1220,7 +1220,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { - char str[512],*keystrokes,rogueaddr[64]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); @@ -1230,7 +1230,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector Date: Mon, 18 Feb 2019 06:42:03 -1100 Subject: [PATCH 0805/1145] +prints --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 6618d62a8..3c7ce393e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -499,7 +499,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); - //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); + fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); @@ -560,7 +560,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke //printf("batonht.%d keystrokes[%d]\n",batonht,numkeys); return(0); } else fprintf(stderr,"couldnt find baton\n"); - } + } else fprintf(stderr,"error with playerdata\n"); } else fprintf(stderr,"findbaton opret error\n"); } else From 31a18239da2ab69cbb4ad37f8610e9161e5592e9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:42:41 -1100 Subject: [PATCH 0806/1145] Ptr --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3c7ce393e..3da4b5977 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1230,7 +1230,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector Date: Mon, 18 Feb 2019 06:43:17 -1100 Subject: [PATCH 0807/1145] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3da4b5977..a11319daa 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1230,7 +1230,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector Date: Mon, 18 Feb 2019 18:47:07 +0100 Subject: [PATCH 0808/1145] update win makefile --- zcutil/build-win.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zcutil/build-win.sh b/zcutil/build-win.sh index ef0c09549..8cf1751af 100755 --- a/zcutil/build-win.sh +++ b/zcutil/build-win.sh @@ -1,5 +1,5 @@ #!/bin/bash -HOST=x86_64-w64-mingw32 +export HOST=x86_64-w64-mingw32 CXX=x86_64-w64-mingw32-g++-posix CC=x86_64-w64-mingw32-gcc-posix PREFIX="$(pwd)/depends/$HOST" From 3b0f836867283e68528b7bebd7632ac760bd0554 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:51:31 -1100 Subject: [PATCH 0809/1145] Prints --- src/cc/rogue_rpc.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index a11319daa..c3016c356 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -836,7 +836,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat { UniValue obj; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); - //fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d playertxid.%s\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size(),playertxid.GetHex().c_str()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -1220,7 +1220,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { - char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; struct rogue_player P; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); @@ -1230,7 +1230,14 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector no playerdata\n"); + } + fprintf(stderr,"playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); + fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str()); } return(-1); } From 0d644e8be0518a2f54e732e6df27eb731f1dd2a2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:52:11 -1100 Subject: [PATCH 0810/1145] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c3016c356..5c149e19e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1220,7 +1220,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { - char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; struct rogue_player P; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; struct rogue_player P; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); From f70593d5fbe61a79eb16aff958da2f72c2610b57 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 06:52:44 -1100 Subject: [PATCH 0811/1145] Size --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5c149e19e..424799597 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1230,7 +1230,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector Date: Mon, 18 Feb 2019 07:02:58 -1100 Subject: [PATCH 0812/1145] Clear maxstre --- src/cc/rogue_rpc.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 424799597..1a60bc268 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1220,6 +1220,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { + static uint32_t good,bad; char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; struct rogue_player P; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); @@ -1229,7 +1230,18 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector no playerdata\n"); } fprintf(stderr,"playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); - fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str()); + fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str()); } return(-1); } From 9ff01f928fa9fcc3f6971b9b162011d6c5a1041e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:04:51 -1100 Subject: [PATCH 0813/1145] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1a60bc268..3730d2aa2 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1249,7 +1249,7 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector no playerdata\n"); } fprintf(stderr,"playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); - fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str()); + fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); } return(-1); } From 68cd9e8792e742817c5c9ddcba8592e84dfb20ce Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:15:34 -1100 Subject: [PATCH 0814/1145] Test --- src/cc/rogue_rpc.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3730d2aa2..581603889 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1218,10 +1218,10 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } -int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) +int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { static uint32_t good,bad; - char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; uint256 playertxid; CPubKey roguepk; struct rogue_player P; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; CPubKey roguepk; struct rogue_player P; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); @@ -1232,13 +1232,14 @@ int32_t rogue_playerdata_validate(struct CCcontract_info *cp,std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 20000 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) @@ -1336,10 +1337,10 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C // verify pk belongs to this tx if ( playerdata.size() > 0 ) { - if ( rogue_playerdata_validate(cp,playerdata,gametxid,pk) < 0 ) + if ( rogue_playerdata_validate(ptxid,cp,playerdata,gametxid,pk) < 0 ) { - fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),playertxid.GetHex().c_str(),(int32_t)playerdata.size()); - } else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,playertxid.GetHex().c_str()); + fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); + } else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,ptxid.GetHex().c_str()); } if ( funcid == 'Q' ) { From 3c9f9ce5542383ef69ac90dedd8c6937676d0f87 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:24:05 -1100 Subject: [PATCH 0815/1145] -prints --- src/cc/rogue/rogue.c | 2 +- src/cc/rogue_rpc.cpp | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 21c229860..786718039 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -650,7 +650,7 @@ int32_t _quit() } else { - fprintf(stderr,"'Q' answer (%c)\n",c); + //fprintf(stderr,"'Q' answer (%c)\n",c); move(0, 0); clrtoeol(); status(rs); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 581603889..cf8e3feed 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -499,10 +499,10 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); - fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); + //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); if ( rogue_registeropretdecode(txid,tokenid,playertxid,matchtx.vout[numvouts-1].scriptPubKey) == 'R' )//&& txid == gametxid ) { - fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); + //fprintf(stderr,"tokenid.%s txid.%s vs gametxid.%s player.%s\n",tokenid.GetHex().c_str(),txid.GetHex().c_str(),gametxid.GetHex().c_str(),playertxid.GetHex().c_str()); if ( tokenid != zeroid ) active = tokenid; else active = playertxid; @@ -836,7 +836,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat { UniValue obj; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); - fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d playertxid.%s\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size(),playertxid.GetHex().c_str()); + //fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d playertxid.%s\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size(),playertxid.GetHex().c_str()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -1339,8 +1339,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( rogue_playerdata_validate(ptxid,cp,playerdata,gametxid,pk) < 0 ) { - fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); - } else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,ptxid.GetHex().c_str()); + //fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); + } //else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,ptxid.GetHex().c_str()); } if ( funcid == 'Q' ) { From 84dacb5ff8c0c8fdd6db19ae7da1cd54ab65b3b7 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 19:31:49 +0100 Subject: [PATCH 0816/1145] update Makefile_rogue --- src/cc/Makefile_rogue | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 543ab2895..45efdc803 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -23,14 +23,15 @@ $(TARGET): $(SOURCES) ifeq ($(OS),Darwin) $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET_DARWIN) -c $(SOURCES) -lncurses cp $(TARGET_DARWIN) ../libcc.dylib -else ifeq ($(OS),Linux) - $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) -lncurses - cp $(TARGET) ../libcc.so -#else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host -else +else ifeq ($(HOST),x86_64-w64-mingw32) $(info WINDOWS) $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses - cp $(TARGET_WIN) ../libcc.dll + cp $(TARGET_WIN) ../libcc.dll +#else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host +else + $(info LINUX) + $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) -lncurses + cp $(TARGET) ../libcc.so endif clean: From 7e3a9acab7578eef88e3d507279ae94f8944d84f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:32:50 -1100 Subject: [PATCH 0817/1145] +gametxid --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index cf8e3feed..45e67d286 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1232,14 +1232,14 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp if ( newdata == playerdata ) { good++; - fprintf(stderr,"good.%d bad.%d\n",good,bad); + fprintf(stderr,"%s good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); return(0); } newdata[10] = newdata[11] = playerdata[10] = playerdata[11] = 0; if ( newdata == playerdata ) { good++; - fprintf(stderr,"matched after clearing maxstrength good.%d bad.%d\n",good,bad); + fprintf(stderr,"%s matched after clearing maxstrength good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); return(0); } bad++; From 5bb65c9e8bb34c78bbf9df6dbd0850afd8fbd92a Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:35:29 -1100 Subject: [PATCH 0818/1145] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 45e67d286..9c4463930 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1258,7 +1258,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; - if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 20000 ) + if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) { From 7b43e451d0b1a1003be23f031b58b8df0b60a54b Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:39:50 -1100 Subject: [PATCH 0819/1145] -print --- src/cc/assets.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/assets.cpp b/src/cc/assets.cpp index 921d33d69..6e3fd5909 100644 --- a/src/cc/assets.cpp +++ b/src/cc/assets.cpp @@ -259,7 +259,7 @@ bool AssetsValidate(struct CCcontract_info *cpAssets,Eval* eval,const CTransacti return eval->Invalid("invalid refund for cancelbuy"); preventCCvins = 3; preventCCvouts = 0; - fprintf(stderr,"cancelbuy validated to origaddr.(%s)\n",origNormalAddr); + //fprintf(stderr,"cancelbuy validated to origaddr.(%s)\n",origNormalAddr); break; case 'B': // fillbuy: From 6019a16cf161eddb3c4e6901dd9bfcfe3cb4bff7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 07:46:03 -1100 Subject: [PATCH 0820/1145] Test --- src/cc/rogue_rpc.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9c4463930..d74bc9619 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1220,8 +1220,11 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { - static uint32_t good,bad; + static uint32_t good,bad; static uint256 prevgame; char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; CPubKey roguepk; struct rogue_player P; + if ( gametxid == prevgame ) + return(0); + prevgame = gametxid; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); @@ -1249,7 +1252,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp { fprintf(stderr,"zero value character was killed -> no playerdata\n"); } - fprintf(stderr,"playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); + fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); } return(-1); From 8ac6e7458b2a3ffd982c2d3dd4151e63b9a17f9d Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 20:55:08 +0100 Subject: [PATCH 0821/1145] test --- src/cc/rogue/mdport.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index 9d6c7d2c6..f87650f38 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -33,7 +33,7 @@ #include #if defined(_WIN32) -#include +#include #include #include #include From 846e102e7b9b4774552ab05dabe4b319974b4772 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 22:13:28 +0100 Subject: [PATCH 0822/1145] fix --- src/cc/rogue/mdport.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index f87650f38..d9c4e9c21 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -34,7 +34,7 @@ #if defined(_WIN32) #include -#include +#include #include #include #pragma warning( disable: 4201 ) From 10dfaedb062d1c7a8520d41a3ae9c5d72f8695d2 Mon Sep 17 00:00:00 2001 From: ca333 Date: Mon, 18 Feb 2019 23:23:26 +0100 Subject: [PATCH 0823/1145] fix --- src/cc/rogue/mdport.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index d9c4e9c21..988e1c7b7 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -40,7 +40,7 @@ #pragma warning( disable: 4201 ) #include #pragma warning( default: 4201 ) -#include +#include #undef MOUSE_MOVED #endif From 640f3e0699cfd2d93c6ceb7a2c6977a0d7bb5bbe Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 00:15:41 +0100 Subject: [PATCH 0824/1145] resolve conflict --- src/cc/rogue_rpc.cpp | 121 +++++++++++++++++++++++++++++++------------ 1 file changed, 88 insertions(+), 33 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ef24489ba..d74bc9619 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -265,7 +265,7 @@ int32_t rogue_iamregistered(int32_t maxplayers,uint256 gametxid,CTransaction tx, vout = i+1; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { - if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) { Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); if ( strcmp(myrogueaddr,destaddr) == 0 ) @@ -296,7 +296,7 @@ int32_t rogue_playersalive(int32_t &numplayers,uint256 gametxid,int32_t maxplaye uint64_t rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 gametxid,char *myrogueaddr) { CBlockIndex *pindex; int32_t ht,delay,numplayers; uint256 hashBlock; uint64_t seed=0; char cmd[512]; CTransaction tx; - if ( GetTransaction(gametxid,tx,hashBlock,false) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) + if ( myGetTransaction(gametxid,tx,hashBlock) != 0 && (pindex= komodo_blockindex(hashBlock)) != 0 ) { ht = pindex->GetHeight(); delay = ROGUE_REGISTRATION * (maxplayers > 1); @@ -329,7 +329,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa { uint256 hashBlock; int32_t i,numvouts; char coinaddr[64]; CPubKey roguepk; uint64_t txfee = 10000; buyin = maxplayers = 0; - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) { gameheight = komodo_blockheight(hashBlock); if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) >= txfee && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,0) == 0 ) @@ -434,14 +434,14 @@ int32_t rogue_iterateplayer(uint256 ®istertxid,uint256 firsttxid,int32_t firs int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint256 &tokenid,CPubKey &pk,std::vector &playerdata,std::string &symbol,std::string &pname,uint256 playertxid) { uint256 origplayertxid,hashBlock,gametxid,registertxid; CTransaction gametx,playertx,highlandertx; std::vector vopret; uint8_t *script,e,f; int32_t i,regslot,gameheight,numvouts,maxplayers; int64_t buyin; - if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 && (numvouts= playertx.vout.size()) > 0 ) + if ( myGetTransaction(playertxid,playertx,hashBlock) != 0 && (numvouts= playertx.vout.size()) > 0 ) { if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,playertx.vout[numvouts-1].scriptPubKey)) == 'H' || f == 'Q' ) { if ( tokenid != zeroid ) { playertxid = tokenid; - if ( GetTransaction(playertxid,playertx,hashBlock,false) == 0 || (numvouts= playertx.vout.size()) <= 0 ) + if ( myGetTransaction(playertxid,playertx,hashBlock) == 0 || (numvouts= playertx.vout.size()) <= 0 ) { fprintf(stderr,"couldnt get tokenid.%s\n",playertxid.GetHex().c_str()); return(-2); @@ -478,9 +478,10 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke playertxid = zeroid; for (i=0; i= 0 ) { - if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) { numplayers++; Getscriptaddress(ccaddr,spenttx.vout[0].scriptPubKey); @@ -524,7 +525,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke txid = spenttxid; if ( spentvini != 0 ) return(-3); - if ( keystrokesp != 0 && GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() >= 2 ) + if ( keystrokesp != 0 && myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() >= 2 ) { uint256 g,b; CPubKey p; std::vector k; if ( rogue_keystrokesopretdecode(g,b,p,k,spenttx.vout[spenttx.vout.size()-1].scriptPubKey) == 'K' ) @@ -541,13 +542,14 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke fprintf(stderr,"rogue_findbaton n.%d, seems something is wrong\n",n); return(-5); } + //fprintf(stderr,"n.%d txid.%s\n",n,txid.GetHex().c_str()); } //fprintf(stderr,"set baton %s\n",txid.GetHex().c_str()); batontxid = txid; batonvout = 0; // not vini // how to detect timeout, bailedout, highlander hashBlock = zeroid; - if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 0 ) + if ( myGetTransaction(batontxid,batontx,hashBlock) != 0 && batontx.vout.size() > 0 ) { if ( hashBlock == zeroid ) batonht = komodo_nextheight(); @@ -555,10 +557,10 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke return(-4); else batonht = pindex->GetHeight(); batonvalue = batontx.vout[0].nValue; - //printf("keystrokes[%d]\n",numkeys); + //printf("batonht.%d keystrokes[%d]\n",batonht,numkeys); return(0); - } - } + } else fprintf(stderr,"couldnt find baton\n"); + } else fprintf(stderr,"error with playerdata\n"); } else fprintf(stderr,"findbaton opret error\n"); } else @@ -577,7 +579,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet destaddr[0] = 0; if ( myIsutxo_spent(spenttxid,gametxid,vout) >= 0 ) { - if ( GetTransaction(spenttxid,spenttx,hashBlock,false) != 0 && spenttx.vout.size() > 0 ) + if ( myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() > 0 ) Getscriptaddress(destaddr,spenttx.vout[0].scriptPubKey); } obj.push_back(Pair("slot",(int64_t)vout-1)); @@ -585,7 +587,7 @@ void rogue_gameplayerinfo(struct CCcontract_info *cp,UniValue &obj,uint256 gamet { if ( CCgettxout(gametxid,maxplayers+vout,1) == 10000 ) { - if ( GetTransaction(batontxid,batontx,hashBlock,false) != 0 && batontx.vout.size() > 1 ) + if ( myGetTransaction(batontxid,batontx,hashBlock) != 0 && batontx.vout.size() > 1 ) { if ( rogue_registeropretdecode(gtxid,tokenid,ptxid,batontx.vout[batontx.vout.size()-1].scriptPubKey) == 'R' && ptxid == playertxid && gtxid == gametxid ) obj.push_back(Pair("status","registered")); @@ -758,7 +760,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( playertxid != zeroid ) { voutPubkeysEmpty.push_back(burnpk); - if ( GetTransaction(playertxid,playertx,hashBlock,false) != 0 ) + if ( myGetTransaction(playertxid,playertx,hashBlock) != 0 ) { if ( (funcid= DecodeTokenOpRet(playertx.vout.back().scriptPubKey, e, tid, voutPubkeys, vopretExtra)) != 0) { // if token in the opret @@ -834,7 +836,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat { UniValue obj; seed = rogue_gamefields(obj,maxplayers,buyin,gametxid,rogueaddr); - //fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size()); + //fprintf(stderr,"(%s) found baton %s numkeys.%d seed.%llu playerdata.%d playertxid.%s\n",pname.size()!=0?pname.c_str():Rogue_pname.c_str(),batontxid.ToString().c_str(),numkeys,(long long)seed,(int32_t)playerdata.size(),playertxid.GetHex().c_str()); memset(&P,0,sizeof(P)); if ( playerdata.size() > 0 ) { @@ -872,8 +874,8 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); fprintf(stderr,"%s\n",str); } else num = 0; - } - } + } else fprintf(stderr,"extractgame: couldnt find baton\n"); + } else fprintf(stderr,"extractgame: invalid game\n"); *numkeysp = numkeys; return(keystrokes); } @@ -1174,7 +1176,7 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( vout == 0 ) { - if ( GetTransaction(txid,tx,hashBlock,false) != 0 && (numvouts= tx.vout.size()) > 1 ) + if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) { if ( rogue_registeropretdecode(gametxid,tokenid,playertxid,tx.vout[numvouts-1].scriptPubKey) == 'R' ) { @@ -1216,9 +1218,51 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } +int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) +{ + static uint32_t good,bad; static uint256 prevgame; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; CPubKey roguepk; struct rogue_player P; + if ( gametxid == prevgame ) + return(0); + prevgame = gametxid; + roguepk = GetUnspendable(cp,0); + GetCCaddress1of2(cp,rogueaddr,roguepk,pk); + //fprintf(stderr,"call extractgame\n"); + if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) + { + free(keystrokes); + //fprintf(stderr,"extracted.(%s)\n",str); + if ( newdata == playerdata ) + { + good++; + fprintf(stderr,"%s good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); + return(0); + } + newdata[10] = newdata[11] = playerdata[10] = playerdata[11] = 0; + if ( newdata == playerdata ) + { + good++; + fprintf(stderr,"%s matched after clearing maxstrength good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); + return(0); + } + bad++; + for (i=0; i no playerdata\n"); + } + fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); + fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); + } + return(-1); +} + bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) + return(true); if ( (numvouts= tx.vout.size()) > 1 ) { scriptPubKey = tx.vout[numvouts-1].scriptPubKey; @@ -1233,10 +1277,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) { - funcid = 'Q'; fprintf(stderr,"ht.%d couldnt decode tokens opret (%c)\n",height,script[1]); - if ( height < 20000 ) - e = EVAL_ROGUE; } else e = EVAL_ROGUE, decoded = 1; } else e = EVAL_ROGUE, decoded = 1; } @@ -1250,8 +1291,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'G': if ( (funcid= rogue_newgameopreturndecode(buyin,maxplayers,scriptPubKey)) != 'G' ) { - fprintf(stderr,"height.%d couldnt decode newgame opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode newgame opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode newgame opret"); } // validate newgame tx @@ -1260,8 +1301,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'R': if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) != 'R' ) { - fprintf(stderr,"height.%d couldnt decode register opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode register opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode register opret"); } // validation is done below @@ -1269,8 +1310,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'K': if ( (funcid= rogue_keystrokesopretdecode(gametxid,batontxid,pk,keystrokes,scriptPubKey)) != 'K' ) { - fprintf(stderr,"height.%d couldnt decode keystrokes opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode keystrokes opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode keystrokes opret"); } // validate keystrokes are from the correct pk. might need to add vin @@ -1279,8 +1320,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'H': case 'Q': if ( (f= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) != funcid ) { - fprintf(stderr,"height.%d couldnt decode H/Q opret\n",height); - if ( height > 20000 ) + //fprintf(stderr,"height.%d couldnt decode H/Q opret\n",height); + //if ( height > 20000 ) return eval->Invalid("couldnt decode H/Q opret"); } // validation is done below @@ -1292,12 +1333,26 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } switch ( funcid ) { - case 'G': // newgame case 'R': // register - case 'K': // keystrokes + return(true); case 'H': // win case 'Q': // bailout - //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); + // verify pk belongs to this tx + if ( playerdata.size() > 0 ) + { + if ( rogue_playerdata_validate(ptxid,cp,playerdata,gametxid,pk) < 0 ) + { + //fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); + } //else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,ptxid.GetHex().c_str()); + } + if ( funcid == 'Q' ) + { + // verify vin/vout + } + else // 'H' + { + // verify vin/vout + } return(true); break; default: From aa60acbf2764632b9e0a206364a959f503f0c729 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 21:15:47 -1100 Subject: [PATCH 0825/1145] ROGUE_MAXTOTAL = strength*2, ISMANY -> 1 --- src/cc/rogue/init.c | 11 +++++++++-- src/cc/rogue/pack.c | 6 +++--- src/cc/rogue/rogue.h | 3 +++ 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index 30370f958..ffc0b3707 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -22,6 +22,13 @@ */ void rogue_restoreobject(THING *o,struct rogue_packitem *item); +int32_t rogue_total(THING *o) +{ + if ( (o->o_flags & ISMANY) != 0 ) + return(1); + else return(o->o_count); +} + void restore_player(struct rogue_state *rs) { int32_t i,total = 0; THING *obj; @@ -38,8 +45,8 @@ void restore_player(struct rogue_state *rs) { obj = new_item(); rogue_restoreobject(obj,&rs->P.roguepack[i]); - total += obj->o_count; - if ( total > pstats.s_str*3 ) + total += rogue_total(obj); + if ( total > ROGUE_MAXTOTAL ) break; add_pack(rs,obj,TRUE); } diff --git a/src/cc/rogue/pack.c b/src/cc/rogue/pack.c index e4ceee689..776669b3b 100644 --- a/src/cc/rogue/pack.c +++ b/src/cc/rogue/pack.c @@ -166,16 +166,16 @@ int32_t num_packitems(struct rogue_state *rs) if ( list->o_packch != 0 ) { n++; - total += list->o_count; + total += rogue_total(list); } } if ( rs->guiflag != 0 ) { char str[MAXSTR]; - sprintf(str,"strength*3 %d vs total.%d vs %d inventory letters\n",pstats.s_str*3,total,n); + sprintf(str,"strength*2 %d vs total.%d vs %d inventory letters\n",ROGUE_MAXTOTAL,total,n); add_line(rs,"%s",str); } - if ( total > pstats.s_str*3 ) + if ( total > ROGUE_MAXTOTAL ) return(MAXPACK); return(n); } diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 515c1d44a..9339b630f 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -381,6 +381,9 @@ void restore_player(struct rogue_state *rs); int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis); void rogue_bailout(struct rogue_state *rs); +#define ROGUE_MAXTOTAL (pstats.s_str*2) +int32_t rogue_total(THING *o); + /* * Help list */ From f77c99d7817ea50bb83c6d1d3929434016a8fe3e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 21:16:32 -1100 Subject: [PATCH 0826/1145] int32_t rogue_total(THING *o); --- src/cc/rogue/rogue.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 9339b630f..f687b170c 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -382,7 +382,6 @@ int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t nu void rogue_bailout(struct rogue_state *rs); #define ROGUE_MAXTOTAL (pstats.s_str*2) -int32_t rogue_total(THING *o); /* * Help list @@ -806,6 +805,7 @@ THING *new_item(void); THING *new_thing(struct rogue_state *rs); void end_line(struct rogue_state *rs); int32_t num_packitems(struct rogue_state *rs); +int32_t rogue_total(THING *o); void runners(struct rogue_state *rs,int); void land(struct rogue_state *rs,int); From 2c6640cdd4c7774a25cce074be62ea3fd772563f Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 22:21:26 -1100 Subject: [PATCH 0827/1145] Change multiplayer payout to 2x, if amulet then 10x --- src/cc/rogue/rogue_player.h | 2 +- src/cc/rogue/state.c | 1 + src/cc/rogue_rpc.cpp | 8 +++++--- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/rogue_player.h b/src/cc/rogue/rogue_player.h index 1319b3213..e6b7a69e6 100644 --- a/src/cc/rogue/rogue_player.h +++ b/src/cc/rogue/rogue_player.h @@ -25,7 +25,7 @@ struct rogue_packitem }; struct rogue_player { - int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,pad; + int32_t gold,hitpoints,strength,level,experience,packsize,dungeonlevel,amulet; struct rogue_packitem roguepack[MAXPACK]; }; int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis); diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 778540b68..589f77422 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1452,6 +1452,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) rs->P.level = pstats.s_lvl; rs->P.experience = pstats.s_exp; rs->P.dungeonlevel = level; + rs->P.amulet = amulet; //fprintf(stderr,"%ld gold.%d hp.%d strength.%d/%d level.%d exp.%d %d\n",ftell(savef),purse,max_hp,pstats.s_str,max_stats.s_str,pstats.s_lvl,pstats.s_exp,level); } //fprintf(stderr,"object (%s) x.%d y.%d type.%d pack.(%c:%d)\n",inv_name(o,FALSE),o->_o._o_pos.x,o->_o._o_pos.y,o->_o._o_type,o->_o._o_packch,o->_o._o_packch); diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d74bc9619..a7bbaa489 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -957,7 +957,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param else { funcid = 'H'; - mult = 1000000; + mult = 200000; } if ( (params= cclib_reparse(&n,params)) != 0 ) { @@ -1008,11 +1008,13 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param cpTokens = CCinit(&tokensC, EVAL_TOKENS); mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cpTokens,NULL))); // marker to token cc addr, burnable and validated mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,1,mypk)); - fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d n.%d size.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel,n,(int32_t)sizeof(P)); + fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d n.%d amulet.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel,n,P.amulet); + if ( P.amulet != 0 ) + mult *= 5; cashout = (uint64_t)P.gold * mult; if ( funcid == 'H' && maxplayers > 1 ) { - if ( numplayers != maxplayers || (numplayers - rogue_playersalive(tmp,gametxid,maxplayers)) > 1 && (P.dungeonlevel > 1 || P.gold < 10000 || P.level < 20) ) + if ( (numplayers != maxplayers || (numplayers - rogue_playersalive(tmp,gametxid,maxplayers)) > 1) && P.amulet == 0 ) return(cclib_error(result,"highlander must be a winner or last one standing")); cashout += numplayers * buyin; } From 1c85c52f49c17e7520ff253aaeee70d37a9233d8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:04:17 -1100 Subject: [PATCH 0828/1145] You can ignore ./makerogue: shell: not found --- src/cc/makerogue | 1 + src/cc/rogue_rpc.cpp | 50 ++++++++++++++++++++++++-------------------- 2 files changed, 28 insertions(+), 23 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index 249e646f5..fb7a53cec 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,4 +1,5 @@ #!/bin/sh +echo "you can ignore ./makerogue: shell: not found" cd rogue; ./configure # only need this first time make; cd .. diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index a7bbaa489..1ca1bce88 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -325,18 +325,20 @@ uint64_t rogue_gamefields(UniValue &obj,int64_t maxplayers,int64_t buyin,uint256 return(seed); } -int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransaction &tx,int64_t &buyin,int32_t &maxplayers,uint256 txid) +int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransaction &tx,int64_t &buyin,int32_t &maxplayers,uint256 txid,int32_t unspentv0) { uint256 hashBlock; int32_t i,numvouts; char coinaddr[64]; CPubKey roguepk; uint64_t txfee = 10000; buyin = maxplayers = 0; if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) { gameheight = komodo_blockheight(hashBlock); - if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) >= txfee && myIsutxo_spentinmempool(ignoretxid,ignorevin,txid,0) == 0 ) + if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && (unspentv0 == 0 || CCgettxout(playertxid,0,1) == txfee) ) { if ( rogue_newgameopreturndecode(buyin,maxplayers,tx.vout[numvouts-1].scriptPubKey) == 'G' ) { - if ( numvouts > maxplayers+1 ) + if ( maxplayers < 1 || maxplayers > ROGUE_MAXPLAYERS || buyin < 0 ) + return(-6); + if ( numvouts > 2*maxplayers+1 ) { for (i=0; i 0 ) { gametxid = juint256(jitem(params,0)); - if ( (err= rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid)) == 0 ) + if ( (err= rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid,1)) == 0 ) { if ( n > 1 ) { @@ -803,7 +806,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param mypk = pubkey2pk(Mypubkey()); roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,destaddr,roguepk,mypk); - if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid) == 0 ) + if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,gametxid,1) == 0 ) { if ( rogue_findbaton(cp,playertxid,0,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,tx,maxplayers,destaddr,numplayers,symbol,pname) == 0 ) { @@ -811,7 +814,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param result.push_back(Pair("playertxid",playertxid.GetHex())); if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) { - mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); + mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); // this validates user mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,batonvalue-txfee,roguepk,mypk)); Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,destaddr); @@ -830,7 +833,7 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat roguepk = GetUnspendable(cp,0); *numkeysp = 0; seed = 0; - if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) + if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) == 0 ) { if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,rogueaddr,numplayers,symbol,pname) == 0 ) { @@ -965,7 +968,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { gametxid = juint256(jitem(params,0)); result.push_back(Pair("gametxid",gametxid.GetHex())); - if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid)) == 0 ) + if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,1)) == 0 ) { if ( rogue_findbaton(cp,playertxid,&keystrokes,numkeys,regslot,playerdata,batontxid,batonvout,batonvalue,batonht,gametxid,gametx,maxplayers,myrogueaddr,numplayers,symbol,pname) == 0 ) { @@ -1078,7 +1081,7 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { txid = juint256(jitem(params,0)); result.push_back(Pair("gametxid",txid.GetHex())); - if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,txid) == 0 ) + if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,txid,0) == 0 ) { result.push_back(Pair("result","success")); result.push_back(Pair("gameheight",(int64_t)gameheight)); @@ -1118,7 +1121,7 @@ UniValue rogue_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //char str[65]; fprintf(stderr,"%s check %s/v%d %.8f\n",coinaddr,uint256_str(str,txid),vout,(double)it->second.satoshis/COIN); if ( it->second.satoshis != txfee || vout != 0 ) // reject any that are not highlander markers continue; - if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,txid) == 0 && nextheight <= gameheight+ROGUE_MAXKEYSTROKESGAP ) + if ( rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,txid,1) == 0 && nextheight <= gameheight+ROGUE_MAXKEYSTROKESGAP ) { rogue_playersalive(numplayers,txid,maxplayers); if ( numplayers < maxplayers ) @@ -1182,7 +1185,7 @@ UniValue rogue_games(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( rogue_registeropretdecode(gametxid,tokenid,playertxid,tx.vout[numvouts-1].scriptPubKey) == 'R' ) { - if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid) == 0 ) + if ( rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0) == 0 ) { if ( CCgettxout(txid,vout,1) < 0 ) b.push_back(gametxid.GetHex()); @@ -1262,7 +1265,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errflag,dispflag,score,numvouts; CTransaction vintx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errs,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) @@ -1291,13 +1294,12 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C switch ( funcid ) { case 'G': - if ( (funcid= rogue_newgameopreturndecode(buyin,maxplayers,scriptPubKey)) != 'G' ) + if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) != 0 ) { - //fprintf(stderr,"height.%d couldnt decode newgame opret\n",height); + fprintf(stderr,"height.%d rogue_isvalidgame error.%d\n",height,err); //if ( height > 20000 ) - return eval->Invalid("couldnt decode newgame opret"); + return eval->Invalid("invalid gametxid"); } - // validate newgame tx return(true); break; case 'R': @@ -1307,6 +1309,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C //if ( height > 20000 ) return eval->Invalid("couldnt decode register opret"); } + // baton is created // validation is done below break; case 'K': @@ -1316,7 +1319,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C //if ( height > 20000 ) return eval->Invalid("couldnt decode keystrokes opret"); } - // validate keystrokes are from the correct pk. might need to add vin + // spending the baton proves it is the user if the pk is the signer return(true); break; case 'H': case 'Q': @@ -1326,7 +1329,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C //if ( height > 20000 ) return eval->Invalid("couldnt decode H/Q opret"); } - // validation is done below + // spending the baton proves it is the user if the pk is the signer + // rest of validation is done below break; default: return eval->Invalid("illegal rogue non-decoded funcid"); @@ -1353,7 +1357,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } else // 'H' { - // verify vin/vout + // verify vin/vout and proper payouts } return(true); break; From fed6024ee745bf526d543ba70f9253239b09a6c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:05:43 -1100 Subject: [PATCH 0829/1145] err --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1ca1bce88..b5e44aad5 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -332,7 +332,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) { gameheight = komodo_blockheight(hashBlock); - if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && (unspentv0 == 0 || CCgettxout(playertxid,0,1) == txfee) ) + if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && (unspentv0 == 0 || CCgettxout(txid,0,1) == txfee) ) { if ( rogue_newgameopreturndecode(buyin,maxplayers,tx.vout[numvouts-1].scriptPubKey) == 'G' ) { @@ -1265,7 +1265,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,errs,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) From 9377ec6542066c435b6660797d38ccd92393175d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:06:36 -1100 Subject: [PATCH 0830/1145] Ignore --- src/cc/makerogue | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index fb7a53cec..d737f39fa 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,9 +1,8 @@ #!/bin/sh -echo "you can ignore ./makerogue: shell: not found" cd rogue; ./configure # only need this first time +echo "you can ignore ./makerogue: shell: not found" make; cd .. gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -#gcc -std=c++11 -fPIC -shared -o librogue.so cclib.o rogue/rogue.so cp librogue.so ../libcc.so From 0ca1b888c395737651ddf73b4592d4021e3c7c30 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:10:55 -1100 Subject: [PATCH 0831/1145] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index b5e44aad5..510b67727 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1297,7 +1297,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) != 0 ) { fprintf(stderr,"height.%d rogue_isvalidgame error.%d\n",height,err); - //if ( height > 20000 ) + if ( height > 30000 ) return eval->Invalid("invalid gametxid"); } return(true); From 60e6554848eacda156de40263806f6966ca315a1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:16:24 -1100 Subject: [PATCH 0832/1145] Test --- src/cc/rogue_rpc.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 510b67727..d4ee66b57 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1294,12 +1294,14 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C switch ( funcid ) { case 'G': + gametxid = tx.GetHash(); if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) != 0 ) { - fprintf(stderr,"height.%d rogue_isvalidgame error.%d\n",height,err); + fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); if ( height > 30000 ) return eval->Invalid("invalid gametxid"); } + fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); return(true); break; case 'R': From 79e09db7e6a8a0b1c35fc5a3d75bd54f2ae9497d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:28:25 -1100 Subject: [PATCH 0833/1145] +print --- src/cc/rogue_rpc.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d4ee66b57..f7ac0162a 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -814,7 +814,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param result.push_back(Pair("playertxid",playertxid.GetHex())); if ( maxplayers == 1 || nextheight <= batonht+ROGUE_MAXKEYSTROKESGAP ) { - mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); // this validates user + mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); //this validates user if pk mtx.vout.push_back(MakeCC1of2vout(cp->evalcode,batonvalue-txfee,roguepk,mypk)); Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,destaddr); @@ -1293,7 +1293,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { switch ( funcid ) { - case 'G': + case 'G': // seems just need to make sure no vout abuse is left to do gametxid = tx.GetHash(); if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) != 0 ) { @@ -1301,7 +1301,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C if ( height > 30000 ) return eval->Invalid("invalid gametxid"); } - fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); + //fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); return(true); break; case 'R': @@ -1342,6 +1342,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C switch ( funcid ) { case 'R': // register + // verify vout amounts are as they should be and no vins that shouldnt be return(true); case 'H': // win case 'Q': // bailout From 961a1eb0a2b1967cfdb74fe548f661fd3b5a7713 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 18 Feb 2019 23:28:46 -1100 Subject: [PATCH 0834/1145] Enforce new game --- src/cc/rogue_rpc.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f7ac0162a..ec1b669dc 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1298,8 +1298,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) != 0 ) { fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); - if ( height > 30000 ) - return eval->Invalid("invalid gametxid"); + return eval->Invalid("invalid gametxid"); } //fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); return(true); From f3c28c684a58e4601e439be6200f8365aac0d6fa Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 00:07:07 -1100 Subject: [PATCH 0835/1145] -print --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index ec1b669dc..9cef26d83 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1288,7 +1288,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } if ( e == EVAL_ROGUE ) { - fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); + //fprintf(stderr,"ht.%d rogue.(%c)\n",height,script[1]); if ( decoded == 0 ) { switch ( funcid ) From d0888260aa142faab3044a6ea0876a2ed5849a61 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:24:08 -1100 Subject: [PATCH 0836/1145] +print validgame --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9cef26d83..d1c63f592 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1300,7 +1300,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); return eval->Invalid("invalid gametxid"); } - //fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); + fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); return(true); break; case 'R': From ef05677ec88427b56d6083c6711a0de05af00297 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:24:32 -1100 Subject: [PATCH 0837/1145] -print --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d1c63f592..9cef26d83 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1300,7 +1300,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); return eval->Invalid("invalid gametxid"); } - fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); + //fprintf(stderr,"height.%d %s rogue_isvalidgame\n",height,gametxid.GetHex().c_str()); return(true); break; case 'R': From ee5d656a2c1c7df3160281939ebebeab3fbeba8a Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:31:02 -1100 Subject: [PATCH 0838/1145] Rework game validation --- src/cc/rogue_rpc.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9cef26d83..78541b63c 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -329,9 +329,10 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa { uint256 hashBlock; int32_t i,numvouts; char coinaddr[64]; CPubKey roguepk; uint64_t txfee = 10000; buyin = maxplayers = 0; - if ( myGetTransaction(txid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) + if ( (txid == zeroid || myGetTransaction(txid,tx,hashBlock) != 0) && (numvouts= tx.vout.size()) > 1 ) { - gameheight = komodo_blockheight(hashBlock); + if ( txid != zeroid ) + gameheight = komodo_blockheight(hashBlock); if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && (unspentv0 == 0 || CCgettxout(txid,0,1) == txfee) ) { if ( rogue_newgameopreturndecode(buyin,maxplayers,tx.vout[numvouts-1].scriptPubKey) == 'G' ) @@ -1295,7 +1296,8 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { case 'G': // seems just need to make sure no vout abuse is left to do gametxid = tx.GetHash(); - if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,gametxid,0)) != 0 ) + gameheight = height; + if ( (err= rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,zerotxid,0)) != 0 ) { fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); return eval->Invalid("invalid gametxid"); From 67eb2929d63534398efdea4007c7d6192b598634 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:31:56 -1100 Subject: [PATCH 0839/1145] Zeroed --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 78541b63c..9d493e5ae 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1297,7 +1297,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C case 'G': // seems just need to make sure no vout abuse is left to do gametxid = tx.GetHash(); gameheight = height; - if ( (err= rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,zerotxid,0)) != 0 ) + if ( (err= rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,zeroid,0)) != 0 ) { fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); return eval->Invalid("invalid gametxid"); From 92c9825cdea8ad8be5a00b7f74412556840d69a3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:41:28 -1100 Subject: [PATCH 0840/1145] Test --- src/cc/rogue_rpc.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9d493e5ae..50492e2cf 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -333,6 +333,11 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa { if ( txid != zeroid ) gameheight = komodo_blockheight(hashBlock); + else + { + txid = tx.GetHash(); + fprintf(stderr,"set txid %s %llu\n",txid.GetHex().c_str(),(long long)CCgettxout(txid,0,1)); + } if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && (unspentv0 == 0 || CCgettxout(txid,0,1) == txfee) ) { if ( rogue_newgameopreturndecode(buyin,maxplayers,tx.vout[numvouts-1].scriptPubKey) == 'G' ) From fbe6061dc6e76a292ae49e284a1354dc2de4f8b0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:42:45 -1100 Subject: [PATCH 0841/1145] Test --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 50492e2cf..2496d6a5e 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1300,9 +1300,10 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C switch ( funcid ) { case 'G': // seems just need to make sure no vout abuse is left to do + gametx = tx; gametxid = tx.GetHash(); gameheight = height; - if ( (err= rogue_isvalidgame(cp,gameheight,tx,buyin,maxplayers,zeroid,0)) != 0 ) + if ( (err= rogue_isvalidgame(cp,gameheight,gametx,buyin,maxplayers,zeroid,0)) != 0 ) { fprintf(stderr,"height.%d %s rogue_isvalidgame error.%d\n",height,gametxid.GetHex().c_str(),err); return eval->Invalid("invalid gametxid"); From 180114697aaf5f7ff6ee96ec51722e1150aeea42 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 01:44:36 -1100 Subject: [PATCH 0842/1145] -print --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 2496d6a5e..3d89e0568 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -336,7 +336,7 @@ int32_t rogue_isvalidgame(struct CCcontract_info *cp,int32_t &gameheight,CTransa else { txid = tx.GetHash(); - fprintf(stderr,"set txid %s %llu\n",txid.GetHex().c_str(),(long long)CCgettxout(txid,0,1)); + //fprintf(stderr,"set txid %s %llu\n",txid.GetHex().c_str(),(long long)CCgettxout(txid,0,1)); } if ( IsCClibvout(cp,tx,0,cp->unspendableCCaddr) == txfee && (unspentv0 == 0 || CCgettxout(txid,0,1) == txfee) ) { From 2ca8d1eedaef49bccd8622bc8f61a6d6fa4c6dc9 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 14:15:09 +0100 Subject: [PATCH 0843/1145] resolve conflict PR for multi OS build will follow this PR --- src/cc/makerogue | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index d737f39fa..a38eab6a4 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,8 +1,11 @@ #!/bin/sh cd rogue; -./configure # only need this first time -echo "you can ignore ./makerogue: shell: not found" +./configure make; cd .. -gcc -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -o librogue.so -c cclib.cpp -cp librogue.so ../libcc.so +if make -f Makefile_rogue "$@"; then + echo ROGUE BUILD SUCCESSFUL +else + echo ROGUE BUILD FAILED + exit 1 +fi From 4bf1256a68a0248dfdc9b54b8e31dbe759cf073b Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 16:57:47 +0100 Subject: [PATCH 0844/1145] add ifndef WIN --- src/cc/rogue/cursesd.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cc/rogue/cursesd.h b/src/cc/rogue/cursesd.h index 87304cfa6..cb74941e5 100644 --- a/src/cc/rogue/cursesd.h +++ b/src/cc/rogue/cursesd.h @@ -48,7 +48,10 @@ extern WINDOW *stdscr,*curscr; extern int32_t ESCDELAY; typedef char chtype; +#ifndef __MINGW32__ int32_t getch(void); // stub +#endif + int32_t md_readchar(void); // stub WINDOW *initscr(void); From c127a8f0b5bfd89e76364e6432c8a70b5eb3a203 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 06:34:34 -1100 Subject: [PATCH 0845/1145] ENABLE_MODULE_MUSIG --- src/secp256k1/Makefile.am | 5 + src/secp256k1/src/ecmult.h | 55 + src/secp256k1/src/ecmult_impl.h | 1176 +++++++++++++++++ .../src/modules/musig/Makefile.am.include | 17 + src/secp256k1/src/modules/musig/example.c | 166 +++ src/secp256k1/src/modules/musig/main_impl.h | 631 +++++++++ src/secp256k1/src/modules/musig/tests_impl.h | 758 +++++++++++ .../modules/schnorrsig/Makefile.am.include | 9 + .../src/modules/schnorrsig/main_impl.h | 339 +++++ .../src/modules/schnorrsig/tests_impl.h | 727 ++++++++++ src/secp256k1/src/scalar.h | 235 ++++ src/secp256k1/src/scalar_4x64.h | 49 + src/secp256k1/src/scalar_4x64_impl.h | 1056 +++++++++++++++ src/secp256k1/src/scalar_8x32.h | 24 + src/secp256k1/src/scalar_8x32_impl.h | 838 ++++++++++++ src/secp256k1/src/scalar_impl.h | 340 +++++ src/secp256k1/src/scalar_low.h | 20 + src/secp256k1/src/scalar_low_impl.h | 126 ++ 18 files changed, 6571 insertions(+) create mode 100644 src/secp256k1/src/modules/musig/Makefile.am.include create mode 100644 src/secp256k1/src/modules/musig/example.c create mode 100644 src/secp256k1/src/modules/musig/main_impl.h create mode 100644 src/secp256k1/src/modules/musig/tests_impl.h create mode 100644 src/secp256k1/src/modules/schnorrsig/Makefile.am.include create mode 100644 src/secp256k1/src/modules/schnorrsig/main_impl.h create mode 100644 src/secp256k1/src/modules/schnorrsig/tests_impl.h diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index c071fbe27..ff5a2c50c 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -172,6 +172,11 @@ if ENABLE_MODULE_ECDH include src/modules/ecdh/Makefile.am.include endif +if ENABLE_MODULE_MUSIG +include src/modules/schnorrsig/Makefile.am.include +include src/modules/musig/Makefile.am.include +endif + if ENABLE_MODULE_RECOVERY include src/modules/recovery/Makefile.am.include endif diff --git a/src/secp256k1/src/ecmult.h b/src/secp256k1/src/ecmult.h index 6d44aba60..7fe619b21 100644 --- a/src/secp256k1/src/ecmult.h +++ b/src/secp256k1/src/ecmult.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2013, 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -29,3 +31,56 @@ static int secp256k1_ecmult_context_is_built(const secp256k1_ecmult_context *ctx static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng); #endif /* SECP256K1_ECMULT_H */ + +#else +/********************************************************************** + * Copyright (c) 2013, 2014, 2017 Pieter Wuille, Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_H +#define SECP256K1_ECMULT_H + +#include "num.h" +#include "group.h" +#include "scalar.h" +#include "scratch.h" + +typedef struct { + /* For accelerating the computation of a*P + b*G: */ + secp256k1_ge_storage (*pre_g)[]; /* odd multiples of the generator */ +#ifdef USE_ENDOMORPHISM + secp256k1_ge_storage (*pre_g_128)[]; /* odd multiples of 2^128*generator */ +#endif +} secp256k1_ecmult_context; + +static void secp256k1_ecmult_context_init(secp256k1_ecmult_context *ctx); +static void secp256k1_ecmult_context_build(secp256k1_ecmult_context *ctx, const secp256k1_callback *cb); +static void secp256k1_ecmult_context_clone(secp256k1_ecmult_context *dst, + const secp256k1_ecmult_context *src, const secp256k1_callback *cb); +static void secp256k1_ecmult_context_clear(secp256k1_ecmult_context *ctx); +static int secp256k1_ecmult_context_is_built(const secp256k1_ecmult_context *ctx); + +/** Double multiply: R = na*A + ng*G */ +static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng); + +typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); + +/** + * Multi-multiply: R = inp_g_sc * G + sum_i ni * Ai. + * Chooses the right algorithm for a given number of points and scratch space + * size. Resets and overwrites the given scratch space. If the points do not + * fit in the scratch space the algorithm is repeatedly run with batches of + * points. If no scratch space is given then a simple algorithm is used that + * simply multiplies the points with the corresponding scalars and adds them up. + * Returns: 1 on success (including when inp_g_sc is NULL and n is 0) + * 0 if there is not enough scratch space for a single point or + * callback returns 0 + */ +static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); + +#endif /* SECP256K1_ECMULT_H */ + +#endif + diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 93d3794cb..6c9a1daf2 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1,3 +1,6 @@ +#ifndef ENABLE_MODULE_MUSIG + + /********************************************************************** * Copyright (c) 2013, 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -404,3 +407,1176 @@ static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej } #endif /* SECP256K1_ECMULT_IMPL_H */ + +#else + +/***************************************************************************** + * Copyright (c) 2013, 2014, 2017 Pieter Wuille, Andrew Poelstra, Jonas Nick * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php. * + *****************************************************************************/ + +#ifndef SECP256K1_ECMULT_IMPL_H +#define SECP256K1_ECMULT_IMPL_H + +#include +#include + +#include "group.h" +#include "scalar.h" +#include "ecmult.h" + +#if defined(EXHAUSTIVE_TEST_ORDER) +/* We need to lower these values for exhaustive tests because + * the tables cannot have infinities in them (this breaks the + * affine-isomorphism stuff which tracks z-ratios) */ +# if EXHAUSTIVE_TEST_ORDER > 128 +# define WINDOW_A 5 +# define WINDOW_G 8 +# elif EXHAUSTIVE_TEST_ORDER > 8 +# define WINDOW_A 4 +# define WINDOW_G 4 +# else +# define WINDOW_A 2 +# define WINDOW_G 2 +# endif +#else +/* optimal for 128-bit and 256-bit exponents. */ +#define WINDOW_A 5 +/** larger numbers may result in slightly better performance, at the cost of + exponentially larger precomputed tables. */ +#ifdef USE_ENDOMORPHISM +/** Two tables for window size 15: 1.375 MiB. */ +#define WINDOW_G 15 +#else +/** One table for window size 16: 1.375 MiB. */ +#define WINDOW_G 16 +#endif +#endif + +#ifdef USE_ENDOMORPHISM +#define WNAF_BITS 128 +#else +#define WNAF_BITS 256 +#endif +#define WNAF_SIZE_BITS(bits, w) (((bits) + (w) - 1) / (w)) +#define WNAF_SIZE(w) WNAF_SIZE_BITS(WNAF_BITS, w) + +/** The number of entries a table with precomputed multiples needs to have. */ +#define ECMULT_TABLE_SIZE(w) (1 << ((w)-2)) + +/* The number of objects allocated on the scratch space for ecmult_multi algorithms */ +#define PIPPENGER_SCRATCH_OBJECTS 6 +#define STRAUSS_SCRATCH_OBJECTS 6 + +#define PIPPENGER_MAX_BUCKET_WINDOW 12 + +/* Minimum number of points for which pippenger_wnaf is faster than strauss wnaf */ +#ifdef USE_ENDOMORPHISM +#define ECMULT_PIPPENGER_THRESHOLD 88 +#else +#define ECMULT_PIPPENGER_THRESHOLD 160 +#endif + +#ifdef USE_ENDOMORPHISM +#define ECMULT_MAX_POINTS_PER_BATCH 5000000 +#else +#define ECMULT_MAX_POINTS_PER_BATCH 10000000 +#endif + +/** Fill a table 'prej' with precomputed odd multiples of a. Prej will contain + * the values [1*a,3*a,...,(2*n-1)*a], so it space for n values. zr[0] will + * contain prej[0].z / a.z. The other zr[i] values = prej[i].z / prej[i-1].z. + * Prej's Z values are undefined, except for the last value. + */ +static void secp256k1_ecmult_odd_multiples_table(int n, secp256k1_gej *prej, secp256k1_fe *zr, const secp256k1_gej *a) { + secp256k1_gej d; + secp256k1_ge a_ge, d_ge; + int i; + + VERIFY_CHECK(!a->infinity); + + secp256k1_gej_double_var(&d, a, NULL); + + /* + * Perform the additions on an isomorphism where 'd' is affine: drop the z coordinate + * of 'd', and scale the 1P starting value's x/y coordinates without changing its z. + */ + d_ge.x = d.x; + d_ge.y = d.y; + d_ge.infinity = 0; + + secp256k1_ge_set_gej_zinv(&a_ge, a, &d.z); + prej[0].x = a_ge.x; + prej[0].y = a_ge.y; + prej[0].z = a->z; + prej[0].infinity = 0; + + zr[0] = d.z; + for (i = 1; i < n; i++) { + secp256k1_gej_add_ge_var(&prej[i], &prej[i-1], &d_ge, &zr[i]); + } + + /* + * Each point in 'prej' has a z coordinate too small by a factor of 'd.z'. Only + * the final point's z coordinate is actually used though, so just update that. + */ + secp256k1_fe_mul(&prej[n-1].z, &prej[n-1].z, &d.z); +} + +/** Fill a table 'pre' with precomputed odd multiples of a. + * + * There are two versions of this function: + * - secp256k1_ecmult_odd_multiples_table_globalz_windowa which brings its + * resulting point set to a single constant Z denominator, stores the X and Y + * coordinates as ge_storage points in pre, and stores the global Z in rz. + * It only operates on tables sized for WINDOW_A wnaf multiples. + * - secp256k1_ecmult_odd_multiples_table_storage_var, which converts its + * resulting point set to actually affine points, and stores those in pre. + * It operates on tables of any size, but uses heap-allocated temporaries. + * + * To compute a*P + b*G, we compute a table for P using the first function, + * and for G using the second (which requires an inverse, but it only needs to + * happen once). + */ +static void secp256k1_ecmult_odd_multiples_table_globalz_windowa(secp256k1_ge *pre, secp256k1_fe *globalz, const secp256k1_gej *a) { + secp256k1_gej prej[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_fe zr[ECMULT_TABLE_SIZE(WINDOW_A)]; + + /* Compute the odd multiples in Jacobian form. */ + secp256k1_ecmult_odd_multiples_table(ECMULT_TABLE_SIZE(WINDOW_A), prej, zr, a); + /* Bring them to the same Z denominator. */ + secp256k1_ge_globalz_set_table_gej(ECMULT_TABLE_SIZE(WINDOW_A), pre, globalz, prej, zr); +} + +static void secp256k1_ecmult_odd_multiples_table_storage_var(const int n, secp256k1_ge_storage *pre, const secp256k1_gej *a) { + secp256k1_gej d; + secp256k1_ge d_ge, p_ge; + secp256k1_gej pj; + secp256k1_fe zi; + secp256k1_fe zr; + secp256k1_fe dx_over_dz_squared; + int i; + + VERIFY_CHECK(!a->infinity); + + secp256k1_gej_double_var(&d, a, NULL); + + /* First, we perform all the additions in an isomorphic curve obtained by multiplying + * all `z` coordinates by 1/`d.z`. In these coordinates `d` is affine so we can use + * `secp256k1_gej_add_ge_var` to perform the additions. For each addition, we store + * the resulting y-coordinate and the z-ratio, since we only have enough memory to + * store two field elements. These are sufficient to efficiently undo the isomorphism + * and recompute all the `x`s. + */ + d_ge.x = d.x; + d_ge.y = d.y; + d_ge.infinity = 0; + + secp256k1_ge_set_gej_zinv(&p_ge, a, &d.z); + pj.x = p_ge.x; + pj.y = p_ge.y; + pj.z = a->z; + pj.infinity = 0; + + for (i = 0; i < (n - 1); i++) { + secp256k1_fe_normalize_var(&pj.y); + secp256k1_fe_to_storage(&pre[i].y, &pj.y); + secp256k1_gej_add_ge_var(&pj, &pj, &d_ge, &zr); + secp256k1_fe_normalize_var(&zr); + secp256k1_fe_to_storage(&pre[i].x, &zr); + } + + /* Invert d.z in the same batch, preserving pj.z so we can extract 1/d.z */ + secp256k1_fe_mul(&zi, &pj.z, &d.z); + secp256k1_fe_inv_var(&zi, &zi); + + /* Directly set `pre[n - 1]` to `pj`, saving the inverted z-coordinate so + * that we can combine it with the saved z-ratios to compute the other zs + * without any more inversions. */ + secp256k1_ge_set_gej_zinv(&p_ge, &pj, &zi); + secp256k1_ge_to_storage(&pre[n - 1], &p_ge); + + /* Compute the actual x-coordinate of D, which will be needed below. */ + secp256k1_fe_mul(&d.z, &zi, &pj.z); /* d.z = 1/d.z */ + secp256k1_fe_sqr(&dx_over_dz_squared, &d.z); + secp256k1_fe_mul(&dx_over_dz_squared, &dx_over_dz_squared, &d.x); + + /* Going into the second loop, we have set `pre[n-1]` to its final affine + * form, but still need to set `pre[i]` for `i` in 0 through `n-2`. We + * have `zi = (p.z * d.z)^-1`, where + * + * `p.z` is the z-coordinate of the point on the isomorphic curve + * which was ultimately assigned to `pre[n-1]`. + * `d.z` is the multiplier that must be applied to all z-coordinates + * to move from our isomorphic curve back to secp256k1; so the + * product `p.z * d.z` is the z-coordinate of the secp256k1 + * point assigned to `pre[n-1]`. + * + * All subsequent inverse-z-coordinates can be obtained by multiplying this + * factor by successive z-ratios, which is much more efficient than directly + * computing each one. + * + * Importantly, these inverse-zs will be coordinates of points on secp256k1, + * while our other stored values come from computations on the isomorphic + * curve. So in the below loop, we will take care not to actually use `zi` + * or any derived values until we're back on secp256k1. + */ + i = n - 1; + while (i > 0) { + secp256k1_fe zi2, zi3; + const secp256k1_fe *rzr; + i--; + + secp256k1_ge_from_storage(&p_ge, &pre[i]); + + /* For each remaining point, we extract the z-ratio from the stored + * x-coordinate, compute its z^-1 from that, and compute the full + * point from that. */ + rzr = &p_ge.x; + secp256k1_fe_mul(&zi, &zi, rzr); + secp256k1_fe_sqr(&zi2, &zi); + secp256k1_fe_mul(&zi3, &zi2, &zi); + /* To compute the actual x-coordinate, we use the stored z ratio and + * y-coordinate, which we obtained from `secp256k1_gej_add_ge_var` + * in the loop above, as well as the inverse of the square of its + * z-coordinate. We store the latter in the `zi2` variable, which is + * computed iteratively starting from the overall Z inverse then + * multiplying by each z-ratio in turn. + * + * Denoting the z-ratio as `rzr`, we observe that it is equal to `h` + * from the inside of the above `gej_add_ge_var` call. This satisfies + * + * rzr = d_x * z^2 - x * d_z^2 + * + * where (`d_x`, `d_z`) are Jacobian coordinates of `D` and `(x, z)` + * are Jacobian coordinates of our desired point -- except both are on + * the isomorphic curve that we were using when we called `gej_add_ge_var`. + * To get back to secp256k1, we must multiply both `z`s by `d_z`, or + * equivalently divide both `x`s by `d_z^2`. Our equation then becomes + * + * rzr = d_x * z^2 / d_z^2 - x + * + * (The left-hand-side, being a ratio of z-coordinates, is unaffected + * by the isomorphism.) + * + * Rearranging to solve for `x`, we have + * + * x = d_x * z^2 / d_z^2 - rzr + * + * But what we actually want is the affine coordinate `X = x/z^2`, + * which will satisfy + * + * X = d_x / d_z^2 - rzr / z^2 + * = dx_over_dz_squared - rzr * zi2 + */ + secp256k1_fe_mul(&p_ge.x, rzr, &zi2); + secp256k1_fe_negate(&p_ge.x, &p_ge.x, 1); + secp256k1_fe_add(&p_ge.x, &dx_over_dz_squared); + /* y is stored_y/z^3, as we expect */ + secp256k1_fe_mul(&p_ge.y, &p_ge.y, &zi3); + /* Store */ + secp256k1_ge_to_storage(&pre[i], &p_ge); + } +} + +/** The following two macro retrieves a particular odd multiple from a table + * of precomputed multiples. */ +#define ECMULT_TABLE_GET_GE(r,pre,n,w) do { \ +VERIFY_CHECK(((n) & 1) == 1); \ +VERIFY_CHECK((n) >= -((1 << ((w)-1)) - 1)); \ +VERIFY_CHECK((n) <= ((1 << ((w)-1)) - 1)); \ +if ((n) > 0) { \ +*(r) = (pre)[((n)-1)/2]; \ +} else { \ +secp256k1_ge_neg((r), &(pre)[(-(n)-1)/2]); \ +} \ +} while(0) + +#define ECMULT_TABLE_GET_GE_STORAGE(r,pre,n,w) do { \ +VERIFY_CHECK(((n) & 1) == 1); \ +VERIFY_CHECK((n) >= -((1 << ((w)-1)) - 1)); \ +VERIFY_CHECK((n) <= ((1 << ((w)-1)) - 1)); \ +if ((n) > 0) { \ +secp256k1_ge_from_storage((r), &(pre)[((n)-1)/2]); \ +} else { \ +secp256k1_ge_from_storage((r), &(pre)[(-(n)-1)/2]); \ +secp256k1_ge_neg((r), (r)); \ +} \ +} while(0) + +static void secp256k1_ecmult_context_init(secp256k1_ecmult_context *ctx) { + ctx->pre_g = NULL; +#ifdef USE_ENDOMORPHISM + ctx->pre_g_128 = NULL; +#endif +} + +static void secp256k1_ecmult_context_build(secp256k1_ecmult_context *ctx, const secp256k1_callback *cb) { + secp256k1_gej gj; + + if (ctx->pre_g != NULL) { + return; + } + + /* get the generator */ + secp256k1_gej_set_ge(&gj, &secp256k1_ge_const_g); + + ctx->pre_g = (secp256k1_ge_storage (*)[])checked_malloc(cb, sizeof((*ctx->pre_g)[0]) * ECMULT_TABLE_SIZE(WINDOW_G)); + + /* precompute the tables with odd multiples */ + secp256k1_ecmult_odd_multiples_table_storage_var(ECMULT_TABLE_SIZE(WINDOW_G), *ctx->pre_g, &gj); + +#ifdef USE_ENDOMORPHISM + { + secp256k1_gej g_128j; + int i; + + ctx->pre_g_128 = (secp256k1_ge_storage (*)[])checked_malloc(cb, sizeof((*ctx->pre_g_128)[0]) * ECMULT_TABLE_SIZE(WINDOW_G)); + + /* calculate 2^128*generator */ + g_128j = gj; + for (i = 0; i < 128; i++) { + secp256k1_gej_double_var(&g_128j, &g_128j, NULL); + } + secp256k1_ecmult_odd_multiples_table_storage_var(ECMULT_TABLE_SIZE(WINDOW_G), *ctx->pre_g_128, &g_128j); + } +#endif +} + +static void secp256k1_ecmult_context_clone(secp256k1_ecmult_context *dst, + const secp256k1_ecmult_context *src, const secp256k1_callback *cb) { + if (src->pre_g == NULL) { + dst->pre_g = NULL; + } else { + size_t size = sizeof((*dst->pre_g)[0]) * ECMULT_TABLE_SIZE(WINDOW_G); + dst->pre_g = (secp256k1_ge_storage (*)[])checked_malloc(cb, size); + memcpy(dst->pre_g, src->pre_g, size); + } +#ifdef USE_ENDOMORPHISM + if (src->pre_g_128 == NULL) { + dst->pre_g_128 = NULL; + } else { + size_t size = sizeof((*dst->pre_g_128)[0]) * ECMULT_TABLE_SIZE(WINDOW_G); + dst->pre_g_128 = (secp256k1_ge_storage (*)[])checked_malloc(cb, size); + memcpy(dst->pre_g_128, src->pre_g_128, size); + } +#endif +} + +static int secp256k1_ecmult_context_is_built(const secp256k1_ecmult_context *ctx) { + return ctx->pre_g != NULL; +} + +static void secp256k1_ecmult_context_clear(secp256k1_ecmult_context *ctx) { + free(ctx->pre_g); +#ifdef USE_ENDOMORPHISM + free(ctx->pre_g_128); +#endif + secp256k1_ecmult_context_init(ctx); +} + +/** Convert a number to WNAF notation. The number becomes represented by sum(2^i * wnaf[i], i=0..bits), + * with the following guarantees: + * - each wnaf[i] is either 0, or an odd integer between -(1<<(w-1) - 1) and (1<<(w-1) - 1) + * - two non-zero entries in wnaf are separated by at least w-1 zeroes. + * - the number of set values in wnaf is returned. This number is at most 256, and at most one more + * than the number of bits in the (absolute value) of the input. + */ +static int secp256k1_ecmult_wnaf(int *wnaf, int len, const secp256k1_scalar *a, int w) { + secp256k1_scalar s = *a; + int last_set_bit = -1; + int bit = 0; + int sign = 1; + int carry = 0; + + VERIFY_CHECK(wnaf != NULL); + VERIFY_CHECK(0 <= len && len <= 256); + VERIFY_CHECK(a != NULL); + VERIFY_CHECK(2 <= w && w <= 31); + + memset(wnaf, 0, len * sizeof(wnaf[0])); + + if (secp256k1_scalar_get_bits(&s, 255, 1)) { + secp256k1_scalar_negate(&s, &s); + sign = -1; + } + + while (bit < len) { + int now; + int word; + if (secp256k1_scalar_get_bits(&s, bit, 1) == (unsigned int)carry) { + bit++; + continue; + } + + now = w; + if (now > len - bit) { + now = len - bit; + } + + word = secp256k1_scalar_get_bits_var(&s, bit, now) + carry; + + carry = (word >> (w-1)) & 1; + word -= carry << w; + + wnaf[bit] = sign * word; + last_set_bit = bit; + + bit += now; + } +#ifdef VERIFY + CHECK(carry == 0); + while (bit < 256) { + CHECK(secp256k1_scalar_get_bits(&s, bit++, 1) == 0); + } +#endif + return last_set_bit + 1; +} + +struct secp256k1_strauss_point_state { +#ifdef USE_ENDOMORPHISM + secp256k1_scalar na_1, na_lam; + int wnaf_na_1[130]; + int wnaf_na_lam[130]; + int bits_na_1; + int bits_na_lam; +#else + int wnaf_na[256]; + int bits_na; +#endif + size_t input_pos; +}; + +struct secp256k1_strauss_state { + secp256k1_gej* prej; + secp256k1_fe* zr; + secp256k1_ge* pre_a; +#ifdef USE_ENDOMORPHISM + secp256k1_ge* pre_a_lam; +#endif + struct secp256k1_strauss_point_state* ps; +}; + +static void secp256k1_ecmult_strauss_wnaf(const secp256k1_ecmult_context *ctx, const struct secp256k1_strauss_state *state, secp256k1_gej *r, int num, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng) { + secp256k1_ge tmpa; + secp256k1_fe Z; +#ifdef USE_ENDOMORPHISM + /* Splitted G factors. */ + secp256k1_scalar ng_1, ng_128; + int wnaf_ng_1[129]; + int bits_ng_1 = 0; + int wnaf_ng_128[129]; + int bits_ng_128 = 0; +#else + int wnaf_ng[256]; + int bits_ng = 0; +#endif + int i; + int bits = 0; + int np; + int no = 0; + + for (np = 0; np < num; ++np) { + if (secp256k1_scalar_is_zero(&na[np]) || secp256k1_gej_is_infinity(&a[np])) { + continue; + } + state->ps[no].input_pos = np; +#ifdef USE_ENDOMORPHISM + /* split na into na_1 and na_lam (where na = na_1 + na_lam*lambda, and na_1 and na_lam are ~128 bit) */ + secp256k1_scalar_split_lambda(&state->ps[no].na_1, &state->ps[no].na_lam, &na[np]); + + /* build wnaf representation for na_1 and na_lam. */ + state->ps[no].bits_na_1 = secp256k1_ecmult_wnaf(state->ps[no].wnaf_na_1, 130, &state->ps[no].na_1, WINDOW_A); + state->ps[no].bits_na_lam = secp256k1_ecmult_wnaf(state->ps[no].wnaf_na_lam, 130, &state->ps[no].na_lam, WINDOW_A); + VERIFY_CHECK(state->ps[no].bits_na_1 <= 130); + VERIFY_CHECK(state->ps[no].bits_na_lam <= 130); + if (state->ps[no].bits_na_1 > bits) { + bits = state->ps[no].bits_na_1; + } + if (state->ps[no].bits_na_lam > bits) { + bits = state->ps[no].bits_na_lam; + } +#else + /* build wnaf representation for na. */ + state->ps[no].bits_na = secp256k1_ecmult_wnaf(state->ps[no].wnaf_na, 256, &na[np], WINDOW_A); + if (state->ps[no].bits_na > bits) { + bits = state->ps[no].bits_na; + } +#endif + ++no; + } + + /* Calculate odd multiples of a. + * All multiples are brought to the same Z 'denominator', which is stored + * in Z. Due to secp256k1' isomorphism we can do all operations pretending + * that the Z coordinate was 1, use affine addition formulae, and correct + * the Z coordinate of the result once at the end. + * The exception is the precomputed G table points, which are actually + * affine. Compared to the base used for other points, they have a Z ratio + * of 1/Z, so we can use secp256k1_gej_add_zinv_var, which uses the same + * isomorphism to efficiently add with a known Z inverse. + */ + if (no > 0) { + /* Compute the odd multiples in Jacobian form. */ + secp256k1_ecmult_odd_multiples_table(ECMULT_TABLE_SIZE(WINDOW_A), state->prej, state->zr, &a[state->ps[0].input_pos]); + for (np = 1; np < no; ++np) { + secp256k1_gej tmp = a[state->ps[np].input_pos]; +#ifdef VERIFY + secp256k1_fe_normalize_var(&(state->prej[(np - 1) * ECMULT_TABLE_SIZE(WINDOW_A) + ECMULT_TABLE_SIZE(WINDOW_A) - 1].z)); +#endif + secp256k1_gej_rescale(&tmp, &(state->prej[(np - 1) * ECMULT_TABLE_SIZE(WINDOW_A) + ECMULT_TABLE_SIZE(WINDOW_A) - 1].z)); + secp256k1_ecmult_odd_multiples_table(ECMULT_TABLE_SIZE(WINDOW_A), state->prej + np * ECMULT_TABLE_SIZE(WINDOW_A), state->zr + np * ECMULT_TABLE_SIZE(WINDOW_A), &tmp); + secp256k1_fe_mul(state->zr + np * ECMULT_TABLE_SIZE(WINDOW_A), state->zr + np * ECMULT_TABLE_SIZE(WINDOW_A), &(a[state->ps[np].input_pos].z)); + } + /* Bring them to the same Z denominator. */ + secp256k1_ge_globalz_set_table_gej(ECMULT_TABLE_SIZE(WINDOW_A) * no, state->pre_a, &Z, state->prej, state->zr); + } else { + secp256k1_fe_set_int(&Z, 1); + } + +#ifdef USE_ENDOMORPHISM + for (np = 0; np < no; ++np) { + for (i = 0; i < ECMULT_TABLE_SIZE(WINDOW_A); i++) { + secp256k1_ge_mul_lambda(&state->pre_a_lam[np * ECMULT_TABLE_SIZE(WINDOW_A) + i], &state->pre_a[np * ECMULT_TABLE_SIZE(WINDOW_A) + i]); + } + } + + if (ng) { + /* split ng into ng_1 and ng_128 (where gn = gn_1 + gn_128*2^128, and gn_1 and gn_128 are ~128 bit) */ + secp256k1_scalar_split_128(&ng_1, &ng_128, ng); + + /* Build wnaf representation for ng_1 and ng_128 */ + bits_ng_1 = secp256k1_ecmult_wnaf(wnaf_ng_1, 129, &ng_1, WINDOW_G); + bits_ng_128 = secp256k1_ecmult_wnaf(wnaf_ng_128, 129, &ng_128, WINDOW_G); + if (bits_ng_1 > bits) { + bits = bits_ng_1; + } + if (bits_ng_128 > bits) { + bits = bits_ng_128; + } + } +#else + if (ng) { + bits_ng = secp256k1_ecmult_wnaf(wnaf_ng, 256, ng, WINDOW_G); + if (bits_ng > bits) { + bits = bits_ng; + } + } +#endif + + secp256k1_gej_set_infinity(r); + + for (i = bits - 1; i >= 0; i--) { + int n; + secp256k1_gej_double_var(r, r, NULL); +#ifdef USE_ENDOMORPHISM + for (np = 0; np < no; ++np) { + if (i < state->ps[np].bits_na_1 && (n = state->ps[np].wnaf_na_1[i])) { + ECMULT_TABLE_GET_GE(&tmpa, state->pre_a + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A); + secp256k1_gej_add_ge_var(r, r, &tmpa, NULL); + } + if (i < state->ps[np].bits_na_lam && (n = state->ps[np].wnaf_na_lam[i])) { + ECMULT_TABLE_GET_GE(&tmpa, state->pre_a_lam + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A); + secp256k1_gej_add_ge_var(r, r, &tmpa, NULL); + } + } + if (i < bits_ng_1 && (n = wnaf_ng_1[i])) { + ECMULT_TABLE_GET_GE_STORAGE(&tmpa, *ctx->pre_g, n, WINDOW_G); + secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z); + } + if (i < bits_ng_128 && (n = wnaf_ng_128[i])) { + ECMULT_TABLE_GET_GE_STORAGE(&tmpa, *ctx->pre_g_128, n, WINDOW_G); + secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z); + } +#else + for (np = 0; np < no; ++np) { + if (i < state->ps[np].bits_na && (n = state->ps[np].wnaf_na[i])) { + ECMULT_TABLE_GET_GE(&tmpa, state->pre_a + np * ECMULT_TABLE_SIZE(WINDOW_A), n, WINDOW_A); + secp256k1_gej_add_ge_var(r, r, &tmpa, NULL); + } + } + if (i < bits_ng && (n = wnaf_ng[i])) { + ECMULT_TABLE_GET_GE_STORAGE(&tmpa, *ctx->pre_g, n, WINDOW_G); + secp256k1_gej_add_zinv_var(r, r, &tmpa, &Z); + } +#endif + } + + if (!r->infinity) { + secp256k1_fe_mul(&r->z, &r->z, &Z); + } +} + +static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_gej *a, const secp256k1_scalar *na, const secp256k1_scalar *ng) { + secp256k1_gej prej[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_fe zr[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_ge pre_a[ECMULT_TABLE_SIZE(WINDOW_A)]; + struct secp256k1_strauss_point_state ps[1]; +#ifdef USE_ENDOMORPHISM + secp256k1_ge pre_a_lam[ECMULT_TABLE_SIZE(WINDOW_A)]; +#endif + struct secp256k1_strauss_state state; + + state.prej = prej; + state.zr = zr; + state.pre_a = pre_a; +#ifdef USE_ENDOMORPHISM + state.pre_a_lam = pre_a_lam; +#endif + state.ps = ps; + secp256k1_ecmult_strauss_wnaf(ctx, &state, r, 1, a, na, ng); +} + +static size_t secp256k1_strauss_scratch_size(size_t n_points) { +#ifdef USE_ENDOMORPHISM + static const size_t point_size = (2 * sizeof(secp256k1_ge) + sizeof(secp256k1_gej) + sizeof(secp256k1_fe)) * ECMULT_TABLE_SIZE(WINDOW_A) + sizeof(struct secp256k1_strauss_point_state) + sizeof(secp256k1_gej) + sizeof(secp256k1_scalar); +#else + static const size_t point_size = (sizeof(secp256k1_ge) + sizeof(secp256k1_gej) + sizeof(secp256k1_fe)) * ECMULT_TABLE_SIZE(WINDOW_A) + sizeof(struct secp256k1_strauss_point_state) + sizeof(secp256k1_gej) + sizeof(secp256k1_scalar); +#endif + return n_points*point_size; +} + +static int secp256k1_ecmult_strauss_batch(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points, size_t cb_offset) { + secp256k1_gej* points; + secp256k1_scalar* scalars; + struct secp256k1_strauss_state state; + size_t i; + + secp256k1_gej_set_infinity(r); + if (inp_g_sc == NULL && n_points == 0) { + return 1; + } + + if (!secp256k1_scratch_allocate_frame(scratch, secp256k1_strauss_scratch_size(n_points), STRAUSS_SCRATCH_OBJECTS)) { + return 0; + } + points = (secp256k1_gej*)secp256k1_scratch_alloc(scratch, n_points * sizeof(secp256k1_gej)); + scalars = (secp256k1_scalar*)secp256k1_scratch_alloc(scratch, n_points * sizeof(secp256k1_scalar)); + state.prej = (secp256k1_gej*)secp256k1_scratch_alloc(scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_gej)); + state.zr = (secp256k1_fe*)secp256k1_scratch_alloc(scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_fe)); +#ifdef USE_ENDOMORPHISM + state.pre_a = (secp256k1_ge*)secp256k1_scratch_alloc(scratch, n_points * 2 * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_ge)); + state.pre_a_lam = state.pre_a + n_points * ECMULT_TABLE_SIZE(WINDOW_A); +#else + state.pre_a = (secp256k1_ge*)secp256k1_scratch_alloc(scratch, n_points * ECMULT_TABLE_SIZE(WINDOW_A) * sizeof(secp256k1_ge)); +#endif + state.ps = (struct secp256k1_strauss_point_state*)secp256k1_scratch_alloc(scratch, n_points * sizeof(struct secp256k1_strauss_point_state)); + + for (i = 0; i < n_points; i++) { + secp256k1_ge point; + if (!cb(&scalars[i], &point, i+cb_offset, cbdata)) { + secp256k1_scratch_deallocate_frame(scratch); + return 0; + } + secp256k1_gej_set_ge(&points[i], &point); + } + secp256k1_ecmult_strauss_wnaf(ctx, &state, r, n_points, points, scalars, inp_g_sc); + secp256k1_scratch_deallocate_frame(scratch); + return 1; +} + +/* Wrapper for secp256k1_ecmult_multi_func interface */ +static int secp256k1_ecmult_strauss_batch_single(const secp256k1_ecmult_context *actx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { + return secp256k1_ecmult_strauss_batch(actx, scratch, r, inp_g_sc, cb, cbdata, n, 0); +} + +static size_t secp256k1_strauss_max_points(secp256k1_scratch *scratch) { + return secp256k1_scratch_max_allocation(scratch, STRAUSS_SCRATCH_OBJECTS) / secp256k1_strauss_scratch_size(1); +} + +/** Convert a number to WNAF notation. + * The number becomes represented by sum(2^{wi} * wnaf[i], i=0..WNAF_SIZE(w)+1) - return_val. + * It has the following guarantees: + * - each wnaf[i] is either 0 or an odd integer between -(1 << w) and (1 << w) + * - the number of words set is always WNAF_SIZE(w) + * - the returned skew is 0 or 1 + */ +static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { + int skew = 0; + int pos; + int max_pos; + int last_w; + const secp256k1_scalar *work = s; + + if (secp256k1_scalar_is_zero(s)) { + for (pos = 0; pos < WNAF_SIZE(w); pos++) { + wnaf[pos] = 0; + } + return 0; + } + + if (secp256k1_scalar_is_even(s)) { + skew = 1; + } + + wnaf[0] = secp256k1_scalar_get_bits_var(work, 0, w) + skew; + /* Compute last window size. Relevant when window size doesn't divide the + * number of bits in the scalar */ + last_w = WNAF_BITS - (WNAF_SIZE(w) - 1) * w; + + /* Store the position of the first nonzero word in max_pos to allow + * skipping leading zeros when calculating the wnaf. */ + for (pos = WNAF_SIZE(w) - 1; pos > 0; pos--) { + int val = secp256k1_scalar_get_bits_var(work, pos * w, pos == WNAF_SIZE(w)-1 ? last_w : w); + if(val != 0) { + break; + } + wnaf[pos] = 0; + } + max_pos = pos; + pos = 1; + + while (pos <= max_pos) { + int val = secp256k1_scalar_get_bits_var(work, pos * w, pos == WNAF_SIZE(w)-1 ? last_w : w); + if ((val & 1) == 0) { + wnaf[pos - 1] -= (1 << w); + wnaf[pos] = (val + 1); + } else { + wnaf[pos] = val; + } + /* Set a coefficient to zero if it is 1 or -1 and the proceeding digit + * is strictly negative or strictly positive respectively. Only change + * coefficients at previous positions because above code assumes that + * wnaf[pos - 1] is odd. + */ + if (pos >= 2 && ((wnaf[pos - 1] == 1 && wnaf[pos - 2] < 0) || (wnaf[pos - 1] == -1 && wnaf[pos - 2] > 0))) { + if (wnaf[pos - 1] == 1) { + wnaf[pos - 2] += 1 << w; + } else { + wnaf[pos - 2] -= 1 << w; + } + wnaf[pos - 1] = 0; + } + ++pos; + } + + return skew; +} + +struct secp256k1_pippenger_point_state { + int skew_na; + size_t input_pos; +}; + +struct secp256k1_pippenger_state { + int *wnaf_na; + struct secp256k1_pippenger_point_state* ps; +}; + +/* + * pippenger_wnaf computes the result of a multi-point multiplication as + * follows: The scalars are brought into wnaf with n_wnaf elements each. Then + * for every i < n_wnaf, first each point is added to a "bucket" corresponding + * to the point's wnaf[i]. Second, the buckets are added together such that + * r += 1*bucket[0] + 3*bucket[1] + 5*bucket[2] + ... + */ +static int secp256k1_ecmult_pippenger_wnaf(secp256k1_gej *buckets, int bucket_window, struct secp256k1_pippenger_state *state, secp256k1_gej *r, const secp256k1_scalar *sc, const secp256k1_ge *pt, size_t num) { + size_t n_wnaf = WNAF_SIZE(bucket_window+1); + size_t np; + size_t no = 0; + int i; + int j; + + for (np = 0; np < num; ++np) { + if (secp256k1_scalar_is_zero(&sc[np]) || secp256k1_ge_is_infinity(&pt[np])) { + continue; + } + state->ps[no].input_pos = np; + state->ps[no].skew_na = secp256k1_wnaf_fixed(&state->wnaf_na[no*n_wnaf], &sc[np], bucket_window+1); + no++; + } + secp256k1_gej_set_infinity(r); + + if (no == 0) { + return 1; + } + + for (i = n_wnaf - 1; i >= 0; i--) { + secp256k1_gej running_sum; + + for(j = 0; j < ECMULT_TABLE_SIZE(bucket_window+2); j++) { + secp256k1_gej_set_infinity(&buckets[j]); + } + + for (np = 0; np < no; ++np) { + int n = state->wnaf_na[np*n_wnaf + i]; + struct secp256k1_pippenger_point_state point_state = state->ps[np]; + secp256k1_ge tmp; + int idx; + + if (i == 0) { + /* correct for wnaf skew */ + int skew = point_state.skew_na; + if (skew) { + secp256k1_ge_neg(&tmp, &pt[point_state.input_pos]); + secp256k1_gej_add_ge_var(&buckets[0], &buckets[0], &tmp, NULL); + } + } + if (n > 0) { + idx = (n - 1)/2; + secp256k1_gej_add_ge_var(&buckets[idx], &buckets[idx], &pt[point_state.input_pos], NULL); + } else if (n < 0) { + idx = -(n + 1)/2; + secp256k1_ge_neg(&tmp, &pt[point_state.input_pos]); + secp256k1_gej_add_ge_var(&buckets[idx], &buckets[idx], &tmp, NULL); + } + } + + for(j = 0; j < bucket_window; j++) { + secp256k1_gej_double_var(r, r, NULL); + } + + secp256k1_gej_set_infinity(&running_sum); + /* Accumulate the sum: bucket[0] + 3*bucket[1] + 5*bucket[2] + 7*bucket[3] + ... + * = bucket[0] + bucket[1] + bucket[2] + bucket[3] + ... + * + 2 * (bucket[1] + 2*bucket[2] + 3*bucket[3] + ...) + * using an intermediate running sum: + * running_sum = bucket[0] + bucket[1] + bucket[2] + ... + * + * The doubling is done implicitly by deferring the final window doubling (of 'r'). + */ + for(j = ECMULT_TABLE_SIZE(bucket_window+2) - 1; j > 0; j--) { + secp256k1_gej_add_var(&running_sum, &running_sum, &buckets[j], NULL); + secp256k1_gej_add_var(r, r, &running_sum, NULL); + } + + secp256k1_gej_add_var(&running_sum, &running_sum, &buckets[0], NULL); + secp256k1_gej_double_var(r, r, NULL); + secp256k1_gej_add_var(r, r, &running_sum, NULL); + } + return 1; +} + +/** + * Returns optimal bucket_window (number of bits of a scalar represented by a + * set of buckets) for a given number of points. + */ +static int secp256k1_pippenger_bucket_window(size_t n) { +#ifdef USE_ENDOMORPHISM + if (n <= 1) { + return 1; + } else if (n <= 4) { + return 2; + } else if (n <= 20) { + return 3; + } else if (n <= 57) { + return 4; + } else if (n <= 136) { + return 5; + } else if (n <= 235) { + return 6; + } else if (n <= 1260) { + return 7; + } else if (n <= 4420) { + return 9; + } else if (n <= 7880) { + return 10; + } else if (n <= 16050) { + return 11; + } else { + return PIPPENGER_MAX_BUCKET_WINDOW; + } +#else + if (n <= 1) { + return 1; + } else if (n <= 11) { + return 2; + } else if (n <= 45) { + return 3; + } else if (n <= 100) { + return 4; + } else if (n <= 275) { + return 5; + } else if (n <= 625) { + return 6; + } else if (n <= 1850) { + return 7; + } else if (n <= 3400) { + return 8; + } else if (n <= 9630) { + return 9; + } else if (n <= 17900) { + return 10; + } else if (n <= 32800) { + return 11; + } else { + return PIPPENGER_MAX_BUCKET_WINDOW; + } +#endif +} + +/** + * Returns the maximum optimal number of points for a bucket_window. + */ +static size_t secp256k1_pippenger_bucket_window_inv(int bucket_window) { + switch(bucket_window) { +#ifdef USE_ENDOMORPHISM + case 1: return 1; + case 2: return 4; + case 3: return 20; + case 4: return 57; + case 5: return 136; + case 6: return 235; + case 7: return 1260; + case 8: return 1260; + case 9: return 4420; + case 10: return 7880; + case 11: return 16050; + case PIPPENGER_MAX_BUCKET_WINDOW: return SIZE_MAX; +#else + case 1: return 1; + case 2: return 11; + case 3: return 45; + case 4: return 100; + case 5: return 275; + case 6: return 625; + case 7: return 1850; + case 8: return 3400; + case 9: return 9630; + case 10: return 17900; + case 11: return 32800; + case PIPPENGER_MAX_BUCKET_WINDOW: return SIZE_MAX; +#endif + } + return 0; +} + + +#ifdef USE_ENDOMORPHISM +SECP256K1_INLINE static void secp256k1_ecmult_endo_split(secp256k1_scalar *s1, secp256k1_scalar *s2, secp256k1_ge *p1, secp256k1_ge *p2) { + secp256k1_scalar tmp = *s1; + secp256k1_scalar_split_lambda(s1, s2, &tmp); + secp256k1_ge_mul_lambda(p2, p1); + + if (secp256k1_scalar_is_high(s1)) { + secp256k1_scalar_negate(s1, s1); + secp256k1_ge_neg(p1, p1); + } + if (secp256k1_scalar_is_high(s2)) { + secp256k1_scalar_negate(s2, s2); + secp256k1_ge_neg(p2, p2); + } +} +#endif + +/** + * Returns the scratch size required for a given number of points (excluding + * base point G) without considering alignment. + */ +static size_t secp256k1_pippenger_scratch_size(size_t n_points, int bucket_window) { +#ifdef USE_ENDOMORPHISM + size_t entries = 2*n_points + 2; +#else + size_t entries = n_points + 1; +#endif + size_t entry_size = sizeof(secp256k1_ge) + sizeof(secp256k1_scalar) + sizeof(struct secp256k1_pippenger_point_state) + (WNAF_SIZE(bucket_window+1)+1)*sizeof(int); + return ((1<ps = (struct secp256k1_pippenger_point_state *) secp256k1_scratch_alloc(scratch, entries * sizeof(*state_space->ps)); + state_space->wnaf_na = (int *) secp256k1_scratch_alloc(scratch, entries*(WNAF_SIZE(bucket_window+1)) * sizeof(int)); + buckets = (secp256k1_gej *) secp256k1_scratch_alloc(scratch, (1<ps[i].skew_na = 0; + for(j = 0; j < WNAF_SIZE(bucket_window+1); j++) { + state_space->wnaf_na[i * WNAF_SIZE(bucket_window+1) + j] = 0; + } + } + for(i = 0; i < 1< max_alloc) { + break; + } + space_for_points = max_alloc - space_overhead; + + n_points = space_for_points/entry_size; + n_points = n_points > max_points ? max_points : n_points; + if (n_points > res) { + res = n_points; + } + if (n_points < max_points) { + /* A larger bucket_window may support even more points. But if we + * would choose that then the caller couldn't safely use any number + * smaller than what this function returns */ + break; + } + } + return res; +} + +/* Computes ecmult_multi by simply multiplying and adding each point. Does not + * require a scratch space */ +static int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { + size_t point_idx; + secp256k1_scalar szero; + secp256k1_gej tmpj; + + secp256k1_scalar_set_int(&szero, 0); + /* r = inp_g_sc*G */ + secp256k1_gej_set_infinity(r); + secp256k1_ecmult(ctx, r, &tmpj, &szero, inp_g_sc); + for (point_idx = 0; point_idx < n_points; point_idx++) { + secp256k1_ge point; + secp256k1_gej pointj; + secp256k1_scalar scalar; + if (!cb(&scalar, &point, point_idx, cbdata)) { + return 0; + } + /* r += scalar*point */ + secp256k1_gej_set_ge(&pointj, &point); + secp256k1_ecmult(ctx, &tmpj, &pointj, &scalar, NULL); + secp256k1_gej_add_var(r, r, &tmpj, NULL); + } + return 1; +} + +typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t); +static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { + size_t i; + + int (*f)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t, size_t); + size_t max_points; + size_t n_batches; + size_t n_batch_points; + + secp256k1_gej_set_infinity(r); + if (inp_g_sc == NULL && n == 0) { + return 1; + } else if (n == 0) { + secp256k1_scalar szero; + secp256k1_scalar_set_int(&szero, 0); + secp256k1_ecmult(ctx, r, r, &szero, inp_g_sc); + return 1; + } + if (scratch == NULL) { + return secp256k1_ecmult_multi_var_simple(ctx, r, inp_g_sc, cb, cbdata, n); + } + + max_points = secp256k1_pippenger_max_points(scratch); + if (max_points == 0) { + return 0; + } else if (max_points > ECMULT_MAX_POINTS_PER_BATCH) { + max_points = ECMULT_MAX_POINTS_PER_BATCH; + } + n_batches = (n+max_points-1)/max_points; + n_batch_points = (n+n_batches-1)/n_batches; + + if (n_batch_points >= ECMULT_PIPPENGER_THRESHOLD) { + f = secp256k1_ecmult_pippenger_batch; + } else { + max_points = secp256k1_strauss_max_points(scratch); + if (max_points == 0) { + return 0; + } + n_batches = (n+max_points-1)/max_points; + n_batch_points = (n+n_batches-1)/n_batches; + f = secp256k1_ecmult_strauss_batch; + } + for(i = 0; i < n_batches; i++) { + size_t nbp = n < n_batch_points ? n : n_batch_points; + size_t offset = n_batch_points*i; + secp256k1_gej tmp; + if (!f(ctx, scratch, &tmp, i == 0 ? inp_g_sc : NULL, cb, cbdata, nbp, offset)) { + return 0; + } + secp256k1_gej_add_var(r, r, &tmp, NULL); + n -= nbp; + } + return 1; +} + +#endif /* SECP256K1_ECMULT_IMPL_H */ + +#endif + diff --git a/src/secp256k1/src/modules/musig/Makefile.am.include b/src/secp256k1/src/modules/musig/Makefile.am.include new file mode 100644 index 000000000..34583a23a --- /dev/null +++ b/src/secp256k1/src/modules/musig/Makefile.am.include @@ -0,0 +1,17 @@ +include_HEADERS += include/secp256k1_musig.h +noinst_HEADERS += src/modules/musig/main_impl.h +noinst_HEADERS += src/modules/musig/tests_impl.h + +noinst_PROGRAMS += example_musig +example_musig_SOURCES = src/modules/musig/example.c +example_musig_CPPFLAGS = -DSECP256K1_BUILD -I$(top_srcdir)/include $(SECP_INCLUDES) +if !ENABLE_COVERAGE +example_musig_CPPFLAGS += -DVERIFY +endif +example_musig_LDADD = libsecp256k1.la $(SECP_LIBS) +example_musig_LDFLAGS = -static + +if USE_TESTS +TESTS += example_musig +endif + diff --git a/src/secp256k1/src/modules/musig/example.c b/src/secp256k1/src/modules/musig/example.c new file mode 100644 index 000000000..ceae18686 --- /dev/null +++ b/src/secp256k1/src/modules/musig/example.c @@ -0,0 +1,166 @@ +/********************************************************************** + * Copyright (c) 2018 Jonas Nick * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +/** + * This file demonstrates how to use the MuSig module to create a multisignature. + * Additionally, see the documentation in include/secp256k1_musig.h. + */ + +#include +#include +#include +#include +#include + + /* Number of public keys involved in creating the aggregate signature */ +#define N_SIGNERS 3 + /* Create a key pair and store it in seckey and pubkey */ +int create_key(const secp256k1_context* ctx, unsigned char* seckey, secp256k1_pubkey* pubkey) { + int ret; + FILE *frand = fopen("/dev/urandom", "r"); + if (frand == NULL) { + return 0; + } + do { + if(!fread(seckey, 32, 1, frand)) { + fclose(frand); + return 0; + } + /* The probability that this not a valid secret key is approximately 2^-128 */ + } while (!secp256k1_ec_seckey_verify(ctx, seckey)); + fclose(frand); + ret = secp256k1_ec_pubkey_create(ctx, pubkey, seckey); + return ret; +} + +/* Sign a message hash with the given key pairs and store the result in sig */ +int sign(const secp256k1_context* ctx, unsigned char seckeys[][32], const secp256k1_pubkey* pubkeys, const unsigned char* msg32, secp256k1_schnorrsig *sig) { + secp256k1_musig_session musig_session[N_SIGNERS]; + unsigned char nonce_commitment[N_SIGNERS][32]; + const unsigned char *nonce_commitment_ptr[N_SIGNERS]; + secp256k1_musig_session_signer_data signer_data[N_SIGNERS][N_SIGNERS]; + secp256k1_pubkey nonce[N_SIGNERS]; + int i, j; + secp256k1_musig_partial_signature partial_sig[N_SIGNERS]; + + for (i = 0; i < N_SIGNERS; i++) { + FILE *frand; + unsigned char session_id32[32]; + unsigned char pk_hash[32]; + secp256k1_pubkey combined_pk; + + /* Create combined pubkey and initialize signer data */ + if (!secp256k1_musig_pubkey_combine(ctx, NULL, &combined_pk, pk_hash, pubkeys, N_SIGNERS)) { + return 0; + } + /* Create random session ID. It is absolutely necessary that the session ID + * is unique for every call of secp256k1_musig_session_initialize. Otherwise + * it's trivial for an attacker to extract the secret key! */ + frand = fopen("/dev/urandom", "r"); + if(frand == NULL) { + return 0; + } + if (!fread(session_id32, 32, 1, frand)) { + fclose(frand); + return 0; + } + fclose(frand); + /* Initialize session */ + if (!secp256k1_musig_session_initialize(ctx, &musig_session[i], signer_data[i], nonce_commitment[i], session_id32, msg32, &combined_pk, pk_hash, N_SIGNERS, i, seckeys[i])) { + return 0; + } + nonce_commitment_ptr[i] = &nonce_commitment[i][0]; + } + /* Communication round 1: Exchange nonce commitments */ + for (i = 0; i < N_SIGNERS; i++) { + /* Set nonce commitments in the signer data and get the own public nonce */ + if (!secp256k1_musig_session_get_public_nonce(ctx, &musig_session[i], signer_data[i], &nonce[i], nonce_commitment_ptr, N_SIGNERS)) { + return 0; + } + } + /* Communication round 2: Exchange nonces */ + for (i = 0; i < N_SIGNERS; i++) { + for (j = 0; j < N_SIGNERS; j++) { + if (!secp256k1_musig_set_nonce(ctx, &signer_data[i][j], &nonce[j])) { + /* Signer j's nonce does not match the nonce commitment. In this case + * abort the protocol. If you make another attempt at finishing the + * protocol, create a new session (with a fresh session ID!). */ + return 0; + } + } + if (!secp256k1_musig_session_combine_nonces(ctx, &musig_session[i], signer_data[i], N_SIGNERS, NULL, NULL)) { + return 0; + } + } + for (i = 0; i < N_SIGNERS; i++) { + if (!secp256k1_musig_partial_sign(ctx, &musig_session[i], &partial_sig[i])) { + return 0; + } + } + /* Communication round 3: Exchange partial signatures */ + for (i = 0; i < N_SIGNERS; i++) { + for (j = 0; j < N_SIGNERS; j++) { + /* To check whether signing was successful, it suffices to either verify + * the the combined signature with the combined public key using + * secp256k1_schnorrsig_verify, or verify all partial signatures of all + * signers individually. Verifying the combined signature is cheaper but + * verifying the individual partial signatures has the advantage that it + * can be used to determine which of the partial signatures are invalid + * (if any), i.e., which of the partial signatures cause the combined + * signature to be invalid and thus the protocol run to fail. It's also + * fine to first verify the combined sig, and only verify the individual + * sigs if it does not work. + */ + if (!secp256k1_musig_partial_sig_verify(ctx, &musig_session[i], &signer_data[i][j], &partial_sig[j], &pubkeys[j])) { + return 0; + } + } + } + return secp256k1_musig_partial_sig_combine(ctx, &musig_session[0], sig, partial_sig, N_SIGNERS); +} + + int main(void) { + secp256k1_context* ctx; + int i; + unsigned char seckeys[N_SIGNERS][32]; + secp256k1_pubkey pubkeys[N_SIGNERS]; + secp256k1_pubkey combined_pk; + unsigned char msg[32] = "this_could_be_the_hash_of_a_msg!"; + secp256k1_schnorrsig sig; + + /* Create a context for signing and verification */ + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + printf("Creating key pairs......"); + for (i = 0; i < N_SIGNERS; i++) { + if (!create_key(ctx, seckeys[i], &pubkeys[i])) { + printf("FAILED\n"); + return 1; + } + } + printf("ok\n"); + printf("Combining public keys..."); + if (!secp256k1_musig_pubkey_combine(ctx, NULL, &combined_pk, NULL, pubkeys, N_SIGNERS)) { + printf("FAILED\n"); + return 1; + } + printf("ok\n"); + printf("Signing message........."); + if (!sign(ctx, seckeys, pubkeys, msg, &sig)) { + printf("FAILED\n"); + return 1; + } + printf("ok\n"); + printf("Verifying signature....."); + if (!secp256k1_schnorrsig_verify(ctx, &sig, msg, &combined_pk)) { + printf("FAILED\n"); + return 1; + } + printf("ok\n"); + secp256k1_context_destroy(ctx); + return 0; +} + + diff --git a/src/secp256k1/src/modules/musig/main_impl.h b/src/secp256k1/src/modules/musig/main_impl.h new file mode 100644 index 000000000..dece823d6 --- /dev/null +++ b/src/secp256k1/src/modules/musig/main_impl.h @@ -0,0 +1,631 @@ + +/********************************************************************** + * Copyright (c) 2018 Andrew Poelstra, Jonas Nick * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_MODULE_MUSIG_MAIN_ +#define _SECP256K1_MODULE_MUSIG_MAIN_ + +#include "include/secp256k1.h" +#include "include/secp256k1_musig.h" +#include "hash.h" + +/* Computes ell = SHA256(pk[0], ..., pk[np-1]) */ +static int secp256k1_musig_compute_ell(const secp256k1_context *ctx, unsigned char *ell, const secp256k1_pubkey *pk, size_t np) { + secp256k1_sha256 sha; + size_t i; + + secp256k1_sha256_initialize(&sha); + for (i = 0; i < np; i++) { + unsigned char ser[33]; + size_t serlen = sizeof(ser); + if (!secp256k1_ec_pubkey_serialize(ctx, ser, &serlen, &pk[i], SECP256K1_EC_COMPRESSED)) { + return 0; + } + secp256k1_sha256_write(&sha, ser, serlen); + } + secp256k1_sha256_finalize(&sha, ell); + return 1; +} + +/* Initializes SHA256 with fixed midstate. This midstate was computed by applying + * SHA256 to SHA256("MuSig coefficient")||SHA256("MuSig coefficient"). */ +static void secp256k1_musig_sha256_init_tagged(secp256k1_sha256 *sha) { + secp256k1_sha256_initialize(sha); + + sha->s[0] = 0x0fd0690cul; + sha->s[1] = 0xfefeae97ul; + sha->s[2] = 0x996eac7ful; + sha->s[3] = 0x5c30d864ul; + sha->s[4] = 0x8c4a0573ul; + sha->s[5] = 0xaca1a22ful; + sha->s[6] = 0x6f43b801ul; + sha->s[7] = 0x85ce27cdul; + sha->bytes = 64; +} + +/* Compute r = SHA256(ell, idx). The four bytes of idx are serialized least significant byte first. */ +static void secp256k1_musig_coefficient(secp256k1_scalar *r, const unsigned char *ell, uint32_t idx) { + secp256k1_sha256 sha; + unsigned char buf[32]; + size_t i; + + secp256k1_musig_sha256_init_tagged(&sha); + secp256k1_sha256_write(&sha, ell, 32); + /* We're hashing the index of the signer instead of its public key as specified + * in the MuSig paper. This reduces the total amount of data that needs to be + * hashed. + * Additionally, it prevents creating identical musig_coefficients for identical + * public keys. A participant Bob could choose his public key to be the same as + * Alice's, then replay Alice's messages (nonce and partial signature) to create + * a valid partial signature. This is not a problem for MuSig per se, but could + * result in subtle issues with protocols building on threshold signatures. + * With the assumption that public keys are unique, hashing the index is + * equivalent to hashing the public key. Because the public key can be + * identified by the index given the ordered list of public keys (included in + * ell), the index is just a different encoding of the public key.*/ + for (i = 0; i < sizeof(uint32_t); i++) { + unsigned char c = idx; + secp256k1_sha256_write(&sha, &c, 1); + idx >>= 8; + } + secp256k1_sha256_finalize(&sha, buf); + secp256k1_scalar_set_b32(r, buf, NULL); +} + +typedef struct { + const secp256k1_context *ctx; + unsigned char ell[32]; + const secp256k1_pubkey *pks; +} secp256k1_musig_pubkey_combine_ecmult_data; + +/* Callback for batch EC multiplication to compute ell_0*P0 + ell_1*P1 + ... */ +static int secp256k1_musig_pubkey_combine_callback(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data) { + secp256k1_musig_pubkey_combine_ecmult_data *ctx = (secp256k1_musig_pubkey_combine_ecmult_data *) data; + secp256k1_musig_coefficient(sc, ctx->ell, idx); + return secp256k1_pubkey_load(ctx->ctx, pt, &ctx->pks[idx]); +} + + +static void secp256k1_musig_signers_init(secp256k1_musig_session_signer_data *signers, uint32_t n_signers) { + uint32_t i; + for (i = 0; i < n_signers; i++) { + memset(&signers[i], 0, sizeof(signers[i])); + signers[i].index = i; + signers[i].present = 0; + } +} + +int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, unsigned char *pk_hash32, const secp256k1_pubkey *pubkeys, size_t n_pubkeys) { + secp256k1_musig_pubkey_combine_ecmult_data ecmult_data; + secp256k1_gej pkj; + secp256k1_ge pkp; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(combined_pk != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(pubkeys != NULL); + ARG_CHECK(n_pubkeys > 0); + + ecmult_data.ctx = ctx; + ecmult_data.pks = pubkeys; + if (!secp256k1_musig_compute_ell(ctx, ecmult_data.ell, pubkeys, n_pubkeys)) { + return 0; + } + if (!secp256k1_ecmult_multi_var(&ctx->ecmult_ctx, scratch, &pkj, NULL, secp256k1_musig_pubkey_combine_callback, (void *) &ecmult_data, n_pubkeys)) { + return 0; + } + secp256k1_ge_set_gej(&pkp, &pkj); + secp256k1_pubkey_save(combined_pk, &pkp); + + if (pk_hash32 != NULL) { + memcpy(pk_hash32, ecmult_data.ell, 32); + } + return 1; +} + +int secp256k1_musig_session_initialize(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, unsigned char *nonce_commitment32, const unsigned char *session_id32, const unsigned char *msg32, const secp256k1_pubkey *combined_pk, const unsigned char *pk_hash32, size_t n_signers, size_t my_index, const unsigned char *seckey) { + unsigned char combined_ser[33]; + size_t combined_ser_size = sizeof(combined_ser); + int overflow; + secp256k1_scalar secret; + secp256k1_scalar mu; + secp256k1_sha256 sha; + secp256k1_gej rj; + secp256k1_ge rp; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + ARG_CHECK(session != NULL); + ARG_CHECK(signers != NULL); + ARG_CHECK(nonce_commitment32 != NULL); + ARG_CHECK(session_id32 != NULL); + ARG_CHECK(combined_pk != NULL); + ARG_CHECK(pk_hash32 != NULL); + ARG_CHECK(seckey != NULL); + + memset(session, 0, sizeof(*session)); + + if (msg32 != NULL) { + memcpy(session->msg, msg32, 32); + session->msg_is_set = 1; + } else { + session->msg_is_set = 0; + } + memcpy(&session->combined_pk, combined_pk, sizeof(*combined_pk)); + memcpy(session->pk_hash, pk_hash32, 32); + session->nonce_is_set = 0; + session->has_secret_data = 1; + if (n_signers == 0 || my_index >= n_signers) { + return 0; + } + if (n_signers > UINT32_MAX) { + return 0; + } + session->n_signers = (uint32_t) n_signers; + secp256k1_musig_signers_init(signers, session->n_signers); + session->nonce_commitments_hash_is_set = 0; + + /* Compute secret key */ + secp256k1_scalar_set_b32(&secret, seckey, &overflow); + if (overflow) { + secp256k1_scalar_clear(&secret); + return 0; + } + secp256k1_musig_coefficient(&mu, pk_hash32, (uint32_t) my_index); + secp256k1_scalar_mul(&secret, &secret, &mu); + secp256k1_scalar_get_b32(session->seckey, &secret); + + /* Compute secret nonce */ + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, session_id32, 32); + if (session->msg_is_set) { + secp256k1_sha256_write(&sha, msg32, 32); + } + secp256k1_ec_pubkey_serialize(ctx, combined_ser, &combined_ser_size, combined_pk, SECP256K1_EC_COMPRESSED); + secp256k1_sha256_write(&sha, combined_ser, combined_ser_size); + secp256k1_sha256_write(&sha, seckey, 32); + secp256k1_sha256_finalize(&sha, session->secnonce); + secp256k1_scalar_set_b32(&secret, session->secnonce, &overflow); + if (overflow) { + secp256k1_scalar_clear(&secret); + return 0; + } + + /* Compute public nonce and commitment */ + secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &rj, &secret); + secp256k1_ge_set_gej(&rp, &rj); + secp256k1_pubkey_save(&session->nonce, &rp); + + if (nonce_commitment32 != NULL) { + unsigned char commit[33]; + size_t commit_size = sizeof(commit); + secp256k1_sha256_initialize(&sha); + secp256k1_ec_pubkey_serialize(ctx, commit, &commit_size, &session->nonce, SECP256K1_EC_COMPRESSED); + secp256k1_sha256_write(&sha, commit, commit_size); + secp256k1_sha256_finalize(&sha, nonce_commitment32); + } + + secp256k1_scalar_clear(&secret); + return 1; +} + +int secp256k1_musig_session_get_public_nonce(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, secp256k1_pubkey *nonce, const unsigned char *const *commitments, size_t n_commitments) { + secp256k1_sha256 sha; + unsigned char nonce_commitments_hash[32]; + size_t i; + (void) ctx; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(session != NULL); + ARG_CHECK(signers != NULL); + ARG_CHECK(nonce != NULL); + ARG_CHECK(commitments != NULL); + + if (!session->has_secret_data || n_commitments != session->n_signers) { + return 0; + } + for (i = 0; i < n_commitments; i++) { + ARG_CHECK(commitments[i] != NULL); + } + + secp256k1_sha256_initialize(&sha); + for (i = 0; i < n_commitments; i++) { + memcpy(signers[i].nonce_commitment, commitments[i], 32); + secp256k1_sha256_write(&sha, commitments[i], 32); + } + secp256k1_sha256_finalize(&sha, nonce_commitments_hash); + if (session->nonce_commitments_hash_is_set + && memcmp(session->nonce_commitments_hash, nonce_commitments_hash, 32) != 0) { + /* Abort if get_public_nonce has been called before with a different array of + * commitments. */ + return 0; + } + memcpy(session->nonce_commitments_hash, nonce_commitments_hash, 32); + session->nonce_commitments_hash_is_set = 1; + memcpy(nonce, &session->nonce, sizeof(*nonce)); + return 1; +} + +int secp256k1_musig_session_initialize_verifier(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, const unsigned char *msg32, const secp256k1_pubkey *combined_pk, const unsigned char *pk_hash32, const unsigned char *const *commitments, size_t n_signers) { + size_t i; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(session != NULL); + ARG_CHECK(signers != NULL); + ARG_CHECK(combined_pk != NULL); + ARG_CHECK(pk_hash32 != NULL); + ARG_CHECK(commitments != NULL); + /* Check n_signers before checking commitments to allow testing the case where + * n_signers is big without allocating the space. */ + if (n_signers > UINT32_MAX) { + return 0; + } + for (i = 0; i < n_signers; i++) { + ARG_CHECK(commitments[i] != NULL); + } + (void) ctx; + + memset(session, 0, sizeof(*session)); + + memcpy(&session->combined_pk, combined_pk, sizeof(*combined_pk)); + if (n_signers == 0) { + return 0; + } + session->n_signers = (uint32_t) n_signers; + secp256k1_musig_signers_init(signers, session->n_signers); + + memcpy(session->pk_hash, pk_hash32, 32); + session->nonce_is_set = 0; + session->msg_is_set = 0; + if (msg32 != NULL) { + memcpy(session->msg, msg32, 32); + session->msg_is_set = 1; + } + session->has_secret_data = 0; + session->nonce_commitments_hash_is_set = 0; + + for (i = 0; i < n_signers; i++) { + memcpy(signers[i].nonce_commitment, commitments[i], 32); + } + return 1; +} + +int secp256k1_musig_set_nonce(const secp256k1_context* ctx, secp256k1_musig_session_signer_data *signer, const secp256k1_pubkey *nonce) { + unsigned char commit[33]; + size_t commit_size = sizeof(commit); + secp256k1_sha256 sha; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(signer != NULL); + ARG_CHECK(nonce != NULL); + + secp256k1_sha256_initialize(&sha); + secp256k1_ec_pubkey_serialize(ctx, commit, &commit_size, nonce, SECP256K1_EC_COMPRESSED); + secp256k1_sha256_write(&sha, commit, commit_size); + secp256k1_sha256_finalize(&sha, commit); + + if (memcmp(commit, signer->nonce_commitment, 32) != 0) { + return 0; + } + memcpy(&signer->nonce, nonce, sizeof(*nonce)); + signer->present = 1; + return 1; +} + +int secp256k1_musig_session_combine_nonces(const secp256k1_context* ctx, secp256k1_musig_session *session, const secp256k1_musig_session_signer_data *signers, size_t n_signers, int *nonce_is_negated, const secp256k1_pubkey *adaptor) { + secp256k1_gej combined_noncej; + secp256k1_ge combined_noncep; + secp256k1_ge noncep; + secp256k1_sha256 sha; + unsigned char nonce_commitments_hash[32]; + size_t i; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(session != NULL); + ARG_CHECK(signers != NULL); + + if (n_signers != session->n_signers) { + return 0; + } + secp256k1_sha256_initialize(&sha); + secp256k1_gej_set_infinity(&combined_noncej); + for (i = 0; i < n_signers; i++) { + if (!signers[i].present) { + return 0; + } + secp256k1_sha256_write(&sha, signers[i].nonce_commitment, 32); + secp256k1_pubkey_load(ctx, &noncep, &signers[i].nonce); + secp256k1_gej_add_ge_var(&combined_noncej, &combined_noncej, &noncep, NULL); + } + secp256k1_sha256_finalize(&sha, nonce_commitments_hash); + /* Either the session is a verifier session or or the nonce_commitments_hash has + * been set in `musig_session_get_public_nonce`. */ + VERIFY_CHECK(!session->has_secret_data || session->nonce_commitments_hash_is_set); + if (session->has_secret_data + && memcmp(session->nonce_commitments_hash, nonce_commitments_hash, 32) != 0) { + /* If the signers' commitments changed between get_public_nonce and now we + * have to abort because in that case they may have seen our nonce before + * creating their commitment. That can happen if the signer_data given to + * this function is different to the signer_data given to get_public_nonce. + * */ + return 0; + } + + /* Add public adaptor to nonce */ + if (adaptor != NULL) { + secp256k1_pubkey_load(ctx, &noncep, adaptor); + secp256k1_gej_add_ge_var(&combined_noncej, &combined_noncej, &noncep, NULL); + } + secp256k1_ge_set_gej(&combined_noncep, &combined_noncej); + if (secp256k1_fe_is_quad_var(&combined_noncep.y)) { + session->nonce_is_negated = 0; + } else { + session->nonce_is_negated = 1; + secp256k1_ge_neg(&combined_noncep, &combined_noncep); + } + if (nonce_is_negated != NULL) { + *nonce_is_negated = session->nonce_is_negated; + } + secp256k1_pubkey_save(&session->combined_nonce, &combined_noncep); + session->nonce_is_set = 1; + return 1; +} + +int secp256k1_musig_session_set_msg(const secp256k1_context* ctx, secp256k1_musig_session *session, const unsigned char *msg32) { + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(session != NULL); + ARG_CHECK(msg32 != NULL); + + if (session->msg_is_set) { + return 0; + } + memcpy(session->msg, msg32, 32); + session->msg_is_set = 1; + return 1; +} + +int secp256k1_musig_partial_signature_serialize(const secp256k1_context* ctx, unsigned char *out32, const secp256k1_musig_partial_signature* sig) { + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(out32 != NULL); + ARG_CHECK(sig != NULL); + memcpy(out32, sig->data, 32); + return 1; +} + +int secp256k1_musig_partial_signature_parse(const secp256k1_context* ctx, secp256k1_musig_partial_signature* sig, const unsigned char *in32) { + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(in32 != NULL); + memcpy(sig->data, in32, 32); + return 1; +} + +/* Compute msghash = SHA256(combined_nonce, combined_pk, msg) */ +static int secp256k1_musig_compute_messagehash(const secp256k1_context *ctx, unsigned char *msghash, const secp256k1_musig_session *session) { + unsigned char buf[33]; + size_t bufsize = 33; + secp256k1_ge rp; + secp256k1_sha256 sha; + + secp256k1_sha256_initialize(&sha); + if (!session->nonce_is_set) { + return 0; + } + secp256k1_pubkey_load(ctx, &rp, &session->combined_nonce); + secp256k1_fe_get_b32(buf, &rp.x); + secp256k1_sha256_write(&sha, buf, 32); + secp256k1_ec_pubkey_serialize(ctx, buf, &bufsize, &session->combined_pk, SECP256K1_EC_COMPRESSED); + VERIFY_CHECK(bufsize == 33); + secp256k1_sha256_write(&sha, buf, bufsize); + if (!session->msg_is_set) { + return 0; + } + secp256k1_sha256_write(&sha, session->msg, 32); + secp256k1_sha256_finalize(&sha, msghash); + return 1; +} + +int secp256k1_musig_partial_sign(const secp256k1_context* ctx, const secp256k1_musig_session *session, secp256k1_musig_partial_signature *partial_sig) { + unsigned char msghash[32]; + int overflow; + secp256k1_scalar sk; + secp256k1_scalar e, k; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(partial_sig != NULL); + ARG_CHECK(session != NULL); + + if (!session->nonce_is_set || !session->has_secret_data) { + return 0; + } + + /* build message hash */ + if (!secp256k1_musig_compute_messagehash(ctx, msghash, session)) { + return 0; + } + secp256k1_scalar_set_b32(&e, msghash, NULL); + + secp256k1_scalar_set_b32(&sk, session->seckey, &overflow); + if (overflow) { + secp256k1_scalar_clear(&sk); + return 0; + } + + secp256k1_scalar_set_b32(&k, session->secnonce, &overflow); + if (overflow || secp256k1_scalar_is_zero(&k)) { + secp256k1_scalar_clear(&sk); + secp256k1_scalar_clear(&k); + return 0; + } + if (session->nonce_is_negated) { + secp256k1_scalar_negate(&k, &k); + } + + /* Sign */ + secp256k1_scalar_mul(&e, &e, &sk); + secp256k1_scalar_add(&e, &e, &k); + secp256k1_scalar_get_b32(&partial_sig->data[0], &e); + secp256k1_scalar_clear(&sk); + secp256k1_scalar_clear(&k); + + return 1; +} + +int secp256k1_musig_partial_sig_combine(const secp256k1_context* ctx, const secp256k1_musig_session *session, secp256k1_schnorrsig *sig, const secp256k1_musig_partial_signature *partial_sigs, size_t n_sigs) { + size_t i; + secp256k1_scalar s; + secp256k1_ge noncep; + (void) ctx; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(partial_sigs != NULL); + ARG_CHECK(session != NULL); + + if (!session->nonce_is_set) { + return 0; + } + if (n_sigs != session->n_signers) { + return 0; + } + secp256k1_scalar_clear(&s); + for (i = 0; i < n_sigs; i++) { + int overflow; + secp256k1_scalar term; + + secp256k1_scalar_set_b32(&term, partial_sigs[i].data, &overflow); + if (overflow) { + return 0; + } + secp256k1_scalar_add(&s, &s, &term); + } + + secp256k1_pubkey_load(ctx, &noncep, &session->combined_nonce); + VERIFY_CHECK(secp256k1_fe_is_quad_var(&noncep.y)); + secp256k1_fe_normalize(&noncep.x); + secp256k1_fe_get_b32(&sig->data[0], &noncep.x); + secp256k1_scalar_get_b32(&sig->data[32], &s); + + return 1; +} + +int secp256k1_musig_partial_sig_verify(const secp256k1_context* ctx, const secp256k1_musig_session *session, const secp256k1_musig_session_signer_data *signer, const secp256k1_musig_partial_signature *partial_sig, const secp256k1_pubkey *pubkey) { + unsigned char msghash[32]; + secp256k1_scalar s; + secp256k1_scalar e; + secp256k1_scalar mu; + secp256k1_gej rj; + secp256k1_ge rp; + int overflow; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(session != NULL); + ARG_CHECK(signer != NULL); + ARG_CHECK(partial_sig != NULL); + ARG_CHECK(pubkey != NULL); + + if (!session->nonce_is_set || !signer->present) { + return 0; + } + secp256k1_scalar_set_b32(&s, partial_sig->data, &overflow); + if (overflow) { + return 0; + } + if (!secp256k1_musig_compute_messagehash(ctx, msghash, session)) { + return 0; + } + secp256k1_scalar_set_b32(&e, msghash, NULL); + + /* Multiplying the messagehash by the musig coefficient is equivalent + * to multiplying the signer's public key by the coefficient, except + * much easier to do. */ + secp256k1_musig_coefficient(&mu, session->pk_hash, signer->index); + secp256k1_scalar_mul(&e, &e, &mu); + + if (!secp256k1_pubkey_load(ctx, &rp, &signer->nonce)) { + return 0; + } + + if (!secp256k1_schnorrsig_real_verify(ctx, &rj, &s, &e, pubkey)) { + return 0; + } + if (!session->nonce_is_negated) { + secp256k1_ge_neg(&rp, &rp); + } + secp256k1_gej_add_ge_var(&rj, &rj, &rp, NULL); + + return secp256k1_gej_is_infinity(&rj); +} + +int secp256k1_musig_partial_sig_adapt(const secp256k1_context* ctx, secp256k1_musig_partial_signature *adaptor_sig, const secp256k1_musig_partial_signature *partial_sig, const unsigned char *sec_adaptor32, int nonce_is_negated) { + secp256k1_scalar s; + secp256k1_scalar t; + int overflow; + + (void) ctx; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(adaptor_sig != NULL); + ARG_CHECK(partial_sig != NULL); + ARG_CHECK(sec_adaptor32 != NULL); + + secp256k1_scalar_set_b32(&s, partial_sig->data, &overflow); + if (overflow) { + return 0; + } + secp256k1_scalar_set_b32(&t, sec_adaptor32, &overflow); + if (overflow) { + secp256k1_scalar_clear(&t); + return 0; + } + + if (nonce_is_negated) { + secp256k1_scalar_negate(&t, &t); + } + + secp256k1_scalar_add(&s, &s, &t); + secp256k1_scalar_get_b32(adaptor_sig->data, &s); + secp256k1_scalar_clear(&t); + return 1; +} + +int secp256k1_musig_extract_secret_adaptor(const secp256k1_context* ctx, unsigned char *sec_adaptor32, const secp256k1_schnorrsig *sig, const secp256k1_musig_partial_signature *partial_sigs, size_t n_partial_sigs, int nonce_is_negated) { + secp256k1_scalar t; + secp256k1_scalar s; + int overflow; + size_t i; + + (void) ctx; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sec_adaptor32 != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(partial_sigs != NULL); + + secp256k1_scalar_set_b32(&t, &sig->data[32], &overflow); + if (overflow) { + return 0; + } + secp256k1_scalar_negate(&t, &t); + + for (i = 0; i < n_partial_sigs; i++) { + secp256k1_scalar_set_b32(&s, partial_sigs[i].data, &overflow); + if (overflow) { + secp256k1_scalar_clear(&t); + return 0; + } + secp256k1_scalar_add(&t, &t, &s); + } + + if (!nonce_is_negated) { + secp256k1_scalar_negate(&t, &t); + } + secp256k1_scalar_get_b32(sec_adaptor32, &t); + secp256k1_scalar_clear(&t); + return 1; +} + +#endif + diff --git a/src/secp256k1/src/modules/musig/tests_impl.h b/src/secp256k1/src/modules/musig/tests_impl.h new file mode 100644 index 000000000..c58ae95af --- /dev/null +++ b/src/secp256k1/src/modules/musig/tests_impl.h @@ -0,0 +1,758 @@ +/********************************************************************** + * Copyright (c) 2018 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_MODULE_MUSIG_TESTS_ +#define _SECP256K1_MODULE_MUSIG_TESTS_ + +#include "secp256k1_musig.h" + +void musig_api_tests(secp256k1_scratch_space *scratch) { + secp256k1_scratch_space *scratch_small; + secp256k1_musig_session session[2]; + secp256k1_musig_session verifier_session; + secp256k1_musig_session_signer_data signer0[2]; + secp256k1_musig_session_signer_data signer1[2]; + secp256k1_musig_session_signer_data verifier_signer_data[2]; + secp256k1_musig_partial_signature partial_sig[2]; + secp256k1_musig_partial_signature partial_sig_adapted[2]; + secp256k1_musig_partial_signature partial_sig_overflow; + secp256k1_schnorrsig final_sig; + secp256k1_schnorrsig final_sig_cmp; + + unsigned char buf[32]; + unsigned char sk[2][32]; + unsigned char ones[32]; + unsigned char session_id[2][32]; + unsigned char nonce_commitment[2][32]; + int nonce_is_negated; + const unsigned char *ncs[2]; + unsigned char msg[32]; + unsigned char msghash[32]; + secp256k1_pubkey combined_pk; + unsigned char pk_hash[32]; + secp256k1_pubkey pk[2]; + + unsigned char sec_adaptor[32]; + unsigned char sec_adaptor1[32]; + secp256k1_pubkey adaptor; + + /** setup **/ + secp256k1_context *none = secp256k1_context_create(SECP256K1_CONTEXT_NONE); + secp256k1_context *sign = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); + secp256k1_context *vrfy = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); + int ecount; + + secp256k1_context_set_error_callback(none, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_error_callback(sign, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_error_callback(vrfy, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(none, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(sign, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(vrfy, counting_illegal_callback_fn, &ecount); + + memset(ones, 0xff, 32); + + secp256k1_rand256(session_id[0]); + secp256k1_rand256(session_id[1]); + secp256k1_rand256(sk[0]); + secp256k1_rand256(sk[1]); + secp256k1_rand256(msg); + secp256k1_rand256(sec_adaptor); + + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[0], sk[0]) == 1); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[1], sk[1]) == 1); + CHECK(secp256k1_ec_pubkey_create(ctx, &adaptor, sec_adaptor) == 1); + + /** main test body **/ + + /* Key combination */ + ecount = 0; + CHECK(secp256k1_musig_pubkey_combine(none, scratch, &combined_pk, pk_hash, pk, 2) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_pubkey_combine(sign, scratch, &combined_pk, pk_hash, pk, 2) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, pk, 2) == 1); + CHECK(ecount == 2); + /* pubkey_combine does not require a scratch space */ + CHECK(secp256k1_musig_pubkey_combine(vrfy, NULL, &combined_pk, pk_hash, pk, 2) == 1); + CHECK(ecount == 2); + /* If a scratch space is given it shouldn't be too small */ + scratch_small = secp256k1_scratch_space_create(ctx, 1); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch_small, &combined_pk, pk_hash, pk, 2) == 0); + secp256k1_scratch_space_destroy(scratch_small); + CHECK(ecount == 2); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, NULL, pk_hash, pk, 2) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, NULL, pk, 2) == 1); + CHECK(ecount == 3); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, NULL, 2) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, pk, 0) == 0); + CHECK(ecount == 5); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, NULL, 0) == 0); + CHECK(ecount == 6); + + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, pk, 2) == 1); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, pk, 2) == 1); + CHECK(secp256k1_musig_pubkey_combine(vrfy, scratch, &combined_pk, pk_hash, pk, 2) == 1); + + /** Session creation **/ + ecount = 0; + CHECK(secp256k1_musig_session_initialize(none, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_session_initialize(vrfy, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_musig_session_initialize(sign, NULL, signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], NULL, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, NULL, session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 5); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], NULL, msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 6); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], NULL, &combined_pk, pk_hash, 2, 0, sk[0]) == 1); + CHECK(ecount == 6); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, NULL, pk_hash, 2, 0, sk[0]) == 0); + CHECK(ecount == 7); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, NULL, 2, 0, sk[0]) == 0); + CHECK(ecount == 8); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 0, 0, sk[0]) == 0); + CHECK(ecount == 8); + /* If more than UINT32_MAX fits in a size_t, test that session_initialize + * rejects n_signers that high. */ + if (SIZE_MAX > UINT32_MAX) { + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, ((size_t) UINT32_MAX) + 2, 0, sk[0]) == 0); + } + CHECK(ecount == 8); + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, NULL) == 0); + CHECK(ecount == 9); + /* secret key overflows */ + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, ones) == 0); + CHECK(ecount == 9); + + + { + secp256k1_musig_session session_without_msg; + CHECK(secp256k1_musig_session_initialize(sign, &session_without_msg, signer0, nonce_commitment[0], session_id[0], NULL, &combined_pk, pk_hash, 2, 0, sk[0]) == 1); + CHECK(secp256k1_musig_session_set_msg(none, &session_without_msg, msg) == 1); + CHECK(secp256k1_musig_session_set_msg(none, &session_without_msg, msg) == 0); + } + CHECK(secp256k1_musig_session_initialize(sign, &session[0], signer0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 1); + CHECK(secp256k1_musig_session_initialize(sign, &session[1], signer1, nonce_commitment[1], session_id[1], msg, &combined_pk, pk_hash, 2, 1, sk[1]) == 1); + ncs[0] = nonce_commitment[0]; + ncs[1] = nonce_commitment[1]; + + ecount = 0; + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, pk_hash, ncs, 2) == 1); + CHECK(ecount == 0); + CHECK(secp256k1_musig_session_initialize_verifier(none, NULL, verifier_signer_data, msg, &combined_pk, pk_hash, ncs, 2) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, NULL, &combined_pk, pk_hash, ncs, 2) == 1); + CHECK(ecount == 1); + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, NULL, pk_hash, ncs, 2) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, NULL, ncs, 2) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, pk_hash, NULL, 2) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, pk_hash, ncs, 0) == 0); + CHECK(ecount == 4); + if (SIZE_MAX > UINT32_MAX) { + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, pk_hash, ncs, ((size_t) UINT32_MAX) + 2) == 0); + } + CHECK(ecount == 4); + CHECK(secp256k1_musig_session_initialize_verifier(none, &verifier_session, verifier_signer_data, msg, &combined_pk, pk_hash, ncs, 2) == 1); + + CHECK(secp256k1_musig_compute_messagehash(none, msghash, &verifier_session) == 0); + CHECK(secp256k1_musig_compute_messagehash(none, msghash, &session[0]) == 0); + + /** Signing step 0 -- exchange nonce commitments */ + ecount = 0; + { + secp256k1_pubkey nonce; + + /* Can obtain public nonce after commitments have been exchanged; still can't sign */ + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], signer0, &nonce, ncs, 2) == 1); + CHECK(secp256k1_musig_partial_sign(none, &session[0], &partial_sig[0]) == 0); + CHECK(ecount == 0); + } + + /** Signing step 1 -- exchange nonces */ + ecount = 0; + { + secp256k1_pubkey public_nonce[3]; + + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], signer0, &public_nonce[0], ncs, 2) == 1); + CHECK(ecount == 0); + CHECK(secp256k1_musig_session_get_public_nonce(none, NULL, signer0, &public_nonce[0], ncs, 2) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], NULL, &public_nonce[0], ncs, 2) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], signer0, NULL, ncs, 2) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], signer0, &public_nonce[0], NULL, 2) == 0); + CHECK(ecount == 4); + /* Number of commitments and number of signers are different */ + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], signer0, &public_nonce[0], ncs, 1) == 0); + CHECK(ecount == 4); + + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[0], signer0, &public_nonce[0], ncs, 2) == 1); + CHECK(secp256k1_musig_session_get_public_nonce(none, &session[1], signer1, &public_nonce[1], ncs, 2) == 1); + + CHECK(secp256k1_musig_set_nonce(none, &signer0[0], &public_nonce[0]) == 1); + CHECK(secp256k1_musig_set_nonce(none, &signer0[1], &public_nonce[0]) == 0); + CHECK(secp256k1_musig_set_nonce(none, &signer0[1], &public_nonce[1]) == 1); + CHECK(secp256k1_musig_set_nonce(none, &signer0[1], &public_nonce[1]) == 1); + CHECK(ecount == 4); + + CHECK(secp256k1_musig_set_nonce(none, NULL, &public_nonce[0]) == 0); + CHECK(ecount == 5); + CHECK(secp256k1_musig_set_nonce(none, &signer1[0], NULL) == 0); + CHECK(ecount == 6); + + CHECK(secp256k1_musig_set_nonce(none, &signer1[0], &public_nonce[0]) == 1); + CHECK(secp256k1_musig_set_nonce(none, &signer1[1], &public_nonce[1]) == 1); + CHECK(secp256k1_musig_set_nonce(none, &verifier_signer_data[0], &public_nonce[0]) == 1); + CHECK(secp256k1_musig_set_nonce(none, &verifier_signer_data[1], &public_nonce[1]) == 1); + + ecount = 0; + CHECK(secp256k1_musig_session_combine_nonces(none, &session[0], signer0, 2, &nonce_is_negated, &adaptor) == 1); + CHECK(secp256k1_musig_session_combine_nonces(none, NULL, signer0, 2, &nonce_is_negated, &adaptor) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_session_combine_nonces(none, &session[0], NULL, 2, &nonce_is_negated, &adaptor) == 0); + CHECK(ecount == 2); + /* Number of signers differs from number during intialization */ + CHECK(secp256k1_musig_session_combine_nonces(none, &session[0], signer0, 1, &nonce_is_negated, &adaptor) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_session_combine_nonces(none, &session[0], signer0, 2, NULL, &adaptor) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_musig_session_combine_nonces(none, &session[0], signer0, 2, &nonce_is_negated, NULL) == 1); + + CHECK(secp256k1_musig_session_combine_nonces(none, &session[0], signer0, 2, &nonce_is_negated, &adaptor) == 1); + CHECK(secp256k1_musig_session_combine_nonces(none, &session[1], signer0, 2, &nonce_is_negated, &adaptor) == 1); + CHECK(secp256k1_musig_session_combine_nonces(none, &verifier_session, verifier_signer_data, 2, &nonce_is_negated, &adaptor) == 1); + } + + /** Signing step 2 -- partial signatures */ + ecount = 0; + CHECK(secp256k1_musig_partial_sign(none, &session[0], &partial_sig[0]) == 1); + CHECK(ecount == 0); + CHECK(secp256k1_musig_partial_sign(none, NULL, &partial_sig[0]) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_partial_sign(none, &session[0], NULL) == 0); + CHECK(ecount == 2); + + CHECK(secp256k1_musig_partial_sign(none, &session[0], &partial_sig[0]) == 1); + CHECK(secp256k1_musig_partial_sign(none, &session[1], &partial_sig[1]) == 1); + /* observer can't sign */ + CHECK(secp256k1_musig_partial_sign(none, &verifier_session, &partial_sig[2]) == 0); + CHECK(ecount == 2); + + ecount = 0; + CHECK(secp256k1_musig_partial_signature_serialize(none, buf, &partial_sig[0]) == 1); + CHECK(secp256k1_musig_partial_signature_serialize(none, NULL, &partial_sig[0]) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_partial_signature_serialize(none, buf, NULL) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_signature_parse(none, &partial_sig[0], buf) == 1); + CHECK(secp256k1_musig_partial_signature_parse(none, NULL, buf) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_partial_signature_parse(none, &partial_sig[0], NULL) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_musig_partial_signature_parse(none, &partial_sig_overflow, ones) == 1); + + /** Partial signature verification */ + ecount = 0; + CHECK(secp256k1_musig_partial_sig_verify(none, &session[0], &signer0[0], &partial_sig[0], &pk[0]) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_partial_sig_verify(sign, &session[0], &signer0[0], &partial_sig[0], &pk[0]) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig[0], &pk[0]) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig[1], &pk[0]) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, NULL, &signer0[0], &partial_sig[0], &pk[0]) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], NULL, &partial_sig[0], &pk[0]) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], NULL, &pk[0]) == 0); + CHECK(ecount == 5); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig_overflow, &pk[0]) == 0); + CHECK(ecount == 5); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig[0], NULL) == 0); + CHECK(ecount == 6); + + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[0], &partial_sig[0], &pk[0]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[1], &signer1[0], &partial_sig[0], &pk[0]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[0], &signer0[1], &partial_sig[1], &pk[1]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &session[1], &signer1[1], &partial_sig[1], &pk[1]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &verifier_session, &verifier_signer_data[0], &partial_sig[0], &pk[0]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(vrfy, &verifier_session, &verifier_signer_data[1], &partial_sig[1], &pk[1]) == 1); + CHECK(ecount == 6); + + /** Adaptor signature verification */ + memcpy(&partial_sig_adapted[1], &partial_sig[1], sizeof(partial_sig_adapted[1])); + ecount = 0; + CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], &partial_sig[0], sec_adaptor, nonce_is_negated) == 1); + CHECK(secp256k1_musig_partial_sig_adapt(none, NULL, &partial_sig[0], sec_adaptor, 0) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], NULL, sec_adaptor, 0) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], &partial_sig_overflow, sec_adaptor, nonce_is_negated) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], &partial_sig[0], NULL, 0) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_musig_partial_sig_adapt(none, &partial_sig_adapted[0], &partial_sig[0], ones, nonce_is_negated) == 0); + CHECK(ecount == 3); + + /** Signing combining and verification */ + ecount = 0; + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], &final_sig, partial_sig_adapted, 2) == 1); + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], &final_sig_cmp, partial_sig_adapted, 2) == 1); + CHECK(memcmp(&final_sig, &final_sig_cmp, sizeof(final_sig)) == 0); + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], &final_sig_cmp, partial_sig_adapted, 2) == 1); + CHECK(memcmp(&final_sig, &final_sig_cmp, sizeof(final_sig)) == 0); + + CHECK(secp256k1_musig_partial_sig_combine(none, NULL, &final_sig, partial_sig_adapted, 2) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], NULL, partial_sig_adapted, 2) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], &final_sig, NULL, 2) == 0); + CHECK(ecount == 3); + { + secp256k1_musig_partial_signature partial_sig_tmp[2]; + partial_sig_tmp[0] = partial_sig_adapted[0]; + partial_sig_tmp[1] = partial_sig_overflow; + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], &final_sig, partial_sig_tmp, 2) == 0); + } + CHECK(ecount == 3); + /* Wrong number of partial sigs */ + CHECK(secp256k1_musig_partial_sig_combine(none, &session[0], &final_sig, partial_sig_adapted, 1) == 0); + CHECK(ecount == 3); + + CHECK(secp256k1_schnorrsig_verify(vrfy, &final_sig, msg, &combined_pk) == 1); + + /** Secret adaptor can be extracted from signature */ + ecount = 0; + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, &final_sig, partial_sig, 2, nonce_is_negated) == 1); + CHECK(memcmp(sec_adaptor, sec_adaptor1, 32) == 0); + CHECK(secp256k1_musig_extract_secret_adaptor(none, NULL, &final_sig, partial_sig, 2, 0) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, NULL, partial_sig, 2, 0) == 0); + CHECK(ecount == 2); + { + secp256k1_schnorrsig final_sig_tmp = final_sig; + memcpy(&final_sig_tmp.data[32], ones, 32); + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, &final_sig_tmp, partial_sig, 2, nonce_is_negated) == 0); + } + CHECK(ecount == 2); + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, &final_sig, NULL, 2, 0) == 0); + CHECK(ecount == 3); + { + secp256k1_musig_partial_signature partial_sig_tmp[2]; + partial_sig_tmp[0] = partial_sig[0]; + partial_sig_tmp[1] = partial_sig_overflow; + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, &final_sig, partial_sig_tmp, 2, nonce_is_negated) == 0); + } + CHECK(ecount == 3); + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, &final_sig, partial_sig, 0, 0) == 1); + CHECK(secp256k1_musig_extract_secret_adaptor(none, sec_adaptor1, &final_sig, partial_sig, 2, 1) == 1); + + /** cleanup **/ + memset(&session, 0, sizeof(session)); + secp256k1_context_destroy(none); + secp256k1_context_destroy(sign); + secp256k1_context_destroy(vrfy); +} + +/* Initializes two sessions, one use the given parameters (session_id, + * nonce_commitments, etc.) except that `session_tmp` uses new signers with different + * public keys. The point of this test is to call `musig_session_get_public_nonce` + * with signers from `session_tmp` who have different public keys than the correct + * ones and return the resulting messagehash. This should not result in a different + * messagehash because the public keys of the signers are only used during session + * initialization. */ +int musig_state_machine_diff_signer_msghash_test(unsigned char *msghash, secp256k1_pubkey *pks, secp256k1_pubkey *combined_pk, unsigned char *pk_hash, const unsigned char * const *nonce_commitments, unsigned char *msg, secp256k1_pubkey *nonce_other, unsigned char *sk, unsigned char *session_id) { + secp256k1_musig_session session; + secp256k1_musig_session session_tmp; + unsigned char nonce_commitment[32]; + secp256k1_musig_session_signer_data signers[2]; + secp256k1_musig_session_signer_data signers_tmp[2]; + unsigned char sk_dummy[32]; + secp256k1_pubkey pks_tmp[2]; + secp256k1_pubkey combined_pk_tmp; + unsigned char pk_hash_tmp[32]; + secp256k1_pubkey nonce; + + /* Set up signers with different public keys */ + secp256k1_rand256(sk_dummy); + pks_tmp[0] = pks[0]; + CHECK(secp256k1_ec_pubkey_create(ctx, &pks_tmp[1], sk_dummy) == 1); + CHECK(secp256k1_musig_pubkey_combine(ctx, NULL, &combined_pk_tmp, pk_hash_tmp, pks_tmp, 2) == 1); + CHECK(secp256k1_musig_session_initialize(ctx, &session_tmp, signers_tmp, nonce_commitment, session_id, msg, &combined_pk_tmp, pk_hash_tmp, 2, 0, sk_dummy) == 1); + + CHECK(secp256k1_musig_session_initialize(ctx, &session, signers, nonce_commitment, session_id, msg, combined_pk, pk_hash, 2, 0, sk) == 1); + CHECK(memcmp(nonce_commitment, nonce_commitments[1], 32) == 0); + /* Call get_public_nonce with different signers than the signers the session was + * initialized with. */ + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session_tmp, signers, &nonce, nonce_commitments, 2) == 1); + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session, signers_tmp, &nonce, nonce_commitments, 2) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[0], nonce_other) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], &nonce) == 1); + CHECK(secp256k1_musig_session_combine_nonces(ctx, &session, signers, 2, NULL, NULL) == 1); + + return secp256k1_musig_compute_messagehash(ctx, msghash, &session); +} + +/* Creates a new session (with a different session id) and tries to use that session + * to combine nonces with given signers_other. This should fail, because the nonce + * commitments of signers_other do not match the nonce commitments the new session + * was initialized with. If do_test is 0, the correct signers are being used and + * therefore the function should return 1. */ +int musig_state_machine_diff_signers_combine_nonce_test(secp256k1_pubkey *combined_pk, unsigned char *pk_hash, unsigned char *nonce_commitment_other, secp256k1_pubkey *nonce_other, unsigned char *msg, unsigned char *sk, secp256k1_musig_session_signer_data *signers_other, int do_test) { + secp256k1_musig_session session; + secp256k1_musig_session_signer_data signers[2]; + secp256k1_musig_session_signer_data *signers_to_use; + unsigned char nonce_commitment[32]; + unsigned char session_id[32]; + secp256k1_pubkey nonce; + const unsigned char *ncs[2]; + + /* Initialize new signers */ + secp256k1_rand256(session_id); + CHECK(secp256k1_musig_session_initialize(ctx, &session, signers, nonce_commitment, session_id, msg, combined_pk, pk_hash, 2, 1, sk) == 1); + ncs[0] = nonce_commitment_other; + ncs[1] = nonce_commitment; + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session, signers, &nonce, ncs, 2) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[0], nonce_other) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], &nonce) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], &nonce) == 1); + secp256k1_musig_session_combine_nonces(ctx, &session, signers_other, 2, NULL, NULL); + if (do_test) { + signers_to_use = signers_other; + } else { + signers_to_use = signers; + } + return secp256k1_musig_session_combine_nonces(ctx, &session, signers_to_use, 2, NULL, NULL); +} + +/* Recreates a session with the given session_id, signers, pk, msg etc. parameters + * and tries to sign and verify the other signers partial signature. Both should fail + * if msg is NULL. */ +int musig_state_machine_missing_msg_test(secp256k1_pubkey *pks, secp256k1_pubkey *combined_pk, unsigned char *pk_hash, unsigned char *nonce_commitment_other, secp256k1_pubkey *nonce_other, secp256k1_musig_partial_signature *partial_sig_other, unsigned char *sk, unsigned char *session_id, unsigned char *msg) { + secp256k1_musig_session session; + secp256k1_musig_session_signer_data signers[2]; + unsigned char nonce_commitment[32]; + const unsigned char *ncs[2]; + secp256k1_pubkey nonce; + secp256k1_musig_partial_signature partial_sig; + int partial_sign, partial_verify; + + CHECK(secp256k1_musig_session_initialize(ctx, &session, signers, nonce_commitment, session_id, msg, combined_pk, pk_hash, 2, 0, sk) == 1); + ncs[0] = nonce_commitment_other; + ncs[1] = nonce_commitment; + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session, signers, &nonce, ncs, 2) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[0], nonce_other) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], &nonce) == 1); + + CHECK(secp256k1_musig_session_combine_nonces(ctx, &session, signers, 2, NULL, NULL) == 1); + partial_sign = secp256k1_musig_partial_sign(ctx, &session, &partial_sig); + partial_verify = secp256k1_musig_partial_sig_verify(ctx, &session, &signers[0], partial_sig_other, &pks[0]); + if (msg != NULL) { + /* Return 1 if both succeeded */ + return partial_sign && partial_verify; + } + /* Return 0 if both failed */ + return partial_sign || partial_verify; +} + +/* Recreates a session with the given session_id, signers, pk, msg etc. parameters + * and tries to verify and combine partial sigs. If do_combine is 0, the + * combine_nonces step is left out. In that case verify and combine should fail and + * this function should return 0. */ +int musig_state_machine_missing_combine_test(secp256k1_pubkey *pks, secp256k1_pubkey *combined_pk, unsigned char *pk_hash, unsigned char *nonce_commitment_other, secp256k1_pubkey *nonce_other, secp256k1_musig_partial_signature *partial_sig_other, unsigned char *msg, unsigned char *sk, unsigned char *session_id, secp256k1_musig_partial_signature *partial_sig, int do_combine) { + secp256k1_musig_session session; + secp256k1_musig_session_signer_data signers[2]; + unsigned char nonce_commitment[32]; + const unsigned char *ncs[2]; + secp256k1_pubkey nonce; + secp256k1_musig_partial_signature partial_sigs[2]; + secp256k1_schnorrsig sig; + int partial_verify, sig_combine; + + CHECK(secp256k1_musig_session_initialize(ctx, &session, signers, nonce_commitment, session_id, msg, combined_pk, pk_hash, 2, 0, sk) == 1); + ncs[0] = nonce_commitment_other; + ncs[1] = nonce_commitment; + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session, signers, &nonce, ncs, 2) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[0], nonce_other) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers[1], &nonce) == 1); + + partial_sigs[0] = *partial_sig_other; + partial_sigs[1] = *partial_sig; + if (do_combine != 0) { + CHECK(secp256k1_musig_session_combine_nonces(ctx, &session, signers, 2, NULL, NULL) == 1); + } + partial_verify = secp256k1_musig_partial_sig_verify(ctx, &session, signers, partial_sig_other, &pks[0]); + sig_combine = secp256k1_musig_partial_sig_combine(ctx, &session, &sig, partial_sigs, 2); + if (do_combine != 0) { + /* Return 1 if both succeeded */ + return partial_verify && sig_combine; + } + /* Return 0 if both failed */ + return partial_verify || sig_combine; +} + +void musig_state_machine_tests(secp256k1_scratch_space *scratch) { + size_t i; + secp256k1_musig_session session[2]; + secp256k1_musig_session_signer_data signers0[2]; + secp256k1_musig_session_signer_data signers1[2]; + unsigned char nonce_commitment[2][32]; + unsigned char session_id[2][32]; + unsigned char msg[32]; + unsigned char sk[2][32]; + secp256k1_pubkey pk[2]; + secp256k1_pubkey combined_pk; + unsigned char pk_hash[32]; + secp256k1_pubkey nonce[2]; + const unsigned char *ncs[2]; + secp256k1_musig_partial_signature partial_sig[2]; + unsigned char msghash1[32]; + unsigned char msghash2[32]; + + /* Run state machine with the same objects twice to test that it's allowed to + * reinitialize session and session_signer_data. */ + for (i = 0; i < 2; i++) { + /* Setup */ + secp256k1_rand256(session_id[0]); + secp256k1_rand256(session_id[1]); + secp256k1_rand256(sk[0]); + secp256k1_rand256(sk[1]); + secp256k1_rand256(msg); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[0], sk[0]) == 1); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[1], sk[1]) == 1); + CHECK(secp256k1_musig_pubkey_combine(ctx, scratch, &combined_pk, pk_hash, pk, 2) == 1); + CHECK(secp256k1_musig_session_initialize(ctx, &session[0], signers0, nonce_commitment[0], session_id[0], msg, &combined_pk, pk_hash, 2, 0, sk[0]) == 1); + CHECK(secp256k1_musig_session_initialize(ctx, &session[1], signers1, nonce_commitment[1], session_id[1], msg, &combined_pk, pk_hash, 2, 1, sk[1]) == 1); + + /* Set nonce commitments */ + ncs[0] = nonce_commitment[0]; + ncs[1] = nonce_commitment[1]; + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[0], signers0, &nonce[0], ncs, 2) == 1); + /* Changing a nonce commitment is not okay */ + ncs[1] = (unsigned char*) "this isn't a nonce commitment..."; + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[0], signers0, &nonce[0], ncs, 2) == 0); + /* Repeating with the same nonce commitments is okay */ + ncs[1] = nonce_commitment[1]; + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[0], signers0, &nonce[0], ncs, 2) == 1); + + /* Get nonce for signer 1 */ + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &session[1], signers1, &nonce[1], ncs, 2) == 1); + + /* Set nonces */ + CHECK(secp256k1_musig_set_nonce(ctx, &signers0[0], &nonce[0]) == 1); + /* Can't set nonce that doesn't match nonce commitment */ + CHECK(secp256k1_musig_set_nonce(ctx, &signers0[1], &nonce[0]) == 0); + /* Set correct nonce */ + CHECK(secp256k1_musig_set_nonce(ctx, &signers0[1], &nonce[1]) == 1); + + /* Combine nonces */ + CHECK(secp256k1_musig_session_combine_nonces(ctx, &session[0], signers0, 2, NULL, NULL) == 1); + /* Not everyone is present from signer 1's view */ + CHECK(secp256k1_musig_session_combine_nonces(ctx, &session[1], signers1, 2, NULL, NULL) == 0); + /* Make everyone present */ + CHECK(secp256k1_musig_set_nonce(ctx, &signers1[0], &nonce[0]) == 1); + CHECK(secp256k1_musig_set_nonce(ctx, &signers1[1], &nonce[1]) == 1); + + /* Can't combine nonces from signers of a different session */ + CHECK(musig_state_machine_diff_signers_combine_nonce_test(&combined_pk, pk_hash, nonce_commitment[0], &nonce[0], msg, sk[1], signers1, 1) == 0); + CHECK(musig_state_machine_diff_signers_combine_nonce_test(&combined_pk, pk_hash, nonce_commitment[0], &nonce[0], msg, sk[1], signers1, 0) == 1); + + /* Partially sign */ + CHECK(secp256k1_musig_partial_sign(ctx, &session[0], &partial_sig[0]) == 1); + /* Can't verify or sign until nonce is combined */ + CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[1], &signers1[0], &partial_sig[0], &pk[0]) == 0); + CHECK(secp256k1_musig_partial_sign(ctx, &session[1], &partial_sig[1]) == 0); + CHECK(secp256k1_musig_session_combine_nonces(ctx, &session[1], signers1, 2, NULL, NULL) == 1); + CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[1], &signers1[0], &partial_sig[0], &pk[0]) == 1); + /* messagehash should be the same as a session whose get_public_nonce was called + * with different signers (i.e. they diff in public keys). This is because the + * public keys of the signers is set in stone when initializing the session. */ + CHECK(secp256k1_musig_compute_messagehash(ctx, msghash1, &session[1]) == 1); + CHECK(musig_state_machine_diff_signer_msghash_test(msghash2, pk, &combined_pk, pk_hash, ncs, msg, &nonce[0], sk[1], session_id[1]) == 1); + CHECK(memcmp(msghash1, msghash2, 32) == 0); + CHECK(secp256k1_musig_partial_sign(ctx, &session[1], &partial_sig[1]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[1], &signers1[1], &partial_sig[1], &pk[1]) == 1); + /* Wrong signature */ + CHECK(secp256k1_musig_partial_sig_verify(ctx, &session[1], &signers1[1], &partial_sig[0], &pk[1]) == 0); + /* Can't sign or verify until msg is set */ + CHECK(musig_state_machine_missing_msg_test(pk, &combined_pk, pk_hash, nonce_commitment[0], &nonce[0], &partial_sig[0], sk[1], session_id[1], NULL) == 0); + CHECK(musig_state_machine_missing_msg_test(pk, &combined_pk, pk_hash, nonce_commitment[0], &nonce[0], &partial_sig[0], sk[1], session_id[1], msg) == 1); + + /* Can't verify and combine partial sigs until nonces are combined */ + CHECK(musig_state_machine_missing_combine_test(pk, &combined_pk, pk_hash, nonce_commitment[0], &nonce[0], &partial_sig[0], msg, sk[1], session_id[1], &partial_sig[1], 0) == 0); + CHECK(musig_state_machine_missing_combine_test(pk, &combined_pk, pk_hash, nonce_commitment[0], &nonce[0], &partial_sig[0], msg, sk[1], session_id[1], &partial_sig[1], 1) == 1); + } +} + +void scriptless_atomic_swap(secp256k1_scratch_space *scratch) { + /* Throughout this test "a" and "b" refer to two hypothetical blockchains, + * while the indices 0 and 1 refer to the two signers. Here signer 0 is + * sending a-coins to signer 1, while signer 1 is sending b-coins to signer + * 0. Signer 0 produces the adaptor signatures. */ + secp256k1_schnorrsig final_sig_a; + secp256k1_schnorrsig final_sig_b; + secp256k1_musig_partial_signature partial_sig_a[2]; + secp256k1_musig_partial_signature partial_sig_b_adapted[2]; + secp256k1_musig_partial_signature partial_sig_b[2]; + unsigned char sec_adaptor[32]; + unsigned char sec_adaptor_extracted[32]; + secp256k1_pubkey pub_adaptor; + + unsigned char seckey_a[2][32]; + unsigned char seckey_b[2][32]; + secp256k1_pubkey pk_a[2]; + secp256k1_pubkey pk_b[2]; + unsigned char pk_hash_a[32]; + unsigned char pk_hash_b[32]; + secp256k1_pubkey combined_pk_a; + secp256k1_pubkey combined_pk_b; + secp256k1_musig_session musig_session_a[2]; + secp256k1_musig_session musig_session_b[2]; + unsigned char noncommit_a[2][32]; + unsigned char noncommit_b[2][32]; + const unsigned char *noncommit_a_ptr[2]; + const unsigned char *noncommit_b_ptr[2]; + secp256k1_pubkey pubnon_a[2]; + secp256k1_pubkey pubnon_b[2]; + int nonce_is_negated_a; + int nonce_is_negated_b; + secp256k1_musig_session_signer_data data_a[2]; + secp256k1_musig_session_signer_data data_b[2]; + + const unsigned char seed[32] = "still tired of choosing seeds..."; + const unsigned char msg32_a[32] = "this is the message blockchain a"; + const unsigned char msg32_b[32] = "this is the message blockchain b"; + + /* Step 1: key setup */ + secp256k1_rand256(seckey_a[0]); + secp256k1_rand256(seckey_a[1]); + secp256k1_rand256(seckey_b[0]); + secp256k1_rand256(seckey_b[1]); + secp256k1_rand256(sec_adaptor); + + CHECK(secp256k1_ec_pubkey_create(ctx, &pk_a[0], seckey_a[0])); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk_a[1], seckey_a[1])); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk_b[0], seckey_b[0])); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk_b[1], seckey_b[1])); + CHECK(secp256k1_ec_pubkey_create(ctx, &pub_adaptor, sec_adaptor)); + + CHECK(secp256k1_musig_pubkey_combine(ctx, scratch, &combined_pk_a, pk_hash_a, pk_a, 2)); + CHECK(secp256k1_musig_pubkey_combine(ctx, scratch, &combined_pk_b, pk_hash_b, pk_b, 2)); + + CHECK(secp256k1_musig_session_initialize(ctx, &musig_session_a[0], data_a, noncommit_a[0], seed, msg32_a, &combined_pk_a, pk_hash_a, 2, 0, seckey_a[0])); + CHECK(secp256k1_musig_session_initialize(ctx, &musig_session_a[1], data_a, noncommit_a[1], seed, msg32_a, &combined_pk_a, pk_hash_a, 2, 1, seckey_a[1])); + noncommit_a_ptr[0] = noncommit_a[0]; + noncommit_a_ptr[1] = noncommit_a[1]; + + CHECK(secp256k1_musig_session_initialize(ctx, &musig_session_b[0], data_b, noncommit_b[0], seed, msg32_b, &combined_pk_b, pk_hash_b, 2, 0, seckey_b[0])); + CHECK(secp256k1_musig_session_initialize(ctx, &musig_session_b[1], data_b, noncommit_b[1], seed, msg32_b, &combined_pk_b, pk_hash_b, 2, 1, seckey_b[1])); + noncommit_b_ptr[0] = noncommit_b[0]; + noncommit_b_ptr[1] = noncommit_b[1]; + + /* Step 2: Exchange nonces */ + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &musig_session_a[0], data_a, &pubnon_a[0], noncommit_a_ptr, 2)); + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &musig_session_a[1], data_a, &pubnon_a[1], noncommit_a_ptr, 2)); + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &musig_session_b[0], data_b, &pubnon_b[0], noncommit_b_ptr, 2)); + CHECK(secp256k1_musig_session_get_public_nonce(ctx, &musig_session_b[1], data_b, &pubnon_b[1], noncommit_b_ptr, 2)); + CHECK(secp256k1_musig_set_nonce(ctx, &data_a[0], &pubnon_a[0])); + CHECK(secp256k1_musig_set_nonce(ctx, &data_a[1], &pubnon_a[1])); + CHECK(secp256k1_musig_set_nonce(ctx, &data_b[0], &pubnon_b[0])); + CHECK(secp256k1_musig_set_nonce(ctx, &data_b[1], &pubnon_b[1])); + CHECK(secp256k1_musig_session_combine_nonces(ctx, &musig_session_a[0], data_a, 2, &nonce_is_negated_a, &pub_adaptor)); + CHECK(secp256k1_musig_session_combine_nonces(ctx, &musig_session_a[1], data_a, 2, NULL, &pub_adaptor)); + CHECK(secp256k1_musig_session_combine_nonces(ctx, &musig_session_b[0], data_b, 2, &nonce_is_negated_b, &pub_adaptor)); + CHECK(secp256k1_musig_session_combine_nonces(ctx, &musig_session_b[1], data_b, 2, NULL, &pub_adaptor)); + + /* Step 3: Signer 0 produces partial signatures for both chains. */ + CHECK(secp256k1_musig_partial_sign(ctx, &musig_session_a[0], &partial_sig_a[0])); + CHECK(secp256k1_musig_partial_sign(ctx, &musig_session_b[0], &partial_sig_b[0])); + + /* Step 4: Signer 1 receives partial signatures, verifies them and creates a + * partial signature to send B-coins to signer 0. */ + CHECK(secp256k1_musig_partial_sig_verify(ctx, &musig_session_a[1], data_a, &partial_sig_a[0], &pk_a[0]) == 1); + CHECK(secp256k1_musig_partial_sig_verify(ctx, &musig_session_b[1], data_b, &partial_sig_b[0], &pk_b[0]) == 1); + CHECK(secp256k1_musig_partial_sign(ctx, &musig_session_b[1], &partial_sig_b[1])); + + /* Step 5: Signer 0 adapts its own partial signature and combines it with the + * partial signature from signer 1. This results in a complete signature which + * is broadcasted by signer 0 to take B-coins. */ + CHECK(secp256k1_musig_partial_sig_adapt(ctx, &partial_sig_b_adapted[0], &partial_sig_b[0], sec_adaptor, nonce_is_negated_b)); + memcpy(&partial_sig_b_adapted[1], &partial_sig_b[1], sizeof(partial_sig_b_adapted[1])); + CHECK(secp256k1_musig_partial_sig_combine(ctx, &musig_session_b[0], &final_sig_b, partial_sig_b_adapted, 2) == 1); + CHECK(secp256k1_schnorrsig_verify(ctx, &final_sig_b, msg32_b, &combined_pk_b) == 1); + + /* Step 6: Signer 1 extracts adaptor from the published signature, applies it to + * other partial signature, and takes A-coins. */ + CHECK(secp256k1_musig_extract_secret_adaptor(ctx, sec_adaptor_extracted, &final_sig_b, partial_sig_b, 2, nonce_is_negated_b) == 1); + CHECK(memcmp(sec_adaptor_extracted, sec_adaptor, sizeof(sec_adaptor)) == 0); /* in real life we couldn't check this, of course */ + CHECK(secp256k1_musig_partial_sig_adapt(ctx, &partial_sig_a[0], &partial_sig_a[0], sec_adaptor_extracted, nonce_is_negated_a)); + CHECK(secp256k1_musig_partial_sign(ctx, &musig_session_a[1], &partial_sig_a[1])); + CHECK(secp256k1_musig_partial_sig_combine(ctx, &musig_session_a[1], &final_sig_a, partial_sig_a, 2) == 1); + CHECK(secp256k1_schnorrsig_verify(ctx, &final_sig_a, msg32_a, &combined_pk_a) == 1); +} + +/* Checks that hash initialized by secp256k1_musig_sha256_init_tagged has the + * expected state. */ +void sha256_tag_test(void) { + char tag[17] = "MuSig coefficient"; + secp256k1_sha256 sha; + secp256k1_sha256 sha_tagged; + unsigned char buf[32]; + unsigned char buf2[32]; + size_t i; + + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, (unsigned char *) tag, 17); + secp256k1_sha256_finalize(&sha, buf); + /* buf = SHA256("MuSig coefficient") */ + + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, buf, 32); + secp256k1_sha256_write(&sha, buf, 32); + /* Is buffer fully consumed? */ + CHECK((sha.bytes & 0x3F) == 0); + + /* Compare with tagged SHA */ + secp256k1_musig_sha256_init_tagged(&sha_tagged); + for (i = 0; i < 8; i++) { + CHECK(sha_tagged.s[i] == sha.s[i]); + } + secp256k1_sha256_write(&sha, buf, 32); + secp256k1_sha256_write(&sha_tagged, buf, 32); + secp256k1_sha256_finalize(&sha, buf); + secp256k1_sha256_finalize(&sha_tagged, buf2); + CHECK(memcmp(buf, buf2, 32) == 0); +} + +void run_musig_tests(void) { + int i; + secp256k1_scratch_space *scratch = secp256k1_scratch_space_create(ctx, 1024 * 1024); + + musig_api_tests(scratch); + musig_state_machine_tests(scratch); + for (i = 0; i < count; i++) { + /* Run multiple times to ensure that the nonce is negated in some tests */ + scriptless_atomic_swap(scratch); + } + sha256_tag_test(); + + secp256k1_scratch_space_destroy(scratch); +} + +#endif + diff --git a/src/secp256k1/src/modules/schnorrsig/Makefile.am.include b/src/secp256k1/src/modules/schnorrsig/Makefile.am.include new file mode 100644 index 000000000..0296c1299 --- /dev/null +++ b/src/secp256k1/src/modules/schnorrsig/Makefile.am.include @@ -0,0 +1,9 @@ +include_HEADERS += include/secp256k1_schnorrsig.h +noinst_HEADERS += src/modules/schnorrsig/main_impl.h +noinst_HEADERS += src/modules/schnorrsig/tests_impl.h +if USE_BENCHMARK +noinst_PROGRAMS += bench_schnorrsig +bench_schnorrsig_SOURCES = src/bench_schnorrsig.c +bench_schnorrsig_LDADD = libsecp256k1.la $(SECP_LIBS) $(COMMON_LIB) +endif + diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h new file mode 100644 index 000000000..b366236d8 --- /dev/null +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -0,0 +1,339 @@ +/********************************************************************** + * Copyright (c) 2018 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_MODULE_SCHNORRSIG_MAIN_ +#define _SECP256K1_MODULE_SCHNORRSIG_MAIN_ + +#include "include/secp256k1.h" +#include "include/secp256k1_schnorrsig.h" +#include "hash.h" + +int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { + (void) ctx; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(out64 != NULL); + ARG_CHECK(sig != NULL); + memcpy(out64, sig->data, 64); + return 1; +} + +int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64) { + (void) ctx; + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(sig != NULL); + ARG_CHECK(in64 != NULL); + memcpy(sig->data, in64, 64); + return 1; +} + +int secp256k1_schnorrsig_sign(const secp256k1_context* ctx, secp256k1_schnorrsig *sig, int *nonce_is_negated, const unsigned char *msg32, const unsigned char *seckey, secp256k1_nonce_function noncefp, void *ndata) { + secp256k1_scalar x; + secp256k1_scalar e; + secp256k1_scalar k; + secp256k1_gej pkj; + secp256k1_gej rj; + secp256k1_ge pk; + secp256k1_ge r; + secp256k1_sha256 sha; + int overflow; + unsigned char buf[33]; + size_t buflen = sizeof(buf); + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_gen_context_is_built(&ctx->ecmult_gen_ctx)); + ARG_CHECK(sig != NULL); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(seckey != NULL); + + if (noncefp == NULL) { + noncefp = secp256k1_nonce_function_bipschnorr; + } + secp256k1_scalar_set_b32(&x, seckey, &overflow); + /* Fail if the secret key is invalid. */ + if (overflow || secp256k1_scalar_is_zero(&x)) { + memset(sig, 0, sizeof(*sig)); + return 0; + } + + secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pkj, &x); + secp256k1_ge_set_gej(&pk, &pkj); + + if (!noncefp(buf, msg32, seckey, NULL, (void*)ndata, 0)) { + return 0; + } + secp256k1_scalar_set_b32(&k, buf, NULL); + if (secp256k1_scalar_is_zero(&k)) { + return 0; + } + + secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &rj, &k); + secp256k1_ge_set_gej(&r, &rj); + + if (nonce_is_negated != NULL) { + *nonce_is_negated = 0; + } + if (!secp256k1_fe_is_quad_var(&r.y)) { + secp256k1_scalar_negate(&k, &k); + if (nonce_is_negated != NULL) { + *nonce_is_negated = 1; + } + } + secp256k1_fe_normalize(&r.x); + secp256k1_fe_get_b32(&sig->data[0], &r.x); + + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, &sig->data[0], 32); + secp256k1_eckey_pubkey_serialize(&pk, buf, &buflen, 1); + secp256k1_sha256_write(&sha, buf, buflen); + secp256k1_sha256_write(&sha, msg32, 32); + secp256k1_sha256_finalize(&sha, buf); + + secp256k1_scalar_set_b32(&e, buf, NULL); + secp256k1_scalar_mul(&e, &e, &x); + secp256k1_scalar_add(&e, &e, &k); + + secp256k1_scalar_get_b32(&sig->data[32], &e); + secp256k1_scalar_clear(&k); + secp256k1_scalar_clear(&x); + + return 1; +} + +/* Helper function for verification and batch verification. + * Computes R = sG - eP. */ +static int secp256k1_schnorrsig_real_verify(const secp256k1_context* ctx, secp256k1_gej *rj, const secp256k1_scalar *s, const secp256k1_scalar *e, const secp256k1_pubkey *pk) { + secp256k1_scalar nege; + secp256k1_ge pkp; + secp256k1_gej pkj; + + secp256k1_scalar_negate(&nege, e); + + if (!secp256k1_pubkey_load(ctx, &pkp, pk)) { + return 0; + } + secp256k1_gej_set_ge(&pkj, &pkp); + + /* rj = s*G + (-e)*pkj */ + secp256k1_ecmult(&ctx->ecmult_ctx, rj, &pkj, &nege, s); + return 1; +} + +int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk) { + secp256k1_scalar s; + secp256k1_scalar e; + secp256k1_gej rj; + secp256k1_fe rx; + secp256k1_sha256 sha; + unsigned char buf[33]; + size_t buflen = sizeof(buf); + int overflow; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(sig != NULL); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(pk != NULL); + + if (!secp256k1_fe_set_b32(&rx, &sig->data[0])) { + return 0; + } + + secp256k1_scalar_set_b32(&s, &sig->data[32], &overflow); + if (overflow) { + return 0; + } + + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, &sig->data[0], 32); + secp256k1_ec_pubkey_serialize(ctx, buf, &buflen, pk, SECP256K1_EC_COMPRESSED); + secp256k1_sha256_write(&sha, buf, buflen); + secp256k1_sha256_write(&sha, msg32, 32); + secp256k1_sha256_finalize(&sha, buf); + secp256k1_scalar_set_b32(&e, buf, NULL); + + if (!secp256k1_schnorrsig_real_verify(ctx, &rj, &s, &e, pk) + || !secp256k1_gej_has_quad_y_var(&rj) /* fails if rj is infinity */ + || !secp256k1_gej_eq_x_var(&rx, &rj)) { + return 0; + } + + return 1; +} + +/* Data that is used by the batch verification ecmult callback */ +typedef struct { + const secp256k1_context *ctx; + /* Seed for the random number generator */ + unsigned char chacha_seed[32]; + /* Caches randomizers generated by the PRNG which returns two randomizers per call. Caching + * avoids having to call the PRNG twice as often. The very first randomizer will be set to 1 and + * the PRNG is called at every odd indexed schnorrsig to fill the cache. */ + secp256k1_scalar randomizer_cache[2]; + /* Signature, message, public key tuples to verify */ + const secp256k1_schnorrsig *const *sig; + const unsigned char *const *msg32; + const secp256k1_pubkey *const *pk; + size_t n_sigs; +} secp256k1_schnorrsig_verify_ecmult_context; + +/* Callback function which is called by ecmult_multi in order to convert the ecmult_context + * consisting of signature, message and public key tuples into scalars and points. */ +static int secp256k1_schnorrsig_verify_batch_ecmult_callback(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data) { + secp256k1_schnorrsig_verify_ecmult_context *ecmult_context = (secp256k1_schnorrsig_verify_ecmult_context *) data; + + if (idx % 4 == 2) { + /* Every idx corresponds to a (scalar,point)-tuple. So this callback is called with 4 + * consecutive tuples before we need to call the RNG for new randomizers: + * (-randomizer_cache[0], R1) + * (-randomizer_cache[0]*e1, P1) + * (-randomizer_cache[1], R2) + * (-randomizer_cache[1]*e2, P2) */ + secp256k1_scalar_chacha20(&ecmult_context->randomizer_cache[0], &ecmult_context->randomizer_cache[1], ecmult_context->chacha_seed, idx / 4); + } + + /* R */ + if (idx % 2 == 0) { + secp256k1_fe rx; + *sc = ecmult_context->randomizer_cache[(idx / 2) % 2]; + if (!secp256k1_fe_set_b32(&rx, &ecmult_context->sig[idx / 2]->data[0])) { + return 0; + } + if (!secp256k1_ge_set_xquad(pt, &rx)) { + return 0; + } + /* eP */ + } else { + unsigned char buf[33]; + size_t buflen = sizeof(buf); + secp256k1_sha256 sha; + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, &ecmult_context->sig[idx / 2]->data[0], 32); + secp256k1_ec_pubkey_serialize(ecmult_context->ctx, buf, &buflen, ecmult_context->pk[idx / 2], SECP256K1_EC_COMPRESSED); + secp256k1_sha256_write(&sha, buf, buflen); + secp256k1_sha256_write(&sha, ecmult_context->msg32[idx / 2], 32); + secp256k1_sha256_finalize(&sha, buf); + + secp256k1_scalar_set_b32(sc, buf, NULL); + secp256k1_scalar_mul(sc, sc, &ecmult_context->randomizer_cache[(idx / 2) % 2]); + + if (!secp256k1_pubkey_load(ecmult_context->ctx, pt, ecmult_context->pk[idx / 2])) { + return 0; + } + } + return 1; +} + +/** Helper function for batch verification. Hashes signature verification data into the + * randomization seed and initializes ecmult_context. + * + * Returns 1 if the randomizer was successfully initialized. + * + * Args: ctx: a secp256k1 context object + * Out: ecmult_context: context for batch_ecmult_callback + * In/Out sha: an initialized sha256 object which hashes the schnorrsig input in order to get a + * seed for the randomizer PRNG + * In: sig: array of signatures, or NULL if there are no signatures + * msg32: array of messages, or NULL if there are no signatures + * pk: array of public keys, or NULL if there are no signatures + * n_sigs: number of signatures in above arrays (must be 0 if they are NULL) + */ +int secp256k1_schnorrsig_verify_batch_init_randomizer(const secp256k1_context *ctx, secp256k1_schnorrsig_verify_ecmult_context *ecmult_context, secp256k1_sha256 *sha, const secp256k1_schnorrsig *const *sig, const unsigned char *const *msg32, const secp256k1_pubkey *const *pk, size_t n_sigs) { + size_t i; + + if (n_sigs > 0) { + ARG_CHECK(sig != NULL); + ARG_CHECK(msg32 != NULL); + ARG_CHECK(pk != NULL); + } + + for (i = 0; i < n_sigs; i++) { + unsigned char buf[33]; + size_t buflen = sizeof(buf); + secp256k1_sha256_write(sha, sig[i]->data, 64); + secp256k1_sha256_write(sha, msg32[i], 32); + secp256k1_ec_pubkey_serialize(ctx, buf, &buflen, pk[i], SECP256K1_EC_COMPRESSED); + secp256k1_sha256_write(sha, buf, 32); + } + ecmult_context->ctx = ctx; + ecmult_context->sig = sig; + ecmult_context->msg32 = msg32; + ecmult_context->pk = pk; + ecmult_context->n_sigs = n_sigs; + + return 1; +} + +/** Helper function for batch verification. Sums the s part of all signatures multiplied by their + * randomizer. + * + * Returns 1 if s is successfully summed. + * + * In/Out: s: the s part of the input sigs is added to this s argument + * In: chacha_seed: PRNG seed for computing randomizers + * sig: array of signatures, or NULL if there are no signatures + * n_sigs: number of signatures in above array (must be 0 if they are NULL) + */ +int secp256k1_schnorrsig_verify_batch_sum_s(secp256k1_scalar *s, unsigned char *chacha_seed, const secp256k1_schnorrsig *const *sig, size_t n_sigs) { + secp256k1_scalar randomizer_cache[2]; + size_t i; + + secp256k1_scalar_set_int(&randomizer_cache[0], 1); + for (i = 0; i < n_sigs; i++) { + int overflow; + secp256k1_scalar term; + if (i % 2 == 1) { + secp256k1_scalar_chacha20(&randomizer_cache[0], &randomizer_cache[1], chacha_seed, i / 2); + } + + secp256k1_scalar_set_b32(&term, &sig[i]->data[32], &overflow); + if (overflow) { + return 0; + } + secp256k1_scalar_mul(&term, &term, &randomizer_cache[i % 2]); + secp256k1_scalar_add(s, s, &term); + } + return 1; +} + +/* schnorrsig batch verification. + * Seeds a random number generator with the inputs and derives a random number ai for every + * signature i. Fails if y-coordinate of any R is not a quadratic residue or if + * 0 != -(s1 + a2*s2 + ... + au*su)G + R1 + a2*R2 + ... + au*Ru + e1*P1 + (a2*e2)P2 + ... + (au*eu)Pu. */ +int secp256k1_schnorrsig_verify_batch(const secp256k1_context *ctx, secp256k1_scratch *scratch, const secp256k1_schnorrsig *const *sig, const unsigned char *const *msg32, const secp256k1_pubkey *const *pk, size_t n_sigs) { + secp256k1_schnorrsig_verify_ecmult_context ecmult_context; + secp256k1_sha256 sha; + secp256k1_scalar s; + secp256k1_gej rj; + + VERIFY_CHECK(ctx != NULL); + ARG_CHECK(secp256k1_ecmult_context_is_built(&ctx->ecmult_ctx)); + ARG_CHECK(scratch != NULL); + /* Check that n_sigs is less than half of the maximum size_t value. This is necessary because + * the number of points given to ecmult_multi is 2*n_sigs. */ + ARG_CHECK(n_sigs <= SIZE_MAX / 2); + /* Check that n_sigs is less than 2^31 to ensure the same behavior of this function on 32-bit + * and 64-bit platforms. */ + ARG_CHECK(n_sigs < (size_t)(1 << 31)); + + secp256k1_sha256_initialize(&sha); + if (!secp256k1_schnorrsig_verify_batch_init_randomizer(ctx, &ecmult_context, &sha, sig, msg32, pk, n_sigs)) { + return 0; + } + secp256k1_sha256_finalize(&sha, ecmult_context.chacha_seed); + secp256k1_scalar_set_int(&ecmult_context.randomizer_cache[0], 1); + + secp256k1_scalar_clear(&s); + if (!secp256k1_schnorrsig_verify_batch_sum_s(&s, ecmult_context.chacha_seed, sig, n_sigs)) { + return 0; + } + secp256k1_scalar_negate(&s, &s); + + return secp256k1_ecmult_multi_var(&ctx->ecmult_ctx, scratch, &rj, &s, secp256k1_schnorrsig_verify_batch_ecmult_callback, (void *) &ecmult_context, 2 * n_sigs) + && secp256k1_gej_is_infinity(&rj); +} + +#endif + diff --git a/src/secp256k1/src/modules/schnorrsig/tests_impl.h b/src/secp256k1/src/modules/schnorrsig/tests_impl.h new file mode 100644 index 000000000..de84992a9 --- /dev/null +++ b/src/secp256k1/src/modules/schnorrsig/tests_impl.h @@ -0,0 +1,727 @@ +/********************************************************************** + * Copyright (c) 2018 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_MODULE_SCHNORRSIG_TESTS_ +#define _SECP256K1_MODULE_SCHNORRSIG_TESTS_ + +#include "secp256k1_schnorrsig.h" + +void test_schnorrsig_serialize(void) { + secp256k1_schnorrsig sig; + unsigned char in[64]; + unsigned char out[64]; + + memset(in, 0x12, 64); + CHECK(secp256k1_schnorrsig_parse(ctx, &sig, in)); + CHECK(secp256k1_schnorrsig_serialize(ctx, out, &sig)); + CHECK(memcmp(in, out, 64) == 0); +} + +void test_schnorrsig_api(secp256k1_scratch_space *scratch) { + unsigned char sk1[32]; + unsigned char sk2[32]; + unsigned char sk3[32]; + unsigned char msg[32]; + unsigned char sig64[64]; + secp256k1_pubkey pk[3]; + secp256k1_schnorrsig sig; + const secp256k1_schnorrsig *sigptr = &sig; + const unsigned char *msgptr = msg; + const secp256k1_pubkey *pkptr = &pk[0]; + int nonce_is_negated; + + /** setup **/ + secp256k1_context *none = secp256k1_context_create(SECP256K1_CONTEXT_NONE); + secp256k1_context *sign = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); + secp256k1_context *vrfy = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); + secp256k1_context *both = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + int ecount; + + secp256k1_context_set_error_callback(none, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_error_callback(sign, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_error_callback(vrfy, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_error_callback(both, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(none, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(sign, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(vrfy, counting_illegal_callback_fn, &ecount); + secp256k1_context_set_illegal_callback(both, counting_illegal_callback_fn, &ecount); + + secp256k1_rand256(sk1); + secp256k1_rand256(sk2); + secp256k1_rand256(sk3); + secp256k1_rand256(msg); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[0], sk1) == 1); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[1], sk2) == 1); + CHECK(secp256k1_ec_pubkey_create(ctx, &pk[2], sk3) == 1); + + /** main test body **/ + ecount = 0; + CHECK(secp256k1_schnorrsig_sign(none, &sig, &nonce_is_negated, msg, sk1, NULL, NULL) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_schnorrsig_sign(vrfy, &sig, &nonce_is_negated, msg, sk1, NULL, NULL) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_sign(sign, &sig, &nonce_is_negated, msg, sk1, NULL, NULL) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_sign(sign, NULL, &nonce_is_negated, msg, sk1, NULL, NULL) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_schnorrsig_sign(sign, &sig, NULL, msg, sk1, NULL, NULL) == 1); + CHECK(ecount == 3); + CHECK(secp256k1_schnorrsig_sign(sign, &sig, &nonce_is_negated, NULL, sk1, NULL, NULL) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_schnorrsig_sign(sign, &sig, &nonce_is_negated, msg, NULL, NULL, NULL) == 0); + CHECK(ecount == 5); + + ecount = 0; + CHECK(secp256k1_schnorrsig_serialize(none, sig64, &sig) == 1); + CHECK(ecount == 0); + CHECK(secp256k1_schnorrsig_serialize(none, NULL, &sig) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_schnorrsig_serialize(none, sig64, NULL) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_parse(none, &sig, sig64) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_parse(none, NULL, sig64) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_schnorrsig_parse(none, &sig, NULL) == 0); + CHECK(ecount == 4); + + ecount = 0; + CHECK(secp256k1_schnorrsig_verify(none, &sig, msg, &pk[0]) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_schnorrsig_verify(sign, &sig, msg, &pk[0]) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_verify(vrfy, &sig, msg, &pk[0]) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_verify(vrfy, NULL, msg, &pk[0]) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_schnorrsig_verify(vrfy, &sig, NULL, &pk[0]) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_schnorrsig_verify(vrfy, &sig, msg, NULL) == 0); + CHECK(ecount == 5); + + ecount = 0; + CHECK(secp256k1_schnorrsig_verify_batch(none, scratch, &sigptr, &msgptr, &pkptr, 1) == 0); + CHECK(ecount == 1); + CHECK(secp256k1_schnorrsig_verify_batch(sign, scratch, &sigptr, &msgptr, &pkptr, 1) == 0); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, &sigptr, &msgptr, &pkptr, 1) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, NULL, NULL, NULL, 0) == 1); + CHECK(ecount == 2); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, NULL, &msgptr, &pkptr, 1) == 0); + CHECK(ecount == 3); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, &sigptr, NULL, &pkptr, 1) == 0); + CHECK(ecount == 4); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, &sigptr, &msgptr, NULL, 1) == 0); + CHECK(ecount == 5); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, &sigptr, &msgptr, &pkptr, (size_t)1 << (sizeof(size_t)*8-1)) == 0); + CHECK(ecount == 6); + CHECK(secp256k1_schnorrsig_verify_batch(vrfy, scratch, &sigptr, &msgptr, &pkptr, 1 << 31) == 0); + CHECK(ecount == 7); + + secp256k1_context_destroy(none); + secp256k1_context_destroy(sign); + secp256k1_context_destroy(vrfy); + secp256k1_context_destroy(both); +} + +/* Helper function for schnorrsig_bip_vectors + * Signs the message and checks that it's the same as expected_sig. */ +void test_schnorrsig_bip_vectors_check_signing(const unsigned char *sk, const unsigned char *pk_serialized, const unsigned char *msg, const unsigned char *expected_sig, const int expected_nonce_is_negated) { + secp256k1_schnorrsig sig; + unsigned char serialized_sig[64]; + secp256k1_pubkey pk; + int nonce_is_negated; + + CHECK(secp256k1_schnorrsig_sign(ctx, &sig, &nonce_is_negated, msg, sk, NULL, NULL)); + CHECK(nonce_is_negated == expected_nonce_is_negated); + CHECK(secp256k1_schnorrsig_serialize(ctx, serialized_sig, &sig)); + CHECK(memcmp(serialized_sig, expected_sig, 64) == 0); + + CHECK(secp256k1_ec_pubkey_parse(ctx, &pk, pk_serialized, 33)); + CHECK(secp256k1_schnorrsig_verify(ctx, &sig, msg, &pk)); +} + +/* Helper function for schnorrsig_bip_vectors + * Checks that both verify and verify_batch return the same value as expected. */ +void test_schnorrsig_bip_vectors_check_verify(secp256k1_scratch_space *scratch, const unsigned char *pk_serialized, const unsigned char *msg32, const unsigned char *sig_serialized, int expected) { + const unsigned char *msg_arr[1]; + const secp256k1_schnorrsig *sig_arr[1]; + const secp256k1_pubkey *pk_arr[1]; + secp256k1_pubkey pk; + secp256k1_schnorrsig sig; + + CHECK(secp256k1_ec_pubkey_parse(ctx, &pk, pk_serialized, 33)); + CHECK(secp256k1_schnorrsig_parse(ctx, &sig, sig_serialized)); + + sig_arr[0] = &sig; + msg_arr[0] = msg32; + pk_arr[0] = &pk; + + CHECK(expected == secp256k1_schnorrsig_verify(ctx, &sig, msg32, &pk)); + CHECK(expected == secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 1)); +} + +/* Test vectors according to BIP-schnorr + * (https://github.com/sipa/bips/blob/7f6a73e53c8bbcf2d008ea0546f76433e22094a8/bip-schnorr/test-vectors.csv). + */ +void test_schnorrsig_bip_vectors(secp256k1_scratch_space *scratch) { + { + /* Test vector 1 */ + const unsigned char sk1[32] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 + }; + const unsigned char pk1[33] = { + 0x02, 0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB, + 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B, + 0x07, 0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28, + 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17, + 0x98 + }; + const unsigned char msg1[32] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + const unsigned char sig1[64] = { + 0x78, 0x7A, 0x84, 0x8E, 0x71, 0x04, 0x3D, 0x28, + 0x0C, 0x50, 0x47, 0x0E, 0x8E, 0x15, 0x32, 0xB2, + 0xDD, 0x5D, 0x20, 0xEE, 0x91, 0x2A, 0x45, 0xDB, + 0xDD, 0x2B, 0xD1, 0xDF, 0xBF, 0x18, 0x7E, 0xF6, + 0x70, 0x31, 0xA9, 0x88, 0x31, 0x85, 0x9D, 0xC3, + 0x4D, 0xFF, 0xEE, 0xDD, 0xA8, 0x68, 0x31, 0x84, + 0x2C, 0xCD, 0x00, 0x79, 0xE1, 0xF9, 0x2A, 0xF1, + 0x77, 0xF7, 0xF2, 0x2C, 0xC1, 0xDC, 0xED, 0x05 + }; + test_schnorrsig_bip_vectors_check_signing(sk1, pk1, msg1, sig1, 1); + test_schnorrsig_bip_vectors_check_verify(scratch, pk1, msg1, sig1, 1); + } + { + /* Test vector 2 */ + const unsigned char sk2[32] = { + 0xB7, 0xE1, 0x51, 0x62, 0x8A, 0xED, 0x2A, 0x6A, + 0xBF, 0x71, 0x58, 0x80, 0x9C, 0xF4, 0xF3, 0xC7, + 0x62, 0xE7, 0x16, 0x0F, 0x38, 0xB4, 0xDA, 0x56, + 0xA7, 0x84, 0xD9, 0x04, 0x51, 0x90, 0xCF, 0xEF + }; + const unsigned char pk2[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg2[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig2[64] = { + 0x2A, 0x29, 0x8D, 0xAC, 0xAE, 0x57, 0x39, 0x5A, + 0x15, 0xD0, 0x79, 0x5D, 0xDB, 0xFD, 0x1D, 0xCB, + 0x56, 0x4D, 0xA8, 0x2B, 0x0F, 0x26, 0x9B, 0xC7, + 0x0A, 0x74, 0xF8, 0x22, 0x04, 0x29, 0xBA, 0x1D, + 0x1E, 0x51, 0xA2, 0x2C, 0xCE, 0xC3, 0x55, 0x99, + 0xB8, 0xF2, 0x66, 0x91, 0x22, 0x81, 0xF8, 0x36, + 0x5F, 0xFC, 0x2D, 0x03, 0x5A, 0x23, 0x04, 0x34, + 0xA1, 0xA6, 0x4D, 0xC5, 0x9F, 0x70, 0x13, 0xFD + }; + test_schnorrsig_bip_vectors_check_signing(sk2, pk2, msg2, sig2, 0); + test_schnorrsig_bip_vectors_check_verify(scratch, pk2, msg2, sig2, 1); + } + { + /* Test vector 3 */ + const unsigned char sk3[32] = { + 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, + 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, + 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, + 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x14, 0xE5, 0xC7 + }; + const unsigned char pk3[33] = { + 0x03, 0xFA, 0xC2, 0x11, 0x4C, 0x2F, 0xBB, 0x09, + 0x15, 0x27, 0xEB, 0x7C, 0x64, 0xEC, 0xB1, 0x1F, + 0x80, 0x21, 0xCB, 0x45, 0xE8, 0xE7, 0x80, 0x9D, + 0x3C, 0x09, 0x38, 0xE4, 0xB8, 0xC0, 0xE5, 0xF8, + 0x4B + }; + const unsigned char msg3[32] = { + 0x5E, 0x2D, 0x58, 0xD8, 0xB3, 0xBC, 0xDF, 0x1A, + 0xBA, 0xDE, 0xC7, 0x82, 0x90, 0x54, 0xF9, 0x0D, + 0xDA, 0x98, 0x05, 0xAA, 0xB5, 0x6C, 0x77, 0x33, + 0x30, 0x24, 0xB9, 0xD0, 0xA5, 0x08, 0xB7, 0x5C + }; + const unsigned char sig3[64] = { + 0x00, 0xDA, 0x9B, 0x08, 0x17, 0x2A, 0x9B, 0x6F, + 0x04, 0x66, 0xA2, 0xDE, 0xFD, 0x81, 0x7F, 0x2D, + 0x7A, 0xB4, 0x37, 0xE0, 0xD2, 0x53, 0xCB, 0x53, + 0x95, 0xA9, 0x63, 0x86, 0x6B, 0x35, 0x74, 0xBE, + 0x00, 0x88, 0x03, 0x71, 0xD0, 0x17, 0x66, 0x93, + 0x5B, 0x92, 0xD2, 0xAB, 0x4C, 0xD5, 0xC8, 0xA2, + 0xA5, 0x83, 0x7E, 0xC5, 0x7F, 0xED, 0x76, 0x60, + 0x77, 0x3A, 0x05, 0xF0, 0xDE, 0x14, 0x23, 0x80 + }; + test_schnorrsig_bip_vectors_check_signing(sk3, pk3, msg3, sig3, 0); + test_schnorrsig_bip_vectors_check_verify(scratch, pk3, msg3, sig3, 1); + } + { + /* Test vector 4 */ + const unsigned char pk4[33] = { + 0x03, 0xDE, 0xFD, 0xEA, 0x4C, 0xDB, 0x67, 0x77, + 0x50, 0xA4, 0x20, 0xFE, 0xE8, 0x07, 0xEA, 0xCF, + 0x21, 0xEB, 0x98, 0x98, 0xAE, 0x79, 0xB9, 0x76, + 0x87, 0x66, 0xE4, 0xFA, 0xA0, 0x4A, 0x2D, 0x4A, + 0x34 + }; + const unsigned char msg4[32] = { + 0x4D, 0xF3, 0xC3, 0xF6, 0x8F, 0xCC, 0x83, 0xB2, + 0x7E, 0x9D, 0x42, 0xC9, 0x04, 0x31, 0xA7, 0x24, + 0x99, 0xF1, 0x78, 0x75, 0xC8, 0x1A, 0x59, 0x9B, + 0x56, 0x6C, 0x98, 0x89, 0xB9, 0x69, 0x67, 0x03 + }; + const unsigned char sig4[64] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x3B, 0x78, 0xCE, 0x56, 0x3F, + 0x89, 0xA0, 0xED, 0x94, 0x14, 0xF5, 0xAA, 0x28, + 0xAD, 0x0D, 0x96, 0xD6, 0x79, 0x5F, 0x9C, 0x63, + 0x02, 0xA8, 0xDC, 0x32, 0xE6, 0x4E, 0x86, 0xA3, + 0x33, 0xF2, 0x0E, 0xF5, 0x6E, 0xAC, 0x9B, 0xA3, + 0x0B, 0x72, 0x46, 0xD6, 0xD2, 0x5E, 0x22, 0xAD, + 0xB8, 0xC6, 0xBE, 0x1A, 0xEB, 0x08, 0xD4, 0x9D + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk4, msg4, sig4, 1); + } + { + /* Test vector 5 */ + const unsigned char pk5[33] = { + 0x03, 0x1B, 0x84, 0xC5, 0x56, 0x7B, 0x12, 0x64, + 0x40, 0x99, 0x5D, 0x3E, 0xD5, 0xAA, 0xBA, 0x05, + 0x65, 0xD7, 0x1E, 0x18, 0x34, 0x60, 0x48, 0x19, + 0xFF, 0x9C, 0x17, 0xF5, 0xE9, 0xD5, 0xDD, 0x07, + 0x8F + }; + const unsigned char msg5[32] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + const unsigned char sig5[64] = { + 0x52, 0x81, 0x85, 0x79, 0xAC, 0xA5, 0x97, 0x67, + 0xE3, 0x29, 0x1D, 0x91, 0xB7, 0x6B, 0x63, 0x7B, + 0xEF, 0x06, 0x20, 0x83, 0x28, 0x49, 0x92, 0xF2, + 0xD9, 0x5F, 0x56, 0x4C, 0xA6, 0xCB, 0x4E, 0x35, + 0x30, 0xB1, 0xDA, 0x84, 0x9C, 0x8E, 0x83, 0x04, + 0xAD, 0xC0, 0xCF, 0xE8, 0x70, 0x66, 0x03, 0x34, + 0xB3, 0xCF, 0xC1, 0x8E, 0x82, 0x5E, 0xF1, 0xDB, + 0x34, 0xCF, 0xAE, 0x3D, 0xFC, 0x5D, 0x81, 0x87 + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk5, msg5, sig5, 1); + } + { + /* Test vector 6 */ + const unsigned char pk6[33] = { + 0x03, 0xFA, 0xC2, 0x11, 0x4C, 0x2F, 0xBB, 0x09, + 0x15, 0x27, 0xEB, 0x7C, 0x64, 0xEC, 0xB1, 0x1F, + 0x80, 0x21, 0xCB, 0x45, 0xE8, 0xE7, 0x80, 0x9D, + 0x3C, 0x09, 0x38, 0xE4, 0xB8, 0xC0, 0xE5, 0xF8, + 0x4B + }; + const unsigned char msg6[32] = { + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF + }; + const unsigned char sig6[64] = { + 0x57, 0x0D, 0xD4, 0xCA, 0x83, 0xD4, 0xE6, 0x31, + 0x7B, 0x8E, 0xE6, 0xBA, 0xE8, 0x34, 0x67, 0xA1, + 0xBF, 0x41, 0x9D, 0x07, 0x67, 0x12, 0x2D, 0xE4, + 0x09, 0x39, 0x44, 0x14, 0xB0, 0x50, 0x80, 0xDC, + 0xE9, 0xEE, 0x5F, 0x23, 0x7C, 0xBD, 0x10, 0x8E, + 0xAB, 0xAE, 0x1E, 0x37, 0x75, 0x9A, 0xE4, 0x7F, + 0x8E, 0x42, 0x03, 0xDA, 0x35, 0x32, 0xEB, 0x28, + 0xDB, 0x86, 0x0F, 0x33, 0xD6, 0x2D, 0x49, 0xBD + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk6, msg6, sig6, 1); + } + { + /* Test vector 7 */ + const unsigned char pk7[33] = { + 0x03, 0xEE, 0xFD, 0xEA, 0x4C, 0xDB, 0x67, 0x77, + 0x50, 0xA4, 0x20, 0xFE, 0xE8, 0x07, 0xEA, 0xCF, + 0x21, 0xEB, 0x98, 0x98, 0xAE, 0x79, 0xB9, 0x76, + 0x87, 0x66, 0xE4, 0xFA, 0xA0, 0x4A, 0x2D, 0x4A, + 0x34 + }; + secp256k1_pubkey pk7_parsed; + /* No need to check the signature of the test vector as parsing the pubkey already fails */ + CHECK(!secp256k1_ec_pubkey_parse(ctx, &pk7_parsed, pk7, 33)); + } + { + /* Test vector 8 */ + const unsigned char pk8[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg8[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig8[64] = { + 0x2A, 0x29, 0x8D, 0xAC, 0xAE, 0x57, 0x39, 0x5A, + 0x15, 0xD0, 0x79, 0x5D, 0xDB, 0xFD, 0x1D, 0xCB, + 0x56, 0x4D, 0xA8, 0x2B, 0x0F, 0x26, 0x9B, 0xC7, + 0x0A, 0x74, 0xF8, 0x22, 0x04, 0x29, 0xBA, 0x1D, + 0xFA, 0x16, 0xAE, 0xE0, 0x66, 0x09, 0x28, 0x0A, + 0x19, 0xB6, 0x7A, 0x24, 0xE1, 0x97, 0x7E, 0x46, + 0x97, 0x71, 0x2B, 0x5F, 0xD2, 0x94, 0x39, 0x14, + 0xEC, 0xD5, 0xF7, 0x30, 0x90, 0x1B, 0x4A, 0xB7 + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk8, msg8, sig8, 0); + } + { + /* Test vector 9 */ + const unsigned char pk9[33] = { + 0x03, 0xFA, 0xC2, 0x11, 0x4C, 0x2F, 0xBB, 0x09, + 0x15, 0x27, 0xEB, 0x7C, 0x64, 0xEC, 0xB1, 0x1F, + 0x80, 0x21, 0xCB, 0x45, 0xE8, 0xE7, 0x80, 0x9D, + 0x3C, 0x09, 0x38, 0xE4, 0xB8, 0xC0, 0xE5, 0xF8, + 0x4B + }; + const unsigned char msg9[32] = { + 0x5E, 0x2D, 0x58, 0xD8, 0xB3, 0xBC, 0xDF, 0x1A, + 0xBA, 0xDE, 0xC7, 0x82, 0x90, 0x54, 0xF9, 0x0D, + 0xDA, 0x98, 0x05, 0xAA, 0xB5, 0x6C, 0x77, 0x33, + 0x30, 0x24, 0xB9, 0xD0, 0xA5, 0x08, 0xB7, 0x5C + }; + const unsigned char sig9[64] = { + 0x00, 0xDA, 0x9B, 0x08, 0x17, 0x2A, 0x9B, 0x6F, + 0x04, 0x66, 0xA2, 0xDE, 0xFD, 0x81, 0x7F, 0x2D, + 0x7A, 0xB4, 0x37, 0xE0, 0xD2, 0x53, 0xCB, 0x53, + 0x95, 0xA9, 0x63, 0x86, 0x6B, 0x35, 0x74, 0xBE, + 0xD0, 0x92, 0xF9, 0xD8, 0x60, 0xF1, 0x77, 0x6A, + 0x1F, 0x74, 0x12, 0xAD, 0x8A, 0x1E, 0xB5, 0x0D, + 0xAC, 0xCC, 0x22, 0x2B, 0xC8, 0xC0, 0xE2, 0x6B, + 0x20, 0x56, 0xDF, 0x2F, 0x27, 0x3E, 0xFD, 0xEC + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk9, msg9, sig9, 0); + } + { + /* Test vector 10 */ + const unsigned char pk10[33] = { + 0x02, 0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB, + 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B, + 0x07, 0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28, + 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17, + 0x98 + }; + const unsigned char msg10[32] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + const unsigned char sig10[64] = { + 0x78, 0x7A, 0x84, 0x8E, 0x71, 0x04, 0x3D, 0x28, + 0x0C, 0x50, 0x47, 0x0E, 0x8E, 0x15, 0x32, 0xB2, + 0xDD, 0x5D, 0x20, 0xEE, 0x91, 0x2A, 0x45, 0xDB, + 0xDD, 0x2B, 0xD1, 0xDF, 0xBF, 0x18, 0x7E, 0xF6, + 0x8F, 0xCE, 0x56, 0x77, 0xCE, 0x7A, 0x62, 0x3C, + 0xB2, 0x00, 0x11, 0x22, 0x57, 0x97, 0xCE, 0x7A, + 0x8D, 0xE1, 0xDC, 0x6C, 0xCD, 0x4F, 0x75, 0x4A, + 0x47, 0xDA, 0x6C, 0x60, 0x0E, 0x59, 0x54, 0x3C + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk10, msg10, sig10, 0); + } + { + /* Test vector 11 */ + const unsigned char pk11[33] = { + 0x03, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg11[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig11[64] = { + 0x2A, 0x29, 0x8D, 0xAC, 0xAE, 0x57, 0x39, 0x5A, + 0x15, 0xD0, 0x79, 0x5D, 0xDB, 0xFD, 0x1D, 0xCB, + 0x56, 0x4D, 0xA8, 0x2B, 0x0F, 0x26, 0x9B, 0xC7, + 0x0A, 0x74, 0xF8, 0x22, 0x04, 0x29, 0xBA, 0x1D, + 0x1E, 0x51, 0xA2, 0x2C, 0xCE, 0xC3, 0x55, 0x99, + 0xB8, 0xF2, 0x66, 0x91, 0x22, 0x81, 0xF8, 0x36, + 0x5F, 0xFC, 0x2D, 0x03, 0x5A, 0x23, 0x04, 0x34, + 0xA1, 0xA6, 0x4D, 0xC5, 0x9F, 0x70, 0x13, 0xFD + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk11, msg11, sig11, 0); + } + { + /* Test vector 12 */ + const unsigned char pk12[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg12[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig12[64] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x9E, 0x9D, 0x01, 0xAF, 0x98, 0x8B, 0x5C, 0xED, + 0xCE, 0x47, 0x22, 0x1B, 0xFA, 0x9B, 0x22, 0x27, + 0x21, 0xF3, 0xFA, 0x40, 0x89, 0x15, 0x44, 0x4A, + 0x4B, 0x48, 0x90, 0x21, 0xDB, 0x55, 0x77, 0x5F + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk12, msg12, sig12, 0); + } + { + /* Test vector 13 */ + const unsigned char pk13[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg13[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig13[64] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0xD3, 0x7D, 0xDF, 0x02, 0x54, 0x35, 0x18, 0x36, + 0xD8, 0x4B, 0x1B, 0xD6, 0xA7, 0x95, 0xFD, 0x5D, + 0x52, 0x30, 0x48, 0xF2, 0x98, 0xC4, 0x21, 0x4D, + 0x18, 0x7F, 0xE4, 0x89, 0x29, 0x47, 0xF7, 0x28 + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk13, msg13, sig13, 0); + } + { + /* Test vector 14 */ + const unsigned char pk14[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg14[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x14, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig14[64] = { + 0x4A, 0x29, 0x8D, 0xAC, 0xAE, 0x57, 0x39, 0x5A, + 0x15, 0xD0, 0x79, 0x5D, 0xDB, 0xFD, 0x1D, 0xCB, + 0x56, 0x4D, 0xA8, 0x2B, 0x0F, 0x26, 0x9B, 0xC7, + 0x0A, 0x74, 0xF8, 0x22, 0x04, 0x29, 0xBA, 0x1D, + 0x1E, 0x51, 0xA2, 0x2C, 0xCE, 0xC3, 0x55, 0x99, + 0xB8, 0xF2, 0x66, 0x91, 0x22, 0x81, 0xF8, 0x36, + 0x5F, 0xFC, 0x2D, 0x03, 0x5A, 0x23, 0x04, 0x34, + 0xA1, 0xA6, 0x4D, 0xC5, 0x9F, 0x70, 0x13, 0xFD + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk14, msg14, sig14, 0); + } + { + /* Test vector 15 */ + const unsigned char pk15[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg15[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig15[64] = { + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0x2F, + 0x1E, 0x51, 0xA2, 0x2C, 0xCE, 0xC3, 0x55, 0x99, + 0xB8, 0xF2, 0x66, 0x91, 0x22, 0x81, 0xF8, 0x36, + 0x5F, 0xFC, 0x2D, 0x03, 0x5A, 0x23, 0x04, 0x34, + 0xA1, 0xA6, 0x4D, 0xC5, 0x9F, 0x70, 0x13, 0xFD + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk15, msg15, sig15, 0); + } + { + /* Test vector 16 */ + const unsigned char pk16[33] = { + 0x02, 0xDF, 0xF1, 0xD7, 0x7F, 0x2A, 0x67, 0x1C, + 0x5F, 0x36, 0x18, 0x37, 0x26, 0xDB, 0x23, 0x41, + 0xBE, 0x58, 0xFE, 0xAE, 0x1D, 0xA2, 0xDE, 0xCE, + 0xD8, 0x43, 0x24, 0x0F, 0x7B, 0x50, 0x2B, 0xA6, + 0x59 + }; + const unsigned char msg16[32] = { + 0x24, 0x3F, 0x6A, 0x88, 0x85, 0xA3, 0x08, 0xD3, + 0x13, 0x19, 0x8A, 0x2E, 0x03, 0x70, 0x73, 0x44, + 0xA4, 0x09, 0x38, 0x22, 0x29, 0x9F, 0x31, 0xD0, + 0x08, 0x2E, 0xFA, 0x98, 0xEC, 0x4E, 0x6C, 0x89 + }; + const unsigned char sig16[64] = { + 0x2A, 0x29, 0x8D, 0xAC, 0xAE, 0x57, 0x39, 0x5A, + 0x15, 0xD0, 0x79, 0x5D, 0xDB, 0xFD, 0x1D, 0xCB, + 0x56, 0x4D, 0xA8, 0x2B, 0x0F, 0x26, 0x9B, 0xC7, + 0x0A, 0x74, 0xF8, 0x22, 0x04, 0x29, 0xBA, 0x1D, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, + 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, + 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41 + }; + test_schnorrsig_bip_vectors_check_verify(scratch, pk16, msg16, sig16, 0); + } +} + +/* Nonce function that returns constant 0 */ +static int nonce_function_failing(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { + (void) msg32; + (void) key32; + (void) algo16; + (void) data; + (void) counter; + (void) nonce32; + return 0; +} + +/* Nonce function that sets nonce to 0 */ +static int nonce_function_0(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { + (void) msg32; + (void) key32; + (void) algo16; + (void) data; + (void) counter; + + memset(nonce32, 0, 32); + return 1; +} + +void test_schnorrsig_sign(void) { + unsigned char sk[32]; + const unsigned char msg[32] = "this is a msg for a schnorrsig.."; + secp256k1_schnorrsig sig; + + memset(sk, 23, sizeof(sk)); + CHECK(secp256k1_schnorrsig_sign(ctx, &sig, NULL, msg, sk, NULL, NULL) == 1); + + /* Overflowing secret key */ + memset(sk, 0xFF, sizeof(sk)); + CHECK(secp256k1_schnorrsig_sign(ctx, &sig, NULL, msg, sk, NULL, NULL) == 0); + memset(sk, 23, sizeof(sk)); + + CHECK(secp256k1_schnorrsig_sign(ctx, &sig, NULL, msg, sk, nonce_function_failing, NULL) == 0); + CHECK(secp256k1_schnorrsig_sign(ctx, &sig, NULL, msg, sk, nonce_function_0, NULL) == 0); +} + +#define N_SIGS 200 +/* Creates N_SIGS valid signatures and verifies them with verify and verify_batch. Then flips some + * bits and checks that verification now fails. */ +void test_schnorrsig_sign_verify(secp256k1_scratch_space *scratch) { + const unsigned char sk[32] = "shhhhhhhh! this key is a secret."; + unsigned char msg[N_SIGS][32]; + secp256k1_schnorrsig sig[N_SIGS]; + size_t i; + const secp256k1_schnorrsig *sig_arr[N_SIGS]; + const unsigned char *msg_arr[N_SIGS]; + const secp256k1_pubkey *pk_arr[N_SIGS]; + secp256k1_pubkey pk; + + CHECK(secp256k1_ec_pubkey_create(ctx, &pk, sk)); + + CHECK(secp256k1_schnorrsig_verify_batch(ctx, scratch, NULL, NULL, NULL, 0)); + + for (i = 0; i < N_SIGS; i++) { + secp256k1_rand256(msg[i]); + CHECK(secp256k1_schnorrsig_sign(ctx, &sig[i], NULL, msg[i], sk, NULL, NULL)); + CHECK(secp256k1_schnorrsig_verify(ctx, &sig[i], msg[i], &pk)); + sig_arr[i] = &sig[i]; + msg_arr[i] = msg[i]; + pk_arr[i] = &pk; + } + + CHECK(secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 1)); + CHECK(secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 2)); + CHECK(secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 4)); + CHECK(secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, N_SIGS)); + + { + /* Flip a few bits in the signature and in the message and check that + * verify and verify_batch fail */ + size_t sig_idx = secp256k1_rand_int(4); + size_t byte_idx = secp256k1_rand_int(32); + unsigned char xorbyte = secp256k1_rand_int(254)+1; + sig[sig_idx].data[byte_idx] ^= xorbyte; + CHECK(!secp256k1_schnorrsig_verify(ctx, &sig[sig_idx], msg[sig_idx], &pk)); + CHECK(!secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 4)); + sig[sig_idx].data[byte_idx] ^= xorbyte; + + byte_idx = secp256k1_rand_int(32); + sig[sig_idx].data[32+byte_idx] ^= xorbyte; + CHECK(!secp256k1_schnorrsig_verify(ctx, &sig[sig_idx], msg[sig_idx], &pk)); + CHECK(!secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 4)); + sig[sig_idx].data[32+byte_idx] ^= xorbyte; + + byte_idx = secp256k1_rand_int(32); + msg[sig_idx][byte_idx] ^= xorbyte; + CHECK(!secp256k1_schnorrsig_verify(ctx, &sig[sig_idx], msg[sig_idx], &pk)); + CHECK(!secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 4)); + msg[sig_idx][byte_idx] ^= xorbyte; + + /* Check that above bitflips have been reversed correctly */ + CHECK(secp256k1_schnorrsig_verify(ctx, &sig[sig_idx], msg[sig_idx], &pk)); + CHECK(secp256k1_schnorrsig_verify_batch(ctx, scratch, sig_arr, msg_arr, pk_arr, 4)); + } +} +#undef N_SIGS + +void run_schnorrsig_tests(void) { + secp256k1_scratch_space *scratch = secp256k1_scratch_space_create(ctx, 1024 * 1024); + + test_schnorrsig_serialize(); + test_schnorrsig_api(scratch); + test_schnorrsig_bip_vectors(scratch); + test_schnorrsig_sign(); + test_schnorrsig_sign_verify(scratch); + + secp256k1_scratch_space_destroy(scratch); +} + +#endif + diff --git a/src/secp256k1/src/scalar.h b/src/secp256k1/src/scalar.h index 59304cb66..3d972dc84 100644 --- a/src/secp256k1/src/scalar.h +++ b/src/secp256k1/src/scalar.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -104,3 +106,236 @@ static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift); #endif /* SECP256K1_SCALAR_H */ + +#else + +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_H +#define SECP256K1_SCALAR_H + +#include "num.h" + +#if defined HAVE_CONFIG_H +#include "libsecp256k1-config.h" +#endif + +#if defined(EXHAUSTIVE_TEST_ORDER) +#include "scalar_low.h" +#elif defined(USE_SCALAR_4X64) +#include "scalar_4x64.h" +#elif defined(USE_SCALAR_8X32) +#include "scalar_8x32.h" +#else +#error "Please select scalar implementation" +#endif + +/** Clear a scalar to prevent the leak of sensitive data. */ +static void secp256k1_scalar_clear(secp256k1_scalar *r); + +/** Access bits from a scalar. All requested bits must belong to the same 32-bit limb. */ +static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count); + +/** Access bits from a scalar. Not constant time. */ +static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count); + +/** Set a scalar from a big endian byte array. */ +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *bin, int *overflow); + +/** Set a scalar to an unsigned integer. */ +static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v); + +/** Set a scalar to an unsigned 64-bit integer */ +static void secp256k1_scalar_set_u64(secp256k1_scalar *r, uint64_t v); + +/** Convert a scalar to a byte array. */ +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a); + +/** Add two scalars together (modulo the group order). Returns whether it overflowed. */ +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); + +/** Conditionally add a power of two to a scalar. The result is not allowed to overflow. */ +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag); + +/** Multiply two scalars (modulo the group order). */ +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); + +/** Shift a scalar right by some amount strictly between 0 and 16, returning + * the low bits that were shifted off */ +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n); + +/** Compute the square of a scalar (modulo the group order). */ +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the inverse of a scalar (modulo the group order). */ +static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the inverse of a scalar (modulo the group order), without constant-time guarantee. */ +static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the complement of a scalar (modulo the group order). */ +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Check whether a scalar equals zero. */ +static int secp256k1_scalar_is_zero(const secp256k1_scalar *a); + +/** Check whether a scalar equals one. */ +static int secp256k1_scalar_is_one(const secp256k1_scalar *a); + +/** Check whether a scalar, considered as an nonnegative integer, is even. */ +static int secp256k1_scalar_is_even(const secp256k1_scalar *a); + +/** Check whether a scalar is higher than the group order divided by 2. */ +static int secp256k1_scalar_is_high(const secp256k1_scalar *a); + +/** Conditionally negate a number, in constant time. + * Returns -1 if the number was negated, 1 otherwise */ +static int secp256k1_scalar_cond_negate(secp256k1_scalar *a, int flag); + +#ifndef USE_NUM_NONE +/** Convert a scalar to a number. */ +static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a); + +/** Get the order of the group as a number. */ +static void secp256k1_scalar_order_get_num(secp256k1_num *r); +#endif + +/** Compare two scalars. */ +static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b); + +#ifdef USE_ENDOMORPHISM +/** Find r1 and r2 such that r1+r2*2^128 = a. */ +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a); +/** Find r1 and r2 such that r1+r2*lambda = a, and r1 and r2 are maximum 128 bits long (see secp256k1_gej_mul_lambda). */ +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a); +#endif + +/** Multiply a and b (without taking the modulus!), divide by 2**shift, and round to the nearest integer. Shift must be at least 256. */ +static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift); + +/** Generate two scalars from a 32-byte seed and an integer using the chacha20 stream cipher */ +static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); + +#endif /* SECP256K1_SCALAR_H */ +#endif + +#else + +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_H +#define SECP256K1_SCALAR_H + +#include "num.h" + +#if defined HAVE_CONFIG_H +#include "libsecp256k1-config.h" +#endif + +#if defined(EXHAUSTIVE_TEST_ORDER) +#include "scalar_low.h" +#elif defined(USE_SCALAR_4X64) +#include "scalar_4x64.h" +#elif defined(USE_SCALAR_8X32) +#include "scalar_8x32.h" +#else +#error "Please select scalar implementation" +#endif + +/** Clear a scalar to prevent the leak of sensitive data. */ +static void secp256k1_scalar_clear(secp256k1_scalar *r); + +/** Access bits from a scalar. All requested bits must belong to the same 32-bit limb. */ +static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count); + +/** Access bits from a scalar. Not constant time. */ +static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count); + +/** Set a scalar from a big endian byte array. */ +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *bin, int *overflow); + +/** Set a scalar to an unsigned integer. */ +static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v); + +/** Set a scalar to an unsigned 64-bit integer */ +static void secp256k1_scalar_set_u64(secp256k1_scalar *r, uint64_t v); + +/** Convert a scalar to a byte array. */ +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a); + +/** Add two scalars together (modulo the group order). Returns whether it overflowed. */ +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); + +/** Conditionally add a power of two to a scalar. The result is not allowed to overflow. */ +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag); + +/** Multiply two scalars (modulo the group order). */ +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); + +/** Shift a scalar right by some amount strictly between 0 and 16, returning + * the low bits that were shifted off */ +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n); + +/** Compute the square of a scalar (modulo the group order). */ +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the inverse of a scalar (modulo the group order). */ +static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the inverse of a scalar (modulo the group order), without constant-time guarantee. */ +static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Compute the complement of a scalar (modulo the group order). */ +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a); + +/** Check whether a scalar equals zero. */ +static int secp256k1_scalar_is_zero(const secp256k1_scalar *a); + +/** Check whether a scalar equals one. */ +static int secp256k1_scalar_is_one(const secp256k1_scalar *a); + +/** Check whether a scalar, considered as an nonnegative integer, is even. */ +static int secp256k1_scalar_is_even(const secp256k1_scalar *a); + +/** Check whether a scalar is higher than the group order divided by 2. */ +static int secp256k1_scalar_is_high(const secp256k1_scalar *a); + +/** Conditionally negate a number, in constant time. + * Returns -1 if the number was negated, 1 otherwise */ +static int secp256k1_scalar_cond_negate(secp256k1_scalar *a, int flag); + +#ifndef USE_NUM_NONE +/** Convert a scalar to a number. */ +static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a); + +/** Get the order of the group as a number. */ +static void secp256k1_scalar_order_get_num(secp256k1_num *r); +#endif + +/** Compare two scalars. */ +static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b); + +#ifdef USE_ENDOMORPHISM +/** Find r1 and r2 such that r1+r2*2^128 = a. */ +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a); +/** Find r1 and r2 such that r1+r2*lambda = a, and r1 and r2 are maximum 128 bits long (see secp256k1_gej_mul_lambda). */ +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a); +#endif + +/** Multiply a and b (without taking the modulus!), divide by 2**shift, and round to the nearest integer. Shift must be at least 256. */ +static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift); + +/** Generate two scalars from a 32-byte seed and an integer using the chacha20 stream cipher */ +static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); + +#endif /* SECP256K1_SCALAR_H */ +#endif + diff --git a/src/secp256k1/src/scalar_4x64.h b/src/secp256k1/src/scalar_4x64.h index 19c7495d1..326afd6b5 100644 --- a/src/secp256k1/src/scalar_4x64.h +++ b/src/secp256k1/src/scalar_4x64.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -17,3 +19,50 @@ typedef struct { #define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{((uint64_t)(d1)) << 32 | (d0), ((uint64_t)(d3)) << 32 | (d2), ((uint64_t)(d5)) << 32 | (d4), ((uint64_t)(d7)) << 32 | (d6)}} #endif /* SECP256K1_SCALAR_REPR_H */ + +#else +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef struct { + uint64_t d[4]; +} secp256k1_scalar; + +#define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{((uint64_t)(d1)) << 32 | (d0), ((uint64_t)(d3)) << 32 | (d2), ((uint64_t)(d5)) << 32 | (d4), ((uint64_t)(d7)) << 32 | (d6)}} + +#endif /* SECP256K1_SCALAR_REPR_H */ +#endif + + +#else +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef struct { + uint64_t d[4]; +} secp256k1_scalar; + +#define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{((uint64_t)(d1)) << 32 | (d0), ((uint64_t)(d3)) << 32 | (d2), ((uint64_t)(d5)) << 32 | (d4), ((uint64_t)(d7)) << 32 | (d6)}} + +#endif /* SECP256K1_SCALAR_REPR_H */ +#endif + + diff --git a/src/secp256k1/src/scalar_4x64_impl.h b/src/secp256k1/src/scalar_4x64_impl.h index db1ebf94b..ee75ad51e 100644 --- a/src/secp256k1/src/scalar_4x64_impl.h +++ b/src/secp256k1/src/scalar_4x64_impl.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2013, 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -947,3 +949,1057 @@ SECP256K1_INLINE static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, } #endif /* SECP256K1_SCALAR_REPR_IMPL_H */ + + +#else +/********************************************************************** + * Copyright (c) 2013, 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_IMPL_H +#define SECP256K1_SCALAR_REPR_IMPL_H + +#include "scalar.h" +#include + +/* Limbs of the secp256k1 order. */ +#define SECP256K1_N_0 ((uint64_t)0xBFD25E8CD0364141ULL) +#define SECP256K1_N_1 ((uint64_t)0xBAAEDCE6AF48A03BULL) +#define SECP256K1_N_2 ((uint64_t)0xFFFFFFFFFFFFFFFEULL) +#define SECP256K1_N_3 ((uint64_t)0xFFFFFFFFFFFFFFFFULL) + +/* Limbs of 2^256 minus the secp256k1 order. */ +#define SECP256K1_N_C_0 (~SECP256K1_N_0 + 1) +#define SECP256K1_N_C_1 (~SECP256K1_N_1) +#define SECP256K1_N_C_2 (1) + +/* Limbs of half the secp256k1 order. */ +#define SECP256K1_N_H_0 ((uint64_t)0xDFE92F46681B20A0ULL) +#define SECP256K1_N_H_1 ((uint64_t)0x5D576E7357A4501DULL) +#define SECP256K1_N_H_2 ((uint64_t)0xFFFFFFFFFFFFFFFFULL) +#define SECP256K1_N_H_3 ((uint64_t)0x7FFFFFFFFFFFFFFFULL) + +SECP256K1_INLINE static void secp256k1_scalar_clear(secp256k1_scalar *r) { + r->d[0] = 0; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v) { + r->d[0] = v; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_set_u64(secp256k1_scalar *r, uint64_t v) { + r->d[0] = v; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + VERIFY_CHECK((offset + count - 1) >> 6 == offset >> 6); + return (a->d[offset >> 6] >> (offset & 0x3F)) & ((((uint64_t)1) << count) - 1); +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + VERIFY_CHECK(count < 32); + VERIFY_CHECK(offset + count <= 256); + if ((offset + count - 1) >> 6 == offset >> 6) { + return secp256k1_scalar_get_bits(a, offset, count); + } else { + VERIFY_CHECK((offset >> 6) + 1 < 4); + return ((a->d[offset >> 6] >> (offset & 0x3F)) | (a->d[(offset >> 6) + 1] << (64 - (offset & 0x3F)))) & ((((uint64_t)1) << count) - 1); + } +} + +SECP256K1_INLINE static int secp256k1_scalar_check_overflow(const secp256k1_scalar *a) { + int yes = 0; + int no = 0; + no |= (a->d[3] < SECP256K1_N_3); /* No need for a > check. */ + no |= (a->d[2] < SECP256K1_N_2); + yes |= (a->d[2] > SECP256K1_N_2) & ~no; + no |= (a->d[1] < SECP256K1_N_1); + yes |= (a->d[1] > SECP256K1_N_1) & ~no; + yes |= (a->d[0] >= SECP256K1_N_0) & ~no; + return yes; +} + +SECP256K1_INLINE static int secp256k1_scalar_reduce(secp256k1_scalar *r, unsigned int overflow) { + uint128_t t; + VERIFY_CHECK(overflow <= 1); + t = (uint128_t)r->d[0] + overflow * SECP256K1_N_C_0; + r->d[0] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[1] + overflow * SECP256K1_N_C_1; + r->d[1] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[2] + overflow * SECP256K1_N_C_2; + r->d[2] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint64_t)r->d[3]; + r->d[3] = t & 0xFFFFFFFFFFFFFFFFULL; + return overflow; +} + +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + int overflow; + uint128_t t = (uint128_t)a->d[0] + b->d[0]; + r->d[0] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)a->d[1] + b->d[1]; + r->d[1] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)a->d[2] + b->d[2]; + r->d[2] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)a->d[3] + b->d[3]; + r->d[3] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + overflow = t + secp256k1_scalar_check_overflow(r); + VERIFY_CHECK(overflow == 0 || overflow == 1); + secp256k1_scalar_reduce(r, overflow); + return overflow; +} + +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag) { + uint128_t t; + VERIFY_CHECK(bit < 256); + bit += ((uint32_t) flag - 1) & 0x100; /* forcing (bit >> 6) > 3 makes this a noop */ + t = (uint128_t)r->d[0] + (((uint64_t)((bit >> 6) == 0)) << (bit & 0x3F)); + r->d[0] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[1] + (((uint64_t)((bit >> 6) == 1)) << (bit & 0x3F)); + r->d[1] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[2] + (((uint64_t)((bit >> 6) == 2)) << (bit & 0x3F)); + r->d[2] = t & 0xFFFFFFFFFFFFFFFFULL; t >>= 64; + t += (uint128_t)r->d[3] + (((uint64_t)((bit >> 6) == 3)) << (bit & 0x3F)); + r->d[3] = t & 0xFFFFFFFFFFFFFFFFULL; +#ifdef VERIFY + VERIFY_CHECK((t >> 64) == 0); + VERIFY_CHECK(secp256k1_scalar_check_overflow(r) == 0); +#endif +} + +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *b32, int *overflow) { + int over; + r->d[0] = (uint64_t)b32[31] | (uint64_t)b32[30] << 8 | (uint64_t)b32[29] << 16 | (uint64_t)b32[28] << 24 | (uint64_t)b32[27] << 32 | (uint64_t)b32[26] << 40 | (uint64_t)b32[25] << 48 | (uint64_t)b32[24] << 56; + r->d[1] = (uint64_t)b32[23] | (uint64_t)b32[22] << 8 | (uint64_t)b32[21] << 16 | (uint64_t)b32[20] << 24 | (uint64_t)b32[19] << 32 | (uint64_t)b32[18] << 40 | (uint64_t)b32[17] << 48 | (uint64_t)b32[16] << 56; + r->d[2] = (uint64_t)b32[15] | (uint64_t)b32[14] << 8 | (uint64_t)b32[13] << 16 | (uint64_t)b32[12] << 24 | (uint64_t)b32[11] << 32 | (uint64_t)b32[10] << 40 | (uint64_t)b32[9] << 48 | (uint64_t)b32[8] << 56; + r->d[3] = (uint64_t)b32[7] | (uint64_t)b32[6] << 8 | (uint64_t)b32[5] << 16 | (uint64_t)b32[4] << 24 | (uint64_t)b32[3] << 32 | (uint64_t)b32[2] << 40 | (uint64_t)b32[1] << 48 | (uint64_t)b32[0] << 56; + over = secp256k1_scalar_reduce(r, secp256k1_scalar_check_overflow(r)); + if (overflow) { + *overflow = over; + } +} + +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a) { + bin[0] = a->d[3] >> 56; bin[1] = a->d[3] >> 48; bin[2] = a->d[3] >> 40; bin[3] = a->d[3] >> 32; bin[4] = a->d[3] >> 24; bin[5] = a->d[3] >> 16; bin[6] = a->d[3] >> 8; bin[7] = a->d[3]; + bin[8] = a->d[2] >> 56; bin[9] = a->d[2] >> 48; bin[10] = a->d[2] >> 40; bin[11] = a->d[2] >> 32; bin[12] = a->d[2] >> 24; bin[13] = a->d[2] >> 16; bin[14] = a->d[2] >> 8; bin[15] = a->d[2]; + bin[16] = a->d[1] >> 56; bin[17] = a->d[1] >> 48; bin[18] = a->d[1] >> 40; bin[19] = a->d[1] >> 32; bin[20] = a->d[1] >> 24; bin[21] = a->d[1] >> 16; bin[22] = a->d[1] >> 8; bin[23] = a->d[1]; + bin[24] = a->d[0] >> 56; bin[25] = a->d[0] >> 48; bin[26] = a->d[0] >> 40; bin[27] = a->d[0] >> 32; bin[28] = a->d[0] >> 24; bin[29] = a->d[0] >> 16; bin[30] = a->d[0] >> 8; bin[31] = a->d[0]; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_zero(const secp256k1_scalar *a) { + return (a->d[0] | a->d[1] | a->d[2] | a->d[3]) == 0; +} + +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a) { + uint64_t nonzero = 0xFFFFFFFFFFFFFFFFULL * (secp256k1_scalar_is_zero(a) == 0); + uint128_t t = (uint128_t)(~a->d[0]) + SECP256K1_N_0 + 1; + r->d[0] = t & nonzero; t >>= 64; + t += (uint128_t)(~a->d[1]) + SECP256K1_N_1; + r->d[1] = t & nonzero; t >>= 64; + t += (uint128_t)(~a->d[2]) + SECP256K1_N_2; + r->d[2] = t & nonzero; t >>= 64; + t += (uint128_t)(~a->d[3]) + SECP256K1_N_3; + r->d[3] = t & nonzero; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_one(const secp256k1_scalar *a) { + return ((a->d[0] ^ 1) | a->d[1] | a->d[2] | a->d[3]) == 0; +} + +static int secp256k1_scalar_is_high(const secp256k1_scalar *a) { + int yes = 0; + int no = 0; + no |= (a->d[3] < SECP256K1_N_H_3); + yes |= (a->d[3] > SECP256K1_N_H_3) & ~no; + no |= (a->d[2] < SECP256K1_N_H_2) & ~yes; /* No need for a > check. */ + no |= (a->d[1] < SECP256K1_N_H_1) & ~yes; + yes |= (a->d[1] > SECP256K1_N_H_1) & ~no; + yes |= (a->d[0] > SECP256K1_N_H_0) & ~no; + return yes; +} + +static int secp256k1_scalar_cond_negate(secp256k1_scalar *r, int flag) { + /* If we are flag = 0, mask = 00...00 and this is a no-op; + * if we are flag = 1, mask = 11...11 and this is identical to secp256k1_scalar_negate */ + uint64_t mask = !flag - 1; + uint64_t nonzero = (secp256k1_scalar_is_zero(r) != 0) - 1; + uint128_t t = (uint128_t)(r->d[0] ^ mask) + ((SECP256K1_N_0 + 1) & mask); + r->d[0] = t & nonzero; t >>= 64; + t += (uint128_t)(r->d[1] ^ mask) + (SECP256K1_N_1 & mask); + r->d[1] = t & nonzero; t >>= 64; + t += (uint128_t)(r->d[2] ^ mask) + (SECP256K1_N_2 & mask); + r->d[2] = t & nonzero; t >>= 64; + t += (uint128_t)(r->d[3] ^ mask) + (SECP256K1_N_3 & mask); + r->d[3] = t & nonzero; + return 2 * (mask == 0) - 1; +} + +/* Inspired by the macros in OpenSSL's crypto/bn/asm/x86_64-gcc.c. */ + +/** Add a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define muladd(a,b) { \ +uint64_t tl, th; \ +{ \ +uint128_t t = (uint128_t)a * b; \ +th = t >> 64; /* at most 0xFFFFFFFFFFFFFFFE */ \ +tl = t; \ +} \ +c0 += tl; /* overflow is handled on the next line */ \ +th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFFFFFFFFFF */ \ +c1 += th; /* overflow is handled on the next line */ \ +c2 += (c1 < th) ? 1 : 0; /* never overflows by contract (verified in the next line) */ \ +VERIFY_CHECK((c1 >= th) || (c2 != 0)); \ +} + +/** Add a*b to the number defined by (c0,c1). c1 must never overflow. */ +#define muladd_fast(a,b) { \ +uint64_t tl, th; \ +{ \ +uint128_t t = (uint128_t)a * b; \ +th = t >> 64; /* at most 0xFFFFFFFFFFFFFFFE */ \ +tl = t; \ +} \ +c0 += tl; /* overflow is handled on the next line */ \ +th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFFFFFFFFFF */ \ +c1 += th; /* never overflows by contract (verified in the next line) */ \ +VERIFY_CHECK(c1 >= th); \ +} + +/** Add 2*a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define muladd2(a,b) { \ +uint64_t tl, th, th2, tl2; \ +{ \ +uint128_t t = (uint128_t)a * b; \ +th = t >> 64; /* at most 0xFFFFFFFFFFFFFFFE */ \ +tl = t; \ +} \ +th2 = th + th; /* at most 0xFFFFFFFFFFFFFFFE (in case th was 0x7FFFFFFFFFFFFFFF) */ \ +c2 += (th2 < th) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ +VERIFY_CHECK((th2 >= th) || (c2 != 0)); \ +tl2 = tl + tl; /* at most 0xFFFFFFFFFFFFFFFE (in case the lowest 63 bits of tl were 0x7FFFFFFFFFFFFFFF) */ \ +th2 += (tl2 < tl) ? 1 : 0; /* at most 0xFFFFFFFFFFFFFFFF */ \ +c0 += tl2; /* overflow is handled on the next line */ \ +th2 += (c0 < tl2) ? 1 : 0; /* second overflow is handled on the next line */ \ +c2 += (c0 < tl2) & (th2 == 0); /* never overflows by contract (verified the next line) */ \ +VERIFY_CHECK((c0 >= tl2) || (th2 != 0) || (c2 != 0)); \ +c1 += th2; /* overflow is handled on the next line */ \ +c2 += (c1 < th2) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ +VERIFY_CHECK((c1 >= th2) || (c2 != 0)); \ +} + +/** Add a to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define sumadd(a) { \ +unsigned int over; \ +c0 += (a); /* overflow is handled on the next line */ \ +over = (c0 < (a)) ? 1 : 0; \ +c1 += over; /* overflow is handled on the next line */ \ +c2 += (c1 < over) ? 1 : 0; /* never overflows by contract */ \ +} + +/** Add a to the number defined by (c0,c1). c1 must never overflow, c2 must be zero. */ +#define sumadd_fast(a) { \ +c0 += (a); /* overflow is handled on the next line */ \ +c1 += (c0 < (a)) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ +VERIFY_CHECK((c1 != 0) | (c0 >= (a))); \ +VERIFY_CHECK(c2 == 0); \ +} + +/** Extract the lowest 64 bits of (c0,c1,c2) into n, and left shift the number 64 bits. */ +#define extract(n) { \ +(n) = c0; \ +c0 = c1; \ +c1 = c2; \ +c2 = 0; \ +} + +/** Extract the lowest 64 bits of (c0,c1,c2) into n, and left shift the number 64 bits. c2 is required to be zero. */ +#define extract_fast(n) { \ +(n) = c0; \ +c0 = c1; \ +c1 = 0; \ +VERIFY_CHECK(c2 == 0); \ +} + +static void secp256k1_scalar_reduce_512(secp256k1_scalar *r, const uint64_t *l) { +#ifdef USE_ASM_X86_64 + /* Reduce 512 bits into 385. */ + uint64_t m0, m1, m2, m3, m4, m5, m6; + uint64_t p0, p1, p2, p3, p4; + uint64_t c; + + __asm__ __volatile__( + /* Preload. */ + "movq 32(%%rsi), %%r11\n" + "movq 40(%%rsi), %%r12\n" + "movq 48(%%rsi), %%r13\n" + "movq 56(%%rsi), %%r14\n" + /* Initialize r8,r9,r10 */ + "movq 0(%%rsi), %%r8\n" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%r10\n" + /* (r8,r9) += n0 * c0 */ + "movq %8, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + /* extract m0 */ + "movq %%r8, %q0\n" + "xorq %%r8, %%r8\n" + /* (r9,r10) += l1 */ + "addq 8(%%rsi), %%r9\n" + "adcq $0, %%r10\n" + /* (r9,r10,r8) += n1 * c0 */ + "movq %8, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += n0 * c1 */ + "movq %9, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* extract m1 */ + "movq %%r9, %q1\n" + "xorq %%r9, %%r9\n" + /* (r10,r8,r9) += l2 */ + "addq 16(%%rsi), %%r10\n" + "adcq $0, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += n2 * c0 */ + "movq %8, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += n1 * c1 */ + "movq %9, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += n0 */ + "addq %%r11, %%r10\n" + "adcq $0, %%r8\n" + "adcq $0, %%r9\n" + /* extract m2 */ + "movq %%r10, %q2\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += l3 */ + "addq 24(%%rsi), %%r8\n" + "adcq $0, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += n3 * c0 */ + "movq %8, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += n2 * c1 */ + "movq %9, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += n1 */ + "addq %%r12, %%r8\n" + "adcq $0, %%r9\n" + "adcq $0, %%r10\n" + /* extract m3 */ + "movq %%r8, %q3\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += n3 * c1 */ + "movq %9, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += n2 */ + "addq %%r13, %%r9\n" + "adcq $0, %%r10\n" + "adcq $0, %%r8\n" + /* extract m4 */ + "movq %%r9, %q4\n" + /* (r10,r8) += n3 */ + "addq %%r14, %%r10\n" + "adcq $0, %%r8\n" + /* extract m5 */ + "movq %%r10, %q5\n" + /* extract m6 */ + "movq %%r8, %q6\n" + : "=g"(m0), "=g"(m1), "=g"(m2), "=g"(m3), "=g"(m4), "=g"(m5), "=g"(m6) + : "S"(l), "n"(SECP256K1_N_C_0), "n"(SECP256K1_N_C_1) + : "rax", "rdx", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "cc"); + + /* Reduce 385 bits into 258. */ + __asm__ __volatile__( + /* Preload */ + "movq %q9, %%r11\n" + "movq %q10, %%r12\n" + "movq %q11, %%r13\n" + /* Initialize (r8,r9,r10) */ + "movq %q5, %%r8\n" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%r10\n" + /* (r8,r9) += m4 * c0 */ + "movq %12, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + /* extract p0 */ + "movq %%r8, %q0\n" + "xorq %%r8, %%r8\n" + /* (r9,r10) += m1 */ + "addq %q6, %%r9\n" + "adcq $0, %%r10\n" + /* (r9,r10,r8) += m5 * c0 */ + "movq %12, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += m4 * c1 */ + "movq %13, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* extract p1 */ + "movq %%r9, %q1\n" + "xorq %%r9, %%r9\n" + /* (r10,r8,r9) += m2 */ + "addq %q7, %%r10\n" + "adcq $0, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += m6 * c0 */ + "movq %12, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += m5 * c1 */ + "movq %13, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += m4 */ + "addq %%r11, %%r10\n" + "adcq $0, %%r8\n" + "adcq $0, %%r9\n" + /* extract p2 */ + "movq %%r10, %q2\n" + /* (r8,r9) += m3 */ + "addq %q8, %%r8\n" + "adcq $0, %%r9\n" + /* (r8,r9) += m6 * c1 */ + "movq %13, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + /* (r8,r9) += m5 */ + "addq %%r12, %%r8\n" + "adcq $0, %%r9\n" + /* extract p3 */ + "movq %%r8, %q3\n" + /* (r9) += m6 */ + "addq %%r13, %%r9\n" + /* extract p4 */ + "movq %%r9, %q4\n" + : "=&g"(p0), "=&g"(p1), "=&g"(p2), "=g"(p3), "=g"(p4) + : "g"(m0), "g"(m1), "g"(m2), "g"(m3), "g"(m4), "g"(m5), "g"(m6), "n"(SECP256K1_N_C_0), "n"(SECP256K1_N_C_1) + : "rax", "rdx", "r8", "r9", "r10", "r11", "r12", "r13", "cc"); + + /* Reduce 258 bits into 256. */ + __asm__ __volatile__( + /* Preload */ + "movq %q5, %%r10\n" + /* (rax,rdx) = p4 * c0 */ + "movq %7, %%rax\n" + "mulq %%r10\n" + /* (rax,rdx) += p0 */ + "addq %q1, %%rax\n" + "adcq $0, %%rdx\n" + /* extract r0 */ + "movq %%rax, 0(%q6)\n" + /* Move to (r8,r9) */ + "movq %%rdx, %%r8\n" + "xorq %%r9, %%r9\n" + /* (r8,r9) += p1 */ + "addq %q2, %%r8\n" + "adcq $0, %%r9\n" + /* (r8,r9) += p4 * c1 */ + "movq %8, %%rax\n" + "mulq %%r10\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + /* Extract r1 */ + "movq %%r8, 8(%q6)\n" + "xorq %%r8, %%r8\n" + /* (r9,r8) += p4 */ + "addq %%r10, %%r9\n" + "adcq $0, %%r8\n" + /* (r9,r8) += p2 */ + "addq %q3, %%r9\n" + "adcq $0, %%r8\n" + /* Extract r2 */ + "movq %%r9, 16(%q6)\n" + "xorq %%r9, %%r9\n" + /* (r8,r9) += p3 */ + "addq %q4, %%r8\n" + "adcq $0, %%r9\n" + /* Extract r3 */ + "movq %%r8, 24(%q6)\n" + /* Extract c */ + "movq %%r9, %q0\n" + : "=g"(c) + : "g"(p0), "g"(p1), "g"(p2), "g"(p3), "g"(p4), "D"(r), "n"(SECP256K1_N_C_0), "n"(SECP256K1_N_C_1) + : "rax", "rdx", "r8", "r9", "r10", "cc", "memory"); +#else + uint128_t c; + uint64_t c0, c1, c2; + uint64_t n0 = l[4], n1 = l[5], n2 = l[6], n3 = l[7]; + uint64_t m0, m1, m2, m3, m4, m5; + uint32_t m6; + uint64_t p0, p1, p2, p3; + uint32_t p4; + + /* Reduce 512 bits into 385. */ + /* m[0..6] = l[0..3] + n[0..3] * SECP256K1_N_C. */ + c0 = l[0]; c1 = 0; c2 = 0; + muladd_fast(n0, SECP256K1_N_C_0); + extract_fast(m0); + sumadd_fast(l[1]); + muladd(n1, SECP256K1_N_C_0); + muladd(n0, SECP256K1_N_C_1); + extract(m1); + sumadd(l[2]); + muladd(n2, SECP256K1_N_C_0); + muladd(n1, SECP256K1_N_C_1); + sumadd(n0); + extract(m2); + sumadd(l[3]); + muladd(n3, SECP256K1_N_C_0); + muladd(n2, SECP256K1_N_C_1); + sumadd(n1); + extract(m3); + muladd(n3, SECP256K1_N_C_1); + sumadd(n2); + extract(m4); + sumadd_fast(n3); + extract_fast(m5); + VERIFY_CHECK(c0 <= 1); + m6 = c0; + + /* Reduce 385 bits into 258. */ + /* p[0..4] = m[0..3] + m[4..6] * SECP256K1_N_C. */ + c0 = m0; c1 = 0; c2 = 0; + muladd_fast(m4, SECP256K1_N_C_0); + extract_fast(p0); + sumadd_fast(m1); + muladd(m5, SECP256K1_N_C_0); + muladd(m4, SECP256K1_N_C_1); + extract(p1); + sumadd(m2); + muladd(m6, SECP256K1_N_C_0); + muladd(m5, SECP256K1_N_C_1); + sumadd(m4); + extract(p2); + sumadd_fast(m3); + muladd_fast(m6, SECP256K1_N_C_1); + sumadd_fast(m5); + extract_fast(p3); + p4 = c0 + m6; + VERIFY_CHECK(p4 <= 2); + + /* Reduce 258 bits into 256. */ + /* r[0..3] = p[0..3] + p[4] * SECP256K1_N_C. */ + c = p0 + (uint128_t)SECP256K1_N_C_0 * p4; + r->d[0] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; + c += p1 + (uint128_t)SECP256K1_N_C_1 * p4; + r->d[1] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; + c += p2 + (uint128_t)p4; + r->d[2] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; + c += p3; + r->d[3] = c & 0xFFFFFFFFFFFFFFFFULL; c >>= 64; +#endif + + /* Final reduction of r. */ + secp256k1_scalar_reduce(r, c + secp256k1_scalar_check_overflow(r)); +} + +static void secp256k1_scalar_mul_512(uint64_t l[8], const secp256k1_scalar *a, const secp256k1_scalar *b) { +#ifdef USE_ASM_X86_64 + const uint64_t *pb = b->d; + __asm__ __volatile__( + /* Preload */ + "movq 0(%%rdi), %%r15\n" + "movq 8(%%rdi), %%rbx\n" + "movq 16(%%rdi), %%rcx\n" + "movq 0(%%rdx), %%r11\n" + "movq 8(%%rdx), %%r12\n" + "movq 16(%%rdx), %%r13\n" + "movq 24(%%rdx), %%r14\n" + /* (rax,rdx) = a0 * b0 */ + "movq %%r15, %%rax\n" + "mulq %%r11\n" + /* Extract l0 */ + "movq %%rax, 0(%%rsi)\n" + /* (r8,r9,r10) = (rdx) */ + "movq %%rdx, %%r8\n" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += a0 * b1 */ + "movq %%r15, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += a1 * b0 */ + "movq %%rbx, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* Extract l1 */ + "movq %%r8, 8(%%rsi)\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += a0 * b2 */ + "movq %%r15, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += a1 * b1 */ + "movq %%rbx, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += a2 * b0 */ + "movq %%rcx, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* Extract l2 */ + "movq %%r9, 16(%%rsi)\n" + "xorq %%r9, %%r9\n" + /* (r10,r8,r9) += a0 * b3 */ + "movq %%r15, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* Preload a3 */ + "movq 24(%%rdi), %%r15\n" + /* (r10,r8,r9) += a1 * b2 */ + "movq %%rbx, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += a2 * b1 */ + "movq %%rcx, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += a3 * b0 */ + "movq %%r15, %%rax\n" + "mulq %%r11\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* Extract l3 */ + "movq %%r10, 24(%%rsi)\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += a1 * b3 */ + "movq %%rbx, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += a2 * b2 */ + "movq %%rcx, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += a3 * b1 */ + "movq %%r15, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* Extract l4 */ + "movq %%r8, 32(%%rsi)\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += a2 * b3 */ + "movq %%rcx, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += a3 * b2 */ + "movq %%r15, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* Extract l5 */ + "movq %%r9, 40(%%rsi)\n" + /* (r10,r8) += a3 * b3 */ + "movq %%r15, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + /* Extract l6 */ + "movq %%r10, 48(%%rsi)\n" + /* Extract l7 */ + "movq %%r8, 56(%%rsi)\n" + : "+d"(pb) + : "S"(l), "D"(a->d) + : "rax", "rbx", "rcx", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "cc", "memory"); +#else + /* 160 bit accumulator. */ + uint64_t c0 = 0, c1 = 0; + uint32_t c2 = 0; + + /* l[0..7] = a[0..3] * b[0..3]. */ + muladd_fast(a->d[0], b->d[0]); + extract_fast(l[0]); + muladd(a->d[0], b->d[1]); + muladd(a->d[1], b->d[0]); + extract(l[1]); + muladd(a->d[0], b->d[2]); + muladd(a->d[1], b->d[1]); + muladd(a->d[2], b->d[0]); + extract(l[2]); + muladd(a->d[0], b->d[3]); + muladd(a->d[1], b->d[2]); + muladd(a->d[2], b->d[1]); + muladd(a->d[3], b->d[0]); + extract(l[3]); + muladd(a->d[1], b->d[3]); + muladd(a->d[2], b->d[2]); + muladd(a->d[3], b->d[1]); + extract(l[4]); + muladd(a->d[2], b->d[3]); + muladd(a->d[3], b->d[2]); + extract(l[5]); + muladd_fast(a->d[3], b->d[3]); + extract_fast(l[6]); + VERIFY_CHECK(c1 == 0); + l[7] = c0; +#endif +} + +static void secp256k1_scalar_sqr_512(uint64_t l[8], const secp256k1_scalar *a) { +#ifdef USE_ASM_X86_64 + __asm__ __volatile__( + /* Preload */ + "movq 0(%%rdi), %%r11\n" + "movq 8(%%rdi), %%r12\n" + "movq 16(%%rdi), %%r13\n" + "movq 24(%%rdi), %%r14\n" + /* (rax,rdx) = a0 * a0 */ + "movq %%r11, %%rax\n" + "mulq %%r11\n" + /* Extract l0 */ + "movq %%rax, 0(%%rsi)\n" + /* (r8,r9,r10) = (rdx,0) */ + "movq %%rdx, %%r8\n" + "xorq %%r9, %%r9\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += 2 * a0 * a1 */ + "movq %%r11, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* Extract l1 */ + "movq %%r8, 8(%%rsi)\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += 2 * a0 * a2 */ + "movq %%r11, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* (r9,r10,r8) += a1 * a1 */ + "movq %%r12, %%rax\n" + "mulq %%r12\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* Extract l2 */ + "movq %%r9, 16(%%rsi)\n" + "xorq %%r9, %%r9\n" + /* (r10,r8,r9) += 2 * a0 * a3 */ + "movq %%r11, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* (r10,r8,r9) += 2 * a1 * a2 */ + "movq %%r12, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + "adcq $0, %%r9\n" + /* Extract l3 */ + "movq %%r10, 24(%%rsi)\n" + "xorq %%r10, %%r10\n" + /* (r8,r9,r10) += 2 * a1 * a3 */ + "movq %%r12, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* (r8,r9,r10) += a2 * a2 */ + "movq %%r13, %%rax\n" + "mulq %%r13\n" + "addq %%rax, %%r8\n" + "adcq %%rdx, %%r9\n" + "adcq $0, %%r10\n" + /* Extract l4 */ + "movq %%r8, 32(%%rsi)\n" + "xorq %%r8, %%r8\n" + /* (r9,r10,r8) += 2 * a2 * a3 */ + "movq %%r13, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + "addq %%rax, %%r9\n" + "adcq %%rdx, %%r10\n" + "adcq $0, %%r8\n" + /* Extract l5 */ + "movq %%r9, 40(%%rsi)\n" + /* (r10,r8) += a3 * a3 */ + "movq %%r14, %%rax\n" + "mulq %%r14\n" + "addq %%rax, %%r10\n" + "adcq %%rdx, %%r8\n" + /* Extract l6 */ + "movq %%r10, 48(%%rsi)\n" + /* Extract l7 */ + "movq %%r8, 56(%%rsi)\n" + : + : "S"(l), "D"(a->d) + : "rax", "rdx", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "cc", "memory"); +#else + /* 160 bit accumulator. */ + uint64_t c0 = 0, c1 = 0; + uint32_t c2 = 0; + + /* l[0..7] = a[0..3] * b[0..3]. */ + muladd_fast(a->d[0], a->d[0]); + extract_fast(l[0]); + muladd2(a->d[0], a->d[1]); + extract(l[1]); + muladd2(a->d[0], a->d[2]); + muladd(a->d[1], a->d[1]); + extract(l[2]); + muladd2(a->d[0], a->d[3]); + muladd2(a->d[1], a->d[2]); + extract(l[3]); + muladd2(a->d[1], a->d[3]); + muladd(a->d[2], a->d[2]); + extract(l[4]); + muladd2(a->d[2], a->d[3]); + extract(l[5]); + muladd_fast(a->d[3], a->d[3]); + extract_fast(l[6]); + VERIFY_CHECK(c1 == 0); + l[7] = c0; +#endif +} + +#undef sumadd +#undef sumadd_fast +#undef muladd +#undef muladd_fast +#undef muladd2 +#undef extract +#undef extract_fast + +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + uint64_t l[8]; + secp256k1_scalar_mul_512(l, a, b); + secp256k1_scalar_reduce_512(r, l); +} + +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n) { + int ret; + VERIFY_CHECK(n > 0); + VERIFY_CHECK(n < 16); + ret = r->d[0] & ((1 << n) - 1); + r->d[0] = (r->d[0] >> n) + (r->d[1] << (64 - n)); + r->d[1] = (r->d[1] >> n) + (r->d[2] << (64 - n)); + r->d[2] = (r->d[2] >> n) + (r->d[3] << (64 - n)); + r->d[3] = (r->d[3] >> n); + return ret; +} + +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a) { + uint64_t l[8]; + secp256k1_scalar_sqr_512(l, a); + secp256k1_scalar_reduce_512(r, l); +} + +#ifdef USE_ENDOMORPHISM +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + r1->d[0] = a->d[0]; + r1->d[1] = a->d[1]; + r1->d[2] = 0; + r1->d[3] = 0; + r2->d[0] = a->d[2]; + r2->d[1] = a->d[3]; + r2->d[2] = 0; + r2->d[3] = 0; +} +#endif + +SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b) { + return ((a->d[0] ^ b->d[0]) | (a->d[1] ^ b->d[1]) | (a->d[2] ^ b->d[2]) | (a->d[3] ^ b->d[3])) == 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift) { + uint64_t l[8]; + unsigned int shiftlimbs; + unsigned int shiftlow; + unsigned int shifthigh; + VERIFY_CHECK(shift >= 256); + secp256k1_scalar_mul_512(l, a, b); + shiftlimbs = shift >> 6; + shiftlow = shift & 0x3F; + shifthigh = 64 - shiftlow; + r->d[0] = shift < 512 ? (l[0 + shiftlimbs] >> shiftlow | (shift < 448 && shiftlow ? (l[1 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[1] = shift < 448 ? (l[1 + shiftlimbs] >> shiftlow | (shift < 384 && shiftlow ? (l[2 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[2] = shift < 384 ? (l[2 + shiftlimbs] >> shiftlow | (shift < 320 && shiftlow ? (l[3 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[3] = shift < 320 ? (l[3 + shiftlimbs] >> shiftlow) : 0; + secp256k1_scalar_cadd_bit(r, 0, (l[(shift - 1) >> 6] >> ((shift - 1) & 0x3f)) & 1); +} + +#define ROTL32(x,n) ((x) << (n) | (x) >> (32-(n))) +#define QUARTERROUND(a,b,c,d) \ +a += b; d = ROTL32(d ^ a, 16); \ +c += d; b = ROTL32(b ^ c, 12); \ +a += b; d = ROTL32(d ^ a, 8); \ +c += d; b = ROTL32(b ^ c, 7); + +#ifdef WORDS_BIGENDIAN +#define LE32(p) ((((p) & 0xFF) << 24) | (((p) & 0xFF00) << 8) | (((p) & 0xFF0000) >> 8) | (((p) & 0xFF000000) >> 24)) +#define BE32(p) (p) +#else +#define BE32(p) ((((p) & 0xFF) << 24) | (((p) & 0xFF00) << 8) | (((p) & 0xFF0000) >> 8) | (((p) & 0xFF000000) >> 24)) +#define LE32(p) (p) +#endif + +static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx) { + size_t n; + size_t over_count = 0; + uint32_t seed32[8]; + uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; + int over1, over2; + + memcpy((void *) seed32, (const void *) seed, 32); + do { + x0 = 0x61707865; + x1 = 0x3320646e; + x2 = 0x79622d32; + x3 = 0x6b206574; + x4 = LE32(seed32[0]); + x5 = LE32(seed32[1]); + x6 = LE32(seed32[2]); + x7 = LE32(seed32[3]); + x8 = LE32(seed32[4]); + x9 = LE32(seed32[5]); + x10 = LE32(seed32[6]); + x11 = LE32(seed32[7]); + x12 = idx; + x13 = idx >> 32; + x14 = 0; + x15 = over_count; + + n = 10; + while (n--) { + QUARTERROUND(x0, x4, x8,x12) + QUARTERROUND(x1, x5, x9,x13) + QUARTERROUND(x2, x6,x10,x14) + QUARTERROUND(x3, x7,x11,x15) + QUARTERROUND(x0, x5,x10,x15) + QUARTERROUND(x1, x6,x11,x12) + QUARTERROUND(x2, x7, x8,x13) + QUARTERROUND(x3, x4, x9,x14) + } + + x0 += 0x61707865; + x1 += 0x3320646e; + x2 += 0x79622d32; + x3 += 0x6b206574; + x4 += LE32(seed32[0]); + x5 += LE32(seed32[1]); + x6 += LE32(seed32[2]); + x7 += LE32(seed32[3]); + x8 += LE32(seed32[4]); + x9 += LE32(seed32[5]); + x10 += LE32(seed32[6]); + x11 += LE32(seed32[7]); + x12 += idx; + x13 += idx >> 32; + x14 += 0; + x15 += over_count; + + r1->d[3] = LE32((uint64_t) x0) << 32 | LE32(x1); + r1->d[2] = LE32((uint64_t) x2) << 32 | LE32(x3); + r1->d[1] = LE32((uint64_t) x4) << 32 | LE32(x5); + r1->d[0] = LE32((uint64_t) x6) << 32 | LE32(x7); + r2->d[3] = LE32((uint64_t) x8) << 32 | LE32(x9); + r2->d[2] = LE32((uint64_t) x10) << 32 | LE32(x11); + r2->d[1] = LE32((uint64_t) x12) << 32 | LE32(x13); + r2->d[0] = LE32((uint64_t) x14) << 32 | LE32(x15); + + over1 = secp256k1_scalar_check_overflow(r1); + over2 = secp256k1_scalar_check_overflow(r2); + over_count++; + } while (over1 | over2); +} + +#undef ROTL32 +#undef QUARTERROUND +#undef BE32 +#undef LE32 + +#endif /* SECP256K1_SCALAR_REPR_IMPL_H */ +#endif + diff --git a/src/secp256k1/src/scalar_8x32.h b/src/secp256k1/src/scalar_8x32.h index 2c9a348e2..68a2c0428 100644 --- a/src/secp256k1/src/scalar_8x32.h +++ b/src/secp256k1/src/scalar_8x32.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -17,3 +19,25 @@ typedef struct { #define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{(d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7)}} #endif /* SECP256K1_SCALAR_REPR_H */ + +#else +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef struct { + uint32_t d[8]; +} secp256k1_scalar; + +#define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{(d0), (d1), (d2), (d3), (d4), (d5), (d6), (d7)}} + +#endif /* SECP256K1_SCALAR_REPR_H */ +#endif diff --git a/src/secp256k1/src/scalar_8x32_impl.h b/src/secp256k1/src/scalar_8x32_impl.h index 4f9ed61fe..e1299cbaa 100644 --- a/src/secp256k1/src/scalar_8x32_impl.h +++ b/src/secp256k1/src/scalar_8x32_impl.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -719,3 +721,839 @@ SECP256K1_INLINE static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, } #endif /* SECP256K1_SCALAR_REPR_IMPL_H */ + +#else +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_IMPL_H +#define SECP256K1_SCALAR_REPR_IMPL_H + +#include + +/* Limbs of the secp256k1 order. */ +#define SECP256K1_N_0 ((uint32_t)0xD0364141UL) +#define SECP256K1_N_1 ((uint32_t)0xBFD25E8CUL) +#define SECP256K1_N_2 ((uint32_t)0xAF48A03BUL) +#define SECP256K1_N_3 ((uint32_t)0xBAAEDCE6UL) +#define SECP256K1_N_4 ((uint32_t)0xFFFFFFFEUL) +#define SECP256K1_N_5 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_6 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_7 ((uint32_t)0xFFFFFFFFUL) + +/* Limbs of 2^256 minus the secp256k1 order. */ +#define SECP256K1_N_C_0 (~SECP256K1_N_0 + 1) +#define SECP256K1_N_C_1 (~SECP256K1_N_1) +#define SECP256K1_N_C_2 (~SECP256K1_N_2) +#define SECP256K1_N_C_3 (~SECP256K1_N_3) +#define SECP256K1_N_C_4 (1) + +/* Limbs of half the secp256k1 order. */ +#define SECP256K1_N_H_0 ((uint32_t)0x681B20A0UL) +#define SECP256K1_N_H_1 ((uint32_t)0xDFE92F46UL) +#define SECP256K1_N_H_2 ((uint32_t)0x57A4501DUL) +#define SECP256K1_N_H_3 ((uint32_t)0x5D576E73UL) +#define SECP256K1_N_H_4 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_H_5 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_H_6 ((uint32_t)0xFFFFFFFFUL) +#define SECP256K1_N_H_7 ((uint32_t)0x7FFFFFFFUL) + +SECP256K1_INLINE static void secp256k1_scalar_clear(secp256k1_scalar *r) { + r->d[0] = 0; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; + r->d[4] = 0; + r->d[5] = 0; + r->d[6] = 0; + r->d[7] = 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v) { + r->d[0] = v; + r->d[1] = 0; + r->d[2] = 0; + r->d[3] = 0; + r->d[4] = 0; + r->d[5] = 0; + r->d[6] = 0; + r->d[7] = 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_set_u64(secp256k1_scalar *r, uint64_t v) { + r->d[0] = v; + r->d[1] = v >> 32; + r->d[2] = 0; + r->d[3] = 0; + r->d[4] = 0; + r->d[5] = 0; + r->d[6] = 0; + r->d[7] = 0; +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + VERIFY_CHECK((offset + count - 1) >> 5 == offset >> 5); + return (a->d[offset >> 5] >> (offset & 0x1F)) & ((1 << count) - 1); +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + VERIFY_CHECK(count < 32); + VERIFY_CHECK(offset + count <= 256); + if ((offset + count - 1) >> 5 == offset >> 5) { + return secp256k1_scalar_get_bits(a, offset, count); + } else { + VERIFY_CHECK((offset >> 5) + 1 < 8); + return ((a->d[offset >> 5] >> (offset & 0x1F)) | (a->d[(offset >> 5) + 1] << (32 - (offset & 0x1F)))) & ((((uint32_t)1) << count) - 1); + } +} + +SECP256K1_INLINE static int secp256k1_scalar_check_overflow(const secp256k1_scalar *a) { + int yes = 0; + int no = 0; + no |= (a->d[7] < SECP256K1_N_7); /* No need for a > check. */ + no |= (a->d[6] < SECP256K1_N_6); /* No need for a > check. */ + no |= (a->d[5] < SECP256K1_N_5); /* No need for a > check. */ + no |= (a->d[4] < SECP256K1_N_4); + yes |= (a->d[4] > SECP256K1_N_4) & ~no; + no |= (a->d[3] < SECP256K1_N_3) & ~yes; + yes |= (a->d[3] > SECP256K1_N_3) & ~no; + no |= (a->d[2] < SECP256K1_N_2) & ~yes; + yes |= (a->d[2] > SECP256K1_N_2) & ~no; + no |= (a->d[1] < SECP256K1_N_1) & ~yes; + yes |= (a->d[1] > SECP256K1_N_1) & ~no; + yes |= (a->d[0] >= SECP256K1_N_0) & ~no; + return yes; +} + +SECP256K1_INLINE static int secp256k1_scalar_reduce(secp256k1_scalar *r, uint32_t overflow) { + uint64_t t; + VERIFY_CHECK(overflow <= 1); + t = (uint64_t)r->d[0] + overflow * SECP256K1_N_C_0; + r->d[0] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[1] + overflow * SECP256K1_N_C_1; + r->d[1] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[2] + overflow * SECP256K1_N_C_2; + r->d[2] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[3] + overflow * SECP256K1_N_C_3; + r->d[3] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[4] + overflow * SECP256K1_N_C_4; + r->d[4] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[5]; + r->d[5] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[6]; + r->d[6] = t & 0xFFFFFFFFUL; t >>= 32; + t += (uint64_t)r->d[7]; + r->d[7] = t & 0xFFFFFFFFUL; + return overflow; +} + +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + int overflow; + uint64_t t = (uint64_t)a->d[0] + b->d[0]; + r->d[0] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[1] + b->d[1]; + r->d[1] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[2] + b->d[2]; + r->d[2] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[3] + b->d[3]; + r->d[3] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[4] + b->d[4]; + r->d[4] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[5] + b->d[5]; + r->d[5] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[6] + b->d[6]; + r->d[6] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)a->d[7] + b->d[7]; + r->d[7] = t & 0xFFFFFFFFULL; t >>= 32; + overflow = t + secp256k1_scalar_check_overflow(r); + VERIFY_CHECK(overflow == 0 || overflow == 1); + secp256k1_scalar_reduce(r, overflow); + return overflow; +} + +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag) { + uint64_t t; + VERIFY_CHECK(bit < 256); + bit += ((uint32_t) flag - 1) & 0x100; /* forcing (bit >> 5) > 7 makes this a noop */ + t = (uint64_t)r->d[0] + (((uint32_t)((bit >> 5) == 0)) << (bit & 0x1F)); + r->d[0] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[1] + (((uint32_t)((bit >> 5) == 1)) << (bit & 0x1F)); + r->d[1] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[2] + (((uint32_t)((bit >> 5) == 2)) << (bit & 0x1F)); + r->d[2] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[3] + (((uint32_t)((bit >> 5) == 3)) << (bit & 0x1F)); + r->d[3] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[4] + (((uint32_t)((bit >> 5) == 4)) << (bit & 0x1F)); + r->d[4] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[5] + (((uint32_t)((bit >> 5) == 5)) << (bit & 0x1F)); + r->d[5] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[6] + (((uint32_t)((bit >> 5) == 6)) << (bit & 0x1F)); + r->d[6] = t & 0xFFFFFFFFULL; t >>= 32; + t += (uint64_t)r->d[7] + (((uint32_t)((bit >> 5) == 7)) << (bit & 0x1F)); + r->d[7] = t & 0xFFFFFFFFULL; +#ifdef VERIFY + VERIFY_CHECK((t >> 32) == 0); + VERIFY_CHECK(secp256k1_scalar_check_overflow(r) == 0); +#endif +} + +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *b32, int *overflow) { + int over; + r->d[0] = (uint32_t)b32[31] | (uint32_t)b32[30] << 8 | (uint32_t)b32[29] << 16 | (uint32_t)b32[28] << 24; + r->d[1] = (uint32_t)b32[27] | (uint32_t)b32[26] << 8 | (uint32_t)b32[25] << 16 | (uint32_t)b32[24] << 24; + r->d[2] = (uint32_t)b32[23] | (uint32_t)b32[22] << 8 | (uint32_t)b32[21] << 16 | (uint32_t)b32[20] << 24; + r->d[3] = (uint32_t)b32[19] | (uint32_t)b32[18] << 8 | (uint32_t)b32[17] << 16 | (uint32_t)b32[16] << 24; + r->d[4] = (uint32_t)b32[15] | (uint32_t)b32[14] << 8 | (uint32_t)b32[13] << 16 | (uint32_t)b32[12] << 24; + r->d[5] = (uint32_t)b32[11] | (uint32_t)b32[10] << 8 | (uint32_t)b32[9] << 16 | (uint32_t)b32[8] << 24; + r->d[6] = (uint32_t)b32[7] | (uint32_t)b32[6] << 8 | (uint32_t)b32[5] << 16 | (uint32_t)b32[4] << 24; + r->d[7] = (uint32_t)b32[3] | (uint32_t)b32[2] << 8 | (uint32_t)b32[1] << 16 | (uint32_t)b32[0] << 24; + over = secp256k1_scalar_reduce(r, secp256k1_scalar_check_overflow(r)); + if (overflow) { + *overflow = over; + } +} + +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a) { + bin[0] = a->d[7] >> 24; bin[1] = a->d[7] >> 16; bin[2] = a->d[7] >> 8; bin[3] = a->d[7]; + bin[4] = a->d[6] >> 24; bin[5] = a->d[6] >> 16; bin[6] = a->d[6] >> 8; bin[7] = a->d[6]; + bin[8] = a->d[5] >> 24; bin[9] = a->d[5] >> 16; bin[10] = a->d[5] >> 8; bin[11] = a->d[5]; + bin[12] = a->d[4] >> 24; bin[13] = a->d[4] >> 16; bin[14] = a->d[4] >> 8; bin[15] = a->d[4]; + bin[16] = a->d[3] >> 24; bin[17] = a->d[3] >> 16; bin[18] = a->d[3] >> 8; bin[19] = a->d[3]; + bin[20] = a->d[2] >> 24; bin[21] = a->d[2] >> 16; bin[22] = a->d[2] >> 8; bin[23] = a->d[2]; + bin[24] = a->d[1] >> 24; bin[25] = a->d[1] >> 16; bin[26] = a->d[1] >> 8; bin[27] = a->d[1]; + bin[28] = a->d[0] >> 24; bin[29] = a->d[0] >> 16; bin[30] = a->d[0] >> 8; bin[31] = a->d[0]; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_zero(const secp256k1_scalar *a) { + return (a->d[0] | a->d[1] | a->d[2] | a->d[3] | a->d[4] | a->d[5] | a->d[6] | a->d[7]) == 0; +} + +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a) { + uint32_t nonzero = 0xFFFFFFFFUL * (secp256k1_scalar_is_zero(a) == 0); + uint64_t t = (uint64_t)(~a->d[0]) + SECP256K1_N_0 + 1; + r->d[0] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[1]) + SECP256K1_N_1; + r->d[1] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[2]) + SECP256K1_N_2; + r->d[2] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[3]) + SECP256K1_N_3; + r->d[3] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[4]) + SECP256K1_N_4; + r->d[4] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[5]) + SECP256K1_N_5; + r->d[5] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[6]) + SECP256K1_N_6; + r->d[6] = t & nonzero; t >>= 32; + t += (uint64_t)(~a->d[7]) + SECP256K1_N_7; + r->d[7] = t & nonzero; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_one(const secp256k1_scalar *a) { + return ((a->d[0] ^ 1) | a->d[1] | a->d[2] | a->d[3] | a->d[4] | a->d[5] | a->d[6] | a->d[7]) == 0; +} + +static int secp256k1_scalar_is_high(const secp256k1_scalar *a) { + int yes = 0; + int no = 0; + no |= (a->d[7] < SECP256K1_N_H_7); + yes |= (a->d[7] > SECP256K1_N_H_7) & ~no; + no |= (a->d[6] < SECP256K1_N_H_6) & ~yes; /* No need for a > check. */ + no |= (a->d[5] < SECP256K1_N_H_5) & ~yes; /* No need for a > check. */ + no |= (a->d[4] < SECP256K1_N_H_4) & ~yes; /* No need for a > check. */ + no |= (a->d[3] < SECP256K1_N_H_3) & ~yes; + yes |= (a->d[3] > SECP256K1_N_H_3) & ~no; + no |= (a->d[2] < SECP256K1_N_H_2) & ~yes; + yes |= (a->d[2] > SECP256K1_N_H_2) & ~no; + no |= (a->d[1] < SECP256K1_N_H_1) & ~yes; + yes |= (a->d[1] > SECP256K1_N_H_1) & ~no; + yes |= (a->d[0] > SECP256K1_N_H_0) & ~no; + return yes; +} + +static int secp256k1_scalar_cond_negate(secp256k1_scalar *r, int flag) { + /* If we are flag = 0, mask = 00...00 and this is a no-op; + * if we are flag = 1, mask = 11...11 and this is identical to secp256k1_scalar_negate */ + uint32_t mask = !flag - 1; + uint32_t nonzero = 0xFFFFFFFFUL * (secp256k1_scalar_is_zero(r) == 0); + uint64_t t = (uint64_t)(r->d[0] ^ mask) + ((SECP256K1_N_0 + 1) & mask); + r->d[0] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[1] ^ mask) + (SECP256K1_N_1 & mask); + r->d[1] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[2] ^ mask) + (SECP256K1_N_2 & mask); + r->d[2] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[3] ^ mask) + (SECP256K1_N_3 & mask); + r->d[3] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[4] ^ mask) + (SECP256K1_N_4 & mask); + r->d[4] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[5] ^ mask) + (SECP256K1_N_5 & mask); + r->d[5] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[6] ^ mask) + (SECP256K1_N_6 & mask); + r->d[6] = t & nonzero; t >>= 32; + t += (uint64_t)(r->d[7] ^ mask) + (SECP256K1_N_7 & mask); + r->d[7] = t & nonzero; + return 2 * (mask == 0) - 1; +} + + +/* Inspired by the macros in OpenSSL's crypto/bn/asm/x86_64-gcc.c. */ + +/** Add a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define muladd(a,b) { \ +uint32_t tl, th; \ +{ \ +uint64_t t = (uint64_t)a * b; \ +th = t >> 32; /* at most 0xFFFFFFFE */ \ +tl = t; \ +} \ +c0 += tl; /* overflow is handled on the next line */ \ +th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFF */ \ +c1 += th; /* overflow is handled on the next line */ \ +c2 += (c1 < th) ? 1 : 0; /* never overflows by contract (verified in the next line) */ \ +VERIFY_CHECK((c1 >= th) || (c2 != 0)); \ +} + +/** Add a*b to the number defined by (c0,c1). c1 must never overflow. */ +#define muladd_fast(a,b) { \ +uint32_t tl, th; \ +{ \ +uint64_t t = (uint64_t)a * b; \ +th = t >> 32; /* at most 0xFFFFFFFE */ \ +tl = t; \ +} \ +c0 += tl; /* overflow is handled on the next line */ \ +th += (c0 < tl) ? 1 : 0; /* at most 0xFFFFFFFF */ \ +c1 += th; /* never overflows by contract (verified in the next line) */ \ +VERIFY_CHECK(c1 >= th); \ +} + +/** Add 2*a*b to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define muladd2(a,b) { \ +uint32_t tl, th, th2, tl2; \ +{ \ +uint64_t t = (uint64_t)a * b; \ +th = t >> 32; /* at most 0xFFFFFFFE */ \ +tl = t; \ +} \ +th2 = th + th; /* at most 0xFFFFFFFE (in case th was 0x7FFFFFFF) */ \ +c2 += (th2 < th) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ +VERIFY_CHECK((th2 >= th) || (c2 != 0)); \ +tl2 = tl + tl; /* at most 0xFFFFFFFE (in case the lowest 63 bits of tl were 0x7FFFFFFF) */ \ +th2 += (tl2 < tl) ? 1 : 0; /* at most 0xFFFFFFFF */ \ +c0 += tl2; /* overflow is handled on the next line */ \ +th2 += (c0 < tl2) ? 1 : 0; /* second overflow is handled on the next line */ \ +c2 += (c0 < tl2) & (th2 == 0); /* never overflows by contract (verified the next line) */ \ +VERIFY_CHECK((c0 >= tl2) || (th2 != 0) || (c2 != 0)); \ +c1 += th2; /* overflow is handled on the next line */ \ +c2 += (c1 < th2) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ +VERIFY_CHECK((c1 >= th2) || (c2 != 0)); \ +} + +/** Add a to the number defined by (c0,c1,c2). c2 must never overflow. */ +#define sumadd(a) { \ +unsigned int over; \ +c0 += (a); /* overflow is handled on the next line */ \ +over = (c0 < (a)) ? 1 : 0; \ +c1 += over; /* overflow is handled on the next line */ \ +c2 += (c1 < over) ? 1 : 0; /* never overflows by contract */ \ +} + +/** Add a to the number defined by (c0,c1). c1 must never overflow, c2 must be zero. */ +#define sumadd_fast(a) { \ +c0 += (a); /* overflow is handled on the next line */ \ +c1 += (c0 < (a)) ? 1 : 0; /* never overflows by contract (verified the next line) */ \ +VERIFY_CHECK((c1 != 0) | (c0 >= (a))); \ +VERIFY_CHECK(c2 == 0); \ +} + +/** Extract the lowest 32 bits of (c0,c1,c2) into n, and left shift the number 32 bits. */ +#define extract(n) { \ +(n) = c0; \ +c0 = c1; \ +c1 = c2; \ +c2 = 0; \ +} + +/** Extract the lowest 32 bits of (c0,c1,c2) into n, and left shift the number 32 bits. c2 is required to be zero. */ +#define extract_fast(n) { \ +(n) = c0; \ +c0 = c1; \ +c1 = 0; \ +VERIFY_CHECK(c2 == 0); \ +} + +static void secp256k1_scalar_reduce_512(secp256k1_scalar *r, const uint32_t *l) { + uint64_t c; + uint32_t n0 = l[8], n1 = l[9], n2 = l[10], n3 = l[11], n4 = l[12], n5 = l[13], n6 = l[14], n7 = l[15]; + uint32_t m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12; + uint32_t p0, p1, p2, p3, p4, p5, p6, p7, p8; + + /* 96 bit accumulator. */ + uint32_t c0, c1, c2; + + /* Reduce 512 bits into 385. */ + /* m[0..12] = l[0..7] + n[0..7] * SECP256K1_N_C. */ + c0 = l[0]; c1 = 0; c2 = 0; + muladd_fast(n0, SECP256K1_N_C_0); + extract_fast(m0); + sumadd_fast(l[1]); + muladd(n1, SECP256K1_N_C_0); + muladd(n0, SECP256K1_N_C_1); + extract(m1); + sumadd(l[2]); + muladd(n2, SECP256K1_N_C_0); + muladd(n1, SECP256K1_N_C_1); + muladd(n0, SECP256K1_N_C_2); + extract(m2); + sumadd(l[3]); + muladd(n3, SECP256K1_N_C_0); + muladd(n2, SECP256K1_N_C_1); + muladd(n1, SECP256K1_N_C_2); + muladd(n0, SECP256K1_N_C_3); + extract(m3); + sumadd(l[4]); + muladd(n4, SECP256K1_N_C_0); + muladd(n3, SECP256K1_N_C_1); + muladd(n2, SECP256K1_N_C_2); + muladd(n1, SECP256K1_N_C_3); + sumadd(n0); + extract(m4); + sumadd(l[5]); + muladd(n5, SECP256K1_N_C_0); + muladd(n4, SECP256K1_N_C_1); + muladd(n3, SECP256K1_N_C_2); + muladd(n2, SECP256K1_N_C_3); + sumadd(n1); + extract(m5); + sumadd(l[6]); + muladd(n6, SECP256K1_N_C_0); + muladd(n5, SECP256K1_N_C_1); + muladd(n4, SECP256K1_N_C_2); + muladd(n3, SECP256K1_N_C_3); + sumadd(n2); + extract(m6); + sumadd(l[7]); + muladd(n7, SECP256K1_N_C_0); + muladd(n6, SECP256K1_N_C_1); + muladd(n5, SECP256K1_N_C_2); + muladd(n4, SECP256K1_N_C_3); + sumadd(n3); + extract(m7); + muladd(n7, SECP256K1_N_C_1); + muladd(n6, SECP256K1_N_C_2); + muladd(n5, SECP256K1_N_C_3); + sumadd(n4); + extract(m8); + muladd(n7, SECP256K1_N_C_2); + muladd(n6, SECP256K1_N_C_3); + sumadd(n5); + extract(m9); + muladd(n7, SECP256K1_N_C_3); + sumadd(n6); + extract(m10); + sumadd_fast(n7); + extract_fast(m11); + VERIFY_CHECK(c0 <= 1); + m12 = c0; + + /* Reduce 385 bits into 258. */ + /* p[0..8] = m[0..7] + m[8..12] * SECP256K1_N_C. */ + c0 = m0; c1 = 0; c2 = 0; + muladd_fast(m8, SECP256K1_N_C_0); + extract_fast(p0); + sumadd_fast(m1); + muladd(m9, SECP256K1_N_C_0); + muladd(m8, SECP256K1_N_C_1); + extract(p1); + sumadd(m2); + muladd(m10, SECP256K1_N_C_0); + muladd(m9, SECP256K1_N_C_1); + muladd(m8, SECP256K1_N_C_2); + extract(p2); + sumadd(m3); + muladd(m11, SECP256K1_N_C_0); + muladd(m10, SECP256K1_N_C_1); + muladd(m9, SECP256K1_N_C_2); + muladd(m8, SECP256K1_N_C_3); + extract(p3); + sumadd(m4); + muladd(m12, SECP256K1_N_C_0); + muladd(m11, SECP256K1_N_C_1); + muladd(m10, SECP256K1_N_C_2); + muladd(m9, SECP256K1_N_C_3); + sumadd(m8); + extract(p4); + sumadd(m5); + muladd(m12, SECP256K1_N_C_1); + muladd(m11, SECP256K1_N_C_2); + muladd(m10, SECP256K1_N_C_3); + sumadd(m9); + extract(p5); + sumadd(m6); + muladd(m12, SECP256K1_N_C_2); + muladd(m11, SECP256K1_N_C_3); + sumadd(m10); + extract(p6); + sumadd_fast(m7); + muladd_fast(m12, SECP256K1_N_C_3); + sumadd_fast(m11); + extract_fast(p7); + p8 = c0 + m12; + VERIFY_CHECK(p8 <= 2); + + /* Reduce 258 bits into 256. */ + /* r[0..7] = p[0..7] + p[8] * SECP256K1_N_C. */ + c = p0 + (uint64_t)SECP256K1_N_C_0 * p8; + r->d[0] = c & 0xFFFFFFFFUL; c >>= 32; + c += p1 + (uint64_t)SECP256K1_N_C_1 * p8; + r->d[1] = c & 0xFFFFFFFFUL; c >>= 32; + c += p2 + (uint64_t)SECP256K1_N_C_2 * p8; + r->d[2] = c & 0xFFFFFFFFUL; c >>= 32; + c += p3 + (uint64_t)SECP256K1_N_C_3 * p8; + r->d[3] = c & 0xFFFFFFFFUL; c >>= 32; + c += p4 + (uint64_t)p8; + r->d[4] = c & 0xFFFFFFFFUL; c >>= 32; + c += p5; + r->d[5] = c & 0xFFFFFFFFUL; c >>= 32; + c += p6; + r->d[6] = c & 0xFFFFFFFFUL; c >>= 32; + c += p7; + r->d[7] = c & 0xFFFFFFFFUL; c >>= 32; + + /* Final reduction of r. */ + secp256k1_scalar_reduce(r, c + secp256k1_scalar_check_overflow(r)); +} + +static void secp256k1_scalar_mul_512(uint32_t *l, const secp256k1_scalar *a, const secp256k1_scalar *b) { + /* 96 bit accumulator. */ + uint32_t c0 = 0, c1 = 0, c2 = 0; + + /* l[0..15] = a[0..7] * b[0..7]. */ + muladd_fast(a->d[0], b->d[0]); + extract_fast(l[0]); + muladd(a->d[0], b->d[1]); + muladd(a->d[1], b->d[0]); + extract(l[1]); + muladd(a->d[0], b->d[2]); + muladd(a->d[1], b->d[1]); + muladd(a->d[2], b->d[0]); + extract(l[2]); + muladd(a->d[0], b->d[3]); + muladd(a->d[1], b->d[2]); + muladd(a->d[2], b->d[1]); + muladd(a->d[3], b->d[0]); + extract(l[3]); + muladd(a->d[0], b->d[4]); + muladd(a->d[1], b->d[3]); + muladd(a->d[2], b->d[2]); + muladd(a->d[3], b->d[1]); + muladd(a->d[4], b->d[0]); + extract(l[4]); + muladd(a->d[0], b->d[5]); + muladd(a->d[1], b->d[4]); + muladd(a->d[2], b->d[3]); + muladd(a->d[3], b->d[2]); + muladd(a->d[4], b->d[1]); + muladd(a->d[5], b->d[0]); + extract(l[5]); + muladd(a->d[0], b->d[6]); + muladd(a->d[1], b->d[5]); + muladd(a->d[2], b->d[4]); + muladd(a->d[3], b->d[3]); + muladd(a->d[4], b->d[2]); + muladd(a->d[5], b->d[1]); + muladd(a->d[6], b->d[0]); + extract(l[6]); + muladd(a->d[0], b->d[7]); + muladd(a->d[1], b->d[6]); + muladd(a->d[2], b->d[5]); + muladd(a->d[3], b->d[4]); + muladd(a->d[4], b->d[3]); + muladd(a->d[5], b->d[2]); + muladd(a->d[6], b->d[1]); + muladd(a->d[7], b->d[0]); + extract(l[7]); + muladd(a->d[1], b->d[7]); + muladd(a->d[2], b->d[6]); + muladd(a->d[3], b->d[5]); + muladd(a->d[4], b->d[4]); + muladd(a->d[5], b->d[3]); + muladd(a->d[6], b->d[2]); + muladd(a->d[7], b->d[1]); + extract(l[8]); + muladd(a->d[2], b->d[7]); + muladd(a->d[3], b->d[6]); + muladd(a->d[4], b->d[5]); + muladd(a->d[5], b->d[4]); + muladd(a->d[6], b->d[3]); + muladd(a->d[7], b->d[2]); + extract(l[9]); + muladd(a->d[3], b->d[7]); + muladd(a->d[4], b->d[6]); + muladd(a->d[5], b->d[5]); + muladd(a->d[6], b->d[4]); + muladd(a->d[7], b->d[3]); + extract(l[10]); + muladd(a->d[4], b->d[7]); + muladd(a->d[5], b->d[6]); + muladd(a->d[6], b->d[5]); + muladd(a->d[7], b->d[4]); + extract(l[11]); + muladd(a->d[5], b->d[7]); + muladd(a->d[6], b->d[6]); + muladd(a->d[7], b->d[5]); + extract(l[12]); + muladd(a->d[6], b->d[7]); + muladd(a->d[7], b->d[6]); + extract(l[13]); + muladd_fast(a->d[7], b->d[7]); + extract_fast(l[14]); + VERIFY_CHECK(c1 == 0); + l[15] = c0; +} + +static void secp256k1_scalar_sqr_512(uint32_t *l, const secp256k1_scalar *a) { + /* 96 bit accumulator. */ + uint32_t c0 = 0, c1 = 0, c2 = 0; + + /* l[0..15] = a[0..7]^2. */ + muladd_fast(a->d[0], a->d[0]); + extract_fast(l[0]); + muladd2(a->d[0], a->d[1]); + extract(l[1]); + muladd2(a->d[0], a->d[2]); + muladd(a->d[1], a->d[1]); + extract(l[2]); + muladd2(a->d[0], a->d[3]); + muladd2(a->d[1], a->d[2]); + extract(l[3]); + muladd2(a->d[0], a->d[4]); + muladd2(a->d[1], a->d[3]); + muladd(a->d[2], a->d[2]); + extract(l[4]); + muladd2(a->d[0], a->d[5]); + muladd2(a->d[1], a->d[4]); + muladd2(a->d[2], a->d[3]); + extract(l[5]); + muladd2(a->d[0], a->d[6]); + muladd2(a->d[1], a->d[5]); + muladd2(a->d[2], a->d[4]); + muladd(a->d[3], a->d[3]); + extract(l[6]); + muladd2(a->d[0], a->d[7]); + muladd2(a->d[1], a->d[6]); + muladd2(a->d[2], a->d[5]); + muladd2(a->d[3], a->d[4]); + extract(l[7]); + muladd2(a->d[1], a->d[7]); + muladd2(a->d[2], a->d[6]); + muladd2(a->d[3], a->d[5]); + muladd(a->d[4], a->d[4]); + extract(l[8]); + muladd2(a->d[2], a->d[7]); + muladd2(a->d[3], a->d[6]); + muladd2(a->d[4], a->d[5]); + extract(l[9]); + muladd2(a->d[3], a->d[7]); + muladd2(a->d[4], a->d[6]); + muladd(a->d[5], a->d[5]); + extract(l[10]); + muladd2(a->d[4], a->d[7]); + muladd2(a->d[5], a->d[6]); + extract(l[11]); + muladd2(a->d[5], a->d[7]); + muladd(a->d[6], a->d[6]); + extract(l[12]); + muladd2(a->d[6], a->d[7]); + extract(l[13]); + muladd_fast(a->d[7], a->d[7]); + extract_fast(l[14]); + VERIFY_CHECK(c1 == 0); + l[15] = c0; +} + +#undef sumadd +#undef sumadd_fast +#undef muladd +#undef muladd_fast +#undef muladd2 +#undef extract +#undef extract_fast + +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + uint32_t l[16]; + secp256k1_scalar_mul_512(l, a, b); + secp256k1_scalar_reduce_512(r, l); +} + +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n) { + int ret; + VERIFY_CHECK(n > 0); + VERIFY_CHECK(n < 16); + ret = r->d[0] & ((1 << n) - 1); + r->d[0] = (r->d[0] >> n) + (r->d[1] << (32 - n)); + r->d[1] = (r->d[1] >> n) + (r->d[2] << (32 - n)); + r->d[2] = (r->d[2] >> n) + (r->d[3] << (32 - n)); + r->d[3] = (r->d[3] >> n) + (r->d[4] << (32 - n)); + r->d[4] = (r->d[4] >> n) + (r->d[5] << (32 - n)); + r->d[5] = (r->d[5] >> n) + (r->d[6] << (32 - n)); + r->d[6] = (r->d[6] >> n) + (r->d[7] << (32 - n)); + r->d[7] = (r->d[7] >> n); + return ret; +} + +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a) { + uint32_t l[16]; + secp256k1_scalar_sqr_512(l, a); + secp256k1_scalar_reduce_512(r, l); +} + +#ifdef USE_ENDOMORPHISM +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + r1->d[0] = a->d[0]; + r1->d[1] = a->d[1]; + r1->d[2] = a->d[2]; + r1->d[3] = a->d[3]; + r1->d[4] = 0; + r1->d[5] = 0; + r1->d[6] = 0; + r1->d[7] = 0; + r2->d[0] = a->d[4]; + r2->d[1] = a->d[5]; + r2->d[2] = a->d[6]; + r2->d[3] = a->d[7]; + r2->d[4] = 0; + r2->d[5] = 0; + r2->d[6] = 0; + r2->d[7] = 0; +} +#endif + +SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b) { + return ((a->d[0] ^ b->d[0]) | (a->d[1] ^ b->d[1]) | (a->d[2] ^ b->d[2]) | (a->d[3] ^ b->d[3]) | (a->d[4] ^ b->d[4]) | (a->d[5] ^ b->d[5]) | (a->d[6] ^ b->d[6]) | (a->d[7] ^ b->d[7])) == 0; +} + +SECP256K1_INLINE static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift) { + uint32_t l[16]; + unsigned int shiftlimbs; + unsigned int shiftlow; + unsigned int shifthigh; + VERIFY_CHECK(shift >= 256); + secp256k1_scalar_mul_512(l, a, b); + shiftlimbs = shift >> 5; + shiftlow = shift & 0x1F; + shifthigh = 32 - shiftlow; + r->d[0] = shift < 512 ? (l[0 + shiftlimbs] >> shiftlow | (shift < 480 && shiftlow ? (l[1 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[1] = shift < 480 ? (l[1 + shiftlimbs] >> shiftlow | (shift < 448 && shiftlow ? (l[2 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[2] = shift < 448 ? (l[2 + shiftlimbs] >> shiftlow | (shift < 416 && shiftlow ? (l[3 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[3] = shift < 416 ? (l[3 + shiftlimbs] >> shiftlow | (shift < 384 && shiftlow ? (l[4 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[4] = shift < 384 ? (l[4 + shiftlimbs] >> shiftlow | (shift < 352 && shiftlow ? (l[5 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[5] = shift < 352 ? (l[5 + shiftlimbs] >> shiftlow | (shift < 320 && shiftlow ? (l[6 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[6] = shift < 320 ? (l[6 + shiftlimbs] >> shiftlow | (shift < 288 && shiftlow ? (l[7 + shiftlimbs] << shifthigh) : 0)) : 0; + r->d[7] = shift < 288 ? (l[7 + shiftlimbs] >> shiftlow) : 0; + secp256k1_scalar_cadd_bit(r, 0, (l[(shift - 1) >> 5] >> ((shift - 1) & 0x1f)) & 1); +} + +#define ROTL32(x,n) ((x) << (n) | (x) >> (32-(n))) +#define QUARTERROUND(a,b,c,d) \ +a += b; d = ROTL32(d ^ a, 16); \ +c += d; b = ROTL32(b ^ c, 12); \ +a += b; d = ROTL32(d ^ a, 8); \ +c += d; b = ROTL32(b ^ c, 7); + +#ifdef WORDS_BIGENDIAN +#define LE32(p) ((((p) & 0xFF) << 24) | (((p) & 0xFF00) << 8) | (((p) & 0xFF0000) >> 8) | (((p) & 0xFF000000) >> 24)) +#define BE32(p) (p) +#else +#define BE32(p) ((((p) & 0xFF) << 24) | (((p) & 0xFF00) << 8) | (((p) & 0xFF0000) >> 8) | (((p) & 0xFF000000) >> 24)) +#define LE32(p) (p) +#endif + +static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx) { + size_t n; + size_t over_count = 0; + uint32_t seed32[8]; + uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; + int over1, over2; + + memcpy((void *) seed32, (const void *) seed, 32); + do { + x0 = 0x61707865; + x1 = 0x3320646e; + x2 = 0x79622d32; + x3 = 0x6b206574; + x4 = LE32(seed32[0]); + x5 = LE32(seed32[1]); + x6 = LE32(seed32[2]); + x7 = LE32(seed32[3]); + x8 = LE32(seed32[4]); + x9 = LE32(seed32[5]); + x10 = LE32(seed32[6]); + x11 = LE32(seed32[7]); + x12 = idx; + x13 = idx >> 32; + x14 = 0; + x15 = over_count; + + n = 10; + while (n--) { + QUARTERROUND(x0, x4, x8,x12) + QUARTERROUND(x1, x5, x9,x13) + QUARTERROUND(x2, x6,x10,x14) + QUARTERROUND(x3, x7,x11,x15) + QUARTERROUND(x0, x5,x10,x15) + QUARTERROUND(x1, x6,x11,x12) + QUARTERROUND(x2, x7, x8,x13) + QUARTERROUND(x3, x4, x9,x14) + } + + x0 += 0x61707865; + x1 += 0x3320646e; + x2 += 0x79622d32; + x3 += 0x6b206574; + x4 += LE32(seed32[0]); + x5 += LE32(seed32[1]); + x6 += LE32(seed32[2]); + x7 += LE32(seed32[3]); + x8 += LE32(seed32[4]); + x9 += LE32(seed32[5]); + x10 += LE32(seed32[6]); + x11 += LE32(seed32[7]); + x12 += idx; + x13 += idx >> 32; + x14 += 0; + x15 += over_count; + + r1->d[7] = LE32(x0); + r1->d[6] = LE32(x1); + r1->d[5] = LE32(x2); + r1->d[4] = LE32(x3); + r1->d[3] = LE32(x4); + r1->d[2] = LE32(x5); + r1->d[1] = LE32(x6); + r1->d[0] = LE32(x7); + r2->d[7] = LE32(x8); + r2->d[6] = LE32(x9); + r2->d[5] = LE32(x10); + r2->d[4] = LE32(x11); + r2->d[3] = LE32(x12); + r2->d[2] = LE32(x13); + r2->d[1] = LE32(x14); + r2->d[0] = LE32(x15); + + over1 = secp256k1_scalar_check_overflow(r1); + over2 = secp256k1_scalar_check_overflow(r2); + over_count++; + } while (over1 | over2); +} + +#undef ROTL32 +#undef QUARTERROUND +#undef BE32 +#undef LE32 + +#endif /* SECP256K1_SCALAR_REPR_IMPL_H */ +#endif + diff --git a/src/secp256k1/src/scalar_impl.h b/src/secp256k1/src/scalar_impl.h index fa790570f..494168e53 100644 --- a/src/secp256k1/src/scalar_impl.h +++ b/src/secp256k1/src/scalar_impl.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * @@ -331,3 +333,341 @@ static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar #endif #endif /* SECP256K1_SCALAR_IMPL_H */ + + +#else +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_IMPL_H +#define SECP256K1_SCALAR_IMPL_H + +#include "group.h" +#include "scalar.h" + +#if defined HAVE_CONFIG_H +#include "libsecp256k1-config.h" +#endif + +#if defined(EXHAUSTIVE_TEST_ORDER) +#include "scalar_low_impl.h" +#elif defined(USE_SCALAR_4X64) +#include "scalar_4x64_impl.h" +#elif defined(USE_SCALAR_8X32) +#include "scalar_8x32_impl.h" +#else +#error "Please select scalar implementation" +#endif + +#ifndef USE_NUM_NONE +static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a) { + unsigned char c[32]; + secp256k1_scalar_get_b32(c, a); + secp256k1_num_set_bin(r, c, 32); +} + +/** secp256k1 curve order, see secp256k1_ecdsa_const_order_as_fe in ecdsa_impl.h */ +static void secp256k1_scalar_order_get_num(secp256k1_num *r) { +#if defined(EXHAUSTIVE_TEST_ORDER) + static const unsigned char order[32] = { + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,EXHAUSTIVE_TEST_ORDER + }; +#else + static const unsigned char order[32] = { + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE, + 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B, + 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x41 + }; +#endif + secp256k1_num_set_bin(r, order, 32); +} +#endif + +static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *x) { +#if defined(EXHAUSTIVE_TEST_ORDER) + int i; + *r = 0; + for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) + if ((i * *x) % EXHAUSTIVE_TEST_ORDER == 1) + *r = i; + /* If this VERIFY_CHECK triggers we were given a noninvertible scalar (and thus + * have a composite group order; fix it in exhaustive_tests.c). */ + VERIFY_CHECK(*r != 0); +} +#else +secp256k1_scalar *t; +int i; +/* First compute xN as x ^ (2^N - 1) for some values of N, + * and uM as x ^ M for some values of M. */ +secp256k1_scalar x2, x3, x6, x8, x14, x28, x56, x112, x126; +secp256k1_scalar u2, u5, u9, u11, u13; + +secp256k1_scalar_sqr(&u2, x); +secp256k1_scalar_mul(&x2, &u2, x); +secp256k1_scalar_mul(&u5, &u2, &x2); +secp256k1_scalar_mul(&x3, &u5, &u2); +secp256k1_scalar_mul(&u9, &x3, &u2); +secp256k1_scalar_mul(&u11, &u9, &u2); +secp256k1_scalar_mul(&u13, &u11, &u2); + +secp256k1_scalar_sqr(&x6, &u13); +secp256k1_scalar_sqr(&x6, &x6); +secp256k1_scalar_mul(&x6, &x6, &u11); + +secp256k1_scalar_sqr(&x8, &x6); +secp256k1_scalar_sqr(&x8, &x8); +secp256k1_scalar_mul(&x8, &x8, &x2); + +secp256k1_scalar_sqr(&x14, &x8); +for (i = 0; i < 5; i++) { + secp256k1_scalar_sqr(&x14, &x14); +} +secp256k1_scalar_mul(&x14, &x14, &x6); + +secp256k1_scalar_sqr(&x28, &x14); +for (i = 0; i < 13; i++) { + secp256k1_scalar_sqr(&x28, &x28); +} +secp256k1_scalar_mul(&x28, &x28, &x14); + +secp256k1_scalar_sqr(&x56, &x28); +for (i = 0; i < 27; i++) { + secp256k1_scalar_sqr(&x56, &x56); +} +secp256k1_scalar_mul(&x56, &x56, &x28); + +secp256k1_scalar_sqr(&x112, &x56); +for (i = 0; i < 55; i++) { + secp256k1_scalar_sqr(&x112, &x112); +} +secp256k1_scalar_mul(&x112, &x112, &x56); + +secp256k1_scalar_sqr(&x126, &x112); +for (i = 0; i < 13; i++) { + secp256k1_scalar_sqr(&x126, &x126); +} +secp256k1_scalar_mul(&x126, &x126, &x14); + +/* Then accumulate the final result (t starts at x126). */ +t = &x126; +for (i = 0; i < 3; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u11); /* 1011 */ +for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u11); /* 1011 */ +for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 5; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +for (i = 0; i < 3; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u9); /* 1001 */ +for (i = 0; i < 6; i++) { /* 000 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +for (i = 0; i < 10; i++) { /* 0000000 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 9; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x8); /* 11111111 */ +for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u9); /* 1001 */ +for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u11); /* 1011 */ +for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 5; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x2); /* 11 */ +for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 10; i++) { /* 000000 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u9); /* 1001 */ +for (i = 0; i < 6; i++) { /* 00000 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, x); /* 1 */ +for (i = 0; i < 8; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(r, t, &x6); /* 111111 */ +} + +SECP256K1_INLINE static int secp256k1_scalar_is_even(const secp256k1_scalar *a) { + return !(a->d[0] & 1); +} +#endif + +static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *x) { +#if defined(USE_SCALAR_INV_BUILTIN) + secp256k1_scalar_inverse(r, x); +#elif defined(USE_SCALAR_INV_NUM) + unsigned char b[32]; + secp256k1_num n, m; + secp256k1_scalar t = *x; + secp256k1_scalar_get_b32(b, &t); + secp256k1_num_set_bin(&n, b, 32); + secp256k1_scalar_order_get_num(&m); + secp256k1_num_mod_inverse(&n, &n, &m); + secp256k1_num_get_bin(b, 32, &n); + secp256k1_scalar_set_b32(r, b, NULL); + /* Verify that the inverse was computed correctly, without GMP code. */ + secp256k1_scalar_mul(&t, &t, r); + CHECK(secp256k1_scalar_is_one(&t)); +#else +#error "Please select scalar inverse implementation" +#endif +} + +#ifdef USE_ENDOMORPHISM +#if defined(EXHAUSTIVE_TEST_ORDER) +/** + * Find k1 and k2 given k, such that k1 + k2 * lambda == k mod n; unlike in the + * full case we don't bother making k1 and k2 be small, we just want them to be + * nontrivial to get full test coverage for the exhaustive tests. We therefore + * (arbitrarily) set k2 = k + 5 and k1 = k - k2 * lambda. + */ +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + *r2 = (*a + 5) % EXHAUSTIVE_TEST_ORDER; + *r1 = (*a + (EXHAUSTIVE_TEST_ORDER - *r2) * EXHAUSTIVE_TEST_LAMBDA) % EXHAUSTIVE_TEST_ORDER; +} +#else +/** + * The Secp256k1 curve has an endomorphism, where lambda * (x, y) = (beta * x, y), where + * lambda is {0x53,0x63,0xad,0x4c,0xc0,0x5c,0x30,0xe0,0xa5,0x26,0x1c,0x02,0x88,0x12,0x64,0x5a, + * 0x12,0x2e,0x22,0xea,0x20,0x81,0x66,0x78,0xdf,0x02,0x96,0x7c,0x1b,0x23,0xbd,0x72} + * + * "Guide to Elliptic Curve Cryptography" (Hankerson, Menezes, Vanstone) gives an algorithm + * (algorithm 3.74) to find k1 and k2 given k, such that k1 + k2 * lambda == k mod n, and k1 + * and k2 have a small size. + * It relies on constants a1, b1, a2, b2. These constants for the value of lambda above are: + * + * - a1 = {0x30,0x86,0xd2,0x21,0xa7,0xd4,0x6b,0xcd,0xe8,0x6c,0x90,0xe4,0x92,0x84,0xeb,0x15} + * - b1 = -{0xe4,0x43,0x7e,0xd6,0x01,0x0e,0x88,0x28,0x6f,0x54,0x7f,0xa9,0x0a,0xbf,0xe4,0xc3} + * - a2 = {0x01,0x14,0xca,0x50,0xf7,0xa8,0xe2,0xf3,0xf6,0x57,0xc1,0x10,0x8d,0x9d,0x44,0xcf,0xd8} + * - b2 = {0x30,0x86,0xd2,0x21,0xa7,0xd4,0x6b,0xcd,0xe8,0x6c,0x90,0xe4,0x92,0x84,0xeb,0x15} + * + * The algorithm then computes c1 = round(b1 * k / n) and c2 = round(b2 * k / n), and gives + * k1 = k - (c1*a1 + c2*a2) and k2 = -(c1*b1 + c2*b2). Instead, we use modular arithmetic, and + * compute k1 as k - k2 * lambda, avoiding the need for constants a1 and a2. + * + * g1, g2 are precomputed constants used to replace division with a rounded multiplication + * when decomposing the scalar for an endomorphism-based point multiplication. + * + * The possibility of using precomputed estimates is mentioned in "Guide to Elliptic Curve + * Cryptography" (Hankerson, Menezes, Vanstone) in section 3.5. + * + * The derivation is described in the paper "Efficient Software Implementation of Public-Key + * Cryptography on Sensor Networks Using the MSP430X Microcontroller" (Gouvea, Oliveira, Lopez), + * Section 4.3 (here we use a somewhat higher-precision estimate): + * d = a1*b2 - b1*a2 + * g1 = round((2^272)*b2/d) + * g2 = round((2^272)*b1/d) + * + * (Note that 'd' is also equal to the curve order here because [a1,b1] and [a2,b2] are found + * as outputs of the Extended Euclidean Algorithm on inputs 'order' and 'lambda'). + * + * The function below splits a in r1 and r2, such that r1 + lambda * r2 == a (mod order). + */ + +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + secp256k1_scalar c1, c2; + static const secp256k1_scalar minus_lambda = SECP256K1_SCALAR_CONST( + 0xAC9C52B3UL, 0x3FA3CF1FUL, 0x5AD9E3FDUL, 0x77ED9BA4UL, + 0xA880B9FCUL, 0x8EC739C2UL, 0xE0CFC810UL, 0xB51283CFUL + ); + static const secp256k1_scalar minus_b1 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00000000UL, + 0xE4437ED6UL, 0x010E8828UL, 0x6F547FA9UL, 0x0ABFE4C3UL + ); + static const secp256k1_scalar minus_b2 = SECP256K1_SCALAR_CONST( + 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, + 0x8A280AC5UL, 0x0774346DUL, 0xD765CDA8UL, 0x3DB1562CUL + ); + static const secp256k1_scalar g1 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00003086UL, + 0xD221A7D4UL, 0x6BCDE86CUL, 0x90E49284UL, 0xEB153DABUL + ); + static const secp256k1_scalar g2 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x0000E443UL, + 0x7ED6010EUL, 0x88286F54UL, 0x7FA90ABFUL, 0xE4C42212UL + ); + VERIFY_CHECK(r1 != a); + VERIFY_CHECK(r2 != a); + /* these _var calls are constant time since the shift amount is constant */ + secp256k1_scalar_mul_shift_var(&c1, a, &g1, 272); + secp256k1_scalar_mul_shift_var(&c2, a, &g2, 272); + secp256k1_scalar_mul(&c1, &c1, &minus_b1); + secp256k1_scalar_mul(&c2, &c2, &minus_b2); + secp256k1_scalar_add(r2, &c1, &c2); + secp256k1_scalar_mul(r1, r2, &minus_lambda); + secp256k1_scalar_add(r1, r1, a); +} +#endif +#endif + +#endif /* SECP256K1_SCALAR_IMPL_H */ +#endif + diff --git a/src/secp256k1/src/scalar_low.h b/src/secp256k1/src/scalar_low.h index 5836febc5..2039aafc7 100644 --- a/src/secp256k1/src/scalar_low.h +++ b/src/secp256k1/src/scalar_low.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2015 Andrew Poelstra * * Distributed under the MIT software license, see the accompanying * @@ -13,3 +15,21 @@ typedef uint32_t secp256k1_scalar; #endif /* SECP256K1_SCALAR_REPR_H */ + +#else +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_H +#define SECP256K1_SCALAR_REPR_H + +#include + +/** A scalar modulo the group order of the secp256k1 curve. */ +typedef uint32_t secp256k1_scalar; + +#endif /* SECP256K1_SCALAR_REPR_H */ +#endif diff --git a/src/secp256k1/src/scalar_low_impl.h b/src/secp256k1/src/scalar_low_impl.h index c80e70c5a..99689a4fd 100644 --- a/src/secp256k1/src/scalar_low_impl.h +++ b/src/secp256k1/src/scalar_low_impl.h @@ -1,3 +1,5 @@ +#ifdef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2015 Andrew Poelstra * * Distributed under the MIT software license, see the accompanying * @@ -112,3 +114,127 @@ SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const } #endif /* SECP256K1_SCALAR_REPR_IMPL_H */ + +#else +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_REPR_IMPL_H +#define SECP256K1_SCALAR_REPR_IMPL_H + +#include "scalar.h" + +#include + +SECP256K1_INLINE static int secp256k1_scalar_is_even(const secp256k1_scalar *a) { + return !(*a & 1); +} + +SECP256K1_INLINE static void secp256k1_scalar_clear(secp256k1_scalar *r) { *r = 0; } +SECP256K1_INLINE static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v) { *r = v; } +SECP256K1_INLINE static void secp256k1_scalar_set_u64(secp256k1_scalar *r, uint64_t v) { *r = v % EXHAUSTIVE_TEST_ORDER; } + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + if (offset < 32) + return ((*a >> offset) & ((((uint32_t)1) << count) - 1)); + else + return 0; +} + +SECP256K1_INLINE static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count) { + return secp256k1_scalar_get_bits(a, offset, count); +} + +SECP256K1_INLINE static int secp256k1_scalar_check_overflow(const secp256k1_scalar *a) { return *a >= EXHAUSTIVE_TEST_ORDER; } + +static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + *r = (*a + *b) % EXHAUSTIVE_TEST_ORDER; + return *r < *b; +} + +static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag) { + if (flag && bit < 32) + *r += (1 << bit); +#ifdef VERIFY + VERIFY_CHECK(secp256k1_scalar_check_overflow(r) == 0); +#endif +} + +static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *b32, int *overflow) { + const int base = 0x100 % EXHAUSTIVE_TEST_ORDER; + int i; + *r = 0; + for (i = 0; i < 32; i++) { + *r = ((*r * base) + b32[i]) % EXHAUSTIVE_TEST_ORDER; + } + /* just deny overflow, it basically always happens */ + if (overflow) *overflow = 0; +} + +static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a) { + memset(bin, 0, 32); + bin[28] = *a >> 24; bin[29] = *a >> 16; bin[30] = *a >> 8; bin[31] = *a; +} + +SECP256K1_INLINE static int secp256k1_scalar_is_zero(const secp256k1_scalar *a) { + return *a == 0; +} + +static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a) { + if (*a == 0) { + *r = 0; + } else { + *r = EXHAUSTIVE_TEST_ORDER - *a; + } +} + +SECP256K1_INLINE static int secp256k1_scalar_is_one(const secp256k1_scalar *a) { + return *a == 1; +} + +static int secp256k1_scalar_is_high(const secp256k1_scalar *a) { + return *a > EXHAUSTIVE_TEST_ORDER / 2; +} + +static int secp256k1_scalar_cond_negate(secp256k1_scalar *r, int flag) { + if (flag) secp256k1_scalar_negate(r, r); + return flag ? -1 : 1; +} + +static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b) { + *r = (*a * *b) % EXHAUSTIVE_TEST_ORDER; +} + +static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n) { + int ret; + VERIFY_CHECK(n > 0); + VERIFY_CHECK(n < 16); + ret = *r & ((1 << n) - 1); + *r >>= n; + return ret; +} + +static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a) { + *r = (*a * *a) % EXHAUSTIVE_TEST_ORDER; +} + +static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + *r1 = *a; + *r2 = 0; +} + +SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b) { + return *a == *b; +} + +SECP256K1_INLINE static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t n) { + *r1 = (seed[0] + n) % EXHAUSTIVE_TEST_ORDER; + *r2 = (seed[1] + n) % EXHAUSTIVE_TEST_ORDER; +} + +#endif /* SECP256K1_SCALAR_REPR_IMPL_H */ +#endif + From cf2a4fb66a2f714b78f9cfc69f28a08cdcd1f603 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 06:36:26 -1100 Subject: [PATCH 0846/1145] AM_CONDITIONAL --- src/secp256k1/configure.ac | 1 + 1 file changed, 1 insertion(+) diff --git a/src/secp256k1/configure.ac b/src/secp256k1/configure.ac index e5fcbcb4e..4c46f321f 100644 --- a/src/secp256k1/configure.ac +++ b/src/secp256k1/configure.ac @@ -479,6 +479,7 @@ AM_CONDITIONAL([USE_TESTS], [test x"$use_tests" != x"no"]) AM_CONDITIONAL([USE_EXHAUSTIVE_TESTS], [test x"$use_exhaustive_tests" != x"no"]) AM_CONDITIONAL([USE_BENCHMARK], [test x"$use_benchmark" = x"yes"]) AM_CONDITIONAL([USE_ECMULT_STATIC_PRECOMPUTATION], [test x"$set_precomp" = x"yes"]) +AM_CONDITIONAL([ENABLE_MODULE_MUSIG], [test x"$enable_module_musig" = x"yes"]) AM_CONDITIONAL([ENABLE_MODULE_ECDH], [test x"$enable_module_ecdh" = x"yes"]) AM_CONDITIONAL([ENABLE_MODULE_RECOVERY], [test x"$enable_module_recovery" = x"yes"]) AM_CONDITIONAL([USE_JNI], [test x"$use_jni" == x"yes"]) From a8b89a2d87884db14f7398a29c75164e792fcca8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 06:43:01 -1100 Subject: [PATCH 0847/1145] #include "scratch_impl.h" --- src/secp256k1/Makefile.am | 2 + src/secp256k1/src/scalar.h | 117 ------------------------------- src/secp256k1/src/scalar_4x64.h | 24 ------- src/secp256k1/src/scratch.h | 40 +++++++++++ src/secp256k1/src/scratch_impl.h | 87 +++++++++++++++++++++++ src/secp256k1/src/secp256k1.c | 1 + 6 files changed, 130 insertions(+), 141 deletions(-) create mode 100644 src/secp256k1/src/scratch.h create mode 100644 src/secp256k1/src/scratch_impl.h diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index ff5a2c50c..36d56a9ac 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -42,6 +42,8 @@ noinst_HEADERS += src/field_5x52_asm_impl.h noinst_HEADERS += src/java/org_bitcoin_NativeSecp256k1.h noinst_HEADERS += src/java/org_bitcoin_Secp256k1Context.h noinst_HEADERS += src/util.h +noinst_HEADERS += src/scratch.h +noinst_HEADERS += src/scratch_impl.h noinst_HEADERS += src/testrand.h noinst_HEADERS += src/testrand_impl.h noinst_HEADERS += src/hash.h diff --git a/src/secp256k1/src/scalar.h b/src/secp256k1/src/scalar.h index 3d972dc84..aa1cc3286 100644 --- a/src/secp256k1/src/scalar.h +++ b/src/secp256k1/src/scalar.h @@ -222,120 +222,3 @@ static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2 #endif /* SECP256K1_SCALAR_H */ #endif - -#else - -/********************************************************************** - * Copyright (c) 2014 Pieter Wuille * - * Distributed under the MIT software license, see the accompanying * - * file COPYING or http://www.opensource.org/licenses/mit-license.php.* - **********************************************************************/ - -#ifndef SECP256K1_SCALAR_H -#define SECP256K1_SCALAR_H - -#include "num.h" - -#if defined HAVE_CONFIG_H -#include "libsecp256k1-config.h" -#endif - -#if defined(EXHAUSTIVE_TEST_ORDER) -#include "scalar_low.h" -#elif defined(USE_SCALAR_4X64) -#include "scalar_4x64.h" -#elif defined(USE_SCALAR_8X32) -#include "scalar_8x32.h" -#else -#error "Please select scalar implementation" -#endif - -/** Clear a scalar to prevent the leak of sensitive data. */ -static void secp256k1_scalar_clear(secp256k1_scalar *r); - -/** Access bits from a scalar. All requested bits must belong to the same 32-bit limb. */ -static unsigned int secp256k1_scalar_get_bits(const secp256k1_scalar *a, unsigned int offset, unsigned int count); - -/** Access bits from a scalar. Not constant time. */ -static unsigned int secp256k1_scalar_get_bits_var(const secp256k1_scalar *a, unsigned int offset, unsigned int count); - -/** Set a scalar from a big endian byte array. */ -static void secp256k1_scalar_set_b32(secp256k1_scalar *r, const unsigned char *bin, int *overflow); - -/** Set a scalar to an unsigned integer. */ -static void secp256k1_scalar_set_int(secp256k1_scalar *r, unsigned int v); - -/** Set a scalar to an unsigned 64-bit integer */ -static void secp256k1_scalar_set_u64(secp256k1_scalar *r, uint64_t v); - -/** Convert a scalar to a byte array. */ -static void secp256k1_scalar_get_b32(unsigned char *bin, const secp256k1_scalar* a); - -/** Add two scalars together (modulo the group order). Returns whether it overflowed. */ -static int secp256k1_scalar_add(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); - -/** Conditionally add a power of two to a scalar. The result is not allowed to overflow. */ -static void secp256k1_scalar_cadd_bit(secp256k1_scalar *r, unsigned int bit, int flag); - -/** Multiply two scalars (modulo the group order). */ -static void secp256k1_scalar_mul(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b); - -/** Shift a scalar right by some amount strictly between 0 and 16, returning - * the low bits that were shifted off */ -static int secp256k1_scalar_shr_int(secp256k1_scalar *r, int n); - -/** Compute the square of a scalar (modulo the group order). */ -static void secp256k1_scalar_sqr(secp256k1_scalar *r, const secp256k1_scalar *a); - -/** Compute the inverse of a scalar (modulo the group order). */ -static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *a); - -/** Compute the inverse of a scalar (modulo the group order), without constant-time guarantee. */ -static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *a); - -/** Compute the complement of a scalar (modulo the group order). */ -static void secp256k1_scalar_negate(secp256k1_scalar *r, const secp256k1_scalar *a); - -/** Check whether a scalar equals zero. */ -static int secp256k1_scalar_is_zero(const secp256k1_scalar *a); - -/** Check whether a scalar equals one. */ -static int secp256k1_scalar_is_one(const secp256k1_scalar *a); - -/** Check whether a scalar, considered as an nonnegative integer, is even. */ -static int secp256k1_scalar_is_even(const secp256k1_scalar *a); - -/** Check whether a scalar is higher than the group order divided by 2. */ -static int secp256k1_scalar_is_high(const secp256k1_scalar *a); - -/** Conditionally negate a number, in constant time. - * Returns -1 if the number was negated, 1 otherwise */ -static int secp256k1_scalar_cond_negate(secp256k1_scalar *a, int flag); - -#ifndef USE_NUM_NONE -/** Convert a scalar to a number. */ -static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a); - -/** Get the order of the group as a number. */ -static void secp256k1_scalar_order_get_num(secp256k1_num *r); -#endif - -/** Compare two scalars. */ -static int secp256k1_scalar_eq(const secp256k1_scalar *a, const secp256k1_scalar *b); - -#ifdef USE_ENDOMORPHISM -/** Find r1 and r2 such that r1+r2*2^128 = a. */ -static void secp256k1_scalar_split_128(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a); -/** Find r1 and r2 such that r1+r2*lambda = a, and r1 and r2 are maximum 128 bits long (see secp256k1_gej_mul_lambda). */ -static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a); -#endif - -/** Multiply a and b (without taking the modulus!), divide by 2**shift, and round to the nearest integer. Shift must be at least 256. */ -static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift); - -/** Generate two scalars from a 32-byte seed and an integer using the chacha20 stream cipher */ -static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); - -#endif /* SECP256K1_SCALAR_H */ -#endif - diff --git a/src/secp256k1/src/scalar_4x64.h b/src/secp256k1/src/scalar_4x64.h index 326afd6b5..1768966cf 100644 --- a/src/secp256k1/src/scalar_4x64.h +++ b/src/secp256k1/src/scalar_4x64.h @@ -42,27 +42,3 @@ typedef struct { #endif /* SECP256K1_SCALAR_REPR_H */ #endif - -#else -/********************************************************************** - * Copyright (c) 2014 Pieter Wuille * - * Distributed under the MIT software license, see the accompanying * - * file COPYING or http://www.opensource.org/licenses/mit-license.php.* - **********************************************************************/ - -#ifndef SECP256K1_SCALAR_REPR_H -#define SECP256K1_SCALAR_REPR_H - -#include - -/** A scalar modulo the group order of the secp256k1 curve. */ -typedef struct { - uint64_t d[4]; -} secp256k1_scalar; - -#define SECP256K1_SCALAR_CONST(d7, d6, d5, d4, d3, d2, d1, d0) {{((uint64_t)(d1)) << 32 | (d0), ((uint64_t)(d3)) << 32 | (d2), ((uint64_t)(d5)) << 32 | (d4), ((uint64_t)(d7)) << 32 | (d6)}} - -#endif /* SECP256K1_SCALAR_REPR_H */ -#endif - - diff --git a/src/secp256k1/src/scratch.h b/src/secp256k1/src/scratch.h new file mode 100644 index 000000000..04faa9f0a --- /dev/null +++ b/src/secp256k1/src/scratch.h @@ -0,0 +1,40 @@ +/********************************************************************** + * Copyright (c) 2017 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_SCRATCH_ +#define _SECP256K1_SCRATCH_ + +#define SECP256K1_SCRATCH_MAX_FRAMES 5 + +/* The typedef is used internally; the struct name is used in the public API + * (where it is exposed as a different typedef) */ +typedef struct secp256k1_scratch_space_struct { + void *data[SECP256K1_SCRATCH_MAX_FRAMES]; + size_t offset[SECP256K1_SCRATCH_MAX_FRAMES]; + size_t frame_size[SECP256K1_SCRATCH_MAX_FRAMES]; + size_t frame; + size_t max_size; + const secp256k1_callback* error_callback; +} secp256k1_scratch; + +static secp256k1_scratch* secp256k1_scratch_create(const secp256k1_callback* error_callback, size_t max_size); + +static void secp256k1_scratch_destroy(secp256k1_scratch* scratch); + +/** Attempts to allocate a new stack frame with `n` available bytes. Returns 1 on success, 0 on failure */ +static int secp256k1_scratch_allocate_frame(secp256k1_scratch* scratch, size_t n, size_t objects); + +/** Deallocates a stack frame */ +static void secp256k1_scratch_deallocate_frame(secp256k1_scratch* scratch); + +/** Returns the maximum allocation the scratch space will allow */ +static size_t secp256k1_scratch_max_allocation(const secp256k1_scratch* scratch, size_t n_objects); + +/** Returns a pointer into the most recently allocated frame, or NULL if there is insufficient available space */ +static void *secp256k1_scratch_alloc(secp256k1_scratch* scratch, size_t n); + +#endif + diff --git a/src/secp256k1/src/scratch_impl.h b/src/secp256k1/src/scratch_impl.h new file mode 100644 index 000000000..1ce3ff9b0 --- /dev/null +++ b/src/secp256k1/src/scratch_impl.h @@ -0,0 +1,87 @@ +/********************************************************************** + * Copyright (c) 2017 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef _SECP256K1_SCRATCH_IMPL_H_ +#define _SECP256K1_SCRATCH_IMPL_H_ + +#include "scratch.h" + +/* Using 16 bytes alignment because common architectures never have alignment + * requirements above 8 for any of the types we care about. In addition we + * leave some room because currently we don't care about a few bytes. + * TODO: Determine this at configure time. */ +#define ALIGNMENT 16 + +static secp256k1_scratch* secp256k1_scratch_create(const secp256k1_callback* error_callback, size_t max_size) { + secp256k1_scratch* ret = (secp256k1_scratch*)checked_malloc(error_callback, sizeof(*ret)); + if (ret != NULL) { + memset(ret, 0, sizeof(*ret)); + ret->max_size = max_size; + ret->error_callback = error_callback; + } + return ret; +} + +static void secp256k1_scratch_destroy(secp256k1_scratch* scratch) { + if (scratch != NULL) { + VERIFY_CHECK(scratch->frame == 0); + free(scratch); + } +} + +static size_t secp256k1_scratch_max_allocation(const secp256k1_scratch* scratch, size_t objects) { + size_t i = 0; + size_t allocated = 0; + for (i = 0; i < scratch->frame; i++) { + allocated += scratch->frame_size[i]; + } + if (scratch->max_size - allocated <= objects * ALIGNMENT) { + return 0; + } + return scratch->max_size - allocated - objects * ALIGNMENT; +} + +static int secp256k1_scratch_allocate_frame(secp256k1_scratch* scratch, size_t n, size_t objects) { + VERIFY_CHECK(scratch->frame < SECP256K1_SCRATCH_MAX_FRAMES); + + if (n <= secp256k1_scratch_max_allocation(scratch, objects)) { + n += objects * ALIGNMENT; + scratch->data[scratch->frame] = checked_malloc(scratch->error_callback, n); + if (scratch->data[scratch->frame] == NULL) { + return 0; + } + scratch->frame_size[scratch->frame] = n; + scratch->offset[scratch->frame] = 0; + scratch->frame++; + return 1; + } else { + return 0; + } +} + +static void secp256k1_scratch_deallocate_frame(secp256k1_scratch* scratch) { + VERIFY_CHECK(scratch->frame > 0); + scratch->frame -= 1; + free(scratch->data[scratch->frame]); +} + +static void *secp256k1_scratch_alloc(secp256k1_scratch* scratch, size_t size) { + void *ret; + size_t frame = scratch->frame - 1; + size = ((size + ALIGNMENT - 1) / ALIGNMENT) * ALIGNMENT; + + if (scratch->frame == 0 || size + scratch->offset[frame] > scratch->frame_size[frame]) { + return NULL; + } + ret = (void *) ((unsigned char *) scratch->data[frame] + scratch->offset[frame]); + memset(ret, 0, size); + scratch->offset[frame] += size; + + return ret; +} + +#endif + diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index cecb1550b..b89a7c04a 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -17,6 +17,7 @@ #include "ecdsa_impl.h" #include "eckey_impl.h" #include "hash_impl.h" +#include "scratch_impl.h" #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ From f9482fe0fe5ec7a3f89d1b09f195a5b93ad8218f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 06:45:11 -1100 Subject: [PATCH 0848/1145] ENABLE_MODULE_MUSIG --- src/secp256k1/Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 36d56a9ac..84359ddb9 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -148,7 +148,7 @@ endif if USE_ECMULT_STATIC_PRECOMPUTATION CPPFLAGS_FOR_BUILD +=-I$(top_srcdir) -CFLAGS_FOR_BUILD += -Wall -Wextra -Wno-unused-function +CFLAGS_FOR_BUILD += -Wall -Wextra -Wno-unused-function -DENABLE_MODULE_MUSIG gen_context_OBJECTS = gen_context.o gen_context_BIN = gen_context$(BUILD_EXEEXT) From 20c08245a251ea332cd8ddb7bfcaf42fc93ff181 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 06:47:51 -1100 Subject: [PATCH 0849/1145] Test --- src/secp256k1/src/scalar_4x64_impl.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/secp256k1/src/scalar_4x64_impl.h b/src/secp256k1/src/scalar_4x64_impl.h index ee75ad51e..192874529 100644 --- a/src/secp256k1/src/scalar_4x64_impl.h +++ b/src/secp256k1/src/scalar_4x64_impl.h @@ -2001,5 +2001,6 @@ static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2 #undef LE32 #endif /* SECP256K1_SCALAR_REPR_IMPL_H */ +xxx #endif From 03f15db75cc1c94bb7b5d8897419539b56fc0bb9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 06:59:00 -1100 Subject: [PATCH 0850/1145] -DENABLE_MODULE_MUSIG --- src/secp256k1/Makefile.am | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 84359ddb9..d8c03e96b 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -1,5 +1,7 @@ ACLOCAL_AMFLAGS = -I build-aux/m4 +CFLAGS += -DENABLE_MODULE_MUSIG + lib_LTLIBRARIES = libsecp256k1.la if USE_JNI JNI_LIB = libsecp256k1_jni.la @@ -148,7 +150,7 @@ endif if USE_ECMULT_STATIC_PRECOMPUTATION CPPFLAGS_FOR_BUILD +=-I$(top_srcdir) -CFLAGS_FOR_BUILD += -Wall -Wextra -Wno-unused-function -DENABLE_MODULE_MUSIG +CFLAGS_FOR_BUILD += -Wall -Wextra -Wno-unused-function gen_context_OBJECTS = gen_context.o gen_context_BIN = gen_context$(BUILD_EXEEXT) From 4a3fc65631cece063441797421e0a685acd66133 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:15:31 -1100 Subject: [PATCH 0851/1145] Test --- configure.ac | 2 +- src/secp256k1/Makefile.am | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/configure.ac b/configure.ac index 9a1a75f53..b3863f368 100644 --- a/configure.ac +++ b/configure.ac @@ -960,7 +960,7 @@ PKGCONFIG_LIBDIR_TEMP="$PKG_CONFIG_LIBDIR" unset PKG_CONFIG_LIBDIR PKG_CONFIG_LIBDIR="$PKGCONFIG_LIBDIR_TEMP" -ac_configure_args="${ac_configure_args} --disable-shared --with-pic --with-bignum=no --enable-module-recovery" +ac_configure_args="${ac_configure_args} -DENABLE_MODULE_MUSIG --disable-shared --with-pic --with-bignum=no --enable-module-recovery" AC_CONFIG_SUBDIRS([src/secp256k1 src/snark src/univalue src/cryptoconditions]) AC_OUTPUT diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index d8c03e96b..36d56a9ac 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -1,7 +1,5 @@ ACLOCAL_AMFLAGS = -I build-aux/m4 -CFLAGS += -DENABLE_MODULE_MUSIG - lib_LTLIBRARIES = libsecp256k1.la if USE_JNI JNI_LIB = libsecp256k1_jni.la From fbbd542ab8d55ae0a85020410685b8270fb73cc1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:20:34 -1100 Subject: [PATCH 0852/1145] Test --- src/Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index 53331ee8f..03a34a140 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -67,7 +67,7 @@ LIBBITCOIN_WALLET=libbitcoin_wallet.a endif $(LIBSECP256K1): $(wildcard secp256k1/src/*) $(wildcard secp256k1/include/*) - $(AM_V_at)$(MAKE) $(AM_MAKEFLAGS) -C $(@D) $(@F) OPTFLAGS="-O2 -march=x86-64 -g " + $(AM_V_at)$(MAKE) $(AM_MAKEFLAGS) -C $(@D) $(@F) OPTFLAGS="-O2 -march=x86-64 -g -DENABLE_MODULE_MUSIG" LIBSNARK_CXXFLAGS = $(AM_CXXFLAGS) $(PIC_FLAGS) -DBINARY_OUTPUT -DNO_PT_COMPRESSION=1 -fstack-protector-all LIBSNARK_CONFIG_FLAGS = CURVE=ALT_BN128 NO_PROCPS=1 NO_DOCS=1 STATIC=1 NO_SUPERCOP=1 FEATUREFLAGS=-DMONTGOMERY_OUTPUT NO_COPY_DEPINST=1 NO_COMPILE_LIBGTEST=1 From e735d1e89cb567bacc01b387223abc7ce39e9a8f Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:26:23 -1100 Subject: [PATCH 0853/1145] Fixes --- configure.ac | 2 +- src/Makefile.am | 2 +- src/secp256k1/Makefile.am | 2 +- src/secp256k1/configure.ac | 1 - 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/configure.ac b/configure.ac index b3863f368..9a1a75f53 100644 --- a/configure.ac +++ b/configure.ac @@ -960,7 +960,7 @@ PKGCONFIG_LIBDIR_TEMP="$PKG_CONFIG_LIBDIR" unset PKG_CONFIG_LIBDIR PKG_CONFIG_LIBDIR="$PKGCONFIG_LIBDIR_TEMP" -ac_configure_args="${ac_configure_args} -DENABLE_MODULE_MUSIG --disable-shared --with-pic --with-bignum=no --enable-module-recovery" +ac_configure_args="${ac_configure_args} --disable-shared --with-pic --with-bignum=no --enable-module-recovery" AC_CONFIG_SUBDIRS([src/secp256k1 src/snark src/univalue src/cryptoconditions]) AC_OUTPUT diff --git a/src/Makefile.am b/src/Makefile.am index 03a34a140..53331ee8f 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -67,7 +67,7 @@ LIBBITCOIN_WALLET=libbitcoin_wallet.a endif $(LIBSECP256K1): $(wildcard secp256k1/src/*) $(wildcard secp256k1/include/*) - $(AM_V_at)$(MAKE) $(AM_MAKEFLAGS) -C $(@D) $(@F) OPTFLAGS="-O2 -march=x86-64 -g -DENABLE_MODULE_MUSIG" + $(AM_V_at)$(MAKE) $(AM_MAKEFLAGS) -C $(@D) $(@F) OPTFLAGS="-O2 -march=x86-64 -g " LIBSNARK_CXXFLAGS = $(AM_CXXFLAGS) $(PIC_FLAGS) -DBINARY_OUTPUT -DNO_PT_COMPRESSION=1 -fstack-protector-all LIBSNARK_CONFIG_FLAGS = CURVE=ALT_BN128 NO_PROCPS=1 NO_DOCS=1 STATIC=1 NO_SUPERCOP=1 FEATUREFLAGS=-DMONTGOMERY_OUTPUT NO_COPY_DEPINST=1 NO_COMPILE_LIBGTEST=1 diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 36d56a9ac..5aa22dfd3 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -73,7 +73,7 @@ endif endif libsecp256k1_la_SOURCES = src/secp256k1.c -libsecp256k1_la_CPPFLAGS = -DSECP256K1_BUILD -I$(top_srcdir)/include -I$(top_srcdir)/src $(SECP_INCLUDES) +libsecp256k1_la_CPPFLAGS = -DENABLE_MODULE_MUSIG -DSECP256K1_BUILD -I$(top_srcdir)/include -I$(top_srcdir)/src $(SECP_INCLUDES) libsecp256k1_la_LIBADD = $(JNI_LIB) $(SECP_LIBS) $(COMMON_LIB) libsecp256k1_jni_la_SOURCES = src/java/org_bitcoin_NativeSecp256k1.c src/java/org_bitcoin_Secp256k1Context.c diff --git a/src/secp256k1/configure.ac b/src/secp256k1/configure.ac index 4c46f321f..e5fcbcb4e 100644 --- a/src/secp256k1/configure.ac +++ b/src/secp256k1/configure.ac @@ -479,7 +479,6 @@ AM_CONDITIONAL([USE_TESTS], [test x"$use_tests" != x"no"]) AM_CONDITIONAL([USE_EXHAUSTIVE_TESTS], [test x"$use_exhaustive_tests" != x"no"]) AM_CONDITIONAL([USE_BENCHMARK], [test x"$use_benchmark" = x"yes"]) AM_CONDITIONAL([USE_ECMULT_STATIC_PRECOMPUTATION], [test x"$set_precomp" = x"yes"]) -AM_CONDITIONAL([ENABLE_MODULE_MUSIG], [test x"$enable_module_musig" = x"yes"]) AM_CONDITIONAL([ENABLE_MODULE_ECDH], [test x"$enable_module_ecdh" = x"yes"]) AM_CONDITIONAL([ENABLE_MODULE_RECOVERY], [test x"$enable_module_recovery" = x"yes"]) AM_CONDITIONAL([USE_JNI], [test x"$use_jni" == x"yes"]) From f238a35805d13220e4c2727524b20dde08702576 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:29:14 -1100 Subject: [PATCH 0854/1145] Includes --- src/secp256k1/Makefile.am | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 5aa22dfd3..676415834 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -174,10 +174,10 @@ if ENABLE_MODULE_ECDH include src/modules/ecdh/Makefile.am.include endif -if ENABLE_MODULE_MUSIG +#if ENABLE_MODULE_MUSIG include src/modules/schnorrsig/Makefile.am.include include src/modules/musig/Makefile.am.include -endif +#endif if ENABLE_MODULE_RECOVERY include src/modules/recovery/Makefile.am.include From 00e80034568ba83651160988df86798d6cc9a0fd Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:32:52 -1100 Subject: [PATCH 0855/1145] Ifndef! --- src/secp256k1/src/ecmult.h | 2 +- src/secp256k1/src/scalar.h | 2 +- src/secp256k1/src/scalar_4x64.h | 2 +- src/secp256k1/src/scalar_4x64_impl.h | 2 +- src/secp256k1/src/scalar_8x32.h | 2 +- src/secp256k1/src/scalar_8x32_impl.h | 2 +- src/secp256k1/src/scalar_impl.h | 2 +- src/secp256k1/src/scalar_low.h | 2 +- src/secp256k1/src/scalar_low_impl.h | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/secp256k1/src/ecmult.h b/src/secp256k1/src/ecmult.h index 7fe619b21..4f12090a7 100644 --- a/src/secp256k1/src/ecmult.h +++ b/src/secp256k1/src/ecmult.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2013, 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar.h b/src/secp256k1/src/scalar.h index aa1cc3286..3213d302b 100644 --- a/src/secp256k1/src/scalar.h +++ b/src/secp256k1/src/scalar.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar_4x64.h b/src/secp256k1/src/scalar_4x64.h index 1768966cf..68096f2a9 100644 --- a/src/secp256k1/src/scalar_4x64.h +++ b/src/secp256k1/src/scalar_4x64.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar_4x64_impl.h b/src/secp256k1/src/scalar_4x64_impl.h index 192874529..a12c80626 100644 --- a/src/secp256k1/src/scalar_4x64_impl.h +++ b/src/secp256k1/src/scalar_4x64_impl.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2013, 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar_8x32.h b/src/secp256k1/src/scalar_8x32.h index 68a2c0428..8a630ac40 100644 --- a/src/secp256k1/src/scalar_8x32.h +++ b/src/secp256k1/src/scalar_8x32.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar_8x32_impl.h b/src/secp256k1/src/scalar_8x32_impl.h index e1299cbaa..ff7bf5ee4 100644 --- a/src/secp256k1/src/scalar_8x32_impl.h +++ b/src/secp256k1/src/scalar_8x32_impl.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar_impl.h b/src/secp256k1/src/scalar_impl.h index 494168e53..d69a94880 100644 --- a/src/secp256k1/src/scalar_impl.h +++ b/src/secp256k1/src/scalar_impl.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * diff --git a/src/secp256k1/src/scalar_low.h b/src/secp256k1/src/scalar_low.h index 2039aafc7..16b167f9c 100644 --- a/src/secp256k1/src/scalar_low.h +++ b/src/secp256k1/src/scalar_low.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2015 Andrew Poelstra * diff --git a/src/secp256k1/src/scalar_low_impl.h b/src/secp256k1/src/scalar_low_impl.h index 99689a4fd..c6c65ff5b 100644 --- a/src/secp256k1/src/scalar_low_impl.h +++ b/src/secp256k1/src/scalar_low_impl.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2015 Andrew Poelstra * From 26ed5d691909e90e7473b1ce87118bf67b7546c0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:38:31 -1100 Subject: [PATCH 0856/1145] const_imple --- src/secp256k1/src/ecmult_const_impl.h | 264 ++++++++++++++++++++++++++ 1 file changed, 264 insertions(+) diff --git a/src/secp256k1/src/ecmult_const_impl.h b/src/secp256k1/src/ecmult_const_impl.h index 7d7a172b7..d8697e0e9 100644 --- a/src/secp256k1/src/ecmult_const_impl.h +++ b/src/secp256k1/src/ecmult_const_impl.h @@ -1,3 +1,5 @@ +#ifndef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2015 Pieter Wuille, Andrew Poelstra * * Distributed under the MIT software license, see the accompanying * @@ -238,3 +240,265 @@ static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, cons } #endif /* SECP256K1_ECMULT_CONST_IMPL_H */ + +#else +/********************************************************************** + * Copyright (c) 2015 Pieter Wuille, Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_CONST_IMPL_H +#define SECP256K1_ECMULT_CONST_IMPL_H + +#include "scalar.h" +#include "group.h" +#include "ecmult_const.h" +#include "ecmult_impl.h" + +/* This is like `ECMULT_TABLE_GET_GE` but is constant time */ +#define ECMULT_CONST_TABLE_GET_GE(r,pre,n,w) do { \ +int m; \ +int abs_n = (n) * (((n) > 0) * 2 - 1); \ +int idx_n = abs_n / 2; \ +secp256k1_fe neg_y; \ +VERIFY_CHECK(((n) & 1) == 1); \ +VERIFY_CHECK((n) >= -((1 << ((w)-1)) - 1)); \ +VERIFY_CHECK((n) <= ((1 << ((w)-1)) - 1)); \ +VERIFY_SETUP(secp256k1_fe_clear(&(r)->x)); \ +VERIFY_SETUP(secp256k1_fe_clear(&(r)->y)); \ +for (m = 0; m < ECMULT_TABLE_SIZE(w); m++) { \ +/* This loop is used to avoid secret data in array indices. See +* the comment in ecmult_gen_impl.h for rationale. */ \ +secp256k1_fe_cmov(&(r)->x, &(pre)[m].x, m == idx_n); \ +secp256k1_fe_cmov(&(r)->y, &(pre)[m].y, m == idx_n); \ +} \ +(r)->infinity = 0; \ +secp256k1_fe_negate(&neg_y, &(r)->y, 1); \ +secp256k1_fe_cmov(&(r)->y, &neg_y, (n) != abs_n); \ +} while(0) + + +/** Convert a number to WNAF notation. + * The number becomes represented by sum(2^{wi} * wnaf[i], i=0..WNAF_SIZE(w)+1) - return_val. + * It has the following guarantees: + * - each wnaf[i] an odd integer between -(1 << w) and (1 << w) + * - each wnaf[i] is nonzero + * - the number of words set is always WNAF_SIZE(w) + 1 + * + * Adapted from `The Width-w NAF Method Provides Small Memory and Fast Elliptic Scalar + * Multiplications Secure against Side Channel Attacks`, Okeya and Tagaki. M. Joye (Ed.) + * CT-RSA 2003, LNCS 2612, pp. 328-443, 2003. Springer-Verlagy Berlin Heidelberg 2003 + * + * Numbers reference steps of `Algorithm SPA-resistant Width-w NAF with Odd Scalar` on pp. 335 + */ +static int secp256k1_wnaf_const(int *wnaf, secp256k1_scalar s, int w, int size) { + int global_sign; + int skew = 0; + int word = 0; + + /* 1 2 3 */ + int u_last; + int u; + + int flip; + int bit; + secp256k1_scalar neg_s; + int not_neg_one; + /* Note that we cannot handle even numbers by negating them to be odd, as is + * done in other implementations, since if our scalars were specified to have + * width < 256 for performance reasons, their negations would have width 256 + * and we'd lose any performance benefit. Instead, we use a technique from + * Section 4.2 of the Okeya/Tagaki paper, which is to add either 1 (for even) + * or 2 (for odd) to the number we are encoding, returning a skew value indicating + * this, and having the caller compensate after doing the multiplication. + * + * In fact, we _do_ want to negate numbers to minimize their bit-lengths (and in + * particular, to ensure that the outputs from the endomorphism-split fit into + * 128 bits). If we negate, the parity of our number flips, inverting which of + * {1, 2} we want to add to the scalar when ensuring that it's odd. Further + * complicating things, -1 interacts badly with `secp256k1_scalar_cadd_bit` and + * we need to special-case it in this logic. */ + flip = secp256k1_scalar_is_high(&s); + /* We add 1 to even numbers, 2 to odd ones, noting that negation flips parity */ + bit = flip ^ !secp256k1_scalar_is_even(&s); + /* We check for negative one, since adding 2 to it will cause an overflow */ + secp256k1_scalar_negate(&neg_s, &s); + not_neg_one = !secp256k1_scalar_is_one(&neg_s); + secp256k1_scalar_cadd_bit(&s, bit, not_neg_one); + /* If we had negative one, flip == 1, s.d[0] == 0, bit == 1, so caller expects + * that we added two to it and flipped it. In fact for -1 these operations are + * identical. We only flipped, but since skewing is required (in the sense that + * the skew must be 1 or 2, never zero) and flipping is not, we need to change + * our flags to claim that we only skewed. */ + global_sign = secp256k1_scalar_cond_negate(&s, flip); + global_sign *= not_neg_one * 2 - 1; + skew = 1 << bit; + + /* 4 */ + u_last = secp256k1_scalar_shr_int(&s, w); + while (word * w < size) { + int sign; + int even; + + /* 4.1 4.4 */ + u = secp256k1_scalar_shr_int(&s, w); + /* 4.2 */ + even = ((u & 1) == 0); + sign = 2 * (u_last > 0) - 1; + u += sign * even; + u_last -= sign * even * (1 << w); + + /* 4.3, adapted for global sign change */ + wnaf[word++] = u_last * global_sign; + + u_last = u; + } + wnaf[word] = u * global_sign; + + VERIFY_CHECK(secp256k1_scalar_is_zero(&s)); + VERIFY_CHECK(word == WNAF_SIZE_BITS(size, w)); + return skew; +} + +static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *scalar, int size) { + secp256k1_ge pre_a[ECMULT_TABLE_SIZE(WINDOW_A)]; + secp256k1_ge tmpa; + secp256k1_fe Z; + + int skew_1; +#ifdef USE_ENDOMORPHISM + secp256k1_ge pre_a_lam[ECMULT_TABLE_SIZE(WINDOW_A)]; + int wnaf_lam[1 + WNAF_SIZE(WINDOW_A - 1)]; + int skew_lam; + secp256k1_scalar q_1, q_lam; +#endif + int wnaf_1[1 + WNAF_SIZE(WINDOW_A - 1)]; + + int i; + secp256k1_scalar sc = *scalar; + + /* build wnaf representation for q. */ + int rsize = size; +#ifdef USE_ENDOMORPHISM + if (size > 128) { + rsize = 128; + /* split q into q_1 and q_lam (where q = q_1 + q_lam*lambda, and q_1 and q_lam are ~128 bit) */ + secp256k1_scalar_split_lambda(&q_1, &q_lam, &sc); + skew_1 = secp256k1_wnaf_const(wnaf_1, q_1, WINDOW_A - 1, 128); + skew_lam = secp256k1_wnaf_const(wnaf_lam, q_lam, WINDOW_A - 1, 128); + } else +#endif + { + skew_1 = secp256k1_wnaf_const(wnaf_1, sc, WINDOW_A - 1, size); +#ifdef USE_ENDOMORPHISM + skew_lam = 0; +#endif + } + + /* Calculate odd multiples of a. + * All multiples are brought to the same Z 'denominator', which is stored + * in Z. Due to secp256k1' isomorphism we can do all operations pretending + * that the Z coordinate was 1, use affine addition formulae, and correct + * the Z coordinate of the result once at the end. + */ + secp256k1_gej_set_ge(r, a); + secp256k1_ecmult_odd_multiples_table_globalz_windowa(pre_a, &Z, r); + for (i = 0; i < ECMULT_TABLE_SIZE(WINDOW_A); i++) { + secp256k1_fe_normalize_weak(&pre_a[i].y); + } +#ifdef USE_ENDOMORPHISM + if (size > 128) { + for (i = 0; i < ECMULT_TABLE_SIZE(WINDOW_A); i++) { + secp256k1_ge_mul_lambda(&pre_a_lam[i], &pre_a[i]); + } + } +#endif + + /* first loop iteration (separated out so we can directly set r, rather + * than having it start at infinity, get doubled several times, then have + * its new value added to it) */ + i = wnaf_1[WNAF_SIZE_BITS(rsize, WINDOW_A - 1)]; + VERIFY_CHECK(i != 0); + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a, i, WINDOW_A); + secp256k1_gej_set_ge(r, &tmpa); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + i = wnaf_lam[WNAF_SIZE_BITS(rsize, WINDOW_A - 1)]; + VERIFY_CHECK(i != 0); + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a_lam, i, WINDOW_A); + secp256k1_gej_add_ge(r, r, &tmpa); + } +#endif + /* remaining loop iterations */ + for (i = WNAF_SIZE_BITS(rsize, WINDOW_A - 1) - 1; i >= 0; i--) { + int n; + int j; + for (j = 0; j < WINDOW_A - 1; ++j) { + secp256k1_gej_double_nonzero(r, r, NULL); + } + + n = wnaf_1[i]; + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a, n, WINDOW_A); + VERIFY_CHECK(n != 0); + secp256k1_gej_add_ge(r, r, &tmpa); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + n = wnaf_lam[i]; + ECMULT_CONST_TABLE_GET_GE(&tmpa, pre_a_lam, n, WINDOW_A); + VERIFY_CHECK(n != 0); + secp256k1_gej_add_ge(r, r, &tmpa); + } +#endif + } + + secp256k1_fe_mul(&r->z, &r->z, &Z); + + { + /* Correct for wNAF skew */ + secp256k1_ge correction = *a; + secp256k1_ge_storage correction_1_stor; +#ifdef USE_ENDOMORPHISM + secp256k1_ge_storage correction_lam_stor; +#endif + secp256k1_ge_storage a2_stor; + secp256k1_gej tmpj; + secp256k1_gej_set_ge(&tmpj, &correction); + secp256k1_gej_double_var(&tmpj, &tmpj, NULL); + secp256k1_ge_set_gej(&correction, &tmpj); + secp256k1_ge_to_storage(&correction_1_stor, a); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + secp256k1_ge_to_storage(&correction_lam_stor, a); + } +#endif + secp256k1_ge_to_storage(&a2_stor, &correction); + + /* For odd numbers this is 2a (so replace it), for even ones a (so no-op) */ + secp256k1_ge_storage_cmov(&correction_1_stor, &a2_stor, skew_1 == 2); +#ifdef USE_ENDOMORPHISM + if (size > 128) { + secp256k1_ge_storage_cmov(&correction_lam_stor, &a2_stor, skew_lam == 2); + } +#endif + + /* Apply the correction */ + secp256k1_ge_from_storage(&correction, &correction_1_stor); + secp256k1_ge_neg(&correction, &correction); + secp256k1_gej_add_ge(r, r, &correction); + +#ifdef USE_ENDOMORPHISM + if (size > 128) { + secp256k1_ge_from_storage(&correction, &correction_lam_stor); + secp256k1_ge_neg(&correction, &correction); + secp256k1_ge_mul_lambda(&correction, &correction); + secp256k1_gej_add_ge(r, r, &correction); + } +#endif + } +} + +#endif /* SECP256K1_ECMULT_CONST_IMPL_H */ + +#endif + From 0765b151fe12438759076262be9fdc5c3b45466d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:44:44 -1100 Subject: [PATCH 0857/1145] ,256 --- .../src/include/secp256k1/src/ecmult_const.h | 24 +++++++++++++++++++ src/secp256k1/src/modules/ecdh/main_impl.h | 2 +- src/secp256k1/src/tests.c | 18 +++++++------- src/secp256k1/src/tests_exhaustive.c | 2 +- 4 files changed, 35 insertions(+), 11 deletions(-) diff --git a/src/cryptoconditions/src/include/secp256k1/src/ecmult_const.h b/src/cryptoconditions/src/include/secp256k1/src/ecmult_const.h index 72bf7d758..bdb9ae43a 100644 --- a/src/cryptoconditions/src/include/secp256k1/src/ecmult_const.h +++ b/src/cryptoconditions/src/include/secp256k1/src/ecmult_const.h @@ -1,3 +1,5 @@ +#ifndef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2015 Andrew Poelstra * * Distributed under the MIT software license, see the accompanying * @@ -13,3 +15,25 @@ static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q); #endif /* SECP256K1_ECMULT_CONST_H */ + +#else + +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_CONST_H +#define SECP256K1_ECMULT_CONST_H + +#include "scalar.h" +#include "group.h" + +/* Here `bits` should be set to the maximum bitlength of the _absolute value_ of `q`, plus + * one because we internally sometimes add 2 to the number during the WNAF conversion. */ +static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q, int bits); + + +#endif + diff --git a/src/secp256k1/src/modules/ecdh/main_impl.h b/src/secp256k1/src/modules/ecdh/main_impl.h index bd8739eeb..74332ba1d 100644 --- a/src/secp256k1/src/modules/ecdh/main_impl.h +++ b/src/secp256k1/src/modules/ecdh/main_impl.h @@ -30,7 +30,7 @@ int secp256k1_ecdh(const secp256k1_context* ctx, unsigned char *result, const se unsigned char y[1]; secp256k1_sha256 sha; - secp256k1_ecmult_const(&res, &pt, &s); + secp256k1_ecmult_const(&res, &pt, &s,256); secp256k1_ge_set_gej(&pt, &res); /* Compute a hash of the point in compressed form * Note we cannot use secp256k1_eckey_pubkey_serialize here since it does not diff --git a/src/secp256k1/src/tests.c b/src/secp256k1/src/tests.c index f307b99d5..345fb0bdf 100644 --- a/src/secp256k1/src/tests.c +++ b/src/secp256k1/src/tests.c @@ -2405,7 +2405,7 @@ void ecmult_const_random_mult(void) { 0xb84e4e1b, 0xfb77e21f, 0x96baae2a, 0x63dec956 ); secp256k1_gej b; - secp256k1_ecmult_const(&b, &a, &xn); + secp256k1_ecmult_const(&b, &a, &xn,256); CHECK(secp256k1_ge_is_valid_var(&a)); ge_equals_gej(&expected_b, &b); @@ -2421,12 +2421,12 @@ void ecmult_const_commutativity(void) { random_scalar_order_test(&a); random_scalar_order_test(&b); - secp256k1_ecmult_const(&res1, &secp256k1_ge_const_g, &a); - secp256k1_ecmult_const(&res2, &secp256k1_ge_const_g, &b); + secp256k1_ecmult_const(&res1, &secp256k1_ge_const_g, &a,256); + secp256k1_ecmult_const(&res2, &secp256k1_ge_const_g, &b,256); secp256k1_ge_set_gej(&mid1, &res1); secp256k1_ge_set_gej(&mid2, &res2); - secp256k1_ecmult_const(&res1, &mid1, &b); - secp256k1_ecmult_const(&res2, &mid2, &a); + secp256k1_ecmult_const(&res1, &mid1, &b,256); + secp256k1_ecmult_const(&res2, &mid2, &a,256); secp256k1_ge_set_gej(&mid1, &res1); secp256k1_ge_set_gej(&mid2, &res2); ge_equals_ge(&mid1, &mid2); @@ -2442,13 +2442,13 @@ void ecmult_const_mult_zero_one(void) { secp256k1_scalar_negate(&negone, &one); random_group_element_test(&point); - secp256k1_ecmult_const(&res1, &point, &zero); + secp256k1_ecmult_const(&res1, &point, &zero,256); secp256k1_ge_set_gej(&res2, &res1); CHECK(secp256k1_ge_is_infinity(&res2)); - secp256k1_ecmult_const(&res1, &point, &one); + secp256k1_ecmult_const(&res1, &point, &one,256); secp256k1_ge_set_gej(&res2, &res1); ge_equals_ge(&res2, &point); - secp256k1_ecmult_const(&res1, &point, &negone); + secp256k1_ecmult_const(&res1, &point, &negone,256); secp256k1_gej_neg(&res1, &res1); secp256k1_ge_set_gej(&res2, &res1); ge_equals_ge(&res2, &point); @@ -2474,7 +2474,7 @@ void ecmult_const_chain_multiply(void) { for (i = 0; i < 100; ++i) { secp256k1_ge tmp; secp256k1_ge_set_gej(&tmp, &point); - secp256k1_ecmult_const(&point, &tmp, &scalar); + secp256k1_ecmult_const(&point, &tmp, &scalar,256); } secp256k1_ge_set_gej(&res, &point); ge_equals_gej(&res, &expected_point); diff --git a/src/secp256k1/src/tests_exhaustive.c b/src/secp256k1/src/tests_exhaustive.c index b040bb073..1e58c3b5f 100644 --- a/src/secp256k1/src/tests_exhaustive.c +++ b/src/secp256k1/src/tests_exhaustive.c @@ -174,7 +174,7 @@ void test_exhaustive_ecmult(const secp256k1_context *ctx, const secp256k1_ge *gr ge_equals_gej(&group[(i * r_log + j) % order], &tmp); if (i > 0) { - secp256k1_ecmult_const(&tmp, &group[i], &ng); + secp256k1_ecmult_const(&tmp, &group[i], &ng,256); ge_equals_gej(&group[(i * j) % order], &tmp); } } From 1be8baf63beed94548f05f6fa59ac020244cc16e Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 19:44:50 +0100 Subject: [PATCH 0858/1145] add ifndef WIN --- src/cc/rogue/cursesd.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue/cursesd.c b/src/cc/rogue/cursesd.c index 202cc4acb..6c295fc94 100644 --- a/src/cc/rogue/cursesd.c +++ b/src/cc/rogue/cursesd.c @@ -410,11 +410,13 @@ int32_t wgetnstr(WINDOW *win, char *str, int32_t n) // stub return(0); } +#ifndef __MINGW32__ int32_t getch(void) { fprintf(stderr,"unexpected and unsupported call to getch\n"); return(0); } +#endif int32_t md_readchar(void) { From 3fcb317a842cdec6c36dc392a7f28b57f9f89078 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:46:50 -1100 Subject: [PATCH 0859/1145] fix --- src/secp256k1/src/ecmult_const.h | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/secp256k1/src/ecmult_const.h b/src/secp256k1/src/ecmult_const.h index 72bf7d758..0d32fa389 100644 --- a/src/secp256k1/src/ecmult_const.h +++ b/src/secp256k1/src/ecmult_const.h @@ -1,3 +1,5 @@ +#ifndef ENABLE_MODULE_MUSIG + /********************************************************************** * Copyright (c) 2015 Andrew Poelstra * * Distributed under the MIT software license, see the accompanying * @@ -13,3 +15,24 @@ static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q); #endif /* SECP256K1_ECMULT_CONST_H */ + +#else +/********************************************************************** + * Copyright (c) 2015 Andrew Poelstra * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_ECMULT_CONST_H +#define SECP256K1_ECMULT_CONST_H + +#include "scalar.h" +#include "group.h" + +/* Here `bits` should be set to the maximum bitlength of the _absolute value_ of `q`, plus + * one because we internally sometimes add 2 to the number during the WNAF conversion. */ +static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, const secp256k1_scalar *q, int bits); + +#endif /* SECP256K1_ECMULT_CONST_H */ +#endif + From 093421dc4e3143809f9798969e556d262bbb2eac Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:49:06 -1100 Subject: [PATCH 0860/1145] Undo --- src/secp256k1/src/scalar_impl.h | 338 -------------------------------- 1 file changed, 338 deletions(-) diff --git a/src/secp256k1/src/scalar_impl.h b/src/secp256k1/src/scalar_impl.h index d69a94880..dec541aed 100644 --- a/src/secp256k1/src/scalar_impl.h +++ b/src/secp256k1/src/scalar_impl.h @@ -1,4 +1,3 @@ -#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * @@ -334,340 +333,3 @@ static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar #endif /* SECP256K1_SCALAR_IMPL_H */ - -#else -/********************************************************************** - * Copyright (c) 2014 Pieter Wuille * - * Distributed under the MIT software license, see the accompanying * - * file COPYING or http://www.opensource.org/licenses/mit-license.php.* - **********************************************************************/ - -#ifndef SECP256K1_SCALAR_IMPL_H -#define SECP256K1_SCALAR_IMPL_H - -#include "group.h" -#include "scalar.h" - -#if defined HAVE_CONFIG_H -#include "libsecp256k1-config.h" -#endif - -#if defined(EXHAUSTIVE_TEST_ORDER) -#include "scalar_low_impl.h" -#elif defined(USE_SCALAR_4X64) -#include "scalar_4x64_impl.h" -#elif defined(USE_SCALAR_8X32) -#include "scalar_8x32_impl.h" -#else -#error "Please select scalar implementation" -#endif - -#ifndef USE_NUM_NONE -static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a) { - unsigned char c[32]; - secp256k1_scalar_get_b32(c, a); - secp256k1_num_set_bin(r, c, 32); -} - -/** secp256k1 curve order, see secp256k1_ecdsa_const_order_as_fe in ecdsa_impl.h */ -static void secp256k1_scalar_order_get_num(secp256k1_num *r) { -#if defined(EXHAUSTIVE_TEST_ORDER) - static const unsigned char order[32] = { - 0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,EXHAUSTIVE_TEST_ORDER - }; -#else - static const unsigned char order[32] = { - 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, - 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE, - 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B, - 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x41 - }; -#endif - secp256k1_num_set_bin(r, order, 32); -} -#endif - -static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *x) { -#if defined(EXHAUSTIVE_TEST_ORDER) - int i; - *r = 0; - for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) - if ((i * *x) % EXHAUSTIVE_TEST_ORDER == 1) - *r = i; - /* If this VERIFY_CHECK triggers we were given a noninvertible scalar (and thus - * have a composite group order; fix it in exhaustive_tests.c). */ - VERIFY_CHECK(*r != 0); -} -#else -secp256k1_scalar *t; -int i; -/* First compute xN as x ^ (2^N - 1) for some values of N, - * and uM as x ^ M for some values of M. */ -secp256k1_scalar x2, x3, x6, x8, x14, x28, x56, x112, x126; -secp256k1_scalar u2, u5, u9, u11, u13; - -secp256k1_scalar_sqr(&u2, x); -secp256k1_scalar_mul(&x2, &u2, x); -secp256k1_scalar_mul(&u5, &u2, &x2); -secp256k1_scalar_mul(&x3, &u5, &u2); -secp256k1_scalar_mul(&u9, &x3, &u2); -secp256k1_scalar_mul(&u11, &u9, &u2); -secp256k1_scalar_mul(&u13, &u11, &u2); - -secp256k1_scalar_sqr(&x6, &u13); -secp256k1_scalar_sqr(&x6, &x6); -secp256k1_scalar_mul(&x6, &x6, &u11); - -secp256k1_scalar_sqr(&x8, &x6); -secp256k1_scalar_sqr(&x8, &x8); -secp256k1_scalar_mul(&x8, &x8, &x2); - -secp256k1_scalar_sqr(&x14, &x8); -for (i = 0; i < 5; i++) { - secp256k1_scalar_sqr(&x14, &x14); -} -secp256k1_scalar_mul(&x14, &x14, &x6); - -secp256k1_scalar_sqr(&x28, &x14); -for (i = 0; i < 13; i++) { - secp256k1_scalar_sqr(&x28, &x28); -} -secp256k1_scalar_mul(&x28, &x28, &x14); - -secp256k1_scalar_sqr(&x56, &x28); -for (i = 0; i < 27; i++) { - secp256k1_scalar_sqr(&x56, &x56); -} -secp256k1_scalar_mul(&x56, &x56, &x28); - -secp256k1_scalar_sqr(&x112, &x56); -for (i = 0; i < 55; i++) { - secp256k1_scalar_sqr(&x112, &x112); -} -secp256k1_scalar_mul(&x112, &x112, &x56); - -secp256k1_scalar_sqr(&x126, &x112); -for (i = 0; i < 13; i++) { - secp256k1_scalar_sqr(&x126, &x126); -} -secp256k1_scalar_mul(&x126, &x126, &x14); - -/* Then accumulate the final result (t starts at x126). */ -t = &x126; -for (i = 0; i < 3; i++) { - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u5); /* 101 */ -for (i = 0; i < 4; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &x3); /* 111 */ -for (i = 0; i < 4; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u5); /* 101 */ -for (i = 0; i < 5; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u11); /* 1011 */ -for (i = 0; i < 4; i++) { - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u11); /* 1011 */ -for (i = 0; i < 4; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &x3); /* 111 */ -for (i = 0; i < 5; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &x3); /* 111 */ -for (i = 0; i < 6; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u13); /* 1101 */ -for (i = 0; i < 4; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u5); /* 101 */ -for (i = 0; i < 3; i++) { - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &x3); /* 111 */ -for (i = 0; i < 5; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u9); /* 1001 */ -for (i = 0; i < 6; i++) { /* 000 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u5); /* 101 */ -for (i = 0; i < 10; i++) { /* 0000000 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &x3); /* 111 */ -for (i = 0; i < 4; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &x3); /* 111 */ -for (i = 0; i < 9; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &x8); /* 11111111 */ -for (i = 0; i < 5; i++) { /* 0 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u9); /* 1001 */ -for (i = 0; i < 6; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u11); /* 1011 */ -for (i = 0; i < 4; i++) { - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u13); /* 1101 */ -for (i = 0; i < 5; i++) { - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &x2); /* 11 */ -for (i = 0; i < 6; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u13); /* 1101 */ -for (i = 0; i < 10; i++) { /* 000000 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u13); /* 1101 */ -for (i = 0; i < 4; i++) { - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, &u9); /* 1001 */ -for (i = 0; i < 6; i++) { /* 00000 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(t, t, x); /* 1 */ -for (i = 0; i < 8; i++) { /* 00 */ - secp256k1_scalar_sqr(t, t); -} -secp256k1_scalar_mul(r, t, &x6); /* 111111 */ -} - -SECP256K1_INLINE static int secp256k1_scalar_is_even(const secp256k1_scalar *a) { - return !(a->d[0] & 1); -} -#endif - -static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *x) { -#if defined(USE_SCALAR_INV_BUILTIN) - secp256k1_scalar_inverse(r, x); -#elif defined(USE_SCALAR_INV_NUM) - unsigned char b[32]; - secp256k1_num n, m; - secp256k1_scalar t = *x; - secp256k1_scalar_get_b32(b, &t); - secp256k1_num_set_bin(&n, b, 32); - secp256k1_scalar_order_get_num(&m); - secp256k1_num_mod_inverse(&n, &n, &m); - secp256k1_num_get_bin(b, 32, &n); - secp256k1_scalar_set_b32(r, b, NULL); - /* Verify that the inverse was computed correctly, without GMP code. */ - secp256k1_scalar_mul(&t, &t, r); - CHECK(secp256k1_scalar_is_one(&t)); -#else -#error "Please select scalar inverse implementation" -#endif -} - -#ifdef USE_ENDOMORPHISM -#if defined(EXHAUSTIVE_TEST_ORDER) -/** - * Find k1 and k2 given k, such that k1 + k2 * lambda == k mod n; unlike in the - * full case we don't bother making k1 and k2 be small, we just want them to be - * nontrivial to get full test coverage for the exhaustive tests. We therefore - * (arbitrarily) set k2 = k + 5 and k1 = k - k2 * lambda. - */ -static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { - *r2 = (*a + 5) % EXHAUSTIVE_TEST_ORDER; - *r1 = (*a + (EXHAUSTIVE_TEST_ORDER - *r2) * EXHAUSTIVE_TEST_LAMBDA) % EXHAUSTIVE_TEST_ORDER; -} -#else -/** - * The Secp256k1 curve has an endomorphism, where lambda * (x, y) = (beta * x, y), where - * lambda is {0x53,0x63,0xad,0x4c,0xc0,0x5c,0x30,0xe0,0xa5,0x26,0x1c,0x02,0x88,0x12,0x64,0x5a, - * 0x12,0x2e,0x22,0xea,0x20,0x81,0x66,0x78,0xdf,0x02,0x96,0x7c,0x1b,0x23,0xbd,0x72} - * - * "Guide to Elliptic Curve Cryptography" (Hankerson, Menezes, Vanstone) gives an algorithm - * (algorithm 3.74) to find k1 and k2 given k, such that k1 + k2 * lambda == k mod n, and k1 - * and k2 have a small size. - * It relies on constants a1, b1, a2, b2. These constants for the value of lambda above are: - * - * - a1 = {0x30,0x86,0xd2,0x21,0xa7,0xd4,0x6b,0xcd,0xe8,0x6c,0x90,0xe4,0x92,0x84,0xeb,0x15} - * - b1 = -{0xe4,0x43,0x7e,0xd6,0x01,0x0e,0x88,0x28,0x6f,0x54,0x7f,0xa9,0x0a,0xbf,0xe4,0xc3} - * - a2 = {0x01,0x14,0xca,0x50,0xf7,0xa8,0xe2,0xf3,0xf6,0x57,0xc1,0x10,0x8d,0x9d,0x44,0xcf,0xd8} - * - b2 = {0x30,0x86,0xd2,0x21,0xa7,0xd4,0x6b,0xcd,0xe8,0x6c,0x90,0xe4,0x92,0x84,0xeb,0x15} - * - * The algorithm then computes c1 = round(b1 * k / n) and c2 = round(b2 * k / n), and gives - * k1 = k - (c1*a1 + c2*a2) and k2 = -(c1*b1 + c2*b2). Instead, we use modular arithmetic, and - * compute k1 as k - k2 * lambda, avoiding the need for constants a1 and a2. - * - * g1, g2 are precomputed constants used to replace division with a rounded multiplication - * when decomposing the scalar for an endomorphism-based point multiplication. - * - * The possibility of using precomputed estimates is mentioned in "Guide to Elliptic Curve - * Cryptography" (Hankerson, Menezes, Vanstone) in section 3.5. - * - * The derivation is described in the paper "Efficient Software Implementation of Public-Key - * Cryptography on Sensor Networks Using the MSP430X Microcontroller" (Gouvea, Oliveira, Lopez), - * Section 4.3 (here we use a somewhat higher-precision estimate): - * d = a1*b2 - b1*a2 - * g1 = round((2^272)*b2/d) - * g2 = round((2^272)*b1/d) - * - * (Note that 'd' is also equal to the curve order here because [a1,b1] and [a2,b2] are found - * as outputs of the Extended Euclidean Algorithm on inputs 'order' and 'lambda'). - * - * The function below splits a in r1 and r2, such that r1 + lambda * r2 == a (mod order). - */ - -static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { - secp256k1_scalar c1, c2; - static const secp256k1_scalar minus_lambda = SECP256K1_SCALAR_CONST( - 0xAC9C52B3UL, 0x3FA3CF1FUL, 0x5AD9E3FDUL, 0x77ED9BA4UL, - 0xA880B9FCUL, 0x8EC739C2UL, 0xE0CFC810UL, 0xB51283CFUL - ); - static const secp256k1_scalar minus_b1 = SECP256K1_SCALAR_CONST( - 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00000000UL, - 0xE4437ED6UL, 0x010E8828UL, 0x6F547FA9UL, 0x0ABFE4C3UL - ); - static const secp256k1_scalar minus_b2 = SECP256K1_SCALAR_CONST( - 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, - 0x8A280AC5UL, 0x0774346DUL, 0xD765CDA8UL, 0x3DB1562CUL - ); - static const secp256k1_scalar g1 = SECP256K1_SCALAR_CONST( - 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00003086UL, - 0xD221A7D4UL, 0x6BCDE86CUL, 0x90E49284UL, 0xEB153DABUL - ); - static const secp256k1_scalar g2 = SECP256K1_SCALAR_CONST( - 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x0000E443UL, - 0x7ED6010EUL, 0x88286F54UL, 0x7FA90ABFUL, 0xE4C42212UL - ); - VERIFY_CHECK(r1 != a); - VERIFY_CHECK(r2 != a); - /* these _var calls are constant time since the shift amount is constant */ - secp256k1_scalar_mul_shift_var(&c1, a, &g1, 272); - secp256k1_scalar_mul_shift_var(&c2, a, &g2, 272); - secp256k1_scalar_mul(&c1, &c1, &minus_b1); - secp256k1_scalar_mul(&c2, &c2, &minus_b2); - secp256k1_scalar_add(r2, &c1, &c2); - secp256k1_scalar_mul(r1, r2, &minus_lambda); - secp256k1_scalar_add(r1, r1, a); -} -#endif -#endif - -#endif /* SECP256K1_SCALAR_IMPL_H */ -#endif - From 56837e817483890243612313293ec76a809f2627 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:52:56 -1100 Subject: [PATCH 0861/1145] -xxx --- src/secp256k1/src/scalar_4x64_impl.h | 2 +- src/secp256k1/src/scalar_impl.h | 338 +++++++++++++++++++++++++++ 2 files changed, 339 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/src/scalar_4x64_impl.h b/src/secp256k1/src/scalar_4x64_impl.h index a12c80626..b1b62ac1f 100644 --- a/src/secp256k1/src/scalar_4x64_impl.h +++ b/src/secp256k1/src/scalar_4x64_impl.h @@ -2001,6 +2001,6 @@ static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2 #undef LE32 #endif /* SECP256K1_SCALAR_REPR_IMPL_H */ -xxx + #endif diff --git a/src/secp256k1/src/scalar_impl.h b/src/secp256k1/src/scalar_impl.h index dec541aed..d69a94880 100644 --- a/src/secp256k1/src/scalar_impl.h +++ b/src/secp256k1/src/scalar_impl.h @@ -1,3 +1,4 @@ +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** * Copyright (c) 2014 Pieter Wuille * @@ -333,3 +334,340 @@ static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar #endif /* SECP256K1_SCALAR_IMPL_H */ + +#else +/********************************************************************** + * Copyright (c) 2014 Pieter Wuille * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#ifndef SECP256K1_SCALAR_IMPL_H +#define SECP256K1_SCALAR_IMPL_H + +#include "group.h" +#include "scalar.h" + +#if defined HAVE_CONFIG_H +#include "libsecp256k1-config.h" +#endif + +#if defined(EXHAUSTIVE_TEST_ORDER) +#include "scalar_low_impl.h" +#elif defined(USE_SCALAR_4X64) +#include "scalar_4x64_impl.h" +#elif defined(USE_SCALAR_8X32) +#include "scalar_8x32_impl.h" +#else +#error "Please select scalar implementation" +#endif + +#ifndef USE_NUM_NONE +static void secp256k1_scalar_get_num(secp256k1_num *r, const secp256k1_scalar *a) { + unsigned char c[32]; + secp256k1_scalar_get_b32(c, a); + secp256k1_num_set_bin(r, c, 32); +} + +/** secp256k1 curve order, see secp256k1_ecdsa_const_order_as_fe in ecdsa_impl.h */ +static void secp256k1_scalar_order_get_num(secp256k1_num *r) { +#if defined(EXHAUSTIVE_TEST_ORDER) + static const unsigned char order[32] = { + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,EXHAUSTIVE_TEST_ORDER + }; +#else + static const unsigned char order[32] = { + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE, + 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B, + 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x41 + }; +#endif + secp256k1_num_set_bin(r, order, 32); +} +#endif + +static void secp256k1_scalar_inverse(secp256k1_scalar *r, const secp256k1_scalar *x) { +#if defined(EXHAUSTIVE_TEST_ORDER) + int i; + *r = 0; + for (i = 0; i < EXHAUSTIVE_TEST_ORDER; i++) + if ((i * *x) % EXHAUSTIVE_TEST_ORDER == 1) + *r = i; + /* If this VERIFY_CHECK triggers we were given a noninvertible scalar (and thus + * have a composite group order; fix it in exhaustive_tests.c). */ + VERIFY_CHECK(*r != 0); +} +#else +secp256k1_scalar *t; +int i; +/* First compute xN as x ^ (2^N - 1) for some values of N, + * and uM as x ^ M for some values of M. */ +secp256k1_scalar x2, x3, x6, x8, x14, x28, x56, x112, x126; +secp256k1_scalar u2, u5, u9, u11, u13; + +secp256k1_scalar_sqr(&u2, x); +secp256k1_scalar_mul(&x2, &u2, x); +secp256k1_scalar_mul(&u5, &u2, &x2); +secp256k1_scalar_mul(&x3, &u5, &u2); +secp256k1_scalar_mul(&u9, &x3, &u2); +secp256k1_scalar_mul(&u11, &u9, &u2); +secp256k1_scalar_mul(&u13, &u11, &u2); + +secp256k1_scalar_sqr(&x6, &u13); +secp256k1_scalar_sqr(&x6, &x6); +secp256k1_scalar_mul(&x6, &x6, &u11); + +secp256k1_scalar_sqr(&x8, &x6); +secp256k1_scalar_sqr(&x8, &x8); +secp256k1_scalar_mul(&x8, &x8, &x2); + +secp256k1_scalar_sqr(&x14, &x8); +for (i = 0; i < 5; i++) { + secp256k1_scalar_sqr(&x14, &x14); +} +secp256k1_scalar_mul(&x14, &x14, &x6); + +secp256k1_scalar_sqr(&x28, &x14); +for (i = 0; i < 13; i++) { + secp256k1_scalar_sqr(&x28, &x28); +} +secp256k1_scalar_mul(&x28, &x28, &x14); + +secp256k1_scalar_sqr(&x56, &x28); +for (i = 0; i < 27; i++) { + secp256k1_scalar_sqr(&x56, &x56); +} +secp256k1_scalar_mul(&x56, &x56, &x28); + +secp256k1_scalar_sqr(&x112, &x56); +for (i = 0; i < 55; i++) { + secp256k1_scalar_sqr(&x112, &x112); +} +secp256k1_scalar_mul(&x112, &x112, &x56); + +secp256k1_scalar_sqr(&x126, &x112); +for (i = 0; i < 13; i++) { + secp256k1_scalar_sqr(&x126, &x126); +} +secp256k1_scalar_mul(&x126, &x126, &x14); + +/* Then accumulate the final result (t starts at x126). */ +t = &x126; +for (i = 0; i < 3; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u11); /* 1011 */ +for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u11); /* 1011 */ +for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 5; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +for (i = 0; i < 3; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u9); /* 1001 */ +for (i = 0; i < 6; i++) { /* 000 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u5); /* 101 */ +for (i = 0; i < 10; i++) { /* 0000000 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 4; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x3); /* 111 */ +for (i = 0; i < 9; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x8); /* 11111111 */ +for (i = 0; i < 5; i++) { /* 0 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u9); /* 1001 */ +for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u11); /* 1011 */ +for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 5; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &x2); /* 11 */ +for (i = 0; i < 6; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 10; i++) { /* 000000 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u13); /* 1101 */ +for (i = 0; i < 4; i++) { + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, &u9); /* 1001 */ +for (i = 0; i < 6; i++) { /* 00000 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(t, t, x); /* 1 */ +for (i = 0; i < 8; i++) { /* 00 */ + secp256k1_scalar_sqr(t, t); +} +secp256k1_scalar_mul(r, t, &x6); /* 111111 */ +} + +SECP256K1_INLINE static int secp256k1_scalar_is_even(const secp256k1_scalar *a) { + return !(a->d[0] & 1); +} +#endif + +static void secp256k1_scalar_inverse_var(secp256k1_scalar *r, const secp256k1_scalar *x) { +#if defined(USE_SCALAR_INV_BUILTIN) + secp256k1_scalar_inverse(r, x); +#elif defined(USE_SCALAR_INV_NUM) + unsigned char b[32]; + secp256k1_num n, m; + secp256k1_scalar t = *x; + secp256k1_scalar_get_b32(b, &t); + secp256k1_num_set_bin(&n, b, 32); + secp256k1_scalar_order_get_num(&m); + secp256k1_num_mod_inverse(&n, &n, &m); + secp256k1_num_get_bin(b, 32, &n); + secp256k1_scalar_set_b32(r, b, NULL); + /* Verify that the inverse was computed correctly, without GMP code. */ + secp256k1_scalar_mul(&t, &t, r); + CHECK(secp256k1_scalar_is_one(&t)); +#else +#error "Please select scalar inverse implementation" +#endif +} + +#ifdef USE_ENDOMORPHISM +#if defined(EXHAUSTIVE_TEST_ORDER) +/** + * Find k1 and k2 given k, such that k1 + k2 * lambda == k mod n; unlike in the + * full case we don't bother making k1 and k2 be small, we just want them to be + * nontrivial to get full test coverage for the exhaustive tests. We therefore + * (arbitrarily) set k2 = k + 5 and k1 = k - k2 * lambda. + */ +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + *r2 = (*a + 5) % EXHAUSTIVE_TEST_ORDER; + *r1 = (*a + (EXHAUSTIVE_TEST_ORDER - *r2) * EXHAUSTIVE_TEST_LAMBDA) % EXHAUSTIVE_TEST_ORDER; +} +#else +/** + * The Secp256k1 curve has an endomorphism, where lambda * (x, y) = (beta * x, y), where + * lambda is {0x53,0x63,0xad,0x4c,0xc0,0x5c,0x30,0xe0,0xa5,0x26,0x1c,0x02,0x88,0x12,0x64,0x5a, + * 0x12,0x2e,0x22,0xea,0x20,0x81,0x66,0x78,0xdf,0x02,0x96,0x7c,0x1b,0x23,0xbd,0x72} + * + * "Guide to Elliptic Curve Cryptography" (Hankerson, Menezes, Vanstone) gives an algorithm + * (algorithm 3.74) to find k1 and k2 given k, such that k1 + k2 * lambda == k mod n, and k1 + * and k2 have a small size. + * It relies on constants a1, b1, a2, b2. These constants for the value of lambda above are: + * + * - a1 = {0x30,0x86,0xd2,0x21,0xa7,0xd4,0x6b,0xcd,0xe8,0x6c,0x90,0xe4,0x92,0x84,0xeb,0x15} + * - b1 = -{0xe4,0x43,0x7e,0xd6,0x01,0x0e,0x88,0x28,0x6f,0x54,0x7f,0xa9,0x0a,0xbf,0xe4,0xc3} + * - a2 = {0x01,0x14,0xca,0x50,0xf7,0xa8,0xe2,0xf3,0xf6,0x57,0xc1,0x10,0x8d,0x9d,0x44,0xcf,0xd8} + * - b2 = {0x30,0x86,0xd2,0x21,0xa7,0xd4,0x6b,0xcd,0xe8,0x6c,0x90,0xe4,0x92,0x84,0xeb,0x15} + * + * The algorithm then computes c1 = round(b1 * k / n) and c2 = round(b2 * k / n), and gives + * k1 = k - (c1*a1 + c2*a2) and k2 = -(c1*b1 + c2*b2). Instead, we use modular arithmetic, and + * compute k1 as k - k2 * lambda, avoiding the need for constants a1 and a2. + * + * g1, g2 are precomputed constants used to replace division with a rounded multiplication + * when decomposing the scalar for an endomorphism-based point multiplication. + * + * The possibility of using precomputed estimates is mentioned in "Guide to Elliptic Curve + * Cryptography" (Hankerson, Menezes, Vanstone) in section 3.5. + * + * The derivation is described in the paper "Efficient Software Implementation of Public-Key + * Cryptography on Sensor Networks Using the MSP430X Microcontroller" (Gouvea, Oliveira, Lopez), + * Section 4.3 (here we use a somewhat higher-precision estimate): + * d = a1*b2 - b1*a2 + * g1 = round((2^272)*b2/d) + * g2 = round((2^272)*b1/d) + * + * (Note that 'd' is also equal to the curve order here because [a1,b1] and [a2,b2] are found + * as outputs of the Extended Euclidean Algorithm on inputs 'order' and 'lambda'). + * + * The function below splits a in r1 and r2, such that r1 + lambda * r2 == a (mod order). + */ + +static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar *r2, const secp256k1_scalar *a) { + secp256k1_scalar c1, c2; + static const secp256k1_scalar minus_lambda = SECP256K1_SCALAR_CONST( + 0xAC9C52B3UL, 0x3FA3CF1FUL, 0x5AD9E3FDUL, 0x77ED9BA4UL, + 0xA880B9FCUL, 0x8EC739C2UL, 0xE0CFC810UL, 0xB51283CFUL + ); + static const secp256k1_scalar minus_b1 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00000000UL, + 0xE4437ED6UL, 0x010E8828UL, 0x6F547FA9UL, 0x0ABFE4C3UL + ); + static const secp256k1_scalar minus_b2 = SECP256K1_SCALAR_CONST( + 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFEUL, + 0x8A280AC5UL, 0x0774346DUL, 0xD765CDA8UL, 0x3DB1562CUL + ); + static const secp256k1_scalar g1 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x00003086UL, + 0xD221A7D4UL, 0x6BCDE86CUL, 0x90E49284UL, 0xEB153DABUL + ); + static const secp256k1_scalar g2 = SECP256K1_SCALAR_CONST( + 0x00000000UL, 0x00000000UL, 0x00000000UL, 0x0000E443UL, + 0x7ED6010EUL, 0x88286F54UL, 0x7FA90ABFUL, 0xE4C42212UL + ); + VERIFY_CHECK(r1 != a); + VERIFY_CHECK(r2 != a); + /* these _var calls are constant time since the shift amount is constant */ + secp256k1_scalar_mul_shift_var(&c1, a, &g1, 272); + secp256k1_scalar_mul_shift_var(&c2, a, &g2, 272); + secp256k1_scalar_mul(&c1, &c1, &minus_b1); + secp256k1_scalar_mul(&c2, &c2, &minus_b2); + secp256k1_scalar_add(r2, &c1, &c2); + secp256k1_scalar_mul(r1, r2, &minus_lambda); + secp256k1_scalar_add(r1, r1, a); +} +#endif +#endif + +#endif /* SECP256K1_SCALAR_IMPL_H */ +#endif + From 4a4e2f0bdd0c20eb653305cf91d1eee68fa5e341 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 19:54:03 +0100 Subject: [PATCH 0862/1145] add mingw32 ncurses this is a test with mingw32 crossbuilt ncurses release from the original ncurses dev --- src/cc/Makefile_rogue | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 45efdc803..ddaf392a3 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -9,6 +9,7 @@ DEBUGFLAGS = -O0 -D _DEBUG RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program $(info $(OS)) OS := $(shell uname -s) +DIR := ${CURDIR} $(info $(OS)) TARGET = librogue.so TARGET_DARWIN = librogue.dylib @@ -25,6 +26,9 @@ ifeq ($(OS),Darwin) cp $(TARGET_DARWIN) ../libcc.dylib else ifeq ($(HOST),x86_64-w64-mingw32) $(info WINDOWS) + wget -O ../../depends/x86_64-w64-mingw32/mingw64.zip https://invisible-island.net/datafiles/release/mingw32.zip + cd ../../depends/x86_64-w64-mingw32 && unzip mingw32.zip + cd $(DIR) $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses cp $(TARGET_WIN) ../libcc.dll #else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host From 380b4f61582ae61faaf8e3f15561703537f6d7ad Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 07:58:23 -1100 Subject: [PATCH 0863/1145] Sudoku est --- src/cc/sudoku.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index 7571d22e4..2d1b4477c 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -3049,3 +3049,8 @@ bool sudoku_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const return eval->Invalid("not enough vouts"); } +#include +#include +#include + + From 5448b0af3481609b8eaec481380b72fb9faca0b8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:02:35 -1100 Subject: [PATCH 0864/1145] Create includes --- src/secp256k1/include/secp256k1_musig.h | 432 +++++++++++++++++++ src/secp256k1/include/secp256k1_schnorrsig.h | 119 +++++ 2 files changed, 551 insertions(+) create mode 100644 src/secp256k1/include/secp256k1_musig.h create mode 100644 src/secp256k1/include/secp256k1_schnorrsig.h diff --git a/src/secp256k1/include/secp256k1_musig.h b/src/secp256k1/include/secp256k1_musig.h new file mode 100644 index 000000000..5796f677f --- /dev/null +++ b/src/secp256k1/include/secp256k1_musig.h @@ -0,0 +1,432 @@ +#ifndef SECP256K1_MUSIG_H +#define SECP256K1_MUSIG_H + +#include + +/** This module implements a Schnorr-based multi-signature scheme called MuSig + * (https://eprint.iacr.org/2018/068.pdf). There's an example C source file in the + * module's directory (src/modules/musig/example.c) that demonstrates how it can be + * used. + */ + +/** Data structure containing data related to a signing session resulting in a single + * signature. + * + * This structure is not opaque, but it MUST NOT be copied or read or written to it + * directly. A signer who is online throughout the whole process and can keep this + * structure in memory can use the provided API functions for a safe standard + * workflow. + * + * A signer who goes offline and needs to import/export or save/load this structure + * **must** take measures prevent replay attacks wherein an old state is loaded and + * the signing protocol forked from that point. One straightforward way to accomplish + * this is to attach the output of a monotonic non-resettable counter (hardware + * support is needed for this). Increment the counter before each output and + * encrypt+sign the entire package. If a package is deserialized with an old counter + * state or bad signature it should be rejected. + * + * Observe that an independent counter is needed for each concurrent signing session + * such a device is involved in. To avoid fragility, it is therefore recommended that + * any offline signer be usable for only a single session at once. + * + * Given access to such a counter, its output should be used as (or mixed into) the + * session ID to ensure uniqueness. + * + * Fields: + * combined_pk: MuSig-computed combined public key + * n_signers: Number of signers + * pk_hash: The 32-byte hash of the original public keys + * combined_nonce: Summed combined public nonce (undefined if `nonce_is_set` is false) + * nonce_is_set: Whether the above nonce has been set + * nonce_is_negated: If `nonce_is_set`, whether the above nonce was negated after + * summing the participants' nonces. Needed to ensure the nonce's y + * coordinate has a quadratic-residue y coordinate + * msg: The 32-byte message (hash) to be signed + * msg_is_set: Whether the above message has been set + * has_secret_data: Whether this session object has a signers' secret data; if this + * is `false`, it may still be used for verification purposes. + * seckey: If `has_secret_data`, the signer's secret key + * secnonce: If `has_secret_data`, the signer's secret nonce + * nonce: If `has_secret_data`, the signer's public nonce + * nonce_commitments_hash: If `has_secret_data` and `nonce_commitments_hash_is_set`, + * the hash of all signers' commitments + * nonce_commitments_hash_is_set: If `has_secret_data`, whether the + * nonce_commitments_hash has been set + */ +typedef struct { + secp256k1_pubkey combined_pk; + uint32_t n_signers; + unsigned char pk_hash[32]; + secp256k1_pubkey combined_nonce; + int nonce_is_set; + int nonce_is_negated; + unsigned char msg[32]; + int msg_is_set; + int has_secret_data; + unsigned char seckey[32]; + unsigned char secnonce[32]; + secp256k1_pubkey nonce; + unsigned char nonce_commitments_hash[32]; + int nonce_commitments_hash_is_set; +} secp256k1_musig_session; + +/** Data structure containing data on all signers in a single session. + * + * The workflow for this structure is as follows: + * + * 1. This structure is initialized with `musig_session_initialize` or + * `musig_session_initialize_verifier`, which set the `index` field, and zero out + * all other fields. The public session is initialized with the signers' + * nonce_commitments. + * + * 2. In a non-public session the nonce_commitments are set with the function + * `musig_get_public_nonce`, which also returns the signer's public nonce. This + * ensures that the public nonce is not exposed until all commitments have been + * received. + * + * 3. Each individual data struct should be updated with `musig_set_nonce` once a + * nonce is available. This function takes a single signer data struct rather than + * an array because it may fail in the case that the provided nonce does not match + * the commitment. In this case, it is desirable to identify the exact party whose + * nonce was inconsistent. + * + * Fields: + * present: indicates whether the signer's nonce is set + * index: index of the signer in the MuSig key aggregation + * nonce: public nonce, must be a valid curvepoint if the signer is `present` + * nonce_commitment: commitment to the nonce, or all-bits zero if a commitment + * has not yet been set + */ +typedef struct { + int present; + uint32_t index; + secp256k1_pubkey nonce; + unsigned char nonce_commitment[32]; +} secp256k1_musig_session_signer_data; + +/** Opaque data structure that holds a MuSig partial signature. + * + * The exact representation of data inside is implementation defined and not + * guaranteed to be portable between different platforms or versions. It is however + * guaranteed to be 32 bytes in size, and can be safely copied/moved. If you need + * to convert to a format suitable for storage, transmission, or comparison, use the + * `musig_partial_signature_serialize` and `musig_partial_signature_parse` + * functions. + */ +typedef struct { + unsigned char data[32]; +} secp256k1_musig_partial_signature; + +/** Computes a combined public key and the hash of the given public keys + * + * Returns: 1 if the public keys were successfully combined, 0 otherwise + * Args: ctx: pointer to a context object initialized for verification + * (cannot be NULL) + * scratch: scratch space used to compute the combined pubkey by + * multiexponentiation. If NULL, an inefficient algorithm is used. + * Out: combined_pk: the MuSig-combined public key (cannot be NULL) + * pk_hash32: if non-NULL, filled with the 32-byte hash of all input public + * keys in order to be used in `musig_session_initialize`. + * In: pubkeys: input array of public keys to combine. The order is important; + * a different order will result in a different combined public + * key (cannot be NULL) + * n_pubkeys: length of pubkeys array + */ +SECP256K1_API int secp256k1_musig_pubkey_combine( + const secp256k1_context* ctx, + secp256k1_scratch_space *scratch, + secp256k1_pubkey *combined_pk, + unsigned char *pk_hash32, + const secp256k1_pubkey *pubkeys, + size_t n_pubkeys +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(5); + +/** Initializes a signing session for a signer + * + * Returns: 1: session is successfully initialized + * 0: session could not be initialized: secret key or secret nonce overflow + * Args: ctx: pointer to a context object, initialized for signing (cannot + * be NULL) + * Out: session: the session structure to initialize (cannot be NULL) + * signers: an array of signers' data to be initialized. Array length must + * equal to `n_signers` (cannot be NULL) + * nonce_commitment32: filled with a 32-byte commitment to the generated nonce + * (cannot be NULL) + * In: session_id32: a *unique* 32-byte ID to assign to this session (cannot be + * NULL). If a non-unique session_id32 was given then a partial + * signature will LEAK THE SECRET KEY. + * msg32: the 32-byte message to be signed. Shouldn't be NULL unless you + * require sharing public nonces before the message is known + * because it reduces nonce misuse resistance. If NULL, must be + * set with `musig_session_set_msg` before signing and verifying. + * combined_pk: the combined public key of all signers (cannot be NULL) + * pk_hash32: the 32-byte hash of the signers' individual keys (cannot be + * NULL) + * n_signers: length of signers array. Number of signers participating in + * the MuSig. Must be greater than 0 and at most 2^32 - 1. + * my_index: index of this signer in the signers array + * seckey: the signer's 32-byte secret key (cannot be NULL) + */ +SECP256K1_API int secp256k1_musig_session_initialize( + const secp256k1_context* ctx, + secp256k1_musig_session *session, + secp256k1_musig_session_signer_data *signers, + unsigned char *nonce_commitment32, + const unsigned char *session_id32, + const unsigned char *msg32, + const secp256k1_pubkey *combined_pk, + const unsigned char *pk_hash32, + size_t n_signers, + size_t my_index, + const unsigned char *seckey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5) SECP256K1_ARG_NONNULL(7) SECP256K1_ARG_NONNULL(8) SECP256K1_ARG_NONNULL(11); + +/** Gets the signer's public nonce given a list of all signers' data with commitments + * + * Returns: 1: public nonce is written in nonce + * 0: signer data is missing commitments or session isn't initialized + * for signing + * Args: ctx: pointer to a context object (cannot be NULL) + * session: the signing session to get the nonce from (cannot be NULL) + * signers: an array of signers' data initialized with + * `musig_session_initialize`. Array length must equal to + * `n_commitments` (cannot be NULL) + * Out: nonce: the nonce (cannot be NULL) + * In: commitments: array of 32-byte nonce commitments (cannot be NULL) + * n_commitments: the length of commitments and signers array. Must be the total + * number of signers participating in the MuSig. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_get_public_nonce( + const secp256k1_context* ctx, + secp256k1_musig_session *session, + secp256k1_musig_session_signer_data *signers, + secp256k1_pubkey *nonce, + const unsigned char *const *commitments, + size_t n_commitments +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5); + +/** Initializes a verifier session that can be used for verifying nonce commitments + * and partial signatures. It does not have secret key material and therefore can not + * be used to create signatures. + * + * Returns: 1 when session is successfully initialized, 0 otherwise + * Args: ctx: pointer to a context object (cannot be NULL) + * Out: session: the session structure to initialize (cannot be NULL) + * signers: an array of signers' data to be initialized. Array length must + * equal to `n_signers`(cannot be NULL) + * In: msg32: the 32-byte message to be signed If NULL, must be set with + * `musig_session_set_msg` before using the session for verifying + * partial signatures. + * combined_pk: the combined public key of all signers (cannot be NULL) + * pk_hash32: the 32-byte hash of the signers' individual keys (cannot be NULL) + * commitments: array of 32-byte nonce commitments. Array length must equal to + * `n_signers` (cannot be NULL) + * n_signers: length of signers and commitments array. Number of signers + * participating in the MuSig. Must be greater than 0 and at most + * 2^32 - 1. + */ +SECP256K1_API int secp256k1_musig_session_initialize_verifier( + const secp256k1_context* ctx, + secp256k1_musig_session *session, + secp256k1_musig_session_signer_data *signers, + const unsigned char *msg32, + const secp256k1_pubkey *combined_pk, + const unsigned char *pk_hash32, + const unsigned char *const *commitments, + size_t n_signers +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(5) SECP256K1_ARG_NONNULL(6) SECP256K1_ARG_NONNULL(7); + +/** Checks a signer's public nonce against a commitment to said nonce, and update + * data structure if they match + * + * Returns: 1: commitment was valid, data structure updated + * 0: commitment was invalid, nothing happened + * Args: ctx: pointer to a context object (cannot be NULL) + * signer: pointer to the signer data to update (cannot be NULL). Must have + * been used with `musig_session_get_public_nonce` or initialized + * with `musig_session_initialize_verifier`. + * In: nonce: signer's alleged public nonce (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_set_nonce( + const secp256k1_context* ctx, + secp256k1_musig_session_signer_data *signer, + const secp256k1_pubkey *nonce +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Updates a session with the combined public nonce of all signers. The combined + * public nonce is the sum of every signer's public nonce. + * + * Returns: 1: nonces are successfully combined + * 0: a signer's nonce is missing + * Args: ctx: pointer to a context object (cannot be NULL) + * session: session to update with the combined public nonce (cannot be + * NULL) + * signers: an array of signers' data, which must have had public nonces + * set with `musig_set_nonce`. Array length must equal to `n_signers` + * (cannot be NULL) + * n_signers: the length of the signers array. Must be the total number of + * signers participating in the MuSig. + * Out: nonce_is_negated: a pointer to an integer that indicates if the combined + * public nonce had to be negated. + * adaptor: point to add to the combined public nonce. If NULL, nothing is + * added to the combined nonce. + */ +SECP256K1_API int secp256k1_musig_session_combine_nonces( + const secp256k1_context* ctx, + secp256k1_musig_session *session, + const secp256k1_musig_session_signer_data *signers, + size_t n_signers, + int *nonce_is_negated, + const secp256k1_pubkey *adaptor +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4); + +/** Sets the message of a session if previously unset + * + * Returns 1 if the message was not set yet and is now successfully set + * 0 otherwise + * Args: ctx: pointer to a context object (cannot be NULL) + * session: the session structure to update with the message (cannot be NULL) + * In: msg32: the 32-byte message to be signed (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_set_msg( + const secp256k1_context* ctx, + secp256k1_musig_session *session, + const unsigned char *msg32 +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Serialize a MuSig partial signature or adaptor signature + * + * Returns: 1 when the signature could be serialized, 0 otherwise + * Args: ctx: a secp256k1 context object + * Out: out32: pointer to a 32-byte array to store the serialized signature + * In: sig: pointer to the signature + */ +SECP256K1_API int secp256k1_musig_partial_signature_serialize( + const secp256k1_context* ctx, + unsigned char *out32, + const secp256k1_musig_partial_signature* sig +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Parse and verify a MuSig partial signature. + * + * Returns: 1 when the signature could be parsed, 0 otherwise. + * Args: ctx: a secp256k1 context object + * Out: sig: pointer to a signature object + * In: in32: pointer to the 32-byte signature to be parsed + * + * After the call, sig will always be initialized. If parsing failed or the + * encoded numbers are out of range, signature verification with it is + * guaranteed to fail for every message and public key. + */ +SECP256K1_API int secp256k1_musig_partial_signature_parse( + const secp256k1_context* ctx, + secp256k1_musig_partial_signature* sig, + const unsigned char *in32 +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Produces a partial signature + * + * Returns: 1: partial signature constructed + * 0: session in incorrect or inconsistent state + * Args: ctx: pointer to a context object (cannot be NULL) + * session: active signing session for which the combined nonce has been + * computed (cannot be NULL) + * Out: partial_sig: partial signature (cannot be NULL) + */ +SECP256K1_API int secp256k1_musig_partial_sign( + const secp256k1_context* ctx, + const secp256k1_musig_session *session, + secp256k1_musig_partial_signature *partial_sig +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Checks that an individual partial signature verifies + * + * This function is essential when using protocols with adaptor signatures. + * However, it is not essential for regular MuSig's, in the sense that if any + * partial signatures does not verify, the full signature will also not verify, so the + * problem will be caught. But this function allows determining the specific party + * who produced an invalid signature, so that signing can be restarted without them. + * + * Returns: 1: partial signature verifies + * 0: invalid signature or bad data + * Args: ctx: pointer to a context object (cannot be NULL) + * session: active session for which the combined nonce has been computed + * (cannot be NULL) + * signer: data for the signer who produced this signature (cannot be NULL) + * In: partial_sig: signature to verify (cannot be NULL) + * pubkey: public key of the signer who produced the signature (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_verify( + const secp256k1_context* ctx, + const secp256k1_musig_session *session, + const secp256k1_musig_session_signer_data *signer, + const secp256k1_musig_partial_signature *partial_sig, + const secp256k1_pubkey *pubkey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5); + +/** Combines partial signatures + * + * Returns: 1: all partial signatures have values in range. Does NOT mean the + * resulting signature verifies. + * 0: some partial signature had s/r out of range + * Args: ctx: pointer to a context object (cannot be NULL) + * session: initialized session for which the combined nonce has been + * computed (cannot be NULL) + * Out: sig: complete signature (cannot be NULL) + * In: partial_sigs: array of partial signatures to combine (cannot be NULL) + * n_sigs: number of signatures in the partial_sigs array + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_combine( + const secp256k1_context* ctx, + const secp256k1_musig_session *session, + secp256k1_schnorrsig *sig, + const secp256k1_musig_partial_signature *partial_sigs, + size_t n_sigs +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Converts a partial signature to an adaptor signature by adding a given secret + * adaptor. + * + * Returns: 1: signature and secret adaptor contained valid values + * 0: otherwise + * Args: ctx: pointer to a context object (cannot be NULL) + * Out: adaptor_sig: adaptor signature to produce (cannot be NULL) + * In: partial_sig: partial signature to tweak with secret adaptor (cannot be NULL) + * sec_adaptor32: 32-byte secret adaptor to add to the partial signature (cannot + * be NULL) + * nonce_is_negated: the `nonce_is_negated` output of `musig_session_combine_nonces` + */ +SECP256K1_API int secp256k1_musig_partial_sig_adapt( + const secp256k1_context* ctx, + secp256k1_musig_partial_signature *adaptor_sig, + const secp256k1_musig_partial_signature *partial_sig, + const unsigned char *sec_adaptor32, + int nonce_is_negated +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Extracts a secret adaptor from a MuSig, given all parties' partial + * signatures. This function will not fail unless given grossly invalid data; if it + * is merely given signatures that do not verify, the returned value will be + * nonsense. It is therefore important that all data be verified at earlier steps of + * any protocol that uses this function. + * + * Returns: 1: signatures contained valid data such that an adaptor could be extracted + * 0: otherwise + * Args: ctx: pointer to a context object (cannot be NULL) + * Out:sec_adaptor32: 32-byte secret adaptor (cannot be NULL) + * In: sig: complete 2-of-2 signature (cannot be NULL) + * partial_sigs: array of partial signatures (cannot be NULL) + * n_partial_sigs: number of elements in partial_sigs array + * nonce_is_negated: the `nonce_is_negated` output of `musig_session_combine_nonces` + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_extract_secret_adaptor( + const secp256k1_context* ctx, + unsigned char *sec_adaptor32, + const secp256k1_schnorrsig *sig, + const secp256k1_musig_partial_signature *partial_sigs, + size_t n_partial_sigs, + int nonce_is_negated +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +#endif + diff --git a/src/secp256k1/include/secp256k1_schnorrsig.h b/src/secp256k1/include/secp256k1_schnorrsig.h new file mode 100644 index 000000000..9dea16653 --- /dev/null +++ b/src/secp256k1/include/secp256k1_schnorrsig.h @@ -0,0 +1,119 @@ +#ifndef SECP256K1_SCHNORRSIG_H +#define SECP256K1_SCHNORRSIG_H + +/** This module implements a variant of Schnorr signatures compliant with + * BIP-schnorr + * (https://github.com/sipa/bips/blob/bip-schnorr/bip-schnorr.mediawiki). + */ + +/** Opaque data structure that holds a parsed Schnorr signature. + * + * The exact representation of data inside is implementation defined and not + * guaranteed to be portable between different platforms or versions. It is + * however guaranteed to be 64 bytes in size, and can be safely copied/moved. + * If you need to convert to a format suitable for storage, transmission, or + * comparison, use the `secp256k1_schnorrsig_serialize` and + * `secp256k1_schnorrsig_parse` functions. + */ +typedef struct { + unsigned char data[64]; +} secp256k1_schnorrsig; + +/** Serialize a Schnorr signature. + * + * Returns: 1 + * Args: ctx: a secp256k1 context object + * Out: out64: pointer to a 64-byte array to store the serialized signature + * In: sig: pointer to the signature + * + * See secp256k1_schnorrsig_parse for details about the encoding. + */ +SECP256K1_API int secp256k1_schnorrsig_serialize( + const secp256k1_context* ctx, + unsigned char *out64, + const secp256k1_schnorrsig* sig +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Parse a Schnorr signature. + * + * Returns: 1 when the signature could be parsed, 0 otherwise. + * Args: ctx: a secp256k1 context object + * Out: sig: pointer to a signature object + * In: in64: pointer to the 64-byte signature to be parsed + * + * The signature is serialized in the form R||s, where R is a 32-byte public + * key (x-coordinate only; the y-coordinate is considered to be the unique + * y-coordinate satisfying the curve equation that is a quadratic residue) + * and s is a 32-byte big-endian scalar. + * + * After the call, sig will always be initialized. If parsing failed or the + * encoded numbers are out of range, signature validation with it is + * guaranteed to fail for every message and public key. + */ +SECP256K1_API int secp256k1_schnorrsig_parse( + const secp256k1_context* ctx, + secp256k1_schnorrsig* sig, + const unsigned char *in64 +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); + +/** Create a Schnorr signature. + * + * Returns 1 on success, 0 on failure. + * Args: ctx: pointer to a context object, initialized for signing (cannot be NULL) + * Out: sig: pointer to the returned signature (cannot be NULL) + * nonce_is_negated: a pointer to an integer indicates if signing algorithm negated the + * nonce (can be NULL) + * In: msg32: the 32-byte message hash being signed (cannot be NULL) + * seckey: pointer to a 32-byte secret key (cannot be NULL) + * noncefp: pointer to a nonce generation function. If NULL, secp256k1_nonce_function_bipschnorr is used + * ndata: pointer to arbitrary data used by the nonce generation function (can be NULL) + */ +SECP256K1_API int secp256k1_schnorrsig_sign( + const secp256k1_context* ctx, + secp256k1_schnorrsig *sig, + int *nonce_is_negated, + const unsigned char *msg32, + const unsigned char *seckey, + secp256k1_nonce_function noncefp, + void *ndata +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5); + +/** Verify a Schnorr signature. + * + * Returns: 1: correct signature + * 0: incorrect or unparseable signature + * Args: ctx: a secp256k1 context object, initialized for verification. + * In: sig: the signature being verified (cannot be NULL) + * msg32: the 32-byte message hash being verified (cannot be NULL) + * pubkey: pointer to a public key to verify with (cannot be NULL) + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_schnorrsig_verify( + const secp256k1_context* ctx, + const secp256k1_schnorrsig *sig, + const unsigned char *msg32, + const secp256k1_pubkey *pubkey +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); + +/** Verifies a set of Schnorr signatures. + * + * Returns 1 if all succeeded, 0 otherwise. In particular, returns 1 if n_sigs is 0. + * + * Args: ctx: a secp256k1 context object, initialized for verification. + * scratch: scratch space used for the multiexponentiation + * In: sig: array of signatures, or NULL if there are no signatures + * msg32: array of messages, or NULL if there are no signatures + * pk: array of public keys, or NULL if there are no signatures + * n_sigs: number of signatures in above arrays. Must be smaller than + * 2^31 and smaller than half the maximum size_t value. Must be 0 + * if above arrays are NULL. + */ +SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_schnorrsig_verify_batch( + const secp256k1_context* ctx, + secp256k1_scratch_space *scratch, + const secp256k1_schnorrsig *const *sig, + const unsigned char *const *msg32, + const secp256k1_pubkey *const *pk, + size_t n_sigs +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2); +#endif + From 7d570282f5ffef0de82e56e9ed39682f8d196395 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:03:24 -1100 Subject: [PATCH 0865/1145] Makecclib --- src/cc/makecclib | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makecclib b/src/cc/makecclib index ea44acdae..832cf1e96 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1,2 +1,2 @@ #!/bin/sh -gcc -std=c++11 -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp +gcc -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp From 839e7791512d49d9ce0bfe8cbe84ae5c491aca20 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:06:31 -1100 Subject: [PATCH 0866/1145] Scratch --- src/secp256k1/include/secp256k1.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/secp256k1/include/secp256k1.h b/src/secp256k1/include/secp256k1.h index 3e9c098d1..7dcdd7d0b 100644 --- a/src/secp256k1/include/secp256k1.h +++ b/src/secp256k1/include/secp256k1.h @@ -42,6 +42,19 @@ extern "C" { */ typedef struct secp256k1_context_struct secp256k1_context; +/** Opaque data structure that holds rewriteable "scratch space" + * + * The purpose of this structure is to replace dynamic memory allocations, + * because we target architectures where this may not be available. It is + * essentially a resizable (within specified parameters) block of bytes, + * which is initially created either by memory allocation or TODO as a pointer + * into some fixed rewritable space. + * + * Unlike the context object, this cannot safely be shared between threads + * without additional synchronization logic. + */ +typedef struct secp256k1_scratch_space_struct secp256k1_scratch_space; + /** Opaque data structure that holds a parsed and valid public key. * * The exact representation of data inside is implementation defined and not From ae5ec5372580029458a6cb16601f447f7ecc890e Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:12:19 -1100 Subject: [PATCH 0867/1145] 4 -> 3 --- src/secp256k1/include/secp256k1_musig.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/include/secp256k1_musig.h b/src/secp256k1/include/secp256k1_musig.h index 5796f677f..7e974e36d 100644 --- a/src/secp256k1/include/secp256k1_musig.h +++ b/src/secp256k1/include/secp256k1_musig.h @@ -278,7 +278,7 @@ SECP256K1_API int secp256k1_musig_session_combine_nonces( size_t n_signers, int *nonce_is_negated, const secp256k1_pubkey *adaptor -) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4); +) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); /** Sets the message of a session if previously unset * From a29516ed1e6ceef22cd6041a509e0c81fc076f77 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 20:26:24 +0100 Subject: [PATCH 0868/1145] winify rogue makefile --- src/cc/Makefile_rogue | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index ddaf392a3..0122764c1 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -27,8 +27,8 @@ ifeq ($(OS),Darwin) else ifeq ($(HOST),x86_64-w64-mingw32) $(info WINDOWS) wget -O ../../depends/x86_64-w64-mingw32/mingw64.zip https://invisible-island.net/datafiles/release/mingw32.zip - cd ../../depends/x86_64-w64-mingw32 && unzip mingw32.zip - cd $(DIR) + cd ../../depends/x86_64-w64-mingw32 && unzip mingw32.zip + cd $(DIR) $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses cp $(TARGET_WIN) ../libcc.dll #else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host From 653da2b728bafb32d59fb24ad08f706acafec66e Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:48:59 -1100 Subject: [PATCH 0869/1145] main.$(O) --- src/cc/rogue/Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index a6d410b23..e6cfde467 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -130,7 +130,7 @@ MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c $(PROGRAM): $(HDRS) $(OBJS) - $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2) -lcurses; $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2) -lcurses; $(CC) $(CFLAGS) $(LDFLAGS) main.$(O) $(OBJS) $(LIBS) -o $@ clean: $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so From 34a3ff37050d47cd8e1d1e5f27baf79471b7a37a Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:50:25 -1100 Subject: [PATCH 0870/1145] Revert --- src/cc/rogue/Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index e6cfde467..a6d410b23 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -130,7 +130,7 @@ MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c $(PROGRAM): $(HDRS) $(OBJS) - $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2) -lcurses; $(CC) $(CFLAGS) $(LDFLAGS) main.$(O) $(OBJS) $(LIBS) -o $@ + $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2) -lcurses; $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ clean: $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so From 7649ce3e67c4d5429599b6e19d14057f307d47dd Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 20:56:28 +0100 Subject: [PATCH 0871/1145] fix arch --- src/cc/Makefile_rogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 0122764c1..4697cd8f7 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -26,7 +26,7 @@ ifeq ($(OS),Darwin) cp $(TARGET_DARWIN) ../libcc.dylib else ifeq ($(HOST),x86_64-w64-mingw32) $(info WINDOWS) - wget -O ../../depends/x86_64-w64-mingw32/mingw64.zip https://invisible-island.net/datafiles/release/mingw32.zip + wget -O ../../depends/x86_64-w64-mingw32/mingw32.zip https://invisible-island.net/datafiles/release/mingw32.zip cd ../../depends/x86_64-w64-mingw32 && unzip mingw32.zip cd $(DIR) $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses From f2eb58fa7910448e6f3505f7d4a8043ca98562d0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 08:58:17 -1100 Subject: [PATCH 0872/1145] Remove -lncurses --- src/Makefile.am | 4 ++-- src/cc/Makefile_rogue | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index 53331ee8f..395ff0352 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -574,9 +574,9 @@ komodod_LDADD += \ $(LIBZCASH_LIBS) if TARGET_DARWIN -komodod_LDADD += libcc.dylib # -lncurses +komodod_LDADD += libcc.dylib else -komodod_LDADD += libcc.so # -lncurses +komodod_LDADD += libcc.so endif diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 45efdc803..a7c60f724 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -21,16 +21,16 @@ all: $(TARGET) $(TARGET): $(SOURCES) $(info Building cclib to src/) ifeq ($(OS),Darwin) - $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET_DARWIN) -c $(SOURCES) -lncurses + $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET_DARWIN) -c $(SOURCES) cp $(TARGET_DARWIN) ../libcc.dylib else ifeq ($(HOST),x86_64-w64-mingw32) $(info WINDOWS) - $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses + $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) cp $(TARGET_WIN) ../libcc.dll #else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host else $(info LINUX) - $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) -lncurses + $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) cp $(TARGET) ../libcc.so endif From 30cab829bdc6739254527ca315e7803a55cf224c Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 09:00:53 -1100 Subject: [PATCH 0873/1145] -lcurses --- src/cc/rogue/Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index a6d410b23..8e6f7ca24 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -130,7 +130,7 @@ MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c $(PROGRAM): $(HDRS) $(OBJS) - $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2) -lcurses; $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ clean: $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so From 5ff8a7c25caaaa3e56ac760af7cf3a62986e8985 Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 09:02:36 -1100 Subject: [PATCH 0874/1145] Add cursesd.c --- src/cc/rogue/Makefile.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index 8e6f7ca24..d40c25826 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -111,7 +111,7 @@ CFILES = vers.c extern.c armor.c chase.c command.c daemon.c \ main.c mdport.c misc.c monsters.c move.c new_level.c \ options.c pack.c passages.c potions.c rings.c rip.c \ rooms.c save.c scrolls.c state.c sticks.c things.c \ - weapons.c wizard.c xcrypt.c + weapons.c wizard.c xcrypt.c cursesd.c MISC_C = findpw.c scedit.c scmisc.c DOCSRC = rogue.me.in rogue.6.in rogue.doc.in rogue.html.in rogue.cat.in DOCS = $(PROGRAM).doc $(PROGRAM).html $(PROGRAM).cat $(PROGRAM).me \ @@ -130,7 +130,7 @@ MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c $(PROGRAM): $(HDRS) $(OBJS) - $(RM) rogue.so ; $(CC) -shared -o rogue.so $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + $(RM) rogue.so ; $(CC) -shared -o rogue.so cursesd.o $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ clean: $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so From 08bbf62d12366a5e8e0a882d5b3f8b4f19fd699d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 09:04:10 -1100 Subject: [PATCH 0875/1145] .0 -> .c --- src/cc/rogue/Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index d40c25826..40044b082 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -130,7 +130,7 @@ MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c $(PROGRAM): $(HDRS) $(OBJS) - $(RM) rogue.so ; $(CC) -shared -o rogue.so cursesd.o $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + $(RM) rogue.so ; $(CC) -shared -o rogue.so cursesd.c $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ clean: $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so From e027678ec2eae6e1ecab6886057e9abab9835b9c Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 09:05:31 -1100 Subject: [PATCH 0876/1145] Make just rogue --- src/cc/rogue/Makefile.in | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index 40044b082..c53ece6ac 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -111,7 +111,7 @@ CFILES = vers.c extern.c armor.c chase.c command.c daemon.c \ main.c mdport.c misc.c monsters.c move.c new_level.c \ options.c pack.c passages.c potions.c rings.c rip.c \ rooms.c save.c scrolls.c state.c sticks.c things.c \ - weapons.c wizard.c xcrypt.c cursesd.c + weapons.c wizard.c xcrypt.c MISC_C = findpw.c scedit.c scmisc.c DOCSRC = rogue.me.in rogue.6.in rogue.doc.in rogue.html.in rogue.cat.in DOCS = $(PROGRAM).doc $(PROGRAM).html $(PROGRAM).cat $(PROGRAM).me \ @@ -128,9 +128,11 @@ MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ .c.o: $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c - + +#$(RM) rogue.so ; $(CC) -shared -o rogue.so cursesd.c $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + $(PROGRAM): $(HDRS) $(OBJS) - $(RM) rogue.so ; $(CC) -shared -o rogue.so cursesd.c $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ clean: $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so From 6b3ba45960bdae80b7dc700425b6b48de1bbec8f Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 21:26:58 +0100 Subject: [PATCH 0877/1145] include ncursesw --- src/cc/Makefile_rogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 4697cd8f7..330854bea 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -4,7 +4,7 @@ CC_DARWIN = g++-6 CC_WIN = x86_64-w64-mingw32-gcc-posix CFLAGS_DARWIN = -DBUILD_ROGUE -std=c++11 -arch x86_64 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -Wl,-undefined -Wl,dynamic_lookup -Wno-write-strings -shared -dynamiclib CFLAGS = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/x86_64-w64-mingw32/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared +CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/x86_64-w64-mingw32/include -I../../depends/x86_64-w64-mingw32/include/ncursesw -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared DEBUGFLAGS = -O0 -D _DEBUG RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program $(info $(OS)) From ad7631f4cee2f57704a393e008478d76c8181290 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 22:23:10 +0100 Subject: [PATCH 0878/1145] test --- src/Makefile.am | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index 53331ee8f..eee289704 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -575,11 +575,13 @@ komodod_LDADD += \ if TARGET_DARWIN komodod_LDADD += libcc.dylib # -lncurses +endif +if TARGET_WINDOWS +komodod_LDADD += libcc.dll else komodod_LDADD += libcc.so # -lncurses endif - if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) endif From fb462bf7de0248b4c4ce6b17f7faba60891b8a14 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 22:53:56 +0100 Subject: [PATCH 0879/1145] update boost --- depends/packages/boost.mk | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 8f3fd1b1c..7a0439ba7 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -1,9 +1,8 @@ - package=boost -$(package)_version=1_66_0 -$(package)_download_path=https://dl.bintray.com/boostorg/release/1.66.0/source +$(package)_version=1_69_0 +$(package)_download_path=https://dl.bintray.com/boostorg/release/1.69.0/source $(package)_file_name=$(package)_$($(package)_version).tar.bz2 -$(package)_sha256_hash=5721818253e6a0989583192f96782c4a98eb6204965316df9f5ad75819225ca9 +$(package)_sha256_hash=8f32d4617390d1c2d16f26a27ab60d97807b35440d45891fa340fc2648b04406 define $(package)_set_vars $(package)_config_opts_release=variant=release From 85071d5d9cf12142fca556246f7e571e1f0df719 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 22:54:44 +0100 Subject: [PATCH 0880/1145] update libsodium --- depends/packages/libsodium.mk | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/depends/packages/libsodium.mk b/depends/packages/libsodium.mk index 76f0d9a28..179ebe86c 100644 --- a/depends/packages/libsodium.mk +++ b/depends/packages/libsodium.mk @@ -1,12 +1,3 @@ -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 $(package)_version=1.0.15 $(package)_download_path=https://download.libsodium.org/libsodium/releases/old @@ -14,6 +5,13 @@ $(package)_file_name=$(package)-$($(package)_version).tar.gz $(package)_sha256_hash=fb6a9e879a2f674592e4328c5d9f79f082405ee4bb05cb6e679b90afe9e178f4 $(package)_dependencies= $(package)_config_opts= + +ifeq ($(build_os),darwin) +define $(package)_set_vars + $(package)_build_env=MACOSX_DEPLOYMENT_TARGET="10.11" + $(package)_cc=clang + $(package)_cxx=clang++ +endef endif define $(package)_preprocess_cmds From d257da66dce007e5405f2639b55a9559844b1b3a Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 22:55:14 +0100 Subject: [PATCH 0881/1145] update openssl --- depends/packages/openssl.mk | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/depends/packages/openssl.mk b/depends/packages/openssl.mk index dec8ecef6..e378088e6 100644 --- a/depends/packages/openssl.mk +++ b/depends/packages/openssl.mk @@ -1,8 +1,8 @@ package=openssl -$(package)_version=1.1.0h +$(package)_version=1.1.1a $(package)_download_path=https://www.openssl.org/source $(package)_file_name=$(package)-$($(package)_version).tar.gz -$(package)_sha256_hash=5835626cde9e99656585fc7aaa2302a73a7e1340bf8c14fd635a62c66802a517 +$(package)_sha256_hash=fc20130f8b7cbd2fb918b2f14e2f429e109c31ddd0fb38fc5d71d9ffed3f9f41 define $(package)_set_vars $(package)_config_env=AR="$($(package)_ar)" RANLIB="$($(package)_ranlib)" CC="$($(package)_cc)" @@ -92,7 +92,7 @@ $(package)_config_opts_i686_mingw32=mingw endef define $(package)_preprocess_cmds - sed -i.old "/define DATE/d" util/mkbuildinf.pl && \ + sed -i.old 's/built on: $date/built on: not available/' util/mkbuildinf.pl && \ sed -i.old "s|\"engines\", \"apps\", \"test\"|\"engines\"|" Configure endef From 9c3581f568b78714ee8605bb11aa1d1b53ce542f Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 22:55:49 +0100 Subject: [PATCH 0882/1145] update rust --- depends/packages/rust.mk | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/depends/packages/rust.mk b/depends/packages/rust.mk index a08ac2747..9cfb95054 100644 --- a/depends/packages/rust.mk +++ b/depends/packages/rust.mk @@ -1,13 +1,13 @@ package=rust -$(package)_version=1.28.0 +$(package)_version=1.32.0 $(package)_download_path=https://static.rust-lang.org/dist $(package)_file_name_linux=rust-$($(package)_version)-x86_64-unknown-linux-gnu.tar.gz -$(package)_sha256_hash_linux=2a1390340db1d24a9498036884e6b2748e9b4b057fc5219694e298bdaa37b810 +$(package)_sha256_hash_linux=e024698320d76b74daf0e6e71be3681a1e7923122e3ebd03673fcac3ecc23810 $(package)_file_name_darwin=rust-$($(package)_version)-x86_64-apple-darwin.tar.gz -$(package)_sha256_hash_darwin=5d7a70ed4701fe9410041c1eea025c95cad97e5b3d8acc46426f9ac4f9f02393 +$(package)_sha256_hash_darwin=f0dfba507192f9b5c330b5984ba71d57d434475f3d62bd44a39201e36fa76304 $(package)_file_name_mingw32=rust-$($(package)_version)-x86_64-pc-windows-gnu.tar.gz -$(package)_sha256_hash_mingw32=55c07426f791c51c8a2b6934b35784175c4abb4e03f123f3e847109c4dc1ad8b +$(package)_sha256_hash_mingw32=358e1435347c67dbf33aa9cad6fe501a833d6633ed5d5aa1863d5dffa0349be9 ifeq ($(build_os),darwin) $(package)_file_name=$($(package)_file_name_darwin) From 4ad570e237003e559e64e459e64ebd42c3ffeeaa Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 23:16:22 +0100 Subject: [PATCH 0883/1145] remove ncurses remove -lncurses flag from Makefile_rogue --- src/cc/Makefile_rogue | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/cc/Makefile_rogue b/src/cc/Makefile_rogue index 330854bea..a7c60f724 100644 --- a/src/cc/Makefile_rogue +++ b/src/cc/Makefile_rogue @@ -4,12 +4,11 @@ CC_DARWIN = g++-6 CC_WIN = x86_64-w64-mingw32-gcc-posix CFLAGS_DARWIN = -DBUILD_ROGUE -std=c++11 -arch x86_64 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -Wl,-undefined -Wl,dynamic_lookup -Wno-write-strings -shared -dynamiclib CFLAGS = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/$(shell echo `../..//depends/config.guess`/include) -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/x86_64-w64-mingw32/include -I../../depends/x86_64-w64-mingw32/include/ncursesw -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared +CFLAGS_WIN = -Wno-write-strings -DBUILD_ROGUE -std=c++11 -I../../depends/x86_64-w64-mingw32/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared DEBUGFLAGS = -O0 -D _DEBUG RELEASEFLAGS = -O2 -D NDEBUG -combine -fwhole-program $(info $(OS)) OS := $(shell uname -s) -DIR := ${CURDIR} $(info $(OS)) TARGET = librogue.so TARGET_DARWIN = librogue.dylib @@ -22,19 +21,16 @@ all: $(TARGET) $(TARGET): $(SOURCES) $(info Building cclib to src/) ifeq ($(OS),Darwin) - $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET_DARWIN) -c $(SOURCES) -lncurses + $(CC_DARWIN) $(CFLAGS_DARWIN) $(DEBUGFLAGS) -o $(TARGET_DARWIN) -c $(SOURCES) cp $(TARGET_DARWIN) ../libcc.dylib else ifeq ($(HOST),x86_64-w64-mingw32) $(info WINDOWS) - wget -O ../../depends/x86_64-w64-mingw32/mingw32.zip https://invisible-island.net/datafiles/release/mingw32.zip - cd ../../depends/x86_64-w64-mingw32 && unzip mingw32.zip - cd $(DIR) - $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) -lncurses + $(CC_WIN) $(CFLAGS_WIN) $(DEBUGFLAGS) -o $(TARGET_WIN) -c $(SOURCES) cp $(TARGET_WIN) ../libcc.dll #else ifeq ($(WIN_HOST),True) - todo: pass ENV var from build.sh if WIN host else $(info LINUX) - $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) -lncurses + $(CC) $(CFLAGS) $(DEBUGFLAGS) -o $(TARGET) -c $(SOURCES) cp $(TARGET) ../libcc.so endif From edb2fad98eedc0c76a6ed6f7c56fb05a0aa45219 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 23:18:14 +0100 Subject: [PATCH 0884/1145] remove ncurses from automake makefile --- src/Makefile.am | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index eee289704..395ff0352 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -574,14 +574,12 @@ komodod_LDADD += \ $(LIBZCASH_LIBS) if TARGET_DARWIN -komodod_LDADD += libcc.dylib # -lncurses -endif -if TARGET_WINDOWS -komodod_LDADD += libcc.dll +komodod_LDADD += libcc.dylib else -komodod_LDADD += libcc.so # -lncurses +komodod_LDADD += libcc.so endif + if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) endif From bc902be9e57fa9a8ef7062553cdda20dc2fe08f4 Mon Sep 17 00:00:00 2001 From: ca333 Date: Tue, 19 Feb 2019 23:21:47 +0100 Subject: [PATCH 0885/1145] add WIN --- src/Makefile.am | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index 395ff0352..e9d41a510 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -572,13 +572,15 @@ komodod_LDADD += \ $(LIBVERUS_CRYPTO) \ $(LIBVERUS_PORTABLE_CRYPTO) \ $(LIBZCASH_LIBS) - + if TARGET_DARWIN komodod_LDADD += libcc.dylib -else -komodod_LDADD += libcc.so endif - +if TARGET_WINDOWS +komodod_LDADD += libcc.dll +else +komodod_LDADD += libcc.so +endif if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) From 619c92a1ac2a08cd4dae195bb706f7d89abcce2d Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 16:57:07 -1100 Subject: [PATCH 0886/1145] Remove OS specific --- src/cc/rogue/rogue.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 786718039..80a4e7da2 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -548,13 +548,13 @@ tstp(int ignored) getyx(curscr, y, x); mvcur(y, x, oy, ox); fflush(stdout); - //wmove(curscr,oy,ox); -#ifndef __APPLE__ + wmove(curscr,oy,ox); +/*#ifndef __APPLE__ #ifndef BUILD_ROGUE curscr->_cury = oy; curscr->_curx = ox; #endif -#endif +#endif*/x } /* From 61966f52f8b9c337c011d76db1e81f31ade20c7b Mon Sep 17 00:00:00 2001 From: jl777 Date: Tue, 19 Feb 2019 16:57:56 -1100 Subject: [PATCH 0887/1145] -x --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 80a4e7da2..92d3ad378 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -554,7 +554,7 @@ tstp(int ignored) curscr->_cury = oy; curscr->_curx = ox; #endif -#endif*/x +#endif*/ } /* From f1d392b72c168edf4c6216c29f8a5b4f9381b7b3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 07:10:36 -1100 Subject: [PATCH 0888/1145] Initial musig CC commit --- src/cc/cclib.cpp | 81 ++++++++++--- src/cc/musig.cpp | 265 +++++++++++++++++++++++++++++++++++++++++++ src/cc/rogue_rpc.cpp | 5 +- src/cc/sudoku.cpp | 4 - 4 files changed, 332 insertions(+), 23 deletions(-) create mode 100755 src/cc/musig.cpp diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index f2f13837c..ae3d88573 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -36,6 +36,7 @@ std::string MYCCLIBNAME = (char *)"rogue"; #else #define EVAL_SUDOKU 17 +#define EVAL_MUSIG 18 std::string MYCCLIBNAME = (char *)"sudoku"; #endif @@ -70,6 +71,16 @@ CClib_methods[] = { (char *)"sudoku", (char *)"txidinfo", (char *)"txid", 1, 1, 'T', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"pending", (char *)"", 0, 0, 'U', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"solution", (char *)"txid solution timestamps[81]", 83, 83, 'S', EVAL_SUDOKU }, + { (char *)"musig", (char *)"calcmsg", (char *)"sendtxid scriptPubKey", 2, 2, 'C', EVAL_MUSIG }, + { (char *)"musig", (char *)"combine", (char *)"pubkeys ...", 2, 256, 'P', EVAL_MUSIG }, + { (char *)"musig", (char *)"session", (char *)"msg pkhash", 2, 2, 'R', EVAL_MUSIG }, + { (char *)"musig", (char *)"commit", (char *)"pubkeys ...", 2, 256, 'H', EVAL_MUSIG }, + { (char *)"musig", (char *)"nonce", (char *)"pubkeys ...", 2, 256, 'N', EVAL_MUSIG }, + { (char *)"musig", (char *)"partialsign", (char *)"pubkeys ...", 2, 256, 'S', EVAL_MUSIG }, + { (char *)"musig", (char *)"sigcombine", (char *)"pubkeys ...", 2, 256, 'M', EVAL_MUSIG }, + { (char *)"musig", (char *)"verify", (char *)"msg sig pubkey", 3, 3, 'V', EVAL_MUSIG }, + { (char *)"musig", (char *)"send", (char *)"combined_pk amount", 2, 2, 'x', EVAL_MUSIG }, + { (char *)"musig", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_MUSIG }, #endif }; @@ -98,6 +109,18 @@ UniValue sudoku_txidinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params UniValue sudoku_generate(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue sudoku_pending(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); + +bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); +UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); #endif UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) @@ -158,6 +181,37 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) return(result); } } + else if ( cp->evalcode == EVAL_MUSIG ) + { + //printf("CClib_method params.%p\n",params); + if ( strcmp(method,"combine") == 0 ) + return(musig_combine(txfee,cp,params)); + else if ( strcmp(method,"calcmsg") == 0 ) + return(musig_calcmsg(txfee,cp,params)); + else if ( strcmp(method,"session") == 0 ) + return(musig_session(txfee,cp,params)); + else if ( strcmp(method,"commit") == 0 ) + return(musig_commit(txfee,cp,params)); + else if ( strcmp(method,"nonce") == 0 ) // returns combined nonce if ready + return(musig_nonce(txfee,cp,params)); + else if ( strcmp(method,"partialsign") == 0 ) + return(musig_partialsign(txfee,cp,params)); + else if ( strcmp(method,"sigcombine") == 0 ) + return(musig_sigcombine(txfee,cp,params)); + else if ( strcmp(method,"verify") == 0 ) + return(musig_verify(txfee,cp,params)); + else if ( strcmp(method,"send") == 0 ) + return(musig_send(txfee,cp,params)); + else if ( strcmp(method,"spend") == 0 ) + return(musig_spend(txfee,cp,params)); + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","invalid musig method")); + result.push_back(Pair("method",method)); + return(result); + } + } #endif else { @@ -278,7 +332,11 @@ bool CClib_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C #ifdef BUILD_ROGUE return(rogue_validate(cp,height,eval,tx)); #else - return(sudoku_validate(cp,height,eval,tx)); + if ( cp->evalcode == EVAL_SUDOKU ) + return(sudoku_validate(cp,height,eval,tx)); + else if ( cp->evalcode == EVAL_MUSIG ) + return(musig_validate(cp,height,eval,tx)); + else return eval->Invalid("invalid evalcode"); #endif } numvins = tx.vin.size(); @@ -385,21 +443,6 @@ std::string Faucet2Fund(struct CCcontract_info *cp,uint64_t txfee,int64_t funds) return(""); } -/*UniValue FaucetInfo() -{ - UniValue result(UniValue::VOBJ); char numstr[64]; - CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - CPubKey faucetpk; struct CCcontract_info *cp,C; int64_t funding; - result.push_back(Pair("result","success")); - result.push_back(Pair("name","Faucet")); - cp = CCinit(&C,EVAL_FAUCET); - faucetpk = GetUnspendable(cp,0); - funding = AddFaucetInputs(cp,mtx,faucetpk,0,0); - sprintf(numstr,"%.8f",(double)funding/COIN); - result.push_back(Pair("funding",numstr)); - return(result); -}*/ - std::string CClib_rawtxgen(struct CCcontract_info *cp,uint8_t funcid,cJSON *params) { CMutableTransaction tmpmtx,mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); @@ -481,7 +524,10 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will { newstr[j++] = '"'; i += 2; - } else newstr[j++] = jsonstr[i]; + } + else if ( jsonstr[i] == ''' ) + newstr[j++] = '"'; + else newstr[j++] = jsonstr[i]; } newstr[j] = 0; params = cJSON_Parse(newstr); @@ -533,5 +579,6 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will #else #include "sudoku.cpp" +#include "musig.cpp" #endif diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp new file mode 100755 index 000000000..1a9d860cf --- /dev/null +++ b/src/cc/musig.cpp @@ -0,0 +1,265 @@ +/****************************************************************************** + * Copyright © 2014-2019 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. * + * * + ******************************************************************************/ + + +#include +#include +#include + +#define MUSIG_PREVN 0 // for now, just use vout0 for the musig output + +uint256 musig_msghash(uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) +{ + std::vector data; uint256 hash; int32_t len = 0; + data << E_MARSHAL(ss << prevhash << prevn << vout << combined_pk); +fprintf(stderr,"data size %d\n",(int32_t)data.size()); + vcalc_sha256(0,(uint8_t *)&hash,data.ptr(),data.size()); + return(hash); +} + +uint256 musig_prevoutmsg(uint256 sendtxid,CScript scriptPubKey) +{ + CTransaction vintx; uint256 hashBlock; int32_t numvouts; CTxOut vout; secp256k1_pubkey combined_pk; + if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) + { + if ( musig_sendopretdecode(combined_pk,vintx.vouts[numvouts-1].scriptPubKey) == 'x' ) + { + vout.nValue = vintx.vout[MUSIG_PREVN].nValue - txfee; + vout.scriptPubKey = scriptPubKey; + return(musig_msghash(prevhash,MUSIG_PREVN,vout,combined_pk)); + } + } + return(zeroid); +} + +UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); uint256 sendtxid,msg; char *scriptstr; int32_t n; + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n == 2 ) + { + sendtxid = juint256(jitem(params,0)); + scriptstr = jstr(jitem(params,1),0); + if ( is_hexstr(scriptstr,0) != 0 ) + { + CScript scriptPubKey(ParseHex(scriptstr)); + msg = musig_prevoutmsg(sendtxid,scriptPubKey); + result.push_back("result","success"); + result.push_back("msg",msg.GetHex()); + return(result); + } else return(cclib_error(result,"script is not hex")); + } else return(cclib_error(result,"need exactly 2 parameters: sendtxid, scriptPubKey")); + } else return(cclib_error(result,"couldnt parse params")); +} + +UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back("result","success"); + return(result); +} + +// helpers for rpc calls that generate/validate onchain tx + +UniValue musig_rawtxresult(UniValue &result,std::string rawtx) +{ + CTransaction tx; + if ( rawtx.size() > 0 ) + { + result.push_back(Pair("hex",rawtx)); + if ( DecodeHexTx(tx,rawtx) != 0 ) + { + //if ( broadcastflag != 0 && myAddtomempool(tx) != 0 ) + // RelayTransaction(tx); + result.push_back(Pair("txid",tx.GetHash().ToString())); + result.push_back(Pair("result","success")); + } else result.push_back(Pair("error","decode hex")); + } else result.push_back(Pair("error","couldnt finalize CCtx")); + return(result); +} + +CScript musig_sendopret(uint8_t funcid,secp256k1_pubkey combined_pk) +{ + CScript opret; uint8_t evalcode = EVAL_MUSIG; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << combined_pk); + return(opret); +} + +uint8_t musig_sendopretdecode(secp256k1_pubkey &combined_pk,CScript scriptPubKey) +{ + std::vector vopret; uint8_t e,f; + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> combined_pk) != 0 && e == EVAL_MUSIG && f == 'x' ) + { + return(f); + } + return(0); +} + +CScript musig_spendopret(uint8_t funcid,secp256k1_pubkey combined_pk,secp256k1_schnorrsig musig) +{ + CScript opret; uint8_t evalcode = EVAL_MUSIG; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << combined_pk << musig); + return(opret); +} + +uint8_t musig_spendopretdecode(secp256k1_pubkey &combined_pk,secp256k1_schnorrsig &musig,CScript scriptPubKey) +{ + std::vector vopret; uint8_t e,f; + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> combined_pk; ss >> musig) != 0 && e == EVAL_MUSIG && f == 'y' ) + { + return(f); + } + return(0); +} + +UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + UniValue result(UniValue::VOBJ); int32_t n; char *hexstr; std::string rawtx; int64_t amount; CPubKey musigpk,mypk; + if ( txfee == 0 ) + txfee = 10000; + mypk = pubkey2pk(Mypubkey()); + musigpk = GetUnspendable(cp,0); + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n == 2 && (hexstr= jstr(jitem(params,0),0)) != 0 && is_hexstr(hexstr,0) == 66 ) + { + secp256k1_pubkey combined_pk(ParseHex(hexstr)); + amount = jdouble(jitem(params,1),0) * COIN + 0.0000000049; + if ( amount >= 3*txfee && AddNormalinputs(mtx,mypk,amount+2*txfee,64) >= amount+2*txfee ) + { + mtx.vout.push_back(MakeCC1vout(cp->evalcode,amount+txfee,musigpk)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_sendopret('x',combined_pk)); + return(musig_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt find funds or less than 0.0003")); + } else return(cclib_error(result,"must have 2 params: combined_pk, amount")); + } else return(cclib_error(result,"not enough parameters")); +} + +UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + static secp256k1_context *ctx; + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint256 msg,prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n == 3 ) + { + prevhash = juint256(jitem(params,0)); + scriptstr = jstr(jitem(params,1),0); + musigstr = jstr(jitem(params,2),0); + if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 0 ) + { + if ( txfee == 0 ) + txfee = 10000; + mypk = pubkey2pk(Mypubkey()); + secp256k1_schnorrsig musig(ParseHex(musigstr)); + CScript scriptPubKey(ParseHex(scriptstr)); + if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) + { + vout.nValue = vintx.vout[0].nValue - txfee; + vout.scriptPubKey = scriptPubKey; + if ( musig_sendopretdecode(combined_pk,vintx.vouts[numvouts-1].scriptPubKey) == 'x' ) + { + msg = musig_prevoutmsg(prevhash,vout.scriptPubKey); + if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) + return(cclib_error(result,"musig didnt validate")); + mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); + mtx.vout.push_back(vout); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_spendopret('y',combined_pk,musig)); + return(musig_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt decode send opret")); + } else return(cclib_error(result,"couldnt find vin0")); + } else return(cclib_error(result,"script or musig is not hex")); + } else return(cclib_error(result,"need to have exactly 3 params prevhash, scriptPubKey, musig")); + } else return(cclib_error(result,"params parse error")); +} + +bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) +{ + static secp256k1_context *ctx; + secp256k1_pubkey combined_pk,checkpk; secp256k1_schnorrsig musig; uint256 msg,hashBlock; CTransaction vintx; int32_t numvouts; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( tx.vout.size() != 2 ) + return eval->Invalid("numvouts != 2"); + else if ( tx.vin.size() != 1 ) + return eval->Invalid("numvins != 1"); + else if ( IsCCInput(tx.vin[0].scriptSig) == 0 ) + return eval->Invalid("illegal normal vin0"); + else if ( myGetTransaction(tx.vin[0].prevout.hash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) + { + if ( musig_sendopretdecode(combined_pk,vintx.vouts[numvouts-1].scriptPubKey) == 'x' ) + { + if ( musig_spendopretdecode(check_pk,musig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) + { + if ( combined_pk == check_pk ) + { + msg = musig_prevoutmsg(tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); + if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) + return eval->Invalid("failed schnorrsig_verify"); + else return(true); + } else return eval->Invalid("combined_pk didnt match send opret"); + } else return eval->Invalid("failed decode musig spendopret"); + } else return eval->Invalid("couldnt decode send opret"); + } else return eval->Invalid("couldnt find vin0 tx"); +} diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3d89e0568..8ca239c7b 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1078,7 +1078,7 @@ UniValue rogue_highlander(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,gameheight,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; bits256 t; char myrogueaddr[64]; CPubKey mypk,roguepk; + UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,gameheight,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; uint64_t seed; bits256 t; char myrogueaddr[64]; CPubKey mypk,roguepk; result.push_back(Pair("name","rogue")); result.push_back(Pair("method","gameinfo")); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -1095,7 +1095,8 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,myrogueaddr,roguepk,mypk); //fprintf(stderr,"myrogueaddr.%s\n",myrogueaddr); - rogue_gamefields(result,maxplayers,buyin,txid,myrogueaddr); + seed = rogue_gamefields(result,maxplayers,buyin,txid,myrogueaddr); + result.push_back(Pair("seed",(int64_t)seed)); for (i=0; iInvalid("not enough vouts"); } -#include -#include -#include - From 998a2cf173f5b199d95c2b7ba71e032dee411ce5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 07:17:05 -1100 Subject: [PATCH 0889/1145] CScript opret; uint8_t evalcode = EVAL_MUSIG; opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << combined_pk); --- src/cc/cclib.cpp | 2 +- src/cc/musig.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index ae3d88573..0d907d4ca 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -525,7 +525,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will newstr[j++] = '"'; i += 2; } - else if ( jsonstr[i] == ''' ) + else if ( jsonstr[i] == '\'' ) newstr[j++] = '"'; else newstr[j++] = jsonstr[i]; } diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 1a9d860cf..4696f7949 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -22,6 +22,7 @@ uint256 musig_msghash(uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) { + CScript data; std::vector data; uint256 hash; int32_t len = 0; data << E_MARSHAL(ss << prevhash << prevn << vout << combined_pk); fprintf(stderr,"data size %d\n",(int32_t)data.size()); From fdaf1fb297d1535d2016cbe15d171c3701e10b8f Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 07:21:15 -1100 Subject: [PATCH 0890/1145] syntax --- src/cc/musig.cpp | 232 +++++++++++++++++++++++------------------------ 1 file changed, 116 insertions(+), 116 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 4696f7949..12da40f1d 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -19,120 +19,7 @@ #include #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output - -uint256 musig_msghash(uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) -{ - CScript data; - std::vector data; uint256 hash; int32_t len = 0; - data << E_MARSHAL(ss << prevhash << prevn << vout << combined_pk); -fprintf(stderr,"data size %d\n",(int32_t)data.size()); - vcalc_sha256(0,(uint8_t *)&hash,data.ptr(),data.size()); - return(hash); -} - -uint256 musig_prevoutmsg(uint256 sendtxid,CScript scriptPubKey) -{ - CTransaction vintx; uint256 hashBlock; int32_t numvouts; CTxOut vout; secp256k1_pubkey combined_pk; - if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) - { - if ( musig_sendopretdecode(combined_pk,vintx.vouts[numvouts-1].scriptPubKey) == 'x' ) - { - vout.nValue = vintx.vout[MUSIG_PREVN].nValue - txfee; - vout.scriptPubKey = scriptPubKey; - return(musig_msghash(prevhash,MUSIG_PREVN,vout,combined_pk)); - } - } - return(zeroid); -} - -UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); uint256 sendtxid,msg; char *scriptstr; int32_t n; - if ( (params= cclib_reparse(&n,params)) != 0 ) - { - if ( n == 2 ) - { - sendtxid = juint256(jitem(params,0)); - scriptstr = jstr(jitem(params,1),0); - if ( is_hexstr(scriptstr,0) != 0 ) - { - CScript scriptPubKey(ParseHex(scriptstr)); - msg = musig_prevoutmsg(sendtxid,scriptPubKey); - result.push_back("result","success"); - result.push_back("msg",msg.GetHex()); - return(result); - } else return(cclib_error(result,"script is not hex")); - } else return(cclib_error(result,"need exactly 2 parameters: sendtxid, scriptPubKey")); - } else return(cclib_error(result,"couldnt parse params")); -} - -UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - UniValue result(UniValue::VOBJ); - result.push_back("result","success"); - return(result); -} - -// helpers for rpc calls that generate/validate onchain tx - -UniValue musig_rawtxresult(UniValue &result,std::string rawtx) -{ - CTransaction tx; - if ( rawtx.size() > 0 ) - { - result.push_back(Pair("hex",rawtx)); - if ( DecodeHexTx(tx,rawtx) != 0 ) - { - //if ( broadcastflag != 0 && myAddtomempool(tx) != 0 ) - // RelayTransaction(tx); - result.push_back(Pair("txid",tx.GetHash().ToString())); - result.push_back(Pair("result","success")); - } else result.push_back(Pair("error","decode hex")); - } else result.push_back(Pair("error","couldnt finalize CCtx")); - return(result); -} +#define MUSIG_TXFEE 10000 CScript musig_sendopret(uint8_t funcid,secp256k1_pubkey combined_pk) { @@ -170,12 +57,125 @@ uint8_t musig_spendopretdecode(secp256k1_pubkey &combined_pk,secp256k1_schnorrsi return(0); } +uint256 musig_msghash(uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) +{ + CScript data; uint256 hash; int32_t len = 0; + data << E_MARSHAL(ss << prevhash << prevn << vout << combined_pk); +fprintf(stderr,"data size %d\n",(int32_t)data.size()); + vcalc_sha256(0,(uint8_t *)&hash,data.data(),data.size()); + return(hash); +} + +uint256 musig_prevoutmsg(uint256 sendtxid,CScript scriptPubKey) +{ + CTransaction vintx; uint256 hashBlock; int32_t numvouts; CTxOut vout; secp256k1_pubkey combined_pk; + if ( myGetTransaction(sendtxid,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) + { + if ( musig_sendopretdecode(combined_pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) + { + vout.nValue = vintx.vout[MUSIG_PREVN].nValue - MUSIG_TXFEE; + vout.scriptPubKey = scriptPubKey; + return(musig_msghash(sendtxid,MUSIG_PREVN,vout,combined_pk)); + } + } + return(zeroid); +} + +UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); uint256 sendtxid,msg; char *scriptstr; int32_t n; + if ( (params= cclib_reparse(&n,params)) != 0 ) + { + if ( n == 2 ) + { + sendtxid = juint256(jitem(params,0)); + scriptstr = jstr(jitem(params,1),0); + if ( is_hexstr(scriptstr,0) != 0 ) + { + CScript scriptPubKey(ParseHex(scriptstr)); + msg = musig_prevoutmsg(sendtxid,scriptPubKey); + result.push_back(Pair("result","success")); + result.push_back(Pair("msg",msg.GetHex())); + return(result); + } else return(cclib_error(result,"script is not hex")); + } else return(cclib_error(result,"need exactly 2 parameters: sendtxid, scriptPubKey")); + } else return(cclib_error(result,"couldnt parse params")); +} + +UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); + result.push_back(Pair("result","success")); + return(result); +} + +// helpers for rpc calls that generate/validate onchain tx + +UniValue musig_rawtxresult(UniValue &result,std::string rawtx) +{ + CTransaction tx; + if ( rawtx.size() > 0 ) + { + result.push_back(Pair("hex",rawtx)); + if ( DecodeHexTx(tx,rawtx) != 0 ) + { + //if ( broadcastflag != 0 && myAddtomempool(tx) != 0 ) + // RelayTransaction(tx); + result.push_back(Pair("txid",tx.GetHash().ToString())); + result.push_back(Pair("result","success")); + } else result.push_back(Pair("error","decode hex")); + } else result.push_back(Pair("error","couldnt finalize CCtx")); + return(result); +} + UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); UniValue result(UniValue::VOBJ); int32_t n; char *hexstr; std::string rawtx; int64_t amount; CPubKey musigpk,mypk; if ( txfee == 0 ) - txfee = 10000; + txfee = MUSIG_TXFEE; mypk = pubkey2pk(Mypubkey()); musigpk = GetUnspendable(cp,0); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -211,7 +211,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 0 ) { if ( txfee == 0 ) - txfee = 10000; + txfee = MUSIG_TXFEE; mypk = pubkey2pk(Mypubkey()); secp256k1_schnorrsig musig(ParseHex(musigstr)); CScript scriptPubKey(ParseHex(scriptstr)); From a2d6ae5e145cff32f35981f71229022785b272a3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 07:28:27 -1100 Subject: [PATCH 0891/1145] Msg -> msg[32] --- src/cc/musig.cpp | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 12da40f1d..6d2a1f583 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -57,16 +57,15 @@ uint8_t musig_spendopretdecode(secp256k1_pubkey &combined_pk,secp256k1_schnorrsi return(0); } -uint256 musig_msghash(uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) +void musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) { CScript data; uint256 hash; int32_t len = 0; data << E_MARSHAL(ss << prevhash << prevn << vout << combined_pk); fprintf(stderr,"data size %d\n",(int32_t)data.size()); - vcalc_sha256(0,(uint8_t *)&hash,data.data(),data.size()); - return(hash); + vcalc_sha256(0,msg,data.data(),data.size()); } -uint256 musig_prevoutmsg(uint256 sendtxid,CScript scriptPubKey) +int32_t musig_prevoutmsg(uint8_t *msg,uint256 sendtxid,CScript scriptPubKey) { CTransaction vintx; uint256 hashBlock; int32_t numvouts; CTxOut vout; secp256k1_pubkey combined_pk; if ( myGetTransaction(sendtxid,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) @@ -75,7 +74,7 @@ uint256 musig_prevoutmsg(uint256 sendtxid,CScript scriptPubKey) { vout.nValue = vintx.vout[MUSIG_PREVN].nValue - MUSIG_TXFEE; vout.scriptPubKey = scriptPubKey; - return(musig_msghash(sendtxid,MUSIG_PREVN,vout,combined_pk)); + return(musig_msghash(msg,sendtxid,MUSIG_PREVN,vout,combined_pk)); } } return(zeroid); @@ -83,7 +82,7 @@ uint256 musig_prevoutmsg(uint256 sendtxid,CScript scriptPubKey) UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint256 sendtxid,msg; char *scriptstr; int32_t n; + UniValue result(UniValue::VOBJ); uint256 sendtxid; int32_t i; uint8_t msg[32]; char *scriptstr,str[65]; int32_t n; if ( (params= cclib_reparse(&n,params)) != 0 ) { if ( n == 2 ) @@ -93,9 +92,12 @@ UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) if ( is_hexstr(scriptstr,0) != 0 ) { CScript scriptPubKey(ParseHex(scriptstr)); - msg = musig_prevoutmsg(sendtxid,scriptPubKey); + musig_prevoutmsg(msg,sendtxid,scriptPubKey); result.push_back(Pair("result","success")); - result.push_back(Pair("msg",msg.GetHex())); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",msg[i]); + str[64] = 0; + result.push_back(Pair("msg",str)); return(result); } else return(cclib_error(result,"script is not hex")); } else return(cclib_error(result,"need exactly 2 parameters: sendtxid, scriptPubKey")); @@ -198,7 +200,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint256 msg,prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -219,9 +221,9 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { vout.nValue = vintx.vout[0].nValue - txfee; vout.scriptPubKey = scriptPubKey; - if ( musig_sendopretdecode(combined_pk,vintx.vouts[numvouts-1].scriptPubKey) == 'x' ) + if ( musig_sendopretdecode(combined_pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - msg = musig_prevoutmsg(prevhash,vout.scriptPubKey); + musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) return(cclib_error(result,"musig didnt validate")); mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); @@ -238,7 +240,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { static secp256k1_context *ctx; - secp256k1_pubkey combined_pk,checkpk; secp256k1_schnorrsig musig; uint256 msg,hashBlock; CTransaction vintx; int32_t numvouts; + secp256k1_pubkey combined_pk,checkpk; secp256k1_schnorrsig musig; uint256 hashBlock; CTransaction vintx; int32_t numvouts; uint8_t msg[32]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( tx.vout.size() != 2 ) @@ -249,13 +251,13 @@ bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return eval->Invalid("illegal normal vin0"); else if ( myGetTransaction(tx.vin[0].prevout.hash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { - if ( musig_sendopretdecode(combined_pk,vintx.vouts[numvouts-1].scriptPubKey) == 'x' ) + if ( musig_sendopretdecode(combined_pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - if ( musig_spendopretdecode(check_pk,musig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) + if ( musig_spendopretdecode(checkpk,musig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) { - if ( combined_pk == check_pk ) + if ( combined_pk == checkpk ) { - msg = musig_prevoutmsg(tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); + musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) return eval->Invalid("failed schnorrsig_verify"); else return(true); From 30edb30e4aca089bbe7fe59246ae1b0aeff35485 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 07:47:39 -1100 Subject: [PATCH 0892/1145] Serialize pk -> combined_pk --- src/cc/musig.cpp | 76 ++++++++++++++++++++++++++---------------------- 1 file changed, 42 insertions(+), 34 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 6d2a1f583..561851640 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -21,63 +21,65 @@ #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 -CScript musig_sendopret(uint8_t funcid,secp256k1_pubkey combined_pk) +CScript musig_sendopret(uint8_t funcid,CPubKey pk) { CScript opret; uint8_t evalcode = EVAL_MUSIG; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << combined_pk); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << pk); return(opret); } -uint8_t musig_sendopretdecode(secp256k1_pubkey &combined_pk,CScript scriptPubKey) +uint8_t musig_sendopretdecode(CPubKey &pk,CScript scriptPubKey) { std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> combined_pk) != 0 && e == EVAL_MUSIG && f == 'x' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> pk) != 0 && e == EVAL_MUSIG && f == 'x' ) { return(f); } return(0); } -CScript musig_spendopret(uint8_t funcid,secp256k1_pubkey combined_pk,secp256k1_schnorrsig musig) +CScript musig_spendopret(uint8_t funcid,CPubKey pk,secp256k1_schnorrsig musig) { CScript opret; uint8_t evalcode = EVAL_MUSIG; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << combined_pk << musig); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << pk << musig); return(opret); } -uint8_t musig_spendopretdecode(secp256k1_pubkey &combined_pk,secp256k1_schnorrsig &musig,CScript scriptPubKey) +uint8_t musig_spendopretdecode(CPubKey &pk,secp256k1_schnorrsig &musig,CScript scriptPubKey) { std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> combined_pk; ss >> musig) != 0 && e == EVAL_MUSIG && f == 'y' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> pk; ss >> musig) != 0 && e == EVAL_MUSIG && f == 'y' ) { return(f); } return(0); } -void musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,secp256k1_pubkey combined_pk) +int32_t musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,CPubKey pk) { CScript data; uint256 hash; int32_t len = 0; - data << E_MARSHAL(ss << prevhash << prevn << vout << combined_pk); + data << E_MARSHAL(ss << prevhash << prevn << vout << pk); fprintf(stderr,"data size %d\n",(int32_t)data.size()); - vcalc_sha256(0,msg,data.data(),data.size()); + vcalc_sha256(0,msg,data.begin(),data.size()); + return(0); } int32_t musig_prevoutmsg(uint8_t *msg,uint256 sendtxid,CScript scriptPubKey) { - CTransaction vintx; uint256 hashBlock; int32_t numvouts; CTxOut vout; secp256k1_pubkey combined_pk; + CTransaction vintx; uint256 hashBlock; int32_t numvouts; CTxOut vout; CPubKey pk; + memset(msg,0,32); if ( myGetTransaction(sendtxid,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { - if ( musig_sendopretdecode(combined_pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) + if ( musig_sendopretdecode(pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { vout.nValue = vintx.vout[MUSIG_PREVN].nValue - MUSIG_TXFEE; vout.scriptPubKey = scriptPubKey; - return(musig_msghash(msg,sendtxid,MUSIG_PREVN,vout,combined_pk)); + return(musig_msghash(msg,sendtxid,MUSIG_PREVN,vout,pk)); } } - return(zeroid); + return(-1); } UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) @@ -184,15 +186,15 @@ UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( n == 2 && (hexstr= jstr(jitem(params,0),0)) != 0 && is_hexstr(hexstr,0) == 66 ) { - secp256k1_pubkey combined_pk(ParseHex(hexstr)); + CPubKey pk(ParseHex(hexstr)); amount = jdouble(jitem(params,1),0) * COIN + 0.0000000049; if ( amount >= 3*txfee && AddNormalinputs(mtx,mypk,amount+2*txfee,64) >= amount+2*txfee ) { mtx.vout.push_back(MakeCC1vout(cp->evalcode,amount+txfee,musigpk)); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_sendopret('x',combined_pk)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_sendopret('x',pk)); return(musig_rawtxresult(result,rawtx)); } else return(cclib_error(result,"couldnt find funds or less than 0.0003")); - } else return(cclib_error(result,"must have 2 params: combined_pk, amount")); + } else return(cclib_error(result,"must have 2 params: pk, amount")); } else return(cclib_error(result,"not enough parameters")); } @@ -200,7 +202,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( (params= cclib_reparse(&n,params)) != 0 ) @@ -221,15 +223,18 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { vout.nValue = vintx.vout[0].nValue - txfee; vout.scriptPubKey = scriptPubKey; - if ( musig_sendopretdecode(combined_pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) + if ( musig_sendopretdecode(pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); - if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) - return(cclib_error(result,"musig didnt validate")); - mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); - mtx.vout.push_back(vout); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_spendopret('y',combined_pk,musig)); - return(musig_rawtxresult(result,rawtx)); + if ( secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) + { + musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); + if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) + return(cclib_error(result,"musig didnt validate")); + mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); + mtx.vout.push_back(vout); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_spendopret('y',pk,musig)); + return(musig_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt parse pk")); } else return(cclib_error(result,"couldnt decode send opret")); } else return(cclib_error(result,"couldnt find vin0")); } else return(cclib_error(result,"script or musig is not hex")); @@ -240,7 +245,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { static secp256k1_context *ctx; - secp256k1_pubkey combined_pk,checkpk; secp256k1_schnorrsig musig; uint256 hashBlock; CTransaction vintx; int32_t numvouts; uint8_t msg[32]; + secp256k1_pubkey combined_pk; CPubKey pk,checkpk; secp256k1_schnorrsig musig; uint256 hashBlock; CTransaction vintx; int32_t numvouts; uint8_t msg[32]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( tx.vout.size() != 2 ) @@ -251,16 +256,19 @@ bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return eval->Invalid("illegal normal vin0"); else if ( myGetTransaction(tx.vin[0].prevout.hash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { - if ( musig_sendopretdecode(combined_pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) + if ( musig_sendopretdecode(pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { if ( musig_spendopretdecode(checkpk,musig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) { - if ( combined_pk == checkpk ) + if ( pk == checkpk ) { - musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); - if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) - return eval->Invalid("failed schnorrsig_verify"); - else return(true); + if ( secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) + { + musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); + if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) + return eval->Invalid("failed schnorrsig_verify"); + else return(true); + } else return eval->Invalid("couldnt parse pk"); } else return eval->Invalid("combined_pk didnt match send opret"); } else return eval->Invalid("failed decode musig spendopret"); } else return eval->Invalid("couldnt decode send opret"); From 8de3c71baa8ab11903439d50f8e0191a326ce112 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 07:56:45 -1100 Subject: [PATCH 0893/1145] musig64 --- src/cc/musig.cpp | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 561851640..64d7528b6 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -39,18 +39,18 @@ uint8_t musig_sendopretdecode(CPubKey &pk,CScript scriptPubKey) return(0); } -CScript musig_spendopret(uint8_t funcid,CPubKey pk,secp256k1_schnorrsig musig) +CScript musig_spendopret(uint8_t funcid,CPubKey pk,std::vector musig64) { CScript opret; uint8_t evalcode = EVAL_MUSIG; - opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << pk << musig); + opret << OP_RETURN << E_MARSHAL(ss << evalcode << funcid << pk << musig64); return(opret); } -uint8_t musig_spendopretdecode(CPubKey &pk,secp256k1_schnorrsig &musig,CScript scriptPubKey) +uint8_t musig_spendopretdecode(CPubKey &pk,std::vector &musig64,CScript scriptPubKey) { std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> pk; ss >> musig) != 0 && e == EVAL_MUSIG && f == 'y' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> pk; ss >> musig64) != 0 && e == EVAL_MUSIG && f == 'y' ) { return(f); } @@ -62,7 +62,7 @@ int32_t musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,CP CScript data; uint256 hash; int32_t len = 0; data << E_MARSHAL(ss << prevhash << prevn << vout << pk); fprintf(stderr,"data size %d\n",(int32_t)data.size()); - vcalc_sha256(0,msg,data.begin(),data.size()); + vcalc_sha256(0,msg,data.begin(),(int32_t)data.size()); return(0); } @@ -212,12 +212,12 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) prevhash = juint256(jitem(params,0)); scriptstr = jstr(jitem(params,1),0); musigstr = jstr(jitem(params,2),0); - if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 0 ) + if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 128 ) { if ( txfee == 0 ) txfee = MUSIG_TXFEE; mypk = pubkey2pk(Mypubkey()); - secp256k1_schnorrsig musig(ParseHex(musigstr)); + std::vector musig64(ParseHex(musigstr)); CScript scriptPubKey(ParseHex(scriptstr)); if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { @@ -225,16 +225,17 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) vout.scriptPubKey = scriptPubKey; if ( musig_sendopretdecode(pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - if ( secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) + if ( secp256k1_schnorrsig_parse(ctx,&musig,&musig64[0]) > 0 && + secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) { musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) return(cclib_error(result,"musig didnt validate")); mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); mtx.vout.push_back(vout); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_spendopret('y',pk,musig)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_spendopret('y',pk,musig64)); return(musig_rawtxresult(result,rawtx)); - } else return(cclib_error(result,"couldnt parse pk")); + } else return(cclib_error(result,"couldnt parse pk or musig")); } else return(cclib_error(result,"couldnt decode send opret")); } else return(cclib_error(result,"couldnt find vin0")); } else return(cclib_error(result,"script or musig is not hex")); @@ -245,7 +246,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { static secp256k1_context *ctx; - secp256k1_pubkey combined_pk; CPubKey pk,checkpk; secp256k1_schnorrsig musig; uint256 hashBlock; CTransaction vintx; int32_t numvouts; uint8_t msg[32]; + secp256k1_pubkey combined_pk; CPubKey pk,checkpk; secp256k1_schnorrsig musig; uint256 hashBlock; CTransaction vintx; int32_t numvouts; std::vector musig64; uint8_t msg[32]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( tx.vout.size() != 2 ) @@ -258,17 +259,18 @@ bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( musig_sendopretdecode(pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - if ( musig_spendopretdecode(checkpk,musig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) + if ( musig_spendopretdecode(checkpk,musig64,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) { if ( pk == checkpk ) { - if ( secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) + if ( secp256k1_schnorrsig_parse(ctx,&musig,&musig64[0]) > 0 && + secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) { musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) return eval->Invalid("failed schnorrsig_verify"); else return(true); - } else return eval->Invalid("couldnt parse pk"); + } else return eval->Invalid("couldnt parse pk or musig"); } else return eval->Invalid("combined_pk didnt match send opret"); } else return eval->Invalid("failed decode musig spendopret"); } else return eval->Invalid("couldnt decode send opret"); From 6ed384ff471be6653e0084f7b8fcf0e524e6611e Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:07:05 -1100 Subject: [PATCH 0894/1145] Fixes --- src/cc/musig.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 64d7528b6..c12866865 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -62,7 +62,8 @@ int32_t musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,CP CScript data; uint256 hash; int32_t len = 0; data << E_MARSHAL(ss << prevhash << prevn << vout << pk); fprintf(stderr,"data size %d\n",(int32_t)data.size()); - vcalc_sha256(0,msg,data.begin(),(int32_t)data.size()); + hash = Hash(data.begin(),data.end()); + memcpy(msg,&hash,sizeof(hash)); return(0); } @@ -202,7 +203,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; secp256k1_schnorrsig musig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( (params= cclib_reparse(&n,params)) != 0 ) From fb69ddb0c66c37f949b3e007720162344c7e4b8b Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:12:36 -1100 Subject: [PATCH 0895/1145] Add modules --- src/secp256k1/Makefile.am | 5 ----- src/secp256k1/src/secp256k1.c | 6 ++++++ 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 676415834..089d3ee8e 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -174,11 +174,6 @@ if ENABLE_MODULE_ECDH include src/modules/ecdh/Makefile.am.include endif -#if ENABLE_MODULE_MUSIG -include src/modules/schnorrsig/Makefile.am.include -include src/modules/musig/Makefile.am.include -#endif - if ENABLE_MODULE_RECOVERY include src/modules/recovery/Makefile.am.include endif diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index b89a7c04a..2cf57856b 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -580,6 +580,12 @@ int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey * # include "modules/ecdh/main_impl.h" #endif +#ifdef ENABLE_MODULE_MUSIG +#include "modules/schnorrsig/main_impl.h" +#include "modules/musig/main_impl.h" +#endif + + #ifdef ENABLE_MODULE_RECOVERY # include "modules/recovery/main_impl.h" #endif From 88d08c07fa1ebce2f59216f2719014e198a41d2d Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:17:34 -1100 Subject: [PATCH 0896/1145] secp256k1_nonce_function_bipschnorr --- src/secp256k1/src/secp256k1.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 2cf57856b..fbff4b3aa 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -340,6 +340,27 @@ static int nonce_function_rfc6979(unsigned char *nonce32, const unsigned char *m return 1; } +/* This nonce function is described in BIP-schnorr + * (https://github.com/sipa/bips/blob/bip-schnorr/bip-schnorr.mediawiki) */ +static int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { + secp256k1_sha256 sha; + (void) data; + (void) counter; + VERIFY_CHECK(counter == 0); + + /* Hash x||msg as per the spec */ + secp256k1_sha256_initialize(&sha); + secp256k1_sha256_write(&sha, key32, 32); + secp256k1_sha256_write(&sha, msg32, 32); + /* Hash in algorithm, which is not in the spec, but may be critical to + * users depending on it to avoid nonce reuse across algorithms. */ + if (algo16 != NULL) { + secp256k1_sha256_write(&sha, algo16, 16); + } + secp256k1_sha256_finalize(&sha, nonce32); + return 1; +} + const secp256k1_nonce_function secp256k1_nonce_function_rfc6979 = nonce_function_rfc6979; const secp256k1_nonce_function secp256k1_nonce_function_default = nonce_function_rfc6979; From 6adebc5e7bf3a82cfbaf8b0b35e06df8a4cbaf6b Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:19:37 -1100 Subject: [PATCH 0897/1145] Test --- src/secp256k1/src/modules/schnorrsig/main_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index b366236d8..6ccec1523 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -10,7 +10,7 @@ #include "include/secp256k1.h" #include "include/secp256k1_schnorrsig.h" #include "hash.h" - +hello int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; VERIFY_CHECK(ctx != NULL); From 0a433f453bd4098de592b12219f545655aa04c06 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:20:59 -1100 Subject: [PATCH 0898/1145] ENABLE_MODULE_MUSIG --- src/secp256k1/src/modules/schnorrsig/main_impl.h | 2 +- src/secp256k1/src/secp256k1.c | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index 6ccec1523..b366236d8 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -10,7 +10,7 @@ #include "include/secp256k1.h" #include "include/secp256k1_schnorrsig.h" #include "hash.h" -hello + int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; VERIFY_CHECK(ctx != NULL); diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index fbff4b3aa..1f04af395 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -4,6 +4,7 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ +#define ENABLE_MODULE_MUSIG #include "include/secp256k1.h" #include "util.h" From 965abd3d526caa3f87188cb62836b29a9f798115 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:23:06 -1100 Subject: [PATCH 0899/1145] Force include --- src/secp256k1/src/secp256k1.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 1f04af395..4c24c1084 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -4,7 +4,6 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#define ENABLE_MODULE_MUSIG #include "include/secp256k1.h" #include "util.h" @@ -602,10 +601,10 @@ int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey * # include "modules/ecdh/main_impl.h" #endif -#ifdef ENABLE_MODULE_MUSIG +//#ifdef ENABLE_MODULE_MUSIG #include "modules/schnorrsig/main_impl.h" #include "modules/musig/main_impl.h" -#endif +//#endif #ifdef ENABLE_MODULE_RECOVERY From 5944b3e64fce54a06a5dbbe971fac12c617645cd Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:25:10 -1100 Subject: [PATCH 0900/1145] Test --- src/secp256k1/src/secp256k1.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 4c24c1084..1c7b75bc5 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -601,10 +601,8 @@ int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey * # include "modules/ecdh/main_impl.h" #endif -//#ifdef ENABLE_MODULE_MUSIG #include "modules/schnorrsig/main_impl.h" #include "modules/musig/main_impl.h" -//#endif #ifdef ENABLE_MODULE_RECOVERY From 8de28666e0e18373444888d390be2ded4ea2795e Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:34:19 -1100 Subject: [PATCH 0901/1145] $(LIBSECP256K1) --- src/Makefile.am | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index 395ff0352..22668c91f 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -574,9 +574,9 @@ komodod_LDADD += \ $(LIBZCASH_LIBS) if TARGET_DARWIN -komodod_LDADD += libcc.dylib +komodod_LDADD += libcc.dylib $(LIBSECP256K1) else -komodod_LDADD += libcc.so +komodod_LDADD += libcc.so $(LIBSECP256K1) endif From 9ca5858eebdca923517dd5e786c6d63034dd2bcf Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:41:10 -1100 Subject: [PATCH 0902/1145] Include secp --- src/cc/cclib.cpp | 1 + src/cc/makecclib | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 0d907d4ca..f02d63dbd 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -579,6 +579,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will #else #include "sudoku.cpp" +#include "../secp256k1/src/secp256k1.c" #include "musig.cpp" #endif diff --git a/src/cc/makecclib b/src/cc/makecclib index 832cf1e96..871569325 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1,2 +1,2 @@ #!/bin/sh -gcc -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp +gcc -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp ../secp256k1/libsecp256k1.la From 38e67bca763fed2b6d2b618d5089019ac1b145fd Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:45:05 -1100 Subject: [PATCH 0903/1145] ../include --- src/cc/makecclib | 2 +- src/secp256k1/src/secp256k1.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/makecclib b/src/cc/makecclib index 871569325..f4d2bd01b 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1,2 +1,2 @@ #!/bin/sh -gcc -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp ../secp256k1/libsecp256k1.la +gcc -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 1c7b75bc5..657893d0d 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -4,7 +4,7 @@ * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ -#include "include/secp256k1.h" +#include "../include/secp256k1.h" #include "util.h" #include "num_impl.h" From b82b61d772c9b321ff662b49a888d8464051a8fb Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:50:03 -1100 Subject: [PATCH 0904/1145] -DSECP256K1_BUILD --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index f02d63dbd..3cfb1a185 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -579,6 +579,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will #else #include "sudoku.cpp" +#define SECP256K1_BUILD #include "../secp256k1/src/secp256k1.c" #include "musig.cpp" #endif From 8ce89adfe711d8972d72c48b4cd8442cd65ca349 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:55:49 -1100 Subject: [PATCH 0905/1145] Basic-config --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 3cfb1a185..88fa9b554 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -579,7 +579,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will #else #include "sudoku.cpp" -#define SECP256K1_BUILD +#include "../secp256k1/src/basic-config.h" #include "../secp256k1/src/secp256k1.c" #include "musig.cpp" #endif From d745071b2abc938668eaea61517a00fcb35c332a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 08:59:00 -1100 Subject: [PATCH 0906/1145] USE_BASIC_CONFIG --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 88fa9b554..1fc8c45a7 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -579,6 +579,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will #else #include "sudoku.cpp" +#define USE_BASIC_CONFIG #include "../secp256k1/src/basic-config.h" #include "../secp256k1/src/secp256k1.c" #include "musig.cpp" From 5d7ffa476033156a598430775e57e6992e839e66 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:01:29 -1100 Subject: [PATCH 0907/1145] ../../.. --- src/secp256k1/src/modules/musig/main_impl.h | 4 ++-- src/secp256k1/src/modules/schnorrsig/main_impl.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/secp256k1/src/modules/musig/main_impl.h b/src/secp256k1/src/modules/musig/main_impl.h index dece823d6..8bd2f1831 100644 --- a/src/secp256k1/src/modules/musig/main_impl.h +++ b/src/secp256k1/src/modules/musig/main_impl.h @@ -8,8 +8,8 @@ #ifndef _SECP256K1_MODULE_MUSIG_MAIN_ #define _SECP256K1_MODULE_MUSIG_MAIN_ -#include "include/secp256k1.h" -#include "include/secp256k1_musig.h" +#include "../../../include/secp256k1.h" +#include "../../../include/secp256k1_musig.h" #include "hash.h" /* Computes ell = SHA256(pk[0], ..., pk[np-1]) */ diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index b366236d8..f2b418159 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -7,8 +7,8 @@ #ifndef _SECP256K1_MODULE_SCHNORRSIG_MAIN_ #define _SECP256K1_MODULE_SCHNORRSIG_MAIN_ -#include "include/secp256k1.h" -#include "include/secp256k1_schnorrsig.h" +#include "../../../include/secp256k1.h" +#include "../../../include/secp256k1_schnorrsig.h" #include "hash.h" int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { From 96c6f295339ddb1f9f5f92b55e41fa4b33ec4ea4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:06:09 -1100 Subject: [PATCH 0908/1145] Define funds --- src/secp256k1/src/modules/schnorrsig/main_impl.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index f2b418159..9a08e81d8 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -11,6 +11,9 @@ #include "../../../include/secp256k1_schnorrsig.h" #include "hash.h" +static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); +static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); + int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; VERIFY_CHECK(ctx != NULL); From 23a530ae4ebb7dc2f23c06aeecce591a9fc2c117 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:09:43 -1100 Subject: [PATCH 0909/1145] static int secp256k1_musig_pubkey_combine_callback(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data) --- src/secp256k1/src/modules/schnorrsig/main_impl.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index 9a08e81d8..00f241020 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -13,6 +13,7 @@ static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; From c1264e8ddb42fae26bb3c128ae204391416706e2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:12:08 -1100 Subject: [PATCH 0910/1145] Reorder --- src/secp256k1/src/modules/schnorrsig/main_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index 00f241020..2eb939f55 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -11,9 +11,9 @@ #include "../../../include/secp256k1_schnorrsig.h" #include "hash.h" +typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); -typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; From dfb71e518242d8ea2bef87a9cb2647e5915c1542 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:14:59 -1100 Subject: [PATCH 0911/1145] e tes --- src/cc/cclib.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 1fc8c45a7..33b76ff91 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -579,9 +579,9 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will #else #include "sudoku.cpp" -#define USE_BASIC_CONFIG -#include "../secp256k1/src/basic-config.h" -#include "../secp256k1/src/secp256k1.c" +//#define USE_BASIC_CONFIG +//#include "../secp256k1/src/basic-config.h" +//#include "../secp256k1/src/secp256k1.c" #include "musig.cpp" #endif From e4494dc1207d38a16a26166c760c417b8bab1197 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:16:35 -1100 Subject: [PATCH 0912/1145] Test --- src/cc/musig.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index c12866865..34561d820 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -14,9 +14,9 @@ ******************************************************************************/ -#include -#include -#include +#include "../secp256k1/include/secp256k1.h" +#include "../secp256k1/include/secp256k1_schnorrsig.h" +#include "../secp256k1/include/secp256k1_musig.h" #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 From 60122c9eeca2a91331eae3ed8dd50c8369552fbe Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:23:32 -1100 Subject: [PATCH 0913/1145] (const uint8_t *) --- src/cc/musig.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 34561d820..800102e13 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -226,11 +226,11 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) vout.scriptPubKey = scriptPubKey; if ( musig_sendopretdecode(pk,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - if ( secp256k1_schnorrsig_parse(ctx,&musig,&musig64[0]) > 0 && + if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) { musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); - if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) + if ( !secp256k1_schnorrsig_verify((const secp256k1_context *)ctx,&musig,(const uint8_t *)msg,(const secp256k1_pubkey *)&combined_pk) ) return(cclib_error(result,"musig didnt validate")); mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); mtx.vout.push_back(vout); @@ -264,11 +264,11 @@ bool musig_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( pk == checkpk ) { - if ( secp256k1_schnorrsig_parse(ctx,&musig,&musig64[0]) > 0 && + if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) { musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); - if ( !secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) ) + if ( !secp256k1_schnorrsig_verify((const secp256k1_context *)ctx,&musig,(const uint8_t *)msg,(const secp256k1_pubkey *)&combined_pk) ) return eval->Invalid("failed schnorrsig_verify"); else return(true); } else return eval->Invalid("couldnt parse pk or musig"); From 6cdecbe7f78ddf29eeab4368f150dbeb7a302e7b Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:30:27 -1100 Subject: [PATCH 0914/1145] Pull in schnorr --- src/komodo_gateway.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 02ab67407..35952bebf 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -16,6 +16,17 @@ // paxdeposit equivalent in reverse makes opreturn and KMD does the same in reverse #include "komodo_defs.h" +#include "secp256k1/include/secp256k1.h" +#include "secp256k1/include/secp256k1_schnorrsig.h" +#include "secp256k1/include/secp256k1_musig.h" + +void dummy_linker_tricker() +{ + secp256k1_context *ctx = 0; std::vector musig64; CPubKey pk; secp256k1_schnorrsig musig; secp256k1_pubkey combined_pk; + if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) + return(1); +} + int32_t MarmaraValidateCoinbase(int32_t height,CTransaction tx); int32_t pax_fiatstatus(uint64_t *available,uint64_t *deposited,uint64_t *issued,uint64_t *withdrawn,uint64_t *approved,uint64_t *redeemed,char *base) From bb07e87c4a993b12b0fc43c91b0bf677f15e185b Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:31:44 -1100 Subject: [PATCH 0915/1145] Int32 --- 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 35952bebf..5dd9907c9 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -20,7 +20,7 @@ #include "secp256k1/include/secp256k1_schnorrsig.h" #include "secp256k1/include/secp256k1_musig.h" -void dummy_linker_tricker() +int32_t dummy_linker_tricker() { secp256k1_context *ctx = 0; std::vector musig64; CPubKey pk; secp256k1_schnorrsig musig; secp256k1_pubkey combined_pk; if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) From befefc81c9e22b9f1a191ee3d5012dcf26113254 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:34:07 -1100 Subject: [PATCH 0916/1145] Test --- src/komodo_gateway.h | 4 ++-- src/secp256k1/src/modules/schnorrsig/main_impl.h | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 5dd9907c9..68e648b14 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -16,7 +16,7 @@ // paxdeposit equivalent in reverse makes opreturn and KMD does the same in reverse #include "komodo_defs.h" -#include "secp256k1/include/secp256k1.h" +/*#include "secp256k1/include/secp256k1.h" #include "secp256k1/include/secp256k1_schnorrsig.h" #include "secp256k1/include/secp256k1_musig.h" @@ -25,7 +25,7 @@ int32_t dummy_linker_tricker() secp256k1_context *ctx = 0; std::vector musig64; CPubKey pk; secp256k1_schnorrsig musig; secp256k1_pubkey combined_pk; if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) return(1); -} +}*/ int32_t MarmaraValidateCoinbase(int32_t height,CTransaction tx); diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index 2eb939f55..925c49d2a 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -25,6 +25,7 @@ int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char * } int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64) { + parse is here (void) ctx; VERIFY_CHECK(ctx != NULL); ARG_CHECK(sig != NULL); From 0fe4fdd07cbac8b174db05227f398315be1690ef Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:43:00 -1100 Subject: [PATCH 0917/1145] Disable for now --- src/cc/cclib.cpp | 2 +- src/secp256k1/src/modules/schnorrsig/main_impl.h | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 33b76ff91..75dd13fa2 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -582,6 +582,6 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will //#define USE_BASIC_CONFIG //#include "../secp256k1/src/basic-config.h" //#include "../secp256k1/src/secp256k1.c" -#include "musig.cpp" +//#include "musig.cpp" #endif diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index 925c49d2a..2eb939f55 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -25,7 +25,6 @@ int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char * } int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64) { - parse is here (void) ctx; VERIFY_CHECK(ctx != NULL); ARG_CHECK(sig != NULL); From 33c9f37abe0da91e990047e3204c0f989cb713af Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:45:12 -1100 Subject: [PATCH 0918/1145] Enable --- src/cc/cclib.cpp | 2 +- src/secp256k1/src/modules/schnorrsig/main_impl.h | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 75dd13fa2..33b76ff91 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -582,6 +582,6 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will //#define USE_BASIC_CONFIG //#include "../secp256k1/src/basic-config.h" //#include "../secp256k1/src/secp256k1.c" -//#include "musig.cpp" +#include "musig.cpp" #endif diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index 2eb939f55..a99897d2c 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -11,9 +11,9 @@ #include "../../../include/secp256k1_schnorrsig.h" #include "hash.h" -typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); -static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); -static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +//typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); +//static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); +//static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; From 3c802c4a0219207903151d7ca483665a749d37a3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 09:53:09 -1100 Subject: [PATCH 0919/1145] -// --- src/secp256k1/src/modules/schnorrsig/main_impl.h | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/secp256k1/src/modules/schnorrsig/main_impl.h b/src/secp256k1/src/modules/schnorrsig/main_impl.h index a99897d2c..f2b418159 100644 --- a/src/secp256k1/src/modules/schnorrsig/main_impl.h +++ b/src/secp256k1/src/modules/schnorrsig/main_impl.h @@ -11,10 +11,6 @@ #include "../../../include/secp256k1_schnorrsig.h" #include "hash.h" -//typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); -//static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); -//static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); - int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig) { (void) ctx; VERIFY_CHECK(ctx != NULL); From ea3e9ee36a7fb89f48aecc824ce18050de53848c Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 10:01:21 -1100 Subject: [PATCH 0920/1145] Parse --- src/komodo_gateway.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 68e648b14..5dd9907c9 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -16,7 +16,7 @@ // paxdeposit equivalent in reverse makes opreturn and KMD does the same in reverse #include "komodo_defs.h" -/*#include "secp256k1/include/secp256k1.h" +#include "secp256k1/include/secp256k1.h" #include "secp256k1/include/secp256k1_schnorrsig.h" #include "secp256k1/include/secp256k1_musig.h" @@ -25,7 +25,7 @@ int32_t dummy_linker_tricker() secp256k1_context *ctx = 0; std::vector musig64; CPubKey pk; secp256k1_schnorrsig musig; secp256k1_pubkey combined_pk; if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) return(1); -}*/ +} int32_t MarmaraValidateCoinbase(int32_t height,CTransaction tx); From 5280af8c12010d7cc7929651fc7d92337d4a2368 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 10:13:16 -1100 Subject: [PATCH 0921/1145] Revert --- src/komodo_gateway.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/komodo_gateway.h b/src/komodo_gateway.h index 5dd9907c9..68e648b14 100644 --- a/src/komodo_gateway.h +++ b/src/komodo_gateway.h @@ -16,7 +16,7 @@ // paxdeposit equivalent in reverse makes opreturn and KMD does the same in reverse #include "komodo_defs.h" -#include "secp256k1/include/secp256k1.h" +/*#include "secp256k1/include/secp256k1.h" #include "secp256k1/include/secp256k1_schnorrsig.h" #include "secp256k1/include/secp256k1_musig.h" @@ -25,7 +25,7 @@ int32_t dummy_linker_tricker() secp256k1_context *ctx = 0; std::vector musig64; CPubKey pk; secp256k1_schnorrsig musig; secp256k1_pubkey combined_pk; if ( secp256k1_schnorrsig_parse((const secp256k1_context *)ctx,&musig,(const uint8_t *)&musig64[0]) > 0 && secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) return(1); -} +}*/ int32_t MarmaraValidateCoinbase(int32_t height,CTransaction tx); From 0594b52df25a3b8096ac18e99ed02f283c8d320a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 20:33:13 -1100 Subject: [PATCH 0922/1145] Big buffer --- .gitignore | 10 ++++++++++ src/cc/rogue/init.c | 1 + src/cc/rogue/io.c | 12 ++++++++++++ src/cc/rogue/rip.c | 2 +- src/cc/rogue/rogue.c | 2 +- 5 files changed, 25 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index ebaa71f4d..2f97780ab 100644 --- a/.gitignore +++ b/.gitignore @@ -132,3 +132,13 @@ src/cc/rogue/rogue src/cc/rogue/rogue.so src/cc/rogue/test.zip + +src/rogue.530623577502174316.0 + +src/rogue.530623577502174316.pack + +src/rogue.530623577502174316.player + +src/checkfile + +src/log diff --git a/src/cc/rogue/init.c b/src/cc/rogue/init.c index ffc0b3707..b11cfa80c 100644 --- a/src/cc/rogue/init.c +++ b/src/cc/rogue/init.c @@ -34,6 +34,7 @@ void restore_player(struct rogue_state *rs) int32_t i,total = 0; THING *obj; //rs->P.gold = purse; max_hp = rs->P.hitpoints; + //pstats.s_hpt = max_hp; pstats.s_str = rs->P.strength & 0xffff; if ( (max_stats.s_str= (rs->P.strength >> 16) & 0xffff) == 0 ) max_stats.s_str = 16; diff --git a/src/cc/rogue/io.c b/src/cc/rogue/io.c index 9842ba353..994f112e2 100644 --- a/src/cc/rogue/io.c +++ b/src/cc/rogue/io.c @@ -160,6 +160,18 @@ readchar(struct rogue_state *rs) if ( rs->ind < rs->numkeys ) { c = rs->keystrokes[rs->ind++]; + if ( 0 ) + { + static FILE *fp; static int32_t counter; + if ( fp == 0 ) + fp = fopen("log","wb"); + if ( fp != 0 ) + { + fprintf(fp,"%d: (%c) hp.%d\n",counter,c,pstats.s_hpt); + fflush(fp); + counter++; + } + } while ( c == 'Q' && rs->ind < rs->numkeys ) { //fprintf(stderr,"Got 'Q' next (%c)\n",rs->keystrokes[rs->ind]); sleep(2); diff --git a/src/cc/rogue/rip.c b/src/cc/rogue/rip.c index 65be2e8fa..1866f0b48 100644 --- a/src/cc/rogue/rip.c +++ b/src/cc/rogue/rip.c @@ -238,7 +238,7 @@ death(struct rogue_state *rs,char monst) //struct tm *localtime(const time_t *); if ( rs->guiflag == 0 ) { - fprintf(stderr,"death during replay\n"); + fprintf(stderr,"death during replay by (%c)\n",monst); //sleep(3); rs->replaydone = (uint32_t)time(NULL); return; } diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 92d3ad378..2f4545585 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -607,7 +607,7 @@ playit(struct rogue_state *rs) } else { - if ( rs->needflush != 0 && rs->num > 1024 ) + if ( rs->needflush != 0 && rs->num > 8000 ) { if ( flushkeystrokes(rs) == 0 ) rs->needflush = 0; From 23caa3477367a08556128a329ffd1ba602591fef Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 21:33:25 -1100 Subject: [PATCH 0923/1145] Allow zombies --- .gitignore | 2 + src/cc/rogue/main.c | 514 +++++++++++++++++++++++++++++++++++++++++++ src/cc/rogue/rogue.c | 71 +----- src/cc/rogue/rogue.h | 4 +- src/cc/rogue/state.c | 2 +- src/cc/rogue_rpc.cpp | 2 +- 6 files changed, 526 insertions(+), 69 deletions(-) diff --git a/.gitignore b/.gitignore index 2f97780ab..0d0846e31 100644 --- a/.gitignore +++ b/.gitignore @@ -142,3 +142,5 @@ src/rogue.530623577502174316.player src/checkfile src/log + +src/foo.zip diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index c0fa36752..1131e3429 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -20,10 +20,17 @@ #include #include #include +#include +#include + +char USERPASS[8192]; +char Gametxidstr[67]; #define SMALLVAL 0.000000000000001 #define SATOSHIDEN ((uint64_t)100000000L) #define dstr(x) ((double)(x) / SATOSHIDEN) +#define KOMODO_ASSETCHAIN_MAXLEN 65 +#define ASSETCHAINS_SYMBOL "ROGUE" #ifndef _BITS256 #define _BITS256 @@ -31,6 +38,15 @@ union _bits256 { uint8_t bytes[32]; uint16_t ushorts[16]; uint32_t uints[8]; uin typedef union _bits256 bits256; #endif +double OS_milliseconds() +{ + struct timeval tv; double millis; + gettimeofday(&tv,NULL); + millis = ((double)tv.tv_sec * 1000. + (double)tv.tv_usec / 1000.); + //printf("tv_sec.%ld usec.%d %f\n",tv.tv_sec,tv.tv_usec,millis); + return(millis); +} + int32_t _unhex(char c) { if ( c >= '0' && c <= '9' ) @@ -167,6 +183,23 @@ char *clonestr(char *str) strcpy(clone,str); return(clone); } + +char *parse_conf_line(char *line,char *field) +{ + line += strlen(field); + for (; *line!='='&&*line!=0; line++) + break; + if ( *line == 0 ) + return(0); + if ( *line == '=' ) + line++; + while ( line[strlen(line)-1] == '\r' || line[strlen(line)-1] == '\n' || line[strlen(line)-1] == ' ' ) + line[strlen(line)-1] = 0; + //printf("LINE.(%s)\n",line); + _stripwhite(line,0); + return(clonestr(line)); +} + int32_t safecopy(char *dest,char *src,long len) { int32_t i = -1; @@ -246,6 +279,487 @@ uint8_t *OS_fileptr(long *allocsizep,char *fname) return((uint8_t *)retptr); } +struct MemoryStruct { char *memory; size_t size; }; +struct return_string { char *ptr; size_t len; }; + +// return data from the server +#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32) +#define CURL_GLOBAL_SSL (1<<0) +#define CURL_GLOBAL_WIN32 (1<<1) + + +/************************************************************************ + * + * Initialize the string handler so that it is thread safe + * + ************************************************************************/ + +void init_string(struct return_string *s) +{ + s->len = 0; + s->ptr = (char *)calloc(1,s->len+1); + if ( s->ptr == NULL ) + { + fprintf(stderr,"init_string malloc() failed\n"); + exit(-1); + } + s->ptr[0] = '\0'; +} + +/************************************************************************ + * + * Use the "writer" to accumulate text until done + * + ************************************************************************/ + +size_t accumulatebytes(void *ptr,size_t size,size_t nmemb,struct return_string *s) +{ + size_t new_len = s->len + size*nmemb; + s->ptr = (char *)realloc(s->ptr,new_len+1); + if ( s->ptr == NULL ) + { + fprintf(stderr, "accumulate realloc() failed\n"); + exit(-1); + } + memcpy(s->ptr+s->len,ptr,size*nmemb); + s->ptr[new_len] = '\0'; + s->len = new_len; + return(size * nmemb); +} + +/************************************************************************ + * + * return the current system time in milliseconds + * + ************************************************************************/ + +#define EXTRACT_BITCOIND_RESULT // if defined, ensures error is null and returns the "result" field +#ifdef EXTRACT_BITCOIND_RESULT + +/************************************************************************ + * + * perform post processing of the results + * + ************************************************************************/ + +char *post_process_bitcoind_RPC(char *debugstr,char *command,char *rpcstr,char *params) +{ + long i,j,len; char *retstr = 0; cJSON *json,*result,*error; + //printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC.%s.[%s]\n",debugstr,command,rpcstr); + if ( command == 0 || rpcstr == 0 || rpcstr[0] == 0 ) + { + if ( strcmp(command,"signrawtransaction") != 0 ) + printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC.%s.[%s]\n",debugstr,command,rpcstr); + return(rpcstr); + } + json = cJSON_Parse(rpcstr); + if ( json == 0 ) + { + printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC.%s can't parse.(%s) params.(%s)\n",debugstr,command,rpcstr,params); + free(rpcstr); + return(0); + } + result = cJSON_GetObjectItem(json,"result"); + error = cJSON_GetObjectItem(json,"error"); + if ( error != 0 && result != 0 ) + { + if ( (error->type&0xff) == cJSON_NULL && (result->type&0xff) != cJSON_NULL ) + { + retstr = cJSON_Print(result); + len = strlen(retstr); + if ( retstr[0] == '"' && retstr[len-1] == '"' ) + { + for (i=1,j=0; itype&0xff) != cJSON_NULL || (result->type&0xff) != cJSON_NULL ) + { + if ( strcmp(command,"signrawtransaction") != 0 ) + printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC (%s) error.%s\n",debugstr,command,rpcstr); + } + free(rpcstr); + } else retstr = rpcstr; + free_json(json); + //fprintf(stderr,"<<<<<<<<<<< bitcoind_RPC: postprocess returns.(%s)\n",retstr); + return(retstr); +} +#endif + +/************************************************************************ + * + * perform the query + * + ************************************************************************/ + +char *bitcoind_RPC(char **retstrp,char *debugstr,char *url,char *userpass,char *command,char *params) +{ + static int didinit,count,count2; static double elapsedsum,elapsedsum2; + struct curl_slist *headers = NULL; struct return_string s; CURLcode res; CURL *curl_handle; + char *bracket0,*bracket1,*databuf = 0; long len; int32_t specialcase,numretries; double starttime; + if ( didinit == 0 ) + { + didinit = 1; + curl_global_init(CURL_GLOBAL_ALL); //init the curl session + } + numretries = 0; + if ( debugstr != 0 && strcmp(debugstr,"BTCD") == 0 && command != 0 && strcmp(command,"SuperNET") == 0 ) + specialcase = 1; + else specialcase = 0; + if ( url[0] == 0 ) + strcpy(url,"http://127.0.0.1:7876/nxt"); + if ( specialcase != 0 && 0 ) + printf("<<<<<<<<<<< bitcoind_RPC: debug.(%s) url.(%s) command.(%s) params.(%s)\n",debugstr,url,command,params); +try_again: + if ( retstrp != 0 ) + *retstrp = 0; + starttime = OS_milliseconds(); + curl_handle = curl_easy_init(); + init_string(&s); + headers = curl_slist_append(0,"Expect:"); + + curl_easy_setopt(curl_handle,CURLOPT_USERAGENT,"mozilla/4.0");//"Mozilla/4.0 (compatible; )"); + curl_easy_setopt(curl_handle,CURLOPT_HTTPHEADER, headers); + curl_easy_setopt(curl_handle,CURLOPT_URL, url); + curl_easy_setopt(curl_handle,CURLOPT_WRITEFUNCTION, (void *)accumulatebytes); // send all data to this function + curl_easy_setopt(curl_handle,CURLOPT_WRITEDATA, &s); // we pass our 's' struct to the callback + curl_easy_setopt(curl_handle,CURLOPT_NOSIGNAL, 1L); // supposed to fix "Alarm clock" and long jump crash + curl_easy_setopt(curl_handle,CURLOPT_NOPROGRESS, 1L); // no progress callback + if ( strncmp(url,"https",5) == 0 ) + { + curl_easy_setopt(curl_handle,CURLOPT_SSL_VERIFYPEER,0); + curl_easy_setopt(curl_handle,CURLOPT_SSL_VERIFYHOST,0); + } + if ( userpass != 0 ) + curl_easy_setopt(curl_handle,CURLOPT_USERPWD, userpass); + databuf = 0; + if ( params != 0 ) + { + if ( command != 0 && specialcase == 0 ) + { + len = strlen(params); + if ( len > 0 && params[0] == '[' && params[len-1] == ']' ) { + bracket0 = bracket1 = (char *)""; + } + else + { + bracket0 = (char *)"["; + bracket1 = (char *)"]"; + } + + databuf = (char *)malloc(256 + strlen(command) + strlen(params)); + sprintf(databuf,"{\"id\":\"jl777\",\"method\":\"%s\",\"params\":%s%s%s}",command,bracket0,params,bracket1); + //printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); + // + } //else if ( specialcase != 0 ) fprintf(stderr,"databuf.(%s)\n",params); + curl_easy_setopt(curl_handle,CURLOPT_POST,1L); + if ( databuf != 0 ) + curl_easy_setopt(curl_handle,CURLOPT_POSTFIELDS,databuf); + else curl_easy_setopt(curl_handle,CURLOPT_POSTFIELDS,params); + } + //laststart = milliseconds(); + res = curl_easy_perform(curl_handle); + curl_slist_free_all(headers); + curl_easy_cleanup(curl_handle); + if ( databuf != 0 ) // clean up temporary buffer + { + free(databuf); + databuf = 0; + } + if ( res != CURLE_OK ) + { + numretries++; + if ( specialcase != 0 ) + { + printf("<<<<<<<<<<< bitcoind_RPC.(%s): BTCD.%s timeout params.(%s) s.ptr.(%s) err.%d\n",url,command,params,s.ptr,res); + free(s.ptr); + return(0); + } + else if ( numretries >= 1 ) + { + //printf("Maximum number of retries exceeded!\n"); + free(s.ptr); + return(0); + } + if ( (rand() % 1000) == 0 ) + printf( "curl_easy_perform() failed: %s %s.(%s %s), retries: %d\n",curl_easy_strerror(res),debugstr,url,command,numretries); + free(s.ptr); + sleep((1< (%s)\n",params,s.ptr); + count2++; + elapsedsum2 += (OS_milliseconds() - starttime); + if ( (count2 % 10000) == 0) + printf("%d: ave %9.6f | elapsed %.3f millis | NXT calls.(%s) cmd.(%s)\n",count2,elapsedsum2/count2,(double)(OS_milliseconds() - starttime),url,command); + return(s.ptr); + } + } + printf("bitcoind_RPC: impossible case\n"); + free(s.ptr); + return(0); +} + +static size_t WriteMemoryCallback(void *ptr,size_t size,size_t nmemb,void *data) +{ + size_t realsize = (size * nmemb); + struct MemoryStruct *mem = (struct MemoryStruct *)data; + mem->memory = (char *)((ptr != 0) ? realloc(mem->memory,mem->size + realsize + 1) : malloc(mem->size + realsize + 1)); + if ( mem->memory != 0 ) + { + if ( ptr != 0 ) + memcpy(&(mem->memory[mem->size]),ptr,realsize); + mem->size += realsize; + mem->memory[mem->size] = 0; + } + //printf("got %d bytes\n",(int32_t)(size*nmemb)); + return(realsize); +} + +char *curl_post(CURL **cHandlep,char *url,char *userpass,char *postfields,char *hdr0,char *hdr1,char *hdr2,char *hdr3) +{ + struct MemoryStruct chunk; CURL *cHandle; long code; struct curl_slist *headers = 0; + if ( (cHandle= *cHandlep) == NULL ) + *cHandlep = cHandle = curl_easy_init(); + else curl_easy_reset(cHandle); + //#ifdef DEBUG + //curl_easy_setopt(cHandle,CURLOPT_VERBOSE, 1); + //#endif + curl_easy_setopt(cHandle,CURLOPT_USERAGENT,"mozilla/4.0");//"Mozilla/4.0 (compatible; )"); + curl_easy_setopt(cHandle,CURLOPT_SSL_VERIFYPEER,0); + //curl_easy_setopt(cHandle,CURLOPT_SSLVERSION,1); + curl_easy_setopt(cHandle,CURLOPT_URL,url); + curl_easy_setopt(cHandle,CURLOPT_CONNECTTIMEOUT,10); + if ( userpass != 0 && userpass[0] != 0 ) + curl_easy_setopt(cHandle,CURLOPT_USERPWD,userpass); + if ( postfields != 0 && postfields[0] != 0 ) + { + curl_easy_setopt(cHandle,CURLOPT_POST,1); + curl_easy_setopt(cHandle,CURLOPT_POSTFIELDS,postfields); + } + if ( hdr0 != NULL && hdr0[0] != 0 ) + { + //printf("HDR0.(%s) HDR1.(%s) HDR2.(%s) HDR3.(%s)\n",hdr0!=0?hdr0:"",hdr1!=0?hdr1:"",hdr2!=0?hdr2:"",hdr3!=0?hdr3:""); + headers = curl_slist_append(headers,hdr0); + if ( hdr1 != 0 && hdr1[0] != 0 ) + headers = curl_slist_append(headers,hdr1); + if ( hdr2 != 0 && hdr2[0] != 0 ) + headers = curl_slist_append(headers,hdr2); + if ( hdr3 != 0 && hdr3[0] != 0 ) + headers = curl_slist_append(headers,hdr3); + } //headers = curl_slist_append(0,"Expect:"); + if ( headers != 0 ) + curl_easy_setopt(cHandle,CURLOPT_HTTPHEADER,headers); + //res = curl_easy_perform(cHandle); + memset(&chunk,0,sizeof(chunk)); + curl_easy_setopt(cHandle,CURLOPT_WRITEFUNCTION,WriteMemoryCallback); + curl_easy_setopt(cHandle,CURLOPT_WRITEDATA,(void *)&chunk); + curl_easy_perform(cHandle); + curl_easy_getinfo(cHandle,CURLINFO_RESPONSE_CODE,&code); + if ( headers != 0 ) + curl_slist_free_all(headers); + if ( code != 200 ) + printf("(%s) server responded with code %ld (%s)\n",url,code,chunk.memory); + return(chunk.memory); +} + +#ifdef autoextract +uint16_t _komodo_userpass(char *username,char *password,FILE *fp) +{ + char *rpcuser,*rpcpassword,*str,line[8192]; uint16_t port = 0; + rpcuser = rpcpassword = 0; + username[0] = password[0] = 0; + while ( fgets(line,sizeof(line),fp) != 0 ) + { + if ( line[0] == '#' ) + continue; + //printf("line.(%s) %p %p\n",line,strstr(line,(char *)"rpcuser"),strstr(line,(char *)"rpcpassword")); + if ( (str= strstr(line,(char *)"rpcuser")) != 0 ) + rpcuser = parse_conf_line(str,(char *)"rpcuser"); + else if ( (str= strstr(line,(char *)"rpcpassword")) != 0 ) + rpcpassword = parse_conf_line(str,(char *)"rpcpassword"); + else if ( (str= strstr(line,(char *)"rpcport")) != 0 ) + { + port = atoi(parse_conf_line(str,(char *)"rpcport")); + //fprintf(stderr,"rpcport.%u in file\n",port); + } + } + if ( rpcuser != 0 && rpcpassword != 0 ) + { + strcpy(username,rpcuser); + strcpy(password,rpcpassword); + } + //printf("rpcuser.(%s) rpcpassword.(%s) KMDUSERPASS.(%s) %u\n",rpcuser,rpcpassword,KMDUSERPASS,port); + if ( rpcuser != 0 ) + free(rpcuser); + if ( rpcpassword != 0 ) + free(rpcpassword); + return(port); +} + +void komodo_statefname(char *fname,char *symbol,char *str) +{ + int32_t n,len; + sprintf(fname,"%s",getDataDir()); + if ( (n= (int32_t)strlen(ASSETCHAINS_SYMBOL)) != 0 ) + { + len = (int32_t)strlen(fname); + if ( strcmp(ASSETCHAINS_SYMBOL,&fname[len - n]) == 0 ) + fname[len - n] = 0; + else + { + printf("unexpected fname.(%s) vs %s [%s] n.%d len.%d (%s)\n",fname,symbol,ASSETCHAINS_SYMBOL,n,len,&fname[len - n]); + return; + } + } + else + { +#ifdef _WIN32 + strcat(fname,"\\"); +#else + strcat(fname,"/"); +#endif + } + if ( symbol != 0 && symbol[0] != 0 && strcmp("KMD",symbol) != 0 ) + { + strcat(fname,symbol); + //printf("statefname.(%s) -> (%s)\n",symbol,fname); +#ifdef _WIN32 + strcat(fname,"\\"); +#else + strcat(fname,"/"); +#endif + } + strcat(fname,str); + //printf("test.(%s) -> [%s] statename.(%s) %s\n",test,ASSETCHAINS_SYMBOL,symbol,fname); +} + +uint16_t komodo_userpass(char *userpass,char *symbol) +{ + FILE *fp; uint16_t port = 0; char fname[512],username[512],password[512],confname[KOMODO_ASSETCHAIN_MAXLEN]; + userpass[0] = 0; + if ( strcmp("KMD",symbol) == 0 ) + { +#ifdef __APPLE__ + sprintf(confname,"Komodo.conf"); +#else + sprintf(confname,"komodo.conf"); +#endif + } + else sprintf(confname,"%s.conf",symbol); + komodo_statefname(fname,symbol,confname); + if ( (fp= fopen(fname,"rb")) != 0 ) + { + port = _komodo_userpass(username,password,fp); + sprintf(userpass,"%s:%s",username,password); + if ( strcmp(symbol,ASSETCHAINS_SYMBOL) == 0 ) + strcpy(USERPASS,userpass); + fclose(fp); + } + return(port); +} +#endif + +#define is_cJSON_True(json) ((json) != 0 && ((json)->type & 0xff) == cJSON_True) + +char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) +{ + //static void *cHandle; + char url[512],*retstr=0,*retstr2=0,postdata[8192]; + if ( params == 0 || params[0] == 0 ) + params = (char *)"[]"; + if ( strlen(params) < sizeof(postdata)-128 ) + { + sprintf(url,(char *)"http://127.0.0.1:%u",port); + sprintf(postdata,"{\"method\":\"%s\",\"params\":%s}",method,params); + //printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,KMDUSERPASS); + retstr2 = bitcoind_RPC(&retstr,(char *)"debug",url,userpass,method,params); + //retstr = curl_post(&cHandle,url,USERPASS,postdata,0,0,0,0); + } + return(retstr2); +} + +#include "rogue.h" + +void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) +{ + char cmd[16384],hexstr[16384]; int32_t i; + if ( rs->guiflag != 0 && Gametxidstr[0] != 0 ) + { + for (i=0; i> keystrokes.log",Gametxidstr,hexstr); + if ( system(cmd) != 0 ) + fprintf(stderr,"error issuing (%s)\n",cmd); + } +} + +int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) +{ + char cmd[32768]; int32_t i,n,retval=-1; char *filestr,*pname,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; + if ( rs->guiflag == 0 ) + return(-1); + if ( gametxidstr == 0 || *gametxidstr == 0 ) + return(retval); + sprintf(fname,"%s.gameinfo",gametxidstr); + sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); + if ( system(cmd) != 0 ) + fprintf(stderr,"error issuing (%s)\n",cmd); + else + { + filestr = (char *)OS_fileptr(&allocsize,fname); + if ( (retjson= cJSON_Parse(filestr)) != 0 ) + { + if ( (array= jarray(&n,retjson,"players")) != 0 ) + { + for (i=0; iP,(int32_t)strlen(datastr)/2,datastr); + fprintf(stderr,"set pname[%s] %s\n",pname==0?"":pname,jprint(item,0)); + rs->restoring = 1; + } + } + } + } + } + free_json(retjson); + } + free(filestr); + } + return(retval); +} + int main(int argc, char **argv, char **envp) { uint64_t seed; FILE *fp = 0; diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 2f4545585..7e5a53fe5 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -26,7 +26,6 @@ */ struct rogue_state globalR; void garbage_collect(); -char Gametxidstr[67]; void purge_obj_guess(struct obj_info *array,int32_t n) { @@ -152,71 +151,11 @@ int32_t flushkeystrokes(struct rogue_state *rs) } #else -uint8_t *OS_fileptr(long *allocsizep,char *fname); -#define is_cJSON_True(json) ((json) != 0 && ((json)->type & 0xff) == cJSON_True) - -int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) -{ - char cmd[32768]; int32_t i,n,retval=-1; char *filestr,*pname,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; - if ( gametxidstr == 0 || *gametxidstr == 0 ) - return(retval); - sprintf(fname,"%s.gameinfo",gametxidstr); - sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); - if ( system(cmd) != 0 ) - fprintf(stderr,"error issuing (%s)\n",cmd); - else - { - filestr = (char *)OS_fileptr(&allocsize,fname); - if ( (retjson= cJSON_Parse(filestr)) != 0 ) - { - if ( (array= jarray(&n,retjson,"players")) != 0 ) - { - for (i=0; iP,(int32_t)strlen(datastr)/2,datastr); - fprintf(stderr,"set pname[%s] %s\n",pname==0?"":pname,jprint(item,0)); - rs->restoring = 1; - } - } - } - } - } - free_json(retjson); - } - free(filestr); - } - return(retval); -} - -void rogue_progress(uint64_t seed,char *keystrokes,int32_t num) -{ - char cmd[16384],hexstr[16384]; int32_t i; - if ( Gametxidstr[0] != 0 ) - { - for (i=0; i> keystrokes.log",Gametxidstr,hexstr); - if ( system(cmd) != 0 ) - fprintf(stderr,"error issuing (%s)\n",cmd); - } -} - int32_t flushkeystrokes(struct rogue_state *rs) { if ( rs->num > 0 ) { - rogue_progress(rs->seed,rs->buffered,rs->num); + rogue_progress(rs,rs->seed,rs->buffered,rs->num); memset(rs->buffered,0,sizeof(rs->buffered)); rs->counter++; rs->num = 0; @@ -230,10 +169,10 @@ void rogue_bailout(struct rogue_state *rs) flushkeystrokes(rs); //sleep(5); return; - fprintf(stderr,"bailing out\n"); + /*fprintf(stderr,"bailing out\n"); sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib bailout 17 \\\"[%%22%s%%22]\\\" >> bailout.log",Gametxidstr); if ( system(cmd) != 0 ) - fprintf(stderr,"error issuing (%s)\n",cmd); + fprintf(stderr,"error issuing (%s)\n",cmd);*/ } int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis) @@ -356,6 +295,8 @@ int rogue(int argc, char **argv, char **envp) { char *env; int lowtime; struct rogue_state *rs = &globalR; memset(rs,0,sizeof(*rs)); + rs->guiflag = 1; + rs->sleeptime = 1; // non-zero to allow refresh() if ( argc == 3 && strlen(argv[2]) == 64 ) { rs->seed = atol(argv[1]); @@ -366,8 +307,6 @@ int rogue(int argc, char **argv, char **envp) return(-1); } } else rs->seed = 777; - rs->guiflag = 1; - rs->sleeptime = 1; // non-zero to allow refresh() md_init(); #ifdef MASTER diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index f687b170c..802dd5f64 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -370,7 +370,7 @@ struct rogue_state uint8_t playerdata[10000]; }; extern struct rogue_state globalR; - +extern char Gametxidstr[67]; int rogue(int argc, char **argv, char **envp); void rogueiterate(struct rogue_state *rs); @@ -380,6 +380,8 @@ int32_t rogue_restorepack(struct rogue_state *rs); void restore_player(struct rogue_state *rs); int32_t rogue_replay2(uint8_t *newdata,uint64_t seed,char *keystrokes,int32_t num,struct rogue_player *player,int32_t sleepmillis); void rogue_bailout(struct rogue_state *rs); +void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num); +int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr); #define ROGUE_MAXTOTAL (pstats.s_str*2) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 589f77422..7a0e2e4c6 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1432,7 +1432,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) if ( o->_o._o_packch != 0 ) { item = &rs->P.roguepack[rs->P.packsize]; - if ( pstats.s_hpt <= 0 ) + if ( 0 && pstats.s_hpt <= 0 ) { //fprintf(stderr,"KILLED\n"); rs->P.gold = -1; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 8ca239c7b..2d34d27c8 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1005,7 +1005,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param newdata[i] = player[i]; ((uint8_t *)&P)[i] = player[i]; } - if ( P.gold <= 0 || P.hitpoints <= 0 || (P.strength&0xffff) <= 0 || P.level <= 0 || P.experience <= 0 || P.dungeonlevel <= 0 ) + if ( 0 && (P.gold <= 0 || P.hitpoints <= 0 || (P.strength&0xffff) <= 0 || P.level <= 0 || P.experience <= 0 || P.dungeonlevel <= 0) ) { fprintf(stderr,"zero value character was killed -> no playerdata\n"); newdata.resize(0); From a08a6f3be4a9dce2379a8a1b0057e4ed05a8fa21 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 21:35:14 -1100 Subject: [PATCH 0924/1145] -lcurl --- src/cc/rogue/Makefile.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/Makefile.in b/src/cc/rogue/Makefile.in index c53ece6ac..2669a2025 100644 --- a/src/cc/rogue/Makefile.in +++ b/src/cc/rogue/Makefile.in @@ -28,8 +28,8 @@ CC = @CC@ #CFLAGS=-O2 CFLAGS= @CFLAGS@ -fPIC -#LIBS=-lcurses -LIBS = @LIBS@ +LIBS=-lcurses -lcurl +#LIBS = @LIBS@ #RM=rm -f RM = rm -f From 0514250ce31de0ebe26e23e09c39b2af036baa6e Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:07:25 -1100 Subject: [PATCH 0925/1145] Attempt curl. Will be broken until debugged --- .gitignore | 8 ++ src/cc/rogue/config.h | 270 ------------------------------------------ src/cc/rogue/main.c | 77 ++++++++---- 3 files changed, 65 insertions(+), 290 deletions(-) delete mode 100644 src/cc/rogue/config.h diff --git a/.gitignore b/.gitignore index 0d0846e31..030c9dc5a 100644 --- a/.gitignore +++ b/.gitignore @@ -144,3 +144,11 @@ src/checkfile src/log src/foo.zip + +src/cc/rogue/config.h + +src/cc/rogue/config.h + +src/ROGUE.conf + +src/rogue.scr diff --git a/src/cc/rogue/config.h b/src/cc/rogue/config.h deleted file mode 100644 index 558ae3ba1..000000000 --- a/src/cc/rogue/config.h +++ /dev/null @@ -1,270 +0,0 @@ -/* config.h. Generated from config.h.in by configure. */ -/* config.h.in. Generated from configure.ac by autoheader. */ - -/* Define if scorefile is top scores, not top players */ -#define ALLSCORES 1 - -/* Define if checktime feature should be enabled */ -/* #undef CHECKTIME */ - -/* Define to group owner of setgid executable */ -/* #undef GROUPOWNER */ - -/* Define to 1 if you have the `alarm' function. */ -#define HAVE_ALARM 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_ARPA_INET_H 1 - -/* Define to 1 if libcurses is requested */ -#define HAVE_CURSES_H 1 - -/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */ -/* #undef HAVE_DOPRNT */ - -/* Define to 1 if you have the `erasechar' function. */ -#define HAVE_ERASECHAR 1 - -/* Define if ncurses has ESCDELAY variable */ -#define HAVE_ESCDELAY 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_FCNTL_H 1 - -/* Define to 1 if you have the `fork' function. */ -#define HAVE_FORK 1 - -/* Define to 1 if you have the `getgid' function. */ -#define HAVE_GETGID 1 - -/* Define to 1 if you have the `getloadavg' function. */ -#define HAVE_GETLOADAVG 1 - -/* Define to 1 if you have the `getpass' function. */ -#define HAVE_GETPASS 1 - -/* Define to 1 if you have the `getpwuid' function. */ -#define HAVE_GETPWUID 1 - -/* Define to 1 if you have the `getuid' function. */ -#define HAVE_GETUID 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_INTTYPES_H 1 - -/* Define to 1 if you have the `killchar' function. */ -#define HAVE_KILLCHAR 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_LIMITS_H 1 - -/* Define to 1 if you have the `loadav' function. */ -/* #undef HAVE_LOADAV */ - -/* Define to 1 if `lstat' has the bug that it succeeds when given the - zero-length file name argument. */ -/* #undef HAVE_LSTAT_EMPTY_STRING_BUG */ - -/* Define to 1 if you have the header file. */ -#define HAVE_MEMORY_H 1 - -/* Define to 1 if you have the `memset' function. */ -#define HAVE_MEMSET 1 - -/* Define to 1 if libncurses is requested */ -/* #undef HAVE_NCURSES_H */ - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_NCURSES_TERM_H */ - -/* Define to 1 if you have the `nlist' function. */ -/* #undef HAVE_NLIST */ - -/* Define to 1 if you have the header file. */ -#define HAVE_NLIST_H 1 - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_PROCESS_H */ - -/* Define to 1 if you have the header file. */ -#define HAVE_PWD_H 1 - -/* Define to 1 if you have the `setenv' function. */ -#define HAVE_SETENV 1 - -/* Define to 1 if you have the `setgid' function. */ -#define HAVE_SETGID 1 - -/* Define to 1 if you have the `setregid' function. */ -#define HAVE_SETREGID 1 - -/* Define to 1 if you have the `setresgid' function. */ -/* #undef HAVE_SETRESGID */ - -/* Define to 1 if you have the `setresuid' function. */ -/* #undef HAVE_SETRESUID */ - -/* Define to 1 if you have the `setreuid' function. */ -#define HAVE_SETREUID 1 - -/* Define to 1 if you have the `setuid' function. */ -#define HAVE_SETUID 1 - -/* Define to 1 if you have the `spawnl' function. */ -/* #undef HAVE_SPAWNL */ - -/* Define to 1 if `stat' has the bug that it succeeds when given the - zero-length file name argument. */ -/* #undef HAVE_STAT_EMPTY_STRING_BUG */ - -/* Define to 1 if stdbool.h conforms to C99. */ -#define HAVE_STDBOOL_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDINT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDLIB_H 1 - -/* Define to 1 if you have the `strchr' function. */ -#define HAVE_STRCHR 1 - -/* Define to 1 if you have the `strerror' function. */ -#define HAVE_STRERROR 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STRINGS_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STRING_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_IOCTL_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_STAT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_TYPES_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_UTSNAME_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_TERMIOS_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_TERM_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_UNISTD_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_UTMP_H 1 - -/* Define to 1 if you have the `vfork' function. */ -#define HAVE_VFORK 1 - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_VFORK_H */ - -/* Define to 1 if you have the `vprintf' function. */ -#define HAVE_VPRINTF 1 - -/* Define to 1 if `fork' works. */ -#define HAVE_WORKING_FORK 1 - -/* Define to 1 if `vfork' works. */ -#define HAVE_WORKING_VFORK 1 - -/* Define to 1 if the system has the type `_Bool'. */ -#define HAVE__BOOL 1 - -/* Define to 1 if you have the `_spawnl' function. */ -/* #undef HAVE__SPAWNL */ - -/* define if we should use program's load average function instead of system - */ -/* #undef LOADAV */ - -/* Define to file to use for scoreboard lockfile */ -#define LOCKFILE "rogue.lck" - -/* Define to 1 if `lstat' dereferences a symlink specified with a trailing - slash. */ -/* #undef LSTAT_FOLLOWS_SLASHED_SYMLINK */ - -/* Define to include wizard mode */ -/* #undef MASTER */ - -/* Define if maxusers feature should be enabled */ -/* #undef MAXLOAD */ - -/* Define if maxusers feature should be enabled */ -/* #undef MAXUSERS */ - -/* kernel file to pass to nlist() when reading load average (unlikely to work) - */ -/* #undef NAMELIST */ - -/* word for the number of scores to store in scoreboard */ -#define NUMNAME "Ten" - -/* number of scores to store in scoreboard */ -#define NUMSCORES 10 - -/* Define to the address where bug reports for this package should be sent. */ -#define PACKAGE_BUGREPORT "yendor@rogueforge.net" - -/* Define to the full name of this package. */ -#define PACKAGE_NAME "Rogue" - -/* Define to the full name and version of this package. */ -#define PACKAGE_STRING "Rogue 5.4.4" - -/* Define to the one symbol short name of this package. */ -#define PACKAGE_TARNAME "rogue" - -/* Define to the version of this package. */ -#define PACKAGE_VERSION "5.4.4" - -/* Define crypt(3) wizard mode password */ -/* #undef PASSWD */ - -/* Define as the return type of signal handlers (`int' or `void'). */ -#define RETSIGTYPE void - -/* Define to file to use for scoreboard */ -#define SCOREFILE "rogue.scr" - -/* Define to 1 if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define to 1 if your declares `struct tm'. */ -/* #undef TM_IN_SYS_TIME */ - -/* define if we should use program's user counting function instead of - system's */ -/* #undef UCOUNT */ - -/* utmp like file to pass to ucount() when counting online users (unlikely to - work) */ -/* #undef UTMP */ - -/* Define to empty if `const' does not conform to ANSI C. */ -/* #undef const */ - -/* Define to `int' if doesn't define. */ -/* #undef gid_t */ - -/* Define to `int' if does not define. */ -/* #undef pid_t */ - -/* Define to `unsigned int' if does not define. */ -/* #undef size_t */ - -/* Define to `int' if doesn't define. */ -/* #undef uid_t */ - -/* Define as `fork' if `vfork' does not work. */ -/* #undef vfork */ diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 1131e3429..01ae794eb 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -23,14 +23,14 @@ #include #include -char USERPASS[8192]; +char USERPASS[8192]; uint16_t ROGUE_PORT; char Gametxidstr[67]; #define SMALLVAL 0.000000000000001 #define SATOSHIDEN ((uint64_t)100000000L) #define dstr(x) ((double)(x) / SATOSHIDEN) #define KOMODO_ASSETCHAIN_MAXLEN 65 -#define ASSETCHAINS_SYMBOL "ROGUE" +char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; #ifndef _BITS256 #define _BITS256 @@ -583,7 +583,6 @@ char *curl_post(CURL **cHandlep,char *url,char *userpass,char *postfields,char * return(chunk.memory); } -#ifdef autoextract uint16_t _komodo_userpass(char *username,char *password,FILE *fp) { char *rpcuser,*rpcpassword,*str,line[8192]; uint16_t port = 0; @@ -617,7 +616,7 @@ uint16_t _komodo_userpass(char *username,char *password,FILE *fp) return(port); } -void komodo_statefname(char *fname,char *symbol,char *str) +/*void komodo_statefname(char *fname,char *symbol,char *str) { int32_t n,len; sprintf(fname,"%s",getDataDir()); @@ -652,7 +651,7 @@ void komodo_statefname(char *fname,char *symbol,char *str) } strcat(fname,str); //printf("test.(%s) -> [%s] statename.(%s) %s\n",test,ASSETCHAINS_SYMBOL,symbol,fname); -} +}*/ uint16_t komodo_userpass(char *userpass,char *symbol) { @@ -667,8 +666,8 @@ uint16_t komodo_userpass(char *userpass,char *symbol) #endif } else sprintf(confname,"%s.conf",symbol); - komodo_statefname(fname,symbol,confname); - if ( (fp= fopen(fname,"rb")) != 0 ) + //komodo_statefname(fname,symbol,confname); + if ( (fp= fopen(confname,"rb")) != 0 ) { port = _komodo_userpass(username,password,fp); sprintf(userpass,"%s:%s",username,password); @@ -678,7 +677,6 @@ uint16_t komodo_userpass(char *userpass,char *symbol) } return(port); } -#endif #define is_cJSON_True(json) ((json) != 0 && ((json)->type & 0xff) == cJSON_True) @@ -703,32 +701,53 @@ char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) { - char cmd[16384],hexstr[16384]; int32_t i; + char cmd[16384],hexstr[16384],params[32768]; int32_t i; if ( rs->guiflag != 0 && Gametxidstr[0] != 0 ) { for (i=0; i> keystrokes.log",Gametxidstr,hexstr); - if ( system(cmd) != 0 ) - fprintf(stderr,"error issuing (%s)\n",cmd); + if ( 0 ) + { + sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib keystrokes 17 \\\"[%%22%s%%22,%%22%s%%22]\\\" >> keystrokes.log",Gametxidstr,hexstr); + if ( system(cmd) != 0 ) + fprintf(stderr,"error issuing (%s)\n",cmd); + } + else + { + sprintf(params,"[\"keystrokes\",17,[\"%s\",\"%s\"]]",Gametxidstr,hexstr); + if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) + { + fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); + free(retstr); + } + } } } int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) { - char cmd[32768]; int32_t i,n,retval=-1; char *filestr,*pname,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; + char cmd[32768]; int32_t i,n,retval=-1; char *filestr=0,*pname,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; if ( rs->guiflag == 0 ) return(-1); if ( gametxidstr == 0 || *gametxidstr == 0 ) return(retval); - sprintf(fname,"%s.gameinfo",gametxidstr); - sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); - if ( system(cmd) != 0 ) - fprintf(stderr,"error issuing (%s)\n",cmd); + if ( 0 ) + { + sprintf(fname,"%s.gameinfo",gametxidstr); + sprintf(cmd,"./komodo-cli -ac_name=ROGUE cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",gametxidstr,fname); + if ( system(cmd) != 0 ) + fprintf(stderr,"error issuing (%s)\n",cmd); + else filestr = (char *)OS_fileptr(&allocsize,fname); + } else { - filestr = (char *)OS_fileptr(&allocsize,fname); + sprintf(params,"[\"gameinfo\",17,[\"%s\"]]",gametxidstr); + filestr = komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); + } + if ( filestr != 0 ) + { + fprintf(stderr,"gameinfo.(%s)\n",filestr); if ( (retjson= cJSON_Parse(filestr)) != 0 ) { if ( (array= jarray(&n,retjson,"players")) != 0 ) @@ -762,7 +781,20 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) int main(int argc, char **argv, char **envp) { - uint64_t seed; FILE *fp = 0; + uint64_t seed; FILE *fp = 0; int32_t i,j,c; char userpass[8192]; + for (i=j=0; argv[0][i]!=0&&j Date: Wed, 20 Feb 2019 22:09:20 -1100 Subject: [PATCH 0926/1145] syntax --- .gitignore | 2 ++ src/cc/rogue/main.c | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 030c9dc5a..2ab07ee0f 100644 --- a/.gitignore +++ b/.gitignore @@ -152,3 +152,5 @@ src/cc/rogue/config.h src/ROGUE.conf src/rogue.scr + +src/cc/rogue/confdefs.h diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 01ae794eb..84e7ae91f 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -701,7 +701,7 @@ char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) { - char cmd[16384],hexstr[16384],params[32768]; int32_t i; + char cmd[16384],hexstr[16384],params[32768],*retstr; int32_t i; if ( rs->guiflag != 0 && Gametxidstr[0] != 0 ) { for (i=0; iguiflag == 0 ) return(-1); if ( gametxidstr == 0 || *gametxidstr == 0 ) From 513a9cc3fc5b6a8b9144cc697da31973a44ed59c Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:20:36 -1100 Subject: [PATCH 0927/1145] +prints --- src/cc/cclib.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 33b76ff91..578ce84d8 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -253,7 +253,7 @@ UniValue CClib_info(struct CCcontract_info *cp) UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params) { UniValue result(UniValue::VOBJ); int32_t i; std::string rawtx; - //printf("CClib params.%p\n",params); + printf("CClib params.%p (%s)\n",params,params!=0?jprint(params,0):""); for (i=0; ievalcode == CClib_methods[i].evalcode && strcmp(method,CClib_methods[i].method) == 0 ) @@ -531,7 +531,7 @@ cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will } newstr[j] = 0; params = cJSON_Parse(newstr); - if ( 0 && params != 0 ) + if ( 1 && params != 0 ) printf("new.(%s) -> %s\n",newstr,jprint(params,0)); free(newstr); *nump = cJSON_GetArraySize(params); From b60b2118c54d2031df82f95d046b3e399728f1e9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:28:44 -1100 Subject: [PATCH 0928/1145] Stubs --- src/cc/rogue/main.c | 2 +- src/cc/rogue/rogue.c | 13 +++++++++++++ src/cc/rogue/rogue.h | 1 - 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 84e7ae91f..f0e7df58a 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -24,7 +24,7 @@ #include char USERPASS[8192]; uint16_t ROGUE_PORT; -char Gametxidstr[67]; +extern char Gametxidstr[67]; #define SMALLVAL 0.000000000000001 #define SATOSHIDEN ((uint64_t)100000000L) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 7e5a53fe5..b4cb6244f 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -25,6 +25,7 @@ * The main program, of course */ struct rogue_state globalR; +char Gametxidstr[67]; void garbage_collect(); void purge_obj_guess(struct obj_info *array,int32_t n) @@ -151,6 +152,18 @@ int32_t flushkeystrokes(struct rogue_state *rs) } #else +#ifdef BUILD_ROGUE +// stubs for inside daemon +void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) +{ +} + +int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) +{ + return(-1); +} +#endif + int32_t flushkeystrokes(struct rogue_state *rs) { if ( rs->num > 0 ) diff --git a/src/cc/rogue/rogue.h b/src/cc/rogue/rogue.h index 802dd5f64..b64af8f1a 100644 --- a/src/cc/rogue/rogue.h +++ b/src/cc/rogue/rogue.h @@ -370,7 +370,6 @@ struct rogue_state uint8_t playerdata[10000]; }; extern struct rogue_state globalR; -extern char Gametxidstr[67]; int rogue(int argc, char **argv, char **envp); void rogueiterate(struct rogue_state *rs); From 3db424cdf87bd91c3855292bc77f887bb90d3254 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:30:21 -1100 Subject: [PATCH 0929/1145] Test --- src/cc/rogue/rogue.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index b4cb6244f..6d0af34b2 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -154,6 +154,7 @@ int32_t flushkeystrokes(struct rogue_state *rs) #ifdef BUILD_ROGUE // stubs for inside daemon +xxx void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) { } From 8d39e0119b11d8084bbb724e9dd277dfc34a9a29 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:32:17 -1100 Subject: [PATCH 0930/1145] Fix --- src/cc/rogue/rogue.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 6d0af34b2..0a6d83cff 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -154,7 +154,8 @@ int32_t flushkeystrokes(struct rogue_state *rs) #ifdef BUILD_ROGUE // stubs for inside daemon -xxx +char Gametxidstr[67]; + void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) { } From d835211676faa3bcbdd26690ed38f0a6a7e57b21 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:32:57 -1100 Subject: [PATCH 0931/1145] -Gameidstr --- src/cc/rogue/rogue.c | 1 - 1 file changed, 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 0a6d83cff..e8de063de 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -154,7 +154,6 @@ int32_t flushkeystrokes(struct rogue_state *rs) #ifdef BUILD_ROGUE // stubs for inside daemon -char Gametxidstr[67]; void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_t num) { From f6d2b31ab65be445a56fe70fdd5ad7e9344512ea Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:39:20 -1100 Subject: [PATCH 0932/1145] tst --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index f0e7df58a..5056ff14d 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -742,7 +742,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } else { - sprintf(params,"[\"gameinfo\",17,[\"%s\"]]",gametxidstr); + sprintf(params,"[\"gameinfo\",\"17\",\"[\'%s\']\"]",gametxidstr); filestr = komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); } if ( filestr != 0 ) From c5dce15a91ea65c7629b3e85c9e8666d1b6dc49b Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:40:23 -1100 Subject: [PATCH 0933/1145] %22 --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 5056ff14d..8ec480a0a 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -742,7 +742,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } else { - sprintf(params,"[\"gameinfo\",\"17\",\"[\'%s\']\"]",gametxidstr); + sprintf(params,"[\"gameinfo\",\"17\",\"[%22%s%22]\"]",gametxidstr); filestr = komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); } if ( filestr != 0 ) From acd6f878168806bc48ac761e14215066efbd2665 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:41:08 -1100 Subject: [PATCH 0934/1145] %22 --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 8ec480a0a..c338cf397 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -715,7 +715,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ } else { - sprintf(params,"[\"keystrokes\",17,[\"%s\",\"%s\"]]",Gametxidstr,hexstr); + sprintf(params,"[\"keystrokes\",\"17\",\"[%22%s%22,%22%s%22]\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); From f394bf75acb1022d8ea37550cd23b1f87f427714 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:42:05 -1100 Subject: [PATCH 0935/1145] %% --- src/cc/rogue/main.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index c338cf397..8f674ba40 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -715,7 +715,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ } else { - sprintf(params,"[\"keystrokes\",\"17\",\"[%22%s%22,%22%s%22]\"]",Gametxidstr,hexstr); + sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); @@ -742,7 +742,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } else { - sprintf(params,"[\"gameinfo\",\"17\",\"[%22%s%22]\"]",gametxidstr); + sprintf(params,"[\"gameinfo\",\"17\",\"[%%22%s%%22]\"]",gametxidstr); filestr = komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); } if ( filestr != 0 ) From f98831dafdc41acf0ea694296a148dac2a3f1b9a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:43:28 -1100 Subject: [PATCH 0936/1145] Test --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 8f674ba40..a7c1d1d3f 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -690,7 +690,7 @@ char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) { sprintf(url,(char *)"http://127.0.0.1:%u",port); sprintf(postdata,"{\"method\":\"%s\",\"params\":%s}",method,params); - //printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,KMDUSERPASS); + printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,KMDUSERPASS); retstr2 = bitcoind_RPC(&retstr,(char *)"debug",url,userpass,method,params); //retstr = curl_post(&cHandle,url,USERPASS,postdata,0,0,0,0); } From 652d9880a7ffce3a756995a05dc0a45439fb8757 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:43:56 -1100 Subject: [PATCH 0937/1145] USERPASS --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index a7c1d1d3f..969314166 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -690,7 +690,7 @@ char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) { sprintf(url,(char *)"http://127.0.0.1:%u",port); sprintf(postdata,"{\"method\":\"%s\",\"params\":%s}",method,params); - printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,KMDUSERPASS); + printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,USERPASS); retstr2 = bitcoind_RPC(&retstr,(char *)"debug",url,userpass,method,params); //retstr = curl_post(&cHandle,url,USERPASS,postdata,0,0,0,0); } From 957178495bbeee8f426621ee1733903a25c2c04f Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:46:12 -1100 Subject: [PATCH 0938/1145] Test --- src/cc/rogue/main.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 969314166..49a09a5cf 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -450,7 +450,7 @@ try_again: databuf = (char *)malloc(256 + strlen(command) + strlen(params)); sprintf(databuf,"{\"id\":\"jl777\",\"method\":\"%s\",\"params\":%s%s%s}",command,bracket0,params,bracket1); - //printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); + printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); // } //else if ( specialcase != 0 ) fprintf(stderr,"databuf.(%s)\n",params); curl_easy_setopt(curl_handle,CURLOPT_POST,1L); @@ -690,7 +690,7 @@ char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) { sprintf(url,(char *)"http://127.0.0.1:%u",port); sprintf(postdata,"{\"method\":\"%s\",\"params\":%s}",method,params); - printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,USERPASS); + //printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,USERPASS); retstr2 = bitcoind_RPC(&retstr,(char *)"debug",url,userpass,method,params); //retstr = curl_post(&cHandle,url,USERPASS,postdata,0,0,0,0); } From 3881f9cea47df07f7ad7ce02f06cdd88e0b28e95 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:50:57 -1100 Subject: [PATCH 0939/1145] Prints --- src/wallet/rpcwallet.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 47f7d3004..99d9b87f1 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5416,6 +5416,7 @@ UniValue cclib(const UniValue& params, bool fHelp) } if ( params.size() == 3 ) { + fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); jsonparams = cJSON_Parse(params[2].get_str().c_str()); } } From a65a83bdb8d4619bc45c14883d77d9ffddd81eee Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:55:40 -1100 Subject: [PATCH 0940/1145] Test --- src/cc/rogue/main.c | 6 +++--- src/wallet/rpcwallet.cpp | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 49a09a5cf..fab4875b1 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -450,7 +450,7 @@ try_again: databuf = (char *)malloc(256 + strlen(command) + strlen(params)); sprintf(databuf,"{\"id\":\"jl777\",\"method\":\"%s\",\"params\":%s%s%s}",command,bracket0,params,bracket1); - printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); + //printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); // } //else if ( specialcase != 0 ) fprintf(stderr,"databuf.(%s)\n",params); curl_easy_setopt(curl_handle,CURLOPT_POST,1L); @@ -715,7 +715,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ } else { - sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); + sprintf(params,"[\"keystrokes\",\"17\",\\\"[%%22%s%%22,%%22%s%%22]\\\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); @@ -742,7 +742,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } else { - sprintf(params,"[\"gameinfo\",\"17\",\"[%%22%s%%22]\"]",gametxidstr); + sprintf(params,"[\"gameinfo\",\"17\",\\\"[%%22%s%%22]\\\"]",gametxidstr); filestr = komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); } if ( filestr != 0 ) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 99d9b87f1..decb6fb96 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5416,7 +5416,7 @@ UniValue cclib(const UniValue& params, bool fHelp) } if ( params.size() == 3 ) { - fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); + //fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); jsonparams = cJSON_Parse(params[2].get_str().c_str()); } } From c2def52cb232f7faf28829aa4624e1a36d9c4929 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 22:56:53 -1100 Subject: [PATCH 0941/1145] Test --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index fab4875b1..6ac9efe3b 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -715,7 +715,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ } else { - sprintf(params,"[\"keystrokes\",\"17\",\\\"[%%22%s%%22,%%22%s%%22]\\\"]",Gametxidstr,hexstr); + sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); From 2496f79e41c478c780b6142cb1036490361c9949 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:05:58 -1100 Subject: [PATCH 0942/1145] Jsonstr --- src/cc/CCinclude.h | 2 +- src/cc/cclib.cpp | 76 +++++++++++++++++++++------------------- src/wallet/rpcwallet.cpp | 6 ++-- 3 files changed, 43 insertions(+), 41 deletions(-) diff --git a/src/cc/CCinclude.h b/src/cc/CCinclude.h index eb9297a36..ca51506e8 100644 --- a/src/cc/CCinclude.h +++ b/src/cc/CCinclude.h @@ -139,7 +139,7 @@ int32_t komodo_nextheight(); int32_t CCgetspenttxid(uint256 &spenttxid,int32_t &vini,int32_t &height,uint256 txid,int32_t vout); void CCclearvars(struct CCcontract_info *cp); -UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params); +UniValue CClib(struct CCcontract_info *cp,char *method,char *jsonstr); UniValue CClib_info(struct CCcontract_info *cp); CBlockIndex *komodo_blockindex(uint256 hash); CBlockIndex *komodo_chainactive(int32_t height); diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 578ce84d8..88db00732 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -123,9 +123,43 @@ UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); #endif -UniValue CClib_method(struct CCcontract_info *cp,char *method,cJSON *params) +cJSON *cclib_reparse(int32_t *nump,char *jsonstr) // assumes origparams will be freed by caller { - UniValue result(UniValue::VOBJ); uint64_t txfee = 10000; + cJSON *params; char *jsonstr,*newstr; int32_t i,j; + *nump = 0; + if ( jsonstr != 0 ) + { + if ( jsonstr[0] == '"' && jsonstr[strlen(jsonstr)-1] == '"' ) + { + jsonstr[strlen(jsonstr)-1] = 0; + jsonstr++; + } + newstr = (char *)malloc(strlen(jsonstr)+1); + for (i=j=0; jsonstr[i]!=0; i++) + { + if ( jsonstr[i] == '%' && jsonstr[i+1] == '2' && jsonstr[i+2] == '2' ) + { + newstr[j++] = '"'; + i += 2; + } + else if ( jsonstr[i] == '\'' ) + newstr[j++] = '"'; + else newstr[j++] = jsonstr[i]; + } + newstr[j] = 0; + params = cJSON_Parse(newstr); + if ( 1 && params != 0 ) + printf("new.(%s) -> %s\n",newstr,jprint(params,0)); + free(newstr); + *nump = cJSON_GetArraySize(params); + //free(origparams); + } else params = 0; + return(params); +} + +UniValue CClib_method(struct CCcontract_info *cp,char *method,char *jsonstr) +{ + UniValue result(UniValue::VOBJ); uint64_t txfee = 10000; int32_t m; cJSON *params = cclib_reparse(&m,jsonstr); #ifdef BUILD_ROGUE if ( cp->evalcode == EVAL_ROGUE ) { @@ -250,10 +284,10 @@ UniValue CClib_info(struct CCcontract_info *cp) return(result); } -UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params) +UniValue CClib(struct CCcontract_info *cp,char *method,char *jsonstr) { UniValue result(UniValue::VOBJ); int32_t i; std::string rawtx; - printf("CClib params.%p (%s)\n",params,params!=0?jprint(params,0):""); + printf("CClib params.(%s)\n",jsonstr!=0?jsonstr:""); for (i=0; ievalcode == CClib_methods[i].evalcode && strcmp(method,CClib_methods[i].method) == 0 ) @@ -265,7 +299,7 @@ UniValue CClib(struct CCcontract_info *cp,char *method,cJSON *params) rawtx = CClib_rawtxgen(cp,CClib_methods[i].funcid,params); result.push_back(Pair("rawtx",rawtx)); return(result); - } else return(CClib_method(cp,method,params)); + } else return(CClib_method(cp,method,jsonstr)); } } result.push_back(Pair("result","error")); @@ -507,38 +541,6 @@ uint256 juint256(cJSON *obj) return(revuint256(tmp)); } -cJSON *cclib_reparse(int32_t *nump,cJSON *origparams) // assumes origparams will be freed by caller -{ - cJSON *params; char *jsonstr,*newstr; int32_t i,j; - if ( (jsonstr= jprint(origparams,0)) != 0 ) - { - if ( jsonstr[0] == '"' && jsonstr[strlen(jsonstr)-1] == '"' ) - { - jsonstr[strlen(jsonstr)-1] = 0; - jsonstr++; - } - newstr = (char *)malloc(strlen(jsonstr)+1); - for (i=j=0; jsonstr[i]!=0; i++) - { - if ( jsonstr[i] == '%' && jsonstr[i+1] == '2' && jsonstr[i+2] == '2' ) - { - newstr[j++] = '"'; - i += 2; - } - else if ( jsonstr[i] == '\'' ) - newstr[j++] = '"'; - else newstr[j++] = jsonstr[i]; - } - newstr[j] = 0; - params = cJSON_Parse(newstr); - if ( 1 && params != 0 ) - printf("new.(%s) -> %s\n",newstr,jprint(params,0)); - free(newstr); - *nump = cJSON_GetArraySize(params); - //free(origparams); - } else params = 0; - return(params); -} #ifdef BUILD_ROGUE #include "rogue_rpc.cpp" diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index decb6fb96..3965416c4 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5396,7 +5396,7 @@ UniValue cclibinfo(const UniValue& params, bool fHelp) UniValue cclib(const UniValue& params, bool fHelp) { - struct CCcontract_info *cp,C; char *method; cJSON *jsonparams=0; uint8_t evalcode = EVAL_FIRSTUSER; + struct CCcontract_info *cp,C; char *method,*jsonstr=0; uint8_t evalcode = EVAL_FIRSTUSER; if ( fHelp || params.size() > 3 ) throw runtime_error("cclib method [evalcode] [JSON params]\n"); if ( ASSETCHAINS_CCLIB.size() == 0 ) @@ -5417,11 +5417,11 @@ UniValue cclib(const UniValue& params, bool fHelp) if ( params.size() == 3 ) { //fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); - jsonparams = cJSON_Parse(params[2].get_str().c_str()); + jsonparams = params[2].get_str().c_str(); } } cp = CCinit(&C,evalcode); - return(CClib(cp,method,jsonparams)); + return(CClib(cp,method,jsonstr)); } UniValue oraclesaddress(const UniValue& params, bool fHelp) From d9a52ff53cd8099f5dac9a768a68df26eb1f83c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:08:13 -1100 Subject: [PATCH 0943/1145] if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) --- src/cc/musig.cpp | 6 +++--- src/cc/rogue_rpc.cpp | 16 ++++++++-------- src/cc/sudoku.cpp | 2 +- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 800102e13..04f3fe35d 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -86,7 +86,7 @@ int32_t musig_prevoutmsg(uint8_t *msg,uint256 sendtxid,CScript scriptPubKey) UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); uint256 sendtxid; int32_t i; uint8_t msg[32]; char *scriptstr,str[65]; int32_t n; - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n == 2 ) { @@ -183,7 +183,7 @@ UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) txfee = MUSIG_TXFEE; mypk = pubkey2pk(Mypubkey()); musigpk = GetUnspendable(cp,0); - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n == 2 && (hexstr= jstr(jitem(params,0),0)) != 0 && is_hexstr(hexstr,0) == 66 ) { @@ -206,7 +206,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; secp256k1_schnorrsig musig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n == 3 ) { diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 2d34d27c8..60d9a5cfd 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -657,7 +657,7 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey roguepk,mypk; char *jsonstr; uint64_t inputsum,change,required,buyin=0; int32_t i,n,maxplayers = 1; if ( txfee == 0 ) txfee = 10000; - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { @@ -693,7 +693,7 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue result(UniValue::VOBJ); std::vector playerdata; uint256 playertxid,tokenid,origplayergame;int32_t n; CPubKey pk; bits256 t; std::string symbol,pname; result.push_back(Pair("result","success")); rogue_univalue(result,"playerinfo",-1,-1); - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { @@ -723,7 +723,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) roguepk = GetUnspendable(cp,0); rogue_univalue(result,"register",-1,-1); playertxid = tokenid = zeroid; - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { @@ -803,7 +803,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( txfee == 0 ) txfee = 10000; rogue_univalue(result,"keystrokes",-1,-1); - if ( (params= cclib_reparse(&n,params)) != 0 && n == 2 && (keystrokestr= jstr(jitem(params,1),0)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) == 2 && (keystrokestr= jstr(jitem(params,1),0)) != 0 ) { gametxid = juint256(jitem(params,0)); result.push_back(Pair("gametxid",gametxid.GetHex())); @@ -896,7 +896,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) roguepk = GetUnspendable(cp,0); result.push_back(Pair("name","rogue")); result.push_back(Pair("method","extract")); - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { @@ -968,7 +968,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param funcid = 'H'; mult = 200000; } - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { @@ -1081,7 +1081,7 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,gameheight,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; uint64_t seed; bits256 t; char myrogueaddr[64]; CPubKey mypk,roguepk; result.push_back(Pair("name","rogue")); result.push_back(Pair("method","gameinfo")); - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { @@ -1212,7 +1212,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); int32_t n; char *namestr = 0; rogue_univalue(result,"setname",-1,-1); - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 0 ) { diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index d48a1bc2c..a8e7c651b 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2817,7 +2817,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params good = 0; if ( params != 0 ) { - if ( (params= cclib_reparse(&n,params)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) { if ( n > 2 && n <= (sizeof(timestamps)/sizeof(*timestamps))+2 ) { From 2dff5b98f025b4dda5b391d93e447956211c4934 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:10:26 -1100 Subject: [PATCH 0944/1145] Jsonstr --- src/wallet/rpcwallet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 3965416c4..36172a612 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5417,7 +5417,7 @@ UniValue cclib(const UniValue& params, bool fHelp) if ( params.size() == 3 ) { //fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); - jsonparams = params[2].get_str().c_str(); + jsonstr = params[2].get_str().c_str(); } } cp = CCinit(&C,evalcode); From 695278546955eeab749f3f3b2b5a8f7a0f8eff5a Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:12:58 -1100 Subject: [PATCH 0945/1145] params --- src/cc/musig.cpp | 6 +++--- src/cc/rogue_rpc.cpp | 16 ++++++++-------- src/cc/sudoku.cpp | 2 +- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 04f3fe35d..5d56635aa 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -86,7 +86,7 @@ int32_t musig_prevoutmsg(uint8_t *msg,uint256 sendtxid,CScript scriptPubKey) UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); uint256 sendtxid; int32_t i; uint8_t msg[32]; char *scriptstr,str[65]; int32_t n; - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n == 2 ) { @@ -183,7 +183,7 @@ UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) txfee = MUSIG_TXFEE; mypk = pubkey2pk(Mypubkey()); musigpk = GetUnspendable(cp,0); - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n == 2 && (hexstr= jstr(jitem(params,0),0)) != 0 && is_hexstr(hexstr,0) == 66 ) { @@ -206,7 +206,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; secp256k1_schnorrsig musig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n == 3 ) { diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 60d9a5cfd..57ce1e14b 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -657,7 +657,7 @@ UniValue rogue_newgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey roguepk,mypk; char *jsonstr; uint64_t inputsum,change,required,buyin=0; int32_t i,n,maxplayers = 1; if ( txfee == 0 ) txfee = 10000; - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { @@ -693,7 +693,7 @@ UniValue rogue_playerinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue result(UniValue::VOBJ); std::vector playerdata; uint256 playertxid,tokenid,origplayergame;int32_t n; CPubKey pk; bits256 t; std::string symbol,pname; result.push_back(Pair("result","success")); rogue_univalue(result,"playerinfo",-1,-1); - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { @@ -723,7 +723,7 @@ UniValue rogue_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) roguepk = GetUnspendable(cp,0); rogue_univalue(result,"register",-1,-1); playertxid = tokenid = zeroid; - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { @@ -803,7 +803,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( txfee == 0 ) txfee = 10000; rogue_univalue(result,"keystrokes",-1,-1); - if ( params != 0 && (n= cJSON_GetArraySize()) == 2 && (keystrokestr= jstr(jitem(params,1),0)) != 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 2 && (keystrokestr= jstr(jitem(params,1),0)) != 0 ) { gametxid = juint256(jitem(params,0)); result.push_back(Pair("gametxid",gametxid.GetHex())); @@ -896,7 +896,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) roguepk = GetUnspendable(cp,0); result.push_back(Pair("name","rogue")); result.push_back(Pair("method","extract")); - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { @@ -968,7 +968,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param funcid = 'H'; mult = 200000; } - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { @@ -1081,7 +1081,7 @@ UniValue rogue_gameinfo(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ),a(UniValue::VARR); int32_t i,n,gameheight,maxplayers,numvouts; uint256 txid; CTransaction tx; int64_t buyin; uint64_t seed; bits256 t; char myrogueaddr[64]; CPubKey mypk,roguepk; result.push_back(Pair("name","rogue")); result.push_back(Pair("method","gameinfo")); - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { @@ -1212,7 +1212,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); int32_t n; char *namestr = 0; rogue_univalue(result,"setname",-1,-1); - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 0 ) { diff --git a/src/cc/sudoku.cpp b/src/cc/sudoku.cpp index a8e7c651b..49bcf79d9 100644 --- a/src/cc/sudoku.cpp +++ b/src/cc/sudoku.cpp @@ -2817,7 +2817,7 @@ UniValue sudoku_solution(uint64_t txfee,struct CCcontract_info *cp,cJSON *params good = 0; if ( params != 0 ) { - if ( params != 0 && (n= cJSON_GetArraySize()) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n > 2 && n <= (sizeof(timestamps)/sizeof(*timestamps))+2 ) { From 0dd112c6d85de51692730161a31ff06646e29ea5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:16:37 -1100 Subject: [PATCH 0946/1145] Syntax --- src/cc/cclib.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 88db00732..f17f04273 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -125,7 +125,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); cJSON *cclib_reparse(int32_t *nump,char *jsonstr) // assumes origparams will be freed by caller { - cJSON *params; char *jsonstr,*newstr; int32_t i,j; + cJSON *params; char *newstr; int32_t i,j; *nump = 0; if ( jsonstr != 0 ) { @@ -286,7 +286,7 @@ UniValue CClib_info(struct CCcontract_info *cp) UniValue CClib(struct CCcontract_info *cp,char *method,char *jsonstr) { - UniValue result(UniValue::VOBJ); int32_t i; std::string rawtx; + UniValue result(UniValue::VOBJ); int32_t i; std::string rawtx; cJSON *params; printf("CClib params.(%s)\n",jsonstr!=0?jsonstr:""); for (i=0; i Date: Wed, 20 Feb 2019 23:17:40 -1100 Subject: [PATCH 0947/1145] Char * --- src/wallet/rpcwallet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 36172a612..ab8992c0d 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5417,7 +5417,7 @@ UniValue cclib(const UniValue& params, bool fHelp) if ( params.size() == 3 ) { //fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); - jsonstr = params[2].get_str().c_str(); + jsonstr = (char *)params[2].get_str().c_str(); } } cp = CCinit(&C,evalcode); From d58bfc8a7fbda8a03f009f2242dd5df7e3c9a106 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:20:37 -1100 Subject: [PATCH 0948/1145] Prints --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index f17f04273..3f4a5d6a8 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -160,6 +160,7 @@ cJSON *cclib_reparse(int32_t *nump,char *jsonstr) // assumes origparams will be UniValue CClib_method(struct CCcontract_info *cp,char *method,char *jsonstr) { UniValue result(UniValue::VOBJ); uint64_t txfee = 10000; int32_t m; cJSON *params = cclib_reparse(&m,jsonstr); + fprintf(stderr,"method.(%s) -> (%s)\n",jsonstr!=0?jsonstr:"",params!=0?jprint(params,0):""); #ifdef BUILD_ROGUE if ( cp->evalcode == EVAL_ROGUE ) { From e392999374bfb4cded273a333aeac44c52739a99 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:24:27 -1100 Subject: [PATCH 0949/1145] Jsonstr --- src/wallet/rpcwallet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index ab8992c0d..de4b22b7e 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5416,8 +5416,8 @@ UniValue cclib(const UniValue& params, bool fHelp) } if ( params.size() == 3 ) { - //fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),params[2].get_str().c_str()); jsonstr = (char *)params[2].get_str().c_str(); + fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),jsonstr); } } cp = CCinit(&C,evalcode); From 0cc4ef9d9008f73e3f0ff855a80bb048372de4d8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:26:36 -1100 Subject: [PATCH 0950/1145] Test --- src/cc/rogue/main.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 6ac9efe3b..49a09a5cf 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -450,7 +450,7 @@ try_again: databuf = (char *)malloc(256 + strlen(command) + strlen(params)); sprintf(databuf,"{\"id\":\"jl777\",\"method\":\"%s\",\"params\":%s%s%s}",command,bracket0,params,bracket1); - //printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); + printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); // } //else if ( specialcase != 0 ) fprintf(stderr,"databuf.(%s)\n",params); curl_easy_setopt(curl_handle,CURLOPT_POST,1L); @@ -742,7 +742,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } else { - sprintf(params,"[\"gameinfo\",\"17\",\\\"[%%22%s%%22]\\\"]",gametxidstr); + sprintf(params,"[\"gameinfo\",\"17\",\"[%%22%s%%22]\"]",gametxidstr); filestr = komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT); } if ( filestr != 0 ) From 13ba8a70ca9a86f8964d1c0b478b984b4921cadd Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:28:57 -1100 Subject: [PATCH 0951/1145] -prints --- src/cc/cclib.cpp | 4 ++-- src/cc/rogue/main.c | 2 +- src/wallet/rpcwallet.cpp | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 3f4a5d6a8..a595f5559 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -160,7 +160,7 @@ cJSON *cclib_reparse(int32_t *nump,char *jsonstr) // assumes origparams will be UniValue CClib_method(struct CCcontract_info *cp,char *method,char *jsonstr) { UniValue result(UniValue::VOBJ); uint64_t txfee = 10000; int32_t m; cJSON *params = cclib_reparse(&m,jsonstr); - fprintf(stderr,"method.(%s) -> (%s)\n",jsonstr!=0?jsonstr:"",params!=0?jprint(params,0):""); + //fprintf(stderr,"method.(%s) -> (%s)\n",jsonstr!=0?jsonstr:"",params!=0?jprint(params,0):""); #ifdef BUILD_ROGUE if ( cp->evalcode == EVAL_ROGUE ) { @@ -288,7 +288,7 @@ UniValue CClib_info(struct CCcontract_info *cp) UniValue CClib(struct CCcontract_info *cp,char *method,char *jsonstr) { UniValue result(UniValue::VOBJ); int32_t i; std::string rawtx; cJSON *params; - printf("CClib params.(%s)\n",jsonstr!=0?jsonstr:""); + //printf("CClib params.(%s)\n",jsonstr!=0?jsonstr:""); for (i=0; ievalcode == CClib_methods[i].evalcode && strcmp(method,CClib_methods[i].method) == 0 ) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 49a09a5cf..af357feb8 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -450,7 +450,7 @@ try_again: databuf = (char *)malloc(256 + strlen(command) + strlen(params)); sprintf(databuf,"{\"id\":\"jl777\",\"method\":\"%s\",\"params\":%s%s%s}",command,bracket0,params,bracket1); - printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); + //printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf); // } //else if ( specialcase != 0 ) fprintf(stderr,"databuf.(%s)\n",params); curl_easy_setopt(curl_handle,CURLOPT_POST,1L); diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index de4b22b7e..0ed2f866c 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5417,7 +5417,7 @@ UniValue cclib(const UniValue& params, bool fHelp) if ( params.size() == 3 ) { jsonstr = (char *)params[2].get_str().c_str(); - fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),jsonstr); + //fprintf(stderr,"params.(%s %s %s)\n",params[0].get_str().c_str(),params[1].get_str().c_str(),jsonstr); } } cp = CCinit(&C,evalcode); From 89e375e95dbccb5877f55a94c298134e6f5f8fe6 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:32:23 -1100 Subject: [PATCH 0952/1145] Resultjson --- src/cc/cclib.cpp | 2 +- src/cc/rogue/main.c | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index a595f5559..625872483 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -148,7 +148,7 @@ cJSON *cclib_reparse(int32_t *nump,char *jsonstr) // assumes origparams will be } newstr[j] = 0; params = cJSON_Parse(newstr); - if ( 1 && params != 0 ) + if ( 0 && params != 0 ) printf("new.(%s) -> %s\n",newstr,jprint(params,0)); free(newstr); *nump = cJSON_GetArraySize(params); diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index af357feb8..32967614c 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -727,7 +727,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) { - char cmd[32768]; int32_t i,n,retval=-1; char params[1024],*filestr=0,*pname,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item; + char cmd[32768]; int32_t i,n,retval=-1; char params[1024],*filestr=0,*pname,*statusstr,*datastr,fname[128]; long allocsize; cJSON *retjson,*array,*item,*resultjson; if ( rs->guiflag == 0 ) return(-1); if ( gametxidstr == 0 || *gametxidstr == 0 ) @@ -747,10 +747,10 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } if ( filestr != 0 ) { - fprintf(stderr,"gameinfo.(%s)\n",filestr); - if ( (retjson= cJSON_Parse(filestr)) != 0 ) + if ( (retjson= cJSON_Parse(filestr)) != 0 && (resultjson= jitem(retjson,"result")) != 0 ) { - if ( (array= jarray(&n,retjson,"players")) != 0 ) + fprintf(stderr,"gameinfo.(%s)\n",jprint(resultjson,0)); + if ( (array= jarray(&n,resultjson,"players")) != 0 ) { for (i=0; i Date: Wed, 20 Feb 2019 23:32:59 -1100 Subject: [PATCH 0953/1145] jobj --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 32967614c..7971a9b3d 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -747,7 +747,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) } if ( filestr != 0 ) { - if ( (retjson= cJSON_Parse(filestr)) != 0 && (resultjson= jitem(retjson,"result")) != 0 ) + if ( (retjson= cJSON_Parse(filestr)) != 0 && (resultjson= jobj(retjson,"result")) != 0 ) { fprintf(stderr,"gameinfo.(%s)\n",jprint(resultjson,0)); if ( (array= jarray(&n,resultjson,"players")) != 0 ) From 2fdc745c0b75bf03ede1bb02be566eaff6b5b026 Mon Sep 17 00:00:00 2001 From: jl777 Date: Wed, 20 Feb 2019 23:35:42 -1100 Subject: [PATCH 0954/1145] -print --- src/cc/rogue/main.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 7971a9b3d..ca05226d3 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -718,7 +718,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { - fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); + //fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); free(retstr); } } @@ -749,7 +749,7 @@ int32_t rogue_setplayerdata(struct rogue_state *rs,char *gametxidstr) { if ( (retjson= cJSON_Parse(filestr)) != 0 && (resultjson= jobj(retjson,"result")) != 0 ) { - fprintf(stderr,"gameinfo.(%s)\n",jprint(resultjson,0)); + //fprintf(stderr,"gameinfo.(%s)\n",jprint(resultjson,0)); if ( (array= jarray(&n,resultjson,"players")) != 0 ) { for (i=0; i Date: Thu, 21 Feb 2019 00:19:53 -1100 Subject: [PATCH 0955/1145] ../secp256k1/src/ --- src/cc/cclib.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 625872483..df60833d2 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -584,9 +584,12 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" -//#define USE_BASIC_CONFIG -//#include "../secp256k1/src/basic-config.h" +#define USE_BASIC_CONFIG +#include "../secp256k1/src/basic-config.h" //#include "../secp256k1/src/secp256k1.c" +#include "../secp256k1/src/modules/schnorrsig/main_impl.h" +#include "../secp256k1/src/modules/musig/main_impl.h" + #include "musig.cpp" #endif From 9d8ec78d880dce011f65bc67d680656a9d0a9322 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:21:49 -1100 Subject: [PATCH 0956/1145] ../secp256k1/src/ --- src/cc/cclib.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index df60833d2..2ccfcce46 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -586,6 +586,21 @@ uint256 juint256(cJSON *obj) #include "sudoku.cpp" #define USE_BASIC_CONFIG #include "../secp256k1/src/basic-config.h" +#include "../secp256k1/include/secp256k1.h" + +#include "../secp256k1/src/util.h" +#include "../secp256k1/src/num_impl.h" +#include "../secp256k1/src/field_impl.h" +#include "../secp256k1/src/scalar_impl.h" +#include "../secp256k1/src/group_impl.h" +#include "../secp256k1/src/ecmult_impl.h" +#include "../secp256k1/src/ecmult_const_impl.h" +#include "../secp256k1/src/ecmult_gen_impl.h" +#include "../secp256k1/src/ecdsa_impl.h" +#include "../secp256k1/src/eckey_impl.h" +#include "../secp256k1/src/hash_impl.h" +#include "../secp256k1/src/scratch_impl.h" + //#include "../secp256k1/src/secp256k1.c" #include "../secp256k1/src/modules/schnorrsig/main_impl.h" #include "../secp256k1/src/modules/musig/main_impl.h" From df9f4a10928e80e91fc83c01dc5c49767490398e Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:22:54 -1100 Subject: [PATCH 0957/1145] ARG_CHECK --- src/cc/cclib.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 2ccfcce46..b6a79b32e 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -601,6 +601,13 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/hash_impl.h" #include "../secp256k1/src/scratch_impl.h" +#define ARG_CHECK(cond) do { \ +if (EXPECT(!(cond), 0)) { \ +secp256k1_callback_call(&ctx->illegal_callback, #cond); \ +return 0; \ +} \ +} while(0) + //#include "../secp256k1/src/secp256k1.c" #include "../secp256k1/src/modules/schnorrsig/main_impl.h" #include "../secp256k1/src/modules/musig/main_impl.h" From b9c1f3bc3d1e46f524abc207d9a5166bebd107a0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:33:15 -1100 Subject: [PATCH 0958/1145] Ctx --- src/cc/cclib.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index b6a79b32e..496005016 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -601,6 +601,13 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/hash_impl.h" #include "../secp256k1/src/scratch_impl.h" +struct secp256k1_context_struct { + secp256k1_ecmult_context ecmult_ctx; + secp256k1_ecmult_gen_context ecmult_gen_ctx; + secp256k1_callback illegal_callback; + secp256k1_callback error_callback; +}; + #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ secp256k1_callback_call(&ctx->illegal_callback, #cond); \ From 6d3246be8115432643197f91b6ae3000a2a08c0b Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:39:15 -1100 Subject: [PATCH 0959/1145] Declare --- src/cc/cclib.cpp | 5 +++++ src/secp256k1/src/ecmult.h | 2 +- src/secp256k1/src/scalar.h | 2 +- src/secp256k1/src/scalar_4x64_impl.h | 2 +- src/secp256k1/src/scalar_8x32_impl.h | 2 +- src/secp256k1/src/scalar_low_impl.h | 2 +- src/secp256k1/src/secp256k1.c | 4 ++-- 7 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 496005016..da8829de6 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -608,6 +608,11 @@ struct secp256k1_context_struct { secp256k1_callback error_callback; }; +int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); +int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); +void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); +int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); + #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ secp256k1_callback_call(&ctx->illegal_callback, #cond); \ diff --git a/src/secp256k1/src/ecmult.h b/src/secp256k1/src/ecmult.h index 4f12090a7..fbcf6a445 100644 --- a/src/secp256k1/src/ecmult.h +++ b/src/secp256k1/src/ecmult.h @@ -78,7 +78,7 @@ typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge * 0 if there is not enough scratch space for a single point or * callback returns 0 */ -static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); #endif /* SECP256K1_ECMULT_H */ diff --git a/src/secp256k1/src/scalar.h b/src/secp256k1/src/scalar.h index 3213d302b..d83ccc22a 100644 --- a/src/secp256k1/src/scalar.h +++ b/src/secp256k1/src/scalar.h @@ -218,7 +218,7 @@ static void secp256k1_scalar_split_lambda(secp256k1_scalar *r1, secp256k1_scalar static void secp256k1_scalar_mul_shift_var(secp256k1_scalar *r, const secp256k1_scalar *a, const secp256k1_scalar *b, unsigned int shift); /** Generate two scalars from a 32-byte seed and an integer using the chacha20 stream cipher */ -static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); +void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); #endif /* SECP256K1_SCALAR_H */ #endif diff --git a/src/secp256k1/src/scalar_4x64_impl.h b/src/secp256k1/src/scalar_4x64_impl.h index b1b62ac1f..04f1da85d 100644 --- a/src/secp256k1/src/scalar_4x64_impl.h +++ b/src/secp256k1/src/scalar_4x64_impl.h @@ -1925,7 +1925,7 @@ c += d; b = ROTL32(b ^ c, 7); #define LE32(p) (p) #endif -static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx) { +void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx) { size_t n; size_t over_count = 0; uint32_t seed32[8]; diff --git a/src/secp256k1/src/scalar_8x32_impl.h b/src/secp256k1/src/scalar_8x32_impl.h index ff7bf5ee4..f1429b162 100644 --- a/src/secp256k1/src/scalar_8x32_impl.h +++ b/src/secp256k1/src/scalar_8x32_impl.h @@ -1471,7 +1471,7 @@ c += d; b = ROTL32(b ^ c, 7); #define LE32(p) (p) #endif -static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx) { +void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx) { size_t n; size_t over_count = 0; uint32_t seed32[8]; diff --git a/src/secp256k1/src/scalar_low_impl.h b/src/secp256k1/src/scalar_low_impl.h index c6c65ff5b..cc83eb8c7 100644 --- a/src/secp256k1/src/scalar_low_impl.h +++ b/src/secp256k1/src/scalar_low_impl.h @@ -230,7 +230,7 @@ SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const return *a == *b; } -SECP256K1_INLINE static void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t n) { +SECP256K1_INLINE void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t n) { *r1 = (seed[0] + n) % EXHAUSTIVE_TEST_ORDER; *r2 = (seed[1] + n) % EXHAUSTIVE_TEST_ORDER; } diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 657893d0d..1acb028d2 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -115,7 +115,7 @@ void secp256k1_context_set_error_callback(secp256k1_context* ctx, void (*fun)(co ctx->error_callback.data = data; } -static int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { +int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { if (sizeof(secp256k1_ge_storage) == 64) { /* When the secp256k1_ge_storage type is exactly 64 byte, use its * representation inside secp256k1_pubkey, as conversion is very fast. @@ -342,7 +342,7 @@ static int nonce_function_rfc6979(unsigned char *nonce32, const unsigned char *m /* This nonce function is described in BIP-schnorr * (https://github.com/sipa/bips/blob/bip-schnorr/bip-schnorr.mediawiki) */ -static int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { +int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { secp256k1_sha256 sha; (void) data; (void) counter; From 8ceea089ae28523f1cf1347adcf9c54893ca8aa4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:41:42 -1100 Subject: [PATCH 0960/1145] typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); --- src/cc/cclib.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index da8829de6..9f66e7022 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -608,6 +608,8 @@ struct secp256k1_context_struct { secp256k1_callback error_callback; }; +typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); + int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); From b81052aff00e17a4e659da9a4e8fd68812215fc1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:44:37 -1100 Subject: [PATCH 0961/1145] void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge) --- src/cc/cclib.cpp | 2 +- src/secp256k1/src/ecmult_impl.h | 4 ++-- src/secp256k1/src/secp256k1.c | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 9f66e7022..1d7bedd82 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -609,7 +609,7 @@ struct secp256k1_context_struct { }; typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); - +void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 6c9a1daf2..6f2242d7c 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1497,7 +1497,7 @@ static size_t secp256k1_pippenger_max_points(secp256k1_scratch *scratch) { /* Computes ecmult_multi by simply multiplying and adding each point. Does not * require a scratch space */ -static int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { + int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { size_t point_idx; secp256k1_scalar szero; secp256k1_gej tmpj; @@ -1522,7 +1522,7 @@ static int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx } typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t); -static int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { +int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { size_t i; int (*f)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t, size_t); diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 1acb028d2..2b219b589 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -134,7 +134,7 @@ int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const return 1; } -static void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge) { +void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge) { if (sizeof(secp256k1_ge_storage) == 64) { secp256k1_ge_storage s; secp256k1_ge_to_storage(&s, ge); From 82bacc85ff2d319c7fb8213e5e69796f5079f3c9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:47:38 -1100 Subject: [PATCH 0962/1145] "C" --- src/cc/cclib.cpp | 2 +- src/secp256k1/src/secp256k1.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 1d7bedd82..c63d03a38 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -611,7 +611,7 @@ struct secp256k1_context_struct { typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); -int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); +"C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 2b219b589..8be12059d 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -115,7 +115,7 @@ void secp256k1_context_set_error_callback(secp256k1_context* ctx, void (*fun)(co ctx->error_callback.data = data; } -int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { +extern "C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { if (sizeof(secp256k1_ge_storage) == 64) { /* When the secp256k1_ge_storage type is exactly 64 byte, use its * representation inside secp256k1_pubkey, as conversion is very fast. From da61c3f152361c5ba0b7f8a3684b59cc1be01c0d Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:48:14 -1100 Subject: [PATCH 0963/1145] Extern "C" --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index c63d03a38..7fb06259a 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -611,7 +611,7 @@ struct secp256k1_context_struct { typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); -"C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); +extern "C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); From bb264c86e12bc41f3688ae2a9b7f5fbda76ff42c Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:49:07 -1100 Subject: [PATCH 0964/1145] "C" --- src/secp256k1/src/secp256k1.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 8be12059d..f39d373e3 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -115,7 +115,7 @@ void secp256k1_context_set_error_callback(secp256k1_context* ctx, void (*fun)(co ctx->error_callback.data = data; } -extern "C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { +"C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { if (sizeof(secp256k1_ge_storage) == 64) { /* When the secp256k1_ge_storage type is exactly 64 byte, use its * representation inside secp256k1_pubkey, as conversion is very fast. From 85dfd9107105a311ce7a84cb28b7328fac6f5d19 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:49:44 -1100 Subject: [PATCH 0965/1145] -"C" --- src/secp256k1/src/secp256k1.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index f39d373e3..2b219b589 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -115,7 +115,7 @@ void secp256k1_context_set_error_callback(secp256k1_context* ctx, void (*fun)(co ctx->error_callback.data = data; } -"C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { +int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey) { if (sizeof(secp256k1_ge_storage) == 64) { /* When the secp256k1_ge_storage type is exactly 64 byte, use its * representation inside secp256k1_pubkey, as conversion is very fast. From 0e67be94c996dc2cdcfa6bbdd9374b59528aab1b Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 00:51:20 -1100 Subject: [PATCH 0966/1145] Extern "C" --- src/cc/cclib.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 7fb06259a..e6b405955 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -609,11 +609,11 @@ struct secp256k1_context_struct { }; typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); -void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); -int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); +extern "C" void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); +extern "C" int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); extern "C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); -void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); -int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +extern "C" void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); +extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ From 991766db5f089befe038ff7b061d88c1c82af691 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:01:31 -1100 Subject: [PATCH 0967/1145] -ENABLE_MODULE_MUSIG --- src/secp256k1/Makefile.am | 2 +- src/secp256k1/src/secp256k1.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 089d3ee8e..7603cc626 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -73,7 +73,7 @@ endif endif libsecp256k1_la_SOURCES = src/secp256k1.c -libsecp256k1_la_CPPFLAGS = -DENABLE_MODULE_MUSIG -DSECP256K1_BUILD -I$(top_srcdir)/include -I$(top_srcdir)/src $(SECP_INCLUDES) +libsecp256k1_la_CPPFLAGS = -DSECP256K1_BUILD -I$(top_srcdir)/include -I$(top_srcdir)/src $(SECP_INCLUDES) libsecp256k1_la_LIBADD = $(JNI_LIB) $(SECP_LIBS) $(COMMON_LIB) libsecp256k1_jni_la_SOURCES = src/java/org_bitcoin_NativeSecp256k1.c src/java/org_bitcoin_Secp256k1Context.c diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 2b219b589..4643ab903 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -601,8 +601,8 @@ int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey * # include "modules/ecdh/main_impl.h" #endif -#include "modules/schnorrsig/main_impl.h" -#include "modules/musig/main_impl.h" +//#include "modules/schnorrsig/main_impl.h" +//#include "modules/musig/main_impl.h" #ifdef ENABLE_MODULE_RECOVERY From db9f81504bca3e1f50f76e06fe0c9e3909c3e5cb Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:02:56 -1100 Subject: [PATCH 0968/1145] Revert --- src/secp256k1/src/secp256k1.c | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 4643ab903..065ce72d4 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -17,7 +17,6 @@ #include "ecdsa_impl.h" #include "eckey_impl.h" #include "hash_impl.h" -#include "scratch_impl.h" #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ @@ -601,9 +600,6 @@ int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey * # include "modules/ecdh/main_impl.h" #endif -//#include "modules/schnorrsig/main_impl.h" -//#include "modules/musig/main_impl.h" - #ifdef ENABLE_MODULE_RECOVERY # include "modules/recovery/main_impl.h" From 340c8ba1ca2e30a7b182f282ff005264d020b3f5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:04:53 -1100 Subject: [PATCH 0969/1145] -SCALAR_INLINE --- src/secp256k1/src/scalar_low_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/scalar_low_impl.h b/src/secp256k1/src/scalar_low_impl.h index cc83eb8c7..956cccd04 100644 --- a/src/secp256k1/src/scalar_low_impl.h +++ b/src/secp256k1/src/scalar_low_impl.h @@ -230,7 +230,7 @@ SECP256K1_INLINE static int secp256k1_scalar_eq(const secp256k1_scalar *a, const return *a == *b; } -SECP256K1_INLINE void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t n) { +void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t n) { *r1 = (seed[0] + n) % EXHAUSTIVE_TEST_ORDER; *r2 = (seed[1] + n) % EXHAUSTIVE_TEST_ORDER; } From 1d47bd1cc7167d03c59b18b68453e69d8e03670b Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:08:23 -1100 Subject: [PATCH 0970/1145] Pippenger --- src/secp256k1/src/ecmult_impl.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 6f2242d7c..88a9cfae2 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1154,6 +1154,8 @@ static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { return skew; } +#endif /* SECP256K1_ECMULT_IMPL_H */ + struct secp256k1_pippenger_point_state { int skew_na; size_t input_pos; @@ -1497,7 +1499,7 @@ static size_t secp256k1_pippenger_max_points(secp256k1_scratch *scratch) { /* Computes ecmult_multi by simply multiplying and adding each point. Does not * require a scratch space */ - int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { +int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { size_t point_idx; secp256k1_scalar szero; secp256k1_gej tmpj; @@ -1522,6 +1524,7 @@ static size_t secp256k1_pippenger_max_points(secp256k1_scratch *scratch) { } typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t); + int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { size_t i; @@ -1576,7 +1579,5 @@ int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_sc return 1; } -#endif /* SECP256K1_ECMULT_IMPL_H */ - #endif From 0caedf0c8c60ea9536cc15c39bc4967bfec2c463 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:09:43 -1100 Subject: [PATCH 0971/1145] Move endif --- src/secp256k1/src/ecmult_impl.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 88a9cfae2..48d8af8f4 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1155,6 +1155,8 @@ static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { } #endif /* SECP256K1_ECMULT_IMPL_H */ +#endif + struct secp256k1_pippenger_point_state { int skew_na; @@ -1579,5 +1581,4 @@ int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_sc return 1; } -#endif From 22e3b0b00ddebfdd56e97d378904a181829fb858 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:12:00 -1100 Subject: [PATCH 0972/1145] scratch.h --- src/secp256k1/src/ecmult_impl.h | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 48d8af8f4..c0d21f4ba 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1157,6 +1157,20 @@ static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { #endif /* SECP256K1_ECMULT_IMPL_H */ #endif +#include "../scratch.h" + +/* The number of objects allocated on the scratch space for ecmult_multi algorithms */ +#define PIPPENGER_SCRATCH_OBJECTS 6 +#define STRAUSS_SCRATCH_OBJECTS 6 + +#define PIPPENGER_MAX_BUCKET_WINDOW 12 + +/* Minimum number of points for which pippenger_wnaf is faster than strauss wnaf */ +#ifdef USE_ENDOMORPHISM +#define ECMULT_PIPPENGER_THRESHOLD 88 +#else +#define ECMULT_PIPPENGER_THRESHOLD 160 +#endif struct secp256k1_pippenger_point_state { int skew_na; From 061dde468e52ca35a5307c37b19942871dadd89c Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:14:59 -1100 Subject: [PATCH 0973/1145] -.. --- src/secp256k1/src/ecmult_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index c0d21f4ba..2a0fac4e7 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1157,7 +1157,7 @@ static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { #endif /* SECP256K1_ECMULT_IMPL_H */ #endif -#include "../scratch.h" +#include "scratch.h" /* The number of objects allocated on the scratch space for ecmult_multi algorithms */ #define PIPPENGER_SCRATCH_OBJECTS 6 From f04c2097fb47546e6bdd3ccb10fae9d650f757b3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:21:14 -1100 Subject: [PATCH 0974/1145] Test --- src/secp256k1/src/ecmult_impl.h | 26 +++++--------------------- 1 file changed, 5 insertions(+), 21 deletions(-) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 2a0fac4e7..bc596608e 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1,4 +1,4 @@ -#ifndef ENABLE_MODULE_MUSIG +#ifdef always_do_ENABLE_MODULE_MUSIG /********************************************************************** @@ -1154,24 +1154,6 @@ static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { return skew; } -#endif /* SECP256K1_ECMULT_IMPL_H */ -#endif - -#include "scratch.h" - -/* The number of objects allocated on the scratch space for ecmult_multi algorithms */ -#define PIPPENGER_SCRATCH_OBJECTS 6 -#define STRAUSS_SCRATCH_OBJECTS 6 - -#define PIPPENGER_MAX_BUCKET_WINDOW 12 - -/* Minimum number of points for which pippenger_wnaf is faster than strauss wnaf */ -#ifdef USE_ENDOMORPHISM -#define ECMULT_PIPPENGER_THRESHOLD 88 -#else -#define ECMULT_PIPPENGER_THRESHOLD 160 -#endif - struct secp256k1_pippenger_point_state { int skew_na; size_t input_pos; @@ -1515,7 +1497,7 @@ static size_t secp256k1_pippenger_max_points(secp256k1_scratch *scratch) { /* Computes ecmult_multi by simply multiplying and adding each point. Does not * require a scratch space */ -int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { + int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n_points) { size_t point_idx; secp256k1_scalar szero; secp256k1_gej tmpj; @@ -1540,7 +1522,6 @@ int secp256k1_ecmult_multi_var_simple(const secp256k1_ecmult_context *ctx, secp2 } typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t); - int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { size_t i; @@ -1595,4 +1576,7 @@ int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_sc return 1; } +#endif /* SECP256K1_ECMULT_IMPL_H */ + +#endif From 75ffdd2e91b5779152c8a6eee1672ca9c29f62a3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:25:39 -1100 Subject: [PATCH 0975/1145] -DENABLE_MODULE_MUSIG --- src/secp256k1/Makefile.am | 2 +- src/secp256k1/src/ecmult.h | 1 - src/secp256k1/src/ecmult_impl.h | 2 +- src/secp256k1/src/secp256k1.c | 1 + 4 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/secp256k1/Makefile.am b/src/secp256k1/Makefile.am index 7603cc626..c5fa00fc5 100644 --- a/src/secp256k1/Makefile.am +++ b/src/secp256k1/Makefile.am @@ -73,7 +73,7 @@ endif endif libsecp256k1_la_SOURCES = src/secp256k1.c -libsecp256k1_la_CPPFLAGS = -DSECP256K1_BUILD -I$(top_srcdir)/include -I$(top_srcdir)/src $(SECP_INCLUDES) +libsecp256k1_la_CPPFLAGS = -DSECP256K1_BUILD -DENABLE_MODULE_MUSIG -I$(top_srcdir)/include -I$(top_srcdir)/src $(SECP_INCLUDES) libsecp256k1_la_LIBADD = $(JNI_LIB) $(SECP_LIBS) $(COMMON_LIB) libsecp256k1_jni_la_SOURCES = src/java/org_bitcoin_NativeSecp256k1.c src/java/org_bitcoin_Secp256k1Context.c diff --git a/src/secp256k1/src/ecmult.h b/src/secp256k1/src/ecmult.h index fbcf6a445..88475791b 100644 --- a/src/secp256k1/src/ecmult.h +++ b/src/secp256k1/src/ecmult.h @@ -45,7 +45,6 @@ static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej #include "num.h" #include "group.h" #include "scalar.h" -#include "scratch.h" typedef struct { /* For accelerating the computation of a*P + b*G: */ diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index bc596608e..116a9f154 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1,4 +1,4 @@ -#ifdef always_do_ENABLE_MODULE_MUSIG +#ifdef ENABLE_MODULE_MUSIG /********************************************************************** diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 065ce72d4..4225607ff 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -17,6 +17,7 @@ #include "ecdsa_impl.h" #include "eckey_impl.h" #include "hash_impl.h" +#include "scratch_impl.h" #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ From 5ee30cdd96d7fe085401b4b2bf7cc41c650f85e4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:30:47 -1100 Subject: [PATCH 0976/1145] scratch.h --- src/secp256k1/src/ecmult.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/secp256k1/src/ecmult.h b/src/secp256k1/src/ecmult.h index 88475791b..fbcf6a445 100644 --- a/src/secp256k1/src/ecmult.h +++ b/src/secp256k1/src/ecmult.h @@ -45,6 +45,7 @@ static void secp256k1_ecmult(const secp256k1_ecmult_context *ctx, secp256k1_gej #include "num.h" #include "group.h" #include "scalar.h" +#include "scratch.h" typedef struct { /* For accelerating the computation of a*P + b*G: */ From 57ef97ca58085e6d5204860e8a3763020da71219 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:38:49 -1100 Subject: [PATCH 0977/1145] #include "util.h" --- src/secp256k1/src/secp256k1.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 4225607ff..2f482803a 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -6,13 +6,13 @@ #include "../include/secp256k1.h" -#include "util.h" #include "num_impl.h" #include "field_impl.h" #include "scalar_impl.h" #include "group_impl.h" #include "ecmult_impl.h" #include "ecmult_const_impl.h" +#include "util.h" #include "ecmult_gen_impl.h" #include "ecdsa_impl.h" #include "eckey_impl.h" From 0a460a527382e5d59813d389bbc034df2ed7c07e Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:41:57 -1100 Subject: [PATCH 0978/1145] Header order --- src/secp256k1/src/secp256k1.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 2f482803a..e6af45df7 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -6,13 +6,13 @@ #include "../include/secp256k1.h" +#include "ecmult_impl.h" +#include "ecmult_const_impl.h" +#include "util.h" #include "num_impl.h" #include "field_impl.h" #include "scalar_impl.h" #include "group_impl.h" -#include "ecmult_impl.h" -#include "ecmult_const_impl.h" -#include "util.h" #include "ecmult_gen_impl.h" #include "ecdsa_impl.h" #include "eckey_impl.h" From d7e8e8d4b35c7dce5af8a60a5506515fdfe8e835 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:44:15 -1100 Subject: [PATCH 0979/1145] Fx --- src/cc/cclib.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index e6b405955..e570be7d1 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -588,13 +588,14 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" + +#include "../secp256k1/src/ecmult_impl.h" +#include "../secp256k1/src/ecmult_const_impl.h" #include "../secp256k1/src/util.h" #include "../secp256k1/src/num_impl.h" #include "../secp256k1/src/field_impl.h" #include "../secp256k1/src/scalar_impl.h" #include "../secp256k1/src/group_impl.h" -#include "../secp256k1/src/ecmult_impl.h" -#include "../secp256k1/src/ecmult_const_impl.h" #include "../secp256k1/src/ecmult_gen_impl.h" #include "../secp256k1/src/ecdsa_impl.h" #include "../secp256k1/src/eckey_impl.h" From 99bf645bf19752c76f813a4164b3dbdcd8d01f73 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:50:25 -1100 Subject: [PATCH 0980/1145] Revert --- src/cc/cclib.cpp | 5 ++--- src/secp256k1/src/secp256k1.c | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index e570be7d1..e6b405955 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -588,14 +588,13 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" - -#include "../secp256k1/src/ecmult_impl.h" -#include "../secp256k1/src/ecmult_const_impl.h" #include "../secp256k1/src/util.h" #include "../secp256k1/src/num_impl.h" #include "../secp256k1/src/field_impl.h" #include "../secp256k1/src/scalar_impl.h" #include "../secp256k1/src/group_impl.h" +#include "../secp256k1/src/ecmult_impl.h" +#include "../secp256k1/src/ecmult_const_impl.h" #include "../secp256k1/src/ecmult_gen_impl.h" #include "../secp256k1/src/ecdsa_impl.h" #include "../secp256k1/src/eckey_impl.h" diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index e6af45df7..4225607ff 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -6,13 +6,13 @@ #include "../include/secp256k1.h" -#include "ecmult_impl.h" -#include "ecmult_const_impl.h" #include "util.h" #include "num_impl.h" #include "field_impl.h" #include "scalar_impl.h" #include "group_impl.h" +#include "ecmult_impl.h" +#include "ecmult_const_impl.h" #include "ecmult_gen_impl.h" #include "ecdsa_impl.h" #include "eckey_impl.h" From ba4917acf45ec4943a2dcec065596446a6f581af Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:55:28 -1100 Subject: [PATCH 0981/1145] WNAF_SIZE --- src/secp256k1/src/ecmult_const_impl.h | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/src/ecmult_const_impl.h b/src/secp256k1/src/ecmult_const_impl.h index d8697e0e9..410c4a6b6 100644 --- a/src/secp256k1/src/ecmult_const_impl.h +++ b/src/secp256k1/src/ecmult_const_impl.h @@ -14,12 +14,20 @@ #include "ecmult_const.h" #include "ecmult_impl.h" +#ifdef USE_ENDOMORPHISM +#define WNAF_BITS 128 +#else +#define WNAF_BITS 256 +#endif +#define WNAF_SIZE_BITS(bits, w) (((bits) + (w) - 1) / (w)) +#define WNAF_SIZE(w) WNAF_SIZE_BITS(WNAF_BITS, w) + #ifdef USE_ENDOMORPHISM #define WNAF_BITS 128 #else #define WNAF_BITS 256 #endif -#define WNAF_SIZE(w) ((WNAF_BITS + (w) - 1) / (w)) +//#define WNAF_SIZE(w) ((WNAF_BITS + (w) - 1) / (w)) /* This is like `ECMULT_TABLE_GET_GE` but is constant time */ #define ECMULT_CONST_TABLE_GET_GE(r,pre,n,w) do { \ From 4fab71d374a4c64bfe1214b3e9c688e6e4f95748 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 01:59:32 -1100 Subject: [PATCH 0982/1145] Define WNAF BITS --- src/secp256k1/src/ecmult_const_impl.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/src/ecmult_const_impl.h b/src/secp256k1/src/ecmult_const_impl.h index 410c4a6b6..d2eaa2368 100644 --- a/src/secp256k1/src/ecmult_const_impl.h +++ b/src/secp256k1/src/ecmult_const_impl.h @@ -14,6 +14,7 @@ #include "ecmult_const.h" #include "ecmult_impl.h" + #ifdef USE_ENDOMORPHISM #define WNAF_BITS 128 #else @@ -22,12 +23,13 @@ #define WNAF_SIZE_BITS(bits, w) (((bits) + (w) - 1) / (w)) #define WNAF_SIZE(w) WNAF_SIZE_BITS(WNAF_BITS, w) +/* #ifdef USE_ENDOMORPHISM #define WNAF_BITS 128 #else #define WNAF_BITS 256 #endif -//#define WNAF_SIZE(w) ((WNAF_BITS + (w) - 1) / (w)) +#define WNAF_SIZE(w) ((WNAF_BITS + (w) - 1) / (w))*/ /* This is like `ECMULT_TABLE_GET_GE` but is constant time */ #define ECMULT_CONST_TABLE_GET_GE(r,pre,n,w) do { \ From 15fb6f16954f9c9a6b77330ac0ae641b4aa98343 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:03:12 -1100 Subject: [PATCH 0983/1145] ... --- src/secp256k1/src/ecmult_const_impl.h | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/secp256k1/src/ecmult_const_impl.h b/src/secp256k1/src/ecmult_const_impl.h index d2eaa2368..28636290d 100644 --- a/src/secp256k1/src/ecmult_const_impl.h +++ b/src/secp256k1/src/ecmult_const_impl.h @@ -15,21 +15,12 @@ #include "ecmult_impl.h" -#ifdef USE_ENDOMORPHISM -#define WNAF_BITS 128 -#else -#define WNAF_BITS 256 -#endif -#define WNAF_SIZE_BITS(bits, w) (((bits) + (w) - 1) / (w)) -#define WNAF_SIZE(w) WNAF_SIZE_BITS(WNAF_BITS, w) - -/* #ifdef USE_ENDOMORPHISM #define WNAF_BITS 128 #else #define WNAF_BITS 256 #endif -#define WNAF_SIZE(w) ((WNAF_BITS + (w) - 1) / (w))*/ +#define WNAF_SIZE(w) ((WNAF_BITS + (w) - 1) / (w)) /* This is like `ECMULT_TABLE_GET_GE` but is constant time */ #define ECMULT_CONST_TABLE_GET_GE(r,pre,n,w) do { \ @@ -266,6 +257,14 @@ static void secp256k1_ecmult_const(secp256k1_gej *r, const secp256k1_ge *a, cons #include "ecmult_const.h" #include "ecmult_impl.h" +#ifdef USE_ENDOMORPHISM +#define WNAF_BITS 128 +#else +#define WNAF_BITS 256 +#endif +#define WNAF_SIZE_BITS(bits, w) (((bits) + (w) - 1) / (w)) +#define WNAF_SIZE(w) WNAF_SIZE_BITS(WNAF_BITS, w) + /* This is like `ECMULT_TABLE_GET_GE` but is constant time */ #define ECMULT_CONST_TABLE_GET_GE(r,pre,n,w) do { \ int m; \ From 1b9cfb04a9a4dab9d8405ee90617e7c498bfd68a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:08:02 -1100 Subject: [PATCH 0984/1145] Scratch --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index e6b405955..4019bf422 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -600,6 +600,7 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/eckey_impl.h" #include "../secp256k1/src/hash_impl.h" #include "../secp256k1/src/scratch_impl.h" +#include "../secp256k1/src/scratch.h" struct secp256k1_context_struct { secp256k1_ecmult_context ecmult_ctx; From 1b099fca7157e64ccd27bccbb359626d78f749bc Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:09:33 -1100 Subject: [PATCH 0985/1145] Reorder --- src/cc/cclib.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 4019bf422..9a2f9c3ab 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -593,14 +593,13 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/field_impl.h" #include "../secp256k1/src/scalar_impl.h" #include "../secp256k1/src/group_impl.h" +#include "../secp256k1/src/scratch_impl.h" #include "../secp256k1/src/ecmult_impl.h" #include "../secp256k1/src/ecmult_const_impl.h" #include "../secp256k1/src/ecmult_gen_impl.h" #include "../secp256k1/src/ecdsa_impl.h" #include "../secp256k1/src/eckey_impl.h" #include "../secp256k1/src/hash_impl.h" -#include "../secp256k1/src/scratch_impl.h" -#include "../secp256k1/src/scratch.h" struct secp256k1_context_struct { secp256k1_ecmult_context ecmult_ctx; From 8c96abe167f9d9166a5eade2b16652dfdf1b4978 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:11:39 -1100 Subject: [PATCH 0986/1145] Enable --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 9a2f9c3ab..b02456b33 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -585,6 +585,7 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" #define USE_BASIC_CONFIG +#define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" From a244fe9cdc8abaaa2e510ecc8146ceb11229c890 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:14:20 -1100 Subject: [PATCH 0987/1145] removes --- src/cc/cclib.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index b02456b33..4fc753b8c 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -589,7 +589,7 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" -#include "../secp256k1/src/util.h" +/*#include "../secp256k1/src/util.h" #include "../secp256k1/src/num_impl.h" #include "../secp256k1/src/field_impl.h" #include "../secp256k1/src/scalar_impl.h" @@ -600,7 +600,7 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/ecmult_gen_impl.h" #include "../secp256k1/src/ecdsa_impl.h" #include "../secp256k1/src/eckey_impl.h" -#include "../secp256k1/src/hash_impl.h" +#include "../secp256k1/src/hash_impl.h"*/ struct secp256k1_context_struct { secp256k1_ecmult_context ecmult_ctx; From c95287714595b64b419d4af5c8e2ad31f9b9ee0f Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:16:57 -1100 Subject: [PATCH 0988/1145] Revert --- src/cc/cclib.cpp | 6 ++---- src/secp256k1/src/secp256k1.c | 2 ++ 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 4fc753b8c..3c0baf856 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -600,14 +600,14 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/ecmult_gen_impl.h" #include "../secp256k1/src/ecdsa_impl.h" #include "../secp256k1/src/eckey_impl.h" -#include "../secp256k1/src/hash_impl.h"*/ +#include "../secp256k1/src/hash_impl.h" struct secp256k1_context_struct { secp256k1_ecmult_context ecmult_ctx; secp256k1_ecmult_gen_context ecmult_gen_ctx; secp256k1_callback illegal_callback; secp256k1_callback error_callback; -}; +};*/ typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); extern "C" void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); @@ -624,8 +624,6 @@ return 0; \ } while(0) //#include "../secp256k1/src/secp256k1.c" -#include "../secp256k1/src/modules/schnorrsig/main_impl.h" -#include "../secp256k1/src/modules/musig/main_impl.h" #include "musig.cpp" #endif diff --git a/src/secp256k1/src/secp256k1.c b/src/secp256k1/src/secp256k1.c index 4225607ff..7861a5f79 100644 --- a/src/secp256k1/src/secp256k1.c +++ b/src/secp256k1/src/secp256k1.c @@ -601,6 +601,8 @@ int secp256k1_ec_pubkey_combine(const secp256k1_context* ctx, secp256k1_pubkey * # include "modules/ecdh/main_impl.h" #endif +#include "../secp256k1/src/modules/schnorrsig/main_impl.h" +#include "../secp256k1/src/modules/musig/main_impl.h" #ifdef ENABLE_MODULE_RECOVERY # include "modules/recovery/main_impl.h" From ecdd65b56690b0471b783c53ccf18ed1f9cf7980 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:20:11 -1100 Subject: [PATCH 0989/1145] xx --- src/cc/cclib.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 3c0baf856..f7df312e7 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -584,12 +584,12 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" -#define USE_BASIC_CONFIG +/*#define USE_BASIC_CONFIG #define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" -/*#include "../secp256k1/src/util.h" +#include "../secp256k1/src/util.h" #include "../secp256k1/src/num_impl.h" #include "../secp256k1/src/field_impl.h" #include "../secp256k1/src/scalar_impl.h" @@ -607,7 +607,7 @@ struct secp256k1_context_struct { secp256k1_ecmult_gen_context ecmult_gen_ctx; secp256k1_callback illegal_callback; secp256k1_callback error_callback; -};*/ +}; typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); extern "C" void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); @@ -621,7 +621,7 @@ if (EXPECT(!(cond), 0)) { \ secp256k1_callback_call(&ctx->illegal_callback, #cond); \ return 0; \ } \ -} while(0) +} while(0)*/ //#include "../secp256k1/src/secp256k1.c" From 4c934237feb82112ee9a0bd0d721e8034d15ef1c Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:25:31 -1100 Subject: [PATCH 0990/1145] Almost --- src/cc/cclib.cpp | 4 +++- src/cc/musig.cpp | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index f7df312e7..a83107234 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -614,7 +614,6 @@ extern "C" void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge extern "C" int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); extern "C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); extern "C" void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); -extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); #define ARG_CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ @@ -624,6 +623,9 @@ return 0; \ } while(0)*/ //#include "../secp256k1/src/secp256k1.c" +extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); +extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); #include "musig.cpp" #endif diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 5d56635aa..520234da1 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -15,9 +15,11 @@ #include "../secp256k1/include/secp256k1.h" -#include "../secp256k1/include/secp256k1_schnorrsig.h" +//#include "../secp256k1/include/secp256k1_schnorrsig.h" #include "../secp256k1/include/secp256k1_musig.h" +typedef struct { unsigned char data[64]; } secp256k1_schnorrsig; + #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 From d17ef9b3e264e7bac9cccc4d27de3b19ae7fc40d Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:28:36 -1100 Subject: [PATCH 0991/1145] ees --- src/cc/cclib.cpp | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index a83107234..484be6191 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -584,10 +584,11 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" +#include "../secp256k1/include/secp256k1.h" +#include "../secp256k1/src/ecmult.h" /*#define USE_BASIC_CONFIG #define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" -#include "../secp256k1/include/secp256k1.h" #include "../secp256k1/src/util.h" #include "../secp256k1/src/num_impl.h" @@ -602,12 +603,7 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/eckey_impl.h" #include "../secp256k1/src/hash_impl.h" -struct secp256k1_context_struct { - secp256k1_ecmult_context ecmult_ctx; - secp256k1_ecmult_gen_context ecmult_gen_ctx; - secp256k1_callback illegal_callback; - secp256k1_callback error_callback; -}; + typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); extern "C" void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); @@ -623,6 +619,12 @@ return 0; \ } while(0)*/ //#include "../secp256k1/src/secp256k1.c" +struct secp256k1_context_struct { + secp256k1_ecmult_context ecmult_ctx; + secp256k1_ecmult_gen_context ecmult_gen_ctx; + secp256k1_callback illegal_callback; + secp256k1_callback error_callback; +}; extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); From 7833fc5f4b1af8d19a49edb8dfd396da3ff2c995 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:29:47 -1100 Subject: [PATCH 0992/1145] Sss --- src/cc/cclib.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 484be6191..35a6362ec 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -584,12 +584,12 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" -#include "../secp256k1/include/secp256k1.h" -#include "../secp256k1/src/ecmult.h" -/*#define USE_BASIC_CONFIG +#define USE_BASIC_CONFIG #define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" +#include "../secp256k1/include/secp256k1.h" +/* #include "../secp256k1/src/util.h" #include "../secp256k1/src/num_impl.h" #include "../secp256k1/src/field_impl.h" From 7573d3f815cca5c5d08e9e8a56c9a9b3f41c6c93 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:31:15 -1100 Subject: [PATCH 0993/1145] Tes --- src/cc/cclib.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 35a6362ec..5681a380f 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -588,6 +588,7 @@ uint256 juint256(cJSON *obj) #define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" +#include "../secp256k1/include/ecmult.h" /* #include "../secp256k1/src/util.h" From aec159bdc0bcbceb80f2ccb4d4e3bc479854cb2d Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:31:47 -1100 Subject: [PATCH 0994/1145] Src --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 5681a380f..8a96a81bf 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -588,7 +588,7 @@ uint256 juint256(cJSON *obj) #define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" -#include "../secp256k1/include/ecmult.h" +#include "../secp256k1/src/ecmult.h" /* #include "../secp256k1/src/util.h" From 3106e5f0a83784a4dff7128920acfc2f44eba786 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:33:11 -1100 Subject: [PATCH 0995/1145] typedef struct { unsigned char data[64]; } secp256k1_schnorrsig; --- src/cc/cclib.cpp | 3 +++ src/cc/musig.cpp | 1 - 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 8a96a81bf..76d1dfa39 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -589,6 +589,9 @@ uint256 juint256(cJSON *obj) #include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" #include "../secp256k1/src/ecmult.h" +#include "../secp256k1/src/ecmult_gen.h" + +typedef struct { unsigned char data[64]; } secp256k1_schnorrsig; /* #include "../secp256k1/src/util.h" diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 520234da1..318cb7664 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -18,7 +18,6 @@ //#include "../secp256k1/include/secp256k1_schnorrsig.h" #include "../secp256k1/include/secp256k1_musig.h" -typedef struct { unsigned char data[64]; } secp256k1_schnorrsig; #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 From 51ae3da5ec6a575c8d7b003f62e72af65a03949a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:38:45 -1100 Subject: [PATCH 0996/1145] #ifdef __cplusplus --- src/secp256k1/src/ecmult.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/secp256k1/src/ecmult.h b/src/secp256k1/src/ecmult.h index fbcf6a445..3ed2e435a 100644 --- a/src/secp256k1/src/ecmult.h +++ b/src/secp256k1/src/ecmult.h @@ -78,6 +78,10 @@ typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge * 0 if there is not enough scratch space for a single point or * callback returns 0 */ + +#ifdef __cplusplus +extern "C" +#endif int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); #endif /* SECP256K1_ECMULT_H */ From 4da533ffc5cb53f0ea28010601e09ec8effc46c4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:42:25 -1100 Subject: [PATCH 0997/1145] Test --- src/cc/cclib.cpp | 1 + src/secp256k1/src/ecmult_impl.h | 1 + 2 files changed, 2 insertions(+) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 76d1dfa39..5d321bdae 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -629,6 +629,7 @@ struct secp256k1_context_struct { secp256k1_callback illegal_callback; secp256k1_callback error_callback; }; + extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 116a9f154..6fd705ef4 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1522,6 +1522,7 @@ static size_t secp256k1_pippenger_max_points(secp256k1_scratch *scratch) { } typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t); + int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { size_t i; From b09b0261aca1812eef070b5046aad2b4cbefebf7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:45:02 -1100 Subject: [PATCH 0998/1145] Test --- src/secp256k1/src/ecmult_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index 6fd705ef4..bea64ebcd 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1525,7 +1525,7 @@ typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { size_t i; - + xxx int (*f)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t, size_t); size_t max_points; size_t n_batches; From c44e7ae038a9b462b83f69dbb2f31d9fe1b5e97d Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 02:48:05 -1100 Subject: [PATCH 0999/1145] Fix --- src/secp256k1/src/ecmult_impl.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/secp256k1/src/ecmult_impl.h b/src/secp256k1/src/ecmult_impl.h index bea64ebcd..b761304cf 100644 --- a/src/secp256k1/src/ecmult_impl.h +++ b/src/secp256k1/src/ecmult_impl.h @@ -1,4 +1,4 @@ -#ifdef ENABLE_MODULE_MUSIG +#ifndef ENABLE_MODULE_MUSIG /********************************************************************** @@ -1525,7 +1525,6 @@ typedef int (*secp256k1_ecmult_multi_func)(const secp256k1_ecmult_context*, secp int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n) { size_t i; - xxx int (*f)(const secp256k1_ecmult_context*, secp256k1_scratch*, secp256k1_gej*, const secp256k1_scalar*, secp256k1_ecmult_multi_callback cb, void*, size_t, size_t); size_t max_points; size_t n_batches; From ccd1b516294fedc391e29b763aa640e72f58fdb0 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 15:36:02 +0100 Subject: [PATCH 1000/1145] resolve conflict --- src/Makefile.am | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/Makefile.am b/src/Makefile.am index e9d41a510..22668c91f 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -572,16 +572,14 @@ komodod_LDADD += \ $(LIBVERUS_CRYPTO) \ $(LIBVERUS_PORTABLE_CRYPTO) \ $(LIBZCASH_LIBS) - + if TARGET_DARWIN -komodod_LDADD += libcc.dylib -endif -if TARGET_WINDOWS -komodod_LDADD += libcc.dll +komodod_LDADD += libcc.dylib $(LIBSECP256K1) else -komodod_LDADD += libcc.so +komodod_LDADD += libcc.so $(LIBSECP256K1) endif + if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) endif From a659c209e489adf22ec8cad02e016d3dd3c75731 Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Thu, 21 Feb 2019 22:38:40 +0800 Subject: [PATCH 1001/1145] it builds --- src/cc/rogue/main.c | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index ca05226d3..93391d153 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -30,7 +30,7 @@ extern char Gametxidstr[67]; #define SATOSHIDEN ((uint64_t)100000000L) #define dstr(x) ((double)(x) / SATOSHIDEN) #define KOMODO_ASSETCHAIN_MAXLEN 65 -char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN]; +char ASSETCHAINS_SYMBOL[KOMODO_ASSETCHAIN_MAXLEN],IPADDRESS[100]; #ifndef _BITS256 #define _BITS256 @@ -583,7 +583,7 @@ char *curl_post(CURL **cHandlep,char *url,char *userpass,char *postfields,char * return(chunk.memory); } -uint16_t _komodo_userpass(char *username,char *password,FILE *fp) +uint16_t _komodo_userpass(char *username, char *password, char *ipaddress, FILE *fp) { char *rpcuser,*rpcpassword,*str,line[8192]; uint16_t port = 0; rpcuser = rpcpassword = 0; @@ -602,6 +602,10 @@ uint16_t _komodo_userpass(char *username,char *password,FILE *fp) port = atoi(parse_conf_line(str,(char *)"rpcport")); //fprintf(stderr,"rpcport.%u in file\n",port); } + else if ( (str= strstr(line,(char *)"ipaddress")) != 0 ) + { + ipaddress = parse_conf_line(str,(char *)"ipaddress"); + } } if ( rpcuser != 0 && rpcpassword != 0 ) { @@ -653,7 +657,7 @@ uint16_t _komodo_userpass(char *username,char *password,FILE *fp) //printf("test.(%s) -> [%s] statename.(%s) %s\n",test,ASSETCHAINS_SYMBOL,symbol,fname); }*/ -uint16_t komodo_userpass(char *userpass,char *symbol) +uint16_t komodo_userpass(char *userpass,char *symbol,char *ipaddress) { FILE *fp; uint16_t port = 0; char fname[512],username[512],password[512],confname[KOMODO_ASSETCHAIN_MAXLEN]; userpass[0] = 0; @@ -669,7 +673,7 @@ uint16_t komodo_userpass(char *userpass,char *symbol) //komodo_statefname(fname,symbol,confname); if ( (fp= fopen(confname,"rb")) != 0 ) { - port = _komodo_userpass(username,password,fp); + port = _komodo_userpass(username,password,ipaddress,fp); sprintf(userpass,"%s:%s",username,password); if ( strcmp(symbol,ASSETCHAINS_SYMBOL) == 0 ) strcpy(USERPASS,userpass); @@ -688,7 +692,7 @@ char *komodo_issuemethod(char *userpass,char *method,char *params,uint16_t port) params = (char *)"[]"; if ( strlen(params) < sizeof(postdata)-128 ) { - sprintf(url,(char *)"http://127.0.0.1:%u",port); + sprintf(url,(char *)"http://%s:%u",IPADDRESS,port); sprintf(postdata,"{\"method\":\"%s\",\"params\":%s}",method,params); //printf("[%s] (%s) postdata.(%s) params.(%s) USERPASS.(%s)\n",ASSETCHAINS_SYMBOL,url,postdata,params,USERPASS); retstr2 = bitcoind_RPC(&retstr,(char *)"debug",url,userpass,method,params); @@ -793,7 +797,7 @@ int main(int argc, char **argv, char **envp) ASSETCHAINS_SYMBOL[j++] = toupper(c); } ASSETCHAINS_SYMBOL[j++] = 0; - ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL); + ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL,IPADDRESS); printf("ASSETCHAINS_SYMBOL.(%s) port.%u (%s)\n",ASSETCHAINS_SYMBOL,ROGUE_PORT,USERPASS); sleep(1); if ( argc == 2 && (fp=fopen(argv[1],"rb")) == 0 ) { @@ -813,5 +817,3 @@ int main(int argc, char **argv, char **envp) return(rogue(argc,argv,envp)); } } - - From f6d693768f1f733dbdb18c02a1b904c23cfcb5f5 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 15:40:26 +0100 Subject: [PATCH 1002/1145] winify Makefile --- src/Makefile.am | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index 22668c91f..fa2c17b5d 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -575,11 +575,13 @@ komodod_LDADD += \ if TARGET_DARWIN komodod_LDADD += libcc.dylib $(LIBSECP256K1) +endif +if TARGET_WINDOWS +komodod_LDADD += libcc.dll $(LIBSECP256K1) else komodod_LDADD += libcc.so $(LIBSECP256K1) endif - if ENABLE_PROTON komodod_LDADD += $(LIBBITCOIN_PROTON) $(PROTON_LIBS) endif From 0816deb0b0f328e0ded5ee722b088d359c97956a Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 04:04:18 -1100 Subject: [PATCH 1003/1145] Musig combine rpc --- src/cc/musig.cpp | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 318cb7664..865ec311c 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -110,9 +110,40 @@ UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - result.push_back(Pair("result","success")); - return(result); + static secp256k1_context *ctx; secp256k1_scratch_space scratch; + size_t clen = CPubKey::PUBLIC_KEY_SIZE; + UniValue result(UniValue::VOBJ); int32_t i,n; uint8_t pkhash[32]; char *hexstr,str[67]; secp256k1_pubkey combined_pk,spk; std::vector pubkeys; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + { + for (i=0; i 0 ) + pubkeys.push_back(spk); + else return(cclib_error(result,"error parsing pk")); + } else return(cclib_error(result,"all pubkeys must be 33 bytes hexdata")); + } + if ( secp256k1_musig_pubkey_combine(ctx,&scratch,&combined_pk,pkhash,&pubkeys[0],n) > 0 ) + { + if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&combined_pk,SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) + { + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",pkhash[i]); + str[64] = 0; + result.push_back(Pair("pkhash",str)); + + for (i=0; i<33; i++) + sprintf(&str[i<<1],"%02x",((uint8_t *)pk.begin())[i]); + str[66] = 0; + result.push_back(Pair("combined_pk",str)); + result.push_back(Pair("result","success")); + } else return(cclib_error(result,"error serializeing combined_pk")); + } else return(cclib_error(result,"error combining pukbeys")); + } else return(cclib_error(result,"need pubkeys params")); } UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) From a96f0c861eae0bc5df1d327d8ddbc73a10abe5e9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 04:06:22 -1100 Subject: [PATCH 1004/1145] Declare pk --- src/cc/musig.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 865ec311c..057307fae 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -112,7 +112,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; secp256k1_scratch_space scratch; size_t clen = CPubKey::PUBLIC_KEY_SIZE; - UniValue result(UniValue::VOBJ); int32_t i,n; uint8_t pkhash[32]; char *hexstr,str[67]; secp256k1_pubkey combined_pk,spk; std::vector pubkeys; + UniValue result(UniValue::VOBJ); CPubKey pk; int32_t i,n; uint8_t pkhash[32]; char *hexstr,str[67]; secp256k1_pubkey combined_pk,spk; std::vector pubkeys; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) From 556a45f37b87d7fe7f9ce2445a7044964dee4f81 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 04:08:41 -1100 Subject: [PATCH 1005/1145] Extern C --- src/cc/cclib.cpp | 19 ------------------- src/cc/musig.cpp | 22 +++++++++++++++++++++- 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 5d321bdae..bfd57e61d 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -584,14 +584,6 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" -#define USE_BASIC_CONFIG -#define ENABLE_MODULE_MUSIG -#include "../secp256k1/src/basic-config.h" -#include "../secp256k1/include/secp256k1.h" -#include "../secp256k1/src/ecmult.h" -#include "../secp256k1/src/ecmult_gen.h" - -typedef struct { unsigned char data[64]; } secp256k1_schnorrsig; /* #include "../secp256k1/src/util.h" @@ -623,17 +615,6 @@ return 0; \ } while(0)*/ //#include "../secp256k1/src/secp256k1.c" -struct secp256k1_context_struct { - secp256k1_ecmult_context ecmult_ctx; - secp256k1_ecmult_gen_context ecmult_gen_ctx; - secp256k1_callback illegal_callback; - secp256k1_callback error_callback; -}; - -extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); -extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); -extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); - #include "musig.cpp" #endif diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 057307fae..23c14bb8e 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -13,8 +13,28 @@ * * ******************************************************************************/ - +#define USE_BASIC_CONFIG +#define ENABLE_MODULE_MUSIG +#include "../secp256k1/src/basic-config.h" #include "../secp256k1/include/secp256k1.h" +#include "../secp256k1/src/ecmult.h" +#include "../secp256k1/src/ecmult_gen.h" + +typedef struct { unsigned char data[64]; } secp256k1_schnorrsig; +struct secp256k1_context_struct { + secp256k1_ecmult_context ecmult_ctx; + secp256k1_ecmult_gen_context ecmult_gen_ctx; + secp256k1_callback illegal_callback; + secp256k1_callback error_callback; +}; + +extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); +extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); +extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, unsigned char *pk_hash32, const secp256k1_pubkey *pubkeys, size_t n_pubkeys); + + +//#include "../secp256k1/include/secp256k1.h" //#include "../secp256k1/include/secp256k1_schnorrsig.h" #include "../secp256k1/include/secp256k1_musig.h" From c96ca4eab9a842e001edeedb2ad6e97a687d693c Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 04:12:42 -1100 Subject: [PATCH 1006/1145] Test --- src/cc/musig.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 23c14bb8e..ee4c3400e 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -135,6 +135,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); CPubKey pk; int32_t i,n; uint8_t pkhash[32]; char *hexstr,str[67]; secp256k1_pubkey combined_pk,spk; std::vector pubkeys; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + fprintf(stderr,"args.(%s)\n",jprint(params,0)); if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { for (i=0; i Date: Thu, 21 Feb 2019 04:17:20 -1100 Subject: [PATCH 1007/1145] Test --- src/cc/musig.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index ee4c3400e..0b8600de4 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -135,9 +135,9 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); CPubKey pk; int32_t i,n; uint8_t pkhash[32]; char *hexstr,str[67]; secp256k1_pubkey combined_pk,spk; std::vector pubkeys; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - fprintf(stderr,"args.(%s)\n",jprint(params,0)); if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { + fprintf(stderr,"n.%d args.(%s)\n",jprint(params,0)); for (i=0; i Date: Thu, 21 Feb 2019 04:18:37 -1100 Subject: [PATCH 1008/1145] N, --- src/cc/musig.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 0b8600de4..0c2ce2d15 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -137,7 +137,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { - fprintf(stderr,"n.%d args.(%s)\n",jprint(params,0)); + fprintf(stderr,"n.%d args.(%s)\n",n,jprint(params,0)); for (i=0; i Date: Thu, 21 Feb 2019 04:20:26 -1100 Subject: [PATCH 1009/1145] -scratch --- src/cc/musig.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 0c2ce2d15..0e7f374db 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -130,7 +130,7 @@ UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - static secp256k1_context *ctx; secp256k1_scratch_space scratch; + static secp256k1_context *ctx; size_t clen = CPubKey::PUBLIC_KEY_SIZE; UniValue result(UniValue::VOBJ); CPubKey pk; int32_t i,n; uint8_t pkhash[32]; char *hexstr,str[67]; secp256k1_pubkey combined_pk,spk; std::vector pubkeys; if ( ctx == 0 ) @@ -148,7 +148,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) else return(cclib_error(result,"error parsing pk")); } else return(cclib_error(result,"all pubkeys must be 33 bytes hexdata")); } - if ( secp256k1_musig_pubkey_combine(ctx,&scratch,&combined_pk,pkhash,&pubkeys[0],n) > 0 ) + if ( secp256k1_musig_pubkey_combine(ctx,NULL,&combined_pk,pkhash,&pubkeys[0],n) > 0 ) { if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&combined_pk,SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) { From d32c12e0bbfb75f620b80ff84e8affbd033694f0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 04:24:21 -1100 Subject: [PATCH 1010/1145] Return! --- src/cc/musig.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 0e7f374db..1a664f4b4 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -162,6 +162,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) str[66] = 0; result.push_back(Pair("combined_pk",str)); result.push_back(Pair("result","success")); + return(result); } else return(cclib_error(result,"error serializeing combined_pk")); } else return(cclib_error(result,"error combining pukbeys")); } else return(cclib_error(result,"need pubkeys params")); From c6b2a865e65c8bb54a54baafe1d2e3cb3fa064c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 04:33:06 -1100 Subject: [PATCH 1011/1145] Music usage example --- src/cc/musig.cpp | 49 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 1a664f4b4..17c4d1368 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -13,6 +13,52 @@ * * ******************************************************************************/ +/* first make a combined pk: +./c cclib combine 18 \"[%2202aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22,%22039433dc3749aece1bd568f374a45da3b0bc6856990d7da3cd175399577940a775%22]\" +{ + "pkhash": "5be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba", + "combined_pk": "032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b", + "result": "success" +} +*/ + +/* second, send 0.777 coins to the combined_pk + ./c cclib send 18 \"[%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,0.777]\" + { + "hex": "0400008085202f8901bf7afcbbab7a5e1ba20c8010325e199305afa7d15b4bc86a589a512201d39924000000004847304402203e0cff8aaa831dd990afd979bbc0a648316f77407cb5e02780d18e0670f5172a0220283d5c52d0406b10c508cc2b19dd6dbe2420e7c5cf431a1d41072d0eec28edb901ffffffff03b0c2a10400000000302ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cca91e223700000000232102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac0000000000000000266a24127821032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b00000000900000000000000000000000000000", + "txid": "cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be", + "result": "success" + } + + { + "value": 0.77710000, + "valueZat": 77710000, + "n": 0, + "scriptPubKey": { + "asm": "a22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401 OP_CHECKCRYPTOCONDITION", + "hex": "2ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cc", + "reqSigs": 1, + "type": "cryptocondition", + "addresses": [ + "RKWS7jxyjPX9iaJttk8iMKf1AumanKypez" + ] + } + change script: 2102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac + + sendtxid: cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be + + broadcast sendtxid and wait for it to be confirmed. then get the msg we need to sign: + + ./c cclib calcmsg 18 \"[%22cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22]\" + + { + "result": "success", + "msg": "63b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485" + } + +*/ + + #define USE_BASIC_CONFIG #define ENABLE_MODULE_MUSIG #include "../secp256k1/src/basic-config.h" @@ -82,7 +128,6 @@ int32_t musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,CP { CScript data; uint256 hash; int32_t len = 0; data << E_MARSHAL(ss << prevhash << prevn << vout << pk); -fprintf(stderr,"data size %d\n",(int32_t)data.size()); hash = Hash(data.begin(),data.end()); memcpy(msg,&hash,sizeof(hash)); return(0); @@ -137,7 +182,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { - fprintf(stderr,"n.%d args.(%s)\n",n,jprint(params,0)); + //fprintf(stderr,"n.%d args.(%s)\n",n,jprint(params,0)); for (i=0; i Date: Thu, 21 Feb 2019 16:35:00 +0100 Subject: [PATCH 1012/1145] add WIN makefile target: rogue.exe --- src/cc/rogue/Makefile_win | 222 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 src/cc/rogue/Makefile_win diff --git a/src/cc/rogue/Makefile_win b/src/cc/rogue/Makefile_win new file mode 100644 index 000000000..dbc900e48 --- /dev/null +++ b/src/cc/rogue/Makefile_win @@ -0,0 +1,222 @@ +############################################################################### +# +# Makefile for rogue +# +# Rogue: Exploring the Dungeons of Doom +# Copyright (C) 1980-1983, 1985, 1999 Michael Toy, Ken Arnold and Glenn Wichman +# All rights reserved. +# +# See the file LICENSE.TXT for full copyright and licensing information. +# +############################################################################### + +############################################################################### +# Site configuration occurs beneath this comment +# Typically ./configure (autoconf tools) configures this section +# This section could be manually configured if autoconf/configure fails +############################################################################### + +DISTNAME=rogue5.4.4 +PACKAGE_TARNAME = rogue-5.4.4 +PROGRAM=rogue + +O=o + +#CC=gcc +CC = x86_64-w64-mingw32-gcc + +#CFLAGS=-O2 +CFLAGS= -g -O2 -I./ncurses/include + +#LIBS=-lcurses +LIBS = -L./ncurses/lib -lncursesw + +#RM=rm -f +RM = rm -f + +#GROFF=groff +GROFF = groff + +#NROFF=nroff +NROFF = nroff + +#TBL=tbl +TBL = tbl + +#COLCRT=colcrt +COLCRT = colcrt + +#SED=sed +SED = sed + +#SCOREFILE=rogue54.scr +SCOREFILE = rogue.scr + +#LOCKFILE=rogue54.lck +LOCKFILE = rogue.lck + +#GROUPOWNER=games +GROUPOWNER = + +#CPPFLAGS=-DHAVE_CONFIG_H +CPPFLAGS =-DHAVE_CONFIG_H + +#DISTFILE = $(PROGRAM) +DISTFILE = $(DISTNAME)-x86_64-w64-mingw32 + +INSTALL=./install-sh + +#INSTGROUP=-g games +INSTGROUP= +#INSTOWNER=-u root +INSTOWNER= + +CHGRP=chgrp + +MKDIR=mkdir + +TOUCH=touch + +RMDIR=rmdir + +CHMOD=chmod + +DESTDIR= + +prefix=/usr/local +exec_prefix=${prefix} +datarootdir=${prefix}/share +datadir=${datarootdir} +bindir=${exec_prefix}/bin +mandir=${datarootdir}/man +docdir=${datarootdir}/doc/${PACKAGE_TARNAME} +man6dir = $(mandir)/man6 + +############################################################################### +# Site configuration occurs above this comment +# It should not be necessary to change anything below this comment +############################################################################### + +HDRS = rogue.h extern.h score.h +OBJS1 = vers.$(O) extern.$(O) armor.$(O) chase.$(O) command.$(O) \ + daemon.$(O) daemons.$(O) fight.$(O) init.$(O) io.$(O) list.$(O) \ + mach_dep.$(O) rogue.$(O) mdport.$(O) misc.$(O) monsters.$(O) \ + move.$(O) new_level.$(O) +OBJS2 = options.$(O) pack.$(O) passages.$(O) potions.$(O) rings.$(O) \ + rip.$(O) rooms.$(O) save.$(O) scrolls.$(O) state.$(O) sticks.$(O) \ + things.$(O) weapons.$(O) wizard.$(O) xcrypt.$(O) +OBJS = main.$(O) $(OBJS1) $(OBJS2) +CFILES = vers.c extern.c armor.c chase.c command.c daemon.c \ + daemons.c fight.c init.c io.c list.c mach_dep.c \ + main.c mdport.c misc.c monsters.c move.c new_level.c \ + options.c pack.c passages.c potions.c rings.c rip.c \ + rooms.c save.c scrolls.c state.c sticks.c things.c \ + weapons.c wizard.c xcrypt.c +MISC_C = findpw.c scedit.c scmisc.c +DOCSRC = rogue.me.in rogue.6.in rogue.doc.in rogue.html.in rogue.cat.in +DOCS = $(PROGRAM).doc $(PROGRAM).html $(PROGRAM).cat $(PROGRAM).me \ + $(PROGRAM).6 +AFILES = configure Makefile.in configure.ac config.h.in config.sub config.guess \ + install-sh rogue.6.in rogue.me.in rogue.html.in rogue.doc.in rogue.cat.in +MISC = Makefile.std LICENSE.TXT rogue54.sln rogue54.vcproj rogue.spec \ + rogue.png rogue.desktop + +.SUFFIXES: .obj + +.c.obj: + $(CC) $(CFLAGS) $(CPPFLAGS) /c $*.c + +.c.o: + $(CC) $(CFLAGS) $(CPPFLAGS) -c $*.c + +#$(RM) rogue.so ; $(CC) -shared -o rogue.so cursesd.c $(OBJS1) $(OBJS2); $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@ + +$(PROGRAM): $(HDRS) $(OBJS) + $(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@.exe + +clean: + $(RM) $(OBJS1); $(RM) main.$(O) ; $(RM) rogue.so + $(RM) $(OBJS2) + $(RM) core a.exe a.out a.exe.stackdump $(PROGRAM) $(PROGRAM).exe + $(RM) $(PROGRAM).tar $(PROGRAM).tar.gz $(PROGRAM).zip + $(RM) $(DISTNAME)/* + -rmdir $(DISTNAME) + +maintainer-clean: + $(RM) config.h + $(RM) Makefile + $(RM) config.status + $(RM) -r autom4te.cache + $(RM) config.log + $(RM) $(PROGRAM).scr $(PROGRAM).lck + +stddocs: + sed -e 's/rogue/rogue/' -e 's/rogue.scr/rogue.scr/' rogue.6.in > rogue.6 + sed -e 's/rogue/rogue/' -e 's/rogue.scr/rogue.scr/' rogue.me.in > rogue.me + sed -e 's/rogue/rogue/' -e 's/rogue.scr/rogue.scr/' rogue.html.in > rogue,html + sed -e 's/rogue/rogue/' -e 's/rogue.scr/rogue.scr/' rogue.doc.in > rogue.doc + sed -e 's/rogue/rogue/' -e 's/rogue.scr/rogue.scr/' rogue.cat.in > rogue.cat + +dist.src: + $(MAKE) $(MAKEFILE) clean + mkdir $(DISTNAME) + cp $(CFILES) $(HDRS) $(MISC) $(AFILES) $(DISTNAME) + tar cf $(DISTNAME)-src.tar $(DISTNAME) + gzip -f $(DISTNAME)-src.tar + rm -fr $(DISTNAME) + +findpw: findpw.c xcrypt.o mdport.o xcrypt.o + $(CC) -s -o findpw findpw.c xcrypt.o mdport.o -lcurses + +scedit: scedit.o scmisc.o vers.o mdport.o xcrypt.o + $(CC) -s -o scedit vers.o scedit.o scmisc.o mdport.o xcrypt.o -lcurses + +scmisc.o scedit.o: + $(CC) -O -c $(SF) $*.c + +$(PROGRAM).doc: rogue.me + if test "x$(GROFF)" != "x" -a "x$(SED)" != "x" ; then \ + $(GROFF) -P-c -t -me -Tascii rogue.me | $(SED) -e 's/.\x08//g' > $(PROGRAM).doc ;\ + elif test "x$(NROFF)" != "x" -a "x$(TBL)" != "x" -a "x$(COLCRT)" != "x" ; then \ + tbl rogue.me | $(NROFF) -me | colcrt - > $(PROGRAM).doc ;\ + fi + +$(PROGRAM).cat: rogue.6 + if test "x$(GROFF)" != "x" -a "x$(SED)" != "x" ; then \ + $(GROFF) -Tascii -man rogue.6 | $(SED) -e 's/.\x08//g' > $(PROGRAM).cat ;\ + elif test "x$(NROFF)" != "x" -a "x$(TBL)" != "x" -a "x$(COLCRT)" != "x" ; then \ + $(NROFF) -man rogue.6 | $(COLCRT) - > $(PROGRAM).cat ;\ + fi + +dist: clean $(PROGRAM) + tar cf $(DISTFILE).tar $(PROGRAM) LICENSE.TXT $(DOCS) + gzip -f $(DISTFILE).tar + +install: $(PROGRAM) + -$(TOUCH) test + -if test ! -f $(DESTDIR)$(SCOREFILE) ; then $(INSTALL) -m 0664 test $(DESTDIR)$(SCOREFILE) ; fi + -$(INSTALL) -m 0755 $(PROGRAM) $(DESTDIR)$(bindir)/$(PROGRAM) + -if test "x$(GROUPOWNER)" != "x" ; then \ + $(CHGRP) $(GROUPOWNER) $(DESTDIR)$(SCOREFILE) ; \ + $(CHGRP) $(GROUPOWNER) $(DESTDIR)$(bindir)/$(PROGRAM) ; \ + $(CHMOD) 02755 $(DESTDIR)$(bindir)/$(PROGRAM) ; \ + $(CHMOD) 0464 $(DESTDIR)$(SCOREFILE) ; \ + fi + -if test -d $(man6dir) ; then $(INSTALL) -m 0644 rogue.6 $(DESTDIR)$(man6dir)/$(PROGRAM).6 ; fi + -if test ! -d $(man6dir) ; then $(INSTALL) -m 0644 rogue.6 $(DESTDIR)$(mandir)/$(PROGRAM).6 ; fi + -$(INSTALL) -m 0644 rogue.doc $(DESTDIR)$(docdir)/$(PROGRAM).doc + -$(INSTALL) -m 0644 rogue.html $(DESTDIR)$(docdir)/$(PROGRAM).html + -$(INSTALL) -m 0644 rogue.cat $(DESTDIR)$(docdir)/$(PROGRAM).cat + -$(INSTALL) -m 0644 LICENSE.TXT $(DESTDIR)$(docdir)/LICENSE.TXT + -$(INSTALL) -m 0644 rogue.me $(DESTDIR)$(docdir)/$(PROGRAM).me + -if test ! -f $(DESTDIR)$(LOCKFILE) ; then $(INSTALL) -m 0666 test $(DESTDIR)$(LOCKFILE) ; $(RM) $(DESTDIR)$(LOCKFILE) ; fi + -$(RM) test + +uninstall: + -$(RM) $(DESTDIR)$(bindir)/$(PROGRAM) + -$(RM) $(DESTDIR)$(man6dir)/$(PROGRAM).6 + -$(RM) $(DESTDIR)$(docdir)$(PROGRAM)/$(PROGRAM).doc + -$(RM) $(DESTDIR)$(LOCKFILE) + -$(RMDIR) $(DESTDIR)$(docdir)$(PROGRAM) + +reinstall: uninstall install From e8a72377f732410718b5e4b912270a9725e2a943 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 16:36:12 +0100 Subject: [PATCH 1013/1145] WINify makerogue modify rogue game build --- src/cc/makerogue | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index a38eab6a4..3068fa38e 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -1,7 +1,26 @@ #!/bin/sh cd rogue; -./configure -make; cd .. + +if [ "$HOST" = "x86_64-w64-mingw32" ]; then + echo building rogue.exe... + if make -f Makefile_win "$@"; then + echo rogue.exe build SUCCESSFUL + cd .. + else + echo rogue.exe build FAILED + exit 1 + fi +else + echo building rogue... + ./configure + if make "$@"; then + echo rogue build SUCCESSFUL + cd .. + else + echo rogue build FAILED + exit 1 + fi +fi if make -f Makefile_rogue "$@"; then echo ROGUE BUILD SUCCESSFUL From cfcde22a1e0a0ce80e4c0e365ba53282e79bb920 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 17:48:52 +0100 Subject: [PATCH 1014/1145] add ncurses for rogue.exe --- src/cc/makerogue | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/makerogue b/src/cc/makerogue index 3068fa38e..ff175c586 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -3,6 +3,10 @@ cd rogue; if [ "$HOST" = "x86_64-w64-mingw32" ]; then echo building rogue.exe... + mkdir ncurses && cd ncurses + wget https://invisible-island.net/datafiles/release/mingw32.zip + unzip mingw32.zip && delete mingw32.zip + cd .. if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL cd .. From 7453b21b6da2b0f7ecc5bac28832cfb3ccda88c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 06:01:19 -1100 Subject: [PATCH 1015/1145] Comments --- src/cc/musig.cpp | 151 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 149 insertions(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 17c4d1368..ec7f5e788 100755 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -217,6 +217,37 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); result.push_back(Pair("result","success")); + /** Initializes a signing session for a signer + * + * Returns: 1: session is successfully initialized + * 0: session could not be initialized: secret key or secret nonce overflow + * Args: ctx: pointer to a context object, initialized for signing (cannot + * be NULL) + * Out: session: the session structure to initialize (cannot be NULL) + * signers: an array of signers' data to be initialized. Array length must + * equal to `n_signers` (cannot be NULL) + * nonce_commitment32: filled with a 32-byte commitment to the generated nonce + * (cannot be NULL) + * In: session_id32: a *unique* 32-byte ID to assign to this session (cannot be + * NULL). If a non-unique session_id32 was given then a partial + * signature will LEAK THE SECRET KEY. + * msg32: the 32-byte message to be signed. Shouldn't be NULL unless you + * require sharing public nonces before the message is known + * because it reduces nonce misuse resistance. If NULL, must be + * set with `musig_session_set_msg` before signing and verifying. + * combined_pk: the combined public key of all signers (cannot be NULL) + * pk_hash32: the 32-byte hash of the signers' individual keys (cannot be + * NULL) + * n_signers: length of signers array. Number of signers participating in + * the MuSig. Must be greater than 0 and at most 2^32 - 1. + * my_index: index of this signer in the signers array + * seckey: the signer's 32-byte secret key (cannot be NULL) + */ + //if (!secp256k1_musig_session_initialize(ctx, &musig_session[i], signer_data[i], nonce_commitment[i], session_id32, msg32, &combined_pk, pk_hash, N_SIGNERS, i, seckeys[i])) + //return 0; + // randombytes_buf(buf, num); + + //nonce_commitment_ptr[i] = &nonce_commitment[i][0]; return(result); } @@ -224,6 +255,25 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); result.push_back(Pair("result","success")); + /** Gets the signer's public nonce given a list of all signers' data with commitments + * + * Returns: 1: public nonce is written in nonce + * 0: signer data is missing commitments or session isn't initialized + * for signing + * Args: ctx: pointer to a context object (cannot be NULL) + * session: the signing session to get the nonce from (cannot be NULL) + * signers: an array of signers' data initialized with + * `musig_session_initialize`. Array length must equal to + * `n_commitments` (cannot be NULL) + * Out: nonce: the nonce (cannot be NULL) + * In: commitments: array of 32-byte nonce commitments (cannot be NULL) + * n_commitments: the length of commitments and signers array. Must be the total + * number of signers participating in the MuSig. + */ + // Set nonce commitments in the signer data and get the own public nonce + //if (!secp256k1_musig_session_get_public_nonce(ctx, &musig_session[i], signer_data[i], &nonce[i], nonce_commitment_ptr, N_SIGNERS)) + // return 0; + return(result); } @@ -231,13 +281,69 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); result.push_back(Pair("result","success")); - return(result); + /** Checks a signer's public nonce against a commitment to said nonce, and update + * data structure if they match + * + * Returns: 1: commitment was valid, data structure updated + * 0: commitment was invalid, nothing happened + * Args: ctx: pointer to a context object (cannot be NULL) + * signer: pointer to the signer data to update (cannot be NULL). Must have + * been used with `musig_session_get_public_nonce` or initialized + * with `musig_session_initialize_verifier`. + * In: nonce: signer's alleged public nonce (cannot be NULL) + */ + //if (!secp256k1_musig_set_nonce(ctx, &signer_data[i][j], &nonce[j])) { + + + /** Updates a session with the combined public nonce of all signers. The combined + * public nonce is the sum of every signer's public nonce. + * + * Returns: 1: nonces are successfully combined + * 0: a signer's nonce is missing + * Args: ctx: pointer to a context object (cannot be NULL) + * session: session to update with the combined public nonce (cannot be + * NULL) + * signers: an array of signers' data, which must have had public nonces + * set with `musig_set_nonce`. Array length must equal to `n_signers` + * (cannot be NULL) + * n_signers: the length of the signers array. Must be the total number of + * signers participating in the MuSig. + * Out: nonce_is_negated: a pointer to an integer that indicates if the combined + * public nonce had to be negated. + * adaptor: point to add to the combined public nonce. If NULL, nothing is + * added to the combined nonce. + */ + // after all nonces: if (!secp256k1_musig_session_combine_nonces(ctx, &musig_session[i], signer_data[i], N_SIGNERS, NULL, NULL)) { + return(result); } UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); result.push_back(Pair("result","success")); + /** Produces a partial signature + * + * Returns: 1: partial signature constructed + * 0: session in incorrect or inconsistent state + * Args: ctx: pointer to a context object (cannot be NULL) + * session: active signing session for which the combined nonce has been + * computed (cannot be NULL) + * Out: partial_sig: partial signature (cannot be NULL) + */ + //if (!secp256k1_musig_partial_sign(ctx, &musig_session[i], &partial_sig[i])) { + /** Parse and verify a MuSig partial signature. + * + * Returns: 1 when the signature could be parsed, 0 otherwise. + * Args: ctx: a secp256k1 context object + * Out: sig: pointer to a signature object + * In: in32: pointer to the 32-byte signature to be parsed + * + * After the call, sig will always be initialized. If parsing failed or the + * encoded numbers are out of range, signature verification with it is + * guaranteed to fail for every message and public key. + */ + //SECP256K1_API int secp256k1_musig_partial_signature_parse( + return(result); } @@ -245,13 +351,54 @@ UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { UniValue result(UniValue::VOBJ); result.push_back(Pair("result","success")); - return(result); + /** Checks that an individual partial signature verifies + * + * This function is essential when using protocols with adaptor signatures. + * However, it is not essential for regular MuSig's, in the sense that if any + * partial signatures does not verify, the full signature will also not verify, so the + * problem will be caught. But this function allows determining the specific party + * who produced an invalid signature, so that signing can be restarted without them. + * + * Returns: 1: partial signature verifies + * 0: invalid signature or bad data + * Args: ctx: pointer to a context object (cannot be NULL) + * session: active session for which the combined nonce has been computed + * (cannot be NULL) + * signer: data for the signer who produced this signature (cannot be NULL) + * In: partial_sig: signature to verify (cannot be NULL) + * pubkey: public key of the signer who produced the signature (cannot be NULL) + */ + //if (!secp256k1_musig_partial_sig_verify(ctx, &musig_session[i], &signer_data[i][j], &partial_sig[j], &pubkeys[j])) { + return 0; + /** Combines partial signatures + * + * Returns: 1: all partial signatures have values in range. Does NOT mean the + * resulting signature verifies. + * 0: some partial signature had s/r out of range + * Args: ctx: pointer to a context object (cannot be NULL) + * session: initialized session for which the combined nonce has been + * computed (cannot be NULL) + * Out: sig: complete signature (cannot be NULL) + * In: partial_sigs: array of partial signatures to combine (cannot be NULL) + * n_sigs: number of signatures in the partial_sigs array + */ + // after all partials: return secp256k1_musig_partial_sig_combine(ctx, &musig_session[0], sig, partial_sig, N_SIGNERS return(result); } UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); result.push_back(Pair("result","success")); + /** Verify a Schnorr signature. + * + * Returns: 1: correct signature + * 0: incorrect or unparseable signature + * Args: ctx: a secp256k1 context object, initialized for verification. + * In: sig: the signature being verified (cannot be NULL) + * msg32: the 32-byte message hash being verified (cannot be NULL) + * pubkey: pointer to a public key to verify with (cannot be NULL) + */ + // if (!secp256k1_schnorrsig_verify(ctx, &sig, msg, &combined_pk)) { return(result); } From a709fe0fef57f03a74e6506b56ff450f31c6f5db Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 06:44:01 -1100 Subject: [PATCH 1016/1145] Remove exe permission on source files --- src/cc/dapps/cJSON.c | 0 src/cc/musig.cpp | 0 src/komodo_cJSON.c | 0 src/komodo_cJSON.h | 0 src/komodo_jumblr.h | 0 src/uthash.h | 0 src/utlist.h | 0 7 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 src/cc/dapps/cJSON.c mode change 100755 => 100644 src/cc/musig.cpp mode change 100755 => 100644 src/komodo_cJSON.c mode change 100755 => 100644 src/komodo_cJSON.h mode change 100755 => 100644 src/komodo_jumblr.h mode change 100755 => 100644 src/uthash.h mode change 100755 => 100644 src/utlist.h diff --git a/src/cc/dapps/cJSON.c b/src/cc/dapps/cJSON.c old mode 100755 new mode 100644 diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp old mode 100755 new mode 100644 diff --git a/src/komodo_cJSON.c b/src/komodo_cJSON.c old mode 100755 new mode 100644 diff --git a/src/komodo_cJSON.h b/src/komodo_cJSON.h old mode 100755 new mode 100644 diff --git a/src/komodo_jumblr.h b/src/komodo_jumblr.h old mode 100755 new mode 100644 diff --git a/src/uthash.h b/src/uthash.h old mode 100755 new mode 100644 diff --git a/src/utlist.h b/src/utlist.h old mode 100755 new mode 100644 From 7cef15077601820d30f2b14788daa3f1aad75b9d Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 18:48:22 +0100 Subject: [PATCH 1017/1145] add win deps --- src/cc/rogue/Makefile_win | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile_win b/src/cc/rogue/Makefile_win index dbc900e48..96b6e61be 100644 --- a/src/cc/rogue/Makefile_win +++ b/src/cc/rogue/Makefile_win @@ -26,7 +26,7 @@ O=o CC = x86_64-w64-mingw32-gcc #CFLAGS=-O2 -CFLAGS= -g -O2 -I./ncurses/include +CFLAGS= -g -O2 -I./ncurses/include --I../../../depends/x86_64-w64-mingw32/include #LIBS=-lcurses LIBS = -L./ncurses/lib -lncursesw From 118461e55427865e34bdbb8a873b489ca9809aab Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 18:51:12 +0100 Subject: [PATCH 1018/1145] fix typo --- src/cc/makerogue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index ff175c586..c67892b90 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -5,7 +5,7 @@ if [ "$HOST" = "x86_64-w64-mingw32" ]; then echo building rogue.exe... mkdir ncurses && cd ncurses wget https://invisible-island.net/datafiles/release/mingw32.zip - unzip mingw32.zip && delete mingw32.zip + unzip mingw32.zip && rm mingw32.zip cd .. if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL From bf44755dadc8ba400c86018d3aed161b778cb8cf Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 18:56:25 +0100 Subject: [PATCH 1019/1145] pwd --- src/cc/makerogue | 1 - 1 file changed, 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index c67892b90..9135753c1 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -6,7 +6,6 @@ if [ "$HOST" = "x86_64-w64-mingw32" ]; then mkdir ncurses && cd ncurses wget https://invisible-island.net/datafiles/release/mingw32.zip unzip mingw32.zip && rm mingw32.zip - cd .. if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL cd .. From 8998c66874885248c2ac53aa044fdee3c413bcfb Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 18:58:09 +0100 Subject: [PATCH 1020/1145] revert --- src/cc/makerogue | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/makerogue b/src/cc/makerogue index 9135753c1..c67892b90 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -6,6 +6,7 @@ if [ "$HOST" = "x86_64-w64-mingw32" ]; then mkdir ncurses && cd ncurses wget https://invisible-island.net/datafiles/release/mingw32.zip unzip mingw32.zip && rm mingw32.zip + cd .. if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL cd .. From 55b7035f9b0736f06607768e13e2cd5b94a8da06 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 19:04:45 +0100 Subject: [PATCH 1021/1145] add include --- src/cc/rogue/Makefile_win | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile_win b/src/cc/rogue/Makefile_win index 96b6e61be..17941732c 100644 --- a/src/cc/rogue/Makefile_win +++ b/src/cc/rogue/Makefile_win @@ -26,7 +26,7 @@ O=o CC = x86_64-w64-mingw32-gcc #CFLAGS=-O2 -CFLAGS= -g -O2 -I./ncurses/include --I../../../depends/x86_64-w64-mingw32/include +CFLAGS= -g -O2 -I./ncurses/include -I../../../depends/x86_64-w64-mingw32/include #LIBS=-lcurses LIBS = -L./ncurses/lib -lncursesw From 762e3582d1d1109e97c3cb81ac8fb9501236033e Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 19:09:07 +0100 Subject: [PATCH 1022/1145] pwd --- src/cc/makerogue | 1 - 1 file changed, 1 deletion(-) diff --git a/src/cc/makerogue b/src/cc/makerogue index c67892b90..9135753c1 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -6,7 +6,6 @@ if [ "$HOST" = "x86_64-w64-mingw32" ]; then mkdir ncurses && cd ncurses wget https://invisible-island.net/datafiles/release/mingw32.zip unzip mingw32.zip && rm mingw32.zip - cd .. if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL cd .. From b635717ec1219c8d3542962cfc01dc43432815b1 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 19:40:52 +0100 Subject: [PATCH 1023/1145] add ncursesw --- src/cc/rogue/Makefile_win | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile_win b/src/cc/rogue/Makefile_win index 17941732c..9c440349e 100644 --- a/src/cc/rogue/Makefile_win +++ b/src/cc/rogue/Makefile_win @@ -26,7 +26,7 @@ O=o CC = x86_64-w64-mingw32-gcc #CFLAGS=-O2 -CFLAGS= -g -O2 -I./ncurses/include -I../../../depends/x86_64-w64-mingw32/include +CFLAGS= -g -O2 -I./ncurses/include -I./ncurses/include/ncursesw -I../../../depends/x86_64-w64-mingw32/include #LIBS=-lcurses LIBS = -L./ncurses/lib -lncursesw From 47b99da2a3d4a7dfa6bd9ccce67446a6183dcabb Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 20:41:57 +0100 Subject: [PATCH 1024/1145] add debug --- src/cc/makerogue | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cc/makerogue b/src/cc/makerogue index 9135753c1..b690e60e7 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -4,8 +4,11 @@ cd rogue; if [ "$HOST" = "x86_64-w64-mingw32" ]; then echo building rogue.exe... mkdir ncurses && cd ncurses + echo $PWD wget https://invisible-island.net/datafiles/release/mingw32.zip unzip mingw32.zip && rm mingw32.zip + echo lib archive cleaned + echo $PWD if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL cd .. From fddc7d4369b242cb3b481f0a09d6247513a7913a Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 21:28:57 +0100 Subject: [PATCH 1025/1145] change dir --- src/cc/makerogue | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/makerogue b/src/cc/makerogue index b690e60e7..063de081e 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -8,6 +8,7 @@ if [ "$HOST" = "x86_64-w64-mingw32" ]; then wget https://invisible-island.net/datafiles/release/mingw32.zip unzip mingw32.zip && rm mingw32.zip echo lib archive cleaned + cd .. echo $PWD if make -f Makefile_win "$@"; then echo rogue.exe build SUCCESSFUL From adb32b5a5138baa53adb30e7d324cb3d28405fdd Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 22:36:25 +0100 Subject: [PATCH 1026/1145] add WIN ifdef --- src/cc/rogue/main.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index ca05226d3..bcd35da73 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -41,7 +41,11 @@ typedef union _bits256 bits256; double OS_milliseconds() { struct timeval tv; double millis; + #ifdef __MINGW32__ + mingw_gettimeofday(&tv,NULL); + #else gettimeofday(&tv,NULL); + #endif millis = ((double)tv.tv_sec * 1000. + (double)tv.tv_usec / 1000.); //printf("tv_sec.%ld usec.%d %f\n",tv.tv_sec,tv.tv_usec,millis); return(millis); From 064179cf1894a31b018cf1461074e6895e3b0677 Mon Sep 17 00:00:00 2001 From: ca333 Date: Thu, 21 Feb 2019 23:09:25 +0100 Subject: [PATCH 1027/1145] config WIN --- src/cc/makerogue | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/makerogue b/src/cc/makerogue index 063de081e..51caef6e2 100755 --- a/src/cc/makerogue +++ b/src/cc/makerogue @@ -3,6 +3,7 @@ cd rogue; if [ "$HOST" = "x86_64-w64-mingw32" ]; then echo building rogue.exe... + ./configure --host=x86_64-w64-mingw32 mkdir ncurses && cd ncurses echo $PWD wget https://invisible-island.net/datafiles/release/mingw32.zip From 6ca1613add51ece97efb7c9bb33ab878bd76cc2a Mon Sep 17 00:00:00 2001 From: ca333 Date: Fri, 22 Feb 2019 00:31:49 +0100 Subject: [PATCH 1028/1145] add ifdef WIN mdport --- src/cc/rogue/mdport.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/rogue/mdport.c b/src/cc/rogue/mdport.c index 988e1c7b7..fd53be72c 100644 --- a/src/cc/rogue/mdport.c +++ b/src/cc/rogue/mdport.c @@ -705,7 +705,9 @@ md_erasechar() #elif defined(VERASE) return(_tty.c_cc[VERASE]); /* process erase character */ #else + #ifndef __MINGW32__ return(_tty.sg_erase); /* process erase character */ + #endif #endif } @@ -717,7 +719,9 @@ md_killchar() #elif defined(VKILL) return(_tty.c_cc[VKILL]); #else + #ifndef __MINGW32__ return(_tty.sg_kill); + #endif #endif } From ff9f59279bc6bf3a4e178b99eebda54050208014 Mon Sep 17 00:00:00 2001 From: ca333 Date: Fri, 22 Feb 2019 01:21:04 +0100 Subject: [PATCH 1029/1145] cache deps --- .gitlab-ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 3ace05cb9..a9fb7a01b 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -32,9 +32,9 @@ build:ubuntu: variables: DOCKER_DRIVER: overlay2 cache: - key: "${CI_JOB_NAME}${CI_COMMIT_REF_NAME}" + key: ${CI_COMMIT_REF_SLUG} paths: - - depends/built + - depends/ script: - zcutil/build.sh -j$(nproc) - mkdir ${PACKAGE_DIR_LINUX} From c7b070e91ca79f220e25cfae3d65e057fae519b4 Mon Sep 17 00:00:00 2001 From: ca333 Date: Fri, 22 Feb 2019 01:48:44 +0100 Subject: [PATCH 1030/1145] add curl --- src/cc/rogue/Makefile_win | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/Makefile_win b/src/cc/rogue/Makefile_win index 9c440349e..6e558960c 100644 --- a/src/cc/rogue/Makefile_win +++ b/src/cc/rogue/Makefile_win @@ -29,7 +29,7 @@ CC = x86_64-w64-mingw32-gcc CFLAGS= -g -O2 -I./ncurses/include -I./ncurses/include/ncursesw -I../../../depends/x86_64-w64-mingw32/include #LIBS=-lcurses -LIBS = -L./ncurses/lib -lncursesw +LIBS = -L./ncurses/lib -lncursesw -lcurl #RM=rm -f RM = rm -f From ba34a8050009e4d1bef4df01b9ec685d7db5cca1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 19:58:07 -1100 Subject: [PATCH 1031/1145] +print --- src/cc/faucet.cpp | 2 +- src/cc/musig.cpp | 297 +++++++++++++++++++++++++++++++--------------- 2 files changed, 204 insertions(+), 95 deletions(-) diff --git a/src/cc/faucet.cpp b/src/cc/faucet.cpp index b44337461..3f1ac4982 100644 --- a/src/cc/faucet.cpp +++ b/src/cc/faucet.cpp @@ -124,9 +124,9 @@ bool FaucetValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx //int height = it->first.blockHeight; if ( CCduration(numblocks,it->first.txhash) > 0 && numblocks > 3 ) { - //fprintf(stderr,"would return error %s numblocks.%d ago\n",uint256_str(str,it->first.txhash),numblocks); return eval->Invalid("faucet is only for brand new addresses"); } + fprintf(stderr,"txid %s numblocks.%d ago\n",uint256_str(str,it->first.txhash),numblocks); } retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts); if ( retval != 0 ) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index ec7f5e788..263ed2fff 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -88,6 +88,54 @@ extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 +struct musig_info +{ + secp256k1_musig_session musig_session; + secp256k1_pubkey combined_pk; + uint8_t *nonce_commitments; // 32*N_SIGNERS + secp256k1_musig_session_signer_data *signer_data; //[N_SIGNERS]; + secp256k1_pubkey *nonce; //[N_SIGNERS]; + secp256k1_musig_partial_signature *partial_sig; //[N_SIGNERS]; + int32_t myind,num; + uint8_t msg[32],pkhash[32],combpk[33]; +} *MUSIG; + +struct musig_info *musig_infocreate(int32_t myind,int32_t num) +{ + struct musig_info *mp = (struct musig_info *)calloc(1,sizeof(*mp)); + mp->myind = myind, mp->num = num; + mp->nonce_commitments = (uint8_t *)calloc(num,32); + mp->signer_data = (uint8_t *)calloc(num,sizeof(*np->signer_data)); + mp->nonce = (uint8_t *)calloc(num,sizeof(*np->nonce)); + mp->partial_sig = (uint8_t *)calloc(num,sizeof(*np->partial_sig)); + return(mp); +} + +void musig_infofree(struct musig_info *mp) +{ + if ( mp->partial_sig != 0 ) + { + random_buf(mp->partial_sig,num*sizeof(*np->partial_sig)) + free(mp->partial_sig); + } + if ( mp->nonce != 0 ) + { + random_buf(mp->nonce,num*sizeof(*np->nonce)) + free(mp->nonce); + } + if ( mp->signer_data != 0 ) + { + random_buf(mp->signer_data,num*sizeof(*np->signer_data)) + free(mp->signer_data); + } + if ( mp->nonce_commitments != 0 ) + { + random_buf(mp->nonce_commitments,num*32) + free(mp->nonce_commitments); + } + free(mp); +} + CScript musig_sendopret(uint8_t funcid,CPubKey pk) { CScript opret; uint8_t evalcode = EVAL_MUSIG; @@ -215,111 +263,158 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - result.push_back(Pair("result","success")); - /** Initializes a signing session for a signer - * - * Returns: 1: session is successfully initialized - * 0: session could not be initialized: secret key or secret nonce overflow - * Args: ctx: pointer to a context object, initialized for signing (cannot - * be NULL) - * Out: session: the session structure to initialize (cannot be NULL) - * signers: an array of signers' data to be initialized. Array length must - * equal to `n_signers` (cannot be NULL) - * nonce_commitment32: filled with a 32-byte commitment to the generated nonce - * (cannot be NULL) - * In: session_id32: a *unique* 32-byte ID to assign to this session (cannot be - * NULL). If a non-unique session_id32 was given then a partial - * signature will LEAK THE SECRET KEY. - * msg32: the 32-byte message to be signed. Shouldn't be NULL unless you - * require sharing public nonces before the message is known - * because it reduces nonce misuse resistance. If NULL, must be - * set with `musig_session_set_msg` before signing and verifying. - * combined_pk: the combined public key of all signers (cannot be NULL) - * pk_hash32: the 32-byte hash of the signers' individual keys (cannot be - * NULL) - * n_signers: length of signers array. Number of signers participating in - * the MuSig. Must be greater than 0 and at most 2^32 - 1. - * my_index: index of this signer in the signers array - * seckey: the signer's 32-byte secret key (cannot be NULL) - */ - //if (!secp256k1_musig_session_initialize(ctx, &musig_session[i], signer_data[i], nonce_commitment[i], session_id32, msg32, &combined_pk, pk_hash, N_SIGNERS, i, seckeys[i])) - //return 0; - // randombytes_buf(buf, num); - - //nonce_commitment_ptr[i] = &nonce_commitment[i][0]; - return(result); + static secp256k1_context *ctx; + UniValue result(UniValue::VOBJ); int32_t i,n,myind,num; char *pkstr,*pkhashstr,*msgstr; uint8_t session[32],msg[32],pkhash[32],privkey[32],pub33[33]; CPubKey pk; char str[67]; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 5 ) + { + // set the 5 args: myind, num, pub33, pkhash32, msg32 + if ( MUSIG != 0 ) + musig_infofree(MUSIG), MUSIG = 0; + MUSIG = musig_infocreate(myind,num); + pk = buf2pk(pub33); + if ( secp256k1_ec_pubkey_parse(ctx,&MUSIG->combined_pk,pk.begin(),33) > 0 ) + { + memcpy(MUSIG->pkhash,pkhash,sizeof(pkhash)); + memcpy(MUSIG->msg,msg,sizeof(msg)); + random_buf(session,32); + Myprivkey(privkey); + /** Initializes a signing session for a signer + * + * Returns: 1: session is successfully initialized + * 0: session could not be initialized: secret key or secret nonce overflow + * Args: ctx: pointer to a context object, initialized for signing (cannot + * be NULL) + * Out: session: the session structure to initialize (cannot be NULL) + * signers: an array of signers' data to be initialized. Array length must + * equal to `n_signers` (cannot be NULL) + * nonce_commitment32: filled with a 32-byte commitment to the generated nonce + * (cannot be NULL) + * In: session_id32: a *unique* 32-byte ID to assign to this session (cannot be + * NULL). If a non-unique session_id32 was given then a partial + * signature will LEAK THE SECRET KEY. + * msg32: the 32-byte message to be signed. Shouldn't be NULL unless you + * require sharing public nonces before the message is known + * because it reduces nonce misuse resistance. If NULL, must be + * set with `musig_session_set_msg` before signing and verifying. + * combined_pk: the combined public key of all signers (cannot be NULL) + * pk_hash32: the 32-byte hash of the signers' individual keys (cannot be + * NULL) + * n_signers: length of signers array. Number of signers participating in + * the MuSig. Must be greater than 0 and at most 2^32 - 1. + * my_index: index of this signer in the signers array + * seckey: the signer's 32-byte secret key (cannot be NULL) + */ + if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitment[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) + { + result.push_back(Pair("myind",(int64_t)myind)); + result.push_back(Pair("numsigners",(int64_t)num)); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitment[MUSIG->myind*32 + i]); + str[64] = 0; + result.push_back(Pair("commitment",str)); + result.push_back(Pair("result","success")); + return(result) + } else return(cclib_error(result,"couldnt initialize session")); + } else return(cclib_error(result,"couldnt parse combined pubkey")); + } else return(cclib_error(result,"wrong number of params, need 5: myindex, numsigners, combined_pk, pkhash, msg32")); } UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - result.push_back(Pair("result","success")); - /** Gets the signer's public nonce given a list of all signers' data with commitments - * - * Returns: 1: public nonce is written in nonce - * 0: signer data is missing commitments or session isn't initialized - * for signing - * Args: ctx: pointer to a context object (cannot be NULL) - * session: the signing session to get the nonce from (cannot be NULL) - * signers: an array of signers' data initialized with - * `musig_session_initialize`. Array length must equal to - * `n_commitments` (cannot be NULL) - * Out: nonce: the nonce (cannot be NULL) - * In: commitments: array of 32-byte nonce commitments (cannot be NULL) - * n_commitments: the length of commitments and signers array. Must be the total - * number of signers participating in the MuSig. - */ - // Set nonce commitments in the signer data and get the own public nonce - //if (!secp256k1_musig_session_get_public_nonce(ctx, &musig_session[i], signer_data[i], &nonce[i], nonce_commitment_ptr, N_SIGNERS)) - // return 0; - - return(result); + static secp256k1_context *ctx; + UniValue result(UniValue::VOBJ); int32_t n; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + { + // pkhash, ind, commitment + // if all commitments, emit nonce, else just update MUSIG-> + + /** Gets the signer's public nonce given a list of all signers' data with commitments + * + * Returns: 1: public nonce is written in nonce + * 0: signer data is missing commitments or session isn't initialized + * for signing + * Args: ctx: pointer to a context object (cannot be NULL) + * session: the signing session to get the nonce from (cannot be NULL) + * signers: an array of signers' data initialized with + * `musig_session_initialize`. Array length must equal to + * `n_commitments` (cannot be NULL) + * Out: nonce: the nonce (cannot be NULL) + * In: commitments: array of 32-byte nonce commitments (cannot be NULL) + * n_commitments: the length of commitments and signers array. Must be the total + * number of signers participating in the MuSig. + */ + // Set nonce commitments in the signer data and get the own public nonce + //if (secp256k1_musig_session_get_public_nonce(ctx, &musig_session[i], signer_data[i], &nonce[i], nonce_commitment_ptr, N_SIGNERS) > 0 ) + { + // publish nonce + result.push_back(Pair("result","success")); + } + // return 0; + } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, commitment")); } UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - result.push_back(Pair("result","success")); - /** Checks a signer's public nonce against a commitment to said nonce, and update - * data structure if they match - * - * Returns: 1: commitment was valid, data structure updated - * 0: commitment was invalid, nothing happened - * Args: ctx: pointer to a context object (cannot be NULL) - * signer: pointer to the signer data to update (cannot be NULL). Must have - * been used with `musig_session_get_public_nonce` or initialized - * with `musig_session_initialize_verifier`. - * In: nonce: signer's alleged public nonce (cannot be NULL) - */ - //if (!secp256k1_musig_set_nonce(ctx, &signer_data[i][j], &nonce[j])) { - - - /** Updates a session with the combined public nonce of all signers. The combined - * public nonce is the sum of every signer's public nonce. - * - * Returns: 1: nonces are successfully combined - * 0: a signer's nonce is missing - * Args: ctx: pointer to a context object (cannot be NULL) - * session: session to update with the combined public nonce (cannot be - * NULL) - * signers: an array of signers' data, which must have had public nonces - * set with `musig_set_nonce`. Array length must equal to `n_signers` - * (cannot be NULL) - * n_signers: the length of the signers array. Must be the total number of - * signers participating in the MuSig. - * Out: nonce_is_negated: a pointer to an integer that indicates if the combined - * public nonce had to be negated. - * adaptor: point to add to the combined public nonce. If NULL, nothing is - * added to the combined nonce. - */ - // after all nonces: if (!secp256k1_musig_session_combine_nonces(ctx, &musig_session[i], signer_data[i], N_SIGNERS, NULL, NULL)) { + static secp256k1_context *ctx; + UniValue result(UniValue::VOBJ); int32_t n; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + { + // pkhash, ind, nonce + // if all nonces, combine nonce, else just update MUSIG-> + result.push_back(Pair("result","success")); + /** Checks a signer's public nonce against a commitment to said nonce, and update + * data structure if they match + * + * Returns: 1: commitment was valid, data structure updated + * 0: commitment was invalid, nothing happened + * Args: ctx: pointer to a context object (cannot be NULL) + * signer: pointer to the signer data to update (cannot be NULL). Must have + * been used with `musig_session_get_public_nonce` or initialized + * with `musig_session_initialize_verifier`. + * In: nonce: signer's alleged public nonce (cannot be NULL) + */ + //if (!secp256k1_musig_set_nonce(ctx, &signer_data[i][j], &nonce[j])) { + + + /** Updates a session with the combined public nonce of all signers. The combined + * public nonce is the sum of every signer's public nonce. + * + * Returns: 1: nonces are successfully combined + * 0: a signer's nonce is missing + * Args: ctx: pointer to a context object (cannot be NULL) + * session: session to update with the combined public nonce (cannot be + * NULL) + * signers: an array of signers' data, which must have had public nonces + * set with `musig_set_nonce`. Array length must equal to `n_signers` + * (cannot be NULL) + * n_signers: the length of the signers array. Must be the total number of + * signers participating in the MuSig. + * Out: nonce_is_negated: a pointer to an integer that indicates if the combined + * public nonce had to be negated. + * adaptor: point to add to the combined public nonce. If NULL, nothing is + * added to the combined nonce. + */ + // after all nonces: if (!secp256k1_musig_session_combine_nonces(ctx, &musig_session[i], signer_data[i], N_SIGNERS, NULL, NULL)) { return(result); + } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, nonce")); } UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); + static secp256k1_context *ctx; + UniValue result(UniValue::VOBJ); int32_t n; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + { + // similar to commit/nonce + } result.push_back(Pair("result","success")); /** Produces a partial signature * @@ -349,7 +444,14 @@ UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *para UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); + static secp256k1_context *ctx; + UniValue result(UniValue::VOBJ); int32_t n; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + { + // finally! + } result.push_back(Pair("result","success")); /** Checks that an individual partial signature verifies * @@ -387,7 +489,14 @@ UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); + static secp256k1_context *ctx; + UniValue result(UniValue::VOBJ); int32_t n; + if ( ctx == 0 ) + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + { + // can code this out of order + } result.push_back(Pair("result","success")); /** Verify a Schnorr signature. * From cb1a6291c6e45addf50146971703be58badeff52 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 19:59:46 -1100 Subject: [PATCH 1032/1145] Mp --- src/cc/musig.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 263ed2fff..b54bf26d1 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -105,9 +105,9 @@ struct musig_info *musig_infocreate(int32_t myind,int32_t num) struct musig_info *mp = (struct musig_info *)calloc(1,sizeof(*mp)); mp->myind = myind, mp->num = num; mp->nonce_commitments = (uint8_t *)calloc(num,32); - mp->signer_data = (uint8_t *)calloc(num,sizeof(*np->signer_data)); - mp->nonce = (uint8_t *)calloc(num,sizeof(*np->nonce)); - mp->partial_sig = (uint8_t *)calloc(num,sizeof(*np->partial_sig)); + mp->signer_data = (uint8_t *)calloc(num,sizeof(*mp->signer_data)); + mp->nonce = (uint8_t *)calloc(num,sizeof(*mp->nonce)); + mp->partial_sig = (uint8_t *)calloc(num,sizeof(*mp->partial_sig)); return(mp); } @@ -115,22 +115,22 @@ void musig_infofree(struct musig_info *mp) { if ( mp->partial_sig != 0 ) { - random_buf(mp->partial_sig,num*sizeof(*np->partial_sig)) + random_buf(mp->partial_sig,mp->num*sizeof(*np->partial_sig)) free(mp->partial_sig); } if ( mp->nonce != 0 ) { - random_buf(mp->nonce,num*sizeof(*np->nonce)) + random_buf(mp->nonce,mp->num*sizeof(*mp->nonce)) free(mp->nonce); } if ( mp->signer_data != 0 ) { - random_buf(mp->signer_data,num*sizeof(*np->signer_data)) + random_buf(mp->signer_data,mp->num*sizeof(*mp->signer_data)) free(mp->signer_data); } if ( mp->nonce_commitments != 0 ) { - random_buf(mp->nonce_commitments,num*32) + random_buf(mp->nonce_commitments,mp->num*32) free(mp->nonce_commitments); } free(mp); From da11af7c0ff54a3071e0e3f50723d2d6610e4364 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:01:06 -1100 Subject: [PATCH 1033/1145] Test --- src/cc/musig.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index b54bf26d1..44ddf6ef3 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -87,6 +87,7 @@ extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 +#define random_buf(a,b) struct musig_info { @@ -105,9 +106,9 @@ struct musig_info *musig_infocreate(int32_t myind,int32_t num) struct musig_info *mp = (struct musig_info *)calloc(1,sizeof(*mp)); mp->myind = myind, mp->num = num; mp->nonce_commitments = (uint8_t *)calloc(num,32); - mp->signer_data = (uint8_t *)calloc(num,sizeof(*mp->signer_data)); - mp->nonce = (uint8_t *)calloc(num,sizeof(*mp->nonce)); - mp->partial_sig = (uint8_t *)calloc(num,sizeof(*mp->partial_sig)); + mp->signer_data = (secp256k1_musig_session_signer_data *)calloc(num,sizeof(*mp->signer_data)); + mp->nonce = (secp256k1_pubkey *)calloc(num,sizeof(*mp->nonce)); + mp->partial_sig = (secp256k1_musig_partial_signature *)calloc(num,sizeof(*mp->partial_sig)); return(mp); } @@ -115,7 +116,7 @@ void musig_infofree(struct musig_info *mp) { if ( mp->partial_sig != 0 ) { - random_buf(mp->partial_sig,mp->num*sizeof(*np->partial_sig)) + random_buf(mp->partial_sig,mp->num*sizeof(*mp->partial_sig)) free(mp->partial_sig); } if ( mp->nonce != 0 ) From e1c434466734a26921d98c6e0db1cb12df3a2f08 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:02:05 -1100 Subject: [PATCH 1034/1145] syntax --- src/cc/musig.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 44ddf6ef3..aa821f644 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -307,16 +307,16 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * my_index: index of this signer in the signers array * seckey: the signer's 32-byte secret key (cannot be NULL) */ - if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitment[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) + if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) { result.push_back(Pair("myind",(int64_t)myind)); result.push_back(Pair("numsigners",(int64_t)num)); for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitment[MUSIG->myind*32 + i]); + sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitments[MUSIG->myind*32 + i]); str[64] = 0; result.push_back(Pair("commitment",str)); result.push_back(Pair("result","success")); - return(result) + return(result); } else return(cclib_error(result,"couldnt initialize session")); } else return(cclib_error(result,"couldnt parse combined pubkey")); } else return(cclib_error(result,"wrong number of params, need 5: myindex, numsigners, combined_pk, pkhash, msg32")); From 40c26873ba97286ed860c8e4c742b68cc28f237c Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:03:14 -1100 Subject: [PATCH 1035/1145] extern "C" --- src/cc/musig.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index aa821f644..68787e67b 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -78,6 +78,7 @@ extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, s extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, unsigned char *pk_hash32, const secp256k1_pubkey *pubkeys, size_t n_pubkeys); +extern "C" int secp256k1_musig_session_initialize(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, unsigned char *nonce_commitment32, const unsigned char *session_id32, const unsigned char *msg32, const secp256k1_pubkey *combined_pk, const unsigned char *pk_hash32, size_t n_signers, size_t my_index, const unsigned char *seckey); //#include "../secp256k1/include/secp256k1.h" From 146d452410880c1657f479c22f33d51402b667aa Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:03:56 -1100 Subject: [PATCH 1036/1145] Reorder --- src/cc/musig.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 68787e67b..8fdba80a2 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -74,18 +74,18 @@ struct secp256k1_context_struct { secp256k1_callback error_callback; }; -extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); -extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); -extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); -extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, unsigned char *pk_hash32, const secp256k1_pubkey *pubkeys, size_t n_pubkeys); -extern "C" int secp256k1_musig_session_initialize(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, unsigned char *nonce_commitment32, const unsigned char *session_id32, const unsigned char *msg32, const secp256k1_pubkey *combined_pk, const unsigned char *pk_hash32, size_t n_signers, size_t my_index, const unsigned char *seckey); - //#include "../secp256k1/include/secp256k1.h" //#include "../secp256k1/include/secp256k1_schnorrsig.h" #include "../secp256k1/include/secp256k1_musig.h" +extern "C" int secp256k1_ecmult_multi_var(const secp256k1_ecmult_context *ctx, secp256k1_scratch *scratch, secp256k1_gej *r, const secp256k1_scalar *inp_g_sc, secp256k1_ecmult_multi_callback cb, void *cbdata, size_t n); +extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const secp256k1_schnorrsig *sig, const unsigned char *msg32, const secp256k1_pubkey *pk); +extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); +extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, unsigned char *pk_hash32, const secp256k1_pubkey *pubkeys, size_t n_pubkeys); +extern "C" int secp256k1_musig_session_initialize(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, unsigned char *nonce_commitment32, const unsigned char *session_id32, const unsigned char *msg32, const secp256k1_pubkey *combined_pk, const unsigned char *pk_hash32, size_t n_signers, size_t my_index, const unsigned char *seckey); + #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 #define random_buf(a,b) From c76bd865230436337d54231fcaa6ca86957cb0b2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:06:25 -1100 Subject: [PATCH 1037/1145] #ifdef __cplusplus --- src/secp256k1/include/secp256k1_musig.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/include/secp256k1_musig.h b/src/secp256k1/include/secp256k1_musig.h index 7e974e36d..d58550cf8 100644 --- a/src/secp256k1/include/secp256k1_musig.h +++ b/src/secp256k1/include/secp256k1_musig.h @@ -167,7 +167,12 @@ SECP256K1_API int secp256k1_musig_pubkey_combine( * my_index: index of this signer in the signers array * seckey: the signer's 32-byte secret key (cannot be NULL) */ -SECP256K1_API int secp256k1_musig_session_initialize( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_session_initialize( const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, From db9149577974a6cda3a60ae4196c9b2d7a3eeec5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:07:50 -1100 Subject: [PATCH 1038/1145] Again --- src/secp256k1/include/secp256k1_musig.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/secp256k1/include/secp256k1_musig.h b/src/secp256k1/include/secp256k1_musig.h index d58550cf8..a0106e691 100644 --- a/src/secp256k1/include/secp256k1_musig.h +++ b/src/secp256k1/include/secp256k1_musig.h @@ -132,7 +132,12 @@ typedef struct { * key (cannot be NULL) * n_pubkeys: length of pubkeys array */ -SECP256K1_API int secp256k1_musig_pubkey_combine( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_pubkey_combine( const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, From f20d2860dec77fcdca16d874787a037058855cf5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:11:38 -1100 Subject: [PATCH 1039/1145] -print --- src/cc/faucet.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/faucet.cpp b/src/cc/faucet.cpp index 3f1ac4982..b794d9b1c 100644 --- a/src/cc/faucet.cpp +++ b/src/cc/faucet.cpp @@ -126,7 +126,7 @@ bool FaucetValidate(struct CCcontract_info *cp,Eval* eval,const CTransaction &tx { return eval->Invalid("faucet is only for brand new addresses"); } - fprintf(stderr,"txid %s numblocks.%d ago\n",uint256_str(str,it->first.txhash),numblocks); + //fprintf(stderr,"txid %s numblocks.%d ago\n",uint256_str(str,it->first.txhash),numblocks); } retval = PreventCC(eval,tx,preventCCvins,numvins,preventCCvouts,numvouts); if ( retval != 0 ) From f448c53ac872751e8a2f3d5bd6ed562b61e28443 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:13:18 -1100 Subject: [PATCH 1040/1145] (uint8_t *) --- src/cc/musig.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 8fdba80a2..80da59927 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -88,7 +88,6 @@ extern "C" int secp256k1_musig_session_initialize(const secp256k1_context* ctx, #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 -#define random_buf(a,b) struct musig_info { @@ -117,22 +116,22 @@ void musig_infofree(struct musig_info *mp) { if ( mp->partial_sig != 0 ) { - random_buf(mp->partial_sig,mp->num*sizeof(*mp->partial_sig)) + GetRandBytes((uint8_t *)mp->partial_sig,mp->num*sizeof(*mp->partial_sig)) free(mp->partial_sig); } if ( mp->nonce != 0 ) { - random_buf(mp->nonce,mp->num*sizeof(*mp->nonce)) + GetRandBytes((uint8_t *)mp->nonce,mp->num*sizeof(*mp->nonce)) free(mp->nonce); } if ( mp->signer_data != 0 ) { - random_buf(mp->signer_data,mp->num*sizeof(*mp->signer_data)) + GetRandBytes((uint8_t *)mp->signer_data,mp->num*sizeof(*mp->signer_data)) free(mp->signer_data); } if ( mp->nonce_commitments != 0 ) { - random_buf(mp->nonce_commitments,mp->num*32) + GetRandBytes((uint8_t *)mp->nonce_commitments,mp->num*32) free(mp->nonce_commitments); } free(mp); @@ -280,7 +279,7 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { memcpy(MUSIG->pkhash,pkhash,sizeof(pkhash)); memcpy(MUSIG->msg,msg,sizeof(msg)); - random_buf(session,32); + GetRandBytes(session,32); Myprivkey(privkey); /** Initializes a signing session for a signer * From 41d1eef0191a48413140f73c5d8abb30602cfceb Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:14:14 -1100 Subject: [PATCH 1041/1145] ; --- src/cc/musig.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 80da59927..633c95feb 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -116,24 +116,25 @@ void musig_infofree(struct musig_info *mp) { if ( mp->partial_sig != 0 ) { - GetRandBytes((uint8_t *)mp->partial_sig,mp->num*sizeof(*mp->partial_sig)) + GetRandBytes((uint8_t *)mp->partial_sig,mp->num*sizeof(*mp->partial_sig)); free(mp->partial_sig); } if ( mp->nonce != 0 ) { - GetRandBytes((uint8_t *)mp->nonce,mp->num*sizeof(*mp->nonce)) + GetRandBytes((uint8_t *)mp->nonce,mp->num*sizeof(*mp->nonce)); free(mp->nonce); } if ( mp->signer_data != 0 ) { - GetRandBytes((uint8_t *)mp->signer_data,mp->num*sizeof(*mp->signer_data)) + GetRandBytes((uint8_t *)mp->signer_data,mp->num*sizeof(*mp->signer_data)); free(mp->signer_data); } if ( mp->nonce_commitments != 0 ) { - GetRandBytes((uint8_t *)mp->nonce_commitments,mp->num*32) + GetRandBytes((uint8_t *)mp->nonce_commitments,mp->num*32); free(mp->nonce_commitments); } + GetRandBytes((uint8_t *)mp,sizeof(*mp)); free(mp); } From dc3767b68f5369114164235da1297ebb07525356 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:15:40 -1100 Subject: [PATCH 1042/1145] Session --- src/cc/musig.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 633c95feb..9f529a341 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -281,6 +281,10 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) memcpy(MUSIG->pkhash,pkhash,sizeof(pkhash)); memcpy(MUSIG->msg,msg,sizeof(msg)); GetRandBytes(session,32); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",session[i]); + str[64] = 0; + fprintf(stderr,"session %s\n",str); Myprivkey(privkey); /** Initializes a signing session for a signer * From 3bc10962e5af83cbca4eaf7f8edf5046ce21b5d0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 20:17:28 -1100 Subject: [PATCH 1043/1145] Move --- src/cc/musig.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 9f529a341..fc83fe382 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -276,15 +276,15 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) musig_infofree(MUSIG), MUSIG = 0; MUSIG = musig_infocreate(myind,num); pk = buf2pk(pub33); + GetRandBytes(session,32); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",session[i]); + str[64] = 0; + fprintf(stderr,"session %s\n",str); if ( secp256k1_ec_pubkey_parse(ctx,&MUSIG->combined_pk,pk.begin(),33) > 0 ) { memcpy(MUSIG->pkhash,pkhash,sizeof(pkhash)); memcpy(MUSIG->msg,msg,sizeof(msg)); - GetRandBytes(session,32); - for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",session[i]); - str[64] = 0; - fprintf(stderr,"session %s\n",str); Myprivkey(privkey); /** Initializes a signing session for a signer * From d84a9afe6f071c0801f1350c9acbf7a128f96c55 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 22:03:15 -1100 Subject: [PATCH 1044/1145] Add parsing for session --- src/cc/musig.cpp | 64 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 46 insertions(+), 18 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index fc83fe382..ccb554e0f 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -223,6 +223,27 @@ UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } else return(cclib_error(result,"couldnt parse params")); } +int32_t musig_parsepubkey(secp256k1_context *ctx,secp256k1_pubkey &spk,cJSON *item) +{ + char *hexstr; + if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 66 ) + { + CPubKey pk(ParseHex(hexstr)); + if ( secp256k1_ec_pubkey_parse(ctx,&spk,pk.begin(),33) > 0 ) + return(1); + } else return(-1); +} + +int32_t musig_parsehash32(uint8_t *hash32,cJSON *item) +{ + char *hexstr; + if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 64 ) + { + decode_hex(hash32,32,hexstr); + return(0); + } else return(-1); +} + UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; @@ -235,13 +256,9 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //fprintf(stderr,"n.%d args.(%s)\n",n,jprint(params,0)); for (i=0; i 0 ) - pubkeys.push_back(spk); - else return(cclib_error(result,"error parsing pk")); - } else return(cclib_error(result,"all pubkeys must be 33 bytes hexdata")); + if ( musig_parsepubkey(ctx,spk,jitem(params,i)) < 0 ) + return(cclib_error(result,"error parsing pk")); + pubkeys.push_back(spk); } if ( secp256k1_musig_pubkey_combine(ctx,NULL,&combined_pk,pkhash,&pubkeys[0],n) > 0 ) { @@ -271,21 +288,26 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 5 ) { - // set the 5 args: myind, num, pub33, pkhash32, msg32 + myind = juint(jitem(params,0),0); + num = juint(jitem(params,1),0); + if ( myind < 0 || myind >= num || num <= 0 ) + return(cclib_error(result,"illegal myindex and numsigners")); if ( MUSIG != 0 ) musig_infofree(MUSIG), MUSIG = 0; MUSIG = musig_infocreate(myind,num); - pk = buf2pk(pub33); - GetRandBytes(session,32); - for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",session[i]); - str[64] = 0; - fprintf(stderr,"session %s\n",str); - if ( secp256k1_ec_pubkey_parse(ctx,&MUSIG->combined_pk,pk.begin(),33) > 0 ) + if ( musig_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) + return(cclib_error(result,"error parsing combined_pubkey")); { - memcpy(MUSIG->pkhash,pkhash,sizeof(pkhash)); - memcpy(MUSIG->msg,msg,sizeof(msg)); + if ( musig_parsehash32(MUSIG->pkhash,jitem(params,3)) < 0 ) + return(cclib_error(result,"error parsing pkhash")); + if ( musig_parsehash32(MUSIG->msg,jitem(params,4)) < 0 ) + return(cclib_error(result,"error parsing msg")); Myprivkey(privkey); + GetRandBytes(session,32); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",session[i]); + str[64] = 0; + fprintf(stderr,"session %s\n",str); /** Initializes a signing session for a signer * * Returns: 1: session is successfully initialized @@ -314,6 +336,7 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) */ if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) { + memset(session,0,sizeof(session)); result.push_back(Pair("myind",(int64_t)myind)); result.push_back(Pair("numsigners",(int64_t)num)); for (i=0; i<32; i++) @@ -322,7 +345,12 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("commitment",str)); result.push_back(Pair("result","success")); return(result); - } else return(cclib_error(result,"couldnt initialize session")); + } + else + { + memset(session,0,sizeof(session)); + return(cclib_error(result,"couldnt initialize session")); + } } else return(cclib_error(result,"couldnt parse combined pubkey")); } else return(cclib_error(result,"wrong number of params, need 5: myindex, numsigners, combined_pk, pkhash, msg32")); } From 101a4153799c06ce3efc6705286c36184c3c383b Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 22:05:27 -1100 Subject: [PATCH 1045/1145] Fix --- src/cc/musig.cpp | 52 +++++++++++++++++++++--------------------------- 1 file changed, 23 insertions(+), 29 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index ccb554e0f..7b9510b2a 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -297,17 +297,12 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) MUSIG = musig_infocreate(myind,num); if ( musig_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing combined_pubkey")); - { - if ( musig_parsehash32(MUSIG->pkhash,jitem(params,3)) < 0 ) - return(cclib_error(result,"error parsing pkhash")); - if ( musig_parsehash32(MUSIG->msg,jitem(params,4)) < 0 ) - return(cclib_error(result,"error parsing msg")); - Myprivkey(privkey); - GetRandBytes(session,32); - for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",session[i]); - str[64] = 0; - fprintf(stderr,"session %s\n",str); + else if ( musig_parsehash32(MUSIG->pkhash,jitem(params,3)) < 0 ) + return(cclib_error(result,"error parsing pkhash")); + else if ( musig_parsehash32(MUSIG->msg,jitem(params,4)) < 0 ) + return(cclib_error(result,"error parsing msg")); + Myprivkey(privkey); + GetRandBytes(session,32); /** Initializes a signing session for a signer * * Returns: 1: session is successfully initialized @@ -334,24 +329,23 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * my_index: index of this signer in the signers array * seckey: the signer's 32-byte secret key (cannot be NULL) */ - if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) - { - memset(session,0,sizeof(session)); - result.push_back(Pair("myind",(int64_t)myind)); - result.push_back(Pair("numsigners",(int64_t)num)); - for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitments[MUSIG->myind*32 + i]); - str[64] = 0; - result.push_back(Pair("commitment",str)); - result.push_back(Pair("result","success")); - return(result); - } - else - { - memset(session,0,sizeof(session)); - return(cclib_error(result,"couldnt initialize session")); - } - } else return(cclib_error(result,"couldnt parse combined pubkey")); + if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) + { + memset(session,0,sizeof(session)); + result.push_back(Pair("myind",(int64_t)myind)); + result.push_back(Pair("numsigners",(int64_t)num)); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitments[MUSIG->myind*32 + i]); + str[64] = 0; + result.push_back(Pair("commitment",str)); + result.push_back(Pair("result","success")); + return(result); + } + else + { + memset(session,0,sizeof(session)); + return(cclib_error(result,"couldnt initialize session")); + } } else return(cclib_error(result,"wrong number of params, need 5: myindex, numsigners, combined_pk, pkhash, msg32")); } From eb09e81eaedefc639bb3ea61729066e3b33224b4 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:29:46 -1100 Subject: [PATCH 1046/1145] Musig commitment, nonce and partial sig roc --- src/cc/cclib.cpp | 20 +- src/cc/musig.cpp | 231 +++++++++++-------- src/secp256k1/include/secp256k1_musig.h | 84 ++++++- src/secp256k1/include/secp256k1_schnorrsig.h | 14 +- 4 files changed, 226 insertions(+), 123 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index bfd57e61d..ec74877b6 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -72,12 +72,11 @@ CClib_methods[] = { (char *)"sudoku", (char *)"pending", (char *)"", 0, 0, 'U', EVAL_SUDOKU }, { (char *)"sudoku", (char *)"solution", (char *)"txid solution timestamps[81]", 83, 83, 'S', EVAL_SUDOKU }, { (char *)"musig", (char *)"calcmsg", (char *)"sendtxid scriptPubKey", 2, 2, 'C', EVAL_MUSIG }, - { (char *)"musig", (char *)"combine", (char *)"pubkeys ...", 2, 256, 'P', EVAL_MUSIG }, - { (char *)"musig", (char *)"session", (char *)"msg pkhash", 2, 2, 'R', EVAL_MUSIG }, - { (char *)"musig", (char *)"commit", (char *)"pubkeys ...", 2, 256, 'H', EVAL_MUSIG }, - { (char *)"musig", (char *)"nonce", (char *)"pubkeys ...", 2, 256, 'N', EVAL_MUSIG }, - { (char *)"musig", (char *)"partialsign", (char *)"pubkeys ...", 2, 256, 'S', EVAL_MUSIG }, - { (char *)"musig", (char *)"sigcombine", (char *)"pubkeys ...", 2, 256, 'M', EVAL_MUSIG }, + { (char *)"musig", (char *)"combine", (char *)"pubkeys ...", 2, 999999999, 'P', EVAL_MUSIG }, + { (char *)"musig", (char *)"session", (char *)"myindex,numsigners,combined_pk,pkhash,msg32", 5, 5, 'R', EVAL_MUSIG }, + { (char *)"musig", (char *)"commit", (char *)"pkhash,ind,commitment", 3, 3, 'H', EVAL_MUSIG }, + { (char *)"musig", (char *)"nonce", (char *)"pkhash,ind,nonce", 3, 3, 'N', EVAL_MUSIG }, + { (char *)"musig", (char *)"partialsig", (char *)"pkhash,ind,partialsig", 3, 3, 'S', EVAL_MUSIG }, { (char *)"musig", (char *)"verify", (char *)"msg sig pubkey", 3, 3, 'V', EVAL_MUSIG }, { (char *)"musig", (char *)"send", (char *)"combined_pk amount", 2, 2, 'x', EVAL_MUSIG }, { (char *)"musig", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_MUSIG }, @@ -116,8 +115,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); -UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); -UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); @@ -229,10 +227,8 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,char *jsonstr) return(musig_commit(txfee,cp,params)); else if ( strcmp(method,"nonce") == 0 ) // returns combined nonce if ready return(musig_nonce(txfee,cp,params)); - else if ( strcmp(method,"partialsign") == 0 ) - return(musig_partialsign(txfee,cp,params)); - else if ( strcmp(method,"sigcombine") == 0 ) - return(musig_sigcombine(txfee,cp,params)); + else if ( strcmp(method,"partialsig") == 0 ) + return(musig_partialsig(txfee,cp,params)); else if ( strcmp(method,"verify") == 0 ) return(musig_verify(txfee,cp,params)); else if ( strcmp(method,"send") == 0 ) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 7b9510b2a..f6a7bf7b7 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -20,6 +20,7 @@ "combined_pk": "032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b", "result": "success" } + the combined_pk and pkhash will be needed for various other rpc calls */ /* second, send 0.777 coins to the combined_pk @@ -55,6 +56,33 @@ "result": "success", "msg": "63b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485" } +the "msg" is what needs to be signed to create a valid spend + + now on each signing node, a session needs to be created: + 5 args: ind, numsigners, combined_pk, pkhash, message to be signed + + on node with pubkey: 02aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848 + ./c cclib session 18 \"[0,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%2263b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485%22]\" + { + "myind": 0, + "numsigners": 2, + "commitment": "053a97ba56b1b8adf174a0a28dc16b1bb4e91a33ca0b52a579ce9ba4af299973", + "result": "success" + } + + on node with pubkey: 039433dc3749aece1bd568f374a45da3b0bc6856990d7da3cd175399577940a775 + ./c cclib session 18 \"[1,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%2263b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485%22]\" + { + "myind": 1, + "numsigners": 2, + "commitment": "8c8dc6717aaa1994d4a51d1094c0c5cbfaf033c11642dbeeab32a32de4cfbc86", + "result": "success" + } + + now we need to get the commitment from each node to the other one. the session already put the commitment for each node into the global struct. Keep in mind there is a single global struct with session unique to each cclib session call. that means no restarting any deamon in the middle of the process on any of the nodes and only call cclib session a single time. this is an artificial restriction just to simplify the initial implementation of musig + + ./c cclib commitment 18 \"[1,%228c8dc6717aaa1994d4a51d1094c0c5cbfaf033c11642dbeeab32a32de4cfbc86%22]\" + ./c cclib commitment 18 \"[0,%22053a97ba56b1b8adf174a0a28dc16b1bb4e91a33ca0b52a579ce9ba4af299973%22]\" */ @@ -91,9 +119,9 @@ extern "C" int secp256k1_musig_session_initialize(const secp256k1_context* ctx, struct musig_info { - secp256k1_musig_session musig_session; + secp256k1_musig_session session; secp256k1_pubkey combined_pk; - uint8_t *nonce_commitments; // 32*N_SIGNERS + uint8_t *nonce_commitments,**commitment_ptrs; // 32*N_SIGNERS secp256k1_musig_session_signer_data *signer_data; //[N_SIGNERS]; secp256k1_pubkey *nonce; //[N_SIGNERS]; secp256k1_musig_partial_signature *partial_sig; //[N_SIGNERS]; @@ -103,9 +131,12 @@ struct musig_info struct musig_info *musig_infocreate(int32_t myind,int32_t num) { - struct musig_info *mp = (struct musig_info *)calloc(1,sizeof(*mp)); + int32_t i; struct musig_info *mp = (struct musig_info *)calloc(1,sizeof(*mp)); mp->myind = myind, mp->num = num; mp->nonce_commitments = (uint8_t *)calloc(num,32); + mp->commitment_ptrs = (uint8_t **)calloc(num,sizeof(*mp->commitment_ptrs)); + for (i=0; icommitment_ptrs[i] = &mp->nonce_commitments[i*32]; mp->signer_data = (secp256k1_musig_session_signer_data *)calloc(num,sizeof(*mp->signer_data)); mp->nonce = (secp256k1_pubkey *)calloc(num,sizeof(*mp->nonce)); mp->partial_sig = (secp256k1_musig_partial_signature *)calloc(num,sizeof(*mp->partial_sig)); @@ -134,6 +165,11 @@ void musig_infofree(struct musig_info *mp) GetRandBytes((uint8_t *)mp->nonce_commitments,mp->num*32); free(mp->nonce_commitments); } + if ( mp->commitment_ptrs != 0 ) + { + GetRandBytes((uint8_t *)mp->commitment_ptrs,mp->num*sizeof(*mp->commitment_ptrs)); + free(mp->commitment_ptrs); + } GetRandBytes((uint8_t *)mp,sizeof(*mp)); free(mp); } @@ -329,7 +365,7 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * my_index: index of this signer in the signers array * seckey: the signer's 32-byte secret key (cannot be NULL) */ - if ( secp256k1_musig_session_initialize(ctx,&MUSIG->musig_session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) + if ( secp256k1_musig_session_initialize(ctx,&MUSIG->session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) { memset(session,0,sizeof(session)); result.push_back(Pair("myind",(int64_t)myind)); @@ -352,14 +388,19 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t n; + UniValue result(UniValue::VOBJ); int32_t n,ind; uint8_t pkhash[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - // pkhash, ind, commitment - // if all commitments, emit nonce, else just update MUSIG-> - + if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) + return(cclib_error(result,"error parsing pkhash")); + else if ( memcmp(MUSING->pkhash,pkhash,32) != 0 ) + return(cclib_error(result,"pkhash doesnt match session pkhash")); + else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + return(cclib_error(result,"illegal ind for session")); + else if ( musig_parsehash32(&MUSIG->commitment[ind*32],jitem(params,2)) < 0 ) + return(cclib_error(result,"error parsing commitment")); /** Gets the signer's public nonce given a list of all signers' data with commitments * * Returns: 1: public nonce is written in nonce @@ -375,27 +416,44 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * n_commitments: the length of commitments and signers array. Must be the total * number of signers participating in the MuSig. */ - // Set nonce commitments in the signer data and get the own public nonce - //if (secp256k1_musig_session_get_public_nonce(ctx, &musig_session[i], signer_data[i], &nonce[i], nonce_commitment_ptr, N_SIGNERS) > 0 ) + result.push_back(Pair("added_index",ind)); + if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->nonce_commitments,MUSIG->num) > 0 ) { - // publish nonce + if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG->nonces[MUSIG->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) + { + for (i=0; i<33; i++) + sprintf(&str[i<<1],"%02x",((uint8_t *)pk.begin())[i]); + str[66] = 0; + result.push_back(Pair("nonce",str)); + result.push_back(Pair("result","success")); + } else return(cclib_error(result,"error serializing nonce (pubkey)")); + } + else + { + result.push_back(Pair("status","not enough commitments")); result.push_back(Pair("result","success")); } - // return 0; + return(result); } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, commitment")); } UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t n; + UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32],psig[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - // pkhash, ind, nonce - // if all nonces, combine nonce, else just update MUSIG-> - result.push_back(Pair("result","success")); + if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) + return(cclib_error(result,"error parsing pkhash")); + else if ( memcmp(MUSING->pkhash,pkhash,32) != 0 ) + return(cclib_error(result,"pkhash doesnt match session pkhash")); + else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + return(cclib_error(result,"illegal ind for session")); + else if ( musig_parsepubkey(ctx,&MUSIG->nonces[ind],jitem(params,2)) < 0 ) + return(cclib_error(result,"error parsing nonce")); + result.push_back(Pair("added_index",ind)); /** Checks a signer's public nonce against a commitment to said nonce, and update * data structure if they match * @@ -407,9 +465,11 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * with `musig_session_initialize_verifier`. * In: nonce: signer's alleged public nonce (cannot be NULL) */ - //if (!secp256k1_musig_set_nonce(ctx, &signer_data[i][j], &nonce[j])) { - - + for (i=0; inum; i++) + { + if ( secp256k1_musig_set_nonce(ctx,&MUSIG->signer_data[i],&MUSIG->nonces[i]) == 0 ) + return(cclib_error(result,"error setting nonce")); + } /** Updates a session with the combined public nonce of all signers. The combined * public nonce is the sum of every signer's public nonce. * @@ -428,91 +488,68 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * adaptor: point to add to the combined public nonce. If NULL, nothing is * added to the combined nonce. */ - // after all nonces: if (!secp256k1_musig_session_combine_nonces(ctx, &musig_session[i], signer_data[i], N_SIGNERS, NULL, NULL)) { - return(result); + if ( secp256k1_musig_session_combine_nonces(ctx,&MUSIG->session,MUSIG->signer_data,MUSIG->num,NULL,NULL) > 0 ) + { + if ( secp256k1_musig_partial_sign(ctx,&MUSIG->session,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + { + if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + { + result.push_back(Pair("myind",ind)); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",psig[i]); + str[64] = 0; + result.push_back(Pair("partialsig",str)); + result.push_back(Pair("result","success")); + return(result); + } else return(cclib_error(result,"error serializing partial sig")); + } else return(cclib_error(result,"error making partial sig")); + } else return(cclib_error(result,"error combining nonces")); } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, nonce")); } -UniValue musig_partialsign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t n; + UniValue result(UniValue::VOBJ); int32_t ind,n; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - // similar to commit/nonce - } - result.push_back(Pair("result","success")); - /** Produces a partial signature - * - * Returns: 1: partial signature constructed - * 0: session in incorrect or inconsistent state - * Args: ctx: pointer to a context object (cannot be NULL) - * session: active signing session for which the combined nonce has been - * computed (cannot be NULL) - * Out: partial_sig: partial signature (cannot be NULL) - */ - //if (!secp256k1_musig_partial_sign(ctx, &musig_session[i], &partial_sig[i])) { - /** Parse and verify a MuSig partial signature. - * - * Returns: 1 when the signature could be parsed, 0 otherwise. - * Args: ctx: a secp256k1 context object - * Out: sig: pointer to a signature object - * In: in32: pointer to the 32-byte signature to be parsed - * - * After the call, sig will always be initialized. If parsing failed or the - * encoded numbers are out of range, signature verification with it is - * guaranteed to fail for every message and public key. - */ - //SECP256K1_API int secp256k1_musig_partial_signature_parse( - - return(result); -} - -UniValue musig_sigcombine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) -{ - static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t n; - if ( ctx == 0 ) - ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) - { - // finally! - } - result.push_back(Pair("result","success")); - /** Checks that an individual partial signature verifies - * - * This function is essential when using protocols with adaptor signatures. - * However, it is not essential for regular MuSig's, in the sense that if any - * partial signatures does not verify, the full signature will also not verify, so the - * problem will be caught. But this function allows determining the specific party - * who produced an invalid signature, so that signing can be restarted without them. - * - * Returns: 1: partial signature verifies - * 0: invalid signature or bad data - * Args: ctx: pointer to a context object (cannot be NULL) - * session: active session for which the combined nonce has been computed - * (cannot be NULL) - * signer: data for the signer who produced this signature (cannot be NULL) - * In: partial_sig: signature to verify (cannot be NULL) - * pubkey: public key of the signer who produced the signature (cannot be NULL) - */ - //if (!secp256k1_musig_partial_sig_verify(ctx, &musig_session[i], &signer_data[i][j], &partial_sig[j], &pubkeys[j])) { - return 0; - /** Combines partial signatures - * - * Returns: 1: all partial signatures have values in range. Does NOT mean the - * resulting signature verifies. - * 0: some partial signature had s/r out of range - * Args: ctx: pointer to a context object (cannot be NULL) - * session: initialized session for which the combined nonce has been - * computed (cannot be NULL) - * Out: sig: complete signature (cannot be NULL) - * In: partial_sigs: array of partial signatures to combine (cannot be NULL) - * n_sigs: number of signatures in the partial_sigs array - */ - // after all partials: return secp256k1_musig_partial_sig_combine(ctx, &musig_session[0], sig, partial_sig, N_SIGNERS return(result); + if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) + return(cclib_error(result,"error parsing pkhash")); + else if ( memcmp(MUSING->pkhash,pkhash,32) != 0 ) + return(cclib_error(result,"pkhash doesnt match session pkhash")); + else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + return(cclib_error(result,"illegal ind for session")); + else if ( musig_parsepartial(ctx,&MUSIG->partial_sig[ind],jitem(params,2)) < 0 ) + return(cclib_error(result,"error parsing partialsig")); + result.push_back(Pair("added_index",ind)); + if (secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) + { + if ( secp256k1_schnorrsig_serialize(ctx,out64,&sig) > 0 ) + { + result.push_back(Pair("result","success")); + for (i=0; i<64; i++) + sprintf(&str[i<<1],"%02x",out64[i]); + str[128] = 0; + result.push_back(Pair("combinedsig",str)); + } else return(cclib_error(result,"error serializing combinedsig")); + } + else + { + if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + { + result.push_back(Pair("myind",ind)); + for (i=0; i<32; i++) + sprintf(&str[i<<1],"%02x",psig[i]); + str[64] = 0; + result.push_back(Pair("partialsig",str)); + result.push_back(Pair("result","success")); + result.push_back(Pair("status","need more partialsigs")); + } else return(cclib_error(result,"error generating my partialsig")); + } + return(result); + } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, partialsig")); } UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) diff --git a/src/secp256k1/include/secp256k1_musig.h b/src/secp256k1/include/secp256k1_musig.h index a0106e691..84106822a 100644 --- a/src/secp256k1/include/secp256k1_musig.h +++ b/src/secp256k1/include/secp256k1_musig.h @@ -206,7 +206,12 @@ SECP256K1_API * n_commitments: the length of commitments and signers array. Must be the total * number of signers participating in the MuSig. */ -SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_get_public_nonce( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_get_public_nonce( const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, @@ -235,7 +240,12 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_get_publi * participating in the MuSig. Must be greater than 0 and at most * 2^32 - 1. */ -SECP256K1_API int secp256k1_musig_session_initialize_verifier( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_session_initialize_verifier( const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, @@ -257,7 +267,12 @@ SECP256K1_API int secp256k1_musig_session_initialize_verifier( * with `musig_session_initialize_verifier`. * In: nonce: signer's alleged public nonce (cannot be NULL) */ -SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_set_nonce( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_set_nonce( const secp256k1_context* ctx, secp256k1_musig_session_signer_data *signer, const secp256k1_pubkey *nonce @@ -281,7 +296,12 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_set_nonce( * adaptor: point to add to the combined public nonce. If NULL, nothing is * added to the combined nonce. */ -SECP256K1_API int secp256k1_musig_session_combine_nonces( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_session_combine_nonces( const secp256k1_context* ctx, secp256k1_musig_session *session, const secp256k1_musig_session_signer_data *signers, @@ -298,7 +318,12 @@ SECP256K1_API int secp256k1_musig_session_combine_nonces( * session: the session structure to update with the message (cannot be NULL) * In: msg32: the 32-byte message to be signed (cannot be NULL) */ -SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_set_msg( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_set_msg( const secp256k1_context* ctx, secp256k1_musig_session *session, const unsigned char *msg32 @@ -311,7 +336,12 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_session_set_msg( * Out: out32: pointer to a 32-byte array to store the serialized signature * In: sig: pointer to the signature */ -SECP256K1_API int secp256k1_musig_partial_signature_serialize( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_partial_signature_serialize( const secp256k1_context* ctx, unsigned char *out32, const secp256k1_musig_partial_signature* sig @@ -328,7 +358,12 @@ SECP256K1_API int secp256k1_musig_partial_signature_serialize( * encoded numbers are out of range, signature verification with it is * guaranteed to fail for every message and public key. */ -SECP256K1_API int secp256k1_musig_partial_signature_parse( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_partial_signature_parse( const secp256k1_context* ctx, secp256k1_musig_partial_signature* sig, const unsigned char *in32 @@ -343,7 +378,12 @@ SECP256K1_API int secp256k1_musig_partial_signature_parse( * computed (cannot be NULL) * Out: partial_sig: partial signature (cannot be NULL) */ -SECP256K1_API int secp256k1_musig_partial_sign( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_partial_sign( const secp256k1_context* ctx, const secp256k1_musig_session *session, secp256k1_musig_partial_signature *partial_sig @@ -366,7 +406,12 @@ SECP256K1_API int secp256k1_musig_partial_sign( * In: partial_sig: signature to verify (cannot be NULL) * pubkey: public key of the signer who produced the signature (cannot be NULL) */ -SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_verify( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_verify( const secp256k1_context* ctx, const secp256k1_musig_session *session, const secp256k1_musig_session_signer_data *signer, @@ -386,7 +431,12 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_verif * In: partial_sigs: array of partial signatures to combine (cannot be NULL) * n_sigs: number of signatures in the partial_sigs array */ -SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_combine( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_combine( const secp256k1_context* ctx, const secp256k1_musig_session *session, secp256k1_schnorrsig *sig, @@ -406,7 +456,12 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_partial_sig_combi * be NULL) * nonce_is_negated: the `nonce_is_negated` output of `musig_session_combine_nonces` */ -SECP256K1_API int secp256k1_musig_partial_sig_adapt( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + int secp256k1_musig_partial_sig_adapt( const secp256k1_context* ctx, secp256k1_musig_partial_signature *adaptor_sig, const secp256k1_musig_partial_signature *partial_sig, @@ -429,7 +484,12 @@ SECP256K1_API int secp256k1_musig_partial_sig_adapt( * n_partial_sigs: number of elements in partial_sigs array * nonce_is_negated: the `nonce_is_negated` output of `musig_session_combine_nonces` */ -SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_extract_secret_adaptor( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif + SECP256K1_WARN_UNUSED_RESULT int secp256k1_musig_extract_secret_adaptor( const secp256k1_context* ctx, unsigned char *sec_adaptor32, const secp256k1_schnorrsig *sig, diff --git a/src/secp256k1/include/secp256k1_schnorrsig.h b/src/secp256k1/include/secp256k1_schnorrsig.h index 9dea16653..e4d02f34f 100644 --- a/src/secp256k1/include/secp256k1_schnorrsig.h +++ b/src/secp256k1/include/secp256k1_schnorrsig.h @@ -28,7 +28,12 @@ typedef struct { * * See secp256k1_schnorrsig_parse for details about the encoding. */ -SECP256K1_API int secp256k1_schnorrsig_serialize( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif +int secp256k1_schnorrsig_serialize( const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig @@ -50,7 +55,12 @@ SECP256K1_API int secp256k1_schnorrsig_serialize( * encoded numbers are out of range, signature validation with it is * guaranteed to fail for every message and public key. */ -SECP256K1_API int secp256k1_schnorrsig_parse( +#ifdef __cplusplus +extern "C" +#else +SECP256K1_API +#endif +int secp256k1_schnorrsig_parse( const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64 From 141790634d27cc0461329d2261859c54ec3bebfa Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:33:13 -1100 Subject: [PATCH 1047/1145] Syntax --- src/cc/musig.cpp | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index f6a7bf7b7..8696809da 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -123,7 +123,7 @@ struct musig_info secp256k1_pubkey combined_pk; uint8_t *nonce_commitments,**commitment_ptrs; // 32*N_SIGNERS secp256k1_musig_session_signer_data *signer_data; //[N_SIGNERS]; - secp256k1_pubkey *nonce; //[N_SIGNERS]; + secp256k1_pubkey *nonces; //[N_SIGNERS]; secp256k1_musig_partial_signature *partial_sig; //[N_SIGNERS]; int32_t myind,num; uint8_t msg[32],pkhash[32],combpk[33]; @@ -138,7 +138,7 @@ struct musig_info *musig_infocreate(int32_t myind,int32_t num) for (i=0; icommitment_ptrs[i] = &mp->nonce_commitments[i*32]; mp->signer_data = (secp256k1_musig_session_signer_data *)calloc(num,sizeof(*mp->signer_data)); - mp->nonce = (secp256k1_pubkey *)calloc(num,sizeof(*mp->nonce)); + mp->nonces = (secp256k1_pubkey *)calloc(num,sizeof(*mp->nonces)); mp->partial_sig = (secp256k1_musig_partial_signature *)calloc(num,sizeof(*mp->partial_sig)); return(mp); } @@ -150,10 +150,10 @@ void musig_infofree(struct musig_info *mp) GetRandBytes((uint8_t *)mp->partial_sig,mp->num*sizeof(*mp->partial_sig)); free(mp->partial_sig); } - if ( mp->nonce != 0 ) + if ( mp->nonces != 0 ) { - GetRandBytes((uint8_t *)mp->nonce,mp->num*sizeof(*mp->nonce)); - free(mp->nonce); + GetRandBytes((uint8_t *)mp->nonces,mp->num*sizeof(*mp->nonces)); + free(mp->nonces); } if ( mp->signer_data != 0 ) { @@ -388,14 +388,14 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t n,ind; uint8_t pkhash[32]; CPubKey pk; char str[67]; + UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSING->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); @@ -424,6 +424,7 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) for (i=0; i<33; i++) sprintf(&str[i<<1],"%02x",((uint8_t *)pk.begin())[i]); str[66] = 0; + result.push_back(Pair("myind",MUSIG->myind)); result.push_back(Pair("nonce",str)); result.push_back(Pair("result","success")); } else return(cclib_error(result,"error serializing nonce (pubkey)")); @@ -447,7 +448,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSING->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); @@ -498,6 +499,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) for (i=0; i<32; i++) sprintf(&str[i<<1],"%02x",psig[i]); str[64] = 0; + result.push_back(Pair("myind",MUSIG->myind)); result.push_back(Pair("partialsig",str)); result.push_back(Pair("result","success")); return(result); @@ -510,14 +512,14 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t ind,n; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; + UniValue result(UniValue::VOBJ); int32_t i,ind,n; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSING->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); From 3d99ab8a66a0de574abfd066ff6980390734f860 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:39:37 -1100 Subject: [PATCH 1048/1145] Fix --- src/cc/musig.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 8696809da..2d4002059 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -388,6 +388,7 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; + size_t clen = CPubKey::PUBLIC_KEY_SIZE; UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); @@ -399,7 +400,7 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash32(&MUSIG->commitment[ind*32],jitem(params,2)) < 0 ) + else if ( musig_parsehash32(&MUSIG->nonce_commitments[ind*32],jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing commitment")); /** Gets the signer's public nonce given a list of all signers' data with commitments * @@ -417,7 +418,7 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * number of signers participating in the MuSig. */ result.push_back(Pair("added_index",ind)); - if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->nonce_commitments,MUSIG->num) > 0 ) + if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->commitment_ptrs,MUSIG->num) > 0 ) { if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG->nonces[MUSIG->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) { @@ -452,7 +453,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsepubkey(ctx,&MUSIG->nonces[ind],jitem(params,2)) < 0 ) + else if ( musig_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing nonce")); result.push_back(Pair("added_index",ind)); /** Checks a signer's public nonce against a commitment to said nonce, and update @@ -523,7 +524,9 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsepartial(ctx,&MUSIG->partial_sig[ind],jitem(params,2)) < 0 ) + else if ( musig_parsehash32(ctx,psig,jitem(params,2)) < 0 ) + return(cclib_error(result,"error parsing psig")); + else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); result.push_back(Pair("added_index",ind)); if (secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) From b17065ce1762782a13ab6205c06bd20df5a644ba Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:41:10 -1100 Subject: [PATCH 1049/1145] extern "C" --- src/cc/musig.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 2d4002059..03eb01e3e 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -113,6 +113,7 @@ extern "C" int secp256k1_schnorrsig_verify(const secp256k1_context* ctx, const s extern "C" int secp256k1_schnorrsig_parse(const secp256k1_context* ctx, secp256k1_schnorrsig* sig, const unsigned char *in64); extern "C" int secp256k1_musig_pubkey_combine(const secp256k1_context* ctx, secp256k1_scratch_space *scratch, secp256k1_pubkey *combined_pk, unsigned char *pk_hash32, const secp256k1_pubkey *pubkeys, size_t n_pubkeys); extern "C" int secp256k1_musig_session_initialize(const secp256k1_context* ctx, secp256k1_musig_session *session, secp256k1_musig_session_signer_data *signers, unsigned char *nonce_commitment32, const unsigned char *session_id32, const unsigned char *msg32, const secp256k1_pubkey *combined_pk, const unsigned char *pk_hash32, size_t n_signers, size_t my_index, const unsigned char *seckey); +extern "C" int secp256k1_schnorrsig_serialize(const secp256k1_context* ctx, unsigned char *out64, const secp256k1_schnorrsig* sig); #define MUSIG_PREVN 0 // for now, just use vout0 for the musig output #define MUSIG_TXFEE 10000 @@ -524,12 +525,12 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash32(ctx,psig,jitem(params,2)) < 0 ) + else if ( musig_parsehash32(psig,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing psig")); else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); result.push_back(Pair("added_index",ind)); - if (secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) + if ( secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) { if ( secp256k1_schnorrsig_serialize(ctx,out64,&sig) > 0 ) { From c07c6724b2d05dac81104b69a53f8fc23c49b845 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:52:20 -1100 Subject: [PATCH 1050/1145] Rpc examples to make a combined signature "combinedsig": "bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf4 2d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320" --- src/cc/musig.cpp | 67 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 62 insertions(+), 5 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 03eb01e3e..4f08dd4cf 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -66,7 +66,7 @@ the "msg" is what needs to be signed to create a valid spend { "myind": 0, "numsigners": 2, - "commitment": "053a97ba56b1b8adf174a0a28dc16b1bb4e91a33ca0b52a579ce9ba4af299973", + "commitment": "89af8f6db69fc3d4b95480a914dceba9933039e9823151a82677c3ca4e961fcc", "result": "success" } @@ -75,15 +75,73 @@ the "msg" is what needs to be signed to create a valid spend { "myind": 1, "numsigners": 2, - "commitment": "8c8dc6717aaa1994d4a51d1094c0c5cbfaf033c11642dbeeab32a32de4cfbc86", + "commitment": "a43da5ef8322abb43b9fddadef7b6479baf7853e860f915e01521e3060e5342b", "result": "success" } now we need to get the commitment from each node to the other one. the session already put the commitment for each node into the global struct. Keep in mind there is a single global struct with session unique to each cclib session call. that means no restarting any deamon in the middle of the process on any of the nodes and only call cclib session a single time. this is an artificial restriction just to simplify the initial implementation of musig - ./c cclib commitment 18 \"[1,%228c8dc6717aaa1994d4a51d1094c0c5cbfaf033c11642dbeeab32a32de4cfbc86%22]\" - ./c cclib commitment 18 \"[0,%22053a97ba56b1b8adf174a0a28dc16b1bb4e91a33ca0b52a579ce9ba4af299973%22]\" + ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%22a43da5ef8322abb43b9fddadef7b6479baf7853e860f915e01521e3060e5342b%22]\" + { + "added_index": 1, + "myind": 0, + "nonce": "03bf28874f5e5dccf55170406d58ded84ac6ca713011d718c6048400d700cb879a", + "result": "success" + } + + ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%2289af8f6db69fc3d4b95480a914dceba9933039e9823151a82677c3ca4e961fcc%22]\" + { + "added_index": 0, + "myind": 1, + "nonce": "039ae1f542e8f0f6d03d734dc2295651973e1b7fa99508e2f36dad5d21f09889f6", + "result": "success" + } + + Now exchange the revealed nonces to each node: + + ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%22039ae1f542e8f0f6d03d734dc2295651973e1b7fa99508e2f36dad5d21f09889f6%22]\" + { + "added_index": 1, + "myind": 0, + "partialsig": "5da4c1ec828cd1563bc6554aa74c90c29fcd38b2aea26f7fa92e0d007aa9463f", + "result": "success" + } + + ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%2203bf28874f5e5dccf55170406d58ded84ac6ca713011d718c6048400d700cb879a%22]\" + { + "added_index": 0, + "myind": 1, + "partialsig": "7e55fd564fe26b1054208bc47786d6e1ce30a2fd0045bbbf0e6915adcf4b0ce1", + "result": "success" + } + + Almost there! final step is to exchange the partial sigs between signers + ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%227e55fd564fe26b1054208bc47786d6e1ce30a2fd0045bbbf0e6915adcf4b0ce1%22]\" + { + "added_index": 1, + "result": "success", + "combinedsig": "bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf42d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320" + } + + ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%225da4c1ec828cd1563bc6554aa74c90c29fcd38b2aea26f7fa92e0d007aa9463f%22]\" + + { + "added_index": 0, + "result": "success", + "combinedsig": "bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf42d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320" + } + + Notice both nodes generated the same combined signature! + + Now for a sanity test, we can use the verify call to make sure this sig will work with the msg needed for the spend: + + xxxx + + + and finally the spend: + + */ @@ -497,7 +555,6 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) { - result.push_back(Pair("myind",ind)); for (i=0; i<32; i++) sprintf(&str[i<<1],"%02x",psig[i]); str[64] = 0; From 925eaa285162afaeed9396aced6413ed38c61a62 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:57:30 -1100 Subject: [PATCH 1051/1145] Test --- src/cc/musig.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 4f08dd4cf..6b2e7abca 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -139,9 +139,9 @@ the "msg" is what needs to be signed to create a valid spend xxxx - and finally the spend: - + and finally the spend: sendtxid, scriptPubKey, musig +./c cclib spend 18 \"[%22cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22,%22bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf42d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320%22]\" */ @@ -696,6 +696,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) prevhash = juint256(jitem(params,0)); scriptstr = jstr(jitem(params,1),0); musigstr = jstr(jitem(params,2),0); + printf("script.(%s) musig.(%s) %d\n",scriptstr,musigstr,(int32_t)strlen(musigstr)); if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 128 ) { if ( txfee == 0 ) @@ -723,7 +724,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } else return(cclib_error(result,"couldnt decode send opret")); } else return(cclib_error(result,"couldnt find vin0")); } else return(cclib_error(result,"script or musig is not hex")); - } else return(cclib_error(result,"need to have exactly 3 params prevhash, scriptPubKey, musig")); + } else return(cclib_error(result,"need to have exactly 3 params sendtxid, scriptPubKey, musig")); } else return(cclib_error(result,"params parse error")); } From 748ab667e2d36b71c29d943b855d7dbbc07abd86 Mon Sep 17 00:00:00 2001 From: jl777 Date: Thu, 21 Feb 2019 23:59:42 -1100 Subject: [PATCH 1052/1145] Test --- src/cc/musig.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 6b2e7abca..172958fba 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -696,7 +696,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) prevhash = juint256(jitem(params,0)); scriptstr = jstr(jitem(params,1),0); musigstr = jstr(jitem(params,2),0); - printf("script.(%s) musig.(%s) %d\n",scriptstr,musigstr,(int32_t)strlen(musigstr)); + printf("script.(%s) %d musig.(%s) %d\n",scriptstr,is_hexstr(scriptstr,0),musigstr,is_hexstr(musigstr,0)); if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 128 ) { if ( txfee == 0 ) From 3bea6f84e4c353df73316e8079e516a903461516 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:00:55 -1100 Subject: [PATCH 1053/1145] Fix --- src/cc/musig.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 172958fba..a690e4d01 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -696,8 +696,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) prevhash = juint256(jitem(params,0)); scriptstr = jstr(jitem(params,1),0); musigstr = jstr(jitem(params,2),0); - printf("script.(%s) %d musig.(%s) %d\n",scriptstr,is_hexstr(scriptstr,0),musigstr,is_hexstr(musigstr,0)); - if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) != 128 ) + if ( is_hexstr(scriptstr,0) != 0 && is_hexstr(musigstr,0) == 128 ) { if ( txfee == 0 ) txfee = MUSIG_TXFEE; From 33811cce5f78616998d2b7fe1a75714d028fae23 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:16:26 -1100 Subject: [PATCH 1054/1145] +print --- src/cc/musig.cpp | 64 ++++++++++++++++++++++++++++++------------------ 1 file changed, 40 insertions(+), 24 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index a690e4d01..be4ff278e 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -26,8 +26,8 @@ /* second, send 0.777 coins to the combined_pk ./c cclib send 18 \"[%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,0.777]\" { - "hex": "0400008085202f8901bf7afcbbab7a5e1ba20c8010325e199305afa7d15b4bc86a589a512201d39924000000004847304402203e0cff8aaa831dd990afd979bbc0a648316f77407cb5e02780d18e0670f5172a0220283d5c52d0406b10c508cc2b19dd6dbe2420e7c5cf431a1d41072d0eec28edb901ffffffff03b0c2a10400000000302ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cca91e223700000000232102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac0000000000000000266a24127821032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b00000000900000000000000000000000000000", - "txid": "cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be", + "hex": "0400008085202f8908018bbc4a0acf0f896680b84cc1000ec5530042fa3cf7471ab5c11cde56f6d0e60000000048473044022041a900fa57e54f939b797d09f0cee81ab9a79d978cd473ef3fc9f09c7678ad6b02206386bd15ee7ee8224a984fdd1d2a094738d082aec06028a5846d7bc61ddf16ca01ffffffff0b969f0e1ea787f0cc4e81d128353bd1cb670ab89bd1db4b47fbb7e872cd39fb00000000494830450221008c5de4b196e57b0dd94aa415950adf274e3e6859b82cf218729af84c1f15e76c022024aeab7eda63e6a652ef488bf26a8dc4ef8d2d4aa5746726085bfe5f169a5db701ffffffff0b36b70b43457fab377f28fb22da5a3e9d8186a37daae18cf0f710a221ab26250000000048473044022004ec20ae7490e7adabf9a3f78e4a58df84a3245485bfdd40f421cafe61d19c340220456d2b6f3c6e88632027c02606a0af1c21208d05f2de0826fbf4dfe7391ec83901ffffffff0aaff3cfe4ca22b97b6179a6f7cfac91945e5440e9438b89d1ec09500167176a0000000048473044022074dcad30c8ab9ed79a3ac69169611fc9e5f4b76a561b183461d968249316997f022063b25decaa285f494d277b9c8c2bcf6445b7929a304542e89c0645828d30a1a901ffffffff090e1bb92e9bf404a0d6455701b21af3dbf6765e61a1dc28b7c0f608ec4f12da000000004847304402202f9182c532c66138a6bdfcbb85a06cf1bf1532f2bf8f63170ef20843e4a81d0202207612a4353eb9606e84621c444ec7db1b683ff29c56127bda2d5e9c0eb13dbbc001ffffffff08a57005c7a40a923b1a510820b07f7318d760fe2a233b077d918cce357ad3af00000000484730440220643d60c68634fb2e0f6656389fc70c9f84c7086fc6e35b0fa26297e844f6c5fc02201d79669e073efe738d47de0130fdcba875e284e18fd478c0e6834d46632d8b8101ffffffff068cfd0ea6c0f5d401c67ec38f92425a9e59b0d5ade55bb2971ea955675a17bd00000000484730440220747139724248da4bcc1e5e3828e0ea811756e1fad0ebc40aeb006fd8079d46e402200d8f1c229c79494b5617e4373a3e083966dcd74571323f9d334be901d53871fa01ffffffff0200382fb6984b6128bb75115346242809c6555274e0cacef822825a2b4d231700000000484730440220454fcac398f6913fb4d8ed330f110f9cf62eec6c8cdb67d5df1effd2cf8222d5022017f6323630669777573e342e870c88727a917cc06c33611ebbd9d1fccc1dcd3701ffffffff03b0c2a10400000000302ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cc40ca220000000000232102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac0000000000000000266a24127821032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b00000000460100000000000000000000000000", + "txid": "2c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68", "result": "success" } @@ -46,92 +46,94 @@ } change script: 2102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac - sendtxid: cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be + sendtxid: 2c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68 broadcast sendtxid and wait for it to be confirmed. then get the msg we need to sign: - ./c cclib calcmsg 18 \"[%22cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22]\" + ./c cclib calcmsg 18 \"[%222c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22]\" { "result": "success", - "msg": "63b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485" + "msg": "caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0" } + the "msg" is what needs to be signed to create a valid spend now on each signing node, a session needs to be created: 5 args: ind, numsigners, combined_pk, pkhash, message to be signed on node with pubkey: 02aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848 - ./c cclib session 18 \"[0,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%2263b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485%22]\" + ./c cclib session 18 \"[0,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%22caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0%22]\" { "myind": 0, "numsigners": 2, - "commitment": "89af8f6db69fc3d4b95480a914dceba9933039e9823151a82677c3ca4e961fcc", + "commitment": "e82228c10d0e100477630349150dea744d3b2790dcd347511a1a98199840cda4", "result": "success" } on node with pubkey: 039433dc3749aece1bd568f374a45da3b0bc6856990d7da3cd175399577940a775 - ./c cclib session 18 \"[1,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%2263b799913d4c9487f321b32d6ae8614f653f38e0b50d4df4bc1d36339ea18485%22]\" + ./c cclib session 18 \"[1,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%22caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0%22]\" { "myind": 1, "numsigners": 2, - "commitment": "a43da5ef8322abb43b9fddadef7b6479baf7853e860f915e01521e3060e5342b", + "commitment": "6e426e850ddc45e7742cfb6321781c00ee69a995ab12fa1f9ded7fe43658babf", "result": "success" } now we need to get the commitment from each node to the other one. the session already put the commitment for each node into the global struct. Keep in mind there is a single global struct with session unique to each cclib session call. that means no restarting any deamon in the middle of the process on any of the nodes and only call cclib session a single time. this is an artificial restriction just to simplify the initial implementation of musig - ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%22a43da5ef8322abb43b9fddadef7b6479baf7853e860f915e01521e3060e5342b%22]\" + ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%226e426e850ddc45e7742cfb6321781c00ee69a995ab12fa1f9ded7fe43658babf%22]\" { "added_index": 1, "myind": 0, - "nonce": "03bf28874f5e5dccf55170406d58ded84ac6ca713011d718c6048400d700cb879a", + "nonce": "0261671b0a6de416938cf035c98f8af37c6ca88bbbd1bcce693d709d4919b010e1", "result": "success" } - ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%2289af8f6db69fc3d4b95480a914dceba9933039e9823151a82677c3ca4e961fcc%22]\" + ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%22e82228c10d0e100477630349150dea744d3b2790dcd347511a1a98199840cda4%22]\" { "added_index": 0, "myind": 1, - "nonce": "039ae1f542e8f0f6d03d734dc2295651973e1b7fa99508e2f36dad5d21f09889f6", + "nonce": "02570f62a625ceb19a754a053152b162810c3e403df63f3d443e85bdacc74bfdfe", "result": "success" } Now exchange the revealed nonces to each node: - ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%22039ae1f542e8f0f6d03d734dc2295651973e1b7fa99508e2f36dad5d21f09889f6%22]\" + ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%2202570f62a625ceb19a754a053152b162810c3e403df63f3d443e85bdacc74bfdfe%22]\" { "added_index": 1, "myind": 0, - "partialsig": "5da4c1ec828cd1563bc6554aa74c90c29fcd38b2aea26f7fa92e0d007aa9463f", + "partialsig": "3f21885e6d2d020e1473435ccd148a61cdcb1d1105867fed45913185dc0acf59", "result": "success" } - ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%2203bf28874f5e5dccf55170406d58ded84ac6ca713011d718c6048400d700cb879a%22]\" + ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%220261671b0a6de416938cf035c98f8af37c6ca88bbbd1bcce693d709d4919b010e1%22]\" { "added_index": 0, + "myind": 0, "myind": 1, - "partialsig": "7e55fd564fe26b1054208bc47786d6e1ce30a2fd0045bbbf0e6915adcf4b0ce1", + "partialsig": "af7f28455fb2e988d81068cd9d800879cd334036a8300118dc307b777a38c1ed", "result": "success" } Almost there! final step is to exchange the partial sigs between signers - ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%227e55fd564fe26b1054208bc47786d6e1ce30a2fd0045bbbf0e6915adcf4b0ce1%22]\" + ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%22af7f28455fb2e988d81068cd9d800879cd334036a8300118dc307b777a38c1ed%22]\" { "added_index": 1, "result": "success", - "combinedsig": "bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf42d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320" + "combinedsig": "5e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146" } + - ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%225da4c1ec828cd1563bc6554aa74c90c29fcd38b2aea26f7fa92e0d007aa9463f%22]\" + ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%223f21885e6d2d020e1473435ccd148a61cdcb1d1105867fed45913185dc0acf59%22]\" { "added_index": 0, "result": "success", - "combinedsig": "bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf42d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320" + "combinedsig": "5e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146" } - Notice both nodes generated the same combined signature! Now for a sanity test, we can use the verify call to make sure this sig will work with the msg needed for the spend: @@ -141,7 +143,7 @@ the "msg" is what needs to be signed to create a valid spend and finally the spend: sendtxid, scriptPubKey, musig -./c cclib spend 18 \"[%22cb5309ed249da95e2b5696eb763a8736e2fff1d14922ada737b931494ca3d2be%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22,%22bc0062cd3233433e098fbf4f3c333946779c3dccfaefc423243e3f90edfdf9a6dbfabf42d26f3c668fe6e10f1ed367a46dfddbafaee82b3eb79722ae49f45320%22]\" +./c cclib spend 18 \"[%222c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22,%225e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146%22]\" */ @@ -686,7 +688,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t n,numvouts; CTxOut vout; secp256k1_schnorrsig musig; + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,pk; secp256k1_pubkey combined_pk; char *scriptstr,*musigstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock; int32_t i,n,numvouts; char str[129]; CTxOut vout; secp256k1_schnorrsig musig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) @@ -713,6 +715,20 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) secp256k1_ec_pubkey_parse(ctx,&combined_pk,pk.begin(),33) > 0 ) { musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); + { + for (i=0; i<32; i++) + sprintf(&str[i*2],"%02x",msg[i]); + str[64] = 0; + result.push_back(Pair("msg",str)); + for (i=0; i<33; i++) + sprintf(&str[i*2],"%02x",((uint8_t *)pk.begin)[i]); + str[66] = 0; + result.push_back(Pair("combined_pk",str)); + for (i=0; i<64; i++) + sprintf(&str[i*2],"%02x",musig64[i]); + str[128] = 0; + result.push_back(Pair("combinedsig",str)); + } if ( !secp256k1_schnorrsig_verify((const secp256k1_context *)ctx,&musig,(const uint8_t *)msg,(const secp256k1_pubkey *)&combined_pk) ) return(cclib_error(result,"musig didnt validate")); mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); From 8b8339b5b941963c6ea6331cf57af5c5edc2facc Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:17:05 -1100 Subject: [PATCH 1055/1145] () --- src/cc/musig.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index be4ff278e..88bf62449 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -721,7 +721,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) str[64] = 0; result.push_back(Pair("msg",str)); for (i=0; i<33; i++) - sprintf(&str[i*2],"%02x",((uint8_t *)pk.begin)[i]); + sprintf(&str[i*2],"%02x",((uint8_t *)pk.begin())[i]); str[66] = 0; result.push_back(Pair("combined_pk",str)); for (i=0; i<64; i++) From 6eaac8547a3ddb506e70896e3251daf07524395c Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:23:02 -1100 Subject: [PATCH 1056/1145] Skip test --- src/cc/musig.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 88bf62449..63d7e5291 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -730,7 +730,9 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("combinedsig",str)); } if ( !secp256k1_schnorrsig_verify((const secp256k1_context *)ctx,&musig,(const uint8_t *)msg,(const secp256k1_pubkey *)&combined_pk) ) - return(cclib_error(result,"musig didnt validate")); + { + //return(cclib_error(result,"musig didnt validate")); + } mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); mtx.vout.push_back(vout); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,musig_spendopret('y',pk,musig64)); From baef592f94e608d939f4bf627d1ae34e785f1187 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:26:39 -1100 Subject: [PATCH 1057/1145] Fix script parsing --- src/cc/musig.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 63d7e5291..28795d95c 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -704,7 +704,9 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) txfee = MUSIG_TXFEE; mypk = pubkey2pk(Mypubkey()); std::vector musig64(ParseHex(musigstr)); - CScript scriptPubKey(ParseHex(scriptstr)); + CScript scriptPubKey; + scriptPubKey.resize(strlen(scriptstr)/2); + decode_hex((uint8_t *)scriptPubKey.data(),strlen(scriptstr)/2,scriptstr); if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { vout.nValue = vintx.vout[0].nValue - txfee; From 3de50a250b2d1ad2321d67c2336dfe061fb6d2da Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:29:48 -1100 Subject: [PATCH 1058/1145] Test --- src/cc/musig.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 28795d95c..fdb24f7a0 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -706,7 +706,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) std::vector musig64(ParseHex(musigstr)); CScript scriptPubKey; scriptPubKey.resize(strlen(scriptstr)/2); - decode_hex((uint8_t *)scriptPubKey.data(),strlen(scriptstr)/2,scriptstr); + decode_hex(&scriptPubKey[0],strlen(scriptstr)/2,scriptstr); if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { vout.nValue = vintx.vout[0].nValue - txfee; From a687d695af02abc60505583027971cfc2373c446 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:41:51 -1100 Subject: [PATCH 1059/1145] Verify roc --- src/cc/musig.cpp | 44 +++++++++++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index fdb24f7a0..9eaec4404 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -620,25 +620,35 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t n; + UniValue result(UniValue::VOBJ); int32_t i,n; uint8_t msg[32],musig64[64]; secp256k1_pubkey combined_pk; secp256k1_schnorrsig musig; char str[129]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) != 3 ) { - // can code this out of order - } - result.push_back(Pair("result","success")); - /** Verify a Schnorr signature. - * - * Returns: 1: correct signature - * 0: incorrect or unparseable signature - * Args: ctx: a secp256k1 context object, initialized for verification. - * In: sig: the signature being verified (cannot be NULL) - * msg32: the 32-byte message hash being verified (cannot be NULL) - * pubkey: pointer to a public key to verify with (cannot be NULL) - */ - // if (!secp256k1_schnorrsig_verify(ctx, &sig, msg, &combined_pk)) { - return(result); + if ( musig_parsehash32(msg,jitem(params,0)) < 0 ) + return(cclib_error(result,"error parsing pkhash")); + else if ( musig_parsepubkey(ctx,combined_pk,jitem(params,1)) < 0 ) + return(cclib_error(result,"error parsing combined_pk")); + else if ( musig_parsehash64(musig64,jitem(params,2)) < 0 ) + return(cclib_error(result,"error parsing musig64")); + for (i=0; i<32; i++) + sprintf(&str[i*2],"%02x",msg[i]); + str[64] = 0; + result.push_back(Pair("msg",str)); + result.push_back(Pair("combined_pk",jstr(jitem(params,1),0))); + for (i=0; i<64; i++) + sprintf(&str[i*2],"%02x",musig64[i]); + str[128] = 0; + result.push_back(Pair("combinedsig",str)); + if ( secp256k1_schnorrsig_parse(ctx,&musig,&musig64[0]) > 0 ) + { + if ( secp256k1_schnorrsig_verify(ctx,&musig,msg,&combined_pk) > 0 ) + { + result.push_back(Pair("result","success")); + return(result); + } else return(cclib_error(result,"musig didnt verify")); + } else return(cclib_error(result,"couldnt parse musig64")); + } else return(cclib_error(result,"wrong number of params, need 3: msg, combined_pk, combinedsig")); } // helpers for rpc calls that generate/validate onchain tx @@ -733,7 +743,7 @@ UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } if ( !secp256k1_schnorrsig_verify((const secp256k1_context *)ctx,&musig,(const uint8_t *)msg,(const secp256k1_pubkey *)&combined_pk) ) { - //return(cclib_error(result,"musig didnt validate")); + return(cclib_error(result,"musig didnt validate")); } mtx.vin.push_back(CTxIn(prevhash,MUSIG_PREVN)); mtx.vout.push_back(vout); From 317fa937b3ca5010daa59cfdb58725c7bc2b7d45 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:43:44 -1100 Subject: [PATCH 1060/1145] parsehash --- src/cc/musig.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 9eaec4404..c5cf5fc4e 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -331,12 +331,12 @@ int32_t musig_parsepubkey(secp256k1_context *ctx,secp256k1_pubkey &spk,cJSON *it } else return(-1); } -int32_t musig_parsehash32(uint8_t *hash32,cJSON *item) +int32_t musig_parsehash(uint8_t *hash32,cJSON *item,int32_t len) { char *hexstr; - if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 64 ) + if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == len*2 ) { - decode_hex(hash32,32,hexstr); + decode_hex(hash32,len,hexstr); return(0); } else return(-1); } @@ -394,9 +394,9 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) MUSIG = musig_infocreate(myind,num); if ( musig_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing combined_pubkey")); - else if ( musig_parsehash32(MUSIG->pkhash,jitem(params,3)) < 0 ) + else if ( musig_parsehash(MUSIG->pkhash,jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( musig_parsehash32(MUSIG->msg,jitem(params,4)) < 0 ) + else if ( musig_parsehash(MUSIG->msg,jitem(params,4),32) < 0 ) return(cclib_error(result,"error parsing msg")); Myprivkey(privkey); GetRandBytes(session,32); @@ -455,13 +455,13 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) + if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash32(&MUSIG->nonce_commitments[ind*32],jitem(params,2)) < 0 ) + else if ( musig_parsehash(&MUSIG->nonce_commitments[ind*32],jitem(params,2),32) < 0 ) return(cclib_error(result,"error parsing commitment")); /** Gets the signer's public nonce given a list of all signers' data with commitments * @@ -508,7 +508,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) + if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); @@ -578,13 +578,13 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash32(pkhash,jitem(params,0)) < 0 ) + if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash32(psig,jitem(params,2)) < 0 ) + else if ( musig_parsehash(psig,jitem(params,2),32) < 0 ) return(cclib_error(result,"error parsing psig")); else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); @@ -625,11 +625,11 @@ UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) != 3 ) { - if ( musig_parsehash32(msg,jitem(params,0)) < 0 ) + if ( musig_parsehash(msg,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( musig_parsepubkey(ctx,combined_pk,jitem(params,1)) < 0 ) return(cclib_error(result,"error parsing combined_pk")); - else if ( musig_parsehash64(musig64,jitem(params,2)) < 0 ) + else if ( musig_parsehash(musig64,jitem(params,2),64) < 0 ) return(cclib_error(result,"error parsing musig64")); for (i=0; i<32; i++) sprintf(&str[i*2],"%02x",msg[i]); From 6704dd969965d0b938ad2dceab6714a90daca687 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:52:37 -1100 Subject: [PATCH 1061/1145] Fix --- src/cc/musig.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index c5cf5fc4e..8e37a2add 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -138,7 +138,7 @@ the "msg" is what needs to be signed to create a valid spend Now for a sanity test, we can use the verify call to make sure this sig will work with the msg needed for the spend: - xxxx + ./c cclib verify 18 \"[%22caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0%22,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146%22]\" and finally the spend: sendtxid, scriptPubKey, musig @@ -623,7 +623,7 @@ UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue result(UniValue::VOBJ); int32_t i,n; uint8_t msg[32],musig64[64]; secp256k1_pubkey combined_pk; secp256k1_schnorrsig musig; char str[129]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) != 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { if ( musig_parsehash(msg,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); From 3caa4fb350c74d5af61b02770a523272ddc8324d Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:59:15 -1100 Subject: [PATCH 1062/1145] Test check.c --- src/cc/cclib.cpp | 32 +---------------------- src/secp256k1/src/modules/musig/example.c | 6 ++--- 2 files changed, 4 insertions(+), 34 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index ec74877b6..b070ded78 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -580,37 +580,7 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" - -/* -#include "../secp256k1/src/util.h" -#include "../secp256k1/src/num_impl.h" -#include "../secp256k1/src/field_impl.h" -#include "../secp256k1/src/scalar_impl.h" -#include "../secp256k1/src/group_impl.h" -#include "../secp256k1/src/scratch_impl.h" -#include "../secp256k1/src/ecmult_impl.h" -#include "../secp256k1/src/ecmult_const_impl.h" -#include "../secp256k1/src/ecmult_gen_impl.h" -#include "../secp256k1/src/ecdsa_impl.h" -#include "../secp256k1/src/eckey_impl.h" -#include "../secp256k1/src/hash_impl.h" - - - -typedef int (secp256k1_ecmult_multi_callback)(secp256k1_scalar *sc, secp256k1_ge *pt, size_t idx, void *data); -extern "C" void secp256k1_pubkey_save(secp256k1_pubkey* pubkey, secp256k1_ge* ge); -extern "C" int secp256k1_nonce_function_bipschnorr(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter); -extern "C" int secp256k1_pubkey_load(const secp256k1_context* ctx, secp256k1_ge* ge, const secp256k1_pubkey* pubkey); -extern "C" void secp256k1_scalar_chacha20(secp256k1_scalar *r1, secp256k1_scalar *r2, const unsigned char *seed, uint64_t idx); - -#define ARG_CHECK(cond) do { \ -if (EXPECT(!(cond), 0)) { \ -secp256k1_callback_call(&ctx->illegal_callback, #cond); \ -return 0; \ -} \ -} while(0)*/ - -//#include "../secp256k1/src/secp256k1.c" #include "musig.cpp" +#include "../secp256k1/modules/musig/check.c" #endif diff --git a/src/secp256k1/src/modules/musig/example.c b/src/secp256k1/src/modules/musig/example.c index ceae18686..94c9fdef2 100644 --- a/src/secp256k1/src/modules/musig/example.c +++ b/src/secp256k1/src/modules/musig/example.c @@ -9,11 +9,11 @@ * Additionally, see the documentation in include/secp256k1_musig.h. */ -#include +/*#include #include #include #include -#include +#include */ /* Number of public keys involved in creating the aggregate signature */ #define N_SIGNERS 3 @@ -122,7 +122,7 @@ int sign(const secp256k1_context* ctx, unsigned char seckeys[][32], const secp25 return secp256k1_musig_partial_sig_combine(ctx, &musig_session[0], sig, partial_sig, N_SIGNERS); } - int main(void) { + int testmain(void) { secp256k1_context* ctx; int i; unsigned char seckeys[N_SIGNERS][32]; From fe60cfbf6eb486ac08a5b3906854ab1c82d1d1c3 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 00:59:44 -1100 Subject: [PATCH 1063/1145] Src --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index b070ded78..9cd947efc 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -581,6 +581,6 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" #include "musig.cpp" -#include "../secp256k1/modules/musig/check.c" +#include "../secp256k1/src/modules/musig/check.c" #endif From 1a34721c44c35815f90b739c30eb4d28ef3e6783 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 01:01:00 -1100 Subject: [PATCH 1064/1145] example.c --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 9cd947efc..c770917ea 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -581,6 +581,6 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" #include "musig.cpp" -#include "../secp256k1/src/modules/musig/check.c" +#include "../secp256k1/src/modules/musig/example.c" #endif From 93acda143f271f0e08b07393f958dc194bb352ba Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 01:03:17 -1100 Subject: [PATCH 1065/1145] fprintf(stderr, --- src/cc/musig.cpp | 2 ++ src/secp256k1/src/modules/musig/example.c | 26 +++++++++++------------ 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 8e37a2add..446f9333d 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -617,10 +617,12 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, partialsig")); } +int testmain(void); UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; UniValue result(UniValue::VOBJ); int32_t i,n; uint8_t msg[32],musig64[64]; secp256k1_pubkey combined_pk; secp256k1_schnorrsig musig; char str[129]; + testmain(); if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) diff --git a/src/secp256k1/src/modules/musig/example.c b/src/secp256k1/src/modules/musig/example.c index 94c9fdef2..70d183e7d 100644 --- a/src/secp256k1/src/modules/musig/example.c +++ b/src/secp256k1/src/modules/musig/example.c @@ -128,37 +128,37 @@ int sign(const secp256k1_context* ctx, unsigned char seckeys[][32], const secp25 unsigned char seckeys[N_SIGNERS][32]; secp256k1_pubkey pubkeys[N_SIGNERS]; secp256k1_pubkey combined_pk; - unsigned char msg[32] = "this_could_be_the_hash_of_a_msg!"; + unsigned char msg[32] = "this_could_be_the_hash_of_a_msg"; secp256k1_schnorrsig sig; /* Create a context for signing and verification */ ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - printf("Creating key pairs......"); + fprintf(stderr,"Creating key pairs......"); for (i = 0; i < N_SIGNERS; i++) { if (!create_key(ctx, seckeys[i], &pubkeys[i])) { - printf("FAILED\n"); + fprintf(stderr,"FAILED\n"); return 1; } } - printf("ok\n"); - printf("Combining public keys..."); + fprintf(stderr,"ok\n"); + fprintf(stderr,"Combining public keys..."); if (!secp256k1_musig_pubkey_combine(ctx, NULL, &combined_pk, NULL, pubkeys, N_SIGNERS)) { - printf("FAILED\n"); + fprintf(stderr,"FAILED\n"); return 1; } - printf("ok\n"); - printf("Signing message........."); + fprintf(stderr,"ok\n"); + fprintf(stderr,"Signing message........."); if (!sign(ctx, seckeys, pubkeys, msg, &sig)) { - printf("FAILED\n"); + fprintf(stderr,"FAILED\n"); return 1; } - printf("ok\n"); - printf("Verifying signature....."); + fprintf(stderr,"ok\n"); + fprintf(stderr,"Verifying signature....."); if (!secp256k1_schnorrsig_verify(ctx, &sig, msg, &combined_pk)) { - printf("FAILED\n"); + fprintf(stderr,"FAILED\n"); return 1; } - printf("ok\n"); + fprintf(stderr,"ok\n"); secp256k1_context_destroy(ctx); return 0; } From a0b7227e007bcfa96ad6e99c54a85875652eed63 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 09:29:09 -1100 Subject: [PATCH 1066/1145] Dont create rogue files on validation --- src/cc/rogue_rpc.cpp | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 57ce1e14b..213e382a1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -833,7 +833,7 @@ UniValue rogue_keystrokes(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"couldnt reparse params")); } -char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdata,uint64_t &seed,uint256 &playertxid,struct CCcontract_info *cp,uint256 gametxid,char *rogueaddr) +char *rogue_extractgame(int32_t makefiles,char *str,int32_t *numkeysp,std::vector &newdata,uint64_t &seed,uint256 &playertxid,struct CCcontract_info *cp,uint256 gametxid,char *rogueaddr) { CPubKey roguepk; int32_t i,num,maxplayers,gameheight,batonht,batonvout,numplayers,regslot,numkeys,err; std::string symbol,pname; CTransaction gametx; int64_t buyin,batonvalue; char fname[64],*keystrokes = 0; std::vector playerdata; uint256 batontxid; FILE *fp; uint8_t newplayer[10000]; struct rogue_player P,endP; roguepk = GetUnspendable(cp,0); @@ -854,19 +854,22 @@ char *rogue_extractgame(char *str,int32_t *numkeysp,std::vector &newdat } if ( keystrokes != 0 ) { - sprintf(fname,"rogue.%llu.0",(long long)seed); - if ( (fp= fopen(fname,"wb")) != 0 ) + if ( makefiles != 0 ) { - if ( fwrite(keystrokes,1,numkeys,fp) != numkeys ) - fprintf(stderr,"error writing %s\n",fname); - fclose(fp); - } - sprintf(fname,"rogue.%llu.player",(long long)seed); - if ( (fp= fopen(fname,"wb")) != 0 ) - { - if ( fwrite(&playerdata[0],1,(int32_t)playerdata.size(),fp) != playerdata.size() ) - fprintf(stderr,"error writing %s\n",fname); - fclose(fp); + sprintf(fname,"rogue.%llu.0",(long long)seed); + if ( (fp= fopen(fname,"wb")) != 0 ) + { + if ( fwrite(keystrokes,1,numkeys,fp) != numkeys ) + fprintf(stderr,"error writing %s\n",fname); + fclose(fp); + } + sprintf(fname,"rogue.%llu.player",(long long)seed); + if ( (fp= fopen(fname,"wb")) != 0 ) + { + if ( fwrite(&playerdata[0],1,(int32_t)playerdata.size(),fp) != playerdata.size() ) + fprintf(stderr,"error writing %s\n",fname); + fclose(fp); + } } num = rogue_replay2(newplayer,seed,keystrokes,numkeys,playerdata.size()==0?0:&P,0); newdata.resize(num); @@ -914,7 +917,7 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) GetCCaddress1of2(cp,rogueaddr,roguepk,pk); result.push_back(Pair("rogueaddr",rogueaddr)); str[0] = 0; - if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) + if ( (keystrokes= rogue_extractgame(1,str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) { result.push_back(Pair("status","success")); flag = 1; @@ -1240,7 +1243,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); - if ( (keystrokes= rogue_extractgame(str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) + if ( (keystrokes= rogue_extractgame(0,str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) { free(keystrokes); //fprintf(stderr,"extracted.(%s)\n",str); From fa3b624d512d7476ea3a3927a810c1f426b98b14 Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sat, 23 Feb 2019 15:12:00 +0800 Subject: [PATCH 1067/1145] fix musig and working example added --- src/cc/musig.cpp | 236 ++++++++++++++++++++++++++++------------------- 1 file changed, 139 insertions(+), 97 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 446f9333d..bd3d74a95 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -14,47 +14,67 @@ ******************************************************************************/ /* first make a combined pk: -./c cclib combine 18 \"[%2202aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22,%22039433dc3749aece1bd568f374a45da3b0bc6856990d7da3cd175399577940a775%22]\" -{ - "pkhash": "5be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba", - "combined_pk": "032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b", - "result": "success" -} - the combined_pk and pkhash will be needed for various other rpc calls -*/ -/* second, send 0.777 coins to the combined_pk - ./c cclib send 18 \"[%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,0.777]\" +./komodo-cli -ac_name=MUSIG cclib combine 18 '["02fb6aa0b96cad24d46b5da93eba3864c45ce07a73bba12da530ae841e140fcf28","0255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4"]' +{ + "pkhash": "5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b", + "combined_pk": "03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b", + "result": "success" +} + + the combined_pk and pkhash will be needed for various other rpc calls + + second, send 1 coin to the combined_pk + ./komodo-cli -ac_name=MUSIG cclib send 18 '["03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b",1]' { - "hex": "0400008085202f8908018bbc4a0acf0f896680b84cc1000ec5530042fa3cf7471ab5c11cde56f6d0e60000000048473044022041a900fa57e54f939b797d09f0cee81ab9a79d978cd473ef3fc9f09c7678ad6b02206386bd15ee7ee8224a984fdd1d2a094738d082aec06028a5846d7bc61ddf16ca01ffffffff0b969f0e1ea787f0cc4e81d128353bd1cb670ab89bd1db4b47fbb7e872cd39fb00000000494830450221008c5de4b196e57b0dd94aa415950adf274e3e6859b82cf218729af84c1f15e76c022024aeab7eda63e6a652ef488bf26a8dc4ef8d2d4aa5746726085bfe5f169a5db701ffffffff0b36b70b43457fab377f28fb22da5a3e9d8186a37daae18cf0f710a221ab26250000000048473044022004ec20ae7490e7adabf9a3f78e4a58df84a3245485bfdd40f421cafe61d19c340220456d2b6f3c6e88632027c02606a0af1c21208d05f2de0826fbf4dfe7391ec83901ffffffff0aaff3cfe4ca22b97b6179a6f7cfac91945e5440e9438b89d1ec09500167176a0000000048473044022074dcad30c8ab9ed79a3ac69169611fc9e5f4b76a561b183461d968249316997f022063b25decaa285f494d277b9c8c2bcf6445b7929a304542e89c0645828d30a1a901ffffffff090e1bb92e9bf404a0d6455701b21af3dbf6765e61a1dc28b7c0f608ec4f12da000000004847304402202f9182c532c66138a6bdfcbb85a06cf1bf1532f2bf8f63170ef20843e4a81d0202207612a4353eb9606e84621c444ec7db1b683ff29c56127bda2d5e9c0eb13dbbc001ffffffff08a57005c7a40a923b1a510820b07f7318d760fe2a233b077d918cce357ad3af00000000484730440220643d60c68634fb2e0f6656389fc70c9f84c7086fc6e35b0fa26297e844f6c5fc02201d79669e073efe738d47de0130fdcba875e284e18fd478c0e6834d46632d8b8101ffffffff068cfd0ea6c0f5d401c67ec38f92425a9e59b0d5ade55bb2971ea955675a17bd00000000484730440220747139724248da4bcc1e5e3828e0ea811756e1fad0ebc40aeb006fd8079d46e402200d8f1c229c79494b5617e4373a3e083966dcd74571323f9d334be901d53871fa01ffffffff0200382fb6984b6128bb75115346242809c6555274e0cacef822825a2b4d231700000000484730440220454fcac398f6913fb4d8ed330f110f9cf62eec6c8cdb67d5df1effd2cf8222d5022017f6323630669777573e342e870c88727a917cc06c33611ebbd9d1fccc1dcd3701ffffffff03b0c2a10400000000302ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cc40ca220000000000232102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac0000000000000000266a24127821032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b00000000460100000000000000000000000000", - "txid": "2c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68", - "result": "success" + "hex": "0400008085202f8901a980664dffc810725a79ffb89ac48be4c7b6bade9b789732fcf871acf8e81a2e010000006a47304402207e52763661ecd2c34a65d6623950be11794825db71576dc11894c606ddc317800220028fef46dc20630d0fdf22647b5d4ff0f1c47cf75f48702d0a91d5589eff99d001210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ffffffff031008f60500000000302ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cce09aa4350000000023210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac0000000000000000266a2412782103f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b00000000920500000000000000000000000000", + "txid": "5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c", + "result": "success" } - { - "value": 0.77710000, - "valueZat": 77710000, - "n": 0, - "scriptPubKey": { - "asm": "a22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401 OP_CHECKCRYPTOCONDITION", - "hex": "2ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cc", - "reqSigs": 1, - "type": "cryptocondition", - "addresses": [ - "RKWS7jxyjPX9iaJttk8iMKf1AumanKypez" - ] - } - change script: 2102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac + sendrawtransaction of the above hex. - sendtxid: 2c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68 + ./komodo-cli -ac_name=MUSIG getrawtransaction 5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c 1 + "vout": [ + { + "value": 1.00010000, + "valueSat": 100010000, + "n": 0, + "scriptPubKey": { + "asm": "a22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401 OP_CHECKCRYPTOCONDITION", + "hex": "2ea22c8020c71ddb3aac7f9b9e4bdacf032aaa8b8e4433c4ff9f8a43cebb9c1f5da96928a48103120c008203000401cc", + "reqSigs": 1, + "type": "cryptocondition", + "addresses": [ + "RKWS7jxyjPX9iaJttk8iMKf1AumanKypez" + ] + } + }, + { + "value": 8.99980000, + "valueSat": 899980000, + "n": 1, + "scriptPubKey": { + "asm": "0255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4 OP_CHECKSIG", + "hex": "210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac", + "reqSigs": 1, + "type": "pubkey", + "addresses": [ + "RVQjvGdRbYLJ49bfH4SAFseipvwE3UdoDw" + ] + } - broadcast sendtxid and wait for it to be confirmed. then get the msg we need to sign: + script: 210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac - ./c cclib calcmsg 18 \"[%222c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22]\" + sendtxid: 5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c + + get the msg we need to sign: + + ./komodo-cli -ac_name=MUSIG cclib calcmsg 18 '["5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c","210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac"]' { - "result": "success", - "msg": "caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0" + "msg": "f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75", + "result": "success" } the "msg" is what needs to be signed to create a valid spend @@ -62,88 +82,101 @@ the "msg" is what needs to be signed to create a valid spend now on each signing node, a session needs to be created: 5 args: ind, numsigners, combined_pk, pkhash, message to be signed - on node with pubkey: 02aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848 - ./c cclib session 18 \"[0,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%22caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0%22]\" + on node with pubkey: 02fb6aa0b96cad24d46b5da93eba3864c45ce07a73bba12da530ae841e140fcf28 + ./komodo-cli -ac_name=MUSIG cclib session 18 '[0,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","c1b34139744f3b54b652dc741ebd0f9d5b53ad28795cc6614dd8ad3aaabf15ae","f5d91999b23b85630a4cbd0baea3736529411b052cf5f1f4345c5d181af12825"]' { - "myind": 0, - "numsigners": 2, - "commitment": "e82228c10d0e100477630349150dea744d3b2790dcd347511a1a98199840cda4", - "result": "success" + "myind": 0, + "numsigners": 2, + "commitment": "bbea1f2562eca01b9a1393c5dc188bdd44551aebf684f4459930f59dde01f7ae", + "result": "success" } - - on node with pubkey: 039433dc3749aece1bd568f374a45da3b0bc6856990d7da3cd175399577940a775 - ./c cclib session 18 \"[1,2,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,%22caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0%22]\" - { - "myind": 1, - "numsigners": 2, - "commitment": "6e426e850ddc45e7742cfb6321781c00ee69a995ab12fa1f9ded7fe43658babf", - "result": "success" - } - - now we need to get the commitment from each node to the other one. the session already put the commitment for each node into the global struct. Keep in mind there is a single global struct with session unique to each cclib session call. that means no restarting any deamon in the middle of the process on any of the nodes and only call cclib session a single time. this is an artificial restriction just to simplify the initial implementation of musig - - ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%226e426e850ddc45e7742cfb6321781c00ee69a995ab12fa1f9ded7fe43658babf%22]\" - { - "added_index": 1, - "myind": 0, - "nonce": "0261671b0a6de416938cf035c98f8af37c6ca88bbbd1bcce693d709d4919b010e1", - "result": "success" - } - - ./c cclib commit 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%22e82228c10d0e100477630349150dea744d3b2790dcd347511a1a98199840cda4%22]\" - { - "added_index": 0, - "myind": 1, - "nonce": "02570f62a625ceb19a754a053152b162810c3e403df63f3d443e85bdacc74bfdfe", - "result": "success" - } - - Now exchange the revealed nonces to each node: - - ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%2202570f62a625ceb19a754a053152b162810c3e403df63f3d443e85bdacc74bfdfe%22]\" + on node with pubkey: 0255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4 + ./komodo-cli -ac_name=MUSIG cclib session 18 '[1,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75"]' { - "added_index": 1, - "myind": 0, - "partialsig": "3f21885e6d2d020e1473435ccd148a61cdcb1d1105867fed45913185dc0acf59", - "result": "success" + "myind": 1, + "numsigners": 2, + "commitment": "c2291acb747a75b1a40014d8eb0cc90a1360f74d413f65f78e20a7de45eda851", + "result": "success" + } + + now we need to get the commitment from each node to the other one. the session already put the commitment for each node into the global struct. Keep in mind there is a single global struct with session unique to each cclib session call. that means no restarting any deamon in the middle of the process on any of the nodes and only call cclib session a single time. this is an artificial restriction just to simplify the initial implementation of musig + ./komodo-cli -ac_name=MUSIG cclib commit 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","1","c2291acb747a75b1a40014d8eb0cc90a1360f74d413f65f78e20a7de45eda851"]' + { + "added_index": 1, + "myind": 0, + "nonce": "02fec7a9310c959a0a97b86bc3f8c30d392d1fb51793915898c568f73f1f70476b", + "result": "success" } - ./c cclib nonce 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%220261671b0a6de416938cf035c98f8af37c6ca88bbbd1bcce693d709d4919b010e1%22]\" + ./komodo-cli -ac_name=MUSIG cclib commit 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b",0,"d242cff13fa8c9b83248e4219fda459ada146b885f2171481f1b0f66c66d94ad"]' { - "added_index": 0, - "myind": 0, - "myind": 1, - "partialsig": "af7f28455fb2e988d81068cd9d800879cd334036a8300118dc307b777a38c1ed", - "result": "success" + "added_index": 0, + "myind": 1, + "nonce": "039365deaaaea089d509ba4c9f846de2baf4aa04cf6b26fa2c1cd818553e47f80c", + "result": "success" } + + Now exchange the revealed nonces to each node: + ./komodo-cli -ac_name=MUSIG cclib nonce 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","1","039365deaaaea089d509ba4c9f846de2baf4aa04cf6b26fa2c1cd818553e47f80c"]' +{ + "added_index": 1, + "myind": 0, + "partialsig": "1d65c09cd9bffe4f0604227e66cd7cd221480bbb08262fe885563a9df7cf8f5b", + "result": "success" +} + +./komodo-cli -ac_name=MUSIG cclib nonce 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b",0,"02fec7a9310c959a0a97b86bc3f8c30d392d1fb51793915898c568f73f1f70476b"]' +{ + "added_index": 0, + "myind": 1, + "partialsig": "4a3795e6801b355102c617390cf5a462061e082e35dc2ed8f8b1fab54cc0769e", + "result": "success" +} Almost there! final step is to exchange the partial sigs between signers - ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,1,%22af7f28455fb2e988d81068cd9d800879cd334036a8300118dc307b777a38c1ed%22]\" + ./komodo-cli -ac_name=MUSIG cclib partialsig 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","1","4a3795e6801b355102c617390cf5a462061e082e35dc2ed8f8b1fab54cc0769e"]' { - "added_index": 1, - "result": "success", - "combinedsig": "5e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146" + "added_index": 1, + "result": "success", + "combinedsig": "a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9" } - - ./c cclib partialsig 18 \"[%225be117f3c5ce87e7dc6882c24b8231e0652ee82054bf7b9f94aef1f45e055cba%22,0,%223f21885e6d2d020e1473435ccd148a61cdcb1d1105867fed45913185dc0acf59%22]\" - + ./komodo-cli -ac_name=MUSIG cclib partialsig 18 '["5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b",0,"1d65c09cd9bffe4f0604227e66cd7cd221480bbb08262fe885563a9df7cf8f5b"]' { - "added_index": 0, - "result": "success", - "combinedsig": "5e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146" + "added_index": 0, + "result": "success", + "combinedsig": "a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9" } + Notice both nodes generated the same combined signature! Now for a sanity test, we can use the verify call to make sure this sig will work with the msg needed for the spend: - ./c cclib verify 18 \"[%22caa64ba398ddfe5c33d8c70a61e556caa0e69b19d93110c5a458a1b37ad44cb0%22,%22032ddac56613cd0667b589bd7f32b665e2d2ce0247e337a5a0bca6c72e3d9d057b%22,%225e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146%22]\" - + ./komodo-cli -ac_name=MUSIG cclib verify 18 '["f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75","03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9"]' + { + "msg": "f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75", + "combined_pk": "03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b", + "combinedsig": "a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9", + "result": "success" + } and finally the spend: sendtxid, scriptPubKey, musig -./c cclib spend 18 \"[%222c4159bb19212dcaa412ae37de7d72398f063194053e04a65b0facf767ebcc68%22,%222102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac%22,%225e64dc5dda93b2d3f25fe44b2aaca69b8f15d21f70e2bc1c2c53e17262d941bbeea0b0a3ccdfeb96ec83ac2a6a9492db9afe5d47adb6810621c1acfd56439146%22]\" + ./komodo-cli -ac_name=MUSIG cclib spend 18 '["5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c","210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac","a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9"]' +{ + "scriptpubkey": "210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac", + "msg": "f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75", + "combined_pk": "03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b", + "combinedsig": "a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f9", + "hex": "0400008085202f89014c821930f9eb360daaf1a1e12d5a82998b63884e8db4130421ee53a13740e75c000000007b4c79a276a072a26ba067a5658021032d29d6545a2aafad795d9cf50912ecade549137 +163934dfb2895ebc0e211ce8a81409671a60db89b3bc58966f3acc80194479b1a43d868e95a11ebc5609646d18710341a8ff92a7817571980307f5d660cc00a2735ac6333e0a7191243f1263f1959a100af03800112 +a10001ffffffff0200e1f5050000000023210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac0000000000000000686a4c6512792103f016c348437c7422eed92d865aa9789614f +75327cada463eefc566126b54785b40a76f2790747ed2436a281f2660bdbee21bad9ee130b9cab6e542fa618fba1512679d568359db33a008ca39b773c32134276613e93e025ec17e083553449005f900000000a805 +00000000000000000000000000", + "txid": "910635bf69a047fc90567a83ff12e47b753f470658b6d0855ec96e07e7349a8a", + "result": "success" +} */ @@ -298,7 +331,7 @@ int32_t musig_prevoutmsg(uint8_t *msg,uint256 sendtxid,CScript scriptPubKey) UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint256 sendtxid; int32_t i; uint8_t msg[32]; char *scriptstr,str[65]; int32_t n; + UniValue result(UniValue::VOBJ); uint256 sendtxid; int32_t i,zeros=0; uint8_t msg[32]; char *scriptstr,str[65]; int32_t n; if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { if ( n == 2 ) @@ -307,14 +340,23 @@ UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) scriptstr = jstr(jitem(params,1),0); if ( is_hexstr(scriptstr,0) != 0 ) { - CScript scriptPubKey(ParseHex(scriptstr)); + CScript scriptPubKey; + scriptPubKey.resize(strlen(scriptstr)/2); + decode_hex(&scriptPubKey[0],strlen(scriptstr)/2,scriptstr); musig_prevoutmsg(msg,sendtxid,scriptPubKey); - result.push_back(Pair("result","success")); for (i=0; i<32; i++) + { sprintf(&str[i<<1],"%02x",msg[i]); + if ( msg[i] == 0 ) + zeros++; + } str[64] = 0; - result.push_back(Pair("msg",str)); - return(result); + if ( zeros != 32 ) + { + result.push_back(Pair("msg",str)); + result.push_back(Pair("result","success")); + return(result); + } else return(cclib_error(result,"null result, make sure params are sendtxid, scriptPubKey")); } else return(cclib_error(result,"script is not hex")); } else return(cclib_error(result,"need exactly 2 parameters: sendtxid, scriptPubKey")); } else return(cclib_error(result,"couldnt parse params")); From ebc07912fdb319358e162ec5be149f8e03bd5c0f Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sat, 23 Feb 2019 15:18:18 +0800 Subject: [PATCH 1068/1145] fix rogue ipaddress thing for Alright. Needs to be tested! --- depends/packages/boost.mk | 6 +-- src/cc/rogue/main.c | 2 + src/musigtest.py | 91 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 3 deletions(-) create mode 100755 src/musigtest.py diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 7a0439ba7..3c180b0ce 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -1,8 +1,8 @@ package=boost -$(package)_version=1_69_0 -$(package)_download_path=https://dl.bintray.com/boostorg/release/1.69.0/source +$(package)_version=1_66_0 +$(package)_download_path=https://dl.bintray.com/boostorg/release/1.66.0/source $(package)_file_name=$(package)_$($(package)_version).tar.bz2 -$(package)_sha256_hash=8f32d4617390d1c2d16f26a27ab60d97807b35440d45891fa340fc2648b04406 +$(package)_sha256_hash=5721818253e6a0989583192f96782c4a98eb6204965316df9f5ad75819225ca9 define $(package)_set_vars $(package)_config_opts_release=variant=release diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 3461445ee..6fc3d36c8 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -802,6 +802,8 @@ int main(int argc, char **argv, char **envp) } ASSETCHAINS_SYMBOL[j++] = 0; ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL,IPADDRESS); + if ( IPADDRESS[0] == 0 ) + strcopy("127.0.0.1",IPADDRESS); printf("ASSETCHAINS_SYMBOL.(%s) port.%u (%s)\n",ASSETCHAINS_SYMBOL,ROGUE_PORT,USERPASS); sleep(1); if ( argc == 2 && (fp=fopen(argv[1],"rb")) == 0 ) { diff --git a/src/musigtest.py b/src/musigtest.py new file mode 100755 index 000000000..f5f25d250 --- /dev/null +++ b/src/musigtest.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +import platform +import os +import re +import json +import random +import base58 +import binascii +import hashlib +import sys +from slickrpc import Proxy + +# fucntion to define rpc_connection +def def_credentials(chain): + rpcport = ''; + operating_system = platform.system() + if operating_system == 'Darwin': + ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo' + elif operating_system == 'Linux': + ac_dir = os.environ['HOME'] + '/.komodo' + elif operating_system == 'Windows': + ac_dir = '%s/komodo/' % os.environ['APPDATA'] + if chain == 'KMD': + coin_config_file = str(ac_dir + '/komodo.conf') + else: + coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') + with open(coin_config_file, 'r') as f: + for line in f: + l = line.rstrip() + if re.search('rpcuser', l): + rpcuser = l.replace('rpcuser=', '') + elif re.search('rpcpassword', l): + rpcpassword = l.replace('rpcpassword=', '') + elif re.search('rpcport', l): + rpcport = l.replace('rpcport=', '') + if len(rpcport) == 0: + if chain == 'KMD': + rpcport = 7771 + else: + print("rpcport not in conf file, exiting") + print("check " + coin_config_file) + exit(1) + return (Proxy("http://%s:%s@127.0.0.1:%d" % (rpcuser, rpcpassword, int(rpcport)))) + + +# generate address, validate address, dump private key +def genvaldump(rpc_connection): + # get new address + address = rpc_connection.getnewaddress() + # validate address + validateaddress_result = rpc_connection.validateaddress(address) + pubkey = validateaddress_result['pubkey'] + address = validateaddress_result['address'] + # dump private key for the address + privkey = rpc_connection.dumpprivkey(address) + # function output + output = [pubkey, privkey, address] + return(output) + +CHAIN = 'MUSIG' #sys.argv[1] + +rpc = def_credentials(CHAIN) + +pubkeys = [] +address_info = [] +ret = input('Do you want to generate new pubkeys? ').lower() + +if ret.startswith('y'): + numpks = int(input('Enter number of pubkeys to combine: ')) + if os.path.isfile("list.json"): + print('Already have list.json, move it if you would like to generate a new set.') + sys.exit(0) + while len(address_info) < numpks: + addressinfo = genvaldump(rpc) + address_info.append(addressinfo) + f = open("list.json", "w+") + f.write(json.dumps(address_info)) +else: + if os.path.isfile("list.json"): + with open('list.json') as list: + address_info = json.load(list) + else: + sys.exit('No list.json you need to create new pubkeys!') + +for addressinfo in address_info: + pubkeys.append(addressinfo[0]) + +ret = rpc.setpubkey(pubkeys[0]) +combinedpk = rpc.cclib("combine", "18", str(pubkeys))['combined_pk'] + +print('Your combined pubkey is: ' + combinedpk) From fb82fc82aaae27fc885a0ad156747bbfbde0b78a Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sat, 23 Feb 2019 15:23:08 +0800 Subject: [PATCH 1069/1145] fix --- src/cc/rogue/main.c | 2 +- src/musigtest.py | 91 --------------------------------------------- 2 files changed, 1 insertion(+), 92 deletions(-) delete mode 100755 src/musigtest.py diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 6fc3d36c8..4dfc0a70a 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -803,7 +803,7 @@ int main(int argc, char **argv, char **envp) ASSETCHAINS_SYMBOL[j++] = 0; ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL,IPADDRESS); if ( IPADDRESS[0] == 0 ) - strcopy("127.0.0.1",IPADDRESS); + strcpy("127.0.0.1",IPADDRESS); printf("ASSETCHAINS_SYMBOL.(%s) port.%u (%s)\n",ASSETCHAINS_SYMBOL,ROGUE_PORT,USERPASS); sleep(1); if ( argc == 2 && (fp=fopen(argv[1],"rb")) == 0 ) { diff --git a/src/musigtest.py b/src/musigtest.py deleted file mode 100755 index f5f25d250..000000000 --- a/src/musigtest.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python3 -import platform -import os -import re -import json -import random -import base58 -import binascii -import hashlib -import sys -from slickrpc import Proxy - -# fucntion to define rpc_connection -def def_credentials(chain): - rpcport = ''; - operating_system = platform.system() - if operating_system == 'Darwin': - ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo' - elif operating_system == 'Linux': - ac_dir = os.environ['HOME'] + '/.komodo' - elif operating_system == 'Windows': - ac_dir = '%s/komodo/' % os.environ['APPDATA'] - if chain == 'KMD': - coin_config_file = str(ac_dir + '/komodo.conf') - else: - coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') - with open(coin_config_file, 'r') as f: - for line in f: - l = line.rstrip() - if re.search('rpcuser', l): - rpcuser = l.replace('rpcuser=', '') - elif re.search('rpcpassword', l): - rpcpassword = l.replace('rpcpassword=', '') - elif re.search('rpcport', l): - rpcport = l.replace('rpcport=', '') - if len(rpcport) == 0: - if chain == 'KMD': - rpcport = 7771 - else: - print("rpcport not in conf file, exiting") - print("check " + coin_config_file) - exit(1) - return (Proxy("http://%s:%s@127.0.0.1:%d" % (rpcuser, rpcpassword, int(rpcport)))) - - -# generate address, validate address, dump private key -def genvaldump(rpc_connection): - # get new address - address = rpc_connection.getnewaddress() - # validate address - validateaddress_result = rpc_connection.validateaddress(address) - pubkey = validateaddress_result['pubkey'] - address = validateaddress_result['address'] - # dump private key for the address - privkey = rpc_connection.dumpprivkey(address) - # function output - output = [pubkey, privkey, address] - return(output) - -CHAIN = 'MUSIG' #sys.argv[1] - -rpc = def_credentials(CHAIN) - -pubkeys = [] -address_info = [] -ret = input('Do you want to generate new pubkeys? ').lower() - -if ret.startswith('y'): - numpks = int(input('Enter number of pubkeys to combine: ')) - if os.path.isfile("list.json"): - print('Already have list.json, move it if you would like to generate a new set.') - sys.exit(0) - while len(address_info) < numpks: - addressinfo = genvaldump(rpc) - address_info.append(addressinfo) - f = open("list.json", "w+") - f.write(json.dumps(address_info)) -else: - if os.path.isfile("list.json"): - with open('list.json') as list: - address_info = json.load(list) - else: - sys.exit('No list.json you need to create new pubkeys!') - -for addressinfo in address_info: - pubkeys.append(addressinfo[0]) - -ret = rpc.setpubkey(pubkeys[0]) -combinedpk = rpc.cclib("combine", "18", str(pubkeys))['combined_pk'] - -print('Your combined pubkey is: ' + combinedpk) From 9ed121b9477012c42e16acb4ec4cebf38b39cb6d Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sat, 23 Feb 2019 15:24:23 +0800 Subject: [PATCH 1070/1145] undo --- depends/packages/boost.mk | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 3c180b0ce..7a0439ba7 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -1,8 +1,8 @@ package=boost -$(package)_version=1_66_0 -$(package)_download_path=https://dl.bintray.com/boostorg/release/1.66.0/source +$(package)_version=1_69_0 +$(package)_download_path=https://dl.bintray.com/boostorg/release/1.69.0/source $(package)_file_name=$(package)_$($(package)_version).tar.bz2 -$(package)_sha256_hash=5721818253e6a0989583192f96782c4a98eb6204965316df9f5ad75819225ca9 +$(package)_sha256_hash=8f32d4617390d1c2d16f26a27ab60d97807b35440d45891fa340fc2648b04406 define $(package)_set_vars $(package)_config_opts_release=variant=release From aa6b693feecac75cf90c4dd3657499f13818d220 Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sat, 23 Feb 2019 15:26:18 +0800 Subject: [PATCH 1071/1145] fix strcpy --- src/cc/rogue/main.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 4dfc0a70a..165f01dfd 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -803,7 +803,7 @@ int main(int argc, char **argv, char **envp) ASSETCHAINS_SYMBOL[j++] = 0; ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL,IPADDRESS); if ( IPADDRESS[0] == 0 ) - strcpy("127.0.0.1",IPADDRESS); + strcpy(IPADDRESS,"127.0.0.1"); printf("ASSETCHAINS_SYMBOL.(%s) port.%u (%s)\n",ASSETCHAINS_SYMBOL,ROGUE_PORT,USERPASS); sleep(1); if ( argc == 2 && (fp=fopen(argv[1],"rb")) == 0 ) { From 9df722e1b6a5f82254bcf7281e3a4f365f200023 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 21:04:55 -1100 Subject: [PATCH 1072/1145] Dilithium lib --- src/cc/cclib.cpp | 3 +- src/cc/dilithium.c | 2837 ++++++++++++++++++++++++++++++++++++++++++++ src/cc/dilithium.h | 474 ++++++++ src/cc/makecclib | 2 +- src/cc/musig.cpp | 4 +- 5 files changed, 3316 insertions(+), 4 deletions(-) create mode 100644 src/cc/dilithium.c create mode 100644 src/cc/dilithium.h diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index c770917ea..84f229069 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -581,6 +581,7 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" #include "musig.cpp" -#include "../secp256k1/src/modules/musig/example.c" +#inclide "dilithium.c" +//#include "../secp256k1/src/modules/musig/example.c" #endif diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c new file mode 100644 index 000000000..b6624353e --- /dev/null +++ b/src/cc/dilithium.c @@ -0,0 +1,2837 @@ +/* Based on the public domain implementation in + * crypto_hash/keccakc512/simple/ from http://bench.cr.yp.to/supercop.html + * by Ronny Van Keer + * and the public domain "TweetFips202" implementation + * from https://twitter.com/tweetfips202 + * by Gilles Van Assche, Daniel J. Bernstein, and Peter Schwabe */ + +#include +#include "dilithium.h" + + +#define NROUNDS 24 +#define ROL(a, offset) ((a << offset) ^ (a >> (64-offset))) + +/************************************************* +* Name: load64 +* +* Description: Load 8 bytes into uint64_t in little-endian order +* +* Arguments: - const uint8_t *x: pointer to input byte array +* +* Returns the loaded 64-bit unsigned integer +**************************************************/ +static uint64_t load64(const uint8_t *x) { + uint32_t i; + uint64_t r = 0; + + for (i = 0; i < 8; ++i) + r |= (uint64_t)x[i] << 8*i; + + return r; +} + +/************************************************* +* Name: store64 +* +* Description: Store a 64-bit integer to array of 8 bytes in little-endian order +* +* Arguments: - uint8_t *x: pointer to the output byte array (allocated) +* - uint64_t u: input 64-bit unsigned integer +**************************************************/ +static void store64(uint8_t *x, uint64_t u) { + uint32_t i; + + for(i = 0; i < 8; ++i) + x[i] = u >> 8*i; +} + +/* Keccak round constants */ +static const uint64_t KeccakF_RoundConstants[NROUNDS] = { + (uint64_t)0x0000000000000001ULL, + (uint64_t)0x0000000000008082ULL, + (uint64_t)0x800000000000808aULL, + (uint64_t)0x8000000080008000ULL, + (uint64_t)0x000000000000808bULL, + (uint64_t)0x0000000080000001ULL, + (uint64_t)0x8000000080008081ULL, + (uint64_t)0x8000000000008009ULL, + (uint64_t)0x000000000000008aULL, + (uint64_t)0x0000000000000088ULL, + (uint64_t)0x0000000080008009ULL, + (uint64_t)0x000000008000000aULL, + (uint64_t)0x000000008000808bULL, + (uint64_t)0x800000000000008bULL, + (uint64_t)0x8000000000008089ULL, + (uint64_t)0x8000000000008003ULL, + (uint64_t)0x8000000000008002ULL, + (uint64_t)0x8000000000000080ULL, + (uint64_t)0x000000000000800aULL, + (uint64_t)0x800000008000000aULL, + (uint64_t)0x8000000080008081ULL, + (uint64_t)0x8000000000008080ULL, + (uint64_t)0x0000000080000001ULL, + (uint64_t)0x8000000080008008ULL +}; + +/************************************************* +* Name: KeccakF1600_StatePermute +* +* Description: The Keccak F1600 Permutation +* +* Arguments: - uint64_t *state: pointer to input/output Keccak state +**************************************************/ +static void KeccakF1600_StatePermute(uint64_t *state) +{ + int round; + + uint64_t Aba, Abe, Abi, Abo, Abu; + uint64_t Aga, Age, Agi, Ago, Agu; + uint64_t Aka, Ake, Aki, Ako, Aku; + uint64_t Ama, Ame, Ami, Amo, Amu; + uint64_t Asa, Ase, Asi, Aso, Asu; + uint64_t BCa, BCe, BCi, BCo, BCu; + uint64_t Da, De, Di, Do, Du; + uint64_t Eba, Ebe, Ebi, Ebo, Ebu; + uint64_t Ega, Ege, Egi, Ego, Egu; + uint64_t Eka, Eke, Eki, Eko, Eku; + uint64_t Ema, Eme, Emi, Emo, Emu; + uint64_t Esa, Ese, Esi, Eso, Esu; + + //copyFromState(A, state) + Aba = state[ 0]; + Abe = state[ 1]; + Abi = state[ 2]; + Abo = state[ 3]; + Abu = state[ 4]; + Aga = state[ 5]; + Age = state[ 6]; + Agi = state[ 7]; + Ago = state[ 8]; + Agu = state[ 9]; + Aka = state[10]; + Ake = state[11]; + Aki = state[12]; + Ako = state[13]; + Aku = state[14]; + Ama = state[15]; + Ame = state[16]; + Ami = state[17]; + Amo = state[18]; + Amu = state[19]; + Asa = state[20]; + Ase = state[21]; + Asi = state[22]; + Aso = state[23]; + Asu = state[24]; + + for( round = 0; round < NROUNDS; round += 2 ) + { + // prepareTheta + BCa = Aba^Aga^Aka^Ama^Asa; + BCe = Abe^Age^Ake^Ame^Ase; + BCi = Abi^Agi^Aki^Ami^Asi; + BCo = Abo^Ago^Ako^Amo^Aso; + BCu = Abu^Agu^Aku^Amu^Asu; + + //thetaRhoPiChiIotaPrepareTheta(round , A, E) + Da = BCu^ROL(BCe, 1); + De = BCa^ROL(BCi, 1); + Di = BCe^ROL(BCo, 1); + Do = BCi^ROL(BCu, 1); + Du = BCo^ROL(BCa, 1); + + Aba ^= Da; + BCa = Aba; + Age ^= De; + BCe = ROL(Age, 44); + Aki ^= Di; + BCi = ROL(Aki, 43); + Amo ^= Do; + BCo = ROL(Amo, 21); + Asu ^= Du; + BCu = ROL(Asu, 14); + Eba = BCa ^((~BCe)& BCi ); + Eba ^= (uint64_t)KeccakF_RoundConstants[round]; + Ebe = BCe ^((~BCi)& BCo ); + Ebi = BCi ^((~BCo)& BCu ); + Ebo = BCo ^((~BCu)& BCa ); + Ebu = BCu ^((~BCa)& BCe ); + + Abo ^= Do; + BCa = ROL(Abo, 28); + Agu ^= Du; + BCe = ROL(Agu, 20); + Aka ^= Da; + BCi = ROL(Aka, 3); + Ame ^= De; + BCo = ROL(Ame, 45); + Asi ^= Di; + BCu = ROL(Asi, 61); + Ega = BCa ^((~BCe)& BCi ); + Ege = BCe ^((~BCi)& BCo ); + Egi = BCi ^((~BCo)& BCu ); + Ego = BCo ^((~BCu)& BCa ); + Egu = BCu ^((~BCa)& BCe ); + + Abe ^= De; + BCa = ROL(Abe, 1); + Agi ^= Di; + BCe = ROL(Agi, 6); + Ako ^= Do; + BCi = ROL(Ako, 25); + Amu ^= Du; + BCo = ROL(Amu, 8); + Asa ^= Da; + BCu = ROL(Asa, 18); + Eka = BCa ^((~BCe)& BCi ); + Eke = BCe ^((~BCi)& BCo ); + Eki = BCi ^((~BCo)& BCu ); + Eko = BCo ^((~BCu)& BCa ); + Eku = BCu ^((~BCa)& BCe ); + + Abu ^= Du; + BCa = ROL(Abu, 27); + Aga ^= Da; + BCe = ROL(Aga, 36); + Ake ^= De; + BCi = ROL(Ake, 10); + Ami ^= Di; + BCo = ROL(Ami, 15); + Aso ^= Do; + BCu = ROL(Aso, 56); + Ema = BCa ^((~BCe)& BCi ); + Eme = BCe ^((~BCi)& BCo ); + Emi = BCi ^((~BCo)& BCu ); + Emo = BCo ^((~BCu)& BCa ); + Emu = BCu ^((~BCa)& BCe ); + + Abi ^= Di; + BCa = ROL(Abi, 62); + Ago ^= Do; + BCe = ROL(Ago, 55); + Aku ^= Du; + BCi = ROL(Aku, 39); + Ama ^= Da; + BCo = ROL(Ama, 41); + Ase ^= De; + BCu = ROL(Ase, 2); + Esa = BCa ^((~BCe)& BCi ); + Ese = BCe ^((~BCi)& BCo ); + Esi = BCi ^((~BCo)& BCu ); + Eso = BCo ^((~BCu)& BCa ); + Esu = BCu ^((~BCa)& BCe ); + + // prepareTheta + BCa = Eba^Ega^Eka^Ema^Esa; + BCe = Ebe^Ege^Eke^Eme^Ese; + BCi = Ebi^Egi^Eki^Emi^Esi; + BCo = Ebo^Ego^Eko^Emo^Eso; + BCu = Ebu^Egu^Eku^Emu^Esu; + + //thetaRhoPiChiIotaPrepareTheta(round+1, E, A) + Da = BCu^ROL(BCe, 1); + De = BCa^ROL(BCi, 1); + Di = BCe^ROL(BCo, 1); + Do = BCi^ROL(BCu, 1); + Du = BCo^ROL(BCa, 1); + + Eba ^= Da; + BCa = Eba; + Ege ^= De; + BCe = ROL(Ege, 44); + Eki ^= Di; + BCi = ROL(Eki, 43); + Emo ^= Do; + BCo = ROL(Emo, 21); + Esu ^= Du; + BCu = ROL(Esu, 14); + Aba = BCa ^((~BCe)& BCi ); + Aba ^= (uint64_t)KeccakF_RoundConstants[round+1]; + Abe = BCe ^((~BCi)& BCo ); + Abi = BCi ^((~BCo)& BCu ); + Abo = BCo ^((~BCu)& BCa ); + Abu = BCu ^((~BCa)& BCe ); + + Ebo ^= Do; + BCa = ROL(Ebo, 28); + Egu ^= Du; + BCe = ROL(Egu, 20); + Eka ^= Da; + BCi = ROL(Eka, 3); + Eme ^= De; + BCo = ROL(Eme, 45); + Esi ^= Di; + BCu = ROL(Esi, 61); + Aga = BCa ^((~BCe)& BCi ); + Age = BCe ^((~BCi)& BCo ); + Agi = BCi ^((~BCo)& BCu ); + Ago = BCo ^((~BCu)& BCa ); + Agu = BCu ^((~BCa)& BCe ); + + Ebe ^= De; + BCa = ROL(Ebe, 1); + Egi ^= Di; + BCe = ROL(Egi, 6); + Eko ^= Do; + BCi = ROL(Eko, 25); + Emu ^= Du; + BCo = ROL(Emu, 8); + Esa ^= Da; + BCu = ROL(Esa, 18); + Aka = BCa ^((~BCe)& BCi ); + Ake = BCe ^((~BCi)& BCo ); + Aki = BCi ^((~BCo)& BCu ); + Ako = BCo ^((~BCu)& BCa ); + Aku = BCu ^((~BCa)& BCe ); + + Ebu ^= Du; + BCa = ROL(Ebu, 27); + Ega ^= Da; + BCe = ROL(Ega, 36); + Eke ^= De; + BCi = ROL(Eke, 10); + Emi ^= Di; + BCo = ROL(Emi, 15); + Eso ^= Do; + BCu = ROL(Eso, 56); + Ama = BCa ^((~BCe)& BCi ); + Ame = BCe ^((~BCi)& BCo ); + Ami = BCi ^((~BCo)& BCu ); + Amo = BCo ^((~BCu)& BCa ); + Amu = BCu ^((~BCa)& BCe ); + + Ebi ^= Di; + BCa = ROL(Ebi, 62); + Ego ^= Do; + BCe = ROL(Ego, 55); + Eku ^= Du; + BCi = ROL(Eku, 39); + Ema ^= Da; + BCo = ROL(Ema, 41); + Ese ^= De; + BCu = ROL(Ese, 2); + Asa = BCa ^((~BCe)& BCi ); + Ase = BCe ^((~BCi)& BCo ); + Asi = BCi ^((~BCo)& BCu ); + Aso = BCo ^((~BCu)& BCa ); + Asu = BCu ^((~BCa)& BCe ); + } + + //copyToState(state, A) + state[ 0] = Aba; + state[ 1] = Abe; + state[ 2] = Abi; + state[ 3] = Abo; + state[ 4] = Abu; + state[ 5] = Aga; + state[ 6] = Age; + state[ 7] = Agi; + state[ 8] = Ago; + state[ 9] = Agu; + state[10] = Aka; + state[11] = Ake; + state[12] = Aki; + state[13] = Ako; + state[14] = Aku; + state[15] = Ama; + state[16] = Ame; + state[17] = Ami; + state[18] = Amo; + state[19] = Amu; + state[20] = Asa; + state[21] = Ase; + state[22] = Asi; + state[23] = Aso; + state[24] = Asu; +} + +/************************************************* +* Name: keccak_absorb +* +* Description: Absorb step of Keccak; +* non-incremental, starts by zeroeing the state. +* +* Arguments: - uint64_t *s: pointer to (uninitialized) output Keccak state +* - unsigned int r: rate in bytes (e.g., 168 for SHAKE128) +* - const uint8_t *m: pointer to input to be absorbed into s +* - int32_t mlen: length of input in bytes +* - uint8_t p: domain-separation byte for different +* Keccak-derived functions +**************************************************/ +static void keccak_absorb(uint64_t *s, + uint32_t r, + const uint8_t *m, + int32_t mlen, + uint8_t p) +{ + uint32_t i; + uint8_t t[200]; + DBENCH_START(); + + /* Zero state */ + for(i = 0; i < 25; ++i) + s[i] = 0; + + while(mlen >= r) { + for(i = 0; i < r/8; ++i) + s[i] ^= load64(m + 8*i); + + KeccakF1600_StatePermute(s); + mlen -= r; + m += r; + } + + for(i = 0; i < r; ++i) + t[i] = 0; + for(i = 0; i < mlen; ++i) + t[i] = m[i]; + t[i] = p; + t[r-1] |= 128; + for(i = 0; i < r/8; ++i) + s[i] ^= load64(t + 8*i); + + DBENCH_STOP(*tshake); +} + +/************************************************* +* Name: keccak_squeezeblocks +* +* Description: Squeeze step of Keccak. Squeezes full blocks of r bytes each. +* Modifies the state. Can be called multiple times to keep +* squeezing, i.e., is incremental. +* +* Arguments: - uint8_t *h: pointer to output blocks +* - int32_t int nblocks: number of blocks to be +* squeezed (written to h) +* - uint64_t *s: pointer to input/output Keccak state +* - uint32_t r: rate in bytes (e.g., 168 for SHAKE128) +**************************************************/ +static void keccak_squeezeblocks(uint8_t *h, + int32_t nblocks, + uint64_t *s, + uint32_t r) +{ + uint32_t i; + DBENCH_START(); + + while(nblocks > 0) { + KeccakF1600_StatePermute(s); + for(i=0; i < (r >> 3); i++) { + store64(h + 8*i, s[i]); + } + h += r; + --nblocks; + } + + DBENCH_STOP(*tshake); +} + +/************************************************* +* Name: shake128_absorb +* +* Description: Absorb step of the SHAKE128 XOF. +* non-incremental, starts by zeroeing the state. +* +* Arguments: - uint64_t *s: pointer to (uninitialized) output Keccak state +* - const uint8_t *input: pointer to input to be absorbed +* into s +* - int32_t inlen: length of input in bytes +**************************************************/ +void shake128_absorb(uint64_t *s, + const uint8_t *input, + int32_t inlen) +{ + keccak_absorb(s, SHAKE128_RATE, input, inlen, 0x1F); +} + +/************************************************* +* Name: shake128_squeezeblocks +* +* Description: Squeeze step of SHAKE128 XOF. Squeezes full blocks of +* SHAKE128_RATE bytes each. Modifies the state. Can be called +* multiple times to keep squeezing, i.e., is incremental. +* +* Arguments: - uint8_t *output: pointer to output blocks +* - int32_t nblocks: number of blocks to be squeezed +* (written to output) +* - uint64_t *s: pointer to input/output Keccak state +**************************************************/ +void shake128_squeezeblocks(uint8_t *output, + int32_t nblocks, + uint64_t *s) +{ + keccak_squeezeblocks(output, nblocks, s, SHAKE128_RATE); +} + +/************************************************* +* Name: shake256_absorb +* +* Description: Absorb step of the SHAKE256 XOF. +* non-incremental, starts by zeroeing the state. +* +* Arguments: - uint64_t *s: pointer to (uninitialized) output Keccak state +* - const uint8_t *input: pointer to input to be absorbed +* into s +* - int32_t inlen: length of input in bytes +**************************************************/ +void shake256_absorb(uint64_t *s, + const uint8_t *input, + int32_t inlen) +{ + keccak_absorb(s, SHAKE256_RATE, input, inlen, 0x1F); +} + +/************************************************* +* Name: shake256_squeezeblocks +* +* Description: Squeeze step of SHAKE256 XOF. Squeezes full blocks of +* SHAKE256_RATE bytes each. Modifies the state. Can be called +* multiple times to keep squeezing, i.e., is incremental. +* +* Arguments: - uint8_t *output: pointer to output blocks +* - int32_t nblocks: number of blocks to be squeezed +* (written to output) +* - uint64_t *s: pointer to input/output Keccak state +**************************************************/ +void shake256_squeezeblocks(uint8_t *output, + int32_t nblocks, + uint64_t *s) +{ + keccak_squeezeblocks(output, nblocks, s, SHAKE256_RATE); +} + +/************************************************* +* Name: shake128 +* +* Description: SHAKE128 XOF with non-incremental API +* +* Arguments: - uint8_t *output: pointer to output +* - int32_t outlen: requested output length in bytes +* - const uint8_t *input: pointer to input +* - int32_t inlen: length of input in bytes +**************************************************/ +void shake128(uint8_t *output, + int32_t outlen, + const uint8_t *input, + int32_t inlen) +{ + uint32_t i,nblocks = outlen/SHAKE128_RATE; + uint8_t t[SHAKE128_RATE]; + uint64_t s[25]; + + shake128_absorb(s, input, inlen); + shake128_squeezeblocks(output, nblocks, s); + + output += nblocks*SHAKE128_RATE; + outlen -= nblocks*SHAKE128_RATE; + + if(outlen) { + shake128_squeezeblocks(t, 1, s); + for(i = 0; i < outlen; ++i) + output[i] = t[i]; + } +} + +/************************************************* +* Name: shake256 +* +* Description: SHAKE256 XOF with non-incremental API +* +* Arguments: - uint8_t *output: pointer to output +* - int32_t outlen: requested output length in bytes +* - const uint8_t *input: pointer to input +* - int32_t inlen: length of input in bytes +**************************************************/ +void shake256(uint8_t *output, + int32_t outlen, + const uint8_t *input, + int32_t inlen) +{ + uint32_t i,nblocks = outlen/SHAKE256_RATE; + uint8_t t[SHAKE256_RATE]; + uint64_t s[25]; + + shake256_absorb(s, input, inlen); + shake256_squeezeblocks(output, nblocks, s); + + output += nblocks*SHAKE256_RATE; + outlen -= nblocks*SHAKE256_RATE; + + if(outlen) { + shake256_squeezeblocks(t, 1, s); + for(i = 0; i < outlen; ++i) + output[i] = t[i]; + } +} +//#include "params.h" +//#include "reduce.h" +//#include "ntt.h" +//#include "poly.h" + +/* Roots of unity in order needed by forward ntt */ +static const uint32_t zetas[N] = {0, 25847, 5771523, 7861508, 237124, 7602457, 7504169, 466468, 1826347, 2353451, 8021166, 6288512, 3119733, 5495562, 3111497, 2680103, 2725464, 1024112, 7300517, 3585928, 7830929, 7260833, 2619752, 6271868, 6262231, 4520680, 6980856, 5102745, 1757237, 8360995, 4010497, 280005, 2706023, 95776, 3077325, 3530437, 6718724, 4788269, 5842901, 3915439, 4519302, 5336701, 3574422, 5512770, 3539968, 8079950, 2348700, 7841118, 6681150, 6736599, 3505694, 4558682, 3507263, 6239768, 6779997, 3699596, 811944, 531354, 954230, 3881043, 3900724, 5823537, 2071892, 5582638, 4450022, 6851714, 4702672, 5339162, 6927966, 3475950, 2176455, 6795196, 7122806, 1939314, 4296819, 7380215, 5190273, 5223087, 4747489, 126922, 3412210, 7396998, 2147896, 2715295, 5412772, 4686924, 7969390, 5903370, 7709315, 7151892, 8357436, 7072248, 7998430, 1349076, 1852771, 6949987, 5037034, 264944, 508951, 3097992, 44288, 7280319, 904516, 3958618, 4656075, 8371839, 1653064, 5130689, 2389356, 8169440, 759969, 7063561, 189548, 4827145, 3159746, 6529015, 5971092, 8202977, 1315589, 1341330, 1285669, 6795489, 7567685, 6940675, 5361315, 4499357, 4751448, 3839961, 2091667, 3407706, 2316500, 3817976, 5037939, 2244091, 5933984, 4817955, 266997, 2434439, 7144689, 3513181, 4860065, 4621053, 7183191, 5187039, 900702, 1859098, 909542, 819034, 495491, 6767243, 8337157, 7857917, 7725090, 5257975, 2031748, 3207046, 4823422, 7855319, 7611795, 4784579, 342297, 286988, 5942594, 4108315, 3437287, 5038140, 1735879, 203044, 2842341, 2691481, 5790267, 1265009, 4055324, 1247620, 2486353, 1595974, 4613401, 1250494, 2635921, 4832145, 5386378, 1869119, 1903435, 7329447, 7047359, 1237275, 5062207, 6950192, 7929317, 1312455, 3306115, 6417775, 7100756, 1917081, 5834105, 7005614, 1500165, 777191, 2235880, 3406031, 7838005, 5548557, 6709241, 6533464, 5796124, 4656147, 594136, 4603424, 6366809, 2432395, 2454455, 8215696, 1957272, 3369112, 185531, 7173032, 5196991, 162844, 1616392, 3014001, 810149, 1652634, 4686184, 6581310, 5341501, 3523897, 3866901, 269760, 2213111, 7404533, 1717735, 472078, 7953734, 1723600, 6577327, 1910376, 6712985, 7276084, 8119771, 4546524, 5441381, 6144432, 7959518, 6094090, 183443, 7403526, 1612842, 4834730, 7826001, 3919660, 8332111, 7018208, 3937738, 1400424, 7534263, 1976782}; + +/* Roots of unity in order needed by inverse ntt */ +static const uint32_t zetas_inv[N] = {6403635, 846154, 6979993, 4442679, 1362209, 48306, 4460757, 554416, 3545687, 6767575, 976891, 8196974, 2286327, 420899, 2235985, 2939036, 3833893, 260646, 1104333, 1667432, 6470041, 1803090, 6656817, 426683, 7908339, 6662682, 975884, 6167306, 8110657, 4513516, 4856520, 3038916, 1799107, 3694233, 6727783, 7570268, 5366416, 6764025, 8217573, 3183426, 1207385, 8194886, 5011305, 6423145, 164721, 5925962, 5948022, 2013608, 3776993, 7786281, 3724270, 2584293, 1846953, 1671176, 2831860, 542412, 4974386, 6144537, 7603226, 6880252, 1374803, 2546312, 6463336, 1279661, 1962642, 5074302, 7067962, 451100, 1430225, 3318210, 7143142, 1333058, 1050970, 6476982, 6511298, 2994039, 3548272, 5744496, 7129923, 3767016, 6784443, 5894064, 7132797, 4325093, 7115408, 2590150, 5688936, 5538076, 8177373, 6644538, 3342277, 4943130, 4272102, 2437823, 8093429, 8038120, 3595838, 768622, 525098, 3556995, 5173371, 6348669, 3122442, 655327, 522500, 43260, 1613174, 7884926, 7561383, 7470875, 6521319, 7479715, 3193378, 1197226, 3759364, 3520352, 4867236, 1235728, 5945978, 8113420, 3562462, 2446433, 6136326, 3342478, 4562441, 6063917, 4972711, 6288750, 4540456, 3628969, 3881060, 3019102, 1439742, 812732, 1584928, 7094748, 7039087, 7064828, 177440, 2409325, 1851402, 5220671, 3553272, 8190869, 1316856, 7620448, 210977, 5991061, 3249728, 6727353, 8578, 3724342, 4421799, 7475901, 1100098, 8336129, 5282425, 7871466, 8115473, 3343383, 1430430, 6527646, 7031341, 381987, 1308169, 22981, 1228525, 671102, 2477047, 411027, 3693493, 2967645, 5665122, 6232521, 983419, 4968207, 8253495, 3632928, 3157330, 3190144, 1000202, 4083598, 6441103, 1257611, 1585221, 6203962, 4904467, 1452451, 3041255, 3677745, 1528703, 3930395, 2797779, 6308525, 2556880, 4479693, 4499374, 7426187, 7849063, 7568473, 4680821, 1600420, 2140649, 4873154, 3821735, 4874723, 1643818, 1699267, 539299, 6031717, 300467, 4840449, 2867647, 4805995, 3043716, 3861115, 4464978, 2537516, 3592148, 1661693, 4849980, 5303092, 8284641, 5674394, 8100412, 4369920, 19422, 6623180, 3277672, 1399561, 3859737, 2118186, 2108549, 5760665, 1119584, 549488, 4794489, 1079900, 7356305, 5654953, 5700314, 5268920, 2884855, 5260684, 2091905, 359251, 6026966, 6554070, 7913949, 876248, 777960, 8143293, 518909, 2608894, 8354570}; + +/************************************************* +* Name: ntt +* +* Description: Forward NTT, in-place. No modular reduction is performed after +* additions or subtractions. Hence output coefficients can be up +* to 16*Q larger than the coefficients of the input polynomial. +* Output vector is in bitreversed order. +* +* Arguments: - uint32_t p[N]: input/output coefficient array +**************************************************/ +void ntt(uint32_t p[N]) { + uint32_t len, start, j, k; + uint32_t zeta, t; + + k = 1; + for(len = 128; len > 0; len >>= 1) { + for(start = 0; start < N; start = j + len) { + zeta = zetas[k++]; + for(j = start; j < start + len; ++j) { + t = montgomery_reduce((uint64_t)zeta * p[j + len]); + p[j + len] = p[j] + 2*Q - t; + p[j] = p[j] + t; + } + } + } +} + +/************************************************* +* Name: invntt_frominvmont +* +* Description: Inverse NTT and multiplication by Montgomery factor 2^32. +* In-place. No modular reductions after additions or +* subtractions. Input coefficient need to be smaller than 2*Q. +* Output coefficient are smaller than 2*Q. +* +* Arguments: - uint32_t p[N]: input/output coefficient array +**************************************************/ +void invntt_frominvmont(uint32_t p[N]) { + uint32_t start, len, j, k; + uint32_t t, zeta; + const uint32_t f = (((uint64_t)MONT*MONT % Q) * (Q-1) % Q) * ((Q-1) >> 8) % Q; + + k = 0; + for(len = 1; len < N; len <<= 1) { + for(start = 0; start < N; start = j + len) { + zeta = zetas_inv[k++]; + for(j = start; j < start + len; ++j) { + t = p[j]; + p[j] = t + p[j + len]; + p[j + len] = t + 256*Q - p[j + len]; + p[j + len] = montgomery_reduce((uint64_t)zeta * p[j + len]); + } + } + } + + for(j = 0; j < N; ++j) { + p[j] = montgomery_reduce((uint64_t)f * p[j]); + } +} +//#include "params.h" +//#include "poly.h" +//#include "polyvec.h" +//#include "packing.h" + +/************************************************* +* Name: pack_pk +* +* Description: Bit-pack public key pk = (rho, t1). +* +* Arguments: - uint8_t pk[]: output byte array +* - const uint8_t rho[]: byte array containing rho +* - const polyveck *t1: pointer to vector t1 +**************************************************/ +void pack_pk(uint8_t pk[CRYPTO_PUBLICKEYBYTES], + const uint8_t rho[SEEDBYTES], + const polyveck *t1) +{ + uint32_t i; + + for(i = 0; i < SEEDBYTES; ++i) + pk[i] = rho[i]; + pk += SEEDBYTES; + + for(i = 0; i < K; ++i) + polyt1_pack(pk + i*POLT1_SIZE_PACKED, t1->vec+i); +} + +/************************************************* +* Name: unpack_pk +* +* Description: Unpack public key pk = (rho, t1). +* +* Arguments: - const uint8_t rho[]: output byte array for rho +* - const polyveck *t1: pointer to output vector t1 +* - uint8_t pk[]: byte array containing bit-packed pk +**************************************************/ +void unpack_pk(uint8_t rho[SEEDBYTES], + polyveck *t1, + const uint8_t pk[CRYPTO_PUBLICKEYBYTES]) +{ + uint32_t i; + + for(i = 0; i < SEEDBYTES; ++i) + rho[i] = pk[i]; + pk += SEEDBYTES; + + for(i = 0; i < K; ++i) + polyt1_unpack(t1->vec+i, pk + i*POLT1_SIZE_PACKED); +} + +/************************************************* +* Name: pack_sk +* +* Description: Bit-pack secret key sk = (rho, key, tr, s1, s2, t0). +* +* Arguments: - uint8_t sk[]: output byte array +* - const uint8_t rho[]: byte array containing rho +* - const uint8_t key[]: byte array containing key +* - const uint8_t tr[]: byte array containing tr +* - const polyvecl *s1: pointer to vector s1 +* - const polyveck *s2: pointer to vector s2 +* - const polyveck *t0: pointer to vector t0 +**************************************************/ +void pack_sk(uint8_t sk[CRYPTO_SECRETKEYBYTES], + const uint8_t rho[SEEDBYTES], + const uint8_t key[SEEDBYTES], + const uint8_t tr[CRHBYTES], + const polyvecl *s1, + const polyveck *s2, + const polyveck *t0) +{ + uint32_t i; + + for(i = 0; i < SEEDBYTES; ++i) + sk[i] = rho[i]; + sk += SEEDBYTES; + + for(i = 0; i < SEEDBYTES; ++i) + sk[i] = key[i]; + sk += SEEDBYTES; + + for(i = 0; i < CRHBYTES; ++i) + sk[i] = tr[i]; + sk += CRHBYTES; + + for(i = 0; i < L; ++i) + polyeta_pack(sk + i*POLETA_SIZE_PACKED, s1->vec+i); + sk += L*POLETA_SIZE_PACKED; + + for(i = 0; i < K; ++i) + polyeta_pack(sk + i*POLETA_SIZE_PACKED, s2->vec+i); + sk += K*POLETA_SIZE_PACKED; + + for(i = 0; i < K; ++i) + polyt0_pack(sk + i*POLT0_SIZE_PACKED, t0->vec+i); +} + +/************************************************* +* Name: unpack_sk +* +* Description: Unpack secret key sk = (rho, key, tr, s1, s2, t0). +* +* Arguments: - const uint8_t rho[]: output byte array for rho +* - const uint8_t key[]: output byte array for key +* - const uint8_t tr[]: output byte array for tr +* - const polyvecl *s1: pointer to output vector s1 +* - const polyveck *s2: pointer to output vector s2 +* - const polyveck *r0: pointer to output vector t0 +* - uint8_t sk[]: byte array containing bit-packed sk +**************************************************/ +void unpack_sk(uint8_t rho[SEEDBYTES], + uint8_t key[SEEDBYTES], + uint8_t tr[CRHBYTES], + polyvecl *s1, + polyveck *s2, + polyveck *t0, + const uint8_t sk[CRYPTO_SECRETKEYBYTES]) +{ + uint32_t i; + + for(i = 0; i < SEEDBYTES; ++i) + rho[i] = sk[i]; + sk += SEEDBYTES; + + for(i = 0; i < SEEDBYTES; ++i) + key[i] = sk[i]; + sk += SEEDBYTES; + + for(i = 0; i < CRHBYTES; ++i) + tr[i] = sk[i]; + sk += CRHBYTES; + + for(i=0; i < L; ++i) + polyeta_unpack(s1->vec+i, sk + i*POLETA_SIZE_PACKED); + sk += L*POLETA_SIZE_PACKED; + + for(i=0; i < K; ++i) + polyeta_unpack(s2->vec+i, sk + i*POLETA_SIZE_PACKED); + sk += K*POLETA_SIZE_PACKED; + + for(i=0; i < K; ++i) + polyt0_unpack(t0->vec+i, sk + i*POLT0_SIZE_PACKED); +} + +/************************************************* +* Name: pack_sig +* +* Description: Bit-pack signature sig = (z, h, c). +* +* Arguments: - uint8_t sig[]: output byte array +* - const polyvecl *z: pointer to vector z +* - const polyveck *h: pointer to hint vector h +* - const poly *c: pointer to challenge polynomial +**************************************************/ +void pack_sig(uint8_t sig[CRYPTO_BYTES], + const polyvecl *z, + const polyveck *h, + const poly *c) +{ + uint32_t i, j, k; + uint64_t signs, mask; + + for(i = 0; i < L; ++i) + polyz_pack(sig + i*POLZ_SIZE_PACKED, z->vec+i); + sig += L*POLZ_SIZE_PACKED; + + /* Encode h */ + k = 0; + for(i = 0; i < K; ++i) { + for(j = 0; j < N; ++j) + if(h->vec[i].coeffs[j] != 0) + sig[k++] = j; + + sig[OMEGA + i] = k; + } + while(k < OMEGA) sig[k++] = 0; + sig += OMEGA + K; + + /* Encode c */ + signs = 0; + mask = 1; + for(i = 0; i < N/8; ++i) { + sig[i] = 0; + for(j = 0; j < 8; ++j) { + if(c->coeffs[8*i+j] != 0) { + sig[i] |= (1U << j); + if(c->coeffs[8*i+j] == (Q - 1)) signs |= mask; + mask <<= 1; + } + } + } + sig += N/8; + for(i = 0; i < 8; ++i) + sig[i] = signs >> 8*i; +} + +/************************************************* +* Name: unpack_sig +* +* Description: Unpack signature sig = (z, h, c). +* +* Arguments: - polyvecl *z: pointer to output vector z +* - polyveck *h: pointer to output hint vector h +* - poly *c: pointer to output challenge polynomial +* - const uint8_t sig[]: byte array containing +* bit-packed signature +* +* Returns 1 in case of malformed signature; otherwise 0. +**************************************************/ +int unpack_sig(polyvecl *z, + polyveck *h, + poly *c, + const uint8_t sig[CRYPTO_BYTES]) +{ + uint32_t i, j, k; + uint64_t signs, mask; + + for(i = 0; i < L; ++i) + polyz_unpack(z->vec+i, sig + i*POLZ_SIZE_PACKED); + sig += L*POLZ_SIZE_PACKED; + + /* Decode h */ + k = 0; + for(i = 0; i < K; ++i) { + for(j = 0; j < N; ++j) + h->vec[i].coeffs[j] = 0; + + if(sig[OMEGA + i] < k || sig[OMEGA + i] > OMEGA) + return 1; + + for(j = k; j < sig[OMEGA + i]; ++j) { + /* Coefficients are ordered for strong unforgeability */ + if(j > k && sig[j] <= sig[j-1]) return 1; + h->vec[i].coeffs[sig[j]] = 1; + } + + k = sig[OMEGA + i]; + } + + /* Extra indices are zero for strong unforgeability */ + for(j = k; j < OMEGA; ++j) + if(sig[j]) + return 1; + + sig += OMEGA + K; + + /* Decode c */ + for(i = 0; i < N; ++i) + c->coeffs[i] = 0; + + signs = 0; + for(i = 0; i < 8; ++i) + signs |= (uint64_t)sig[N/8+i] << 8*i; + + /* Extra sign bits are zero for strong unforgeability */ + if(signs >> 60) + return 1; + + mask = 1; + for(i = 0; i < N/8; ++i) { + for(j = 0; j < 8; ++j) { + if((sig[i] >> j) & 0x01) { + c->coeffs[8*i+j] = (signs & mask) ? Q - 1 : 1; + mask <<= 1; + } + } + } + + return 0; +} +//#include +//#include "test/cpucycles.h" +//#include "fips202.h" +//#include "params.h" +//#include "reduce.h" +//#include "rounding.h" +//#include "ntt.h" +//#include "poly.h" + +#ifdef DBENCH +extern const uint64_t timing_overhead; +extern uint64_t *tred, *tadd, *tmul, *tround, *tsample, *tpack; +#endif + +/************************************************* +* Name: poly_reduce +* +* Description: Reduce all coefficients of input polynomial to representative +* in [0,2*Q[. +* +* Arguments: - poly *a: pointer to input/output polynomial +**************************************************/ +void poly_reduce(poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a->coeffs[i] = reduce32(a->coeffs[i]); + + DBENCH_STOP(*tred); +} + +/************************************************* +* Name: poly_csubq +* +* Description: For all coefficients of input polynomial subtract Q if +* coefficient is bigger than Q. +* +* Arguments: - poly *a: pointer to input/output polynomial +**************************************************/ +void poly_csubq(poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a->coeffs[i] = csubq(a->coeffs[i]); + + DBENCH_STOP(*tred); +} + +/************************************************* +* Name: poly_freeze +* +* Description: Reduce all coefficients of the polynomial to standard +* representatives. +* +* Arguments: - poly *a: pointer to input/output polynomial +**************************************************/ +void poly_freeze(poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a->coeffs[i] = freeze(a->coeffs[i]); + + DBENCH_STOP(*tred); +} + +/************************************************* +* Name: poly_add +* +* Description: Add polynomials. No modular reduction is performed. +* +* Arguments: - poly *c: pointer to output polynomial +* - const poly *a: pointer to first summand +* - const poly *b: pointer to second summand +**************************************************/ +void poly_add(poly *c, const poly *a, const poly *b) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + c->coeffs[i] = a->coeffs[i] + b->coeffs[i]; + + DBENCH_STOP(*tadd); +} + +/************************************************* +* Name: poly_sub +* +* Description: Subtract polynomials. Assumes coefficients of second input +* polynomial to be less than 2*Q. No modular reduction is +* performed. +* +* Arguments: - poly *c: pointer to output polynomial +* - const poly *a: pointer to first input polynomial +* - const poly *b: pointer to second input polynomial to be +* subtraced from first input polynomial +**************************************************/ +void poly_sub(poly *c, const poly *a, const poly *b) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + c->coeffs[i] = a->coeffs[i] + 2*Q - b->coeffs[i]; + + DBENCH_STOP(*tadd); +} + +/************************************************* +* Name: poly_neg +* +* Description: Negate polynomial. Assumes input coefficients to be standard +* representatives. +* +* Arguments: - poly *a: pointer to input/output polynomial +**************************************************/ +void poly_neg(poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a->coeffs[i] = Q - a->coeffs[i]; + + DBENCH_STOP(*tadd); +} + +/************************************************* +* Name: poly_shiftl +* +* Description: Multiply polynomial by 2^k without modular reduction. Assumes +* input coefficients to be less than 2^{32-k}. +* +* Arguments: - poly *a: pointer to input/output polynomial +* - uint32_t k: exponent +**************************************************/ +void poly_shiftl(poly *a, uint32_t k) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a->coeffs[i] <<= k; + + DBENCH_STOP(*tmul); +} + +/************************************************* +* Name: poly_ntt +* +* Description: Forward NTT. Output coefficients can be up to 16*Q larger than +* input coefficients. +* +* Arguments: - poly *a: pointer to input/output polynomial +**************************************************/ +void poly_ntt(poly *a) { + DBENCH_START(); + + ntt(a->coeffs); + + DBENCH_STOP(*tmul); +} + +/************************************************* +* Name: poly_invntt_montgomery +* +* Description: Inverse NTT and multiplication with 2^{32}. Input coefficients +* need to be less than 2*Q. Output coefficients are less than 2*Q. +* +* Arguments: - poly *a: pointer to input/output polynomial +**************************************************/ +void poly_invntt_montgomery(poly *a) { + DBENCH_START(); + + invntt_frominvmont(a->coeffs); + + DBENCH_STOP(*tmul); +} + +/************************************************* +* Name: poly_pointwise_invmontgomery +* +* Description: Pointwise multiplication of polynomials in NTT domain +* representation and multiplication of resulting polynomial +* with 2^{-32}. Output coefficients are less than 2*Q if input +* coefficient are less than 22*Q. +* +* Arguments: - poly *c: pointer to output polynomial +* - const poly *a: pointer to first input polynomial +* - const poly *b: pointer to second input polynomial +**************************************************/ +void poly_pointwise_invmontgomery(poly *c, const poly *a, const poly *b) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + c->coeffs[i] = montgomery_reduce((uint64_t)a->coeffs[i] * b->coeffs[i]); + + DBENCH_STOP(*tmul); +} + +/************************************************* +* Name: poly_power2round +* +* Description: For all coefficients c of the input polynomial, +* compute c0, c1 such that c mod Q = c1*2^D + c0 +* with -2^{D-1} < c0 <= 2^{D-1}. Assumes coefficients to be +* standard representatives. +* +* Arguments: - poly *a1: pointer to output polynomial with coefficients c1 +* - poly *a0: pointer to output polynomial with coefficients Q + a0 +* - const poly *v: pointer to input polynomial +**************************************************/ +void poly_power2round(poly *a1, poly *a0, const poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a1->coeffs[i] = power2round(a->coeffs[i], a0->coeffs+i); + + DBENCH_STOP(*tround); +} + +/************************************************* +* Name: poly_decompose +* +* Description: For all coefficients c of the input polynomial, +* compute high and low bits c0, c1 such c mod Q = c1*ALPHA + c0 +* with -ALPHA/2 < c0 <= ALPHA/2 except c1 = (Q-1)/ALPHA where we +* set c1 = 0 and -ALPHA/2 <= c0 = c mod Q - Q < 0. +* Assumes coefficients to be standard representatives. +* +* Arguments: - poly *a1: pointer to output polynomial with coefficients c1 +* - poly *a0: pointer to output polynomial with coefficients Q + a0 +* - const poly *c: pointer to input polynomial +**************************************************/ +void poly_decompose(poly *a1, poly *a0, const poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a1->coeffs[i] = decompose(a->coeffs[i], a0->coeffs+i); + + DBENCH_STOP(*tround); +} + +/************************************************* +* Name: poly_make_hint +* +* Description: Compute hint polynomial. The coefficients of which indicate +* whether the high bits of the corresponding coefficients +* of the first input polynomial and of the sum of the input +* polynomials differ. +* +* Arguments: - poly *h: pointer to output hint polynomial +* - const poly *a: pointer to first input polynomial +* - const poly *b: pointer to second input polynomial +* +* Returns number of 1 bits. +**************************************************/ +uint32_t poly_make_hint(poly *h, const poly *a, const poly *b) { + uint32_t i, s = 0; + DBENCH_START(); + + for(i = 0; i < N; ++i) { + h->coeffs[i] = make_hint(a->coeffs[i], b->coeffs[i]); + s += h->coeffs[i]; + } + + DBENCH_STOP(*tround); + return s; +} + +/************************************************* +* Name: poly_use_hint +* +* Description: Use hint polynomial to correct the high bits of a polynomial. +* +* Arguments: - poly *a: pointer to output polynomial with corrected high bits +* - const poly *b: pointer to input polynomial +* - const poly *h: pointer to input hint polynomial +**************************************************/ +void poly_use_hint(poly *a, const poly *b, const poly *h) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N; ++i) + a->coeffs[i] = use_hint(b->coeffs[i], h->coeffs[i]); + + DBENCH_STOP(*tround); +} + +/************************************************* +* Name: poly_chknorm +* +* Description: Check infinity norm of polynomial against given bound. +* Assumes input coefficients to be standard representatives. +* +* Arguments: - const poly *a: pointer to polynomial +* - uint32_t B: norm bound +* +* Returns 0 if norm is strictly smaller than B and 1 otherwise. +**************************************************/ +int poly_chknorm(const poly *a, uint32_t B) { + uint32_t i; + int32_t t; + DBENCH_START(); + + /* It is ok to leak which coefficient violates the bound since + the probability for each coefficient is independent of secret + data but we must not leak the sign of the centralized representative. */ + for(i = 0; i < N; ++i) { + /* Absolute value of centralized representative */ + t = (Q-1)/2 - a->coeffs[i]; + t ^= (t >> 31); + t = (Q-1)/2 - t; + + if((uint32_t)t >= B) { + DBENCH_STOP(*tsample); + return 1; + } + } + + DBENCH_STOP(*tsample); + return 0; +} + +/************************************************* +* Name: poly_uniform +* +* Description: Sample uniformly random polynomial using stream of random bytes. +* Assumes that enough random bytes are given (e.g. +* 5*SHAKE128_RATE bytes). +* +* Arguments: - poly *a: pointer to output polynomial +* - const uint8_t *buf: array of random bytes +**************************************************/ +void poly_uniform(poly *a, const uint8_t *buf) { + uint32_t ctr, pos; + uint32_t t; + DBENCH_START(); + + ctr = pos = 0; + while(ctr < N) { + t = buf[pos++]; + t |= (uint32_t)buf[pos++] << 8; + t |= (uint32_t)buf[pos++] << 16; + t &= 0x7FFFFF; + + if(t < Q) + a->coeffs[ctr++] = t; + } + + DBENCH_STOP(*tsample); +} + +/************************************************* +* Name: rej_eta +* +* Description: Sample uniformly random coefficients in [-ETA, ETA] by +* performing rejection sampling using array of random bytes. +* +* Arguments: - uint32_t *a: pointer to output array (allocated) +* - uint32_t len: number of coefficients to be sampled +* - const uint8_t *buf: array of random bytes +* - uint32_t buflen: length of array of random bytes +* +* Returns number of sampled coefficients. Can be smaller than len if not enough +* random bytes were given. +**************************************************/ +static uint32_t rej_eta(uint32_t *a, + uint32_t len, + const uint8_t *buf, + uint32_t buflen) +{ +#if ETA > 7 +#error "rej_eta() assumes ETA <= 7" +#endif + uint32_t ctr, pos; + uint8_t t0, t1; + DBENCH_START(); + + ctr = pos = 0; + while(ctr < len && pos < buflen) { +#if ETA <= 3 + t0 = buf[pos] & 0x07; + t1 = buf[pos++] >> 5; +#else + t0 = buf[pos] & 0x0F; + t1 = buf[pos++] >> 4; +#endif + + if(t0 <= 2*ETA) + a[ctr++] = Q + ETA - t0; + if(t1 <= 2*ETA && ctr < len) + a[ctr++] = Q + ETA - t1; + } + + DBENCH_STOP(*tsample); + return ctr; +} + +/************************************************* +* Name: poly_uniform_eta +* +* Description: Sample polynomial with uniformly random coefficients +* in [-ETA,ETA] by performing rejection sampling using the +* output stream from SHAKE256(seed|nonce). +* +* Arguments: - poly *a: pointer to output polynomial +* - const uint8_t seed[]: byte array with seed of length +* SEEDBYTES +* - uint8_t nonce: nonce byte +**************************************************/ +void poly_uniform_eta(poly *a, + const uint8_t seed[SEEDBYTES], + uint8_t nonce) +{ + uint32_t i, ctr; + uint8_t inbuf[SEEDBYTES + 1]; + /* Probability that we need more than 2 blocks: < 2^{-84} + Probability that we need more than 3 blocks: < 2^{-352} */ + uint8_t outbuf[2*SHAKE256_RATE]; + uint64_t state[25]; + + for(i= 0; i < SEEDBYTES; ++i) + inbuf[i] = seed[i]; + inbuf[SEEDBYTES] = nonce; + + shake256_absorb(state, inbuf, SEEDBYTES + 1); + shake256_squeezeblocks(outbuf, 2, state); + + ctr = rej_eta(a->coeffs, N, outbuf, 2*SHAKE256_RATE); + if(ctr < N) { + shake256_squeezeblocks(outbuf, 1, state); + rej_eta(a->coeffs + ctr, N - ctr, outbuf, SHAKE256_RATE); + } +} + +/************************************************* +* Name: rej_gamma1m1 +* +* Description: Sample uniformly random coefficients +* in [-(GAMMA1 - 1), GAMMA1 - 1] by performing rejection sampling +* using array of random bytes. +* +* Arguments: - uint32_t *a: pointer to output array (allocated) +* - uint32_t len: number of coefficients to be sampled +* - const uint8_t *buf: array of random bytes +* - uint32_t buflen: length of array of random bytes +* +* Returns number of sampled coefficients. Can be smaller than len if not enough +* random bytes were given. +**************************************************/ +static uint32_t rej_gamma1m1(uint32_t *a, + uint32_t len, + const uint8_t *buf, + uint32_t buflen) +{ +#if GAMMA1 > (1 << 19) +#error "rej_gamma1m1() assumes GAMMA1 - 1 fits in 19 bits" +#endif + uint32_t ctr, pos; + uint32_t t0, t1; + DBENCH_START(); + + ctr = pos = 0; + while(ctr < len && pos + 5 <= buflen) { + t0 = buf[pos]; + t0 |= (uint32_t)buf[pos + 1] << 8; + t0 |= (uint32_t)buf[pos + 2] << 16; + t0 &= 0xFFFFF; + + t1 = buf[pos + 2] >> 4; + t1 |= (uint32_t)buf[pos + 3] << 4; + t1 |= (uint32_t)buf[pos + 4] << 12; + + pos += 5; + + if(t0 <= 2*GAMMA1 - 2) + a[ctr++] = Q + GAMMA1 - 1 - t0; + if(t1 <= 2*GAMMA1 - 2 && ctr < len) + a[ctr++] = Q + GAMMA1 - 1 - t1; + } + + DBENCH_STOP(*tsample); + return ctr; +} + +/************************************************* +* Name: poly_uniform_gamma1m1 +* +* Description: Sample polynomial with uniformly random coefficients +* in [-(GAMMA1 - 1), GAMMA1 - 1] by performing rejection +* sampling on output stream of SHAKE256(seed|nonce). +* +* Arguments: - poly *a: pointer to output polynomial +* - const uint8_t seed[]: byte array with seed of length +* SEEDBYTES + CRHBYTES +* - uint16_t nonce: 16-bit nonce +**************************************************/ +void poly_uniform_gamma1m1(poly *a, + const uint8_t seed[SEEDBYTES + CRHBYTES], + uint16_t nonce) +{ + uint32_t i, ctr; + uint8_t inbuf[SEEDBYTES + CRHBYTES + 2]; + /* Probability that we need more than 5 blocks: < 2^{-81} + Probability that we need more than 6 blocks: < 2^{-467} */ + uint8_t outbuf[5*SHAKE256_RATE]; + uint64_t state[25]; + + for(i = 0; i < SEEDBYTES + CRHBYTES; ++i) + inbuf[i] = seed[i]; + inbuf[SEEDBYTES + CRHBYTES] = nonce & 0xFF; + inbuf[SEEDBYTES + CRHBYTES + 1] = nonce >> 8; + + shake256_absorb(state, inbuf, SEEDBYTES + CRHBYTES + 2); + shake256_squeezeblocks(outbuf, 5, state); + + ctr = rej_gamma1m1(a->coeffs, N, outbuf, 5*SHAKE256_RATE); + if(ctr < N) { + /* There are no bytes left in outbuf + since 5*SHAKE256_RATE is divisible by 5 */ + shake256_squeezeblocks(outbuf, 1, state); + rej_gamma1m1(a->coeffs + ctr, N - ctr, outbuf, SHAKE256_RATE); + } +} + +/************************************************* +* Name: polyeta_pack +* +* Description: Bit-pack polynomial with coefficients in [-ETA,ETA]. +* Input coefficients are assumed to lie in [Q-ETA,Q+ETA]. +* +* Arguments: - uint8_t *r: pointer to output byte array with at least +* POLETA_SIZE_PACKED bytes +* - const poly *a: pointer to input polynomial +**************************************************/ +void polyeta_pack(uint8_t *r, const poly *a) { +#if ETA > 7 +#error "polyeta_pack() assumes ETA <= 7" +#endif + uint32_t i; + uint8_t t[8]; + DBENCH_START(); + +#if ETA <= 3 + for(i = 0; i < N/8; ++i) { + t[0] = Q + ETA - a->coeffs[8*i+0]; + t[1] = Q + ETA - a->coeffs[8*i+1]; + t[2] = Q + ETA - a->coeffs[8*i+2]; + t[3] = Q + ETA - a->coeffs[8*i+3]; + t[4] = Q + ETA - a->coeffs[8*i+4]; + t[5] = Q + ETA - a->coeffs[8*i+5]; + t[6] = Q + ETA - a->coeffs[8*i+6]; + t[7] = Q + ETA - a->coeffs[8*i+7]; + + r[3*i+0] = t[0]; + r[3*i+0] |= t[1] << 3; + r[3*i+0] |= t[2] << 6; + r[3*i+1] = t[2] >> 2; + r[3*i+1] |= t[3] << 1; + r[3*i+1] |= t[4] << 4; + r[3*i+1] |= t[5] << 7; + r[3*i+2] = t[5] >> 1; + r[3*i+2] |= t[6] << 2; + r[3*i+2] |= t[7] << 5; + } +#else + for(i = 0; i < N/2; ++i) { + t[0] = Q + ETA - a->coeffs[2*i+0]; + t[1] = Q + ETA - a->coeffs[2*i+1]; + r[i] = t[0] | (t[1] << 4); + } +#endif + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyeta_unpack +* +* Description: Unpack polynomial with coefficients in [-ETA,ETA]. +* Output coefficients lie in [Q-ETA,Q+ETA]. +* +* Arguments: - poly *r: pointer to output polynomial +* - const uint8_t *a: byte array with bit-packed polynomial +**************************************************/ +void polyeta_unpack(poly *r, const uint8_t *a) { + uint32_t i; + DBENCH_START(); + +#if ETA <= 3 + for(i = 0; i < N/8; ++i) { + r->coeffs[8*i+0] = a[3*i+0] & 0x07; + r->coeffs[8*i+1] = (a[3*i+0] >> 3) & 0x07; + r->coeffs[8*i+2] = (a[3*i+0] >> 6) | ((a[3*i+1] & 0x01) << 2); + r->coeffs[8*i+3] = (a[3*i+1] >> 1) & 0x07; + r->coeffs[8*i+4] = (a[3*i+1] >> 4) & 0x07; + r->coeffs[8*i+5] = (a[3*i+1] >> 7) | ((a[3*i+2] & 0x03) << 1); + r->coeffs[8*i+6] = (a[3*i+2] >> 2) & 0x07; + r->coeffs[8*i+7] = (a[3*i+2] >> 5); + + r->coeffs[8*i+0] = Q + ETA - r->coeffs[8*i+0]; + r->coeffs[8*i+1] = Q + ETA - r->coeffs[8*i+1]; + r->coeffs[8*i+2] = Q + ETA - r->coeffs[8*i+2]; + r->coeffs[8*i+3] = Q + ETA - r->coeffs[8*i+3]; + r->coeffs[8*i+4] = Q + ETA - r->coeffs[8*i+4]; + r->coeffs[8*i+5] = Q + ETA - r->coeffs[8*i+5]; + r->coeffs[8*i+6] = Q + ETA - r->coeffs[8*i+6]; + r->coeffs[8*i+7] = Q + ETA - r->coeffs[8*i+7]; + } +#else + for(i = 0; i < N/2; ++i) { + r->coeffs[2*i+0] = a[i] & 0x0F; + r->coeffs[2*i+1] = a[i] >> 4; + r->coeffs[2*i+0] = Q + ETA - r->coeffs[2*i+0]; + r->coeffs[2*i+1] = Q + ETA - r->coeffs[2*i+1]; + } +#endif + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyt1_pack +* +* Description: Bit-pack polynomial t1 with coefficients fitting in 9 bits. +* Input coefficients are assumed to be standard representatives. +* +* Arguments: - uint8_t *r: pointer to output byte array with at least +* POLT1_SIZE_PACKED bytes +* - const poly *a: pointer to input polynomial +**************************************************/ +void polyt1_pack(uint8_t *r, const poly *a) { +#if D != 14 +#error "polyt1_pack() assumes D == 14" +#endif + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N/8; ++i) { + r[9*i+0] = a->coeffs[8*i+0] & 0xFF; + r[9*i+1] = (a->coeffs[8*i+0] >> 8) | ((a->coeffs[8*i+1] & 0x7F) << 1); + r[9*i+2] = (a->coeffs[8*i+1] >> 7) | ((a->coeffs[8*i+2] & 0x3F) << 2); + r[9*i+3] = (a->coeffs[8*i+2] >> 6) | ((a->coeffs[8*i+3] & 0x1F) << 3); + r[9*i+4] = (a->coeffs[8*i+3] >> 5) | ((a->coeffs[8*i+4] & 0x0F) << 4); + r[9*i+5] = (a->coeffs[8*i+4] >> 4) | ((a->coeffs[8*i+5] & 0x07) << 5); + r[9*i+6] = (a->coeffs[8*i+5] >> 3) | ((a->coeffs[8*i+6] & 0x03) << 6); + r[9*i+7] = (a->coeffs[8*i+6] >> 2) | ((a->coeffs[8*i+7] & 0x01) << 7); + r[9*i+8] = a->coeffs[8*i+7] >> 1; + } + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyt1_unpack +* +* Description: Unpack polynomial t1 with 9-bit coefficients. +* Output coefficients are standard representatives. +* +* Arguments: - poly *r: pointer to output polynomial +* - const uint8_t *a: byte array with bit-packed polynomial +**************************************************/ +void polyt1_unpack(poly *r, const uint8_t *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N/8; ++i) { + r->coeffs[8*i+0] = a[9*i+0] | ((uint32_t)(a[9*i+1] & 0x01) << 8); + r->coeffs[8*i+1] = (a[9*i+1] >> 1) | ((uint32_t)(a[9*i+2] & 0x03) << 7); + r->coeffs[8*i+2] = (a[9*i+2] >> 2) | ((uint32_t)(a[9*i+3] & 0x07) << 6); + r->coeffs[8*i+3] = (a[9*i+3] >> 3) | ((uint32_t)(a[9*i+4] & 0x0F) << 5); + r->coeffs[8*i+4] = (a[9*i+4] >> 4) | ((uint32_t)(a[9*i+5] & 0x1F) << 4); + r->coeffs[8*i+5] = (a[9*i+5] >> 5) | ((uint32_t)(a[9*i+6] & 0x3F) << 3); + r->coeffs[8*i+6] = (a[9*i+6] >> 6) | ((uint32_t)(a[9*i+7] & 0x7F) << 2); + r->coeffs[8*i+7] = (a[9*i+7] >> 7) | ((uint32_t)(a[9*i+8] & 0xFF) << 1); + } + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyt0_pack +* +* Description: Bit-pack polynomial t0 with coefficients in ]-2^{D-1}, 2^{D-1}]. +* Input coefficients are assumed to lie in ]Q-2^{D-1}, Q+2^{D-1}]. +* +* Arguments: - uint8_t *r: pointer to output byte array with at least +* POLT0_SIZE_PACKED bytes +* - const poly *a: pointer to input polynomial +**************************************************/ +void polyt0_pack(uint8_t *r, const poly *a) { + uint32_t i; + uint32_t t[4]; + DBENCH_START(); + + for(i = 0; i < N/4; ++i) { + t[0] = Q + (1 << (D-1)) - a->coeffs[4*i+0]; + t[1] = Q + (1 << (D-1)) - a->coeffs[4*i+1]; + t[2] = Q + (1 << (D-1)) - a->coeffs[4*i+2]; + t[3] = Q + (1 << (D-1)) - a->coeffs[4*i+3]; + + r[7*i+0] = t[0]; + r[7*i+1] = t[0] >> 8; + r[7*i+1] |= t[1] << 6; + r[7*i+2] = t[1] >> 2; + r[7*i+3] = t[1] >> 10; + r[7*i+3] |= t[2] << 4; + r[7*i+4] = t[2] >> 4; + r[7*i+5] = t[2] >> 12; + r[7*i+5] |= t[3] << 2; + r[7*i+6] = t[3] >> 6; + } + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyt0_unpack +* +* Description: Unpack polynomial t0 with coefficients in ]-2^{D-1}, 2^{D-1}]. +* Output coefficients lie in ]Q-2^{D-1},Q+2^{D-1}]. +* +* Arguments: - poly *r: pointer to output polynomial +* - const uint8_t *a: byte array with bit-packed polynomial +**************************************************/ +void polyt0_unpack(poly *r, const uint8_t *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N/4; ++i) { + r->coeffs[4*i+0] = a[7*i+0]; + r->coeffs[4*i+0] |= (uint32_t)(a[7*i+1] & 0x3F) << 8; + + r->coeffs[4*i+1] = a[7*i+1] >> 6; + r->coeffs[4*i+1] |= (uint32_t)a[7*i+2] << 2; + r->coeffs[4*i+1] |= (uint32_t)(a[7*i+3] & 0x0F) << 10; + + r->coeffs[4*i+2] = a[7*i+3] >> 4; + r->coeffs[4*i+2] |= (uint32_t)a[7*i+4] << 4; + r->coeffs[4*i+2] |= (uint32_t)(a[7*i+5] & 0x03) << 12; + + r->coeffs[4*i+3] = a[7*i+5] >> 2; + r->coeffs[4*i+3] |= (uint32_t)a[7*i+6] << 6; + + r->coeffs[4*i+0] = Q + (1 << (D-1)) - r->coeffs[4*i+0]; + r->coeffs[4*i+1] = Q + (1 << (D-1)) - r->coeffs[4*i+1]; + r->coeffs[4*i+2] = Q + (1 << (D-1)) - r->coeffs[4*i+2]; + r->coeffs[4*i+3] = Q + (1 << (D-1)) - r->coeffs[4*i+3]; + } + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyz_pack +* +* Description: Bit-pack polynomial z with coefficients +* in [-(GAMMA1 - 1), GAMMA1 - 1]. +* Input coefficients are assumed to be standard representatives. +* +* Arguments: - uint8_t *r: pointer to output byte array with at least +* POLZ_SIZE_PACKED bytes +* - const poly *a: pointer to input polynomial +**************************************************/ +void polyz_pack(uint8_t *r, const poly *a) { +#if GAMMA1 > (1 << 19) +#error "polyz_pack() assumes GAMMA1 <= 2^{19}" +#endif + uint32_t i; + uint32_t t[2]; + DBENCH_START(); + + for(i = 0; i < N/2; ++i) { + /* Map to {0,...,2*GAMMA1 - 2} */ + t[0] = GAMMA1 - 1 - a->coeffs[2*i+0]; + t[0] += ((int32_t)t[0] >> 31) & Q; + t[1] = GAMMA1 - 1 - a->coeffs[2*i+1]; + t[1] += ((int32_t)t[1] >> 31) & Q; + + r[5*i+0] = t[0]; + r[5*i+1] = t[0] >> 8; + r[5*i+2] = t[0] >> 16; + r[5*i+2] |= t[1] << 4; + r[5*i+3] = t[1] >> 4; + r[5*i+4] = t[1] >> 12; + } + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyz_unpack +* +* Description: Unpack polynomial z with coefficients +* in [-(GAMMA1 - 1), GAMMA1 - 1]. +* Output coefficients are standard representatives. +* +* Arguments: - poly *r: pointer to output polynomial +* - const uint8_t *a: byte array with bit-packed polynomial +**************************************************/ +void polyz_unpack(poly *r, const uint8_t *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N/2; ++i) { + r->coeffs[2*i+0] = a[5*i+0]; + r->coeffs[2*i+0] |= (uint32_t)a[5*i+1] << 8; + r->coeffs[2*i+0] |= (uint32_t)(a[5*i+2] & 0x0F) << 16; + + r->coeffs[2*i+1] = a[5*i+2] >> 4; + r->coeffs[2*i+1] |= (uint32_t)a[5*i+3] << 4; + r->coeffs[2*i+1] |= (uint32_t)a[5*i+4] << 12; + + r->coeffs[2*i+0] = GAMMA1 - 1 - r->coeffs[2*i+0]; + r->coeffs[2*i+0] += ((int32_t)r->coeffs[2*i+0] >> 31) & Q; + r->coeffs[2*i+1] = GAMMA1 - 1 - r->coeffs[2*i+1]; + r->coeffs[2*i+1] += ((int32_t)r->coeffs[2*i+1] >> 31) & Q; + } + + DBENCH_STOP(*tpack); +} + +/************************************************* +* Name: polyw1_pack +* +* Description: Bit-pack polynomial w1 with coefficients in [0, 15]. +* Input coefficients are assumed to be standard representatives. +* +* Arguments: - uint8_t *r: pointer to output byte array with at least +* POLW1_SIZE_PACKED bytes +* - const poly *a: pointer to input polynomial +**************************************************/ +void polyw1_pack(uint8_t *r, const poly *a) { + uint32_t i; + DBENCH_START(); + + for(i = 0; i < N/2; ++i) + r[i] = a->coeffs[2*i+0] | (a->coeffs[2*i+1] << 4); + + DBENCH_STOP(*tpack); +} +//#include +//#include "params.h" +//#include "poly.h" +//#include "polyvec.h" + +/**************************************************************/ +/************ Vectors of polynomials of length L **************/ +/**************************************************************/ + +/************************************************* +* Name: polyvecl_freeze +* +* Description: Reduce coefficients of polynomials in vector of length L +* to standard representatives. +* +* Arguments: - polyvecl *v: pointer to input/output vector +**************************************************/ +void polyvecl_freeze(polyvecl *v) { + uint32_t i; + + for(i = 0; i < L; ++i) + poly_freeze(v->vec+i); +} + +/************************************************* +* Name: polyvecl_add +* +* Description: Add vectors of polynomials of length L. +* No modular reduction is performed. +* +* Arguments: - polyvecl *w: pointer to output vector +* - const polyvecl *u: pointer to first summand +* - const polyvecl *v: pointer to second summand +**************************************************/ +void polyvecl_add(polyvecl *w, const polyvecl *u, const polyvecl *v) { + uint32_t i; + + for(i = 0; i < L; ++i) + poly_add(w->vec+i, u->vec+i, v->vec+i); +} + +/************************************************* +* Name: polyvecl_ntt +* +* Description: Forward NTT of all polynomials in vector of length L. Output +* coefficients can be up to 16*Q larger than input coefficients. +* +* Arguments: - polyvecl *v: pointer to input/output vector +**************************************************/ +void polyvecl_ntt(polyvecl *v) { + uint32_t i; + + for(i = 0; i < L; ++i) + poly_ntt(v->vec+i); +} + +/************************************************* +* Name: polyvecl_pointwise_acc_invmontgomery +* +* Description: Pointwise multiply vectors of polynomials of length L, multiply +* resulting vector by 2^{-32} and add (accumulate) polynomials +* in it. Input/output vectors are in NTT domain representation. +* Input coefficients are assumed to be less than 22*Q. Output +* coeffcient are less than 2*L*Q. +* +* Arguments: - poly *w: output polynomial +* - const polyvecl *u: pointer to first input vector +* - const polyvecl *v: pointer to second input vector +**************************************************/ +void polyvecl_pointwise_acc_invmontgomery(poly *w, + const polyvecl *u, + const polyvecl *v) +{ + uint32_t i; + poly t; + + poly_pointwise_invmontgomery(w, u->vec+0, v->vec+0); + + for(i = 1; i < L; ++i) { + poly_pointwise_invmontgomery(&t, u->vec+i, v->vec+i); + poly_add(w, w, &t); + } +} + +/************************************************* +* Name: polyvecl_chknorm +* +* Description: Check infinity norm of polynomials in vector of length L. +* Assumes input coefficients to be standard representatives. +* +* Arguments: - const polyvecl *v: pointer to vector +* - uint32_t B: norm bound +* +* Returns 0 if norm of all polynomials is strictly smaller than B and 1 +* otherwise. +**************************************************/ +int polyvecl_chknorm(const polyvecl *v, uint32_t bound) { + uint32_t i; + int ret = 0; + + for(i = 0; i < L; ++i) + ret |= poly_chknorm(v->vec+i, bound); + + return ret; +} + +/**************************************************************/ +/************ Vectors of polynomials of length K **************/ +/**************************************************************/ + + +/************************************************* +* Name: polyveck_reduce +* +* Description: Reduce coefficients of polynomials in vector of length K +* to representatives in [0,2*Q[. +* +* Arguments: - polyveck *v: pointer to input/output vector +**************************************************/ +void polyveck_reduce(polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_reduce(v->vec+i); +} + +/************************************************* +* Name: polyveck_csubq +* +* Description: For all coefficients of polynomials in vector of length K +* subtract Q if coefficient is bigger than Q. +* +* Arguments: - polyveck *v: pointer to input/output vector +**************************************************/ +void polyveck_csubq(polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_csubq(v->vec+i); +} + +/************************************************* +* Name: polyveck_freeze +* +* Description: Reduce coefficients of polynomials in vector of length K +* to standard representatives. +* +* Arguments: - polyveck *v: pointer to input/output vector +**************************************************/ +void polyveck_freeze(polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_freeze(v->vec+i); +} + +/************************************************* +* Name: polyveck_add +* +* Description: Add vectors of polynomials of length K. +* No modular reduction is performed. +* +* Arguments: - polyveck *w: pointer to output vector +* - const polyveck *u: pointer to first summand +* - const polyveck *v: pointer to second summand +**************************************************/ +void polyveck_add(polyveck *w, const polyveck *u, const polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_add(w->vec+i, u->vec+i, v->vec+i); +} + +/************************************************* +* Name: polyveck_sub +* +* Description: Subtract vectors of polynomials of length K. +* Assumes coefficients of polynomials in second input vector +* to be less than 2*Q. No modular reduction is performed. +* +* Arguments: - polyveck *w: pointer to output vector +* - const polyveck *u: pointer to first input vector +* - const polyveck *v: pointer to second input vector to be +* subtracted from first input vector +**************************************************/ +void polyveck_sub(polyveck *w, const polyveck *u, const polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_sub(w->vec+i, u->vec+i, v->vec+i); +} + +/************************************************* +* Name: polyveck_shiftl +* +* Description: Multiply vector of polynomials of Length K by 2^k without modular +* reduction. Assumes input coefficients to be less than 2^{32-k}. +* +* Arguments: - polyveck *v: pointer to input/output vector +* - uint32_t k: exponent +**************************************************/ +void polyveck_shiftl(polyveck *v, uint32_t k) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_shiftl(v->vec+i, k); +} + +/************************************************* +* Name: polyveck_ntt +* +* Description: Forward NTT of all polynomials in vector of length K. Output +* coefficients can be up to 16*Q larger than input coefficients. +* +* Arguments: - polyveck *v: pointer to input/output vector +**************************************************/ +void polyveck_ntt(polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_ntt(v->vec+i); +} + +/************************************************* +* Name: polyveck_invntt_montgomery +* +* Description: Inverse NTT and multiplication by 2^{32} of polynomials +* in vector of length K. Input coefficients need to be less +* than 2*Q. +* +* Arguments: - polyveck *v: pointer to input/output vector +**************************************************/ +void polyveck_invntt_montgomery(polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_invntt_montgomery(v->vec+i); +} + +/************************************************* +* Name: polyveck_chknorm +* +* Description: Check infinity norm of polynomials in vector of length K. +* Assumes input coefficients to be standard representatives. +* +* Arguments: - const polyveck *v: pointer to vector +* - uint32_t B: norm bound +* +* Returns 0 if norm of all polynomials are strictly smaller than B and 1 +* otherwise. +**************************************************/ +int polyveck_chknorm(const polyveck *v, uint32_t bound) { + uint32_t i; + int ret = 0; + + for(i = 0; i < K; ++i) + ret |= poly_chknorm(v->vec+i, bound); + + return ret; +} + +/************************************************* +* Name: polyveck_power2round +* +* Description: For all coefficients a of polynomials in vector of length K, +* compute a0, a1 such that a mod Q = a1*2^D + a0 +* with -2^{D-1} < a0 <= 2^{D-1}. Assumes coefficients to be +* standard representatives. +* +* Arguments: - polyveck *v1: pointer to output vector of polynomials with +* coefficients a1 +* - polyveck *v0: pointer to output vector of polynomials with +* coefficients Q + a0 +* - const polyveck *v: pointer to input vector +**************************************************/ +void polyveck_power2round(polyveck *v1, polyveck *v0, const polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_power2round(v1->vec+i, v0->vec+i, v->vec+i); +} + +/************************************************* +* Name: polyveck_decompose +* +* Description: For all coefficients a of polynomials in vector of length K, +* compute high and low bits a0, a1 such a mod Q = a1*ALPHA + a0 +* with -ALPHA/2 < a0 <= ALPHA/2 except a1 = (Q-1)/ALPHA where we +* set a1 = 0 and -ALPHA/2 <= a0 = a mod Q - Q < 0. +* Assumes coefficients to be standard representatives. +* +* Arguments: - polyveck *v1: pointer to output vector of polynomials with +* coefficients a1 +* - polyveck *v0: pointer to output vector of polynomials with +* coefficients Q + a0 +* - const polyveck *v: pointer to input vector +**************************************************/ +void polyveck_decompose(polyveck *v1, polyveck *v0, const polyveck *v) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_decompose(v1->vec+i, v0->vec+i, v->vec+i); +} + +/************************************************* +* Name: polyveck_make_hint +* +* Description: Compute hint vector. +* +* Arguments: - polyveck *h: pointer to output vector +* - const polyveck *u: pointer to first input vector +* - const polyveck *u: pointer to second input vector +* +* Returns number of 1 bits. +**************************************************/ +uint32_t polyveck_make_hint(polyveck *h, + const polyveck *u, + const polyveck *v) +{ + uint32_t i, s = 0; + + for(i = 0; i < K; ++i) + s += poly_make_hint(h->vec+i, u->vec+i, v->vec+i); + + return s; +} + +/************************************************* +* Name: polyveck_use_hint +* +* Description: Use hint vector to correct the high bits of input vector. +* +* Arguments: - polyveck *w: pointer to output vector of polynomials with +* corrected high bits +* - const polyveck *u: pointer to input vector +* - const polyveck *h: pointer to input hint vector +**************************************************/ +void polyveck_use_hint(polyveck *w, const polyveck *u, const polyveck *h) { + uint32_t i; + + for(i = 0; i < K; ++i) + poly_use_hint(w->vec+i, u->vec+i, h->vec+i); +} +//#include +//#include "params.h" +//#include "reduce.h" + +/************************************************* +* Name: montgomery_reduce +* +* Description: For finite field element a with 0 <= a <= Q*2^32, +* compute r \equiv a*2^{-32} (mod Q) such that 0 <= r < 2*Q. +* +* Arguments: - uint64_t: finite field element a +* +* Returns r. +**************************************************/ +uint32_t montgomery_reduce(uint64_t a) { + uint64_t t; + + t = a * QINV; + t &= (1ULL << 32) - 1; + t *= Q; + t = a + t; + t >>= 32; + return t; +} + +/************************************************* +* Name: reduce32 +* +* Description: For finite field element a, compute r \equiv a (mod Q) +* such that 0 <= r < 2*Q. +* +* Arguments: - uint32_t: finite field element a +* +* Returns r. +**************************************************/ +uint32_t reduce32(uint32_t a) { + uint32_t t; + + t = a & 0x7FFFFF; + a >>= 23; + t += (a << 13) - a; + return t; +} + +/************************************************* +* Name: csubq +* +* Description: Subtract Q if input coefficient is bigger than Q. +* +* Arguments: - uint32_t: finite field element a +* +* Returns r. +**************************************************/ +uint32_t csubq(uint32_t a) { + a -= Q; + a += ((int32_t)a >> 31) & Q; + return a; +} + +/************************************************* +* Name: freeze +* +* Description: For finite field element a, compute standard +* representative r = a mod Q. +* +* Arguments: - uint32_t: finite field element a +* +* Returns r. +**************************************************/ +uint32_t freeze(uint32_t a) { + a = reduce32(a); + a = csubq(a); + return a; +} +//#include +//#include "params.h" + +/************************************************* +* Name: power2round +* +* Description: For finite field element a, compute a0, a1 such that +* a mod Q = a1*2^D + a0 with -2^{D-1} < a0 <= 2^{D-1}. +* Assumes a to be standard representative. +* +* Arguments: - uint32_t a: input element +* - uint32_t *a0: pointer to output element Q + a0 +* +* Returns a1. +**************************************************/ +uint32_t power2round(uint32_t a, uint32_t *a0) { + int32_t t; + + /* Centralized remainder mod 2^D */ + t = a & ((1 << D) - 1); + t -= (1 << (D-1)) + 1; + t += (t >> 31) & (1 << D); + t -= (1 << (D-1)) - 1; + *a0 = Q + t; + a = (a - t) >> D; + return a; +} + +/************************************************* +* Name: decompose +* +* Description: For finite field element a, compute high and low bits a0, a1 such +* that a mod Q = a1*ALPHA + a0 with -ALPHA/2 < a0 <= ALPHA/2 except +* if a1 = (Q-1)/ALPHA where we set a1 = 0 and +* -ALPHA/2 <= a0 = a mod Q - Q < 0. Assumes a to be standard +* representative. +* +* Arguments: - uint32_t a: input element +* - uint32_t *a0: pointer to output element Q + a0 +* +* Returns a1. +**************************************************/ +uint32_t decompose(uint32_t a, uint32_t *a0) { +#if ALPHA != (Q-1)/16 +#error "decompose assumes ALPHA == (Q-1)/16" +#endif + int32_t t, u; + + /* Centralized remainder mod ALPHA */ + t = a & 0x7FFFF; + t += (a >> 19) << 9; + t -= ALPHA/2 + 1; + t += (t >> 31) & ALPHA; + t -= ALPHA/2 - 1; + a -= t; + + /* Divide by ALPHA (possible to avoid) */ + u = a - 1; + u >>= 31; + a = (a >> 19) + 1; + a -= u & 1; + + /* Border case */ + *a0 = Q + t - (a >> 4); + a &= 0xF; + return a; +} + +/************************************************* +* Name: make_hint +* +* Description: Compute hint bit indicating whether or not high bits of two +* finite field elements differ. Assumes input elements to be +* standard representatives. +* +* Arguments: - uint32_t a: first input element +* - uint32_t b: second input element +* +* Returns 1 if high bits of a and b differ and 0 otherwise. +**************************************************/ +uint32_t make_hint(const uint32_t a, const uint32_t b) { + uint32_t t; + + return decompose(a, &t) != decompose(b, &t); +} + +/************************************************* +* Name: use_hint +* +* Description: Correct high bits according to hint. +* +* Arguments: - uint32_t a: input element +* - uint32_t hint: hint bit +* +* Returns corrected high bits. +**************************************************/ +uint32_t use_hint(const uint32_t a, const uint32_t hint) { + uint32_t a0, a1; + + a1 = decompose(a, &a0); + if(hint == 0) + return a1; + else if(a0 > Q) + return (a1 + 1) & 0xF; + else + return (a1 - 1) & 0xF; + + /* If decompose does not divide out ALPHA: + if(hint == 0) + return a1; + else if(a0 > Q) + return (a1 + ALPHA) % (Q - 1); + else + return (a1 - ALPHA) % (Q - 1); + */ +} +//#include +//#include "params.h" +//#include "sign.h" +//#include "randombytes.h" +//#include "fips202.h" +//#include "poly.h" +//#include "polyvec.h" +//#include "packing.h" +#ifdef STANDALONE +#ifdef _WIN32 +#include +void randombytes(unsigned char *x,long xlen) +{ + HCRYPTPROV prov = 0; + CryptAcquireContextW(&prov, NULL, NULL,PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT); + CryptGenRandom(prov, xlen, x); + CryptReleaseContext(prov, 0); +} +#else +#include +#include +#include +void randombytes(unsigned char *x,long xlen) +{ + static int fd = -1; + int32_t i; + if (fd == -1) { + for (;;) { + fd = open("/dev/urandom",O_RDONLY); + if (fd != -1) break; + sleep(1); + } + } + while (xlen > 0) { + if (xlen < 1048576) i = (int32_t)xlen; else i = 1048576; + i = (int32_t)read(fd,x,i); + if (i < 1) { + sleep(1); + continue; + } + if ( 0 ) + { + int32_t j; + for (j=0; j %p\n",x); + } + x += i; + xlen -= i; + } +} +#endif +#endif + +/************************************************* +* Name: expand_mat +* +* Description: Implementation of ExpandA. Generates matrix A with uniformly +* random coefficients a_{i,j} by performing rejection +* sampling on the output stream of SHAKE128(rho|i|j). +* +* Arguments: - polyvecl mat[K]: output matrix +* - const uint8_t rho[]: byte array containing seed rho +**************************************************/ +void expand_mat(polyvecl mat[K], const uint8_t rho[SEEDBYTES]) { + uint32_t i, j; + uint8_t inbuf[SEEDBYTES + 1]; + /* Don't change this to smaller values, + * sampling later assumes sufficient SHAKE output! + * Probability that we need more than 5 blocks: < 2^{-132}. + * Probability that we need more than 6 blocks: < 2^{-546}. */ + uint8_t outbuf[5*SHAKE128_RATE]; + + for(i = 0; i < SEEDBYTES; ++i) + inbuf[i] = rho[i]; + + for(i = 0; i < K; ++i) { + for(j = 0; j < L; ++j) { + inbuf[SEEDBYTES] = i + (j << 4); + shake128(outbuf, sizeof(outbuf), inbuf, SEEDBYTES + 1); + poly_uniform(mat[i].vec+j, outbuf); + } + } +} + +/************************************************* +* Name: challenge +* +* Description: Implementation of H. Samples polynomial with 60 nonzero +* coefficients in {-1,1} using the output stream of +* SHAKE256(mu|w1). +* +* Arguments: - poly *c: pointer to output polynomial +* - const uint8_t mu[]: byte array containing mu +* - const polyveck *w1: pointer to vector w1 +**************************************************/ +void challenge(poly *c, + const uint8_t mu[CRHBYTES], + const polyveck *w1) +{ + uint32_t i, b, pos; + uint8_t inbuf[CRHBYTES + K*POLW1_SIZE_PACKED]; + uint8_t outbuf[SHAKE256_RATE]; + uint64_t state[25], signs, mask; + + for(i = 0; i < CRHBYTES; ++i) + inbuf[i] = mu[i]; + for(i = 0; i < K; ++i) + polyw1_pack(inbuf + CRHBYTES + i*POLW1_SIZE_PACKED, w1->vec+i); + + shake256_absorb(state, inbuf, sizeof(inbuf)); + shake256_squeezeblocks(outbuf, 1, state); + + signs = 0; + for(i = 0; i < 8; ++i) + signs |= (uint64_t)outbuf[i] << 8*i; + + pos = 8; + mask = 1; + + for(i = 0; i < N; ++i) + c->coeffs[i] = 0; + + for(i = 196; i < 256; ++i) { + do { + if(pos >= SHAKE256_RATE) { + shake256_squeezeblocks(outbuf, 1, state); + pos = 0; + } + + b = outbuf[pos++]; + } while(b > i); + + c->coeffs[i] = c->coeffs[b]; + c->coeffs[b] = (signs & mask) ? Q - 1 : 1; + mask <<= 1; + } +} + +/************************************************* +* Name: dilithium_keypair +* +* Description: Generates public and private key. +* +* Arguments: - uint8_t *pk: pointer to output public key (allocated +* array of CRYPTO_PUBLICKEYBYTES bytes) +* - uint8_t *sk: pointer to output private key (allocated +* array of CRYPTO_SECRETKEYBYTES bytes) +* +* Returns 0 (success) +**************************************************/ +int dilithium_keypair(uint8_t *pk, uint8_t *sk) { + uint32_t i; + uint8_t seedbuf[3*SEEDBYTES]; + uint8_t tr[CRHBYTES]; + uint8_t *rho, *rhoprime, *key; + uint16_t nonce = 0; + polyvecl mat[K]; + polyvecl s1, s1hat; + polyveck s2, t, t1, t0; + + /* Expand 32 bytes of randomness into rho, rhoprime and key */ + randombytes(seedbuf, SEEDBYTES); + shake256(seedbuf, 3*SEEDBYTES, seedbuf, SEEDBYTES); + rho = seedbuf; + rhoprime = rho + SEEDBYTES; + key = rho + 2*SEEDBYTES; + + /* Expand matrix */ + expand_mat(mat, rho); + + /* Sample short vectors s1 and s2 */ + for(i = 0; i < L; ++i) + poly_uniform_eta(s1.vec+i, rhoprime, nonce++); + for(i = 0; i < K; ++i) + poly_uniform_eta(s2.vec+i, rhoprime, nonce++); + + /* Matrix-vector multiplication */ + s1hat = s1; + polyvecl_ntt(&s1hat); + for(i = 0; i < K; ++i) { + polyvecl_pointwise_acc_invmontgomery(t.vec+i, mat+i, &s1hat); + poly_reduce(t.vec+i); + poly_invntt_montgomery(t.vec+i); + } + + /* Add noise vector s2 */ + polyveck_add(&t, &t, &s2); + + /* Extract t1 and write public key */ + polyveck_freeze(&t); + polyveck_power2round(&t1, &t0, &t); + pack_pk(pk, rho, &t1); + + /* Compute CRH(rho, t1) and write secret key */ + shake256(tr, CRHBYTES, pk, CRYPTO_PUBLICKEYBYTES); + pack_sk(sk, rho, key, tr, &s1, &s2, &t0); + + return 0; +} + +/************************************************* +* Name: dilithium_sign +* +* Description: Compute signed message. +* +* Arguments: - uint8_t *sm: pointer to output signed message (allocated +* array with CRYPTO_BYTES + mlen bytes), +* can be equal to m +* - int32_t *smlen: pointer to output length of signed +* message +* - const uint8_t *m: pointer to message to be signed +* - int32_t mlen: length of message +* - const uint8_t *sk: pointer to bit-packed secret key +* +* Returns 0 (success) +**************************************************/ +int dilithium_sign(uint8_t *sm, + int32_t *smlen, + const uint8_t *m, + int32_t mlen, + const uint8_t *sk) +{ + int32_t i, j; + uint32_t n; + uint8_t seedbuf[2*SEEDBYTES + CRHBYTES]; // TODO: nonce in seedbuf (2x) + uint8_t tr[CRHBYTES]; + uint8_t *rho, *key, *mu; + uint16_t nonce = 0; + poly c, chat; + polyvecl mat[K], s1, y, yhat, z; + polyveck s2, t0, w, w1; + polyveck h, wcs2, wcs20, ct0, tmp; + + rho = seedbuf; + key = seedbuf + SEEDBYTES; + mu = seedbuf + 2*SEEDBYTES; + unpack_sk(rho, key, tr, &s1, &s2, &t0, sk); + + /* Copy tr and message into the sm buffer, + * backwards since m and sm can be equal in SUPERCOP API */ + for(i = 1; i <= mlen; ++i) + sm[CRYPTO_BYTES + mlen - i] = m[mlen - i]; + for(i = 0; i < CRHBYTES; ++i) + sm[CRYPTO_BYTES - CRHBYTES + i] = tr[i]; + + /* Compute CRH(tr, msg) */ + shake256(mu, CRHBYTES, sm + CRYPTO_BYTES - CRHBYTES, CRHBYTES + mlen); + + /* Expand matrix and transform vectors */ + expand_mat(mat, rho); + polyvecl_ntt(&s1); + polyveck_ntt(&s2); + polyveck_ntt(&t0); + + rej: + /* Sample intermediate vector y */ + for(i = 0; i < L; ++i) + poly_uniform_gamma1m1(y.vec+i, key, nonce++); + + /* Matrix-vector multiplication */ + yhat = y; + polyvecl_ntt(&yhat); + for(i = 0; i < K; ++i) { + polyvecl_pointwise_acc_invmontgomery(w.vec+i, mat+i, &yhat); + poly_reduce(w.vec+i); + poly_invntt_montgomery(w.vec+i); + } + + /* Decompose w and call the random oracle */ + polyveck_csubq(&w); + polyveck_decompose(&w1, &tmp, &w); + challenge(&c, mu, &w1); + + /* Compute z, reject if it reveals secret */ + chat = c; + poly_ntt(&chat); + for(i = 0; i < L; ++i) { + poly_pointwise_invmontgomery(z.vec+i, &chat, s1.vec+i); + poly_invntt_montgomery(z.vec+i); + } + polyvecl_add(&z, &z, &y); + polyvecl_freeze(&z); + if(polyvecl_chknorm(&z, GAMMA1 - BETA)) + goto rej; + + /* Compute w - cs2, reject if w1 can not be computed from it */ + for(i = 0; i < K; ++i) { + poly_pointwise_invmontgomery(wcs2.vec+i, &chat, s2.vec+i); + poly_invntt_montgomery(wcs2.vec+i); + } + polyveck_sub(&wcs2, &w, &wcs2); + polyveck_freeze(&wcs2); + polyveck_decompose(&tmp, &wcs20, &wcs2); + polyveck_csubq(&wcs20); + if(polyveck_chknorm(&wcs20, GAMMA2 - BETA)) + goto rej; + + for(i = 0; i < K; ++i) + for(j = 0; j < N; ++j) + if(tmp.vec[i].coeffs[j] != w1.vec[i].coeffs[j]) + goto rej; + + /* Compute hints for w1 */ + for(i = 0; i < K; ++i) { + poly_pointwise_invmontgomery(ct0.vec+i, &chat, t0.vec+i); + poly_invntt_montgomery(ct0.vec+i); + } + + polyveck_csubq(&ct0); + if(polyveck_chknorm(&ct0, GAMMA2)) + goto rej; + + polyveck_add(&tmp, &wcs2, &ct0); + polyveck_csubq(&tmp); + n = polyveck_make_hint(&h, &wcs2, &tmp); + if(n > OMEGA) + goto rej; + + /* Write signature */ + pack_sig(sm, &z, &h, &c); + + *smlen = mlen + CRYPTO_BYTES; + return 0; +} + +/************************************************* +* Name: dilithium_verify +* +* Description: Verify signed message. +* +* Arguments: - uint8_t *m: pointer to output message (allocated +* array with smlen bytes), can be equal to sm +* - int32_t *mlen: pointer to output length of message +* - const uint8_t *sm: pointer to signed message +* - int32_t smlen: length of signed message +* - const uint8_t *pk: pointer to bit-packed public key +* +* Returns 0 if signed message could be verified correctly and -1 otherwise +**************************************************/ +int dilithium_verify(uint8_t *m, + int32_t *mlen, + const uint8_t *sm, + int32_t smlen, + const uint8_t *pk) +{ + int32_t i; + uint8_t rho[SEEDBYTES]; + uint8_t mu[CRHBYTES]; + poly c, chat, cp; + polyvecl mat[K], z; + polyveck t1, w1, h, tmp1, tmp2; + + if(smlen < CRYPTO_BYTES) + goto badsig; + + *mlen = smlen - CRYPTO_BYTES; + + unpack_pk(rho, &t1, pk); + if(unpack_sig(&z, &h, &c, sm)) + goto badsig; + if(polyvecl_chknorm(&z, GAMMA1 - BETA)) + goto badsig; + + /* Compute CRH(CRH(rho, t1), msg) using m as "playground" buffer */ + if(sm != m) + for(i = 0; i < *mlen; ++i) + m[CRYPTO_BYTES + i] = sm[CRYPTO_BYTES + i]; + + shake256(m + CRYPTO_BYTES - CRHBYTES, CRHBYTES, pk, CRYPTO_PUBLICKEYBYTES); + shake256(mu, CRHBYTES, m + CRYPTO_BYTES - CRHBYTES, CRHBYTES + *mlen); + + /* Matrix-vector multiplication; compute Az - c2^dt1 */ + expand_mat(mat, rho); + polyvecl_ntt(&z); + for(i = 0; i < K ; ++i) + polyvecl_pointwise_acc_invmontgomery(tmp1.vec+i, mat+i, &z); + + chat = c; + poly_ntt(&chat); + polyveck_shiftl(&t1, D); + polyveck_ntt(&t1); + for(i = 0; i < K; ++i) + poly_pointwise_invmontgomery(tmp2.vec+i, &chat, t1.vec+i); + + polyveck_sub(&tmp1, &tmp1, &tmp2); + polyveck_reduce(&tmp1); + polyveck_invntt_montgomery(&tmp1); + + /* Reconstruct w1 */ + polyveck_csubq(&tmp1); + polyveck_use_hint(&w1, &tmp1, &h); + + /* Call random oracle and verify challenge */ + challenge(&cp, mu, &w1); + for(i = 0; i < N; ++i) + if(c.coeffs[i] != cp.coeffs[i]) + { + /* Signature verification failed */ + badsig: + *mlen = (int32_t) -1; + for(i = 0; i < smlen; ++i) + m[i] = 0; + + return -1; + } + + /* All good, copy msg, return 0 */ + for(i = 0; i < *mlen; ++i) + m[i] = sm[CRYPTO_BYTES + i]; + return 0; +} + +#ifdef STANDALONE +/////////////////////////////////////////////////////////////////////////////// +#include +#include + +#define MLEN 59 +#define NTESTS 10000 + +int64_t timing_overhead; +#ifdef DBENCH +int64_t *tred, *tadd, *tmul, *tround, *tsample, *tpack, *tshake; +#endif + +static int cmp_llu(const void *a, const void*b) +{ + if(*(int64_t *)a < *(int64_t *)b) return -1; + if(*(int64_t *)a > *(int64_t *)b) return 1; + return 0; +} + +static int64_t median(int64_t *l, size_t llen) +{ + qsort(l,llen,sizeof(uint64_t),cmp_llu); + + if(llen%2) return l[llen/2]; + else return (l[llen/2-1]+l[llen/2])/2; +} + +static int64_t average(int64_t *t, size_t tlen) +{ + uint64_t acc=0; + size_t i; + for(i=0;i + +#ifndef CPUCYCLES_H +#define CPUCYCLES_H + +#ifdef DBENCH +#define DBENCH_START() uint64_t time = cpucycles_start() +#define DBENCH_STOP(t) t += cpucycles_stop() - time - timing_overhead +#else +#define DBENCH_START() +#define DBENCH_STOP(t) +#endif + +#ifdef USE_RDPMC /* Needs echo 2 > /sys/devices/cpu/rdpmc */ +#ifdef SERIALIZE_RDC + +static inline uint64_t cpucycles_start(void) { + const uint32_t ecx = (1U << 30) + 1; + uint64_t result; + + asm volatile("cpuid; movl %1,%%ecx; rdpmc; shlq $32,%%rdx; orq %%rdx,%%rax" + : "=&a" (result) : "r" (ecx) : "rbx", "rcx", "rdx"); + + return result; +} + +static inline uint64_t cpucycles_stop(void) { + const uint32_t ecx = (1U << 30) + 1; + uint64_t result, dummy; + + asm volatile("rdpmc; shlq $32,%%rdx; orq %%rdx,%%rax; movq %%rax,%0; cpuid" + : "=&r" (result), "=c" (dummy) : "c" (ecx) : "rax", "rbx", "rdx"); + + return result; +} + +#else + +static inline uint64_t cpucycles_start(void) { + const uint32_t ecx = (1U << 30) + 1; + uint64_t result; + + asm volatile("rdpmc; shlq $32,%%rdx; orq %%rdx,%%rax" + : "=a" (result) : "c" (ecx) : "rdx"); + + return result; +} + +static inline uint64_t cpucycles_stop(void) { + const uint32_t ecx = (1U << 30) + 1; + uint64_t result; + + asm volatile("rdpmc; shlq $32,%%rdx; orq %%rdx,%%rax" + : "=a" (result) : "c" (ecx) : "rdx"); + + return result; +} + +#endif +#else +#ifdef SERIALIZE_RDC + +static inline uint64_t cpucycles_start(void) { + uint64_t result; + + asm volatile("cpuid; rdtsc; shlq $32,%%rdx; orq %%rdx,%%rax" + : "=a" (result) : : "%rbx", "%rcx", "%rdx"); + + return result; +} + +static inline uint64_t cpucycles_stop(void) { + uint64_t result; + + asm volatile("rdtscp; shlq $32,%%rdx; orq %%rdx,%%rax; mov %%rax,%0; cpuid" + : "=r" (result) : : "%rax", "%rbx", "%rcx", "%rdx"); + + return result; +} + +#else + +static inline uint64_t cpucycles_start(void) { + uint64_t result; + + asm volatile("rdtsc; shlq $32,%%rdx; orq %%rdx,%%rax" + : "=a" (result) : : "%rdx"); + + return result; +} + +static inline uint64_t cpucycles_stop(void) { + uint64_t result; + + asm volatile("rdtsc; shlq $32,%%rdx; orq %%rdx,%%rax" + : "=a" (result) : : "%rdx"); + + return result; +} + +#endif +#endif + +int64_t cpucycles_overhead(void); + +#endif + +#ifndef FIPS202_H +#define FIPS202_H + + +#define SHAKE128_RATE 168 +#define SHAKE256_RATE 136 + +void shake128_absorb(uint64_t *s, + const uint8_t *input, + int32_t inlen); + +void shake128_squeezeblocks(uint8_t *output, + int32_t nblocks, + uint64_t *s); + +void shake256_absorb(uint64_t *s, + const uint8_t *input, + int32_t inlen); + +void shake256_squeezeblocks(uint8_t *output, + int32_t nblocks, + uint64_t *s); + +void shake128(uint8_t *output, + int32_t outlen, + const uint8_t *input, + int32_t inlen); + +void shake256(uint8_t *output, + int32_t outlen, + const uint8_t *input, + int32_t inlen); + +#endif + +#ifndef PARAMS_H +#define PARAMS_H + +#ifndef MODE +#define MODE 2 +#endif + +#define SEEDBYTES 32U +#define CRHBYTES 48U +#define N 256U +#define Q 8380417U +#define QBITS 23U +#define ROOT_OF_UNITY 1753U +#define D 14U +#define GAMMA1 ((Q - 1U)/16U) +#define GAMMA2 (GAMMA1/2U) +#define ALPHA (2U*GAMMA2) + +#if MODE == 0 +#define K 3U +#define L 2U +#define ETA 7U +#define SETABITS 4U +#define BETA 375U +#define OMEGA 64U + +#elif MODE == 1 +#define K 4U +#define L 3U +#define ETA 6U +#define SETABITS 4U +#define BETA 325U +#define OMEGA 80U + +#elif MODE == 2 +#define K 5U +#define L 4U +#define ETA 5U +#define SETABITS 4U +#define BETA 275U +#define OMEGA 96U + +#elif MODE == 3 +#define K 6U +#define L 5U +#define ETA 3U +#define SETABITS 3U +#define BETA 175U +#define OMEGA 120U + +#endif + +#define POL_SIZE_PACKED ((N*QBITS)/8) +#define POLT1_SIZE_PACKED ((N*(QBITS - D))/8) +#define POLT0_SIZE_PACKED ((N*D)/8) +#define POLETA_SIZE_PACKED ((N*SETABITS)/8) +#define POLZ_SIZE_PACKED ((N*(QBITS - 3))/8) +#define POLW1_SIZE_PACKED ((N*4)/8) +#define POLVECK_SIZE_PACKED (K*POL_SIZE_PACKED) +#define POLVECL_SIZE_PACKED (L*POL_SIZE_PACKED) + +#define CRYPTO_PUBLICKEYBYTES (SEEDBYTES + K*POLT1_SIZE_PACKED) +#define CRYPTO_SECRETKEYBYTES (2*SEEDBYTES + (L + K)*POLETA_SIZE_PACKED + CRHBYTES + K*POLT0_SIZE_PACKED) +#define CRYPTO_BYTES (L*POLZ_SIZE_PACKED + (OMEGA + K) + (N/8 + 8)) + +#endif +#ifndef POLY_H +#define POLY_H + +//#include +//#include "params.h" +//#include "fips202.h" + +typedef struct { + uint32_t coeffs[N]; +} poly __attribute__((aligned(32))); + +void poly_reduce(poly *a); +void poly_csubq(poly *a); +void poly_freeze(poly *a); + +void poly_add(poly *c, const poly *a, const poly *b); +void poly_sub(poly *c, const poly *a, const poly *b); +void poly_neg(poly *a); +void poly_shiftl(poly *a, uint32_t k); + +void poly_ntt(poly *a); +void poly_invntt_montgomery(poly *a); +void poly_pointwise_invmontgomery(poly *c, const poly *a, const poly *b); + +void poly_power2round(poly *a1, poly *a0, const poly *a); +void poly_decompose(poly *a1, poly *a0, const poly *a); +uint32_t poly_make_hint(poly *h, const poly *a, const poly *b); +void poly_use_hint(poly *a, const poly *b, const poly *h); + +int poly_chknorm(const poly *a, uint32_t B); +void poly_uniform(poly *a, const uint8_t *buf); +void poly_uniform_eta(poly *a, + const uint8_t seed[SEEDBYTES], + uint8_t nonce); +void poly_uniform_gamma1m1(poly *a, + const uint8_t seed[SEEDBYTES + CRHBYTES], + uint16_t nonce); + +void polyeta_pack(uint8_t *r, const poly *a); +void polyeta_unpack(poly *r, const uint8_t *a); + +void polyt1_pack(uint8_t *r, const poly *a); +void polyt1_unpack(poly *r, const uint8_t *a); + +void polyt0_pack(uint8_t *r, const poly *a); +void polyt0_unpack(poly *r, const uint8_t *a); + +void polyz_pack(uint8_t *r, const poly *a); +void polyz_unpack(poly *r, const uint8_t *a); + +void polyw1_pack(uint8_t *r, const poly *a); +#endif +#ifndef POLYVEC_H +#define POLYVEC_H + +//#include +//#include "params.h" +//#include "poly.h" + +/* Vectors of polynomials of length L */ +typedef struct { + poly vec[L]; +} polyvecl; + +void polyvecl_freeze(polyvecl *v); + +void polyvecl_add(polyvecl *w, const polyvecl *u, const polyvecl *v); + +void polyvecl_ntt(polyvecl *v); +void polyvecl_pointwise_acc_invmontgomery(poly *w, + const polyvecl *u, + const polyvecl *v); + +int polyvecl_chknorm(const polyvecl *v, uint32_t B); + + + +/* Vectors of polynomials of length K */ +typedef struct { + poly vec[K]; +} polyveck; + +void polyveck_reduce(polyveck *v); +void polyveck_csubq(polyveck *v); +void polyveck_freeze(polyveck *v); + +void polyveck_add(polyveck *w, const polyveck *u, const polyveck *v); +void polyveck_sub(polyveck *w, const polyveck *u, const polyveck *v); +void polyveck_shiftl(polyveck *v, uint32_t k); + +void polyveck_ntt(polyveck *v); +void polyveck_invntt_montgomery(polyveck *v); + +int polyveck_chknorm(const polyveck *v, uint32_t B); + +void polyveck_power2round(polyveck *v1, polyveck *v0, const polyveck *v); +void polyveck_decompose(polyveck *v1, polyveck *v0, const polyveck *v); +uint32_t polyveck_make_hint(polyveck *h, + const polyveck *u, + const polyveck *v); +void polyveck_use_hint(polyveck *w, const polyveck *v, const polyveck *h); + +#endif + +#ifndef NTT_H +#define NTT_H + +//#include +//#include "params.h" + +void ntt(uint32_t p[N]); +void invntt_frominvmont(uint32_t p[N]); + +#endif +#ifndef PACKING_H +#define PACKING_H + +//#include "params.h" +//#include "polyvec.h" + +void pack_pk(uint8_t pk[CRYPTO_PUBLICKEYBYTES], + const uint8_t rho[SEEDBYTES], const polyveck *t1); +void pack_sk(uint8_t sk[CRYPTO_SECRETKEYBYTES], + const uint8_t rho[SEEDBYTES], + const uint8_t key[SEEDBYTES], + const uint8_t tr[CRHBYTES], + const polyvecl *s1, + const polyveck *s2, + const polyveck *t0); +void pack_sig(uint8_t sig[CRYPTO_BYTES], + const polyvecl *z, const polyveck *h, const poly *c); + +void unpack_pk(uint8_t rho[SEEDBYTES], polyveck *t1, + const uint8_t pk[CRYPTO_PUBLICKEYBYTES]); +void unpack_sk(uint8_t rho[SEEDBYTES], + uint8_t key[SEEDBYTES], + uint8_t tr[CRHBYTES], + polyvecl *s1, + polyveck *s2, + polyveck *t0, + const uint8_t sk[CRYPTO_SECRETKEYBYTES]); +int unpack_sig(polyvecl *z, polyveck *h, poly *c, + const uint8_t sig[CRYPTO_BYTES]); + +#endif +#ifndef REDUCE_H +#define REDUCE_H + +//#include + +#define MONT 4193792U // 2^32 % Q +#define QINV 4236238847U // -q^(-1) mod 2^32 + +/* a <= Q*2^32 => r < 2*Q */ +uint32_t montgomery_reduce(uint64_t a); + +/* r < 2*Q */ +uint32_t reduce32(uint32_t a); + +/* a < 2*Q => r < Q */ +uint32_t csubq(uint32_t a); + +/* r < Q */ +uint32_t freeze(uint32_t a); + +#endif +#ifndef ROUNDING_H +#define ROUNDING_H + +//#include + +uint32_t power2round(const uint32_t a, uint32_t *a0); +uint32_t decompose(uint32_t a, uint32_t *a0); +uint32_t make_hint(const uint32_t a, const uint32_t b); +uint32_t use_hint(const uint32_t a, const uint32_t hint); + +#endif +#ifndef SIGN_H +#define SIGN_H + +//#include "params.h" +//#include "poly.h" +//#include "polyvec.h" + +void expand_mat(polyvecl mat[K], const uint8_t rho[SEEDBYTES]); +void challenge(poly *c, const uint8_t mu[CRHBYTES], + const polyveck *w1); + +int crypto_sign_keypair(uint8_t *pk, uint8_t *sk); + +int crypto_sign(uint8_t *sm, int32_t *smlen, + const uint8_t *msg, int32_t len, + const uint8_t *sk); + +int crypto_sign_open(uint8_t *m, int32_t *mlen, + const uint8_t *sm, int32_t smlen, + const uint8_t *pk); + +#endif + +#ifndef API_H +#define API_H + +#ifndef MODE +#define MODE 2 +#endif + +#if MODE == 0 +#if CRYPTO_PUBLICKEYBYTES -896U +CRYPTO_PUBLICKEYBYTES size error +#endif +#if CRYPTO_SECRETKEYBYTES -2096U +CRYPTO_SECRETKEYBYTES size error +#endif +#if CRYPTO_BYTES -1387U +CRYPTO_BYTES size error +#endif + +#elif MODE == 1 +#if CRYPTO_PUBLICKEYBYTES -1184U +CRYPTO_PUBLICKEYBYTES size error +#endif +#if CRYPTO_SECRETKEYBYTES -2800U +CRYPTO_SECRETKEYBYTES size error +#endif +#if CRYPTO_BYTES -2044U +CRYPTO_BYTES size error +#endif + +#elif MODE == 2 +#if CRYPTO_PUBLICKEYBYTES -1472U +CRYPTO_PUBLICKEYBYTES size error +#endif +#if CRYPTO_SECRETKEYBYTES -3504U +CRYPTO_SECRETKEYBYTES size error +#endif +#if CRYPTO_BYTES -2701U +CRYPTO_BYTES size error +#endif + +#elif MODE == 3 +#if CRYPTO_PUBLICKEYBYTES -1760U +CRYPTO_PUBLICKEYBYTES size error +#endif +#if CRYPTO_SECRETKEYBYTES -3856U +CRYPTO_SECRETKEYBYTES size error +#endif +#if CRYPTO_BYTES -3366U +CRYPTO_BYTES size error +#endif + +#endif + +#define CRYPTO_ALGNAME "Dilithium" + +int crypto_sign_keypair(uint8_t *pk, uint8_t *sk); + +int crypto_sign(uint8_t *sm, int32_t *smlen, + const uint8_t *msg, int32_t len, + const uint8_t *sk); + +int crypto_sign_open(uint8_t *m, int32_t *mlen, + const uint8_t *sm, int32_t smlen, + const uint8_t *pk); + +#endif diff --git a/src/cc/makecclib b/src/cc/makecclib index f4d2bd01b..adac757c3 100755 --- a/src/cc/makecclib +++ b/src/cc/makecclib @@ -1,2 +1,2 @@ #!/bin/sh -gcc -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp +gcc -O3 -std=c++11 -I../secp256k1/include -I../univalue/include -I../cryptoconditions/include -I../cryptoconditions/src -I../cryptoconditions/src/asn -I.. -I. -fPIC -shared -c -o ../libcc.so cclib.cpp diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index bd3d74a95..6dbab482a 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -659,12 +659,12 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, partialsig")); } -int testmain(void); +//int testmain(void); UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; UniValue result(UniValue::VOBJ); int32_t i,n; uint8_t msg[32],musig64[64]; secp256k1_pubkey combined_pk; secp256k1_schnorrsig musig; char str[129]; - testmain(); + //testmain(); if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) From ad439274bd21d003280c35468f937ef152ceac35 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 21:07:37 -1100 Subject: [PATCH 1073/1145] include --- src/cc/cclib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 84f229069..c7372907e 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -581,7 +581,7 @@ uint256 juint256(cJSON *obj) #else #include "sudoku.cpp" #include "musig.cpp" -#inclide "dilithium.c" +#include "dilithium.c" //#include "../secp256k1/src/modules/musig/example.c" #endif From fc0b7b15c8f46618794734d27449f031acc8f34c Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 21:16:25 -1100 Subject: [PATCH 1074/1145] Revert to boost 1.66 --- depends/packages/boost.mk | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/depends/packages/boost.mk b/depends/packages/boost.mk index 7a0439ba7..3c180b0ce 100644 --- a/depends/packages/boost.mk +++ b/depends/packages/boost.mk @@ -1,8 +1,8 @@ package=boost -$(package)_version=1_69_0 -$(package)_download_path=https://dl.bintray.com/boostorg/release/1.69.0/source +$(package)_version=1_66_0 +$(package)_download_path=https://dl.bintray.com/boostorg/release/1.66.0/source $(package)_file_name=$(package)_$($(package)_version).tar.bz2 -$(package)_sha256_hash=8f32d4617390d1c2d16f26a27ab60d97807b35440d45891fa340fc2648b04406 +$(package)_sha256_hash=5721818253e6a0989583192f96782c4a98eb6204965316df9f5ad75819225ca9 define $(package)_set_vars $(package)_config_opts_release=variant=release From 33f126914ed4152f7832c660299980af972b847c Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 21:45:03 -1100 Subject: [PATCH 1075/1145] Dilithium key pair --- src/cc/cclib.cpp | 33 +++++++++++++++++++++++++++++++++ src/cc/dilithium.c | 39 +++++++++++++++++++++++++++++++++++++++ src/cc/dilithium.h | 9 +++++---- 3 files changed, 77 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index c7372907e..46a5f4736 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -37,6 +37,7 @@ std::string MYCCLIBNAME = (char *)"rogue"; #define EVAL_SUDOKU 17 #define EVAL_MUSIG 18 +#define EVAL_DILITHIUM 19 std::string MYCCLIBNAME = (char *)"sudoku"; #endif @@ -80,6 +81,11 @@ CClib_methods[] = { (char *)"musig", (char *)"verify", (char *)"msg sig pubkey", 3, 3, 'V', EVAL_MUSIG }, { (char *)"musig", (char *)"send", (char *)"combined_pk amount", 2, 2, 'x', EVAL_MUSIG }, { (char *)"musig", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_MUSIG }, + { (char *)"dilithium", (char *)"keypair", (char *)"", 0, 0, 'K', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"sign", (char *)"msg privkey", 2, 2, 'S', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"verify", (char *)"msg sig pubtxid", 3, 3, 'V', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"send", (char *)"pubtxid amount", 2, 2, 'x', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_DILITHIUM }, #endif }; @@ -119,6 +125,13 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); + +UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); + #endif cJSON *cclib_reparse(int32_t *nump,char *jsonstr) // assumes origparams will be freed by caller @@ -243,6 +256,26 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,char *jsonstr) return(result); } } + else if ( cp->evalcode == EVAL_DILITHIUM ) + { + if ( strcmp(method,"send") == 0 ) + return(dilithium_send(txfee,cp,params)); + else if ( strcmp(method,"spend") == 0 ) + return(dilithium_spend(txfee,cp,params)); + else if ( strcmp(method,"keypair") == 0 ) + return(dilithium_keypair(txfee,cp,params)); + else if ( strcmp(method,"sign") == 0 ) + return(dilithium_sign(txfee,cp,params)); + else if ( strcmp(method,"verify") == 0 ) + return(dilithium_verify(txfee,cp,params)); + else + { + result.push_back(Pair("result","error")); + result.push_back(Pair("error","invalid dilithium method")); + result.push_back(Pair("method",method)); + return(result); + } + } #endif else { diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index b6624353e..902a3ca49 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2835,3 +2835,42 @@ int32_t main(void) } #endif +UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) +{ + UniValue result(UniValue::VOBJ); uint8_t pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i; + dilithium_keypair(pk,sk); + for (i=0; i +/* #ifndef CPUCYCLES_H #define CPUCYCLES_H @@ -11,7 +12,7 @@ #define DBENCH_STOP(t) #endif -#ifdef USE_RDPMC /* Needs echo 2 > /sys/devices/cpu/rdpmc */ +#ifdef USE_RDPMC // Needs echo 2 > /sys/devices/cpu/rdpmc #ifdef SERIALIZE_RDC static inline uint64_t cpucycles_start(void) { @@ -103,7 +104,7 @@ static inline uint64_t cpucycles_stop(void) { int64_t cpucycles_overhead(void); -#endif +#endif*/ #ifndef FIPS202_H #define FIPS202_H @@ -144,7 +145,7 @@ void shake256(uint8_t *output, #define PARAMS_H #ifndef MODE -#define MODE 2 +#define MODE 3 #endif #define SEEDBYTES 32U @@ -410,7 +411,7 @@ int crypto_sign_open(uint8_t *m, int32_t *mlen, #define API_H #ifndef MODE -#define MODE 2 +#define MODE 3 #endif #if MODE == 0 From 3846555d1914b38bb95455e3e2143bc1b427252f Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 21:46:51 -1100 Subject: [PATCH 1076/1145] Dbench start/stop --- src/cc/dilithium.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 902a3ca49..6a7f90d83 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -6,6 +6,10 @@ * by Gilles Van Assche, Daniel J. Bernstein, and Peter Schwabe */ #include + +#define DBENCH_START() +#define DBENCH_STOP() + #include "dilithium.h" From 54e28a8ebf715800b4d3436a1adf445f07760070 Mon Sep 17 00:00:00 2001 From: jl777 Date: Fri, 22 Feb 2019 21:48:26 -1100 Subject: [PATCH 1077/1145] Arg --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 6a7f90d83..cfe3b253f 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -8,7 +8,7 @@ #include #define DBENCH_START() -#define DBENCH_STOP() +#define DBENCH_STOP(arg) #include "dilithium.h" From 99f94425ebc6d1b1eedaaf50cb871092f97fc09e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 03:18:52 -1100 Subject: [PATCH 1078/1145] +prints --- src/cc/dilithium.c | 22 ++++++++++++---------- src/cc/rogue_rpc.cpp | 9 ++++++--- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index cfe3b253f..9103a6037 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2426,7 +2426,7 @@ void challenge(poly *c, } /************************************************* -* Name: dilithium_keypair +* Name: _dilithium_keypair * * Description: Generates public and private key. * @@ -2437,7 +2437,7 @@ void challenge(poly *c, * * Returns 0 (success) **************************************************/ -int dilithium_keypair(uint8_t *pk, uint8_t *sk) { +int _dilithium_keypair(uint8_t *pk, uint8_t *sk) { uint32_t i; uint8_t seedbuf[3*SEEDBYTES]; uint8_t tr[CRHBYTES]; @@ -2488,7 +2488,7 @@ int dilithium_keypair(uint8_t *pk, uint8_t *sk) { } /************************************************* -* Name: dilithium_sign +* Name: _dilithium_sign * * Description: Compute signed message. * @@ -2503,7 +2503,7 @@ int dilithium_keypair(uint8_t *pk, uint8_t *sk) { * * Returns 0 (success) **************************************************/ -int dilithium_sign(uint8_t *sm, +int _dilithium_sign(uint8_t *sm, int32_t *smlen, const uint8_t *m, int32_t mlen, @@ -2613,7 +2613,7 @@ int dilithium_sign(uint8_t *sm, } /************************************************* -* Name: dilithium_verify +* Name: _dilithium_verify * * Description: Verify signed message. * @@ -2626,7 +2626,7 @@ int dilithium_sign(uint8_t *sm, * * Returns 0 if signed message could be verified correctly and -1 otherwise **************************************************/ -int dilithium_verify(uint8_t *m, +int _dilithium_verify(uint8_t *m, int32_t *mlen, const uint8_t *sm, int32_t smlen, @@ -2785,7 +2785,7 @@ int32_t main(void) tkeygen[i] = cpucycles_start(); #endif - dilithium_keypair(pk, sk); // 1.3 + _dilithium_keypair(pk, sk); // 1.3 #ifdef DBENCH tkeygen[i] = cpucycles_stop() - tkeygen[i] - timing_overhead; // tred = tadd = tmul = tround = tsample = tpack = tshake = &dummy; @@ -2793,13 +2793,13 @@ int32_t main(void) #endif randombytes(m, MLEN); // 1.27 - dilithium_sign(sm, &smlen, m, MLEN, sk); // 7.2 + _dilithium_sign(sm, &smlen, m, MLEN, sk); // 7.2 #ifdef DBENCH tsign[i] = cpucycles_stop() - tsign[i] - timing_overhead; tverify[i] = cpucycles_start(); #endif - ret = dilithium_verify(m2, &mlen, sm, smlen, pk); + ret = _dilithium_verify(m2, &mlen, sm, smlen, pk); #ifdef DBENCH tverify[i] = cpucycles_stop() - tverify[i] - timing_overhead; #endif @@ -2842,7 +2842,7 @@ int32_t main(void) UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); uint8_t pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i; - dilithium_keypair(pk,sk); + _dilithium_keypair(pk,sk); for (i=0; i>16,endP.level,endP.experience,endP.dungeonlevel); fprintf(stderr,"%s\n",str); + *numkeysp = numkeys; + return(keystrokes); } else num = 0; } else fprintf(stderr,"extractgame: couldnt find baton\n"); } else fprintf(stderr,"extractgame: invalid game\n"); - *numkeysp = numkeys; - return(keystrokes); + return(0); } UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) From 504fed539e7b2d8759ebf72d13a4e1469affa649 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 03:30:44 -1100 Subject: [PATCH 1079/1145] +prints --- src/cc/rogue_rpc.cpp | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index edac1d813..fd068aca4 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -890,8 +890,15 @@ char *rogue_extractgame(int32_t makefiles,char *str,int32_t *numkeysp,std::vecto *numkeysp = numkeys; return(keystrokes); } else num = 0; - } else fprintf(stderr,"extractgame: couldnt find baton\n"); + } + else + { + fprintf(stderr,"extractgame: couldnt find baton keystrokes.%p\n",keystrokes); + if ( keystrokes != 0 ) + free(keystrokes), keystrokes = 0; + } } else fprintf(stderr,"extractgame: invalid game\n"); + fprintf(stderr,"extract %s\n",gametxid.GetHex().c_str()); return(0); } @@ -1248,6 +1255,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp //fprintf(stderr,"call extractgame\n"); if ( (keystrokes= rogue_extractgame(0,str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) { + fprintf(stderr,"numkeys.%d rogue_extractgame %s\n",numkeys,gametxid.GetHex().c_str()); free(keystrokes); //fprintf(stderr,"extracted.(%s)\n",str); if ( newdata == playerdata ) @@ -1273,6 +1281,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); } + fprintf(stderr,"no keys rogue_extractgame %s\n",gametxid.GetHex().c_str()); return(-1); } From 348d6df6a520382ef91be6e94d93e7dd60579865 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 03:40:13 -1100 Subject: [PATCH 1080/1145] -print --- src/cc/rogue_rpc.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index fd068aca4..5aa5b3a8d 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -898,7 +898,7 @@ char *rogue_extractgame(int32_t makefiles,char *str,int32_t *numkeysp,std::vecto free(keystrokes), keystrokes = 0; } } else fprintf(stderr,"extractgame: invalid game\n"); - fprintf(stderr,"extract %s\n",gametxid.GetHex().c_str()); + //fprintf(stderr,"extract %s\n",gametxid.GetHex().c_str()); return(0); } @@ -1255,7 +1255,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp //fprintf(stderr,"call extractgame\n"); if ( (keystrokes= rogue_extractgame(0,str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) { - fprintf(stderr,"numkeys.%d rogue_extractgame %s\n",numkeys,gametxid.GetHex().c_str()); + //fprintf(stderr,"numkeys.%d rogue_extractgame %s\n",numkeys,gametxid.GetHex().c_str()); free(keystrokes); //fprintf(stderr,"extracted.(%s)\n",str); if ( newdata == playerdata ) @@ -1281,7 +1281,7 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); } - fprintf(stderr,"no keys rogue_extractgame %s\n",gametxid.GetHex().c_str()); + //fprintf(stderr,"no keys rogue_extractgame %s\n",gametxid.GetHex().c_str()); return(-1); } From 09b5de739be060ae95474754497e4749adc65cfe Mon Sep 17 00:00:00 2001 From: CHMEX <33424502+CHMEX@users.noreply.github.com> Date: Sat, 23 Feb 2019 16:11:56 +0100 Subject: [PATCH 1081/1145] OUR OUR is notarized but missing. --- src/assetchains.json | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/assetchains.json b/src/assetchains.json index 1b23bc616..91baf9829 100644 --- a/src/assetchains.json +++ b/src/assetchains.json @@ -224,5 +224,21 @@ "addnode": [ "37.187.225.231" ] - } + }, + { + "ac_name": "OUR", + "ac_reward": "1478310502", + "ac_halving": "525600", + "ac_cc": "42", + "ac_supply": "100000000", + "ac_perc": "77700", + "ac_staked": "93", + "ac_pubkey": "02652a3f3e00b3a1875a918314f0bac838d6dd189a346fa623f5efe9541ac0b98c", + "ac_public": "1", + "addnode": [ + "51.255.195.65", + "217.182.129.38", + "95.216.150.177" + ] +} ] From 1b5d9b5032f41422113868eca35d182c07529f7e Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sat, 23 Feb 2019 23:24:17 +0800 Subject: [PATCH 1082/1145] show --- src/cc/musig.cpp | 106 +++++++++++++--------- src/musigtest.py | 189 +++++++++++++++++++++++++++++++++++++++ src/wallet/rpcwallet.cpp | 8 +- 3 files changed, 255 insertions(+), 48 deletions(-) create mode 100755 src/musigtest.py diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index bd3d74a95..cdf53be09 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -89,7 +89,7 @@ the "msg" is what needs to be signed to create a valid spend "numsigners": 2, "commitment": "bbea1f2562eca01b9a1393c5dc188bdd44551aebf684f4459930f59dde01f7ae", "result": "success" - } +} on node with pubkey: 0255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4 ./komodo-cli -ac_name=MUSIG cclib session 18 '[1,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75"]' @@ -221,7 +221,9 @@ struct musig_info secp256k1_musig_partial_signature *partial_sig; //[N_SIGNERS]; int32_t myind,num; uint8_t msg[32],pkhash[32],combpk[33]; -} *MUSIG; +}; + +std::vector MUSIG; struct musig_info *musig_infocreate(int32_t myind,int32_t num) { @@ -431,14 +433,15 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) num = juint(jitem(params,1),0); if ( myind < 0 || myind >= num || num <= 0 ) return(cclib_error(result,"illegal myindex and numsigners")); - if ( MUSIG != 0 ) - musig_infofree(MUSIG), MUSIG = 0; - MUSIG = musig_infocreate(myind,num); - if ( musig_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) + //if ( MUSIG[myind] != 0 ) + // musig_infofree(MUSIG[myind]), MUSIG[myind] = 0; + struct musig_info *temp_musig = musig_infocreate(myind,num); + MUSIG.push_back(temp_musig); + if ( musig_parsepubkey(ctx,MUSIG[myind]->combined_pk,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing combined_pubkey")); - else if ( musig_parsehash(MUSIG->pkhash,jitem(params,3),32) < 0 ) + else if ( musig_parsehash(MUSIG[myind]->pkhash,jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( musig_parsehash(MUSIG->msg,jitem(params,4),32) < 0 ) + else if ( musig_parsehash(MUSIG[myind]->msg,jitem(params,4),32) < 0 ) return(cclib_error(result,"error parsing msg")); Myprivkey(privkey); GetRandBytes(session,32); @@ -468,13 +471,13 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * my_index: index of this signer in the signers array * seckey: the signer's 32-byte secret key (cannot be NULL) */ - if ( secp256k1_musig_session_initialize(ctx,&MUSIG->session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) + if ( secp256k1_musig_session_initialize(ctx,&MUSIG[myind]->session,MUSIG[myind]->signer_data, &MUSIG[myind]->nonce_commitments[MUSIG[myind]->myind * 32],session,MUSIG[myind]->msg,&MUSIG[myind]->combined_pk,MUSIG[myind]->pkhash,MUSIG[myind]->num,MUSIG[myind]->myind,privkey) > 0 ) { memset(session,0,sizeof(session)); result.push_back(Pair("myind",(int64_t)myind)); result.push_back(Pair("numsigners",(int64_t)num)); for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitments[MUSIG->myind*32 + i]); + sprintf(&str[i<<1],"%02x",MUSIG[myind]->nonce_commitments[MUSIG[myind]->myind*32 + i]); str[64] = 0; result.push_back(Pair("commitment",str)); result.push_back(Pair("result","success")); @@ -492,18 +495,20 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; size_t clen = CPubKey::PUBLIC_KEY_SIZE; - UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32]; CPubKey pk; char str[67]; + UniValue result(UniValue::VOBJ); int32_t i,n,ind,myind; uint8_t pkhash[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 4 ) { - if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) + if ( (myind= juint(jitem(params,0),0)) < 0 ) + return(cclib_error(result,"myind is wrong")); + if ( musig_parsehash(pkhash,jitem(params,1),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG[myind]->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); - else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + else if ( (ind= juint(jitem(params,2),0)) < 0 || ind >= MUSIG[myind]->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash(&MUSIG->nonce_commitments[ind*32],jitem(params,2),32) < 0 ) + else if ( musig_parsehash(&MUSIG[myind]->nonce_commitments[ind*32],jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing commitment")); /** Gets the signer's public nonce given a list of all signers' data with commitments * @@ -521,14 +526,15 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * number of signers participating in the MuSig. */ result.push_back(Pair("added_index",ind)); - if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->commitment_ptrs,MUSIG->num) > 0 ) + fprintf(stderr, "COMMIT: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); + if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG[myind]->session,MUSIG[myind]->signer_data,&MUSIG[myind]->nonces[MUSIG[myind]->myind],MUSIG[myind]->commitment_ptrs,MUSIG[myind]->num) > 0 ) { - if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG->nonces[MUSIG->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) + if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG[myind]->nonces[MUSIG[myind]->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) { for (i=0; i<33; i++) sprintf(&str[i<<1],"%02x",((uint8_t *)pk.begin())[i]); str[66] = 0; - result.push_back(Pair("myind",MUSIG->myind)); + result.push_back(Pair("myind",MUSIG[myind]->myind)); result.push_back(Pair("nonce",str)); result.push_back(Pair("result","success")); } else return(cclib_error(result,"error serializing nonce (pubkey)")); @@ -539,26 +545,29 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("result","success")); } return(result); - } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, commitment")); + } else return(cclib_error(result,"wrong number of params, need 4: myind, pkhash, ind, commitment")); } UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32],psig[32]; CPubKey pk; char str[67]; + UniValue result(UniValue::VOBJ); int32_t i,n,ind,myind; uint8_t pkhash[32],psig[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 4 ) { - if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) + if ( (myind= juint(jitem(params,0),0)) < 0 ) + return(cclib_error(result,"myind is wrong")); + if ( musig_parsehash(pkhash,jitem(params,1),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG[myind]->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); - else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + else if ( (ind= juint(jitem(params,2),0)) < 0 || ind >= MUSIG[myind]->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) + else if ( musig_parsepubkey(ctx,MUSIG[myind]->nonces[ind],jitem(params,3)) < 0 ) return(cclib_error(result,"error parsing nonce")); result.push_back(Pair("added_index",ind)); + fprintf(stderr, "NONCE: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); /** Checks a signer's public nonce against a commitment to said nonce, and update * data structure if they match * @@ -569,10 +578,16 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * been used with `musig_session_get_public_nonce` or initialized * with `musig_session_initialize_verifier`. * In: nonce: signer's alleged public nonce (cannot be NULL) - */ - for (i=0; inum; i++) + * + if ( ind != MUSIG[myind]->num-1 ) { - if ( secp256k1_musig_set_nonce(ctx,&MUSIG->signer_data[i],&MUSIG->nonces[i]) == 0 ) + fprintf(stderr, "ind.%i MUSIG[myind]->num.%i\n", ind, MUSIG[myind]->num); + return(cclib_error(result,"need rest of nonce's to continue")); + }*/ + for (i=0; inum; i++) + { + fprintf(stderr, "setting nonce for index.%i\n",i); + if ( secp256k1_musig_set_nonce(ctx,&MUSIG[myind]->signer_data[i],&MUSIG[myind]->nonces[i]) == 0 ) return(cclib_error(result,"error setting nonce")); } /** Updates a session with the combined public nonce of all signers. The combined @@ -593,45 +608,48 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * adaptor: point to add to the combined public nonce. If NULL, nothing is * added to the combined nonce. */ - if ( secp256k1_musig_session_combine_nonces(ctx,&MUSIG->session,MUSIG->signer_data,MUSIG->num,NULL,NULL) > 0 ) + if ( secp256k1_musig_session_combine_nonces(ctx,&MUSIG[myind]->session,MUSIG[myind]->signer_data,MUSIG[myind]->num,NULL,NULL) > 0 ) { - if ( secp256k1_musig_partial_sign(ctx,&MUSIG->session,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + if ( secp256k1_musig_partial_sign(ctx,&MUSIG[myind]->session,&MUSIG[myind]->partial_sig[MUSIG[myind]->myind]) > 0 ) { - if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG[myind]->partial_sig[MUSIG[myind]->myind]) > 0 ) { for (i=0; i<32; i++) sprintf(&str[i<<1],"%02x",psig[i]); str[64] = 0; - result.push_back(Pair("myind",MUSIG->myind)); + result.push_back(Pair("myind",MUSIG[myind]->myind)); result.push_back(Pair("partialsig",str)); result.push_back(Pair("result","success")); return(result); } else return(cclib_error(result,"error serializing partial sig")); } else return(cclib_error(result,"error making partial sig")); } else return(cclib_error(result,"error combining nonces")); - } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, nonce")); + } else return(cclib_error(result,"wrong number of params, need 4: myind, pkhash, ind, nonce")); } UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t i,ind,n; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; + UniValue result(UniValue::VOBJ); int32_t i,ind,myind,n; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 4 ) { - if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) + if ( (myind= juint(jitem(params,0),0)) < 0 ) + return(cclib_error(result,"myind is wrong")); + if ( musig_parsehash(pkhash,jitem(params,1),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG[myind]->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); - else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + else if ( (ind= juint(jitem(params,2),0)) < 0 || ind >= MUSIG[myind]->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash(psig,jitem(params,2),32) < 0 ) + else if ( musig_parsehash(psig,jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing psig")); - else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) + else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG[myind]->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); result.push_back(Pair("added_index",ind)); - if ( secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) + fprintf(stderr, "PARTIALSIG: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); + if ( secp256k1_musig_partial_sig_combine(ctx,&MUSIG[myind]->session,&sig,MUSIG[myind]->partial_sig,MUSIG[myind]->num) > 0 ) { if ( secp256k1_schnorrsig_serialize(ctx,out64,&sig) > 0 ) { @@ -644,7 +662,7 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else { - if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG[myind]->partial_sig[MUSIG[myind]->myind]) > 0 ) { result.push_back(Pair("myind",ind)); for (i=0; i<32; i++) @@ -656,7 +674,7 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else return(cclib_error(result,"error generating my partialsig")); } return(result); - } else return(cclib_error(result,"wrong number of params, need 3: pkhash, ind, partialsig")); + } else return(cclib_error(result,"wrong number of params, need 4: myind, pkhash, ind, partialsig")); } int testmain(void); diff --git a/src/musigtest.py b/src/musigtest.py new file mode 100755 index 000000000..26f09d588 --- /dev/null +++ b/src/musigtest.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +import platform +import os +import re +import json +import random +import base58 +import binascii +import hashlib +import sys +import time +from slickrpc import Proxy + +# fucntion to define rpc_connection +def def_credentials(chain): + rpcport = ''; + operating_system = platform.system() + if operating_system == 'Darwin': + ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo' + elif operating_system == 'Linux': + ac_dir = os.environ['HOME'] + '/.komodo' + elif operating_system == 'Windows': + ac_dir = '%s/komodo/' % os.environ['APPDATA'] + if chain == 'KMD': + coin_config_file = str(ac_dir + '/komodo.conf') + else: + coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') + with open(coin_config_file, 'r') as f: + for line in f: + l = line.rstrip() + if re.search('rpcuser', l): + rpcuser = l.replace('rpcuser=', '') + elif re.search('rpcpassword', l): + rpcpassword = l.replace('rpcpassword=', '') + elif re.search('rpcport', l): + rpcport = l.replace('rpcport=', '') + if len(rpcport) == 0: + if chain == 'KMD': + rpcport = 7771 + else: + print("rpcport not in conf file, exiting") + print("check " + coin_config_file) + exit(1) + return (Proxy("http://%s:%s@127.0.0.1:%d" % (rpcuser, rpcpassword, int(rpcport)))) + + +# generate address, validate address, dump private key +def genvaldump(rpc_connection): + # get new address + address = rpc_connection.getnewaddress() + # validate address + validateaddress_result = rpc_connection.validateaddress(address) + pubkey = validateaddress_result['pubkey'] + address = validateaddress_result['address'] + # dump private key for the address + privkey = rpc_connection.dumpprivkey(address) + # function output + output = [pubkey, privkey, address] + return(output) + +CHAIN = 'MUSIG' #sys.argv[1] + +rpc = def_credentials(CHAIN) + +pubkeys = [] +address_info = [] +ret = input('Do you want to generate new pubkeys? ').lower() + +if ret.startswith('y'): + numpks = int(input('Enter number of pubkeys to combine: ')) + if os.path.isfile("list.json"): + print('Already have list.json, move it if you would like to generate a new set.') + sys.exit(0) + while len(address_info) < numpks: + addressinfo = genvaldump(rpc) + address_info.append(addressinfo) + f = open("list.json", "w+") + f.write(json.dumps(address_info)) +else: + if os.path.isfile("list.json"): + with open('list.json') as list: + address_info = json.load(list) + else: + sys.exit('No list.json you need to create new pubkeys!') + +for addressinfo in address_info: + pubkeys.append(addressinfo[0]) + +ret = rpc.setpubkey(pubkeys[0]) +ret = rpc.cclib("combine", "18", str(pubkeys)) +pkhash = str(ret['pkhash']) +combinedpk = str(ret['combined_pk']) +print('Your combined pubkey is: ' + combinedpk) +print('Your pkhash is: ' + pkhash) +amount = int(input('Enter amount to send: ')) +tmp = str([combinedpk, amount]) +hex = rpc.cclib("send", "18", tmp)['hex'] +senttxid = rpc.sendrawtransaction(hex) +print('Your senttxid is: ' + senttxid) + +print("Waiting for tx to be confirmed") +while True: + confirmed = int(rpc.gettransaction(senttxid)["confirmations"]) + if not confirmed: + time.sleep(10) + else: + print('SentTX confirmed') + break + +scriptPubKey = rpc.getrawtransaction(senttxid,1)['vout'][1]['scriptPubKey']['hex'] +print('Your scriptPubKey is: ' + scriptPubKey) +tmp = str([senttxid, scriptPubKey]) +msg = rpc.cclib("calcmsg", "18", tmp)['msg'] +print('Your msg is: ' + msg) + +i = 0; +commitments = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + tmp = str([i, len(pubkeys), combinedpk, pkhash, msg]) + commitments.append(rpc.cclib("session", "18", tmp)['commitment']) + i = i + 1 + +print(commitments) + +i = 0 +nonces = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + n = 0 + for commitment in commitments: + if n == i: + n = n + 1 + continue; + tmp = str([i, pkhash, n, commitment]) + ret = rpc.cclib("commit", "18", tmp) + if len(ret) == 4: + nonces.append(ret['nonce']) + n = n + 1 + i = i + 1 + +print(nonces) + +i = 0 +partialsigs = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + n = 0 + for nonce in nonces: + #if n == i: + # n = n + 1 + # continue; + tmp = str([i, pkhash, n, nonce]) + ret = rpc.cclib("nonce", "18", tmp) + print(ret) + if len(ret) == 4: + partialsigs.append(ret['partialsig']) + n = n + 1 + i = i + 1 + +print(partialsigs) + +i = 0 +combinedsigs = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + n = 0 + for partialsig in partialsigs: + if n == i: + n = n + 1 + continue; + tmp = str([i, pkhash, n, partialsig]) + ret = rpc.cclib("partialsig", "18", tmp) + if len(ret) == 4: + combinedsigs.append(ret['combinedsig']) + n = n + 1 + i = i + 1 + +print(combinedsigs) + +tmp = str([msg, combinedpk, combinedsigs[0]]) +ret = rpc.cclib("verify", "18", tmp) + +print(ret) + +tmp = str([sendtxid, scriptPubKey, combinedsigs[0]]) +ret = rpc.cclib("spend", "18", tmp) + +print(ret) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 0ed2f866c..8cffd78f7 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5308,8 +5308,8 @@ UniValue setpubkey(const UniValue& params, bool fHelp) char Raddress[64]; uint8_t pubkey33[33]; - if ( NOTARY_PUBKEY33[0] == 0 ) - { + //if ( NOTARY_PUBKEY33[0] == 0 ) + //{ if (strlen(params[0].get_str().c_str()) == 66) { decode_hex(pubkey33,33,(char *)params[0].get_str().c_str()); @@ -5337,14 +5337,14 @@ UniValue setpubkey(const UniValue& params, bool fHelp) USE_EXTERNAL_PUBKEY = 1; } } else result.push_back(Pair("error", "pubkey is wrong length, must be 66 char hex string.")); - } + /*} else { result.push_back(Pair("error", "Can only set pubkey once, to change it you need to restart your daemon, pubkey in use is below.")); pubkey2addr((char *)Raddress,(uint8_t *)NOTARY_PUBKEY33); std::string address_ret; address_ret.assign(Raddress); result.push_back(Pair("address",address_ret)); - } + }*/ result.push_back(Pair("pubkey", NOTARY_PUBKEY)); return result; } From 69a890fe53bfa7d2025b8cebb6d3e5feed164c09 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 04:56:59 -1100 Subject: [PATCH 1083/1145] Seed based dilithium key generation --- src/cc/cclib.cpp | 2 +- src/cc/dilithium.c | 26 +++++++++++++++++++++----- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 46a5f4736..4f539b7f9 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -81,7 +81,7 @@ CClib_methods[] = { (char *)"musig", (char *)"verify", (char *)"msg sig pubkey", 3, 3, 'V', EVAL_MUSIG }, { (char *)"musig", (char *)"send", (char *)"combined_pk amount", 2, 2, 'x', EVAL_MUSIG }, { (char *)"musig", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_MUSIG }, - { (char *)"dilithium", (char *)"keypair", (char *)"", 0, 0, 'K', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"keypair", (char *)"[hexseed]", 0, 1, 'K', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"sign", (char *)"msg privkey", 2, 2, 'S', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"verify", (char *)"msg sig pubtxid", 3, 3, 'V', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"send", (char *)"pubtxid amount", 2, 2, 'x', EVAL_DILITHIUM }, diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 9103a6037..10718d1c3 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2437,7 +2437,8 @@ void challenge(poly *c, * * Returns 0 (success) **************************************************/ -int _dilithium_keypair(uint8_t *pk, uint8_t *sk) { +int _dilithium_keypair(uint8_t *pk, uint8_t *sk,uint8_t *privkey) +{ uint32_t i; uint8_t seedbuf[3*SEEDBYTES]; uint8_t tr[CRHBYTES]; @@ -2448,7 +2449,8 @@ int _dilithium_keypair(uint8_t *pk, uint8_t *sk) { polyveck s2, t, t1, t0; /* Expand 32 bytes of randomness into rho, rhoprime and key */ - randombytes(seedbuf, SEEDBYTES); + //randombytes(seedbuf, SEEDBYTES); + memcpy(seedbuf,privkey,SEEDBYTES); shake256(seedbuf, 3*SEEDBYTES, seedbuf, SEEDBYTES); rho = seedbuf; rhoprime = rho + SEEDBYTES; @@ -2841,8 +2843,16 @@ int32_t main(void) UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint8_t pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i; - _dilithium_keypair(pk,sk); + UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; + //randombytes(seed,SEEDBYTES); + Myprivkey(seed); + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 1 ) + { + if ( musig_parsehash(seed,jitem(params,0),32) < 0 ) + return(cclib_error(result,"error parsing seed")); + else externalflag = 1; + } + _dilithium_keypair(pk,sk,seed); for (i=0; i Date: Sat, 23 Feb 2019 05:06:29 -1100 Subject: [PATCH 1084/1145] Pkaddr and skaddr --- src/cc/dilithium.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 10718d1c3..87d55c35d 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2843,7 +2843,7 @@ int32_t main(void) UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; + UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr,str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; //randombytes(seed,SEEDBYTES); Myprivkey(seed); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 1 ) @@ -2865,6 +2865,12 @@ UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *para sprintf(&str[i<<1],"%02x",seed[i]); str[i<<1] = 0; result.push_back(Pair("seed",str)); + calc_rmd160_sha256(rmd160,pk,CRYPTO_PUBLICKEYBYTES); + bitcoin_address(coinaddr,38,rmd160,20); + result.push_back(Pair("pkaddr",coinaddr)); + calc_rmd160_sha256(rmd160,sk,CRYPTO_SECRETKEYBYTES); + bitcoin_address(coinaddr,188,rmd160,20); + result.push_back(Pair("skaddr",coinaddr)); if ( externalflag == 0 ) result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); result.push_back(Pair("result","success")); From 6cdadf77f0f9035e8c7b7020930974d4e8a57ddd Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 05:07:51 -1100 Subject: [PATCH 1085/1145] define --- src/cc/dilithium.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 87d55c35d..730e76faa 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2841,6 +2841,9 @@ int32_t main(void) } #endif +void calc_rmd160_sha256(uint8_t rmd160[20],uint8_t *data,int32_t datalen); +char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160,int32_t len); + UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr,str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; From d689598506cb4b9770bfe1081316a077d3b5d0eb Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 05:09:30 -1100 Subject: [PATCH 1086/1145] [64] --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 730e76faa..65c17c8fb 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2846,7 +2846,7 @@ char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160, UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr,str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; + UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr[64],str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; //randombytes(seed,SEEDBYTES); Myprivkey(seed); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 1 ) From 03920374e4a6ea93530affad1631456ae43271b5 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 05:12:08 -1100 Subject: [PATCH 1087/1145] Try to map base58 address to P... and S.. --- src/cc/dilithium.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 65c17c8fb..cfc482290 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2869,10 +2869,10 @@ UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *para str[i<<1] = 0; result.push_back(Pair("seed",str)); calc_rmd160_sha256(rmd160,pk,CRYPTO_PUBLICKEYBYTES); - bitcoin_address(coinaddr,38,rmd160,20); + bitcoin_address(coinaddr,55,rmd160,20); result.push_back(Pair("pkaddr",coinaddr)); calc_rmd160_sha256(rmd160,sk,CRYPTO_SECRETKEYBYTES); - bitcoin_address(coinaddr,188,rmd160,20); + bitcoin_address(coinaddr,63,rmd160,20); result.push_back(Pair("skaddr",coinaddr)); if ( externalflag == 0 ) result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); From b6990f5f5ef7fc5a40251583873c9cda76620bb4 Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sun, 24 Feb 2019 01:05:18 +0800 Subject: [PATCH 1088/1145] working single node multi sign --- src/cc/musig.cpp | 24 +++++++++++++++++------- src/musigtest.py | 38 ++++++++++++++++++++------------------ 2 files changed, 37 insertions(+), 25 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index cdf53be09..d50ee92d8 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -525,8 +525,13 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * n_commitments: the length of commitments and signers array. Must be the total * number of signers participating in the MuSig. */ + if ( ind != MUSIG[myind]->num-1 ) + { + //fprintf(stderr, "ind.%i MUSIG[myind]->num.%i\n", ind, MUSIG[myind]->num); + return(cclib_error(result,"need rest of nonce's to continue")); + } result.push_back(Pair("added_index",ind)); - fprintf(stderr, "COMMIT: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); + //fprintf(stderr, "COMMIT: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG[myind]->session,MUSIG[myind]->signer_data,&MUSIG[myind]->nonces[MUSIG[myind]->myind],MUSIG[myind]->commitment_ptrs,MUSIG[myind]->num) > 0 ) { if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG[myind]->nonces[MUSIG[myind]->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) @@ -567,7 +572,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) else if ( musig_parsepubkey(ctx,MUSIG[myind]->nonces[ind],jitem(params,3)) < 0 ) return(cclib_error(result,"error parsing nonce")); result.push_back(Pair("added_index",ind)); - fprintf(stderr, "NONCE: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); + //fprintf(stderr, "NONCE: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); /** Checks a signer's public nonce against a commitment to said nonce, and update * data structure if they match * @@ -578,15 +583,15 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * been used with `musig_session_get_public_nonce` or initialized * with `musig_session_initialize_verifier`. * In: nonce: signer's alleged public nonce (cannot be NULL) - * + */ if ( ind != MUSIG[myind]->num-1 ) { - fprintf(stderr, "ind.%i MUSIG[myind]->num.%i\n", ind, MUSIG[myind]->num); + //fprintf(stderr, "ind.%i MUSIG[myind]->num.%i\n", ind, MUSIG[myind]->num); return(cclib_error(result,"need rest of nonce's to continue")); - }*/ + } for (i=0; inum; i++) { - fprintf(stderr, "setting nonce for index.%i\n",i); + //fprintf(stderr, "setting nonce for index.%i\n",i); if ( secp256k1_musig_set_nonce(ctx,&MUSIG[myind]->signer_data[i],&MUSIG[myind]->nonces[i]) == 0 ) return(cclib_error(result,"error setting nonce")); } @@ -648,7 +653,12 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG[myind]->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); result.push_back(Pair("added_index",ind)); - fprintf(stderr, "PARTIALSIG: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); + //fprintf(stderr, "PARTIALSIG: number of MUSIG structs.%li using struct.%i addedindex.%i\n",MUSIG.size(),myind,ind); + if ( ind != MUSIG[myind]->num-1 ) + { + //fprintf(stderr, "ind.%i MUSIG[myind]->num.%i\n", ind, MUSIG[myind]->num); + return(cclib_error(result,"need rest of nonce's to continue")); + } if ( secp256k1_musig_partial_sig_combine(ctx,&MUSIG[myind]->session,&sig,MUSIG[myind]->partial_sig,MUSIG[myind]->num) > 0 ) { if ( secp256k1_schnorrsig_serialize(ctx,out64,&sig) > 0 ) diff --git a/src/musigtest.py b/src/musigtest.py index 26f09d588..9a28bb2d4 100755 --- a/src/musigtest.py +++ b/src/musigtest.py @@ -121,7 +121,7 @@ for pubkey in pubkeys: commitments.append(rpc.cclib("session", "18", tmp)['commitment']) i = i + 1 -print(commitments) +#print(commitments) i = 0 nonces = [] @@ -129,17 +129,16 @@ for pubkey in pubkeys: ret = rpc.setpubkey(pubkey) n = 0 for commitment in commitments: - if n == i: - n = n + 1 - continue; tmp = str([i, pkhash, n, commitment]) ret = rpc.cclib("commit", "18", tmp) - if len(ret) == 4: + try: nonces.append(ret['nonce']) + except: + x = 1 n = n + 1 i = i + 1 -print(nonces) +#print(nonces) i = 0 partialsigs = [] @@ -147,18 +146,17 @@ for pubkey in pubkeys: ret = rpc.setpubkey(pubkey) n = 0 for nonce in nonces: - #if n == i: - # n = n + 1 - # continue; tmp = str([i, pkhash, n, nonce]) ret = rpc.cclib("nonce", "18", tmp) print(ret) - if len(ret) == 4: + try: partialsigs.append(ret['partialsig']) + except: + x = 1 n = n + 1 i = i + 1 -print(partialsigs) +#print(partialsigs) i = 0 combinedsigs = [] @@ -166,24 +164,28 @@ for pubkey in pubkeys: ret = rpc.setpubkey(pubkey) n = 0 for partialsig in partialsigs: - if n == i: - n = n + 1 - continue; tmp = str([i, pkhash, n, partialsig]) ret = rpc.cclib("partialsig", "18", tmp) - if len(ret) == 4: + print(ret) + try: combinedsigs.append(ret['combinedsig']) + except: + x = 1 n = n + 1 i = i + 1 -print(combinedsigs) +#print(combinedsigs) tmp = str([msg, combinedpk, combinedsigs[0]]) ret = rpc.cclib("verify", "18", tmp) -print(ret) +#print(ret) -tmp = str([sendtxid, scriptPubKey, combinedsigs[0]]) +tmp = str([senttxid, scriptPubKey, combinedsigs[0]]) ret = rpc.cclib("spend", "18", tmp) print(ret) + +ret = rpc.sendrawtransaction(ret['hex']) + +print(ret) From d25a12fb8403d1041d9f0f9d9436de2ad9585095 Mon Sep 17 00:00:00 2001 From: ca333 Date: Sun, 24 Feb 2019 00:30:29 +0100 Subject: [PATCH 1089/1145] fix build --- src/Makefile.am | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index fa2c17b5d..c32551c2c 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -578,7 +578,8 @@ komodod_LDADD += libcc.dylib $(LIBSECP256K1) endif if TARGET_WINDOWS komodod_LDADD += libcc.dll $(LIBSECP256K1) -else +endif +if TARGET_LINUX komodod_LDADD += libcc.so $(LIBSECP256K1) endif From 6722c9bc2063b72e2884493a3227741b8ce5418e Mon Sep 17 00:00:00 2001 From: ca333 Date: Sun, 24 Feb 2019 00:52:39 +0100 Subject: [PATCH 1090/1145] add linux target --- src/Makefile.am | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Makefile.am b/src/Makefile.am index c32551c2c..f06de8910 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -36,7 +36,8 @@ LIBBITCOIN_SERVER=libbitcoin_server.a -lcurl endif if TARGET_DARWIN LIBBITCOIN_SERVER=libbitcoin_server.a -lcurl -else +endif +if TARGET_LINUX LIBBITCOIN_SERVER=libbitcoin_server.a -lcurl endif From 2968a6b6339d72618549759d444fd707a1dca673 Mon Sep 17 00:00:00 2001 From: ca333 Date: Sun, 24 Feb 2019 00:57:05 +0100 Subject: [PATCH 1091/1145] add linux target --- configure.ac | 1 + 1 file changed, 1 insertion(+) diff --git a/configure.ac b/configure.ac index 9a1a75f53..12256c0cc 100644 --- a/configure.ac +++ b/configure.ac @@ -884,6 +884,7 @@ fi AM_CONDITIONAL([TARGET_DARWIN], [test x$TARGET_OS = xdarwin]) AM_CONDITIONAL([BUILD_DARWIN], [test x$BUILD_OS = xdarwin]) +AM_CONDITIONAL([TARGET_LINUX], [test x$TARGET_OS = xlinux]) AM_CONDITIONAL([TARGET_WINDOWS], [test x$TARGET_OS = xwindows]) AM_CONDITIONAL([ENABLE_WALLET],[test x$enable_wallet = xyes]) AM_CONDITIONAL([ENABLE_MINING],[test x$enable_mining = xyes]) From 41c82bee96a9fc6f30f82e0e9d604d80d98d09c3 Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Sun, 24 Feb 2019 11:53:17 +0800 Subject: [PATCH 1092/1145] stop print flood --- src/musigtest.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/musigtest.py b/src/musigtest.py index 9a28bb2d4..0880f1494 100755 --- a/src/musigtest.py +++ b/src/musigtest.py @@ -148,7 +148,6 @@ for pubkey in pubkeys: for nonce in nonces: tmp = str([i, pkhash, n, nonce]) ret = rpc.cclib("nonce", "18", tmp) - print(ret) try: partialsigs.append(ret['partialsig']) except: @@ -166,7 +165,6 @@ for pubkey in pubkeys: for partialsig in partialsigs: tmp = str([i, pkhash, n, partialsig]) ret = rpc.cclib("partialsig", "18", tmp) - print(ret) try: combinedsigs.append(ret['combinedsig']) except: From 74070330f5b68c0e164af1b3e186ce118e7ed3c7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 20:31:30 -1100 Subject: [PATCH 1093/1145] Lose 20% gold if killed, remove single player reduction of gold conversion --- src/cc/dilithium.c | 3 +++ src/cc/rogue_rpc.cpp | 29 ++++++++++++++++++----------- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index cfc482290..996d4f2b1 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2877,6 +2877,7 @@ UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *para if ( externalflag == 0 ) result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); result.push_back(Pair("result","success")); + // make a tx that has pubkey in opreturn return(result); } @@ -2897,11 +2898,13 @@ UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); + // copy musig method return(result); } UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { UniValue result(UniValue::VOBJ); + // copy musig method return(result); } diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 5aa5b3a8d..8cfb4379f 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -882,8 +882,9 @@ char *rogue_extractgame(int32_t makefiles,char *str,int32_t *numkeysp,std::vecto } if ( endP.gold <= 0 || endP.hitpoints <= 0 || (endP.strength&0xffff) <= 0 || endP.level <= 0 || endP.experience <= 0 || endP.dungeonlevel <= 0 ) { - fprintf(stderr,"zero value character was killed -> no playerdata\n"); - newdata.resize(0); + //fprintf(stderr,"zero value character was killed -> no playerdata\n"); + //newdata.resize(0); + P.gold = (P.gold * 8) / 10; } sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); fprintf(stderr,"%s\n",str); @@ -1018,22 +1019,23 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param newdata[i] = player[i]; ((uint8_t *)&P)[i] = player[i]; } - if ( 0 && (P.gold <= 0 || P.hitpoints <= 0 || (P.strength&0xffff) <= 0 || P.level <= 0 || P.experience <= 0 || P.dungeonlevel <= 0) ) + if ( (P.gold <= 0 || P.hitpoints <= 0 || (P.strength&0xffff) <= 0 || P.level <= 0 || P.experience <= 0 || P.dungeonlevel <= 0) ) { - fprintf(stderr,"zero value character was killed -> no playerdata\n"); - newdata.resize(0); + //fprintf(stderr,"zero value character was killed -> no playerdata\n"); + //newdata.resize(0); + P.gold = (P.gold * 8) / 10; } - else + //else { - if ( maxplayers == 1 ) - mult /= 2; + //if ( maxplayers == 1 ) + // mult /= 2; cpTokens = CCinit(&tokensC, EVAL_TOKENS); mtx.vout.push_back(MakeCC1vout(EVAL_TOKENS, txfee, GetUnspendable(cpTokens,NULL))); // marker to token cc addr, burnable and validated mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,1,mypk)); - fprintf(stderr,"\nextracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d n.%d amulet.%d\n",P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel,n,P.amulet); if ( P.amulet != 0 ) mult *= 5; cashout = (uint64_t)P.gold * mult; + fprintf(stderr,"\nextracted $$$gold.%d -> %.8f ROGUE hp.%d strength.%d/%d level.%d exp.%d dl.%d n.%d amulet.%d\n",P.gold,(double)cashout/COIN,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel,n,P.amulet); if ( funcid == 'H' && maxplayers > 1 ) { if ( (numplayers != maxplayers || (numplayers - rogue_playersalive(tmp,gametxid,maxplayers)) > 1) && P.amulet == 0 ) @@ -1271,13 +1273,18 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp fprintf(stderr,"%s matched after clearing maxstrength good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); return(0); } - bad++; for (i=0; i no playerdata\n"); + fprintf(stderr,"zero value character was killed -> no playerdata, good.%d bad.%d\n",good,bad); + if ( newdata.size() == 0 ) + { + good++; + return(0); + } } + bad++; fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); } From 4220a1cc929d39b00674849fb1d6e4c928c2fb37 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:07:14 -1100 Subject: [PATCH 1094/1145] Dilithium register, sign, verify rpc calls --- src/cc/cclib.cpp | 28 ++++++- src/cc/dilithium.c | 197 ++++++++++++++++++++++++++++++++++++++------- src/cc/musig.cpp | 47 +++-------- 3 files changed, 206 insertions(+), 66 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 4f539b7f9..20cc8ee32 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -82,8 +82,9 @@ CClib_methods[] = { (char *)"musig", (char *)"send", (char *)"combined_pk amount", 2, 2, 'x', EVAL_MUSIG }, { (char *)"musig", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_MUSIG }, { (char *)"dilithium", (char *)"keypair", (char *)"[hexseed]", 0, 1, 'K', EVAL_DILITHIUM }, - { (char *)"dilithium", (char *)"sign", (char *)"msg privkey", 2, 2, 'S', EVAL_DILITHIUM }, - { (char *)"dilithium", (char *)"verify", (char *)"msg sig pubtxid", 3, 3, 'V', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"register", (char *)"handle, [hexseed]", 1, 2, 'R', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"sign", (char *)"msg [hexseed]", 1, 2, 'S', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"verify", (char *)"pubtxid msg sig", 3, 3, 'V', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"send", (char *)"pubtxid amount", 2, 2, 'x', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_DILITHIUM }, #endif @@ -126,6 +127,7 @@ UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +UniValue dilithium_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); @@ -264,6 +266,8 @@ UniValue CClib_method(struct CCcontract_info *cp,char *method,char *jsonstr) return(dilithium_spend(txfee,cp,params)); else if ( strcmp(method,"keypair") == 0 ) return(dilithium_keypair(txfee,cp,params)); + else if ( strcmp(method,"register") == 0 ) + return(dilithium_register(txfee,cp,params)); else if ( strcmp(method,"sign") == 0 ) return(dilithium_sign(txfee,cp,params)); else if ( strcmp(method,"verify") == 0 ) @@ -573,6 +577,26 @@ uint256 juint256(cJSON *obj) return(revuint256(tmp)); } +int32_t cclib_parsepubkey(secp256k1_context *ctx,secp256k1_pubkey &spk,cJSON *item) +{ + char *hexstr; + if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 66 ) + { + CPubKey pk(ParseHex(hexstr)); + if ( secp256k1_ec_pubkey_parse(ctx,&spk,pk.begin(),33) > 0 ) + return(1); + } else return(-1); +} + +int32_t cclib_parsehash(uint8_t *hash32,cJSON *item,int32_t len) +{ + char *hexstr; + if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == len*2 ) + { + decode_hex(hash32,len,hexstr); + return(0); + } else return(-1); +} #ifdef BUILD_ROGUE #include "rogue_rpc.cpp" diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 996d4f2b1..5881d0840 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2841,58 +2841,195 @@ int32_t main(void) } #endif +#define DILITHIUM_TXFEE 10000 + void calc_rmd160_sha256(uint8_t rmd160[20],uint8_t *data,int32_t datalen); char *bitcoin_address(char *coinaddr,uint8_t addrtype,uint8_t *pubkey_or_rmd160,int32_t len); +CScript dilithium_registeropret(std::string handle,CPubKey pk,std::vector bigpub) +{ + CScript opret; uint8_t evalcode = EVAL_DILITHIUM; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'R' << handle << pk << bigpub); + return(opret); +} + +uint8_t dilithium_registeropretdecode(std::string &handle,CPubKey &pk,std::vector &bigpub,CScript scriptPubKey) +{ + std::vector vopret; uint8_t e,f; + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> handle; ss >> pk; ss >> bigpub) != 0 && e == EVAL_DILITHIUM && f == 'R' ) + { + return(f); + } + return(0); +} + +UniValue dilithium_rawtxresult(UniValue &result,std::string rawtx) +{ + CTransaction tx; + if ( rawtx.size() > 0 ) + { + result.push_back(Pair("hex",rawtx)); + if ( DecodeHexTx(tx,rawtx) != 0 ) + { + //if ( broadcastflag != 0 && myAddtomempool(tx) != 0 ) + // RelayTransaction(tx); + result.push_back(Pair("txid",tx.GetHash().ToString())); + result.push_back(Pair("result","success")); + } else result.push_back(Pair("error","decode hex")); + } else result.push_back(Pair("error","couldnt finalize CCtx")); + return(result); +} + +char *dilithium_addr(char *coinaddr,uint8_t *buf,int32_t len) +{ + uint8_t rmd160[20],addrtype; + if ( len == CRYPTO_PUBLICKEYBYTES ) + addrtype = 55; + else if ( len == CRYPTO_SECRETKEYBYTES ) + addrtype = 63; + else + { + strcpy(coinaddr,"unexpected len.%d",len); + return(coinaddr); + } + calc_rmd160_sha256(rmd160,buf,len); + bitcoin_address(coinaddr,addrtype,rmd160,20); + return(coinaddr); +} + +char *dilithium_hexstr(char *str,uint8_t *buf,int32_t len) +{ + int32_t i; + for (i=0; i bigpub; + if ( myGetTransaction(pubtxid,tx,hashBlock) != 0 && (numvouts= tx.vout.size()) > 1 ) + { + if ( dilithium_registeropretdecode(handle,pk33,bigpub,tx.vout[numvouts-1].scriptPubKey) == 'R' && bigpub.size() == CRYPTO_PUBLICKEYBYTES ) + { + memcpy(pk,&bigpub[0],CRYPTO_PUBLICKEYBYTES); + return(0); + } else return(-2); + } + return(-1); +} + UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr[64],str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; - //randombytes(seed,SEEDBYTES); + UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr[64],str[CRYPTO_SECRETKEYBYTES*2+1]; int32_t i,n,externalflag=0; Myprivkey(seed); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 1 ) { - if ( musig_parsehash(seed,jitem(params,0),32) < 0 ) - return(cclib_error(result,"error parsing seed")); - else externalflag = 1; + if ( cclib_parsehash(seed,jitem(params,0),32) < 0 ) + { + randombytes(seed,SEEDBYTES); + result.push_back(Pair("status","using random high entropy seed")); + } + externalflag = 1; } _dilithium_keypair(pk,sk,seed); - for (i=0; i bigpub; int32_t i,n,warningflag = 0; + if ( txfee == 0 ) + txfee = DILITHIUM_TXFEE; + mypk = pubkey2pk(Mypubkey()); + dilithiumpk = GetUnspendable(cp,0); + if ( params != 0 && ((n= cJSON_GetArraySize(params)) == 1 || n == 2) ) + { + std::string handle(jstr(jitem(params,0),0)); + result.push_back(Pair("handle",handle)); + if ( n == 2 || cclib_parsehash(seed,jitem(params,1),32) < 0 ) + { + Myprivkey(seed); + result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); + } + _dilithium_keypair(pk,sk,seed); + result.push_back(Pair("seed",dilithium_hexstr(str,seed,SEEDBYTES))); + result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); + result.push_back(Pair("skaddr",dilithium_addr(coinaddr,sk,CRYPTO_SECRETKEYBYTES))); + for (i=0; i= 3*txfee ) + { + mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,dilithiumpk)); + mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,mypk)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_registeropret('R',handle,mypk,bigpub)); + return(musig_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt find enough funds")); + } else return(cclib_error(result,"not enough parameters")); +} + UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - //_dilithium_sign(sm, &smlen, m, MLEN, sk); // 7.2 - - return(result); + UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],msg[32],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1],sm[32+CRYPTO_BYTES]; int32_t n,smlen; + if ( params != 0 && ((n= cJSON_GetArraySize(params)) == 1 || n == 2) ) + { + if ( cclib_parsehash(msg,jitem(params,0),32) < 0 ) + return(cclib_error(result,"couldnt parse message to sign")); + else if ( n == 2 || cclib_parsehash(seed,jitem(params,1),32) < 0 ) + { + Myprivkey(seed); + result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); + } + _dilithium_keypair(pk,sk,seed); + result.push_back(Pair("msg32",dilithium_hexstr(str,msg,32))); + result.push_back(Pair("seed",dilithium_hexstr(str,seed,SEEDBYTES))); + result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); + result.push_back(Pair("skaddr",dilithium_addr(coinaddr,sk,CRYPTO_SECRETKEYBYTES))); + _dilithium_sign(sm,&smlen,msg,32,sk); + if ( smlen == 32+CRYPTO_BYTES ) + { + result.push_back(Pair("signature",dilithium_hexstr(str,sm,smlen))); + calc_rmd160_sha256(rmd160,sm,smlen); + result.push_back(Pair("sighash",dilithium_hexstr(str,rmd160,20))); + } else return(cclib_error(result,"unexpected signed message len")); + } else return(cclib_error(result,"not enough parameters")); } UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - return(result); + UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1],sm[32+CRYPTO_BYTES]; int32_t mlen,n; + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + { + pubtxid = juint256(jitem(params,0)); + if ( dilithium_bigpubget(handle,pk33,pk,pubtxid) < 0 ) + return(cclib_error(result,"couldnt parse message to sign")); + else if ( cclib_parsehash(msg,jitem(params,1),32) < 0 ) + return(cclib_error(result,"couldnt parse message to sign")); + else if ( cclib_parsehash(sm,jitem(params,2),32+CRYPTO_BYTES) < 0 ) + return(cclib_error(result,"couldnt parse sig")); + else if ( _dilithium_verify(msg2,&mlen,sm,smlen,pk) < 0 ) + return(cclib_error(result,"dilithium verify error")); + else if ( mlen != 32 ) + return(cclib_error(result,"message len mismatch")); + else if ( memcmp(msg2,msg,32) != 0 ) + return(cclib_error(result,"message content mismatch")); + result.push_back(Pair("msg32",dilithium_hexstr(str,msg,32))); + result.push_back(Pair("handle",handle)); + result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); + result.push_back(Pair("result","success")); + return(result); + } else return(cclib_error(result,"not enough parameters")); } UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 6dbab482a..f4ba51d47 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -362,27 +362,6 @@ UniValue musig_calcmsg(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } else return(cclib_error(result,"couldnt parse params")); } -int32_t musig_parsepubkey(secp256k1_context *ctx,secp256k1_pubkey &spk,cJSON *item) -{ - char *hexstr; - if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 66 ) - { - CPubKey pk(ParseHex(hexstr)); - if ( secp256k1_ec_pubkey_parse(ctx,&spk,pk.begin(),33) > 0 ) - return(1); - } else return(-1); -} - -int32_t musig_parsehash(uint8_t *hash32,cJSON *item,int32_t len) -{ - char *hexstr; - if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == len*2 ) - { - decode_hex(hash32,len,hexstr); - return(0); - } else return(-1); -} - UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; @@ -395,7 +374,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //fprintf(stderr,"n.%d args.(%s)\n",n,jprint(params,0)); for (i=0; icombined_pk,jitem(params,2)) < 0 ) + if ( cclib_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing combined_pubkey")); - else if ( musig_parsehash(MUSIG->pkhash,jitem(params,3),32) < 0 ) + else if ( cclib_parsehash(MUSIG->pkhash,jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( musig_parsehash(MUSIG->msg,jitem(params,4),32) < 0 ) + else if ( cclib_parsehash(MUSIG->msg,jitem(params,4),32) < 0 ) return(cclib_error(result,"error parsing msg")); Myprivkey(privkey); GetRandBytes(session,32); @@ -497,13 +476,13 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) + if ( cclib_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash(&MUSIG->nonce_commitments[ind*32],jitem(params,2),32) < 0 ) + else if ( cclib_parsehash(&MUSIG->nonce_commitments[ind*32],jitem(params,2),32) < 0 ) return(cclib_error(result,"error parsing commitment")); /** Gets the signer's public nonce given a list of all signers' data with commitments * @@ -550,13 +529,13 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) + if ( cclib_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) + else if ( cclib_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing nonce")); result.push_back(Pair("added_index",ind)); /** Checks a signer's public nonce against a commitment to said nonce, and update @@ -620,13 +599,13 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash(pkhash,jitem(params,0),32) < 0 ) + if ( cclib_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsehash(psig,jitem(params,2),32) < 0 ) + else if ( cclib_parsehash(psig,jitem(params,2),32) < 0 ) return(cclib_error(result,"error parsing psig")); else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); @@ -669,11 +648,11 @@ UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { - if ( musig_parsehash(msg,jitem(params,0),32) < 0 ) + if ( cclib_parsehash(msg,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( musig_parsepubkey(ctx,combined_pk,jitem(params,1)) < 0 ) + else if ( cclib_parsepubkey(ctx,combined_pk,jitem(params,1)) < 0 ) return(cclib_error(result,"error parsing combined_pk")); - else if ( musig_parsehash(musig64,jitem(params,2),64) < 0 ) + else if ( cclib_parsehash(musig64,jitem(params,2),64) < 0 ) return(cclib_error(result,"error parsing musig64")); for (i=0; i<32; i++) sprintf(&str[i*2],"%02x",msg[i]); From 4551484dc3da7d4fcc47e52fdc904da31ed4ff6b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:09:23 -1100 Subject: [PATCH 1095/1145] Revert musig_parsepubkey --- src/cc/cclib.cpp | 11 ----------- src/cc/musig.cpp | 19 +++++++++++++++---- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 20cc8ee32..8382ba8a0 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -577,17 +577,6 @@ uint256 juint256(cJSON *obj) return(revuint256(tmp)); } -int32_t cclib_parsepubkey(secp256k1_context *ctx,secp256k1_pubkey &spk,cJSON *item) -{ - char *hexstr; - if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 66 ) - { - CPubKey pk(ParseHex(hexstr)); - if ( secp256k1_ec_pubkey_parse(ctx,&spk,pk.begin(),33) > 0 ) - return(1); - } else return(-1); -} - int32_t cclib_parsehash(uint8_t *hash32,cJSON *item,int32_t len) { char *hexstr; diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index f4ba51d47..d93792463 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -304,6 +304,17 @@ uint8_t musig_spendopretdecode(CPubKey &pk,std::vector &musig64,CScript return(0); } +int32_t musig_parsepubkey(secp256k1_context *ctx,secp256k1_pubkey &spk,cJSON *item) +{ + char *hexstr; + if ( (hexstr= jstr(item,0)) != 0 && is_hexstr(hexstr,0) == 66 ) + { + CPubKey pk(ParseHex(hexstr)); + if ( secp256k1_ec_pubkey_parse(ctx,&spk,pk.begin(),33) > 0 ) + return(1); + } else return(-1); +} + int32_t musig_msghash(uint8_t *msg,uint256 prevhash,int32_t prevn,CTxOut vout,CPubKey pk) { CScript data; uint256 hash; int32_t len = 0; @@ -374,7 +385,7 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) //fprintf(stderr,"n.%d args.(%s)\n",n,jprint(params,0)); for (i=0; icombined_pk,jitem(params,2)) < 0 ) + if ( musig_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing combined_pubkey")); else if ( cclib_parsehash(MUSIG->pkhash,jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); @@ -535,7 +546,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(cclib_error(result,"pkhash doesnt match session pkhash")); else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) return(cclib_error(result,"illegal ind for session")); - else if ( cclib_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) + else if ( musig_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing nonce")); result.push_back(Pair("added_index",ind)); /** Checks a signer's public nonce against a commitment to said nonce, and update @@ -650,7 +661,7 @@ UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { if ( cclib_parsehash(msg,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( cclib_parsepubkey(ctx,combined_pk,jitem(params,1)) < 0 ) + else if ( musig_parsepubkey(ctx,combined_pk,jitem(params,1)) < 0 ) return(cclib_error(result,"error parsing combined_pk")); else if ( cclib_parsehash(musig64,jitem(params,2),64) < 0 ) return(cclib_error(result,"error parsing musig64")); From 89d221c232400573fe5231d292b4fa8cf3c1d28d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:10:45 -1100 Subject: [PATCH 1096/1145] Syntax --- src/cc/dilithium.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 5881d0840..46b05cc50 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2890,7 +2890,7 @@ char *dilithium_addr(char *coinaddr,uint8_t *buf,int32_t len) addrtype = 63; else { - strcpy(coinaddr,"unexpected len.%d",len); + sprintf(coinaddr,"unexpected len.%d",len); return(coinaddr); } calc_rmd160_sha256(rmd160,buf,len); @@ -2968,12 +2968,12 @@ UniValue dilithium_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *par result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); result.push_back(Pair("skaddr",dilithium_addr(coinaddr,sk,CRYPTO_SECRETKEYBYTES))); for (i=0; i= 3*txfee ) { mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,dilithiumpk)); mtx.vout.push_back(MakeCC1vout(cp->evalcode,txfee,mypk)); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_registeropret('R',handle,mypk,bigpub)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_registeropret(handle,mypk,bigpub)); return(musig_rawtxresult(result,rawtx)); } else return(cclib_error(result,"couldnt find enough funds")); } else return(cclib_error(result,"not enough parameters")); From 2eec7b0bfb696b06988427609a621e5e1f720b53 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:12:20 -1100 Subject: [PATCH 1097/1145] Syntax --- src/cc/dilithium.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 46b05cc50..c7ab0d4cb 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2981,7 +2981,7 @@ UniValue dilithium_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *par UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],msg[32],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1],sm[32+CRYPTO_BYTES]; int32_t n,smlen; + UniValue result(UniValue::VOBJ); uint8_t seed[SEEDBYTES],msg[32],rmd160[20],pk[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES],sm[32+CRYPTO_BYTES]; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t n,smlen; if ( params != 0 && ((n= cJSON_GetArraySize(params)) == 1 || n == 2) ) { if ( cclib_parsehash(msg,jitem(params,0),32) < 0 ) @@ -3008,7 +3008,7 @@ UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1],sm[32+CRYPTO_BYTES]; int32_t mlen,n; + UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1],sm[32+CRYPTO_BYTES]; int32_t mlen,n; std::string handle; if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { pubtxid = juint256(jitem(params,0)); From cdd14fd61a312a61d7b3d8dcdf252bd27c717e1e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:13:13 -1100 Subject: [PATCH 1098/1145] uint8 --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index c7ab0d4cb..e4a7e24ac 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3008,7 +3008,7 @@ UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1],sm[32+CRYPTO_BYTES]; int32_t mlen,n; std::string handle; + UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t mlen,n; std::string handle; if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { pubtxid = juint256(jitem(params,0)); From 4acaa5e7fb546c3ae5d0201c1f3a8ff881025e5f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:14:10 -1100 Subject: [PATCH 1099/1145] Smell --- src/cc/dilithium.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index e4a7e24ac..59f53e829 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3008,7 +3008,7 @@ UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t mlen,n; std::string handle; + UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t smlen=32+CRYPTO_BYTES,mlen,n; std::string handle; if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { pubtxid = juint256(jitem(params,0)); @@ -3016,7 +3016,7 @@ UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(cclib_error(result,"couldnt parse message to sign")); else if ( cclib_parsehash(msg,jitem(params,1),32) < 0 ) return(cclib_error(result,"couldnt parse message to sign")); - else if ( cclib_parsehash(sm,jitem(params,2),32+CRYPTO_BYTES) < 0 ) + else if ( cclib_parsehash(sm,jitem(params,2),smlen) < 0 ) return(cclib_error(result,"couldnt parse sig")); else if ( _dilithium_verify(msg2,&mlen,sm,smlen,pk) < 0 ) return(cclib_error(result,"dilithium verify error")); From 27564336b7c94232b7c1819db73404c25f826b37 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:25:28 -1100 Subject: [PATCH 1100/1145] Off by one --- src/cc/dilithium.c | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 59f53e829..d8fcef08c 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2841,6 +2841,28 @@ int32_t main(void) } #endif +////////////////////////////////////////////////////// +/* First register a pubkey,ie. bind handle, pub33 and bigpub together and then can be referred by pubtxid in other calls + + cclib register 19 \"[%22jl777%22]\" + { + "handle": "jl777", + "warning": "test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!", + "pkaddr": "PNoTcVH8G5TBTQigyVZTsaMMNYYRvywUNu", + "skaddr": "SejsccjwGrZKaziD1kpfgQhXA32xvzP75i", + "hex": "0400008085202f89010184fa95fce1a13d441e6c87631f7d0ca5f22ad8b28ae4321e02177b125b5f2400000000494830450221009fb8ff0ea4e810f34e54f0a872952f364e6eb697bb4ab34ea571fd213299b685022017c0b09fc71ec2d2abf49e435a72d32ecc874d14aac39be7b9753704fad7d06c01ffffffff041027000000000000302ea22c8020979f9b424db4e028cdba433622c6cd17b9193763e68b4572cd7f3727dcd335978....00000000000", + "txid": "9d856b2be6e54c8f04ae3f86aef722b0535180b3e9eb926c53740e481a1715f9", + "result": "success" + } + + sendrawtransaction from above -> pubtxid 9d856b2be6e54c8f04ae3f86aef722b0535180b3e9eb926c53740e481a1715f9 + + now test signing some random 32 byte message + + cclib sign 19 \"[%22aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22]\" + + */ + #define DILITHIUM_TXFEE 10000 void calc_rmd160_sha256(uint8_t rmd160[20],uint8_t *data,int32_t datalen); @@ -2931,13 +2953,13 @@ UniValue dilithium_keypair(uint64_t txfee,struct CCcontract_info *cp,cJSON *para { randombytes(seed,SEEDBYTES); result.push_back(Pair("status","using random high entropy seed")); + result.push_back(Pair("seed",dilithium_hexstr(str,seed,SEEDBYTES))); } externalflag = 1; } _dilithium_keypair(pk,sk,seed); result.push_back(Pair("pubkey",dilithium_hexstr(str,pk,CRYPTO_PUBLICKEYBYTES))); result.push_back(Pair("privkey",dilithium_hexstr(str,sk,CRYPTO_SECRETKEYBYTES))); - result.push_back(Pair("seed",dilithium_hexstr(str,seed,SEEDBYTES))); result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); result.push_back(Pair("skaddr",dilithium_addr(coinaddr,sk,CRYPTO_SECRETKEYBYTES))); if ( externalflag == 0 ) @@ -2958,13 +2980,12 @@ UniValue dilithium_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *par { std::string handle(jstr(jitem(params,0),0)); result.push_back(Pair("handle",handle)); - if ( n == 2 || cclib_parsehash(seed,jitem(params,1),32) < 0 ) + if ( n == 1 || cclib_parsehash(seed,jitem(params,1),32) < 0 ) { Myprivkey(seed); result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); } _dilithium_keypair(pk,sk,seed); - result.push_back(Pair("seed",dilithium_hexstr(str,seed,SEEDBYTES))); result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); result.push_back(Pair("skaddr",dilithium_addr(coinaddr,sk,CRYPTO_SECRETKEYBYTES))); for (i=0; i Date: Sat, 23 Feb 2019 22:26:39 -1100 Subject: [PATCH 1101/1145] Return result --- src/cc/dilithium.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index d8fcef08c..35902f266 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3022,6 +3022,7 @@ UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("signature",dilithium_hexstr(str,sm,smlen))); calc_rmd160_sha256(rmd160,sm,smlen); result.push_back(Pair("sighash",dilithium_hexstr(str,rmd160,20))); + return(result); } else return(cclib_error(result,"unexpected signed message len")); } else return(cclib_error(result,"not enough parameters")); } From a0ece6b680f0bdb5a9742d4d7552ba1454e9fd08 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:31:29 -1100 Subject: [PATCH 1102/1145] Add sighash for easy compare --- src/cc/dilithium.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 35902f266..a60c63527 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2860,7 +2860,18 @@ int32_t main(void) now test signing some random 32 byte message cclib sign 19 \"[%22aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22]\" + { + "warning": "test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!", + "msg32": "aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848", + "pkaddr": "PNoTcVH8G5TBTQigyVZTsaMMNYYRvywUNu", + "skaddr": "SejsccjwGrZKaziD1kpfgQhXA32xvzP75i", + "signature": "be067f4bd81b9b0b772e0e2872cc086f6c2ff4c558a465afe80ab71c2c7b39a25ad8300629337c022d8c477cf7728cd11a3f6135bccfdbd68de5cd4517e70a70ec3b836041dc9c2f1abed65f2519e43a31ca6ad4991ce98460a14ee70d28c47f5a1d967c25b1ac93afea7e2b11...836b0f0efbcb26ee679f4f4848", + "sighash": "cfed6d7f059b87635bde6cb31accd736bf99ff3d" + } + it is a very big signature, but that seems to be dilithium sig size. let us verify it: + + cclib verify 19 \"[%229d856b2be6e54c8f04ae3f86aef722b0535180b3e9eb926c53740e481a1715f9%22,%22aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22,%22be067f4bd81b9b0b772e0e2872cc086f6c2ff4c558a465afe80ab71c2c7b39a25ad8300629337c022d8c477cf7728cd11a3f6135bccfdbd68de5cd4517e70a70ec3b836041dc9c2f1abed65f2519e43a31ca6ad4991ce98460a14ee70d28c47f5a1d967c25b1ac93afea7e2b11aa2fb715ac08bd3eac739425c67974ecd682f711a0b175b30278febfe55586650ed8b0098de745944450a6836b6ab23e0c5ebdd7503188428c3159f1671ca27d9d529d344d246e116b2001dbba085afe1bfcdd12d88ae2efbcead268b10cec4f76531aba594887dd239b59c4c676b348a56a1cc2e0032590c74513cfba7f03f8b6d7a14bb6f6a16ae743317ecd8551b3362dc892bcae550032682d130772f65b2e96a5ad4ce2b8e9a41a48c2a52c80f349c99dc110807e7c662f7ef960f628001ca9a9f249b53b23c4680e3a6acec89e3c26d0265b617353654f55a752f9ea3689570c068a414793c3575fae66f6fa425ce282a574981228a52e2ede14fbde3ac66a8e061a538bee737d17fbb48afc39cd914518ef2a182ce1feb66b1a8bf9934b6fef491f2bd3598e3421399fe11754bc61e149e8846f74d44d96c7dc47f06d04d6c09dc2b2c9d78e76a713722eec637f8e3fb5cd5adfd8ba2ce05dacdf2f9522e89bff2ee745d49873755a0079835e982c6c55fd9a96597505d79090da8df4feb422422b1d6427fde4242aafcb6ed581d8e4ffd722daf56fd45b017a2a2fa2f4e30a3a457686bdd184505461fc6749e4a20b7faa2a1d9a295a445ea564b84c1b820d9cf5c06142353671f989565a3767bd6ddabfc3bf1368acdae8870580f21baa2093cea4447688e35719bd78c785821f944ecc9a093f9a65bf2584f1a0c68f70f11f2485e02f288c2c8b6692883983607960aa16065d22082121f6fd6588f07cd3fb57bba624fbb9c7077cb1400fe4edf48156b7622fab70cce1cbd17bde2f4c24b9a86d485727df413e06a6c31cab27284a69fd46e00fc6e80872ed5291b598c74964488ffdb19d0dc94fce37db3f5230d947cb4d83ae55e0357aab1ec86b63fe606f86a77aa78fc4fe986be450b74f1ffbb5ba9eeaea11c7c7ffa6d87a9d49767ce761614bd6cc5df3767ed6396b84354a9634bb3e35606e961fc023504473bf3b7e13244f19d1dee101af1854f80899f95409bb402a5267ad21ddba80e2dd0dd513d0fc88067ac4078e69c12bd19807c03a916d2a42cdbe7b4cdac4bc2314fe3369723d16c30bf277db823c1457f5ff64f3117b82b991ee8b65b7e6b8f7814a15b4ca8cebe88d12236cf1b7dd06b75cab506d78c2072fddf2002be366f43ca68866f87fe9a56808ab7f82aa925091e1f0fba371642039316939446b769973a9c93efe3104699ad3eceac89eb1c2507b65b43d21388f93ff28b194110d7114b97a10cb212515127ede0287d455791e1c6d554b0d8a4e75f2701bc3430786cc69081dbd96a73a308fc6a60fc773fdc7df49b1865c3e989f2a528872fd4c1715dadb11c801c1492ce07bde59e25a801bb542e2caef35f99ca4cb0a3f1d2c2c6e3895c94001a0b2cc648057c2e44c780655f93d56a2cd62a9d55eb8de45e9ec75bfa3d121223aba700062ba3f54162fb9ba136aca6aeb119bca9a0d6bf18e89f54d9ff09c6a2036f767098fbbaf20e10db25e43386ecda201c05e794805269f1a77e50657052d16ae1e154d706a7fa81c419b9d262766e8edb8fd6343f509bed44098ef741f10a6206474c3490354695762a5a4532dd0279abc38ef75a44899a5d8d0e77af638aedd07071f37a3c5f82bbbd05a7b4c0e23d2fc3a5bbc40a52f588c8592f02fb30be56ae0990b24a80690c0b5c9df29549f7dec89f62920a37d05c62c27a62ee01fea164bf28937cdc7d3f2937a5756ada91c2615ce7ed20f0ed07cf486b76d0a63d193363567746eff0ff90ace3dbdfb770d55161c84ccdebca1a600337e7ffed0fdfbc041ed44e0014cced03d1af55ae9fa14d87d60dfe96ac7cde67a1d8ea2150c00ba5fb9a0ec0eff5bd9f734da71edbe7e2f71b6465984c411de8a3cc77a337b2ffdee6ab6d904a79316c15d15176401bc7e72fabb1e9571c7e7188ba09a295400437e4b96549d9827fba6d3493bc6f58f95e240b0a0159054014e5e3103e3af4eef77d3896290c7bf930edbe77615d56aa0a93034c92830c1382c0c06726d2ec7d6c2ed45d3a9fb9646892402812f1df9a003705d3f549d84f9ed3b5fe3c40fcb0bcb28a0d32f2fa27fcdb82509a0725d7314a3eb99a701169fae9e3dcdc2cc20d73aa8b2c5feb645556a8b946581e4e9e82f6a19a21f5babd35d49810dc88923c4908eca3690b774f367a41c3a37b54af9847d73a7eed1ee45edaaed0f316d551c08e3e642cebc97ce71a811664ee9296e7fedffb90011cc353302acd931bc0d152d7e6332a8f0d71059987c3b90f3f57178dec3f30c58ded0bc80eb65b0c9b8d16ec73ebe17e31259181b2376405db17e279419f1c685ad71b6cc91c81a120de2db2c532e67bc3a58d22b549fae61f32398d03cb1f5e245cfec65c40c9dfd0b8a93812f67840c653c5304402a1ff6189fd24f8ce3482e5cf92b3581445009c3b586bb421459ce9457868787c78b787bd45df7e55c3165a92194d38b913a6ef6f31af4c2afcfd0158eb8eb2820f7d41e3efca9367528a0b6fe6ec3fd01082bc60a9fe2a13ab3705b3b0c07173d4d762c8de4b6598d30b97e32339aeb706de47170e1033603267c6ce8caa2977990cbda75984de4e5ede6e36ff889b53b2cbbebc37f9e56e78c62ff856bcb27aba8892ace8fcaae09b31d7f5f850596014e868003d632c9dc12e7c83f6de676d9ae4328862326572e2e0353d5547f7f73fdf5b0227b6d108ae28e3dc622d5ac3dcf98bd1461917d78468ac2912329027c1085611dce7a6b7b3fa8451a5c3c6b448b1b9ad9dd84308991e4688595bcb289ec4b99f63db0c18969bd4b5cdc14d85007d683f936ab3207b59e3971f86f8fb388e72bdc7c9fb3b466061223e85138ee6a5657e8862ca51819c9d92b339ac6900e9f60a71d4a1eb09707cedc32bb477c91a8b5792e850606e1de57122d017a2025423d40b48e0bbe711ec03381630b9003ff55e10ac6f0031dfc54ed54ccd3309abd17ee026958fdf23bb74d53b84d8e2ef150fb2216265454c5f6446e221ab1c95c086571cad14251f618c9c58a9dfb83f9a8c58c9c5c026b9bc8f90860acde16557c064f95b178a9776e463b2d7d658e4acfa1ea30c429c0b813a5872b02d7b0bafcc095e979f737834933fbbf1220c05a0b0346f5932c669c534e22ab5ab42c39fd0e062abff05a2d34060e6f539c7ae9244903d981095fac6cff5d20ac9d298de27cb1ea7079d6dcc47504f988e3bdd1c48ca23f9ec305950459446c51b879a62e75cbc3570d2dbf93594f299111e27b60e5193d6e766a40130ee5d33a43eb43aba5c5701de878fdeaa16c998607e7fbf6c8827cb1f914db9d73c6ae48a0cb416218cc50b335f171e4df050561dfb1669939ccf2c498ff1d8f53a7d7c77195348502c4ffd5c18362f4eb4c3077e504853ff1e84c6166e1f889781bf5dcccf0daf8ac0881ee7202650abdff8d6cda2f8bf3b6a96d23f5ffa0104ee72dd1e8ae7cd08258d36b50cb40048756216845815a3e01efd33d5fae86a0680920422325893296dcb2af0d6df21c7193e387092b61408aac63df4a79c3b1e54869ba3c43ae2a54446e64053c061dd8bb3e132be46d9a83b6675791f49aa9617345801e97be7f4f7159ba1d7da623c7868ad281ddbb0f75fec7fe56ff0a44a8ac3b51a1f784b2b039d6434f92d3254fd83b4221ca18883637a0eb12217ebc8e149681c21e0edbd11289cfa7f78d536d8858a60056b8c28916e1d34ce1a6d344034b2e72162a5fc92b137354c2b791e7ad6ee4679f71181188ba69c9ded078421885a6cc18bc58c383d190c11d236e53eaa39a99d157e4dd74bc4aa2ce1354511128d6b407007dbcaeb9c3b712ed2b334de23c66735f534a9dddb7ab2d06c6a4669d2bd38c8c812b287b39b3591ac77e617834ea7c4c38b1133f2cafdf51f9afca7f44e9b527d3e0e840b05ec8bf57fcceb8a28546a3593ff1b94ee6a8d7d28b8e6007d0ea7da80552e4382b3ff3b6152175083717f42c5c902131b0a27e23bbcf4ba03140a6dc3bcccbc8ca93ba6161fe3c36a1835e9e02695bac571a07f6b2267998213aa0c4c7b93c2ed3a58e12cab5a51edf462a30df14e7e32727b4da1f7f29e9ea30f65ab090b22e9ae00ae9419bf26a44482d536812e2b4c2e1fd2af622d827b04b67eac1052d2ccee68207b3b6ca3d96bc4de4039a3a3e50c58a17786edb08caad6091dab0e7beffd0acb748d5c5ef6a171d8d113c7c310f18712a53607dbf01653157090cdd19c5845c1b7e11a4a61c2229cbb1e6927c74f187964c646b007051841b1b83e670611c1e9eb0b2406ee432122613a4c7e9f60c2cf8db2d6032225604c1d5468b1e90bb57651c2223363743516164a4aab0b4bac2d70d1a254f687384889daee2fc2d32365d78878b8c9aabbbbcc8d7f4fb191d23283f4d5359767e8c99a1b8c8cddfe5040c1e2339606e788ca9cad6f2fc0712236a70c9cdd6fb0000000000000000000000000000000000000000000000000000000000000000000000101c2c3e4c55b80404422409560084401072601824140801b8244ae84401008080081022408cdea5834e5fd1220daff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22]\" */ #define DILITHIUM_TXFEE 10000 @@ -3029,7 +3040,7 @@ UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t smlen=32+CRYPTO_BYTES,mlen,n; std::string handle; + UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t rmd160[20],msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t smlen=32+CRYPTO_BYTES,mlen,n; std::string handle; if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { pubtxid = juint256(jitem(params,0)); @@ -3048,6 +3059,8 @@ UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *param result.push_back(Pair("msg32",dilithium_hexstr(str,msg,32))); result.push_back(Pair("handle",handle)); result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); + calc_rmd160_sha256(rmd160,sm,smlen); + result.push_back(Pair("sighash",dilithium_hexstr(str,rmd160,20))); result.push_back(Pair("result","success")); return(result); } else return(cclib_error(result,"not enough parameters")); From 16953993cce2f6ce0ffd23b8e38880457ceacec9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 22:33:48 -1100 Subject: [PATCH 1103/1145] Reorder --- src/cc/dilithium.c | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index a60c63527..a41e1ea59 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3050,19 +3050,22 @@ UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *param return(cclib_error(result,"couldnt parse message to sign")); else if ( cclib_parsehash(sm,jitem(params,2),smlen) < 0 ) return(cclib_error(result,"couldnt parse sig")); - else if ( _dilithium_verify(msg2,&mlen,sm,smlen,pk) < 0 ) - return(cclib_error(result,"dilithium verify error")); - else if ( mlen != 32 ) - return(cclib_error(result,"message len mismatch")); - else if ( memcmp(msg2,msg,32) != 0 ) - return(cclib_error(result,"message content mismatch")); - result.push_back(Pair("msg32",dilithium_hexstr(str,msg,32))); - result.push_back(Pair("handle",handle)); - result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); - calc_rmd160_sha256(rmd160,sm,smlen); - result.push_back(Pair("sighash",dilithium_hexstr(str,rmd160,20))); - result.push_back(Pair("result","success")); - return(result); + else + { + calc_rmd160_sha256(rmd160,sm,smlen); + result.push_back(Pair("sighash",dilithium_hexstr(str,rmd160,20))); + if ( _dilithium_verify(msg2,&mlen,sm,smlen,pk) < 0 ) + return(cclib_error(result,"dilithium verify error")); + else if ( mlen != 32 ) + return(cclib_error(result,"message len mismatch")); + else if ( memcmp(msg2,msg,32) != 0 ) + return(cclib_error(result,"message content mismatch")); + result.push_back(Pair("msg32",dilithium_hexstr(str,msg,32))); + result.push_back(Pair("handle",handle)); + result.push_back(Pair("pkaddr",dilithium_addr(coinaddr,pk,CRYPTO_PUBLICKEYBYTES))); + result.push_back(Pair("result","success")); + return(result); + } } else return(cclib_error(result,"not enough parameters")); } From 16771b99f2eb4c719ff4cf5bbcfc4843942df73a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:07:50 -1100 Subject: [PATCH 1104/1145] Dilithium send --- src/cc/cclib.cpp | 2 +- src/cc/dilithium.c | 39 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 8382ba8a0..c64ac025b 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -85,7 +85,7 @@ CClib_methods[] = { (char *)"dilithium", (char *)"register", (char *)"handle, [hexseed]", 1, 2, 'R', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"sign", (char *)"msg [hexseed]", 1, 2, 'S', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"verify", (char *)"pubtxid msg sig", 3, 3, 'V', EVAL_DILITHIUM }, - { (char *)"dilithium", (char *)"send", (char *)"pubtxid amount", 2, 2, 'x', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"send", (char *)"handle pubtxid amount", 3, 3, 'x', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_DILITHIUM }, #endif }; diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index a41e1ea59..8406b0c00 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2872,6 +2872,18 @@ int32_t main(void) it is a very big signature, but that seems to be dilithium sig size. let us verify it: cclib verify 19 \"[%229d856b2be6e54c8f04ae3f86aef722b0535180b3e9eb926c53740e481a1715f9%22,%22aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22,%22be067f4bd81b9b0b772e0e2872cc086f6c2ff4c558a465afe80ab71c2c7b39a25ad8300629337c022d8c477cf7728cd11a3f6135bccfdbd68de5cd4517e70a70ec3b836041dc9c2f1abed65f2519e43a31ca6ad4991ce98460a14ee70d28c47f5a1d967c25b1ac93afea7e2b11aa2fb715ac08bd3eac739425c67974ecd682f711a0b175b30278febfe55586650ed8b0098de745944450a6836b6ab23e0c5ebdd7503188428c3159f1671ca27d9d529d344d246e116b2001dbba085afe1bfcdd12d88ae2efbcead268b10cec4f76531aba594887dd239b59c4c676b348a56a1cc2e0032590c74513cfba7f03f8b6d7a14bb6f6a16ae743317ecd8551b3362dc892bcae550032682d130772f65b2e96a5ad4ce2b8e9a41a48c2a52c80f349c99dc110807e7c662f7ef960f628001ca9a9f249b53b23c4680e3a6acec89e3c26d0265b617353654f55a752f9ea3689570c068a414793c3575fae66f6fa425ce282a574981228a52e2ede14fbde3ac66a8e061a538bee737d17fbb48afc39cd914518ef2a182ce1feb66b1a8bf9934b6fef491f2bd3598e3421399fe11754bc61e149e8846f74d44d96c7dc47f06d04d6c09dc2b2c9d78e76a713722eec637f8e3fb5cd5adfd8ba2ce05dacdf2f9522e89bff2ee745d49873755a0079835e982c6c55fd9a96597505d79090da8df4feb422422b1d6427fde4242aafcb6ed581d8e4ffd722daf56fd45b017a2a2fa2f4e30a3a457686bdd184505461fc6749e4a20b7faa2a1d9a295a445ea564b84c1b820d9cf5c06142353671f989565a3767bd6ddabfc3bf1368acdae8870580f21baa2093cea4447688e35719bd78c785821f944ecc9a093f9a65bf2584f1a0c68f70f11f2485e02f288c2c8b6692883983607960aa16065d22082121f6fd6588f07cd3fb57bba624fbb9c7077cb1400fe4edf48156b7622fab70cce1cbd17bde2f4c24b9a86d485727df413e06a6c31cab27284a69fd46e00fc6e80872ed5291b598c74964488ffdb19d0dc94fce37db3f5230d947cb4d83ae55e0357aab1ec86b63fe606f86a77aa78fc4fe986be450b74f1ffbb5ba9eeaea11c7c7ffa6d87a9d49767ce761614bd6cc5df3767ed6396b84354a9634bb3e35606e961fc023504473bf3b7e13244f19d1dee101af1854f80899f95409bb402a5267ad21ddba80e2dd0dd513d0fc88067ac4078e69c12bd19807c03a916d2a42cdbe7b4cdac4bc2314fe3369723d16c30bf277db823c1457f5ff64f3117b82b991ee8b65b7e6b8f7814a15b4ca8cebe88d12236cf1b7dd06b75cab506d78c2072fddf2002be366f43ca68866f87fe9a56808ab7f82aa925091e1f0fba371642039316939446b769973a9c93efe3104699ad3eceac89eb1c2507b65b43d21388f93ff28b194110d7114b97a10cb212515127ede0287d455791e1c6d554b0d8a4e75f2701bc3430786cc69081dbd96a73a308fc6a60fc773fdc7df49b1865c3e989f2a528872fd4c1715dadb11c801c1492ce07bde59e25a801bb542e2caef35f99ca4cb0a3f1d2c2c6e3895c94001a0b2cc648057c2e44c780655f93d56a2cd62a9d55eb8de45e9ec75bfa3d121223aba700062ba3f54162fb9ba136aca6aeb119bca9a0d6bf18e89f54d9ff09c6a2036f767098fbbaf20e10db25e43386ecda201c05e794805269f1a77e50657052d16ae1e154d706a7fa81c419b9d262766e8edb8fd6343f509bed44098ef741f10a6206474c3490354695762a5a4532dd0279abc38ef75a44899a5d8d0e77af638aedd07071f37a3c5f82bbbd05a7b4c0e23d2fc3a5bbc40a52f588c8592f02fb30be56ae0990b24a80690c0b5c9df29549f7dec89f62920a37d05c62c27a62ee01fea164bf28937cdc7d3f2937a5756ada91c2615ce7ed20f0ed07cf486b76d0a63d193363567746eff0ff90ace3dbdfb770d55161c84ccdebca1a600337e7ffed0fdfbc041ed44e0014cced03d1af55ae9fa14d87d60dfe96ac7cde67a1d8ea2150c00ba5fb9a0ec0eff5bd9f734da71edbe7e2f71b6465984c411de8a3cc77a337b2ffdee6ab6d904a79316c15d15176401bc7e72fabb1e9571c7e7188ba09a295400437e4b96549d9827fba6d3493bc6f58f95e240b0a0159054014e5e3103e3af4eef77d3896290c7bf930edbe77615d56aa0a93034c92830c1382c0c06726d2ec7d6c2ed45d3a9fb9646892402812f1df9a003705d3f549d84f9ed3b5fe3c40fcb0bcb28a0d32f2fa27fcdb82509a0725d7314a3eb99a701169fae9e3dcdc2cc20d73aa8b2c5feb645556a8b946581e4e9e82f6a19a21f5babd35d49810dc88923c4908eca3690b774f367a41c3a37b54af9847d73a7eed1ee45edaaed0f316d551c08e3e642cebc97ce71a811664ee9296e7fedffb90011cc353302acd931bc0d152d7e6332a8f0d71059987c3b90f3f57178dec3f30c58ded0bc80eb65b0c9b8d16ec73ebe17e31259181b2376405db17e279419f1c685ad71b6cc91c81a120de2db2c532e67bc3a58d22b549fae61f32398d03cb1f5e245cfec65c40c9dfd0b8a93812f67840c653c5304402a1ff6189fd24f8ce3482e5cf92b3581445009c3b586bb421459ce9457868787c78b787bd45df7e55c3165a92194d38b913a6ef6f31af4c2afcfd0158eb8eb2820f7d41e3efca9367528a0b6fe6ec3fd01082bc60a9fe2a13ab3705b3b0c07173d4d762c8de4b6598d30b97e32339aeb706de47170e1033603267c6ce8caa2977990cbda75984de4e5ede6e36ff889b53b2cbbebc37f9e56e78c62ff856bcb27aba8892ace8fcaae09b31d7f5f850596014e868003d632c9dc12e7c83f6de676d9ae4328862326572e2e0353d5547f7f73fdf5b0227b6d108ae28e3dc622d5ac3dcf98bd1461917d78468ac2912329027c1085611dce7a6b7b3fa8451a5c3c6b448b1b9ad9dd84308991e4688595bcb289ec4b99f63db0c18969bd4b5cdc14d85007d683f936ab3207b59e3971f86f8fb388e72bdc7c9fb3b466061223e85138ee6a5657e8862ca51819c9d92b339ac6900e9f60a71d4a1eb09707cedc32bb477c91a8b5792e850606e1de57122d017a2025423d40b48e0bbe711ec03381630b9003ff55e10ac6f0031dfc54ed54ccd3309abd17ee026958fdf23bb74d53b84d8e2ef150fb2216265454c5f6446e221ab1c95c086571cad14251f618c9c58a9dfb83f9a8c58c9c5c026b9bc8f90860acde16557c064f95b178a9776e463b2d7d658e4acfa1ea30c429c0b813a5872b02d7b0bafcc095e979f737834933fbbf1220c05a0b0346f5932c669c534e22ab5ab42c39fd0e062abff05a2d34060e6f539c7ae9244903d981095fac6cff5d20ac9d298de27cb1ea7079d6dcc47504f988e3bdd1c48ca23f9ec305950459446c51b879a62e75cbc3570d2dbf93594f299111e27b60e5193d6e766a40130ee5d33a43eb43aba5c5701de878fdeaa16c998607e7fbf6c8827cb1f914db9d73c6ae48a0cb416218cc50b335f171e4df050561dfb1669939ccf2c498ff1d8f53a7d7c77195348502c4ffd5c18362f4eb4c3077e504853ff1e84c6166e1f889781bf5dcccf0daf8ac0881ee7202650abdff8d6cda2f8bf3b6a96d23f5ffa0104ee72dd1e8ae7cd08258d36b50cb40048756216845815a3e01efd33d5fae86a0680920422325893296dcb2af0d6df21c7193e387092b61408aac63df4a79c3b1e54869ba3c43ae2a54446e64053c061dd8bb3e132be46d9a83b6675791f49aa9617345801e97be7f4f7159ba1d7da623c7868ad281ddbb0f75fec7fe56ff0a44a8ac3b51a1f784b2b039d6434f92d3254fd83b4221ca18883637a0eb12217ebc8e149681c21e0edbd11289cfa7f78d536d8858a60056b8c28916e1d34ce1a6d344034b2e72162a5fc92b137354c2b791e7ad6ee4679f71181188ba69c9ded078421885a6cc18bc58c383d190c11d236e53eaa39a99d157e4dd74bc4aa2ce1354511128d6b407007dbcaeb9c3b712ed2b334de23c66735f534a9dddb7ab2d06c6a4669d2bd38c8c812b287b39b3591ac77e617834ea7c4c38b1133f2cafdf51f9afca7f44e9b527d3e0e840b05ec8bf57fcceb8a28546a3593ff1b94ee6a8d7d28b8e6007d0ea7da80552e4382b3ff3b6152175083717f42c5c902131b0a27e23bbcf4ba03140a6dc3bcccbc8ca93ba6161fe3c36a1835e9e02695bac571a07f6b2267998213aa0c4c7b93c2ed3a58e12cab5a51edf462a30df14e7e32727b4da1f7f29e9ea30f65ab090b22e9ae00ae9419bf26a44482d536812e2b4c2e1fd2af622d827b04b67eac1052d2ccee68207b3b6ca3d96bc4de4039a3a3e50c58a17786edb08caad6091dab0e7beffd0acb748d5c5ef6a171d8d113c7c310f18712a53607dbf01653157090cdd19c5845c1b7e11a4a61c2229cbb1e6927c74f187964c646b007051841b1b83e670611c1e9eb0b2406ee432122613a4c7e9f60c2cf8db2d6032225604c1d5468b1e90bb57651c2223363743516164a4aab0b4bac2d70d1a254f687384889daee2fc2d32365d78878b8c9aabbbbcc8d7f4fb191d23283f4d5359767e8c99a1b8c8cddfe5040c1e2339606e788ca9cad6f2fc0712236a70c9cdd6fb0000000000000000000000000000000000000000000000000000000000000000000000101c2c3e4c55b80404422409560084401072601824140801b8244ae84401008080081022408cdea5834e5fd1220daff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848%22]\" + { + "sighash": "cfed6d7f059b87635bde6cb31accd736bf99ff3d", + "msg32": "aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848", + "handle": "jl777", + "pkaddr": "PNoTcVH8G5TBTQigyVZTsaMMNYYRvywUNu", + "result": "success" + } + + the basics are working, now it is time to send and spend + + cclib send 19 \"[%22jl777%22,%229d856b2be6e54c8f04ae3f86aef722b0535180b3e9eb926c53740e481a1715f9%22,7.77]\" + */ #define DILITHIUM_TXFEE 10000 @@ -3071,9 +3083,30 @@ UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *param UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - // copy musig method - return(result); + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + UniValue result(UniValue::VOBJ); std::string rawtx,checkhandle; CPubKey destpub33,mypk,dilithiumpk; int32_t i,n; int64_t amount; uint256 destpubtxid; uint8_t pk[CRYPTO_PUBLICKEYBYTES]; + if ( txfee == 0 ) + txfee = DILITHIUM_TXFEE; + mypk = pubkey2pk(Mypubkey()); + dilithiumpk = GetUnspendable(cp,0); + if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + { + amount = jdouble(jitem(params,2),0)*COIN + 0.0000000049; + std::string handle(jstr(jitem(params,0),0)); + result.push_back(Pair("handle",handle)); + destpubtxid = juint256(jitem(params,1)); + if ( dilithium_bigpubget(checkhandle,destpub33,pk,pubtxid) < 0 ) + return(cclib_error(result,"couldnt parse message to sign")); + else if ( handle == checkhandle ) + { + if ( AddNormalinputs(mtx,mypk,amount+txfee,64) >= amount+txfee ) + { + mtx.vout.push_back(MakeCC1vout(cp->evalcode,amount,destpub33)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_sendopret(destpubtxid)); + return(musig_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt find enough funds")); + } else return(cclib_error(result,"handle mismatch")); + } else return(cclib_error(result,"not enough parameters")); } UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) From 60c8bda1305697f429364c0b74309222968b10e1 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:09:13 -1100 Subject: [PATCH 1105/1145] Opret --- src/cc/dilithium.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 8406b0c00..47c447f88 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2909,6 +2909,24 @@ uint8_t dilithium_registeropretdecode(std::string &handle,CPubKey &pk,std::vecto return(0); } +CScript dilithium_sendopret(uint256 destpubtxid) +{ + CScript opret; uint8_t evalcode = EVAL_DILITHIUM; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'x' << destpubtxid); + return(opret); +} + +uint8_t dilithium_sendopretdecode(uint256 &destpubtxid,CScript scriptPubKey) +{ + std::vector vopret; uint8_t e,f; + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> handle; ss >> destpubtxid) != 0 && e == EVAL_DILITHIUM && f == 'x' ) + { + return(f); + } + return(0); +} + UniValue dilithium_rawtxresult(UniValue &result,std::string rawtx) { CTransaction tx; From f86cdd74f9dad20ba2a3a6ead53e8c02507cadcb Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:10:10 -1100 Subject: [PATCH 1106/1145] Destpubtxid --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 47c447f88..5db52bd00 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3113,7 +3113,7 @@ UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) std::string handle(jstr(jitem(params,0),0)); result.push_back(Pair("handle",handle)); destpubtxid = juint256(jitem(params,1)); - if ( dilithium_bigpubget(checkhandle,destpub33,pk,pubtxid) < 0 ) + if ( dilithium_bigpubget(checkhandle,destpub33,pk,destpubtxid) < 0 ) return(cclib_error(result,"couldnt parse message to sign")); else if ( handle == checkhandle ) { From 461ed55d093d71448179fa18f42d99704bebac92 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:10:59 -1100 Subject: [PATCH 1107/1145] Fix --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 5db52bd00..3e485f893 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2920,7 +2920,7 @@ uint8_t dilithium_sendopretdecode(uint256 &destpubtxid,CScript scriptPubKey) { std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> handle; ss >> destpubtxid) != 0 && e == EVAL_DILITHIUM && f == 'x' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> destpubtxid) != 0 && e == EVAL_DILITHIUM && f == 'x' ) { return(f); } From 7d623078f3e3146e111590609b613c70ec55de82 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:44:43 -1100 Subject: [PATCH 1108/1145] Docs --- src/cc/dilithium.c | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 3e485f893..ed0956c62 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2842,7 +2842,18 @@ int32_t main(void) #endif ////////////////////////////////////////////////////// -/* First register a pubkey,ie. bind handle, pub33 and bigpub together and then can be referred by pubtxid in other calls + +/* + dilithium has very big pubkeys and privkeys, so some practical things are done to make them more manageable. luckily the big privkey can be generated from a normal 256bit seed in about 100 microseconds. Of course, if you use a normal privkey that is also having its pubkey known, it defeats the purpose of using quantum secure protocol. however it is convenient for testing. just make sure to use externally generated seeds that never get used for secp256k1 if you want to keep it quantum secure. + + there are some useful "addresses" starting with 'P' and 'S' that are the base58 encoded dilithium pubkey and privkey. this is just so you can make sure the right one was used in an operation as the ~3kb of hex is very hard to compare visually. + + Now comes the cool part. Instead of having to specify these giant pubkeys in each spend and maybe even send, we send to a pubtxid instead. the pubtxid is the txid of a registration tx where a handle, secp256k1 pubkey and the dilithium pubkey are bound together. So by referring to the txid, you refer to all three. Again, for convenience it is possible to use the same secp256k1 pubkey that is derived from the 256bit seed that the dilithium pubkey is generated, but that offers no additonal quantum protection. To gain the quantum protection, use an externally provided seed to generate the dilithium pubkey. there should be no algorithmic linkage between the pubtxid secp256k1 pubkey and the dilithium pubkey. They are linked simply by being in the same register transaction. + + Once you have registered the pubkey(s), then you can do a send to it. Both pubkeys are used so that to spend you need to have a proper CC signature and a dilithium signature. The spend will necessarily need to have the almost 4kb signature in the opreturn, but at least the big pubkey is only referenced via the pubtxid + + + First register a pubkey,ie. bind handle, pub33 and bigpub together and then can be referred by pubtxid in other calls cclib register 19 \"[%22jl777%22]\" { @@ -2883,6 +2894,15 @@ int32_t main(void) the basics are working, now it is time to send and spend cclib send 19 \"[%22jl777%22,%229d856b2be6e54c8f04ae3f86aef722b0535180b3e9eb926c53740e481a1715f9%22,7.77]\" + { + "handle": "jl777", + "hex": "0400008085202f8901ff470ca3fb4f935a32dd312db801dcabce0e8b49c7774bb4f1d39a45b3a68bab0100000049483045022100d1c29d5f870dd18aa865e12632fa0cc8df9a8a770a23360e9c443d39cb141c5f0220304c7c77a6d711888d4bcb836530b6509eabe158496029b0bf57b5716f24beb101ffffffff034014502e00000000302ea22c8020b09ee47b12b5b9a2edcf0e7c4fb2a517b879eb88ac98b16185dfef476506b1dd8103120c008203000401cc3cd0ff7646070000232102aff51dad774a1c612dc82e63f85f07b992b665836b0f0efbcb26ee679f4f4848ac0000000000000000246a221378f915171a480e74536c92ebe9b3805153b022f7ae863fae048f4ce5e62b6b859d00000000120c00000000000000000000000000", + "txid": "4aac73ebe82c12665d1d005a0ae1a1493cb1e2c714680ef9d016f48a7c77b4a2", + "result": "success" + } + dont forget to broadcast it: 4aac73ebe82c12665d1d005a0ae1a1493cb1e2c714680ef9d016f48a7c77b4a2 + notice how small the tx is! 289 bytes as it is sent to the destpubtxid, which in turn contains the handle, pub33 and bigpub. the handle is used for error check, pub33 is used to make the destination CC address, so the normal CC signing needs to be passed in addition to the spend restrictions for dilithium. + */ From 4136857e21370a9c44a9afb0f3a963bc95bfb27b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:50:15 -1100 Subject: [PATCH 1109/1145] Guard against combining before having num music --- src/cc/musig.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index d93792463..33695aeaa 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -219,7 +219,7 @@ struct musig_info secp256k1_musig_session_signer_data *signer_data; //[N_SIGNERS]; secp256k1_pubkey *nonces; //[N_SIGNERS]; secp256k1_musig_partial_signature *partial_sig; //[N_SIGNERS]; - int32_t myind,num; + int32_t myind,num,numcommits,numnonces,numpartials; uint8_t msg[32],pkhash[32],combpk[33]; } *MUSIG; @@ -511,7 +511,8 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * number of signers participating in the MuSig. */ result.push_back(Pair("added_index",ind)); - if ( secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->commitment_ptrs,MUSIG->num) > 0 ) + MUSIG->numcommits++; + if ( MUSIG->numcommits >= MUSIG->num && secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->commitment_ptrs,MUSIG->num) > 0 ) { if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG->nonces[MUSIG->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) { @@ -583,7 +584,8 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * adaptor: point to add to the combined public nonce. If NULL, nothing is * added to the combined nonce. */ - if ( secp256k1_musig_session_combine_nonces(ctx,&MUSIG->session,MUSIG->signer_data,MUSIG->num,NULL,NULL) > 0 ) + MUSIG->numnonces++; + if ( MUSIG->numnonces >= MUSIG->num && secp256k1_musig_session_combine_nonces(ctx,&MUSIG->session,MUSIG->signer_data,MUSIG->num,NULL,NULL) > 0 ) { if ( secp256k1_musig_partial_sign(ctx,&MUSIG->session,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) { @@ -621,7 +623,8 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); result.push_back(Pair("added_index",ind)); - if ( secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) + MUSIG->numpartials++; + if ( MUSIG->numpartials >= MUSIG->num && secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) { if ( secp256k1_schnorrsig_serialize(ctx,out64,&sig) > 0 ) { From 8bfc74cef033bf4ed8d796a85e827a9acca0239f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sat, 23 Feb 2019 23:52:24 -1100 Subject: [PATCH 1110/1145] Set numb to 1 --- src/cc/musig.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 33695aeaa..5986f8716 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -466,6 +466,7 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) for (i=0; i<32; i++) sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitments[MUSIG->myind*32 + i]); str[64] = 0; + MUSIG->numcommits = 1; result.push_back(Pair("commitment",str)); result.push_back(Pair("result","success")); return(result); @@ -519,6 +520,7 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) for (i=0; i<33; i++) sprintf(&str[i<<1],"%02x",((uint8_t *)pk.begin())[i]); str[66] = 0; + MUSIG->numnonces = 1; result.push_back(Pair("myind",MUSIG->myind)); result.push_back(Pair("nonce",str)); result.push_back(Pair("result","success")); @@ -597,6 +599,7 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) result.push_back(Pair("myind",MUSIG->myind)); result.push_back(Pair("partialsig",str)); result.push_back(Pair("result","success")); + MUSIG->numpartials = 1; return(result); } else return(cclib_error(result,"error serializing partial sig")); } else return(cclib_error(result,"error making partial sig")); From 9dcb99c828800311803140e37298d3f0204ced7e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:08:21 -1100 Subject: [PATCH 1111/1145] Dilithium spend --- src/cc/cclib.cpp | 4 +-- src/cc/dilithium.c | 74 ++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 73 insertions(+), 5 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index c64ac025b..b7b2db059 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -80,13 +80,13 @@ CClib_methods[] = { (char *)"musig", (char *)"partialsig", (char *)"pkhash,ind,partialsig", 3, 3, 'S', EVAL_MUSIG }, { (char *)"musig", (char *)"verify", (char *)"msg sig pubkey", 3, 3, 'V', EVAL_MUSIG }, { (char *)"musig", (char *)"send", (char *)"combined_pk amount", 2, 2, 'x', EVAL_MUSIG }, - { (char *)"musig", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_MUSIG }, + { (char *)"musig", (char *)"spend", (char *)"sendtxid sig scriptPubKey", 3, 3, 'y', EVAL_MUSIG }, { (char *)"dilithium", (char *)"keypair", (char *)"[hexseed]", 0, 1, 'K', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"register", (char *)"handle, [hexseed]", 1, 2, 'R', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"sign", (char *)"msg [hexseed]", 1, 2, 'S', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"verify", (char *)"pubtxid msg sig", 3, 3, 'V', EVAL_DILITHIUM }, { (char *)"dilithium", (char *)"send", (char *)"handle pubtxid amount", 3, 3, 'x', EVAL_DILITHIUM }, - { (char *)"dilithium", (char *)"spend", (char *)"sendtxid sig destpubkey", 3, 3, 'y', EVAL_DILITHIUM }, + { (char *)"dilithium", (char *)"spend", (char *)"sendtxid scriptPubKey [hexseed]", 2, 3, 'y', EVAL_DILITHIUM }, #endif }; diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index ed0956c62..30fd2a3bd 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2947,6 +2947,24 @@ uint8_t dilithium_sendopretdecode(uint256 &destpubtxid,CScript scriptPubKey) return(0); } +CScript dilithium_spendopret(uint256 destpubtxid,std::vector sig) +{ + CScript opret; uint8_t evalcode = EVAL_DILITHIUM; + opret << OP_RETURN << E_MARSHAL(ss << evalcode << 'y' << destpubtxid << sig); + return(opret); +} + +uint8_t dilithium_spendopretdecode(uint256 &destpubtxid,std::vector &sig,CScript scriptPubKey) +{ + std::vector vopret; uint8_t e,f; + GetOpReturnData(scriptPubKey,vopret); + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> destpubtxid; ss > sig) != 0 && e == EVAL_DILITHIUM && f == 'y' ) + { + return(f); + } + return(0); +} + UniValue dilithium_rawtxresult(UniValue &result,std::string rawtx) { CTransaction tx; @@ -3147,9 +3165,59 @@ UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) } else return(cclib_error(result,"not enough parameters")); } +/* + ultimately what is needed is to be able to scan all utxos to the CC address and be able to spend many vins in the same tx. to do this the opreturn would need to be able to have txid of special with the sigs. However, it is complicated by the need to create a specific message to sign that is the desired outputs and all the inputs. Also, to properly be able to do change and keep everything in dilithium outputs, there needs to be a second destpub. + + so the proposed opreturn for spend would be: + + destpubtxid0, destpubtxid1 (zeroid if only 1), vector of sigs/sigtxid where if it is len 32 it is a txid that just has the sig in the opreturn. + + however, for now, to keep things simple we will only support spending a specific txid to normal output to avoid needing a combined opreturn and other complications. + */ + UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); - // copy musig method - return(result); + CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,destpub33; char *scriptstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock,destpubtxid; int32_t i,smlen,n,numvouts; char str[129]; CTxOut vout; std::string handle; uint8_t pk[CRYPTO_PUBLICKEYBYTES],pk2[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; std::vector sig; + if ( txfee == 0 ) + txfee = DILITHIUM_TXFEE; + mypk = pubkey2pk(Mypubkey()); + if ( params != 0 && ((n= cJSON_GetArraySize(params)) == 2 || n == 3) ) + { + prevhash = juint256(jitem(params,0)); + scriptstr = jstr(jitem(params,1),0); + if ( n == 2 || cclib_parsehash(seed,jitem(params,2),32) < 0 ) + { + Myprivkey(seed); + result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); + } + _dilithium_keypair(pk,sk,seed); + if ( is_hexstr(scriptstr,0) != 0 ) + { + CScript scriptPubKey; + scriptPubKey.resize(strlen(scriptstr)/2); + decode_hex(&scriptPubKey[0],strlen(scriptstr)/2,scriptstr); + if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) + { + vout.nValue = vintx.vout[0].nValue - txfee; + vout.scriptPubKey = scriptPubKey; + musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); + sig.resize(32+CRYPTO_SIZE); + if ( dilithium_bigpubget(handle,destpub33,pk2,destpubtxid) < 0 ) + return(cclib_error(result,"couldnt parse message to sign")); + else if ( memcmp(pk,pk2,sizeof(pk)) != 0 ) + return(cclib_error(result,"dilithium bigpub mismatch")); + else if ( destpub33 != mypk ) + return(cclib_error(result,"destpub33 is not for this -pubkey")); + else if ( _dilithium_sign(&sig[0],&smlen,msg,32,sk) < 0 ) + return(cclib_error(result,"dilithium signing error")); + else if ( smlen != 32+CRYPTO_SIZE ) + return(cclib_error(result,"siglen error")); + mtx.vin.push_back(CTxIn(prevhash,0)); + mtx.vout.push_back(vout); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_spendopret('y',destpubtxid,sig)); + return(dilithium_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt find vin0")); + } else return(cclib_error(result,"script or bad destpubtxid is not hex")); + } else return(cclib_error(result,"need to have exactly 2 params sendtxid, scriptPubKey")); } From 1d4243bb951802fe5eed257161dcbbbdf307a10e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:11:30 -1100 Subject: [PATCH 1112/1145] > -> >> --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 30fd2a3bd..cc41d2360 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2958,7 +2958,7 @@ uint8_t dilithium_spendopretdecode(uint256 &destpubtxid,std::vector &si { std::vector vopret; uint8_t e,f; GetOpReturnData(scriptPubKey,vopret); - if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> destpubtxid; ss > sig) != 0 && e == EVAL_DILITHIUM && f == 'y' ) + if ( vopret.size() > 2 && E_UNMARSHAL(vopret,ss >> e; ss >> f; ss >> destpubtxid; ss >> sig) != 0 && e == EVAL_DILITHIUM && f == 'y' ) { return(f); } From 852e7ce0162e18c31cbd500df5c7ed97c9e0e444 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:13:30 -1100 Subject: [PATCH 1113/1145] Syntax --- src/cc/dilithium.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index cc41d2360..197d62786 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3178,7 +3178,7 @@ UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,destpub33; char *scriptstr; uint8_t msg[32]; CTransaction vintx; uint256 prevhash,hashBlock,destpubtxid; int32_t i,smlen,n,numvouts; char str[129]; CTxOut vout; std::string handle; uint8_t pk[CRYPTO_PUBLICKEYBYTES],pk2[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES]; std::vector sig; + UniValue result(UniValue::VOBJ); std::string rawtx; CPubKey mypk,destpub33; CTransaction vintx; uint256 prevhash,hashBlock,destpubtxid; int32_t i,smlen,n,numvouts; char str[129],*scriptstr; CTxOut vout; std::string handle; uint8_t pk[CRYPTO_PUBLICKEYBYTES],pk2[CRYPTO_PUBLICKEYBYTES],sk[CRYPTO_SECRETKEYBYTES],msg[32],seed[32]; std::vector sig; if ( txfee == 0 ) txfee = DILITHIUM_TXFEE; mypk = pubkey2pk(Mypubkey()); @@ -3211,11 +3211,11 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params return(cclib_error(result,"destpub33 is not for this -pubkey")); else if ( _dilithium_sign(&sig[0],&smlen,msg,32,sk) < 0 ) return(cclib_error(result,"dilithium signing error")); - else if ( smlen != 32+CRYPTO_SIZE ) + else if ( smlen != 32+CRYPTO_BYTES ) return(cclib_error(result,"siglen error")); mtx.vin.push_back(CTxIn(prevhash,0)); mtx.vout.push_back(vout); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_spendopret('y',destpubtxid,sig)); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_spendopret(destpubtxid,sig)); return(dilithium_rawtxresult(result,rawtx)); } else return(cclib_error(result,"couldnt find vin0")); } else return(cclib_error(result,"script or bad destpubtxid is not hex")); From 32a3cc94bbd6799754f083e0c2eb4fa86bb3f024 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:18:43 -1100 Subject: [PATCH 1114/1145] Prev --- src/cc/dilithium.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 197d62786..8a59ecba3 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2903,6 +2903,7 @@ int32_t main(void) dont forget to broadcast it: 4aac73ebe82c12665d1d005a0ae1a1493cb1e2c714680ef9d016f48a7c77b4a2 notice how small the tx is! 289 bytes as it is sent to the destpubtxid, which in turn contains the handle, pub33 and bigpub. the handle is used for error check, pub33 is used to make the destination CC address, so the normal CC signing needs to be passed in addition to the spend restrictions for dilithium. + cclib spend 19 \"[%224aac73ebe82c12665d1d005a0ae1a1493cb1e2c714680ef9d016f48a7c77b4a2%22,%22210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac%22]\" */ @@ -3182,6 +3183,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( txfee == 0 ) txfee = DILITHIUM_TXFEE; mypk = pubkey2pk(Mypubkey()); + fprintf(stderr,"inside\n"); if ( params != 0 && ((n= cJSON_GetArraySize(params)) == 2 || n == 3) ) { prevhash = juint256(jitem(params,0)); @@ -3192,13 +3194,16 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); } _dilithium_keypair(pk,sk,seed); + fprintf(stderr,"after keypair\n"); if ( is_hexstr(scriptstr,0) != 0 ) { + fprintf(stderr,"have script\n"); CScript scriptPubKey; scriptPubKey.resize(strlen(scriptstr)/2); decode_hex(&scriptPubKey[0],strlen(scriptstr)/2,scriptstr); if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { + fprintf(stderr,"got tx\n"); vout.nValue = vintx.vout[0].nValue - txfee; vout.scriptPubKey = scriptPubKey; musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); @@ -3213,6 +3218,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params return(cclib_error(result,"dilithium signing error")); else if ( smlen != 32+CRYPTO_BYTES ) return(cclib_error(result,"siglen error")); + fprintf(stderr,"prepare tx\n"); mtx.vin.push_back(CTxIn(prevhash,0)); mtx.vout.push_back(vout); rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_spendopret(destpubtxid,sig)); From 93770abb7e0fd41b1e75e936305a91db112cbf2f Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:20:15 -1100 Subject: [PATCH 1115/1145] CRYPTO_BYTES --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 8a59ecba3..d1a700e0b 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3207,7 +3207,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params vout.nValue = vintx.vout[0].nValue - txfee; vout.scriptPubKey = scriptPubKey; musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); - sig.resize(32+CRYPTO_SIZE); + sig.resize(32+CRYPTO_BYTES); if ( dilithium_bigpubget(handle,destpub33,pk2,destpubtxid) < 0 ) return(cclib_error(result,"couldnt parse message to sign")); else if ( memcmp(pk,pk2,sizeof(pk)) != 0 ) From 6deb58ad51184bfb28e48b6be1b1440d201ecb94 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:24:31 -1100 Subject: [PATCH 1116/1145] Fix --- src/cc/dilithium.c | 36 +++++++++++++++++------------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index d1a700e0b..58a3fd514 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3183,7 +3183,6 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( txfee == 0 ) txfee = DILITHIUM_TXFEE; mypk = pubkey2pk(Mypubkey()); - fprintf(stderr,"inside\n"); if ( params != 0 && ((n= cJSON_GetArraySize(params)) == 2 || n == 3) ) { prevhash = juint256(jitem(params,0)); @@ -3194,35 +3193,34 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params result.push_back(Pair("warning","test mode using privkey for -pubkey, only for testing. there is no point using quantum secure signing if you are using a privkey with a known secp256k1 pubkey!!")); } _dilithium_keypair(pk,sk,seed); - fprintf(stderr,"after keypair\n"); if ( is_hexstr(scriptstr,0) != 0 ) { - fprintf(stderr,"have script\n"); CScript scriptPubKey; scriptPubKey.resize(strlen(scriptstr)/2); decode_hex(&scriptPubKey[0],strlen(scriptstr)/2,scriptstr); if ( myGetTransaction(prevhash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { - fprintf(stderr,"got tx\n"); vout.nValue = vintx.vout[0].nValue - txfee; vout.scriptPubKey = scriptPubKey; musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); sig.resize(32+CRYPTO_BYTES); - if ( dilithium_bigpubget(handle,destpub33,pk2,destpubtxid) < 0 ) - return(cclib_error(result,"couldnt parse message to sign")); - else if ( memcmp(pk,pk2,sizeof(pk)) != 0 ) - return(cclib_error(result,"dilithium bigpub mismatch")); - else if ( destpub33 != mypk ) - return(cclib_error(result,"destpub33 is not for this -pubkey")); - else if ( _dilithium_sign(&sig[0],&smlen,msg,32,sk) < 0 ) - return(cclib_error(result,"dilithium signing error")); - else if ( smlen != 32+CRYPTO_BYTES ) - return(cclib_error(result,"siglen error")); - fprintf(stderr,"prepare tx\n"); - mtx.vin.push_back(CTxIn(prevhash,0)); - mtx.vout.push_back(vout); - rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_spendopret(destpubtxid,sig)); - return(dilithium_rawtxresult(result,rawtx)); + if ( dilithium_sendopretdecode(destpubtxid,tx.vout[numvouts-1].scriptPubKey) == 'x' ) + { + if ( dilithium_bigpubget(handle,destpub33,pk2,destpubtxid) < 0 ) + return(cclib_error(result,"couldnt parse message to sign")); + else if ( memcmp(pk,pk2,sizeof(pk)) != 0 ) + return(cclib_error(result,"dilithium bigpub mismatch")); + else if ( destpub33 != mypk ) + return(cclib_error(result,"destpub33 is not for this -pubkey")); + else if ( _dilithium_sign(&sig[0],&smlen,msg,32,sk) < 0 ) + return(cclib_error(result,"dilithium signing error")); + else if ( smlen != 32+CRYPTO_BYTES ) + return(cclib_error(result,"siglen error")); + mtx.vin.push_back(CTxIn(prevhash,0)); + mtx.vout.push_back(vout); + rawtx = FinalizeCCTx(0,cp,mtx,mypk,txfee,dilithium_spendopret(destpubtxid,sig)); + return(dilithium_rawtxresult(result,rawtx)); + } else return(cclib_error(result,"couldnt decode send opret")); } else return(cclib_error(result,"couldnt find vin0")); } else return(cclib_error(result,"script or bad destpubtxid is not hex")); } else return(cclib_error(result,"need to have exactly 2 params sendtxid, scriptPubKey")); From c16c21f664a3ef3f448046f3b8680b70da9324b9 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:25:08 -1100 Subject: [PATCH 1117/1145] Vent --- src/cc/dilithium.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 58a3fd514..94e2efc66 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3204,7 +3204,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params vout.scriptPubKey = scriptPubKey; musig_prevoutmsg(msg,prevhash,vout.scriptPubKey); sig.resize(32+CRYPTO_BYTES); - if ( dilithium_sendopretdecode(destpubtxid,tx.vout[numvouts-1].scriptPubKey) == 'x' ) + if ( dilithium_sendopretdecode(destpubtxid,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { if ( dilithium_bigpubget(handle,destpub33,pk2,destpubtxid) < 0 ) return(cclib_error(result,"couldnt parse message to sign")); From 57c1d1cc8c7303cf6bd81ca20b8e9358136e5fe0 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:43:30 -1100 Subject: [PATCH 1118/1145] Dilithium validate --- src/cc/cclib.cpp | 3 +++ src/cc/dilithium.c | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index b7b2db059..286008660 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -127,6 +127,7 @@ UniValue musig_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue musig_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); +bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx); UniValue dilithium_register(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue dilithium_send(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params); @@ -406,6 +407,8 @@ bool CClib_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return(sudoku_validate(cp,height,eval,tx)); else if ( cp->evalcode == EVAL_MUSIG ) return(musig_validate(cp,height,eval,tx)); + else if ( cp->evalcode == DILITHIUM_MUSIG ) + return(dilithium_validate(cp,height,eval,tx)); else return eval->Invalid("invalid evalcode"); #endif } diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 94e2efc66..dc636d7e8 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3207,7 +3207,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params if ( dilithium_sendopretdecode(destpubtxid,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { if ( dilithium_bigpubget(handle,destpub33,pk2,destpubtxid) < 0 ) - return(cclib_error(result,"couldnt parse message to sign")); + return(cclib_error(result,"couldnt get bigpub")); else if ( memcmp(pk,pk2,sizeof(pk)) != 0 ) return(cclib_error(result,"dilithium bigpub mismatch")); else if ( destpub33 != mypk ) @@ -3225,3 +3225,35 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params } else return(cclib_error(result,"script or bad destpubtxid is not hex")); } else return(cclib_error(result,"need to have exactly 2 params sendtxid, scriptPubKey")); } + +bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) +{ + CPubKey destpub33; std::string handle; uint256 hashBlock,destpubtxid,checktxid; CTransaction vintx; int32_t numvouts,mlen,smlen=CRYPTO_BYTES+32; std::vector sig; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES]; + if ( tx.vout.size() != 2 ) + return eval->Invalid("numvouts != 2"); + else if ( tx.vin.size() != 1 ) + return eval->Invalid("numvins != 1"); + else if ( IsCCInput(tx.vin[0].scriptSig) == 0 ) + return eval->Invalid("illegal normal vin0"); + else if ( myGetTransaction(tx.vin[0].prevout.hash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) + { + if ( dilithium_sendopretdecode(destpubtxid,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) + { + if ( dilithium_spendopretdecode(checktxid,sig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) + { + if ( destpubtxid == checktxid ) + { + musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); + if ( dilithium_bigpubget(handle,destpub33,pk,destpubtxid) < 0 ) + return eval->Invalid(result,"couldnt get bigpub"); + else if ( _dilithium_verify(msg2,&mlen,&sig[0],(int32_t)sig.size(),pk) < 0 ) + return eval->Invalid("failed dilithium verify"); + else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) + return eval->Invalid("failed dilithium msg verify"); + else return eval->Invalid("this is actually success!"); + } else return eval->Invalid("destpubtxid didnt match send opret"); + } else return eval->Invalid("failed decode dilithium spendopret"); + } else return eval->Invalid("couldnt decode send opret"); + } else return eval->Invalid("couldnt find vin0 tx"); +} + From 0ee7d2fed4c0988e49cc79bbcc182cc7a3078213 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:45:00 -1100 Subject: [PATCH 1119/1145] Fix --- src/cc/cclib.cpp | 2 +- src/cc/dilithium.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index 286008660..f7749d99f 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -407,7 +407,7 @@ bool CClib_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C return(sudoku_validate(cp,height,eval,tx)); else if ( cp->evalcode == EVAL_MUSIG ) return(musig_validate(cp,height,eval,tx)); - else if ( cp->evalcode == DILITHIUM_MUSIG ) + else if ( cp->evalcode == EVAL_DILITHIUM ) return(dilithium_validate(cp,height,eval,tx)); else return eval->Invalid("invalid evalcode"); #endif diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index dc636d7e8..cf52a98c2 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3245,7 +3245,7 @@ bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,con { musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); if ( dilithium_bigpubget(handle,destpub33,pk,destpubtxid) < 0 ) - return eval->Invalid(result,"couldnt get bigpub"); + return eval->Invalid("couldnt get bigpub"); else if ( _dilithium_verify(msg2,&mlen,&sig[0],(int32_t)sig.size(),pk) < 0 ) return eval->Invalid("failed dilithium verify"); else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) From 7f601cbfc7b284aceea87bc87d8721cab85c640a Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:50:16 -1100 Subject: [PATCH 1120/1145] +print --- src/cc/dilithium.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index cf52a98c2..bb6b06e91 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3237,13 +3237,18 @@ bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,con return eval->Invalid("illegal normal vin0"); else if ( myGetTransaction(tx.vin[0].prevout.hash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { + fprintf(stderr,"inside\n"); if ( dilithium_sendopretdecode(destpubtxid,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { + fprintf(stderr,"about to spendopret\n"); if ( dilithium_spendopretdecode(checktxid,sig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) { - if ( destpubtxid == checktxid ) + fprintf(stderr,"checktxid.%s vs %s\n",destpubtxid.GetHex().c_str(),checktxid.GetHex().c_str()); + if ( destpubtxid == checktxid && sig.size() == CRYPTO_BYTES+32 ) { + fprintf(stderr,"call prevoutmsg\n"); musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); + fprintf(stderr,"call dilithium_bigpubget\n"); if ( dilithium_bigpubget(handle,destpub33,pk,destpubtxid) < 0 ) return eval->Invalid("couldnt get bigpub"); else if ( _dilithium_verify(msg2,&mlen,&sig[0],(int32_t)sig.size(),pk) < 0 ) @@ -3251,7 +3256,7 @@ bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,con else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) return eval->Invalid("failed dilithium msg verify"); else return eval->Invalid("this is actually success!"); - } else return eval->Invalid("destpubtxid didnt match send opret"); + } else return eval->Invalid("destpubtxid or sig size didnt match send opret"); } else return eval->Invalid("failed decode dilithium spendopret"); } else return eval->Invalid("couldnt decode send opret"); } else return eval->Invalid("couldnt find vin0 tx"); From 97db451dc1e635801dcacf277af8d94538590247 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:55:31 -1100 Subject: [PATCH 1121/1145] Bigger msg2 --- src/cc/dilithium.c | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index bb6b06e91..5e6b926fa 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3109,7 +3109,7 @@ UniValue dilithium_sign(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue dilithium_verify(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { - UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t rmd160[20],msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t smlen=32+CRYPTO_BYTES,mlen,n; std::string handle; + UniValue result(UniValue::VOBJ); CPubKey pk33; uint8_t rmd160[20],msg[32],msg2[CRYPTO_BYTES+32],pk[CRYPTO_PUBLICKEYBYTES],sm[32+CRYPTO_BYTES]; uint256 pubtxid; char coinaddr[64],str[(32+CRYPTO_BYTES)*2+1]; int32_t smlen=32+CRYPTO_BYTES,mlen,n; std::string handle; if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) { pubtxid = juint256(jitem(params,0)); @@ -3228,7 +3228,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CPubKey destpub33; std::string handle; uint256 hashBlock,destpubtxid,checktxid; CTransaction vintx; int32_t numvouts,mlen,smlen=CRYPTO_BYTES+32; std::vector sig; uint8_t msg[32],msg2[32],pk[CRYPTO_PUBLICKEYBYTES]; + CPubKey destpub33; std::string handle; uint256 hashBlock,destpubtxid,checktxid; CTransaction vintx; int32_t numvouts,mlen,smlen=CRYPTO_BYTES+32; std::vector sig; uint8_t msg[32],msg2[CRYPTO_BYTES+32],pk[CRYPTO_PUBLICKEYBYTES]; if ( tx.vout.size() != 2 ) return eval->Invalid("numvouts != 2"); else if ( tx.vin.size() != 1 ) @@ -3244,18 +3244,22 @@ bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,con if ( dilithium_spendopretdecode(checktxid,sig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) { fprintf(stderr,"checktxid.%s vs %s\n",destpubtxid.GetHex().c_str(),checktxid.GetHex().c_str()); - if ( destpubtxid == checktxid && sig.size() == CRYPTO_BYTES+32 ) + if ( destpubtxid == checktxid && sig.size() == smlen ) { fprintf(stderr,"call prevoutmsg\n"); musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); fprintf(stderr,"call dilithium_bigpubget\n"); if ( dilithium_bigpubget(handle,destpub33,pk,destpubtxid) < 0 ) return eval->Invalid("couldnt get bigpub"); - else if ( _dilithium_verify(msg2,&mlen,&sig[0],(int32_t)sig.size(),pk) < 0 ) - return eval->Invalid("failed dilithium verify"); - else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) - return eval->Invalid("failed dilithium msg verify"); - else return eval->Invalid("this is actually success!"); + else + { + fprintf(stderr,"call _dilithium_verify\n"); + if ( _dilithium_verify(msg2,&mlen,&sig[0],smlen,pk) < 0 ) + return eval->Invalid("failed dilithium verify"); + else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) + return eval->Invalid("failed dilithium msg verify"); + else return eval->Invalid("this is actually success!"); + } } else return eval->Invalid("destpubtxid or sig size didnt match send opret"); } else return eval->Invalid("failed decode dilithium spendopret"); } else return eval->Invalid("couldnt decode send opret"); From 38a94fefae6a9a7f448a056dbcc47a1993c370e8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 06:58:12 -1100 Subject: [PATCH 1122/1145] Test bad sig --- src/cc/dilithium.c | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 5e6b926fa..8c56b0bc7 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3237,23 +3237,18 @@ bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,con return eval->Invalid("illegal normal vin0"); else if ( myGetTransaction(tx.vin[0].prevout.hash,vintx,hashBlock) != 0 && (numvouts= vintx.vout.size()) > 1 ) { - fprintf(stderr,"inside\n"); if ( dilithium_sendopretdecode(destpubtxid,vintx.vout[numvouts-1].scriptPubKey) == 'x' ) { - fprintf(stderr,"about to spendopret\n"); if ( dilithium_spendopretdecode(checktxid,sig,tx.vout[tx.vout.size()-1].scriptPubKey) == 'y' ) { - fprintf(stderr,"checktxid.%s vs %s\n",destpubtxid.GetHex().c_str(),checktxid.GetHex().c_str()); if ( destpubtxid == checktxid && sig.size() == smlen ) { - fprintf(stderr,"call prevoutmsg\n"); musig_prevoutmsg(msg,tx.vin[0].prevout.hash,tx.vout[0].scriptPubKey); - fprintf(stderr,"call dilithium_bigpubget\n"); if ( dilithium_bigpubget(handle,destpub33,pk,destpubtxid) < 0 ) return eval->Invalid("couldnt get bigpub"); else { - fprintf(stderr,"call _dilithium_verify\n"); + sig[777] ^= 0xaa; if ( _dilithium_verify(msg2,&mlen,&sig[0],smlen,pk) < 0 ) return eval->Invalid("failed dilithium verify"); else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) From ddae255171e120b7fdb00bfef1a744a98352c6a2 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 07:00:21 -1100 Subject: [PATCH 1123/1145] Dlithium validation active, hardforking change --- src/cc/dilithium.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index 8c56b0bc7..ab8ca9ae5 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -2905,6 +2905,9 @@ int32_t main(void) cclib spend 19 \"[%224aac73ebe82c12665d1d005a0ae1a1493cb1e2c714680ef9d016f48a7c77b4a2%22,%22210255c46dbce584e3751081b39d7fc054fc807100557e73fc444481618b5706afb4ac%22]\" + this generates a really big hex, broadcast it and if all went well it will get confirmed. + a dilithium spend! + */ #define DILITHIUM_TXFEE 10000 @@ -3248,12 +3251,11 @@ bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,con return eval->Invalid("couldnt get bigpub"); else { - sig[777] ^= 0xaa; if ( _dilithium_verify(msg2,&mlen,&sig[0],smlen,pk) < 0 ) return eval->Invalid("failed dilithium verify"); else if ( mlen != 32 || memcmp(msg,msg2,32) != 0 ) return eval->Invalid("failed dilithium msg verify"); - else return eval->Invalid("this is actually success!"); + else return(true); } } else return eval->Invalid("destpubtxid or sig size didnt match send opret"); } else return eval->Invalid("failed decode dilithium spendopret"); From 98d8d03e2f8928e74cc8b3700c041806a3cf39ba Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 07:27:30 -1100 Subject: [PATCH 1124/1145] Gold * gold payout algo change --- src/cc/rogue_rpc.cpp | 106 ++++++++++++++++++++++--------------------- 1 file changed, 54 insertions(+), 52 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 8cfb4379f..16c09fbe9 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -947,6 +947,56 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } +int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) +{ + static uint32_t good,bad; static uint256 prevgame; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; CPubKey roguepk; struct rogue_player P; + if ( gametxid == prevgame ) + return(0); + prevgame = gametxid; + roguepk = GetUnspendable(cp,0); + GetCCaddress1of2(cp,rogueaddr,roguepk,pk); + //fprintf(stderr,"call extractgame\n"); + if ( (keystrokes= rogue_extractgame(0,str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) + { + //fprintf(stderr,"numkeys.%d rogue_extractgame %s\n",numkeys,gametxid.GetHex().c_str()); + free(keystrokes); + //fprintf(stderr,"extracted.(%s)\n",str); + if ( newdata == playerdata ) + { + good++; + fprintf(stderr,"%s good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); + return(0); + } + newdata[10] = newdata[11] = playerdata[10] = playerdata[11] = 0; + if ( newdata == playerdata ) + { + good++; + fprintf(stderr,"%s matched after clearing maxstrength good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); + return(0); + } + for (i=0; i no playerdata, good.%d bad.%d\n",good,bad); + } + bad++; + fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); + fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); + } + //fprintf(stderr,"no keys rogue_extractgame %s\n",gametxid.GetHex().c_str()); + return(-1); +} + UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *params,char *method) { //vin0 -> highlander vout from creategame TCBOO @@ -975,12 +1025,12 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( strcmp(method,"bailout") == 0 ) { funcid = 'Q'; - mult = 100000; + mult = 100; //100000; } else { funcid = 'H'; - mult = 200000; + mult = 200; //200000; } if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { @@ -1005,7 +1055,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param { num = rogue_replay2(player,seed,keystrokes,numkeys,playerdata.size()==0?0:&P,0); if ( keystrokes != 0 ) - free(keystrokes); + free(keystrokes), keystrokes = 0; } else num = 0; mtx.vin.push_back(CTxIn(batontxid,batonvout,CScript())); mtx.vin.push_back(CTxIn(gametxid,1+maxplayers+regslot,CScript())); @@ -1034,7 +1084,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,1,mypk)); if ( P.amulet != 0 ) mult *= 5; - cashout = (uint64_t)P.gold * mult; + cashout = (uint64_t)P.gold * P.gold * mult; fprintf(stderr,"\nextracted $$$gold.%d -> %.8f ROGUE hp.%d strength.%d/%d level.%d exp.%d dl.%d n.%d amulet.%d\n",P.gold,(double)cashout/COIN,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel,n,P.amulet); if ( funcid == 'H' && maxplayers > 1 ) { @@ -1051,7 +1101,6 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } } mtx.vout.push_back(MakeCC1vout(cp->evalcode,CCchange + (batonvalue-3*txfee),roguepk)); - Myprivkey(mypriv); CCaddr1of2set(cp,roguepk,mypk,mypriv,myrogueaddr); CScript opret; @@ -1245,53 +1294,6 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } -int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) -{ - static uint32_t good,bad; static uint256 prevgame; - char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; CPubKey roguepk; struct rogue_player P; - if ( gametxid == prevgame ) - return(0); - prevgame = gametxid; - roguepk = GetUnspendable(cp,0); - GetCCaddress1of2(cp,rogueaddr,roguepk,pk); - //fprintf(stderr,"call extractgame\n"); - if ( (keystrokes= rogue_extractgame(0,str,&numkeys,newdata,seed,playertxid,cp,gametxid,rogueaddr)) != 0 ) - { - //fprintf(stderr,"numkeys.%d rogue_extractgame %s\n",numkeys,gametxid.GetHex().c_str()); - free(keystrokes); - //fprintf(stderr,"extracted.(%s)\n",str); - if ( newdata == playerdata ) - { - good++; - fprintf(stderr,"%s good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); - return(0); - } - newdata[10] = newdata[11] = playerdata[10] = playerdata[11] = 0; - if ( newdata == playerdata ) - { - good++; - fprintf(stderr,"%s matched after clearing maxstrength good.%d bad.%d\n",gametxid.GetHex().c_str(),good,bad); - return(0); - } - for (i=0; i no playerdata, good.%d bad.%d\n",good,bad); - if ( newdata.size() == 0 ) - { - good++; - return(0); - } - } - bad++; - fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); - fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); - } - //fprintf(stderr,"no keys rogue_extractgame %s\n",gametxid.GetHex().c_str()); - return(-1); -} - bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; From 4dcef6624bc8f2c1da09a9e8e78bca8357872028 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 08:17:20 -1100 Subject: [PATCH 1125/1145] Delay after keystrokes --- src/cc/rogue/main.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 165f01dfd..4dba36f2b 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -726,9 +726,10 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { - //fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); + fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); free(retstr); } + sleep(1); } } } From b88129c21cfeb98a32131056daafdcfc462652b7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 08:19:09 -1100 Subject: [PATCH 1126/1145] Force keystrokes --- src/cc/rogue/rogue.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index e8de063de..52d41435c 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -567,6 +567,8 @@ playit(struct rogue_state *rs) } } } + if ( rs->guiflag != 0 ) + flushkeystrokes(rs); endit(0); } From 46055e824fbf3d9b1e132863026faef9eb30236e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 08:29:21 -1100 Subject: [PATCH 1127/1145] Log keystrokes to keystrokes.log --- src/cc/rogue/main.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 4dba36f2b..5de27317e 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -723,10 +723,17 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ } else { + static FILE *fp; + if ( fp == 0 ) + fp = fopen("keystrokes.log","a"); sprintf(params,"[\"keystrokes\",\"17\",\"[%%22%s%%22,%%22%s%%22]\"]",Gametxidstr,hexstr); if ( (retstr= komodo_issuemethod(USERPASS,"cclib",params,ROGUE_PORT)) != 0 ) { - fprintf(stderr,"KEYSTROKES.(%s)\n",retstr); + if ( fp != 0 ) + { + fprintf(fp,"%s\n",retstr); + fflush(fp); + } free(retstr); } sleep(1); From df66ea2b9da0a3bcafc4517077736607cf255f8e Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 08:37:33 -1100 Subject: [PATCH 1128/1145] Kill the zombies --- src/cc/rogue/state.c | 2 +- src/cc/rogue_rpc.cpp | 33 +++++++++++++++++++++------------ 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/cc/rogue/state.c b/src/cc/rogue/state.c index 7a0e2e4c6..b0176a042 100644 --- a/src/cc/rogue/state.c +++ b/src/cc/rogue/state.c @@ -1432,7 +1432,7 @@ rs_write_object(struct rogue_state *rs,FILE *savef, THING *o) if ( o->_o._o_packch != 0 ) { item = &rs->P.roguepack[rs->P.packsize]; - if ( 0 && pstats.s_hpt <= 0 ) + if ( 1 && pstats.s_hpt <= 0 ) { //fprintf(stderr,"KILLED\n"); rs->P.gold = -1; diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 16c09fbe9..4790932d1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -883,13 +883,22 @@ char *rogue_extractgame(int32_t makefiles,char *str,int32_t *numkeysp,std::vecto if ( endP.gold <= 0 || endP.hitpoints <= 0 || (endP.strength&0xffff) <= 0 || endP.level <= 0 || endP.experience <= 0 || endP.dungeonlevel <= 0 ) { //fprintf(stderr,"zero value character was killed -> no playerdata\n"); - //newdata.resize(0); - P.gold = (P.gold * 8) / 10; + newdata.resize(0); + //P.gold = (P.gold * 8) / 10; + if ( keystrokes != 0 ) + { + free(keystrokes); + keystrokes = 0; + *numkeysp = 0; + } + } + else + { + sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); + fprintf(stderr,"%s\n",str); + *numkeysp = numkeys; + return(keystrokes); } - sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); - fprintf(stderr,"%s\n",str); - *numkeysp = numkeys; - return(keystrokes); } else num = 0; } else @@ -979,9 +988,9 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp ((uint8_t *)&P)[i] = playerdata[i]; if ( P.gold <= 0 || P.hitpoints <= 0 || (P.strength&0xffff) <= 0 || P.level <= 0 || P.experience <= 0 || P.dungeonlevel <= 0 ) { - P.gold = (P.gold * 8) / 10; - for (i=0; i no playerdata\n"); - //newdata.resize(0); - P.gold = (P.gold * 8) / 10; + newdata.resize(0); + //P.gold = (P.gold * 8) / 10; } - //else + else { //if ( maxplayers == 1 ) // mult /= 2; From b0735e2f327ce7ca08224e274b86a3a177a9d2d7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 09:11:38 -1100 Subject: [PATCH 1129/1145] Gold payout = (gold * gold * level * 10) satoshi --- src/cc/rogue_rpc.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 4790932d1..1a4f7c1cd 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1020,7 +1020,7 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param // vout0 -> 1% ingame gold // get any playerdata, get all keystrokes, replay game and compare final state CMutableTransaction mtx = CreateNewContextualCMutableTransaction(Params().GetConsensus(), komodo_nextheight()); - UniValue result(UniValue::VOBJ); std::string rawtx,symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,err,gameheight,tmp,numplayers,regslot,n,num,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata,nodata; uint256 batontxid,playertxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; + UniValue result(UniValue::VOBJ); std::string rawtx,symbol,pname; CTransaction gametx; uint64_t seed,mult; int64_t buyin,batonvalue,inputsum,cashout,CCchange=0; int32_t i,err,gameheight,tmp,numplayers,regslot,n,num,dungeonlevel,numkeys,maxplayers,batonht,batonvout; char myrogueaddr[64],*keystrokes = 0; std::vector playerdata,newdata,nodata; uint256 batontxid,playertxid,gametxid; CPubKey mypk,roguepk; uint8_t player[10000],mypriv[32],funcid; struct CCcontract_info *cpTokens, tokensC; if ( txfee == 0 ) @@ -1034,12 +1034,12 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param if ( strcmp(method,"bailout") == 0 ) { funcid = 'Q'; - mult = 100; //100000; + mult = 10; //100000; } else { funcid = 'H'; - mult = 200; //200000; + mult = 20; //200000; } if ( params != 0 && (n= cJSON_GetArraySize(params)) > 0 ) { @@ -1093,7 +1093,10 @@ UniValue rogue_finishgame(uint64_t txfee,struct CCcontract_info *cp,cJSON *param mtx.vout.push_back(MakeTokensCC1vout(cp->evalcode,1,mypk)); if ( P.amulet != 0 ) mult *= 5; - cashout = (uint64_t)P.gold * P.gold * mult; + dungeonlevel = P.dungeonlevel; + if ( P.amulet != 0 && dungeonlevel < 21 ) + dungeonlevel = 21; + cashout = (uint64_t)P.gold * P.gold * mult * dungeonlevel; fprintf(stderr,"\nextracted $$$gold.%d -> %.8f ROGUE hp.%d strength.%d/%d level.%d exp.%d dl.%d n.%d amulet.%d\n",P.gold,(double)cashout/COIN,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel,n,P.amulet); if ( funcid == 'H' && maxplayers > 1 ) { From 8c5ba39d22f91af50e0bf93d1e7cd2f1dce5828f Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Mon, 25 Feb 2019 13:18:14 +0800 Subject: [PATCH 1130/1145] fix ipaddress --- src/cc/rogue/main.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 5de27317e..02690a482 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -587,9 +587,9 @@ char *curl_post(CURL **cHandlep,char *url,char *userpass,char *postfields,char * return(chunk.memory); } -uint16_t _komodo_userpass(char *username, char *password, char *ipaddress, FILE *fp) +uint16_t _komodo_userpass(char *username, char *password, FILE *fp) { - char *rpcuser,*rpcpassword,*str,line[8192]; uint16_t port = 0; + char *rpcuser,*rpcpassword,*str,*ipaddress,line[8192]; uint16_t port = 0; rpcuser = rpcpassword = 0; username[0] = password[0] = 0; while ( fgets(line,sizeof(line),fp) != 0 ) @@ -609,6 +609,7 @@ uint16_t _komodo_userpass(char *username, char *password, char *ipaddress, FILE else if ( (str= strstr(line,(char *)"ipaddress")) != 0 ) { ipaddress = parse_conf_line(str,(char *)"ipaddress"); + strcpy(IPADDRESS,ipaddress); } } if ( rpcuser != 0 && rpcpassword != 0 ) @@ -616,7 +617,7 @@ uint16_t _komodo_userpass(char *username, char *password, char *ipaddress, FILE strcpy(username,rpcuser); strcpy(password,rpcpassword); } - //printf("rpcuser.(%s) rpcpassword.(%s) KMDUSERPASS.(%s) %u\n",rpcuser,rpcpassword,KMDUSERPASS,port); + //printf("rpcuser.(%s) rpcpassword.(%s) %u ipaddress.%s\n",rpcuser,rpcpassword,port,ipaddress); if ( rpcuser != 0 ) free(rpcuser); if ( rpcpassword != 0 ) @@ -661,7 +662,7 @@ uint16_t _komodo_userpass(char *username, char *password, char *ipaddress, FILE //printf("test.(%s) -> [%s] statename.(%s) %s\n",test,ASSETCHAINS_SYMBOL,symbol,fname); }*/ -uint16_t komodo_userpass(char *userpass,char *symbol,char *ipaddress) +uint16_t komodo_userpass(char *userpass,char *symbol) { FILE *fp; uint16_t port = 0; char fname[512],username[512],password[512],confname[KOMODO_ASSETCHAIN_MAXLEN]; userpass[0] = 0; @@ -677,7 +678,7 @@ uint16_t komodo_userpass(char *userpass,char *symbol,char *ipaddress) //komodo_statefname(fname,symbol,confname); if ( (fp= fopen(confname,"rb")) != 0 ) { - port = _komodo_userpass(username,password,ipaddress,fp); + port = _komodo_userpass(username,password,fp); sprintf(userpass,"%s:%s",username,password); if ( strcmp(symbol,ASSETCHAINS_SYMBOL) == 0 ) strcpy(USERPASS,userpass); @@ -809,10 +810,10 @@ int main(int argc, char **argv, char **envp) ASSETCHAINS_SYMBOL[j++] = toupper(c); } ASSETCHAINS_SYMBOL[j++] = 0; - ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL,IPADDRESS); + ROGUE_PORT = komodo_userpass(userpass,ASSETCHAINS_SYMBOL); if ( IPADDRESS[0] == 0 ) strcpy(IPADDRESS,"127.0.0.1"); - printf("ASSETCHAINS_SYMBOL.(%s) port.%u (%s)\n",ASSETCHAINS_SYMBOL,ROGUE_PORT,USERPASS); sleep(1); + printf("ASSETCHAINS_SYMBOL.(%s) port.%u (%s) IPADDRESS.%s \n",ASSETCHAINS_SYMBOL,ROGUE_PORT,USERPASS,IPADDRESS); sleep(1); if ( argc == 2 && (fp=fopen(argv[1],"rb")) == 0 ) { seed = atol(argv[1]); From 6f5d9655c903ae265eb0f0cb72da4cf9af4b0b9d Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Mon, 25 Feb 2019 13:20:48 +0800 Subject: [PATCH 1131/1145] fix --- src/musigtest.py | 189 --------------------------------------- src/wallet/rpcwallet.cpp | 8 +- 2 files changed, 4 insertions(+), 193 deletions(-) delete mode 100755 src/musigtest.py diff --git a/src/musigtest.py b/src/musigtest.py deleted file mode 100755 index 0880f1494..000000000 --- a/src/musigtest.py +++ /dev/null @@ -1,189 +0,0 @@ -#!/usr/bin/env python3 -import platform -import os -import re -import json -import random -import base58 -import binascii -import hashlib -import sys -import time -from slickrpc import Proxy - -# fucntion to define rpc_connection -def def_credentials(chain): - rpcport = ''; - operating_system = platform.system() - if operating_system == 'Darwin': - ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo' - elif operating_system == 'Linux': - ac_dir = os.environ['HOME'] + '/.komodo' - elif operating_system == 'Windows': - ac_dir = '%s/komodo/' % os.environ['APPDATA'] - if chain == 'KMD': - coin_config_file = str(ac_dir + '/komodo.conf') - else: - coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') - with open(coin_config_file, 'r') as f: - for line in f: - l = line.rstrip() - if re.search('rpcuser', l): - rpcuser = l.replace('rpcuser=', '') - elif re.search('rpcpassword', l): - rpcpassword = l.replace('rpcpassword=', '') - elif re.search('rpcport', l): - rpcport = l.replace('rpcport=', '') - if len(rpcport) == 0: - if chain == 'KMD': - rpcport = 7771 - else: - print("rpcport not in conf file, exiting") - print("check " + coin_config_file) - exit(1) - return (Proxy("http://%s:%s@127.0.0.1:%d" % (rpcuser, rpcpassword, int(rpcport)))) - - -# generate address, validate address, dump private key -def genvaldump(rpc_connection): - # get new address - address = rpc_connection.getnewaddress() - # validate address - validateaddress_result = rpc_connection.validateaddress(address) - pubkey = validateaddress_result['pubkey'] - address = validateaddress_result['address'] - # dump private key for the address - privkey = rpc_connection.dumpprivkey(address) - # function output - output = [pubkey, privkey, address] - return(output) - -CHAIN = 'MUSIG' #sys.argv[1] - -rpc = def_credentials(CHAIN) - -pubkeys = [] -address_info = [] -ret = input('Do you want to generate new pubkeys? ').lower() - -if ret.startswith('y'): - numpks = int(input('Enter number of pubkeys to combine: ')) - if os.path.isfile("list.json"): - print('Already have list.json, move it if you would like to generate a new set.') - sys.exit(0) - while len(address_info) < numpks: - addressinfo = genvaldump(rpc) - address_info.append(addressinfo) - f = open("list.json", "w+") - f.write(json.dumps(address_info)) -else: - if os.path.isfile("list.json"): - with open('list.json') as list: - address_info = json.load(list) - else: - sys.exit('No list.json you need to create new pubkeys!') - -for addressinfo in address_info: - pubkeys.append(addressinfo[0]) - -ret = rpc.setpubkey(pubkeys[0]) -ret = rpc.cclib("combine", "18", str(pubkeys)) -pkhash = str(ret['pkhash']) -combinedpk = str(ret['combined_pk']) -print('Your combined pubkey is: ' + combinedpk) -print('Your pkhash is: ' + pkhash) -amount = int(input('Enter amount to send: ')) -tmp = str([combinedpk, amount]) -hex = rpc.cclib("send", "18", tmp)['hex'] -senttxid = rpc.sendrawtransaction(hex) -print('Your senttxid is: ' + senttxid) - -print("Waiting for tx to be confirmed") -while True: - confirmed = int(rpc.gettransaction(senttxid)["confirmations"]) - if not confirmed: - time.sleep(10) - else: - print('SentTX confirmed') - break - -scriptPubKey = rpc.getrawtransaction(senttxid,1)['vout'][1]['scriptPubKey']['hex'] -print('Your scriptPubKey is: ' + scriptPubKey) -tmp = str([senttxid, scriptPubKey]) -msg = rpc.cclib("calcmsg", "18", tmp)['msg'] -print('Your msg is: ' + msg) - -i = 0; -commitments = [] -for pubkey in pubkeys: - ret = rpc.setpubkey(pubkey) - tmp = str([i, len(pubkeys), combinedpk, pkhash, msg]) - commitments.append(rpc.cclib("session", "18", tmp)['commitment']) - i = i + 1 - -#print(commitments) - -i = 0 -nonces = [] -for pubkey in pubkeys: - ret = rpc.setpubkey(pubkey) - n = 0 - for commitment in commitments: - tmp = str([i, pkhash, n, commitment]) - ret = rpc.cclib("commit", "18", tmp) - try: - nonces.append(ret['nonce']) - except: - x = 1 - n = n + 1 - i = i + 1 - -#print(nonces) - -i = 0 -partialsigs = [] -for pubkey in pubkeys: - ret = rpc.setpubkey(pubkey) - n = 0 - for nonce in nonces: - tmp = str([i, pkhash, n, nonce]) - ret = rpc.cclib("nonce", "18", tmp) - try: - partialsigs.append(ret['partialsig']) - except: - x = 1 - n = n + 1 - i = i + 1 - -#print(partialsigs) - -i = 0 -combinedsigs = [] -for pubkey in pubkeys: - ret = rpc.setpubkey(pubkey) - n = 0 - for partialsig in partialsigs: - tmp = str([i, pkhash, n, partialsig]) - ret = rpc.cclib("partialsig", "18", tmp) - try: - combinedsigs.append(ret['combinedsig']) - except: - x = 1 - n = n + 1 - i = i + 1 - -#print(combinedsigs) - -tmp = str([msg, combinedpk, combinedsigs[0]]) -ret = rpc.cclib("verify", "18", tmp) - -#print(ret) - -tmp = str([senttxid, scriptPubKey, combinedsigs[0]]) -ret = rpc.cclib("spend", "18", tmp) - -print(ret) - -ret = rpc.sendrawtransaction(ret['hex']) - -print(ret) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 8cffd78f7..0ed2f866c 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5308,8 +5308,8 @@ UniValue setpubkey(const UniValue& params, bool fHelp) char Raddress[64]; uint8_t pubkey33[33]; - //if ( NOTARY_PUBKEY33[0] == 0 ) - //{ + if ( NOTARY_PUBKEY33[0] == 0 ) + { if (strlen(params[0].get_str().c_str()) == 66) { decode_hex(pubkey33,33,(char *)params[0].get_str().c_str()); @@ -5337,14 +5337,14 @@ UniValue setpubkey(const UniValue& params, bool fHelp) USE_EXTERNAL_PUBKEY = 1; } } else result.push_back(Pair("error", "pubkey is wrong length, must be 66 char hex string.")); - /*} + } else { result.push_back(Pair("error", "Can only set pubkey once, to change it you need to restart your daemon, pubkey in use is below.")); pubkey2addr((char *)Raddress,(uint8_t *)NOTARY_PUBKEY33); std::string address_ret; address_ret.assign(Raddress); result.push_back(Pair("address",address_ret)); - }*/ + } result.push_back(Pair("pubkey", NOTARY_PUBKEY)); return result; } From c5930804ab2789402fa7c0a0d73460a1aa32488b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 18:24:33 -1100 Subject: [PATCH 1132/1145] Flush keystrokes every 1000 --- src/cc/rogue/rogue.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue/rogue.c b/src/cc/rogue/rogue.c index 52d41435c..53f6da353 100644 --- a/src/cc/rogue/rogue.c +++ b/src/cc/rogue/rogue.c @@ -560,7 +560,7 @@ playit(struct rogue_state *rs) } else { - if ( rs->needflush != 0 && rs->num > 8000 ) + if ( rs->needflush != 0 && rs->num > 1000 ) { if ( flushkeystrokes(rs) == 0 ) rs->needflush = 0; From 54ee605f7f5be48886c14e9bfbc56564096238f8 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 18:27:26 -1100 Subject: [PATCH 1133/1145] Save params in keystrokes.log --- src/cc/rogue/main.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/cc/rogue/main.c b/src/cc/rogue/main.c index 5de27317e..ec347dd12 100644 --- a/src/cc/rogue/main.c +++ b/src/cc/rogue/main.c @@ -731,6 +731,7 @@ void rogue_progress(struct rogue_state *rs,uint64_t seed,char *keystrokes,int32_ { if ( fp != 0 ) { + fprintf(fp,"%s\n",params); fprintf(fp,"%s\n",retstr); fflush(fp); } From e8a36b89826e934a20f95a229b3ab103a67414af Mon Sep 17 00:00:00 2001 From: blackjok3r Date: Mon, 25 Feb 2019 17:12:25 +0800 Subject: [PATCH 1134/1145] Update to enable using a single node with musigtest.py script. Fix crash in nonce step. --- src/cc/musig.cpp | 126 +++++++++++++++--------- src/musigtest.py | 200 +++++++++++++++++++++++++++++++++++++++ src/wallet/rpcwallet.cpp | 2 +- 3 files changed, 282 insertions(+), 46 deletions(-) create mode 100755 src/musigtest.py diff --git a/src/cc/musig.cpp b/src/cc/musig.cpp index 5986f8716..35293088c 100644 --- a/src/cc/musig.cpp +++ b/src/cc/musig.cpp @@ -33,7 +33,6 @@ } sendrawtransaction of the above hex. - ./komodo-cli -ac_name=MUSIG getrawtransaction 5ce74037a153ee210413b48d4e88638b99825a2de1a1f1aa0d36ebf93019824c 1 "vout": [ { @@ -83,7 +82,7 @@ the "msg" is what needs to be signed to create a valid spend 5 args: ind, numsigners, combined_pk, pkhash, message to be signed on node with pubkey: 02fb6aa0b96cad24d46b5da93eba3864c45ce07a73bba12da530ae841e140fcf28 - ./komodo-cli -ac_name=MUSIG cclib session 18 '[0,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","c1b34139744f3b54b652dc741ebd0f9d5b53ad28795cc6614dd8ad3aaabf15ae","f5d91999b23b85630a4cbd0baea3736529411b052cf5f1f4345c5d181af12825"]' + ./komodo-cli -ac_name=MUSIG cclib session 18 '[0,2,"03f016c348437c7422eed92d865aa9789614f75327cada463eefc566126b54785b","5cb5a225064ca6ffc1438cb2a6ac2ac65fe2d5055dc7f6c7ebffb9a231f8912b","f7fb85d1412814e3c2f98b990802af6ee33dad368c6ba05c2050e9e5506fcd75"]' { "myind": 0, "numsigners": 2, @@ -221,7 +220,9 @@ struct musig_info secp256k1_musig_partial_signature *partial_sig; //[N_SIGNERS]; int32_t myind,num,numcommits,numnonces,numpartials; uint8_t msg[32],pkhash[32],combpk[33]; -} *MUSIG; +}; + +std::vector MUSIG; struct musig_info *musig_infocreate(int32_t myind,int32_t num) { @@ -412,23 +413,33 @@ UniValue musig_combine(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t i,n,myind,num; char *pkstr,*pkhashstr,*msgstr; uint8_t session[32],msg[32],pkhash[32],privkey[32],pub33[33]; CPubKey pk; char str[67]; + UniValue result(UniValue::VOBJ); int32_t i,n,myind,num,musiglocation; char *pkstr,*pkhashstr,*msgstr; uint8_t session[32],msg[32],pkhash[32],privkey[32],pub33[33]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 5 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) >= 5 ) { myind = juint(jitem(params,0),0); num = juint(jitem(params,1),0); if ( myind < 0 || myind >= num || num <= 0 ) return(cclib_error(result,"illegal myindex and numsigners")); - if ( MUSIG != 0 ) - musig_infofree(MUSIG), MUSIG = 0; - MUSIG = musig_infocreate(myind,num); - if ( musig_parsepubkey(ctx,MUSIG->combined_pk,jitem(params,2)) < 0 ) + if ( n > 5 ) + musiglocation = juint(jitem(params,5),0); + else if ( n == 5 ) + musiglocation = 0; + //printf("number of params.%i musiglocation.%i\n",n,musiglocation); + if ( MUSIG.size() > musiglocation ) + { + for (int i = 0; i < MUSIG.size()-1; i++) + musig_infofree(MUSIG[i]); + MUSIG.clear(); + } + struct musig_info *temp_musig = musig_infocreate(myind,num); + MUSIG.push_back(temp_musig); + if ( musig_parsepubkey(ctx,MUSIG[musiglocation]->combined_pk,jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing combined_pubkey")); - else if ( cclib_parsehash(MUSIG->pkhash,jitem(params,3),32) < 0 ) + else if ( cclib_parsehash(MUSIG[musiglocation]->pkhash,jitem(params,3),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( cclib_parsehash(MUSIG->msg,jitem(params,4),32) < 0 ) + else if ( cclib_parsehash(MUSIG[musiglocation]->msg,jitem(params,4),32) < 0 ) return(cclib_error(result,"error parsing msg")); Myprivkey(privkey); GetRandBytes(session,32); @@ -458,15 +469,17 @@ UniValue musig_session(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * my_index: index of this signer in the signers array * seckey: the signer's 32-byte secret key (cannot be NULL) */ - if ( secp256k1_musig_session_initialize(ctx,&MUSIG->session,MUSIG->signer_data, &MUSIG->nonce_commitments[MUSIG->myind * 32],session,MUSIG->msg,&MUSIG->combined_pk,MUSIG->pkhash,MUSIG->num,MUSIG->myind,privkey) > 0 ) + //fprintf(stderr, "SESSION: struct_size.%li using struct %i\n",MUSIG.size(), musiglocation); + if ( secp256k1_musig_session_initialize(ctx,&MUSIG[musiglocation]->session,MUSIG[musiglocation]->signer_data, &MUSIG[musiglocation]->nonce_commitments[MUSIG[musiglocation]->myind * 32],session,MUSIG[musiglocation]->msg,&MUSIG[musiglocation]->combined_pk,MUSIG[musiglocation]->pkhash,MUSIG[musiglocation]->num,MUSIG[musiglocation]->myind,privkey) > 0 ) { memset(session,0,sizeof(session)); result.push_back(Pair("myind",(int64_t)myind)); result.push_back(Pair("numsigners",(int64_t)num)); for (i=0; i<32; i++) - sprintf(&str[i<<1],"%02x",MUSIG->nonce_commitments[MUSIG->myind*32 + i]); + sprintf(&str[i<<1],"%02x",MUSIG[musiglocation]->nonce_commitments[MUSIG[musiglocation]->myind*32 + i]); str[64] = 0; - MUSIG->numcommits = 1; + if ( n == 5 ) + MUSIG[musiglocation]->numcommits = 1; result.push_back(Pair("commitment",str)); result.push_back(Pair("result","success")); return(result); @@ -483,18 +496,22 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; size_t clen = CPubKey::PUBLIC_KEY_SIZE; - UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32]; CPubKey pk; char str[67]; + UniValue result(UniValue::VOBJ); int32_t i,n,ind,myind; uint8_t pkhash[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) >= 3 ) { + if ( n > 3 ) + myind = juint(jitem(params,3),0); + else if ( n == 3 ) + myind = 0; if ( cclib_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG[myind]->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); - else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG[myind]->num ) return(cclib_error(result,"illegal ind for session")); - else if ( cclib_parsehash(&MUSIG->nonce_commitments[ind*32],jitem(params,2),32) < 0 ) + else if ( cclib_parsehash(&MUSIG[myind]->nonce_commitments[ind*32],jitem(params,2),32) < 0 ) return(cclib_error(result,"error parsing commitment")); /** Gets the signer's public nonce given a list of all signers' data with commitments * @@ -512,16 +529,18 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * number of signers participating in the MuSig. */ result.push_back(Pair("added_index",ind)); - MUSIG->numcommits++; - if ( MUSIG->numcommits >= MUSIG->num && secp256k1_musig_session_get_public_nonce(ctx,&MUSIG->session,MUSIG->signer_data,&MUSIG->nonces[MUSIG->myind],MUSIG->commitment_ptrs,MUSIG->num) > 0 ) + //fprintf(stderr, "COMMIT: struct_size.%li using_struct.%i added_index.%i\n",MUSIG.size(), myind, ind); + MUSIG[myind]->numcommits++; + if ( MUSIG[myind]->numcommits >= MUSIG[myind]->num && secp256k1_musig_session_get_public_nonce(ctx,&MUSIG[myind]->session,MUSIG[myind]->signer_data,&MUSIG[myind]->nonces[MUSIG[myind]->myind],MUSIG[myind]->commitment_ptrs,MUSIG[myind]->num) > 0 ) { - if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG->nonces[MUSIG->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) + if ( secp256k1_ec_pubkey_serialize(ctx,(uint8_t *)pk.begin(),&clen,&MUSIG[myind]->nonces[MUSIG[myind]->myind],SECP256K1_EC_COMPRESSED) > 0 && clen == 33 ) { for (i=0; i<33; i++) sprintf(&str[i<<1],"%02x",((uint8_t *)pk.begin())[i]); str[66] = 0; - MUSIG->numnonces = 1; - result.push_back(Pair("myind",MUSIG->myind)); + if ( n == 5 ) + MUSIG[myind]->numnonces = 1; + result.push_back(Pair("myind",MUSIG[myind]->myind)); result.push_back(Pair("nonce",str)); result.push_back(Pair("result","success")); } else return(cclib_error(result,"error serializing nonce (pubkey)")); @@ -538,18 +557,22 @@ UniValue musig_commit(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t i,n,ind; uint8_t pkhash[32],psig[32]; CPubKey pk; char str[67]; + UniValue result(UniValue::VOBJ); int32_t i,n,ind,myind; uint8_t pkhash[32],psig[32]; CPubKey pk; char str[67]; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) >= 3 ) { + if ( n > 3 ) + myind = juint(jitem(params,3),0); + else if ( n == 3 ) + myind = 0; if ( cclib_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG[myind]->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); - else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG[myind]->num ) return(cclib_error(result,"illegal ind for session")); - else if ( musig_parsepubkey(ctx,MUSIG->nonces[ind],jitem(params,2)) < 0 ) + else if ( musig_parsepubkey(ctx,MUSIG[myind]->nonces[ind],jitem(params,2)) < 0 ) return(cclib_error(result,"error parsing nonce")); result.push_back(Pair("added_index",ind)); /** Checks a signer's public nonce against a commitment to said nonce, and update @@ -563,9 +586,17 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * with `musig_session_initialize_verifier`. * In: nonce: signer's alleged public nonce (cannot be NULL) */ - for (i=0; inum; i++) + MUSIG[myind]->numnonces++; + //fprintf(stderr, "NONCE: struct_size.%li using_struct.%i added_index.%i numnounces.%i num.%i\n",MUSIG.size(), myind, ind, MUSIG[myind]->numnonces, MUSIG[myind]->num); + if ( MUSIG[myind]->numnonces < MUSIG[myind]->num ) { - if ( secp256k1_musig_set_nonce(ctx,&MUSIG->signer_data[i],&MUSIG->nonces[i]) == 0 ) + result.push_back(Pair("status","not enough nonces")); + result.push_back(Pair("result","success")); + return(result); + } + for (i=0; inum; i++) + { + if ( secp256k1_musig_set_nonce(ctx,&MUSIG[myind]->signer_data[i],&MUSIG[myind]->nonces[i]) == 0 ) return(cclib_error(result,"error setting nonce")); } /** Updates a session with the combined public nonce of all signers. The combined @@ -586,20 +617,20 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) * adaptor: point to add to the combined public nonce. If NULL, nothing is * added to the combined nonce. */ - MUSIG->numnonces++; - if ( MUSIG->numnonces >= MUSIG->num && secp256k1_musig_session_combine_nonces(ctx,&MUSIG->session,MUSIG->signer_data,MUSIG->num,NULL,NULL) > 0 ) + if ( secp256k1_musig_session_combine_nonces(ctx,&MUSIG[myind]->session,MUSIG[myind]->signer_data,MUSIG[myind]->num,NULL,NULL) > 0 ) { - if ( secp256k1_musig_partial_sign(ctx,&MUSIG->session,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + if ( secp256k1_musig_partial_sign(ctx,&MUSIG[myind]->session,&MUSIG[myind]->partial_sig[MUSIG[myind]->myind]) > 0 ) { - if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG[myind]->partial_sig[MUSIG[myind]->myind]) > 0 ) { for (i=0; i<32; i++) sprintf(&str[i<<1],"%02x",psig[i]); str[64] = 0; - result.push_back(Pair("myind",MUSIG->myind)); + result.push_back(Pair("myind",MUSIG[myind]->myind)); result.push_back(Pair("partialsig",str)); result.push_back(Pair("result","success")); - MUSIG->numpartials = 1; + if ( n == 5 ) + MUSIG[myind]->numpartials = 1; return(result); } else return(cclib_error(result,"error serializing partial sig")); } else return(cclib_error(result,"error making partial sig")); @@ -610,24 +641,29 @@ UniValue musig_nonce(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) { static secp256k1_context *ctx; - UniValue result(UniValue::VOBJ); int32_t i,ind,n; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; + UniValue result(UniValue::VOBJ); int32_t i,ind,n,myind; uint8_t pkhash[32],psig[32],out64[64]; char str[129]; secp256k1_schnorrsig sig; if ( ctx == 0 ) ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); - if ( params != 0 && (n= cJSON_GetArraySize(params)) == 3 ) + if ( params != 0 && (n= cJSON_GetArraySize(params)) >= 3 ) { + if ( n > 3 ) + myind = juint(jitem(params,3),0); + else if ( n == 3 ) + myind = 0; if ( cclib_parsehash(pkhash,jitem(params,0),32) < 0 ) return(cclib_error(result,"error parsing pkhash")); - else if ( memcmp(MUSIG->pkhash,pkhash,32) != 0 ) + else if ( memcmp(MUSIG[myind]->pkhash,pkhash,32) != 0 ) return(cclib_error(result,"pkhash doesnt match session pkhash")); - else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG->num ) + else if ( (ind= juint(jitem(params,1),0)) < 0 || ind >= MUSIG[myind]->num ) return(cclib_error(result,"illegal ind for session")); else if ( cclib_parsehash(psig,jitem(params,2),32) < 0 ) return(cclib_error(result,"error parsing psig")); - else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG->partial_sig[ind],psig) == 0 ) + else if ( secp256k1_musig_partial_signature_parse(ctx,&MUSIG[myind]->partial_sig[ind],psig) == 0 ) return(cclib_error(result,"error parsing partialsig")); result.push_back(Pair("added_index",ind)); - MUSIG->numpartials++; - if ( MUSIG->numpartials >= MUSIG->num && secp256k1_musig_partial_sig_combine(ctx,&MUSIG->session,&sig,MUSIG->partial_sig,MUSIG->num) > 0 ) + //fprintf(stderr, "SIG: struct_size.%li using_struct.%i added_index.%i\n",MUSIG.size(), myind, ind); + MUSIG[myind]->numpartials++; + if ( MUSIG[myind]->numpartials >= MUSIG[myind]->num && secp256k1_musig_partial_sig_combine(ctx,&MUSIG[myind]->session,&sig,MUSIG[myind]->partial_sig,MUSIG[myind]->num) > 0 ) { if ( secp256k1_schnorrsig_serialize(ctx,out64,&sig) > 0 ) { @@ -640,7 +676,7 @@ UniValue musig_partialsig(uint64_t txfee,struct CCcontract_info *cp,cJSON *param } else { - if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG->partial_sig[MUSIG->myind]) > 0 ) + if ( secp256k1_musig_partial_signature_serialize(ctx,psig,&MUSIG[myind]->partial_sig[MUSIG[myind]->myind]) > 0 ) { result.push_back(Pair("myind",ind)); for (i=0; i<32; i++) diff --git a/src/musigtest.py b/src/musigtest.py new file mode 100755 index 000000000..a452b7e97 --- /dev/null +++ b/src/musigtest.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +import platform +import os +import re +import json +import random +import base58 +import binascii +import hashlib +import sys +import time +from slickrpc import Proxy + +# fucntion to define rpc_connection +def def_credentials(chain): + rpcport = ''; + operating_system = platform.system() + if operating_system == 'Darwin': + ac_dir = os.environ['HOME'] + '/Library/Application Support/Komodo' + elif operating_system == 'Linux': + ac_dir = os.environ['HOME'] + '/.komodo' + elif operating_system == 'Windows': + ac_dir = '%s/komodo/' % os.environ['APPDATA'] + if chain == 'KMD': + coin_config_file = str(ac_dir + '/komodo.conf') + else: + coin_config_file = str(ac_dir + '/' + chain + '/' + chain + '.conf') + with open(coin_config_file, 'r') as f: + for line in f: + l = line.rstrip() + if re.search('rpcuser', l): + rpcuser = l.replace('rpcuser=', '') + elif re.search('rpcpassword', l): + rpcpassword = l.replace('rpcpassword=', '') + elif re.search('rpcport', l): + rpcport = l.replace('rpcport=', '') + if len(rpcport) == 0: + if chain == 'KMD': + rpcport = 7771 + else: + print("rpcport not in conf file, exiting") + print("check " + coin_config_file) + exit(1) + return (Proxy("http://%s:%s@127.0.0.1:%d" % (rpcuser, rpcpassword, int(rpcport)))) + + +# generate address, validate address, dump private key +def genvaldump(rpc_connection): + # get new address + address = rpc_connection.getnewaddress() + # validate address + validateaddress_result = rpc_connection.validateaddress(address) + pubkey = validateaddress_result['pubkey'] + address = validateaddress_result['address'] + # dump private key for the address + privkey = rpc_connection.dumpprivkey(address) + # function output + output = [pubkey, privkey, address] + return(output) + +CHAIN = 'MUSIG' #sys.argv[1] + +rpc = def_credentials(CHAIN) + +pubkeys = [] +address_info = [] +ret = input('Do you want to generate new pubkeys? ').lower() + +if ret.startswith('y'): + numpks = int(input('Enter number of pubkeys to combine: ')) + if os.path.isfile("list.json"): + print('Already have list.json, move it if you would like to generate a new set.') + sys.exit(0) + while len(address_info) < numpks: + addressinfo = genvaldump(rpc) + address_info.append(addressinfo) + f = open("list.json", "w+") + f.write(json.dumps(address_info)) +else: + if os.path.isfile("list.json"): + with open('list.json') as list: + address_info = json.load(list) + else: + sys.exit('No list.json you need to create new pubkeys!') + +for addressinfo in address_info: + pubkeys.append(addressinfo[0]) + +ret = rpc.setpubkey(pubkeys[0]) +ret = rpc.cclib("combine", "18", str(pubkeys)) +pkhash = str(ret['pkhash']) +combinedpk = str(ret['combined_pk']) +print('Your combined pubkey is: ' + combinedpk) +print('Your pkhash is: ' + pkhash) +amount = float(input('Enter amount to send: ')) +if amount == 0: + sys.exit('Cannot send 0 coins. Exiting.') +tmp = str([combinedpk, amount]) +hex = rpc.cclib("send", "18", tmp)['hex'] +senttxid = rpc.sendrawtransaction(hex) +print('Your senttxid is: ' + senttxid) + +print("Waiting for tx to be confirmed") +while True: + confirmed = int(rpc.gettransaction(senttxid)["confirmations"]) + if not confirmed: + time.sleep(10) + else: + print('SentTX confirmed') + break + +scriptPubKey = rpc.getrawtransaction(senttxid,1)['vout'][1]['scriptPubKey']['hex'] +print('Your scriptPubKey is: ' + scriptPubKey) +tmp = str([senttxid, scriptPubKey]) +msg = rpc.cclib("calcmsg", "18", tmp)['msg'] +print('Your msg is: ' + msg) + +i = 0; +commitments = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + tmp = str([i, len(pubkeys), combinedpk, pkhash, msg, i]) + commitments.append(rpc.cclib("session", "18", tmp)['commitment']) + i = i + 1 + +print("Created commitments sucessfully... Sending to all signers.") + +i = 0 +nonces = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + n = 0 + for commitment in commitments: + tmp = str([pkhash, n, commitment, i]) + ret = rpc.cclib("commit", "18", tmp) + try: + nonces.append(ret['nonce']) + except: + x = 1 + n = n + 1 + i = i + 1 + +print("Created nounce's sucessfully... Sending to all signers.") + +i = 0 +partialsigs = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + n = 0 + for nonce in nonces: + tmp = str([pkhash, n, nonce, i]) + ret = rpc.cclib("nonce", "18", tmp) + try: + partialsigs.append(ret['partialsig']) + except: + x = 1 + n = n + 1 + i = i + 1 + +print("Created partial sigs sucessfully... Sending to all signers.") + +i = 0 +combinedsigs = [] +for pubkey in pubkeys: + ret = rpc.setpubkey(pubkey) + n = 0 + for partialsig in partialsigs: + tmp = str([pkhash, n, partialsig, i]) + ret = rpc.cclib("partialsig", "18", tmp) + try: + combinedsigs.append(ret['combinedsig']) + except: + x = 1 + n = n + 1 + i = i + 1 + +print("Created combined sigs sucessfully... Verifying.") + +tmp = str([msg, combinedpk, combinedsigs[0]]) +ret = rpc.cclib("verify", "18", tmp) + +if ret['result'] != "success": + print(ret) + sys.exit('Could not verify signature.') + +print('Verified... Attempting to send.') + +tmp = str([senttxid, scriptPubKey, combinedsigs[0]]) +ret = rpc.cclib("spend", "18", tmp) + +if ret['result'] != "success": + print(ret) + sys.exit('Could not create spend transaction.') + +try: + ret = rpc.sendrawtransaction(ret['hex']) +except: + sys.exit('Could not send transaction.') + +print('Spent txid: ' + ret) diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 0ed2f866c..0e0ab9906 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -5308,7 +5308,7 @@ UniValue setpubkey(const UniValue& params, bool fHelp) char Raddress[64]; uint8_t pubkey33[33]; - if ( NOTARY_PUBKEY33[0] == 0 ) + if ( NOTARY_PUBKEY33[0] == 0 || (strcmp(ASSETCHAINS_SYMBOL, "MUSIG") == 0) ) { if (strlen(params[0].get_str().c_str()) == 66) { From 4d4a74d917c80d4dc2fa46bdf40348049ef3ec8d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 22:44:40 -1100 Subject: [PATCH 1135/1145] Cashout prints --- src/cc/dilithium.c | 1 + src/cc/rogue_rpc.cpp | 65 ++++++++++++++++++++++++++++++-------------- 2 files changed, 46 insertions(+), 20 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index ab8ca9ae5..c0ff8f274 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3232,6 +3232,7 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { CPubKey destpub33; std::string handle; uint256 hashBlock,destpubtxid,checktxid; CTransaction vintx; int32_t numvouts,mlen,smlen=CRYPTO_BYTES+32; std::vector sig; uint8_t msg[32],msg2[CRYPTO_BYTES+32],pk[CRYPTO_PUBLICKEYBYTES]; + // if all dilithium tx -> do multispend/send, else: if ( tx.vout.size() != 2 ) return eval->Invalid("numvouts != 2"); else if ( tx.vin.size() != 1 ) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 1a4f7c1cd..3d9b02115 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -894,7 +894,7 @@ char *rogue_extractgame(int32_t makefiles,char *str,int32_t *numkeysp,std::vecto } else { - sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); + sprintf(str,"extracted $$$gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d",endP.gold,endP.hitpoints,endP.strength&0xffff,endP.strength>>16,endP.level,endP.experience,endP.dungeonlevel); fprintf(stderr,"%s\n",str); *numkeysp = numkeys; return(keystrokes); @@ -956,13 +956,11 @@ UniValue rogue_extract(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) return(result); } -int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) +int32_t rogue_playerdata_validate(int64_t *cashoutp,uint256 &playertxid,struct CCcontract_info *cp,std::vector playerdata,uint256 gametxid,CPubKey pk) { static uint32_t good,bad; static uint256 prevgame; - char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,numkeys; std::vector newdata; uint64_t seed; CPubKey roguepk; struct rogue_player P; - if ( gametxid == prevgame ) - return(0); - prevgame = gametxid; + char str[512],*keystrokes,rogueaddr[64],str2[67]; int32_t i,dungeonlevel,numkeys; std::vector newdata; uint64_t seed,mult = 10; CPubKey roguepk; struct rogue_player P; + *cashoutp = 0; roguepk = GetUnspendable(cp,0); GetCCaddress1of2(cp,rogueaddr,roguepk,pk); //fprintf(stderr,"call extractgame\n"); @@ -971,21 +969,35 @@ int32_t rogue_playerdata_validate(uint256 &playertxid,struct CCcontract_info *cp //fprintf(stderr,"numkeys.%d rogue_extractgame %s\n",numkeys,gametxid.GetHex().c_str()); free(keystrokes); //fprintf(stderr,"extracted.(%s)\n",str); + for (i=0; i no playerdata, good.%d bad.%d\n",good,bad); + } + *cashoutp = 0; return(0); } - fprintf(stderr,"zero value character was killed -> no playerdata, good.%d bad.%d\n",good,bad); } - bad++; - fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); - fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); + if ( gametxid != prevgame ) + { + prevgame = gametxid; + bad++; + fprintf(stderr,"%s playerdata: gold.%d hp.%d strength.%d/%d level.%d exp.%d dl.%d\n",gametxid.GetHex().c_str(),P.gold,P.hitpoints,P.strength&0xffff,P.strength>>16,P.level,P.experience,P.dungeonlevel); + fprintf(stderr,"newdata[%d] != playerdata[%d], numkeys.%d %s pub.%s playertxid.%s good.%d bad.%d\n",(int32_t)newdata.size(),(int32_t)playerdata.size(),numkeys,rogueaddr,pubkey33_str(str2,(uint8_t *)&pk),playertxid.GetHex().c_str(),good,bad); + } } //fprintf(stderr,"no keys rogue_extractgame %s\n",gametxid.GetHex().c_str()); return(-1); @@ -1308,7 +1329,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin,cashout; std::vector playerdata,keystrokes; std::string symbol,pname; if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) @@ -1393,10 +1414,14 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C // verify pk belongs to this tx if ( playerdata.size() > 0 ) { - if ( rogue_playerdata_validate(ptxid,cp,playerdata,gametxid,pk) < 0 ) + if ( rogue_playerdata_validate(&cashout,ptxid,cp,playerdata,gametxid,pk) < 0 ) { //fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); - } //else fprintf(stderr,"ht.%d playertxid.%s validated\n",height,ptxid.GetHex().c_str()); + } + if ( funcid == 'H' ) + cashout *= 2; + if ( tx.vout.size() > 2 ) + fprintf(stderr,"ht.%d playertxid.%s cashout %.8f vs vout2 %.8f\n",height,ptxid.GetHex().c_str(),(double)cashout/COIN,(double)tx.vout[2].nValue/COIN); } if ( funcid == 'Q' ) { From 4a09d29d0ddb199b94ddb3a35352343085409487 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 22:57:10 -1100 Subject: [PATCH 1136/1145] +print --- src/cc/rogue_rpc.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 3d9b02115..f2b6b7986 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -518,7 +518,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( active == zeroid || rogue_playerdata(cp,origplayergame,tid,pk,playerdata,symbol,pname,active) == 0 ) { txid = matchtx.GetHash(); - //fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); + fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); n = 0; while ( CCgettxout(txid,0,1) < 0 ) { @@ -532,6 +532,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke return(-2); } txid = spenttxid; + fprintf(stderr,"next txid.%s/v%d\n",txid.GetHex().c_str(),spentvini); if ( spentvini != 0 ) return(-3); if ( keystrokesp != 0 && myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() >= 2 ) From c8d3d0c13b79ed62e56aeb51c2b377b3cc1b6f03 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 22:59:31 -1100 Subject: [PATCH 1137/1145] Test --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index f2b6b7986..23204e225 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -505,7 +505,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke } if ( matches == 1 ) { - if ( myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) + if ( 1 || myIsutxo_spent(spenttxid,gametxid,maxplayers+i+1) < 0 ) { numvouts = matchtx.vout.size(); //fprintf(stderr,"matchtxid.%s matches.%d numvouts.%d\n",matchtx.GetHash().GetHex().c_str(),matches,numvouts); @@ -576,7 +576,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke else { fprintf(stderr,"already played\n"); - return(-5); + return(-6); } } return(-1); From 957343c1f4fbf420f3ff534c34b3cd2604fb9239 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 23:01:02 -1100 Subject: [PATCH 1138/1145] Fix can't find baton error --- src/cc/rogue_rpc.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 23204e225..305b6cd8f 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -518,7 +518,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke if ( active == zeroid || rogue_playerdata(cp,origplayergame,tid,pk,playerdata,symbol,pname,active) == 0 ) { txid = matchtx.GetHash(); - fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); + //fprintf(stderr,"scan forward active.%s spenttxid.%s\n",active.GetHex().c_str(),txid.GetHex().c_str()); n = 0; while ( CCgettxout(txid,0,1) < 0 ) { @@ -532,7 +532,7 @@ int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **ke return(-2); } txid = spenttxid; - fprintf(stderr,"next txid.%s/v%d\n",txid.GetHex().c_str(),spentvini); + //fprintf(stderr,"next txid.%s/v%d\n",txid.GetHex().c_str(),spentvini); if ( spentvini != 0 ) return(-3); if ( keystrokesp != 0 && myGetTransaction(spenttxid,spenttx,hashBlock) != 0 && spenttx.vout.size() >= 2 ) From 8fa093fad2fce1a3470f9374418493864c30620b Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 23:06:30 -1100 Subject: [PATCH 1139/1145] Test --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 305b6cd8f..4ce8a4748 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1417,7 +1417,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C { if ( rogue_playerdata_validate(&cashout,ptxid,cp,playerdata,gametxid,pk) < 0 ) { - //fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); + fprintf(stderr,"ht.%d gametxid.%s player.%s invalid playerdata[%d]\n",height,gametxid.GetHex().c_str(),ptxid.GetHex().c_str(),(int32_t)playerdata.size()); } if ( funcid == 'H' ) cashout *= 2; From 9340287d340f9625e25f807d89858792161523d7 Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 23:08:08 -1100 Subject: [PATCH 1140/1145] txid --- src/cc/rogue_rpc.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 4ce8a4748..d6a325fa1 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1330,11 +1330,12 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,tokenid,batontxid,playertxid,ptxid; int64_t buyin,cashout; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,txid,tokenid,batontxid,playertxid,ptxid; int64_t buyin,cashout; std::vector playerdata,keystrokes; std::string symbol,pname; if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) { + txid = tx.GetHash(); scriptPubKey = tx.vout[numvouts-1].scriptPubKey; GetOpReturnData(scriptPubKey,vopret); if ( vopret.size() > 2 ) @@ -1422,7 +1423,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C if ( funcid == 'H' ) cashout *= 2; if ( tx.vout.size() > 2 ) - fprintf(stderr,"ht.%d playertxid.%s cashout %.8f vs vout2 %.8f\n",height,ptxid.GetHex().c_str(),(double)cashout/COIN,(double)tx.vout[2].nValue/COIN); + fprintf(stderr,"ht.%d txid.%s cashout %.8f vs vout2 %.8f\n",height,txid.GetHex().c_str(),(double)cashout/COIN,(double)tx.vout[2].nValue/COIN); } if ( funcid == 'Q' ) { From 9a9204085bbce2aa2441c0ed55e358ef7772c59d Mon Sep 17 00:00:00 2001 From: jl777 Date: Sun, 24 Feb 2019 23:18:35 -1100 Subject: [PATCH 1141/1145] -print --- src/cc/rogue_rpc.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d6a325fa1..c8e37d161 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1422,7 +1422,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } if ( funcid == 'H' ) cashout *= 2; - if ( tx.vout.size() > 2 ) + if ( tx.vout.size() > 3 ) // orig of 't' has 0 cashout fprintf(stderr,"ht.%d txid.%s cashout %.8f vs vout2 %.8f\n",height,txid.GetHex().c_str(),(double)cashout/COIN,(double)tx.vout[2].nValue/COIN); } if ( funcid == 'Q' ) From 208aff399794b5eecc5f4c4ac79d7b9536d8391e Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 25 Feb 2019 01:58:46 -1100 Subject: [PATCH 1142/1145] Skip revalidating playertxid for asset tx --- src/cc/rogue_rpc.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index c8e37d161..d98a77711 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1406,6 +1406,16 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C break; } } + else // this is asset transaction, which means playerdata txid already confirmed + { + switch ( funcid ) + { + case 'H': // win + case 'Q': // bailout + return(true); + break; + } + } switch ( funcid ) { case 'R': // register From b711cfaee314f503d5897f14c1cf882eea5b450d Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 25 Feb 2019 02:18:53 -1100 Subject: [PATCH 1143/1145] Test --- src/cc/dilithium.c | 5 ++++- src/cc/rogue_rpc.cpp | 8 +++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/cc/dilithium.c b/src/cc/dilithium.c index c0ff8f274..9a9c4de71 100644 --- a/src/cc/dilithium.c +++ b/src/cc/dilithium.c @@ -3231,8 +3231,11 @@ UniValue dilithium_spend(uint64_t txfee,struct CCcontract_info *cp,cJSON *params bool dilithium_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CPubKey destpub33; std::string handle; uint256 hashBlock,destpubtxid,checktxid; CTransaction vintx; int32_t numvouts,mlen,smlen=CRYPTO_BYTES+32; std::vector sig; uint8_t msg[32],msg2[CRYPTO_BYTES+32],pk[CRYPTO_PUBLICKEYBYTES]; + CPubKey destpub33; std::string handle; uint256 hashBlock,destpubtxid,checktxid; CTransaction vintx; int32_t numvouts,numvins,mlen,smlen=CRYPTO_BYTES+32; std::vector sig; uint8_t msg[32],msg2[CRYPTO_BYTES+32],pk[CRYPTO_PUBLICKEYBYTES]; // if all dilithium tx -> do multispend/send, else: + numvouts = tx.vout.size(); + numvins = tx.vin.size(); + if ( tx.vout.size() != 2 ) return eval->Invalid("numvouts != 2"); else if ( tx.vin.size() != 1 ) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index d98a77711..9accfe7f7 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1330,7 +1330,7 @@ UniValue rogue_setname(uint64_t txfee,struct CCcontract_info *cp,cJSON *params) bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const CTransaction tx) { - CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,txid,tokenid,batontxid,playertxid,ptxid; int64_t buyin,cashout; std::vector playerdata,keystrokes; std::string symbol,pname; + CScript scriptPubKey; std::vector vopret; uint8_t *script,e,f,funcid,tokentx=0; int32_t i,maxplayers,decoded=0,regslot,ind,err,dispflag,gameheight,score,numvouts; CTransaction vintx,gametx; CPubKey pk; uint256 hashBlock,gametxid,txid,tokenid,batontxid,playertxid,ptxid; int64_t buyin,cashout; std::vector playerdata,keystrokes; std::string symbol,pname; if ( strcmp(ASSETCHAINS_SYMBOL,"ROGUE") == 0 && height < 21274 ) return(true); if ( (numvouts= tx.vout.size()) > 1 ) @@ -1344,6 +1344,7 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C funcid = script[1]; if ( (e= script[0]) == EVAL_TOKENS ) { + tokentx = 1; if ( (funcid= rogue_highlanderopretdecode(gametxid,tokenid,regslot,pk,playerdata,symbol,pname,scriptPubKey)) == 0 ) { if ( (funcid= rogue_registeropretdecode(gametxid,tokenid,playertxid,scriptPubKey)) == 0 ) @@ -1408,13 +1409,14 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C } else // this is asset transaction, which means playerdata txid already confirmed { - switch ( funcid ) + fprintf(stderr,"ht.%d tokentx.%d funcid.(%c)\n",height,tokentx,funcid); + /*switch ( funcid ) { case 'H': // win case 'Q': // bailout return(true); break; - } + }*/ } switch ( funcid ) { From 6e51ad8984a21a9e6e34b6bd96012f47978a2b4a Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 25 Feb 2019 02:24:59 -1100 Subject: [PATCH 1144/1145] -print --- src/cc/rogue_rpc.cpp | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 9accfe7f7..88b669799 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -1407,17 +1407,6 @@ bool rogue_validate(struct CCcontract_info *cp,int32_t height,Eval *eval,const C break; } } - else // this is asset transaction, which means playerdata txid already confirmed - { - fprintf(stderr,"ht.%d tokentx.%d funcid.(%c)\n",height,tokentx,funcid); - /*switch ( funcid ) - { - case 'H': // win - case 'Q': // bailout - return(true); - break; - }*/ - } switch ( funcid ) { case 'R': // register From 3ac0038a15b63d913863981a068dfe4bd6097a03 Mon Sep 17 00:00:00 2001 From: jl777 Date: Mon, 25 Feb 2019 02:41:02 -1100 Subject: [PATCH 1145/1145] Rescue cancelled warriors --- src/cc/rogue_rpc.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/cc/rogue_rpc.cpp b/src/cc/rogue_rpc.cpp index 88b669799..aee151530 100644 --- a/src/cc/rogue_rpc.cpp +++ b/src/cc/rogue_rpc.cpp @@ -472,12 +472,25 @@ int32_t rogue_playerdata(struct CCcontract_info *cp,uint256 &origplayergame,uint int32_t rogue_playerdataspend(CMutableTransaction &mtx,uint256 playertxid,int32_t vout,uint256 origplayergame) { - int64_t txfee = 10000; + int64_t txfee = 10000; CTransaction tx; uint256 hashBlock; if ( CCgettxout(playertxid,vout,1) == 1 ) // not sure if this is enough validation { mtx.vin.push_back(CTxIn(playertxid,vout,CScript())); return(0); - } else return(-1); + } + else + { + vout = 0; + if ( myGetTransaction(playertxid,tx,hashBlock) != 0 && tx.vout[vout].nValue == 1 && tx.vout[vout].scriptPubKey.IsPayToCryptoCondition() != 0 ) + { + if ( CCgettxout(playertxid,vout,1) == 1 ) // not sure if this is enough validation + { + mtx.vin.push_back(CTxIn(playertxid,vout,CScript())); + return(0); + } + } + return(-1); + } } int32_t rogue_findbaton(struct CCcontract_info *cp,uint256 &playertxid,char **keystrokesp,int32_t &numkeys,int32_t ®slot,std::vector &playerdata,uint256 &batontxid,int32_t &batonvout,int64_t &batonvalue,int32_t &batonht,uint256 gametxid,CTransaction gametx,int32_t maxplayers,char *destaddr,int32_t &numplayers,std::string &symbol,std::string &pname)