Browse Source

Merge pull request #487 from jl777/beta

barterDEX release candidate, no changes for notaries
dPoW
jl777 7 years ago
committed by GitHub
parent
commit
960035f0f1
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 11
      .gitignore
  2. BIN
      OSlibs/js/libnanomsg.a
  3. BIN
      OSlibs/js/libnanomsg.so
  4. 24
      OSlibs/win/mingw.h
  5. 25
      README_decker.md
  6. 4
      basilisk/basilisk_bitcoin.c
  7. 8
      crypto777/OS_nonportable.c
  8. 4
      crypto777/OS_portable.c
  9. 14
      crypto777/OS_portable.h
  10. 2
      crypto777/OS_time.c
  11. 80
      crypto777/bitcoind_RPC.c
  12. 128
      crypto777/cJSON.c
  13. 6
      crypto777/crypto777.sources
  14. 26
      crypto777/iguana_OS.c
  15. 2
      crypto777/iguana_serdes.c
  16. 4
      crypto777/iguana_utils.c
  17. 2
      crypto777/jpeg/unix/jmemname.c
  18. 75
      crypto777/nanosrc/aio/usock_posix.c
  19. 13
      crypto777/nanosrc/aio/usock_posix.c_dev
  20. 4
      crypto777/nanosrc/aio/usock_posix.h
  21. 2
      crypto777/nanosrc/aio/usock_win.c
  22. 50
      crypto777/nanosrc/aio/worker_posix.c
  23. 90
      crypto777/nanosrc/core/global.c
  24. 9
      crypto777/nanosrc/core/pipe.c
  25. 15
      crypto777/nanosrc/core/sock.c
  26. 8
      crypto777/nanosrc/devices/tcpmuxd.c
  27. 1
      crypto777/nanosrc/nn.h
  28. 14
      crypto777/nanosrc/nn_config.h
  29. 3
      crypto777/nanosrc/protocols/pipeline/xpush.c
  30. 2
      crypto777/nanosrc/protocols/reqrep/xreq.c
  31. 7
      crypto777/nanosrc/protocols/utils/lb.c
  32. 4
      crypto777/nanosrc/protocols/utils/priolist.c
  33. 3
      crypto777/nanosrc/protocols/utils/priolist.h
  34. 6
      crypto777/nanosrc/tests/testutil.h
  35. 4
      crypto777/nanosrc/transports/ipc/bipc.c
  36. 5
      crypto777/nanosrc/transports/ipc/cipc.c
  37. 4
      crypto777/nanosrc/transports/ipc/ipc.c
  38. 4
      crypto777/nanosrc/transports/tcpmux/btcpmux.c
  39. 6
      crypto777/nanosrc/transports/utils/tcpmux.c
  40. 4
      crypto777/nanosrc/transports/ws/cws.c
  41. 4
      crypto777/nanosrc/transports/ws/sws.c
  42. 2
      crypto777/nanosrc/transports/ws/sws.h
  43. 2
      crypto777/nanosrc/transports/ws/ws.c
  44. 4
      crypto777/nanosrc/transports/ws/ws_handshake.c
  45. 4
      crypto777/nanosrc/utils/efd_eventfd.c
  46. 12
      crypto777/nanosrc/utils/efd_pipe.c
  47. 2
      crypto777/nanosrc/utils/efd_socketpair.c
  48. 5
      crypto777/nanosrc/utils/efd_win.c
  49. 4
      crypto777/nanosrc/utils/err.c
  50. 13
      crypto777/nanosrc/utils/err.h
  51. 12
      crypto777/nanosrc/utils/thread_posix.c
  52. 2
      crypto777/nanosrc/utils/win.h
  53. 2
      iguana/coins/basilisk/mnz
  54. 2
      iguana/coins/chips_7776
  55. 2
      iguana/coins/mnz_7776
  56. 7
      iguana/dPoW.h
  57. 16
      iguana/dexscripts.win32/1-client.cmd
  58. 7
      iguana/dexscripts.win32/2-getuserpass.cmd
  59. 4
      iguana/dexscripts.win32/balance.cmd
  60. 7
      iguana/dexscripts.win32/bot_buy.cmd
  61. 7
      iguana/dexscripts.win32/bot_list.cmd
  62. 7
      iguana/dexscripts.win32/bot_statuslist.cmd
  63. 7
      iguana/dexscripts.win32/bot_stop.cmd
  64. BIN
      iguana/dexscripts.win32/curl.exe
  65. 9
      iguana/dexscripts.win32/electrum.cmd
  66. 4
      iguana/dexscripts.win32/enable.cmd
  67. 4
      iguana/dexscripts.win32/getcoin.cmd
  68. 4
      iguana/dexscripts.win32/getutxos.cmd
  69. 2
      iguana/dexscripts.win32/help.cmd
  70. 100
      iguana/dexscripts.win32/how_to_use.md
  71. BIN
      iguana/dexscripts.win32/images/conemu_jq.png
  72. BIN
      iguana/dexscripts.win32/images/userpass.png
  73. BIN
      iguana/dexscripts.win32/images/userpass_usage.png
  74. 4
      iguana/dexscripts.win32/inventory.cmd
  75. 4
      iguana/dexscripts.win32/listunspent.cmd
  76. 4
      iguana/dexscripts.win32/orderbook.cmd
  77. 1
      iguana/dexscripts.win32/passphrase
  78. 4
      iguana/dexscripts.win32/portfolio.cmd
  79. 5
      iguana/dexscripts.win32/sendrawtransaction.cmd
  80. 5
      iguana/dexscripts.win32/snapshot.cmd
  81. 0
      iguana/dexscripts.win32/userpass
  82. 8
      iguana/dexscripts.win32/withdraw.cmd
  83. 14
      iguana/dexscripts.win32/withdraw_10_send.cmd
  84. 14
      iguana/dexscripts.win32/withdraw_send.cmd
  85. 7
      iguana/dpow/dpow_fsm.c
  86. 17
      iguana/dpow/dpow_network.c
  87. 32
      iguana/dpow/dpow_prices.c
  88. 20
      iguana/dpow/dpow_rpc.c
  89. 0
      iguana/exchanges/DB/PRICES/.tmpmarker
  90. 6
      iguana/exchanges/DEXstats.h
  91. 291
      iguana/exchanges/LP_RTmetrics.c
  92. 252
      iguana/exchanges/LP_bitcoin.c
  93. 343
      iguana/exchanges/LP_cache.c
  94. 139
      iguana/exchanges/LP_coins.c
  95. 513
      iguana/exchanges/LP_commands.c
  96. 309
      iguana/exchanges/LP_include.h
  97. 1064
      iguana/exchanges/LP_nativeDEX.c
  98. 314
      iguana/exchanges/LP_network.c
  99. 1422
      iguana/exchanges/LP_ordermatch.c
  100. 162
      iguana/exchanges/LP_peers.c

11
.gitignore

@ -170,7 +170,6 @@ iguana/help.json
iguana/index7778.html
*.json
iguana/DB/KMD/utxo.dat
@ -235,3 +234,13 @@ iguana/marketmaker.dSYM/Contents/Resources/DWARF/marketmaker
iguana/marketmaker.dSYM/Contents/Info.plist
iguana/confs/97f18454bb61e9eb7a827cfbefe42fbf7ae2832dc74c4812bdaef8bcf5c10474
iguana/DB/PRICES/.tmpmarker
iguana/DB/KMD/0/.tmpmarker
*.swp
iguana/myipaddr
iguana/DB/UNSPENTS/.tmpmarker

BIN
OSlibs/js/libnanomsg.a

Binary file not shown.

BIN
OSlibs/js/libnanomsg.so

Binary file not shown.

24
OSlibs/win/mingw.h

@ -5,6 +5,8 @@
#include <io.h>
#define _USE_W32_SOCKETS 1
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <windows.h>
#define PTW32_STATIC_LIB
#include "pthread.h"
@ -38,6 +40,9 @@
* @author - fadedreamz@gmail.com
*/
//TODO: need to update other values to match with WSAPoll() function
#define POLLRDNORM 0x0100
#define POLLRDBAND 0x0200
#define POLLWRNORM 0x0010
#define POLLIN POLLRDNORM | POLLRDBAND /* There is data to read */
#define POLLOUT POLLWRNORM /* Writing now will not block */
#else
@ -56,13 +61,18 @@
* @remarks - #if (defined(_M_X64) || defined(__amd64__)) && defined(WIN32)
* is equivalent to #if defined(_M_X64) as _M_X64 is defined for MSVC only
*/
#if !defined(_M_X64)
struct pollfd {
SOCKET fd; /* file descriptor */
short events; /* requested events */
short revents; /* returned events */
};
#endif
// [Decker] pollfs is already defined in winsock2.h
//#if !defined(_M_X64)
//struct pollfd {
//SOCKET fd; /* file descriptor */
//short events; /* requested events */
//short revents; /* returned events */
//};
//#endif
#if defined(_M_X64)
/*

25
README_decker.md

@ -0,0 +1,25 @@
## What's this?
This is a first build of **MarketMaker** app from barterDEX for Windows (64-bit) platform. This branch includes all that you need to build marketmaker for Windows. 64-bit build uses MSVC 2015 as a default C/C++ compiler, to build - simply open *marketmaker.sln* project file via File -> Open -> Project/Solution ... next choose Release / x64 configuration and build solution. Your binaries will be placed x64\Release folder. To run marketmaker you also need following dll libraries:
- libcurl.dll
- nanomsg.dll
- curl.exe (win64 curl binary, used is scripts)
It already included in this branch.
## How to use?
Please, refer to original barterDEX documentation and Komodo Platform + SuperNET resources to learn how to work this it. Later i will add some examples and useful links here.
Important, coins.json on Windows shouldn't contain coins which haven't running daemons. Add to coins.json only coins that you plan to use, in other case starting marketmaker will too long: about 4 seconds on each not-running coin.
Get the latest binary release from release section and step-by-step run cmd files:
- 1-client.cmd - this runs marketmaker with passphrase taken from a passphrase file.
- 2-getuserpass.cmd - this will save and output your userpass in userpass file for future use.
- 3-orderbook.cmd - to get an orderbook (if u downloaded binary release from release section - it's have only REVS in coins.json and orderbook will be shown at KMD/REVS coins pair).
Other scripts will be post later ... this is just for example that it works.

4
basilisk/basilisk_bitcoin.c

@ -602,7 +602,7 @@ char *iguana_utxoduplicates(struct supernet_info *myinfo,struct iguana_info *coi
free_json(vins);
return(rawtx);
}
printf("splitfunds tx.(%s) vins.(%s)\n",rawtx,jprint(vins,0));
printf("%s splitfunds tx.(%s) vins.(%s)\n",coin->symbol,rawtx,jprint(vins,0));
if ( signedtxidp != 0 )
{
if ( (signedtx= iguana_signrawtx(myinfo,coin,0,signedtxidp,completedp,vins,rawtx,0,0)) != 0 )
@ -615,7 +615,7 @@ char *iguana_utxoduplicates(struct supernet_info *myinfo,struct iguana_info *coi
free(rawtx);
rawtx = signedtx, signedtx = 0;
}
} else printf("error signing raw utxoduplicates tx\n");
} else printf("error signing raw %s utxoduplicates tx\n",coin->symbol);
}
}
if ( vins != 0 )

8
crypto777/OS_nonportable.c

@ -26,10 +26,10 @@
* not from the mingw header, so we need to include the windows header
* if we are compiling in windows 64bit
*/
#if defined(_M_X64)
#define WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#endif
//#if defined(_M_X64)
//#define WIN32_LEAN_AND_MEAN
//#include <WinSock2.h>
//#endif
#include "OS_portable.h"

4
crypto777/OS_portable.c

@ -249,13 +249,13 @@ void *OS_portable_tmpalloc(char *dirname,char *name,struct OS_memspace *mem,long
if ( mem->totalsize > origsize )
size = mem->totalsize;
else size = origsize;
fprintf(stderr,"filealloc.(%s) -> ",fname);
printf("filealloc.(%s) -> ",fname);
if ( OS_filealloc(&mem->M,fname,mem,size) == 0 )
{
printf("couldnt map tmpfile %s\n",fname);
return(0);
}
fprintf(stderr,"created\n");
printf("created\n");
}
ptr = iguana_memalloc(mem,origsize,1);
if ( mem->threadsafe != 0 )

14
crypto777/OS_portable.h

@ -40,7 +40,7 @@
#include <sys/types.h>
#include <time.h>
#ifdef WIN32
#ifdef _WIN32
#define sleep(x) Sleep(1000*(x))
#include "../OSlibs/win/mingw.h"
#include "../OSlibs/win/mman.h"
@ -134,7 +134,7 @@ int32_t hseek(HUFF *hp,int32_t offset,int32_t mode);
struct allocitem { uint32_t allocsize,type; } PACKED;
struct queueitem { struct queueitem *next,*prev; uint32_t allocsize,type; } PACKED;
struct stritem { struct queueitem DL; char str[]; };
struct stritem { struct queueitem DL; void **retptrp; uint32_t expiration; char str[]; };
typedef struct queue
{
@ -143,6 +143,15 @@ typedef struct queue
char name[64],initflag;
} queue_t;
struct rpcrequest_info
{
struct rpcrequest_info *next,*prev;
pthread_t T;
int32_t sock;
uint32_t ipbits;
uint16_t port,pad;
};
struct OS_mappedptr
{
char fname[512];
@ -267,6 +276,7 @@ void *queue_delete(queue_t *queue,struct queueitem *copy,int32_t copysize,int32_
void *queue_free(queue_t *queue);
void *queue_clone(queue_t *clone,queue_t *queue,int32_t size);
int32_t queue_size(queue_t *queue);
char *mbstr(char *str,double n);
void iguana_memreset(struct OS_memspace *mem);
void iguana_mempurge(struct OS_memspace *mem);

2
crypto777/OS_time.c

@ -357,7 +357,7 @@ struct tai tai_now()
#ifndef DISABLE_LEAPS
UTC_ADJUST = -36;
#endif
printf("TAINOW.%llu %03.3f UTC.%u vs %u [diff %d]\n",(long long)t.x,t.millis,First_utc,tai2utc(t),UTC_ADJUST);
//printf("TAINOW.%llu %03.3f UTC.%u vs %u [diff %d]\n",(long long)t.x,t.millis,First_utc,tai2utc(t),UTC_ADJUST);
}
return(t);
}

80
crypto777/bitcoind_RPC.c

@ -13,9 +13,24 @@
* *
******************************************************************************/
#ifndef FROM_JS
#include "OS_portable.h"
#define LIQUIDITY_PROVIDER 1
/*#define malloc(n) LP_alloc(n)
#define realloc(ptr,n) LP_realloc(ptr,n)
#define calloc(a,b) LP_alloc((uint64_t)(a) * (b))
#define free(ptr) LP_free(ptr)
#define clonestr(str) LP_clonestr(str)
void *LP_realloc(void *ptr,uint64_t len);
void *LP_alloc(uint64_t len);
void LP_free(void *ptr);
char *LP_clonestr(char *str);*/
#if LIQUIDITY_PROVIDER
#include <curl/curl.h>
#include <curl/easy.h>
@ -30,8 +45,11 @@ struct return_string {
size_t len;
};
struct MemoryStruct { char *memory; size_t size,allocsize; };
size_t accumulate(void *ptr, size_t size, size_t nmemb, struct return_string *s);
void init_string(struct return_string *s);
static size_t WriteMemoryCallback(void *ptr,size_t size,size_t nmemb,void *data);
/************************************************************************
@ -54,17 +72,20 @@ char *post_process_bitcoind_RPC(char *debugstr,char *command,char *rpcstr,char *
long i,j,len;
char *retstr = 0;
cJSON *json,*result,*error;
#ifdef FROM_MARKETMAKER
usleep(3000);
#endif
//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 && strcmp(command,"getrawtransaction") != 0 )
printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC.%s.[%s]\n",debugstr,command,rpcstr);
printf("<<<<<<<<<<< A bitcoind_RPC: %s post_process_bitcoind_RPC.%s.[%s]\n",debugstr,command,params);
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);
printf("<<<<<<<<<<< B bitcoind_RPC: %s post_process_bitcoind_RPC.%s can't parse.(%s) params.(%s)\n",debugstr,command,rpcstr,params);
free(rpcstr);
return(0);
}
@ -74,7 +95,7 @@ char *post_process_bitcoind_RPC(char *debugstr,char *command,char *rpcstr,char *
{
if ( (error->type&0xff) == cJSON_NULL && (result->type&0xff) != cJSON_NULL )
{
retstr = cJSON_Print(result);
retstr = jprint(result,0);
len = strlen(retstr);
if ( retstr[0] == '"' && retstr[len-1] == '"' )
{
@ -118,8 +139,9 @@ char *Jay_NXTrequest(char *command,char *params)
char *bitcoind_RPC(char **retstrp,char *debugstr,char *url,char *userpass,char *command,char *params,int32_t timeout)
{
static int didinit,count,count2; static double elapsedsum,elapsedsum2; extern int32_t USE_JAY;
struct MemoryStruct chunk;
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;
char *bracket0,*bracket1,*retstr,*databuf = 0; long len; int32_t specialcase,numretries; double starttime;
if ( didinit == 0 )
{
didinit = 1;
@ -143,14 +165,24 @@ try_again:
*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);
if ( (0) )
{
init_string(&s);
curl_easy_setopt(curl_handle,CURLOPT_WRITEFUNCTION, (void *)accumulate); // send all data to this function
curl_easy_setopt(curl_handle,CURLOPT_WRITEDATA, &s); // we pass our 's' struct to the callback
}
else
{
memset(&chunk,0,sizeof(chunk));
curl_easy_setopt(curl_handle,CURLOPT_WRITEFUNCTION,WriteMemoryCallback);
curl_easy_setopt(curl_handle,CURLOPT_WRITEDATA,(void *)&chunk);
}
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 ( timeout > 0 )
@ -205,45 +237,46 @@ try_again:
if ( specialcase != 0 || timeout != 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);
free(chunk.memory); //free(s.ptr);
return(0);
}
else if ( numretries >= 4 )
{
printf( "curl_easy_perform() failed: %s %s.(%s %s), retries: %d\n",curl_easy_strerror(res),debugstr,url,command,numretries);
//printf("Maximum number of retries exceeded!\n");
free(s.ptr);
free(chunk.memory);//free(s.ptr);
return(0);
}
free(s.ptr);
free(chunk.memory);//free(s.ptr);
sleep((1<<numretries));
goto try_again;
}
else
{
retstr = chunk.memory; // retstr = s.ptr;
if ( command != 0 && specialcase == 0 )
{
count++;
elapsedsum += (OS_milliseconds() - starttime);
if ( (count % 10000) == 0)
if ( (count % 100000) == 0)
printf("%d: ave %9.6f | elapsed %.3f millis | bitcoind_RPC.(%s) url.(%s)\n",count,elapsedsum/count,(OS_milliseconds() - starttime),command,url);
if ( retstrp != 0 )
{
*retstrp = s.ptr;
return(s.ptr);
*retstrp = retstr;
return(retstr);
}
return(post_process_bitcoind_RPC(debugstr,command,s.ptr,params));
return(post_process_bitcoind_RPC(debugstr,command,retstr,params));
}
else
{
if ( (0) && specialcase != 0 )
fprintf(stderr,"<<<<<<<<<<< bitcoind_RPC: BTCD.(%s) -> (%s)\n",params,s.ptr);
fprintf(stderr,"<<<<<<<<<<< bitcoind_RPC: BTCD.(%s) -> (%s)\n",params,retstr);
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);
return(retstr);
}
}
//printf("bitcoind_RPC: impossible case\n");
@ -290,13 +323,23 @@ size_t accumulate(void *ptr,size_t size,size_t nmemb,struct return_string *s)
return(size * nmemb);
}
struct MemoryStruct { char *memory; size_t size; };
static size_t WriteMemoryCallback(void *ptr,size_t size,size_t nmemb,void *data)
{
size_t realsize = (size * nmemb);
size_t needed,realsize = (size * nmemb);
struct MemoryStruct *mem = (struct MemoryStruct *)data;
mem->memory = (ptr != 0) ? realloc(mem->memory,mem->size + realsize + 1) : malloc(mem->size + realsize + 1);
needed = mem->size + realsize + 1;
if ( ptr == 0 && needed < 256 )
{
mem->allocsize = 256;
mem->memory = malloc(mem->allocsize);
}
if ( mem->allocsize < needed )
{
//printf("curl needs %d more\n",(int32_t)realsize);
mem->memory = (ptr != 0) ? realloc(mem->memory,needed) : malloc(needed);
mem->allocsize = needed;
}
//mem->memory = (ptr != 0) ? realloc(mem->memory,mem->size + realsize + 1) : malloc(mem->size + realsize + 1);
if ( mem->memory != 0 )
{
if ( ptr != 0 )
@ -371,3 +414,4 @@ void *curl_post(void **cHandlep,char *url,char *userpass,char *postfields,char *
return(clonestr("{\"error\":\"curl is disabled\"}"));
}
#endif
#endif

128
crypto777/cJSON.c

@ -54,8 +54,43 @@ static int32_t cJSON_strcasecmp(const char *s1,const char *s2)
return tolower((int32_t)(*(const unsigned char *)s1)) - tolower((int32_t)(*(const unsigned char *)s2));
}
static void *(*cJSON_malloc)(size_t sz) = malloc;
static void (*cJSON_free)(void *ptr) = free;
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)
{
@ -63,7 +98,7 @@ static char* cJSON_strdup(const char* str)
char* copy;
len = strlen(str) + 1;
if (!(copy = (char*)cJSON_malloc(len+1))) return 0;
if (!(copy = (char*)cJSON_mallocstr((int32_t)len+1))) return 0;
memcpy(copy,str,len);
return copy;
}
@ -83,7 +118,7 @@ void cJSON_InitHooks(cJSON_Hooks* hooks)
/* Internal constructor. */
static cJSON *cJSON_New_Item(void)
{
cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
cJSON* node = (cJSON*)cJSON_mallocnode();
if (node) memset(node,0,sizeof(cJSON));
return node;
}
@ -96,9 +131,9 @@ void cJSON_Delete(cJSON *c)
{
next=c->next;
if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child);
if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring);
if (c->string) cJSON_free(c->string);
cJSON_free(c);
if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_freestr(c->valuestring);
if (c->string) cJSON_freestr(c->string);
cJSON_freenode(c);
c=next;
}
}
@ -132,13 +167,13 @@ static char *print_number(cJSON *item)
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_malloc(24); /* 2^64+1 can be represented in 21 chars + sign. */
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_malloc(66); /* This is a nice tradeoff. */
str = (char *)cJSON_mallocstr(66); /* This is a nice tradeoff. */
if ( str != 0 )
{
if ( fabs(floor(d) - d) <= DBL_EPSILON && fabs(d) < 1.0e60 )
@ -173,7 +208,7 @@ static const char *parse_string(cJSON *item,const char *str)
while (*ptr!='\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; // Skip escaped quotes
out=(char*)cJSON_malloc(len+2); /* This is how long we need for the string, roughly. */
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;
@ -238,7 +273,7 @@ static char *print_string_ptr(const char *str)
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_malloc(len+3+1);
out=(char*)cJSON_mallocstr(len+3+1);
if (!out) return 0;
ptr2=out;ptr=str;
@ -372,7 +407,7 @@ static const char *parse_array(cJSON *item,const char *value)
/* Render an array to text */
static char *print_array(cJSON *item,int32_t depth,int32_t fmt)
{
char **entries;
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;
@ -382,12 +417,12 @@ static char *print_array(cJSON *item,int32_t depth,int32_t fmt)
/* Explicitly handle numentries==0 */
if (!numentries)
{
out=(char*)cJSON_malloc(3+1);
out=(char*)cJSON_mallocstr(3+1);
if (out) strcpy(out,"[]");
return out;
}
/* Allocate an array to hold the values for each */
entries=(char**)cJSON_malloc((1+numentries)*sizeof(char*));
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: */
@ -401,15 +436,15 @@ static char *print_array(cJSON *item,int32_t depth,int32_t fmt)
}
/* If we didn't fail, try to malloc the output string */
if (!fail) out=(char*)cJSON_malloc(len+1);
if (!fail) out=(char*)cJSON_mallocstr(len+1);
/* If that fails, we fail. */
if (!out) fail=1;
/* Handle failure. */
if (fail)
{
for (i=0;i<numentries;i++) if (entries[i]) cJSON_free(entries[i]);
cJSON_free(entries);
for (i=0;i<numentries;i++) if (entries[i]) cJSON_freestr(entries[i]);
cJSON_freeptrs(entries,numentries,space_entries);
return 0;
}
@ -420,9 +455,9 @@ static char *print_array(cJSON *item,int32_t depth,int32_t fmt)
{
strcpy(ptr,entries[i]);ptr+=strlen(entries[i]);
if (i!=numentries-1) {*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;}
cJSON_free(entries[i]);
cJSON_freestr(entries[i]);
}
cJSON_free(entries);
cJSON_freeptrs(entries,numentries,space_entries);
*ptr++=']';*ptr++=0;
return out;
}
@ -466,7 +501,7 @@ static const char *parse_object(cJSON *item,const char *value)
/* Render an object to text. */
static char *print_object(cJSON *item,int32_t depth,int32_t fmt)
{
char **entries=0,**names=0;
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;
@ -485,7 +520,7 @@ static char *print_object(cJSON *item,int32_t depth,int32_t fmt)
/* Explicitly handle empty object case */
if (!numentries)
{
out=(char*)cJSON_malloc(fmt?depth+4+1:3+1);
out=(char*)cJSON_mallocstr(fmt?depth+4+1:3+1);
if (!out) return 0;
ptr=out;*ptr++='{';
if (fmt) {*ptr++='\n';for (i=0;i<depth-1;i++) *ptr++='\t';}
@ -493,10 +528,10 @@ static char *print_object(cJSON *item,int32_t depth,int32_t fmt)
return out;
}
/* Allocate space for the names and the objects */
entries=(char**)cJSON_malloc(numentries*sizeof(char*));
entries=(char**)cJSON_mallocptrs(numentries,space_entries,sizeof(space_entries)/sizeof(*space_entries));
if (!entries) return 0;
names=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!names) {cJSON_free(entries);return 0;}
names=(char**)cJSON_mallocptrs(numentries,space_names,sizeof(space_names)/sizeof(*space_names));
if (!names) {cJSON_freeptrs(entries,numentries,space_entries);return 0;}
memset(entries,0,sizeof(char*)*numentries);
memset(names,0,sizeof(char*)*numentries);
@ -513,14 +548,15 @@ static char *print_object(cJSON *item,int32_t depth,int32_t fmt)
}
/* Try to allocate the output string */
if (!fail) out=(char*)cJSON_malloc(len+1);
if (!fail) out=(char*)cJSON_mallocstr(len+1);
if (!out) fail=1;
/* Handle failure */
if (fail)
{
for (i=0;i<numentries;i++) {if (names[i]) cJSON_free(names[i]);if (entries[i]) cJSON_free(entries[i]);}
cJSON_free(names);cJSON_free(entries);
for (i=0;i<numentries;i++) {if (names[i]) cJSON_freestr(names[i]);if (entries[i]) cJSON_freestr(entries[i]);}
cJSON_freeptrs(names,numentries,space_names);
cJSON_freeptrs(entries,numentries,space_entries);
return 0;
}
@ -534,10 +570,11 @@ static char *print_object(cJSON *item,int32_t depth,int32_t fmt)
strcpy(ptr,entries[i]);ptr+=strlen(entries[i]);
if (i!=numentries-1) *ptr++=',';
if (fmt) *ptr++='\n';*ptr=0;
cJSON_free(names[i]);cJSON_free(entries[i]);
cJSON_freestr(names[i]);cJSON_freestr(entries[i]);
}
cJSON_free(names);cJSON_free(entries);
cJSON_freeptrs(names,numentries,space_names);
cJSON_freeptrs(entries,numentries,space_entries);
if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t';
*ptr++='}';*ptr++=0;
return out;
@ -578,8 +615,6 @@ cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->t
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;}
cJSON *cJSON_CreateArray(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;}
cJSON *cJSON_CreateObject(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;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 && i<count;i++){n=cJSON_CreateNumber((double)numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
@ -1129,4 +1164,33 @@ cJSON *addrs_jsonarray(uint64_t *addrs,int32_t num)
return(array);
}
void free_json(cJSON *json) { if ( json != 0 ) cJSON_Delete(json); }
cJSON *cJSON_CreateArray(void)
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = 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);
}

6
crypto777/crypto777.sources

@ -36,11 +36,11 @@ TRANSPORTS_TCPMUX = $(NANOSRC)/transports/tcpmux/atcpmux.c $(NANOSRC)/transports
NANOMSG_PROTOCOLS = $(PROTOCOLS_UTILS) $(PROTOCOLS_PUBSUB) $(PROTOCOLS_PAIR) $(PROTOCOLS_REQREP) $(PROTOCOLS_BUS) $(PROTOCOLS_PIPELINE) $(PROTOCOLS_SURVEY)
NANOMSG_TRANSPORTS = $(TRANSPORTS_UTILS) $(TRANSPORTS_TCP) $(TRANSPORTS_IPC) $(TRANSPORTS_INPROC)
NANOMSG_TRANSPORTS = $(TRANSPORTS_UTILS) $(TRANSPORTS_TCP) $(TRANSPORTS_IPC) $(TRANSPORTS_INPROC) $(TRANSPORTS_WS)
NANOMSG = $(NANOMSG_CORE) $(NANOMSG_AIO) $(NANOMSG_UTILS) $(NANOMSG_DEVICES) $(NANOMSG_TRANSPORTS) $(NANOMSG_PROTOCOLS)
JPEG_SRCS := ../crypto777/jpeg/jaricom.c ../crypto777/jpeg/jcapimin.c ../crypto777/jpeg/jcapistd.c ../crypto777/jpeg/jcarith.c ../crypto777/jpeg/jccoefct.c ../crypto777/jpeg/jccolor.c ../crypto777/jpeg/jcdctmgr.c ../crypto777/jpeg/jchuff.c ../crypto777/jpeg/jcinit.c ../crypto777/jpeg/jcmainct.c ../crypto777/jpeg/jcmarker.c ../crypto777/jpeg/jcmaster.c ../crypto777/jpeg/jcomapi.c ../crypto777/jpeg/jcparam.c ../crypto777/jpeg/jcprepct.c ../crypto777/jpeg/jcsample.c ../crypto777/jpeg/jctrans.c ../crypto777/jpeg/jdapimin.c ../crypto777/jpeg/jdapistd.c ../crypto777/jpeg/jdarith.c ../crypto777/jpeg/jdatadst.c ../crypto777/jpeg/jdatasrc.c ../crypto777/jpeg/jdcoefct.c ../crypto777/jpeg/jdcolor.c ../crypto777/jpeg/jddctmgr.c ../crypto777/jpeg/jdhuff.c ../crypto777/jpeg/jdinput.c ../crypto777/jpeg/jdmainct.c ../crypto777/jpeg/jdmarker.c ../crypto777/jpeg/jdmaster.c ../crypto777/jpeg/jdmerge.c ../crypto777/jpeg/jdpostct.c ../crypto777/jpeg/jdsample.c ../crypto777/jpeg/jdtrans.c ../crypto777/jpeg/jerror.c ../crypto777/jpeg/jfdctflt.c ../crypto777/jpeg/jfdctfst.c ../crypto777/jpeg/jfdctint.c ../crypto777/jpeg/jidctflt.c ../crypto777/jpeg/jidctfst.c ../crypto777/jpeg/jidctint.c ../crypto777/jpeg/jquant1.c ../crypto777/jpeg/jquant2.c ../crypto777/jpeg/jutils.c ../crypto777/jpeg/misc/jmemnobs.c ../crypto777/jpeg/jmemmgr.c
JPEG_SRCS = ../crypto777/jpeg/jaricom.c ../crypto777/jpeg/jcapimin.c ../crypto777/jpeg/jcapistd.c ../crypto777/jpeg/jcarith.c ../crypto777/jpeg/jccoefct.c ../crypto777/jpeg/jccolor.c ../crypto777/jpeg/jcdctmgr.c ../crypto777/jpeg/jchuff.c ../crypto777/jpeg/jcinit.c ../crypto777/jpeg/jcmainct.c ../crypto777/jpeg/jcmarker.c ../crypto777/jpeg/jcmaster.c ../crypto777/jpeg/jcomapi.c ../crypto777/jpeg/jcparam.c ../crypto777/jpeg/jcprepct.c ../crypto777/jpeg/jcsample.c ../crypto777/jpeg/jctrans.c ../crypto777/jpeg/jdapimin.c ../crypto777/jpeg/jdapistd.c ../crypto777/jpeg/jdarith.c ../crypto777/jpeg/jdatadst.c ../crypto777/jpeg/jdatasrc.c ../crypto777/jpeg/jdcoefct.c ../crypto777/jpeg/jdcolor.c ../crypto777/jpeg/jddctmgr.c ../crypto777/jpeg/jdhuff.c ../crypto777/jpeg/jdinput.c ../crypto777/jpeg/jdmainct.c ../crypto777/jpeg/jdmarker.c ../crypto777/jpeg/jdmaster.c ../crypto777/jpeg/jdmerge.c ../crypto777/jpeg/jdpostct.c ../crypto777/jpeg/jdsample.c ../crypto777/jpeg/jdtrans.c ../crypto777/jpeg/jerror.c ../crypto777/jpeg/jfdctflt.c ../crypto777/jpeg/jfdctfst.c ../crypto777/jpeg/jfdctint.c ../crypto777/jpeg/jidctflt.c ../crypto777/jpeg/jidctfst.c ../crypto777/jpeg/jidctint.c ../crypto777/jpeg/jquant1.c ../crypto777/jpeg/jquant2.c ../crypto777/jpeg/jutils.c ../crypto777/jpeg/misc/jmemnobs.c ../crypto777/jpeg/jmemmgr.c
CRYPTO777_SRCS := ../crypto777/tweetnacl.c ../crypto777/scrypt.c ../crypto777/bitcoind_RPC.c ../crypto777/cJSON.c ../crypto777/iguana_utils.c ../crypto777/OS_nonportable.c ../crypto777/curve25519-donna.c ../crypto777/inet.c ../crypto777/OS_portable.c ../crypto777/curve25519.c ../crypto777/OS_time.c ../crypto777/hmac_sha512.c ../crypto777/ramcoder.c ../crypto777/SaM.c ../crypto777/iguana_OS.c ../crypto777/iguana_serdes.c $(JPEG_SRCS) $(NANOMSG)
CRYPTO777_SRCS = ../crypto777/tweetnacl.c ../crypto777/scrypt.c ../crypto777/bitcoind_RPC.c ../crypto777/cJSON.c ../crypto777/iguana_utils.c ../crypto777/OS_nonportable.c ../crypto777/curve25519-donna.c ../crypto777/inet.c ../crypto777/OS_portable.c ../crypto777/curve25519.c ../crypto777/OS_time.c ../crypto777/hmac_sha512.c ../crypto777/ramcoder.c ../crypto777/SaM.c ../crypto777/iguana_OS.c ../crypto777/iguana_serdes.c $(JPEG_SRCS) $(NANOMSG)

26
crypto777/iguana_OS.c

@ -30,7 +30,7 @@
char *OS_mvstr()
{
#ifdef __WIN32
#ifdef _WIN32
return("rename");
#else
return("mv");
@ -297,11 +297,11 @@ void *queue_dequeue(queue_t *queue)//,int32_t offsetflag)
void *queue_delete(queue_t *queue,struct queueitem *copy,int32_t copysize,int32_t freeitem)
{
struct allocitem *ptr;
struct queueitem *item = 0;
struct queueitem *tmp,*item = 0;
lock_queue(queue);
if ( queue->list != 0 )
{
DL_FOREACH(queue->list,item)
DL_FOREACH_SAFE(queue->list,item,tmp)
{
ptr = (void *)((long)item - sizeof(struct allocitem));
if ( item == copy || (ptr->allocsize == copysize && memcmp((void *)((long)item + sizeof(struct queueitem)),(void *)((long)item + sizeof(struct queueitem)),copysize) == 0) )
@ -321,11 +321,11 @@ void *queue_delete(queue_t *queue,struct queueitem *copy,int32_t copysize,int32_
void *queue_free(queue_t *queue)
{
struct queueitem *item = 0;
struct queueitem *tmp,*item = 0;
lock_queue(queue);
if ( queue->list != 0 )
{
DL_FOREACH(queue->list,item)
DL_FOREACH_SAFE(queue->list,item,tmp)
{
DL_DELETE(queue->list,item);
myfree(item,sizeof(struct queueitem));
@ -338,11 +338,11 @@ void *queue_free(queue_t *queue)
void *queue_clone(queue_t *clone,queue_t *queue,int32_t size)
{
struct queueitem *ptr,*item = 0;
struct queueitem *ptr,*tmp,*item = 0;
lock_queue(queue);
if ( queue->list != 0 )
{
DL_FOREACH(queue->list,item)
DL_FOREACH_SAFE(queue->list,item,tmp)
{
ptr = mycalloc('c',1,sizeof(*ptr));
memcpy(ptr,item,size);
@ -659,7 +659,7 @@ int64_t OS_copyfile(char *src,char *dest,int32_t cmpflag)
{
if ( (destfp= fopen(OS_compatible_path(dest),"wb")) != 0 )
{
#ifdef WIN32
#ifdef _WIN32
allocsize = 1024 * 1024 * 8L;
#else
allocsize = 1024 * 1024 * 128L;
@ -901,11 +901,15 @@ void *OS_loadfile(char *fname,char **bufp,long *lenp,long *allocsizep)
return(buf);
}
void *OS_filestr(long *allocsizep,char *fname)
void *OS_filestr(long *allocsizep,char *_fname)
{
long filesize = 0; char *buf = 0;
long filesize = 0; char *fname,*buf = 0; void *retptr;
*allocsizep = 0;
return(OS_loadfile(fname,&buf,&filesize,allocsizep));
fname = malloc(strlen(_fname)+1);
strcpy(fname,_fname);
retptr = OS_loadfile(fname,&buf,&filesize,allocsizep);
free(fname);
return(retptr);
}
// following functions cant be fully implemented in one or more OS

2
crypto777/iguana_serdes.c

@ -13,6 +13,7 @@
* *
******************************************************************************/
#ifndef FROM_JS
#include "OS_portable.h"
#include "../includes/curve25519.h"
@ -213,3 +214,4 @@ int32_t iguana_rwmem(int32_t rwflag,uint8_t *serialized,int32_t len,void *endian
else memcpy(serialized,endianedp,len);
return(len);
}
#endif

4
crypto777/iguana_utils.c

@ -303,7 +303,7 @@ struct iguana_thread *iguana_launch(struct iguana_info *coin,char *name,iguana_f
coin->Launched[t->type]++;
retval = OS_thread_create(&t->handle,NULL,(void *)iguana_launcher,(void *)t);
if ( retval != 0 )
printf("error launching %s\n",t->name);
printf("error launching %s retval.%d errno.%d\n",t->name,retval,errno);
while ( (t= queue_dequeue(&TerminateQ)) != 0 )
{
if ( (rand() % 100000) == 0 && coin != 0 )
@ -446,7 +446,6 @@ char *clonestr(char *str)
return(clone);
}
int32_t safecopy(char *dest,char *src,long len)
{
int32_t i = -1;
@ -459,6 +458,7 @@ int32_t safecopy(char *dest,char *src,long len)
if ( i == len )
{
printf("safecopy: %s too long %ld\n",src,len);
//printf("divide by zero! %d\n",1/zeroval());
#ifdef __APPLE__
//getchar();
#endif

2
crypto777/jpeg/unix/jmemname.c

@ -11,7 +11,7 @@
* Also, the problem of determining the amount of memory available
* is shoved onto the user.
*/
#ifndef WIN32
#ifndef _WIN32
#include <unistd.h>
#endif

75
crypto777/nanosrc/aio/usock_posix.c

@ -167,7 +167,7 @@ int nn_usock_start (struct nn_usock *self, int domain, int type, int protocol)
s = socket (domain, type, protocol);
if (nn_slow (s < 0))
return -errno;
//PNACL_message("got socket s.%d\n",s);
//printf("got socket s.%d\n",s);
nn_usock_init_from_fd (self, s);
/* Start the state machine. */
@ -286,11 +286,14 @@ int nn_usock_bind (struct nn_usock *self, const struct sockaddr *addr,
/* Allow re-using the address. */
opt = 1;
printf("call setsockopt %d SOL_SOCKET.%d SO_REUSEADDR.%d in nn_usock_bind\n",self->s,SOL_SOCKET,SO_REUSEADDR);
rc = setsockopt (self->s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt));
errno_assert (rc == 0);
printf("called setsockopt in nn_usock_bind returns %d\n",rc);
// ignore SO_REUSEADDR failures
//errno_assert (rc == 0);
rc = bind (self->s, addr, (socklen_t) addrlen);
//printf("usock.%d -> bind rc.%d errno.%d %s\n",self->s,rc,errno,nn_strerror(errno));
printf("usock.%d -> bind rc.%d errno.%d %s\n",self->s,rc,errno,nn_strerror(errno));
if (nn_slow (rc != 0))
return -errno;
@ -306,7 +309,7 @@ int nn_usock_listen (struct nn_usock *self, int backlog)
/* Start listening for incoming connections. */
rc = listen (self->s, backlog);
//printf("usock.%d -> listen rc.%d errno.%d %s\n",self->s,rc,errno,nn_strerror(errno));
printf("usock.%d -> listen rc.%d errno.%d %s\n",self->s,rc,errno,nn_strerror(errno));
if (nn_slow (rc != 0))
return -errno;
@ -333,7 +336,7 @@ void nn_usock_accept (struct nn_usock *self, struct nn_usock *listener)
#else
s = accept (listener->s, NULL, NULL);
#endif
//printf("usock.%d -> accept errno.%d s.%d %s\n",self->s,errno,s,nn_strerror(errno));
printf("usock.%d -> accept errno.%d s.%d %s\n",self->s,errno,s,nn_strerror(errno));
/* Immediate success. */
if (nn_fast (s >= 0)) {
@ -366,7 +369,7 @@ void nn_usock_accept (struct nn_usock *self, struct nn_usock *listener)
and allow processing other events in the meantime */
if (nn_slow (errno != EAGAIN && errno != EWOULDBLOCK && errno != ECONNABORTED && errno != listener->errnum))
{
PNACL_message("listen errno.%d\n",errno);
printf("listen errno.%d\n",errno);
listener->errnum = errno;
listener->state = NN_USOCK_STATE_ACCEPTING_ERROR;
nn_fsm_raise (&listener->fsm,
@ -393,7 +396,7 @@ void nn_usock_connect (struct nn_usock *self, const struct sockaddr *addr,
/* Do the connect itself. */
rc = connect(self->s,addr,(socklen_t)addrlen);
//printf("usock.%d <- connect (%llx) rc.%d errno.%d %s\n",self->s,*(long long *)addr,rc,errno,nn_strerror(errno));
printf("usock.%d <- connect (%llx) rc.%d errno.%d %s\n",self->s,*(long long *)addr,rc,errno,nn_strerror(errno));
/* Immediate success. */
if ( nn_fast(rc == 0) )
{
@ -404,7 +407,7 @@ void nn_usock_connect (struct nn_usock *self, const struct sockaddr *addr,
if ( nn_slow(errno != EINPROGRESS) )
{
self->errnum = errno;
PNACL_message("error.%d not EINPROGRESS\n",errno);
printf("error.%d not EINPROGRESS\n",errno);
nn_fsm_action (&self->fsm, NN_USOCK_ACTION_ERROR);
return;
}
@ -433,13 +436,13 @@ void nn_usock_send (struct nn_usock *self, const struct nn_iovec *iov,
self->out.iov [out].iov_base = iov [i].iov_base;
self->out.iov [out].iov_len = iov [i].iov_len;
out++;
//PNACL_message("{%d} ",(int)iov [i].iov_len);
printf("{%d} ",(int)iov [i].iov_len);
}
//PNACL_message("iov[%d]\n",out);
self->out.hdr.msg_iovlen = out;
/* Try to send the data immediately. */
rc = nn_usock_send_raw (self, &self->out.hdr);
printf("iov[%d] nn_usock_send_raw -> rc.%d\n",out,rc);
/* Success. */
if (nn_fast (rc == 0)) {
@ -472,17 +475,17 @@ void nn_usock_recv (struct nn_usock *self, void *buf, size_t len, int *fd)
rc = nn_usock_recv_raw (self, buf, &nbytes);
if (nn_slow (rc < 0)) {
errnum_assert (rc == -ECONNRESET, -rc);
//PNACL_message("rc.%d vs ECONNRESET\n",rc,ECONNRESET);
//printf("rc.%d vs ECONNRESET\n",rc,ECONNRESET);
nn_fsm_action (&self->fsm, NN_USOCK_ACTION_ERROR);
return;
}
//int i;
//for (i=0; i<16&&i<nbytes; i++)
// PNACL_message("%02x ",((uint8_t *)buf)[i]);
//PNACL_message("nn_usock_recv nbytes.%d\n",(int)nbytes);
// printf("%02x ",((uint8_t *)buf)[i]);
//printf("nn_usock_recv nbytes.%d\n",(int)nbytes);
/* Success. */
if (nn_fast (nbytes == len)) {
//PNACL_message("raise NN_USOCK_RECEIVED\n");
//printf("raise NN_USOCK_RECEIVED\n");
nn_fsm_raise (&self->fsm, &self->event_received, NN_USOCK_RECEIVED);
return;
}
@ -1021,19 +1024,19 @@ int32_t nn_getiovec_size(uint8_t *buf,int32_t maxlen,struct msghdr *hdr)
if ( nn_slow(iov->iov_len == NN_MSG) )
{
errno = EINVAL;
PNACL_message("ERROR: iov->iov_len == NN_MSG\n");
printf("ERROR: iov->iov_len == NN_MSG\n");
return(-1);
}
if ( nn_slow(!iov->iov_base && iov->iov_len) )
{
errno = EFAULT;
PNACL_message("ERROR: !iov->iov_base && iov->iov_len\n");
printf("ERROR: !iov->iov_base && iov->iov_len\n");
return(-1);
}
if ( maxlen > 0 && nn_slow(size + iov->iov_len > maxlen) )
{
errno = EINVAL;
PNACL_message("ERROR: sz.%d + iov->iov_len.%d < maxlen.%d\n",(int32_t)size,(int32_t)iov->iov_len,maxlen);
printf("ERROR: sz.%d + iov->iov_len.%d < maxlen.%d\n",(int32_t)size,(int32_t)iov->iov_len,maxlen);
return(-1);
}
if ( iov->iov_len > 0 )
@ -1054,7 +1057,7 @@ ssize_t mysendmsg(int32_t usock,struct msghdr *hdr,int32_t flags)
clen = hdr->msg_controllen;
if ( hdr->msg_control == 0 )
clen = 0;
nn_assert(clen == 0); // no supporty control messagies
nn_assert(clen == 0); // no support control messagies
if ( veclen > sizeof(_buf) ) // - clen - 5) )
buf = malloc(veclen);// + clen + 5);
else buf = _buf;
@ -1069,10 +1072,10 @@ ssize_t mysendmsg(int32_t usock,struct msghdr *hdr,int32_t flags)
if ( nn_getiovec_size(&buf[offset],veclen,hdr) == veclen )
{
nbytes = send(usock,buf,offset + veclen,0);
//PNACL_message(">>>>>>>>> send.[%d %d %d %d] (n.%d v.%d c.%d)-> usock.%d nbytes.%d\n",buf[offset],buf[offset+1],buf[offset+2],buf[offset+3],(int32_t)offset+veclen,veclen,clen,usock,(int32_t)nbytes);
printf(">>>>>>>>> send.[%d %d %d %d] (n.%d v.%d c.%d)-> usock.%d nbytes.%d\n",buf[offset],buf[offset+1],buf[offset+2],buf[offset+3],(int32_t)offset+veclen,veclen,clen,usock,(int32_t)nbytes);
if ( nbytes != offset + veclen )
{
//PNACL_message("nbytes.%d != offset.%d veclen.%d errno.%d usock.%d\n",(int32_t)nbytes,(int32_t)offset,veclen,errno,usock);
printf("nbytes.%d != offset.%d veclen.%d errno.%d usock.%d\n",(int32_t)nbytes,(int32_t)offset,veclen,errno,usock);
}
if ( nbytes >= offset )
nbytes -= offset;
@ -1080,19 +1083,19 @@ ssize_t mysendmsg(int32_t usock,struct msghdr *hdr,int32_t flags)
else
{
err = -errno;
PNACL_message("mysendmsg: unexpected nn_getiovec_size error %d\n",err);
printf("mysendmsg: unexpected nn_getiovec_size error %d\n",err);
}
if ( buf != _buf )
free(buf);
if ( err != 0 )
{
PNACL_message("nn_usock_send_raw errno.%d err.%d\n",errno,err);
printf("nn_usock_send_raw errno.%d err.%d\n",errno,err);
return(-errno);
}
}
else
{
PNACL_message("nn_usock_send_raw errno.%d invalid iovec size\n",errno);
printf("nn_usock_send_raw errno.%d invalid iovec size\n",errno);
return(-errno);
}
return(nbytes);
@ -1104,32 +1107,32 @@ ssize_t myrecvmsg(int32_t usock,struct msghdr *hdr,int32_t flags,int32_t len)
iov = hdr->msg_iov;
/*if ( (n= (int32_t)recv(usock,lens,sizeof(lens),0)) != sizeof(lens) )
{
PNACL_message("error getting veclen/clen n.%d vs %d from usock.%d\n",n,(int32_t)sizeof(lens),usock);
printf("error getting veclen/clen n.%d vs %d from usock.%d\n",n,(int32_t)sizeof(lens),usock);
return(0);
} else PNACL_message("GOT %d bytes from usock.%d\n",n,usock);
} else printf("GOT %d bytes from usock.%d\n",n,usock);
offset = 0;
veclen = lens[offset++];
veclen |= ((int32_t)lens[offset++] << 8);
veclen |= ((int32_t)lens[offset++] << 16);
clen = lens[offset++];
clen |= ((int32_t)lens[offset++] << 8);
PNACL_message("veclen.%d clen.%d waiting in usock.%d\n",veclen,clen,usock);
printf("veclen.%d clen.%d waiting in usock.%d\n",veclen,clen,usock);
if ( clen > 0 )
{
if ( (cbytes= (int32_t)recv(usock,hdr->msg_control,clen,0)) != clen )
{
PNACL_message("myrecvmsg: unexpected cbytes.%d vs clen.%d\n",cbytes,clen);
printf("myrecvmsg: unexpected cbytes.%d vs clen.%d\n",cbytes,clen);
}
} else cbytes = 0;*/
hdr->msg_controllen = 0;
if ( (nbytes= (int32_t)recv(usock,iov->iov_base,len,0)) != len )
{
//PNACL_message("myrecvmsg: partial nbytes.%d vs veclen.%d\n",(int32_t)nbytes,len);
//printf("myrecvmsg: partial nbytes.%d vs veclen.%d\n",(int32_t)nbytes,len);
}
//PNACL_message("GOT nbytes.%d of len.%d from usock.%d\n",(int32_t)nbytes,len,usock);
//printf("GOT nbytes.%d of len.%d from usock.%d\n",(int32_t)nbytes,len,usock);
if ( 0 && nbytes > 0 )
{
PNACL_message("got nbytes.%d from usock.%d [%d %d %d %d]\n",(int32_t)nbytes,usock,((uint8_t *)iov->iov_base)[0],((uint8_t *)iov->iov_base)[1],((uint8_t *)iov->iov_base)[2],((uint8_t *)iov->iov_base)[3]);
printf("got nbytes.%d from usock.%d [%d %d %d %d]\n",(int32_t)nbytes,usock,((uint8_t *)iov->iov_base)[0],((uint8_t *)iov->iov_base)[1],((uint8_t *)iov->iov_base)[2],((uint8_t *)iov->iov_base)[3]);
}
return(nbytes);
}
@ -1144,7 +1147,7 @@ static int nn_usock_send_raw (struct nn_usock *self, struct msghdr *hdr)
nbytes = sendmsg(self->s,hdr,MSG_NOSIGNAL);
#else
nbytes = sendmsg(self->s,hdr,0);
//printf("sendmsg nbytes.%d\n",(int32_t)nbytes);
printf("nn_usock_send_raw nbytes.%d\n",(int32_t)nbytes);
#endif
#endif
/* Handle errors. */
@ -1199,13 +1202,13 @@ int32_t nn_process_cmsg(struct nn_usock *self,struct msghdr *hdr)
memcpy(&retval,(int32_t *)CMSG_DATA(cmsg),sizeof(int32_t));
if ( self->in.pfd )
{
PNACL_message("CMSG set self->in.pfd (%d)\n",retval);
printf("CMSG set self->in.pfd (%d)\n",retval);
*self->in.pfd = retval;
self->in.pfd = NULL;
}
else
{
PNACL_message("CMSG nn_closefd(%d)\n",retval);
printf("CMSG nn_closefd(%d)\n",retval);
nn_closefd(retval);
}
break;
@ -1257,7 +1260,7 @@ static int nn_usock_recv_raw(struct nn_usock *self, void *buf, size_t *len)
if (!length)
return 0;
}
#ifdef NN_USE_MYMSG
#if NN_USE_MYMSG
usebuf = (length >= NN_USOCK_BATCH_SIZE);
#else
usebuf = (length >= NN_USOCK_BATCH_SIZE);
@ -1286,7 +1289,7 @@ static int nn_usock_recv_raw(struct nn_usock *self, void *buf, size_t *len)
#if NN_USE_MYMSG
nbytes = myrecvmsg(self->s,&hdr,0,(int32_t)iov.iov_len);
//printf("got nbytes.%d from recvmsg errno.%d %s\n",(int32_t)nbytes,errno,nn_strerror(errno));
printf("got nbytes.%d from recvmsg errno.%d %s\n",(int32_t)nbytes,errno,nn_strerror(errno));
#else
nbytes = recvmsg (self->s, &hdr, 0);
#endif
@ -1310,7 +1313,7 @@ static int nn_usock_recv_raw(struct nn_usock *self, void *buf, size_t *len)
}
} else if ( hdr.msg_controllen > 0 )
nn_process_cmsg(self,&hdr);
//PNACL_message("nbytes.%d length.%d *len %d\n",(int)nbytes,(int)length,(int)*len);
printf("nbytes.%d length.%d *len %d\n",(int)nbytes,(int)length,(int)*len);
// If the data were received directly into the place we can return straight away
if ( usebuf != 0 )

13
crypto777/nanosrc/aio/usock_posix.c_dev

@ -31,11 +31,11 @@
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#ifndef __PNACL
//#ifndef __PNACL
#include <sys/uio.h>
#else
#include <glibc-compat/sys/uio.h>
#endif
//#else
//#include <glibc-compat/sys/uio.h>
//#endif
#define NN_USOCK_STATE_IDLE 1
#define NN_USOCK_STATE_STARTING 2
@ -287,7 +287,8 @@ int nn_usock_bind (struct nn_usock *self, const struct sockaddr *addr,
/* Allow re-using the address. */
opt = 1;
rc = setsockopt (self->s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt));
errno_assert (rc == 0);
// ignore SO_REUSEADDR failures
//errno_assert (rc == 0);
rc = bind (self->s, addr, (socklen_t) addrlen);
if (nn_slow (rc != 0))
@ -999,7 +1000,7 @@ static int32_t nn_usock_send_raw(struct nn_usock *self,struct msghdr *hdr)
#else
nbytes = sendmsg(self->s,hdr,0);
#endif
PostMessage("nn_usock_send_raw nbytes.%d for sock.%d\n",(int32_t)nbytes,self->s);
printf("nn_usock_send_raw nbytes.%d for sock.%d\n",(int32_t)nbytes,self->s);
if ( nn_slow(nbytes < 0) ) // Handle errors
{
if ( nn_fast(errno == EAGAIN || errno == EWOULDBLOCK) )

4
crypto777/nanosrc/aio/usock_posix.h

@ -25,11 +25,7 @@
#include <sys/types.h>
#include <sys/socket.h>
#ifndef __PNACL
#include <sys/uio.h>
#else
#include <glibc-compat/sys/uio.h>
#endif
struct nn_usock {

2
crypto777/nanosrc/aio/usock_win.c

@ -126,7 +126,7 @@ int nn_usock_start (struct nn_usock *self, int domain, int type, int protocol)
#if defined HANDLE_FLAG_INHERIT
BOOL brc;
#endif
printf("nn_usock_start protocol %d\n",protocol);
/* NamedPipes aren't sockets. They don't need all the socket
initialisation stuff. */
if (domain != AF_UNIX) {

50
crypto777/nanosrc/aio/worker_posix.c

@ -102,29 +102,28 @@ void nn_worker_task_term (struct nn_worker_task *self)
int nn_worker_init(struct nn_worker *self)
{
int32_t rc;
PNACL_message("nn_worker_init %p\n",self);
//sleep(1);
//PNACL_msg("nn_worker_init %p\n",self);
rc = nn_efd_init(&self->efd);
PNACL_message("efd init: rc.%d\n",rc);
//PNACL_msg("efd init: rc.%d\n",rc);
if ( rc < 0 )
return rc;
PNACL_message("nn_mutex_init\n");
//PNACL_msg("nn_mutex_init\n");
nn_mutex_init(&self->sync);
PNACL_message("nn_queue_init\n");
//PNACL_msg("nn_queue_init\n");
nn_queue_init(&self->tasks);
PNACL_message("nn_queue_item_init\n");
//PNACL_msg("nn_queue_item_init\n");
nn_queue_item_init(&self->stop);
PNACL_message("nn_poller_init\n");
//PNACL_msg("nn_poller_init\n");
nn_poller_init(&self->poller);
PNACL_message("nn_poller_add\n");
//PNACL_msg("nn_poller_add\n");
nn_poller_add(&self->poller,nn_efd_getfd(&self->efd),&self->efd_hndl);
PNACL_message("nn_poller_set_in\n");
//PNACL_msg("nn_poller_set_in\n");
nn_poller_set_in(&self->poller, &self->efd_hndl);
PNACL_message("nn_timerset_init\n");
//PNACL_msg("nn_timerset_init\n");
nn_timerset_init(&self->timerset);
PNACL_message("nn_thread_init\n");
//PNACL_msg("nn_thread_init\n");
nn_thread_init(&self->thread,nn_worker_routine, self);
PNACL_message("finished nn_worker_init\n");
//PNACL_msg("finished nn_worker_init\n");
return 0;
}
@ -174,9 +173,11 @@ static void nn_worker_routine (void *arg)
struct nn_worker_task *task;
struct nn_worker_fd *fd;
struct nn_worker_timer *timer;
PNACL_message("nn_worker_routine started\n");
printf("nn_worker_routine started\n");
self = (struct nn_worker*) arg;
#ifndef FROM_JS
while ( 1 ) // Infinite loop. It will be interrupted only when the object is shut down.
#endif
{
// Wait for new events and/or timeouts.
rc = nn_poller_wait(&self->poller,nn_timerset_timeout (&self->timerset));
@ -186,7 +187,7 @@ static void nn_worker_routine (void *arg)
rc = nn_timerset_event(&self->timerset, &thndl);
if ( rc == -EAGAIN )
break;
PNACL_message("nn_worker process expired user\n");
printf("nn_worker process expired user\n");
errnum_assert(rc == 0, -rc);
timer = nn_cont(thndl, struct nn_worker_timer, hndl);
nn_ctx_enter(timer->owner->ctx);
@ -198,7 +199,7 @@ static void nn_worker_routine (void *arg)
rc = nn_poller_event(&self->poller,&pevent,&phndl); // Get next poller event, such as IN or OUT
if ( nn_slow(rc == -EAGAIN) )
break;
PNACL_message("nn_worker process all events from the poller\n");
printf("nn_worker process all events from the poller\n");
if ( phndl == &self->efd_hndl ) // If there are any new incoming worker tasks, process them
{
nn_assert (pevent == NN_POLLER_IN);
@ -213,31 +214,36 @@ static void nn_worker_routine (void *arg)
item = nn_queue_pop(&tasks); // Next worker task
if ( nn_slow(!item) )
break;
PNACL_message("nn_worker next worker task\n");
printf("nn_worker next worker task\n");
if ( nn_slow(item == &self->stop) ) // If the worker thread is asked to stop, do so
{
nn_queue_term(&tasks);
return;
}
// It's a user-defined task. Notify the user that it has arrived in the worker thread
PNACL_message("nn_worker user defined task\n");
printf("nn_worker user defined task\n");
task = nn_cont(item,struct nn_worker_task,item);
nn_ctx_enter(task->owner->ctx);
nn_fsm_feed(task->owner,task->src,NN_WORKER_TASK_EXECUTE,task);
nn_ctx_leave (task->owner->ctx);
}
nn_queue_term (&tasks);
#ifdef FROM_JS
printf("done worker ITER\n");
return;
#else
continue;
#endif
}
PNACL_message("nn_worker true i/o, invoke handler\n");
printf("nn_worker true i/o, invoke handler\n");
fd = nn_cont(phndl,struct nn_worker_fd,hndl); // It's a true I/O event. Invoke the handler
PNACL_message("nn_worker true i/o, fd.%p\n",fd);
printf("nn_worker true i/o, fd.%p\n",fd);
nn_ctx_enter(fd->owner->ctx);
PNACL_message("nn_worker true i/o, after nn_ctx_enter\n");
printf("nn_worker true i/o, after nn_ctx_enter\n");
nn_fsm_feed(fd->owner,fd->src,pevent,fd);
PNACL_message("nn_worker true i/o, after nn_fsm_feed leave.%p\n",fd->owner->ctx);
printf("nn_worker true i/o, after nn_fsm_feed leave.%p\n",fd->owner->ctx);
nn_ctx_leave(fd->owner->ctx);
PNACL_message("nn_worker true i/o, after nn_ctx_leave\n");
printf("nn_worker true i/o, after nn_ctx_leave\n");
}
}
}

90
crypto777/nanosrc/core/global.c

@ -201,9 +201,9 @@ static void nn_global_add_transport (struct nn_transport *transport)
static void nn_global_add_socktype (struct nn_socktype *socktype)
{
PNACL_message("add socktype %p -> %p\n",socktype,&SELF.socktypes);
PNACL_msg("add socktype %p -> %p\n",socktype,&SELF.socktypes);
nn_list_insert (&SELF.socktypes, &socktype->item,nn_list_end (&SELF.socktypes));
PNACL_message("added socktype %p -> %p\n",socktype,&SELF.socktypes);
PNACL_msg("added socktype %p -> %p\n",socktype,&SELF.socktypes);
}
void nn_global_init (void)
{
@ -218,7 +218,7 @@ void nn_global_init (void)
nn_assert (LOBYTE (data.wVersion) == 2 &&
HIBYTE (data.wVersion) == 2);
#endif
PNACL_message("nn_global_init\n");
PNACL_msg("nn_global_init\n");
nn_alloc_init(); // Initialise the memory allocation subsystem
nn_random_seed(); // Seed the pseudo-random number generator
// Allocate the global table of SP sockets.
@ -227,7 +227,7 @@ void nn_global_init (void)
for (i=0; i<NN_MAX_SOCKETS; i++)
SELF.socks[i] = NULL;
SELF.nsocks = SELF.flags = 0;
PNACL_message("do getenv\n");
PNACL_msg("do getenv\n");
envvar = getenv("NN_PRINT_ERRORS"); // Print connection and accepting errors to the stderr
SELF.print_errors = envvar && *envvar; // any non-empty string is true
envvar = getenv("NN_PRINT_STATISTICS"); // Print socket statistics to stderr
@ -236,26 +236,26 @@ PNACL_message("do getenv\n");
alloc_assert (SELF.unused);
for (i=0; i<NN_MAX_SOCKETS; i++)
SELF.unused [i] = NN_MAX_SOCKETS - i - 1;
PNACL_message("list init\n");
PNACL_msg("list init\n");
// Initialise other parts of the global state.
nn_list_init(&SELF.transports);
nn_list_init(&SELF.socktypes);
//sleep(1);
PNACL_message("transports init\n");
PNACL_msg("transports init\n");
// Plug in individual transports.
//nn_global_add_transport(nn_ipc);
nn_global_add_transport(nn_ipc);
nn_global_add_transport(nn_tcp);
//nn_global_add_transport(nn_inproc);
//nn_global_add_transport(nn_ws);
//nn_global_add_transport(nn_tcpmux);
nn_global_add_transport(nn_inproc);
nn_global_add_transport(nn_ws);
//nn_global_add_transport(nn_tcpmux);
//sleep(1);
PNACL_message("socktypes init\n");
PNACL_msg("socktypes init\n");
// Plug in individual socktypes
nn_global_add_socktype(nn_pair_socktype);
//sleep(1);
PNACL_message("nn_xpair_socktype init\n");
PNACL_msg("nn_xpair_socktype init\n");
nn_global_add_socktype(nn_xpair_socktype);
PNACL_message("did nn_xpair_socktype init\n");
PNACL_msg("did nn_xpair_socktype init\n");
nn_global_add_socktype(nn_rep_socktype);
nn_global_add_socktype(nn_req_socktype);
nn_global_add_socktype(nn_xrep_socktype);
@ -275,19 +275,19 @@ PNACL_message("socktypes init\n");
nn_global_add_socktype(nn_bus_socktype);
nn_global_add_socktype(nn_xbus_socktype);
//sleep(1);
PNACL_message("do pool init\n");
PNACL_msg("do pool init\n");
nn_pool_init(&SELF.pool); // Start the worker threads
//sleep(1);
PNACL_message("do FSM init\n");
PNACL_msg("do FSM init\n");
nn_fsm_init_root(&SELF.fsm,nn_global_handler,nn_global_shutdown,&SELF.ctx); // Start FSM
SELF.state = NN_GLOBAL_STATE_IDLE;
PNACL_message("ctx init\n");
PNACL_msg("ctx init\n");
nn_ctx_init(&SELF.ctx, nn_global_getpool(),NULL);
PNACL_message("timer init\n");
PNACL_msg("timer init\n");
nn_timer_init(&SELF.stat_timer,NN_GLOBAL_SRC_STAT_TIMER,&SELF.fsm);
PNACL_message("do FSM start\n");
PNACL_msg("do FSM start\n");
nn_fsm_start(&SELF.fsm);
PNACL_message("special sockets init\n");
PNACL_msg("special sockets init\n");
// Initializing special sockets.
addr = getenv("NN_STATISTICS_SOCKET");
if ( addr != 0 )
@ -503,7 +503,7 @@ int32_t nn_global_create_socket(int32_t domain,int32_t protocol)
int nn_socket(int domain,int protocol)
{
int rc;
PNACL_message("nn_socket flags.%d\n",SELF.flags);
PNACL_msg("nn_socket flags.%d\n",SELF.flags);
nn_glock_lock();
if (nn_slow (SELF.flags & NN_CTX_FLAG_ZOMBIE)) // If nn_term() was already called, return ETERM
{
@ -511,7 +511,7 @@ int nn_socket(int domain,int protocol)
errno = ETERM;
return -1;
}
//PNACL_message("nn_socket flags.%d\n",SELF.flags);
//PNACL_msg("nn_socket flags.%d\n",SELF.flags);
nn_global_init(); // Make sure that global state is initialised
rc = nn_global_create_socket (domain, protocol);
if ( rc < 0 )
@ -522,7 +522,7 @@ int nn_socket(int domain,int protocol)
return -1;
}
nn_glock_unlock();
//PNACL_message("did nn_global_init\n");
//PNACL_msg("did nn_global_init\n");
return rc;
}
@ -652,6 +652,7 @@ int32_t nn_send(int32_t s,const void *buf,size_t len,int32_t flags)
hdr.msg_iovlen = 1;
hdr.msg_control = NULL;
hdr.msg_controllen = 0;
printf("nn_send calling nn_sendmsg\n");
return nn_sendmsg(s,&hdr,flags);
}
@ -667,20 +668,22 @@ int32_t nn_recv(int32_t s,void *buf,size_t len,int32_t flags)
return nn_recvmsg(s,&hdr,flags);
}
#ifdef NN_USE_MYMSG
#if NN_USE_MYMSG
int32_t nn_sendmsg(int32_t s,const struct nn_msghdr *msghdr,int32_t flags)
{
int32_t rc,i,nnmsg; size_t sz; struct nn_iovec *iov; struct nn_msg msg; void *chunk;
//PNACL_message("nn_sendmsg.(%d) \n",s);
printf("nn_sendmsg.(%d) \n",s);
NN_BASIC_CHECKS;
if ( nn_slow(!msghdr) )
{
printf("nn_sendmsg.(%d) einval\n",s);
errno = EINVAL;
return -1;
}
if ( nn_slow(msghdr->msg_iovlen < 0) )
{
printf("nn_sendmsg.(%d) emsgsize\n",s);
errno = EMSGSIZE;
return -1;
}
@ -689,6 +692,7 @@ int32_t nn_sendmsg(int32_t s,const struct nn_msghdr *msghdr,int32_t flags)
chunk = *(void **)msghdr->msg_iov[0].iov_base;
if ( nn_slow(chunk == NULL) )
{
printf("nn_sendmsg.(%d) efault\n",s);
errno = EFAULT;
return -1;
}
@ -731,6 +735,7 @@ int32_t nn_sendmsg(int32_t s,const struct nn_msghdr *msghdr,int32_t flags)
}
nn_assert(msghdr->msg_control == 0); // cant support msgs until sendmsg()/recvmsg() native to pnacl
rc = nn_sock_send(SELF.socks[s],&msg,flags); // Send it further down the stack
printf("rc from nn_socksend.%d\n",rc);
if ( nn_slow(rc < 0) )
{
// If we are dealing with user-supplied buffer, detach it from the message object
@ -772,13 +777,13 @@ int32_t nn_recvmsg(int32_t s,struct nn_msghdr *msghdr,int32_t flags)
chunk = nn_chunkref_getchunk(&msg.body);
*(void **)(msghdr->msg_iov[0].iov_base) = chunk;
sz = nn_chunk_size(chunk);
//PNACL_message("got message -> iov_base.%p sz.%d\n",msghdr->msg_iov[0].iov_base,(int32_t)sz);
//PNACL_msg("got message -> iov_base.%p sz.%d\n",msghdr->msg_iov[0].iov_base,(int32_t)sz);
}
else // Copy the message content into the supplied gather array
{
data = nn_chunkref_data(&msg.body);
sz = nn_chunkref_size(&msg.body);
//PNACL_message("got message -> data.%p sz.%d\n",data,(int32_t)sz);
//PNACL_msg("got message -> data.%p sz.%d\n",data,(int32_t)sz);
for (i=0; i!=msghdr->msg_iovlen; i++)
{
iov = &msghdr->msg_iov[i];
@ -809,15 +814,17 @@ int32_t nn_recvmsg(int32_t s,struct nn_msghdr *msghdr,int32_t flags)
int32_t nn_sendmsg(int32_t s,const struct nn_msghdr *msghdr,int32_t flags)
{
int32_t rc,i,nnmsg; size_t sz,spsz; struct nn_iovec *iov; struct nn_msg msg; void *chunk; struct nn_cmsghdr *cmsg;
//PNACL_message("nn_sendmsg.(%d) \n",s);
printf("nn_sendmsg.(%d) \n",s);
NN_BASIC_CHECKS;
if ( nn_slow(!msghdr) )
{
printf("nn_sendmsg.EINVAL\n");
errno = EINVAL;
return -1;
}
if ( nn_slow(msghdr->msg_iovlen < 0) )
{
printf("nn_sendmsg.EMSGSIZE\n");
errno = EMSGSIZE;
return -1;
}
@ -827,6 +834,7 @@ int32_t nn_sendmsg(int32_t s,const struct nn_msghdr *msghdr,int32_t flags)
if ( nn_slow(chunk == NULL) )
{
errno = EFAULT;
printf("nn_sendmsg.EFAULT\n");
return -1;
}
sz = nn_chunk_size(chunk);
@ -905,6 +913,7 @@ int32_t nn_sendmsg(int32_t s,const struct nn_msghdr *msghdr,int32_t flags)
/* Send it further down the stack. */
rc = nn_sock_send (SELF.socks [s], &msg, flags);
printf("nn_sock_send rc.%d\n",rc);
if (nn_slow (rc < 0)) {
/* If we are dealing with user-supplied buffer, detach it from
@ -928,7 +937,7 @@ int32_t nn_recvmsg(int32_t s,struct nn_msghdr *msghdr,int32_t flags)
{
struct nn_msg msg; uint8_t *data; struct nn_iovec *iov; void *chunk,*ctrl; struct nn_cmsghdr *chdr;
int32_t i,rc; size_t sz,hdrssz,ctrlsz,spsz,sptotalsz;
//PNACL_message("nn_recvmsg.(%d) \n",s);
//PNACL_msg("nn_recvmsg.(%d) \n",s);
NN_BASIC_CHECKS;
if ( nn_slow(!msghdr) )
{
@ -940,7 +949,7 @@ int32_t nn_recvmsg(int32_t s,struct nn_msghdr *msghdr,int32_t flags)
errno = EMSGSIZE;
return -1;
}
//PNACL_message("get a message from sock.%d\n",s);
//PNACL_msg("get a message from sock.%d\n",s);
rc = nn_sock_recv(SELF.socks[s],&msg,flags); // Get a message
if ( nn_slow(rc < 0) )
{
@ -952,13 +961,13 @@ int32_t nn_recvmsg(int32_t s,struct nn_msghdr *msghdr,int32_t flags)
chunk = nn_chunkref_getchunk(&msg.body);
*(void **)(msghdr->msg_iov[0].iov_base) = chunk;
sz = nn_chunk_size(chunk);
//PNACL_message("got message -> iov_base.%p sz.%d\n",msghdr->msg_iov[0].iov_base,(int32_t)sz);
//PNACL_msg("got message -> iov_base.%p sz.%d\n",msghdr->msg_iov[0].iov_base,(int32_t)sz);
}
else // Copy the message content into the supplied gather array
{
data = nn_chunkref_data(&msg.body);
sz = nn_chunkref_size (&msg.body);
//PNACL_message("got message -> data.%p sz.%d\n",data,(int32_t)sz);
//PNACL_msg("got message -> data.%p sz.%d\n",data,(int32_t)sz);
for (i=0; i!=msghdr->msg_iovlen; i++)
{
iov = &msghdr->msg_iov[i];
@ -1150,7 +1159,7 @@ static void nn_global_submit_errors (int i, struct nn_sock *s,
len = snprintf (curbuf, buf_left,
" nanomsg: Endpoint %d [%s] error: %s\n",
ep->eid, nn_ep_getaddr (ep), nn_strerror (ep->last_errno));
PNACL_message("%s\n",curbuf);
PNACL_msg("%s\n",curbuf);
#endif
if (buf_left < len)
break;
@ -1244,12 +1253,12 @@ static int nn_global_create_ep (int s, const char *addr, int bind)
return -EINVAL;
protosz = delim - addr;
addr += protosz + 3;
#ifdef NN_USE_MYMSG
if ( strncmp("inproc",proto,strlen("inproc")) != 0 && strncmp("ipc",proto,strlen("ipc")) != 0 && strncmp("tcp",proto,strlen("tcp")) != 0 )
#if NN_USE_MYMSG
if ( strncmp("inproc",proto,strlen("inproc")) != 0 && strncmp("ipc",proto,strlen("ipc")) != 0 && strncmp("tcp",proto,strlen("tcp")) && strncmp("ws",proto,strlen("ws")) != 0 )
{
PNACL_message("only ipc, inproc and tcp transport is supported\n");
printf("only ipc, inproc and tcp transport is supported\n");
fprintf(stderr,"only ipc, inproc and tcp transport is supported\n");
PNACL_msg("only ipc, inproc, ws and tcp transport is supported\n");
printf("only ipc, inproc, ws and tcp transport is supported\n");
fprintf(stderr,"only ipc, inproc, ws and tcp transport is supported\n");
exit(-1);
return -EPROTONOSUPPORT;
}
@ -1267,7 +1276,10 @@ static int nn_global_create_ep (int s, const char *addr, int bind)
tp = NULL;
}
if ( !tp ) // The protocol specified doesn't match any known protocol
{
printf("unknown protocol\n");
return -EPROTONOSUPPORT;
}
rc = nn_sock_add_ep (SELF.socks [s], tp, bind, addr); // Ask the socket to create the endpoint
return rc;
}
@ -1324,12 +1336,12 @@ static void nn_global_handler (struct nn_fsm *myself,int src, int type, NN_UNUSE
nn_timer_start (&global->stat_timer, 10000); // Start statistics collection timer
return;
default:
PNACL_message("bad action %d type %d\n",src,type);
PNACL_msg("bad action %d type %d\n",src,type);
nn_fsm_bad_action(global->state, src, type);
}
default:
PNACL_message("bad source %d\n",src);
PNACL_msg("bad source %d\n",src);
nn_fsm_bad_source(global->state, src, type);
}

9
crypto777/nanosrc/core/pipe.c

@ -58,7 +58,7 @@ void nn_pipebase_init(struct nn_pipebase *self,const struct nn_pipebase_vfptr *v
memcpy(&self->options,&epbase->ep->options,sizeof(struct nn_ep_options));
nn_fsm_event_init(&self->in);
nn_fsm_event_init(&self->out);
PNACL_message("pipebase_init vfptr.%p recv.%p rcvprio.%d\n",vfptr,vfptr->recv,self->options.rcvprio);
PNACL_msg("pipebase_init vfptr.%p recv.%p rcvprio.%d\n",vfptr,vfptr->recv,self->options.rcvprio);
}
void nn_pipebase_term (struct nn_pipebase *self)
@ -78,7 +78,7 @@ int nn_pipebase_start (struct nn_pipebase *self)
self->instate = NN_PIPEBASE_INSTATE_ASYNC;
self->outstate = NN_PIPEBASE_OUTSTATE_IDLE;
rc = nn_sock_add(self->sock,(struct nn_pipe *)self);
PNACL_message("nn_pipebase_start self.%p rc.%d\n",self,rc);
PNACL_msg("nn_pipebase_start self.%p rc.%d\n",self,rc);
if ( nn_slow(rc < 0) )
{
self->state = NN_PIPEBASE_STATE_FAILED;
@ -98,7 +98,7 @@ void nn_pipebase_stop(struct nn_pipebase *self)
void nn_pipebase_received(struct nn_pipebase *self)
{
PNACL_message("nn_pipebase_received\n");
PNACL_msg("nn_pipebase_received\n");
if ( nn_fast(self->instate == NN_PIPEBASE_INSTATE_RECEIVING) )
{
self->instate = NN_PIPEBASE_INSTATE_RECEIVED;
@ -176,6 +176,7 @@ int nn_pipe_send(struct nn_pipe *self,struct nn_msg *msg)
int rc;
struct nn_pipebase *pipebase;
pipebase = (struct nn_pipebase *)self;
printf("pipesend\n");
nn_assert (pipebase->outstate == NN_PIPEBASE_OUTSTATE_IDLE);
pipebase->outstate = NN_PIPEBASE_OUTSTATE_SENDING;
rc = pipebase->vfptr->send(pipebase,msg);
@ -196,7 +197,7 @@ int nn_pipe_recv(struct nn_pipe *self,struct nn_msg *msg)
pipebase = (struct nn_pipebase*) self;
nn_assert (pipebase->instate == NN_PIPEBASE_INSTATE_IDLE);
pipebase->instate = NN_PIPEBASE_INSTATE_RECEIVING;
PNACL_message("call pipebase recv\n");
PNACL_msg("call pipebase recv\n");
rc = pipebase->vfptr->recv (pipebase,msg);
errnum_assert (rc >= 0, -rc);
if ( nn_fast(pipebase->instate == NN_PIPEBASE_INSTATE_RECEIVED) )

15
crypto777/nanosrc/core/sock.c

@ -477,6 +477,7 @@ struct nn_ep *nn_find_ep(struct nn_sock *self,int32_t eid,const char *addr,struc
int nn_sock_add_ep(struct nn_sock *self,struct nn_transport *transport,int32_t bind,const char *addr)
{
int rc,eid; struct nn_ep *ep;
printf("nn_sock_add_ep\n");
nn_ctx_enter (&self->ctx);
if ( (ep= nn_find_ep(self,0,addr,transport,bind)) == NULL ) // The endpoint doesn't exist
{
@ -484,16 +485,17 @@ int nn_sock_add_ep(struct nn_sock *self,struct nn_transport *transport,int32_t b
rc = nn_ep_init(ep,NN_SOCK_SRC_EP,self,self->eid,transport,bind,addr);
if ( nn_slow(rc < 0) )
{
printf("nn_sock_add_ep nn_ep_init rc.%d\n",rc);
nn_free(ep);
nn_ctx_leave(&self->ctx);
return rc;
}
nn_ep_start(ep);
PNACL_message("ep sock.(%s) started %s://(%s) bind.%d\n",self->socket_name,transport->name,addr,bind);
printf("ep sock.(%s) started %s://(%s) bind.%d\n",self->socket_name,transport->name,addr,bind);
eid = self->eid++; // Increase the endpoint ID for the next endpoint
nn_list_insert(&self->eps,&ep->item,nn_list_end(&self->eps)); // Add to the list of active endpoints
nn_ctx_leave (&self->ctx);
} else PNACL_message("self->sock.(%s) %p already has (%s)\n",self->socket_name,self->sockbase->sock,addr);
} else printf("self->sock.(%s) %p already has (%s)\n",self->socket_name,self->sockbase->sock,addr);
return(ep->eid);
}
@ -548,6 +550,7 @@ int nn_sock_send(struct nn_sock *self, struct nn_msg *msg, int flags)
/* Try to send the message in a non-blocking way. */
rc = self->sockbase->vfptr->send (self->sockbase, msg);
printf("sockbase send rc.%d\n",rc);
if (nn_fast (rc == 0)) {
nn_ctx_leave (&self->ctx);
return 0;
@ -560,8 +563,7 @@ int nn_sock_send(struct nn_sock *self, struct nn_msg *msg, int flags)
return rc;
}
/* If the message cannot be sent at the moment and the send call
is non-blocking, return immediately. */
// If the message cannot be sent at the moment and the send call is non-blocking, return immediately.
if (nn_fast (flags & NN_DONTWAIT)) {
nn_ctx_leave (&self->ctx);
return -EAGAIN;
@ -673,6 +675,7 @@ int nn_sock_add(struct nn_sock *self, struct nn_pipe *pipe)
{
int rc;
rc = self->sockbase->vfptr->add(self->sockbase,pipe);
printf("nn_sock_add rc.%d\n",rc);
if (nn_slow (rc >= 0)) {
nn_sock_stat_increment (self, NN_STAT_CURRENT_CONNECTIONS, 1);
}
@ -973,12 +976,12 @@ void nn_sock_report_error(struct nn_sock *self,struct nn_ep *ep,int32_t errnum,c
if ( ep != 0 )
{
fprintf(stderr,"nanomsg: socket.%s[%s]: Error: %s\n",self->socket_name,nn_ep_getaddr(ep),nn_strerror(errnum));
PNACL_message("nanomsg: socket.%s[%s]: [%s:%d] Error: %s\n",self->socket_name,nn_ep_getaddr(ep),fname,linenum,nn_strerror(errnum));
PNACL_msg("nanomsg: socket.%s[%s]: [%s:%d] Error: %s\n",self->socket_name,nn_ep_getaddr(ep),fname,linenum,nn_strerror(errnum));
}
else
{
fprintf(stderr,"nanomsg: socket.%s: Error: %s\n",self->socket_name, nn_strerror(errnum));
PNACL_message("nanomsg: socket.%s: [%s:%d] Error: %s\n",self->socket_name,fname,linenum,nn_strerror(errnum));
PNACL_msg("nanomsg: socket.%s: [%s:%d] Error: %s\n",self->socket_name,fname,linenum,nn_strerror(errnum));
}
}

8
crypto777/nanosrc/devices/tcpmuxd.c

@ -53,12 +53,7 @@ int nn_tcpmuxd (int port)
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/time.h>
#ifndef __PNACL
#include <sys/un.h>
#else
#include <glibc-compat/sys/un.h>
#include <glibc-compat/sys/uio.h>
#endif
#include <stddef.h>
#include <ctype.h>
#include <poll.h>
@ -101,7 +96,8 @@ int nn_tcpmuxd (int port)
opt = 1;
rc = setsockopt (tcp_listener, SOL_SOCKET, SO_REUSEADDR, &opt,
sizeof (opt));
if (rc != 0) { return -1; }
// ignore SO_REUSEADDR failures
//if (rc != 0) { return -1; }
memset (&tcp_addr, 0, sizeof (tcp_addr));
tcp_addr.sin_family = AF_INET;
tcp_addr.sin_port = htons (port);

1
crypto777/nanosrc/nn.h

@ -30,6 +30,7 @@ extern "C" {
#include <errno.h>
#include <stddef.h>
#include <stdint.h>
#include "nn_config.h"
/* Handle DSO symbol visibility */

14
crypto777/nanosrc/nn_config.h

@ -32,8 +32,8 @@
// need one of following 3, listed in order of precedence, used by efd*
//#define NN_HAVE_EVENTFD 1
//#define NN_HAVE_PIPE 1
#define NN_HAVE_SOCKETPAIR 1
#define NN_HAVE_PIPE 1
//#define NN_HAVE_SOCKETPAIR 1
// need one of following 3, listed in order of precedence, used by poller*
#define NN_USE_POLL 1
@ -46,21 +46,13 @@
#define NN_HAVE_MSG_CONTROL 0
//#define STANDALONE 1
#define PNACL_msg(...)
#ifdef __PNACL
//#define FD_CLOEXEC 1
void PNACL_message(const char* format, ...);
#include <glibc-compat/sys/uio.h>
#include <glibc-compat/sys/un.h>
#else
#if !defined(WIN32)
//#define NN_ENABLE_EXTRA 1
#define PNACL_message printf
#include <sys/uio.h>
#include <sys/un.h>
#endif
#endif
/* Size of the buffer used for batch-reads of inbound data. To keep the
performance optimal make sure that this value is larger than network MTU. */

3
crypto777/nanosrc/protocols/pipeline/xpush.c

@ -115,7 +115,7 @@ static int nn_xpush_add (struct nn_sockbase *self, struct nn_pipe *pipe)
alloc_assert (data);
nn_pipe_setdata (pipe, data);
nn_lb_add (&xpush->lb, &data->lb, pipe, sndprio);
printf("nn_xpush_add\n");
return 0;
}
@ -160,6 +160,7 @@ static int nn_xpush_events (struct nn_sockbase *self)
static int nn_xpush_send (struct nn_sockbase *self, struct nn_msg *msg)
{
printf("nn_xpush_send\n");
return nn_lb_send (&nn_cont (self, struct nn_xpush, sockbase)->lb,
msg, NULL);
}

2
crypto777/nanosrc/protocols/reqrep/xreq.c

@ -101,7 +101,7 @@ int nn_xreq_add(struct nn_sockbase *self, struct nn_pipe *pipe)
nn_pipe_setdata(pipe,data);
nn_lb_add(&xreq->lb,&data->lb,pipe,sndprio);
nn_fq_add(&xreq->fq,&data->fq,pipe,rcvprio);
printf("nn_xreq_add\n");
return 0;
}

7
crypto777/nanosrc/protocols/utils/lb.c

@ -37,8 +37,7 @@ void nn_lb_term (struct nn_lb *self)
nn_priolist_term (&self->priolist);
}
void nn_lb_add (struct nn_lb *self, struct nn_lb_data *data,
struct nn_pipe *pipe, int priority)
void nn_lb_add (struct nn_lb *self, struct nn_lb_data *data,struct nn_pipe *pipe, int priority)
{
nn_priolist_add (&self->priolist, &data->priodata, pipe, priority);
}
@ -68,14 +67,16 @@ int nn_lb_send (struct nn_lb *self, struct nn_msg *msg, struct nn_pipe **to)
{
int rc;
struct nn_pipe *pipe;
printf("nn_lb_send\n");
/* Pipe is NULL only when there are no avialable pipes. */
pipe = nn_priolist_getpipe (&self->priolist);
printf("nn_lb_send pipe.%p\n",pipe);
if (nn_slow (!pipe))
return -EAGAIN;
/* Send the messsage. */
rc = nn_pipe_send (pipe, msg);
printf("nn_pipe_send rc.%d\n",rc);
errnum_assert (rc >= 0, -rc);
/* Move to the next pipe. */

4
crypto777/nanosrc/protocols/utils/priolist.c

@ -54,7 +54,7 @@ void nn_priolist_add(struct nn_priolist *self,struct nn_priolist_data *data, str
{
data->pipe = pipe;
data->priority = priority;
//printf("nn_priolist_add.%p data.%p priority.%d\n",self,data,priority);
printf("nn_priolist_add.%p data.%p priority.%d\n",self,data,priority);
nn_list_item_init (&data->item);
}
@ -139,7 +139,7 @@ struct nn_pipe *nn_priolist_getpipe(struct nn_priolist *self)
//printf("nn_priolist_getpipe.%p -1 current it is\n",self);
return NULL;
}
//printf("nn_priolist_getpipe.%p current.%d slot.%p\n",self,self->current,self->slots[self->current - 1].current->pipe);
printf("nn_priolist_getpipe.%p current.%d slot.%p\n",self,self->current,self->slots[self->current - 1].current->pipe);
return self->slots[self->current - 1].current->pipe;
}

3
crypto777/nanosrc/protocols/utils/priolist.h

@ -86,8 +86,7 @@ void nn_priolist_activate (struct nn_priolist *self, struct nn_priolist_data *da
0 otherwise. */
int nn_priolist_is_active (struct nn_priolist *self);
/* Get the pointer to the current pipe. If there's no pipe in the list,
NULL is returned. */
// Get the pointer to the current pipe. If there's no pipe in the list, NULL is returned.
struct nn_pipe *nn_priolist_getpipe (struct nn_priolist *self);
/* Moves to the next pipe in the list. If 'release' is set to 1, the current

6
crypto777/nanosrc/tests/testutil.h

@ -26,9 +26,9 @@
#include <stdio.h>
#include <stdlib.h>
#ifdef __PNACL
#define printf PostMessage
#endif
//#ifdef __PNACL
//#define printf PostMessage
//#endif
#include "../utils/attr.h"
#include "../utils/err.h"

4
crypto777/nanosrc/transports/ipc/bipc.c

@ -39,12 +39,8 @@
#include "../../utils/win.h"
#else
#include <unistd.h>
#ifndef __PNACL
#include <sys/uio.h>
#include <sys/un.h>
#else
#include <glibc-compat/sys/un.h>
#endif
#include <fcntl.h>
#endif

5
crypto777/nanosrc/transports/ipc/cipc.c

@ -39,13 +39,8 @@
#include "../../utils/win.h"
#else
#include <unistd.h>
#ifndef __PNACL
#include <sys/uio.h>
#include <sys/un.h>
#else
#include <glibc-compat/sys/uio.h>
#include <glibc-compat/sys/un.h>
#endif
#endif
#define NN_CIPC_STATE_IDLE 1

4
crypto777/nanosrc/transports/ipc/ipc.c

@ -37,11 +37,7 @@
#include "../../utils/win.h"
#else
#include <sys/socket.h>
#ifndef __PNACL
#include <sys/uio.h>
#else
#include <glibc-compat/sys/un.h>
#endif
#include <unistd.h>
#endif

4
crypto777/nanosrc/transports/tcpmux/btcpmux.c

@ -44,12 +44,8 @@
#include "../../utils/win.h"
#else
#include <unistd.h>
#ifndef __PNACL
#include <sys/uio.h>
#include <sys/un.h>
#else
#include <glibc-compat/sys/un.h>
#endif
#include <arpa/inet.h>
#endif

6
crypto777/nanosrc/transports/utils/tcpmux.c

@ -28,11 +28,7 @@
#else
#include <unistd.h>
#include <sys/socket.h>
#ifndef __PNACL
#include <sys/un.h>
#else
#include <glibc-compat/sys/un.h>
#endif
#endif
#include "tcpmux.h"
@ -87,7 +83,7 @@ int tcpmux_accept (int s)
memset (&hdr, 0, sizeof (hdr));
hdr.msg_iov = &iov;
hdr.msg_iovlen = 1;
#ifndef NN_USE_MYMSG
#if !NN_USE_MYMSG
unsigned char buf [256];
hdr.msg_control = buf;
hdr.msg_controllen = sizeof (buf);

4
crypto777/nanosrc/transports/ws/cws.c

@ -329,7 +329,7 @@ static void nn_cws_handler (struct nn_fsm *self, int src, int type,
struct nn_cws *cws;
cws = nn_cont (self, struct nn_cws, fsm);
printf("cws_handler src.%d type.%d state.%d\n",src,type,cws->state);
switch (cws->state) {
/******************************************************************************/
@ -409,6 +409,7 @@ static void nn_cws_handler (struct nn_fsm *self, int src, int type,
case NN_CWS_SRC_USOCK:
switch (type) {
case NN_USOCK_CONNECTED:
printf("cws connected\n");
nn_sws_start (&cws->sws, &cws->usock, NN_WS_CLIENT,
nn_chunkref_data (&cws->resource),
nn_chunkref_data (&cws->remote_host));
@ -421,6 +422,7 @@ static void nn_cws_handler (struct nn_fsm *self, int src, int type,
nn_epbase_clear_error (&cws->epbase);
return;
case NN_USOCK_ERROR:
printf("cws NN_USOCK_ERROR\n");
nn_epbase_set_error (&cws->epbase,nn_usock_geterrno (&cws->usock),__FILE__,__LINE__);
nn_usock_stop(&cws->usock);
cws->state = NN_CWS_STATE_STOPPING_USOCK;

4
crypto777/nanosrc/transports/ws/sws.c

@ -370,7 +370,7 @@ static int nn_sws_send (struct nn_pipebase *self, struct nn_msg *msg)
struct nn_cmsghdr *cmsg;
struct nn_msghdr msghdr;
uint8_t rand_mask [NN_SWS_FRAME_SIZE_MASK];
printf("nn_sws_send\n");
sws = nn_cont (self, struct nn_sws, pipebase);
nn_assert_state (sws, NN_SWS_STATE_ACTIVE);
@ -884,7 +884,7 @@ static void nn_sws_handler (struct nn_fsm *self, int src, int type,
int rc;
sws = nn_cont (self, struct nn_sws, fsm);
printf("sws src.%d type.%d state.%d\n",src,type,sws->state);
switch (sws->state) {
/******************************************************************************/

2
crypto777/nanosrc/transports/ws/sws.h

@ -152,7 +152,7 @@ struct nn_sws {
uint8_t inmsg_control [NN_SWS_PAYLOAD_MAX_LENGTH];
/* Reason this connection is closing to send as closing handshake. */
char fail_msg [NN_SWS_PAYLOAD_MAX_LENGTH];
uint8_t fail_msg [NN_SWS_PAYLOAD_MAX_LENGTH];
size_t fail_msg_len;
/* State of the outbound state machine. */

2
crypto777/nanosrc/transports/ws/ws.c

@ -156,7 +156,7 @@ int nn_ws_send (int s, const void *msg, size_t len, uint8_t msg_type, int flags)
struct nn_msghdr hdr;
struct nn_cmsghdr *cmsg;
size_t cmsgsz;
printf("nn_ws_send\n");
iov.iov_base = (void*) msg;
iov.iov_len = len;

4
crypto777/nanosrc/transports/ws/ws_handshake.c

@ -1213,7 +1213,7 @@ static void nn_ws_handshake_client_request (struct nn_ws_handshake *self)
nn_random_generate (rand_key, sizeof (rand_key));
rc = nn_base64_encode (rand_key, sizeof (rand_key),
rc = _nn_base64_encode (rand_key, sizeof (rand_key),
encoded_key, sizeof (encoded_key));
encoded_key_len = strlen (encoded_key);
@ -1355,7 +1355,7 @@ static int nn_ws_handshake_hash_key (const char *key, size_t key_len,
for (i = 0; i < strlen (NN_WS_HANDSHAKE_MAGIC_GUID); i++)
nn_sha1_hashbyte (&hash, NN_WS_HANDSHAKE_MAGIC_GUID [i]);
rc = nn_base64_encode (nn_sha1_result (&hash),
rc = _nn_base64_encode (nn_sha1_result (&hash),
sizeof (hash.state), hashed, hashed_len);
return rc;

4
crypto777/nanosrc/utils/efd_eventfd.c

@ -32,9 +32,9 @@ int nn_efd_init(struct nn_efd *self)
{
int rc;
int flags;
//PostMessage("inside efd_init eventfd\n");
PNACL_msg("inside efd_init eventfd\n");
self->efd = eventfd(0, EFD_CLOEXEC);
//PostMessage("self->efd: %d\n",self->efd);
PNACL_msg("self->efd: %d\n",self->efd);
if (self->efd == -1 && (errno == EMFILE || errno == ENFILE))
return -EMFILE;
errno_assert(self->efd != -1);

12
crypto777/nanosrc/utils/efd_pipe.c

@ -33,14 +33,14 @@
int nn_efd_init(struct nn_efd *self)
{
int rc,flags,p[2];
PNACL_message("inside efd_init: pipe\n");
PNACL_msg("inside efd_init: pipe\n");
//sleep(1);
#if defined NN_HAVE_PIPE2
rc = pipe2(p, O_NONBLOCK | O_CLOEXEC);
#else
rc = pipe(p);
#endif
PNACL_message("rc efd_init: %d\n",rc);
PNACL_msg("rc efd_init: %d\n",rc);
//sleep(1);
if (rc != 0 && (errno == EMFILE || errno == ENFILE))
return -EMFILE;
@ -50,20 +50,20 @@ int nn_efd_init(struct nn_efd *self)
#if !defined NN_HAVE_PIPE2 && defined FD_CLOEXEC
rc = fcntl (self->r, F_SETFD, FD_CLOEXEC);
PNACL_message("pipe efd_init: F_SETFDr rc %d\n",rc);
PNACL_msg("pipe efd_init: F_SETFDr rc %d\n",rc);
errno_assert(rc != -1);
rc = fcntl(self->w, F_SETFD, FD_CLOEXEC);
PNACL_message("pipe efd_init: F_SETFDw rc %d\n",rc);
PNACL_msg("pipe efd_init: F_SETFDw rc %d\n",rc);
errno_assert(rc != -1);
#endif
#if !defined NN_HAVE_PIPE2
flags = fcntl(self->r, F_GETFL, 0);
PNACL_message("pipe efd_init: flags %d\n",flags);
PNACL_msg("pipe efd_init: flags %d\n",flags);
if ( flags == -1 )
flags = 0;
rc = fcntl(self->r, F_SETFL, flags | O_NONBLOCK);
PNACL_message("pipe efd_init: rc %d flags.%d\n",rc,flags);
PNACL_msg("pipe efd_init: rc %d flags.%d\n",rc,flags);
errno_assert (rc != -1);
#endif

2
crypto777/nanosrc/utils/efd_socketpair.c

@ -35,7 +35,7 @@ int nn_efd_init (struct nn_efd *self)
int rc;
int flags;
int sp [2];
PNACL_msg("socketpair efdinit\n");
#if defined SOCK_CLOEXEC
rc = socketpair (AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sp);
#else

5
crypto777/nanosrc/utils/efd_win.c

@ -84,8 +84,9 @@ int nn_efd_init (struct nn_efd *self)
reuseaddr = 1;
rc = setsockopt (listener, SOL_SOCKET, SO_REUSEADDR,
(char*) &reuseaddr, sizeof (reuseaddr));
if (nn_slow (rc == SOCKET_ERROR))
goto wsafail;
// ignore SO_REUSEADDR failures
// if (nn_slow (rc == SOCKET_ERROR))
// goto wsafail;
/* Bind the listening socket to the local port. */
memset (&addr, 0, sizeof (addr));

4
crypto777/nanosrc/utils/err.c

@ -30,7 +30,7 @@
void nn_err_abort(void)
{
PNACL_message("nn_err_abort\n");
PNACL_msg("nn_err_abort\n");
while ( 1 )
{
printf("exit due to error\n");
@ -111,7 +111,7 @@ const char *nn_err_strerror(int32_t errnum)
#pragma warning (push)
#pragma warning (disable:4996)
#endif
PNACL_message("nanomsg: errno.%d (%s)\n",errnum,strerror(errnum));
PNACL_msg("nanomsg: errno.%d (%s)\n",errnum,strerror(errnum));
getchar();
return strerror (errnum);
#if defined _MSC_VER

13
crypto777/nanosrc/utils/err.h

@ -26,6 +26,7 @@
#include <errno.h>
#include <stdio.h>
#include <string.h>
#define PNACL_msg(...)
/* Include nn.h header to define nanomsg-specific error codes. */
#include "../nn.h"
@ -44,7 +45,7 @@
#define nn_assert(x) \
do {\
if (nn_slow (!(x))) {\
PNACL_message("Assertion failed: %s (%s:%d)\n", #x, \
PNACL_msg("Assertion failed: %s (%s:%d)\n", #x, \
__FILE__, __LINE__);\
fflush (stderr);\
nn_err_abort ();\
@ -54,7 +55,7 @@
#define nn_assert_state(obj, state_name) \
do {\
if (nn_slow ((obj)->state != state_name)) {\
PNACL_message( \
PNACL_msg( \
"Assertion failed: %d == %s (%s:%d)\n", \
(obj)->state, #state_name, \
__FILE__, __LINE__);\
@ -66,7 +67,7 @@
#define alloc_assert(x) \
do {\
if (nn_slow (!x)) {\
PNACL_message("Out of memory (%s:%d)\n",\
PNACL_msg("Out of memory (%s:%d)\n",\
__FILE__, __LINE__);\
nn_err_abort ();\
}\
@ -76,7 +77,7 @@
#define errno_assert(x) \
do {\
if (nn_slow (!(x))) {\
PNACL_message("%s [%d] (%s:%d)\n", nn_err_strerror (errno),\
PNACL_msg("%s [%d] (%s:%d)\n", nn_err_strerror (errno),\
(int) errno, __FILE__, __LINE__);\
nn_err_abort ();\
}\
@ -86,7 +87,7 @@
#define errnum_assert(cond, err) \
do {\
if (nn_slow (!(cond))) {\
PNACL_message("%s [%d] (%s:%d)\n", nn_err_strerror (err),(int) (err), __FILE__, __LINE__);\
PNACL_msg("%s [%d] (%s:%d)\n", nn_err_strerror (err),(int) (err), __FILE__, __LINE__);\
nn_err_abort ();\
}\
} while (0)
@ -118,7 +119,7 @@
/* Assertion-like macros for easier fsm debugging. */
#define nn_fsm_error(message, state, src, type) \
do {\
PNACL_message("%s: state=%d source=%d action=%d (%s:%d)\n", \
PNACL_msg("%s: state=%d source=%d action=%d (%s:%d)\n", \
message, state, src, type, __FILE__, __LINE__);\
nn_err_abort ();\
} while (0)

12
crypto777/nanosrc/utils/thread_posix.c

@ -26,11 +26,11 @@
#include <signal.h>
#include <stdint.h>
static void *nn_thread_main_routine(void *arg)
void *nn_thread_main_routine(void *arg)
{
struct nn_thread *self;
self = (struct nn_thread *)arg;
PNACL_message("nn_thread_main_routine arg.%p self->routine(%p) at %p\n",arg,self->arg,self->routine);
printf("nn_thread_main_routine arg.%p self->routine(%p) at %p\n",arg,self->arg,self->routine);
self->routine(self->arg); // Run the thread routine
return NULL;
}
@ -42,16 +42,22 @@ void nn_thread_term(struct nn_thread *self)
errnum_assert(rc == 0,rc);
}
void *Nanomsg_threadarg;
#ifdef __PNACL
void nn_thread_init(struct nn_thread *self,nn_thread_routine *routine,void *arg)
{
int32_t rc;
// No signals should be processed by this thread. The library doesn't use signals and thus all the signals should be delivered to application threads, not to worker threads.
PNACL_message("nn_thread_init routine.%p arg.%p\n",routine,arg);
printf("nn_thread_init routine.%p arg.%p\n",routine,arg);
self->routine = routine;
self->arg = arg;
#ifdef FROM_JS
Nanomsg_threadarg = self;
#else
rc = pthread_create(&self->handle,NULL,nn_thread_main_routine,(void *)self);
errnum_assert (rc == 0, rc);
#endif
}
#else

2
crypto777/nanosrc/utils/win.h

@ -27,8 +27,8 @@
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <winsock2.h>
#include <windows.h>
#include <mswsock.h>
#include <process.h>
#include <ws2tcpip.h>

2
iguana/coins/basilisk/mnz

@ -0,0 +1,2 @@
curl --url "http://127.0.0.1:7778" --data "{\"conf\":\"MNZ.conf\",\"path\":\"${HOME#"/"}/.komodo/MNZ\",\"unitval\":\"20\",\"zcash\":1,\"RELAY\":0,\"VALIDATE\":0,\"prefetchlag\":-1,\"poll\":100,\"active\":1,\"agent\":\"iguana\",\"method\":\"addcoin\",\"startpend\":4,\"endpend\":4,\"services\":129,\"maxpeers\":8,\"newcoin\":\"MNZ\",\"name\":\"MNZ\",\"hasheaders\":1,\"useaddmultisig\":0,\"netmagic\":\"53d06fde\",\"p2p\":14336,\"rpc\":14337,\"pubval\":60,\"p2shval\":85,\"wifval\":188,\"txfee_satoshis\":\"10000\",\"isPoS\":0,\"minoutput\":10000,\"minconfirms\":2,\"genesishash\":\"027e3758c3a65b12aa1046462b486d0a63bfa1beae327897f56c5cfb7daaae71\",\"protover\":170002,\"genesisblock\":\"0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000000000000000000000000000000000000000000000000000000000000029ab5f490f0f0f200b00000000000000000000000000000000000000000000000000000000000000fd4005000d5ba7cda5d473947263bf194285317179d2b0d307119c2e7cc4bd8ac456f0774bd52b0cd9249be9d40718b6397a4c7bbd8f2b3272fed2823cd2af4bd1632200ba4bf796727d6347b225f670f292343274cc35099466f5fb5f0cd1c105121b28213d15db2ed7bdba490b4cedc69742a57b7c25af24485e523aadbb77a0144fc76f79ef73bd8530d42b9f3b9bed1c135ad1fe152923fafe98f95f76f1615e64c4abb1137f4c31b218ba2782bc15534788dda2cc08a0ee2987c8b27ff41bd4e31cd5fb5643dfe862c9a02ca9f90c8c51a6671d681d04ad47e4b53b1518d4befafefe8cadfb912f3d03051b1efbf1dfe37b56e93a741d8dfd80d576ca250bee55fab1311fc7b3255977558cdda6f7d6f875306e43a14413facdaed2f46093e0ef1e8f8a963e1632dcbeebd8e49fd16b57d49b08f9762de89157c65233f60c8e38a1f503a48c555f8ec45dedecd574a37601323c27be597b956343107f8bd80f3a925afaf30811df83c402116bb9c1e5231c70fff899a7c82f73c902ba54da53cc459b7bf1113db65cc8f6914d3618560ea69abd13658fa7b6af92d374d6eca9529f8bd565166e4fcbf2a8dfb3c9b69539d4d2ee2e9321b85b331925df195915f2757637c2805e1d4131e1ad9ef9bc1bb1c732d8dba4738716d351ab30c996c8657bab39567ee3b29c6d054b711495c0d52e1cd5d8e55b4f0f0325b97369280755b46a02afd54be4ddd9f77c22272b8bbb17ff5118fedbae2564524e797bd28b5f74f7079d532ccc059807989f94d267f47e724b3f1ecfe00ec9e6541c961080d8891251b84b4480bc292f6a180bea089fef5bbda56e1e41390d7c0e85ba0ef530f7177413481a226465a36ef6afe1e2bca69d2078712b3912bba1a99b1fbff0d355d6ffe726d2bb6fbc103c4ac5756e5bee6e47e17424ebcbf1b63d8cb90ce2e40198b4f4198689daea254307e52a25562f4c1455340f0ffeb10f9d8e914775e37d0edca019fb1b9c6ef81255ed86bc51c5391e0591480f66e2d88c5f4fd7277697968656a9b113ab97f874fdd5f2465e5559533e01ba13ef4a8f7a21d02c30c8ded68e8c54603ab9c8084ef6d9eb4e92c75b078539e2ae786ebab6dab73a09e0aa9ac575bcefb29e930ae656e58bcb513f7e3c17e079dce4f05b5dbc18c2a872b22509740ebe6a3903e00ad1abc55076441862643f93606e3dc35e8d9f2caef3ee6be14d513b2e062b21d0061de3bd56881713a1a5c17f5ace05e1ec09da53f99442df175a49bd154aa96e4949decd52fed79ccf7ccbce32941419c314e374e4a396ac553e17b5340336a1a25c22f9e42a243ba5404450b650acfc826a6e432971ace776e15719515e1634ceb9a4a35061b668c74998d3dfb5827f6238ec015377e6f9c94f38108768cf6e5c8b132e0303fb5a200368f845ad9d46343035a6ff94031df8d8309415bb3f6cd5ede9c135fdabcc030599858d803c0f85be7661c88984d88faa3d26fb0e9aac0056a53f1b5d0baed713c853c4a2726869a0a124a8a5bbc0fc0ef80c8ae4cb53636aa02503b86a1eb9836fcc259823e2692d921d88e1ffc1e6cb2bde43939ceb3f32a611686f539f8f7c9f0bf00381f743607d40960f06d347d1cd8ac8a51969c25e37150efdf7aa4c2037a2fd0516fb444525ab157a0ed0a7412b2fa69b217fe397263153782c0f64351fbdf2678fa0dc8569912dcd8e3ccad38f34f23bbbce14c6a26ac24911b308b82c7e43062d180baeac4ba7153858365c72c63dcf5f6a5b08070b730adb017aeae925b7d0439979e2679f45ed2f25a7edcfd2fb77a8794630285ccb0a071f5cce410b46dbf9750b0354aae8b65574501cc69efb5b6a43444074fee116641bb29da56c2b4a7f456991fc92b2\",\"debug\":0,\"seedipaddr\":\"78.47.196.146\"}"

2
iguana/coins/chips_7776

@ -0,0 +1,2 @@
#!/bin/bash
curl --url "http://127.0.0.1:7776" --data "{\"conf\":\"chips.conf\",\"path\":\"${HOME#"/"}/.chips\",\"prefetchlag\":-1,\"poll\":1,\"active\":1,\"agent\":\"iguana\",\"method\":\"addcoin\",\"newcoin\":\"CHIPS\",\"startpend\":64,\"endpend\":64,\"services\":0,\"maxpeers\":512,\"RELAY\":-1,\"VALIDATE\":0,\"portp2p\":57777,\"minconfirms\":1,\"pubval\":60,\"p2shval\":85,\"wifval\":188}"

2
iguana/coins/mnz_7776

@ -0,0 +1,2 @@
curl --url "http://127.0.0.1:7776" --data "{\"conf\":\"MNZ.conf\",\"path\":\"${HOME#"/"}/.komodo/MNZ\",\"unitval\":\"20\",\"zcash\":1,\"RELAY\":-1,\"VALIDATE\":0,\"prefetchlag\":-1,\"poll\":100,\"active\":1,\"agent\":\"iguana\",\"method\":\"addcoin\",\"startpend\":4,\"endpend\":4,\"services\":129,\"maxpeers\":8,\"newcoin\":\"MNZ\",\"name\":\"MNZ\",\"hasheaders\":1,\"useaddmultisig\":0,\"netmagic\":\"53d06fde\",\"p2p\":14336,\"rpc\":14337,\"pubval\":60,\"p2shval\":85,\"wifval\":188,\"txfee_satoshis\":\"10000\",\"isPoS\":0,\"minoutput\":10000,\"minconfirms\":2,\"genesishash\":\"027e3758c3a65b12aa1046462b486d0a63bfa1beae327897f56c5cfb7daaae71\",\"protover\":170002,\"genesisblock\":\"0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000000000000000000000000000000000000000000000000000000000000029ab5f490f0f0f200b00000000000000000000000000000000000000000000000000000000000000fd4005000d5ba7cda5d473947263bf194285317179d2b0d307119c2e7cc4bd8ac456f0774bd52b0cd9249be9d40718b6397a4c7bbd8f2b3272fed2823cd2af4bd1632200ba4bf796727d6347b225f670f292343274cc35099466f5fb5f0cd1c105121b28213d15db2ed7bdba490b4cedc69742a57b7c25af24485e523aadbb77a0144fc76f79ef73bd8530d42b9f3b9bed1c135ad1fe152923fafe98f95f76f1615e64c4abb1137f4c31b218ba2782bc15534788dda2cc08a0ee2987c8b27ff41bd4e31cd5fb5643dfe862c9a02ca9f90c8c51a6671d681d04ad47e4b53b1518d4befafefe8cadfb912f3d03051b1efbf1dfe37b56e93a741d8dfd80d576ca250bee55fab1311fc7b3255977558cdda6f7d6f875306e43a14413facdaed2f46093e0ef1e8f8a963e1632dcbeebd8e49fd16b57d49b08f9762de89157c65233f60c8e38a1f503a48c555f8ec45dedecd574a37601323c27be597b956343107f8bd80f3a925afaf30811df83c402116bb9c1e5231c70fff899a7c82f73c902ba54da53cc459b7bf1113db65cc8f6914d3618560ea69abd13658fa7b6af92d374d6eca9529f8bd565166e4fcbf2a8dfb3c9b69539d4d2ee2e9321b85b331925df195915f2757637c2805e1d4131e1ad9ef9bc1bb1c732d8dba4738716d351ab30c996c8657bab39567ee3b29c6d054b711495c0d52e1cd5d8e55b4f0f0325b97369280755b46a02afd54be4ddd9f77c22272b8bbb17ff5118fedbae2564524e797bd28b5f74f7079d532ccc059807989f94d267f47e724b3f1ecfe00ec9e6541c961080d8891251b84b4480bc292f6a180bea089fef5bbda56e1e41390d7c0e85ba0ef530f7177413481a226465a36ef6afe1e2bca69d2078712b3912bba1a99b1fbff0d355d6ffe726d2bb6fbc103c4ac5756e5bee6e47e17424ebcbf1b63d8cb90ce2e40198b4f4198689daea254307e52a25562f4c1455340f0ffeb10f9d8e914775e37d0edca019fb1b9c6ef81255ed86bc51c5391e0591480f66e2d88c5f4fd7277697968656a9b113ab97f874fdd5f2465e5559533e01ba13ef4a8f7a21d02c30c8ded68e8c54603ab9c8084ef6d9eb4e92c75b078539e2ae786ebab6dab73a09e0aa9ac575bcefb29e930ae656e58bcb513f7e3c17e079dce4f05b5dbc18c2a872b22509740ebe6a3903e00ad1abc55076441862643f93606e3dc35e8d9f2caef3ee6be14d513b2e062b21d0061de3bd56881713a1a5c17f5ace05e1ec09da53f99442df175a49bd154aa96e4949decd52fed79ccf7ccbce32941419c314e374e4a396ac553e17b5340336a1a25c22f9e42a243ba5404450b650acfc826a6e432971ace776e15719515e1634ceb9a4a35061b668c74998d3dfb5827f6238ec015377e6f9c94f38108768cf6e5c8b132e0303fb5a200368f845ad9d46343035a6ff94031df8d8309415bb3f6cd5ede9c135fdabcc030599858d803c0f85be7661c88984d88faa3d26fb0e9aac0056a53f1b5d0baed713c853c4a2726869a0a124a8a5bbc0fc0ef80c8ae4cb53636aa02503b86a1eb9836fcc259823e2692d921d88e1ffc1e6cb2bde43939ceb3f32a611686f539f8f7c9f0bf00381f743607d40960f06d347d1cd8ac8a51969c25e37150efdf7aa4c2037a2fd0516fb444525ab157a0ed0a7412b2fa69b217fe397263153782c0f64351fbdf2678fa0dc8569912dcd8e3ccad38f34f23bbbce14c6a26ac24911b308b82c7e43062d180baeac4ba7153858365c72c63dcf5f6a5b08070b730adb017aeae925b7d0439979e2679f45ed2f25a7edcfd2fb77a8794630285ccb0a071f5cce410b46dbf9750b0354aae8b65574501cc69efb5b6a43444074fee116641bb29da56c2b4a7f456991fc92b2\",\"debug\":0,\"seedipaddr\":\"78.47.196.146\"}"

7
iguana/dPoW.h

@ -20,6 +20,7 @@
#define DPOW_CHECKPOINTFREQ 10
#define DPOW_MINSIGS 13
#define DPOW_MIN_ASSETCHAIN_SIGS 11
//#define DPOW_M(bp) ((bp)->minsigs) // (((bp)->numnotaries >> 1) + 1)
#define DPOW_MODIND(bp,offset) (((((bp)->height / DPOW_CHECKPOINTFREQ) % (bp)->numnotaries) + (offset)) % (bp)->numnotaries)
#define DPOW_VERSION 0x0781
@ -132,12 +133,12 @@ struct dpow_info
char symbol[16],dest[16]; uint8_t minerkey33[33],minerid; uint64_t lastrecvmask;
struct dpow_checkpoint checkpoint,last,destchaintip,srcfifo[DPOW_FIFOSIZE],destfifo[DPOW_FIFOSIZE];
struct dpow_hashheight approved[DPOW_FIFOSIZE],notarized[DPOW_FIFOSIZE];
bits256 srctx[DPOW_MAXTX],desttx[DPOW_MAXTX];
uint32_t SRCREALTIME,destupdated,srcconfirms,numdesttx,numsrctx,lastsplit,cancelratify;
bits256 activehash,lastnotarized,srctx[DPOW_MAXTX],desttx[DPOW_MAXTX];
uint32_t SRCREALTIME,lastsrcupdate,destupdated,srcconfirms,numdesttx,numsrctx,lastsplit,cancelratify;
int32_t lastheight,maxblocks,SRCHEIGHT,SHORTFLAG,ratifying;
struct pax_transaction *PAX;
portable_mutex_t paxmutex,dexmutex;
uint32_t ipbits[64],numipbits;
uint32_t ipbits[128],numipbits;
struct dpow_block **blocks;
};
uint64_t dpow_notarybestk(uint64_t refmask,struct dpow_block *bp,int8_t *lastkp);

16
iguana/dexscripts.win32/1-client.cmd

@ -0,0 +1,16 @@
@echo off
set USERHOME=%APPDATA:\=\\%
rem [!] Coins config now taked from coins.json file, no need to put in environment variable
rem ---------------------------------------------------------------------------------------
rem set COINS=[{\"coin\":\"REVS\",\"active\":1,\"asset\":\"REVS\",\"rpcport\":10196}]
rem marketmaker "{\"gui\":\"nogui\",\"client\":1, \"userhome\":\"%USERHOME%\", \"passphrase\":\"mypassphrase\", \"coins\":%COINS%}"
set COINS=\"\"
set /p PASSPHRASE=<passphrase
rem , \"canbind\":1
rem marketmaker "{\"gui\":\"nogui\",\"client\":1, \"userhome\":\"%USERHOME%\", \"passphrase\":\"%PASSPHRASE%\"}" 1> marketmaker.log 2>&1
marketmaker "{\"gui\":\"nogui\",\"client\":1, \"userhome\":\"%USERHOME%\", \"passphrase\":\"%PASSPHRASE%\"}"

7
iguana/dexscripts.win32/2-getuserpass.cmd

@ -0,0 +1,7 @@
@echo off
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":null,\"method\":\"enable\",\"coin\":\" \"}" -s > userpass.json
for /f "tokens=2 delims=:," %%a in (' find "userpass" "userpass.json" ') do (
echo UserPass: %%~a
echo %%~a > userpass
)
del userpass.json

4
iguana/dexscripts.win32/balance.cmd

@ -0,0 +1,4 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"balance\",\"coin\":\"KMD\",\"address\":\"RSpP2Nffy379SwF1cAkooNg6vwPHpakCpC\"}"

7
iguana/dexscripts.win32/bot_buy.cmd

@ -0,0 +1,7 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
set /p PASSPHRASE=<passphrase
echo passphrase: "%PASSPHRASE%"
echo userpass: "%USERPASS%"
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"bot_buy\",\"base\":\"MNZ\",\"rel\":\"KMD\",\"maxprice\":0.20,\"relvolume\":10.0}"

7
iguana/dexscripts.win32/bot_list.cmd

@ -0,0 +1,7 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
set /p PASSPHRASE=<passphrase
rem echo passphrase: "%PASSPHRASE%"
rem echo userpass: "%USERPASS%"
curl -s --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"bot_list\"}"

7
iguana/dexscripts.win32/bot_statuslist.cmd

@ -0,0 +1,7 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
set /p PASSPHRASE=<passphrase
rem echo passphrase: "%PASSPHRASE%"
rem echo userpass: "%USERPASS%"
curl -s --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"bot_statuslist\"}"

7
iguana/dexscripts.win32/bot_stop.cmd

@ -0,0 +1,7 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
set /p PASSPHRASE=<passphrase
rem echo passphrase: "%PASSPHRASE%"
rem echo userpass: "%USERPASS%"
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"bot_stop\",\"botid\":1376557535}"

BIN
iguana/dexscripts.win32/curl.exe

Binary file not shown.

9
iguana/dexscripts.win32/electrum.cmd

@ -0,0 +1,9 @@
@echo off
rem http://pad.supernet.org/electrum-servers
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
set /p PASSPHRASE=<passphrase
echo passphrase: "%PASSPHRASE%"
echo userpass: "%USERPASS%"
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"electrum\",\"coin\":\"KMD\",\"ipaddr\":\"electrum.cipig.net\",\"port\":10001}"
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"electrum\",\"coin\":\"MNZ\",\"ipaddr\":\"electrum.cipig.net\",\"port\":10002}"

4
iguana/dexscripts.win32/enable.cmd

@ -0,0 +1,4 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"enable\",\"coin\":\"REVS\"}"

4
iguana/dexscripts.win32/getcoin.cmd

@ -0,0 +1,4 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"getcoin\",\"coin\":\"KMD\"}"

4
iguana/dexscripts.win32/getutxos.cmd

@ -0,0 +1,4 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"getutxos\",\"coin\":\"KMD\"}"

2
iguana/dexscripts.win32/help.cmd

@ -0,0 +1,2 @@
@echo off
curl --url "http://127.0.0.1:7783" --data "{\"method\":\"help\"}"

100
iguana/dexscripts.win32/how_to_use.md

@ -0,0 +1,100 @@
## DexScripts for Windows. How to use? ##
**1.** Before start you should put scripts and following binaries into one folder:
- curl.exe (required for all scripts)
- marketmaker.exe
- libcurl.dll (required to run marketmaker)
- nanomsg.dll (required to run marketmaker)
**2.** Don't forget to put `coins.json` file into a same folder. This file is available it this repo.
**3.** Type your passphrase into passphrase file in this folder (you should create file with name `passphrase` and without extension) and run `1-client.cmd`. This will run marketmaker. Next step is to obtain userpass needed for other scripts, you can simply copy and paste it from marketmaker output on startup into userpass file.
![](./images/userpass.png)
Or run `2-getuserpass.cmd` to fill userpass file automatically.** NB!** To get userpass you shouldn't run any scripts between 1-client.cmd and 2-getuserpass.cmd launching.
Sample output of correct `2-getuserpass.cmd` usage is:
![](./images/userpass_usage.png)
You should see your userpass on screen, and after it will automatically copied in userpass file. It's important to all other scripts to have this password in userpass file. If output of `2-getuserpass.cmd` is not same as showed on screen above - wait some seconds and run `2-getuserpass.cmd` again. Also make sure that you have allowed marketmaker to accept incoming connections in your Windows Firewall (first time launched system should automatically asked for it).
**4.** For using other scripts please refer to barterDEX API. Or **barterDEX API Summary by Category** document by *shossain*.
## Scripts List ##
**NB!** Before you use any script that do some actions with your coins (for example, withdraw and others) **edit it** and make sure that it have correct addresses, coin name and volumes inside. Don't run any scripts without looking on it's source and clearly understanding what it does.
* **1-client.cmd** - used to start Marketmaker. Make sure you already have filled a strong passphrase into `passphrase` file as described above.
* **2-getuserpass.cmd** - fills userpass in `userpass` file. this step needed to use any other scripts.
* **balance.cmd** - displays current balance of selected coin.
* **enable.cmd** - enables a selected coin for trading.
* **getcoin.cmd** - prints information about a selecting coin:
{"result":"success","enabled":2,"disabled":70,"coin":{"coin":"KMD","installed":true,"height":580716,"balance":72.68774305,"KMDvalue":72.68774305,"status":"active","electrum":"electrum.cipig.net:10001","smartaddress":"RTCVGuoSNehKG8YYxcoskC7LK1yZhgvQRV","rpc":"127.0.0.1:7771","pubtype":60,"p2shtype":85,"wiftype":188,"txfee":10000}}
* **getutxos.cmd** - seems alredy deprecated.
* **inventory.cmd** - prints your inventory.
* **listunspent.cmd** - prints your utxos.
* **orderbook.cmd** - prints base/rel orderbook.
* **portfolio.cmd** - prints porfolio information.
* **snapshot.cmd** - ...
* **electrum.cmd** - allows you to run coins in electum mode (!), example includes two coins - KMD and MNZ. if you need to run more coins in electrum mode, add needed electrum servers from here - [http://pad.supernet.org/electrum-servers](http://pad.supernet.org/electrum-servers).
* **help.cmd** - displays help about all available API commands.
* **bot_buy.cmd** - launches bot for buying. you'll need to set base and rel coin in script, and also maxprice and relvolume.
* **bot_list.cmd** - lists id of all running bots.
* **bot_statuslist.cmd** - list statuses of all running bots.
* **bot_stop.cmd** - stopt the bot with given bot_id.
* **withdraw.cmd** - example of withdraw method. you can send coins from your smartaddress to any other address using widthraw. as a result method generates signed raw tx in hex, which you can use with sendrawtransaction.cmd . remember, that withdraw only *prepares* transaction, but it doesn't broadcast (send) it to network. after tx is prepared we need to send it using sendrawtransaction method.
* **sendrawtransaction.cmd** - sends raw transaction. you'll need a signedtx in hex.
* **withdraw_send.cmd** - combines withdraw and send raw tx scripts. you can call it `send`, just specify coin, volume and addresses to which you wan send coins and it will prepare and broadcast transaction automatically.
* **withdraw_10_send.cmd** - example of inventory split: this split 10 KMD from your balance to Alice inventory in 10 utxos pairs (1.002, 0.00386871). Strongly recommended to read [http://pad.supernet.org/barterdex-readme](http://pad.supernet.org/barterdex-readme) -> UTXO PAIRS to understand the basics. This script is just for example how you can split your coins in (X, X/777) to start trading them.
## F.A.Q. ##
**Q.** Is any simple way how i can display JSON results returned by all scripts, like orderbook and others, in human readable form?
**A.** Yes, you can use this service [JSON Editor Online](http://jsoneditoronline.org/), just copy and paste output of script in left column and see structured output in right.
**Q.** I see an output like this when i'm start `1-client.cmd` :
bind(0.0.0.0) port.7783 failed: No error sock.1468. errno.0
bind(0.0.0.0) port.7783 failed: No error sock.1516. errno.0
bind(0.0.0.0) port.7783 failed: No error sock.1444. errno.0
bind(0.0.0.0) port.7783 failed: No error sock.1484. errno.0
bind(0.0.0.0) port.7783 failed: No error sock.1412. errno.0
bind(0.0.0.0) port.7783 failed: No error sock.1524. errno.0
bind(0.0.0.0) port.7783 failed: No error sock.1008. errno.0
And nothing works.
**A.** Before run `1-client.cmd` make sure in Task Manager that you haven't already running `marketmaker.exe`. If have - kill this process via Task Manager or via command line command `taskkill /f /im taskkill.exe` .
**Q.** How can i pretty print JSON answers of marketmaker?
**A.** You can get best results with 2 tools - [conemu](https://conemu.github.io/) and [jq](https://stedolan.github.io/jq/), conemu supports ANSI X3.64 and Xterm 256 colors and jq allow you to pretty-print json output with colors, like this:
![](./images/conemu_jq.png)
Also i'm always recommend to install [Far Manager](https://www.farmanager.com/index.php?l=en) - this is powerful console file manager for Windows, like Midnight Commander in *nix.
**Q.** What additional dependencies required by marketmaker?
**A.** Currently marketmaker (Windows) used the following DLLs:
*32 bit:*
- libcrypto-1_1.dll
- libcurl.dll
- libssl-1_1.dll
- nanomsg.dll
- pthreadvc2.dll
*64-bit:*
- libcurl.dll
- nanomsg.dll
It already included in repo and in archive with release.

BIN
iguana/dexscripts.win32/images/conemu_jq.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

BIN
iguana/dexscripts.win32/images/userpass.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

BIN
iguana/dexscripts.win32/images/userpass_usage.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

4
iguana/dexscripts.win32/inventory.cmd

@ -0,0 +1,4 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"inventory\",\"coin\":\"KMD\"}"

4
iguana/dexscripts.win32/listunspent.cmd

@ -0,0 +1,4 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"listunspent\",\"coin\":\"KMD\",\"address\":\"RSpP2Nffy379SwF1cAkooNg6vwPHpakCpC\"}"

4
iguana/dexscripts.win32/orderbook.cmd

@ -0,0 +1,4 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"orderbook\",\"base\":\"KMD\",\"rel\":\"REVS\"}"

1
iguana/dexscripts.win32/passphrase

@ -0,0 +1 @@
your_very_strong_secret_passphrase

4
iguana/dexscripts.win32/portfolio.cmd

@ -0,0 +1,4 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"portfolio\"}"

5
iguana/dexscripts.win32/sendrawtransaction.cmd

@ -0,0 +1,5 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
set HEX=your_signed_raw_tx
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"sendrawtransaction\",\"coin\":\"KMD\",\"signedtx\":%HEX%"\"}"

5
iguana/dexscripts.win32/snapshot.cmd

@ -0,0 +1,5 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
curl --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"snapshot\",\"coin\":\"KMD\",\"height\":%1}"

0
iguana/dexscripts.win32/userpass

8
iguana/dexscripts.win32/withdraw.cmd

@ -0,0 +1,8 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
rem *** Change coin and outputs before use (!) ***
set COIN=KMD
set OUTPUTS=[{\"RDecker69MM5dhDBosUXPNTzfoGqxPQqHu\":0.00007777}]
curl -s --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"withdraw\",\"coin\":\"%COIN%\",\"outputs\":%OUTPUTS%}" > withdraw.txt
type withdraw.txt

14
iguana/dexscripts.win32/withdraw_10_send.cmd

@ -0,0 +1,14 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
rem *** Change coin and outputs before use (!) ***
set COIN=KMD
set SMARTADDRESS=RDecker69MM5dhDBosUXPNTzfoGqxPQqHu
set OUTPUTS=[{\"%SMARTADDRESS%\":1.002},{\"%SMARTADDRESS%\":0.00386871},{\"%SMARTADDRESS%\":1.002},{\"%SMARTADDRESS%\":0.00386871},{\"%SMARTADDRESS%\":1.002},{\"%SMARTADDRESS%\":0.00386871},{\"%SMARTADDRESS%\":1.002},{\"%SMARTADDRESS%\":0.00386871},{\"%SMARTADDRESS%\":1.002},{\"%SMARTADDRESS%\":0.00386871},{\"%SMARTADDRESS%\":1.002},{\"%SMARTADDRESS%\":0.00386871},{\"%SMARTADDRESS%\":1.002},{\"%SMARTADDRESS%\":0.00386871},{\"%SMARTADDRESS%\":1.002},{\"%SMARTADDRESS%\":0.00386871},{\"%SMARTADDRESS%\":1.002},{\"%SMARTADDRESS%\":0.00386871},{\"%SMARTADDRESS%\":1.002},{\"%SMARTADDRESS%\":0.00386871}]
curl -s --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"withdraw\",\"coin\":\"%COIN%\",\"outputs\":%OUTPUTS%}" > withdraw.txt
type withdraw.txt
timeout /t 5 /nobreak
for /f "tokens=4 delims=:," %%a in (' find "hex" "withdraw.txt" ') do (
rem echo [%%~a]
curl -s --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"sendrawtransaction\",\"coin\":\"%COIN%\",\"signedtx\":\"%%~a\"}"
)

14
iguana/dexscripts.win32/withdraw_send.cmd

@ -0,0 +1,14 @@
@echo off
set /p TMPUSERPASS=<userpass
set USERPASS=%TMPUSERPASS: =%
rem *** Change coin and outputs before use (!) ***
set COIN=KMD
set OUTPUTS=[{\"RDecker69MM5dhDBosUXPNTzfoGqxPQqHu\":0.00007777}]
curl -s --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"withdraw\",\"coin\":\"%COIN%\",\"outputs\":%OUTPUTS%}" > withdraw.txt
type withdraw.txt
timeout /t 5 /nobreak
for /f "tokens=4 delims=:," %%a in (' find "hex" "withdraw.txt" ') do (
rem echo [%%~a]
curl -s --url "http://127.0.0.1:7783" --data "{\"userpass\":\"%USERPASS%\",\"method\":\"sendrawtransaction\",\"coin\":\"%COIN%\",\"signedtx\":\"%%~a\"}"
)

7
iguana/dpow/dpow_fsm.c

@ -326,7 +326,7 @@ void dpow_statemachinestart(void *ptr)
return;
}
bp->myind = myind;
printf("[%d] statemachinestart %s->%s %s ht.%d minsigs.%d duration.%d start.%u\n",bp->myind,dp->symbol,dp->dest,bits256_str(str,checkpoint.blockhash.hash),checkpoint.blockhash.height,minsigs,duration,checkpoint.timestamp);
printf("[%d] notarize %s->%s %s ht.%d minsigs.%d duration.%d start.%u\n",bp->myind,dp->symbol,dp->dest,bits256_str(str,checkpoint.blockhash.hash),checkpoint.blockhash.height,minsigs,duration,checkpoint.timestamp);
if ( bp->isratify != 0 && memcmp(bp->notaries[0].pubkey,bp->ratified_pubkeys[0],33) != 0 )
{
for (i=0; i<33; i++)
@ -447,6 +447,11 @@ void dpow_statemachinestart(void *ptr)
dpow_send(myinfo,dp,bp,srchash,bp->hashmsg,0,bp->height,(void *)"ping",0);
dpow_nanomsg_update(myinfo);
}
else
{
dp->lastnotarized = checkpoint.blockhash.hash;
printf("notarized %s %s\n",dp->symbol,bits256_str(str,checkpoint.blockhash.hash));
}
if ( 0 && dp->cancelratify != 0 && bp->isratify != 0 )
{
printf("abort pending ratify\n");

17
iguana/dpow/dpow_network.c

@ -561,7 +561,7 @@ void dex_channelsend(struct supernet_info *myinfo,bits256 srchash,bits256 destha
void dpow_randipbits(struct supernet_info *myinfo,struct iguana_info *coin,cJSON *retjson)
{
int32_t m; uint32_t ipbits; char *coinstr;
int32_t m; uint32_t ipbits; char *coinstr; cJSON *infojson;
if ( is_cJSON_Array(retjson) == 0 )
{
if ( (m= myinfo->numdpowipbits) > 0 )
@ -572,6 +572,11 @@ void dpow_randipbits(struct supernet_info *myinfo,struct iguana_info *coin,cJSON
}
if ( (coinstr= jstr(retjson,"coin")) == 0 )
jaddstr(retjson,"coin",coin->symbol);
if ( (infojson= dpow_getinfo(myinfo,coin)) != 0 )
{
jaddnum(retjson,"notaryheight",juint(infojson,"blocks"));
free_json(infojson);
}
}
}
@ -1318,7 +1323,7 @@ struct dpow_nanomsghdr
{
bits256 srchash,desthash;
struct dpow_nanoutxo ratify,notarize;
uint32_t channel,height,size,datalen,crc32,myipbits,numipbits,ipbits[64];
uint32_t channel,height,size,datalen,crc32,myipbits,numipbits,ipbits[128];
char symbol[16];
uint8_t senderind,version0,version1,packet[];
} PACKED;
@ -2026,10 +2031,10 @@ void dpow_send(struct supernet_info *myinfo,struct dpow_info *dp,struct dpow_blo
printf("%d NANOSEND.%d ht.%d channel.%08x (%d) pax.%08x datalen.%d (%d %llx) (%d %llx) recv.%llx\n",i,sentbytes,np->height,np->channel,size,np->notarize.paxwdcrc,datalen,(int8_t)np->notarize.bestk,(long long)np->notarize.bestmask,bp->notaries[bp->myind].bestk,(long long)bp->notaries[bp->myind].bestmask,(long long)bp->recvmask);
}
void dpow_ipbitsadd(struct supernet_info *myinfo,struct dpow_info *dp,uint32_t *ipbits,int32_t numipbits,int32_t fromid,uint32_t senderipbits)
void dpow_ipbitsadd(struct supernet_info *myinfo,struct dpow_info *dp,uint32_t *ipbits,int32_t numipbits,int32_t maxipbits,int32_t fromid,uint32_t senderipbits)
{
int32_t i,j,matched,missing,n; char ipaddr[64];
if ( numipbits >= 64 )
if ( numipbits >= maxipbits )
{
static int32_t counter;
if ( counter++ < 100 )
@ -2088,7 +2093,7 @@ int32_t dpow_nanomsg_update(struct supernet_info *myinfo)
if ( (flags & 1) == 0 && (size= signed_nn_recv(&freeptr,myinfo,myinfo->notaries,myinfo->numnotaries,myinfo->dpowsock,&np)) > 0 )
{
num++;
if ( size > 0 )
if ( size >= sizeof(*np) )
{
//fprintf(stderr,"%d ",size);
if ( np->version0 == (DPOW_VERSION & 0xff) && np->version1 == ((DPOW_VERSION >> 8) & 0xff) )
@ -2112,7 +2117,7 @@ int32_t dpow_nanomsg_update(struct supernet_info *myinfo)
printf("received nnpacket for (%s)\n",np->symbol);
else
{
dpow_ipbitsadd(myinfo,dp,np->ipbits,np->numipbits,np->senderind,np->myipbits);
dpow_ipbitsadd(myinfo,dp,np->ipbits,np->numipbits,sizeof(np->ipbits)/sizeof(*np->ipbits),np->senderind,np->myipbits);
if ( (bp= dpow_heightfind(myinfo,dp,np->height)) != 0 && bp->state != 0xffffffff && bp->myind >= 0 )
{
//char str[65]; printf("%s RECV ht.%d ch.%08x (%d) crc32.%08x:%08x datalen.%d:%d firstz.%d i.%d senderind.%d myind.%d\n",bits256_str(str,np->srchash),np->height,np->channel,size,np->crc32,crc32,np->datalen,(int32_t)(size - sizeof(*np)),firstz,i,np->senderind,bp->myind);

32
iguana/dpow/dpow_prices.c

@ -1438,7 +1438,7 @@ void PAX_update(struct PAX_data *dp,double *btcusdp,double *kmdbtcp)
*kmdbtcp = 0;
bitcoinave = 0;//url_json("https://api.bitcoinaverage.com/ticker/USD/");
//bitcoincharts = url_json("http://api.bitcoincharts.com/v1/weighted_prices.json");
blockchaininfo = 0;//url_json("https://blockchain.info/ticker");
blockchaininfo = url_json("https://blockchain.info/ticker");
coindesk = 0;//url_json("http://api.coindesk.com/v1/bpi/historical/close.json");
sprintf(url,"https://poloniex.com/public?command=returnChartData&currencyPair=BTC_KMD&start=%ld&end=9999999999&period=86400",(long)(time(NULL)-3600*24));
sprintf(url2,"https://poloniex.com/public?command=returnChartData&currencyPair=BTC_BTCD&start=%ld&end=9999999999&period=86400",(long)(time(NULL)-3600*24));
@ -1541,7 +1541,7 @@ void PAX_update(struct PAX_data *dp,double *btcusdp,double *kmdbtcp)
if ( (item= jobj(blockchaininfo,"USD")) != 0 && item != 0 && (price= jdouble(item,"15m")) > SMALLVAL )
{
dpow_price("blockchain.info","BTCUSD",price,price);
//printf("blockchaininfo %f %f\n",btcusd,price);
printf("blockchaininfo %f %f\n",btcusd,price);
dxblend(&btcusd,price,0.5);
}
free_json(blockchaininfo);
@ -1832,13 +1832,16 @@ void PAX_genecbsplines(struct PAX_data *dp)
portable_mutex_unlock(&mutex);
}
#define BTCFACTOR_TIMESTAMP 1503746319
#define BTCFACTOR_HEIGHT 466266
int32_t PAX_idle(struct supernet_info *myinfo)//struct PAX_data *argdp,int32_t idlegap)
{
static double lastupdate,lastdayupdate; static int32_t didinit; static char *userhome; int32_t idlegap = 10;
static double lastupdate,lastdayupdate; static uint32_t didinit; static char *userhome; int32_t idlegap = 10;
FILE *fp; long filesize; char fname[512]; double splineval; uint32_t pvals[128],timestamp; int32_t i,datenum,seconds,c; struct tai t; struct PAX_data *dp; uint8_t data[512];
if ( Currencymasks[0] == 0 )
return(0);
if ( didinit == 0 )
if ( time(NULL) > didinit+12*3600 )
{
if ( (userhome= OS_filestr(&filesize,"userhome.txt")) == 0 )
userhome = "root";
@ -1849,15 +1852,15 @@ int32_t PAX_idle(struct supernet_info *myinfo)//struct PAX_data *argdp,int32_t i
userhome[strlen(userhome)-1] = 0;
}
}
if ( myinfo->PAXDATA == 0 )
myinfo->PAXDATA = calloc(1,sizeof(*dp));
didinit = 1;
dp = myinfo->PAXDATA;
PAX_genecbsplines(dp);
printf("generated splines\n");
datenum = OS_conv_unixtime(&t,&seconds,(uint32_t)time(NULL));
didinit = (uint32_t)time(NULL);
datenum = OS_conv_unixtime(&t,&seconds,didinit);
expand_datenum(dp->edate,datenum);
}
dp = myinfo->PAXDATA;
/*if ( 0 && time(NULL) > dp->lastupdate+10 )
{
@ -1904,8 +1907,9 @@ int32_t PAX_idle(struct supernet_info *myinfo)//struct PAX_data *argdp,int32_t i
PAX_emitprices(pvals,dp);
}
timestamp = (uint32_t)time(NULL);
int32_t dispflag = ((rand() % 64) == 0);
if ( dp->kmdbtc == 0 || dispflag != 0 )
int32_t dispflag = ((rand() % 6) == 0);
//printf("PAX_IDLE.%d %.8f %.8f\n",dispflag,dp->kmdbtc,dp->btcusd);
if ( dp->kmdbtc == 0 || dp->btcusd == 0 || dispflag != 0 )
{
PAX_update(dp,&dp->btcusd,&dp->kmdbtc);
for (i=0; i<MAX_CURRENCIES; i++)
@ -1920,10 +1924,12 @@ int32_t PAX_idle(struct supernet_info *myinfo)//struct PAX_data *argdp,int32_t i
pvals[1] = timestamp;
pvals[2] = MAX_CURRENCIES + 3;
pvals[3] = PAX_val32(dp->kmdbtc * 1000);
pvals[4] = PAX_val32(dp->btcusd * .001);
double btcfactor;
//if ( time(NULL) > BTCFACTOR_TIMESTAMP )
btcfactor = .00001;
//else btcfactor = .001;
pvals[4] = PAX_val32(dp->btcusd * btcfactor);
pvals[5] = PAX_val32(dp->CNYUSD);
if ( dispflag != 0 )
printf("KMD %.8f BTC %f CNY %f (%f)\n",dp->kmdbtc,dp->btcusd,dp->CNYUSD,1./dp->CNYUSD);
sprintf(fname,"/%s/.komodo/komodofeed",userhome);
if ( (fp= fopen(fname,"wb")) != 0 )
{
@ -1939,7 +1945,7 @@ int32_t PAX_idle(struct supernet_info *myinfo)//struct PAX_data *argdp,int32_t i
{
for (i=0; i<6; i++)
printf("%u ",pvals[i]);
printf("pvals -> %s\n",fname);
printf("KMD %.8f BTC %f CNY %f (%f) btcusd pval.%u\n",dp->kmdbtc,dp->btcusd,dp->CNYUSD,1./dp->CNYUSD,pvals[4]);
}
}
}

20
iguana/dpow/dpow_rpc.c

@ -177,7 +177,7 @@ bits256 dpow_getbestblockhash(struct supernet_info *myinfo,struct iguana_info *c
memset(blockhash.bytes,0,sizeof(blockhash));
if ( coin->FULLNODE < 0 )
{
if ( coin->lastbesthashtime+20 > time(NULL) && bits256_nonz(coin->lastbesthash) != 0 )
if ( coin->lastbesthashtime+2 > time(NULL) && bits256_nonz(coin->lastbesthash) != 0 )
return(coin->lastbesthash);
if ( (retstr= bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"getbestblockhash","")) != 0 )
{
@ -394,7 +394,7 @@ cJSON *dpow_listunspent(struct supernet_info *myinfo,struct iguana_info *coin,ch
char buf[128],*retstr; cJSON *array,*json = 0;
if ( coin->FULLNODE < 0 )
{
sprintf(buf,"0, 99999999, [\"%s\"]",coinaddr);
sprintf(buf,"1, 99999999, [\"%s\"]",coinaddr);
if ( (retstr= bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"listunspent",buf)) != 0 )
{
json = cJSON_Parse(retstr);
@ -820,7 +820,7 @@ int32_t dpow_haveutxo(struct supernet_info *myinfo,struct iguana_info *coin,bits
}
}
if ( haveutxo == 0 )
printf("no utxo: need to fund address.(%s) or wait for splitfund to confirm\n",coinaddr);
printf("no %s utxo: need to fund address.(%s) or wait for splitfund to confirm\n",coin->symbol,coinaddr);
} //else printf("null utxo array size\n");
free_json(unspents);
} else printf("null return from dpow_listunspent\n");
@ -1154,10 +1154,11 @@ void dpow_issuer_voutupdate(struct dpow_info *dp,char *symbol,int32_t isspecial,
}
}
int32_t dpow_issuer_tx(struct dpow_info *dp,struct iguana_info *coin,int32_t height,int32_t txi,char *txidstr,uint32_t port)
int32_t dpow_issuer_tx(int32_t *isspecialp,struct dpow_info *dp,struct iguana_info *coin,int32_t height,int32_t txi,char *txidstr,uint32_t port)
{
char *retstr,params[256],*hexstr; uint8_t script[16384]; cJSON *json,*oldpub,*newpub,*result,*vouts,*item,*sobj; int32_t vout,n,len,isspecial,retval = -1; uint64_t value; bits256 txid;
char *retstr,params[256],*hexstr; uint8_t script[16384]; cJSON *json,*oldpub,*newpub,*result,*vouts,*item,*sobj; int32_t vout,n,len,retval = -1; uint64_t value; bits256 txid;
sprintf(params,"[\"%s\", 1]",txidstr);
*isspecialp = 0;
if ( (retstr= dpow_issuemethod(coin->chain->userpass,(char *)"getrawtransaction",params,port)) != 0 )
{
if ( (json= cJSON_Parse(retstr)) != 0 )
@ -1170,7 +1171,6 @@ int32_t dpow_issuer_tx(struct dpow_info *dp,struct iguana_info *coin,int32_t hei
retval = 0;
if ( oldpub == 0 && newpub == 0 && (vouts= jarray(&n,result,(char *)"vout")) != 0 )
{
isspecial = 0;
txid = jbits256(result,(char *)"txid");
for (vout=0; vout<n; vout++)
{
@ -1182,11 +1182,11 @@ int32_t dpow_issuer_tx(struct dpow_info *dp,struct iguana_info *coin,int32_t hei
{
len = (int32_t)strlen(hexstr) >> 1;
if ( vout == 0 && ((memcmp(&hexstr[2],CRYPTO777_PUBSECPSTR,66) == 0 && len == 35) || (memcmp(&hexstr[6],CRYPTO777_RMD160STR,40) == 0 && len == 25)) )
isspecial = 1;
*isspecialp = 1;
else if ( len <= sizeof(script) )
{
decode_hex(script,len,hexstr);
dpow_issuer_voutupdate(dp,coin->symbol,isspecial,height,txi,txid,vout,n,value,script,len);
dpow_issuer_voutupdate(dp,coin->symbol,*isspecialp,height,txi,txid,vout,n,value,script,len);
}
}
}
@ -1202,7 +1202,7 @@ int32_t dpow_issuer_tx(struct dpow_info *dp,struct iguana_info *coin,int32_t hei
int32_t dpow_issuer_block(struct dpow_info *dp,struct iguana_info *coin,int32_t height,uint16_t port)
{
char *retstr,*retstr2,params[128],*txidstr; int32_t i,n,retval = -1; cJSON *json,*tx=0,*result=0,*result2;
char *retstr,*retstr2,params[128],*txidstr; int32_t i,isspecial,n,retval = -1; cJSON *json,*tx=0,*result=0,*result2;
sprintf(params,"[%d]",height);
if ( (retstr= dpow_issuemethod(coin->chain->userpass,(char *)"getblockhash",params,port)) != 0 )
{
@ -1219,7 +1219,7 @@ int32_t dpow_issuer_block(struct dpow_info *dp,struct iguana_info *coin,int32_t
if ( (result2= jobj(json,(char *)"result")) != 0 && (tx= jarray(&n,result2,(char *)"tx")) != 0 )
{
for (i=0; i<n; i++)
if ( dpow_issuer_tx(dp,coin,height,i,jstri(tx,i),port) < 0 )
if ( dpow_issuer_tx(&isspecial,dp,coin,height,i,jstri(tx,i),port) < 0 )
break;
if ( i == n )
retval = 0;

0
iguana/exchanges/DB/PRICES/.tmpmarker

6
iguana/exchanges/DEXstats.h

@ -51,7 +51,7 @@ struct DEXstats_pricepoint
struct DEXstats_pairinfo
{
char dest[16];
char dest[128];
int32_t numprices;
struct DEXstats_pricepoint *prices;
};
@ -64,7 +64,7 @@ struct DEXstats_datenuminfo
struct DEXstats_priceinfo
{
char symbol[16];
char symbol[128];
int32_t firstdatenum,numdates;
struct DEXstats_datenuminfo *dates;
} Prices[1024];
@ -927,6 +927,7 @@ char *stats_prices(char *symbol,char *dest,struct DEXstats_disp *prices,int32_t
}
#ifndef FROM_MARKETMAKER
#ifndef FROM_PRIVATEBET
char *stats_JSON(void *ctx,char *myipaddr,int32_t mypubsock,cJSON *argjson,char *remoteaddr,uint16_t port)
{
char *method,*agent,*retstr,*source,*dest; struct tai T; uint32_t endtimestamp; struct DEXstats_disp prices[365]; int32_t leftdatenum,seconds,numdates;
@ -953,5 +954,6 @@ char *stats_JSON(void *ctx,char *myipaddr,int32_t mypubsock,cJSON *argjson,char
return(clonestr(jprint(argjson,0)));
}
#endif
#endif
#endif /* DEXstats_h */

291
iguana/exchanges/LP_RTmetrics.c

@ -0,0 +1,291 @@
/******************************************************************************
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* 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. *
* *
******************************************************************************/
//
// LP_RTmetrics.c
// marketmaker
//
struct LP_metricinfo
{
double metric;
double price,balance,minvol;
bits256 pubkey;
double maxvol;
int32_t ind,numutxos,age,pendingswaps;
};
struct LP_RTmetrics_pendings
{
char refbase[65],refrel[65];
int32_t numswaps,numavoidtxids,numwhitelist,numblacklist,numpendings,pending_swaps[1024];
bits256 avoidtxids[8192],whitelist[1024],blacklist[1024],pending_pubkeys[1024];
} LP_RTmetrics;
int32_t LP_bits256_find(bits256 *list,int32_t num,bits256 val)
{
int32_t i;
if ( bits256_nonz(val) != 0 )
{
for (i=0; i<num; i++)
if ( bits256_cmp(list[i],val) == 0 )
return(i);
}
return(-1);
}
int32_t LP_bits256_add(char *debugstr,bits256 *list,int32_t *nump,int32_t maxnum,bits256 val)
{
if ( bits256_nonz(val) != 0 && *nump < maxnum )
{
if ( LP_bits256_find(list,*nump,val) < 0 )
list[(*nump)++] = val;
return(*nump);
} else printf("%s[%d] overflow\n",debugstr,*nump);
return(-1);
}
int32_t LP_RTmetrics_avoidadd(bits256 txid)
{
return(LP_bits256_add("LP_RTmetrics_avoidadd avoidtxids",LP_RTmetrics.avoidtxids,&LP_RTmetrics.numavoidtxids,(int32_t)(sizeof(LP_RTmetrics.avoidtxids)/sizeof(*LP_RTmetrics.avoidtxids)),txid));
}
int32_t LP_RTmetrics_whitelistadd(bits256 pubkey)
{
return(LP_bits256_add("LP_RTmetrics_whitelistadd whitelist",LP_RTmetrics.whitelist,&LP_RTmetrics.numwhitelist,(int32_t)(sizeof(LP_RTmetrics.whitelist)/sizeof(*LP_RTmetrics.whitelist)),pubkey));
}
int32_t LP_RTmetrics_blacklistadd(bits256 pubkey)
{
return(LP_bits256_add("LP_RTmetrics_blacklistadd blacklist",LP_RTmetrics.blacklist,&LP_RTmetrics.numblacklist,(int32_t)(sizeof(LP_RTmetrics.blacklist)/sizeof(*LP_RTmetrics.blacklist)),pubkey));
}
int32_t LP_RTmetrics_pendingswap(bits256 pubkey)
{
int32_t ind;
if ( (ind= LP_bits256_add("LP_RTmetrics_pendingswap",LP_RTmetrics.pending_pubkeys,&LP_RTmetrics.numpendings,(int32_t)(sizeof(LP_RTmetrics.pending_pubkeys)/sizeof(*LP_RTmetrics.pending_pubkeys)),pubkey)) >= 0 )
LP_RTmetrics.pending_swaps[ind]++;
return(ind);
}
int32_t LP_RTmetrics_pendingswaps(bits256 pubkey)
{
int32_t ind;
if ( (ind= LP_bits256_find(LP_RTmetrics.pending_pubkeys,LP_RTmetrics.numpendings,pubkey)) >= 0 )
return(LP_RTmetrics.pending_swaps[ind]);
else return(0);
}
int32_t LP_RTmetrics_avoidtxid(bits256 txid)
{
return(LP_bits256_find(LP_RTmetrics.avoidtxids,LP_RTmetrics.numavoidtxids,txid));
}
int32_t LP_RTmetrics_whitelisted(bits256 pubkey)
{
return(LP_bits256_find(LP_RTmetrics.whitelist,LP_RTmetrics.numwhitelist,pubkey));
}
int32_t LP_RTmetrics_blacklisted(bits256 pubkey)
{
return(LP_bits256_find(LP_RTmetrics.blacklist,LP_RTmetrics.numblacklist,pubkey));
}
void LP_RTmetrics_swapsinfo(char *refbase,char *refrel,cJSON *swaps,int32_t numswaps)
{
int32_t i; char *base,*rel,*retstr; cJSON *item,*swapjson; bits256 srcpub,destpub; uint64_t aliceid,basesatoshis,relsatoshis; uint32_t requestid,quoteid; double price;
for (i=0; i<numswaps; i++)
{
item = jitem(swaps,i);
if ( (base= jstr(item,"base")) == 0 )
base = "";
if ( (rel= jstr(item,"rel")) == 0 )
rel = "";
if ( strcmp(base,refbase) != 0 && strcmp(base,refrel) != 0 && strcmp(rel,refbase) != 0 && strcmp(rel,refrel) != 0 )
continue;
aliceid = j64bits(item,"aliceid");
basesatoshis = SATOSHIDEN * jdouble(item,"basevol");
srcpub = jbits256(item,"src");
relsatoshis = SATOSHIDEN * jdouble(item,"relvol");
destpub = jbits256(item,"dest");
price = jdouble(item,"price");
requestid = juint(item,"requestid");
quoteid = juint(item,"quoteid");
LP_RTmetrics_pendingswap(srcpub);
LP_RTmetrics_pendingswap(destpub);
if ( 0 && (retstr= basilisk_swapentry(requestid,quoteid)) != 0 ) // no need for this
{
if ( (swapjson= cJSON_Parse(retstr)) != 0 )
{
LP_RTmetrics_avoidadd(jbits256(swapjson,"bobdeposit"));
LP_RTmetrics_avoidadd(jbits256(swapjson,"alicepayment"));
LP_RTmetrics_avoidadd(jbits256(swapjson,"bobpayment"));
LP_RTmetrics_avoidadd(jbits256(swapjson,"paymentspent"));
LP_RTmetrics_avoidadd(jbits256(swapjson,"Apaymentspent"));
LP_RTmetrics_avoidadd(jbits256(swapjson,"depositspent"));
free_json(swapjson);
}
free(retstr);
}
}
}
void LP_RTmetrics_update(char *base,char *rel)
{
struct LP_pubkeyinfo *pubp,*tmp; uint32_t futuretime; int32_t i,numswaps; bits256 zero; char *retstr; cJSON *statsjson,*swaps;
memset(&LP_RTmetrics,0,sizeof(LP_RTmetrics));
HASH_ITER(hh,LP_pubkeyinfos,pubp,tmp)
{
if ( pubp->istrusted > 0 )
LP_RTmetrics_whitelistadd(pubp->pubkey);
else if ( pubp->istrusted < 0 )
LP_RTmetrics_blacklistadd(pubp->pubkey);
}
futuretime = (uint32_t)time(NULL) + 3600*100;
memset(zero.bytes,0,sizeof(zero));
if ( (retstr= LP_statslog_disp(100,futuretime,futuretime,"",zero)) != 0 )
{
if ( (statsjson= cJSON_Parse(retstr)) != 0 )
{
if ( (swaps= jarray(&numswaps,statsjson,"swaps")) != 0 )
{
//printf("LP_RTmetrics_update for (%s)\n",jprint(swaps,0));
if ( numswaps > 0 )
LP_RTmetrics_swapsinfo(base,rel,swaps,numswaps);
}
free_json(statsjson);
}
free(retstr);
}
for (i=0; i<LP_RTmetrics.numpendings; i++)
if ( LP_RTmetrics.pending_swaps[i] > LP_MAXPENDING_SWAPS )
{
char str[65]; printf("%s has %d pending swaps! which is more than %d\n",bits256_str(str,LP_RTmetrics.pending_pubkeys[i]),LP_RTmetrics.pending_swaps[i],LP_MAXPENDING_SWAPS);
LP_RTmetrics_blacklistadd(LP_RTmetrics.pending_pubkeys[i]);
}
//printf("%d pubkeys have pending swaps, whitelist.%d blacklist.%d avoidtxids.%d\n",LP_RTmetrics.numpendings,LP_RTmetrics.numwhitelist,LP_RTmetrics.numblacklist,LP_RTmetrics.numavoidtxids);
}
double _LP_RTmetric_calc(struct LP_metricinfo *mp,double bestprice,double maxprice,double relvolume)
{
int32_t n; double metric,origmetric = (mp->price / bestprice);
metric = origmetric;
if ( mp->numutxos == 0 || relvolume == 0. || mp->maxvol == 0. || mp->balance == 0. )
{
//printf("skip i.%d as no info\n",mp->ind);
return(metric * 100.);
}
if ( relvolume < mp->minvol )
{
metric *= (mp->minvol / relvolume);
//printf("relvolume < minvol %.8f\n",(mp->minvol / relvolume));
}
else if ( relvolume > mp->maxvol )
{
metric *= (relvolume / mp->maxvol);
//printf("relvolume > minvol %.8f\n",(relvolume / mp->maxvol));
}
if ( relvolume < mp->balance/LP_MINVOL )
{
metric *= (mp->balance / relvolume);
//printf("relvolume < balance %.8f\n",(mp->balance / relvolume));
}
else if ( relvolume > mp->balance/mp->numutxos )
{
metric *= (relvolume / (mp->balance/mp->numutxos));
//printf("relvolume < ave %.8f\n",(relvolume / (mp->balance/mp->numutxos)));
}
if ( mp->age > LP_ORDERBOOK_DURATION*0.8 )
metric *= 2;
else if ( mp->age > 60 )
metric *= 1.03;
if ( (n= mp->pendingswaps) > 0 )
while ( n-- > 0 )
metric *= 1.1;
//if ( metric != origmetric )
printf("i.%d price %.8f orig %.8f -> %.8f relvol %.8f min %.8f max %.8f bal %.8f age.%d pend.%d\n",mp->ind,mp->price,origmetric,metric,relvolume,mp->minvol,mp->maxvol,mp->balance,mp->age,mp->pendingswaps);
return(metric);
}
void LP_RTmetric_calc(struct LP_metricinfo *sortbuf,int32_t ind,cJSON *item,double bestprice,double maxprice,double relvolume,double prevdepth)
{
sortbuf[ind].pubkey = jbits256(item,"pubkey");
sortbuf[ind].price = jdouble(item,"price");
sortbuf[ind].maxvol = jdouble(item,"maxvolume");
sortbuf[ind].minvol = jdouble(item,"minvolume");
sortbuf[ind].balance = jdouble(item,"depth") - prevdepth;
sortbuf[ind].numutxos = juint(item,"numutxos");
sortbuf[ind].age = juint(item,"age");
sortbuf[ind].ind = ind;
sortbuf[ind].pendingswaps = LP_RTmetrics_pendingswaps(sortbuf[ind].pubkey);
sortbuf[ind].metric = _LP_RTmetric_calc(&sortbuf[ind],bestprice,maxprice,relvolume);
}
int _increasing_metrics(const void *a,const void *b)
{
#define ptr_a ((struct LP_metricinfo *)a)
#define ptr_b ((struct LP_metricinfo *)b)
if ( ptr_b->metric > ptr_a->metric )
return(-1);
else if ( ptr_b->metric < ptr_a->metric )
return(1);
return(0);
#undef ptr_a
#undef ptr_b
}
cJSON *LP_RTmetrics_sort(char *base,char *rel,cJSON *rawasks,int32_t numasks,double maxprice,double relvolume)
{
cJSON *array=rawasks,*item; int32_t i,num,groupi; double price,prevdepth,bestprice; struct LP_metricinfo *sortbuf;
groupi = -1;
bestprice = 0.;
for (num=i=0; i<numasks; i++)
{
item = jitem(rawasks,i);
price = jdouble(item,"price");
if ( price > maxprice )
break;
if ( i == 0 )
bestprice = price;
else if ( price < bestprice*LP_RTMETRICS_TOPGROUP )
groupi = i;
num++;
}
if ( groupi > 0 )
{
sortbuf = calloc(groupi+1,sizeof(*sortbuf));
prevdepth = 0.;
for (i=0; i<=groupi; i++)
{
item = jitem(rawasks,i);
LP_RTmetric_calc(sortbuf,i,item,bestprice,maxprice,relvolume,prevdepth);
prevdepth = jdouble(item,"depth");
//printf("%.8f ",sortbuf[i].metric);
}
qsort(&sortbuf[0].metric,groupi+1,sizeof(*sortbuf),_increasing_metrics);
array = cJSON_CreateArray();
for (i=0; i<=groupi; i++)
{
printf("(%d <- %d %.3f) ",i,sortbuf[i].ind,sortbuf[i].metric);
item = jitem(rawasks,sortbuf[i].ind);
jaddi(array,jduplicate(item));
}
for (; i<numasks; i++)
jaddi(array,jduplicate(jitem(rawasks,i)));
printf("new ask order for %d of %d, capped at num.%d\n",groupi,numasks,num);
free(sortbuf);
}
return(array);
}

252
iguana/exchanges/LP_bitcoin.c

@ -325,35 +325,6 @@ enum opcodetype
OP_INVALIDOPCODE = 0xff,
};
struct { bits256 privkey; uint8_t rmd160[20]; } LP_privkeys[100]; int32_t LP_numprivkeys;
bits256 LP_privkeyfind(uint8_t rmd160[20])
{
int32_t i; static bits256 zero;
for (i=0; i<LP_numprivkeys; i++)
if ( memcmp(rmd160,LP_privkeys[i].rmd160,20) == 0 )
return(LP_privkeys[i].privkey);
//for (i=0; i<20; i++)
// printf("%02x",rmd160[i]);
//printf(" -> no privkey\n");
return(zero);
}
int32_t LP_privkeyadd(bits256 privkey,uint8_t rmd160[20])
{
bits256 tmpkey;
tmpkey = LP_privkeyfind(rmd160);
if ( bits256_nonz(tmpkey) != 0 )
return(-bits256_cmp(privkey,tmpkey));
LP_privkeys[LP_numprivkeys].privkey = privkey;
memcpy(LP_privkeys[LP_numprivkeys].rmd160,rmd160,20);
//int32_t i; for (i=0; i<20; i++)
// printf("%02x",rmd160[i]);
//char str[65]; printf(" -> add privkey.(%s)\n",bits256_str(str,privkey));
LP_numprivkeys++;
return(LP_numprivkeys);
}
int32_t iguana_rwnum(int32_t rwflag,uint8_t *serialized,int32_t len,void *endianedp)
{
int32_t i; uint64_t x;
@ -1988,6 +1959,18 @@ int32_t bitcoin_timelockspend(uint8_t *script,int32_t n,uint8_t rmd160[20],uint3
return(n);
}
int32_t bitcoin_performancebond(uint8_t p2sh_rmd160[20],uint8_t *script,int32_t n,uint32_t unlocktimestamp,uint8_t cltv_rmd160[20],uint8_t anytime_rmd160[20])
{
script[n++] = SCRIPT_OP_IF;
n = bitcoin_checklocktimeverify(script,n,unlocktimestamp);
n = bitcoin_standardspend(script,n,cltv_rmd160);
script[n++] = SCRIPT_OP_ELSE;
n = bitcoin_standardspend(script,n,anytime_rmd160);
script[n++] = SCRIPT_OP_ENDIF;
calc_rmd160_sha256(p2sh_rmd160,script,n);
return(n);
}
int32_t bitcoin_MofNspendscript(uint8_t p2sh_rmd160[20],uint8_t *script,int32_t n,const struct vin_info *vp)
{
int32_t i,plen;
@ -2060,7 +2043,7 @@ int32_t bitcoin_addr2rmd160(uint8_t taddr,uint8_t *addrtypep,uint8_t rmd160[20],
}
for (i=0; i<len; i++)
printf("%02x ",buf[i]);
char str[65]; printf("\ntaddr.%02x checkhash.(%s) len.%d mismatch %02x %02x %02x %02x vs %02x %02x %02x %02x (%s)\n",taddr,coinaddr,len,buf[len-1]&0xff,buf[len-2]&0xff,buf[len-3]&0xff,buf[len-4]&0xff,hash.bytes[31],hash.bytes[30],hash.bytes[29],hash.bytes[28],bits256_str(str,hash));
char str[65]; printf("\naddrtype.%d taddr.%02x checkhash.(%s) len.%d mismatch %02x %02x %02x %02x vs %02x %02x %02x %02x (%s)\n",*addrtypep,taddr,coinaddr,len,buf[len-1]&0xff,buf[len-2]&0xff,buf[len-3]&0xff,buf[len-4]&0xff,hash.bytes[31],hash.bytes[30],hash.bytes[29],hash.bytes[28],bits256_str(str,hash));
}
}
return(0);
@ -2233,21 +2216,6 @@ int32_t bitcoin_priv2wiflong(uint8_t wiftaddr,char *wifstr,bits256 privkey,uint8
return((int32_t)strlen(wifstr));
}
bits256 LP_privkey(char *coinaddr,uint8_t taddr)
{
bits256 privkey; uint8_t addrtype,rmd160[20];
bitcoin_addr2rmd160(taddr,&addrtype,rmd160,coinaddr);
privkey = LP_privkeyfind(rmd160);
return(privkey);
}
bits256 LP_pubkey(bits256 privkey)
{
bits256 pubkey;
pubkey = curve25519(privkey,curve25519_basepoint9());
return(pubkey);
}
char *_setVsigner(uint8_t wiftaddr,uint8_t pubtype,struct vin_info *V,int32_t ind,char *pubstr,char *wifstr)
{
uint8_t addrtype;
@ -2372,7 +2340,7 @@ int32_t iguana_scriptgen(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,int32_t
return(scriptlen);
}
int32_t bitcoin_scriptget(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,int32_t *hashtypep,uint32_t *sigsizep,uint32_t *pubkeysizep,uint8_t **userdatap,uint32_t *userdatalenp,struct vin_info *vp,uint8_t *scriptsig,int32_t len,int32_t spendtype)
int32_t bitcoin_scriptget(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint32_t *hashtypep,uint32_t *sigsizep,uint32_t *pubkeysizep,uint8_t **userdatap,uint32_t *userdatalenp,struct vin_info *vp,uint8_t *scriptsig,int32_t len,int32_t spendtype)
{
int32_t j,n,siglen,plen; uint8_t *p2shscript;
j = n = 0;
@ -2615,10 +2583,44 @@ int32_t iguana_calcrmd160(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,char *a
return(vp->type);
}
uint32_t iguana_vinscriptparse(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,struct vin_info *vp,uint32_t *sigsizep,uint32_t *pubkeysizep,uint32_t *p2shsizep,uint32_t *userdatalenp,uint8_t *vinscript,int32_t scriptlen)
{
uint32_t hashtype; uint8_t *userdata = 0;
*sigsizep = *pubkeysizep = *p2shsizep = *userdatalenp = 0;
if ( bitcoin_scriptget(taddr,pubtype,p2shtype,&hashtype,sigsizep,pubkeysizep,&userdata,userdatalenp,vp,vinscript,scriptlen,0) < 0 )
{
printf("iguana_vinscriptparse: error parsing vinscript?\n");
return(-1);
}
if ( userdata != 0 && *userdatalenp > 0 )
memcpy(vp->userdata,userdata,*userdatalenp);
if ( vp->type == IGUANA_SCRIPT_P2SH )
{
*p2shsizep = vp->p2shlen + 1 + (vp->p2shlen >= 0xfd)*2;
//printf("P2SHSIZE.%d\n",*p2shsizep);
}
return(hashtype);
}
/*char *iguana_scriptget(struct iguana_info *coin,char *scriptstr,char *asmstr,int32_t max,int32_t hdrsi,uint32_t unspentind,bits256 txid,int32_t vout,uint8_t *rmd160,int32_t type,uint8_t *pubkey33)
{
int32_t scriptlen; uint8_t script[IGUANA_MAXSCRIPTSIZE]; struct vin_info V,*vp = &V;
memset(vp,0,sizeof(*vp));
scriptstr[0] = 0;
if ( asmstr != 0 )
asmstr[0] = 0;
if ( pubkey33 != 0 && bitcoin_pubkeylen(pubkey33) > 0 )
memcpy(vp->signers[0].pubkey,pubkey33,33);
scriptlen = iguana_scriptgen(coin,&vp->M,&vp->N,vp->coinaddr,script,asmstr,rmd160,type,(const struct vin_info *)vp,vout);
init_hexbytes_noT(scriptstr,script,scriptlen);
return(scriptstr);
}*/
cJSON *bitcoin_txscript(char *asmstr,char **vardata,int32_t numvars)
{
int32_t i; cJSON *scriptjson,*array;
scriptjson = cJSON_CreateObject();
if ( asmstr != 0 )
jaddstr(scriptjson,"asm",asmstr);
jaddnum(scriptjson,"numvars",numvars);
if ( numvars > 0 )
@ -3186,7 +3188,7 @@ int32_t iguana_parsevoutobj(uint8_t *serialized,int32_t maxsize,struct iguana_ms
cJSON *iguana_voutjson(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,struct iguana_msgvout *vout,int32_t txi,bits256 txid)
{
// 035f1321ed17d387e4433b2fa229c53616057964af065f98bfcae2233c5108055e OP_CHECKSIG
char scriptstr[IGUANA_MAXSCRIPTSIZE+1],asmstr[2*IGUANA_MAXSCRIPTSIZE+1]; int32_t i,m,n,scriptlen,asmtype; struct vin_info *vp;
char scriptstr[IGUANA_MAXSCRIPTSIZE+1]; int32_t i,m,n,scriptlen,asmtype; struct vin_info *vp;
uint8_t space[8192]; cJSON *addrs,*skey,*json = cJSON_CreateObject();
vp = calloc(1,sizeof(*vp));
jadd64bits(json,"satoshis",vout->value);
@ -3196,12 +3198,12 @@ cJSON *iguana_voutjson(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,struct igu
if ( vout->pk_script != 0 && vout->pk_scriptlen*2+1 < sizeof(scriptstr) )
{
memset(vp,0,sizeof(*vp));
if ( (asmtype= iguana_calcrmd160(taddr,pubtype,p2shtype,asmstr,vp,vout->pk_script,vout->pk_scriptlen,txid,txi,0xffffffff)) >= 0 )
if ( (asmtype= iguana_calcrmd160(taddr,pubtype,p2shtype,0,vp,vout->pk_script,vout->pk_scriptlen,txid,txi,0xffffffff)) >= 0 )
{
skey = cJSON_CreateObject();
scriptlen = iguana_scriptgen(taddr,pubtype,p2shtype,&m,&n,vp->coinaddr,space,asmstr,vp->rmd160,asmtype,vp,txi);
if ( asmstr[0] != 0 )
jaddstr(skey,"asm",asmstr);
scriptlen = iguana_scriptgen(taddr,pubtype,p2shtype,&m,&n,vp->coinaddr,space,0,vp->rmd160,asmtype,vp,txi);
//if ( asmstr[0] != 0 )
// jaddstr(skey,"asm",asmstr);
addrs = cJSON_CreateArray();
if ( vp->N == 1 )
{
@ -3229,6 +3231,7 @@ cJSON *iguana_voutjson(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,struct igu
jadd(json,"scriptPubKey",skey);
}
}
free(vp);
return(json);
}
@ -3276,9 +3279,9 @@ int32_t iguana_vinarray_check(cJSON *vinarray,bits256 txid,int32_t vout)
return(-1);
}
int32_t iguana_rwmsgtx(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,int32_t rwflag,cJSON *json,uint8_t *serialized,int32_t maxsize,struct iguana_msgtx *msg,bits256 *txidp,char *vpnstr,uint8_t *extraspace,int32_t extralen,cJSON *vins,int32_t suppress_pubkeys);
int32_t iguana_rwmsgtx(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,int32_t rwflag,cJSON *json,uint8_t *serialized,int32_t maxsize,struct iguana_msgtx *msg,bits256 *txidp,char *vpnstr,uint8_t *extraspace,int32_t extralen,cJSON *vins,int32_t suppress_pubkeys,int32_t zcash);
bits256 bitcoin_sigtxid(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,uint8_t *serialized,int32_t maxlen,struct iguana_msgtx *msgtx,int32_t vini,uint8_t *spendscript,int32_t spendlen,int32_t hashtype,char *vpnstr,int32_t suppress_pubkeys)
bits256 bitcoin_sigtxid(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,uint8_t *serialized,int32_t maxlen,struct iguana_msgtx *msgtx,int32_t vini,uint8_t *spendscript,int32_t spendlen,uint32_t hashtype,char *vpnstr,int32_t suppress_pubkeys,int32_t zcash)
{
int32_t i,len; bits256 sigtxid,txid,revsigtxid; struct iguana_msgtx dest;
dest = *msgtx;
@ -3287,7 +3290,7 @@ bits256 bitcoin_sigtxid(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t i
memcpy(dest.vins,msgtx->vins,dest.tx_in * sizeof(*dest.vins));
memcpy(dest.vouts,msgtx->vouts,dest.tx_out * sizeof(*dest.vouts));
memset(sigtxid.bytes,0,sizeof(sigtxid));
if ( hashtype != SIGHASH_ALL )
if ( (hashtype & ~SIGHASH_FORKID) != SIGHASH_ALL )
{
printf("currently only SIGHASH_ALL supported, not %d\n",hashtype);
return(sigtxid);
@ -3312,7 +3315,7 @@ bits256 bitcoin_sigtxid(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t i
dest.vins[i].userdata = 0;
dest.vins[i].userdatalen = 0;
}
len = iguana_rwmsgtx(taddr,pubtype,p2shtype,isPoS,height,1,0,serialized,maxlen,&dest,&txid,vpnstr,0,0,0,suppress_pubkeys);
len = iguana_rwmsgtx(taddr,pubtype,p2shtype,isPoS,height,1,0,serialized,maxlen,&dest,&txid,vpnstr,0,0,0,suppress_pubkeys,zcash);
//for (i=0; i<len; i++)
// printf("%02x",serialized[i]);
//printf(" <- sigtx len.%d supp.%d user[0].%d\n",len,suppress_pubkeys,dest.vins[0].userdatalen);
@ -3333,9 +3336,36 @@ bits256 bitcoin_sigtxid(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t i
return(sigtxid);
}
int32_t iguana_rwmsgtx(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,int32_t rwflag,cJSON *json,uint8_t *serialized,int32_t maxsize,struct iguana_msgtx *msg,bits256 *txidp,char *vpnstr,uint8_t *extraspace,int32_t extralen,cJSON *vins,int32_t suppress_pubkeys)
int32_t iguana_rwjoinsplit(int32_t rwflag,uint8_t *serialized,struct iguana_msgjoinsplit *msg)
{
int32_t i,n,len = 0,extraused=0; uint8_t spendscript[IGUANA_MAXSCRIPTSIZE],*txstart = serialized,*sigser=0; char txidstr[65]; cJSON *vinarray=0,*voutarray=0; bits256 sigtxid;
int32_t len = 0;
len += iguana_rwnum(rwflag,&serialized[len],sizeof(msg->vpub_old),&msg->vpub_old);
len += iguana_rwnum(rwflag,&serialized[len],sizeof(msg->vpub_new),&msg->vpub_new);
len += iguana_rwbignum(rwflag,&serialized[len],sizeof(msg->anchor),msg->anchor.bytes);
len += iguana_rwbignum(rwflag,&serialized[len],sizeof(msg->nullifiers[0]),msg->nullifiers[0].bytes);
len += iguana_rwbignum(rwflag,&serialized[len],sizeof(msg->nullifiers[1]),msg->nullifiers[1].bytes);
len += iguana_rwbignum(rwflag,&serialized[len],sizeof(msg->commitments[0]),msg->commitments[0].bytes);
len += iguana_rwbignum(rwflag,&serialized[len],sizeof(msg->commitments[1]),msg->commitments[1].bytes);
len += iguana_rwbignum(rwflag,&serialized[len],sizeof(msg->ephemeralkey),msg->ephemeralkey.bytes);
if ( rwflag == 1 )
memcpy(&serialized[len],msg->ciphertexts,sizeof(msg->ciphertexts));
else memcpy(msg->ciphertexts,&serialized[len],sizeof(msg->ciphertexts));
len += sizeof(msg->ciphertexts);
len += iguana_rwbignum(rwflag,&serialized[len],sizeof(msg->randomseed),msg->randomseed.bytes);
len += iguana_rwbignum(rwflag,&serialized[len],sizeof(msg->vmacs[0]),msg->vmacs[0].bytes);
len += iguana_rwbignum(rwflag,&serialized[len],sizeof(msg->vmacs[1]),msg->vmacs[1].bytes);
if ( rwflag == 1 )
memcpy(&serialized[len],msg->zkproof,sizeof(msg->zkproof));
else memcpy(msg->zkproof,&serialized[len],sizeof(msg->zkproof));
len += sizeof(msg->zkproof);
return(len);
}
int32_t iguana_rwmsgtx(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,int32_t rwflag,cJSON *json,uint8_t *serialized,int32_t maxsize,struct iguana_msgtx *msg,bits256 *txidp,char *vpnstr,uint8_t *extraspace,int32_t extralen,cJSON *vins,int32_t suppress_pubkeys,int32_t zcash)
{
int32_t i,j,n,segtxlen,len = 0,extraused=0; uint32_t tmp,segitems; uint8_t *segtx=0,segwitflag=0,spendscript[IGUANA_MAXSCRIPTSIZE],*txstart = serialized,*sigser=0; char txidstr[65]; cJSON *vinarray=0,*voutarray=0; bits256 sigtxid;
len += iguana_rwnum(rwflag,&serialized[len],sizeof(msg->version),&msg->version);
if ( json != 0 )
{
@ -3354,6 +3384,22 @@ int32_t iguana_rwmsgtx(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t is
if ( json != 0 )
jaddnum(json,"timestamp",msg->timestamp);
}
if ( rwflag == 0 && zcash == 0 )
{
/*
normal: nVersion|txins|txouts|nLockTime.
segwit
nVersion|marker|flag|txins|txouts|witness|nLockTime
Format of nVersion, txins, txouts, and nLockTime are same as the original format
The marker MUST be 0x00
The flag MUST be 0x01
*/
if ( serialized[len] == 0x00 && (segwitflag= serialized[len+1]) == 0x01 )
{
len += 2;
//printf("SEGWIT transaction\n");
}
}
len += iguana_rwvarint32(rwflag,&serialized[len],&msg->tx_in);
if ( rwflag == 0 )
{
@ -3371,7 +3417,7 @@ int32_t iguana_rwmsgtx(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t is
}
for (i=0; i<msg->tx_in; i++)
{
//printf("vin.%d starts offset.%d\n",i,len);
//printf("vin.%d starts offset.%d numvins.%d\n",i,len,msg->tx_in);
if ( vins != 0 && jitem(vins,i) != 0 )
iguana_vinobjset(&msg->vins[i],jitem(vins,i),spendscript,sizeof(spendscript));
if ( (n= iguana_vinparse(rwflag,&serialized[len],&msg->vins[i])) < 0 )
@ -3409,7 +3455,7 @@ int32_t iguana_rwmsgtx(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t is
}
for (i=0; i<msg->tx_out; i++)
{
//printf("rwflag.%d vout.%d starts %d\n",rwflag,i,len);
//printf("rwflag.%d vout.%d starts %d numvouts.%d\n",rwflag,i,len,msg->tx_out);
if ( (n= iguana_voutparse(rwflag,&serialized[len],&msg->vouts[i])) < 0 )
return(-1);
len += n;
@ -3421,28 +3467,65 @@ int32_t iguana_rwmsgtx(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t is
if ( voutarray != 0 )
jaddi(voutarray,iguana_voutjson(taddr,pubtype,p2shtype,&msg->vouts[i],i,*txidp));
}
if ( segwitflag != 0 )
{
segtxlen = len - 2 + sizeof(msg->lock_time);
segtx = malloc(segtxlen);
memcpy(segtx,serialized,sizeof(int32_t));
memcpy(&segtx[sizeof(int32_t)],&serialized[sizeof(int32_t)+2],len-2-sizeof(int32_t));
//printf("tx_out %d, tx_in %d %02x %02x %02x\n",msg->tx_out,msg->tx_in,serialized[len],serialized[len+1],serialized[len+2]);
if ( rwflag != 0 )
printf("unsupported rwflag.%d when segwitflag\n",rwflag);
else
{
for (i=0; i<msg->tx_in; i++)
{
len += iguana_rwvarint32(rwflag,&serialized[len],&segitems);
//printf("vini.%d (%d:",i,segitems);
for (j=0; j<segitems; j++)
{
len += iguana_rwvarint32(rwflag,&serialized[len],&tmp);
//printf(" %d",tmp);
if ( len+tmp >= maxsize )
{
printf("vini.%d of %d, j.%d of segitems.%d overflowed %d+%d >= max.%d\n",i,msg->tx_in,j,segitems,len,tmp,maxsize);
break;
} else len += tmp;
}
//printf("), ");
}
memcpy(&segtx[segtxlen-sizeof(int32_t)],&serialized[len],sizeof(int32_t));
*txidp = bits256_doublesha256(0,segtx,segtxlen);
free(segtx);
//char str[65]; printf("witness sum %d vs max.%d txid %s\n",len,maxsize,bits256_str(str,txid));
}
}
len += iguana_rwnum(rwflag,&serialized[len],sizeof(msg->lock_time),&msg->lock_time);
//printf("lock_time.%08x len.%d\n",msg->lock_time,len);
/*if ( strcmp(coin->symbol,"VPN") == 0 )
if ( zcash == LP_IS_ZCASHPROTOCOL && msg->version > 1 )
{
uint16_t ddosflag = 0;
len += iguana_rwnum(rwflag,&serialized[len],sizeof(ddosflag),&ddosflag);
for (i=0; serialized[len]!=0&&len<maxsize; len++,i++) // eat null terminated string
uint32_t numjoinsplits; struct iguana_msgjoinsplit joinsplit; uint8_t joinsplitpubkey[33],joinsplitsig[64];
len += iguana_rwvarint32(rwflag,&serialized[len],&numjoinsplits);
if ( numjoinsplits > 0 )
{
if ( rwflag == 0 )
serialized[len] = vpnstr[i];
else vpnstr[i] = serialized[len];
for (i=0; i<numjoinsplits; i++)
len += iguana_rwjoinsplit(rwflag,&serialized[len],&joinsplit);
if ( rwflag != 0 )
{
memset(joinsplitpubkey,0,sizeof(joinsplitpubkey)); // for now
memset(joinsplitsig,0,sizeof(joinsplitsig)); // set to actuals
memcpy(&serialized[len],joinsplitpubkey+1,32), len += 32;
memcpy(&serialized[len],joinsplitsig,64), len += 64;
}
if ( rwflag == 0 )
serialized[len] = 0;
else vpnstr[i] = 0;
len++;
if ( json != 0 )
else
{
jaddnum(json,"ddosflag",ddosflag);
jaddstr(json,"vpnstr",vpnstr);
joinsplitpubkey[0] = 0x02; // need to verify its not 0x03
memcpy(joinsplitpubkey+1,&serialized[len],32), len += 32;
memcpy(joinsplitsig,&serialized[len],64), len += 64;
}
}
}
}*/
if ( sigser != 0 && vinarray != 0 )
{
for (i=0; i<msg->tx_in; i++)
@ -3450,8 +3533,12 @@ int32_t iguana_rwmsgtx(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t is
memset(sigtxid.bytes,0,sizeof(sigtxid));
if ( vins != 0 && jitem(vins,i) != 0 )
{
uint32_t sighash;
iguana_vinobjset(&msg->vins[i],jitem(vins,i),spendscript,sizeof(spendscript));
sigtxid = bitcoin_sigtxid(taddr,pubtype,p2shtype,isPoS,height,sigser,maxsize*2,msg,i,msg->vins[i].spendscript,msg->vins[i].spendlen,SIGHASH_ALL,vpnstr,suppress_pubkeys);
sighash = SIGHASH_ALL;
if ( zcash == LP_IS_BITCOINCASH )
sighash |= SIGHASH_FORKID;
sigtxid = bitcoin_sigtxid(taddr,pubtype,p2shtype,isPoS,height,sigser,maxsize*2,msg,i,msg->vins[i].spendscript,msg->vins[i].spendlen,sighash,vpnstr,suppress_pubkeys,zcash);
//printf("after vini.%d vinscript.%p spendscript.%p spendlen.%d (%s)\n",i,msg->vins[i].vinscript,msg->vins[i].spendscript,msg->vins[i].spendlen,jprint(jitem(vins,i),0));
if ( iguana_vinarray_check(vinarray,msg->vins[i].prev_hash,msg->vins[i].prev_vout) < 0 )
jaddi(vinarray,iguana_vinjson(&msg->vins[i],sigtxid));
@ -3470,6 +3557,7 @@ int32_t iguana_rwmsgtx(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t is
jadd(json,"vout",voutarray);
jaddnum(json,"numvouts",msg->tx_out);
}
if ( segwitflag == 0 )
*txidp = bits256_doublesha256(txidstr,txstart,len);
if ( json != 0 )
{
@ -3548,13 +3636,13 @@ bits256 iguana_parsetxobj(uint8_t isPoS,int32_t *txstartp,uint8_t *serialized,in
return(txid);
}
char *iguana_rawtxbytes(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,cJSON *json,struct iguana_msgtx *msgtx,int32_t suppress_pubkeys)
char *iguana_rawtxbytes(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,cJSON *json,struct iguana_msgtx *msgtx,int32_t suppress_pubkeys,int32_t zcash)
{
int32_t n; char *txbytes = 0,vpnstr[64]; uint8_t *serialized;
serialized = malloc(IGUANA_MAXPACKETSIZE);
vpnstr[0] = 0;
//char str[65]; printf("%d of %d: %s\n",i,msg.txn_count,bits256_str(str,tx.txid));
if ( (n= iguana_rwmsgtx(taddr,pubtype,p2shtype,isPoS,height,1,json,serialized,IGUANA_MAXPACKETSIZE,msgtx,&msgtx->txid,vpnstr,0,0,0,suppress_pubkeys)) > 0 )
if ( (n= iguana_rwmsgtx(taddr,pubtype,p2shtype,isPoS,height,1,json,serialized,IGUANA_MAXPACKETSIZE,msgtx,&msgtx->txid,vpnstr,0,0,0,suppress_pubkeys,zcash)) > 0 )
{
txbytes = malloc(n*2+1);
init_hexbytes_noT(txbytes,serialized,n);
@ -3582,7 +3670,7 @@ char *bitcoin_json2hex(uint8_t isPoS,bits256 *txidp,cJSON *txjson,struct vin_inf
return(txbytes);
}
cJSON *bitcoin_data2json(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,bits256 *txidp,struct iguana_msgtx *msgtx,uint8_t *extraspace,int32_t extralen,uint8_t *serialized,int32_t len,cJSON *vins,int32_t suppress_pubkeys)
cJSON *bitcoin_data2json(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,bits256 *txidp,struct iguana_msgtx *msgtx,uint8_t *extraspace,int32_t extralen,uint8_t *serialized,int32_t len,cJSON *vins,int32_t suppress_pubkeys,int32_t zcash)
{
int32_t n; char vpnstr[64]; struct iguana_msgtx M; cJSON *txobj;
if ( serialized == 0 )
@ -3593,7 +3681,7 @@ cJSON *bitcoin_data2json(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t
memset(msgtx,0,sizeof(M));
vpnstr[0] = 0;
memset(txidp,0,sizeof(*txidp));
if ( (n= iguana_rwmsgtx(taddr,pubtype,p2shtype,isPoS,height,0,txobj,serialized,len,msgtx,txidp,vpnstr,extraspace,extralen,vins,suppress_pubkeys)) <= 0 )
if ( (n= iguana_rwmsgtx(taddr,pubtype,p2shtype,isPoS,height,0,txobj,serialized,len,msgtx,txidp,vpnstr,extraspace,extralen,vins,suppress_pubkeys,zcash)) <= 0 )
{
printf("errortxobj.(%s)\n",jprint(txobj,0));
free_json(txobj);
@ -3604,14 +3692,14 @@ cJSON *bitcoin_data2json(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t
if ( n != len )
{
int32_t i;
for (i=0; i<=len; i++)
for (i=0; i<len&&i<n; i++)
printf("%02x",serialized[i]);
printf(" data2json n.%d vs len.%d\n",n,len);
}
return(txobj);
}
cJSON *bitcoin_hex2json(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,bits256 *txidp,struct iguana_msgtx *msgtx,char *txbytes,uint8_t *extraspace,int32_t extralen,uint8_t *origserialized,cJSON *vins,int32_t suppress_pubkeys)
cJSON *bitcoin_hex2json(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,bits256 *txidp,struct iguana_msgtx *msgtx,char *txbytes,uint8_t *extraspace,int32_t extralen,uint8_t *origserialized,cJSON *vins,int32_t suppress_pubkeys,int32_t zcash)
{
int32_t len; uint8_t *serialized; cJSON *txobj;
if ( txbytes == 0 )
@ -3620,7 +3708,7 @@ cJSON *bitcoin_hex2json(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t i
if ( (serialized= origserialized) == 0 )
serialized = calloc(1,len+4096);
decode_hex(serialized,len,txbytes);
txobj = bitcoin_data2json(taddr,pubtype,p2shtype,isPoS,height,txidp,msgtx,extraspace,extralen,serialized,len,vins,suppress_pubkeys);
txobj = bitcoin_data2json(taddr,pubtype,p2shtype,isPoS,height,txidp,msgtx,extraspace,extralen,serialized,len,vins,suppress_pubkeys,zcash);
if ( serialized != origserialized )
free(serialized);
return(txobj);

343
iguana/exchanges/LP_cache.c

@ -0,0 +1,343 @@
/******************************************************************************
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* 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. *
* *
******************************************************************************/
//
// LP_cache.c
// marketmaker
//
cJSON *LP_transaction_fromdata(struct iguana_info *coin,bits256 txid,uint8_t *serialized,int32_t len)
{
uint8_t *extraspace; cJSON *txobj; char str[65],str2[65]; struct iguana_msgtx msgtx; bits256 checktxid;
extraspace = calloc(1,4000000);
memset(&msgtx,0,sizeof(msgtx));
txobj = bitcoin_data2json(coin->taddr,coin->pubtype,coin->p2shtype,coin->isPoS,coin->height,&checktxid,&msgtx,extraspace,4000000,serialized,len,0,0,coin->zcash);
//printf("TX.(%s) match.%d\n",jprint(txobj,0),bits256_cmp(txid,checktxid));
free(extraspace);
if ( bits256_cmp(txid,checktxid) != 0 )
{
printf("%s LP_transaction_fromdata mismatched txid %s vs %s\n",coin->symbol,bits256_str(str,txid),bits256_str(str2,checktxid));
free_json(txobj);
txobj = 0;
}
return(txobj);
}
struct LP_transaction *LP_create_transaction(struct iguana_info *coin,bits256 txid,uint8_t *serialized,int32_t len,int32_t height,long fpos)
{
cJSON *txobj; bits256 spenttxid; int32_t i,spentvout,numvins,numvouts; cJSON *vout,*vin,*vins,*vouts; struct LP_transaction *tx; char str[65];
if ( (tx= LP_transactionfind(coin,txid)) != 0 )
return(tx);
if ( (txobj= LP_transaction_fromdata(coin,txid,serialized,len)) != 0 )
{
vins = jarray(&numvins,txobj,"vin");
vouts = jarray(&numvouts,txobj,"vout");
tx = LP_transactionadd(coin,txid,height,numvouts,numvins);
tx->serialized = 0;//serialized;
free(serialized);
tx->fpos = fpos;
tx->len = 0;//tx->len;
tx->SPV = tx->height = height;
//printf("tx.%s numvins.%d numvouts.%d\n",bits256_str(str,txid),numvins,numvouts);
for (i=0; i<numvouts; i++)
{
vout = jitem(vouts,i);
tx->outpoints[i].value = LP_value_extract(vout,0);
tx->outpoints[i].interest = SATOSHIDEN * jdouble(vout,"interest");
LP_destaddr(tx->outpoints[i].coinaddr,vout);
//printf("from transaction init %s %s %s/v%d <- %.8f\n",coin->symbol,tx->outpoints[i].coinaddr,bits256_str(str,txid),i,dstr(tx->outpoints[i].value));
LP_address_utxoadd((uint32_t)time(NULL),"LP_create_transaction",coin,tx->outpoints[i].coinaddr,txid,i,tx->outpoints[i].value,height,-1);
}
for (i=0; i<numvins; i++)
{
vin = jitem(vins,i);
spenttxid = jbits256(vin,"txid");
spentvout = jint(vin,"vout");
if ( i == 0 && bits256_nonz(spenttxid) == 0 )
continue;
if ( (tx= LP_transactionfind(coin,spenttxid)) != 0 )
{
if ( spentvout < tx->numvouts )
{
if ( tx->outpoints[spentvout].spendheight <= 0 )
{
tx->outpoints[spentvout].spendtxid = txid;
tx->outpoints[spentvout].spendvini = i;
tx->outpoints[spentvout].spendheight = height > 0 ? height : 1;
LP_address_utxoadd((uint32_t)time(NULL),"LP_transactioninit iter1",coin,tx->outpoints[spentvout].coinaddr,spenttxid,spentvout,tx->outpoints[spentvout].value,-1,height>0?height:1);
if ( 0 && strcmp(coin->symbol,"REVS") == 0 )
printf("spend %s %s/v%d at ht.%d\n",coin->symbol,bits256_str(str,tx->txid),spentvout,height);
}
} else printf("LP_transactioninit: %s spentvout.%d < numvouts.%d spendheight.%d\n",bits256_str(str,spenttxid),spentvout,tx->numvouts,tx->outpoints[spentvout].spendheight);
} //else printf("LP_transactioninit: couldnt find (%s) ht.%d %s\n",bits256_str(str,spenttxid),height,jprint(vin,0));
if ( bits256_cmp(spenttxid,txid) == 0 )
printf("spending same tx's %p vout ht.%d %s.[%d] s%d\n",tx,height,bits256_str(str,txid),tx!=0?tx->numvouts:0,spentvout);
}
free_json(txobj);
}
return(tx);
}
void LP_SPV_store(struct iguana_info *coin,bits256 txid,int32_t height)
{
FILE *fp; char fname[512]; struct LP_transaction *tx = 0;
if ( (tx= LP_transactionfind(coin,txid)) != 0 && tx->serialized != 0 && tx->len > 0 && tx->fpos == 0 )
{
sprintf(fname,"%s/UNSPENTS/%s.SPV",GLOBAL_DBDIR,coin->symbol), OS_portable_path(fname);
if ( (fp= OS_appendfile(fname)) != 0 )
{
fwrite(&tx->txid,1,sizeof(tx->txid),fp);
fwrite(&tx->len,1,sizeof(tx->len),fp);
fwrite(&tx->height,1,sizeof(tx->height),fp);
tx->fpos = ftell(fp);
fwrite(tx->serialized,1,tx->len,fp);
fclose(fp);
}
} //else printf("cant store %s %s tx.%p [%d] fpos.%ld SPV.%d\n",coin->symbol,bits256_str(str,txid),tx,tx!=0?tx->len:-1,tx!=0?tx->fpos:-1,tx!=0?tx->SPV:-1);
}
int32_t LP_cacheitem(struct iguana_info *coin,FILE *fp)
{
bits256 txid,hash; long fpos; int32_t offset,retval,height,len; uint8_t *serialized; char str[65],str2[65];
fpos = ftell(fp);
if ( fread(&txid,1,sizeof(txid),fp) == sizeof(txid) && fread(&len,1,sizeof(len),fp) == sizeof(len) && fread(&height,1,sizeof(height),fp) == sizeof(height) && len < 100000 )
{
offset = (int32_t)(sizeof(txid) + sizeof(len) + sizeof(height));
serialized = malloc(len);
if ( (retval= (int32_t)fread(serialized,1,len,fp)) == len )
{
hash = bits256_doublesha256(0,serialized,len);
if ( bits256_cmp(hash,txid) == 0 )
{
//printf("%s validated in cache\n",bits256_str(str,hash));
LP_create_transaction(coin,txid,serialized,len,height,fpos+offset);
return((int32_t)(ftell(fp) - fpos));
}
printf("%s vs %s did not validated in cache\n",bits256_str(str,hash),bits256_str(str2,txid));
} else printf("retval.%d vs len.%d\n",retval,len);
} else printf("fread error\n");
return(-1);
}
void LP_cacheptrs_init(struct iguana_info *coin)
{
char fname[1024]; FILE *fp; int32_t count,tflag=0; long n,fsize=0,len = 0;
sprintf(fname,"%s/UNSPENTS/%s.SPV",GLOBAL_DBDIR,coin->symbol), OS_portable_path(fname);
fp = fopen(fname,"rb");
count = 0;
if ( fp != 0 )
{
fseek(fp,0,SEEK_END);
fsize = ftell(fp);
rewind(fp);
while ( len < fsize )
{
if ( (n= LP_cacheitem(coin,fp)) < 0 )
{
printf("cacheitem error at %s offset.%ld when fsize.%ld\n",coin->symbol,len,fsize);
tflag = 1;
break;
}
count++;
len += n;
}
printf("loaded %s %d entries total len.%ld\n",fname,count,len);
fclose(fp);
} //else printf("couldnt find.(%s)\n",fname);
if ( tflag != 0 )
OS_truncate(fname,len);
}
bits256 iguana_merkle(bits256 *tree,int32_t txn_count)
{
int32_t i,n=0,prev; uint8_t serialized[sizeof(bits256) * 2];
if ( txn_count == 1 )
return(tree[0]);
prev = 0;
while ( txn_count > 1 )
{
if ( (txn_count & 1) != 0 )
tree[prev + txn_count] = tree[prev + txn_count-1], txn_count++;
n += txn_count;
for (i=0; i<txn_count; i+=2)
{
iguana_rwbignum(1,serialized,sizeof(*tree),tree[prev + i].bytes);
iguana_rwbignum(1,&serialized[sizeof(*tree)],sizeof(*tree),tree[prev + i + 1].bytes);
tree[n + (i >> 1)] = bits256_doublesha256(0,serialized,sizeof(serialized));
}
prev = n;
txn_count >>= 1;
}
return(tree[n]);
}
bits256 validate_merkle(int32_t pos,bits256 txid,cJSON *proofarray,int32_t proofsize)
{
int32_t i; uint8_t serialized[sizeof(bits256) * 2]; bits256 hash,proof;
hash = txid;
for (i=0; i<proofsize; i++)
{
proof = jbits256i(proofarray,i);
if ( (pos & 1) == 0 )
{
iguana_rwbignum(1,&serialized[0],sizeof(hash),hash.bytes);
iguana_rwbignum(1,&serialized[sizeof(hash)],sizeof(proof),proof.bytes);
}
else
{
iguana_rwbignum(1,&serialized[0],sizeof(proof),proof.bytes);
iguana_rwbignum(1,&serialized[sizeof(hash)],sizeof(hash),hash.bytes);
}
hash = bits256_doublesha256(0,serialized,sizeof(serialized));
pos >>= 1;
}
return(hash);
}
bits256 LP_merkleroot(struct iguana_info *coin,struct electrum_info *ep,int32_t height)
{
cJSON *hdrobj; bits256 merkleroot;
memset(merkleroot.bytes,0,sizeof(merkleroot));
if ( coin->cachedmerkleheight == height )
return(coin->cachedmerkle);
if ( (hdrobj= electrum_getheader(coin->symbol,ep,&hdrobj,height)) != 0 )
{
if ( jobj(hdrobj,"merkle_root") != 0 )
{
merkleroot = jbits256(hdrobj,"merkle_root");
if ( bits256_nonz(merkleroot) != 0 )
{
coin->cachedmerkle = merkleroot;
coin->cachedmerkleheight = height;
}
}
free_json(hdrobj);
} else printf("couldnt get header for ht.%d\n",height);
return(merkleroot);
}
int32_t LP_merkleproof(struct iguana_info *coin,char *coinaddr,struct electrum_info *ep,bits256 txid,int32_t height)
{
struct LP_transaction *tx=0; cJSON *merkobj,*merkles,*retjson; bits256 roothash,merkleroot; int32_t m,SPV = 0;
if ( height <= 0 )
return(0);
if ( (tx= LP_transactionfind(coin,txid)) == 0 && strcmp(coinaddr,coin->smartaddr) == 0 )
{
if ( (retjson= electrum_transaction(coin->symbol,ep,&retjson,txid,0)) != 0 )
free_json(retjson);
}
if ( tx != 0 )
{
tx->height = height;
if ( tx->SPV > 0 )
return(tx->SPV);
}
if ( (merkobj= electrum_getmerkle(coin->symbol,ep,&merkobj,txid,height)) != 0 )
{
char str[65],str2[65],str3[65];
SPV = 0;
memset(roothash.bytes,0,sizeof(roothash));
if ( (merkles= jarray(&m,merkobj,"merkle")) != 0 )
{
roothash = validate_merkle(jint(merkobj,"pos"),txid,merkles,m);
merkleroot = LP_merkleroot(coin,ep,height);
if ( bits256_nonz(merkleroot) != 0 )
{
if ( bits256_cmp(merkleroot,roothash) == 0 )
{
SPV = height;
LP_SPV_store(coin,txid,height);
if ( tx != 0 )
{
tx->SPV = height;
if ( tx->serialized != 0 )
{
free(tx->serialized);
tx->serialized = 0;
tx->len = 0;
}
}
//printf("validated MERK %s ht.%d -> %s root.(%s)\n",bits256_str(str,txid),height,jprint(merkobj,0),bits256_str(str2,roothash));
}
else
{
SPV = -1;
printf("ERROR MERK %s ht.%d -> %s root.(%s) vs %s\n",bits256_str(str,txid),height,jprint(merkobj,0),bits256_str(str2,roothash),bits256_str(str3,merkleroot));
}
} else SPV = 0;
}
if ( SPV < 0 )
{
printf("MERKLE DIDNT VERIFY.%s %s ht.%d (%s)\n",coin->symbol,bits256_str(str,txid),height,jprint(merkobj,0));
if ( jobj(merkobj,"error") != 0 )
SPV = 0; // try again later
}
free_json(merkobj);
}
return(SPV);
}
char *LP_unspents_filestr(char *symbol,char *addr)
{
char fname[1024]; long fsize;
sprintf(fname,"%s/UNSPENTS/%s_%s",GLOBAL_DBDIR,symbol,addr), OS_portable_path(fname);
return(OS_filestr(&fsize,fname));
}
void LP_unspents_cache(char *symbol,char *addr,char *arraystr,int32_t updatedflag)
{
char fname[1024]; FILE *fp=0;
sprintf(fname,"%s/UNSPENTS/%s_%s",GLOBAL_DBDIR,symbol,addr), OS_portable_path(fname);
//printf("unspents cache.(%s) for %s %s, updated.%d\n",fname,symbol,addr,updatedflag);
if ( updatedflag == 0 && (fp= fopen(fname,"rb")) == 0 )
updatedflag = 1;
else if ( fp != 0 )
fclose(fp);
if ( updatedflag != 0 && (fp= fopen(fname,"wb")) != 0 )
{
fwrite(arraystr,1,strlen(arraystr),fp);
fclose(fp);
}
}
uint64_t LP_unspents_load(char *symbol,char *addr)
{
char *arraystr; uint64_t balance = 0; int32_t i,n; cJSON *retjson,*item; struct iguana_info *coin;
if ( (coin= LP_coinfind(symbol)) != 0 )
{
if ( (arraystr= LP_unspents_filestr(symbol,addr)) != 0 )
{
if ( (retjson= cJSON_Parse(arraystr)) != 0 )
{
//printf("PROCESS UNSPENTS %s\n",arraystr);
if ( (n= cJSON_GetArraySize(retjson)) > 0 )
{
for (i=0; i<n; i++)
{
item = jitem(retjson,i);
balance += j64bits(item,"value");
}
}
electrum_process_array(coin,coin->electrum,coin->smartaddr,retjson,1);
free_json(retjson);
}
free(arraystr);
}
}
return(balance);
}

139
iguana/exchanges/LP_coins.c

@ -23,9 +23,12 @@ char *portstrs[][3] = { { "BTC", "8332" }, { "KMD", "7771" } };
uint16_t LP_rpcport(char *symbol)
{
int32_t i;
if ( symbol != 0 && symbol[0] != 0 )
{
for (i=0; i<sizeof(portstrs)/sizeof(*portstrs); i++)
if ( strcmp(portstrs[i][0],symbol) == 0 )
return(atoi(portstrs[i][1]));
}
return(0);
}
@ -54,9 +57,9 @@ char *parse_conf_line(char *line,char *field)
return(clonestr(line));
}
void LP_userpassfp(char *symbol,char *username,char *password,FILE *fp)
uint16_t LP_userpassfp(char *symbol,char *username,char *password,FILE *fp)
{
char *rpcuser,*rpcpassword,*str,line[8192];
char *rpcuser,*rpcpassword,*str,line[8192]; uint16_t port = 0;
rpcuser = rpcpassword = 0;
username[0] = password[0] = 0;
while ( fgets(line,sizeof(line),fp) != 0 )
@ -68,6 +71,16 @@ void LP_userpassfp(char *symbol,char *username,char *password,FILE *fp)
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 )
{
str = parse_conf_line(str,(char *)"rpcport");
if ( str != 0 )
{
port = atoi(str);
//printf("RPCPORT.%u\n",port);
free(str);
}
}
}
if ( rpcuser != 0 && rpcpassword != 0 )
{
@ -79,6 +92,7 @@ void LP_userpassfp(char *symbol,char *username,char *password,FILE *fp)
free(rpcuser);
if ( rpcpassword != 0 )
free(rpcpassword);
return(port);
}
void LP_statefname(char *fname,char *symbol,char *assetname,char *str,char *name,char *confpath)
@ -89,14 +103,14 @@ void LP_statefname(char *fname,char *symbol,char *assetname,char *str,char *name
return;
}
sprintf(fname,"%s",LP_getdatadir());
#ifdef WIN32
#ifdef _WIN32
strcat(fname,"\\");
#else
strcat(fname,"/");
#endif
if ( strcmp(symbol,"BTC") == 0 )
{
#ifdef __APPLE__
#if defined(__APPLE__) || defined(NATIVE_WINDOWS)
strcat(fname,"Bitcoin");
#else
strcat(fname,".bitcoin");
@ -120,14 +134,14 @@ void LP_statefname(char *fname,char *symbol,char *assetname,char *str,char *name
}
else
{
#ifdef __APPLE__
#if defined(__APPLE__) || defined(NATIVE_WINDOWS)
strcat(fname,"Komodo");
#else
strcat(fname,".komodo");
#endif
if ( strcmp(symbol,"KMD") != 0 )
{
#ifdef WIN32
#ifdef _WIN32
strcat(fname,"\\");
#else
strcat(fname,"/");
@ -135,7 +149,7 @@ void LP_statefname(char *fname,char *symbol,char *assetname,char *str,char *name
strcat(fname,assetname);
}
}
#ifdef WIN32
#ifdef _WIN32
strcat(fname,"\\");
#else
strcat(fname,"/");
@ -143,9 +157,9 @@ void LP_statefname(char *fname,char *symbol,char *assetname,char *str,char *name
strcat(fname,str);
}
int32_t LP_userpass(char *userpass,char *symbol,char *assetname,char *confroot,char *name,char *confpath)
uint16_t LP_userpass(char *userpass,char *symbol,char *assetname,char *confroot,char *name,char *confpath,uint16_t origport)
{
FILE *fp; char fname[512],username[512],password[512],confname[512];
FILE *fp; char fname[512],username[512],password[512],confname[512]; uint16_t port = 0;
userpass[0] = 0;
sprintf(confname,"%s.conf",confroot);
if ( 0 )
@ -160,42 +174,81 @@ int32_t LP_userpass(char *userpass,char *symbol,char *assetname,char *confroot,c
LP_statefname(fname,symbol,assetname,confname,name,confpath);
if ( (fp= fopen(fname,"rb")) != 0 )
{
LP_userpassfp(symbol,username,password,fp);
if ( (port= LP_userpassfp(symbol,username,password,fp)) == 0 )
port = origport;
sprintf(userpass,"%s:%s",username,password);
fclose(fp);
if ( 0 )
printf("LP_statefname.(%s) <- %s %s %s (%s) (%s)\n",fname,name,symbol,assetname,userpass,confpath);
return((int32_t)strlen(userpass));
return(port);
} else printf("cant open.(%s)\n",fname);
return(-1);
return(0);
}
cJSON *LP_coinjson(struct iguana_info *coin,int32_t showwif)
{
char wifstr[128]; uint8_t tmptype; bits256 checkkey; cJSON *item = cJSON_CreateObject();
struct electrum_info *ep; uint64_t balance; char wifstr[128],ipaddr[64]; uint8_t tmptype; bits256 checkkey; cJSON *item = cJSON_CreateObject();
jaddstr(item,"coin",coin->symbol);
if ( showwif != 0 )
{
bitcoin_priv2wif(coin->wiftaddr,wifstr,LP_mypriv25519,coin->wiftype);
bitcoin_priv2wif(coin->wiftaddr,wifstr,G.LP_privkey,coin->wiftype);
bitcoin_wif2priv(coin->wiftaddr,&tmptype,&checkkey,wifstr);
if ( bits256_cmp(LP_mypriv25519,checkkey) == 0 )
if ( bits256_cmp(G.LP_privkey,checkkey) == 0 )
jaddstr(item,"wif",wifstr);
else jaddstr(item,"wif","error creating wif");
}
jadd(item,"installed",coin->userpass[0] == 0 ? jfalse() : jtrue());
if ( coin->userpass[0] != 0 )
{
jaddnum(item,"height",LP_getheight(coin));
if ( coin->electrum != 0 )
balance = LP_unspents_load(coin->symbol,coin->smartaddr);
else balance = LP_RTsmartbalance(coin);
jaddnum(item,"balance",dstr(balance));
jaddnum(item,"KMDvalue",dstr(LP_KMDvalue(coin,balance)));
}
else
{
jaddnum(item,"height",-1);
jaddnum(item,"balance",0);
}
if ( coin->inactive != 0 )
{
jaddstr(item,"status","inactive");
}
else jaddstr(item,"status","active");
if ( coin->isPoS != 0 )
jaddstr(item,"type","PoS");
if ( (ep= coin->electrum) != 0 )
{
sprintf(ipaddr,"%s:%u",ep->ipaddr,ep->port);
jaddstr(item,"electrum",ipaddr);
}
jaddstr(item,"smartaddress",coin->smartaddr);
jaddstr(item,"rpc",coin->serverport);
jaddnum(item,"pubtype",coin->pubtype);
jaddnum(item,"p2shtype",coin->p2shtype);
jaddnum(item,"wiftype",coin->wiftype);
jaddnum(item,"txfee",coin->txfee);
jaddnum(item,"txfee",strcmp(coin->symbol,"BTC") != 0 ? coin->txfee : LP_txfeecalc(coin,0,0));
return(item);
}
struct iguana_info *LP_conflicts_find(struct iguana_info *refcoin)
{
struct iguana_info *coin=0,*tmp;
if ( refcoin != 0 )
{
HASH_ITER(hh,LP_coins,coin,tmp)
{
if ( coin->inactive != 0 || coin->electrum != 0 || coin == refcoin )
continue;
if ( strcmp(coin->serverport,refcoin->serverport) == 0 )
break;
}
}
return(coin);
}
cJSON *LP_coinsjson(int32_t showwif)
{
struct iguana_info *coin,*tmp; cJSON *array = cJSON_CreateArray();
@ -209,8 +262,10 @@ cJSON *LP_coinsjson(int32_t showwif)
char *LP_getcoin(char *symbol)
{
int32_t numenabled,numdisabled; struct iguana_info *coin,*tmp; cJSON *item=0,*retjson;
numenabled = numdisabled = 0;
retjson = cJSON_CreateObject();
if ( symbol != 0 && symbol[0] != 0 )
{
numenabled = numdisabled = 0;
HASH_ITER(hh,LP_coins,coin,tmp)
{
if ( strcmp(symbol,coin->symbol) == 0 )
@ -225,46 +280,60 @@ char *LP_getcoin(char *symbol)
if ( item == 0 )
item = cJSON_CreateObject();
jadd(retjson,"coin",item);
}
return(jprint(retjson,1));
}
struct iguana_info *LP_coinsearch(char *symbol)
{
struct iguana_info *coin;
struct iguana_info *coin = 0;
if ( symbol != 0 && symbol[0] != 0 )
{
portable_mutex_lock(&LP_coinmutex);
HASH_FIND(hh,LP_coins,symbol,strlen(symbol),coin);
portable_mutex_unlock(&LP_coinmutex);
}
return(coin);
}
struct iguana_info *LP_coinadd(struct iguana_info *cdata)
{
struct iguana_info *coin = calloc(1,sizeof(*coin));
//printf("%s: (%s) (%s)\n",symbol,cdata.serverport,cdata.userpass);
*coin = *cdata;
portable_mutex_init(&coin->txmutex);
portable_mutex_init(&coin->addrmutex);
portable_mutex_lock(&LP_coinmutex);
HASH_ADD_KEYPTR(hh,LP_coins,coin->symbol,strlen(coin->symbol),coin);
portable_mutex_unlock(&LP_coinmutex);
return(coin);
}
int32_t LP_coininit(struct iguana_info *coin,char *symbol,char *name,char *assetname,int32_t isPoS,uint16_t port,uint8_t pubtype,uint8_t p2shtype,uint8_t wiftype,uint64_t txfee,double estimatedrate,int32_t longestchain,uint8_t wiftaddr,uint8_t taddr,uint16_t busport,char *confpath)
uint16_t LP_coininit(struct iguana_info *coin,char *symbol,char *name,char *assetname,int32_t isPoS,uint16_t port,uint8_t pubtype,uint8_t p2shtype,uint8_t wiftype,uint64_t txfee,double estimatedrate,int32_t longestchain,uint8_t wiftaddr,uint8_t taddr,uint16_t busport,char *confpath)
{
static void *ctx;
char *name2;
memset(coin,0,sizeof(*coin));
safecopy(coin->symbol,symbol,sizeof(coin->symbol));
sprintf(coin->serverport,"127.0.0.1:%u",port);
coin->updaterate = (uint32_t)time(NULL);
coin->isPoS = isPoS;
coin->taddr = taddr;
coin->wiftaddr = wiftaddr;
coin->longestchain = longestchain;
coin->txfee = txfee;
if ( (coin->txfee= txfee) > 0 && txfee < LP_MIN_TXFEE )
coin->txfee = LP_MIN_TXFEE;
coin->pubtype = pubtype;
coin->p2shtype = p2shtype;
coin->wiftype = wiftype;
coin->inactive = (uint32_t)time(NULL);
coin->bussock = LP_coinbus(busport);
if ( ctx == 0 )
ctx = bitcoin_ctx();
coin->ctx = ctx;
if ( assetname != 0 && strcmp(name,assetname) == 0 )
{
//printf("%s is assetchain\n",symbol);
coin->isassetchain = 1;
}
if ( strcmp(symbol,"KMD") == 0 || (assetname != 0 && assetname[0] != 0) )
name2 = 0;
else name2 = name;
@ -273,7 +342,18 @@ int32_t LP_coininit(struct iguana_info *coin,char *symbol,char *name,char *asset
coin->noimportprivkey_flag = 1;
printf("truncate importprivkey for %s\n",symbol);
}
return(LP_userpass(coin->userpass,symbol,assetname,name,name2,confpath));
#ifndef FROM_JS
port = LP_userpass(coin->userpass,symbol,assetname,name,name2,confpath,port);
#endif
sprintf(coin->serverport,"127.0.0.1:%u",port);
if ( strcmp(symbol,"KMD") == 0 || coin->isassetchain != 0 || taddr != 0 )
coin->zcash = LP_IS_ZCASHPROTOCOL;
else if ( strcmp(symbol,"BCH") == 0 )
{
coin->zcash = LP_IS_BITCOINCASH;
//printf("set coin.%s <- LP_IS_BITCOINCASH %d\n",symbol,coin->zcash);
}
return(port);
}
int32_t LP_isdisabled(char *base,char *rel)
@ -289,6 +369,8 @@ int32_t LP_isdisabled(char *base,char *rel)
struct iguana_info *LP_coinfind(char *symbol)
{
struct iguana_info *coin,cdata; int32_t isinactive,isPoS,longestchain = 1; uint16_t port,busport; uint64_t txfee; double estimatedrate; uint8_t pubtype,p2shtype,wiftype; char *name,*assetname;
if ( symbol == 0 || symbol[0] == 0 )
return(0);
if ( (coin= LP_coinsearch(symbol)) != 0 )
return(coin);
if ( (port= LP_rpcport(symbol)) == 0 )
@ -314,13 +396,16 @@ struct iguana_info *LP_coinfind(char *symbol)
else if ( strcmp(symbol,"KMD") == 0 )
name = "komodo";
else return(0);
isinactive = LP_coininit(&cdata,symbol,name,assetname,isPoS,port,pubtype,p2shtype,wiftype,txfee,estimatedrate,longestchain,0,0,busport,0) < 0;
port = LP_coininit(&cdata,symbol,name,assetname,isPoS,port,pubtype,p2shtype,wiftype,txfee,estimatedrate,longestchain,0,0,busport,0);
if ( port == 0 )
isinactive = 1;
else isinactive = 0;
if ( (coin= LP_coinadd(&cdata)) != 0 )
{
coin->inactive = isinactive * (uint32_t)time(NULL);
if ( strcmp(symbol,"KMD") == 0 )
/*if ( strcmp(symbol,"KMD") == 0 )
coin->inactive = 0;
else if ( strcmp(symbol,"BTC") == 0 )
else*/ if ( strcmp(symbol,"BTC") == 0 )
{
coin->inactive = (uint32_t)time(NULL) * !IAMLP;
printf("BTC inactive.%u\n",coin->inactive);
@ -374,7 +459,7 @@ struct iguana_info *LP_coincreate(cJSON *item)
}
} else coin->inactive = 0;
}
if ( coin != 0 && coin->inactive != 0 )
if ( 0 && coin != 0 && coin->inactive != 0 )
printf("LPnode.%d %s inactive.%u %p vs %p\n",IAMLP,coin->symbol,coin->inactive,assetname,name);
return(0);
}

513
iguana/exchanges/LP_commands.c

@ -25,18 +25,21 @@ char *LP_numutxos()
{
jaddstr(retjson,"ipaddr",LP_mypeer->ipaddr);
jaddnum(retjson,"port",LP_mypeer->port);
jaddnum(retjson,"numutxos",LP_mypeer->numutxos);
//jaddnum(retjson,"numutxos",LP_mypeer->numutxos);
jaddnum(retjson,"numpeers",LP_mypeer->numpeers);
jaddnum(retjson,"session",LP_sessionid);
jaddnum(retjson,"session",G.LP_sessionid);
} else jaddstr(retjson,"error","client node");
return(jprint(retjson,1));
}
char *stats_JSON(void *ctx,char *myipaddr,int32_t pubsock,cJSON *argjson,char *remoteaddr,uint16_t port) // from rpc port
{
char *method,*ipaddr,*userpass,*base,*rel,*coin,*retstr = 0; uint16_t argport=0,pushport,subport; int32_t changed,otherpeers,othernumutxos,flag = 0; struct LP_peerinfo *peer; cJSON *retjson,*reqjson = 0; struct iguana_info *ptr;
//printf("stats_JSON(%s)\n",jprint(argjson,0));
if ( (ipaddr= jstr(argjson,"ipaddr")) != 0 && (argport= juint(argjson,"port")) != 0 )
char *method,*userpass,*base,*rel,*coin,*retstr = 0; int32_t changed,flag = 0; cJSON *retjson,*reqjson = 0; struct iguana_info *ptr;
method = jstr(argjson,"method");
if ( method != 0 && (strcmp(method,"addr_unspents") == 0 || strcmp(method,"uitem") == 0 || strcmp(method,"postutxos") == 0) )
return(0);
//printf("stats_JSON %s\n",method);
/*if ( (ipaddr= jstr(argjson,"ipaddr")) != 0 && (argport= juint(argjson,"port")) != 0 && (method == 0 || strcmp(method,"electrum") != 0) )
{
if ( strcmp(ipaddr,"127.0.0.1") != 0 && argport >= 1000 )
{
@ -49,33 +52,30 @@ char *stats_JSON(void *ctx,char *myipaddr,int32_t pubsock,cJSON *argjson,char *r
{
if ( 0 && (otherpeers= jint(argjson,"numpeers")) > peer->numpeers )
peer->numpeers = otherpeers;
if ( 0 && (othernumutxos= jint(argjson,"numutxos")) > peer->numutxos )
{
printf("change.(%s) numutxos.%d -> %d mynumutxos.%d\n",peer->ipaddr,peer->numutxos,othernumutxos,LP_mypeer != 0 ? LP_mypeer->numutxos:0);
peer->numutxos = othernumutxos;
}
if ( peer->sessionid == 0 )
peer->sessionid = juint(argjson,"session");
//printf("peer.(%s) found (%d %d) (%d %d) (%s)\n",peer->ipaddr,peer->numpeers,peer->numutxos,otherpeers,othernumutxos,jprint(argjson,0));
} else LP_addpeer(LP_mypeer,LP_mypubsock,ipaddr,argport,pushport,subport,jint(argjson,"numpeers"),jint(argjson,"numutxos"),juint(argjson,"session"));
}
}
if ( (method= jstr(argjson,"method")) == 0 )
}*/
if ( method == 0 )
{
if ( is_cJSON_Array(argjson) != 0 )
printf("RAWARRAY command? %s\n",jprint(argjson,0));
if ( flag == 0 || jobj(argjson,"result") != 0 )
printf("stats_JSON no method: (%s) (%s:%u)\n",jprint(argjson,0),ipaddr,argport);
printf("stats_JSON no method: (%s)\n",jprint(argjson,0));
return(0);
}
/*if ( strcmp(method,"hello") == 0 )
if ( strcmp(method,"hello") == 0 )
{
//printf("got hello from %s:%u\n",ipaddr!=0?ipaddr:"",argport);
return(0);
return(clonestr("{\"result\":\"success\",\"status\":\"got hello\"}"));
}
else*/ if ( strcmp(method,"sendmessage") == 0 && jobj(argjson,"userpass") == 0 )
/*else if ( strcmp(method,"sendmessage") == 0 && jobj(argjson,"userpass") == 0 )
{
static char *laststr;
char *newstr; bits256 pubkey = jbits256(argjson,"pubkey");
if ( bits256_nonz(pubkey) == 0 || bits256_cmp(pubkey,LP_mypub25519) == 0 )
if ( bits256_nonz(pubkey) == 0 || bits256_cmp(pubkey,G.LP_mypub25519) == 0 )
{
newstr = jprint(argjson,0);
if ( laststr == 0 || strcmp(laststr,newstr) != 0 )
@ -88,64 +88,106 @@ char *stats_JSON(void *ctx,char *myipaddr,int32_t pubsock,cJSON *argjson,char *r
retstr = clonestr(laststr);
}
} else retstr = clonestr("{\"error\":\"duplicate message\"}");
}
}*/
//else if ( strcmp(method,"nn_tests") == 0 )
// return(clonestr("{\"result\":\"success\"}"));
else if ( strcmp(method,"help") == 0 )
return(clonestr("{\"result\":\" \
available localhost RPC commands:\n \
pricearray(base, rel, firsttime=0, lasttime=-1, timescale=60) -> [timestamp, avebid, aveask, highbid, lowask]\n\
available localhost RPC commands: \n \
pricearray(base, rel, starttime=0, endtime=-1, timescale=60) -> [timestamp, avebid, aveask, highbid, lowask]\n\
setprice(base, rel, price)\n\
autoprice(base, rel, price, margin, type)\n\
autoprice(base, rel, fixed, minprice, margin, refbase, refrel, factor, offset)*\n\
goal(coin=*, val=<autocalc>)\n\
myprice(base, rel)\n\
enable(coin)\n\
disable(coin)\n\
inventory(coin)\n\
notarizations(coin)\n\
parselog()\n\
statsdisp(starttime=0, endtime=0, gui="", pubkey="")\n\
getrawtransaction(coin, txid)\n\
inventory(coin, reset=0, [passphrase=])\n\
bestfit(rel, relvolume)\n\
ordermatch(base, txfee=0, rel, desttxfee=0, price, relvolume=0, txid, vout, feetxid, feevout, duration=3600)\n\
trade(price, timeout=10, duration=3600, <quotejson returned from ordermatch>)\n\
autotrade(base, rel, price, relvolume, timeout=10, duration=3600)\n\
lastnonce()\n\
buy(base, rel, price, relvolume, timeout=10, duration=3600, nonce, destpubkey="")\n\
sell(base, rel, price, basevolume, timeout=10, duration=3600, nonce, destpubkey="")\n\
withdraw(coin, outputs[])\n\
sendrawtransaction(coin, signedtx)\n\
swapstatus()\n\
swapstatus(coin, limit=10)\n\
swapstatus(base, rel, limit=10)\n\
swapstatus(requestid, quoteid)\n\
recentswaps(limit=3)\n\
public API:\n \
getcoins()\n\
getcoin(coin)\n\
portfolio()\n\
getpeers()\n\
getutxos()\n\
getutxos(coin, lastn)\n\
passphrase(passphrase, gui)\n\
listunspent(coin, address)\n\
setconfirms(coin, numconfirms, maxconfirms=6)\n\
trust(pubkey, trust) # positive to trust, 0 for normal, negative to blacklist\n\
balance(coin, address)\n\
orderbook(base, rel, duration=3600)\n\
getprices(base, rel)\n\
sendmessage(base=coin, rel="", pubkey=zero, <argjson method2>)\n\
getmessages(firsti=0, num=100)\n\
clearmessages(firsti=0, num=100)\n\
//sendmessage(base=coin, rel="", pubkey=zero, <argjson method2>)\n\
//getmessages(firsti=0, num=100)\n\
//deletemessages(firsti=0, num=100)\n\
secretaddresses(prefix='secretaddress', passphrase, num=10, pubtype=60, taddr=0)\n\
electrum(coin, ipaddr, port)\n\
snapshot(coin, height)\n\
snapshot_balance(coin, height, addresses[])\n\
dividends(coin, height, <args>)\n\
stop()\n\
bot_list()\n\
bot_statuslist()\n\
bot_buy(base, rel, maxprice, relvolume) -> botid\n\
bot_sell(base, rel, minprice, basevolume) -> botid\n\
bot_settings(botid, newprice, newvolume)\n\
bot_status(botid)\n\
bot_stop(botid)\n\
bot_pause(botid)\n\
bot_resume(botid)\n\
\"}"));
//sell(base, rel, price, basevolume, timeout=10, duration=3600)\n\
base = jstr(argjson,"base");
rel = jstr(argjson,"rel");
if ( USERPASS[0] != 0 && strcmp(remoteaddr,"127.0.0.1") == 0 && port != 0 )
if ( (base= jstr(argjson,"base")) == 0 )
base = "";
if ((rel= jstr(argjson,"rel")) == 0 )
rel = "";
if ( (coin= jstr(argjson,"coin")) == 0 )
coin = "";
if ( G.USERPASS[0] != 0 && strcmp(remoteaddr,"127.0.0.1") == 0 && port != 0 ) // protected localhost
{
if ( USERPASS_COUNTER == 0 )
if ( G.USERPASS_COUNTER == 0 )
{
USERPASS_COUNTER = 1;
G.USERPASS_COUNTER = 1;
retjson = cJSON_CreateObject();
jaddstr(retjson,"userpass",USERPASS);
jaddbits256(retjson,"mypubkey",LP_mypub25519);
jaddstr(retjson,"userpass",G.USERPASS);
jaddbits256(retjson,"mypubkey",G.LP_mypub25519);
jadd(retjson,"coins",LP_coinsjson(LP_showwif));
return(jprint(retjson,1));
}
if ( (userpass= jstr(argjson,"userpass")) == 0 || strcmp(userpass,USERPASS) != 0 )
return(clonestr("{\"error\":\"authentication error\"}"));
if ( strcmp(method,"passphrase") != 0 && ((userpass= jstr(argjson,"userpass")) == 0 || strcmp(userpass,G.USERPASS) != 0) )
return(clonestr("{\"error\":\"authentication error you need to make sure userpass is set\"}"));
jdelete(argjson,"userpass");
if ( strcmp(method,"sendmessage") == 0 )
if ( strcmp(method,"passphrase") == 0 )
{
G.USERPASS_COUNTER = 1;
if ( LP_passphrase_init(jstr(argjson,"passphrase"),jstr(argjson,"gui")) < 0 )
return(clonestr("{\"error\":\"couldnt change passphrase\"}"));
{
retjson = cJSON_CreateObject();
jaddstr(retjson,"result","success");
jaddstr(retjson,"userpass",G.USERPASS);
jaddbits256(retjson,"mypubkey",G.LP_mypub25519);
return(jprint(retjson,1));
}
}
/*else if ( strcmp(method,"sendmessage") == 0 )
{
if ( jobj(argjson,"method2") == 0 )
{
printf("broadcast message\n");
LP_broadcast_message(LP_mypubsock,base!=0?base:jstr(argjson,"coin"),rel,jbits256(argjson,"pubkey"),jprint(argjson,0));
LP_broadcast_message(LP_mypubsock,base!=0?base:coin,rel,jbits256(argjson,"pubkey"),jprint(argjson,0));
}
return(clonestr("{\"result\":\"success\"}"));
}
@ -159,38 +201,112 @@ dividends(coin, height, <args>)\n\
{
LP_deletemessages(jint(argjson,"firsti"),jint(argjson,"num"));
return(clonestr("{\"result\":\"success\"}"));
}*/
else if ( strcmp(method,"recentswaps") == 0 )
{
return(LP_recent_swaps(jint(argjson,"limit")));
}
else if ( strcmp(method,"stop") == 0 )
{
printf("DEBUG stop\n");
exit(0);
}
else if ( strcmp(method,"millis") == 0 )
{
LP_millistats_update(0);
return(clonestr("{\"result\":\"success\"}"));
}
else if ( strcmp(method,"getprices") == 0 )
return(LP_prices());
else if ( strcmp(method,"getpeers") == 0 )
return(LP_peers());
else if ( strcmp(method,"getcoins") == 0 )
return(jprint(LP_coinsjson(0),1));
else if ( strcmp(method,"notarizations") == 0 )
{
int32_t height,bestheight;
if ( (ptr= LP_coinsearch(coin)) != 0 )
{
height = LP_notarization_latest(&bestheight,ptr);
retjson = cJSON_CreateObject();
jaddstr(retjson,"result","success");
jaddstr(retjson,"coin",coin);
jaddnum(retjson,"lastnotarization",height);
jaddnum(retjson,"bestheight",bestheight);
return(jprint(retjson,1));
} else return(clonestr("{\"error\":\"cant find coin\"}"));
}
else if ( strcmp(method,"portfolio") == 0 )
{
return(LP_portfolio());
}
if ( base != 0 && rel != 0 )
else if ( strcmp(method,"parselog") == 0 )
{
bits256 zero; int32_t n = LP_statslog_parse();
memset(zero.bytes,0,sizeof(zero));
return(LP_statslog_disp(n,2000000000,2000000000,"",zero));
}
else if ( strcmp(method,"statsdisp") == 0 )
{
int32_t n = LP_statslog_parse();
return(LP_statslog_disp(n,juint(argjson,"starttime"),juint(argjson,"endtime"),jstr(argjson,"gui"),jbits256(argjson,"pubkey")));
}
else if ( strcmp(method,"secretaddresses") == 0 )
{
uint8_t taddr,pubtype;
pubtype = (jobj(argjson,"pubtype") == 0) ? 60 : juint(argjson,"pubtype");
taddr = (jobj(argjson,"taddr") == 0) ? 0 : juint(argjson,"taddr");
return(LP_secretaddresses(ctx,jstr(argjson,"prefix"),jstr(argjson,"passphrase"),juint(argjson,"num"),taddr,pubtype));
}
else if ( strcmp(method,"swapstatus") == 0 )
{
uint32_t requestid,quoteid;
if ( (requestid= juint(argjson,"requestid")) != 0 && (quoteid= juint(argjson,"quoteid")) != 0 )
return(basilisk_swapentry(requestid,quoteid));
else if ( coin[0] != 0 )
return(basilisk_swapentries(coin,0,jint(argjson,"limit")));
else if ( base[0] != 0 && rel[0] != 0 )
return(basilisk_swapentries(base,rel,jint(argjson,"limit")));
else return(basilisk_swaplist(0,0));
}
else if ( (retstr= LP_istradebots_command(ctx,pubsock,method,argjson)) != 0 )
return(retstr);
if ( base[0] != 0 && rel[0] != 0 )
{
double price,bid,ask;
if ( strcmp(method,"autoprice") == 0 )
{
if ( LP_autoprice(base,rel,argjson) < 0 )
return(clonestr("{\"error\":\"couldnt set autoprice\"}"));
else return(clonestr("{\"result\":\"success\"}"));
}
if ( IAMLP == 0 && LP_isdisabled(base,rel) != 0 )
return(clonestr("{\"error\":\"at least one of coins disabled\"}"));
price = jdouble(argjson,"price");
if ( strcmp(method,"setprice") == 0 )
{
if ( price > SMALLVAL )
{
if ( LP_mypriceset(&changed,base,rel,price) < 0 )
return(clonestr("{\"error\":\"couldnt set price\"}"));
//else if ( LP_mypriceset(&changed,rel,base,1./price) < 0 )
// return(clonestr("{\"error\":\"couldnt set price\"}"));
else return(LP_pricepings(ctx,myipaddr,LP_mypubsock,base,rel,price * LP_profitratio));
} else return(clonestr("{\"error\":\"no price\"}"));
}
else if ( strcmp(method,"autoprice") == 0 )
{
if ( LP_autoprice(base,rel,price,jdouble(argjson,"margin"),jstr(argjson,"type")) < 0 )
return(clonestr("{\"error\":\"couldnt set autoprice\"}"));
else return(clonestr("{\"result\":\"success\"}"));
}
else if ( strcmp(method,"pricearray") == 0 )
{
return(jprint(LP_pricearray(base,rel,juint(argjson,"firsttime"),juint(argjson,"lasttime"),jint(argjson,"timescale")),1));
uint32_t firsttime;
if ( base[0] != 0 && rel[0] != 0 )
{
if ( (firsttime= juint(argjson,"firsttime")) < time(NULL)-30*24*3600 )
firsttime = (uint32_t)(time(NULL)-30*24*3600);
return(jprint(LP_pricearray(base,rel,firsttime,juint(argjson,"lasttime"),jint(argjson,"timescale")),1));
} else return(clonestr("{\"error\":\"pricearray needs base and rel\"}"));
}
/*else if ( strcmp(method,"pricearray") == 0 )
{
return(jprint(LP_pricearray(base,rel,juint(argjson,"starttime"),juint(argjson,"endtime"),jint(argjson,"timescale")),1));
}*/
else if ( strcmp(method,"orderbook") == 0 )
return(LP_orderbook(base,rel,jint(argjson,"duration")));
else if ( strcmp(method,"myprice") == 0 )
{
if ( LP_myprice(&bid,&ask,base,rel) > SMALLVAL )
@ -203,49 +319,147 @@ dividends(coin, height, <args>)\n\
return(jprint(retjson,1));
} else return(clonestr("{\"error\":\"no price set\"}"));
}
else if ( strcmp(method,"ordermatch") == 0 )
else if ( strcmp(method,"buy") == 0 )
{
//*
if ( price > SMALLVAL )
return(LP_ordermatch(base,j64bits(argjson,"txfee"),price,jdouble(argjson,"relvolume"),rel,jbits256(argjson,"txid"),jint(argjson,"vout"),jbits256(argjson,"feetxid"),jint(argjson,"feevout"),j64bits(argjson,"desttxfee"),jint(argjson,"duration")));
else return(clonestr("{\"error\":\"no price set\"}"));
}
else if ( strcmp(method,"trade") == 0 )
{
struct LP_quoteinfo Q;
if ( price > SMALLVAL || jobj(argjson,"quote") != 0 )
{
LP_quoteparse(&Q,jobj(argjson,"quote"));
return(LP_trade(ctx,myipaddr,pubsock,&Q,price,jint(argjson,"timeout"),jint(argjson,"duration")));
} else return(clonestr("{\"error\":\"no price set or no quote object\"}"));
return(LP_autobuy(ctx,myipaddr,pubsock,base,rel,price,jdouble(argjson,"relvolume"),jint(argjson,"timeout"),jint(argjson,"duration"),jstr(argjson,"gui"),juint(argjson,"nonce"),jbits256(argjson,"destpubkey"),0));
} else return(clonestr("{\"error\":\"no price set\"}"));
}
else if ( strcmp(method,"autotrade") == 0 )
else if ( strcmp(method,"sell") == 0 )
{
//*
if ( price > SMALLVAL )
{
return(LP_autotrade(ctx,myipaddr,pubsock,base,rel,price,jdouble(argjson,"relvolume"),jint(argjson,"timeout"),jint(argjson,"duration")));
return(LP_autobuy(ctx,myipaddr,pubsock,rel,base,1./price,jdouble(argjson,"basevolume"),jint(argjson,"timeout"),jint(argjson,"duration"),jstr(argjson,"gui"),juint(argjson,"nonce"),jbits256(argjson,"destpubkey"),0));
} else return(clonestr("{\"error\":\"no price set\"}"));
}
}
else if ( rel != 0 && strcmp(method,"bestfit") == 0 )
else if ( rel[0] != 0 && strcmp(method,"bestfit") == 0 )
{
double relvolume;
if ( (relvolume= jdouble(argjson,"relvolume")) > SMALLVAL )
return(LP_bestfit(rel,relvolume));
else return(clonestr("{\"error\":\"no relvolume set\"}"));
}
else if ( (coin= jstr(argjson,"coin")) != 0 )
else if ( coin[0] != 0 )
{
if ( strcmp(method,"enable") == 0 )
{
//*
if ( (ptr= LP_coinsearch(coin)) != 0 )
{
if ( ptr->userpass[0] == 0 )
{
cJSON *retjson = cJSON_CreateObject();
jaddstr(retjson,"error","couldnt find coin locally installed");
jaddstr(retjson,"coin",coin);
return(jprint(retjson,1));
}
if ( LP_conflicts_find(ptr) == 0 )
{
ptr->inactive = 0;
return(jprint(LP_coinsjson(0),1));
cJSON *array;
if ( ptr->smartaddr[0] != 0 )
LP_unspents_load(coin,ptr->smartaddr);
if ( LP_getheight(ptr) <= 0 )
{
ptr->inactive = (uint32_t)time(NULL);
return(clonestr("{\"error\":\"coin cant be activated till synced\"}"));
} else LP_unspents_load(coin,ptr->smartaddr);
array = cJSON_CreateArray();
jaddi(array,LP_coinjson(ptr,0));
return(jprint(array,1));
} else return(clonestr("{\"error\":\"coin port conflicts with existing coin\"}"));
} else return(clonestr("{\"error\":\"couldnt find coin\"}"));
}
else if ( strcmp(method,"disable") == 0 )
{
//*
if ( (ptr= LP_coinsearch(coin)) != 0 )
{
ptr->inactive = (uint32_t)time(NULL);
return(jprint(LP_coinsjson(0),1));
cJSON *array = cJSON_CreateArray();
jaddi(array,LP_coinjson(ptr,0));
return(jprint(array,1));
} else return(clonestr("{\"error\":\"couldnt find coin\"}"));
}
else if ( strcmp(method,"listunspent") == 0 )
{
if ( (ptr= LP_coinsearch(coin)) != 0 )
{
char *coinaddr;
if ( (coinaddr= jstr(argjson,"address")) != 0 )
{
if ( coinaddr[0] != 0 )
{
LP_address(ptr,coinaddr);
if ( strcmp(coinaddr,ptr->smartaddr) == 0 && bits256_nonz(G.LP_privkey) != 0 )
{
LP_listunspent_issue(coin,coinaddr,2);
LP_privkey_init(-1,ptr,G.LP_privkey,G.LP_mypub25519);
//LP_smartutxos_push(ptr);
if ( ptr->electrum != 0 )
return(LP_unspents_filestr(coin,ptr->smartaddr));
else return(jprint(LP_address_utxos(ptr,coinaddr,1),1));
}
else
{
return(clonestr("{\"error\":\"not my address\"}"));
}
}
return(jprint(LP_address_utxos(ptr,coinaddr,1),1));
} else return(clonestr("{\"error\":\"no address specified\"}"));
} else return(clonestr("{\"error\":\"cant find coind\"}"));
}
else if ( strcmp(method,"balance") == 0 )
{
if ( (ptr= LP_coinsearch(coin)) != 0 )
return(jprint(LP_address_balance(ptr,jstr(argjson,"address"),1),1));
else return(clonestr("{\"error\":\"cant find coind\"}"));
}
else if ( strcmp(method,"electrum") == 0 )
{
if ( (ptr= LP_coinsearch(coin)) != 0 )
{
ptr->inactive = 0;
return(jprint(LP_electrumserver(ptr,jstr(argjson,"ipaddr"),juint(argjson,"port")),1));
} else return(clonestr("{\"error\":\"cant find coind\"}"));
}
else if ( strcmp(method,"sendrawtransaction") == 0 )
{
return(LP_sendrawtransaction(coin,jstr(argjson,"signedtx")));
}
else if ( strcmp(method,"getrawtransaction") == 0 )
{
return(jprint(LP_gettx(coin,jbits256(argjson,"txid")),1));
}
else if ( strcmp(method,"withdraw") == 0 )
{
if ( (ptr= LP_coinsearch(coin)) != 0 )
{
if ( jobj(argjson,"outputs") == 0 )
return(clonestr("{\"error\":\"withdraw needs to have outputs\"}"));
else return(LP_withdraw(ptr,argjson));
}
return(clonestr("{\"error\":\"cant find coind\"}"));
}
else if ( strcmp(method,"setconfirms") == 0 )
{
int32_t n;
n = jint(argjson,"numconfirms");
if ( n < 0 )
return(clonestr("{\"error\":\"illegal numconfirms\"}"));
if ( (ptr= LP_coinsearch(coin)) != 0 )
{
ptr->userconfirms = n;
if ( (n= jint(argjson,"maxconfirms")) > 0 )
ptr->maxconfirms = n;
if ( ptr->maxconfirms > 0 && ptr->userconfirms > ptr->maxconfirms )
ptr->userconfirms = ptr->maxconfirms;
return(clonestr("{\"result\":\"success\"}"));
} else return(clonestr("{\"error\":\"cant find coind\"}"));
}
else if ( strcmp(method,"snapshot") == 0 )
{
@ -259,6 +473,12 @@ dividends(coin, height, <args>)\n\
return(LP_dividends(ptr,juint(argjson,"height"),argjson));
else return(clonestr("{\"error\":\"cant find coind\"}"));
}
else if ( strcmp(method,"snapshot_balance") == 0 )
{
if ( (ptr= LP_coinsearch(coin)) != 0 )
return(LP_snapshot_balance(ptr,juint(argjson,"height"),argjson));
else return(clonestr("{\"error\":\"cant find coind\"}"));
}
if ( LP_isdisabled(coin,0) != 0 )
return(clonestr("{\"error\":\"coin is disabled\"}"));
if ( strcmp(method,"inventory") == 0 )
@ -266,16 +486,23 @@ dividends(coin, height, <args>)\n\
struct iguana_info *ptr;
if ( (ptr= LP_coinfind(coin)) != 0 )
{
//privkey = LP_privkeycalc(ctx,pubkey33,&pubkey,ptr,"",USERPASS_WIFSTR);
//LP_utxopurge(0);
if ( bits256_nonz(LP_mypriv25519) != 0 )
LP_privkey_init(-1,ptr,LP_mypriv25519,LP_mypub25519);
LP_address(ptr,ptr->smartaddr);
if ( jint(argjson,"reset") != 0 )
{
ptr->privkeydepth = 0;
LP_address_utxo_reset(ptr);
LP_passphrase_init(jstr(argjson,"passphrase"),G.gui);
}
if ( bits256_nonz(G.LP_privkey) != 0 )
LP_privkey_init(-1,ptr,G.LP_privkey,G.LP_mypub25519);
else printf("no LP_privkey\n");
retjson = cJSON_CreateObject();
jaddstr(retjson,"result","success");
jaddstr(retjson,"coin",coin);
jaddnum(retjson,"timestamp",time(NULL));
jadd(retjson,"alice",LP_inventory(coin,0));
jadd(retjson,"bob",LP_inventory(coin,1));
jadd(retjson,"alice",LP_inventory(coin));
//jadd(retjson,"bob",LP_inventory(coin,1));
LP_smartutxos_push(ptr);
return(jprint(retjson,1));
}
}
@ -286,18 +513,20 @@ dividends(coin, height, <args>)\n\
}
else if ( strcmp(method,"goal") == 0 )
return(LP_portfolio_goal("*",100.));
else if ( strcmp(method,"swapstatus") == 0 )
else if ( strcmp(method,"lastnonce") == 0 )
{
uint32_t requestid,quoteid;
if ( (requestid= juint(argjson,"requestid")) != 0 && (quoteid= juint(argjson,"quoteid")) != 0 )
return(basilisk_swapentry(requestid,quoteid));
else return(basilisk_swaplist());
cJSON *retjson = cJSON_CreateObject();
jaddstr(retjson,"result","success");
jaddnum(retjson,"lastnonce",LP_lastnonce);
return(jprint(retjson,1));
}
else if ( strcmp(method,"myprices") == 0 )
return(LP_myprices());
else if ( strcmp(method,"trust") == 0 )
return(LP_pubkey_trustset(jbits256(argjson,"pubkey"),jint(argjson,"trust")));
}
else if ( strcmp(method,"trusted") == 0 )
return(LP_pubkey_trusted());
} // end of protected localhost commands
if ( IAMLP == 0 )
{
if ( (reqjson= LP_dereference(argjson,"broadcast")) != 0 )
@ -311,75 +540,81 @@ dividends(coin, height, <args>)\n\
argjson = reqjson;
}
}
if ( IAMLP == 0 && LP_isdisabled(base,rel) != 0 )
return(clonestr("{\"result\":\"at least one of coins disabled\"}"));
else if ( IAMLP == 0 && LP_isdisabled(jstr(argjson,"coin"),0) != 0 )
retstr = clonestr("{\"result\":\"coin is disabled\"}");
else if ( strcmp(method,"reserved") == 0 )
retstr = LP_quotereceived(argjson);
else if ( strcmp(method,"connected") == 0 )
retstr = LP_connectedalice(argjson);
else if ( strcmp(method,"checktxid") == 0 )
retstr = LP_spentcheck(argjson);
else if ( strcmp(method,"getcoins") == 0 )
return(jprint(LP_coinsjson(0),1));
else if ( strcmp(method,"numutxos") == 0 )
return(LP_numutxos());
else if ( strcmp(method,"postprice") == 0 )
retstr = LP_postedprice(argjson);
else if ( strcmp(method,"encrypted") == 0 )
retstr = clonestr("{\"result\":\"success\"}");
else if ( strcmp(method,"getprices") == 0 )
return(LP_prices());
else if ( strcmp(method,"orderbook") == 0 )
return(LP_orderbook(base,rel,jint(argjson,"duration")));
else if ( strcmp(method,"registerall") == 0 )
return(clonestr("{\"error\":\"you are running an obsolete version, update\"}"));
else if ( strcmp(method,"forward") == 0 )
return(clonestr("{\"error\":\"you are running an obsolete version, update\"}"));
else if ( strcmp(method,"keepalive") == 0 )
return(clonestr("{\"error\":\"you are running an obsolete version, update\"}"));
// received response
if ( strcmp(method,"postprice") == 0 )
return(LP_postprice_recv(argjson));
else if ( strcmp(method,"postutxos") == 0 )
return(LP_postutxos_recv(argjson));
else if ( strcmp(method,"uitem") == 0 )
return(LP_uitem_recv(argjson));
else if ( strcmp(method,"notify") == 0 )
return(LP_notify_recv(argjson));
else if ( strcmp(method,"getpeers") == 0 )
return(LP_peers());
else if ( strcmp(method,"getutxos") == 0 )
return(LP_utxos(1,LP_mypeer,jstr(argjson,"coin"),jint(argjson,"lastn")));
else if ( strcmp(method,"utxo") == 0 )
retstr = clonestr("{\"error\":\"deprecated\"}");
/*else if ( strcmp(method,"getpeers") == 0 )
{
char *tmpstr;
if ( (tmpstr= jstr(argjson,"LPnode")) != 0 )
LP_addpeer(LP_mypeer,LP_mypubsock,tmpstr,RPC_port,RPC_port+10,RPC_port+20,1,G.LP_sessionid);
if ( IAMLP != 0 )
{
if ( LP_utxoaddjson(1,LP_mypubsock,argjson) != 0 )
retstr = clonestr("{\"result\":\"success\",\"utxo\":\"received\"}");
else retstr = clonestr("{\"result\":\"couldnt add utxo\"}");
printf("send peers list %s\n",LP_peers());
bits256 zero; memset(zero.bytes,0,sizeof(zero));
LP_reserved_msg(0,"","",zero,LP_peers());
}
else
retstr = clonestr("{\"result\":\"success\"}");
}*/
// end received response
else if ( strcmp(method,"tradestatus") == 0 )
{
if ( IAMLP != 0 )
LP_tradecommand_log(argjson);
printf("GOT TRADESTATUS! %s\n",jprint(argjson,0));
retstr = clonestr("{\"result\":\"success\"}");
}
else if ( strcmp(method,"wantnotify") == 0 )
{
if ( strcmp(method,"register") == 0 )
return(clonestr("{\"error\":\"you are running an obsolete version, update\"}"));
else if ( strcmp(method,"lookup") == 0 )
return(clonestr("{\"error\":\"you are running an obsolete version, update\"}"));
if ( strcmp(method,"broadcast") == 0 )
bits256 pub; static uint32_t lastnotify;
pub = jbits256(argjson,"pub");
//char str[65]; printf("got wantnotify.(%s) vs %s\n",jprint(argjson,0),bits256_str(str,G.LP_mypub25519));
if ( bits256_cmp(pub,G.LP_mypub25519) == 0 && time(NULL) > lastnotify+60 )
{
bits256 zero; char *cipherstr; int32_t cipherlen; uint8_t cipher[LP_ENCRYPTED_MAXSIZE];
if ( (reqjson= LP_dereference(argjson,"broadcast")) != 0 )
lastnotify = (uint32_t)time(NULL);
//printf("wantnotify for me!\n");
LP_notify_pubkeys(ctx,LP_mypubsock);
}
retstr = clonestr("{\"result\":\"success\"}");
}
else if ( strcmp(method,"addr_unspents") == 0 )
{
if ( (cipherstr= jstr(reqjson,"cipher")) != 0 )
//printf("GOT ADDR_UNSPENTS %s %s\n",jstr(argjson,"coin"),jstr(argjson,"address"));
if ( (ptr= LP_coinsearch(coin)) != 0 )
{
cipherlen = (int32_t)strlen(cipherstr) >> 1;
if ( cipherlen <= sizeof(cipher) )
char *coinaddr;
if ( (coinaddr= jstr(argjson,"address")) != 0 )
{
decode_hex(cipher,cipherlen,cipherstr);
LP_queuesend(calc_crc32(0,&cipher[2],cipherlen-2),LP_mypubsock,base,rel,cipher,cipherlen);
} else retstr = clonestr("{\"error\":\"cipher too big\"}");
}
else
if ( coinaddr[0] != 0 )
{
memset(zero.bytes,0,sizeof(zero));
LP_broadcast_message(LP_mypubsock,base!=0?base:jstr(argjson,"coin"),rel,zero,jprint(reqjson,0));
LP_address(ptr,coinaddr);
if ( strcmp(coinaddr,ptr->smartaddr) == 0 && bits256_nonz(G.LP_privkey) != 0 )
{
//printf("ADDR_UNSPENTS %s %s is my address being asked for!\n",ptr->symbol,coinaddr);
if ( ptr->lastpushtime > 0 && ptr->addr_listunspent_requested > (uint32_t)time(NULL)-10 )
ptr->lastpushtime -= LP_ORDERBOOK_DURATION*0.1;
ptr->addr_listunspent_requested = (uint32_t)time(NULL);
}
}
}
}
retstr = clonestr("{\"result\":\"success\"}");
} else retstr = clonestr("{\"error\":\"couldnt dereference sendmessage\"}");
}
else if ( strcmp(method,"psock") == 0 )
else if ( strcmp(method,"encrypted") == 0 )
retstr = clonestr("{\"result\":\"success\"}");
else // psock requests/response
{
if ( IAMLP != 0 )
{
if ( strcmp(method,"psock") == 0 )
{
if ( myipaddr == 0 || myipaddr[0] == 0 || strcmp(myipaddr,"127.0.0.1") == 0 )
{
@ -391,8 +626,6 @@ dividends(coin, height, <args>)\n\
return(LP_psock(myipaddr,jint(argjson,"ispaired")));
else return(clonestr("{\"error\":\"you are running an obsolete version, update\"}"));
}
else if ( strcmp(method,"notify") == 0 )
retstr = clonestr("{\"result\":\"success\",\"notify\":\"received\"}");
}
else
{

309
iguana/exchanges/LP_include.h

@ -21,34 +21,70 @@
#ifndef LP_INCLUDE_H
#define LP_INCLUDE_H
#define LP_MAJOR_VERSION "0"
#define LP_MINOR_VERSION "1"
#define LP_BUILD_NUMBER "15256"
#define LP_BARTERDEX_VERSION 1
#define LP_MAGICBITS 8
#ifdef FROM_JS
#include <emscripten.h>
#define sleep(x) emscripten_usleep((x) * 1000000)
void emscripten_usleep(int32_t x); // returns immediate, no sense for sleeping
#define usleep(x) emscripten_usleep(x)
// ./autogen.sh
// emconfigure ./configure CFLAGS="-s PTHREAD_POOL_SIZE=8 -s USE_PTHREADS=1 -O2"
// Edit src/core/sock.c and add here #include <limits.h> for INT_MAX support
// emmake make
// cp .libs/libnanomsg.a ~/SuperNET/OSlibs/js
#endif
//#define LP_STRICTPEERS
#define LP_MAXVINS 64
#define LP_HTTP_TIMEOUT 3 // 1 is too small due to edge cases of time(NULL)
#define LP_AUTOTRADE_TIMEOUT 30
#define LP_RESERVETIME (LP_AUTOTRADE_TIMEOUT * 2)
#define ELECTRUM_TIMEOUT 7
#define LP_ELECTRUM_KEEPALIVE 60
#define LP_ELECTRUM_MAXERRORS 777
#define LP_MEMPOOL_TIMEINCR 10
#define LP_MIN_PEERS 8
#define LP_MAX_PEERS 32
#define LP_MAXDESIRED_UTXOS (IAMLP != 0 ? 128 : 64)
#define LP_MINDESIRED_UTXOS (IAMLP != 0 ? 32 : 16)
#define LP_DUSTCOMBINE_THRESHOLD 1000000
// RTmetrics
#define LP_RTMETRICS_TOPGROUP 1.01
#define LP_MAXPENDING_SWAPS 13
#define LP_COMMAND_SENDSOCK NN_PUSH
#define LP_COMMAND_RECVSOCK NN_PULL
#define LP_ENCRYPTED_MAXSIZE (4096 + 2 + crypto_box_NONCEBYTES + crypto_box_ZEROBYTES)
#define DPOW_MIN_ASSETCHAIN_SIGS 11
#define LP_ENCRYPTED_MAXSIZE (16384 + 2 + crypto_box_NONCEBYTES + crypto_box_ZEROBYTES)
#define LP_MAXPUBKEY_ERRORS 3
#define LP_MAXPUBKEY_ERRORS 10
#define PSOCK_KEEPALIVE 3600
#define MAINLOOP_PERSEC 100
#define MAX_PSOCK_PORT 60000
#define MIN_PSOCK_PORT 10000
#define LP_MEMPOOL_TIMEINCR 10
#define LP_GETINFO_INCR 30
#define LP_ORDERBOOK_DURATION 3600
#define LP_ORDERBOOK_DURATION 180
#define LP_HTTP_TIMEOUT 2 // 1 is too small due to edge cases of time(NULL)
#define LP_MAXPEER_ERRORS 3
#define LP_MINPEER_GOOD 20
#define LP_PEERGOOD_ERRORDECAY 0.9
#define LP_SWAPSTEP_TIMEOUT 30
#define LP_AUTOTRADE_TIMEOUT 60
#define LP_MIN_TXFEE 10000
#define LP_MINVOL 10
#define LP_MINCLIENTVOL 20
#define LP_MINVOL 20
#define LP_MINCLIENTVOL 100
#define LP_MINSIZE_TXFEEMULT 10
#define LP_REQUIRED_TXFEE 0.95
#define LP_REQUIRED_TXFEE 0.8
#define LP_DEXFEE(destsatoshis) ((destsatoshis) / INSTANTDEX_INSURANCEDIV)
#define LP_DEPOSITSATOSHIS(satoshis) ((satoshis) + (satoshis >> 3))
@ -61,21 +97,29 @@
#define JUMBLR_RMD160 "5177f8b427e5f47342a4b8ab5dac770815d4389e"
#define TIERNOLAN_RMD160 "daedddd8dbe7a2439841ced40ba9c3d375f98146"
#define INSTANTDEX_BTC "1KRhTPvoxyJmVALwHFXZdeeWFbcJSbkFPu"
#define INSTANTDEX_BTCD "RThtXup6Zo7LZAi8kRWgjAyi1s4u6U9Cpf"
#define INSTANTDEX_KMD "RThtXup6Zo7LZAi8kRWgjAyi1s4u6U9Cpf"
//#define BASILISK_DISABLEWAITTX
//#define BASILISK_DISABLESENDTX
#define LP_RPCPORT 7783
#define LP_PROPAGATION_SLACK 100 // txid ordering is not enforced, so getting extra recent txid
#define LP_RESERVETIME 60
#define LP_AVETXSIZE 256
#define LP_CACHEDURATION 60
#define BASILISK_DEFAULT_NUMCONFIRMS 1
#define BASILISK_DEFAULT_MAXCONFIRMS 6
#define DEX_SLEEP 3
#define BASILISK_KEYSIZE ((int32_t)(2*sizeof(bits256)+sizeof(uint32_t)*2))
extern char GLOBAL_DBDIR[],USERPASS[],USERPASS_WIFSTR[];
extern int32_t IAMLP,USERPASS_COUNTER;
#define LP_IS_ZCASHPROTOCOL 1
#define LP_IS_BITCOINCASH 2
#define SIGHASH_FORKID 0x40
#define ZKSNARK_PROOF_SIZE 296
#define ZCASH_SOLUTION_ELEMENTS 1344
extern char GLOBAL_DBDIR[];
extern int32_t IAMLP;
struct iguana_msgvin { bits256 prev_hash; uint8_t *vinscript,*userdata,*spendscript,*redeemscript; uint32_t prev_vout,sequence; uint16_t scriptlen,p2shlen,userdatalen,spendlen; };
@ -92,13 +136,22 @@ struct iguana_msgtx
uint8_t *serialized;
};
struct iguana_msgjoinsplit
{
uint64_t vpub_old,vpub_new;
bits256 anchor,nullifiers[2],commitments[2],ephemeralkey;
bits256 randomseed,vmacs[2];
uint8_t zkproof[ZKSNARK_PROOF_SIZE];
uint8_t ciphertexts[2][601];
};
struct vin_signer { bits256 privkey; char coinaddr[64]; uint8_t siglen,sig[80],rmd160[20],pubkey[66]; };
struct vin_info
{
struct iguana_msgvin vin; uint64_t amount; cJSON *extras; bits256 sigtxid;
int32_t M,N,validmask,spendlen,type,p2shlen,numpubkeys,numsigs,height,hashtype,userdatalen,suppress_pubkeys,ignore_cltverr;
uint32_t sequence,unspentind; struct vin_signer signers[16]; char coinaddr[65];
int32_t M,N,validmask,spendlen,type,p2shlen,numpubkeys,numsigs,height,userdatalen,suppress_pubkeys,ignore_cltverr;
uint32_t sequence,unspentind,hashtype; struct vin_signer signers[16]; char coinaddr[65];
uint8_t rmd160[20],spendscript[10000],p2shscript[10000],userdata[10000];
};
@ -113,9 +166,9 @@ struct basilisk_swap;
struct basilisk_rawtxinfo
{
char destaddr[64],coinstr[16];
char destaddr[64];
bits256 txid,signedtxid,actualtxid;
uint64_t amount,change,inputsum;
int64_t amount,change,inputsum;
int32_t redeemlen,datalen,completed,vintype,vouttype,numconfirms,spendlen,secretstart,suppress_pubkeys;
uint32_t locktime,crcs[2];
uint8_t addrtype,pubkey33[33],rmd160[20];
@ -124,20 +177,19 @@ struct basilisk_rawtxinfo
struct basilisk_request
{
uint32_t requestid,timestamp,quoteid,quotetime; // 0 to 15
uint64_t srcamount,unused; // 16 to 31
int64_t srcamount,unused; // 16 to 31
bits256 srchash; // 32 to 63
bits256 desthash;
char src[8],dest[8];
char src[68],dest[68];
uint64_t destamount;
int32_t optionhours,DEXselector;
};
struct basilisk_rawtx
{
char name[32];
char name[32],symbol[65];
struct iguana_msgtx msgtx;
struct basilisk_rawtxinfo I;
struct iguana_info *coin;
char vinstr[8192],p2shaddr[64];
cJSON *vins;
bits256 utxotxid; int32_t utxovout;
@ -147,11 +199,11 @@ struct basilisk_rawtx
struct basilisk_swapinfo
{
struct basilisk_request req;
char bobstr[64],alicestr[64];
char bobstr[128],alicestr[128];
bits256 myhash,otherhash,orderhash;
uint32_t statebits,otherstatebits,started,expiration,finished,dead,reftime,putduration,callduration;
int32_t bobconfirms,aliceconfirms,iambob,reclaimed,bobspent,alicespent,pad;
uint64_t alicesatoshis,bobsatoshis,bobinsurance,aliceinsurance,Atxfee,Btxfee;
int32_t bobconfirms,aliceconfirms,iambob,reclaimed,bobspent,alicespent,pad,aliceistrusted,bobistrusted,otheristrusted,otherstrust,alicemaxconfirms,bobmaxconfirms;
int64_t alicesatoshis,bobsatoshis,bobinsurance,aliceinsurance,Atxfee,Btxfee;
bits256 myprivs[2],mypubs[2],otherpubs[2],pubA0,pubA1,pubB0,pubB1,privAm,pubAm,privBn,pubBn;
uint32_t crcs_mypub[2],crcs_mychoosei[2],crcs_myprivs[2],crcs_mypriv[2];
@ -166,38 +218,69 @@ struct basilisk_swapinfo
uint8_t userdata_bobrefund[256],userdata_bobrefundlen;
};
struct LP_outpoint { bits256 spendtxid; uint64_t value,interest; int32_t spendvini,spendheight; char coinaddr[40]; };
#define BASILISK_ALICESPEND 0
#define BASILISK_BOBSPEND 1
#define BASILISK_BOBPAYMENT 2
#define BASILISK_ALICEPAYMENT 3
#define BASILISK_BOBDEPOSIT 4
#define BASILISK_OTHERFEE 5
#define BASILISK_MYFEE 6
#define BASILISK_BOBREFUND 7
#define BASILISK_BOBRECLAIM 8
#define BASILISK_ALICERECLAIM 9
#define BASILISK_ALICECLAIM 10
//0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0
char *txnames[] = { "alicespend", "bobspend", "bobpayment", "alicepayment", "bobdeposit", "otherfee", "myfee", "bobrefund", "bobreclaim", "alicereclaim", "aliceclaim" };
struct LP_swap_remember
{
bits256 pubA0,pubB0,pubB1,privAm,privBn,paymentspent,Apaymentspent,depositspent,myprivs[2],txids[sizeof(txnames)/sizeof(*txnames)];
uint64_t Atxfee,Btxfee,srcamount,destamount,aliceid;
int64_t values[sizeof(txnames)/sizeof(*txnames)];
uint32_t finishtime,tradeid,requestid,quoteid,plocktime,dlocktime,expiration,state,otherstate;
int32_t iambob,finishedflag,origfinishedflag,Predeemlen,Dredeemlen,sentflags[sizeof(txnames)/sizeof(*txnames)];
uint8_t secretAm[20],secretAm256[32],secretBn[20],secretBn256[32],Predeemscript[1024],Dredeemscript[1024],pubkey33[33],other33[33];
char Agui[65],Bgui[65],gui[65],src[65],dest[65],destaddr[64],Adestaddr[64],Sdestaddr[64],alicepaymentaddr[64],bobpaymentaddr[64],bobdepositaddr[64],alicecoin[65],bobcoin[65],*txbytes[sizeof(txnames)/sizeof(*txnames)];
};
struct LP_transaction
struct LP_outpoint
{
UT_hash_handle hh;
bits256 txid; int32_t height,numvouts,numvins; uint32_t timestamp;
struct LP_outpoint outpoints[];
bits256 spendtxid;
uint64_t value,interest;
int32_t spendvini,spendheight;
char coinaddr[64];
};
struct LP_address
struct LP_transaction
{
UT_hash_handle hh;
int64_t balance;
char coinaddr[40];
bits256 txid;
long fpos;
int32_t height,numvouts,numvins,len,SPV;
uint8_t *serialized;
struct LP_outpoint outpoints[];
};
struct iguana_info
{
UT_hash_handle hh;
portable_mutex_t txmutex; struct LP_transaction *transactions; struct LP_address *addresses;
portable_mutex_t txmutex,addrmutex; struct LP_transaction *transactions; struct LP_address *addresses;
uint64_t txfee;
int32_t longestchain,firstrefht,firstscanht,lastscanht,bussock; uint16_t busport;
uint32_t counter,inactive,lastmempool,lastgetinfo;
uint8_t pubtype,p2shtype,isPoS,wiftype,wiftaddr,taddr,noimportprivkey_flag;
char symbol[16],smartaddr[64],userpass[1024],serverport[128];
int32_t numutxos,longestchain,firstrefht,firstscanht,lastscanht,bussock,height; uint16_t busport;
uint32_t loadedcache,electrumlist,lastunspent,importedprivkey,lastpushtime,lastutxosync,addr_listunspent_requested,lastutxos,updaterate,counter,inactive,lastmempool,lastgetinfo,ratetime,heighttime,lastmonitor,obooktime;
uint8_t pubtype,p2shtype,isPoS,wiftype,wiftaddr,taddr,noimportprivkey_flag,userconfirms,isassetchain,maxconfirms;
char symbol[128],smartaddr[64],userpass[1024],serverport[128];
// portfolio
double price_kmd,force,perc,goal,goalperc,relvolume;
double price_kmd,force,perc,goal,goalperc,relvolume,rate;
void *electrum; void *ctx;
uint64_t maxamount,kmd_equiv,balanceA,balanceB,valuesumA,valuesumB;
uint8_t pubkey33[33];
uint8_t pubkey33[33],zcash;
int32_t privkeydepth;
bits256 cachedtxid; uint8_t *cachedtxiddata; int32_t cachedtxidlen;
bits256 cachedmerkle; int32_t cachedmerkleheight;
};
struct _LP_utxoinfo { bits256 txid; uint64_t value; int32_t vout; };
struct _LP_utxoinfo { bits256 txid; uint64_t value; int32_t vout,height; };
struct LP_utxostats { uint32_t sessionid,lasttime,errors,swappending,spentflag,lastspentcheck,bestflag; };
@ -205,7 +288,7 @@ struct LP_utxobob { struct _LP_utxoinfo utxo,deposit; };
struct LP_utxoalice { struct _LP_utxoinfo utxo,fee; };
struct LP_utxoswap { bits256 otherpubkey; void *swap; uint64_t satoshis; };
struct LP_utxoswap { bits256 otherpubkey; uint64_t satoshis; };
struct LP_utxoinfo
{
@ -214,19 +297,38 @@ struct LP_utxoinfo
struct _LP_utxoinfo payment,deposit,fee;
struct LP_utxostats T;
struct LP_utxoswap S;
//struct LP_utxonetwork N;
int32_t iambob,iamlp;
uint8_t key[sizeof(bits256) + sizeof(int32_t)];
uint8_t key2[sizeof(bits256) + sizeof(int32_t)];
char coin[16],coinaddr[64],spendscript[256],gui[16];
char coin[65],coinaddr[64],gui[16];//spendscript[256];
};
struct LP_address_utxo
{
struct LP_address_utxo *next,*prev;
struct _LP_utxoinfo U;
int32_t SPV,spendheight;
//uint32_t timestamp;
};
struct LP_address
{
UT_hash_handle hh;
struct LP_address_utxo *utxos;
bits256 pubkey;
int64_t balance,total;
uint32_t timestamp,n,unspenttime;
int32_t unspentheight;
char coinaddr[40];
uint8_t pubsecp[33],pad;
};
struct LP_peerinfo
{
UT_hash_handle hh;
uint64_t ip_port;
uint32_t ipbits,errortime,errors,numpeers,numutxos,lasttime,connected,lastutxos,lastpeers,diduquery,good,sessionid;
int32_t pushsock,subsock;
uint32_t recvtime,numrecv,ipbits,errortime,errors,numpeers,needping,lasttime,connected,lastutxos,lastpeers,diduquery,good,sessionid;
int32_t pushsock,subsock,isLP;
uint16_t port;
char ipaddr[64];
};
@ -235,19 +337,21 @@ struct LP_quoteinfo
{
struct basilisk_request R;
bits256 srchash,desthash,txid,txid2,desttxid,feetxid,privkey;
uint64_t satoshis,txfee,destsatoshis,desttxfee;
uint32_t timestamp,quotetime; int32_t vout,vout2,destvout,feevout,pair;
char srccoin[16],coinaddr[64],destcoin[16],destaddr[64];
uint64_t satoshis,txfee,destsatoshis,desttxfee,aliceid;
uint32_t timestamp,quotetime,tradeid;
int32_t vout,vout2,destvout,feevout,pair;
char srccoin[65],coinaddr[64],destcoin[65],destaddr[64],gui[64];
};
struct LP_endpoint { int32_t pair; char ipaddr[64]; uint16_t port; };
struct basilisk_swap
{
void *ctx; struct iguana_info bobcoin,alicecoin; struct LP_utxoinfo *utxo;
void *ctx; //struct LP_utxoinfo *utxo;
struct LP_endpoint N;
void (*balancingtrade)(struct basilisk_swap *swap,int32_t iambob);
int32_t subsock,pushsock,connected,aliceunconf,depositunconf,paymentunconf; uint32_t lasttime,aborted;
int32_t subsock,pushsock,connected,aliceunconf,depositunconf,paymentunconf;
uint32_t lasttime,aborted,tradeid;
FILE *fp;
bits256 persistent_privkey,persistent_pubkey;
struct basilisk_swapinfo I;
@ -255,11 +359,50 @@ struct basilisk_swap
bits256 privkeys[INSTANTDEX_DECKSIZE];
struct basilisk_swapmessage *messages; int32_t nummessages,sentflag;
char Bdeposit[64],Bpayment[64];
uint64_t otherdeck[INSTANTDEX_DECKSIZE][2],deck[INSTANTDEX_DECKSIZE][2];
uint8_t persistent_pubkey33[33],changermd160[20],pad[15],verifybuf[65536];
uint64_t aliceid,otherdeck[INSTANTDEX_DECKSIZE][2],deck[INSTANTDEX_DECKSIZE][2];
uint8_t persistent_pubkey33[33],persistent_other33[33],changermd160[20],pad[15],verifybuf[100000];
};
struct LP_pubkey_quote
{
struct LP_pubkey_quote *next,*prev;
float price;
uint32_t maxutxo,aveutxo;
uint8_t baseind,relind,numutxos,scale;
};
#define LP_MAXPRICEINFOS 256
struct LP_pubkeyinfo
{
UT_hash_handle hh;
bits256 pubkey;
struct LP_pubkey_quote *quotes;
//float matrix[LP_MAXPRICEINFOS][LP_MAXPRICEINFOS];
//uint32_t timestamps[LP_MAXPRICEINFOS][LP_MAXPRICEINFOS];
uint32_t timestamp,numerrors,lasttime;
int32_t istrusted;
uint8_t rmd160[20],sig[65],pubsecp[33],siglen;
};
struct electrum_info
{
queue_t sendQ,pendingQ;
portable_mutex_t mutex,txmutex;
struct electrum_info *prev;
int32_t bufsize,sock,*heightp,numerrors;
struct iguana_info *coin;
uint32_t stratumid,lasttime,keepalive,pending,*heighttimep;
char ipaddr[64],symbol[66];
uint16_t port;
uint8_t buf[];
};
int32_t LP_pubkey_sigcheck(struct LP_pubkeyinfo *pubp,cJSON *item);
int32_t LP_pubkey_sigadd(cJSON *item,uint32_t timestamp,bits256 priv,bits256 pub,uint8_t *rmd160,uint8_t *pubsecp);
int32_t LP_quoteparse(struct LP_quoteinfo *qp,cJSON *argjson);
struct LP_address *LP_address(struct iguana_info *coin,char *coinaddr);
void LP_swap_coinaddr(struct iguana_info *coin,char *coinaddr,uint64_t *valuep,uint8_t *data,int32_t datalen,int32_t vout);
void basilisk_dontforget_update(struct basilisk_swap *swap,struct basilisk_rawtx *rawtx);
uint32_t basilisk_requestid(struct basilisk_request *rp);
uint32_t basilisk_quoteid(struct basilisk_request *rp);
@ -273,17 +416,71 @@ int32_t LP_forward(void *ctx,char *myipaddr,int32_t pubsock,bits256 pubkey,char
int32_t LP_ismine(struct LP_utxoinfo *utxo);
int32_t LP_isavailable(struct LP_utxoinfo *utxo);
struct LP_peerinfo *LP_peerfind(uint32_t ipbits,uint16_t port);
uint64_t LP_value_extract(cJSON *obj,int32_t addinterest);
int32_t LP_swap_getcoinaddr(char *symbol,char *coinaddr,bits256 txid,int32_t vout);
char *LP_command_process(void *ctx,char *myipaddr,int32_t pubsock,cJSON *argjson,uint8_t *data,int32_t datalen);
void LP_availableset(struct LP_utxoinfo *utxo);
int64_t LP_komodo_interest(bits256 txid,int64_t value);
void LP_availableset(bits256 txid,int32_t vout);
int32_t LP_iseligible(uint64_t *valp,uint64_t *val2p,int32_t iambob,char *symbol,bits256 txid,int32_t vout,uint64_t satoshis,bits256 txid2,int32_t vout2);
int32_t LP_pullsock_check(void *ctx,char **retstrp,char *myipaddr,int32_t pubsock,int32_t pullsock);
void LP_unspents_cache(char *symbol,char *addr,char *arraystr,int32_t updatedflag);
uint16_t LP_psock_get(char *connectaddr,char *publicaddr,int32_t ispaired);
void LP_utxo_clientpublish(struct LP_utxoinfo *utxo);
//void LP_utxo_clientpublish(struct LP_utxoinfo *utxo);
int32_t LP_coinbus(uint16_t coin_busport);
int32_t LP_nanomsg_recvs(void *ctx);
void LP_aliceid(uint32_t tradeid,uint64_t aliceid,char *event,uint32_t requestid,uint32_t quoteid);
cJSON *LP_cache_transaction(struct iguana_info *coin,bits256 txid,uint8_t *serialized,int32_t len);
cJSON *LP_transaction_fromdata(struct iguana_info *coin,bits256 txid,uint8_t *serialized,int32_t len);
uint64_t LP_RTsmartbalance(struct iguana_info *coin);
int32_t LP_getheight(struct iguana_info *coin);
int32_t LP_reserved_msg(int32_t priority,char *base,char *rel,bits256 pubkey,char *msg);
struct iguana_info *LP_coinfind(char *symbol);
int32_t LP_crc32find(int32_t *duplicatep,int32_t ind,uint32_t crc32);
char *LP_pricepings(void *ctx,char *myipaddr,int32_t pubsock,char *base,char *rel,double price);
uint64_t LP_txfeecalc(char *symbol,uint64_t txfee);
int32_t LP_merkleproof(struct iguana_info *coin,char *coinaddr,struct electrum_info *ep,bits256 txid,int32_t height);
int32_t _LP_utxos_remove(bits256 txid,int32_t vout);
int32_t LP_utxos_remove(bits256 txid,int32_t vout);
struct LP_transaction *LP_transactionadd(struct iguana_info *coin,bits256 txid,int32_t height,int32_t numvouts,int32_t numvins);
void LP_tradebot_finished(uint32_t tradeid,uint32_t requestid,uint32_t quoteid);
uint64_t LP_txfeecalc(struct iguana_info *coin,uint64_t txfee,int32_t txlen);
struct LP_address *_LP_address(struct iguana_info *coin,char *coinaddr);
struct LP_address *_LP_addressfind(struct iguana_info *coin,char *coinaddr);
struct LP_address *_LP_addressadd(struct iguana_info *coin,char *coinaddr);
int32_t iguana_signrawtransaction(void *ctx,char *symbol,uint8_t wiftaddr,uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,struct iguana_msgtx *msgtx,char **signedtxp,bits256 *signedtxidp,struct vin_info *V,int32_t numinputs,char *rawtx,cJSON *vins,cJSON *privkeysjson,int32_t zcash);
//void LP_butxo_swapfields_set(struct LP_utxoinfo *butxo);
struct LP_address_utxo *LP_address_utxofind(struct iguana_info *coin,char *coinaddr,bits256 txid,int32_t vout);
int32_t LP_destaddr(char *destaddr,cJSON *item);
int32_t LP_waitmempool(char *symbol,char *coinaddr,bits256 txid,int32_t vout,int32_t duration);
char *LP_statslog_disp(int32_t n,uint32_t starttime,uint32_t endtime,char *refgui,bits256 refpubkey);
uint32_t LP_heighttime(char *symbol,int32_t height);
uint64_t LP_unspents_load(char *symbol,char *addr);
int32_t LP_validSPV(char *symbol,char *coinaddr,bits256 txid,int32_t vout);
struct LP_transaction *LP_transactionfind(struct iguana_info *coin,bits256 txid);
cJSON *LP_transactioninit(struct iguana_info *coin,bits256 txid,int32_t iter,cJSON *txobj);
int32_t LP_mempoolscan(char *symbol,bits256 searchtxid);
int32_t LP_txheight(struct iguana_info *coin,bits256 txid);
int32_t LP_numpeers();
char *basilisk_swapentry(uint32_t requestid,uint32_t quoteid);
uint64_t LP_KMDvalue(struct iguana_info *coin,uint64_t balance);
int32_t LP_address_utxoadd(uint32_t timestamp,char *debug,struct iguana_info *coin,char *coinaddr,bits256 txid,int32_t vout,uint64_t value,int32_t height,int32_t spendheight);
void LP_smartutxos_push(struct iguana_info *coin);
void LP_cacheptrs_init(struct iguana_info *coin);
cJSON *LP_address_utxos(struct iguana_info *coin,char *coinaddr,int32_t electrumret);
cJSON *LP_gettxout(char *symbol,char *coinaddr,bits256 txid,int32_t vout);
void LP_postutxos(char *symbol,char *coinaddr);
int32_t LP_listunspent_both(char *symbol,char *coinaddr,int32_t fullflag);
uint16_t LP_randpeer(char *destip);
char *issue_LP_psock(char *destip,uint16_t destport,int32_t ispaired);
char *LP_unspents_filestr(char *symbol,char *addr);
cJSON *bitcoin_data2json(uint8_t taddr,uint8_t pubtype,uint8_t p2shtype,uint8_t isPoS,int32_t height,bits256 *txidp,struct iguana_msgtx *msgtx,uint8_t *extraspace,int32_t extralen,uint8_t *serialized,int32_t len,cJSON *vins,int32_t suppress_pubkeys,int32_t zcash);
//int32_t LP_butxo_findeither(bits256 txid,int32_t vout);
cJSON *LP_listunspent(char *symbol,char *coinaddr);
int32_t LP_gettx_presence(char *symbol,bits256 expectedtxid);
double LP_getestimatedrate(struct iguana_info *coin);
struct LP_utxoinfo *_LP_utxofind(int32_t iambob,bits256 txid,int32_t vout);
struct LP_utxoinfo *_LP_utxo2find(int32_t iambob,bits256 txid,int32_t vout);
void LP_listunspent_query(char *symbol,char *coinaddr);
int32_t bitcoin_priv2wif(uint8_t wiftaddr,char *wifstr,bits256 privkey,uint8_t addrtype);
#endif

1064
iguana/exchanges/LP_nativeDEX.c

File diff suppressed because it is too large

314
iguana/exchanges/LP_network.c

@ -28,9 +28,83 @@ struct psock
uint16_t Numpsocks,Psockport = MIN_PSOCK_PORT;
#ifdef FROM_JS
int32_t nn_socket(int domain, int protocol)
{
return(0);
}
int32_t nn_close(int s)
{
return(0);
}
int32_t nn_setsockopt(int s, int level, int option, const void *optval,size_t optvallen)
{
return(0);
}
int32_t nn_getsockopt(int s, int level, int option, void *optval,size_t *optvallen)
{
return(0);
}
int32_t nn_bind(int s, const char *addr)
{
return(-1);
}
int32_t nn_connect(int s, const char *addr)
{
if ( strncmp("ws://",addr,strlen("ws://")) != 0 )
return(-1);
return(0);
}
int32_t nn_shutdown(int s, int how)
{
return(0);
}
int32_t nn_send(int s, const void *buf, size_t len, int flags)
{
printf("JS cant nn_send (%s)\n",(char *)buf);
return(0);
}
int32_t nn_recv(int s, void *buf, size_t len, int flags)
{
return(0);
}
int32_t nn_errno(void)
{
return(-11);
}
const char *nn_strerror(int errnum)
{
return("nanomsg error");
}
int32_t nn_poll(struct nn_pollfd *fds, int nfds, int timeout)
{
return(0);
}
#endif
char *nanomsg_transportname(int32_t bindflag,char *str,char *ipaddr,uint16_t port)
{
sprintf(str,"tcp://%s:%u",bindflag == 0 ? ipaddr : "*",port); // ws is worse
sprintf(str,"tcp://%s:%u",bindflag == 0 ? ipaddr : "*",port);
return(str);
}
/*char *nanomsg_transportname2(int32_t bindflag,char *str,char *ipaddr,uint16_t port)
{
sprintf(str,"ws://%s:%u",bindflag == 0 ? ipaddr : "*",port+10);
return(str);
}
@ -46,11 +120,11 @@ int32_t _LP_send(int32_t sock,void *msg,int32_t sendlen,int32_t freeflag)
}
if ( (sentbytes= nn_send(sock,msg,sendlen,0)) != sendlen )
printf("LP_send sent %d instead of %d\n",sentbytes,sendlen);
//else printf("SENT.(%s)\n",msg);
else printf("SENT.(%s)\n",(char *)msg);
if ( freeflag != 0 )
free(msg);
return(sentbytes);
}
}*/
int32_t LP_sockcheck(int32_t sock)
{
@ -66,7 +140,7 @@ struct LP_queue
{
struct LP_queue *next,*prev;
int32_t sock,peerind,msglen;
uint32_t starttime,crc32;
uint32_t starttime,crc32,notready;
uint8_t msg[];
} *LP_Q;
int32_t LP_Qenqueued,LP_Qerrors,LP_Qfound;
@ -74,20 +148,72 @@ int32_t LP_Qenqueued,LP_Qerrors,LP_Qfound;
void _LP_sendqueueadd(uint32_t crc32,int32_t sock,uint8_t *msg,int32_t msglen,int32_t peerind)
{
struct LP_queue *ptr;
ptr = calloc(1,sizeof(*ptr) + msglen);
ptr = calloc(1,sizeof(*ptr) + msglen + sizeof(bits256));
ptr->crc32 = crc32;
ptr->sock = sock;
ptr->peerind = peerind;
ptr->msglen = msglen;
memcpy(ptr->msg,msg,msglen);
ptr->msglen = (int32_t)(msglen + sizeof(bits256));
memcpy(ptr->msg,msg,msglen); // sizeof(bits256) at the end all zeroes
DL_APPEND(LP_Q,ptr);
LP_Qenqueued++;
//printf("Q.%p: peerind.%d msglen.%d\n",ptr,peerind,msglen);
}
uint32_t _LP_magic_check(bits256 hash,bits256 magic)
{
bits256 pubkey,shared;
pubkey = curve25519(magic,curve25519_basepoint9());
shared = curve25519(hash,pubkey);
return(shared.uints[1] & ((1 << LP_MAGICBITS)-1));
}
bits256 LP_calc_magic(uint8_t *msg,int32_t len)
{
static uint32_t maxn,counter,nsum; static double sum;
bits256 magic,hash; int32_t n = 0; double millis;
vcalc_sha256(0,hash.bytes,msg,len);
millis = OS_milliseconds();
while ( 1 )
{
magic = rand256(1);
if ( _LP_magic_check(hash,magic) == LP_BARTERDEX_VERSION )
break;
n++;
}
sum += (OS_milliseconds() - millis);
nsum += n;
counter++;
if ( n > maxn || (LP_rand() % 10000) == 0 )
{
if ( n > maxn )
{
printf("LP_calc_magic maxn.%d <- %d | ",maxn,n);
maxn = n;
}
printf("millis %.3f ave %.3f, aveiters %.1f\n",OS_milliseconds() - millis,sum/counter,(double)nsum/counter);
}
return(magic);
}
int32_t LP_magic_check(uint8_t *msg,int32_t recvlen,char *remoteaddr)
{
bits256 magic,hash; uint32_t val;
recvlen -= sizeof(bits256);
if ( recvlen > 0 )
{
vcalc_sha256(0,hash.bytes,msg,recvlen);
memcpy(magic.bytes,&msg[recvlen],sizeof(magic));
val = _LP_magic_check(hash,magic);
if ( val != LP_BARTERDEX_VERSION )
printf("magicval = %x from %s\n",val,remoteaddr);
return(val == LP_BARTERDEX_VERSION);
}
return(-1);
}
int32_t LP_crc32find(int32_t *duplicatep,int32_t ind,uint32_t crc32)
{
static uint32_t crcs[8192]; static unsigned long dup,total;
static uint32_t crcs[4096]; static unsigned long dup,total;
int32_t i;
*duplicatep = 0;
if ( ind < 0 )
@ -111,7 +237,7 @@ int32_t LP_crc32find(int32_t *duplicatep,int32_t ind,uint32_t crc32)
break;
}
if ( i >= sizeof(crcs)/sizeof(*crcs) )
i = (rand() % (sizeof(crcs)/sizeof(*crcs)));
i = (LP_rand() % (sizeof(crcs)/sizeof(*crcs)));
return(i);
}
else
@ -139,49 +265,96 @@ int32_t LP_peerindsock(int32_t *peerindp)
return(-1);
}
void queue_loop(void *ignore)
void gc_loop(void *arg)
{
uint32_t now; struct LP_address_utxo *up,*utmp; struct rpcrequest_info *req,*rtmp; int32_t flag = 0;
strcpy(LP_gcloop_stats.name,"gc_loop");
LP_gcloop_stats.threshold = 11000.;
while ( 1 )
{
flag = 0;
LP_millistats_update(&LP_gcloop_stats);
portable_mutex_lock(&LP_gcmutex);
DL_FOREACH_SAFE(LP_garbage_collector,req,rtmp)
{
DL_DELETE(LP_garbage_collector,req);
//printf("garbage collect ipbits.%x\n",req->ipbits);
free(req);
flag++;
}
now = (uint32_t)time(NULL);
DL_FOREACH_SAFE(LP_garbage_collector2,up,utmp)
{
if ( now > (uint32_t)up->spendheight+120 )
{
DL_DELETE(LP_garbage_collector2,up);
//char str[65]; printf("garbage collect %s/v%d lag.%d\n",bits256_str(str,up->U.txid),up->U.vout,now-up->spendheight);
free(up);
}
flag++;
}
portable_mutex_unlock(&LP_gcmutex);
if ( 0 && flag != 0 )
printf("gc_loop.%d\n",flag);
sleep(10);
}
}
void queue_loop(void *arg)
{
struct LP_queue *ptr,*tmp; int32_t sentbytes,nonz,flag,duplicate,n=0;
strcpy(queue_loop_stats.name,"queue_loop");
queue_loop_stats.threshold = 1000.;
while ( 1 )
{
nonz = 0;
LP_millistats_update(&queue_loop_stats);
//printf("LP_Q.%p next.%p prev.%p\n",LP_Q,LP_Q!=0?LP_Q->next:0,LP_Q!=0?LP_Q->prev:0);
n = 0;
n = nonz = flag = 0;
DL_FOREACH_SAFE(LP_Q,ptr,tmp)
{
n++;
flag = 0;
if ( ptr->sock >= 0 )
{
if ( ptr->notready == 0 || (LP_rand() % ptr->notready) == 0 )
{
if ( LP_sockcheck(ptr->sock) > 0 )
{
bits256 magic;
magic = LP_calc_magic(ptr->msg,(int32_t)(ptr->msglen - sizeof(bits256)));
memcpy(&ptr->msg[ptr->msglen - sizeof(bits256)],&magic,sizeof(magic));
if ( (sentbytes= nn_send(ptr->sock,ptr->msg,ptr->msglen,0)) != ptr->msglen )
printf("%d LP_send sent %d instead of %d\n",n,sentbytes,ptr->msglen);
// else printf("%d %p qsent %u msglen.%d peerind.%d\n",n,ptr,ptr->crc32,ptr->msglen,ptr->peerind);
else flag++;
ptr->sock = -1;
if ( ptr->peerind > 0 )
ptr->starttime = (uint32_t)time(NULL);
else flag = 1;
}
else
{
if ( ptr->notready++ > 1000 )
flag = 1;
}
}
else if ( time(NULL) > ptr->starttime+13 )
}
else if ( 0 && time(NULL) > ptr->starttime+13 )
{
LP_crc32find(&duplicate,-1,ptr->crc32);
if ( duplicate > 0 )
{
LP_Qfound++;
if ( (LP_Qfound % 10) == 0 )
if ( (LP_Qfound % 100) == 0 )
printf("found.%u Q.%d err.%d match.%d\n",ptr->crc32,LP_Qenqueued,LP_Qerrors,LP_Qfound);
flag = 1;
flag++;
}
else
else if ( 0 ) // too much beyond duplicate filter when network is busy
{
printf("couldnt find.%u peerind.%d Q.%d err.%d match.%d\n",ptr->crc32,ptr->peerind,LP_Qenqueued,LP_Qerrors,LP_Qfound);
ptr->peerind++;
if ( (ptr->sock= LP_peerindsock(&ptr->peerind)) < 0 )
{
printf("%d no more peers to try at peerind.%d %p Q_LP.%p\n",n,ptr->peerind,ptr,LP_Q);
flag = 1;
flag++;
LP_Qerrors++;
}
}
@ -194,66 +367,47 @@ void queue_loop(void *ignore)
portable_mutex_unlock(&LP_networkmutex);
free(ptr);
ptr = 0;
break;
}
}
//if ( n != 0 )
// printf("LP_Q.[%d]\n",n);
if ( arg == 0 )
break;
if ( nonz == 0 )
usleep(500000);
{
if ( IAMLP == 0 )
usleep(50000);
else usleep(10000);
}
}
}
void _LP_queuesend(uint32_t crc32,int32_t sock0,int32_t sock1,uint8_t *msg,int32_t msglen,int32_t needack)
{
int32_t sentbytes,peerind = 0;
if ( sock0 >= 0 || sock1 >= 0 )
{
if ( sock0 >= 0 && LP_sockcheck(sock0) > 0 )
{
if ( (sentbytes= nn_send(sock0,msg,msglen,0)) != msglen )
printf("_LP_queuesend0 sent %d instead of %d\n",sentbytes,msglen);
else
{
//printf("Q sent %u\n",crc32);
sock0 = -1;
}
}
if ( sock1 >= 0 && LP_sockcheck(sock1) > 0 )
{
if ( (sentbytes= nn_send(sock1,msg,msglen,0)) != msglen )
printf("_LP_queuesend1 sent %d instead of %d\n",sentbytes,msglen);
else sock1 = -1;
}
int32_t maxind,peerind = 0; //sentbytes,
if ( sock0 < 0 && sock1 < 0 )
return;
}
else
{
peerind = 1;
if ( (maxind= LP_numpeers()) > 0 )
peerind = (LP_rand() % maxind) + 1;
else peerind = 1;
sock0 = LP_peerindsock(&peerind);
if ( (maxind= LP_numpeers()) > 0 )
peerind = (LP_rand() % maxind) + 1;
else peerind = 1;
sock1 = LP_peerindsock(&peerind);
}
portable_mutex_lock(&LP_networkmutex);
if ( sock0 >= 0 )
_LP_sendqueueadd(crc32,sock0,msg,msglen,needack * peerind);
if ( sock1 >= 0 )
_LP_sendqueueadd(crc32,sock1,msg,msglen,needack);
portable_mutex_unlock(&LP_networkmutex);
}
void LP_queuesend(uint32_t crc32,int32_t pubsock,char *base,char *rel,uint8_t *msg,int32_t msglen)
{
//struct iguana_info *coin; int32_t flag=0,socks[2];
portable_mutex_lock(&LP_networkmutex);
if ( pubsock >= 0 )
{
//socks[0] = socks[1] = -1;
//if ( rel != 0 && rel[0] != 0 && (coin= LP_coinfind(rel)) != 0 && coin->bussock >= 0 )
// socks[flag++] = coin->bussock;
//if ( base != 0 && base[0] != 0 && (coin= LP_coinfind(base)) != 0 && coin->bussock >= 0 )
// socks[flag++] = coin->bussock;
//if ( flag == 0 && pubsock >= 0 )
_LP_queuesend(crc32,pubsock,-1,msg,msglen,0);
//else _LP_queuesend(socks[0],socks[1],msg,msglen,0);
} else _LP_queuesend(crc32,-1,-1,msg,msglen,1);
else _LP_queuesend(crc32,-1,-1,msg,msglen,1);
portable_mutex_unlock(&LP_networkmutex);
}
// first 2 bytes == (crc32 & 0xffff) if encrypted, then nonce is next crypto_box_NONCEBYTES
@ -266,11 +420,19 @@ void LP_broadcast_finish(int32_t pubsock,char *base,char *rel,uint8_t *msg,cJSON
msglen = (int32_t)strlen((char *)msg) + 1;
if ( crc32 == 0 )
crc32 = calc_crc32(0,&msg[2],msglen - 2);
#ifdef FROM_MARKETMAKER
if ( G.LP_IAMLP == 0 )
#else
if ( IAMLP == 0 )
#endif
{
free(msg);
//printf("broadcast %s\n",jstr(argjson,"method"));
jdelete(argjson,"method");
jaddstr(argjson,"method","broadcast");
if ( jobj(argjson,"timestamp") == 0 )
jaddnum(argjson,"timestamp",(uint32_t)time(NULL));
// add signature here
msg = (void *)jprint(argjson,0);
msglen = (int32_t)strlen((char *)msg) + 1;
LP_queuesend(crc32,-1,base,rel,msg,msglen);
@ -311,11 +473,14 @@ void LP_broadcast_message(int32_t pubsock,char *base,char *rel,bits256 destpub25
jdelete(argjson,"method2");
jaddstr(argjson,"method2",method);
jaddstr(argjson,"method",method);
//printf("CRC32.%u (%s)\n",crc32,(char *)msg);
//if ( strncmp(method,"connect",7) == 0 || strcmp(method,"reserved") == 0 )
// printf("CRC32.%u (%s)\n",crc32,msgstr);
LP_broadcast_finish(pubsock,base,rel,msg,argjson,0);
//if ( strncmp(method,"connect",7) == 0 || strcmp(method,"reserved") == 0 )
// printf("finished %u\n",crc32);
} // else printf("no valid method in (%s)\n",msgstr);
free_json(argjson);
} else printf("couldnt parse (%s)\n",msgstr);
} else printf("couldnt parse %p (%s)\n",msgstr,msgstr);
}
else
{
@ -360,8 +525,11 @@ void LP_psockloop(void *_ptr) // printouts seem to be needed for forwarding to w
{
static struct nn_pollfd *pfds;
int32_t i,n,nonz,iter,retval,sentbytes,size=0,sendsock = -1; uint32_t now; struct psock *ptr=0; void *buf=0; char keepalive[512];
strcpy(LP_psockloop_stats.name,"LP_psockloop");
LP_psockloop_stats.threshold = 200.;
while ( 1 )
{
LP_millistats_update(&LP_psockloop_stats);
now = (uint32_t)time(NULL);
if ( buf != 0 && ptr != 0 && sendsock >= 0 )
{
@ -406,12 +574,19 @@ void LP_psockloop(void *_ptr) // printouts seem to be needed for forwarding to w
else if ( (pfds[n].revents & POLLIN) != 0 )
{
printf("publicsock.%d %s has pollin\n",ptr->publicsock,ptr->publicaddr);
buf = 0;
if ( (size= nn_recv(ptr->publicsock,&buf,NN_MSG,0)) > 0 )
{
ptr->lasttime = now;
sendsock = ptr->sendsock;
break;
}
else if ( buf != 0 )
{
nn_freemsg(buf);
buf = 0;
size = 0;
}
}
}
n++;
@ -438,7 +613,8 @@ void LP_psockloop(void *_ptr) // printouts seem to be needed for forwarding to w
sendsock = ptr->publicsock;
break;
}
else
}
if ( buf != 0 )
{
nn_freemsg(buf);
buf = 0;
@ -446,7 +622,6 @@ void LP_psockloop(void *_ptr) // printouts seem to be needed for forwarding to w
}
}
}
}
n++;
}
if ( iter == 0 )
@ -611,10 +786,11 @@ char *LP_psock(char *myipaddr,int32_t ispaired)
both are combined in LP_psock_get
*/
char *issue_LP_psock(char *destip,uint16_t destport,int32_t ispaired)
{
char url[512],*retstr;
sprintf(url,"http://%s:%u/api/stats/psock?ispaired=%d",destip,destport,ispaired);
sprintf(url,"http://%s:%u/api/stats/psock?ispaired=%d",destip,destport-1,ispaired);
//return(LP_issue_curl("psock",destip,destport,url));
retstr = issue_curlt(url,LP_HTTP_TIMEOUT*3);
printf("issue_LP_psock got (%s) from %s\n",retstr,destip);
@ -636,6 +812,8 @@ uint16_t LP_psock_get(char *connectaddr,char *publicaddr,int32_t ispaired)
safecopy(publicaddr,addr,128);
if ( (addr= jstr(retjson,"connectaddr")) != 0 )
safecopy(connectaddr,addr,128);
//if ( (addr= jstr(retjson,"connectaddr2")) != 0 )
// safecopy(connectaddr2,addr,128);
if ( publicaddr[0] != 0 && connectaddr[0] != 0 )
publicport = juint(retjson,"publicport");
free_json(retjson);
@ -653,6 +831,7 @@ int32_t LP_initpublicaddr(void *ctx,uint16_t *mypullportp,char *publicaddr,char
{
int32_t nntype,pullsock,timeout; char bindaddr[128],connectaddr[128];
*mypullportp = mypullport;
//connectaddr2[0] = 0;
if ( ispaired == 0 )
{
if ( LP_canbind != 0 )
@ -663,6 +842,7 @@ int32_t LP_initpublicaddr(void *ctx,uint16_t *mypullportp,char *publicaddr,char
{
nanomsg_transportname(0,publicaddr,myipaddr,mypullport);
nanomsg_transportname(1,bindaddr,myipaddr,mypullport);
//nanomsg_transportname2(1,bindaddr2,myipaddr,mypullport);
}
else
{
@ -690,7 +870,13 @@ int32_t LP_initpublicaddr(void *ctx,uint16_t *mypullportp,char *publicaddr,char
{
printf("bind to %s error for %s: %s\n",connectaddr,publicaddr,nn_strerror(nn_errno()));
exit(-1);
} else printf("nntype.%d NN_PAIR.%d connect to %s connectsock.%d\n",nntype,NN_PAIR,connectaddr,pullsock);
}
else
{
//if ( connectaddr2[0] != 0 && nn_connect(pullsock,connectaddr2) > 0 )
// printf("%s ",connectaddr2);
printf("nntype.%d NN_PAIR.%d connect to %s connectsock.%d\n",nntype,NN_PAIR,connectaddr,pullsock);
}
}
else
{
@ -699,6 +885,8 @@ int32_t LP_initpublicaddr(void *ctx,uint16_t *mypullportp,char *publicaddr,char
printf("bind to %s error for %s: %s\n",bindaddr,publicaddr,nn_strerror(nn_errno()));
exit(-1);
}
//if ( nn_bind(pullsock,bindaddr2) >= 0 )
// printf("bound to %s\n",bindaddr2);
}
timeout = 1;
nn_setsockopt(pullsock,NN_SOL_SOCKET,NN_RCVTIMEO,&timeout,sizeof(timeout));

1422
iguana/exchanges/LP_ordermatch.c

File diff suppressed because it is too large

162
iguana/exchanges/LP_peers.c

@ -31,13 +31,13 @@ struct LP_peerinfo *LP_peerfind(uint32_t ipbits,uint16_t port)
cJSON *LP_peerjson(struct LP_peerinfo *peer)
{
cJSON *item = cJSON_CreateObject();
jaddstr(item,"ipaddr",peer->ipaddr);
jaddstr(item,"isLP",peer->ipaddr);
jaddnum(item,"port",peer->port);
if ( strcmp(peer->ipaddr,LP_myipaddr) == 0 )
{
jaddnum(item,"session",LP_sessionid);
if ( LP_mypeer != 0 )
jaddnum(item,"numutxos",LP_mypeer->numutxos);
jaddnum(item,"session",G.LP_sessionid);
//if ( LP_mypeer != 0 )
// jaddnum(item,"numutxos",LP_mypeer->numutxos);
} else jaddnum(item,"session",peer->sessionid);
//jaddnum(item,"profit",peer->profitmargin);
return(item);
@ -49,14 +49,15 @@ char *LP_peers()
HASH_ITER(hh,LP_peerinfos,peer,tmp)
{
//if ( peer->errors < LP_MAXPEER_ERRORS )
if ( peer->isLP != 0 )
jaddi(peersjson,LP_peerjson(peer));
}
return(jprint(peersjson,1));
}
struct LP_peerinfo *LP_addpeer(struct LP_peerinfo *mypeer,int32_t mypubsock,char *ipaddr,uint16_t port,uint16_t pushport,uint16_t subport,int32_t numpeers,int32_t numutxos,uint32_t sessionid)
struct LP_peerinfo *LP_addpeer(struct LP_peerinfo *mypeer,int32_t mypubsock,char *ipaddr,uint16_t port,uint16_t pushport,uint16_t subport,int32_t isLP,uint32_t sessionid)
{
uint32_t ipbits; int32_t pushsock,subsock,timeout; char checkip[64],pushaddr[64],subaddr[64]; struct LP_peerinfo *peer = 0;
uint32_t ipbits; int32_t valid,pushsock,subsock,timeout; char checkip[64],pushaddr[64],subaddr[64]; struct LP_peerinfo *peer = 0;
#ifdef LP_STRICTPEERS
if ( strncmp("5.9.253",ipaddr,strlen("5.9.253")) != 0 )
return(0);
@ -67,6 +68,8 @@ struct LP_peerinfo *LP_addpeer(struct LP_peerinfo *mypeer,int32_t mypubsock,char
{
if ( (peer= LP_peerfind(ipbits,port)) != 0 )
{
if ( isLP != 0 )
peer->isLP = isLP;
/*if ( numpeers > peer->numpeers )
peer->numpeers = numpeers;
if ( numutxos > peer->numutxos )
@ -76,22 +79,34 @@ struct LP_peerinfo *LP_addpeer(struct LP_peerinfo *mypeer,int32_t mypubsock,char
}
else
{
//printf("addpeer (%s:%u) pushport.%u subport.%u\n",ipaddr,port,pushport,subport);
peer = calloc(1,sizeof(*peer));
if ( strcmp(peer->ipaddr,LP_myipaddr) == 0 )
peer->sessionid = LP_sessionid;
peer->sessionid = G.LP_sessionid;
else peer->sessionid = sessionid;
peer->pushsock = peer->subsock = pushsock = subsock = -1;
strcpy(peer->ipaddr,ipaddr);
//peer->profitmargin = profitmargin;
peer->ipbits = ipbits;
peer->isLP = isLP;
peer->port = port;
peer->ip_port = ((uint64_t)port << 32) | ipbits;
if ( pushport != 0 && subport != 0 && (pushsock= nn_socket(AF_SP,NN_PUSH)) >= 0 )
{
nanomsg_transportname(0,pushaddr,peer->ipaddr,pushport);
//nanomsg_transportname2(0,pushaddr2,peer->ipaddr,pushport);
valid = 0;
if ( nn_connect(pushsock,pushaddr) >= 0 )
valid++;
//if ( nn_connect(pushsock,pushaddr2) >= 0 )
// valid++;
if ( valid > 0 )
{
timeout = 1;
nn_setsockopt(pushsock,NN_SOL_SOCKET,NN_SNDTIMEO,&timeout,sizeof(timeout));
//maxsize = 2 * 1024 * 1024;
//nn_setsockopt(pushsock,NN_SOL_SOCKET,NN_SNDBUF,&maxsize,sizeof(maxsize));
printf("connected to push.(%s) %d\n",pushaddr,pushsock);
printf("connected to push.(%s) pushsock.%d valid.%d | ",pushaddr,pushsock,valid);
peer->connected = (uint32_t)time(NULL);
peer->pushsock = pushsock;
if ( (subsock= nn_socket(AF_SP,NN_SUB)) >= 0 )
@ -100,38 +115,49 @@ struct LP_peerinfo *LP_addpeer(struct LP_peerinfo *mypeer,int32_t mypubsock,char
nn_setsockopt(subsock,NN_SOL_SOCKET,NN_RCVTIMEO,&timeout,sizeof(timeout));
nn_setsockopt(subsock,NN_SUB,NN_SUB_SUBSCRIBE,"",0);
nanomsg_transportname(0,subaddr,peer->ipaddr,subport);
//nanomsg_transportname2(0,subaddr2,peer->ipaddr,subport);
valid = 0;
if ( nn_connect(subsock,subaddr) >= 0 )
valid++;
//if ( nn_connect(subsock,subaddr2) >= 0 )
// valid++;
if ( valid > 0 )
{
peer->subsock = subsock;
printf("connected to sub.(%s) %d\n",subaddr,peer->subsock);
} else nn_close(subsock);
printf("connected to sub.(%s) subsock.%d valid.%d\n",subaddr,peer->subsock,valid);
}
else
{
printf("error connecting to subsock.%d (%s)\n",subsock,subaddr);
nn_close(subsock);
subsock = -1;
}
}
}
else
{
nn_close(pushsock);
pushsock = -1;
printf("error connecting to push.(%s)\n",pushaddr);
}
} else printf("%s pushport.%u subport.%u pushsock.%d\n",ipaddr,pushport,subport,pushsock);
//peer->profitmargin = profitmargin;
peer->ipbits = ipbits;
peer->port = port;
peer->ip_port = ((uint64_t)port << 32) | ipbits;
if ( peer->pushsock >= 0 && peer->subsock >= 0 )
{
//printf("add peer %s\n",peer->ipaddr);
portable_mutex_lock(&LP_peermutex);
HASH_ADD(hh,LP_peerinfos,ip_port,sizeof(peer->ip_port),peer);
if ( mypeer != 0 )
{
mypeer->numpeers++;
printf("_LPaddpeer %s -> numpeers.%d mypubsock.%d other.(%d %d)\n",ipaddr,mypeer->numpeers,mypubsock,numpeers,numutxos);
printf("_LPaddpeer %s -> numpeers.%d mypubsock.%d other.(%d)\n",ipaddr,mypeer->numpeers,mypubsock,isLP);
} else peer->numpeers = 1; // will become mypeer
portable_mutex_unlock(&LP_peermutex);
if ( IAMLP != 0 && mypubsock >= 0 )
{
struct iguana_info *coin,*ctmp; bits256 zero; char *msg,busaddr[64];
msg = jprint(LP_peerjson(peer),1);
memset(zero.bytes,0,sizeof(zero));
struct iguana_info *coin,*ctmp; char busaddr[64]; //
//memset(zero.bytes,0,sizeof(zero));
//LP_send(mypubsock,msg,(int32_t)strlen(msg)+1,1);
LP_broadcast_message(mypubsock,"","",zero,msg);
//LP_reserved_msg(0,"","",zero,jprint(LP_peerjson(peer),1));
if ( 0 )
{
HASH_ITER(hh,LP_coins,coin,ctmp)
@ -144,6 +170,7 @@ struct LP_peerinfo *LP_addpeer(struct LP_peerinfo *mypeer,int32_t mypubsock,char
}
}
}
} else printf("%s invalid pushsock.%d or subsock.%d\n",peer->ipaddr,peer->pushsock,peer->subsock);
}
} else printf("LP_addpeer: checkip.(%s) vs (%s)\n",checkip,ipaddr);
return(peer);
@ -179,75 +206,76 @@ int32_t LP_coinbus(uint16_t coin_busport)
return(bussock);
}
int32_t LP_peersparse(struct LP_peerinfo *mypeer,int32_t mypubsock,char *destipaddr,uint16_t destport,char *retstr,uint32_t now)
void LP_peer_recv(char *ipaddr,int32_t ismine)
{
struct LP_peerinfo *peer; uint32_t argipbits; char *argipaddr; uint16_t argport,pushport,subport; cJSON *array,*item; int32_t i,n=0;
if ( (array= cJSON_Parse(retstr)) != 0 )
struct LP_peerinfo *peer;
if ( (peer= LP_peerfind((uint32_t)calc_ipbits(ipaddr),RPC_port)) != 0 )
{
if ( (n= cJSON_GetArraySize(array)) > 0 )
peer->numrecv++;
if ( ismine != 0 )
peer->recvtime = (uint32_t)time(NULL);
}
}
int32_t LP_numpeers()
{
struct LP_peerinfo *peer,*tmp; int32_t numpeers = 0;
HASH_ITER(hh,LP_peerinfos,peer,tmp)
{
for (i=0; i<n; i++)
if ( peer->isLP != 0 )
numpeers++;
}
return(numpeers);
}
uint16_t LP_randpeer(char *destip)
{
struct LP_peerinfo *peer,*tmp; uint16_t port = 0; int32_t n,r,numpeers = 0;
destip[0] = 0;
numpeers = LP_numpeers();
if ( numpeers > 0 )
{
item = jitem(array,i);
if ( (argipaddr= jstr(item,"ipaddr")) != 0 && (argport= juint(item,"port")) != 0 )
r = LP_rand() % numpeers;
n = 0;
HASH_ITER(hh,LP_peerinfos,peer,tmp)
{
if ( (pushport= juint(item,"push")) == 0 )
pushport = argport + 1;
if ( (subport= juint(item,"sub")) == 0 )
subport = argport + 2;
argipbits = (uint32_t)calc_ipbits(argipaddr);
if ( (peer= LP_peerfind(argipbits,argport)) == 0 )
if ( peer->isLP != 0 )
{
peer = LP_addpeer(mypeer,mypubsock,argipaddr,argport,pushport,subport,jint(item,"numpeers"),jint(item,"numutxos"),juint(item,"session"));
}
if ( peer != 0 )
if ( n++ == r )
{
peer->lasttime = now;
if ( strcmp(argipaddr,destipaddr) == 0 && destport == argport && peer->numpeers != n )
peer->numpeers = n;
strcpy(destip,peer->ipaddr);
port = peer->port;
break;
}
}
}
}
free_json(array);
}
return(n);
return(port);
}
void LP_peersquery(struct LP_peerinfo *mypeer,int32_t mypubsock,char *destipaddr,uint16_t destport,char *myipaddr,uint16_t myport)
uint16_t LP_rarestpeer(char *destip)
{
char *retstr; struct LP_peerinfo *peer,*tmp; uint32_t now,flag = 0;
peer = LP_peerfind((uint32_t)calc_ipbits(destipaddr),destport);
if ( (retstr= issue_LP_getpeers(destipaddr,destport,myipaddr,myport,mypeer!=0?mypeer->numpeers:0,mypeer!=0?mypeer->numutxos:0)) != 0 )
{
//printf("got.(%s)\n",retstr);
struct LP_peerinfo *peer,*tmp,*rarest = 0; int32_t iter; uint32_t now;
now = (uint32_t)time(NULL);
LP_peersparse(mypeer,mypubsock,destipaddr,destport,retstr,now);
free(retstr);
if ( IAMLP != 0 )
destip[0] = 0;
for (iter=0; iter<2; iter++)
{
HASH_ITER(hh,LP_peerinfos,peer,tmp)
{
if ( peer->lasttime != now )
if ( iter == 0 && peer->recvtime < now-3600*24 )
continue;
if ( peer->isLP != 0 )
{
printf("{%s:%u}.%d ",peer->ipaddr,peer->port,peer->lasttime - now);
flag++;
if ( (retstr= issue_LP_notify(destipaddr,destport,peer->ipaddr,peer->port,peer->numpeers,0,peer->sessionid)) != 0 )
free(retstr);
if ( rarest == 0 || peer->numrecv < rarest->numrecv )
rarest = peer;
}
}
if ( flag != 0 )
printf(" <- missing peers\n");
}
if ( rarest != 0 )
break;
}
if ( rarest == 0 )
LP_randpeer(destip);
else strcpy(destip,rarest->ipaddr);
return(rarest != 0 ? rarest->port : RPC_port);
}
int32_t LP_numpeers()
{
struct LP_peerinfo *peer,*tmp; int32_t numpeers = 0;
HASH_ITER(hh,LP_peerinfos,peer,tmp)
{
numpeers++;
}
return(numpeers);
}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save