From b7060c7de00002407f3f6fbf8b01e230e33c673f Mon Sep 17 00:00:00 2001 From: DanS Date: Thu, 27 Aug 2026 13:20:51 -0500 Subject: [PATCH] =?UTF-8?q?hygiene:=20Phase=203=20=E2=80=94=20dead-code=20?= =?UTF-8?q?excision=20(~7,100=20lines)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Third phase of the code-hygiene remediation: remove provably-dead code. Each in-file deletion was adversarially verified (a per-finding investigator plus a skeptic that greps the tree to refute deletability); the sanity grep confirms zero dangling references, and the tree builds and self-mines clean. Removed wholesale: - src/cc/dapps/ (9 files, ~6,939 lines): a git-tracked but never-built Komodo DEX / z-migration tool (hushdex.c, zmigrate.c, cJSON.c, ...). Nothing in Makefile.am/configure.ac references it. In-file dead code: - pow.cpp: the `#ifdef original_algo` oldRT_CST_RST function (the macro is never defined in source or build flags) and two `if ( 0 )` debug blocks. - walletdb.cpp: the "orphaned staking transaction" cleanup path (deadTxns) — DragonX is RandomX PoW with no staking, so the guard is always false and the block never runs; also drop the now-unused static/extern decls. - cc/eval.h: the ProcessCC / Eval::ImportCoin / ImportPayout / DisputePayout declarations that have no definition anywhere in the tree. - rpc/crosschain.cpp: the crosschainproof stub RPC (returned {} unconditionally) and its registrations in rpc/server.cpp, rpc/server.h, rpc/client.cpp. - coins.cpp: the commented-out `//TODO: delete` Sprout PushAnchor template. - wallet.cpp: the permanently-zero KMD `interest2` term in CreateTransaction. - rpc/net.cpp: hush_longestchain's always-zero `n` var (num > (n>>1) => num>0) and its `if ( 0 )` debug branch. - hush_nSPV.h / hush_nSPV_fullnode.h: three `if ( 0 && ... )` dead debug branches. - net.cpp, crypter.h, saplingconsolidation.cpp (dup set_error_code), shieldcoinbase.cpp (`donation < 0` on a uint8_t), cclib.cpp (unused FAUCET2SIZE): single-line dead-code fixes. Deliberately NOT touched (verification refuted the audit's "dead on DragonX" premise): the ~2,250-line HUSH3 checkpoint block, the miner notary/timelock paths, and hush_gateway.h — all reachable at runtime via -ac_name / -ac_* args (the inherited Komodo assetchain model), and hush_gateway's hush_opretvalidate is called from ConnectBlock (consensus). Dropping those requires a deliberate decision to remove HAC/HUSH3 mode, tracked separately. Co-Authored-By: Claude Opus 4.8 (1M context) --- .gitignore | 2 - src/cc/cclib.cpp | 1 - src/cc/dapps/Makefile | 20 - src/cc/dapps/README.md | 72 - src/cc/dapps/cJSON.c | 1201 ------------- src/cc/dapps/dappinc.h | 1597 ----------------- src/cc/dapps/dappstd.c | 1114 ------------ src/cc/dapps/hushdex.c | 1385 -------------- src/cc/dapps/hushdex.json | 19 - src/cc/dapps/makedapps | 2 - src/cc/dapps/zmigrate.c | 1529 ---------------- src/cc/eval.h | 16 - src/coins.cpp | 13 - src/hush_nSPV.h | 2 - src/hush_nSPV_fullnode.h | 4 - src/net.cpp | 1 - src/pow.cpp | 83 - src/rpc/client.cpp | 1 - src/rpc/crosschain.cpp | 8 - src/rpc/net.cpp | 7 +- src/rpc/server.cpp | 1 - src/rpc/server.h | 1 - ...asyncrpcoperation_saplingconsolidation.cpp | 1 - .../asyncrpcoperation_shieldcoinbase.cpp | 2 +- src/wallet/crypter.h | 1 - src/wallet/wallet.cpp | 6 +- src/wallet/walletdb.cpp | 28 +- 27 files changed, 6 insertions(+), 7111 deletions(-) delete mode 100644 src/cc/dapps/Makefile delete mode 100644 src/cc/dapps/README.md delete mode 100644 src/cc/dapps/cJSON.c delete mode 100644 src/cc/dapps/dappinc.h delete mode 100644 src/cc/dapps/dappstd.c delete mode 100644 src/cc/dapps/hushdex.c delete mode 100644 src/cc/dapps/hushdex.json delete mode 100755 src/cc/dapps/makedapps delete mode 100644 src/cc/dapps/zmigrate.c diff --git a/.gitignore b/.gitignore index 441696a83..1cc352ee3 100644 --- a/.gitignore +++ b/.gitignore @@ -131,7 +131,6 @@ src/cc/rogue/rogue src/cc/rogue/rogue.so src/cc/rogue/test.zip -src/cc/dapps/a.out src/checkfile src/foo.zip @@ -154,7 +153,6 @@ src/rogue.scr src/cc/rogue/confdefs.h src/cc/rogue/x64 -src/cc/dapps/a.out src/Makefile.in doc/man/Makefile.in Makefile.in diff --git a/src/cc/cclib.cpp b/src/cc/cclib.cpp index cf0dfcfe2..95dc25026 100644 --- a/src/cc/cclib.cpp +++ b/src/cc/cclib.cpp @@ -25,7 +25,6 @@ #include "main.h" #include "chain.h" #include "core_io.h" -#define FAUCET2SIZE COIN #define EVAL_FAUCET2 EVAL_FIRSTUSER #ifdef BUILD_CUSTOMCC diff --git a/src/cc/dapps/Makefile b/src/cc/dapps/Makefile deleted file mode 100644 index 0489d37a9..000000000 --- a/src/cc/dapps/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# Copyright (c) 2016-2024 The Hush Developers -# Distributed under the GPLv3 software license, see the accompanying -# file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html -# Just type make to compile all dat dapp code, fellow cypherpunkz - -# we no longer build zmigrate by default, nobody uses that fucking code -all: hushdex - -hushdex: - $(CC) hushdex.c -o hushdex -lm - -# Just for historical knowledge, to study how fucking stupid -# ZEC+KMD were to still support sprout, to this day!!!!!!!! -# Hush leads the entire world into the future, sans Sprout turdz -zmigrate: - $(CC) zmigrate.c -o zmigrate -lm - -clean: - rm zmigrate - diff --git a/src/cc/dapps/README.md b/src/cc/dapps/README.md deleted file mode 100644 index 86930e87a..000000000 --- a/src/cc/dapps/README.md +++ /dev/null @@ -1,72 +0,0 @@ -# CryptoCondition dApps - -## Compiling - -To compile all dapps in this directory: - - make - -## zmigrate - Sprout to Sapling Migration dApp - -This tool converts Sprout zaddress funds into Sapling funds in a new Sapling address. -This is not applicable to HUSH3, since we have no Sprout funds, but left for historical -purposes. - -### Usage - - ./zmigrate COIN zsaplingaddr - -The above command may need to be run multiple times to complete the process. - -This CLI implementation will be called by GUI wallets, average users do not -need to worry about using this low-level tool. - -## HushDEX - -HushDEX forked from the Subatomic Decentralized App (dapp) and we focus purely -on privacy coin swaps, and specifically, shielded swaps between Zcash Protocol -coins. These are called z-swaps. - -### Z-swap example - -Alice has 1 ZEC and wants to trade it for 5 HUSH, since she hears HushChat is -pretty awesome and ZEC just goes down in price, always. We represent this in -a diagram like this - - Alice (ZEC) <> Bob (HUSH) - -HushDEX is only concerns with Sapling shielded addresses (zaddrs) which start -with `zs1`. Even though ZEC supports Sprout addresses (which start with `zc`), -they cannot be used on HushDEX. Sprout is unsupported on HushDEX. - -So Alice must make sure her ZEC is in a Sapling zaddr, and then she can use -HushDEX on her computer, to z-swap with Bob, in a decentralized way, with -no centralized service. The system is not completely trustless, users must -trust the developers and miners on the relevant chains to not do nefarious -things. There is no central authority to decide who gets to do what, it's -peer-to-peer like BitTorrent or Tor. - -### Privacy Features of Z-Swaps - - * No KYC - * We will not feed the identity theft industry any more free data - * No IP address limiting - * It is trivial to pay for an IP address from any country in the world - * Alice's address never appears in public data - * Bob's address never appears in public data - * Consequently, Alice and Bob's address cannot be searched for on an explorer - * Since you can't see the address of any transaction, you cannot infer if - the same address appears as sender or receiver in many transactions. - * The amount of the transaction, how much ZEC and how much HUSH, is unknown - * It could be pennies or millions - * The exchange rate of the transaction never appears on the blockchain - * The exchange rate will be leaked to the network p2p layer, but it is never - recorded in blockchain history. If you are not there to record it, it is gone. - * Realistically, it's simple to run a malicious node which records all exchange rates - and so we assume an adversary does this - * Since the exchange rate of ZEC/HUSH is already public data, this is not considered valuable - information leakage. We are leaking the differential of CEX ZEC/HUSH exchange ratio to - this DEX's ratio. - * Adversaries watching all possible public data can infer exchange ratios but no amounts - or addresses, which is considered a massive blow against blockchain analysis. - diff --git a/src/cc/dapps/cJSON.c b/src/cc/dapps/cJSON.c deleted file mode 100644 index 555d04993..000000000 --- a/src/cc/dapps/cJSON.c +++ /dev/null @@ -1,1201 +0,0 @@ -// Copyright (c) 2016-2024 The Hush developers -// Distributed under the GPLv3 software license, see the accompanying -// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html -/* - Copyright (c) 2009 Dave Gamble - - 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 - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - */ - -/* cJSON */ -/* JSON parser in C. */ -#include - -#include "../includes/cJSON.h" - -#ifndef DBL_EPSILON -#define DBL_EPSILON 2.2204460492503131E-16 -#endif - -static const char *ep; - -long stripquotes(char *str) -{ - long len,offset; - if ( str == 0 ) - return(0); - len = strlen(str); - if ( str[0] == '"' && str[len-1] == '"' ) - { - str[len-1] = 0; - offset = 1; - } - else offset = 0; - return(offset); -} - -const char *cJSON_GetErrorPtr(void) {return ep;} - -static int32_t cJSON_strcasecmp(const char *s1,const char *s2) -{ - if (!s1) return (s1==s2)?0:1;if (!s2) return 1; - for(; tolower((int32_t)(*s1)) == tolower((int32_t)(*s2)); ++s1, ++s2) if(*s1 == 0) return 0; - return tolower((int32_t)(*(const unsigned char *)s1)) - tolower((int32_t)(*(const unsigned char *)s2)); -} - -void *LP_alloc(uint64_t len); -void LP_free(void *ptr); -static void *(*cJSON_malloc)(size_t sz) = (void *)malloc;//LP_alloc; -static void (*cJSON_free)(void *ptr) = free;//LP_free; - -static void *cJSON_mallocstr(int32_t len) -{ - return(cJSON_malloc(len)); -} - -static char **cJSON_mallocptrs(int32_t num,char **space,int32_t max) -{ - if ( num < max ) - return(space); - else return(cJSON_malloc(num * sizeof(char *))); -} - -static void *cJSON_mallocnode() -{ - return(cJSON_malloc(sizeof(cJSON))); -} - -static void cJSON_freeptrs(char **ptrs,int32_t num,char **space) -{ - if ( ptrs != space ) - cJSON_free(ptrs); -} - -static void cJSON_freestr(char *str) -{ - cJSON_free(str); -} - -static void cJSON_freenode(cJSON *item) -{ - cJSON_free(item); -} - -static char* cJSON_strdup(const char* str) -{ - size_t len; - char* copy; - - len = strlen(str) + 1; - if (!(copy = (char*)cJSON_mallocstr((int32_t)len+1))) return 0; - memcpy(copy,str,len); - return copy; -} - -void cJSON_InitHooks(cJSON_Hooks* hooks) -{ - if (!hooks) { /* Reset hooks */ - cJSON_malloc = malloc; - cJSON_free = free; - return; - } - - cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc; - cJSON_free = (hooks->free_fn)?hooks->free_fn:free; -} - -/* Internal constructor. */ -static cJSON *cJSON_New_Item(void) -{ - cJSON* node = (cJSON*)cJSON_mallocnode(); - if (node) memset(node,0,sizeof(cJSON)); - return node; -} - -/* Delete a cJSON structure. */ -void cJSON_Delete(cJSON *c) -{ - cJSON *next; - while (c) - { - next=c->next; - if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child); - if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_freestr(c->valuestring); - if (c->string) cJSON_freestr(c->string); - cJSON_freenode(c); - c=next; - } -} - -/* Parse the input text to generate a number, and populate the result into item. */ -static const char *parse_number(cJSON *item,const char *num) -{ - double n=0,sign=1,scale=0;int32_t subscale=0,signsubscale=1; - - if (*num=='-') sign=-1,num++; /* Has sign? */ - if (*num=='0') num++; /* is zero */ - if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */ - if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */ - if (*num=='e' || *num=='E') /* Exponent? */ - { num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */ - while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */ - } - - n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */ - - item->valuedouble=n; - item->valueint=(int64_t)n; - item->type=cJSON_Number; - return num; -} - -/* Render the number nicely from the given item into a string. */ -static char *print_number(cJSON *item) -{ - char *str; - double d = item->valuedouble; - if ( fabs(((double)item->valueint) - d) <= DBL_EPSILON && d >= (1. - DBL_EPSILON) && d < (1LL << 62) )//d <= INT_MAX && d >= INT_MIN ) - { - str = (char *)cJSON_mallocstr(24); /* 2^64+1 can be represented in 21 chars + sign. */ - if ( str != 0 ) - sprintf(str,"%lld",(long long)item->valueint); - } - else - { - str = (char *)cJSON_mallocstr(66); /* This is a nice tradeoff. */ - if ( str != 0 ) - { - if ( fabs(floor(d) - d) <= DBL_EPSILON && fabs(d) < 1.0e60 ) - sprintf(str,"%.0f",d); - //else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d); - else - sprintf(str,"%.8f",d); - } - } - return str; -} - -static unsigned parse_hex4(const char *str) -{ - unsigned h=0; - if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; - h=h<<4;str++; - if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; - h=h<<4;str++; - if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; - h=h<<4;str++; - if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; - return h; -} - -/* Parse the input text into an unescaped cstring, and populate item. */ -static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; -static const char *parse_string(cJSON *item,const char *str) -{ - const char *ptr=str+1;char *ptr2;char *out;int32_t len=0;unsigned uc,uc2; - if (*str!='\"') {ep=str;return 0;} /* not a string! */ - - while (*ptr!='\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; // Skip escaped quotes - - out=(char*)cJSON_mallocstr(len+2); /* This is how long we need for the string, roughly. */ - if (!out) return 0; - - ptr=str+1;ptr2=out; - while (*ptr!='\"' && *ptr) - { - if (*ptr!='\\') - { - if ( *ptr == '%' && is_hexstr((char *)&ptr[1],2) && isprint(_decode_hex((char *)&ptr[1])) != 0 ) - *ptr2++ = _decode_hex((char *)&ptr[1]), ptr += 3; - else *ptr2++ = *ptr++; - } - else - { - ptr++; - switch (*ptr) - { - case 'b': *ptr2++='\b'; break; - case 'f': *ptr2++='\f'; break; - case 'n': *ptr2++='\n'; break; - case 'r': *ptr2++='\r'; break; - case 't': *ptr2++='\t'; break; - case 'u': // transcode utf16 to utf8 - uc=parse_hex4(ptr+1);ptr+=4; // get the unicode char - - if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) break; // check for invalid - - if (uc>=0xD800 && uc<=0xDBFF) // UTF16 surrogate pairs - { - if (ptr[1]!='\\' || ptr[2]!='u') break; // missing second-half of surrogate. - uc2=parse_hex4(ptr+3);ptr+=6; - if (uc2<0xDC00 || uc2>0xDFFF) break; // invalid second-half of surrogate - uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF)); - } - - len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; - - switch (len) { - case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; - case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; - case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; - case 1: *--ptr2 =(uc | firstByteMark[len]); - } - ptr2+=len; - break; - default: *ptr2++=*ptr; break; - } - ptr++; - } - } - *ptr2=0; - if (*ptr=='\"') ptr++; - item->valuestring=out; - item->type=cJSON_String; - return ptr; -} - -/* Render the cstring provided to an escaped version that can be printed. */ -static char *print_string_ptr(const char *str) -{ - const char *ptr;char *ptr2,*out;int32_t len=0;unsigned char token; - - if (!str) return cJSON_strdup(""); - ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;} - - out=(char*)cJSON_mallocstr(len+3+1); - if (!out) return 0; - - ptr2=out;ptr=str; - *ptr2++='\"'; - while (*ptr) - { - if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++; - else - { - *ptr2++='\\'; - switch (token=*ptr++) - { - case '\\': *ptr2++='\\'; break; - case '\"': *ptr2++='\"'; break; - case '\b': *ptr2++='b'; break; - case '\f': *ptr2++='f'; break; - case '\n': *ptr2++='n'; break; - case '\r': *ptr2++='r'; break; - case '\t': *ptr2++='t'; break; - default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */ - } - } - } - *ptr2++='\"';*ptr2++=0; - return out; -} -/* Invote print_string_ptr (which is useful) on an item. */ -static char *print_string(cJSON *item) {return print_string_ptr(item->valuestring);} - -/* Predeclare these prototypes. */ -static const char *parse_value(cJSON *item,const char *value); -static char *print_value(cJSON *item,int32_t depth,int32_t fmt); -static const char *parse_array(cJSON *item,const char *value); -static char *print_array(cJSON *item,int32_t depth,int32_t fmt); -static const char *parse_object(cJSON *item,const char *value); -static char *print_object(cJSON *item,int32_t depth,int32_t fmt); - -/* Utility to jump whitespace and cr/lf */ -static const char *skip(const char *in) {while (in && *in && (unsigned char)*in<=32) in++; return in;} - -/* Parse an object - create a new root, and populate. */ -cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int32_t require_null_terminated) -{ - const char *end=0; - cJSON *c=cJSON_New_Item(); - ep=0; - if (!c) return 0; /* memory fail */ - - end=parse_value(c,skip(value)); - if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */ - - /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ - if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);ep=end;return 0;}} - if (return_parse_end) *return_parse_end=end; - return c; -} -/* Default options for cJSON_Parse */ -cJSON *cJSON_Parse(const char *value) -{ - return(cJSON_ParseWithOpts(value,0,0)); -} - -/* Render a cJSON item/entity/structure to text. */ -char *cJSON_Print(cJSON *item) -{ - return(print_value(item,0,1)); -} -char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0);} - -/* Parser core - when encountering text, process appropriately. */ -static const char *parse_value(cJSON *item,const char *value) -{ - if (!value) return 0; /* Fail on null. */ - if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; } - if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; } - if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; } - if (*value=='\"') { return parse_string(item,value); } - if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); } - if (*value=='[') { return parse_array(item,value); } - if (*value=='{') { return parse_object(item,value); } - - ep=value;return 0; /* failure. */ -} - -/* Render a value to text. */ -static char *print_value(cJSON *item,int32_t depth,int32_t fmt) -{ - char *out=0; - if (!item) return 0; - switch ((item->type)&255) - { - case cJSON_NULL: out=cJSON_strdup("null"); break; - case cJSON_False: out=cJSON_strdup("false");break; - case cJSON_True: out=cJSON_strdup("true"); break; - case cJSON_Number: out=print_number(item);break; - case cJSON_String: out=print_string(item);break; - case cJSON_Array: out=print_array(item,depth,fmt);break; - case cJSON_Object: out=print_object(item,depth,fmt);break; - } - return out; -} - -/* Build an array from input text. */ -static const char *parse_array(cJSON *item,const char *value) -{ - cJSON *child; - if (*value!='[') {ep=value;return 0;} /* not an array! */ - - item->type=cJSON_Array; - value=skip(value+1); - if (*value==']') return value+1; /* empty array. */ - - item->child=child=cJSON_New_Item(); - if (!item->child) return 0; /* memory fail */ - value=skip(parse_value(child,skip(value))); /* skip any spacing, get the value. */ - if (!value) return 0; - - while (*value==',') - { - cJSON *new_item; - if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ - child->next=new_item;new_item->prev=child;child=new_item; - value=skip(parse_value(child,skip(value+1))); - if (!value) return 0; /* memory fail */ - } - - if (*value==']') return value+1; /* end of array */ - ep=value;return 0; /* malformed. */ -} - -/* Render an array to text */ -static char *print_array(cJSON *item,int32_t depth,int32_t fmt) -{ - char **entries,*space_entries[512]; - char *out=0,*ptr,*ret;int32_t len=5; - cJSON *child=item->child; - int32_t numentries=0,i=0,fail=0; - - /* How many entries in the array? */ - while (child) numentries++,child=child->next; - /* Explicitly handle numentries==0 */ - if (!numentries) - { - out=(char*)cJSON_mallocstr(3+1); - if (out) strcpy(out,"[]"); - return out; - } - /* Allocate an array to hold the values for each */ - entries=cJSON_mallocptrs(1+numentries,space_entries,sizeof(space_entries)/sizeof(*space_entries)); - if (!entries) return 0; - memset(entries,0,numentries*sizeof(char*)); - /* Retrieve all the results: */ - child=item->child; - while (child && !fail) - { - ret=print_value(child,depth+1,fmt); - entries[i++]=ret; - if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1; - child=child->next; - } - - /* If we didn't fail, try to malloc the output string */ - if (!fail) out=(char*)cJSON_mallocstr(len+1); - /* If that fails, we fail. */ - if (!out) fail=1; - - /* Handle failure. */ - if (fail) - { - for (i=0;itype=cJSON_Object; - value=skip(value+1); - if (*value=='}') return value+1; /* empty array. */ - - item->child=child=cJSON_New_Item(); - if (!item->child) return 0; - value=skip(parse_string(child,skip(value))); - if (!value) return 0; - child->string=child->valuestring;child->valuestring=0; - if (*value!=':') {ep=value;return 0;} /* fail! */ - value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ - if (!value) return 0; - - while (*value==',') - { - cJSON *new_item; - if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ - child->next=new_item;new_item->prev=child;child=new_item; - value=skip(parse_string(child,skip(value+1))); - if (!value) return 0; - child->string=child->valuestring;child->valuestring=0; - if (*value!=':') {ep=value;return 0;} /* fail! */ - value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ - if (!value) return 0; - } - - if (*value=='}') return value+1; /* end of array */ - ep=value;return 0; /* malformed. */ -} - -/* Render an object to text. */ -static char *print_object(cJSON *item,int32_t depth,int32_t fmt) -{ - char **entries=0,**names=0,*space_entries[512],*space_names[512]; - char *out=0,*ptr,*ret,*str;int32_t len=7,i=0,j; - cJSON *child=item->child,*firstchild; - int32_t numentries=0,fail=0; - // Count the number of entries - firstchild = child; - while ( child ) - { - numentries++; - child = child->next; - if ( child == firstchild ) - { - printf("cJSON infinite loop detected\n"); - break; - } - } - /* Explicitly handle empty object case */ - if (!numentries) - { - out=(char*)cJSON_mallocstr(fmt?depth+4+1:3+1); - if (!out) return 0; - ptr=out;*ptr++='{'; - if (fmt) {*ptr++='\n';for (i=0;ichild;depth++;if (fmt) len+=depth; - while ( child ) - { - names[i]=str=print_string_ptr(child->string); - entries[i++]=ret=print_value(child,depth,fmt); - if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1; - child=child->next; - if ( child == firstchild ) - break; - } - - /* Try to allocate the output string */ - if (!fail) out=(char*)cJSON_mallocstr(len+1); - if (!out) fail=1; - - /* Handle failure */ - if (fail) - { - for (i=0;ichild;int32_t i=0;while(c)i++,c=c->next;return i;} -cJSON *cJSON_GetArrayItem(cJSON *array,int32_t item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;} -cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) { if ( object == 0 ) return(0); cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;} - -/* Utility for array list handling. */ -static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;} -/* Utility for handling references. */ -static cJSON *create_reference(cJSON *item) {cJSON *ref=cJSON_New_Item();if (!ref) return 0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;return ref;} - -/* Add item to array/object. */ -void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}} -void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);} -void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));} -void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item) {cJSON_AddItemToObject(object,string,create_reference(item));} - -cJSON *cJSON_DetachItemFromArray(cJSON *array,int32_t which) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0; - if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;} -void cJSON_DeleteItemFromArray(cJSON *array,int32_t which) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));} -cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string) {int32_t i=0;cJSON *c=object->child;while (c && cJSON_strcasecmp(c->string,string)) i++,c=c->next;if (c) return cJSON_DetachItemFromArray(object,i);return 0;} -void cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));} - -/* Replace array/object items with new ones. */ -void cJSON_ReplaceItemInArray(cJSON *array,int32_t which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return; - newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem; - if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);} -void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem){int32_t i=0;cJSON *c=object->child;while(c && cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}} - -/* Create basic types: */ -cJSON *cJSON_CreateNull(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;} -cJSON *cJSON_CreateTrue(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;} -cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;} -cJSON *cJSON_CreateBool(int32_t b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;} -cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int64_t)num;}return item;} -cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);}return item;} - -/* Create Arrays: */ -cJSON *cJSON_CreateIntArray(int64_t *numbers,int32_t count) {int32_t i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} -cJSON *cJSON_CreateFloatArray(float *numbers,int32_t count) {int32_t i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} -cJSON *cJSON_CreateDoubleArray(double *numbers,int32_t count) {int32_t i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} -cJSON *cJSON_CreateStringArray(char **strings,int32_t count) {int32_t i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} - -/* Duplication */ -cJSON *cJSON_Duplicate(cJSON *item,int32_t recurse) -{ - cJSON *newitem,*cptr,*nptr=0,*newchild; - /* Bail on bad ptr */ - if (!item) return 0; - /* Create new item */ - newitem=cJSON_New_Item(); - if (!newitem) return 0; - /* Copy over all vars */ - newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble; - if (item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if (!newitem->valuestring) {cJSON_Delete(newitem);return 0;}} - if (item->string) {newitem->string=cJSON_strdup(item->string); if (!newitem->string) {cJSON_Delete(newitem);return 0;}} - /* If non-recursive, then we're done! */ - if (!recurse) return newitem; - /* Walk the ->next chain for the child. */ - cptr=item->child; - while (cptr) - { - newchild=cJSON_Duplicate(cptr,1); /* Duplicate (with recurse) each item in the ->next chain */ - if (!newchild) {cJSON_Delete(newitem);return 0;} - if (nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */ - else {newitem->child=newchild;nptr=newchild;} /* Set newitem->child and move to it */ - cptr=cptr->next; - } - return newitem; -} - -void cJSON_Minify(char *json) -{ - char *into=json; - while (*json) - { - if (*json==' ') json++; - else if (*json=='\t') json++; // Whitespace characters. - else if (*json=='\r') json++; - else if (*json=='\n') json++; - else if (*json=='/' && json[1]=='/') while (*json && *json!='\n') json++; // double-slash comments, to end of line. - else if (*json=='/' && json[1]=='*') {while (*json && !(*json=='*' && json[1]=='/')) json++;json+=2;} // multiline comments. - else if (*json=='\"'){*into++=*json++;while (*json && *json!='\"'){if (*json=='\\') *into++=*json++;*into++=*json++;}*into++=*json++;} // string literals, which are \" sensitive. - else *into++=*json++; // All other characters. - } - *into=0; // and null-terminate. -} - -// the following written by jl777 -/****************************************************************************** - * 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. * - * * - ******************************************************************************/ - -void copy_cJSON(struct destbuf *dest,cJSON *obj) -{ - char *str; - int i; - long offset; - dest->buf[0] = 0; - if ( obj != 0 ) - { - str = cJSON_Print(obj); - if ( str != 0 ) - { - offset = stripquotes(str); - //strcpy(dest,str+offset); - for (i=0; ibuf[i]= str[offset+i]) == 0 ) - break; - dest->buf[i] = 0; - free(str); - } - } -} - -void copy_cJSON2(char *dest,int32_t maxlen,cJSON *obj) -{ - struct destbuf tmp; - maxlen--; - dest[0] = 0; - if ( maxlen > sizeof(tmp.buf) ) - maxlen = sizeof(tmp.buf); - copy_cJSON(&tmp,obj); - if ( strlen(tmp.buf) < maxlen ) - strcpy(dest,tmp.buf); - else dest[0] = 0; -} - -int64_t _get_cJSON_int(cJSON *json) -{ - struct destbuf tmp; - if ( json != 0 ) - { - copy_cJSON(&tmp,json); - if ( tmp.buf[0] != 0 ) - return(calc_nxt64bits(tmp.buf)); - } - return(0); -} - -int64_t get_cJSON_int(cJSON *json,char *field) -{ - cJSON *numjson; - if ( json != 0 ) - { - numjson = cJSON_GetObjectItem(json,field); - if ( numjson != 0 ) - return(_get_cJSON_int(numjson)); - } - return(0); -} - -int64_t _conv_cJSON_float(cJSON *json) -{ - int64_t conv_floatstr(char *); - struct destbuf tmp; - if ( json != 0 ) - { - copy_cJSON(&tmp,json); - return(conv_floatstr(tmp.buf)); - } - return(0); -} - -int64_t conv_cJSON_float(cJSON *json,char *field) -{ - if ( json != 0 ) - return(_conv_cJSON_float(cJSON_GetObjectItem(json,field))); - return(0); -} - -int32_t extract_cJSON_str(char *dest,int32_t max,cJSON *json,char *field) -{ - int32_t safecopy(char *dest,char *src,long len); - char *str; - cJSON *obj; - int32_t len; - long offset; - dest[0] = 0; - obj = cJSON_GetObjectItem(json,field); - if ( obj != 0 ) - { - str = cJSON_Print(obj); - offset = stripquotes(str); - len = safecopy(dest,str+offset,max); - free(str); - return(len); - } - return(0); -} - -cJSON *gen_list_json(char **list) -{ - cJSON *array,*item; - array = cJSON_CreateArray(); - while ( list != 0 && *list != 0 && *list[0] != 0 ) - { - item = cJSON_CreateString(*list++); - cJSON_AddItemToArray(array,item); - } - return(array); -} - -uint64_t get_API_nxt64bits(cJSON *obj) -{ - uint64_t nxt64bits = 0; - struct destbuf tmp; - if ( obj != 0 ) - { - if ( is_cJSON_Number(obj) != 0 ) - return((uint64_t)obj->valuedouble); - copy_cJSON(&tmp,obj); - nxt64bits = calc_nxt64bits(tmp.buf); - } - return(nxt64bits); -} -uint64_t j64bits(cJSON *json,char *field) { if ( field == 0 ) return(get_API_nxt64bits(json)); return(get_API_nxt64bits(cJSON_GetObjectItem(json,field))); } -uint64_t j64bitsi(cJSON *json,int32_t i) { return(get_API_nxt64bits(cJSON_GetArrayItem(json,i))); } - -uint64_t get_satoshi_obj(cJSON *json,char *field) -{ - int32_t i,n; - uint64_t prev,satoshis,mult = 1; - struct destbuf numstr,checkstr; - cJSON *numjson; - numjson = cJSON_GetObjectItem(json,field); - copy_cJSON(&numstr,numjson); - satoshis = prev = 0; mult = 1; n = (int32_t)strlen(numstr.buf); - for (i=n-1; i>=0; i--,mult*=10) - { - satoshis += (mult * (numstr.buf[i] - '0')); - if ( satoshis < prev ) - printf("get_satoshi_obj numstr.(%s) i.%d prev.%llu vs satoshis.%llu\n",numstr.buf,i,(unsigned long long)prev,(unsigned long long)satoshis); - prev = satoshis; - } - sprintf(checkstr.buf,"%llu",(long long)satoshis); - if ( strcmp(checkstr.buf,numstr.buf) != 0 ) - { - printf("SATOSHI GREMLIN?? numstr.(%s) -> %.8f -> (%s)\n",numstr.buf,dstr(satoshis),checkstr.buf); - } - return(satoshis); -} - -void add_satoshis_json(cJSON *json,char *field,uint64_t satoshis) -{ - cJSON *obj; - char numstr[64]; - sprintf(numstr,"%lld",(long long)satoshis); - obj = cJSON_CreateString(numstr); - cJSON_AddItemToObject(json,field,obj); - if ( satoshis != get_satoshi_obj(json,field) ) - printf("error adding satoshi obj %ld -> %ld\n",(unsigned long)satoshis,(unsigned long)get_satoshi_obj(json,field)); -} - -char *cJSON_str(cJSON *json) -{ - if ( json != 0 && is_cJSON_String(json) != 0 ) - return(json->valuestring); - return(0); -} - -void jadd(cJSON *json,char *field,cJSON *item) { if ( json != 0 )cJSON_AddItemToObject(json,field,item); } -void jaddstr(cJSON *json,char *field,char *str) { if ( json != 0 && str != 0 ) cJSON_AddItemToObject(json,field,cJSON_CreateString(str)); } -void jaddnum(cJSON *json,char *field,double num) { if ( json != 0 )cJSON_AddItemToObject(json,field,cJSON_CreateNumber(num)); } -void jadd64bits(cJSON *json,char *field,uint64_t nxt64bits) { char numstr[64]; sprintf(numstr,"%llu",(long long)nxt64bits), jaddstr(json,field,numstr); } -void jaddi(cJSON *json,cJSON *item) { if ( json != 0 ) cJSON_AddItemToArray(json,item); } -void jaddistr(cJSON *json,char *str) { if ( json != 0 ) cJSON_AddItemToArray(json,cJSON_CreateString(str)); } -void jaddinum(cJSON *json,double num) { if ( json != 0 ) cJSON_AddItemToArray(json,cJSON_CreateNumber(num)); } -void jaddi64bits(cJSON *json,uint64_t nxt64bits) { char numstr[64]; sprintf(numstr,"%llu",(long long)nxt64bits), jaddistr(json,numstr); } -char *jstr(cJSON *json,char *field) { if ( json == 0 ) return(0); if ( field == 0 ) return(cJSON_str(json)); return(cJSON_str(cJSON_GetObjectItem(json,field))); } - -char *jstri(cJSON *json,int32_t i) { return(cJSON_str(cJSON_GetArrayItem(json,i))); } -char *jprint(cJSON *json,int32_t freeflag) -{ - char *str; - /*static portable_mutex_t mutex; static int32_t initflag; - if ( initflag == 0 ) - { - portable_mutex_init(&mutex); - initflag = 1; - }*/ - if ( json == 0 ) - return(clonestr((char *)"{}")); - //portable_mutex_lock(&mutex); - //usleep(5000); - str = cJSON_Print(json), _stripwhite(str,' '); - if ( freeflag != 0 ) - free_json(json); - //portable_mutex_unlock(&mutex); - return(str); -} - -bits256 get_API_bits256(cJSON *obj) -{ - bits256 hash; char *str; - memset(hash.bytes,0,sizeof(hash)); - if ( obj != 0 ) - { - if ( is_cJSON_String(obj) != 0 && (str= obj->valuestring) != 0 && strlen(str) == 64 ) - decode_hex(hash.bytes,sizeof(hash),str); - } - return(hash); -} -bits256 jbits256(cJSON *json,char *field) { if ( field == 0 ) return(get_API_bits256(json)); return(get_API_bits256(json != 0 ? cJSON_GetObjectItem(json,field) : 0)); } -bits256 jbits256i(cJSON *json,int32_t i) { return(get_API_bits256(cJSON_GetArrayItem(json,i))); } -void jaddbits256(cJSON *json,char *field,bits256 hash) { char str[65]; bits256_str(str,hash), jaddstr(json,field,str); } -void jaddibits256(cJSON *json,bits256 hash) { char str[65]; bits256_str(str,hash), jaddistr(json,str); } - -char *get_cJSON_fieldname(cJSON *obj) -{ - if ( obj != 0 ) - { - if ( obj->string != 0 ) - return(obj->string); - if ( obj->child != 0 && obj->child->string != 0 ) - return(obj->child->string); - } - return((char *)""); -} - -int32_t jnum(cJSON *obj,char *field) -{ - char *str; int32_t polarity = 1; - if ( field != 0 ) - obj = jobj(obj,field); - if ( obj != 0 ) - { - if ( is_cJSON_Number(obj) != 0 ) - return(obj->valuedouble); - else if ( is_cJSON_String(obj) != 0 && (str= jstr(obj,0)) != 0 ) - { - if ( str[0] == '-' ) - polarity = -1, str++; - return(polarity * (int32_t)calc_nxt64bits(str)); - } - } - return(0); -} - -void ensure_jsonitem(cJSON *json,char *field,char *value) -{ - cJSON *obj; - if ( json != 0 ) - { - obj = cJSON_GetObjectItem(json,field); - if ( obj == 0 ) - cJSON_AddItemToObject(json,field,cJSON_CreateString(value)); - else cJSON_ReplaceItemInObject(json,field,cJSON_CreateString(value)); - } -} - -int32_t in_jsonarray(cJSON *array,char *value) -{ - int32_t i,n; - struct destbuf remote; - if ( array != 0 && is_cJSON_Array(array) != 0 ) - { - n = cJSON_GetArraySize(array); - for (i=0; i= range ) - x = (range - 1); - return((int32_t)x); -} - -int32_t get_API_int(cJSON *obj,int32_t val) -{ - struct destbuf buf; - if ( obj != 0 ) - { - if ( is_cJSON_Number(obj) != 0 ) - return((int32_t)obj->valuedouble); - copy_cJSON(&buf,obj); - val = myatoi(buf.buf,0); - if ( val < 0 ) - val = 0; - } - return(val); -} -int32_t jint(cJSON *json,char *field) { if ( json == 0 ) return(0); if ( field == 0 ) return(get_API_int(json,0)); return(get_API_int(cJSON_GetObjectItem(json,field),0)); } -int32_t jinti(cJSON *json,int32_t i) { if ( json == 0 ) return(0); return(get_API_int(cJSON_GetArrayItem(json,i),0)); } - -uint32_t get_API_uint(cJSON *obj,uint32_t val) -{ - struct destbuf buf; - if ( obj != 0 ) - { - if ( is_cJSON_Number(obj) != 0 ) - return((uint32_t)obj->valuedouble); - copy_cJSON(&buf,obj); - val = myatoi(buf.buf,0); - } - return(val); -} -uint32_t juint(cJSON *json,char *field) { if ( json == 0 ) return(0); if ( field == 0 ) return(get_API_uint(json,0)); return(get_API_uint(cJSON_GetObjectItem(json,field),0)); } -uint32_t juinti(cJSON *json,int32_t i) { if ( json == 0 ) return(0); return(get_API_uint(cJSON_GetArrayItem(json,i),0)); } - -double get_API_float(cJSON *obj) -{ - double val = 0.; - struct destbuf buf; - if ( obj != 0 ) - { - if ( is_cJSON_Number(obj) != 0 ) - return(obj->valuedouble); - copy_cJSON(&buf,obj); - val = atof(buf.buf); - } - return(val); -} - -double jdouble(cJSON *json,char *field) -{ - if ( json != 0 ) - { - if ( field == 0 ) - return(get_API_float(json)); - else return(get_API_float(cJSON_GetObjectItem(json,field))); - } else return(0.); -} - -double jdoublei(cJSON *json,int32_t i) -{ - if ( json != 0 ) - return(get_API_float(cJSON_GetArrayItem(json,i))); - else return(0.); -} - -cJSON *jobj(cJSON *json,char *field) { if ( json != 0 ) return(cJSON_GetObjectItem(json,field)); return(0); } - -void jdelete(cJSON *json,char *field) -{ - if ( jobj(json,field) != 0 ) - cJSON_DeleteItemFromObject(json,field); -} - -cJSON *jduplicate(cJSON *json) { return(cJSON_Duplicate(json,1)); } - -cJSON *jitem(cJSON *array,int32_t i) { if ( array != 0 && is_cJSON_Array(array) != 0 && cJSON_GetArraySize(array) > i ) return(cJSON_GetArrayItem(array,i)); return(0); } -cJSON *jarray(int32_t *nump,cJSON *json,char *field) -{ - cJSON *array; - if ( json != 0 ) - { - if ( field == 0 ) - array = json; - else array = cJSON_GetObjectItem(json,field); - if ( array != 0 && is_cJSON_Array(array) != 0 && (*nump= cJSON_GetArraySize(array)) > 0 ) - return(array); - } - *nump = 0; - return(0); -} - -int32_t expand_nxt64bits(char *NXTaddr,uint64_t nxt64bits) -{ - int32_t i,n; - uint64_t modval; - char rev[64]; - for (i=0; nxt64bits!=0; i++) - { - modval = nxt64bits % 10; - rev[i] = (char)(modval + '0'); - nxt64bits /= 10; - } - n = i; - for (i=0; i= 22 ) - { - printf("calc_nxt64bits: illegal NXTaddr.(%s) too long\n",NXTaddr); - return(0); - } - else if ( strcmp(NXTaddr,"0") == 0 || strcmp(NXTaddr,"false") == 0 ) - { - // printf("zero address?\n"); getchar(); - return(0); - } - if ( NXTaddr[0] == '-' ) - polarity = -1, NXTaddr++, n--; - mult = 1; - lastval = 0; - for (i=n-1; i>=0; i--,mult*=10) - { - c = NXTaddr[i]; - if ( c < '0' || c > '9' ) - { - //printf("calc_nxt64bits: illegal char.(%c %d) in (%s).%d\n",c,c,NXTaddr,(int32_t)i); -#ifdef __APPLE__ - //while ( 1 ) - { - //sleep(60); - //printf("calc_nxt64bits: illegal char.(%c %d) in (%s).%d\n",c,c,NXTaddr,(int32_t)i); - } -#endif - return(0); - } - nxt64bits += mult * (c - '0'); - if ( nxt64bits < lastval ) - printf("calc_nxt64bits: warning: 64bit overflow %llx < %llx\n",(long long)nxt64bits,(long long)lastval); - lastval = nxt64bits; - } - while ( *NXTaddr == '0' && *NXTaddr != 0 ) - NXTaddr++; - if ( cmp_nxt64bits(NXTaddr,nxt64bits) != 0 ) - printf("error calculating nxt64bits: %s -> %llx -> %s\n",NXTaddr,(long long)nxt64bits,nxt64str(nxt64bits)); - if ( polarity < 0 ) - return(-(int64_t)nxt64bits); - return(nxt64bits); -} - -cJSON *addrs_jsonarray(uint64_t *addrs,int32_t num) -{ - int32_t j; cJSON *array; - array = cJSON_CreateArray(); - for (j=0; jtype = cJSON_Array; -//#ifdef CJSON_GARBAGECOLLECTION -// cJSON_register(item); -//#endif - return(item); -} - -cJSON *cJSON_CreateObject(void) -{ - cJSON *item = cJSON_New_Item(); - if ( item ) - item->type = cJSON_Object; -//#ifdef CJSON_GARBAGECOLLECTION -// cJSON_register(item); -//#endif - return item; -} - -void free_json(cJSON *item) -{ -//#ifdef CJSON_GARBAGECOLLECTION -// cJSON_unregister(item); -//#endif - if ( item != 0 ) - cJSON_Delete(item); -} diff --git a/src/cc/dapps/dappinc.h b/src/cc/dapps/dappinc.h deleted file mode 100644 index e9afd7fdc..000000000 --- a/src/cc/dapps/dappinc.h +++ /dev/null @@ -1,1597 +0,0 @@ -// Copyright (c) 2016-2024 The Hush developers -// Distributed under the GPLv3 software license, see the accompanying -// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html -/****************************************************************************** - * Copyright © 2014-2020 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 -#include -#include "cJSON.c" - -bits256 zeroid; - -int32_t unstringbits(char *buf,uint64_t bits) -{ - int32_t i; - for (i=0; i<8; i++,bits>>=8) - if ( (buf[i]= (char)(bits & 0xff)) == 0 ) - break; - buf[i] = 0; - return(i); -} - -uint64_t stringbits(char *str) -{ - uint64_t bits = 0; - if ( str == 0 ) - return(0); - int32_t i,n = (int32_t)strlen(str); - if ( n > 8 ) - n = 8; - for (i=n-1; i>=0; i--) - bits = (bits << 8) | (str[i] & 0xff); - //printf("(%s) -> %llx %llu\n",str,(long long)bits,(long long)bits); - return(bits); -} - -char hexbyte(int32_t c) -{ - c &= 0xf; - if ( c < 10 ) - return('0'+c); - else if ( c < 16 ) - return('a'+c-10); - else return(0); -} - -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(unsigned char *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 ( 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); -} - -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); -} - -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; i0; i--) - str[i] = str[i-1]; - str[0] = '/'; - str[n+1] = 0; - }*/ -#endif - return(str); -#endif -} - -void *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(portable_path(fname),"rb")) != 0 ) - { - fseek(fp,0,SEEK_END); - filesize = ftell(fp); - if ( filesize == 0 ) - { - fclose(fp); - *lenp = 0; - //printf("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); -} - -void *filestr(long *allocsizep,char *_fname) -{ - long filesize = 0; char *fname,*buf = 0; void *retptr; - *allocsizep = 0; - fname = malloc(strlen(_fname)+1); - strcpy(fname,_fname); - retptr = loadfile(fname,(uint8_t **)&buf,&filesize,allocsizep); - free(fname); - return(retptr); -} - -char *send_curl(char *url,char *fname) -{ - long fsize; char curlstr[1024]; - sprintf(curlstr,"curl --url \"%s\" > %s",url,fname); - system(curlstr); - return(filestr(&fsize,fname)); -} - -cJSON *get_urljson(char *url,char *fname) -{ - char *jsonstr; cJSON *json = 0; - if ( (jsonstr= send_curl(url,fname)) != 0 ) - { - //printf("(%s) -> (%s)\n",url,jsonstr); - json = cJSON_Parse(jsonstr); - free(jsonstr); - } - return(json); -} - -////////////////////////////////////////////// -// start of dapp -////////////////////////////////////////////// -int md_unlink(char *file) -{ -#ifdef _WIN32 - _chmod(file, 0600); - return( _unlink(file) ); -#else - return(unlink(file)); -#endif -} - -char *REFCOIN_CLI,DPOW_pubkeystr[67],DPOW_secpkeystr[67],DPOW_handle[67],DPOW_recvaddr[64],DPOW_recvZaddr[128]; - -cJSON *get_hushcli(char *refcoin,char **retstrp,char *acname,char *method,char *arg0,char *arg1,char *arg2,char *arg3,char *arg4,char *arg5,char *arg6) -{ - long fsize; cJSON *retjson = 0; char cmdstr[32768],*jsonstr,fname[32768]; - sprintf(fname,"/tmp/notarizer_%s_%d",method,(rand() >> 17) % 10000); - if ( acname[0] != 0 ) { - if ( refcoin[0] != 0 && strcmp(refcoin,"HUSH3") != 0 && strcmp(refcoin,acname) != 0 ) - printf("unexpected: refcoin.(%s) acname.(%s)\n",refcoin,acname); - sprintf(cmdstr,"hush-arrakis-chain -ac_name=%s %s %s %s %s %s %s %s %s > %s\n",acname,method,arg0,arg1,arg2,arg3,arg4,arg5,arg6,fname); - } - else if ( strcmp(refcoin,"HUSH3") == 0 ) - sprintf(cmdstr,"hush-cli %s %s %s %s %s %s %s %s > %s\n",method,arg0,arg1,arg2,arg3,arg4,arg5,arg6,fname); - else if ( REFCOIN_CLI != 0 && REFCOIN_CLI[0] != 0 ) - { - sprintf(cmdstr,"%s %s %s %s %s %s %s %s %s > %s\n",REFCOIN_CLI,method,arg0,arg1,arg2,arg3,arg4,arg5,arg6,fname); - //printf("ref.(%s) REFCOIN_CLI (%s)\n",refcoin,cmdstr); - } - //fprintf(stderr,"system(%s)\n",cmdstr); - 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 ) - *retstrp = jsonstr; - else free(jsonstr); - md_unlink(fname); - } //else fprintf(stderr,"system(%s) -> NULL\n",cmdstr); - return(retjson); -} - -cJSON *hushdex_cli(char *clistr,char **retstrp,char *method,char *arg0,char *arg1,char *arg2,char *arg3,char *arg4,char *arg5,char *arg6) -{ - long fsize; cJSON *retjson = 0; char cmdstr[32768],*jsonstr,fname[32768]; - //TODO: fix this shitty insecure jl777 fucktwattery - sprintf(fname,"/tmp/hushdex_%s_%d",method,(rand() >> 17) % 10000); - sprintf(cmdstr,"%s %s %s %s %s %s %s %s %s > %s\n",clistr,method,arg0,arg1,arg2,arg3,arg4,arg5,arg6,fname); - //fprintf(stderr,"system(%s)\n",cmdstr); - 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 ) - *retstrp = jsonstr; - else free(jsonstr); - md_unlink(fname); - } //else fprintf(stderr,"system(%s) -> NULL\n",cmdstr); - return(retjson); -} - -bits256 hushbroadcast(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_hushcli(refcoin,&retstr,acname,"sendrawtransaction",hexstr,"","","","","","")) != 0 ) - { - //fprintf(stderr,"broadcast.(%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,"broadcast %s txid.(%s)\n",strlen(acname)>0?acname:refcoin,bits256_str(str,txid)); - free(retstr); - } - } - return(txid); -} - -bits256 sendtoaddress(char *refcoin,char *acname,char *destaddr,int64_t satoshis,char *oprethexstr) -{ - 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_hushcli(refcoin,&retstr,acname,"sendtoaddress",destaddr,numstr,"false","","",oprethexstr,"")) != 0 ) - { - fprintf(stderr,"unexpected sendrawtransaction 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); -} - -bits256 tokentransfer(char *refcoin,char *acname,char *tokenid,char *destpub,int64_t units) -{ - char numstr[32],*retstr,str[65]; cJSON *retjson; bits256 txid; - memset(txid.bytes,0,sizeof(txid)); - sprintf(numstr,"%llu",(long long)units); - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"tokentransfer",tokenid,destpub,numstr,"","","","")) != 0 ) - { - txid = hushbroadcast(refcoin,acname,retjson); - fprintf(stderr,"tokentransfer returned (%s)\n",jprint(retjson,0)); - free_json(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"tokentransfer.(%s) error.(%s)\n",acname,retstr); - free(retstr); - } - return(txid); -} - -char *get_tokenaddress(char *refcoin,char *acname,char *tokenaddr) -{ - char *retstr,*str; cJSON *retjson; - tokenaddr[0] = 0; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"tokenaddress","","","","","","","")) != 0 ) - { - if ( (str= jstr(retjson,"myCCAddress(Tokens)")) != 0 ) - { - strcpy(tokenaddr,str); - fprintf(stderr,"tokenaddress returned (%s)\n",tokenaddr); - free_json(retjson); - return(tokenaddr); - } - free_json(retjson); - } - else if ( retstr != 0 ) - { - //fprintf(stderr,"tokentransfer.(%s) error.(%s)\n",acname,retstr); - free(retstr); - } - return(0); -} - -int64_t get_tokenbalance(char *refcoin,char *acname,char *tokenid) -{ - cJSON *retjson; char *retstr,cmpstr[64]; int64_t amount=0; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"tokenbalance",tokenid,"","","","","","")) != 0 ) - { - amount = j64bits(retjson,"balance"); - fprintf(stderr,"tokenbalance %llu\n",(long long)amount); - free_json(retjson); - } - else if ( retstr != 0 ) - { - //printf("retstr %s -> %.8f\n",retstr,dstr(amount)); - free(retstr); - } - return (amount); -} - -cJSON *get_decodescript(char *refcoin,char *acname,char *script) -{ - cJSON *retjson; char *retstr; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"decodescript",script,"","","","","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"get_decodescript.(%s) error.(%s)\n",acname,retstr); - free(retstr); - } - return(0); -} - -char *get_createmultisig2(char *refcoin,char *acname,char *msigaddr,char *redeemscript,char *pubkeyA,char *pubkeyB) -{ - //char para 2 '["02c3af47b51a506b08b4ededb156cb4c3f9db9e0ac7ad27b8623c08a056fdcc220", "038e61fbface549a850862f12ed99b7cbeef5c2bd2d8f1daddb34809416f0259e1"]' - cJSON *retjson; char *retstr,*str,params[256]; int32_t height=0; - msigaddr[0] = 0; - redeemscript[0] = 0; - sprintf(params,"'[\"%s\", \"%s\"]'",pubkeyA,pubkeyB); - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"createmultisig","2",params,"","","","","")) != 0 ) - { - if ( (str= jstr(retjson,"address")) != 0 ) - strcpy(msigaddr,str); - if ( (str= jstr(retjson,"redeemScript")) != 0 ) - strcpy(redeemscript,str); - free_json(retjson); - if ( msigaddr[0] != 0 && redeemscript[0] != 0 ) - return(msigaddr); - else return(0); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"%s get_createmultisig2.(%s) error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -int32_t get_coinheight(char *refcoin,char *acname,bits256 *blockhashp) -{ - cJSON *retjson; char *retstr; int32_t height=0; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getblockchaininfo","","","","","","","")) != 0 ) - { - height = jint(retjson,"blocks"); - *blockhashp = jbits256(retjson,"bestblockhash"); - free_json(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"%s get_coinheight.(%s) error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(height); -} - -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_hushcli(refcoin,&retstr,acname,"getblockhash",heightstr,"","","","","","")) != 0 ) - { - fprintf(stderr,"unexpected blockhash json.(%s)\n",jprint(retjson,0)); - free_json(retjson); - } - else if ( retstr != 0 ) - { - if ( strlen(retstr) >= 64 ) - { - retstr[64] = 0; - decode_hex(hash.bytes,32,retstr); - } - free(retstr); - } - return(hash); -} - -bits256 get_coinmerkleroot(char *refcoin,char *acname,bits256 blockhash,uint32_t *blocktimep) -{ - cJSON *retjson; char *retstr,str[65]; bits256 merkleroot; - memset(merkleroot.bytes,0,sizeof(merkleroot)); - *blocktimep = 0; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getblockheader",bits256_str(str,blockhash),"","","","","","")) != 0 ) - { - merkleroot = jbits256(retjson,"merkleroot"); - *blocktimep = juint(retjson,"time"); - //fprintf(stderr,"got merkleroot.(%s)\n",bits256_str(str,merkleroot)); - free_json(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"%s %s get_coinmerkleroot error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(merkleroot); -} - -uint32_t get_heighttime(char *refcoin,char *acname,int32_t height) -{ - bits256 blockhash; uint32_t blocktime; - blockhash = get_coinblockhash(refcoin,acname,height); - get_coinmerkleroot(refcoin,acname,blockhash,&blocktime); - return(blocktime); -} - -int32_t get_coinheader(char *refcoin,char *acname,bits256 *blockhashp,bits256 *merklerootp,int32_t prevheight) -{ - int32_t height = 0; char str[65]; bits256 bhash; uint32_t blocktime; - if ( prevheight == 0 ) - height = get_coinheight(refcoin,acname,&bhash) - 20; - else height = prevheight + 1; - if ( height > 0 ) - { - *blockhashp = get_coinblockhash(refcoin,acname,height); - if ( bits256_nonz(*blockhashp) != 0 ) - { - *merklerootp = get_coinmerkleroot(refcoin,acname,*blockhashp,&blocktime); - if ( bits256_nonz(*merklerootp) != 0 ) - return(height); - } - } - memset(blockhashp,0,sizeof(*blockhashp)); - memset(merklerootp,0,sizeof(*merklerootp)); - return(0); -} - -cJSON *get_rawmempool(char *refcoin,char *acname) -{ - cJSON *retjson; char *retstr; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getrawmempool","","","","","","","")) != 0 ) - { - //printf("mempool.(%s)\n",jprint(retjson,0)); - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"get_rawmempool.(%s) error.(%s)\n",acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *get_addressutxos(char *refcoin,char *acname,char *coinaddr) -{ - cJSON *retjson; char *retstr,jsonbuf[256]; - if ( refcoin[0] != 0 && strcmp(refcoin,"HUSH3") != 0 ) - printf("warning: assumes %s has addressindex enabled\n",refcoin); - sprintf(jsonbuf,"{\\\"addresses\\\":[\\\"%s\\\"]}",coinaddr); - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getaddressutxos",jsonbuf,"","","","","","")) != 0 ) - { - //printf("addressutxos.(%s)\n",jprint(retjson,0)); - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"get_addressutxos.(%s) error.(%s)\n",acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *get_rawtransaction(char *refcoin,char *acname,bits256 txid) -{ - cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getrawtransaction",bits256_str(str,txid),"1","","","","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"get_rawtransaction.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *get_z_viewtransaction(char *refcoin,char *acname,bits256 txid) -{ - cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_viewtransaction",bits256_str(str,txid),"","","","","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"get_z_viewtransaction.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *get_listunspent(char *refcoin,char *acname) -{ - cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"listunspent","","","","","","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"get_listunspent.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *get_getinfo(char *refcoin,char *acname) -{ - cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getinfo","","","","","","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"get_getinfo.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *z_listunspent(char *refcoin,char *acname) -{ - cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_listunspent","","","","","","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"z_listunspent.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *z_listoperationids(char *refcoin,char *acname) -{ - cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_listoperationids","","","","","","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"z_listoperationids.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *z_getoperationstatus(char *refcoin,char *acname,char *opid) -{ - cJSON *retjson; char *retstr,str[65],params[512]; - sprintf(params,"'[\"%s\"]'",opid); - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_getoperationstatus",params,"","","","","","")) != 0 ) - { - //printf("got status (%s)\n",jprint(retjson,0)); - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"z_getoperationstatus.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *z_getoperationresult(char *refcoin,char *acname,char *opid) -{ - cJSON *retjson; char *retstr,str[65],params[512]; - sprintf(params,"'[\"%s\"]'",opid); - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_getoperationresult",params,"","","","","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"z_getoperationresult.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -int32_t validateaddress(char *refcoin,char *acname,char *depositaddr, char* compare) -{ - cJSON *retjson; char *retstr; int32_t res=0; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"validateaddress",depositaddr,"","","","","","")) != 0 ) - { - 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); - } - return (res); -} - -int32_t z_validateaddress(char *refcoin,char *acname,char *depositaddr, char *compare) -{ - cJSON *retjson; char *retstr; int32_t res=0; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_validateaddress",depositaddr,"","","","","","")) != 0 ) - { - if (is_cJSON_True(jobj(retjson,compare)) != 0 ) - res=1; - free_json(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"z_validateaddress.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return (res); -} - -int64_t get_getbalance(char *refcoin,char *acname) -{ - cJSON *retjson; char *retstr,cmpstr[64]; int64_t amount=0; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getbalance","","","","","","","")) != 0 ) - { - fprintf(stderr,"get_getbalance.(%s) %s returned json!\n",refcoin,acname); - free_json(retjson); - } - else if ( retstr != 0 ) - { - amount = atof(retstr) * SATOSHIDEN; - sprintf(cmpstr,"%.8f",dstr(amount)); - if ( strcmp(retstr,cmpstr) != 0 ) - amount++; - //printf("retstr %s -> %.8f\n",retstr,dstr(amount)); - free(retstr); - } - return (amount); -} - -int64_t z_getbalance(char *refcoin,char *acname,char *coinaddr) -{ - cJSON *retjson; char *retstr,cmpstr[64]; int64_t amount=0; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_getbalance",coinaddr,"","","","","","")) != 0 ) - { - fprintf(stderr,"z_getbalance.(%s) %s returned json!\n",refcoin,acname); - free_json(retjson); - } - else if ( retstr != 0 ) - { - amount = atof(retstr) * SATOSHIDEN; - sprintf(cmpstr,"%.8f",dstr(amount)); - if ( strcmp(retstr,cmpstr) != 0 ) - amount++; - //printf("retstr %s -> %.8f\n",retstr,dstr(amount)); - free(retstr); - } - 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_hushcli(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); - } - return(-1); -} - -int32_t getnewaddress(char *coinaddr,char *refcoin,char *acname) -{ - cJSON *retjson; char *retstr; int64_t amount=0; int32_t retval = -1; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getnewaddress","","","","","","","")) != 0 ) - { - fprintf(stderr,"getnewaddress.(%s) %s returned json!\n",refcoin,acname); - free_json(retjson); - } - else if ( retstr != 0 ) - { - strcpy(coinaddr,retstr); - free(retstr); - retval = 0; - } - return(retval); -} - -int32_t z_getnewaddress(char *coinaddr,char *refcoin,char *acname,char *typestr) -{ - cJSON *retjson; char *retstr; int64_t amount=0; int32_t retval = -1; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_getnewaddress",typestr,"","","","","","")) != 0 ) - { - fprintf(stderr,"z_getnewaddress.(%s) %s returned json!\n",refcoin,acname); - free_json(retjson); - } - else if ( retstr != 0 ) - { - strcpy(coinaddr,retstr); - free(retstr); - retval = 0; - } - return(retval); -} - -int64_t find_onetime_amount(char *coinstr,char *coinaddr) -{ - cJSON *array,*item; int32_t i,n; char *addr; int64_t amount = 0; - 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 0 ) - { - for (i=0; i %s\n",coinstr,acname,srcaddr,params); - if ( (retjson= get_hushcli(coinstr,&retstr,acname,"z_sendmany",addr,params,"","","","","")) != 0 ) - { - printf("unexpected json z_sendmany.(%s)\n",jprint(retjson,0)); - free_json(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"z_sendmany.(%s) -> opid.(%s)\n",coinstr,retstr); - strcpy(opidstr,retstr); - free(retstr); - retval = 0; - } - 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\\\"]"); - if ( (retjson= get_hushcli(coinstr,&retstr,acname,"z_mergetoaddress",addr,destaddr,"","","","","")) != 0 ) - { - 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; - if ( (array= get_rawmempool(coinstr,acname)) != 0 ) - { - if ( (n= cJSON_GetArraySize(array)) > 0 ) - return(0); - free_json(array); - return(1); - } - return(-1); -} - -cJSON *getinputarray(int64_t *totalp,cJSON *unspents,int64_t required) -{ - cJSON *vin,*item,*vins = cJSON_CreateArray(); int32_t i,n,v; int64_t satoshis; bits256 txid; - *totalp = 0; - if ( (n= cJSON_GetArraySize(unspents)) > 0 ) - { - for (i=0; i= required ) - break; - } - } - } - return(vins); -} - -int32_t tx_has_voutaddress(char *refcoin,char *acname,bits256 txid,char *coinaddr) -{ - cJSON *txobj,*vouts,*vout,*vins,*vin,*sobj,*addresses; char *addr,str[65]; int32_t i,j,n,numarray,retval = 0, hasvout=0; - if ( (txobj= get_rawtransaction(refcoin,acname,txid)) != 0 ) - { - if ( (vouts= jarray(&numarray,txobj,"vout")) != 0 ) - { - for (i=0; i 0 ) - { - for (i=0; i 0 ) - { - for (j=0; j 0 && strcmp(vinaddr,cmpaddr) == 0 ) - return(0); - printf("mismatched vinaddr.(%s) vs %s\n",vinaddr,cmpaddr); - } - } - return(-1); -} - -int32_t txid_in_vins(char *refcoin,bits256 txid,bits256 cmptxid) -{ - cJSON *txjson,*vins,*vin; int32_t numvins,v,vinvout; bits256 vintxid; char str[65]; - if ( (txjson= get_rawtransaction(refcoin,"",txid)) != 0 ) - { - if ( (vins= jarray(&numvins,txjson,"vin")) != 0 ) - { - for (v=0; v n.%d retval.%d\n",tagA,tagB,pubkeystr,n,retval); - } - free_json(retjson); - } - return(retval); -} - -int32_t dpow_hasmessage(char *payload,char *tagA,char *tagB,char *pubkeystr) -{ - cJSON *retjson,*item,*array; char *retstr,*pstr; int32_t i,n,retval = 0; - if ( (retjson= get_hushcli((char *)"",&retstr,DEXP2P_CHAIN,"DEX_list","0","0",tagA,tagB,pubkeystr,"","")) != 0 ) - { - if ( (array= jarray(&n,retjson,"matches")) != 0 ) - { - for (i=0; i 0 ) - { - ptrs = calloc(n,sizeof(*ptrs)); - for (i=0; ishorthash = juint(item,"id"); - ptrs[m]->jsonstr = ptr; - strcpy(ptrs[m]->senderpub,senderpub); - m++; - } - } - } - *nump = m; - } - free_json(retjson); - } - return(ptrs); -} diff --git a/src/cc/dapps/dappstd.c b/src/cc/dapps/dappstd.c deleted file mode 100644 index 3279e9927..000000000 --- a/src/cc/dapps/dappstd.c +++ /dev/null @@ -1,1114 +0,0 @@ -// Copyright (c) 2016-2024 The Hush developers -// Distributed under the GPLv3 software license, see the accompanying -// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html -/****************************************************************************** - * 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. * - * * - ******************************************************************************/ - -// requires CHAINNAME and GAMEMAIN() to be #defined - -#include -#include -#include -#include -#include -#include -#include - -extern struct games_state globalR; -void *gamesiterate(struct games_state *rs); - -char USERPASS[8192]; uint16_t GAMES_PORT; -char Gametxidstr[67]; -char *clonestr(char *str); - -#define MAXSTR 1024 -char whoami[MAXSTR]; - -#define SMALLVAL 0.000000000000001 -#define SATOSHIDEN ((uint64_t)100000000L) -#define dstr(x) ((double)(x) / SATOSHIDEN) -#define HUSH_SMART_CHAIN_MAXLEN 65 -char ASSETCHAINS_SYMBOL[HUSH_SMART_CHAIN_MAXLEN],IPADDRESS[100]; - -#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 - -#ifdef _WIN32 -#ifdef _MSC_VER -int gettimeofday(struct timeval * tp, struct timezone * tzp) -{ - // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's - static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL); - - SYSTEMTIME system_time; - FILETIME file_time; - uint64_t time; - - GetSystemTime(&system_time); - SystemTimeToFileTime(&system_time, &file_time); - time = ((uint64_t)file_time.dwLowDateTime); - time += ((uint64_t)file_time.dwHighDateTime) << 32; - - tp->tv_sec = (long)((time - EPOCH) / 10000000L); - tp->tv_usec = (long)(system_time.wMilliseconds * 1000); - return 0; -} -#endif // _MSC_VER -#endif - -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); -} - -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 *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; - if ( src != 0 && dest != 0 && src != dest ) - { - if ( dest != 0 ) - memset(dest,0,len); - for (i=0; i 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); -} - -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 - -#ifdef _WIN32 -#ifdef _MSC_VER -#define sleep(x) Sleep(1000*(x)) -#endif -#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); -} - -uint16_t _hush_userpass(char *username, char *password, FILE *fp) -{ - 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 ) - { - 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); - } - else if ( (str= strstr(line,(char *)"ipaddress")) != 0 ) - { - ipaddress = parse_conf_line(str,(char *)"ipaddress"); - strcpy(IPADDRESS,ipaddress); - } - } - if ( rpcuser != 0 && rpcpassword != 0 ) - { - strcpy(username,rpcuser); - strcpy(password,rpcpassword); - } - //printf("rpcuser.(%s) rpcpassword.(%s) %u ipaddress.%s\n",rpcuser,rpcpassword,port,ipaddress); - if ( rpcuser != 0 ) - free(rpcuser); - if ( rpcpassword != 0 ) - free(rpcpassword); - return(port); -} - -uint16_t hush_userpass(char *userpass,char *symbol) -{ - FILE *fp; uint16_t port = 0; char fname[512],username[512],password[512],confname[HUSH_SMART_CHAIN_MAXLEN]; - userpass[0] = 0; - sprintf(confname,"%s.conf",symbol); - //hush_statefname(fname,symbol,confname); - if ( (fp= fopen(confname,"rb")) != 0 ) - { - port = _hush_userpass(username,password,fp); - sprintf(userpass,"%s:%s",username,password); - if ( strcmp(symbol,ASSETCHAINS_SYMBOL) == 0 ) - strcpy(USERPASS,userpass); - fclose(fp); - } - return(port); -} - -#define is_cJSON_True(json) ((json) != 0 && ((json)->type & 0xff) == cJSON_True) - -char *hush_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://%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); - //retstr = curl_post(&cHandle,url,USERPASS,postdata,0,0,0,0); - } - return(retstr2); -} - -int32_t games_sendrawtransaction(char *rawtx) -{ - char *params,*retstr,*hexstr; cJSON *retjson,*resobj; int32_t retval = -1; - params = (char *)malloc(strlen(rawtx) + 16); - sprintf(params,"[\"%s\"]",rawtx); - if ( (retstr= hush_issuemethod(USERPASS,(char *)"sendrawtransaction",params,GAMES_PORT)) != 0 ) - { - if ( 0 ) // causes 4th level crash - { - static FILE *fp; - if ( fp == 0 ) - fp = fopen("games.sendlog","wb"); - if ( fp != 0 ) - { - fprintf(fp,"%s\n",retstr); - fflush(fp); - } - } - if ( (retjson= cJSON_Parse(retstr)) != 0 ) - { - if ( (resobj= jobj(retjson,(char *)"result")) != 0 ) - { - if ( (hexstr= jstr(resobj,0)) != 0 && is_hexstr(hexstr,64) == 64 ) - retval = 0; - } - free_json(retjson); - } - - /* log sendrawtx result in file */ - - /* - FILE *debug_file; - debug_file = fopen("tx_debug.log", "a"); - fprintf(debug_file, "%s\n", retstr); - fflush(debug_file); - fclose(debug_file); - */ - - free(retstr); - } - free(params); - return(retval); -} - -int32_t games_progress(struct games_state *rs,int32_t waitflag,uint64_t seed,gamesevent *keystrokes,int32_t num) -{ - char cmd[16384],hexstr[16384],params[32768],*retstr,*errstr,*rawtx; int32_t i,len,retflag = -1; cJSON *retjson,*resobj; - if ( rs->guiflag != 0 && Gametxidstr[0] != 0 ) - { - if ( rs->keystrokeshex != 0 ) - { - if ( games_sendrawtransaction(rs->keystrokeshex) == 0 ) - { - if ( waitflag == 0 ) - return(0); - else if ( 0 ) - { - while ( games_sendrawtransaction(rs->keystrokeshex) == 0 ) - { - //fprintf(stderr,"pre-rebroadcast\n"); - sleep(10); - } - } - } - free(rs->keystrokeshex), rs->keystrokeshex = 0; - } - memset(hexstr,0,sizeof(hexstr)); - for (i=0; ikeystrokeshex != 0 ) - free(rs->keystrokeshex); - if ( (errstr= jstr(resobj,(char *)"error")) == 0 ) - { - rs->keystrokeshex = (char *)malloc(strlen(rawtx)+1); - strcpy(rs->keystrokeshex,rawtx); - retflag = 1; - } else fprintf(stderr,"error sending keystrokes tx\n"), sleep(1); - //fprintf(stderr,"set keystrokestx <- %s\n",rs->keystrokeshex); - } - free_json(retjson); - } - free(retstr); - } - } - return(retflag); -} - -int32_t gamesfname(char *fname,uint64_t seed,int32_t counter) -{ - sprintf(fname,"%s.%llu.%d",GAMENAME,(long long)seed,counter); - return(0); -} - -int32_t flushkeystrokes_local(struct games_state *rs,int32_t waitflag) -{ -#ifdef STANDALONE - char fname[1024]; FILE *fp; int32_t i,retflag = -1; - rs->counter++; - gamesfname(fname,rs->origseed,rs->counter); - if ( (fp= fopen(fname,"wb")) != 0 ) - { - if ( fwrite(rs->buffered,sizeof(*rs->buffered),rs->num,fp) == rs->num ) - { - rs->num = 0; - retflag = 0; - fclose(fp); - gamesfname(fname,rs->origseed,rs->counter+1); - 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); -#else - return(0); -#endif -} - -#ifndef STANDALONE -// stubs for inside daemon - -int32_t games_progress(struct games_state *rs,int32_t waitflag,uint64_t seed,char *keystrokes,int32_t num) -{ - return(0); -} - -int32_t games_setplayerdata(struct games_state *rs,char *gametxidstr) -{ - return(-1); -} -#endif - -int32_t flushkeystrokes(struct games_state *rs,int32_t waitflag) -{ - if ( rs->num > 0 ) - { - if ( games_progress(rs,waitflag,rs->origseed,rs->buffered,rs->num) > 0 ) - { - flushkeystrokes_local(rs,waitflag); - memset(rs->buffered,0,sizeof(rs->buffered)); - } - } - return(0); -} - -void gamesbailout(struct games_state *rs) -{ - flushkeystrokes(rs,1); -} - -#ifdef _WIN32 -#ifdef _MSC_VER -#define sleep(x) Sleep(1000*(x)) -#endif -#endif - -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); -} - -gamesevent *games_keystrokesload(int32_t *numkeysp,uint64_t seed,int32_t counter) -{ - char fname[1024]; gamesevent *keystrokes = 0; FILE *fp; long fsize; int32_t i,num = 0; - *numkeysp = 0; - while ( 1 ) - { - gamesfname(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= (gamesevent *)realloc(keystrokes,sizeof(*keystrokes)*num+fsize)) == 0 ) - { - fprintf(stderr,"error reallocating keystrokes\n"); - fclose(fp); - return(0); - } - if ( fread(&keystrokes[num],1,fsize,fp) != fsize ) - { - fprintf(stderr,"error reading keystrokes from (%s)\n",fname); - fclose(fp); - free(keystrokes); - return(0); - } - fclose(fp); - num += (int32_t)(fsize / sizeof(gamesevent)); - //for (i=0; i 0 ) - { - sprintf(fname,"%s.%llu.player",GAMENAME,(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); - } - games_replay2(0,seed,keystrokes,num,player,sleeptime); - mvaddstr(LINES - 2, 0, (char *)"replay completed"); - endwin(); - games_exit(); - } - if ( keystrokes != 0 ) - free(keystrokes); - return(num); -} - -int32_t games_setplayerdata(struct games_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,*resultjson; - if ( rs->guiflag == 0 ) - return(-1); - if ( gametxidstr == 0 || *gametxidstr == 0 ) - return(retval); - if ( 0 ) - { - sprintf(fname,"%s.gameinfo",gametxidstr); - sprintf(cmd,"./hush-cli -ac_name=%s cclib gameinfo 17 \\\"[%%22%s%%22]\\\" > %s",ASSETCHAINS_SYMBOL,gametxidstr,fname); - if ( system(cmd) != 0 ) - fprintf(stderr,"error issuing (%s)\n",cmd); - else filestr = (char *)OS_fileptr(&allocsize,fname); - } - else - { - sprintf(params,"[\"gameinfo\",\"17\",\"[%%22%s%%22]\"]",gametxidstr); - filestr = hush_issuemethod(USERPASS,(char *)"cclib",params,GAMES_PORT); - } - if ( filestr != 0 ) - { - if ( (retjson= cJSON_Parse(filestr)) != 0 && (resultjson= jobj(retjson,(char *)"result")) != 0 ) - { - //fprintf(stderr,"gameinfo.(%s)\n",jprint(resultjson,0)); - if ( (array= jarray(&n,resultjson,(char *)"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); -} - -#ifdef _WIN32 -#ifdef _MSC_VER -__inline int msver(void) { - switch (_MSC_VER) { - case 1500: return 2008; - case 1600: return 2010; - case 1700: return 2012; - case 1800: return 2013; - case 1900: return 2015; - //case 1910: return 2017; - default: return (_MSC_VER / 100); - } -} - -static inline bool is_x64(void) { -#if defined(__x86_64__) || defined(_WIN64) || defined(__aarch64__) - return 1; -#elif defined(__amd64__) || defined(__amd64) || defined(_M_X64) || defined(_M_IA64) - return 1; -#else - return 0; -#endif -} - -#define BUILD_DATE __DATE__ " " __TIME__ -#endif // _WIN32 -#endif // _MSC_VER - -int main(int argc, char **argv) -{ - uint64_t seed; FILE *fp = 0; int32_t i,j,c; char userpass[8192]; -#ifdef _WIN32 -#ifdef _MSC_VER - printf("*** games for Windows [ Build %s ] ***\n", BUILD_DATE); - const char* arch = is_x64() ? "64-bits" : "32-bits"; - printf(" Built with VC++ %d (%ld) %s\n\n", msver(), _MSC_FULL_VER, arch); -#endif -#endif - - for (i=j=0; argv[0][i]!=0&&jbase : &mp->rel; - if ( coin[0] == 0 ) - return(coin); - if ( (external= jarray(&n,SUBATOMIC_json,"externalcoins")) != 0 && n > 0 ) - { - for (i=0; icli) ) - { - ptr->isexternal = 1; - strcpy(ptr->cli,clistr); - //fprintf(stderr,"found external coin %s %s\n",coin,clistr); - } - } - } - if ( coin[0] == '#' ) - { - strcpy(ptr->coinstr,coin); - strcpy(ptr->acname,""); - ptr->isfile = 1; - return(coin); - } - else if ( coin[0] != 'z' ) - { - for (i=1; coin[i]!=0; i++) - if ( coin[i] == '.' ) - { - dpow_tokenregister(ptr->tokenid,0,coin,0); - if ( ptr->tokenid[0] != 0 ) - { - strcpy(tmpstr,coin); - tmpstr[i] = 0; - //fprintf(stderr,"found a tokenmap %s -> %s %s\n",coin,tmpstr,ptr->tokenid); - ptr->istoken = 1; - strcpy(ptr->acname,coin); - strcpy(ptr->coinstr,""); - return(tmpstr); - } - } - if ( ptr->isexternal == 0 ) - { - strcpy(ptr->acname,coin); - strcpy(ptr->coinstr,""); - strcpy(ptr->acname,""); - } - else - { - strcpy(ptr->coinstr,coin); - strcpy(ptr->acname,""); - } - return(coin); - } - else - { - for (i=1; coin[i]!=0; i++) - if ( isupper(coin[i]) == 0 ) - return(coin); - ptr->iszaddr = 1; - return(coin+1); - } -} - -int32_t hushdex_zonly(struct coininfo *coin) -{ - if ( strcmp(coin->coin,"HUSH3") == 0 ) - return(1); - - if ( strcmp(coin->coin,"HUSHFILE") == 0 ) - return(1); - - return 0; -} - -// //////////////////////////////// the four key functions needed to support a new item for hushdexs - -int64_t _hushdex_getbalance(struct coininfo *coin) -{ - cJSON *retjson; char *retstr,cmpstr[64]; int64_t amount=0; - if ( (retjson= hushdex_cli(coin->cli,&retstr,"getbalance","","","","","","","")) != 0 ) - { - fprintf(stderr,"_hushdex_getbalance.(%s) %s returned json!\n",coin->coinstr,coin->cli); - free_json(retjson); - } - else if ( retstr != 0 ) - { - amount = atof(retstr) * SATOSHIDEN; - sprintf(cmpstr,"%.8f",dstr(amount)); - if ( strcmp(retstr,cmpstr) != 0 ) - amount++; - //printf("retstr %s -> %.8f\n",retstr,dstr(amount)); - free(retstr); - } - return (amount); -} - -bits256 _hushdex_sendtoaddress(struct coininfo *coin,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= hushdex_cli(coin->cli,&retstr,"sendtoaddress",destaddr,numstr,"false","","","","")) != 0 ) - { - fprintf(stderr,"unexpected _hushdex_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,"_hushdex_sendtoaddress %s %.8f txid.(%s)\n",destaddr,(double)satoshis/SATOSHIDEN,bits256_str(str,txid)); - free(retstr); - } - return(txid); -} - -cJSON *_hushdex_rawtransaction(struct coininfo *coin,bits256 txid) -{ - cJSON *retjson; char *retstr,str[65]; - if ( (retjson= hushdex_cli(coin->cli,&retstr,"getrawtransaction",bits256_str(str,txid),"1","","","","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"_hushdex_rawtransaction.(%s) %s error.(%s)\n",coin->coin,coin->name,retstr); - free(retstr); - } - return(0); -} - -int64_t hushdex_getbalance(struct coininfo *coin) -{ - char *coinstr,*acname=""; FILE *fp; int64_t retval = 0; - coinstr = coin->coin; - if ( coin->isfile != 0 ) - { - if ( (fp= fopen(coin->name+1,"rb")) != 0 ) // if alice, add bob pubkey to fname - { - fclose(fp); - retval = SATOSHIDEN; - } - return(retval); - } else if ( hushdex_zonly(coin) != 0 ) { - return(z_getbalance(coinstr,acname,DPOW_recvZaddr)); - } -} - -bits256 hushdex_coinpayment(uint32_t origid,int32_t OTCmode,struct coininfo *coin,char *destaddr,uint64_t paytoshis,char *memostr,char *destpub,char *senderpub) -{ - bits256 txid; char opidstr[128],opretstr[32],str[65],*status,*coinstr,*acname=""; cJSON *retjson,*retjson2,*item,*res; int32_t i,pending=0; - memset(&txid,0,sizeof(txid)); - if ( OTCmode == 0 ) - { - fprintf(stderr,"micropayment channels are not supported yet\n"); - return(txid); - } - if ( coin->isfile != 0 ) - { - fprintf(stderr,"start broadcast of (%s)\n",coin->coin+1); - if ( (retjson= dpow_publish(SUBATOMIC_PRIORITY,coin->coin+1)) != 0 ) // spawn thread - { - sprintf(opretstr,"%08x",juint(retjson,"id")); - sprintf(opidstr,"%u",origid); - if ( (retjson2= dpow_broadcast(SUBATOMIC_PRIORITY,opretstr,"inbox",opidstr,senderpub,"","")) != 0 ) - free_json(retjson2); - fprintf(stderr,"broadcast file.(%s) and send id.%u to alice (%s)\n",coin->coin+1,juint(retjson,"id"),jprint(retjson,0)); - txid = jbits256(retjson,"filehash"); - free_json(retjson); - } - fprintf(stderr,"end broadcast of (%s) to %s\n",coin->coin+1,senderpub); - return(txid); - } - else if ( hushdex_zonly(coin) != 0 ) - { - if ( memostr[0] == 0 ) - memostr = "beef"; - z_sendmany(opidstr,"",coin->coin,DPOW_recvZaddr,destaddr,paytoshis,memostr); - for (i=0; icoin,opidstr)) != 0 ) - { - item = jitem(retjson,0); - if ( (status= jstr(item,"status")) != 0 ) - { - if ( strcmp(status,"executing") == 0 ) - pending++; - else - { - res = jobj(item,"result"); - txid = jbits256(res,"txid"); - //fprintf(stderr,"got Ztx txid.%s\n",bits256_str(str,txid)); - free_json(retjson); - break; - } - /*else if ( clearresults != 0 ) - { - if ( (result= z_getoperationresult(coinstr,"",jstri(array,i))) != 0 ) - { - free_json(result); - } - }*/ - } - free_json(retjson); - } - sleep(1); - } - if ( i == 60 ) - printf("%u timed out waiting for opid to finish\n",origid); - } - else - { - coinstr = coin->coin; - if ( coin->istoken != 0 ) - txid = tokentransfer(coinstr,acname,coin->tokenid,destpub,paytoshis/SATOSHIDEN); - else if ( coin->isexternal == 0 ) - { - sprintf(opretstr,"%08x",origid); - txid = sendtoaddress(coinstr,acname,destaddr,paytoshis,opretstr); - } else txid = _hushdex_sendtoaddress(coin,destaddr,paytoshis); - printf("%u got txid.%s\n",origid,bits256_str(str,txid)); - } - return(txid); -} - -cJSON *hushdex_txidwait(struct coininfo *coin,bits256 txid,char *hexstr,int32_t numseconds,char *senderpub) -{ - int32_t i,zflag; char *coinstr,str[65],*acname=""; cJSON *rawtx; bits256 z; bits256 filehash; - memset(&z,0,sizeof(z)); - if ( memcmp(&z,&txid,sizeof(txid)) == 0 ) - return(0); - if ( hexstr != 0 && hexstr[0] != 0 ) // probably not worth doing and zaddr is a problem to decode - { - // compare against txid - // if matches, sendrawtransaction if OTC mode, decoode and return if channels mode - } - zflag = (hushdex_zonly(coin) != 0); - coinstr = coin->coin; - for (i=0; iisfile != 0 ) - { - if ( (rawtx= dpow_subscribe(SUBATOMIC_PRIORITY,coin->coin+1,senderpub)) != 0 ) - { - filehash = jbits256(rawtx,"filehash"); - if ( memcmp(&filehash,&txid,sizeof(filehash)) != 0 ) - { - fprintf(stderr,"waiting (%s) (%s)\n",coin->coin+1,jprint(rawtx,0)); - free_json(rawtx); - rawtx = 0; - } else return(rawtx); - } - } - else if ( zflag != 0 ) - rawtx = get_z_viewtransaction(coinstr,acname,txid); - else if ( coin->isexternal == 0 ) - rawtx = get_rawtransaction(coinstr,acname,txid); - else rawtx = _hushdex_rawtransaction(coin,txid); - if ( rawtx != 0 ) - return(rawtx); - sleep(1); - } - printf("%s/%s timeout waiting for %s\n",coin->name,coin->coin,bits256_str(str,txid)); - return(0); -} - -int64_t hushdex_verifypayment(struct coininfo *coin,cJSON *rawtx,uint64_t destsatoshis,char *destaddr,bits256 txid) -{ - int32_t i,n,m,valid=0; bits256 tokenid,filehash,checkhash; cJSON *array,*item,*sobj,*a; char *addr,*acname,*coinstr,tokenaddr[64],*hex; uint8_t hexbuf[512],pub33[33]; uint64_t netval,recvsatoshis = 0; - if ( coin->isfile != 0 ) - { - filehash = jbits256(rawtx,"filehash"); - checkhash = jbits256(rawtx,"checkhash"); - if ( memcmp(&txid,&filehash,sizeof(txid)) == 0 && memcmp(&txid,&checkhash,sizeof(txid)) == 0 ) - { - fprintf(stderr,"verified file is matching the filehash (%s)\n",jprint(rawtx,0)); - return(SATOSHIDEN); - } else return(0); - } - else if ( hushdex_zonly(coin) != 0 ) - { - if ( (array= jarray(&n,rawtx,"outputs")) != 0 && n > 0 ) - { - for (i=0; iistoken != 0 ) - { - if ( (array= jarray(&n,rawtx,"vout")) != 0 && n > 0 ) - { - item = jitem(array,0); - if ( (sobj= jobj(item,"scriptPubKey")) != 0 && (a= jarray(&m,sobj,"addresses")) != 0 && m == 1 ) - { - coinstr = coin->coin; - if ( get_tokenaddress(coinstr,acname,tokenaddr) != 0 ) - { - //fprintf(stderr,"tokenaddr.%s\n",tokenaddr); - if ( (addr= jstri(a,0)) != 0 && strcmp(addr,tokenaddr) == 0 ) - recvsatoshis += SATOSHIDEN * (uint64_t)(jdouble(item,"value")*SATOSHIDEN + 0.000000004999); - else fprintf(stderr,"miscompare (%s) vs %s\n",jprint(sobj,0),addr); - } - } - item = jitem(array,n-1); - if ( (sobj= jobj(item,"scriptPubKey")) != 0 && (hex= jstr(sobj,"hex")) != 0 && (m= is_hexstr(hex,0)) > 1 && m/2 < sizeof(hexbuf) ) - { - m >>= 1; - decode_hex(hexbuf,m,hex); - decode_hex(tokenid.bytes,32,coin->tokenid); - decode_hex(pub33,33,DPOW_secpkeystr); - // opret 69len EVAL_TOKENS 't' tokenid 1 33 pub33 - if ( hexbuf[0] == 0x6a && hexbuf[1] == 0x45 && hexbuf[2] == 0xf2 && hexbuf[3] == 't' && memcmp(&hexbuf[4],&tokenid,sizeof(tokenid)) == 0 && hexbuf[4+32] == 1 && hexbuf[4+32+1] == 33 && memcmp(&hexbuf[4+32+2],pub33,33) == 0 ) - { - valid = 1; - //fprintf(stderr,"validated it is a token transfer!\n"); - } else fprintf(stderr,"need to validate tokentransfer.(%s) %s %d\n",hex,DPOW_secpkeystr,memcmp(&hexbuf[4+32+2],pub33,33) == 0); - //6a 45 f2 74 2b1feef719ecb526b07416dd432bce603ac6dc8bfe794cddf105cb52f6aae3cd 01 21 02b27de3ee5335518b06f69f4fbabb029cfc737613b100996841d5532b324a5a61 - - } - recvsatoshis *= valid; - } - } - else - { - if ( (array= jarray(&n,rawtx,"vout")) != 0 && n > 0 ) - { - for (i=0; iorigid = origid; - HASH_ADD(hh,Messages,origid,sizeof(origid),mp); - return(mp); -} - -int32_t hushdex_status(struct msginfo *mp,int32_t status) -{ - static FILE *fp; - if ( fp == 0 ) - { - int32_t i,oid,s,n,num,count; struct msginfo *m; long fsize; - if ( (fp= fopen("SUBATOMIC.DB","rb+")) == 0 ) - { - if ( (fp= fopen("SUBATOMIC.DB","wb")) == 0 ) - { - fprintf(stderr,"cant create SUBATOMIC.DB\n"); - exit(-1); - } - } - else - { - fseek(fp,0,SEEK_END); - fsize = ftell(fp); - if ( (fsize % (sizeof(uint32_t)*2)) != 0 ) - { - fprintf(stderr,"SUBATOMIC.DB illegal filesize.%ld\n",fsize); - exit(-1); - } - n = (int32_t)(fsize / (sizeof(uint32_t)*2)); - rewind(fp); - for (i=num=count=0; i SUBATOMIC_CLOSED ) - { - fprintf(stderr,"SUBATOMIC.DB corrupted at filepos.%ld: illegal status.%d\n",ftell(fp),s); - exit(-1); - } - //fprintf(stderr,"%u <- %d\n",oid,s); - if ( (m= hushdex_find(oid)) == 0 ) - { - m = hushdex_add(oid); - count++; - } - if ( s > m->status ) - { - m->status = s; - num++; - } - } - fprintf(stderr,"initialized %d messages, updated %d out of total.%d\n",count,num,n); - } - } - if ( mp->status >= status ) - return(-1); - if ( fwrite(&mp->origid,1,sizeof(mp->origid),fp) != sizeof(mp->origid) || fwrite(&status,1,sizeof(status),fp) != sizeof(status) ) - fprintf(stderr,"error updating SUBATOMIC.DB, risk of double spends\n"); - fflush(fp); - mp->status = status; - return(0); -} - -struct msginfo *hushdex_tracker(uint32_t origid) -{ - struct msginfo *mp; - if ( (mp= hushdex_find(origid)) == 0 ) - { - mp = hushdex_add(origid); - hushdex_status(mp,0); - } - return(mp); -} - -char *hushdex_hexstr(char *jsonstr) -{ - char *hexstr; int32_t i,c,n = (int32_t)strlen(jsonstr); - hexstr = malloc(2*n + 3); - strcpy(hexstr,jsonstr); - for (i=0; iorigid); - jaddnum(item,"price",mp->price); - jaddnum(item,"openrequest",mp->openrequestid); - jaddstr(item,"base",mp->base.name); - jaddstr(item,"basecoin",mp->base.coin); - jadd64bits(item,"basesatoshis",mp->base.satoshis); - jadd64bits(item,"basetxfee",mp->base.txfee); - jadd64bits(item,"maxbaseamount",mp->base.maxamount); - jaddstr(item,"rel",mp->rel.name); - jaddstr(item,"relcoin",mp->rel.coin); - jadd64bits(item,"relsatoshis",mp->rel.satoshis); - jadd64bits(item,"reltxfee",mp->rel.txfee); - jadd64bits(item,"maxrelamount",mp->rel.maxamount); - jaddstr(item,"alice",mp->alice.pubkey); - jaddstr(item,"alicesecp",mp->alice.secp); - jaddstr(item,"bob",mp->bob.pubkey); - jaddstr(item,"bobsecp",mp->bob.secp); - if ( hushdex_zonly(&mp->rel) != 0 ) - jaddstr(item,"bobZaddr",mp->bob.recvZaddr); - else jaddstr(item,"bobaddr",mp->bob.recvaddr); - if ( mp->rel.istoken != 0 ) - jaddstr(item,"bobtoken",mp->rel.tokenid); - if ( hushdex_zonly(&mp->base) != 0 ) - jaddstr(item,"aliceZaddr",mp->alice.recvZaddr); - else jaddstr(item,"aliceaddr",mp->alice.recvaddr); - if ( mp->base.istoken != 0 ) - jaddstr(item,"alicetoken",mp->base.tokenid); - return(item); -} - -uint64_t hushdex_orderbook_mpset(struct msginfo *mp,char *basecheck) -{ - cJSON *retjson; char *tagA,*tagB,*senderpub,*str,tmpstr[32]; int32_t matches=0; double volA,volB; int64_t txfee=0; - strcpy(mp->base.name,basecheck); - strcpy(mp->base.coin,hushdex_checkname(tmpstr,mp,0,basecheck)); - mp->rel.txfee = hushdex_txfee(mp->rel.coin); - if ( (retjson= dpow_get(mp->origid)) != 0 ) - { - //fprintf(stderr,"dpow_get.(%s) (%s/%s)\n",jprint(retjson,0),mp->base.coin,mp->rel.coin); - if ( (senderpub= jstr(retjson,"senderpub")) != 0 && is_hexstr(senderpub,0) == 66 && (tagA= jstr(retjson,"tagA")) != 0 && (tagB= jstr(retjson,"tagB")) != 0 && strncmp(tagB,mp->rel.name,strlen(mp->rel.name)) == 0 && strlen(tagA) < sizeof(mp->base.name) ) - { - strcpy(mp->base.name,tagA); - strcpy(mp->base.coin,hushdex_checkname(tmpstr,mp,0,tagA)); - if ( basecheck[0] == 0 || strncmp(basecheck,tagA,strlen(basecheck)) == 0 ) - matches = 1; - else if ( strcmp(tagA,mp->base.name) == 0 ) - matches = 1; - else if ( mp->bobflag != 0 && tagA[0] == '#' && strcmp(mp->base.name,"#allfiles") == 0 ) - matches = 1; - if ( matches != 0 ) - { - if ( (str= jstr(retjson,"decrypted")) != 0 && strlen(str) < 128 ) - strcpy(mp->payload,str); - mp->locktime = juint(retjson,"timestamp") + SUBATOMIC_LOCKTIME; - mp->base.txfee = hushdex_txfee(mp->base.coin); - strcpy(mp->senderpub,senderpub); - volB = jdouble(retjson,"amountB"); - volA = jdouble(retjson,"amountA"); - mp->base.maxamount = volA*SATOSHIDEN + 0.0000000049999; - mp->rel.maxamount = volB*SATOSHIDEN + 0.0000000049999; - if ( 0 && mp->rel.istoken == 0 ) - txfee = mp->rel.txfee; - if ( mp->base.maxamount != 0 && mp->rel.maxamount != 0 && volA > SMALLVAL && volB > SMALLVAL && mp->rel.satoshis <= mp->rel.maxamount ) - { - mp->price = volA / volB; - mp->base.satoshis = (mp->rel.satoshis - txfee) * mp->price; - //fprintf(stderr,"base satoshis.%llu\n",(long long)mp->base.satoshis); - } else fprintf(stderr,"%u rel %llu vs (%llu %llu)\n",mp->origid,(long long)mp->rel.satoshis,(long long)mp->base.maxamount,(long long)mp->rel.maxamount); - } else printf("%u didnt match (%s) tagA.%s %s, tagB.%s %s %d %d\n",mp->origid,basecheck,tagA,mp->base.name,tagB,mp->rel.name,tagA[0] == '#', strcmp(mp->base.name,"#allfiles") == 0); - } else printf("%u didnt compare tagA.%s %s, tagB.%s %s\n",mp->origid,tagA,mp->base.name,tagB,mp->rel.name); - free_json(retjson); - } - return(mp->base.satoshis); -} - -char *randhashstr(char *str) -{ - bits256 rands; int32_t i; - for (i=0; i<32; i++) - rands.bytes[i] = rand() >> 17; - bits256_str(str,rands); - return(str); -} - -void hushdex_extrafields(cJSON *dest,cJSON *src) -{ - char *str; - if ( (str= jstr(src,"approval")) != 0 ) - jaddstr(dest,"approval",str); - if ( (str= jstr(src,"opened")) != 0 ) - jaddstr(dest,"opened",str); - if ( (str= jstr(src,"payamount")) != 0 ) - jaddstr(dest,"payamount",str); - if ( (str= jstr(src,"destaddr")) != 0 ) - jaddstr(dest,"destaddr",str); - if ( (str= jstr(src,"bobpayment")) != 0 ) - jaddstr(dest,"bobpayment",str); - if ( (str= jstr(src,"alicepayment")) != 0 ) - jaddstr(dest,"alicepayment",str); - if ( (str= jstr(src,"bobaddr")) != 0 ) - jaddstr(dest,"bobaddr",str); - if ( (str= jstr(src,"bobZaddr")) != 0 ) - jaddstr(dest,"bobZaddr",str); - if ( (str= jstr(src,"aliceaddr")) != 0 ) - jaddstr(dest,"aliceaddr",str); - if ( (str= jstr(src,"aliceZaddr")) != 0 ) - jaddstr(dest,"aliceZaddr",str); - if ( (str= jstr(src,"alicetoken")) != 0 ) - jaddstr(dest,"alicetoken",str); - if ( (str= jstr(src,"bobtoken")) != 0 ) - jaddstr(dest,"bobtoken",str); -} - -char *hushdex_submit(cJSON *argjson,int32_t tobob) -{ - char *jsonstr,*hexstr; - jaddnum(argjson,"tobob",tobob != 0); - jsonstr = jprint(argjson,1); - hexstr = hushdex_hexstr(jsonstr); - free(jsonstr); - return(hexstr); -} - -#define SCRIPT_OP_IF 0x63 -#define SCRIPT_OP_ELSE 0x67 -#define SCRIPT_OP_DUP 0x76 -#define SCRIPT_OP_ENDIF 0x68 -#define SCRIPT_OP_TRUE 0x51 -#define SCRIPT_OP_2 0x52 -#define SCRIPT_OP_3 0x53 -#define SCRIPT_OP_DROP 0x75 -#define SCRIPT_OP_EQUALVERIFY 0x88 -#define SCRIPT_OP_HASH160 0xa9 -#define SCRIPT_OP_EQUAL 0x87 -#define SCRIPT_OP_CHECKSIG 0xac -#define SCRIPT_OP_CHECKMULTISIG 0xae -#define SCRIPT_OP_CHECKMULTISIGVERIFY 0xaf -#define SCRIPT_OP_CHECKLOCKTIMEVERIFY 0xb1 - -int32_t hushdex_redeemscript(char *redeemscript,uint32_t locktime,char *pubkeyA,char *pubkeyB) // not needed -{ - // if ( refund ) OP_HASH160 <2of2 multisig hash> OP_EQUAL // standard multisig - // else CLTV OP_DROP OP_CHECKSIG // standard spend - uint8_t pubkeyAbytes[33],pubkeyBbytes[33],hex[4096]; int32_t i,n = 0; - decode_hex(pubkeyAbytes,33,pubkeyA); - decode_hex(pubkeyBbytes,33,pubkeyB); - hex[n++] = SCRIPT_OP_IF; - hex[n++] = SCRIPT_OP_2; - hex[n++] = 33, memcpy(&hex[n],pubkeyAbytes,33), n += 33; - hex[n++] = 33, memcpy(&hex[n],pubkeyBbytes,33), n += 33; - hex[n++] = SCRIPT_OP_2; - hex[n++] = SCRIPT_OP_CHECKMULTISIG; - hex[n++] = SCRIPT_OP_ELSE; - hex[n++] = 4; - hex[n++] = locktime & 0xff, locktime >>= 8; - hex[n++] = locktime & 0xff, locktime >>= 8; - hex[n++] = locktime & 0xff, locktime >>= 8; - hex[n++] = locktime & 0xff; - hex[n++] = SCRIPT_OP_CHECKLOCKTIMEVERIFY; - hex[n++] = SCRIPT_OP_DROP; - hex[n++] = 33; memcpy(&hex[n],pubkeyAbytes,33); n += 33; - hex[n++] = SCRIPT_OP_CHECKSIG; - hex[n++] = SCRIPT_OP_ENDIF; - for (i=0; i>4) & 0xf); - redeemscript[i*2 + 1] = hexbyte(hex[i] & 0xf); - } - redeemscript[n*2] = 0; - /*tmpbuf[0] = SCRIPT_OP_HASH160; - tmpbuf[1] = 20; - calc_OP_HASH160(scriptPubKey,tmpbuf+2,redeemscript); - tmpbuf[22] = SCRIPT_OP_EQUAL; - init_hexbytes_noT(scriptPubKey,tmpbuf,23); - if ( p2shaddr != 0 ) - { - p2shaddr[0] = 0; - if ( (btc_addr= base58_encode_check(addrtype,true,tmpbuf+2,20)) != 0 ) - { - if ( strlen(btc_addr->str) < 36 ) - strcpy(p2shaddr,btc_addr->str); - cstr_free(btc_addr,true); - } - }*/ - return(n); -} - -int32_t hushdex_approved(struct msginfo *mp,cJSON *approval,cJSON *msgjson,char *senderpub) -{ - char *hexstr,numstr[32],redeemscript[1024],*coin,*acname=""; cJSON *retjson,*decodejson; int32_t i,retval = 0; - hushdex_extrafields(approval,msgjson); - if ( mp->OTCmode == 0 ) - { - coin = (mp->bobflag != 0) ? mp->base.coin : mp->rel.coin; // the other side gets this coin - if ( get_createmultisig2(coin,acname,mp->msigaddr,mp->redeemscript,mp->alice.secp,mp->bob.secp) != 0 ) - { - hushdex_redeemscript(redeemscript,mp->locktime,mp->alice.secp,mp->bob.secp); - if ( (decodejson= get_decodescript(coin,acname,redeemscript)) != 0 ) - { - fprintf(stderr,"%s %s msigaddr.%s %s -> %s %s\n",mp->bobflag!=0?"bob":"alice",(mp->bobflag != 0) ? mp->base.coin : mp->rel.coin,mp->msigaddr,mp->redeemscript,redeemscript,jprint(decodejson,0)); - free(decodejson); - } - } - } - sprintf(numstr,"%u",mp->origid); - for (i=0; numstr[i]!=0; i++) - sprintf(&mp->approval[i<<1],"%02x",numstr[i]); - sprintf(&mp->approval[i<<1],"%02x",' '); - i++; - mp->approval[i<<1] = 0; - jaddstr(approval,"approval",mp->approval); - hexstr = hushdex_submit(approval,!mp->bobflag); - if ( (retjson= dpow_broadcast(SUBATOMIC_PRIORITY,hexstr,(char *)"inbox",(char *)"approved",senderpub,"","")) != 0 ) - { - if ( (mp->approvalid= juint(retjson,"id")) != 0 ) - retval = 1; - printf("%u approvalid.%u (%s)\n",mp->origid,mp->approvalid,senderpub); - hushdex_status(mp,SUBATOMIC_APPROVED); - free_json(retjson); - } - free(hexstr); - return(retval); -} - -int32_t hushdex_opened(struct msginfo *mp,cJSON *opened,cJSON *msgjson,char *senderpub) -{ - char *hexstr,channelstr[65]; cJSON *retjson; int32_t retval = 0; - hushdex_extrafields(opened,msgjson); - jaddstr(opened,"opened",randhashstr(channelstr)); - hexstr = hushdex_submit(opened,!mp->bobflag); - if ( (retjson= dpow_broadcast(SUBATOMIC_PRIORITY,hexstr,(char *)"inbox",(char *)"opened",senderpub,"","")) != 0 ) - { - if ( (mp->openedid= juint(retjson,"id")) != 0 ) - retval = 1; - printf("%u openedid.%u\n",mp->origid,mp->openedid); - hushdex_status(mp,SUBATOMIC_OPENED); - free_json(retjson); - } - free(hexstr); - return(retval); -} - -int32_t hushdex_payment(struct msginfo *mp,cJSON *payment,cJSON *msgjson,char *senderpub) -{ - bits256 txid; uint64_t paytoshis; cJSON *retjson; char numstr[32],*coin,*dest,*hexstr; int32_t retval = 0; - if ( mp->bobflag == 0 ) - { - coin = mp->rel.name; - paytoshis = mp->rel.satoshis; - if ( hushdex_zonly(&mp->rel) != 0 ) - dest = mp->bob.recvZaddr; - else dest = mp->bob.recvaddr; - sprintf(numstr,"%llu",(long long)paytoshis); - jaddstr(payment,"alicepays",numstr); - jaddstr(payment,"bobdestaddr",dest); - txid = hushdex_coinpayment(mp->origid,mp->OTCmode,&mp->rel,dest,paytoshis,mp->approval,mp->bob.secp,senderpub); - jaddbits256(payment,"alicepayment",txid); - mp->alicepayment = txid; - hexstr = 0; // get it from rawtransaction of txid - jaddstr(payment,"alicetx",hexstr); - } - else - { - coin = mp->base.name; - paytoshis = mp->base.satoshis; - if ( hushdex_zonly(&mp->base) != 0 ) - dest = mp->alice.recvZaddr; - else dest = mp->alice.recvaddr; - sprintf(numstr,"%llu",(long long)paytoshis); - jaddstr(payment,"bobpays",numstr); - jaddstr(payment,"alicedestaddr",dest); - txid = hushdex_coinpayment(mp->origid,mp->OTCmode,&mp->base,dest,paytoshis,mp->approval,mp->alice.secp,senderpub); - jaddbits256(payment,"bobpayment",txid); - mp->bobpayment = txid; - hexstr = 0; // get it from rawtransaction of txid - jaddstr(payment,"bobtx",hexstr); - } - hexstr = hushdex_submit(payment,!mp->bobflag); - if ( (retjson= dpow_broadcast(SUBATOMIC_PRIORITY,hexstr,(char *)"inbox",(char *)"payment",senderpub,"","")) != 0 ) - { - if ( (mp->paymentids[0]= juint(retjson,"id")) != 0 ) - retval = 1; - printf("%u: %.8f %s -> %s, paymentid[0] %u\n",mp->origid,dstr(paytoshis),coin,dest,mp->paymentids[0]); - hushdex_status(mp,SUBATOMIC_PAYMENT); - free_json(retjson); - } - free(hexstr); - return(retval); -} - -int32_t hushdex_paidinfull(struct msginfo *mp,cJSON *paid,cJSON *msgjson,char *senderpub) -{ - char *hexstr; cJSON *retjson; int32_t retval = 0; - jaddstr(paid,"paid","in full"); - hushdex_extrafields(paid,msgjson); - hexstr = hushdex_submit(paid,!mp->bobflag); - if ( (retjson= dpow_broadcast(SUBATOMIC_PRIORITY,hexstr,(char *)"inbox",(char *)"paid",senderpub,"","")) != 0 ) - { - if ( (mp->paidid= juint(retjson,"id")) != 0 ) - retval = 1; - printf("%u paidid.%u\n",mp->origid,mp->paidid); - hushdex_status(mp,SUBATOMIC_PAIDINFULL); - free_json(retjson); - } - free(hexstr); - return(retval); -} - -int32_t hushdex_closed(struct msginfo *mp,cJSON *closed,cJSON *msgjson,char *senderpub) -{ - char *hexstr; cJSON *retjson; int32_t retval = 0; - jaddnum(closed,"closed",mp->origid); - hushdex_extrafields(closed,msgjson); - hexstr = hushdex_submit(closed,!mp->bobflag); - if ( (retjson= dpow_broadcast(SUBATOMIC_PRIORITY,hexstr,(char *)"inbox",(char *)"closed",senderpub,"","")) != 0 ) - { - if ( (mp->closedid= juint(retjson,"id")) != 0 ) - retval = 1; - hushdex_status(mp,SUBATOMIC_CLOSED); - printf("%u closedid.%u\n",mp->origid,mp->closedid); - free_json(retjson); - } - free(hexstr); - return(retval); -} - -uint32_t hushdex_alice_openrequest(struct msginfo *origmp) -{ - struct msginfo *mp; cJSON *retjson,*openrequest; char *hexstr,*str,tmpstr[32]; - mp = hushdex_tracker(origmp->origid); - mp->origid = origmp->origid; - mp->rel.satoshis = origmp->rel.satoshis; - mp->rel.istoken = origmp->rel.istoken; - strcpy(mp->rel.tokenid,origmp->rel.tokenid); - strcpy(mp->rel.name,origmp->rel.name); - strcpy(mp->rel.coin,hushdex_checkname(tmpstr,mp,1,origmp->rel.name)); - strcpy(mp->alice.pubkey,DPOW_pubkeystr); - strcpy(mp->alice.secp,DPOW_secpkeystr); - strcpy(mp->alice.recvZaddr,DPOW_recvZaddr); - strcpy(mp->alice.recvaddr,DPOW_recvaddr); - printf("rel.%s/%s %s openrequest %u status.%d (%s/%s)\n",mp->rel.name,mp->rel.coin,mp->rel.tokenid,mp->origid,mp->status,mp->alice.recvaddr,mp->alice.recvZaddr); - if ( mp->status == 0 && hushdex_orderbook_mpset(mp,"") != 0 ) - { - strcpy(mp->bob.pubkey,mp->senderpub); - if ( hushdex_zonly(&mp->base) != 0 || hushdex_zonly(&mp->rel) != 0 ) - mp->OTCmode = 1; - else mp->OTCmode = SUBATOMIC_OTCDEFAULT; - strcpy(origmp->base.name,mp->base.name); - strcpy(origmp->base.coin,mp->base.coin); - origmp->base.istoken = mp->base.istoken; - strcpy(origmp->base.tokenid,mp->base.tokenid); - origmp->OTCmode = mp->OTCmode; - if ( mp->rel.istoken != 0 && ((mp->rel.satoshis % SATOSHIDEN) != 0 || mp->rel.iszaddr != 0) ) - { - printf("%u cant do zaddr or fractional rel %s.%s tokens %.8f\n",mp->origid,mp->rel.coin,mp->rel.tokenid,dstr(mp->rel.satoshis)); - return(0); - } - else if ( mp->base.istoken != 0 && ((mp->base.satoshis % SATOSHIDEN) != 0 || mp->base.iszaddr != 0 ) ) - { - printf("%u cant do zaddr or fractional base %s.%s tokens %.8f\n",mp->origid,mp->base.coin,mp->base.tokenid,dstr(mp->base.satoshis)); - return(0); - } - else if ( (openrequest= hushdex_mpjson(mp)) != 0 ) - { - hexstr = hushdex_submit(openrequest,!mp->bobflag); - if ( (retjson= dpow_broadcast(SUBATOMIC_PRIORITY,hexstr,(char *)"inbox",(char *)"openrequest",mp->bob.pubkey,"","")) != 0 ) - { - mp->openrequestid = juint(retjson,"id"); - printf("%u openrequest.%u -> (%s)\n",mp->origid,mp->openrequestid,mp->bob.pubkey); - hushdex_status(mp,SUBATOMIC_OPENREQUEST); - free_json(retjson); - } - free(hexstr); - } - } - return(mp->openrequestid); -} - -void hushdex_bob_gotopenrequest(uint32_t inboxid,char *senderpub,cJSON *msgjson,char *basename,char *relname) -{ - struct msginfo *mp; cJSON *approval; int32_t origid; char *addr,tmpstr[32],*coin,*acname=""; - origid = juint(msgjson,"origid"); - mp = hushdex_tracker(origid); - strcpy(mp->base.name,basename); - strcpy(mp->base.coin,hushdex_checkname(tmpstr,mp,0,basename)); - strcpy(mp->rel.name,relname); - strcpy(mp->rel.coin,hushdex_checkname(tmpstr,mp,1,relname)); - mp->origid = origid; - mp->rel.satoshis = j64bits(msgjson,"relsatoshis"); - mp->bobflag = 1; - strcpy(mp->bob.pubkey,DPOW_pubkeystr); - strcpy(mp->bob.secp,DPOW_secpkeystr); - strcpy(mp->bob.recvZaddr,DPOW_recvZaddr); - strcpy(mp->bob.recvaddr,DPOW_recvaddr); - if ( (addr= jstr(msgjson,"aliceaddr")) != 0 ) - strcpy(mp->alice.recvaddr,addr); - if ( (addr= jstr(msgjson,"aliceZaddr")) != 0 ) - strcpy(mp->alice.recvZaddr,addr); - if ( (addr= jstr(msgjson,"alicesecp")) != 0 ) - strcpy(mp->alice.secp,addr); - if ( hushdex_zonly(&mp->base) != 0 || hushdex_zonly(&mp->rel) != 0 ) - mp->OTCmode = 1; - else mp->OTCmode = SUBATOMIC_OTCDEFAULT; - printf("%u got open request\n",mp->origid); - if ( mp->status == 0 && hushdex_orderbook_mpset(mp,basename) != 0 && (approval= hushdex_mpjson(mp)) != 0 ) - { - if ( mp->rel.istoken != 0 && ((mp->rel.satoshis % SATOSHIDEN) != 0 || mp->rel.iszaddr != 0) ) - { - printf("%u cant do zaddr or fractional rel %s.%s tokens %.8f\n",mp->origid,mp->rel.coin,mp->rel.tokenid,dstr(mp->rel.satoshis)); - hushdex_closed(mp,approval,msgjson,senderpub); - return; - } - else if ( mp->base.istoken != 0 && ((mp->base.satoshis % SATOSHIDEN) != 0 || mp->base.iszaddr != 0 ) ) - { - printf("%u cant do zaddr or fractional base %s.%s tokens %.8f\n",mp->origid,mp->base.coin,mp->base.tokenid,dstr(mp->base.satoshis)); - hushdex_closed(mp,approval,msgjson,senderpub); - return; - } - else if ( hushdex_getbalance(&mp->base) < mp->base.satoshis ) - { - printf("%u bob node low on %s funds! %.8f not enough for %.8f\n",mp->origid,mp->base.coin,dstr(hushdex_getbalance(&mp->base)),dstr(mp->base.satoshis)); - hushdex_closed(mp,approval,msgjson,senderpub); - } - else - { - printf("%u bob (%s/%s) gotopenrequest origid.%u status.%d (%s/%s) SENDERPUB.(%s)\n",mp->origid,mp->base.name,mp->rel.name,mp->origid,mp->status,mp->bob.recvaddr,mp->bob.recvZaddr,senderpub); - hushdex_approved(mp,approval,msgjson,senderpub); - } - } -} - -int32_t hushdex_channelapproved(uint32_t inboxid,char *senderpub,cJSON *msgjson,struct msginfo *origmp) -{ - struct msginfo *mp; cJSON *approval; char *addr,*coin,*acname; int32_t retval = 0; - mp = hushdex_tracker(juint(msgjson,"origid")); - if ( hushdex_orderbook_mpset(mp,mp->base.name) != 0 && (approval= hushdex_mpjson(mp)) != 0 ) - { - printf("%u iambob.%d (%s/%s) channelapproved origid.%u status.%d\n",mp->origid,mp->bobflag,mp->base.name,mp->rel.name,mp->origid,mp->status); - if ( mp->bobflag == 0 && mp->status == SUBATOMIC_OPENREQUEST ) - { - if ( (addr= jstr(msgjson,"bobaddr")) != 0 ) - strcpy(mp->bob.recvaddr,addr); - if ( (addr= jstr(msgjson,"bobZaddr")) != 0 ) - strcpy(mp->bob.recvZaddr,addr); - if ( (addr= jstr(msgjson,"bobsecp")) != 0 ) - strcpy(mp->bob.secp,addr); - retval = hushdex_approved(mp,approval,msgjson,senderpub); - } - else if ( mp->bobflag != 0 && mp->status == SUBATOMIC_APPROVED ) - retval = hushdex_opened(mp,approval,msgjson,senderpub); - } - return(retval); -} - -int32_t hushdex_incomingopened(uint32_t inboxid,char *senderpub,cJSON *msgjson,struct msginfo *origmp) -{ - struct msginfo *mp; cJSON *payment; int32_t retval = 0; - mp = hushdex_tracker(juint(msgjson,"origid")); - if ( hushdex_orderbook_mpset(mp,mp->base.name) != 0 && (payment= hushdex_mpjson(mp)) != 0 ) - { - printf("%u iambob.%d (%s/%s) incomingchannel status.%d\n",mp->origid,mp->bobflag,mp->base.name,mp->rel.name,mp->status); - if ( mp->bobflag == 0 && mp->status == SUBATOMIC_APPROVED ) - retval = hushdex_payment(mp,payment,msgjson,senderpub); - else if ( mp->bobflag != 0 && mp->status == SUBATOMIC_OPENED ) - retval = 1; // nothing to do - } - return(retval); -} - -int32_t hushdex_incomingpayment(uint32_t inboxid,char *senderpub,cJSON *msgjson,struct msginfo *origmp) -{ - static FILE *fp; - struct msginfo *mp; cJSON *pay,*rawtx,*retjson; bits256 txid; char str[65],*hexstr; int32_t retval = 0; - mp = hushdex_tracker(juint(msgjson,"origid")); - if ( hushdex_orderbook_mpset(mp,mp->base.name) != 0 && (pay= hushdex_mpjson(mp)) != 0 ) - { - printf("%u iambob.%d (%s/%s) incomingpayment status.%d\n",mp->origid,mp->bobflag,mp->base.name,mp->rel.name,mp->status); - if ( mp->bobflag == 0 ) - { - txid = jbits256(msgjson,"bobpayment"); - jaddbits256(msgjson,"alicepayment",mp->alicepayment); - printf("%u alice waits for %s.%s to be in mempool (%.8f -> %s)\n",mp->origid,mp->base.name,bits256_str(str,txid),dstr(mp->base.satoshis),hushdex_zonly(&mp->base) == 0 ? mp->alice.recvaddr : mp->alice.recvZaddr); - hexstr = jstr(msgjson,"bobtx"); - if ( (rawtx= hushdex_txidwait(&mp->base,txid,hexstr,SUBATOMIC_TIMEOUT,senderpub)) != 0 ) - { - if ( hushdex_verifypayment(&mp->base,rawtx,mp->base.satoshis,hushdex_zonly(&mp->base) == 0 ? mp->alice.recvaddr : mp->alice.recvZaddr,txid) >= 0 ) - mp->gotpayment = 1; - free_json(rawtx); - } - if ( mp->gotpayment != 0 ) - { - printf("%u SWAP COMPLETE <<<<<<<<<<<<<<<<\n",mp->origid); - SUBATOMIC_retval = 0; - if ( mp->base.iszaddr == 0 ) - { - sprintf(str,"%u",mp->origid); - if ( (retjson= dpow_broadcast(SUBATOMIC_PRIORITY,bits256_str(str,mp->alicepayment),(char *)"completed",str,DPOW_pubkeystr,"","")) != 0 ) - free_json(retjson); - } - } - else - { - printf("%u SWAP INCOMPLETE, waiting on %s.%s\n",mp->origid,mp->base.name,bits256_str(str,txid)); - if ( (fp= fopen("SUBATOMIC.incomplete","a+")) != 0 ) - { - char *jsonstr = jprint(msgjson,0); - fwrite(jsonstr,1,strlen(jsonstr),fp); - fputc('\n',fp); - fclose(fp); - free(jsonstr); - } - if ( mp->base.iszaddr == 0 ) - { - sprintf(str,"%u",mp->origid); - if ( (retjson= dpow_broadcast(SUBATOMIC_PRIORITY,bits256_str(str,mp->alicepayment),(char *)"incomplete",str,DPOW_pubkeystr,"","")) != 0 ) - free_json(retjson); - } - hushdex_closed(mp,pay,msgjson,senderpub); - exit(-1); - } - } - if ( mp->gotpayment != 0 ) - retval = hushdex_paidinfull(mp,pay,msgjson,senderpub); - else - { - if ( mp->bobflag != 0 && mp->status == SUBATOMIC_OPENED ) - { - txid = jbits256(msgjson,"alicepayment"); - printf("%u bob waits for %s.%s to be in mempool (%.8f -> %s)\n",mp->origid,mp->rel.name,bits256_str(str,txid),dstr(mp->rel.satoshis),hushdex_zonly(&mp->rel) == 0 ? mp->bob.recvaddr : mp->bob.recvZaddr); - hexstr = jstr(msgjson,"alicetx"); - if ( (rawtx= hushdex_txidwait(&mp->rel,txid,hexstr,SUBATOMIC_TIMEOUT,senderpub)) != 0 ) - { - if ( hushdex_verifypayment(&mp->rel,rawtx,mp->rel.satoshis,hushdex_zonly(&mp->rel) == 0 ? mp->bob.recvaddr : mp->bob.recvZaddr,txid) >= 0 ) - mp->gotpayment = 1; - free_json(rawtx); - } - if ( mp->gotpayment != 0 ) - { - retval = hushdex_payment(mp,pay,msgjson,senderpub); - jaddbits256(msgjson,"bobpayment",mp->bobpayment); - if ( mp->rel.iszaddr == 0 ) - { - sprintf(str,"%u",mp->origid); - if ( (retjson= dpow_broadcast(SUBATOMIC_PRIORITY,bits256_str(str,mp->bobpayment),(char *)"completed",str,DPOW_pubkeystr,"","")) != 0 ) - free_json(retjson); - } - printf("%u SWAP COMPLETE <<<<<<<<<<<<<<<<\n",mp->origid); - if ( (fp= fopen("SUBATOMIC.proof","rb+")) == 0 ) - fp = fopen("SUBATOMIC.proof","wb"); - if ( fp != 0 ) - { - char *jsonstr = jprint(msgjson,0); - fseek(fp,0,SEEK_END); - fwrite(jsonstr,1,strlen(jsonstr),fp); - fputc('\n',fp); - fflush(fp); - free(jsonstr); - } - } else printf("%u SWAP INCOMPLETE: %s\n",mp->origid,jprint(msgjson,0)); - } - } - } - return(retval); -} - -int32_t hushdex_incomingfullypaid(uint32_t inboxid,char *senderpub,cJSON *msgjson,struct msginfo *origmp) -{ - struct msginfo *mp; cJSON *closed; int32_t retval = 0; - mp = hushdex_tracker(juint(msgjson,"origid")); - if ( hushdex_orderbook_mpset(mp,mp->base.name) != 0 && (closed= hushdex_mpjson(mp)) != 0 ) - { - printf("%u iambob.%d (%s/%s) incomingfullypaid status.%d\n",mp->origid,mp->bobflag,mp->base.name,mp->rel.name,mp->status); - // error check msgjson vs M - if ( mp->bobflag == 0 && mp->status == SUBATOMIC_PAIDINFULL ) - retval = hushdex_closed(mp,closed,msgjson,senderpub); - else if ( mp->bobflag != 0 && mp->status == SUBATOMIC_PAYMENT ) - retval = hushdex_paidinfull(mp,closed,msgjson,senderpub); - } - return(retval); -} - -int32_t hushdex_incomingclosed(uint32_t inboxid,char *senderpub,cJSON *msgjson,struct msginfo *origmp) -{ - struct msginfo *mp; cJSON *closed; int32_t retval = 0; - mp = hushdex_tracker(juint(msgjson,"origid")); - if ( hushdex_orderbook_mpset(mp,mp->base.name) != 0 && (closed= hushdex_mpjson(mp)) != 0 ) - { - printf("%u iambob.%d (%s/%s) incomingclose status.%d\n",mp->origid,mp->bobflag,mp->base.name,mp->rel.name,mp->status); - if ( mp->bobflag != 0 ) - dpow_cancel(mp->origid); - if ( mp->status < SUBATOMIC_CLOSED ) - { - retval = hushdex_closed(mp,closed,msgjson,senderpub); - hushdex_status(mp,SUBATOMIC_CLOSED); - } - retval = 1; - } - return(retval); -} - -int32_t hushdex_ismine(int32_t bobflag,cJSON *json,char *basename,char *relname) -{ - char *base,*rel; - if ( (base= jstr(json,"base")) != 0 && (rel= jstr(json,"rel")) != 0 ) - { - if ( strcmp(base,basename) == 0 && strcmp(rel,relname) == 0 ) - return(1); - if ( bobflag != 0 ) - { - if ( strcmp(basename,"#allfiles") == 0 && base[0] == '#' ) - return(1); - fprintf(stderr,"skip ismine (%s/%s) vs (%s/%s)\n",basename,relname,base,rel); - } - } - return(0); -} - -void hushdex_tokensregister(int32_t priority) -{ - char *token_name,*tokenid,existing[65]; cJSON *tokens,*token; int32_t i,numtokens; - if ( SUBATOMIC_json != 0 && (tokens= jarray(&numtokens,SUBATOMIC_json,"tokens")) != 0 ) - { - for (i=0; i 0 ) - { - for (j=0; j %s, %u %llu %u\n",mp->bobflag,mp->base.name,mp->rel.name,mp->origid,(long long)mp->rel.satoshis,mp->openrequestid); - while ( 1 ) - { - if ( msgs == 0 ) - { - sleep(1); - fflush(stdout); - if ( mp->bobflag != 0 ) - { - dpow_pubkeyregister(SUBATOMIC_PRIORITY); - hushdex_tokensregister(SUBATOMIC_PRIORITY); - hushdex_filesregister(SUBATOMIC_PRIORITY); - } - } - msgs = 0; - for (iter=0; iter<(int32_t)(sizeof(tagBs)/sizeof(*tagBs)); iter++) - { - tagB = tagBs[iter]; - if ( (ptrs= dpow_inboxcheck(&n,&stopats[iter],tagB)) != 0 ) - { - for (i=0; ijsonstr)) != 0 ) - { - if ( jint(inboxjson,"tobob") != mp->bobflag ) - continue; - if ( hushdex_ismine(mp->bobflag,inboxjson,mp->base.name,mp->rel.name) != 0 ) - { - if ( strcmp(tagB,"openrequest") == 0 && mp->bobflag != 0 ) - hushdex_bob_gotopenrequest(ptr->shorthash,ptr->senderpub,inboxjson,mp->base.name,mp->rel.name); - else if ( strcmp(tagB,"approved") == 0 ) - mask |= hushdex_channelapproved(ptr->shorthash,ptr->senderpub,inboxjson,mp) << 0; - else if ( strcmp(tagB,"opened") == 0 ) - mask |= hushdex_incomingopened(ptr->shorthash,ptr->senderpub,inboxjson,mp) << 1; - else if ( strcmp(tagB,"payment") == 0 ) - mask |= hushdex_incomingpayment(ptr->shorthash,ptr->senderpub,inboxjson,mp) << 2; - else if ( strcmp(tagB,"paid") == 0 ) - mask |= hushdex_incomingfullypaid(ptr->shorthash,ptr->senderpub,inboxjson,mp) << 3; - else if ( strcmp(tagB,"closed") == 0 ) - mask |= hushdex_incomingclosed(ptr->shorthash,ptr->senderpub,inboxjson,mp) * 0x1f; - else fprintf(stderr,"iambob.%d unknown unexpected tagB.(%s)\n",mp->bobflag,tagB); - } - free_json(inboxjson); - } else fprintf(stderr,"hushdex iambob.%d loop got unparseable(%s)\n",mp->bobflag,ptr->jsonstr); - free(ptr); - ptrs[i] = 0; - } - } - free(ptrs); - } - } - if ( mp->bobflag == 0 && (mask & 0x1f) == 0x1f ) - { - printf("alice %u %llu %u finished\n",mp->origid,(long long)mp->rel.satoshis,mp->openrequestid); - break; - } - } -} - -int32_t main(int32_t argc,char **argv) -{ - char *fname = "hushdex.json"; - int32_t i,height; char *coin,*kcli,*hushdex,*hashstr,*acname=(char *)""; cJSON *retjson; bits256 blockhash; char checkstr[65],str[65],str2[65],tmpstr[32]; long fsize; struct msginfo M; - memset(&M,0,sizeof(M)); - srand((int32_t)time(NULL)); - if ( (hushdex= filestr(&fsize,fname)) == 0 ) - { - fprintf(stderr,"cant load %s file\n",fname); - exit(-1); - } - if ( (SUBATOMIC_json= cJSON_Parse(hushdex)) == 0 ) - { - fprintf(stderr,"cant parse hushdex.json file (%s)\n",hushdex); - exit(-1); - } - free(hushdex); - if ( argc >= 4 ) - { - if ( dpow_pubkey() < 0 ) - { - fprintf(stderr,"couldnt set pubkey for ZEX\n"); - return(-1); - } - coin = (char *)argv[1]; - if ( argv[2][0] != 0 ) { - REFCOIN_CLI = (char *)argv[2]; - } else { - acname = coin; - } - hashstr = (char *)argv[3]; - strcpy(M.rel.coin,hushdex_checkname(tmpstr,&M,1,coin)); - strcpy(M.rel.name,coin); - if ( argc == 4 && strlen(hashstr) == 64 ) // for blocknotify usage, seems not needed - { - height = get_coinheight(coin,acname,&blockhash); - bits256_str(checkstr,blockhash); - if ( strcmp(checkstr,hashstr) == 0 ) - { - fprintf(stderr,"%s: (%s) %s height.%d\n",coin,REFCOIN_CLI!=0?REFCOIN_CLI:"",checkstr,height); - if ( (retjson= dpow_ntzdata(coin,SUBATOMIC_PRIORITY,height,blockhash)) != 0 ) - free_json(retjson); - } else fprintf(stderr,"coin.%s (%s) %s vs %s, height.%d\n",coin,REFCOIN_CLI!=0?REFCOIN_CLI:"",checkstr,hashstr,height); - if ( strcmp("BTC",coin) != 0 ) - { - bits256 prevntzhash,ntzhash; int32_t prevntzheight,ntzheight; uint32_t ntztime,prevntztime; char hexstr[81]; cJSON *retjson2; - prevntzhash = dpow_ntzhash(coin,&prevntzheight,&prevntztime); - if ( (retjson= get_getinfo(coin,acname)) != 0 ) - { - ntzheight = juint(retjson,"notarized"); - ntzhash = jbits256(retjson,"notarizedhash"); - if ( ntzheight > prevntzheight ) - { - get_coinmerkleroot(coin,acname,ntzhash,&ntztime); - fprintf(stderr,"NOTARIZATION %s.%d %s t.%u\n",coin,ntzheight,bits256_str(str,ntzhash),ntztime); - bits256_str(hexstr,ntzhash); - sprintf(&hexstr[64],"%08x",ntzheight); - sprintf(&hexstr[72],"%08x",ntztime); - hexstr[80] = 0; - if ( (retjson2= dpow_broadcast(SUBATOMIC_PRIORITY,hexstr,coin,"notarizations",DPOW_pubkeystr,"","")) != 0 ) - free_json(retjson2); - } - else if ( ntzheight == prevntzheight && memcmp(&prevntzhash,&ntzhash,32) != 0 ) - fprintf(stderr,"NTZ ERROR %s.%d %s != %s\n",coin,ntzheight,bits256_str(str,ntzhash),bits256_str(str2,prevntzhash)); - free_json(retjson); - } - } - } - else if ( argc == 5 && atol(hashstr) > 10000 ) - { - char checkstr[32]; uint64_t mult = 1; - M.origid = (uint32_t)atol(hashstr); - sprintf(checkstr,"%u",M.origid); - if ( strcmp(checkstr,hashstr) == 0 ) // alice - { - M.rel.satoshis = (uint64_t)(atof(argv[4])*SATOSHIDEN+0.0000000049999); - for (i=0; M.rel.name[i]!=0; i++) - if ( M.rel.name[i] == '.' ) - { - mult = SATOSHIDEN; - break; - } - if ( hushdex_getbalance(&M.rel) < M.rel.satoshis/mult ) - { - fprintf(stderr,"not enough balance %s %.8f for %.8f\n",M.rel.coin,dstr(hushdex_getbalance(&M.rel)),dstr(M.rel.satoshis/mult)); - return(-1); - } - fprintf(stderr,"hushdex_channel_alice (%s/%s) %s %u with %.8f %llu\n",M.rel.name,M.rel.coin,hashstr,M.origid,atof(argv[4]),(long long)M.rel.satoshis); - dpow_pubkeyregister(SUBATOMIC_PRIORITY); - M.openrequestid = hushdex_alice_openrequest(&M); - if ( M.openrequestid != 0 ) - hushdex_loop(&M); - } else fprintf(stderr,"checkstr mismatch %s %s != %s\n",coin,hashstr,checkstr); - } - else - { - M.bobflag = 1; - strcpy(M.base.name,hashstr); - strcpy(M.base.coin,hushdex_checkname(tmpstr,&M,0,hashstr)); - hushdex_loop(&M); // while ( 1 ) loop for each relcoin -> basecoin - } - } - return(SUBATOMIC_retval); -} - diff --git a/src/cc/dapps/hushdex.json b/src/cc/dapps/hushdex.json deleted file mode 100644 index dbb7df058..000000000 --- a/src/cc/dapps/hushdex.json +++ /dev/null @@ -1,19 +0,0 @@ -{ -"authorized": [ - {"dukeleto":"030554bffcf6dfcb34a20c486ff0a5be5546b9cc16fba969216527263f8e98c4af" }, - {"gilardh":"020554bffcf6dfcb34a20c486ff5a5be5546b9cc06fba9692165272b3f8e98c448" }, - {"nhdigitalcash":"030554bffcf6dfcb34a20c086ff5a5be5546b9cc16fba9692105272b3f8e98c4a0" }, - {"miodrag":"02b25de3ee5335518b06f69f4fbabb029cfc737603b100996841d5532b324a5a61" } -], -"tokens":[ -], -"files":[ - {"filename":"hushd","prices":[{"HUSH":0.1}, {"ZEC":1}]} -], -"externalcoins":[ - { "BTC":"bitcoin-cli" }, - { "HUSH":"hush-cli" }, - { "ZEC":"zcash-cli" } -] -} - diff --git a/src/cc/dapps/makedapps b/src/cc/dapps/makedapps deleted file mode 100755 index 3a86f68da..000000000 --- a/src/cc/dapps/makedapps +++ /dev/null @@ -1,2 +0,0 @@ -gcc -o oraclefeed cc/dapps/oraclefeed.c -lm -gcc -o zmigrate cc/dapps/zmigrate.c -lm diff --git a/src/cc/dapps/zmigrate.c b/src/cc/dapps/zmigrate.c deleted file mode 100644 index 4ccbc3636..000000000 --- a/src/cc/dapps/zmigrate.c +++ /dev/null @@ -1,1529 +0,0 @@ -// Copyright (c) 2016-2024 The Hush developers -// Distributed under the GPLv3 software license, see the accompanying -// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html -/****************************************************************************** - * 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 -#include -#include "cJSON.c" - -/* -NOTE: HUSH nor any Hush Arrakis Chain has any sprout outputs. This code is kept for historical and educational purposes. - - 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; - -char hexbyte(int32_t c) -{ - c &= 0xf; - if ( c < 10 ) - return('0'+c); - else if ( c < 16 ) - return('a'+c-10); - else return(0); -} - -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(unsigned char *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 ( 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); -} - -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); -} - -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; i0; i--) - str[i] = str[i-1]; - str[0] = '/'; - str[n+1] = 0; - }*/ -#endif - return(str); -#endif -} - -void *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(portable_path(fname),"rb")) != 0 ) - { - fseek(fp,0,SEEK_END); - filesize = ftell(fp); - if ( filesize == 0 ) - { - fclose(fp); - *lenp = 0; - printf("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); -} - -void *filestr(long *allocsizep,char *_fname) -{ - long filesize = 0; char *fname,*buf = 0; void *retptr; - *allocsizep = 0; - fname = malloc(strlen(_fname)+1); - strcpy(fname,_fname); - retptr = loadfile(fname,(uint8_t **)&buf,&filesize,allocsizep); - free(fname); - return(retptr); -} - -char *send_curl(char *url,char *fname) -{ - long fsize; char curlstr[1024]; - sprintf(curlstr,"curl --url \"%s\" > %s",url,fname); - system(curlstr); - return(filestr(&fsize,fname)); -} - -cJSON *get_urljson(char *url,char *fname) -{ - char *jsonstr; cJSON *json = 0; - if ( (jsonstr= send_curl(url,fname)) != 0 ) - { - //printf("(%s) -> (%s)\n",url,jsonstr); - json = cJSON_Parse(jsonstr); - free(jsonstr); - } - return(json); -} - -////////////////////////////////////////////// -// start of dapp -////////////////////////////////////////////// - -char *REFCOIN_CLI; - -cJSON *get_hushcli(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/zmigrate.%s",method); - if ( acname[0] != 0 ) - { - if ( refcoin[0] != 0 && strcmp(refcoin,"HUSH3") != 0 ) - printf("unexpected: refcoin.(%s) acname.(%s)\n",refcoin,acname); - sprintf(cmdstr,"./hush-cli -ac_name=%s %s %s %s %s %s > %s\n",acname,method,arg0,arg1,arg2,arg3,fname); - } - else if ( strcmp(refcoin,"HUSH3") == 0 ) - sprintf(cmdstr,"./hush-cli %s %s %s %s %s > %s\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); - //printf("ref.(%s) REFCOIN_CLI (%s)\n",refcoin,cmdstr); - } - 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 ) - *retstrp = jsonstr; - else free(jsonstr); - } - return(retjson); -} - -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_hushcli(refcoin,&retstr,acname,"sendtoaddress",destaddr,numstr,"","")) != 0 ) - { - fprintf(stderr,"unexpected sendrawtransaction 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; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getblockchaininfo","","","","")) != 0 ) - { - height = jint(retjson,"blocks"); - free_json(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"%s get_coinheight.(%s) error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(height); -} - -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_hushcli(refcoin,&retstr,acname,"getblockhash",heightstr,"","","")) != 0 ) - { - fprintf(stderr,"unexpected blockhash json.(%s)\n",jprint(retjson,0)); - free_json(retjson); - } - else if ( retstr != 0 ) - { - if ( strlen(retstr) >= 64 ) - { - retstr[64] = 0; - decode_hex(hash.bytes,32,retstr); - } - free(retstr); - } - return(hash); -} - -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_hushcli(refcoin,&retstr,acname,"getblockheader",bits256_str(str,blockhash),"","","")) != 0 ) - { - merkleroot = jbits256(retjson,"merkleroot"); - //fprintf(stderr,"got merkleroot.(%s)\n",bits256_str(str,merkleroot)); - free_json(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"%s %s get_coinmerkleroot error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(merkleroot); -} - -int32_t get_coinheader(char *refcoin,char *acname,bits256 *blockhashp,bits256 *merklerootp,int32_t prevheight) -{ - int32_t height = 0; char str[65]; - if ( prevheight == 0 ) - height = get_coinheight(refcoin,acname) - 20; - else height = prevheight + 1; - if ( height > 0 ) - { - *blockhashp = get_coinblockhash(refcoin,acname,height); - if ( bits256_nonz(*blockhashp) != 0 ) - { - *merklerootp = get_coinmerkleroot(refcoin,acname,*blockhashp); - if ( bits256_nonz(*merklerootp) != 0 ) - return(height); - } - } - memset(blockhashp,0,sizeof(*blockhashp)); - memset(merklerootp,0,sizeof(*merklerootp)); - return(0); -} - -cJSON *get_rawmempool(char *refcoin,char *acname) -{ - cJSON *retjson; char *retstr; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getrawmempool","","","","")) != 0 ) - { - //printf("mempool.(%s)\n",jprint(retjson,0)); - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"get_rawmempool.(%s) error.(%s)\n",acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *get_addressutxos(char *refcoin,char *acname,char *coinaddr) -{ - cJSON *retjson; char *retstr,jsonbuf[256]; - if ( refcoin[0] != 0 && strcmp(refcoin,"HUSH3") != 0 ) - printf("warning: assumes %s has addressindex enabled\n",refcoin); - sprintf(jsonbuf,"{\\\"addresses\\\":[\\\"%s\\\"]}",coinaddr); - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getaddressutxos",jsonbuf,"","","")) != 0 ) - { - //printf("addressutxos.(%s)\n",jprint(retjson,0)); - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"get_addressutxos.(%s) error.(%s)\n",acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *get_rawtransaction(char *refcoin,char *acname,bits256 txid) -{ - cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getrawtransaction",bits256_str(str,txid),"1","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"get_rawtransaction.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *get_listunspent(char *refcoin,char *acname) -{ - cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"listunspent","","","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"get_listunspent.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *z_listunspent(char *refcoin,char *acname) -{ - cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_listunspent","","","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"z_listunspent.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *z_listoperationids(char *refcoin,char *acname) -{ - cJSON *retjson; char *retstr,str[65]; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_listoperationids","","","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"z_listoperationids.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *z_getoperationstatus(char *refcoin,char *acname,char *opid) -{ - cJSON *retjson; char *retstr,str[65],params[512]; - sprintf(params,"'[\"%s\"]'",opid); - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_getoperationstatus",params,"","","")) != 0 ) - { - //printf("got status (%s)\n",jprint(retjson,0)); - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"z_getoperationstatus.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -cJSON *z_getoperationresult(char *refcoin,char *acname,char *opid) -{ - cJSON *retjson; char *retstr,str[65],params[512]; - sprintf(params,"'[\"%s\"]'",opid); - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_getoperationresult",params,"","","")) != 0 ) - { - return(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"z_getoperationresult.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return(0); -} - -int32_t validateaddress(char *refcoin,char *acname,char *depositaddr, char* compare) -{ - cJSON *retjson; char *retstr; int32_t res=0; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"validateaddress",depositaddr,"","","")) != 0 ) - { - 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); - } - return (res); -} - -int32_t z_validateaddress(char *refcoin,char *acname,char *depositaddr, char *compare) -{ - cJSON *retjson; char *retstr; int32_t res=0; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_validateaddress",depositaddr,"","","")) != 0 ) - { - if (is_cJSON_True(jobj(retjson,compare)) != 0 ) - res=1; - free_json(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"z_validateaddress.(%s) %s error.(%s)\n",refcoin,acname,retstr); - free(retstr); - } - return (res); -} - -int64_t z_getbalance(char *refcoin,char *acname,char *coinaddr) -{ - cJSON *retjson; char *retstr,cmpstr[64]; int64_t amount=0; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_getbalance",coinaddr,"","","")) != 0 ) - { - fprintf(stderr,"z_getbalance.(%s) %s returned json!\n",refcoin,acname); - free_json(retjson); - } - else if ( retstr != 0 ) - { - amount = atof(retstr) * SATOSHIDEN; - sprintf(cmpstr,"%.8f",dstr(amount)); - if ( strcmp(retstr,cmpstr) != 0 ) - amount++; - //printf("retstr %s -> %.8f\n",retstr,dstr(amount)); - free(retstr); - } - 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_hushcli(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); - } - return(-1); -} - -int32_t getnewaddress(char *coinaddr,char *refcoin,char *acname) -{ - cJSON *retjson; char *retstr; int64_t amount=0; int32_t retval = -1; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"getnewaddress","","","","")) != 0 ) - { - fprintf(stderr,"getnewaddress.(%s) %s returned json!\n",refcoin,acname); - free_json(retjson); - } - else if ( retstr != 0 ) - { - strcpy(coinaddr,retstr); - free(retstr); - retval = 0; - } - return(retval); -} - -int32_t z_getnewaddress(char *coinaddr,char *refcoin,char *acname,char *typestr) -{ - cJSON *retjson; char *retstr; int64_t amount=0; int32_t retval = -1; - if ( (retjson= get_hushcli(refcoin,&retstr,acname,"z_getnewaddress",typestr,"","","")) != 0 ) - { - fprintf(stderr,"z_getnewaddress.(%s) %s returned json!\n",refcoin,acname); - free_json(retjson); - } - else if ( retstr != 0 ) - { - strcpy(coinaddr,retstr); - free(retstr); - retval = 0; - } - return(retval); -} - -int64_t find_onetime_amount(char *coinstr,char *coinaddr) -{ - cJSON *array,*item; int32_t i,n; char *addr; int64_t amount = 0; - 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 0 ) - { - for (i=0; i %s\n",srcaddr,params); - if ( (retjson= get_hushcli(coinstr,&retstr,acname,"z_sendmany",addr,params,"","")) != 0 ) - { - printf("unexpected json z_sendmany.(%s)\n",jprint(retjson,0)); - free_json(retjson); - } - else if ( retstr != 0 ) - { - fprintf(stderr,"z_sendmany.(%s) -> opid.(%s)\n",coinstr,retstr); - strcpy(opidstr,retstr); - free(retstr); - retval = 0; - } - 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\\\"]"); - if ( (retjson= get_hushcli(coinstr,&retstr,acname,"z_mergetoaddress",addr,destaddr,"","")) != 0 ) - { - 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; - if ( (array= get_rawmempool(coinstr,acname)) != 0 ) - { - if ( (n= cJSON_GetArraySize(array)) > 0 ) - return(0); - free_json(array); - return(1); - } - return(-1); -} - -cJSON *getinputarray(int64_t *totalp,cJSON *unspents,int64_t required) -{ - cJSON *vin,*item,*vins = cJSON_CreateArray(); int32_t i,n,v; int64_t satoshis; bits256 txid; - *totalp = 0; - if ( (n= cJSON_GetArraySize(unspents)) > 0 ) - { - for (i=0; i= required ) - break; - } - } - } - return(vins); -} - -int32_t tx_has_voutaddress(char *refcoin,char *acname,bits256 txid,char *coinaddr) -{ - cJSON *txobj,*vouts,*vout,*vins,*vin,*sobj,*addresses; char *addr,str[65]; int32_t i,j,n,numarray,retval = 0, hasvout=0; - if ( (txobj= get_rawtransaction(refcoin,acname,txid)) != 0 ) - { - if ( (vouts= jarray(&numarray,txobj,"vout")) != 0 ) - { - for (i=0; i 0 ) - { - for (i=0; i 0 ) - { - for (j=0; j 0 && strcmp(vinaddr,cmpaddr) == 0 ) - return(0); - printf("mismatched vinaddr.(%s) vs %s\n",vinaddr,cmpaddr); - } - } - return(-1); -} - -int32_t txid_in_vins(char *refcoin,bits256 txid,bits256 cmptxid) -{ - cJSON *txjson,*vins,*vin; int32_t numvins,v,vinvout; bits256 vintxid; char str[65]; - if ( (txjson= get_rawtransaction(refcoin,"",txid)) != 0 ) - { - if ( (vins= jarray(&numvins,txjson,"vin")) != 0 ) - { - for (v=0; vrefundvalue < 0 ) - return(-1); - - sprintf(url,"https://explorer.hush.is/api/addr/%s",item->destaddr); - if ( (retstr= send_curl(url,"/tmp/itemvalid")) != 0 ) - { - if ( (curljson= cJSON_Parse(retstr)) != 0 ) - { - if ( (txids= jarray(&numtxids,curljson,"transactions")) != 0 ) - { - for (i=0; itxid) == 0 ) - { - printf("found item->txid %s inside %s\n",bits256_str(str,item->txid),bits256_str(str2,txid)); - item->approved = 1; - break; - } - } - } - free_json(curljson); - } - printf("%s\n",retstr); - free(retstr); - } - if ( item->approved != 0 ) - return(1); - *waitingp = item->refundvalue; - return(-1); -} - -void scan_claims(int32_t issueflag,char *refcoin,int32_t batchid) -{ - char str[65]; int32_t i,num,numstolen=0,numcandidates=0,numinvalids=0,numrefunded=0,numwaiting=0; struct claimitem *item; int64_t batchmin,batchmax,waiting,refunded,possiblerefund=0,possiblestolen = 0,invalidsum=0,totalrefunded=0,waitingsum=0; - if ( batchid == 0 ) - { - batchmin = 0; - batchmax = 7 * SATOSHIDEN; - } - else if ( batchid == 1 ) - { - batchmin = 7 * SATOSHIDEN; - batchmax = 777 * SATOSHIDEN; - } - else if ( batchid == 2 ) - { - batchmin = 1;//777 * SATOSHIDEN; - batchmax = 5000 * SATOSHIDEN; - } - else if ( batchid == 3 ) - { - batchmin = 1;//117777 * SATOSHIDEN; - batchmax = 10000000 * SATOSHIDEN; - } - for (i=0; irefundvalue < batchmin || item->refundvalue >= batchmax ) - continue; - printf("check.%d %s %.8f vs refund %.8f -> %s\n",batchid,item->oldaddr,dstr(item->total),dstr(item->refundvalue),item->destaddr); - if ( itemvalid(refcoin,&refunded,&waiting,item) < 0 ) - { - if ( refunded != 0 ) - { - numrefunded++; - totalrefunded += refunded; - } - else if ( waiting != 0 ) - { - numwaiting++; - waitingsum += waiting; - } - else - { - invalidsum += item->refundvalue; - numinvalids++; - } - continue; - } - if ( item->total > item->refundvalue*1.1 + 10*SATOSHIDEN ) - { - printf("possible.%d stolen %s %.8f vs refund %.8f -> %.8f\n",batchid,item->oldaddr,dstr(item->total),dstr(item->refundvalue),dstr(item->total)-dstr(item->refundvalue)); - numstolen++; - possiblestolen += (item->total - item->refundvalue); - item->approved = 0; - } - else - { - printf("candidate.%d %s %.8f vs refund %.8f -> %s\n",batchid,item->oldaddr,dstr(item->total),dstr(item->refundvalue),item->destaddr); - numcandidates++; - possiblerefund += item->refundvalue; - } - } - printf("batchid.%d TOTAL exposure %d %.8f, possible refund %d %.8f, invalids %d %.8f, numrefunded %d %.8f, waiting %d %.8f\n",batchid,numstolen,dstr(possiblestolen),numcandidates,dstr(possiblerefund),numinvalids,dstr(invalidsum),numrefunded,dstr(totalrefunded),numwaiting,dstr(waitingsum)); - for (i=num=0; iapproved != 0 ) - { - printf("%d.%d: approved.%d %s %.8f vs refund %.8f -> %s\n",i,num,batchid,item->oldaddr,dstr(item->total),dstr(item->refundvalue),item->destaddr); - num++; - if ( issueflag != 0 ) - { - static FILE *fp; char cmd[1024]; - if ( fp == 0 ) - fp = fopen("refund.log","wb"); - genrefund(cmd,refcoin,item->txid,item->destaddr,item->refundvalue); - if ( fp != 0 ) - { - fprintf(fp,"%s,%s,%s,%s,%s,%.8f,%s\n",item->username,refcoin,bits256_str(str,item->txid),item->oldaddr,item->destaddr,dstr(item->refundvalue),cmd); - fflush(fp); - } - memset(&SECONDVIN,0,sizeof(SECONDVIN)); - SECONDVOUT = 1; -//printf(">>>>>>>>>>>>>>>>>> getchar after (%s)\n",cmd); -//getchar(); - } - } - } -} - -int32_t update_claimvalue(int32_t *disputedp,char *addr,int64_t amount,bits256 txid) -{ - int32_t i; struct claimitem *item; - *disputedp = 0; - for (i=0; irefundvalue = amount; - if ( bits256_nonz(item->txid) != 0 ) - printf("disputed.%d (%s) %s claimed %.8f vs %.8f\n",item->disputed,item->username,addr,dstr(item->total),dstr(amount)); - item->txid = txid; - if ( item->disputed != 0 ) - *disputedp = 1; - return(i); - } - } - return(-1); -} - -int64_t update_claimstats(char *username,char *oldaddr,char *destaddr,int64_t amount) -{ - int32_t i; struct claimitem *item; - printf("claim user.(%s) (%s) -> (%s) %.8f\n",username,oldaddr,destaddr,dstr(amount)); - for (i=0; idestaddr) != 0 )//|| strcmp(username,item->username) != 0 ) - { - item->disputed++; - printf("disputed.%d claim.%-4d: (%36s -> [%36s] %s) vs. (%36s -> [%36s] %s) \n",item->disputed,i,oldaddr,destaddr,username,item->oldaddr,item->destaddr,item->username); - } - item->numutxos++; - item->total += amount; - return(amount); - } - } - item = &CLAIMS[NUM_CLAIMS++]; - item->total = amount; - item->numutxos = 1; - strncpy(item->oldaddr,oldaddr,sizeof(item->oldaddr)); - strncpy(item->destaddr,destaddr,sizeof(item->destaddr)); - strncpy(item->username,username,sizeof(item->username)); - printf("new claim.%-4d: %36s %16.8f -> %36s %s\n",NUM_CLAIMS,oldaddr,dstr(amount),destaddr,username); - return(amount); -} - -int32_t update_addrstats(char *srcaddr,int64_t amount) -{ - int32_t i; struct addritem *item; - for (i=0; itotal = amount; - item->numutxos = 1; - strcpy(item->addr,srcaddr); - printf("%d new address %s\n",NUM_ADDRESSES,srcaddr); - return(-1); -} - -int64_t sum_of_vins(char *refcoin,int32_t *totalvinsp,int32_t *uniqaddrsp,bits256 txid) -{ - cJSON *txjson,*vins,*vin; char str[65],srcaddr[64]; int32_t i,numarray; int64_t amount,total = 0; - if ( (txjson= get_rawtransaction(refcoin,"",txid)) != 0 ) - { - if ( (vins= jarray(&numarray,txjson,"vin")) != 0) - { - for (i=0; i 0 ) - { - printf("%d.(%s)\n",numlines,buf); - str = buf; - n = i = 0; - memset(fields,0,sizeof(fields)); - while ( *str != 0 ) - { - if ( *str == ',' || *str == '\n' || *str == '\r' ) - { - fields[n][i] = 0; - i = 0; - if ( n > 1 ) - { - printf("(%16s) ",fields[n]); - } - n++; - if ( *str == '\n' || *str == '\r' ) - break; - } - if ( *str == ',' || *str == ' ' ) - str++; - else fields[n][i++] = *str++; - } - printf("%s\n",fields[1]); - total += update_claimstats(fields[1],fields[3],fields[5 + (strcmp("HUSH3",refcoin)==0)],atof(fields[4])*SATOSHIDEN + 0.0000000049); - numlines++; - } - fclose(fp); - } - printf("total claims %.8f\n",dstr(total)); -} - -int32_t main(int32_t argc,char **argv) -{ - char *coinstr,*acstr,*addr,buf[64],srcaddr[64],str[65]; cJSON *retjson,*item; int32_t i,n,disputed,numdisputed,numsmall=0,numpayouts=0,numclaims=0,num=0,totalvins=0,uniqaddrs=0; int64_t amount,total = 0,total2 = 0,payout,maxpayout,smallpayout=0,totalpayout = 0,totaldisputed = 0,totaldisputed2 = 0,fundingamount = 0; - if ( argc != 2 ) - { - printf("argc needs to be 2: coin\n"); - return(-1); - } - if ( strcmp(argv[1],"HUSH3") == 0 ) - { - REFCOIN_CLI = "./hush-cli"; - coinstr = clonestr("HUSH3"); - acstr = ""; - } - else - { - sprintf(buf,"./hush-cli -ac_name=%s",argv[1]); - REFCOIN_CLI = clonestr(buf); - coinstr = clonestr(argv[1]); - acstr = coinstr; - } - if ( 1 ) - { - sprintf(buf,"%s-Claims.csv",coinstr); - reconcile_claims(coinstr,buf); - for (i=0; i 0 ) - { - for (i=0; i fundingamount ) - { - fundingamount = amount; - SECONDVIN = jbits256(item,"txid"); - SECONDVOUT = jint(item,"vout"); - printf("set SECONDVIN to %s/v%d %.8f\n",bits256_str(str,SECONDVIN),SECONDVOUT,dstr(amount)); - } - continue; - } - if ( strcmp(coinstr,"HUSH3") == 0 && verify_vin(coinstr,jbits256(item,"txid"),0,"R9JCEd6xnCxNUSpLrHEWvzPSh7CNXm7z75") < 0 ) - { - printf("WARNING: imposter dust detected! %s\n",bits256_str(str,jbits256(item,"txid"))); - continue; - } - else if ( strcmp(coinstr,"HUSH3") != 0 && verify_vin(coinstr,jbits256(item,"txid"),0,"R9MUnxXijovvSeT9sFuUX23TiFtVvZEGjT") < 0 ) - { - printf("WARNING: imposter dust detected! %s\n",bits256_str(str,jbits256(item,"txid"))); - continue; - } - amount = (utxo_value(coinstr,srcaddr,jbits256(item,"txid"),0) - 20000) * SATOSHIDEN; - //printf("%d: %s claimvalue %.8f\n",num,srcaddr,dstr(amount)); - num++; - total2 += amount; - if ( update_claimvalue(&disputed,srcaddr,amount,jbits256(item,"txid")) >= 0 ) - { - if ( disputed != 0 ) - { - totaldisputed2 += amount; - numdisputed++; - } - else - { - numclaims++; - total += amount; - } - } - } - } - } - free_json(retjson); - printf("remaining refunds.%d %.8f, numclaims.%d %.8f, numdisputed.%d %.8f\n",num,dstr(total2),numclaims,dstr(total),numdisputed,dstr(totaldisputed2)); - } - //scan_claims(0,coinstr,0); - //scan_claims(0,coinstr,1); - //scan_claims(0,coinstr,2); - scan_claims(1,coinstr,3); - } - else if ( (retjson= get_listunspent(coinstr,acstr)) != 0 ) - { - if ( (n= cJSON_GetArraySize(retjson)) > 0 ) - { - for (i=0; i= SATOSHIDEN ) - { - payout = ADDRESSES[i].total / SATOSHIDEN; - if ( payout > maxpayout ) - maxpayout = payout; - totalpayout += payout; - numpayouts++; - //if ( payout >= 7 ) - //{ - // numsmall++; - //smallpayout += payout; - genpayout(coinstr,ADDRESSES[i].addr,payout); - //} - //printf("%-4d: %-64s numutxos.%-4lld %llu\n",i,ADDRESSES[i].addr,ADDRESSES[i].numutxos,(long long)payout); - } - } - printf("num.%d total %.8f vs vintotal %.8f, totalvins.%d uniqaddrs.%d:%d totalpayout %llu maxpayout %llu numpayouts.%d numsmall.%d %llu\n",num,dstr(total),dstr(total2),totalvins,uniqaddrs,NUM_ADDRESSES,(long long)totalpayout,(long long)maxpayout,numpayouts,numsmall,(long long)smallpayout); - } -} - -int32_t zmigratemain(int32_t argc,char **argv) -{ - char buf[1024],*zsaddr,*coinstr; - if ( argc != 3 ) - { - printf("argc needs to be 3\n"); - return(-1); - } - if ( strcmp(argv[1],"HUSH3") == 0 ) - { - REFCOIN_CLI = "./hush-cli"; - coinstr = clonestr("HUSH3"); - } - else - { - sprintf(buf,"./hush-cli -ac_name=%s",argv[1]); - REFCOIN_CLI = clonestr(buf); - coinstr = clonestr(argv[1]); - } - if ( argv[2][0] != 'z' || argv[2][1] != 's' ) - { - printf("invalid sapling address (%s)\n",argv[2]); - return(-2); - } - if ( z_validateaddress(coinstr,"",argv[2],"ismine") == 0 ) - { - printf("invalid sapling address (%s)\n",argv[2]); - return(-3); - } - zsaddr = clonestr(argv[2]); - printf("%s: %s %s\n",REFCOIN_CLI,coinstr,zsaddr); - 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; - while ( 1 ) - { - if ( have_pending_opid(coinstr,0) != 0 ) - { - sleep(10); - continue; - } - if ( (amount= find_onetime_amount(coinstr,coinaddr)) > txfee ) - { - // find taddr with funds and send all to zsaddr - z_sendmany(opidstr,coinstr,"",coinaddr,zsaddr,amount-txfee); - lastopid = (uint32_t)time(NULL); - sleep(1); - continue; - } - if ( (amount= find_sprout_amount(coinstr,zcaddr)) > txfee ) - { - // generate taddr, send max of 10000.0001 - 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 < SATOSHIDEN ) - { - stdamount = SATOSHIDEN; - refamount = SATOSHIDEN * 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(3); - continue; - } - if ( time(NULL) > lastopid+600 ) - break; - } - sleep(3); - printf("%s %s ALLDONE! taddr %.8f sprout %.8f mempool empty.%d\n",coinstr,zsaddr,dstr(find_onetime_amount(coinstr,coinaddr)),dstr(find_sprout_amount(coinstr,zcaddr)),empty_mempool(coinstr,"")); - sleep(3); - if ( find_onetime_amount(coinstr,coinaddr) == 0 && find_sprout_amount(coinstr,zcaddr) == 0 ) - { - printf("about to purge all opid results!. ctrl-C to abort, to proceed\n"); - getchar(); - have_pending_opid(coinstr,1); - } else goto again; - return(0); -} diff --git a/src/cc/eval.h b/src/cc/eval.h index d0be279d0..2ca194b61 100644 --- a/src/cc/eval.h +++ b/src/cc/eval.h @@ -80,21 +80,6 @@ public: bool Error(std::string s) { return state.Error(s); } bool Valid() { return true; } - /* - * Dispute a payout using a VM - */ - bool DisputePayout(AppVM &vm, std::vector params, const CTransaction &disputeTx, unsigned int nIn); - - /* - * Test an ImportPayout CC Eval condition - */ - bool ImportPayout(std::vector params, const CTransaction &importTx, unsigned int nIn); - - /* - * Import coin from another chain with same symbol - */ - bool ImportCoin(std::vector params, const CTransaction &importTx, unsigned int nIn); - /* * IO functions */ @@ -281,7 +266,6 @@ typedef std::pair TxProof; uint256 GetMerkleRoot(const std::vector& vLeaves); struct CCcontract_info *CCinit(struct CCcontract_info *cp,uint8_t evalcode); -bool ProcessCC(struct CCcontract_info *cp,Eval* eval, std::vector paramsNull, const CTransaction &tx, unsigned int nIn); #endif /* CC_EVAL_H */ diff --git a/src/coins.cpp b/src/coins.cpp index 1e5bff4e3..2940137ca 100644 --- a/src/coins.cpp +++ b/src/coins.cpp @@ -214,19 +214,6 @@ void CCoinsViewCache::AbstractPushAnchor( } } -//TODO: delete -/* -template<> void CCoinsViewCache::PushAnchor(const SproutMerkleTree &tree) -{ - AbstractPushAnchor( - tree, - SPROUT, - cacheSproutAnchors, - hashSproutAnchor - ); -} -*/ - template<> void CCoinsViewCache::PushAnchor(const SaplingMerkleTree &tree) { AbstractPushAnchor( diff --git a/src/hush_nSPV.h b/src/hush_nSPV.h index bf559e8ce..4d7dc4555 100644 --- a/src/hush_nSPV.h +++ b/src/hush_nSPV.h @@ -568,8 +568,6 @@ uint256 NSPV_opretextract(int32_t *heightp,uint256 *blockhashp,char *symbol,std: ((uint8_t *)blockhashp)[i] = opret[i]; for (i=0; i<32; i++) ((uint8_t *)&desttxid)[i] = opret[4 + 32 + i]; - if ( 0 && *heightp != 2690 ) - fprintf(stderr," ntzht.%d %s <- txid.%s size.%d\n",*heightp,(*blockhashp).GetHex().c_str(),(txid).GetHex().c_str(),(int32_t)opret.size()); return(desttxid); } diff --git a/src/hush_nSPV_fullnode.h b/src/hush_nSPV_fullnode.h index 53817725c..e08ebdd7b 100644 --- a/src/hush_nSPV_fullnode.h +++ b/src/hush_nSPV_fullnode.h @@ -675,8 +675,6 @@ void hush_nSPVreq(CNode *pfrom,std::vector request) // received a reque dragon_rwnum(0,&request[len-8],sizeof(skipcount),&skipcount); dragon_rwnum(0,&request[len-4],sizeof(filter),&filter); } - if ( 0 && isCC != 0 ) - fprintf(stderr,"utxos %s isCC.%d skipcount.%d filter.%x\n",coinaddr,isCC,skipcount,filter); memset(&U,0,sizeof(U)); if ( (slen= NSPV_getaddressutxos(&U,coinaddr,isCC,skipcount,filter)) > 0 ) { @@ -715,8 +713,6 @@ void hush_nSPVreq(CNode *pfrom,std::vector request) // received a reque dragon_rwnum(0,&request[len-8],sizeof(skipcount),&skipcount); dragon_rwnum(0,&request[len-4],sizeof(filter),&filter); } - if ( 0 && isCC != 0 ) - fprintf(stderr,"txids %s isCC.%d skipcount.%d filter.%d\n",coinaddr,isCC,skipcount,filter); memset(&T,0,sizeof(T)); if ( (slen= NSPV_getaddresstxids(&T,coinaddr,isCC,skipcount,filter)) > 0 ) { diff --git a/src/net.cpp b/src/net.cpp index c4d1b3e86..b508122e6 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -1722,7 +1722,6 @@ void ThreadOpenConnections() boost::this_thread::interruption_point(); // Add seed nodes if DNS seeds are all down (an infrastructure attack?). - // if (addrman.size() == 0 && (GetTime() - nStart > 60)) { if (GetTime() - nStart > 60) { static bool done = false; if (!done) { diff --git a/src/pow.cpp b/src/pow.cpp index 8ac7fc596..a4e10e2b4 100644 --- a/src/pow.cpp +++ b/src/pow.cpp @@ -97,76 +97,6 @@ bnTarget = RT_CST_RST (bnTarget, ts, cw, numerator, denominator, W, T, past); #define T ASSETCHAINS_BLOCKTIME #define K ((int64_t)1000000) -#ifdef original_algo -arith_uint256 oldRT_CST_RST(int32_t height,uint32_t nTime,arith_uint256 bnTarget,uint32_t *ts,arith_uint256 *ct,int32_t numerator,int32_t denominator,int32_t W,int32_t past) -{ - //if (ts.size() < 2*W || ct.size() < 2*W ) { exit; } // error. a vector was too small - //if (ts.size() < past+W || ct.size() < past+W ) { past = min(ct.size(), ts.size()) - W; } // past was too small, adjust - int64_t altK; int32_t i,j,k,ii=0; // K is a scaling factor for integer divisions - if ( height < 64 ) - return(bnTarget); - //if ( ((ts[0]-ts[W]) * W * 100)/(W-1) < (T * numerator * 100)/denominator ) - if ( (ts[0] - ts[W]) < (T * numerator)/denominator ) - { - //bnTarget = ((ct[0]-ct[1])/K) * max(K,(K*(nTime-ts[0])*(ts[0]-ts[W])*denominator/numerator)/T/T); - bnTarget = ct[0] / arith_uint256(K); - //altK = (K * (nTime-ts[0]) * (ts[0]-ts[W]) * denominator * W) / (numerator * (W-1) * (T * T)); - altK = (K * (nTime-ts[0]) * (ts[0]-ts[W]) * denominator) / (numerator * (T * T)); - fprintf(stderr,"ht.%d initial altK.%lld %d * %d * %d / %d\n",height,(long long)altK,(nTime-ts[0]),(ts[0]-ts[W]),denominator,numerator); - if ( altK > K ) - altK = K; - bnTarget *= arith_uint256(altK); - if ( altK < K ) - return(bnTarget); - } - /* Check past 24 blocks for any sum of 3 STs < T/2 triggers. This is messy - because the blockchain does not allow us to store a variable to know - if we are currently in a triggered state that is making a sequence of - adjustments to prevTargets, so we have to look for them. - Nested loops do this: if block emission has not slowed to be back on track at - any time since most recent trigger and we are at current block, aggressively - adust prevTarget. */ - - for (j=past-1; j>=2; j--) - { - if ( ts[j]-ts[j+W] < T*numerator/denominator ) - { - ii = 0; - for (i=j-2; i>=0; i--) - { - ii++; - // Check if emission caught up. If yes, "trigger stopped at i". - // Break loop to try more recent j's to see if trigger activates again. - if ( (ts[i] - ts[j+W]) > (ii+W)*T ) - break; - - // We're here, so there was a TS[j]-TS[j-3] < T/2 trigger in the past and emission rate has not yet slowed up to be back on track so the "trigger is still active", aggressively adjusting target here at block "i" - if ( i == 0 ) - { - /* We made it all the way to current block. Emission rate since - last trigger never slowed enough to get back on track, so adjust again. - If avg last 3 STs = T, this increases target to prevTarget as ST increases to T. - This biases it towards ST=~1.75*T to get emission back on track. - If avg last 3 STs = T/2, target increases to prevTarget at 2*T. - Rarely, last 3 STs can be 1/2 speed => target = prevTarget at T/2, & 1/2 at T.*/ - - //bnTarget = ((ct[0]-ct[W])/W/K) * (K*(nTime-ts[0])*(ts[0]-ts[W]))/W/T/T; - bnTarget = ct[0]; - for (k=1; k=0; z--) - fprintf(stderr,"%02x",((uint8_t *)&bnTarget)[z]); - fprintf(stderr," ht.%d innerK %lld (%d * %d) %u - %u width.%d\n",height,(long long)innerK,(nTime-ts[0]),(ts[0]-ts[width]),ts[0],ts[width],width); - } return(bnTarget); } @@ -509,12 +432,6 @@ unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHead } fprintf(stderr," exp() to the rescue cmp.%d mult.%d for ht.%d\n",mult>1,(int32_t)mult,height); } - if ( 0 && zflags[0] == 0 && zawyflag == 0 && mult <= 1 ) - { - bnTarget = zawy_TSA_EMA(height,tipdiff,(bnTarget+ct[0]+ct[1])/arith_uint256(3),ts[0] - ts[1]); - if ( bnTarget < origtarget ) - zawyflag = 3; - } } nbits = bnTarget.GetCompact(); nbits = (nbits & 0xfffffffc) | zawyflag; diff --git a/src/rpc/client.cpp b/src/rpc/client.cpp index 3dbabf097..970cf704e 100644 --- a/src/rpc/client.cpp +++ b/src/rpc/client.cpp @@ -169,7 +169,6 @@ static const CRPCConvertParam vRPCConvertParams[] = // crosschain { "assetchainproof", 1}, - { "crosschainproof", 1}, { "getproofroot", 2}, { "getNotarizationsForBlock", 0}, { "height_MoM", 1}, diff --git a/src/rpc/crosschain.cpp b/src/rpc/crosschain.cpp index ef6d06db4..1e706130c 100644 --- a/src/rpc/crosschain.cpp +++ b/src/rpc/crosschain.cpp @@ -78,14 +78,6 @@ UniValue assetchainproof(const UniValue& params, bool fHelp, const CPubKey& mypk } -UniValue crosschainproof(const UniValue& params, bool fHelp, const CPubKey& mypk) -{ - UniValue ret(UniValue::VOBJ); - //fprintf(stderr,"crosschainproof needs to be implemented\n"); - return(ret); -} - - UniValue height_MoM(const UniValue& params, bool fHelp, const CPubKey& mypk) { int32_t height,depth,notarized_height,MoMoMdepth,MoMoMoffset,hushstarti,hushendi; uint256 MoM,MoMoM,hushtxid; uint32_t timestamp = 0; UniValue ret(UniValue::VOBJ); UniValue a(UniValue::VARR); diff --git a/src/rpc/net.cpp b/src/rpc/net.cpp index 806ab1ed3..62a04f45b 100644 --- a/src/rpc/net.cpp +++ b/src/rpc/net.cpp @@ -218,7 +218,7 @@ int32_t HUSH_LONGESTCHAIN; static int32_t hush_longest_depth = 0; int32_t hush_longestchain() { - int32_t ht,n=0,num=0,maxheight=0,height = 0; + int32_t ht,num=0,maxheight=0,height = 0; if ( hush_longest_depth < 0 ) hush_longest_depth = 0; if ( hush_longest_depth == 0 ) @@ -231,7 +231,6 @@ int32_t hush_longestchain() } BOOST_FOREACH(const CNodeStats& stats, vstats) { - //fprintf(stderr,"hush_longestchain iter.%d\n",n); CNodeStateStats statestats; bool fStateStats = GetNodeStateStats(stats.nodeid,statestats); if ( statestats.nSyncHeight < 0 ) @@ -251,10 +250,8 @@ int32_t hush_longestchain() height = ht; } hush_longest_depth--; - if ( num > (n >> 1) ) + if ( num > 0 ) { - if ( 0 && height != HUSH_LONGESTCHAIN ) - fprintf(stderr,"set %s HUSH_LONGESTCHAIN <- %d\n",SMART_CHAIN_SYMBOL,height); HUSH_LONGESTCHAIN = height; return(height); } diff --git a/src/rpc/server.cpp b/src/rpc/server.cpp index e473ea785..4a040b1a6 100644 --- a/src/rpc/server.cpp +++ b/src/rpc/server.cpp @@ -335,7 +335,6 @@ static const CRPCCommand vRPCCommands[] = { "crosschain", "calc_MoM", &calc_MoM, true }, { "crosschain", "height_MoM", &height_MoM, true }, { "crosschain", "assetchainproof", &assetchainproof, true }, - { "crosschain", "crosschainproof", &crosschainproof, true }, { "crosschain", "getNotarizationsForBlock", &getNotarizationsForBlock, true }, { "crosschain", "scanNotarizationsDB", &scanNotarizationsDB, true }, diff --git a/src/rpc/server.h b/src/rpc/server.h index e6971294a..a2d5c17cc 100644 --- a/src/rpc/server.h +++ b/src/rpc/server.h @@ -380,7 +380,6 @@ extern UniValue MoMoMdata(const UniValue& params, bool fHelp, const CPubKey& myp extern UniValue calc_MoM(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue height_MoM(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue assetchainproof(const UniValue& params, bool fHelp, const CPubKey& mypk); -extern UniValue crosschainproof(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue getNotarizationsForBlock(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue scanNotarizationsDB(const UniValue& params, bool fHelp, const CPubKey& mypk); extern UniValue getimports(const UniValue& params, bool fHelp, const CPubKey& mypk); diff --git a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp index 93431058b..147d9c4a1 100644 --- a/src/wallet/asyncrpcoperation_saplingconsolidation.cpp +++ b/src/wallet/asyncrpcoperation_saplingconsolidation.cpp @@ -52,7 +52,6 @@ void AsyncRPCOperation_saplingconsolidation::main() { set_error_code(code); set_error_message(message); } catch (const runtime_error& e) { - set_error_code(-1); set_error_code(-1); set_error_message("runtime error: " + string(e.what())); } catch (const logic_error& e) { diff --git a/src/wallet/asyncrpcoperation_shieldcoinbase.cpp b/src/wallet/asyncrpcoperation_shieldcoinbase.cpp index 4e69fc23f..e179f4476 100644 --- a/src/wallet/asyncrpcoperation_shieldcoinbase.cpp +++ b/src/wallet/asyncrpcoperation_shieldcoinbase.cpp @@ -68,7 +68,7 @@ AsyncRPCOperation_shieldcoinbase::AsyncRPCOperation_shieldcoinbase( throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Empty inputs"); } - if (donation < 0 || donation > 10 ) { + if (donation > 10 ) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid donation percentage, must be an integer between 0 and 10 inclusive"); } diff --git a/src/wallet/crypter.h b/src/wallet/crypter.h index d72a8a1b6..427f9e5df 100644 --- a/src/wallet/crypter.h +++ b/src/wallet/crypter.h @@ -165,7 +165,6 @@ private: // .second is the ciphertext. std::pair> cryptedMnemonicEntropy; CryptedKeyMap mapCryptedKeys; - //CryptedSproutSpendingKeyMap mapCryptedSproutSpendingKeys; CryptedSaplingSpendingKeyMap mapCryptedSaplingSpendingKeys; CKeyingMaterial vMasterKey; diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index d5ec44b2a..d1f4232f0 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -4359,7 +4359,7 @@ bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount &nFeeRet, int& nC bool CWallet::CreateTransaction(const vector& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, const CCoinControl* coinControl, bool sign) { - uint64_t interest2 = 0; CAmount nValue = 0; unsigned int nSubtractFeeFromAmount = 0; + CAmount nValue = 0; unsigned int nSubtractFeeFromAmount = 0; BOOST_FOREACH (const CRecipient& recipient, vecSend) { if (nValue < 0 || recipient.nAmount < 0) @@ -4480,7 +4480,6 @@ bool CWallet::CreateTransaction(const vector& vecSend, CWalletTx& wt CAmount nValueIn = 0; bool fOnlyCoinbaseCoins = false; bool fNeedCoinbaseCoins = false; - interest2 = 0; if (!SelectCoins(nTotalValue, setCoins, nValueIn, fOnlyCoinbaseCoins, fNeedCoinbaseCoins, coinControl)) { if (fOnlyCoinbaseCoins && Params().GetConsensus().fCoinbaseMustBeProtected) { @@ -4506,8 +4505,7 @@ bool CWallet::CreateTransaction(const vector& vecSend, CWalletTx& wt dPriority += (double)nCredit * age; } - CAmount nChange = (nValueIn - nValue + interest2); -//fprintf(stderr,"wallet change %.8f (%.8f - %.8f) interest2 %.8f total %.8f\n",(double)nChange/COIN,(double)nValueIn/COIN,(double)nValue/COIN,(double)interest2/COIN,(double)nTotalValue/COIN); + CAmount nChange = (nValueIn - nValue); if (nSubtractFeeFromAmount == 0) nChange -= nFeeRet; diff --git a/src/wallet/walletdb.cpp b/src/wallet/walletdb.cpp index cfe632c48..5537972fa 100644 --- a/src/wallet/walletdb.cpp +++ b/src/wallet/walletdb.cpp @@ -46,8 +46,6 @@ const int CHDChain::CURRENT_VERSION; using namespace std; static uint64_t nAccountingEntryNumber = 0; -static list deadTxns; -extern CBlockIndex *hush_blockindex(uint256 hash); // // CWalletDB @@ -1017,8 +1015,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet) { // Leave other errors alone, if we try to fix them we might make things worse. fNoncriticalErrors = true; // ... but do warn the user there is something wrong. - // set rescan for any error that is not vin-empty on staking chains. - if ( deadTxns.empty() && strType == "tx") + if ( strType == "tx") SoftSetBoolArg("-rescan", true); } } @@ -1034,29 +1031,6 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet) result = DB_CORRUPT; } - if ( !deadTxns.empty() ) - { - // staking chains with vin-empty error is a failed staking tx. - // we remove then re add the tx here to stop needing a full rescan, which does not actually fix the problem. - int32_t reAdded = 0; - BOOST_FOREACH (uint256& hash, deadTxns) - { - fprintf(stderr, "Removing possible orphaned staking transaction from wallet.%s\n", hash.ToString().c_str()); - if (!EraseTx(hash)) - fprintf(stderr, "could not delete tx.%s\n",hash.ToString().c_str()); - uint256 blockhash; CTransaction tx; CBlockIndex* pindex; - if ( GetTransaction(hash,tx,blockhash,false) && (pindex= hush_blockindex(blockhash)) != 0 && chainActive.Contains(pindex) ) - { - CWalletTx wtx(pwallet,tx); - pwallet->AddToWallet(wtx, true, NULL); - reAdded++; - } - } - fprintf(stderr, "Cleared %li orphaned staking transactions from wallet. Readded %i real transactions.\n",deadTxns.size(),reAdded); - fNoncriticalErrors = false; - deadTxns.clear(); - } - if (fNoncriticalErrors && result == DB_LOAD_OK) result = DB_NONCRITICAL_ERROR;