Browse Source

Merge pull request #1 from jl777/dev

Dev
dev
Satinder Grewal 7 years ago
committed by GitHub
parent
commit
1db6d0af0d
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 225
      .gitignore
  2. 22
      .vscode/launch.json
  3. 22
      MyTemplate.vstemplate
  4. BIN
      OSlibs/android/lib/libcrypto.so
  5. BIN
      OSlibs/android/lib/libcurl.a
  6. BIN
      OSlibs/android/lib/libssl.so
  7. BIN
      OSlibs/ios/lib/libcrypto.a
  8. BIN
      OSlibs/ios/lib/libcurl.a
  9. BIN
      OSlibs/ios/lib/libssl.a
  10. BIN
      OSlibs/osx/libcrypto.a
  11. BIN
      OSlibs/osx/libcurl.a
  12. BIN
      OSlibs/osx/libgmp.a
  13. BIN
      OSlibs/osx/libsecp256k1.a
  14. BIN
      OSlibs/osx/libssl.a
  15. BIN
      OSlibs/win/libcrypto.a
  16. BIN
      OSlibs/win/libcurl.a
  17. BIN
      OSlibs/win/libcurl.exp
  18. BIN
      OSlibs/win/libcurl.lib
  19. BIN
      OSlibs/win/libcurldll.a
  20. BIN
      OSlibs/win/libpthreadGC2.a
  21. BIN
      OSlibs/win/libpthreadGC2_64.a
  22. BIN
      OSlibs/win/libsecp256k1.a
  23. BIN
      OSlibs/win/libssl.a
  24. 61
      OSlibs/win/mingw.h
  25. BIN
      OSlibs/win/nanomsg.lib
  26. BIN
      OSlibs/win/pthreadGC2.dll
  27. BIN
      OSlibs/win/pthreadGC2_64.dll
  28. BIN
      OSlibs/win/release/nanomsg.lib
  29. BIN
      OSlibs/win/release/pthreadVC2.lib
  30. BIN
      OSlibs/win/x64/libcurl.lib
  31. BIN
      OSlibs/win/x64/libpthreadGC2.a
  32. BIN
      OSlibs/win/x64/nanomsg.lib
  33. BIN
      OSlibs/win/x64/release/libcurl.exp
  34. BIN
      OSlibs/win/x64/release/libcurl.lib
  35. BIN
      OSlibs/win/x64/release/nanomsg.lib
  36. 145
      README.md
  37. 25
      README_decker.md
  38. 40
      ReadMe.txt
  39. BIN
      __TemplateIcon.ico
  40. 1160
      basilisk/basilisk copy.c
  41. 1477
      basilisk/basilisk.c
  42. 89
      basilisk/basilisk.h
  43. 118
      basilisk/basilisk_CMD.c
  44. 393
      basilisk/basilisk_DEX.c
  45. 554
      basilisk/basilisk_MSG.c
  46. 797
      basilisk/basilisk_bitcoin.c
  47. 72
      basilisk/basilisk_ping.c
  48. 4048
      basilisk/basilisk_swap.c
  49. 387
      basilisk/basilisk_tradebot.c
  50. 405
      basilisk/basilisk_vote.c
  51. 772
      basilisk/jumblr.c
  52. 685
      basilisk/smartaddress.c
  53. 1072
      basilisk/tradebots_SVM.h
  54. 1237
      basilisk/tradebots_liquidity.c
  55. 108
      basilisk/tradebots_marketmaker.c
  56. 128
      crypto777/OS_nonportable.c
  57. 43
      crypto777/OS_portable.c
  58. 110
      crypto777/OS_portable.h
  59. 33
      crypto777/OS_time.c
  60. 7
      crypto777/SaM.c
  61. 157
      crypto777/bitcoind_RPC.c
  62. 156
      crypto777/cJSON.c
  63. 6
      crypto777/crypto777.sources
  64. 38
      crypto777/curve25519.c
  65. 4
      crypto777/hmac/sha224.c
  66. 86
      crypto777/hmac/sha256.c
  67. 8
      crypto777/hmac/tomcrypt_hash.h
  68. 26
      crypto777/hmac_sha512.c
  69. 314
      crypto777/iguana_OS.c
  70. 8
      crypto777/iguana_serdes.c
  71. 241
      crypto777/iguana_utils.c
  72. 11
      crypto777/inet.c
  73. 5
      crypto777/jpeg/jconfig.h
  74. 1
      crypto777/jpeg/jmemsys.h
  75. 8
      crypto777/jpeg/unix/jmemname.c
  76. 2
      crypto777/m_LP
  77. 30
      crypto777/m_LP_StaticNanoMsg
  78. 4
      crypto777/m_osx_release
  79. 75
      crypto777/nanosrc/aio/usock_posix.c
  80. 13
      crypto777/nanosrc/aio/usock_posix.c_dev
  81. 4
      crypto777/nanosrc/aio/usock_posix.h
  82. 2
      crypto777/nanosrc/aio/usock_win.c
  83. 50
      crypto777/nanosrc/aio/worker_posix.c
  84. 136
      crypto777/nanosrc/core/global.c
  85. 9
      crypto777/nanosrc/core/pipe.c
  86. 15
      crypto777/nanosrc/core/sock.c
  87. 8
      crypto777/nanosrc/devices/tcpmuxd.c
  88. 1
      crypto777/nanosrc/nn.h
  89. 14
      crypto777/nanosrc/nn_config.h
  90. 3
      crypto777/nanosrc/protocols/pipeline/xpush.c
  91. 2
      crypto777/nanosrc/protocols/reqrep/xreq.c
  92. 7
      crypto777/nanosrc/protocols/utils/lb.c
  93. 4
      crypto777/nanosrc/protocols/utils/priolist.c
  94. 3
      crypto777/nanosrc/protocols/utils/priolist.h
  95. 6
      crypto777/nanosrc/tests/testutil.h
  96. 4
      crypto777/nanosrc/transports/ipc/bipc.c
  97. 5
      crypto777/nanosrc/transports/ipc/cipc.c
  98. 4
      crypto777/nanosrc/transports/ipc/ipc.c
  99. 4
      crypto777/nanosrc/transports/tcpmux/btcpmux.c
  100. 6
      crypto777/nanosrc/transports/utils/tcpmux.c

225
.gitignore

@ -1,11 +1,7 @@
x64
*.o
agents/iguana.exe
Debug/*
iguana/pnacl/Release/iguana_unstripped.pexe
@ -37,3 +33,220 @@ agents/*
iguana/confs/BTC_hdrs.txt
deprecated/.DS_Store
.DS_Store
iguana/help/.tmpmarker
iguana/genesis/.tmpmarker
iguana/help.json
iguana/autoAPI.md
iguana/basilisk.o-2ad8cb38
=======
*.pbxproj
iguana/tmp/.tmpmarker
iguana/SVM/rawfeatures/.tmpmarker
iguana/DB/.tmpmarker
iguana/DB/TRANSACTIONS/.tmpmarker
iguana/DB/purgeable/.tmpmarker
iguana/DB/purgeable/BTCD/.tmpmarker
iguana/DB/purgeable/BTC/.tmpmarker
iguana/DB/ECB/.tmpmarker
iguana/genesis/.tmpmarker
iguana/help/.tmpmarker
iguana/SVM/.tmpmarker
iguana/SVM/models/.tmpmarker
SuperNET.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/xcschememanagement.plist
SuperNET.xcodeproj/xcuserdata/mac.xcuserdatad/xcschemes/SuperNET.xcscheme
iguana/DB/BTC/.tmpmarker
*.vouts
iguana/DB/BTC/vouts/.tmpmarker
iguana/DB/BTC/accounts/.tmpmarker
iguana/DB/BTC/spends/.tmpmarker
iguana/DB/BTC/validated/.tmpmarker
iguana/DB/KMD/.tmpmarker
iguana/DB/KMD/accounts/.tmpmarker
iguana/DB/KMD/spends/.tmpmarker
iguana/DB/KMD/validated/.tmpmarker
iguana/DB/KMD/vouts/.tmpmarker
iguana/DB/purgeable/KMD/.tmpmarker
iguana/DB/ro/.tmpmarker
iguana/DB/ro/BTC/.tmpmarker
iguana/DB/ro/KMD/.tmpmarker
iguana/confs/682c279f7b01b96aee50f11b327bf6c0a3d3481a23a9a265f0796e9bb3765b24
iguana/confs/682c279f7b01b96aee50f11b327bf6c0a3d3481a23a9a265f0796e9bb3765b24.old
iguana/confs/83cb074c13289a91a0cd50a8e6932b2237d1533ec1cbff56ab3d9b1d37f8df35
iguana/confs/83cb074c13289a91a0cd50a8e6932b2237d1533ec1cbff56ab3d9b1d37f8df35.old
iguana/tmp/BTC/.tmpmarker
iguana/tmp/BTC/0/.tmpmarker
iguana/tmp/BTC/0/0/.tmpmarker
iguana/tmp/BTC/peers.txt
iguana/tmp/BTC/RT/.tmpmarker
iguana/tmp/KMD/.tmpmarker
iguana/tmp/KMD/0/.tmpmarker
iguana/tmp/KMD/0/0/.tmpmarker
iguana/tmp/KMD/peers.txt
iguana/tmp/KMD/RT/.tmpmarker
*.xcworkspacedata
*.xcuserstate
includes/iguana_apideclares copy.h
iguana/iguana_tx.o-4b5de8fe
iguana/confs/c6faccf6b625bbb826f47b77c3274e985db7b0a47d435f32bea2f7f3724cdd17
iguana/confs/c6faccf6b625bbb826f47b77c3274e985db7b0a47d435f32bea2f7f3724cdd17.old
iguana/marketmaker
iguana/secp256k1.o-501dfbfe
iguana/confs/cc577d22ca76351d495f147b470103392b5f2ab0948e45608623a7d9728e2c6f
iguana/confs/cc577d22ca76351d495f147b470103392b5f2ab0948e45608623a7d9728e2c6f.old
iguana/DB/DEX.log
iguana/iguana_notary.o-54f98cc3
iguana/basilisk.o-2ad8cb38
iguana/pangea_hand.o-02d25ec3
iguana/confs/4dfa301d0adf61f0ec08e4d4cb4444f4fc377f45f5d6b1da0814033920d72353
iguana/help.json
iguana/index7778.html
iguana/DB/KMD/utxo.dat
iguana/unparsed.txt
iguana/unparsed.txt
iguana/unparsed.txt
iguana/DB/SWAPS/.tmpmarker
iguana/DB/SWAPS/list
iguana/DB/SWAPS/15974209-4014252807
iguana/iguana777.o-0cc60f50
iguana/DB/SWAPS/667293271-3414303895
iguana/DB/SWAPS/667293271-3414303895.swap
iguana/DB/SWAPS/548227681-1452262678.swap
iguana/DB/SWAPS/548227681-1452262678
*.bobdeposit
*.bobpayment
*.bobreclaim
*.bobrefund
*.swap
iguana/DB/SWAPS/1268007736-526212866
iguana/DB/SWAPS/3111936786-3185288772
iguana/DB/SWAPS/3368214189-2405641584
iguana/DB/SWAPS/1133671270-1840176506
iguana/DB/SWAPS/467927158-3437055573
iguana/DB/SWAPS/270159951-1269722638
iguana/DB/SWAPS/244991424-1008712592
iguana/confs/1cc0270abba7f4463a3dcb9908b9d875691a6773fe3cc1b4302233ed76665300
iguana/autoAPI.md
iguana/confs/5228bcea7ae2515a29c3844673de6ee2acba53bf45724744a00ff4306f192912
iguana/confs/630929d976025fafde221c7358eb5805f4359bad3c6b8bd50ad3f6e0a9b5ce78
iguana/confs/5f3283a017c31e52443d61cb43944e2157f7c03eb12d701ebf4a35a695688e1f
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
*.RQ4z6KrMZeEnCSCsChv1ZoR9ExQitHjbpg
iguana/DB/instantdex_RQ4z6KrMZeEnCSCsChv1ZoR9ExQitHjbpg_append.json
iguana/DB/instantdex_RQ4z6KrMZeEnCSCsChv1ZoR9ExQitHjbpg.json

22
.vscode/launch.json

@ -0,0 +1,22 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "C++ Launch (Windows)",
"type": "cppvsdbg",
"request": "launch",
"program": "enter program name, for example ${workspaceRoot}/a.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceRoot}",
"environment": [],
"externalConsole": false
},
{
"name": "C++ Attach (Windows)",
"type": "cppvsdbg",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}

22
MyTemplate.vstemplate

@ -0,0 +1,22 @@
<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
<TemplateData>
<Name>iguana_template</Name>
<Description>&lt;No description available&gt;</Description>
<ProjectType>VC</ProjectType>
<ProjectSubType>
</ProjectSubType>
<SortOrder>1000</SortOrder>
<CreateNewFolder>true</CreateNewFolder>
<DefaultName>iguana_template</DefaultName>
<ProvideDefaultName>true</ProvideDefaultName>
<LocationField>Enabled</LocationField>
<EnableLocationBrowseButton>true</EnableLocationBrowseButton>
<Icon>__TemplateIcon.ico</Icon>
</TemplateData>
<TemplateContent>
<Project TargetFileName="ConsoleApplication3.vcxproj" File="ConsoleApplication3.vcxproj" ReplaceParameters="true">
<ProjectItem ReplaceParameters="false" TargetFileName="$projectname$.vcxproj.filters">ConsoleApplication3.vcxproj.filters</ProjectItem>
<ProjectItem ReplaceParameters="false" TargetFileName="ReadMe.txt">ReadMe.txt</ProjectItem>
</Project>
</TemplateContent>
</VSTemplate>

BIN
OSlibs/android/lib/libcrypto.so

Binary file not shown.

BIN
OSlibs/android/lib/libcurl.a

Binary file not shown.

BIN
OSlibs/android/lib/libssl.so

Binary file not shown.

BIN
OSlibs/ios/lib/libcrypto.a

Binary file not shown.

BIN
OSlibs/ios/lib/libcurl.a

Binary file not shown.

BIN
OSlibs/ios/lib/libssl.a

Binary file not shown.

BIN
OSlibs/osx/libcrypto.a

Binary file not shown.

BIN
OSlibs/osx/libcurl.a

Binary file not shown.

BIN
OSlibs/osx/libgmp.a

Binary file not shown.

BIN
OSlibs/osx/libsecp256k1.a

Binary file not shown.

BIN
OSlibs/osx/libssl.a

Binary file not shown.

BIN
OSlibs/win/libcrypto.a

Binary file not shown.

BIN
OSlibs/win/libcurl.a

Binary file not shown.

BIN
OSlibs/win/libcurl.exp

Binary file not shown.

BIN
OSlibs/win/libcurl.lib

Binary file not shown.

BIN
OSlibs/win/libcurldll.a

Binary file not shown.

BIN
OSlibs/win/libpthreadGC2.a

Binary file not shown.

BIN
OSlibs/win/libpthreadGC2_64.a

Binary file not shown.

BIN
OSlibs/win/libsecp256k1.a

Binary file not shown.

BIN
OSlibs/win/libssl.a

Binary file not shown.

61
OSlibs/win/mingw.h

@ -1,12 +1,17 @@
#ifndef MINGW_H
#define MINGW_H
#define ssize_t __int32
#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"
#ifndef NATIVE_WINDOWS
#define ENOTCONN WSAENOTCONN
#define EWOULDBLOCK WSAEWOULDBLOCK
#define ENOBUFS WSAENOBUFS
@ -18,25 +23,67 @@
#define EISCONN WSAEISCONN
#define ECONNREFUSED WSAECONNREFUSED
#define EHOSTUNREACH WSAEHOSTUNREACH
#endif
/* winsock doesn't feature poll(), so there is a version implemented
* in terms of select() in mingw.c. The following definitions
* are copied from linux man pages. A poll() macro is defined to
* call the version in mingw.c.
*/
#define POLLIN 0x0001 /* There is data to read */
#define POLLPRI 0x0002 /* There is urgent data to read */
#if defined(_M_X64)
/*
* when we are using WSAPoll() with window's struct pollfd struct
* we need to update the value for POLLIN and POLLOUT according to window's
* WSAPoll() return values
* @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
#define POLLIN 0x0001 /* There is data to read */
#define POLLOUT 0x0004 /* Writing now will not block */
#endif
#define POLLERR 0x0008 /* Error condition */
#define POLLHUP 0x0010 /* Hung up */
#define POLLNVAL 0x0020 /* Invalid request: fd not open */
struct pollfd {
SOCKET fd; /* file descriptor */
short events; /* requested events */
short revents; /* returned events */
};
/**
* we want to use mingw provided pollfd if and only if we are compiling this
* in windows 32bit but exclude it when we are compiling it in win 64
*
* @author - fadedreamz@gmail.com
* @remarks - #if (defined(_M_X64) || defined(__amd64__)) && defined(WIN32)
* is equivalent to #if defined(_M_X64) as _M_X64 is defined for MSVC only
*/
// [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)
/*
* we want to use the window's poll function if poll() is invoked in win64
* as we are using window's pollfd struct when we are using x64
* @author - fadedreamz@gmail.com
*/
#define poll(x, y, z) WSAPoll(x, y, z)
#else
#define poll(x, y, z) win32_poll(x, y, z)
#endif
/* These wrappers do nothing special except set the global errno variable if
* an error occurs (winsock doesn't do this by default). They set errno

BIN
OSlibs/win/nanomsg.lib

Binary file not shown.

BIN
OSlibs/win/pthreadGC2.dll

Binary file not shown.

BIN
OSlibs/win/pthreadGC2_64.dll

Binary file not shown.

BIN
OSlibs/win/release/nanomsg.lib

Binary file not shown.

BIN
OSlibs/win/release/pthreadVC2.lib

Binary file not shown.

BIN
OSlibs/win/x64/libcurl.lib

Binary file not shown.

BIN
OSlibs/win/x64/libpthreadGC2.a

Binary file not shown.

BIN
OSlibs/win/x64/nanomsg.lib

Binary file not shown.

BIN
OSlibs/win/x64/release/libcurl.exp

Binary file not shown.

BIN
OSlibs/win/x64/release/libcurl.lib

Binary file not shown.

BIN
OSlibs/win/x64/release/nanomsg.lib

Binary file not shown.

145
README.md

@ -1,13 +1,13 @@
#SuperNET Client "iguana"
# SuperNET Client "iguana"
OS | Build Status
-------------|------
Unix (Ubuntu 14.04) | [![Build Status](https://jenkinsmaster.sprnt.pw/buildStatus/icon?job=Unix-jl777)](https://jenkinsmaster.sprnt.pw/job/Unix-jl777)
Chrome | [![Build Status](https://jenkinsmaster.sprnt.pw/buildStatus/icon?job=PNaCl-jl777)](https://jenkinsmaster.sprnt.pw/job/PNaCl-jl777/)
Android | [![Build Status](https://jenkinsmaster.sprnt.pw/buildStatus/icon?job=Android)](https://jenkinsmaster.sprnt.pw/job/Android/)
iOS | [![Build Status](https://jenkinsmaster.sprnt.pw/buildStatus/icon?job=iOS)](https://jenkinsmaster.sprnt.pw/job/iOS/)
Windows 32 Bit | [![Build Status](https://jenkinsmaster.sprnt.pw/job/Win32/badge/icon)](https://jenkinsmaster.sprnt.pw/job/Win32/)
Windows 64 Bit | [![Build Status](https://jenkinsmaster.sprnt.pw/job/Win64-jl777/badge/icon)](https://jenkinsmaster.sprnt.pw/job/Win64-jl777/)
Unix (Ubuntu 14.04) | [![Build Status](https://jenkinsmaster.sprnt.pw/buildStatus/icon?job=iguana-unix-jl777-release-v0.1)](https://jenkinsmaster.sprnt.pw/job/iguana-unix-jl777-release-v0.1)
Chrome | [![Build Status](https://jenkinsmaster.sprnt.pw/buildStatus/icon?job=iguana-pnacl-jl777-release-v0.1)](https://jenkinsmaster.sprnt.pw/job/iguana-pnacl-jl777-release-v0.1/)
Android | [![Build Status](https://jenkinsmaster.sprnt.pw/buildStatus/icon?job=iguana-android-jl777-release-v0.1)](https://jenkinsmaster.sprnt.pw/job/iguana-android-jl777-release-v0.1/)
iOS | [![Build Status](https://jenkinsmaster.sprnt.pw/buildStatus/icon?job=iguana-ios-jl777-release-v0.1)](https://jenkinsmaster.sprnt.pw/job/iguana-ios-jl777-release-v0.1/)
Windows 32 Bit | [![Build Status](https://jenkinsmaster.sprnt.pw/job/iguana-win32-jl777-release-v0.1/badge/icon)](https://jenkinsmaster.sprnt.pw/job/iguana-win32-jl777-release-v0.1/)
Windows 64 Bit | [![Build Status](https://jenkinsmaster.sprnt.pw/job/iguana-win64-jl777-release-v0.1/badge/icon)](https://jenkinsmaster.sprnt.pw/job/iguana-win64-jl777-release-v0.1/)
docs.supernet.org | [![Build Status](https://jenkinsmaster.sprnt.pw/buildStatus/icon?job=docs.supernet.org-updating)](https://jenkinsmaster.sprnt.pw/job/docs.supernet.org-updating/)
---
@ -22,12 +22,12 @@ iguana: most efficient bitcoin core implementation that can simultaneously be fu
komodo: this is the top secret project I cant talk about publicly yet
> #TL;DR#
>
> ```sudo apt-get update; sudo apt-get install git build-essential; git clone https://github.com/jl777/SuperNET; cd SuperNET; ./m_onetime m_unix;```
>
> The above one line gets SuperNET installed, built and launched for unix.
>
> # TL;DR
>
> ```sudo apt-get update; sudo apt-get install git libcurl4-openssl-dev build-essential libnanomsg-dev; git clone https://github.com/jl777/SuperNET; cd SuperNET; ./m_onetime m_unix;```
>
> The above one line gets SuperNET installed, built and launched for unix.
>
> After that ```./m_unix``` updates to latest.
> *Continue below at "Running".*
@ -40,12 +40,14 @@ TOOL_DIR := /usr/local/gcc-4.8.0-qt-4.8.4-for-mingw32/win32-gcc/bin
MINGW := i586-mingw32
The above two definitions need to be changed to match the mingw install on your system. m_win32 and m_win64 just invokes the makefile in mingw32 and mingw64
##For chrome app##
## For chrome app
You need to make sure the nacl sdk is properly installed and you are able to build the examples.
Now you will need to get the external libs, which can be built from scratch using naclports or there use the reference builds of libcurl.a and libz.a in the SuperNET/crypto777/pnacl_libs. You can just copy those over into $(NACL_SDK_ROOT)/<pepper_dir>/lib/pnacl.
## For android
You have to build a native libnanomsg for android. This section is work in progress. Contact ca333@protonmail.ch for assistance on building latest iguana for android.
#ONETIME#
# ONETIME
Now you are ready to build.
I try to make the build process as simple as possible, so there are no `autoconf`, `autoreconf`, `configure`, `cmake`, `make`, to get properly installed and running and run, etc. You do need a C compiler, like gcc.
@ -80,12 +82,12 @@ To build just iguana, you can ```cd``` into SuperNET/iguana and do ```./m_unix``
```./m_clean``` will remove the files created from the building
#RUNNING#
# RUNNING
The native versions are command line applications: agents/iguana {JSON}
The chrome app pexe requires that the chrome is launched with a command line parameter (tools/chrome.localhost) and then browse to *http://127.0.0.1:7777* to see the pexe
#SUPERUGLYGUI#
# SUPERUGLYGUI
Once iguana is running, you can see the superuglyGUI at *http://127.0.0.1:7778/?method*
by submitting API calls using the forms, you will see it go to some specific URL. You can also do a programmatic GET request to ```http://127.0.0.1:7778/api/<path to apicall>```
@ -103,14 +105,14 @@ Internally, all paths convert the request into a standard SuperNET JSON request.
Another approach is to use the bitcoin RPC syntax via:
curl --url "http://127.0.0.1:7778" --data "{\"coin\":\"BTCD\",\"method\":\"getinfo\",\"params\":[]}"
the params:[] array is where the standard bitcoin parameters go, the only change that is needed is to specify the coin
alternatively {"agent":"SuperNET","method":"bitcoinrpc","coin":"BTCD"} will set the coin
alternatively {"agent":"SuperNET","method":"bitcoinrpc","coin":"BTCD"} will set the coin
to use for bitcoin RPC calls. this will suffice in single coin environments
curl --url "http://127.0.0.1:7778" --data "{\"agent\":\"iguana",\"method\":\"test\"}"
curl --url "http://127.0.0.1:7778/iguana/test" -> html page with results
curl --url "http://127.0.0.1:7778/api/iguana/test" -> just json text
http://127.0.0.1:7778 -> superugly GUI
http://127.0.0.1:7778/iguana/test
http://127.0.0.1:7778/iguana/test
http://127.0.0.1:7778/api/iguana/test
postCall('{"agent":"iguana","method":"test"}'}
iguana_JSON("{\"agent\":\"iguana",\"method\":\"test\"}"); -> direct C function call
@ -124,7 +126,7 @@ iguana can be invoked with a command line argument. if it is a name of a file, i
"exchanges" -> { "name":"<name of exchange>", ... }
"apikey", "apisecret", "userid", "tradepassword" these are as expected
"pollgap" -> gap between each access to exchange for getting prices
on OSX mksquashfs is not native, you will need to install fuse: https://osxfuse.github.io/ and a squashfs for mac: https://github.com/vasi/squashfuse
**********
@ -132,9 +134,9 @@ on OSX mksquashfs is not native, you will need to install fuse: https://osxfuse.
A Note on Installation from pebwindkraft at bitco.in
=======================
Though I had xcode installed, aclocal didn’t work. I installed homebrew, and then:
# brew install autoconf
# brew install automake
# brew install gmp
`brew install autoconf`
`brew install automake`
`brew install gmp`
2.) libsecp256
it complained, that libsecp256 was not there in includes, so I linked it.
@ -156,3 +158,100 @@ once jsoncmp is built, then ./test shows how to use it
the idea is to issue a curl command into a /tmp/file and then use jsoncmp to verify the exact value of one or more fields. it will print to stdout JSON with "error" or "result" and to stderr if there is an error
##### ../agents/iguana notary
0.Have iguana installed at http://wiki.supernet.org/wiki/How_To_Install_Iguana_on_Linux
also install nanomsg: sudo apt-get install libnanomsg-dev
ports 7775 will be used
cd Supernet/iguana -->
../agents/iguana
#In another SSH window:
cd Supernet/iguana/coins -->
./basilisk
1. Create an iguana wallet with encryptwallet and importprivkey into both komodod and bitcoind using the KMDwif and BTCwif in the encryptwallet result
curl --url "http://127.0.0.1:7778" --data "{\"agent\":\"bitcoinrpc\",\"method\":\"encryptwallet\",\"passphrase\":\"insert very secure password here\"}"
2. Go to SuperNET/iguana/
pico wp
curl --url "http://127.0.0.1:7778" --data "{\"method\":\"walletpassphrase\",\"params\":[\"same passphrase as above\", 9999999]}"
#Save the file then run the following command:
chmod +x wp
#Run the file
./wp
#Get the btcpubkey key from the output and give it to James.
3. create a text file SuperNET/iguana/myip.txt with just your ip address in it:
pico myip.txt
#Put your WAN IP of your node
4. create a text file with the user home dir in it:
pico userhome.txt
root
5. make a copy of SuperNET/iguana/wp -> SuperNET/iguana/wp_7776 and change port 7778 to port 7776
cp wp wp_7776
pico wp_7776
#Then change the port to 7776 from within the new file.
6. make a copy of SuperNET/iguana/tests/dpow_7776 to SuperNET/iguana/dpow_7776 and edit the pubkey to match your btcpubkey from above
cp dpow_7776 ../
pico dpow_7776
7. make sure system clock is synchronized
sudo service ntp stop
sudo ntpdate -s time.nist.gov
sudo service ntp start
Now things should be ready. To update and run notary node:
pkill iguana; ./m_LP; tests/notaryinit
##Build for OSX distribution##
Get OSX SDK 10.6 from https://github.com/ca333/MacOSX-SDKs/releases/tag/10.6
Unpack & move the .sdk folder to Xcodes SDK folder:
```cd DownloadDirectory```
```mv MacOSX10.6.sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/.```
If you are using Xcode > 7.3 add the new SDK to XCode by changing MinimumSDKVersion in your Info.plist:
```vi /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Info.plist```
Change the value to:
```
<key>MinimumSDKVersion</key>
<string>10.6</string>
```
Build crypto777 library and agents with OSX release makefile:
```./m_onetime m_osx_release```
Execute the OSX deploy script:
```
./osx_deploy.sh
```
The iguana binary and its linked libraries are in ```$HOME/tmp/iguana```.

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.

40
ReadMe.txt

@ -0,0 +1,40 @@
========================================================================
CONSOLE APPLICATION : ConsoleApplication3 Project Overview
========================================================================
AppWizard has created this ConsoleApplication3 application for you.
This file contains a summary of what you will find in each of the files that
make up your ConsoleApplication3 application.
ConsoleApplication3.vcxproj
This is the main project file for VC++ projects generated using an Application Wizard.
It contains information about the version of Visual C++ that generated the file, and
information about the platforms, configurations, and project features selected with the
Application Wizard.
ConsoleApplication3.vcxproj.filters
This is the filters file for VC++ projects generated using an Application Wizard.
It contains information about the association between the files in your project
and the filters. This association is used in the IDE to show grouping of files with
similar extensions under a specific node (for e.g. ".cpp" files are associated with the
"Source Files" filter).
ConsoleApplication3.cpp
This is the main application source file.
/////////////////////////////////////////////////////////////////////////////
Other standard files:
StdAfx.h, StdAfx.cpp
These files are used to build a precompiled header (PCH) file
named ConsoleApplication3.pch and a precompiled types file named StdAfx.obj.
/////////////////////////////////////////////////////////////////////////////
Other notes:
AppWizard uses "TODO:" comments to indicate parts of the source code you
should add to or customize.
/////////////////////////////////////////////////////////////////////////////

BIN
__TemplateIcon.ico

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

1160
basilisk/basilisk copy.c

File diff suppressed because it is too large

1477
basilisk/basilisk.c

File diff suppressed because it is too large

89
basilisk/basilisk.h

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -16,20 +16,20 @@
#ifndef H_BASILISK_H
#define H_BASILISK_H
#define BASILISK_DISABLETX
//#define BASILISK_DISABLESENDTX
//#define BASILISK_DISABLEWAITTX
#include "../iguana/iguana777.h"
#define BASILISK_TIMEOUT 30000
#define BASILISK_TIMEOUT 3000
#define BASILISK_MINFANOUT 8
#define BASILISK_MAXFANOUT 64
#define BASILISK_DEFAULTDIFF 0x1effffff
#define BASILISK_MAXRELAYS 64
#define BASILISK_DEXDURATION 180
#define BASILISK_MSGDURATION 60
#define BASILISK_DEXDURATION 300
#define BASILISK_MSGDURATION 30
#define BASILISK_AUCTION_DURATION 5
#define BASILISK_MAXFUTUREBLOCK 60
//#define BASILISK_MAXBLOCKLAG 600
#define BASILISK_HDROFFSET ((int32_t)(sizeof(bits256)+sizeof(struct iguana_msghdr)+sizeof(uint32_t)))
#define INSTANTDEX_DECKSIZE 1000
@ -37,38 +37,58 @@
#define INSTANTDEX_INSURANCEDIV 777
#define INSTANTDEX_PUBKEY "03bc2c7ba671bae4a6fc835244c9762b41647b9827d4780a89a949b984a8ddcc06"
#define INSTANTDEX_RMD160 "ca1e04745e8ca0c60d8c5881531d51bec470743f"
#define JUMBLR_RMD160 "5177f8b427e5f47342a4b8ab5dac770815d4389e"
#define TIERNOLAN_RMD160 "daedddd8dbe7a2439841ced40ba9c3d375f98146"
#define INSTANTDEX_BTC "1KRhTPvoxyJmVALwHFXZdeeWFbcJSbkFPu"
#define INSTANTDEX_BTCD "RThtXup6Zo7LZAi8kRWgjAyi1s4u6U9Cpf"
struct basilisk_rawtx
#define JUMBLR_INCR 99.65
#define JUMBLR_FEE 0.001
#define JUMBLR_TXFEE 0.01
struct basilisk_swap;
struct basilisk_rawtxinfo
{
char destaddr[64],coinstr[16];
bits256 txid,signedtxid,actualtxid;
struct iguana_msgtx msgtx;
struct iguana_info *coin;
uint64_t amount,change,inputsum;
int32_t redeemlen,datalen,completed,vintype,vouttype,numconfirms,spendlen,secretstart,suppress_pubkeys;
uint32_t locktime;
char destaddr[64],name[32];
uint8_t addrtype,pubkey33[33],spendscript[512],redeemscript[1024],rmd160[20];
uint8_t *txbytes,extraspace[1024];
uint32_t locktime,crcs[2];
uint8_t addrtype,pubkey33[33],rmd160[20];
};
struct basilisk_rawtx
{
char name[32];
struct iguana_msgtx msgtx;
struct basilisk_rawtxinfo I;
struct iguana_info *coin;
char vinstr[8192],p2shaddr[64];
cJSON *vins;
uint8_t txbytes[16384],spendscript[512],redeemscript[1024],extraspace[4096];
};
struct basilisk_swap
struct basilisk_swapinfo
{
struct basilisk_request req;
struct supernet_info *myinfo; bits256 myhash,otherhash;
uint32_t statebits,otherstatebits,started,expiration,finished,dead,reftime,locktime;
struct iguana_info *bobcoin,*alicecoin; char bobstr[64],alicestr[64];
int32_t bobconfirms,aliceconfirms,iambob,reclaimed;
char bobstr[64],alicestr[64];
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;
bits256 privkeys[INSTANTDEX_DECKSIZE],myprivs[2],mypubs[2],otherpubs[2],pubA0,pubA1,pubB0,pubB1,privAm,pubAm,privBn,pubBn;
uint64_t otherdeck[INSTANTDEX_DECKSIZE][2],deck[INSTANTDEX_DECKSIZE][2];
int32_t choosei,otherchoosei,cutverified,otherverifiedcut,numpubs,havestate,otherhavestate;
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];
int32_t choosei,otherchoosei,cutverified,otherverifiedcut,numpubs,havestate,otherhavestate,pad2;
uint8_t secretAm[20],secretBn[20];
struct basilisk_rawtx bobdeposit,bobpayment,alicepayment,myfee,otherfee,aliceclaim,alicespend,bobreclaim,bobspend,bobrefund,alicereclaim;
uint8_t secretAm256[32],secretBn256[32];
uint8_t userdata_aliceclaim[256],userdata_aliceclaimlen;
uint8_t userdata_alicereclaim[256],userdata_alicereclaimlen;
uint8_t userdata_alicespend[256],userdata_alicespendlen;
uint8_t userdata_bobspend[256],userdata_bobspendlen;
uint8_t userdata_bobreclaim[256],userdata_bobreclaimlen;
uint8_t userdata_bobrefund[256],userdata_bobrefundlen;
};
struct basilisk_value { bits256 txid; int64_t value; int32_t height; int16_t vout; char coinaddr[64]; };
@ -76,8 +96,8 @@ struct basilisk_value { bits256 txid; int64_t value; int32_t height; int16_t vou
struct basilisk_item
{
struct queueitem DL; UT_hash_handle hh;
double expiration; cJSON *retarray;
uint32_t submit,finished,basilisktag,numresults,numsent,numrequired,nBits;
double expiration,finished; cJSON *results[64];
uint32_t submit,basilisktag,numresults,numsent,numrequired,nBits,duration;
char symbol[32],CMD[4],remoteaddr[64],*retstr;
};
@ -85,8 +105,8 @@ struct basilisk_item
struct basilisk_message
{
struct queueitem DL; UT_hash_handle hh;
uint32_t datalen,expiration,duration;
uint8_t key[BASILISK_KEYSIZE],keylen;
uint32_t expiration,duration,datalen;
uint8_t keylen,broadcast,key[BASILISK_KEYSIZE];
uint8_t data[];
};
@ -102,7 +122,7 @@ void basilisk_msgprocess(struct supernet_info *myinfo,void *addr,uint32_t sender
int32_t basilisk_sendcmd(struct supernet_info *myinfo,char *destipaddr,char *type,uint32_t *basilisktagp,int32_t encryptflag,int32_t delaymillis,uint8_t *data,int32_t datalen,int32_t fanout,uint32_t nBits); // data must be offset by sizeof(iguana_msghdr)+sizeof(basilisktag)
void basilisks_init(struct supernet_info *myinfo);
void basilisk_p2p(void *myinfo,void *_addr,char *ipaddr,uint8_t *data,int32_t datalen,char *type,int32_t encrypted);
void basilisk_p2p(struct supernet_info *myinfo,struct iguana_info *coin,struct iguana_peer *addr,char *senderip,uint8_t *data,int32_t datalen,char *type,int32_t encrypted);
uint8_t *basilisk_jsondata(int32_t extraoffset,uint8_t **ptrp,uint8_t *space,int32_t spacesize,int32_t *datalenp,char *symbol,cJSON *sendjson,uint32_t basilisktag);
uint8_t *SuperNET_ciphercalc(void **ptrp,int32_t *cipherlenp,bits256 *privkeyp,bits256 *destpubkeyp,uint8_t *data,int32_t datalen,uint8_t *space2,int32_t space2size);
@ -117,8 +137,15 @@ void basilisk_request_goodbye(struct supernet_info *myinfo);
int32_t basilisk_update(char *symbol,uint32_t reftimestamp);
void basilisk_seqresult(struct supernet_info *myinfo,char *retstr);
struct iguana_info *basilisk_geckochain(struct supernet_info *myinfo,char *symbol,char *chainname,cJSON *valsobj);
void basilisk_alicepayment(struct supernet_info *myinfo,struct iguana_info *coin,struct basilisk_rawtx *alicepayment,bits256 pubAm,bits256 pubBn);
void basilisk_rawtx_setparms(char *name,struct supernet_info *myinfo,struct basilisk_swap *swap,struct basilisk_rawtx *rawtx,struct iguana_info *coin,int32_t numconfirms,int32_t vintype,uint64_t satoshis,int32_t vouttype,uint8_t *pubkey33);
void basilisk_alicepayment(struct supernet_info *myinfo,struct basilisk_swap *swap,struct iguana_info *coin,struct basilisk_rawtx *alicepayment,bits256 pubAm,bits256 pubBn);
void basilisk_rawtx_setparms(char *name,uint32_t quoteid,struct basilisk_rawtx *rawtx,struct iguana_info *coin,int32_t numconfirms,int32_t vintype,uint64_t satoshis,int32_t vouttype,uint8_t *pubkey33,int32_t jumblrflag);
void basilisk_setmyid(struct supernet_info *myinfo);
int32_t basilisk_rwDEXquote(int32_t rwflag,uint8_t *serialized,struct basilisk_request *rp);
cJSON *basilisk_requestjson(struct basilisk_request *rp);
int32_t basilisk_bobscripts_set(struct supernet_info *myinfo,struct basilisk_swap *swap,int32_t depositflag,int32_t genflag);
void basilisk_txlog(struct supernet_info *myinfo,struct basilisk_swap *swap,struct basilisk_rawtx *rawtx,int32_t delay);
int32_t basilisk_messagekey(uint8_t *key,uint32_t channel,uint32_t msgid,bits256 srchash,bits256 desthash);
cJSON *basilisk_unspents(struct supernet_info *myinfo,struct iguana_info *coin,char *coinaddr);
char *basilisk_sendrawtransaction(struct supernet_info *myinfo,struct iguana_info *coin,char *signedtx);
#endif

118
basilisk/basilisk_CMD.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -24,28 +24,33 @@
return(-1);
}*/
struct iguana_peer *basilisk_ensurerelay(struct supernet_info *myinfo,struct iguana_info *btcd,uint32_t ipbits)
void basilisk_ensurerelay(struct supernet_info *myinfo,struct iguana_info *notaries,uint32_t ipbits)
{
char ipaddr[64];
expand_ipbits(ipaddr,ipbits);
//#if ISNOTARYNODE
//dpow_nanomsginit(myinfo,ipaddr);
//#else
struct iguana_peer *addr; int32_t i;
if ( btcd == 0 )
return(0);
if ( (addr= iguana_peerfindipbits(btcd,ipbits,0)) == 0 )
if ( notaries == 0 || ipbits == myinfo->myaddr.myipbits )
return;
if ( (addr= iguana_peerfindipbits(notaries,ipbits,0)) == 0 )
{
if ( (addr= iguana_peerslot(btcd,ipbits,0)) != 0 )
if ( (addr= iguana_peerslot(notaries,ipbits,0)) != 0 && addr->isrelay == 0 )
{
printf("launch peer for relay\n");
printf("launch peer.%s for relay vs (%s)\n",ipaddr,myinfo->ipaddr);
addr->isrelay = 1;
RELAYID = -1;
for (i=0; i<NUMRELAYS; i++)
if ( RELAYS[i].ipbits == myinfo->myaddr.myipbits )
myinfo->NOTARY.RELAYID = -1;
for (i=0; i<myinfo->NOTARY.NUMRELAYS; i++)
if ( myinfo->NOTARY.RELAYS[i].ipbits == myinfo->myaddr.myipbits )
{
RELAYID = i;
myinfo->NOTARY.RELAYID = i;
break;
}
iguana_launch(btcd,"addrelay",iguana_startconnection,addr,IGUANA_CONNTHREAD);
iguana_launch(notaries,"addrelay",iguana_startconnection,addr,IGUANA_CONNTHREAD);
} else printf("error getting peerslot\n");
} else addr->isrelay = 1;
return(addr);
//#endif
}
static int _increasing_ipbits(const void *a,const void *b)
@ -65,58 +70,59 @@ void basilisk_relay_remap(struct supernet_info *myinfo,struct basilisk_relay *rp
{
int32_t i; struct basilisk_relaystatus tmp[BASILISK_MAXRELAYS];
// need to verify this works
for (i=0; i<NUMRELAYS; i++)
for (i=0; i<myinfo->NOTARY.NUMRELAYS; i++)
tmp[i] = rp->reported[i];
for (i=0; i<NUMRELAYS; i++)
rp->reported[RELAYS[i].relayid] = tmp[RELAYS[i].oldrelayid];
for (i=0; i<myinfo->NOTARY.NUMRELAYS; i++)
rp->reported[myinfo->NOTARY.RELAYS[i].relayid] = tmp[myinfo->NOTARY.RELAYS[i].oldrelayid];
}
void basilisk_setmyid(struct supernet_info *myinfo)
{
int32_t i; char ipaddr[64]; struct iguana_info *btcd = iguana_coinfind("BTCD");
for (i=0; i<NUMRELAYS; i++)
int32_t i; char ipaddr[64]; struct iguana_info *notaries = iguana_coinfind("RELAY");
for (i=0; i<myinfo->NOTARY.NUMRELAYS; i++)
{
expand_ipbits(ipaddr,RELAYS[i].ipbits);
if ( myinfo->myaddr.myipbits == RELAYS[i].ipbits )
RELAYID = i;
basilisk_ensurerelay(myinfo,btcd,RELAYS[i].ipbits);
expand_ipbits(ipaddr,myinfo->NOTARY.RELAYS[i].ipbits);
if ( myinfo->myaddr.myipbits == myinfo->NOTARY.RELAYS[i].ipbits )
myinfo->NOTARY.RELAYID = i;
basilisk_ensurerelay(myinfo,notaries,myinfo->NOTARY.RELAYS[i].ipbits);
}
}
char *basilisk_addrelay_info(struct supernet_info *myinfo,uint8_t *pubkey33,uint32_t ipbits,bits256 pubkey)
{
int32_t i; struct basilisk_relay *rp;
for (i=0; i<NUMRELAYS; i++)
for (i=0; i<myinfo->NOTARY.NUMRELAYS; i++)
{
rp = &RELAYS[i];
rp = &myinfo->NOTARY.RELAYS[i];
if ( ipbits == rp->ipbits )
{
if ( bits256_cmp(GENESIS_PUBKEY,pubkey) != 0 && bits256_nonz(pubkey) != 0 )
rp->pubkey = pubkey;
if ( pubkey33 != 0 && pubkey33[0] != 0 )
memcpy(rp->pubkey33,pubkey33,33);
//printf("updated relay[%d] %x\n",i,ipbits);
basilisk_setmyid(myinfo);
//printf("updated relay[%d] %x vs mine.%x\n",i,ipbits,myinfo->myaddr.myipbits);
return(clonestr("{\"error\":\"relay already there\"}"));
}
}
if ( i >= sizeof(RELAYS)/sizeof(*RELAYS) )
i = (rand() % (sizeof(RELAYS)/sizeof(*RELAYS)));
if ( i >= sizeof(myinfo->NOTARY.RELAYS)/sizeof(*myinfo->NOTARY.RELAYS) )
i = (rand() % (sizeof(myinfo->NOTARY.RELAYS)/sizeof(*myinfo->NOTARY.RELAYS)));
printf("add relay[%d] <- %x\n",i,ipbits);
for (i=0; i<NUMRELAYS; i++)
RELAYS[i].oldrelayid = i;
rp = &RELAYS[i];
for (i=0; i<myinfo->NOTARY.NUMRELAYS; i++)
myinfo->NOTARY.RELAYS[i].oldrelayid = i;
rp = &myinfo->NOTARY.RELAYS[i];
rp->ipbits = ipbits;
rp->relayid = NUMRELAYS;
basilisk_ensurerelay(myinfo,iguana_coinfind("BTCD"),rp->ipbits);
if ( NUMRELAYS < sizeof(RELAYS)/sizeof(*RELAYS) )
NUMRELAYS++;
qsort(RELAYS,NUMRELAYS,sizeof(RELAYS[0]),_increasing_ipbits);
for (i=0; i<NUMRELAYS; i++)
RELAYS[i].relayid = i;
rp->relayid = myinfo->NOTARY.NUMRELAYS;
basilisk_ensurerelay(myinfo,iguana_coinfind("RELAY"),rp->ipbits);
if ( myinfo->NOTARY.NUMRELAYS < sizeof(myinfo->NOTARY.RELAYS)/sizeof(*myinfo->NOTARY.RELAYS) )
myinfo->NOTARY.NUMRELAYS++;
qsort(myinfo->NOTARY.RELAYS,myinfo->NOTARY.NUMRELAYS,sizeof(myinfo->NOTARY.RELAYS[0]),_increasing_ipbits);
for (i=0; i<myinfo->NOTARY.NUMRELAYS; i++)
myinfo->NOTARY.RELAYS[i].relayid = i;
basilisk_setmyid(myinfo);
printf("sorted MYRELAYID.%d\n",RELAYID);
for (i=0; i<NUMRELAYS; i++)
basilisk_relay_remap(myinfo,&RELAYS[i]);
printf("sorted MYRELAYID.%d\n",myinfo->NOTARY.RELAYID);
for (i=0; i<myinfo->NOTARY.NUMRELAYS; i++)
basilisk_relay_remap(myinfo,&myinfo->NOTARY.RELAYS[i]);
return(clonestr("{\"result\":\"relay added\"}"));
}
@ -140,6 +146,8 @@ void basilisk_request_goodbye(struct supernet_info *myinfo)
char *basilisk_respond_addrelay(struct supernet_info *myinfo,char *CMD,void *addr,char *remoteaddr,uint32_t basilisktag,cJSON *valsobj,uint8_t *data,int32_t datalen,bits256 hash,int32_t from_basilisk)
{
char *ipaddr,*retstr=0;
if ( valsobj == 0 )
return(clonestr("{\"error\":\"null valsobj\"}"));
if ( (ipaddr= jstr(valsobj,"ipaddr")) != 0 )
retstr = basilisk_addrelay_info(myinfo,0,(uint32_t)calc_ipbits(ipaddr),jbits256(valsobj,"pubkey"));
else retstr = clonestr("{\"error\":\"need rmd160, address and ipaddr\"}");
@ -203,7 +211,7 @@ char *basilisk_respond_VPNmessage(struct supernet_info *myinfo,char *CMD,void *a
if ( coin != 0 && (ptr= basilisk_bitcoinrawtx(&Lptr,myinfo,coin,remoteaddr,basilisktag,timeoutmillis,valsobj)) != 0 )
{
retstr = ptr->retstr;
ptr->finished = (uint32_t)time(NULL);
ptr->finished = OS_milliseconds() + 10000;
} else retstr = clonestr("{\"error\":\"no coin specified or error bitcoinrawtx\"}");
return(retstr);
}*/
@ -217,8 +225,8 @@ char *basilisk_respond_value(struct supernet_info *myinfo,char *CMD,void *addr,c
if ( coin != 0 && (ptr= basilisk_bitcoinvalue(&Lptr,myinfo,coin,remoteaddr,basilisktag,timeoutmillis,valsobj)) != 0 )
{
retstr = ptr->retstr;
ptr->finished = (uint32_t)time(NULL);
} else retstr = clonestr("{\"error\":\"no coin specified or error bitcoinrawtx\"}");
ptr->finished = OS_milliseconds() + 10000;
} else retstr = clonestr("{\"error\":\"no coin specified or error bitcoin value\"}");
return(retstr);
}
@ -231,14 +239,34 @@ char *basilisk_respond_balances(struct supernet_info *myinfo,char *CMD,void *add
if ( coin != 0 && (ptr= basilisk_bitcoinbalances(&Lptr,myinfo,coin,remoteaddr,basilisktag,timeoutmillis,valsobj)) != 0 )
{
retstr = ptr->retstr;
ptr->finished = (uint32_t)time(NULL);
} else retstr = clonestr("{\"error\":\"no coin specified or error bitcoinrawtx\"}");
ptr->finished = OS_milliseconds() + 10000;
} else retstr = clonestr("{\"error\":\"no coin specified or error bitcoin balances\"}");
return(retstr);
}
char *basilisk_respond_getinfo(struct supernet_info *myinfo,char *CMD,void *addr,char *remoteaddr,uint32_t basilisktag,cJSON *valsobj,uint8_t *data,int32_t datalen,bits256 hash,int32_t from_basilisk)
{
char *symbol,*retstr=0; struct basilisk_item Lptr,*ptr; int32_t timeoutmillis; struct iguana_info *coin = 0;
if ( (timeoutmillis= jint(valsobj,"timeout")) <= 0 )
timeoutmillis = 5000;
if ( (symbol= jstr(valsobj,"coin")) != 0 || (symbol= jstr(valsobj,"symbol")) != 0 )
coin = iguana_coinfind(symbol);
if ( coin != 0 && (ptr= basilisk_getinfo(&Lptr,myinfo,coin,remoteaddr,basilisktag,timeoutmillis,valsobj)) != 0 )
{
retstr = ptr->retstr;
ptr->finished = OS_milliseconds() + 10000;
} else retstr = clonestr("{\"error\":\"no coin specified or error bitcoin getinfo\"}");
return(retstr);
}
#include "../includes/iguana_apidefs.h"
#include "../includes/iguana_apideclares.h"
HASH_ARRAY_STRING(basilisk,vote,hash,vals,hexstr)
{
return(basilisk_standardservice("VOT",myinfo,0,hash,vals,hexstr,0));
}
HASH_ARRAY_STRING(basilisk,addrelay,hash,vals,hexstr)
{
return(basilisk_standardservice("ADD",myinfo,0,hash,vals,hexstr,1));

393
basilisk/basilisk_DEX.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -34,7 +34,7 @@ int32_t basilisk_ping_processDEX(struct supernet_info *myinfo,uint32_t senderipb
if ( relay->numrequests < relay->maxrequests )
{
memcpy(serialized,&data[len],clen);
//printf("ping processDEX\n");
printf("ping processDEX\n");
n = basilisk_rwDEXquote(0,serialized,&R);
if ( n != clen )
printf("n.%d clen.%d\n",n,clen);
@ -100,10 +100,10 @@ int32_t basilisk_rwDEXquote(int32_t rwflag,uint8_t *serialized,struct basilisk_r
len += iguana_rwnum(rwflag,&serialized[len],sizeof(rp->timestamp),&rp->timestamp); // must be 2nd
len += iguana_rwnum(rwflag,&serialized[len],sizeof(rp->quoteid),&rp->quoteid);
len += iguana_rwnum(rwflag,&serialized[len],sizeof(rp->quotetime),&rp->quotetime);
len += iguana_rwnum(rwflag,&serialized[len],sizeof(rp->relaybits),&rp->relaybits);
len += iguana_rwnum(rwflag,&serialized[len],sizeof(rp->optionhours),&rp->optionhours);
len += iguana_rwnum(rwflag,&serialized[len],sizeof(rp->srcamount),&rp->srcamount);
len += iguana_rwnum(rwflag,&serialized[len],sizeof(rp->minamount),&rp->minamount);
len += iguana_rwbignum(rwflag,&serialized[len],sizeof(rp->hash),rp->hash.bytes);
len += iguana_rwbignum(rwflag,&serialized[len],sizeof(rp->srchash),rp->srchash.bytes);
len += iguana_rwbignum(rwflag,&serialized[len],sizeof(rp->desthash),rp->desthash.bytes);
len += iguana_rwnum(rwflag,&serialized[len],sizeof(rp->destamount),&rp->destamount);
if ( rwflag != 0 )
@ -116,16 +116,19 @@ int32_t basilisk_rwDEXquote(int32_t rwflag,uint8_t *serialized,struct basilisk_r
memcpy(rp->src,&serialized[len],sizeof(rp->src)), len += sizeof(rp->src);
memcpy(rp->dest,&serialized[len],sizeof(rp->dest)), len += sizeof(rp->dest);
}
//len += iguana_rwnum(rwflag,&serialized[len],sizeof(rp->DEXselector),&rp->DEXselector);
//len += iguana_rwnum(rwflag,&serialized[len],sizeof(rp->extraspace),&rp->extraspace);
if ( rp->quoteid != 0 && basilisk_quoteid(rp) != rp->quoteid )
printf("basilisk_rwDEXquote.%d: quoteid.%u mismatch calc %u\n",rwflag,rp->quoteid,basilisk_quoteid(rp));
printf(" basilisk_rwDEXquote.%d: quoteid.%u mismatch calc %u rp.%p\n",rwflag,rp->quoteid,basilisk_quoteid(rp),rp);
if ( basilisk_requestid(rp) != rp->requestid )
printf("basilisk_rwDEXquote.%d: requestid.%u mismatch calc %u\n",rwflag,rp->requestid,basilisk_requestid(rp));
printf(" basilisk_rwDEXquote.%d: requestid.%u mismatch calc %u rp.%p\n",rwflag,rp->requestid,basilisk_requestid(rp),rp);
return(len);
}
uint32_t basilisk_request_enqueue(struct supernet_info *myinfo,struct basilisk_request *rp)
{
uint8_t serialized[256]; int32_t len; struct queueitem *item;
//printf(" basilisk_request_enqueue\n");
len = basilisk_rwDEXquote(1,serialized+1,rp);
if ( (item= calloc(1,sizeof(*item) + len + 1)) != 0 )
{
@ -134,7 +137,7 @@ uint32_t basilisk_request_enqueue(struct supernet_info *myinfo,struct basilisk_r
portable_mutex_lock(&myinfo->DEX_mutex);
DL_APPEND(myinfo->DEX_quotes,item);
portable_mutex_unlock(&myinfo->DEX_mutex);
printf("ENQUEUE.%u calc.%u\n",rp->requestid,basilisk_requestid(rp));
//printf("ENQUEUE.%u calc.%u\n",rp->requestid,basilisk_requestid(rp));
return(rp->requestid);
}
return(0);
@ -142,13 +145,13 @@ uint32_t basilisk_request_enqueue(struct supernet_info *myinfo,struct basilisk_r
cJSON *basilisk_requestjson(struct basilisk_request *rp)
{
char ipaddr[64]; cJSON *item = cJSON_CreateObject();
if ( rp->relaybits != 0 )
cJSON *item = cJSON_CreateObject();
/*if ( rp->relaybits != 0 )
{
expand_ipbits(ipaddr,rp->relaybits);
jaddstr(item,"relay",ipaddr);
}
jaddbits256(item,"hash",rp->hash);
}*/
jaddbits256(item,"srchash",rp->srchash);
if ( bits256_nonz(rp->desthash) != 0 )
jaddbits256(item,"desthash",rp->desthash);
jaddstr(item,"src",rp->src);
@ -158,11 +161,18 @@ cJSON *basilisk_requestjson(struct basilisk_request *rp)
jadd64bits(item,"minamount",rp->minamount);
jaddstr(item,"dest",rp->dest);
if ( rp->destamount != 0 )
jadd64bits(item,"destamount",rp->destamount);
{
//jadd64bits(item,"destamount",rp->destamount);
jadd64bits(item,"destsatoshis",rp->destamount);
//printf("DESTSATOSHIS.%llu\n",(long long)rp->destamount);
}
jaddnum(item,"quotetime",rp->quotetime);
jaddnum(item,"timestamp",rp->timestamp);
jaddnum(item,"requestid",rp->requestid);
jaddnum(item,"quoteid",rp->quoteid);
//jaddnum(item,"DEXselector",rp->DEXselector);
jaddnum(item,"optionhours",rp->optionhours);
jaddnum(item,"profit",(double)rp->profitmargin / 1000000.);
if ( rp->quoteid != 0 && basilisk_quoteid(rp) != rp->quoteid )
printf("quoteid mismatch %u vs %u\n",basilisk_quoteid(rp),rp->quoteid);
if ( basilisk_requestid(rp) != rp->requestid )
@ -171,11 +181,11 @@ cJSON *basilisk_requestjson(struct basilisk_request *rp)
int32_t i; struct basilisk_request R;
if ( basilisk_parsejson(&R,item) != 0 )
{
if ( memcmp(&R,rp,sizeof(*rp)) != 0 )
if ( memcmp(&R,rp,sizeof(*rp)-sizeof(uint32_t)) != 0 )
{
for (i=0; i<sizeof(*rp); i++)
printf("%02x",((uint8_t *)rp)[i]);
printf(" <- rp\n");
printf(" <- rp.%p\n",rp);
for (i=0; i<sizeof(R); i++)
printf("%02x",((uint8_t *)&R)[i]);
printf(" <- R mismatch\n");
@ -189,7 +199,7 @@ cJSON *basilisk_requestjson(struct basilisk_request *rp)
return(item);
}
int32_t basilisk_request_create(struct basilisk_request *rp,cJSON *valsobj,bits256 hash,uint32_t timestamp)
int32_t basilisk_request_create(struct basilisk_request *rp,cJSON *valsobj,bits256 desthash,uint32_t timestamp,int32_t DEXselector)
{
char *dest,*src; uint32_t i;
memset(rp,0,sizeof(*rp));
@ -197,7 +207,7 @@ int32_t basilisk_request_create(struct basilisk_request *rp,cJSON *valsobj,bits2
{
if ( (rp->destamount= j64bits(valsobj,"destsatoshis")) != 0 )
{
rp->desthash = jbits256(valsobj,"desthash");
rp->desthash = desthash;
for (i=0; i<4; i++)
if ( rp->desthash.ulongs[i] != 0 )
break;
@ -206,14 +216,20 @@ int32_t basilisk_request_create(struct basilisk_request *rp,cJSON *valsobj,bits2
}
rp->minamount = j64bits(valsobj,"minamount");
rp->timestamp = timestamp;
rp->hash = hash;
rp->srchash = jbits256(valsobj,"srchash");
rp->optionhours = jint(valsobj,"optionhours");
rp->profitmargin = jdouble(valsobj,"profit") * 1000000;
//rp->DEXselector = DEXselector;
strncpy(rp->src,src,sizeof(rp->src)-1);
strncpy(rp->dest,dest,sizeof(rp->dest)-1);
//if ( jstr(valsobj,"relay") != 0 )
// rp->relaybits = (uint32_t)calc_ipbits(jstr(valsobj,"relay"));
rp->requestid = basilisk_requestid(rp);
//printf("set requestid <- %u\n",rp->requestid);
if ( rp->destamount != 0 && bits256_nonz(rp->desthash) != 0 )
{
rp->quoteid = basilisk_quoteid(rp);
printf("set quoteid.%u\n",rp->quoteid);
//printf("set quoteid.%u\n",rp->quoteid);
}
//printf("create.%u calc.%u\n",rp->requestid,basilisk_requestid(rp));
return(0);
@ -221,18 +237,42 @@ int32_t basilisk_request_create(struct basilisk_request *rp,cJSON *valsobj,bits2
return(-1);
}
char *basilisk_start(struct supernet_info *myinfo,struct basilisk_request *rp,uint32_t statebits)
char *basilisk_start(struct supernet_info *myinfo,bits256 privkey,struct basilisk_request *_rp,uint32_t statebits,int32_t optionduration)
{
cJSON *retjson;
if ( (bits256_cmp(rp->hash,myinfo->myaddr.persistent) == 0 || bits256_cmp(rp->desthash,myinfo->myaddr.persistent) == 0) )
cJSON *retjson; char typestr[64]; bits256 tmpprivkey; double bidasks[2]; struct basilisk_request *rp=0; int32_t i,srcmatch,destmatch;
if ( _rp->requestid == myinfo->lastdexrequestid )
{
printf("filter duplicate r%u\n",_rp->requestid);
return(clonestr("{\"error\":\"filter duplicate requestid\"}"));
}
srcmatch = smartaddress_pubkey(myinfo,typestr,bidasks,&tmpprivkey,_rp->src,_rp->srchash) >= 0;
destmatch = smartaddress_pubkey(myinfo,typestr,bidasks,&tmpprivkey,_rp->dest,_rp->desthash) >= 0;
char str[65],str2[65]; printf("%s srcmatch.%d %s destmatch.%d\n",bits256_str(str,_rp->srchash),srcmatch,bits256_str(str2,_rp->desthash),destmatch);
if ( srcmatch != 0 || destmatch != 0 )
{
printf("START thread to complete %u/%u for (%s %.8f) <-> (%s %.8f) q.%u\n",rp->requestid,rp->quoteid,rp->src,dstr(rp->srcamount),rp->dest,dstr(rp->destamount),rp->quoteid);
if ( basilisk_thread_start(myinfo,rp) != 0 )
for (i=0; i<myinfo->numswaps; i++)
if ( myinfo->swaps[i]->I.req.requestid == _rp->requestid )
{
printf("basilisk_thread_start error trying to start requestid.%u which is already started\n",rp->requestid);
break;
}
if ( i == myinfo->numswaps )
{
rp = calloc(1,sizeof(*rp));
*rp = *_rp;
printf("START thread to complete %u/%u for (%s %.8f) <-> (%s %.8f) q.%u\n",rp->requestid,rp->quoteid,rp->src,dstr(rp->srcamount),rp->dest,dstr(rp->destamount),rp->quoteid);
myinfo->lastdexrequestid = rp->requestid;
if ( basilisk_thread_start(myinfo,privkey,rp,statebits,optionduration,0) != 0 )
{
basilisk_request_enqueue(myinfo,rp);
return(clonestr("{\"result\":\"started atomic swap thread\"}"));
} else return(clonestr("{\"error\":\"couldnt atomic swap thread\"}"));
}
else
{
basilisk_request_enqueue(myinfo,rp);
return(clonestr("{\"result\":\"started atomic swap thread\"}"));
printf("trying to start already pending swap.r%u\n",rp->requestid);
return(clonestr("{\"error\":\"cant start pending swap\"}"));
}
else return(clonestr("{\"error\":\"couldnt atomic swap thread\"}"));
}
else if ( myinfo->IAMLP != 0 )
{
@ -242,12 +282,69 @@ char *basilisk_start(struct supernet_info *myinfo,struct basilisk_request *rp,ui
} else return(clonestr("{\"error\":\"unexpected basilisk_start not mine and amrelay\"}"));
}
int32_t basilisk_requests_poll(struct supernet_info *myinfo)
{
static uint32_t lastpoll;
char *retstr,typestr[64]; uint8_t data[32768]; cJSON *outerarray,*retjson; uint32_t msgid,channel; int32_t datalen,i,n,retval = 0; struct basilisk_request issueR; bits256 privkey; double bidasks[2],hwm = 0.;
if ( myinfo->IAMNOTARY != 0 || time(NULL) < lastpoll+5 || (myinfo->IAMLP == 0 && myinfo->DEXactive < time(NULL)) )
return(retval);
lastpoll = (uint32_t)time(NULL);
memset(&issueR,0,sizeof(issueR));
memset(&myinfo->DEXaccept,0,sizeof(myinfo->DEXaccept));
//printf("Call incoming\n");
if ( (retstr= InstantDEX_incoming(myinfo,0,0,0,0)) != 0 )
{
//printf("poll.(%s)\n",retstr);
if ( (retjson= cJSON_Parse(retstr)) != 0 )
{
if ( (outerarray= jarray(&n,retjson,"responses")) != 0 )
{
retval++;
for (i=0; i<n; i++)
hwm = basilisk_process_results(myinfo,&issueR,jitem(outerarray,i),hwm);
} //else hwm = basilisk_process_results(myinfo,&issueR,outerarray,hwm);
free_json(retjson);
}
free(retstr);
} else printf("null incoming\n");
channel = 'D' + ((uint32_t)'E' << 8) + ((uint32_t)'X' << 16);
if ( hwm > 0. )
{
myinfo->DEXaccept = issueR;
if ( smartaddress_pubkey(myinfo,typestr,bidasks,&privkey,issueR.src,issueR.srchash) >= 0 )
{
if ( myinfo->DEXtrades > 0 )
{
dex_channelsend(myinfo,issueR.srchash,issueR.desthash,channel,0x4000000,(void *)&issueR.requestid,sizeof(issueR.requestid)); // 60
dpow_nanomsg_update(myinfo);
dex_updateclient(myinfo);
if ( (retstr= basilisk_start(myinfo,privkey,&issueR,1,issueR.optionhours * 3600)) != 0 )
free(retstr);
}
}
else if ( myinfo->IAMLP != 0 && issueR.requestid != myinfo->lastdexrequestid )//if ( issueR.quoteid == 0 )
{
issueR.quoteid = basilisk_quoteid(&issueR);
issueR.desthash = myinfo->myaddr.persistent;
datalen = basilisk_rwDEXquote(1,data,&issueR);
msgid = (uint32_t)time(NULL);
printf("other req hwm %f >>>>>>>>>>> send response (%llx -> %llx) last.%u r.%u quoteid.%u\n",hwm,(long long)issueR.desthash.txid,(long long)issueR.srchash.txid,myinfo->lastdexrequestid,issueR.requestid,issueR.quoteid);
dex_channelsend(myinfo,issueR.desthash,issueR.srchash,channel,msgid,data,datalen); //INSTANTDEX_LOCKTIME*2
dpow_nanomsg_update(myinfo);
dex_updateclient(myinfo);
if ( (retstr= basilisk_start(myinfo,myinfo->persistent_priv,&issueR,0,issueR.optionhours * 3600)) != 0 )
free(retstr);
} //else printf("basilisk_requests_poll unexpected hwm issueR\n");
}
return(retval);
}
struct basilisk_relay *basilisk_request_ensure(struct supernet_info *myinfo,uint32_t senderipbits,int32_t numrequests)
{
int32_t j; struct basilisk_relay *relay = 0;
if ( (j= basilisk_relayid(myinfo,senderipbits)) >= 0 )
{
relay = &RELAYS[j];
relay = &myinfo->NOTARY.RELAYS[j];
if ( numrequests > relay->maxrequests )
{
relay->maxrequests = numrequests;
@ -281,17 +378,30 @@ static int _cmp_requests(const void *a,const void *b)
#undef uint32_b
}
struct basilisk_request *_basilisk_requests_uniq(struct supernet_info *myinfo,int32_t *nump,uint8_t *space,int32_t spacesize)
struct basilisk_request *_basilisk_requests_uniq(struct supernet_info *myinfo,int32_t *nump,uint8_t *space,int32_t spacesize,struct basilisk_request *refrp)
{
int32_t i,j,n,k,m; struct basilisk_relay *relay; struct basilisk_request *requests,*rp;
for (j=m=0; j<NUMRELAYS; j++)
m += RELAYS[j].numrequests;
m = 0;
if ( refrp != 0 )
m = 1;
for (j=0; j<myinfo->NOTARY.NUMRELAYS; j++)
m += myinfo->NOTARY.RELAYS[j].numrequests;
if ( m*sizeof(*requests) <= spacesize )
requests = (void *)space;
else requests = calloc(m,sizeof(*requests));
for (j=m=0; j<NUMRELAYS; j++)
if ( refrp != 0 )
{
relay = &RELAYS[j];
requests[0] = *refrp;
//for (i=0; i<sizeof(*refrp); i++)
// printf("%02x",((uint8_t *)refrp)[i]);
//printf(" uniq\n");
}
if ( refrp != 0 )
m = 1;
else m = 0;
for (j=0; j<myinfo->NOTARY.NUMRELAYS; j++)
{
relay = &myinfo->NOTARY.RELAYS[j];
if ( (n= relay->numrequests) > 0 )
{
for (i=0; i<n; i++)
@ -302,7 +412,7 @@ struct basilisk_request *_basilisk_requests_uniq(struct supernet_info *myinfo,in
break;
if ( k == m )
{
requests[m].relaybits = relay->ipbits;
//requests[m].relaybits = relay->ipbits;
requests[m++] = *rp;
}
}
@ -322,20 +432,22 @@ struct basilisk_request *_basilisk_requests_uniq(struct supernet_info *myinfo,in
return(jprint(retjson,1));
}*/
char *basilisk_respond_requests(struct supernet_info *myinfo,bits256 hash,uint32_t requestid,uint32_t quoteid)
char *basilisk_respond_requests(struct supernet_info *myinfo,bits256 hash,uint32_t requestid,uint32_t quoteid,struct basilisk_request *refrp)
{
int32_t i,qflag,num=0; cJSON *retjson,*array; struct basilisk_request *requests,*rp; uint8_t space[4096];
array = cJSON_CreateArray();
portable_mutex_lock(&myinfo->DEX_reqmutex);
if ( (requests= _basilisk_requests_uniq(myinfo,&num,space,sizeof(space))) != 0 )
if ( (requests= _basilisk_requests_uniq(myinfo,&num,space,sizeof(space),refrp)) != 0 )
{
//printf("numrequests.%d r.%u q.%u\n",num,requestid,quoteid);
for (i=0; i<num; i++)
{
rp = &requests[i];
if ( quoteid == 0 || (quoteid == rp->quoteid && (bits256_cmp(hash,rp->hash) == 0 || bits256_cmp(hash,rp->desthash) == 0)) )
if ( quoteid == 0 || (quoteid == rp->quoteid && (bits256_cmp(hash,rp->srchash) == 0 || bits256_cmp(hash,rp->desthash) == 0)) )
qflag = 1;
else qflag = 0;
//int32_t j; for (j=0; j<sizeof(*rp); j++)
// printf("%02x",((uint8_t *)rp)[j]);
//printf(" rp[%d] of %d qflag.%d\n",i,num,qflag);
if ( requestid == 0 || (rp->requestid == requestid && qflag != 0) )
jaddi(array,basilisk_requestjson(rp));
}
@ -348,11 +460,11 @@ char *basilisk_respond_requests(struct supernet_info *myinfo,bits256 hash,uint32
return(jprint(retjson,1));
}
char *basilisk_respond_accept(struct supernet_info *myinfo,uint32_t requestid,uint32_t quoteid)
char *basilisk_respond_accept(struct supernet_info *myinfo,bits256 privkey,uint32_t requestid,uint32_t quoteid,struct basilisk_request *refrp)
{
int32_t i,num=0; char *retstr=0; struct basilisk_request *requests,*rp; uint8_t space[4096];
portable_mutex_lock(&myinfo->DEX_reqmutex);
if ( (requests= _basilisk_requests_uniq(myinfo,&num,space,sizeof(space))) != 0 )
if ( (requests= _basilisk_requests_uniq(myinfo,&num,space,sizeof(space),refrp)) != 0 )
{
for (i=0; i<num; i++)
{
@ -360,7 +472,7 @@ char *basilisk_respond_accept(struct supernet_info *myinfo,uint32_t requestid,ui
if ( rp->requestid == requestid && rp->quoteid == quoteid )
{
printf("start from accept\n");
retstr = basilisk_start(myinfo,rp,1);
retstr = basilisk_start(myinfo,privkey,rp,1,0);
break;
}
}
@ -373,181 +485,54 @@ char *basilisk_respond_accept(struct supernet_info *myinfo,uint32_t requestid,ui
return(retstr);
}
// respond to incoming RID, ACC, DEX, QST
/*char *basilisk_respond_RID(struct supernet_info *myinfo,char *CMD,void *addr,char *remoteaddr,uint32_t basilisktag,cJSON *valsobj,uint8_t *data,int32_t datalen,bits256 hash,int32_t from_basilisk)
{
return(basilisk_respond_requests(myinfo,hash,juint(valsobj,"requestid"),0));
}
char *basilisk_respond_SWP(struct supernet_info *myinfo,char *CMD,void *addr,char *remoteaddr,uint32_t basilisktag,cJSON *valsobj,uint8_t *data,int32_t datalen,bits256 hash,int32_t from_basilisk)
{
return(basilisk_respond_swapstatus(myinfo,hash,juint(valsobj,"requestid"),juint(valsobj,"quoteid")));
}
char *basilisk_respond_ACC(struct supernet_info *myinfo,char *CMD,void *addr,char *remoteaddr,uint32_t basilisktag,cJSON *valsobj,uint8_t *data,int32_t datalen,bits256 hash,int32_t from_basilisk)
{
uint32_t requestid,quoteid;
if ( (requestid= juint(valsobj,"requestid")) != 0 && (quoteid= juint(valsobj,"quoteid")) != 0 )
return(basilisk_respond_accept(myinfo,requestid,quoteid));
else return(clonestr("{\"error\":\"need nonzero requestid and quoteid\"}"));
}
char *basilisk_respond_DEX(struct supernet_info *myinfo,char *CMD,void *addr,char *remoteaddr,uint32_t basilisktag,cJSON *valsobj,uint8_t *data,int32_t datalen,bits256 hash,int32_t from_basilisk)
cJSON *basilisk_unspents(struct supernet_info *myinfo,struct iguana_info *coin,char *coinaddr)
{
char *retstr=0,buf[256]; struct basilisk_request R;
if ( basilisk_request_create(&R,valsobj,hash,juint(valsobj,"timestamp")) == 0 )
cJSON *unspents=0,*array=0,*json,*ismine; char *retstr; int32_t valid = 0;
if ( coin->FULLNODE > 0 )
{
char str[65]; printf("DEX.(%s %.8f) -> %s %s\n",R.src,dstr(R.srcamount),R.dest,bits256_str(str,hash));
if ( basilisk_request_enqueue(myinfo,&R) != 0 )
{
sprintf(buf,"{\"result\":\"DEX request added\",\"requestid\":%u}",R.requestid);
retstr = clonestr(buf);
} else retstr = clonestr("{\"error\":\"DEX quote couldnt be created\"}");
} else retstr = clonestr("{\"error\":\"missing or invalid fields\"}");
return(retstr);
}*/
#include "../includes/iguana_apidefs.h"
#include "../includes/iguana_apideclares.h"
THREE_STRINGS_AND_DOUBLE(tradebot,aveprice,comment,base,rel,basevolume)
{
double retvals[4],aveprice; cJSON *retjson = cJSON_CreateObject();
aveprice = instantdex_avehbla(myinfo,retvals,base,rel,basevolume);
jaddstr(retjson,"result","success");
jaddnum(retjson,"aveprice",aveprice);
jaddnum(retjson,"avebid",retvals[0]);
jaddnum(retjson,"bidvol",retvals[1]);
jaddnum(retjson,"aveask",retvals[2]);
jaddnum(retjson,"askvol",retvals[3]);
return(jprint(retjson,1));
}
ZERO_ARGS(InstantDEX,allcoins)
{
struct iguana_info *tmp; cJSON *basilisk,*virtual,*full,*retjson = cJSON_CreateObject();
full = cJSON_CreateArray();
basilisk = cJSON_CreateArray();
virtual = cJSON_CreateArray();
HASH_ITER(hh,myinfo->allcoins,coin,tmp)
{
if ( coin->virtualchain != 0 )
jaddistr(virtual,coin->symbol);
if ( coin->FULLNODE != 0 || coin->VALIDATENODE != 0 )
jaddistr(full,coin->symbol);
else jaddistr(basilisk,coin->symbol);
array = cJSON_CreateArray();
jaddistr(array,coinaddr);
unspents = iguana_listunspents(myinfo,coin,array,0,0,"");
free_json(array);
}
jadd(retjson,"basilisk",basilisk);
jadd(retjson,"full",full);
jadd(retjson,"virtual",virtual);
return(jprint(retjson,1));
}
STRING_ARG(InstantDEX,available,source)
{
if ( source != 0 && source[0] != 0 && (coin= iguana_coinfind(source)) != 0 )
{
if ( myinfo->expiration != 0 )
return(bitcoinrpc_getbalance(myinfo,coin,json,remoteaddr,"*",coin->chain->minconfirms,1,1<<30));
else return(clonestr("{\"error\":\"need to unlock wallet\"}"));
} else return(clonestr("{\"error\":\"specified coin is not active\"}"));
}
HASH_ARRAY_STRING(InstantDEX,request,hash,vals,hexstr)
{
uint8_t serialized[512]; struct basilisk_request R; cJSON *reqjson; uint32_t datalen=0,DEX_channel;
myinfo->DEXactive = (uint32_t)time(NULL) + INSTANTDEX_LOCKTIME;
jadd64bits(vals,"minamount",jdouble(vals,"minprice") * jdouble(vals,"amount") * SATOSHIDEN);
if ( jobj(vals,"desthash") == 0 )
jaddbits256(vals,"desthash",hash);
jadd64bits(vals,"satoshis",jdouble(vals,"amount") * SATOSHIDEN);
jadd64bits(vals,"destsatoshis",jdouble(vals,"destamount") * SATOSHIDEN);
jaddnum(vals,"timestamp",time(NULL));
hash = myinfo->myaddr.persistent;
printf("service.(%s)\n",jprint(vals,0));
else
{
memset(&R,0,sizeof(R));
if ( basilisk_request_create(&R,vals,hash,juint(vals,"timestamp")) == 0 )
if ( coin->FULLNODE < 0 && (retstr= dpow_validateaddress(myinfo,coin,coinaddr)) != 0 )
{
printf("R.requestid.%u vs calc %u, q.%u\n",R.requestid,basilisk_requestid(&R),R.quoteid);
if ( RELAYID >= 0 )
R.relaybits = myinfo->myaddr.myipbits;
if ( (reqjson= basilisk_requestjson(&R)) != 0 )
free_json(reqjson);
datalen = basilisk_rwDEXquote(1,serialized,&R);
printf("R.requestid.%u vs calc %u, q.%u datalen.%d\n",R.requestid,basilisk_requestid(&R),R.quoteid,datalen);
basilisk_rwDEXquote(0,serialized,&R);
} else printf("error creating request\n");
}
if ( datalen > 0 )
{
memset(hash.bytes,0,sizeof(hash));
DEX_channel = 'D' + ((uint32_t)'E' << 8) + ((uint32_t)'X' << 16);
if ( basilisk_channelsend(myinfo,hash,DEX_channel,(uint32_t)time(NULL),serialized,datalen,30) == 0 )
return(clonestr("{\"result\":\"DEX message sent\"}"));
else return(clonestr("{\"error\":\"DEX message couldnt be sent\"}"));
}
return(clonestr("{\"error\":\"DEX message not sent\"}"));
//return(basilisk_standardservice("DEX",myinfo,0,myinfo->myaddr.persistent,vals,"",1));
}
INT_ARG(InstantDEX,automatched,requestid)
{
// return quoteid
myinfo->DEXactive = (uint32_t)time(NULL) + INSTANTDEX_LOCKTIME;
return(clonestr("{\"result\":\"automatched not yet\"}"));
}
INT_ARG(InstantDEX,incoming,requestid)
{
cJSON *vals; char *retstr;
myinfo->DEXactive = (uint32_t)time(NULL) + INSTANTDEX_LOCKTIME;
//if ( myinfo->IAMLP != 0 )
// return(basilisk_respond_requests(myinfo,myinfo->myaddr.persistent,requestid,0));
//else
{
vals = cJSON_CreateObject();
jaddnum(vals,"requestid",(uint32_t)requestid);
jaddbits256(vals,"hash",myinfo->myaddr.persistent);
retstr = basilisk_standardservice("RID",myinfo,0,myinfo->myaddr.persistent,vals,"",1);
free_json(vals);
return(retstr);
json = cJSON_Parse(retstr);
if ( (ismine= jobj(json,"ismine")) != 0 && is_cJSON_True(ismine) != 0 )
valid = 1;
free(retstr);
}
if ( coin->FULLNODE == 0 || valid == 0 )
{
if ( (retstr= dex_listunspent(myinfo,coin,0,0,coin->symbol,coinaddr)) != 0 )
{
unspents = cJSON_Parse(retstr);
free(retstr);
}
} else unspents = dpow_listunspent(myinfo,coin,coinaddr);
}
return(unspents);
}
/*TWO_INTS(InstantDEX,swapstatus,requestid,quoteid)
char *basilisk_sendrawtransaction(struct supernet_info *myinfo,struct iguana_info *coin,char *signedtx)
{
cJSON *vals; char *retstr;
myinfo->DEXactive = (uint32_t)time(NULL) + INSTANTDEX_LOCKTIME;
//if ( myinfo->IAMLP != 0 )
// return(basilisk_respond_swapstatus(myinfo,myinfo->myaddr.persistent,requestid,quoteid));
//else
char *retstr,buf[65]; bits256 txid;
if ( coin->FULLNODE > 0 )
{
vals = cJSON_CreateObject();
jaddnum(vals,"requestid",(uint32_t)requestid);
jaddnum(vals,"quoteid",(uint32_t)quoteid);
jaddbits256(vals,"hash",myinfo->myaddr.persistent);
retstr = basilisk_standardservice("SWP",myinfo,0,myinfo->myaddr.persistent,vals,"",1);
free_json(vals);
return(retstr);
txid = iguana_sendrawtransaction(myinfo,coin,signedtx);
if ( bits256_nonz(txid) )
{
bits256_str(buf,txid);
retstr = clonestr(buf);
} else retstr = clonestr("{\"error\":\"couldnt validate or send signedtx\"}");
}
}*/
TWO_INTS(InstantDEX,accept,requestid,quoteid)
{
cJSON *vals; char *retstr;
myinfo->DEXactive = (uint32_t)time(NULL) + INSTANTDEX_LOCKTIME;
//if ( myinfo->IAMLP != 0 )
// return(basilisk_respond_accept(myinfo,requestid,quoteid));
//else
else if ( coin->FULLNODE == 0 )
{
vals = cJSON_CreateObject();
jaddnum(vals,"quoteid",(uint32_t)quoteid);
jaddnum(vals,"requestid",(uint32_t)requestid);
retstr = basilisk_standardservice("ACC",myinfo,0,myinfo->myaddr.persistent,vals,"",1);
free_json(vals);
return(retstr);
retstr = _dex_sendrawtransaction(myinfo,coin->symbol,signedtx);
}
else retstr = dpow_sendrawtransaction(myinfo,coin,signedtx);
return(retstr);
}
#include "../includes/iguana_apiundefs.h"

554
basilisk/basilisk_MSG.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -15,68 +15,16 @@
// included from basilisk.c
char *basilisk_respond_addmessage(struct supernet_info *myinfo,uint8_t *key,int32_t keylen,uint8_t *data,int32_t datalen,int32_t sendping,uint32_t duration)
int32_t basilisk_messagekeyread(uint8_t *key,uint32_t *channelp,uint32_t *msgidp,bits256 *srchashp,bits256 *desthashp)
{
struct basilisk_message *msg; int32_t i;
HASH_FIND(hh,myinfo->messagetable,key,keylen,msg);
if ( msg == 0 && keylen == BASILISK_KEYSIZE )
{
msg = calloc(1,sizeof(*msg) + datalen);
if ( duration == 0 )
duration = BASILISK_MSGDURATION;
else if ( duration > INSTANTDEX_LOCKTIME*2 )
duration = INSTANTDEX_LOCKTIME*2;
msg->duration = duration;
msg->expiration = (uint32_t)time(NULL) + duration;
msg->keylen = keylen;
memcpy(msg->key,key,keylen);
msg->datalen = datalen;
memcpy(msg->data,data,datalen);
portable_mutex_lock(&myinfo->messagemutex);
HASH_ADD_KEYPTR(hh,myinfo->messagetable,msg->key,msg->keylen,msg);
for (i=0; i<BASILISK_KEYSIZE; i++)
printf("%02x",key[i]);
printf(" <- ADDMSG.[%d]\n",QUEUEITEMS);
QUEUEITEMS++;
portable_mutex_unlock(&myinfo->messagemutex);
if ( sendping != 0 )
{
queue_enqueue("basilisk_message",&myinfo->msgQ,&msg->DL,0);
return(clonestr("{\"result\":\"message added to hashtable\"}"));
} else return(0);
} else return(0);
}
cJSON *basilisk_respond_getmessage(struct supernet_info *myinfo,uint8_t *key,int32_t keylen)
{
cJSON *msgjson=0; struct basilisk_message *msg; char *ptr = 0,strbuf[32768];
portable_mutex_lock(&myinfo->messagemutex);
HASH_FIND(hh,myinfo->messagetable,key,keylen,msg);
if ( msg != 0 )
{
msgjson = cJSON_CreateObject();
if ( basilisk_addhexstr(&ptr,msgjson,strbuf,sizeof(strbuf),msg->data,msg->datalen) != 0 )
{
//retjson = cJSON_CreateObject();
jaddnum(msgjson,"expiration",msg->expiration);
jaddnum(msgjson,"duration",msg->duration);
//jadd(retjson,"message",msgjson);
printf("havemessage len.%d\n",msg->datalen);
}
else
{
//jaddstr(retjson,"error","couldnt add message");
printf("couldnt add message\n");
free_json(msgjson);
msgjson = 0;
}
}
portable_mutex_unlock(&myinfo->messagemutex);
return(msgjson);
int32_t keylen = 0;
keylen += iguana_rwnum(0,&key[keylen],sizeof(uint32_t),channelp);
keylen += iguana_rwnum(0,&key[keylen],sizeof(uint32_t),msgidp);
keylen += iguana_rwbignum(0,&key[keylen],sizeof(*srchashp),srchashp->bytes);
keylen += iguana_rwbignum(0,&key[keylen],sizeof(*desthashp),desthashp->bytes);
return(keylen);
}
// respond to incoming OUT, MSG
int32_t basilisk_messagekey(uint8_t *key,uint32_t channel,uint32_t msgid,bits256 srchash,bits256 desthash)
{
int32_t keylen = 0;
@ -87,116 +35,291 @@ int32_t basilisk_messagekey(uint8_t *key,uint32_t channel,uint32_t msgid,bits256
return(keylen);
}
char *basilisk_respond_OUT(struct supernet_info *myinfo,char *CMD,void *addr,char *remoteaddr,uint32_t basilisktag,cJSON *valsobj,uint8_t *data,int32_t datalen,bits256 hash,int32_t from_basilisk)
cJSON *basilisk_msgjson(struct basilisk_message *msg,uint8_t *key,int32_t keylen)
{
int32_t keylen,duration; uint8_t key[BASILISK_KEYSIZE]; bits256 senderhash;
senderhash = jbits256(valsobj,"sender");
duration = juint(valsobj,"duration");
keylen = basilisk_messagekey(key,juint(valsobj,"channel"),juint(valsobj,"msgid"),senderhash,hash);
if( bits256_nonz(senderhash) == 0 && bits256_nonz(hash) == 0 && duration > BASILISK_MSGDURATION )
duration = BASILISK_MSGDURATION;
// printf("OUT keylen.%d datalen.%d\n",keylen,datalen);
// char str[65]; printf("add message.[%d] channel.%u msgid.%x %s\n",datalen,juint(valsobj,"channel"),juint(valsobj,"msgid"),bits256_str(str,hash));
return(basilisk_respond_addmessage(myinfo,key,keylen,data,datalen,1,duration));
cJSON *msgjson=0; char *str = 0,strbuf[32768],keystr[BASILISK_KEYSIZE*2+1];
msgjson = cJSON_CreateObject();
if ( basilisk_addhexstr(&str,msgjson,strbuf,sizeof(strbuf),msg->data,msg->datalen) != 0 )
{
init_hexbytes_noT(keystr,key,keylen);
jaddstr(msgjson,"key",keystr);
jaddnum(msgjson,"expiration",msg->expiration);
jaddnum(msgjson,"duration",msg->duration);
if ( str != 0 )
free(str);
}
else
{
printf("basilisk_respond_getmessage: couldnt basilisk_addhexstr data.[%d]\n",msg->datalen);
free_json(msgjson);
msgjson = 0;
}
return(msgjson);
}
char *basilisk_iterate_MSG(struct supernet_info *myinfo,uint32_t channel,uint32_t msgid,bits256 srchash,bits256 desthash,int32_t width)
cJSON *_basilisk_respond_getmessage(struct supernet_info *myinfo,uint8_t *key,int32_t keylen)
{
uint8_t key[BASILISK_KEYSIZE]; int32_t i,keylen; cJSON *item,*retjson,*array; bits256 zero;
cJSON *msgjson = 0; struct basilisk_message *msg;
HASH_FIND(hh,myinfo->messagetable,key,keylen,msg);
if ( msg != 0 && msg->broadcast == 0 )
msgjson = basilisk_msgjson(msg,key,keylen);
return(msgjson);
}
int32_t basilisk_msgcmp(struct basilisk_message *msg,int32_t width,uint32_t channel,uint32_t msgid,bits256 srchash,bits256 desthash)
{
uint32_t keychannel,keymsgid,n=0; bits256 keysrc,keydest;
basilisk_messagekeyread(msg->key,&keychannel,&keymsgid,&keysrc,&keydest);
if ( bits256_nonz(srchash) == 0 || bits256_cmp(srchash,keysrc) == 0 )
{
if ( bits256_nonz(desthash) == 0 || bits256_cmp(desthash,keydest) == 0 )
{
while ( width >= 0 && n < 60 )
{
if ( (keymsgid == 0 || msgid == keymsgid) && (keychannel == 0 || keychannel == channel) )
return(0);
msgid--;
n++;
}
return(-1);
} else return(-2);
} else return(-3);
}
char *basilisk_iterate_MSG(struct supernet_info *myinfo,uint32_t channel,uint32_t msgid,bits256 srchash,bits256 desthash,int32_t origwidth)
{
uint8_t key[BASILISK_KEYSIZE]; int32_t i,keylen,width; cJSON *msgjson,*item,*retjson,*array; bits256 zero; struct basilisk_message *msg,*tmpmsg; uint32_t origmsgid,now = (uint32_t)time(NULL);
origmsgid = msgid;
memset(zero.bytes,0,sizeof(zero));
array = cJSON_CreateArray();
if ( width > 3600 )
if ( (width= origwidth) > 3600 )
width = 3600;
else if ( width < 1 )
width = 1;
// char str[65],str2[65]; printf("MSGiterate (%s) -> (%s)\n",bits256_str(str,srchash),bits256_str(str2,desthash));
array = cJSON_CreateArray();
portable_mutex_lock(&myinfo->messagemutex);
//printf("iterate_MSG width.%d channel.%d msgid.%d src.%llx -> %llx\n",origwidth,channel,msgid,(long long)srchash.txid,(long long)desthash.txid);
for (i=0; i<width; i++)
{
keylen = basilisk_messagekey(key,channel,msgid,srchash,desthash);
if ( (item= basilisk_respond_getmessage(myinfo,key,keylen)) != 0 )
if ( (item= _basilisk_respond_getmessage(myinfo,key,keylen)) != 0 )
{
jaddbits256(item,"src",srchash);
jaddbits256(item,"dest",desthash);
jaddi(array,item);
if ( width > 0 )
}
//keylen = basilisk_messagekey(key,channel,msgid,desthash,srchash);
//if ( (item= _basilisk_respond_getmessage(myinfo,key,keylen)) != 0 )
// jaddi(array,item);//, printf("gotmsg0.(%s)\n",jprint(item,0));
if ( origwidth > 0 )
{
if ( bits256_nonz(srchash) != 0 )
{
keylen = basilisk_messagekey(key,channel,msgid,zero,desthash);
if ( (item= basilisk_respond_getmessage(myinfo,key,keylen)) != 0 )
if ( (item= _basilisk_respond_getmessage(myinfo,key,keylen)) != 0 )
{
jaddbits256(item,"src",srchash);
jaddbits256(item,"dest",desthash);
jaddi(array,item);
}
//keylen = basilisk_messagekey(key,channel,msgid,desthash,zero);
//if ( (item= _basilisk_respond_getmessage(myinfo,key,keylen)) != 0 )
// jaddi(array,item);//, printf("gotmsg1.(%s)\n",jprint(item,0));
}
if ( bits256_nonz(desthash) != 0 )
{
keylen = basilisk_messagekey(key,channel,msgid,srchash,zero);
if ( (item= basilisk_respond_getmessage(myinfo,key,keylen)) != 0 )
if ( (item= _basilisk_respond_getmessage(myinfo,key,keylen)) != 0 )
{
jaddbits256(item,"src",srchash);
jaddbits256(item,"dest",desthash);
jaddi(array,item);
}
//keylen = basilisk_messagekey(key,channel,msgid,zero,srchash);
//if ( (item= _basilisk_respond_getmessage(myinfo,key,keylen)) != 0 )
// jaddi(array,item);//, printf("gotmsg2.(%s)\n",jprint(item,0));
}
if ( bits256_nonz(srchash) != 0 || bits256_nonz(desthash) != 0 )
if ( bits256_nonz(srchash) != 0 && bits256_nonz(desthash) != 0 )
{
keylen = basilisk_messagekey(key,channel,msgid,zero,zero);
if ( (item= basilisk_respond_getmessage(myinfo,key,keylen)) != 0 )
if ( (item= _basilisk_respond_getmessage(myinfo,key,keylen)) != 0 )
{
jaddbits256(item,"src",srchash);
jaddbits256(item,"dest",desthash);
jaddi(array,item);
}
}
}
msgid--;
iguana_rwnum(1,&key[0],sizeof(uint32_t),&msgid);
}
HASH_ITER(hh,myinfo->messagetable,msg,tmpmsg)
{
if ( bits256_nonz(srchash) == 0 )
{
if ( basilisk_msgcmp(msg,origwidth,channel,origmsgid,zero,zero) == 0 )
{
if ( (msgjson= basilisk_msgjson(msg,msg->key,msg->keylen)) != 0 )
{
jaddbits256(msgjson,"src",srchash);
jaddbits256(msgjson,"dest",desthash);
jaddi(array,msgjson);
}
}
}
if ( now > msg->expiration+60 )
{
printf("delete expired message.%p QUEUEITEMS.%d\n",msg,QUEUEITEMS);
HASH_DELETE(hh,myinfo->messagetable,msg);
QUEUEITEMS--;
free(msg);
}
}
portable_mutex_unlock(&myinfo->messagemutex);
if ( cJSON_GetArraySize(array) > 0 )
{
retjson = cJSON_CreateObject();
jaddstr(retjson,"result","success");
jadd(retjson,"messages",array);
//printf("MESSAGES.(%s)\n",jprint(array,0));
return(jprint(retjson,1));
} else return(clonestr("{\"error\":\"no messages\"}"));
}
//printf("no matching messages\n");
return(clonestr("{\"error\":\"no messages\"}"));
}
char *basilisk_respond_MSG(struct supernet_info *myinfo,char *CMD,void *addr,char *remoteaddr,uint32_t basilisktag,cJSON *valsobj,uint8_t *data,int32_t datalen,bits256 hash,int32_t from_basilisk)
char *basilisk_respond_addmessage(struct supernet_info *myinfo,uint8_t *key,int32_t keylen,uint8_t *data,int32_t datalen,int32_t sendping,uint32_t duration)
{
int32_t width; uint32_t msgid,channel;
width = juint(valsobj,"width");
msgid = juint(valsobj,"msgid");
channel = juint(valsobj,"channel");
char str[65]; printf("%s channel.%u msgid.%x datalen.%d width.%d\n",bits256_str(str,hash),juint(valsobj,"channel"),msgid,datalen,width);
return(basilisk_iterate_MSG(myinfo,channel,msgid,jbits256(valsobj,"sender"),hash,width));
struct basilisk_message *msg; bits256 desthash;
if ( keylen != BASILISK_KEYSIZE )
{
printf("basilisk_respond_addmessage keylen.%d != %d\n",keylen,BASILISK_KEYSIZE);
return(0);
}
if ( duration == 0 )
duration = BASILISK_MSGDURATION;
else if ( duration > INSTANTDEX_LOCKTIME*2 )
duration = INSTANTDEX_LOCKTIME*2;
portable_mutex_lock(&myinfo->messagemutex);
HASH_FIND(hh,myinfo->messagetable,key,keylen,msg);
if ( msg != 0 )
{
if ( msg->datalen != datalen )
{
//printf("overwrite delete of msg.[%d]\n",msg->datalen);
HASH_DELETE(hh,myinfo->messagetable,msg);
QUEUEITEMS--;
free(msg);
msg = 0;
}
else
{
if ( memcmp(msg->data,data,datalen) != 0 )
{
//printf("overwrite update of msg.[%d] <- datalen.%d\n",msg->datalen,datalen);
memcpy(msg->data,data,datalen);
if ( sendping != 0 )
queue_enqueue("basilisk_message",&myinfo->msgQ,&msg->DL);
}
portable_mutex_unlock(&myinfo->messagemutex);
return(clonestr("{\"result\":\"message updated\"}"));
}
}
msg = calloc(1,sizeof(*msg) + datalen + 16);
msg->keylen = keylen;
memcpy(msg->key,key,keylen);
msg->datalen = datalen;
memcpy(msg->data,data,datalen);
memcpy(desthash.bytes,&key[BASILISK_KEYSIZE - sizeof(desthash)],sizeof(desthash));
if ( bits256_nonz(desthash) == 0 )
msg->broadcast = 1;
msg->duration = duration;
msg->expiration = (uint32_t)time(NULL) + duration;
HASH_ADD_KEYPTR(hh,myinfo->messagetable,msg->key,msg->keylen,msg);
QUEUEITEMS++;
portable_mutex_unlock(&myinfo->messagemutex);
{
bits256 srchash,desthash; uint32_t channel,msgid;
basilisk_messagekeyread(key,&channel,&msgid,&srchash,&desthash);
//printf("add message keylen.%d [%d] msgid.%x channel.%x\n",msg->keylen,datalen,msgid,channel);
}
//if ( myinfo->NOTARY.RELAYID >= 0 )
// dpow_handler(myinfo,msg);
if ( sendping != 0 )
queue_enqueue("basilisk_message",&myinfo->msgQ,&msg->DL);
return(clonestr("{\"result\":\"message added to hashtable\"}"));
}
#include "../includes/iguana_apidefs.h"
#include "../includes/iguana_apideclares.h"
// respond to incoming OUT, MSG
HASH_ARRAY_STRING(basilisk,getmessage,hash,vals,hexstr)
char *basilisk_respond_OUT(struct supernet_info *myinfo,char *CMD,void *addr,char *remoteaddr,uint32_t basilisktag,cJSON *valsobj,uint8_t *data,int32_t datalen,bits256 hash,int32_t from_basilisk)
{
uint32_t msgid,width,channel;
if ( (msgid= juint(vals,"msgid")) == 0 )
int32_t keylen,duration; uint8_t key[BASILISK_KEYSIZE]; bits256 desthash,senderhash; char *retstr;
senderhash = jbits256(valsobj,"srchash");
desthash = jbits256(valsobj,"desthash");
duration = juint(valsobj,"duration");
keylen = basilisk_messagekey(key,juint(valsobj,"channel"),juint(valsobj,"msgid"),senderhash,desthash);
if ( bits256_nonz(hash) == 0 )
{
msgid = (uint32_t)time(NULL);
jdelete(vals,"msgid");
jaddnum(vals,"msgid",msgid);
if ( duration > BASILISK_MSGDURATION )
duration = BASILISK_MSGDURATION;
}
if ( RELAYID >= 0 )
//char str[65]; printf("add message.[%d] %s from.%s\n",datalen,bits256_str(str,hash),remoteaddr);
retstr = basilisk_respond_addmessage(myinfo,key,keylen,data,datalen,0,duration);
// printf("OUT keylen.%d datalen.%d\n",keylen,datalen);
return(retstr);
}
char *basilisk_respond_MSG(struct supernet_info *myinfo,char *CMD,void *addr,char *remoteaddr,uint32_t basilisktag,cJSON *valsobj,uint8_t *data,int32_t datalen,bits256 hash,int32_t from_basilisk)
{
int32_t width; uint32_t msgid,channel; char *retstr=0;
if ( valsobj != 0 )
{
channel = juint(vals,"channel");
width = juint(vals,"width");
return(basilisk_iterate_MSG(myinfo,channel,msgid,hash,myinfo->myaddr.persistent,width));
} else return(basilisk_standardservice("MSG",myinfo,0,myinfo->myaddr.persistent,vals,hexstr,1));
width = juint(valsobj,"width");
msgid = juint(valsobj,"msgid");
channel = juint(valsobj,"channel");
//char str[65],str2[65]; printf("%s -> %s channel.%u msgid.%x width.%d from.%s\n",bits256_str(str,jbits256(valsobj,"sender")),bits256_str(str2,jbits256(valsobj,"desthash")),juint(valsobj,"channel"),msgid,width,remoteaddr);
retstr = basilisk_iterate_MSG(myinfo,channel,msgid,jbits256(valsobj,"srchash"),jbits256(valsobj,"desthash"),width);
}
return(retstr);
}
HASH_ARRAY_STRING(basilisk,sendmessage,hash,vals,hexstr)
cJSON *dpow_getmessage(struct supernet_info *myinfo,char *jsonstr)
{
int32_t keylen,datalen; uint8_t key[BASILISK_KEYSIZE],space[16384],*data,*ptr = 0; char *retstr=0;
if ( RELAYID >= 0 )
cJSON *valsobj,*retjson = 0; char *retstr;
if ( (valsobj= cJSON_Parse(jsonstr)) != 0 )
{
keylen = basilisk_messagekey(key,juint(vals,"channel"),juint(vals,"msgid"),jbits256(vals,"sender"),hash);
if ( (data= get_dataptr(BASILISK_HDROFFSET,&ptr,&datalen,space,sizeof(space),hexstr)) != 0 )
retstr = basilisk_respond_addmessage(myinfo,key,keylen,data,datalen,0,juint(vals,"duration"));
if ( ptr != 0 )
free(ptr);
retstr = basilisk_iterate_MSG(myinfo,juint(valsobj,"channel"),juint(valsobj,"msgid"),jbits256(valsobj,"srchash"),jbits256(valsobj,"desthash"),juint(valsobj,"width"));
retjson = cJSON_Parse(retstr);
free(retstr);
}
return(retjson);
}
cJSON *dpow_addmessage(struct supernet_info *myinfo,char *jsonstr)
{
cJSON *vals,*retjson=0; char *retstr=0,*datastr; int32_t datalen,keylen; uint8_t *data=0,key[BASILISK_KEYSIZE];
if ( (vals= cJSON_Parse(jsonstr)) != 0 )
{
keylen = basilisk_messagekey(key,juint(vals,"channel"),juint(vals,"msgid"),jbits256(vals,"srchash"),jbits256(vals,"desthash"));
if ( (datastr= jstr(vals,"data")) != 0 )
{
datalen = (int32_t)strlen(datastr) >> 1;
data = malloc(datalen);
decode_hex(data,datalen,datastr);
if ( (retstr= basilisk_respond_addmessage(myinfo,key,keylen,data,datalen,0,juint(vals,"duration"))) != 0 )
retjson = cJSON_Parse(retstr);
}
if ( retstr != 0 )
free(retstr);
if ( data != 0 )
free(data);
}
if ( vals != 0 && juint(vals,"fanout") == 0 )
jaddnum(vals,"fanout",(int32_t)sqrt(NUMRELAYS)+2);
return(basilisk_standardservice("OUT",myinfo,0,hash,vals,hexstr,0));
if ( retjson == 0 )
retjson = cJSON_Parse("{\"error\":\"couldnt add message\"}");
return(retjson);
}
#include "../includes/iguana_apiundefs.h"
int32_t basilisk_channelsend(struct supernet_info *myinfo,bits256 hash,uint32_t channel,uint32_t msgid,uint8_t *data,int32_t datalen,uint32_t duration)
int32_t basilisk_channelsend(struct supernet_info *myinfo,bits256 srchash,bits256 desthash,uint32_t channel,uint32_t msgid,uint8_t *data,int32_t datalen,uint32_t duration)
{
char *retstr,*hexstr,strbuf[4096],*ptr = 0; int32_t retval = -1; cJSON *valsobj;
if ( (hexstr= basilisk_addhexstr(&ptr,0,strbuf,sizeof(strbuf),data,datalen)) != 0 )
@ -205,12 +328,14 @@ int32_t basilisk_channelsend(struct supernet_info *myinfo,bits256 hash,uint32_t
jaddnum(valsobj,"channel",channel);
if ( msgid == 0 )
msgid = (uint32_t)time(NULL);
jaddnum(valsobj,"fanout",(int32_t)sqrt(NUMRELAYS)+2);
jaddnum(valsobj,"fanout",1);//MAX(8,(int32_t)sqrt(myinfo->NOTARY.NUMRELAYS)+2));
jaddnum(valsobj,"msgid",msgid);
jaddnum(valsobj,"duration",duration);
jaddbits256(valsobj,"sender",myinfo->myaddr.persistent);
char str[65]; printf("sendmessage.[%d] channel.%u msgid.%x -> %s numrelays.%d:%d\n",datalen,channel,msgid,bits256_str(str,hash),NUMRELAYS,juint(valsobj,"fanout"));
if ( (retstr= basilisk_sendmessage(myinfo,0,0,0,hash,valsobj,hexstr)) != 0 )
jaddnum(valsobj,"timeout",1000);
jaddbits256(valsobj,"srchash",srchash);
jaddbits256(valsobj,"desthash",desthash);
//char str[65]; printf("sendmessage.[%d] channel.%u msgid.%x -> %s numrelays.%d\n",datalen,channel,msgid,bits256_str(str,desthash),myinfo->NOTARY.NUMRELAYS);
if ( (retstr= basilisk_sendmessage(myinfo,0,0,0,desthash,valsobj,hexstr)) != 0 )
free(retstr);
free_json(valsobj);
if ( ptr != 0 )
@ -220,26 +345,31 @@ int32_t basilisk_channelsend(struct supernet_info *myinfo,bits256 hash,uint32_t
return(retval);
}
int32_t basilisk_message_returned(uint8_t *data,int32_t maxlen,cJSON *item)
int32_t basilisk_message_returned(uint8_t *key,uint8_t *data,int32_t maxlen,cJSON *json)
{
char *hexstr=0; cJSON *msgobj; int32_t datalen=0,retval = -1;
if ( (msgobj= jobj(item,"message")) != 0 )
char *keystr=0,*hexstr=0; int32_t i,n,datalen=0,retval = -1; cJSON *item,*msgobj;
if ( (msgobj= jarray(&n,json,"messages")) != 0 )
{
if ( (hexstr= jstr(msgobj,"data")) != 0 && (datalen= is_hexstr(hexstr,0)) > 0 )
for (i=0; i<n; i++)
{
datalen >>= 1;
if ( datalen < maxlen )
item = jitem(msgobj,i);
if ( (keystr= jstr(item,"key")) != 0 && is_hexstr(keystr,0) == BASILISK_KEYSIZE*2 && (hexstr= jstr(item,"data")) != 0 && (datalen= is_hexstr(hexstr,0)) > 0 )
{
decode_hex(data,datalen,hexstr);
//printf("decoded hexstr.[%d]\n",datalen);
retval = datalen;
} else printf("datalen.%d < maxlen.%d\n",datalen,maxlen);
} else printf("no hexstr.%p or datalen.%d\n",hexstr,datalen);
} //else printf("no msgobj\n");
decode_hex(key,BASILISK_KEYSIZE,keystr);
datalen >>= 1;
if ( datalen <= maxlen )
{
decode_hex(data,datalen,hexstr);
//printf("decoded hexstr.[%d]\n",datalen);
retval = datalen;
} else printf("datalen.%d >= maxlen.%d\n",datalen,maxlen);
}
}
} //else printf("no hexstr.%p or datalen.%d (%s)\n",hexstr,datalen,jprint(json,0));
return(retval);
}
cJSON *basilisk_channelget(struct supernet_info *myinfo,bits256 hash,uint32_t channel,uint32_t msgid,int32_t width)
cJSON *basilisk_channelget(struct supernet_info *myinfo,bits256 srchash,bits256 desthash,uint32_t channel,uint32_t msgid,int32_t width)
{
char *retstr; cJSON *valsobj,*retarray=0,*item;
valsobj = cJSON_CreateObject();
@ -248,10 +378,21 @@ cJSON *basilisk_channelget(struct supernet_info *myinfo,bits256 hash,uint32_t ch
msgid = (uint32_t)time(NULL);
jaddnum(valsobj,"msgid",msgid);
jaddnum(valsobj,"width",width);
jaddnum(valsobj,"fanout",1);
if ( (retstr= basilisk_getmessage(myinfo,0,0,0,hash,valsobj,0)) != 0 )
jaddnum(valsobj,"timeout",BASILISK_TIMEOUT);
jaddnum(valsobj,"fanout",1);//MAX(8,(int32_t)sqrt(myinfo->NOTARY.NUMRELAYS)+1));
jaddnum(valsobj,"numrequired",1);
jaddbits256(valsobj,"srchash",srchash);
jaddbits256(valsobj,"desthash",desthash);
if ( myinfo->IAMNOTARY != 0 )
retstr = basilisk_getmessage(myinfo,0,0,0,desthash,valsobj,0);
else
{
//char str[65],str2[65];
retstr = _dex_getmessage(myinfo,jprint(valsobj,0));
//printf("channel.%u msgid.%u gotmessage.(%d) %s %s %s\n",channel,msgid,(int32_t)strlen(retstr),strlen(retstr) < 100 ? retstr : "(too long)",bits256_str(str,srchash),bits256_str(str2,desthash));
}
if ( retstr != 0 )
{
printf("channel.%u msgid.%u gotmessage.(%s)\n",channel,msgid,retstr);
if ( (retarray= cJSON_Parse(retstr)) != 0 )
{
if ( is_cJSON_Array(retarray) == 0 )
@ -269,22 +410,153 @@ cJSON *basilisk_channelget(struct supernet_info *myinfo,bits256 hash,uint32_t ch
int32_t basilisk_process_retarray(struct supernet_info *myinfo,void *ptr,int32_t (*process_func)(struct supernet_info *myinfo,void *ptr,int32_t (*internal_func)(struct supernet_info *myinfo,void *ptr,uint8_t *data,int32_t datalen),uint32_t channel,uint32_t msgid,uint8_t *data,int32_t datalen,uint32_t expiration,uint32_t duration),uint8_t *data,int32_t maxlen,uint32_t channel,uint32_t msgid,cJSON *retarray,int32_t (*internal_func)(struct supernet_info *myinfo,void *ptr,uint8_t *data,int32_t datalen))
{
cJSON *item; uint32_t duration,expiration; int32_t i,n,datalen,errs = 0;
cJSON *item; uint32_t duration,expiration; char *retstr; uint8_t key[BASILISK_KEYSIZE]; int32_t i,n,datalen,havedata = 0,errs = 0;
if ( (n= cJSON_GetArraySize(retarray)) > 0 )
{
for (i=0; i<n; i++)
{
item = jitem(retarray,i);
if ( (datalen= basilisk_message_returned(data,maxlen,item)) > 0 )
if ( jobj(item,"error") != 0 )
continue;
//printf("(%s).%d ",jprint(item,0),i);
if ( (datalen= basilisk_message_returned(key,data,maxlen,item)) > 0 )
{
duration = juint(item,"duration");
expiration = juint(item,"expiration");
if ( (*process_func)(myinfo,ptr,internal_func,channel,msgid,data,datalen,expiration,duration) < 0 )
errs++;
if ( (retstr= basilisk_respond_addmessage(myinfo,key,BASILISK_KEYSIZE,data,datalen,0,duration)) != 0 )
{
if ( (*process_func)(myinfo,ptr,internal_func,channel,msgid,data,datalen,expiration,duration) < 0 )
errs++;
else havedata++;
free(retstr);
} // else printf("duplicate.%d skipped\n",datalen);
}
}
//printf("n.%d maxlen.%d\n",n,maxlen);
}
if ( errs > 0 )
if ( havedata == 0 )
return(-1);
else if ( errs > 0 )
return(-errs);
else return(n);
else return(havedata);
}
uint32_t basilisk_majority32(int32_t *datalenp,uint32_t rawcrcs[64],int32_t datalens[64],int32_t numcrcs)
{
int32_t tally[64],candlens[64],i,j,mintally,numcandidates = 0; uint32_t candidates[64];
*datalenp = 0;
mintally = (numcrcs >> 1) + 1;
memset(tally,0,sizeof(tally));
memset(candlens,0,sizeof(candlens));
memset(candidates,0,sizeof(candidates));
if ( numcrcs > 0 )
{
for (i=0; i<numcrcs; i++)
{
//printf("%08x ",rawcrcs[i]);
for (j=0; j<numcandidates; j++)
{
if ( rawcrcs[i] == candidates[j] && datalens[i] == candlens[j] )
{
tally[j]++;
break;
}
}
if ( j == numcandidates )
{
tally[numcandidates] = 1;
candlens[numcandidates] = datalens[i];
candidates[numcandidates] = rawcrcs[i];
numcandidates++;
}
}
//printf("n.%d -> numcandidates.%d\n",i,numcandidates);
if ( numcandidates > 0 )
{
for (j=0; j<numcandidates; j++)
if ( tally[j] >= mintally )
{
*datalenp = candlens[j];
//printf("tally[%d] %d >= mintally.%d numcrcs.%d crc %08x datalen.%d\n",j,tally[j],mintally,numcrcs,candidates[j],*datalenp);
return(candidates[j]);
}
}
}
return(0);
}
uint32_t basilisk_crcrecv(struct supernet_info *myinfo,int32_t width,uint8_t *verifybuf,int32_t maxlen,int32_t *datalenp,bits256 srchash,bits256 desthash,uint32_t channel,uint32_t msgbits)
{
cJSON *retarray,*obj,*item,*msgarray; char *hexstr,*keystr,*retstr; uint32_t rawcrcs[64],crc=0; int32_t numcrcs=0,i,j,m,n,datalen,datalens[64]; uint8_t key[BASILISK_KEYSIZE];
*datalenp = 0;
memset(rawcrcs,0,sizeof(rawcrcs));
memset(datalens,0,sizeof(datalens));
if ( (retarray= basilisk_channelget(myinfo,srchash,desthash,channel,msgbits,width)) != 0 )
{
//printf("retarray.(%s)\n",jprint(retarray,0));
if ( (n= cJSON_GetArraySize(retarray)) > 0 )
{
for (i=0; i<n; i++)
{
obj = jitem(retarray,i);
if ( jobj(obj,"error") != 0 )
continue;
if ( (msgarray= jarray(&m,obj,"messages")) != 0 )
{
for (j=0; j<m; j++)
{
item = jitem(msgarray,j);
keystr = hexstr = 0;
datalen = 0;
if ( (keystr= jstr(item,"key")) != 0 && is_hexstr(keystr,0) == BASILISK_KEYSIZE*2 && (hexstr= jstr(item,"data")) != 0 && (datalen= is_hexstr(hexstr,0)) > 0 )
{
decode_hex(key,BASILISK_KEYSIZE,keystr);
datalen >>= 1;
if ( datalen < maxlen )
{
decode_hex(verifybuf,datalen,hexstr);
if ( (retstr= basilisk_respond_addmessage(myinfo,key,BASILISK_KEYSIZE,verifybuf,datalen,juint(item,"expiration"),juint(item,"duration"))) != 0 )
{
if ( numcrcs < sizeof(rawcrcs)/sizeof(*rawcrcs) )
{
rawcrcs[numcrcs] = calc_crc32(0,verifybuf,datalen);
datalens[numcrcs] = datalen;
numcrcs++;
}
free(retstr);
}
} else printf("datalen.%d >= maxlen.%d\n",datalen,maxlen);
} else printf("not keystr.%p or no data.%p or bad datalen.%d\n",keystr,hexstr,datalen);
}
}
}
//printf("n.%d maxlen.%d\n",n,maxlen);
}
free_json(retarray);
if ( (crc= basilisk_majority32(datalenp,rawcrcs,datalens,numcrcs)) != 0 )
{
//printf("have majority crc.%08x\n",crc);
}
//else printf("no majority from rawcrcs.%d\n",numcrcs);
}
return(crc);
}
uint32_t basilisk_crcsend(struct supernet_info *myinfo,int32_t width,uint8_t *verifybuf,int32_t maxlen,bits256 srchash,bits256 desthash,uint32_t channel,uint32_t msgbits,uint8_t *data,int32_t datalen,uint32_t crcs[2])
{
uint32_t crc; int32_t recvlen=0;
if ( crcs != 0 )
{
crc = calc_crc32(0,data,datalen);
if ( crcs[0] != crc )
crcs[0] = crc, crcs[1] = 0;
else
{
if ( crcs[1] == 0 )
crcs[1] = basilisk_crcrecv(myinfo,width,verifybuf,maxlen,&recvlen,srchash,desthash,channel,msgbits);
if ( crcs[0] == crcs[1] && datalen == recvlen )
return(crcs[0]);
}
}
return(0);
}

797
basilisk/basilisk_bitcoin.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -22,36 +22,6 @@
};*/
#ifdef bitcoincancalculatebalances
int64_t bitcoin_value(struct iguana_info *coin,bits256 txid,int16_t vout,char *coinaddr)
{
char params[512],str[65]; char *curlstr; cJSON *txobj,*vouts,*item,*sobj,*addrs; int32_t j,m,n; int64_t value = 0;
sprintf(params,"[\"%s\", 1]",bits256_str(str,txid));
if ( (curlstr= bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"getrawtransaction",params)) != 0 )
{
if ( (txobj= cJSON_Parse(curlstr)) != 0 )
{
if ( (vouts= jarray(&n,txobj,"vout")) != 0 && vout < n )
{
item = jitem(vouts,vout);
if ( (sobj= jobj(item,"scriptPubKey")) != 0 && (addrs= jarray(&m,sobj,"addresses")) != 0 )
{
for (j=0; j<m; j++)
{
if ( strcmp(jstri(addrs,j),coinaddr) == 0 )
{
value = SATOSHIDEN * jdouble(item,"satoshis");
break;
}
}
}
}
free_json(txobj);
}
free(curlstr);
}
return(value);
}
char *bitcoin_balance(struct iguana_info *coin,char *coinaddr,int32_t lastheight,int32_t minconf)
{
int32_t i,n,height,maxconf=1<<30; int64_t balance = 0; char params[512],*curlstr; cJSON *array,*retjson,*curljson;
@ -84,6 +54,36 @@ char *bitcoin_balance(struct iguana_info *coin,char *coinaddr,int32_t lastheight
return(jprint(retjson,1));
}
int64_t bitcoin_value(struct iguana_info *coin,bits256 txid,int16_t vout,char *coinaddr)
{
char params[512],str[65]; char *curlstr; cJSON *txobj,*vouts,*item,*sobj,*addrs; int32_t j,m,n; int64_t value = 0;
sprintf(params,"[\"%s\", 1]",bits256_str(str,txid));
if ( (curlstr= bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"getrawtransaction",params)) != 0 )
{
if ( (txobj= cJSON_Parse(curlstr)) != 0 )
{
if ( (vouts= jarray(&n,txobj,"vout")) != 0 && vout < n )
{
item = jitem(vouts,vout);
if ( (sobj= jobj(item,"scriptPubKey")) != 0 && (addrs= jarray(&m,sobj,"addresses")) != 0 )
{
for (j=0; j<m; j++)
{
if ( strcmp(jstri(addrs,j),coinaddr) == 0 )
{
value = SATOSHIDEN * jdouble(item,"satoshis");
break;
}
}
}
}
free_json(txobj);
}
free(curlstr);
}
return(value);
}
char *basilisk_bitcoinblockhashstr(char *coinstr,char *serverport,char *userpass,int32_t height)
{
char numstr[128],*blockhashstr=0; bits256 hash2; struct iguana_info *coin;
@ -290,7 +290,7 @@ int32_t basilisk_bitcoinscan(struct iguana_info *coin,uint8_t origblockspace[IGU
int32_t basilisk_bitcoinavail(struct iguana_info *coin)
{
if ( coin->VALIDATENODE != 0 || coin->FULLNODE != 0 )
if ( coin->VALIDATENODE > 0 || coin->FULLNODE > 0 )
return(1);
//else if ( coin->chain->serverport[0] != 0 )
// return(1);
@ -299,7 +299,7 @@ int32_t basilisk_bitcoinavail(struct iguana_info *coin)
void *basilisk_bitcoinbalances(struct basilisk_item *Lptr,struct supernet_info *myinfo,struct iguana_info *coin,char *remoteaddr,uint32_t basilisktag,int32_t timeoutmillis,cJSON *vals)
{
int64_t balance,total = 0; int32_t i,n,hist; cJSON *spends,*unspents,*retjson,*item,*addresses,*array = cJSON_CreateArray();
int64_t balance,total = 0; int32_t i,j,n,hist; char *str; cJSON *spends,*unspents,*retjson,*item,*addresses,*array = cJSON_CreateArray();
spends = unspents = 0;
if ( (hist= juint(vals,"history")) != 0 )
{
@ -313,13 +313,20 @@ void *basilisk_bitcoinbalances(struct basilisk_item *Lptr,struct supernet_info *
{
for (i=0; i<n; i++)
{
//if ( coin->RTheight > 0 )
balance = iguana_addressreceived(myinfo,coin,vals,remoteaddr,0,0,unspents,spends,jstri(addresses,i),juint(vals,"minconf"),juint(vals,"firstheight"));
//else balance = 0;
item = cJSON_CreateObject();
jaddnum(item,jstri(addresses,i),dstr(balance));
jaddi(array,item);
total += balance;
if ( (str= jstri(addresses,i)) != 0 )
{
for (j=0; j<n; j++)
if ( jstri(addresses,j) != 0 && strcmp(jstri(addresses,j),str) == 0 )
break;
if ( j == n )
continue;
balance = iguana_addressreceived(myinfo,coin,vals,remoteaddr,0,0,unspents,spends,str,juint(vals,"minconf"),0);//juint(vals,"firstheight"));
item = cJSON_CreateObject();
jaddnum(item,str,dstr(balance));
jaddstr(item,"address",str);
jaddi(array,item);
total += balance;
}
//printf("%.8f ",dstr(balance));
}
}
@ -327,6 +334,7 @@ void *basilisk_bitcoinbalances(struct basilisk_item *Lptr,struct supernet_info *
jaddstr(retjson,"result","success");
jaddstr(retjson,"ipaddr",myinfo->ipaddr);
jaddnum(retjson,"total",dstr(total));
jaddnum(retjson,"balance",dstr(total));
jadd(retjson,"addresses",array);
if ( unspents != 0 )
jadd(retjson,"unspents",unspents);
@ -335,6 +343,7 @@ void *basilisk_bitcoinbalances(struct basilisk_item *Lptr,struct supernet_info *
jaddnum(retjson,"RTheight",coin->RTheight);
jaddnum(retjson,"longest",coin->longestchain);
jaddnum(retjson,"lag",coin->longestchain- coin->RTheight);
//printf("BAL.(%s)\n",jprint(retjson,0));
Lptr->retstr = jprint(retjson,1);
return(Lptr);
}
@ -345,6 +354,7 @@ char *basilisk_valuestr(struct iguana_info *coin,char *coinaddr,uint64_t value,i
jaddstr(retjson,"result","success");
jaddstr(retjson,"address",coinaddr);
jadd64bits(retjson,"satoshis",value);
jaddnum(retjson,"amount",dstr(value));
jaddnum(retjson,"value",dstr(value));
jaddnum(retjson,"height",height);
jaddnum(retjson,"numconfirms",coin->blocks.hwmchain.height - height + 1);
@ -374,16 +384,18 @@ double basilisk_bitcoin_valuemetric(struct supernet_info *myinfo,struct basilisk
void *basilisk_bitcoinvalue(struct basilisk_item *Lptr,struct supernet_info *myinfo,struct iguana_info *coin,char *remoteaddr,uint32_t basilisktag,int32_t timeoutmillis,cJSON *valsobj)
{
int32_t i,height,vout,numsent; struct basilisk_item *ptr; char coinaddr[64],str[64]; struct basilisk_value *v; uint64_t value = 0; bits256 txid;
if ( RELAYID >= 0 )
int32_t i,j,height,vout,numsent; cJSON *retjson; struct basilisk_item *ptr; char coinaddr[64],str[65]; struct basilisk_value *v; uint64_t value = 0; bits256 txid; struct iguana_outpoint outpt;
if ( valsobj == 0 )
return(clonestr("{\"error\":\"null valsobj\"}"));
if ( myinfo->IAMNOTARY != 0 && myinfo->NOTARY.RELAYID >= 0 )
return(0);
txid = jbits256(valsobj,"txid");
vout = jint(valsobj,"vout");
if ( coin != 0 && basilisk_bitcoinavail(coin) != 0 )
{
if ( (coin->VALIDATENODE != 0 || coin->FULLNODE != 0) )//&& coinaddr != 0 && coinaddr[0] != 0 )
if ( (coin->VALIDATENODE > 0 || coin->FULLNODE > 0) )//&& coinaddr != 0 && coinaddr[0] != 0 )
{
if ( iguana_RTunspentindfind(myinfo,coin,coinaddr,0,0,&value,&height,txid,vout,coin->bundlescount,0) > 0 )
if ( iguana_RTunspentindfind(myinfo,coin,&outpt,coinaddr,0,0,&value,&height,txid,vout,coin->bundlescount,0) == 0 )
{
//printf("bitcoinvalue found iguana\n");
Lptr->retstr = basilisk_valuestr(coin,coinaddr,value,height,txid,vout);
@ -401,18 +413,83 @@ void *basilisk_bitcoinvalue(struct basilisk_item *Lptr,struct supernet_info *myi
if ( v->vout == vout && bits256_cmp(txid,v->txid) == 0 && strcmp(v->coinaddr,coinaddr) == 0 )
{
printf("bitcoinvalue local ht.%d %s %.8f\n",v->height,v->coinaddr,dstr(v->value));
ptr = basilisk_issueremote(myinfo,0,&numsent,"VAL",coin->symbol,1,valsobj,juint(valsobj,"fanout"),juint(valsobj,"minresults"),basilisktag,timeoutmillis,0,basilisk_valuestr(coin,v->coinaddr,v->value,v->height,txid,vout),0,0,BASILISK_DEFAULTDIFF); // this completes immediate
ptr = basilisk_issueremote(myinfo,0,&numsent,"VAL",coin->symbol,1,valsobj,juint(valsobj,"fanout"),juint(valsobj,"numrequired"),basilisktag,timeoutmillis,0,basilisk_valuestr(coin,v->coinaddr,v->value,v->height,txid,vout),0,0,BASILISK_DEFAULTDIFF); // this completes immediate
//queue_enqueue("submitQ",&myinfo->basilisks.submitQ,&ptr->DL,0);
if ( ptr->numresults > 0 )
{
retjson = cJSON_CreateArray();
for (j=0; j<ptr->numresults; j++)
jaddi(retjson,ptr->results[j]), ptr->results[j] = 0;
ptr->retstr = jprint(retjson,1);
//printf("numresults.%d (%p)\n",ptr->numresults,ptr);
}
return(ptr);
}
}
}
printf("bitcoinvalue issue remote tag.%u\n",basilisktag);
ptr = basilisk_issueremote(myinfo,0,&numsent,"VAL",coin->symbol,1,valsobj,juint(valsobj,"fanout"),juint(valsobj,"minresults"),basilisktag,timeoutmillis,0,0,0,0,BASILISK_DEFAULTDIFF);
ptr = basilisk_issueremote(myinfo,0,&numsent,"VAL",coin->symbol,1,valsobj,juint(valsobj,"fanout"),juint(valsobj,"numrequired"),basilisktag,timeoutmillis,0,0,0,0,BASILISK_DEFAULTDIFF);
if ( ptr->numresults > 0 )
{
retjson = cJSON_CreateArray();
for (j=0; j<ptr->numresults; j++)
jaddi(retjson,ptr->results[j]), ptr->results[j] = 0;
ptr->retstr = jprint(retjson,1);
//printf("numresults.%d (%p)\n",ptr->numresults,ptr);
}
//queue_enqueue("submitQ",&myinfo->basilisks.submitQ,&ptr->DL,0);
return(ptr);
}
void *basilisk_getinfo(struct basilisk_item *Lptr,struct supernet_info *myinfo,struct iguana_info *coin,char *remoteaddr,uint32_t basilisktag,int32_t timeoutmillis,cJSON *valsobj)
{
struct basilisk_item *ptr; cJSON *infojson,*retjson; int32_t j,numsent,fanout,numrequired;
if ( valsobj == 0 )
return(clonestr("{\"error\":\"null valsobj\"}"));
if ( (myinfo->IAMNOTARY != 0 || myinfo->NOTARY.RELAYID >= 0) && strcmp(coin->symbol,"RELAY") != 0 )
return(0);
if ( coin->VALIDATENODE > 0 || coin->FULLNODE > 0 || coin->notarychain >= 0 )
{
infojson = iguana_getinfo(myinfo,coin);
Lptr->retstr = jprint(infojson,1);
return(Lptr);
}
if ( (fanout= juint(valsobj,"fanout")) < 8 )
fanout = 8;
if ( (numrequired= juint(valsobj,"numrequired")) < fanout )
{
jaddnum(valsobj,"numrequired",fanout);
numrequired = 1;
}
ptr = basilisk_issueremote(myinfo,0,&numsent,"INF",coin->symbol,1,valsobj,fanout,numrequired,basilisktag,timeoutmillis,0,0,0,0,BASILISK_DEFAULTDIFF);
if ( ptr->numresults > 0 )
{
retjson = cJSON_CreateArray();
for (j=0; j<ptr->numresults; j++)
jaddi(retjson,ptr->results[j]), ptr->results[j] = 0;
ptr->retstr = jprint(retjson,1);
//printf("numresults.%d (%p)\n",ptr->numresults,ptr);
}
return(ptr);
}
int64_t iguana_getestimatedfee(struct supernet_info *myinfo,struct iguana_info *coin)
{
char *retstr; cJSON *retjson; double x; int64_t txfeeperbyte = 200;
if ( (retstr= _dex_getinfo(myinfo,coin->symbol)) != 0 )
{
if ( (retjson= cJSON_Parse(retstr)) != 0 )
{
if ( (x= jdouble(retjson,"estimatefee")) > SMALLVAL )
txfeeperbyte = 1 + (x * SATOSHIDEN) / 1024;
printf("SET txfeeperbyte %lld (%s)\n",(long long)txfeeperbyte,retstr);
free(retjson);
}
free(retstr);
}
return(txfeeperbyte);
}
int32_t basilisk_voutvin_validate(struct iguana_info *coin,char *rawtx,uint64_t inputsum,uint64_t amount,uint64_t txfee)
{
//static int counter;
@ -483,19 +560,219 @@ int32_t basilisk_vins_validate(struct supernet_info *myinfo,struct iguana_info *
return(retval);
}
char *basilisk_bitcoinrawtx(struct supernet_info *myinfo,struct iguana_info *coin,char *remoteaddr,uint32_t basilisktag,int32_t timeoutmillis,cJSON *valsobj)
int64_t iguana_esttxfee(struct supernet_info *myinfo,struct iguana_info *coin,char *rawtx,char *signedtx,int32_t numvins)
{
int64_t txfee = 0;
if ( coin->estimatedfee == 0 )
coin->estimatedfee = iguana_getestimatedfee(myinfo,coin);
if ( signedtx != 0 )
{
txfee = coin->estimatedfee * (strlen(signedtx)/2 + numvins);
free(signedtx);
}
else if ( rawtx != 0 )
{
txfee = coin->estimatedfee * (strlen(rawtx)/2 + numvins * 110);
free(rawtx);
}
return(txfee);
}
char *iguana_utxoduplicates(struct supernet_info *myinfo,struct iguana_info *coin,uint8_t *pubkey33,uint64_t satoshis,int32_t duplicates,int32_t *completedp,bits256 *signedtxidp,int32_t sendflag,cJSON *addresses)
{
uint8_t script[35]; int64_t txfee; int32_t i,spendlen; cJSON *txobj=0,*vins=0; char *rawtx=0,*signedtx=0,changeaddr[64];
*completedp = 0;
if ( signedtxidp != 0 )
memset(signedtxidp,0,sizeof(*signedtxidp));
bitcoin_address(changeaddr,coin->chain->pubtype,myinfo->persistent_pubkey33,33);
txfee = (coin->txfee + duplicates*coin->txfee*2);
if ( (txobj= bitcoin_txcreate(coin->symbol,coin->chain->isPoS,0,1,0)) != 0 )
{
if ( duplicates <= 0 )
duplicates = 1;
spendlen = bitcoin_pubkeyspend(script,0,pubkey33);
for (i=0; i<duplicates; i++)
bitcoin_txoutput(txobj,script,spendlen,satoshis);
rawtx = iguana_calcrawtx(myinfo,coin,&vins,txobj,satoshis * duplicates,changeaddr,txfee,addresses,0,0,0,0,"127.0.0.1",0,1);
if ( strcmp(coin->chain->symbol,"BTC") == 0 && cJSON_GetArraySize(vins) > duplicates/2 )
{
free(rawtx);
rawtx = 0;
fprintf(stderr,"No point to recycle utxo when trying to create utxo duplicates, numvins.%d vs duplicates.%d\n",cJSON_GetArraySize(vins),duplicates);
free_json(vins);
return(rawtx);
}
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 )
{
if ( *completedp != 0 )
{
printf("splitfunds signedtx.(%s)\n",signedtx);
if ( sendflag != 0 )
iguana_sendrawtransaction(myinfo,coin,signedtx);
free(rawtx);
rawtx = signedtx, signedtx = 0;
}
} else printf("error signing raw %s utxoduplicates tx\n",coin->symbol);
}
}
if ( vins != 0 )
free_json(vins);
if ( txobj != 0 )
free_json(txobj);
return(rawtx);
}
int64_t iguana_verifytimelock(struct supernet_info *myinfo,struct iguana_info *coin,uint32_t timelocked,char *destaddr,bits256 txid,int32_t vout)
{
uint8_t script[35],script2[35],p2shscript[128],rmd160[20],addrtype; char *retstr,*spendscriptstr; int32_t p2shlen,spendlen; cJSON *sobj,*txout=0; int64_t value = 0;
bitcoin_addr2rmd160(&addrtype,rmd160,destaddr);
if ( addrtype != coin->chain->pubtype )
return(-1);
p2shlen = bitcoin_timelockspend(p2shscript,0,rmd160,timelocked);
calc_rmd160(0,rmd160,p2shscript,p2shlen);
spendlen = bitcoin_p2shspend(script,0,rmd160);
if ( coin->FULLNODE != 0 )
txout = dpow_gettxout(myinfo,coin,txid,vout);
else if ( (retstr= _dex_gettxout(myinfo,coin->symbol,txid,vout)) != 0 )
{
txout = cJSON_Parse(retstr);
free(retstr);
}
if ( txout != 0 )
{
if ( (sobj= jobj(txout,"scriptPubKey")) != 0 && (spendscriptstr= jstr(sobj,"hex")) == 0 )
{
if ( strlen(spendscriptstr) == spendlen*2 )
{
decode_hex(script2,spendlen,spendscriptstr);
if ( memcmp(script,script2,spendlen) != 0 )
return(-2);
value = SATOSHIDEN * jdouble(txout,"value");
} else return(-4);
}
free_json(txout);
return(value);
} return(-2);
}
char *iguana_utxorawtx(struct supernet_info *myinfo,struct iguana_info *coin,int32_t timelock,char *destaddr,char *changeaddr,int64_t *satoshis,int32_t numoutputs,uint64_t txfee,int32_t *completedp,int32_t sendflag,cJSON *utxos,cJSON *privkeys)
{
uint8_t script[35],p2shscript[128],rmd160[20],addrtype; bits256 txid; int32_t i,p2shlen,iter,spendlen; cJSON *retjson,*txcopy,*txobj=0,*vins=0; char *rawtx=0,*signedtx=0; uint32_t timelocked = 0;
*completedp = 0;
if ( iguana_addressvalidate(coin,&addrtype,destaddr) < 0 || iguana_addressvalidate(coin,&addrtype,changeaddr) < 0 )
return(clonestr("{\"error\":\"invalid coin address\"}"));
bitcoin_addr2rmd160(&addrtype,rmd160,changeaddr);
if ( addrtype != coin->chain->pubtype )
return(clonestr("{\"error\":\"invalid changeaddr type\"}"));
bitcoin_addr2rmd160(&addrtype,rmd160,destaddr);
if ( addrtype != coin->chain->pubtype )
return(clonestr("{\"error\":\"invalid dest address type\"}"));
if ( txfee == 0 && strcmp(coin->symbol,"BTC") != 0 && (txfee= coin->txfee) == 0 )
txfee = coin->chain->txfee;
retjson = cJSON_CreateObject();
if ( (txobj= bitcoin_txcreate(coin->symbol,coin->chain->isPoS,0,1,0)) != 0 )
{
if ( timelock == 0 )
spendlen = bitcoin_standardspend(script,0,rmd160);
else
{
timelocked = (uint32_t)(time(NULL)+timelock);
if ( (timelocked % 3600) != 0 )
timelocked += (3600 - (timelocked % 3600));
p2shlen = bitcoin_timelockspend(p2shscript,0,rmd160,timelocked);
calc_rmd160(0,rmd160,p2shscript,p2shlen);
spendlen = bitcoin_p2shspend(script,0,rmd160);
printf("timelock.%d spend timelocked %u\n",timelock,timelocked);
}
for (i=0; i<numoutputs; i++)
if ( satoshis[i] > 0 )
bitcoin_txoutput(txobj,script,spendlen,satoshis[i]);
for (iter=0; iter<2; iter++)
{
txcopy = jduplicate(txobj);
if ( (rawtx= iguana_calcutxorawtx(myinfo,coin,&vins,txobj,satoshis,numoutputs,changeaddr,txfee,utxos,"",0,0)) != 0 )
{
if ( iter == 1 || txfee != 0 )
jaddstr(retjson,"rawtx",rawtx);
if ( (signedtx= iguana_signrawtx(myinfo,coin,0,&txid,completedp,vins,rawtx,privkeys,0)) != 0 )
{
if ( (iter == 1 || txfee != 0) && *completedp != 0 )
{
jaddbits256(retjson,"txid",txid);
jaddstr(retjson,"signedtx",signedtx);
if ( sendflag != 0 )
{
txid = iguana_sendrawtransaction(myinfo,coin,signedtx);
jaddbits256(retjson,"sent",txid);
} else printf("dont send signedtx.(%s)\n",signedtx);
}
} else printf("error signing raw utxorawtx tx\n");
} else printf("null rawtx from calcutxorawtx\n");
if ( txfee != 0 )
{
free_json(txcopy);
break;
}
else // must be BTC and txfee == 0
{
txfee = iguana_esttxfee(myinfo,coin,rawtx,signedtx,cJSON_GetArraySize(vins));
free_json(vins);
rawtx = signedtx = 0;
vins = 0;
*completedp = 0;
txobj = txcopy;
}
}
}
if ( timelock != 0 )
{
jaddnum(retjson,"timelock",timelock);
jaddnum(retjson,"timelocked",timelocked);
}
jaddstr(retjson,"result","success");
if ( *completedp != 0 )
jadd(retjson,"completed",jtrue());
else jadd(retjson,"completed",jfalse());
if ( vins != 0 )
free_json(vins);
if ( txobj != 0 )
free_json(txobj);
if ( rawtx != 0 )
{
jaddstr(retjson,"rawtx",rawtx);
free(rawtx);
}
if ( signedtx != 0 )
{
jaddstr(retjson,"signedtx",signedtx);
free(signedtx);
}
return(jprint(retjson,1));
}
char *basilisk_bitcoinrawtx(struct supernet_info *myinfo,struct iguana_info *coin,char *remoteaddr,uint32_t basilisktag,int32_t timeoutmillis,cJSON *valsobj,struct vin_info *V)
{
uint8_t buf[4096]; int32_t oplen,offset,minconf,spendlen; cJSON *vins,*addresses,*txobj = 0; uint32_t locktime; char *opreturn,*spendscriptstr,*changeaddr,*rawtx = 0; int64_t amount,txfee,burnamount;
if ( RELAYID >= 0 )
return(clonestr("{\"error\":\"special relays only do OUT and MSG\"}"));
if ( valsobj == 0 )
return(clonestr("{\"error\":\"null valsobj\"}"));
//if ( myinfo->IAMNOTARY != 0 || myinfo->NOTARY.RELAYID >= 0 )
// return(clonestr("{\"error\":\"special relays only do OUT and MSG\"}"));
vins = 0;
changeaddr = jstr(valsobj,"changeaddr");
if ( (amount= j64bits(valsobj,"satoshis")) == 0 )
amount = jdouble(valsobj,"value") * SATOSHIDEN;
if ( (txfee= j64bits(valsobj,"txfee")) == 0 )
txfee = coin->chain->txfee;
if ( txfee == 0 )
txfee = 10000;
{
//if ( strcmp(coin->symbol,"BTC") != 0 )
{
txfee = coin->chain->txfee;
if ( txfee < 50000 )
txfee = 50000;
}
}
spendscriptstr = jstr(valsobj,"spendscript");
minconf = juint(valsobj,"minconf");
locktime = jint(valsobj,"locktime");
@ -504,13 +781,13 @@ char *basilisk_bitcoinrawtx(struct supernet_info *myinfo,struct iguana_info *coi
addresses = iguana_getaddressesbyaccount(myinfo,coin,"*");
jadd(valsobj,"addresses",addresses);
}
//printf("use addresses.(%s)\n",jprint(addresses,0));
printf("use addresses.(%s) (%s)\n",jprint(addresses,0),spendscriptstr!=0?spendscriptstr:"no script");
//printf("(%s) vals.(%s) change.(%s) spend.%s\n",coin->symbol,jprint(valsobj,0),changeaddr,spendscriptstr);
if ( changeaddr == 0 || changeaddr[0] == 0 || spendscriptstr == 0 || spendscriptstr[0] == 0 )
return(clonestr("{\"error\":\"invalid changeaddr or spendscript or addresses\"}"));
if ( coin != 0 )//&& basilisk_bitcoinavail(coin) != 0 )
if ( coin != 0 )
{
if ( (txobj= bitcoin_txcreate(coin->chain->isPoS,locktime,locktime==0?coin->chain->normal_txversion:coin->chain->locktime_txversion)) != 0 )
if ( (txobj= bitcoin_txcreate(coin->symbol,coin->chain->isPoS,locktime,locktime==0?coin->chain->normal_txversion:coin->chain->locktime_txversion,juint(valsobj,"timestamp"))) != 0 )
{
spendlen = (int32_t)strlen(spendscriptstr) >> 1;
decode_hex(buf,spendlen,spendscriptstr);
@ -519,17 +796,28 @@ char *basilisk_bitcoinrawtx(struct supernet_info *myinfo,struct iguana_info *coi
if ( (opreturn= jstr(valsobj,"opreturn")) != 0 && (oplen= is_hexstr(opreturn,0)) > 0 )
{
oplen >>= 1;
if ( (strcmp("BTC",coin->symbol) == 0 && oplen < 77) || coin->chain->do_opreturn == 0 )
if ( (strcmp("BTC",coin->symbol) == 0 && oplen < 76) || coin->chain->do_opreturn == 0 )
{
decode_hex(&buf[sizeof(buf) - oplen],oplen,opreturn);
spendlen = datachain_datascript(coin,buf,&buf[sizeof(buf) - oplen],oplen);
if ( (burnamount= SATOSHIDEN * jdouble(valsobj,"burn")) < 10000 )
burnamount = 10000;
{
//burnamount = 10000;
printf("low burnamount %.8f\n",dstr(burnamount));
}
bitcoin_txoutput(txobj,buf,spendlen,burnamount);
oplen = 0;
} else oplen = datachain_opreturnscript(coin,buf,opreturn,oplen);
}
rawtx = iguana_calcrawtx(myinfo,coin,&vins,txobj,amount,changeaddr,txfee,addresses,minconf,oplen!=0?buf:0,oplen+offset,burnamount,remoteaddr);
rawtx = iguana_calcrawtx(myinfo,coin,&vins,txobj,amount,changeaddr,txfee,addresses,minconf,oplen!=0?buf:0,oplen+offset,burnamount,remoteaddr,V,1);
if ( txfee == 0 )
{
txfee = iguana_esttxfee(myinfo,coin,rawtx,0,vins != 0 ? cJSON_GetArraySize(vins): 0);
if ( vins != 0 )
free_json(vins), vins = 0;
rawtx = iguana_calcrawtx(myinfo,coin,&vins,txobj,amount,changeaddr,txfee,addresses,minconf,oplen!=0?buf:0,oplen+offset,burnamount,remoteaddr,V,1);
printf("new txfee %.8f (%s)\n",dstr(txfee),rawtx);
}
//printf("generated.(%s) vins.(%s)\n",rawtx!=0?rawtx:"",vins!=0?jprint(vins,0):"");
}
if ( rawtx != 0 )
@ -552,7 +840,6 @@ char *basilisk_bitcoinrawtx(struct supernet_info *myinfo,struct iguana_info *coi
return(clonestr("{\"error\":\"couldnt create rawtx\"}"));
}
return(clonestr("{\"error\":\"dont have coin to create rawtx\"}"));
//return(basilisk_issueremote(myinfo,0,&numsent,"RAW",coin->symbol,1,valsobj,juint(valsobj,"fanout"),juint(valsobj,"minresults"),basilisktag,timeoutmillis,0,0,0,0,BASILISK_DEFAULTDIFF));
}
/*
@ -585,7 +872,7 @@ char *basilisk_bitcoinrawtx(struct supernet_info *myinfo,struct iguana_info *coi
*/
#ifdef later
#ifdef oldway
int32_t instantdex_feetxverify(struct supernet_info *myinfo,struct iguana_info *coin,struct basilisk_swap *swap,cJSON *argjson)
{
@ -776,131 +1063,9 @@ cJSON *BTC_makeclaimfunc(struct supernet_info *myinfo,struct exchange_info *exch
}
#endif
#include "../includes/iguana_apidefs.h"
#include "../includes/iguana_apideclares.h"
HASH_ARRAY_STRING(basilisk,value,hash,vals,hexstr)
{
char *retstr=0,*symbol; uint32_t basilisktag; struct basilisk_item *ptr,Lptr; int32_t timeoutmillis;
if ( RELAYID >= 0 )
return(clonestr("{\"error\":\"special relays only do OUT and MSG\"}"));
//if ( coin == 0 )
{
if ( (symbol= jstr(vals,"symbol")) != 0 || (symbol= jstr(vals,"coin")) != 0 )
coin = iguana_coinfind(symbol);
}
if ( jobj(vals,"fanout") == 0 )
jaddnum(vals,"fanout",(int32_t)sqrt(NUMRELAYS)+1);
if ( coin != 0 )
{
if ( (basilisktag= juint(vals,"basilisktag")) == 0 )
basilisktag = rand();
if ( (timeoutmillis= juint(vals,"timeout")) <= 0 )
timeoutmillis = BASILISK_TIMEOUT;
if ( coin->FULLNODE != 0 && (ptr= basilisk_bitcoinvalue(&Lptr,myinfo,coin,remoteaddr,basilisktag,timeoutmillis,vals)) != 0 )
{
retstr = ptr->retstr, ptr->retstr = 0;
ptr->finished = (uint32_t)time(NULL);
return(retstr);
}
}
return(basilisk_standardservice("VAL",myinfo,0,hash,vals,hexstr,1));
}
/*HASH_ARRAY_STRING(basilisk,rawtx,hash,vals,hexstr)
{
char *retstr=0,*symbol; uint32_t basilisktag; struct basilisk_item *ptr,Lptr; int32_t timeoutmillis,i,retval = -1; uint64_t amount,txfee; cJSON *retarray;
//if ( coin == 0 )
{
if ( (symbol= jstr(vals,"symbol")) != 0 || (symbol= jstr(vals,"coin")) != 0 )
coin = iguana_coinfind(symbol);
}
if ( jobj(vals,"numrequired") == 0 )
jaddnum(vals,"numrequired",myinfo->numrelays);
if ( jobj(vals,"fanout") == 0 )
jaddnum(vals,"fanout",(int32_t)sqrt(myinfo->numrelays));
if ( coin != 0 )
{
if ( juint(vals,"burn") == 0 )
jaddnum(vals,"burn",0.0001);
if ( (basilisktag= juint(vals,"basilisktag")) == 0 )
basilisktag = rand();
if ( (timeoutmillis= juint(vals,"timeout")) <= 0 )
timeoutmillis = BASILISK_TIMEOUT;
if ( (ptr= basilisk_bitcoinrawtx(&Lptr,myinfo,coin,remoteaddr,basilisktag,timeoutmillis,vals)) != 0 )
{
if ( (retstr= ptr->retstr) != 0 )
{
if ( (amount= j64bits(vals,"satoshis")) == 0 )
amount = jdouble(vals,"value") * SATOSHIDEN;
if ( (txfee= j64bits(vals,"txfee")) == 0 )
txfee = coin->chain->txfee;
if ( txfee == 0 )
txfee = 10000;
retval = -1;
if ( (retarray= cJSON_Parse(retstr)) != 0 )
{
if ( is_cJSON_Array(retarray) != 0 )
{
for (i=0; i<cJSON_GetArraySize(retarray); i++)
{
if ( basilisk_vins_validate(myinfo,coin,jitem(retarray,i),amount,txfee) == 0 )
{
retval = 0;
break;
}
}
} else retval = basilisk_vins_validate(myinfo,coin,retarray,amount,txfee);
if ( retval < 0 )
{
printf("ERROR.(%s)\n",retstr);
free(retstr);
retstr = clonestr("{\"error\":\"invalid vin in rawtx\"}");
}
}
ptr->retstr = 0;
ptr->finished = (uint32_t)time(NULL);
}
}
}
return(retstr);
}*/
cJSON *basilisk_history_item(struct iguana_info *coin,int64_t *totalp,char *coinaddr,int64_t value,uint32_t timestamp,bits256 txid,char *vinvoutstr,int32_t vinvout,int32_t height,char *otherheightstr,int32_t otherheight,uint64_t relaymask,int32_t ismine)
{
cJSON *item,*details;
item = cJSON_CreateObject();
jaddstr(item,"address",coinaddr);
jaddnum(item,"amount",dstr(value));
jaddnum(item,"numseconds",time(NULL) - timestamp);
details = cJSON_CreateObject();
if ( ismine > 0 )
{
jaddnum(details,"ismine",ismine);
if ( strcmp(vinvoutstr,"spentheight") == 0 )
jaddstr(details,"category","sent");
else jaddstr(details,"category","received");
}
jaddbits256(details,"txid",txid);
jaddnum(details,vinvoutstr,vinvout);
jaddnum(details,"height",height);
if ( coin->blocks.hwmchain.height > 0 )
jaddnum(details,"confirms",coin->blocks.hwmchain.height - height);
jaddnum(details,"height",height);
if ( otherheight != 0 )
jaddnum(details,otherheightstr,otherheight);
else *totalp += value;
jaddnum(details,"relays",bitweight(relaymask));
jadd(item,"details",details);
return(item);
}
#include "../includes/iguana_apiundefs.h"
int32_t basilisk_unspentfind(struct supernet_info *myinfo,struct iguana_info *coin,bits256 *txidp,int32_t *voutp,uint8_t *spendscript,struct iguana_outpoint outpt,int64_t value)
{
struct basilisk_unspent *bu; int32_t i,spendlen; struct iguana_waccount *wacct,*tmp; struct iguana_waddress *waddr,*tmp2; char str[65];
struct iguana_waccount *wacct,*tmp; struct iguana_waddress *waddr,*tmp2;
memset(txidp,0,sizeof(*txidp));
*voutp = -1;
portable_mutex_lock(&myinfo->bu_mutex);
@ -908,223 +1073,115 @@ int32_t basilisk_unspentfind(struct supernet_info *myinfo,struct iguana_info *co
{
HASH_ITER(hh,wacct->waddr,waddr,tmp2)
{
for (i=0; i<waddr->numunspents; i++)
{
bu = &waddr->unspents[i];
if ( bu->hdrsi == outpt.hdrsi && bu->unspentind == outpt.unspentind && bu->value == value )
{
if ( bu->status == 0 )
{
*txidp = bu->txid;
*voutp = bu->vout;
memcpy(spendscript,bu->script,bu->spendlen);
spendlen = bu->spendlen;
portable_mutex_unlock(&myinfo->bu_mutex);
return(spendlen);
} else printf("unspentfind skip %s/v%d\n",bits256_str(str,bu->txid),bu->vout);
}
}
printf("need to port basilisk_unspentfind\n");
}
}
portable_mutex_unlock(&myinfo->bu_mutex);
return(-1);
}
struct basilisk_spend *basilisk_addspend(struct supernet_info *myinfo,char *symbol,bits256 txid,uint16_t vout,int32_t addflag)
cJSON *basilisk_jsonmerge(char *symbol,cJSON *array)
{
int32_t i; struct basilisk_spend *s;
// mutex
if ( myinfo->numspends > 0 )
int32_t i,j,n,m; cJSON *jobj,*iobj,*dest = cJSON_CreateArray();
if ( dest != 0 && (n= cJSON_GetArraySize(array)) > 0 )
{
for (i=0; i<myinfo->numspends; i++)
for (i=0; i<n; i++)
{
if ( myinfo->spends[i].vout == vout && bits256_cmp(txid,myinfo->spends[i].txid) == 0 )
m = cJSON_GetArraySize(dest);
iobj = jitem(array,i);
for (j=0; j<m; j++)
{
char str[65]; printf("found spend.%s v%d skip it\n",bits256_str(str,txid),vout);
return(&myinfo->spends[i]);
jobj = jitem(dest,j);
if ( bits256_cmp(jbits256(jobj,"txid"),jbits256(iobj,"txid")) == 0 && jint(jobj,"vout") == jint(iobj,"vout") )
{
//printf("(%s) == (%s)\n",jprint(iobj,0),jprint(jobj,0));
break;
}
}
if ( j == m )
{
jaddi(dest,jduplicate(iobj));
//printf("add.(%s) ",jprint(iobj,0));
} //else printf("j.%d != m.%d\n",j,m);
}
}
if ( addflag != 0 && i == myinfo->numspends )
{
printf("realloc spends.[%d] %p\n",myinfo->numspends,myinfo->spends);
myinfo->spends = realloc(myinfo->spends,sizeof(*myinfo->spends) * (myinfo->numspends+1));
printf("allocated spends.[%d] %p\n",myinfo->numspends+1,myinfo->spends);
s = &myinfo->spends[myinfo->numspends++];
memset(s,0,sizeof(*s));
s->txid = txid;
s->vout = vout;
strcpy(s->symbol,symbol);
//char str[65]; printf("ADDSPEND.%s %s/v%d\n",symbol,bits256_str(str,txid),vout);
// mutex
return(s);
}
// mutex
return(0);
return(dest);
}
void basilisk_unspent_update(struct supernet_info *myinfo,struct iguana_info *coin,cJSON *item,int32_t spentheight,int32_t relayid,int32_t RTheight)
void basilisk_unspent_update(struct supernet_info *myinfo,struct iguana_info *coin,cJSON *json)
{
//{"txid":"4814dc8a357f93f16271eb43806a69416ec41ab1956b128d170402b0a1b37c7f","vout":2,"address":"RSyKVKNxrSDc1Vwvh4guYb9ZDEpvMFz2rm","scriptPubKey":"76a914c210f6711e98fe9971757ede2b2dcb0507f3f25e88ac","amount":9.99920000,"timestamp":1466684518,"height":1160306,"confirmations":22528,"checkind":1157,"spent":{"hdrsi":2320,"pkind":168,"unspentind":1157,"prevunspentind":0,"satoshis":"999920000","txidind":619,"vout":2,"type":2,"fileid":0,"scriptpos":0,"scriptlen":25},"spentheight":1161800,"dest":{"error":"couldnt find spent info"}}
int32_t i,n,j,m,already_spent=0; struct basilisk_unspent bu,bu2; char *address,*script=0,*destaddr; struct iguana_waccount *wacct; struct iguana_waddress *waddr=0; cJSON *dest,*vouts,*vitem; double ratio;
if ( (address= jstr(item,"address")) != 0 && (script= jstr(item,"scriptPubKey")) != 0 && (waddr= iguana_waddresssearch(myinfo,&wacct,address)) != 0 )
cJSON *unspents,*spends,*item; int32_t n; char *address; //struct iguana_waccount *wacct; struct iguana_waddress *waddr=0;
if ( (spends= jarray(&n,json,"spends")) != 0 && n > 0 )
{
if ( relayid >= 64 )
relayid = 0;
memset(&bu,0,sizeof(bu));
bu.spendlen = (int32_t)strlen(script) >> 1;
if ( bu.spendlen > sizeof(bu.script) )
item = jitem(spends,0);
if ( (address= jstr(item,"address")) != 0 )//&& (waddr= iguana_waddresssearch(myinfo,&wacct,address)) != 0 )
{
printf("spendscript too big.%d\n",bu.spendlen);
return;
}
strcpy(bu.symbol,coin->symbol);
bu.txid = jbits256(item,"txid");
bu.vout = jint(item,"vout");
bu.value = jdouble(item,"amount") * SATOSHIDEN;
bu.height = jint(item,"height");
bu.hdrsi = (bu.height / coin->chain->bundlesize);
bu.unspentind = juint(item,"checkind");
bu.timestamp = juint(item,"timestamp");
decode_hex(bu.script,bu.spendlen,script);
//printf("unspentupdate.(%s)\n",jprint(item,0));
n = waddr->numunspents;
for (i=0; i<n; i++)
{
bu2 = waddr->unspents[i];
bu2.status = 0;
bu2.RTheight = bu2.spentheight = 0;
bu2.relaymask = 0;
if ( memcmp(&bu,&bu2,sizeof(bu)) == 0 )
{
if ( waddr->unspents[i].RTheight > RTheight )
RTheight = waddr->unspents[i].RTheight;
already_spent = waddr->unspents[i].spentheight;
bu.relaymask = waddr->unspents[i].relaymask;
if ( (bu.status= waddr->unspents[i].status) != 0 )
{
//printf("mempool spend for %s/%d\n",bits256_str(str,bu.txid),bu.vout);
}
break;
}
}
bu.RTheight = RTheight;
bu.relaymask |= ((uint64_t)1 << relayid);
//printf("relayid.%d -> %llx wt.%d\n",relayid,(long long)bu.relaymask,bitweight(bu.relaymask));
if ( spentheight != 0 )
already_spent = spentheight;
if ( (bu.spentheight= already_spent) != 0 )
bu.status = 1;
//printf("i.%d n.%d\n",i,n);
if ( i == n )
{
if ( i >= waddr->maxunspents )
{
waddr->maxunspents += 16;
waddr->unspents = realloc(waddr->unspents,sizeof(*waddr->unspents) * waddr->maxunspents);
//printf("allocate max.%d for %s\n",waddr->maxunspents,waddr->coinaddr);
}
waddr->numunspents++;
//printf("new unspent.%s %d script.%p [%d]\n",waddr->coinaddr,waddr->numunspents,bu.script,bu.spendlen);
if ( myinfo->Cspends == 0 )
myinfo->Cspends = cJSON_CreateObject();
if ( jobj(myinfo->Cspends,coin->symbol) != 0 )
jdelete(myinfo->Cspends,coin->symbol);
jadd(myinfo->Cspends,coin->symbol,basilisk_jsonmerge(coin->symbol,spends));
//printf("S.(%s)\n",jprint(waddr->Cspends,0));
}
waddr->unspents[i] = bu;
//PREVENT DOUBLE SPENDS!!! and use p2sh
if ( i == n && bu.spentheight != 0 && (dest= jobj(item,"dest")) != 0 )
//printf("merge spends.(%s)\n",jprint(spends,0));
}
if ( (unspents= jarray(&n,json,"unspents")) != 0 && n > 0 )
{
item = jitem(unspents,0);
if ( (address= jstr(item,"address")) != 0 )//&& (waddr= iguana_waddresssearch(myinfo,&wacct,address)) != 0 )
{
struct basilisk_spend *s;
//{"txid":"cd4fb72f871d481c534f15d7f639883958936d49e965f58276f0925798e762df","vin":1,"height":<spentheight>,"unspentheight":<bu.height>,"relays":2}},
if ( (s= basilisk_addspend(myinfo,coin->symbol,bu.txid,bu.vout,1)) != 0 )
{
s->spentfrom = jbits256(dest,"spentfrom");
s->vini = jint(dest,"vin");
s->height = bu.spentheight;
s->timestamp = juint(dest,"timestamp");
s->unspentheight = bu.height;
s->relaymask = bu.relaymask;
ratio = jdouble(dest,"ratio");
if ( (vouts= jobj(dest,"vouts")) != 0 && (m= cJSON_GetArraySize(vouts)) > 0 )
{
for (j=0; j<m; j++)
{
vitem = jitem(vouts,j);
if ( (destaddr= jfieldname(vitem)) != 0 )
{
safecopy(s->destaddr,destaddr,sizeof(s->destaddr));
s->ismine = (iguana_waddresssearch(myinfo,&wacct,destaddr) != 0);
s->value = jdouble(vitem,jfieldname(vitem)) * SATOSHIDEN;
//printf("(%s %.8f) ",s->destaddr,dstr(s->value));
}
}
//char str[65]; printf("SPEND dest.(%s) ratio %.8f (%s/v%d)\n",jprint(dest,0),ratio,bits256_str(str,s->txid),s->vini);
}
}
if ( myinfo->Cunspents == 0 )
myinfo->Cunspents = cJSON_CreateObject();
if ( jobj(myinfo->Cunspents,coin->symbol) != 0 )
jdelete(myinfo->Cunspents,coin->symbol);
jadd(myinfo->Cunspents,coin->symbol,basilisk_jsonmerge(coin->symbol,unspents));
//printf("U.(%s)\n",jprint(myinfo->Cunspents,0));
}
} else printf("waddr.%p script.%p address.%p %s\n",waddr,script,address,address!=0?address:"");
//printf("merge unspents.(%s)\n",jprint(unspents,0));
}
}
void basilisk_relay_unspentsprocess(struct supernet_info *myinfo,struct iguana_info *coin,cJSON *relayjson)
void basilisk_unspents_process(struct supernet_info *myinfo,struct iguana_info *coin,char *retstr)
{
int32_t RTheight,relayid,num,j; cJSON *unspents,*spends;
RTheight = jint(relayjson,"RTheight");
if ( (relayid= basilisk_relayid(myinfo,(uint32_t)calc_ipbits(jstr(relayjson,"relay")))) < BASILISK_MAXRELAYS )
{
coin->relay_RTheights[relayid] = RTheight;
}
//printf("basilisk_relay_unspentsprocess relayid.%d RT.%d (%s)\n",relayid,RTheight,jprint(relayjson,0));
if ( (unspents= jarray(&num,relayjson,"unspents")) != 0 )
{
for (j=0; j<num; j++)
basilisk_unspent_update(myinfo,coin,jitem(unspents,j),0,relayid,RTheight);
}
if ( (spends= jarray(&num,relayjson,"spends")) != 0 )
cJSON *retarray; int32_t i,n;
portable_mutex_lock(&myinfo->bu_mutex);
if ( myinfo->Cspends != 0 )
free_json(myinfo->Cspends), myinfo->Cspends = 0;
if ( myinfo->Cunspents != 0 )
free_json(myinfo->Cunspents), myinfo->Cunspents = 0;
if ( (retarray= cJSON_Parse(retstr)) != 0 )
{
for (j=0; j<num; j++)
basilisk_unspent_update(myinfo,coin,jitem(spends,j),jint(jitem(spends,j),"spentheight"),relayid,RTheight);
if ( is_cJSON_Array(retarray) != 0 )
{
n = cJSON_GetArraySize(retarray);
for (i=0; i<n; i++)
basilisk_unspent_update(myinfo,coin,jitem(retarray,i));
} else basilisk_unspent_update(myinfo,coin,retarray);
free_json(retarray);
}
portable_mutex_unlock(&myinfo->bu_mutex);
}
cJSON *basilisk_balance_valsobj(struct supernet_info *myinfo,struct iguana_info *coin)
{
int32_t oldest,i,RTheight; cJSON *vals;
for (i=oldest=0; i<BASILISK_MAXRELAYS; i++)
if ( (RTheight= coin->relay_RTheights[i]) != 0 && (oldest == 0 || RTheight < oldest) )
oldest = RTheight;
vals = cJSON_CreateObject();
jaddnum(vals,"firstheight",oldest);
jaddnum(vals,"history",3);
jaddstr(vals,"coin",coin->symbol);
return(vals);
}
void basilisk_unspents_update(struct supernet_info *myinfo,struct iguana_info *coin)
{
char *retstr; cJSON *retarray,*vals; int32_t oldest,i,n,RTheight;
//if ( coin->FULLNODE == 0 && coin->VALIDATENODE == 0 )
char *retstr; cJSON *vals;
if ( (vals= basilisk_balance_valsobj(myinfo,coin)) != 0 && (retstr= basilisk_balances(myinfo,coin,0,0,GENESIS_PUBKEY,vals,"")) != 0 )
{
vals = cJSON_CreateObject();
for (i=oldest=0; i<BASILISK_MAXRELAYS; i++)
if ( (RTheight= coin->relay_RTheights[i]) != 0 && (oldest == 0 || RTheight < oldest) )
oldest = RTheight;
jaddnum(vals,"firstheight",oldest);
jaddnum(vals,"history",3);
jaddstr(vals,"coin",coin->symbol);
if ( (retstr= basilisk_balances(myinfo,coin,0,0,GENESIS_PUBKEY,vals,"")) != 0 )
{
portable_mutex_lock(&myinfo->bu_mutex);
if ( (retarray= cJSON_Parse(retstr)) != 0 )
{
//printf("%s UNSPENTS_UPDATE.(%s)\n",coin->symbol,retstr);
if ( jobj(retarray,"error") == 0 )
{
if ( (jstr(retarray,"ipaddr") == 0 || strcmp(jstr(retarray,"ipaddr"),myinfo->ipaddr) != 0) && (n= cJSON_GetArraySize(retarray)) > 0 )
{
for (i=0; i<n; i++)
basilisk_relay_unspentsprocess(myinfo,coin,jitem(retarray,i));
} else basilisk_relay_unspentsprocess(myinfo,coin,retarray);
if ( 0 )
{
bits256 pubAm,pubBn; struct basilisk_rawtx test; struct basilisk_swap swap;
memset(&swap,0,sizeof(swap));
printf("create alicepayment\n");
swap.alicecoin = iguana_coinfind("BTCD");
swap.alicesatoshis = 100000;
basilisk_rawtx_setparms("alicepayment",myinfo,&swap,&test,swap.alicecoin,swap.aliceconfirms,0,swap.alicesatoshis,2,0);
basilisk_alicepayment(myinfo,swap.alicecoin,&test,pubAm,pubBn);
}
}
} else printf("couldnt parse.(%s)\n",retstr);
if ( retarray != 0 )
free_json(retarray);
free(retstr);
portable_mutex_unlock(&myinfo->bu_mutex);
}
free_json(vals);
basilisk_unspents_process(myinfo,coin,retstr);
free(retstr);
}
free_json(vals);
}

72
basilisk/basilisk_ping.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -16,7 +16,7 @@
// included from basilisk.c
#ifdef ENABLE_VIRTPING
int32_t basilisk_blocksend(struct supernet_info *myinfo,struct iguana_info *btcd,struct iguana_info *virt,struct iguana_peer *addr,int32_t height)
int32_t basilisk_blocksend(struct supernet_info *myinfo,struct iguana_info *notary,struct iguana_info *virt,struct iguana_peer *addr,int32_t height)
{
int32_t blocklen; bits256 hash2; uint8_t *data = 0; char str[65],strbuf[4096],*blockstr,*allocptr = 0; struct iguana_block *block;
hash2 = iguana_blockhash(virt,height);
@ -42,7 +42,7 @@ int32_t basilisk_blocksend(struct supernet_info *myinfo,struct iguana_info *btcd
{
blockstr = basilisk_addhexstr(&allocptr,0,strbuf,sizeof(strbuf),data,blocklen);
printf("RELAYID.%d send block.%d %s -> (%s) %s\n",myinfo->RELAYID,height,blockstr,addr->ipaddr,bits256_str(str,hash2));
basilisk_blocksubmit(myinfo,btcd,virt,addr,blockstr,hash2,height);
basilisk_blocksubmit(myinfo,notary,virt,addr,blockstr,hash2,height);
if ( allocptr != 0 )
free(allocptr);
return(0);
@ -50,7 +50,7 @@ int32_t basilisk_blocksend(struct supernet_info *myinfo,struct iguana_info *btcd
return(-1);
}
int32_t basilisk_ping_processvirts(struct supernet_info *myinfo,struct iguana_info *btcd,struct iguana_peer *addr,uint8_t *data,int32_t datalen)
int32_t basilisk_ping_processvirts(struct supernet_info *myinfo,struct iguana_info *notary,struct iguana_peer *addr,uint8_t *data,int32_t datalen)
{
int32_t diff,i,j,len = 0; struct iguana_info *virt; char symbol[7]; uint32_t numvirts,height;
len += iguana_rwvarint32(0,&data[len],&numvirts);
@ -72,7 +72,7 @@ int32_t basilisk_ping_processvirts(struct supernet_info *myinfo,struct iguana_in
if ( (rand() % diff) == 0 )
{
for (j=1; height+j<virt->blocks.hwmchain.height && j<3; j++)
basilisk_blocksend(myinfo,btcd,virt,addr,height+j);
basilisk_blocksend(myinfo,notary,virt,addr,height+j);
}
}
}
@ -107,7 +107,7 @@ int32_t basilisk_ping_genvirts(struct supernet_info *myinfo,uint8_t *data,int32_
int32_t basilisk_ping_processMSG(struct supernet_info *myinfo,uint32_t senderipbits,uint8_t *data,int32_t datalen)
{
int32_t i,msglen,len=0; uint8_t num,keylen,*msg,*key; uint32_t duration;
int32_t i,msglen=0,len=0; uint8_t num,keylen,*message,*key; uint32_t duration;
if ( (num= data[len++]) > 0 )
{
//printf("processMSG num.%d datalen.%d\n",num,datalen);
@ -127,14 +127,14 @@ int32_t basilisk_ping_processMSG(struct supernet_info *myinfo,uint32_t senderipb
}
len += iguana_rwnum(0,&data[len],sizeof(msglen),&msglen);
len += iguana_rwnum(0,&data[len],sizeof(duration),&duration);
msg = &data[len], len += msglen;
message = &data[len], len += msglen;
if ( msglen <= 0 || len > datalen )
{
printf("illegal msglen.%d or len.%d > %d\n",msglen,len,datalen);
return(0);
}
//printf("i.%d: keylen.%d msglen.%d\n",i,keylen,msglen);
basilisk_respond_addmessage(myinfo,key,keylen,msg,msglen,0,duration);
basilisk_respond_addmessage(myinfo,key,keylen,message,msglen,0,duration);
}
}
return(len);
@ -143,7 +143,7 @@ int32_t basilisk_ping_processMSG(struct supernet_info *myinfo,uint32_t senderipb
int32_t basilisk_ping_genMSG(struct supernet_info *myinfo,uint8_t *data,int32_t maxlen)
{
struct basilisk_message *msg; int32_t datalen = 0;
if ( maxlen > sizeof(msg->key) && (msg= queue_dequeue(&myinfo->msgQ,0)) != 0 ) // oneshot ping
if ( maxlen > sizeof(msg->key) && (msg= queue_dequeue(&myinfo->msgQ)) != 0 ) // oneshot ping
{
data[datalen++] = 1;
data[datalen++] = msg->keylen;
@ -188,7 +188,7 @@ int32_t baslisk_relay_report(struct supernet_info *myinfo,uint8_t *data,int32_t
int32_t basilisk_ping_processrelay(struct supernet_info *myinfo,uint8_t *data,int32_t maxlen,struct basilisk_relay *rp,int32_t i)
{
uint8_t pingdelay; int32_t j,datalen = 0; uint32_t ipbits;
uint8_t pingdelay; int32_t j,datalen = 0; uint32_t ipbits; char ipaddr[64];
ipbits = rp->ipbits;
if ( maxlen < sizeof(ipbits)+1 )
{
@ -202,19 +202,21 @@ int32_t basilisk_ping_processrelay(struct supernet_info *myinfo,uint8_t *data,in
datalen += baslisk_relay_report(myinfo,&data[datalen],maxlen-datalen,&rp->reported[j],pingdelay);
return(datalen);
}
printf("notified about unknown relay\n"); // parse it to match bytes sent
datalen += baslisk_relay_report(myinfo,&data[datalen],maxlen-datalen,0,pingdelay);
expand_ipbits(ipaddr,ipbits);
printf("notified about unknown relay (%s)\n",ipaddr); // parse it to match bytes sent
basilisk_addrelay_info(myinfo,0,ipbits,GENESIS_PUBKEY);
return(datalen);
}
void basilisk_ping_process(struct supernet_info *myinfo,struct iguana_peer *addr,uint32_t senderipbits,uint8_t *data,int32_t datalen)
{
int32_t diff,i,n,len = 0; struct iguana_info *btcd; char ipbuf[64]; struct basilisk_relay *rp; uint8_t numrelays; uint16_t sn; uint32_t now = (uint32_t)time(NULL);
int32_t diff,i,n,len = 0; struct iguana_info *notary; char ipbuf[64]; struct basilisk_relay *rp; uint8_t numrelays; uint16_t sn; uint32_t now = (uint32_t)time(NULL);
expand_ipbits(ipbuf,senderipbits);
btcd = iguana_coinfind("BTCD");
for (i=0; i<NUMRELAYS; i++)
notary = iguana_coinfind("RELAY");
for (i=0; i<myinfo->NOTARY.NUMRELAYS; i++)
{
rp = &RELAYS[i];
rp = &myinfo->NOTARY.RELAYS[i];
rp->direct.pingdelay = 0;
if ( rp->ipbits == senderipbits )
rp->lastping = now;
@ -228,9 +230,10 @@ void basilisk_ping_process(struct supernet_info *myinfo,struct iguana_peer *addr
}
}
numrelays = data[len++];
//len += basilisk_ping_processvirts(myinfo,btcd,addr,&data[len],datalen - len);
//len += basilisk_ping_processvirts(myinfo,notary,addr,&data[len],datalen - len);
for (i=0; i<numrelays; i++)
{
rp = &myinfo->NOTARY.RELAYS[i];
if ( len > datalen )
break;
if ( (n= basilisk_ping_processrelay(myinfo,&data[len],datalen-len,rp,i)) < 0 )
@ -246,54 +249,58 @@ void basilisk_ping_process(struct supernet_info *myinfo,struct iguana_peer *addr
//else printf("\n");
//for (i=0; i<datalen; i++)
// printf("%02x",data[i]);
//printf("<<<<<<<<<<< input ping from.(%s) rel.%d numrelays.%d datalen.%d relay.%d Q.%d\n",ipbuf,basilisk_relayid(myinfo,(uint32_t)calc_ipbits(ipbuf)),numrelays,datalen,myinfo->RELAYID,QUEUEITEMS);
//printf("<<<<<<<<<<< input ping from.(%s) rel.%d numrelays.%d datalen.%d relay.%d Q.%d\n",ipbuf,basilisk_relayid(myinfo,(uint32_t)calc_ipbits(ipbuf)),numrelays,datalen,myinfo->NOTARY.RELAYID,QUEUEITEMS);
//basilisk_addrelay_info(myinfo,0,(uint32_t)calc_ipbits(ipbuf),GENESIS_PUBKEY);
}
int32_t basilisk_ping_gen(struct supernet_info *myinfo,uint8_t *data,int32_t maxlen)
{
int32_t i,datalen = 0;
data[datalen++] = NUMRELAYS;
data[datalen++] = myinfo->NOTARY.NUMRELAYS;
//datalen += basilisk_ping_genvirts(myinfo,&data[datalen],maxlen - datalen);
for (i=0; i<NUMRELAYS; i++)
datalen += basilisk_ping_genrelay(myinfo,&data[datalen],maxlen - datalen,&RELAYS[i]);
for (i=0; i<myinfo->NOTARY.NUMRELAYS; i++)
datalen += basilisk_ping_genrelay(myinfo,&data[datalen],maxlen - datalen,&myinfo->NOTARY.RELAYS[i]);
//datalen += basilisk_ping_genDEX(myinfo,&data[datalen],maxlen - datalen);
datalen += basilisk_ping_genMSG(myinfo,&data[datalen],maxlen - datalen);
//for (i=0; i<datalen; i++)
// printf("%02x",data[i]);
//printf("output ping datalen.%d relay.%d >>>>>>>>>> Q.%d\n",datalen,myinfo->RELAYID,QUEUEITEMS);
//printf(" output ping datalen.%d relay.%d >>>>>>>>>> Q.%d\n",datalen,myinfo->NOTARY.RELAYID,QUEUEITEMS);
return(datalen);
}
// encapsulate other messages inside msgQ for onetime ping
// filter out duplicates
void basilisk_ping_send(struct supernet_info *myinfo,struct iguana_info *btcd)
void basilisk_ping_send(struct supernet_info *myinfo,struct iguana_info *notary)
{
struct iguana_peer *addr; char ipaddr[64]; struct basilisk_relay *rp; uint32_t r; int32_t i,j,incr,datalen=0; uint64_t alreadysent;
if ( btcd == 0 || NUMRELAYS <= 0 )
if ( notary == 0 || myinfo->NOTARY.NUMRELAYS <= 0 || myinfo->IAMNOTARY == 0 )
{
printf("skip ping send %p %d %d\n",notary,myinfo->NOTARY.NUMRELAYS,myinfo->IAMNOTARY);
return;
}
if ( myinfo->pingbuf == 0 )
myinfo->pingbuf = malloc(IGUANA_MAXPACKETSIZE);
datalen = basilisk_ping_gen(myinfo,&myinfo->pingbuf[sizeof(struct iguana_msghdr)],IGUANA_MAXPACKETSIZE-sizeof(struct iguana_msghdr));
incr = sqrt(NUMRELAYS) + 1;
incr = sqrt(myinfo->NOTARY.NUMRELAYS) + 1;
OS_randombytes((void *)&r,sizeof(r));
for (alreadysent=j=0; j<=incr; j++)
{
OS_randombytes((void *)&r,sizeof(r));
i = (j == 0) ? RELAYID : (r % NUMRELAYS);
if ( j != 0 && i == RELAYID )
i = (RELAYID + 1) % NUMRELAYS;
i = (j == 0) ? myinfo->NOTARY.RELAYID : ((r+j) % myinfo->NOTARY.NUMRELAYS);
if ( j != 0 && i == myinfo->NOTARY.RELAYID )
i = (myinfo->NOTARY.RELAYID + 1) % myinfo->NOTARY.NUMRELAYS;
if ( (((uint64_t)1 << i) & alreadysent) != 0 )
{
j--;
continue;
break;
}
alreadysent |= ((uint64_t)1 << i);
rp = &RELAYS[i];
rp = &myinfo->NOTARY.RELAYS[i];
addr = 0;
expand_ipbits(ipaddr,rp->ipbits);
if ( rp->ipbits == myinfo->myaddr.myipbits )
basilisk_ping_process(myinfo,0,myinfo->myaddr.myipbits,&myinfo->pingbuf[sizeof(struct iguana_msghdr)],datalen);
else if ( (addr= iguana_peerfindipbits(btcd,rp->ipbits,1)) != 0 && addr->usock >= 0 )
else if ( (addr= iguana_peerfindipbits(notary,rp->ipbits,1)) != 0 && addr->usock >= 0 )
{
if ( iguana_queue_send(addr,0,myinfo->pingbuf,"SuperNETPIN",datalen) <= 0 )
printf("error sending %d to (%s)\n",datalen,addr->ipaddr);
@ -301,6 +308,7 @@ void basilisk_ping_send(struct supernet_info *myinfo,struct iguana_info *btcd)
fprintf(stderr,"+(%s).%d ",ipaddr,i);
} //else fprintf(stderr,"-(%s).%d ",ipaddr,i);
}
//printf("my RELAYID.%d of %d\n",myinfo->RELAYID,NUMRELAYS);
if ( 0 && datalen > 200 )
printf("my RELAYID.%d of %d\n",myinfo->NOTARY.RELAYID,myinfo->NOTARY.NUMRELAYS);
}

4048
basilisk/basilisk_swap.c

File diff suppressed because it is too large

387
basilisk/basilisk_tradebot.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -15,13 +15,191 @@
// included from basilisk.c
cJSON *basilisk_rawtxobj(struct supernet_info *myinfo,struct basilisk_swap *swap,struct basilisk_rawtx *rawtx)
{
char hexstr[sizeof(rawtx->I)*2+1+4096]; cJSON *obj = cJSON_CreateObject();
jaddstr(obj,"name",rawtx->name);
init_hexbytes_noT(hexstr,(void *)&rawtx->I,sizeof(rawtx->I));
jaddstr(obj,"info",hexstr);
if ( rawtx->I.datalen < sizeof(hexstr)/2 )
{
init_hexbytes_noT(hexstr,(void *)rawtx->txbytes,rawtx->I.datalen);
jaddstr(obj,"txbytes",hexstr);
}
return(obj);
}
struct basilisk_rawtx *basilisk_nameconv(struct supernet_info *myinfo,struct basilisk_swap *swap,char *name)
{
if ( strcmp("myfee",name) == 0 )
return(&swap->myfee);
else if ( strcmp("otherfee",name) == 0 )
return(&swap->otherfee);
else if ( strcmp("bobdeposit",name) == 0 )
return(&swap->bobdeposit);
else if ( strcmp("bobrefund",name) == 0 )
return(&swap->bobrefund);
else if ( strcmp("aliceclaim",name) == 0 )
return(&swap->aliceclaim);
else if ( strcmp("bobpayment",name) == 0 )
return(&swap->bobpayment);
else if ( strcmp("alicespend",name) == 0 )
return(&swap->alicespend);
else if ( strcmp("bobreclaim",name) == 0 )
return(&swap->bobreclaim);
else if ( strcmp("alicepayment",name) == 0 )
return(&swap->alicepayment);
else if ( strcmp("bobspend",name) == 0 )
return(&swap->bobspend);
else if ( strcmp("alicereclaim",name) == 0 )
return(&swap->alicereclaim);
else return(0);
}
int32_t basilisk_txitem(struct supernet_info *myinfo,struct basilisk_swap *swap,cJSON *obj)
{
char *hexstr,*name; struct basilisk_rawtx *rawtx = 0;
if ( (name= jstr(obj,"name")) == 0 || (rawtx= basilisk_nameconv(myinfo,swap,name)) == 0 )
{
printf("basilisk_txitem illegal name.(%s)\n",name);
return(-1);
}
if ( rawtx != 0 && (hexstr= jstr(obj,"info")) != 0 && strlen(hexstr) == sizeof(rawtx->I)*2 )
{
decode_hex((void *)&rawtx->I,sizeof(rawtx->I),hexstr);
if ( (hexstr= jstr(obj,"txbytes")) != 0 && strlen(hexstr) == rawtx->I.datalen*2 )
{
/*if ( rawtx->txbytes == 0 )
{
printf("free (%s) txbytes\n",name);
free(rawtx->txbytes);
}
rawtx->txbytes = calloc(1,rawtx->I.datalen);*/
decode_hex((void *)rawtx->txbytes,rawtx->I.datalen,hexstr);
}
printf("PROCESS.(%s)\n",jprint(obj,0));
return(0);
}
return(-1);
}
cJSON *basilisk_swapobj(struct supernet_info *myinfo,struct basilisk_swap *swap)
{
char hexstr[sizeof(swap->I)*2+1]; cJSON *obj = cJSON_CreateObject();
init_hexbytes_noT(hexstr,(void *)&swap->I,sizeof(swap->I));
jaddstr(obj,"name","swap");
jaddnum(obj,"requestid",swap->I.req.requestid);
jaddnum(obj,"quoteid",swap->I.req.quoteid);
jadd(obj,"req",basilisk_requestjson(&swap->I.req));
jaddstr(obj,"info",hexstr);
//printf("strlen(hexstr) swap->I %d vs %d\n",(int32_t)strlen(hexstr),(int32_t)sizeof(swap->I)*2);
return(obj);
}
int32_t basilisk_swapconv(struct supernet_info *myinfo,struct basilisk_swap *swap,cJSON *obj)
{
char *hexstr;
if ( (hexstr= jstr(obj,"info")) != 0 && strlen(hexstr) == sizeof(swap->I)*2 )
{
decode_hex((void *)&swap->I,sizeof(swap->I),hexstr);
if ( juint(obj,"requestid") == swap->I.req.requestid && juint(obj,"quoteid") == swap->I.req.quoteid )
return(0);
printf("swapconv mismatched req/quote %d %d, %d %d\n",juint(obj,"requestid"),swap->I.req.requestid,juint(obj,"quoteid"),swap->I.req.quoteid);
} //else printf("no info field in swap obj.(%s) len.%d vs %d\n",jprint(obj,0),(int32_t)strlen(hexstr),(int32_t)sizeof(swap->I)*2);
return(-1);
}
struct basilisk_swap *basilisk_swapstore(struct supernet_info *myinfo,struct basilisk_swap *swap)
{
// save based on requestid/quoteid
return(swap);
}
struct basilisk_swap *basilisk_swapload(struct supernet_info *myinfo,struct basilisk_swap *swap,uint32_t requestid,uint32_t quoteid)
{
// set swap fields and return it if found
return(0);
}
void basilisk_swapstart(struct supernet_info *myinfo) // scan saved tmpswap, purge if complete, else Q
{
// for resuming pending swaps
}
void basilisk_txlog(struct supernet_info *myinfo,struct basilisk_swap *swap,struct basilisk_rawtx *rawtx,int32_t delay)
{
char fname[1024],*jsonstr; long filesize; cJSON *item,*dexobj = 0; int32_t i,n,pending; struct basilisk_swap tmpswap,*swapptr;
sprintf(fname,"%s/DEX.log",GLOBAL_DBDIR), OS_compatible_path(fname);
if ( myinfo->dexfp == 0 )
{
if ( (jsonstr= OS_filestr(&filesize,fname)) != 0 )
{
jsonstr[strlen(jsonstr)-1] = ']';
if ( jsonstr[strlen(jsonstr)-2] == ',' )
jsonstr[strlen(jsonstr)-2] = ' ';
if ( jsonstr[strlen(jsonstr)-3] == ',' )
jsonstr[strlen(jsonstr)-3] = ' ';
if ( (dexobj= cJSON_Parse(jsonstr)) != 0 )
{
if ( is_cJSON_Array(dexobj) != 0 && (n= cJSON_GetArraySize(dexobj)) > 0 )
{
pending = 0;
memset(&tmpswap,0,sizeof(tmpswap));
swapptr = 0;
for (i=0; i<n; i++)
{
item = jitem(dexobj,i);
if ( jstr(item,"name") != 0 && strcmp(jstr(item,"name"),"swap") == 0 )
{
if ( basilisk_swapconv(myinfo,&tmpswap,item) == 0 )
swapptr = basilisk_swapstore(myinfo,&tmpswap);
}
else if ( swapptr != 0 )
{
if ( swapptr->I.req.requestid == juint(item,"requestid") && swapptr->I.req.quoteid == juint(item,"quoteid") )
basilisk_txitem(myinfo,swapptr,item);
}
else if ( (swapptr= basilisk_swapload(myinfo,&tmpswap,juint(item,"requestid"),juint(item,"quoteid"))) != 0 )
basilisk_txitem(myinfo,swapptr,item);
}
basilisk_swapstart(myinfo);
}
free_json(dexobj);
dexobj = 0;
} else printf("basilisk_txlog error parsing.(%s)\n",jsonstr);
free(jsonstr);
}
if ( (myinfo->dexfp= fopen(fname,"rb+")) != 0 )
fseek(myinfo->dexfp,0,SEEK_END);
else if ( (myinfo->dexfp= fopen(fname,"wb")) != 0 )
fprintf(myinfo->dexfp,"[\n");
}
if ( rawtx != 0 )
{
// delay -1 -> dont issue, else submit after block timestamp is delay after swap->started
dexobj = basilisk_rawtxobj(myinfo,swap,rawtx);
}
else if ( swap != 0 )
dexobj = basilisk_swapobj(myinfo,swap);
if ( dexobj != 0 && (jsonstr= jprint(dexobj,1)) != 0 )
{
//printf("%s\n",jsonstr);
if ( myinfo->dexfp != 0 )
{
fprintf(myinfo->dexfp,"%s,\n",jsonstr);
fflush(myinfo->dexfp);
}
free(jsonstr);
}
}
uint32_t basilisk_requestid(struct basilisk_request *rp)
{
struct basilisk_request R;
R = *rp;
R.requestid = R.quoteid = R.quotetime = 0;
R.destamount = 0;
R.relaybits = 0;
R.destamount = R.profitmargin = 0;
//R.relaybits = 0;
memset(R.desthash.bytes,0,sizeof(R.desthash.bytes));
if ( 0 )
{
@ -29,7 +207,7 @@ uint32_t basilisk_requestid(struct basilisk_request *rp)
for (i=0; i<sizeof(R); i++)
printf("%02x",((uint8_t *)&R)[i]);
printf(" <- crc.%u\n",calc_crc32(0,(void *)&R,sizeof(R)));
char str[65],str2[65]; printf("B REQUESTID: t.%u r.%u q.%u %s %.8f %s -> %s %.8f %s crc.%u\n",R.timestamp,R.requestid,R.quoteid,R.src,dstr(R.srcamount),bits256_str(str,R.hash),R.dest,dstr(R.destamount),bits256_str(str2,R.desthash),calc_crc32(0,(void *)&R,sizeof(R)));
char str[65],str2[65]; printf("B REQUESTID: t.%u r.%u q.%u %s %.8f %s -> %s %.8f %s crc.%u\n",R.timestamp,R.requestid,R.quoteid,R.src,dstr(R.srcamount),bits256_str(str,R.srchash),R.dest,dstr(R.destamount),bits256_str(str2,R.desthash),calc_crc32(0,(void *)&R,sizeof(R)));
}
return(calc_crc32(0,(void *)&R,sizeof(R)));
}
@ -38,7 +216,7 @@ uint32_t basilisk_quoteid(struct basilisk_request *rp)
{
struct basilisk_request R;
R = *rp;
R.requestid = R.quoteid = R.relaybits = 0;
R.requestid = R.quoteid = R.profitmargin = 0; //R.relaybits =
return(calc_crc32(0,(void *)&R,sizeof(R)));
}
@ -46,15 +224,17 @@ struct basilisk_request *basilisk_parsejson(struct basilisk_request *rp,cJSON *r
{
uint32_t requestid,quoteid;
memset(rp,0,sizeof(*rp));
rp->hash = jbits256(reqjson,"hash");
rp->srchash = jbits256(reqjson,"srchash");
rp->desthash = jbits256(reqjson,"desthash");
rp->srcamount = j64bits(reqjson,"srcamount");
rp->minamount = j64bits(reqjson,"minamount");
rp->destamount = j64bits(reqjson,"destamount");
//rp->destamount = j64bits(reqjson,"destamount");
rp->destamount = j64bits(reqjson,"destsatoshis");
//printf("parse DESTSATOSHIS.%llu (%s)\n",(long long)rp->destamount,jprint(reqjson,0));
requestid = juint(reqjson,"requestid");
quoteid = juint(reqjson,"quoteid");
if ( jstr(reqjson,"relay") != 0 )
rp->relaybits = (uint32_t)calc_ipbits(jstr(reqjson,"relay"));
//if ( jstr(reqjson,"relay") != 0 )
// rp->relaybits = (uint32_t)calc_ipbits(jstr(reqjson,"relay"));
rp->timestamp = juint(reqjson,"timestamp");
rp->quotetime = juint(reqjson,"quotetime");
safecopy(rp->src,jstr(reqjson,"src"),sizeof(rp->src));
@ -67,30 +247,20 @@ struct basilisk_request *basilisk_parsejson(struct basilisk_request *rp,cJSON *r
}
rp->requestid = basilisk_requestid(rp);
if ( requestid != rp->requestid )
printf("basilisk_parsejson requestid.%u != %u error\n",requestid,rp->requestid);
return(rp);
}
void basilisk_swap_balancingtrade(struct supernet_info *myinfo,struct basilisk_swap *swap,int32_t iambob)
{
// update balance, compare to target balance, issue balancing trade via central exchanges, if needed
if ( iambob != 0 )
{
}
else
{
int32_t i; for (i=0; i<sizeof(*rp); i++)
printf("%02x",((uint8_t *)rp)[i]);
printf(" basilisk_parsejson.(%s) requestid.%u != %u error\n",jprint(reqjson,0),requestid,rp->requestid);
}
return(rp);
}
struct basilisk_swap *basilisk_request_started(struct supernet_info *myinfo,uint32_t requestid)
{
int32_t i; struct basilisk_swap *active = 0;
portable_mutex_lock(&myinfo->DEX_swapmutex);
for (i=0; i<myinfo->numswaps; i++)
if ( myinfo->swaps[i]->req.requestid == requestid )
if ( myinfo->swaps[i]->I.req.requestid == requestid )
{
//printf("REQUEST STARTED.[%d] <- req.%u\n",i,requestid);
active = myinfo->swaps[i];
@ -102,67 +272,26 @@ struct basilisk_swap *basilisk_request_started(struct supernet_info *myinfo,uint
int32_t basilisk_request_cmpref(struct basilisk_request *ref,struct basilisk_request *rp)
{
if ( bits256_cmp(rp->hash,ref->hash) != 0 || memcmp(rp->src,ref->src,sizeof(ref->src)) != 0 || memcmp(rp->dest,ref->dest,sizeof(ref->dest)) != 0 || rp->srcamount != ref->srcamount || rp->timestamp != ref->timestamp )
if ( bits256_cmp(rp->srchash,ref->srchash) != 0 || memcmp(rp->src,ref->src,sizeof(ref->src)) != 0 || memcmp(rp->dest,ref->dest,sizeof(ref->dest)) != 0 || rp->srcamount != ref->srcamount || rp->timestamp != ref->timestamp )
{
printf("basilisk_request_listprocess mismatched hash\n");
return(-1);
} else return(0);
}
void tradebot_liquidity_command(struct supernet_info *myinfo,char *base,bits256 hash,cJSON *vals)
{
struct liquidity_info li,refli; int32_t i;
memset(&li,0,sizeof(li));
strcpy(li.base,base), strcpy(li.rel,"BTC");
li.profit = jdouble(vals,"profit");
li.refprice = jdouble(vals,"refprice");
for (i=0; i<sizeof(myinfo->linfos)/sizeof(*myinfo->linfos); i++)
{
refli = myinfo->linfos[i];
if ( strcmp(li.rel,refli.base) == 0 && strcmp(li.base,refli.rel) == 0 )
{
strcpy(li.base,refli.base);
strcpy(li.rel,refli.rel);
li.refprice = (1. / li.refprice);
printf("Set rev linfo[%d] (%s/%s) %.6f %.8f\n",i,li.base,li.rel,li.profit,li.refprice);
myinfo->linfos[i] = li;
return;
}
else if ( refli.base[0] == 0 || (strcmp(li.base,refli.base) == 0 && strcmp(li.rel,refli.rel) == 0) )
{
myinfo->linfos[i] = li;
printf("Set linfo[%d] (%s/%s) %.6f %.8f\n",i,li.base,li.rel,li.profit,li.refprice);
return;
}
}
printf("ERROR: too many linfos %d\n",i);
}
double tradebot_liquidity_active(struct supernet_info *myinfo,double *refpricep,char *base,char *rel)
{
int32_t i; struct liquidity_info refli;
*refpricep = 0.;
for (i=0; i<sizeof(myinfo->linfos)/sizeof(*myinfo->linfos); i++)
{
refli = myinfo->linfos[i];
if ( (strcmp(base,refli.base) == 0 && strcmp(rel,refli.rel) == 0) || (strcmp(rel,refli.base) == 0 && strcmp(base,refli.rel) == 0 ))
{
*refpricep = refli.refprice;
return(refli.profit);
}
}
return(0.);
}
double basilisk_request_listprocess(struct supernet_info *myinfo,struct basilisk_request *issueR,struct basilisk_request *list,int32_t n)
{
int32_t i,noquoteflag=0,havequoteflag=0,myrequest=0,maxi=-1; uint64_t destamount,minamount = 0,maxamount = 0; uint32_t pendingid=0; struct basilisk_swap *active; double metric = 0.;
int32_t i,noquoteflag=0,havequoteflag=0,myrequest=0,maxi=-1; int64_t balance=0,destamount,minamount = 0,maxamount = 0; bits256 privkey; uint32_t pendingid=0; struct basilisk_swap *active; double metric = 0.,bidasks[2]; char typestr[64];
memset(issueR,0,sizeof(*issueR));
minamount = list[0].minamount;
printf("need to verify null quoteid is list[0] requestid.%u quoteid.%u\n",list[0].requestid,list[0].quoteid);
//printf("need to verify null quoteid is list[0] requestid.%u quoteid.%u\n",list[0].requestid,list[0].quoteid);
if ( (active= basilisk_request_started(myinfo,list[0].requestid)) != 0 )
pendingid = active->req.quoteid;
if ( bits256_cmp(myinfo->myaddr.persistent,list[0].hash) == 0 ) // my request
{
if ( active->I.req.quoteid != 0 )
return(0.);
pendingid = active->I.req.quoteid;
}
if ( smartaddress_pubkey(myinfo,typestr,bidasks,&privkey,list[0].src,list[0].srchash) >= 0 )
myrequest = 1;
for (i=0; i<n; i++)
{
@ -170,7 +299,7 @@ double basilisk_request_listprocess(struct supernet_info *myinfo,struct basilisk
return(-1);
if ( list[i].quoteid != 0 )
{
if ( bits256_cmp(myinfo->myaddr.persistent,list[i].desthash) == 0 ) // my quoteid
if ( smartaddress_pubkey(myinfo,typestr,bidasks,&privkey,list[i].dest,list[i].desthash) >= 0 )
myrequest |= 2;
havequoteflag++;
if ( pendingid == 0 )
@ -178,6 +307,7 @@ double basilisk_request_listprocess(struct supernet_info *myinfo,struct basilisk
if ( list[i].destamount > maxamount )
{
maxamount = list[i].destamount;
//printf("set maxamount %llu\n",(long long)maxamount);
maxi = i;
}
}
@ -186,38 +316,65 @@ double basilisk_request_listprocess(struct supernet_info *myinfo,struct basilisk
}
} else noquoteflag++;
}
printf("myrequest.%d pendingid.%u noquoteflag.%d havequoteflag.%d maxi.%d %.8f\n",myrequest,pendingid,noquoteflag,havequoteflag,maxi,dstr(maxamount));
double retvals[4],refprice,profitmargin,aveprice,balance=0.; cJSON *retjson; char *retstr;
if ( myinfo->IAMLP != 0 && myrequest == 0 && pendingid == 0 && noquoteflag != 0 && (profitmargin= tradebot_liquidity_active(myinfo,&refprice,list[0].src,list[0].dest)) > 0. )
struct iguana_info *coin; char coinaddr[64]; double retvals[4],refprice=0.,profitmargin,aveprice,destvolume;
destvolume = dstr(maxamount);
//printf("destvolume <- %.8f\n",dstr(destvolume));
if ( fabs(destvolume) < SMALLVAL )
{
if ( (destvolume= dstr(minamount)) == 0 )
{
aveprice = instantdex_avehbla(myinfo,retvals,list[0].src,list[0].dest,1.3 * dstr(list[0].srcamount));
destvolume = aveprice * dstr(list[0].srcamount);
printf("set destvolume %.8f\n",destvolume);
} // else printf("destvolume %.8f <- minamount\n",destvolume);
}
printf("<<<<<<< %s -> %s myrequest.%d pendingid.%u noquoteflag.%d havequoteflag.%d maxi.%d %.8f destvol %.8f\n",list[0].src,list[0].dest,myrequest,pendingid,noquoteflag,havequoteflag,maxi,dstr(maxamount),destvolume);
if ( myinfo->IAMLP != 0 && myrequest == 0 && pendingid == 0 && noquoteflag != 0 && ((profitmargin= tradebot_liquidity_active(myinfo,&refprice,"DEX",list[0].src,list[0].dest,destvolume)) > 0. || refprice != 0.) )
{
if ( (aveprice= instantdex_avehbla(myinfo,retvals,list[0].src,list[0].dest,1.3 * dstr(list[0].srcamount))) == 0. || refprice > aveprice )
if ( profitmargin == 0. || (aveprice= instantdex_avehbla(myinfo,retvals,list[0].src,list[0].dest,.1 * dstr(list[0].srcamount))) == 0. || refprice > aveprice )
aveprice = refprice;
if ( fabs(aveprice) < SMALLVAL )
return(0);
if ( strcmp("BTC",list[0].src) == 0 )
aveprice = (1. / aveprice);
//retvals[0] = avebid, retvals[1] = bidvol, retvals[2] = aveask, retvals[3] = askvol;
destamount = (1.0 - profitmargin) * aveprice * list[0].srcamount;
if ( (retstr= InstantDEX_available(myinfo,iguana_coinfind(list[0].dest),0,0,list[0].dest)) != 0 )
if ( destamount > minamount )
destamount = minamount + ((destamount - minamount) * (1 + (rand() % 100))) / 100.;
printf("%s/%s pm %f aveprice %f src %.8f dest %.8f avebid %f bidvol %f, aveask %f askvol %f\n",list[0].src,list[0].dest,profitmargin,aveprice,dstr(list[0].srcamount),dstr(destamount),retvals[0],retvals[1],retvals[2],retvals[3]);
if ( (coin= iguana_coinfind(list[0].dest)) != 0 )
{
bitcoin_address(coinaddr,coin->chain->pubtype,myinfo->persistent_pubkey33,33);
balance = jumblr_balance(myinfo,coin,coinaddr);
printf("%s %s balance %.8f destamount %.8f aveprice %.8f maxamount %.8f minamount %.8f\n",list[0].dest,coinaddr,dstr(balance),dstr(destamount),aveprice,dstr(maxamount),dstr(minamount));
}
/*if ( (retstr= InstantDEX_available(myinfo,iguana_coinfind(list[0].dest),0,0,list[0].dest)) != 0 )
{
if ( (retjson= cJSON_Parse(retstr)) != 0 )
{
balance = jdouble(retjson,"result");
balance = jdouble(retjson,"result") * SATOSHIDEN;
free_json(retjson);
}
free(retstr);
}
printf("balance %.8f destamount %.8f aveprice %.8f minamount %.8f\n",balance,dstr(destamount),aveprice,dstr(minamount));
if ( balance > destamount && destamount > 0 && destamount >= maxamount && destamount >= minamount )
}*/
if ( balance > destamount && (int64_t)destamount > 0 && destamount >= minamount ) // max?
{
metric = 1.;
*issueR = list[0];
issueR->desthash = myinfo->myaddr.persistent;
issueR->destamount = destamount;
issueR->quotetime = (uint32_t)time(NULL);
issueR->profitmargin = (uint32_t)(profitmargin * 1000000);
}
}
else if ( myrequest != 0 && pendingid == 0 && maxi >= 0 ) // automatch best quote
{
if ( minamount != 0 && maxamount > minamount && time(NULL) > BASILISK_DEXDURATION/2 )
if ( minamount != 0 && maxamount >= minamount )//&& time(NULL) > list[0].timestamp+BASILISK_AUCTION_DURATION )
{
printf("automatch quoteid.%u triggered %.8f > %.8f\n",list[maxi].quoteid,dstr(maxamount),dstr(minamount));
*issueR = list[maxi];
for (i=0; i<sizeof(*issueR); i++)
printf("%02x",((uint8_t *)issueR)[i]);
printf(" automatch[%d] r.%u quoteid.%u triggered %.8f >= %.8f\n",maxi,list[maxi].requestid,list[maxi].quoteid,dstr(maxamount),dstr(minamount));
if ( minamount > 0 )
metric = (dstr(maxamount) / dstr(minamount)) - 1.;
else metric = 1.;
@ -228,31 +385,61 @@ double basilisk_request_listprocess(struct supernet_info *myinfo,struct basilisk
double basilisk_process_results(struct supernet_info *myinfo,struct basilisk_request *issueR,cJSON *retjson,double hwm)
{
cJSON *array,*item; int32_t i,n,m; struct basilisk_request tmpR,R,refR,list[BASILISK_MAXRELAYS]; double metric=0.;
//printf("process_results.(%s)\n",jprint(retjson,0));
if ( (array= jarray(&n,retjson,"result")) != 0 )
cJSON *array,*item; uint8_t *hexdata,*allocptr,hexspace[32768]; char *hexstr; int32_t i,hexlen,n,m,nonz; struct basilisk_request tmpR,R,refR,list[BASILISK_MAXRELAYS]; double metric=0.;
memset(&refR,0,sizeof(refR));
memset(&R,0,sizeof(R));
//printf("process.(%s)\n",jprint(retjson,0));
if ( (array= jarray(&n,retjson,"messages")) != 0 )
{
for (i=m=0; i<n; i++)
for (i=nonz=m=0; i<n; i++)
{
item = jitem(array,i);
if ( i != 0 )
if ( jobj(item,"error") == 0 )
{
basilisk_parsejson(&R,item);
if ( refR.requestid == R.requestid )
list[m++] = R;
else
if ( (hexstr= jstr(item,"data")) != 0 )
{
if ( (hexdata= get_dataptr(0,&allocptr,&hexlen,hexspace,sizeof(hexspace),hexstr)) != 0 )
{
memset(&R,0,sizeof(R));
basilisk_rwDEXquote(0,hexdata,&R);
//printf("[%d].(%s)\n",i,jprint(basilisk_requestjson(&R),1));
}
} else basilisk_parsejson(&R,item);
if ( nonz != 0 )
{
if ( (metric= basilisk_request_listprocess(myinfo,&tmpR,list,m)) > hwm )
*issueR = tmpR, hwm = metric;
m = 0;
if ( refR.requestid == R.requestid )
list[m++] = R;
else
{
if ( (metric= basilisk_request_listprocess(myinfo,&tmpR,list,m)) > hwm )
{
*issueR = tmpR;
hwm = metric;
refR = tmpR;
printf("SET HWM\n");
}
m = 0;
}
}
nonz++;
if ( m < sizeof(list)/sizeof(*list) )
{
//basilisk_parsejson(&list[m++],item);
list[m++] = R;
}
}
if ( m < sizeof(list)/sizeof(*list) )
basilisk_parsejson(&list[m++],item);
}
//printf("process_results n.%d m.%d nonz.%d\n",n,m,nonz);
if ( m > 0 && m < sizeof(list)/sizeof(*list) )
if ( (metric= basilisk_request_listprocess(myinfo,&tmpR,list,m)) > hwm )
{
*issueR = tmpR, hwm = metric;
//printf("set hwm\n");
//for (i=0; i<sizeof(*issueR); i++)
// printf("%02x",((uint8_t *)issueR)[i]);
//printf("\n");
}
}
return(hwm);
}

405
basilisk/basilisk_vote.c

@ -0,0 +1,405 @@
/******************************************************************************
* Copyright © 2014-2016 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. *
* *
******************************************************************************/
#define MAX_ELECTIONS 64
struct vote_info
{
bits256 commit,vote;
uint64_t stake,repstake;
int32_t repid;
uint8_t sig[74],siglen;
uint8_t pubkey[33],rmd160[20];
};
struct election_info
{
bits256 hash;
char name[64];
uint32_t expiration,duration,numcandidates,numvotes;
cJSON *ballot;
struct vote_info *votes;
} Elections[MAX_ELECTIONS];
int64_t basilisk_voter_stake(struct supernet_info *myinfo,uint8_t *rmd160,struct iguana_info *coin,uint8_t *pubkey)
{
char coinaddr[64]; int64_t stake = 1;
calc_rmd160_sha256(rmd160,pubkey,33);
bitcoin_address(coinaddr,coin->chain->pubtype,pubkey,33);
// get stake of address
return(stake);
}
int32_t basilisk_voter_process(struct supernet_info *myinfo,uint8_t *rmd160,struct iguana_info *coin,struct election_info *ep,struct vote_info *vp)
{
int32_t i;
if ( vp->stake == 0 )
vp->stake = 1;
if ( bits256_nonz(vp->vote) != 0 )
{
for (i=1; i<8; i++)
if ( vp->vote.uints[i] != 0 )
break;
if ( i == 8 )
return(vp->vote.uints[0]);
else
{
for (i=0; i<20; i++)
rmd160[i] = vp->vote.bytes[i + 4];
return(ep->numcandidates);
}
}
return(-1);
}
int32_t basilisk_election_process(struct supernet_info *myinfo,int64_t *tally,struct iguana_info *coin,struct election_info *ep)
{
int32_t i,j,pending = 0; struct vote_info *vp; uint8_t rmd160[20];
for (i=0; i<ep->numvotes; i++)
ep->votes[i].repstake = 0;
for (i=0; i<ep->numvotes; i++)
{
vp = &ep->votes[i];
if ( basilisk_voter_process(myinfo,rmd160,coin,ep,vp) == ep->numcandidates && vp->repid < 0 )
{
for (j=0; j<ep->numvotes; j++)
{
if ( i != j && memcmp(rmd160,ep->votes[j].rmd160,20) == 0 )
{
vp->repid = j;
ep->votes[j].repstake += vp->stake;
break;
}
}
}
}
if ( tally != 0 )
{
memset(tally,0,ep->numcandidates*sizeof(*tally));
for (i=0; i<ep->numvotes; i++)
{
vp = &ep->votes[i];
if ( vp->repid < 0 && vp->vote.uints[0] > 0 && vp->vote.uints[0] <= ep->numcandidates )
tally[vp->vote.uints[0]] += (vp->stake + vp->repstake);
else if ( vp->repid < 0 )
pending++;
}
}
return(pending);
}
cJSON *basilisk_voterjson(struct supernet_info *myinfo,struct iguana_info *coin,struct election_info *ep,struct vote_info *vp)
{
char coinaddr[64],sigstr[74*2+1]; int32_t i; uint8_t rmd160[20]; cJSON *item;
item = cJSON_CreateObject();
basilisk_voter_process(myinfo,rmd160,coin,ep,vp);
bitcoin_address(coinaddr,5,vp->pubkey,sizeof(vp->pubkey));
jaddstr(item,"coinaddr",coinaddr);
jaddnum(item,"stake",dstr(vp->stake));
if ( vp->repstake != 0 )
jaddnum(item,"repstake",dstr(vp->repstake));
if ( bits256_nonz(vp->vote) != 0 )
{
for (i=1; i<8; i++)
if ( vp->vote.uints[i] != 0 )
break;
if ( i == 8 )
{
if ( vp->vote.uints[0] <= ep->numcandidates )
jaddnum(item,"vote",vp->vote.uints[0]);
else jaddstr(item,"error","illegal vote");
}
else
{
for (i=0; i<20; i++)
rmd160[i] = vp->vote.bytes[i + 4];
bitcoin_address(coinaddr,5,rmd160,20);
jaddstr(item,"delegated",coinaddr);
}
}
else if ( bits256_nonz(vp->commit) != 0 )
jaddbits256(item,"commit",vp->commit);
init_hexbytes_noT(sigstr,vp->sig,vp->siglen);
jaddstr(item,"sig",sigstr);
return(item);
}
cJSON *basilisk_electionjson(struct supernet_info *myinfo,struct iguana_info *coin,struct election_info *ep)
{
int32_t i; cJSON *array,*obj = cJSON_CreateObject();
jaddstr(obj,"name",ep->name);
jaddbits256(obj,"hash",ep->hash);
jaddnum(obj,"expiration",ep->expiration);
jaddnum(obj,"numcandidates",ep->numcandidates);
jaddnum(obj,"numvotes",ep->numvotes);
jadd(obj,"ballot",jduplicate(ep->ballot));
array = cJSON_CreateArray();
for (i=0; i<ep->numvotes; i++)
jaddi(array,basilisk_voterjson(myinfo,coin,ep,&ep->votes[i]));
jadd(obj,"votes",array);
return(obj);
}
int32_t basilisk_electionsave(struct election_info *ep)
{
char fname[512],str[65],*ballotstr; int32_t n; FILE *fp;
OS_ensure_directory("elections");
sprintf(fname,"elections/%s",bits256_str(str,ep->hash));
OS_compatible_path(fname);
if ( (fp= fopen(fname,"wb")) != 0 )
{
if ( fwrite(ep,1,sizeof(*ep),fp) != sizeof(*ep) )
printf("error saving election.(%s) to %s\n",ep->name,fname);
else
{
if ( fwrite(&ep->numvotes,1,sizeof(ep->numvotes),fp) != sizeof(ep->numvotes) )
printf("error saving numvotes.%d to %s\n",ep->numvotes,fname);
else if ( ep->numvotes > 0 )
{
if ( fwrite(ep->votes,sizeof(*ep->votes),ep->numvotes,fp) != ep->numvotes )
printf("error saving votes.%d for %s to %s\n",ep->numvotes,ep->name,fname);
else
{
if ( (ballotstr= jprint(ep->ballot,0)) != 0 )
{
n = (int32_t)strlen(ballotstr) + 1;
if ( fwrite(&n,1,sizeof(n),fp) != sizeof(n) )
printf("error saving n.%d for (%s) to %s\n",n,ballotstr,fname);
else if ( fwrite(ballotstr,1,n,fp) != n )
printf("error saving election.(%s) to %s\n",ballotstr,fname);
free(ballotstr);
}
}
}
}
fclose(fp);
return(0);
}
return(-1);
}
struct vote_info *basilisk_vote_find(struct election_info *ep,struct vote_info *vote)
{
int32_t i;
for (i=0; i<ep->numvotes; i++)
{
if ( memcmp(ep->votes[i].pubkey,vote->pubkey,33) == 0 )
return(&ep->votes[i]);
}
return(0);
}
struct election_info *basilisk_election_find(int32_t createflag,bits256 hash)
{
int32_t i; uint32_t now = (uint32_t)time(NULL);
for (i=0; i<sizeof(Elections)/sizeof(*Elections); i++)
{
if ( Elections[i].expiration != 0 && now > Elections[i].expiration )
{
basilisk_electionsave(&Elections[i]);
memset(&Elections[i],0,sizeof(Elections[i]));
}
if ( bits256_nonz(hash) != 0 )
{
if ( bits256_nonz(Elections[i].hash) == 0 )
return(&Elections[i]);
else if ( bits256_cmp(Elections[i].hash,hash) == 0 )
return(0);
}
}
return(0);
}
int32_t basilisk_vote_extract(struct supernet_info *myinfo,char *coinaddr,struct vote_info *vote,cJSON *item)
{
char str[65],str2[65],str3[65]; uint8_t *sig,*pubkey; int32_t action,siglen,plen; bits256 data,hash;
memset(vote,0,sizeof(*vote));
if ( get_dataptr(0,&sig,&siglen,vote->sig,sizeof(vote->sig),jstr(item,"sig")) != 0 )
{
vote->siglen = siglen;
action = juint(item,"action");
if ( get_dataptr(0,&pubkey,&plen,vote->pubkey,sizeof(vote->pubkey),jstr(item,"pubkey")) != 0 )
{
bitcoin_address(coinaddr,5,pubkey,33);
data = jbits256(item,"data");
if ( bitcoin_verify(myinfo->ctx,vote->sig,vote->siglen,data,vote->pubkey,33) == 0 )
{
if ( (action & 0xff) == 'c' )
{
vote->commit = data;
printf("%s commits to %s\n",coinaddr,bits256_str(str,data));
return(action);
}
else if ( (action & 0xff) == 'r' )
{
if ( bits256_nonz(vote->commit) != 0 )
{
vcalc_sha256(0,hash.bytes,data.bytes,sizeof(data));
if ( bits256_cmp(hash,vote->commit) == 0 )
{
printf("%s vote %s -> %s matches commit %s\n",coinaddr,bits256_str(str,data),bits256_str(str2,hash),bits256_str(str3,vote->commit));
vote->vote = data;
// error check vote
return(action);
}
else
{
printf("%s vote %s -> %s doesnt match commit %s\n",coinaddr,bits256_str(str,data),bits256_str(str2,hash),bits256_str(str3,vote->commit));
return(-2);
}
}
}
} else return(-1);
}
}
return(-1);
}
char *basilisk_respond_VOT(struct supernet_info *myinfo,char *CMD,void *addr,char *remoteaddr,uint32_t basilisktag,cJSON *valsobj,uint8_t *data,int32_t datalen,bits256 hash,int32_t from_basilisk)
{
int32_t i,duration,winner,pending,action,numcandidates; char coinaddr[64],*symbol,*votemethod,*ballotstr; cJSON *item,*array,*electionobj,*ballot,*retjson; struct election_info *ep; struct vote_info vote,*vp; struct iguana_info *coin; int64_t *tally,max;
retjson = cJSON_CreateObject();
if ( (symbol= jstr(valsobj,"coin")) == 0 )
symbol = "BTCD";
coin = iguana_coinfind(symbol);
if ( (votemethod= jstr(valsobj,"votemethod")) != 0 )
{
if ( strcmp(votemethod,"create") == 0 )
{
if ( (ballot= jarray(&numcandidates,valsobj,"ballot")) != 0 && numcandidates > 0 )
{
if ( (duration= juint(valsobj,"duration")) == 0 )
duration = 3600;
ballotstr = jprint(ballot,0);
vcalc_sha256(0,hash.bytes,(uint8_t *)ballotstr,(int32_t)strlen(ballotstr));
free(ballotstr);
if ( (ep= basilisk_election_find(1,hash)) != 0 )
{
ep->hash = hash;
ep->duration = duration;
ep->expiration = (uint32_t)time(NULL) + duration;
ep->ballot = jduplicate(ballot);
ep->numcandidates = numcandidates;
safecopy(ep->name,jstr(valsobj,"name"),sizeof(ep->name));
if ( (electionobj= basilisk_electionjson(myinfo,coin,ep)) != 0 )
{
jaddstr(retjson,"result","success");
jadd(retjson,"election",electionobj);
} else jaddstr(retjson,"error","couldnt create election object");
} else jaddstr(retjson,"error","couldnt allocate election slot");
}
}
else if ( strcmp(votemethod,"list") == 0 )
{
array = cJSON_CreateArray();
for (i=0; i<sizeof(Elections)/sizeof(*Elections); i++)
{
if ( bits256_nonz(Elections[i].hash) != 0 )
{
item = cJSON_CreateObject();
jaddstr(item,"name",Elections[i].name);
jaddbits256(item,"hash",Elections[i].hash);
jaddi(array,item);
}
}
jaddstr(retjson,"result","success");
jadd(retjson,"elections",array);
}
if ( (ep= basilisk_election_find(0,hash)) != 0 )
{
if ( strcmp(votemethod,"info") == 0 )
{
jaddstr(retjson,"result","success");
tally = calloc(ep->numcandidates+1,sizeof(*tally));
pending = basilisk_election_process(myinfo,tally,coin,ep);
if ( pending != 0 )
jaddnum(retjson,"pending",pending);
jadd(retjson,"election",basilisk_electionjson(myinfo,coin,ep));
array = cJSON_CreateArray();
max = 0;
winner = -1;
for (i=1; i<=ep->numcandidates; i++)
{
if ( tally[i] > max )
{
max = tally[i];
winner = i;
}
jaddinum(array,dstr(tally[i]));
}
jadd(retjson,"tally",array);
if ( winner > 0 )
{
item = jitem(ep->ballot,winner-1);
jadd(retjson,"winner",item);
}
free(tally);
}
else if ( strcmp(votemethod,"ratify") == 0 )
{
// record ratification of tally
}
else if ( (action= basilisk_vote_extract(myinfo,coinaddr,&vote,valsobj)) > 0 )
{
vp = basilisk_vote_find(ep,&vote);
if ( strcmp(votemethod,"vote") == 0 )
{
if ( vp == 0 )
{
ep->votes = realloc(ep->votes,sizeof(*ep->votes) + (ep->numvotes + 1));
vote.repid = -1;
vote.stake = basilisk_voter_stake(myinfo,vote.rmd160,coin,vote.pubkey);
ep->votes[ep->numvotes++] = vote;
jaddstr(retjson,"result","success");
}
else if ( action == 'c' )
{
*vp = vote;
jaddstr(retjson,"result","success");
}
else if ( action == 'r' )
{
*vp = vote;
jaddstr(retjson,"result","success");
} else jaddstr(retjson,"error","illegal vote action");
}
else if ( strcmp(votemethod,"verify") == 0 )
{
if ( vp == 0 )
jaddstr(retjson,"error","cant find voter");
else if ( action == 'c' )
{
if ( bits256_cmp(vote.commit,vp->commit) == 0 )
jaddstr(retjson,"result","success");
else jaddstr(retjson,"error","mismatched commit");
jaddbits256(retjson,"oldcommit",vp->commit);
jaddbits256(retjson,"newcommit",vote.commit);
}
else if ( action == 'r' )
{
if ( bits256_cmp(vote.vote,vp->vote) == 0 )
jaddstr(retjson,"result","success");
else jaddstr(retjson,"error","mismatched vote");
jaddbits256(retjson,"oldvote",vp->vote);
jaddbits256(retjson,"newvote",vote.vote);
} else jaddstr(retjson,"error","illegal vote action");
} else jaddstr(retjson,"error","illegal vote method");
} else jaddstr(retjson,"error","couldnt extract vote info");
}
}
return(jprint(retjson,1));
}

772
basilisk/jumblr.c

@ -0,0 +1,772 @@
/******************************************************************************
* 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. *
* *
******************************************************************************/
// included from basilisk.c
// connect DEX to jumblr-core
/*
z_exportkey "zaddr"
z_exportwallet "filename"
z_getoperationstatus (["operationid", ... ])
z_gettotalbalance ( minconf )
z_importkey "zkey" ( rescan )
z_importwallet "filename"
z_listaddresses
z_sendmany "fromaddress" [{"address":... ,"amount":..., "memo":"<hex>"},...] ( minconf ) ( fee )
*/
#define JUMBLR_ADDR "RGhxXpXSSBTBm9EvNsXnTQczthMCxHX91t"
#define JUMBLR_BTCADDR "18RmTJe9qMech8siuhYfMtHo8RtcN1obC6"
int32_t jumblr_addresstype(struct supernet_info *myinfo,struct iguana_info *coin,char *addr)
{
if ( strcmp(coin->symbol,"KMD") == 0 )
{
if ( addr[0] == 'z' && addr[1] == 'c' && strlen(addr) >= 40 )
return('z');
else if ( strlen(addr) < 40 )
return('t');
else return(-1);
} else return('t');
}
struct jumblr_item *jumblr_opidfind(struct supernet_info *myinfo,char *opid)
{
struct jumblr_item *ptr;
HASH_FIND(hh,myinfo->jumblrs,opid,(int32_t)strlen(opid),ptr);
return(ptr);
}
struct jumblr_item *jumblr_opidadd(struct supernet_info *myinfo,struct iguana_info *coin,char *opid)
{
struct jumblr_item *ptr;
if ( (ptr= jumblr_opidfind(myinfo,opid)) == 0 )
{
ptr = calloc(1,sizeof(*ptr));
safecopy(ptr->opid,opid,sizeof(ptr->opid));
HASH_ADD_KEYPTR(hh,myinfo->jumblrs,ptr->opid,(int32_t)strlen(ptr->opid),ptr);
if ( ptr != jumblr_opidfind(myinfo,opid) )
printf("jumblr_opidadd.(%s) ERROR, couldnt find after add\n",opid);
}
return(ptr);
}
char *jumblr_validateaddress(struct supernet_info *myinfo,struct iguana_info *coin,char *addr)
{
char params[1024];
if ( coin->FULLNODE < 0 )
{
sprintf(params,"[\"%s\"]",addr);
return(bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"validateaddress",params));
} else return(_dex_validateaddress(myinfo,coin->symbol,addr));
}
int32_t jumblr_ismine(struct supernet_info *myinfo,struct iguana_info *coin,char *addr)
{
char params[1024],*retstr; cJSON *retjson,*obj; int32_t retval = -1;
sprintf(params,"[\"%s\"]",addr);
if ( (retstr= jumblr_validateaddress(myinfo,coin,addr)) != 0 )
{
if ( (retjson= cJSON_Parse(retstr)) != 0 )
{
if ( (obj= jobj(retjson,"ismine")) != 0 && is_cJSON_True(obj) != 0 )
retval = 1;
else retval = 0;
free_json(retjson);
}
free(retstr);
}
return(retval);
}
char *jumblr_zgetnewaddress(struct supernet_info *myinfo,struct iguana_info *coin)
{
return(bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"z_getnewaddress",""));
}
char *jumblr_zlistoperationids(struct supernet_info *myinfo,struct iguana_info *coin)
{
return(bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"z_listoperationids",""));
}
char *jumblr_zgetoperationresult(struct supernet_info *myinfo,struct iguana_info *coin,char *opid)
{
char params[1024];
sprintf(params,"[[\"%s\"]]",opid);
return(bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"z_getoperationresult",params));
}
char *jumblr_zgetoperationstatus(struct supernet_info *myinfo,struct iguana_info *coin,char *opid)
{
char params[1024];
sprintf(params,"[[\"%s\"]]",opid);
return(bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"z_getoperationstatus",params));
}
char *jumblr_sendt_to_z(struct supernet_info *myinfo,struct iguana_info *coin,char *taddr,char *zaddr,double amount)
{
char params[1024]; double fee = (amount-3*JUMBLR_TXFEE) * JUMBLR_FEE;
if ( jumblr_addresstype(myinfo,coin,zaddr) != 'z' || jumblr_addresstype(myinfo,coin,taddr) != 't' )
return(clonestr("{\"error\":\"illegal address in t to z\"}"));
sprintf(params,"[\"%s\", [{\"address\":\"%s\",\"amount\":%.8f}, {\"address\":\"%s\",\"amount\":%.8f}], 1, %.8f]",taddr,zaddr,amount-fee-JUMBLR_TXFEE,JUMBLR_ADDR,fee,JUMBLR_TXFEE);
return(bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"z_sendmany",params));
}
char *jumblr_sendz_to_z(struct supernet_info *myinfo,struct iguana_info *coin,char *zaddrS,char *zaddrD,double amount)
{
char params[1024]; double fee = (amount-2*JUMBLR_TXFEE) * JUMBLR_FEE;
if ( jumblr_addresstype(myinfo,coin,zaddrS) != 'z' || jumblr_addresstype(myinfo,coin,zaddrD) != 'z' )
return(clonestr("{\"error\":\"illegal address in z to z\"}"));
sprintf(params,"[\"%s\", [{\"address\":\"%s\",\"amount\":%.8f}, {\"address\":\"%s\",\"amount\":%.8f}], 1, %.8f]",zaddrS,zaddrD,amount-fee-JUMBLR_TXFEE,JUMBLR_ADDR,fee,JUMBLR_TXFEE);
return(bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"z_sendmany",params));
}
char *jumblr_sendz_to_t(struct supernet_info *myinfo,struct iguana_info *coin,char *zaddr,char *taddr,double amount)
{
char params[1024]; double fee = (amount-JUMBLR_TXFEE) * JUMBLR_FEE;
if ( jumblr_addresstype(myinfo,coin,zaddr) != 'z' || jumblr_addresstype(myinfo,coin,taddr) != 't' )
return(clonestr("{\"error\":\"illegal address in z to t\"}"));
sprintf(params,"[\"%s\", [{\"address\":\"%s\",\"amount\":%.8f}, {\"address\":\"%s\",\"amount\":%.8f}], 1, %.8f]",zaddr,taddr,amount-fee-JUMBLR_TXFEE,JUMBLR_ADDR,fee,JUMBLR_TXFEE);
return(bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"z_sendmany",params));
}
char *jumblr_zlistreceivedbyaddress(struct supernet_info *myinfo,struct iguana_info *coin,char *addr)
{
char params[1024];
sprintf(params,"[\"%s\", 1]",addr);
return(bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"z_listreceivedbyaddress",params));
}
char *jumblr_getreceivedbyaddress(struct supernet_info *myinfo,struct iguana_info *coin,char *addr)
{
char params[1024];
sprintf(params,"[\"%s\", 1]",addr);
return(bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"getreceivedbyaddress",params));
}
char *jumblr_importprivkey(struct supernet_info *myinfo,struct iguana_info *coin,char *wifstr)
{
char params[1024];
sprintf(params,"[\"%s\", \"\", false]",wifstr);
return(bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"importprivkey",params));
}
char *jumblr_zgetbalance(struct supernet_info *myinfo,struct iguana_info *coin,char *addr)
{
char params[1024];
sprintf(params,"[\"%s\", 1]",addr);
return(bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"z_getbalance",params));
}
char *jumblr_listunspent(struct supernet_info *myinfo,struct iguana_info *coin,char *coinaddr)
{
char params[1024];
if ( coin->FULLNODE == 0 )
return(dex_listunspent(myinfo,coin,0,0,coin->symbol,coinaddr));
sprintf(params,"[1, 99999999, [\"%s\"]]",coinaddr);
return(bitcoind_passthru(coin->symbol,coin->chain->serverport,coin->chain->userpass,"listunspent",params));
}
int64_t jumblr_receivedby(struct supernet_info *myinfo,struct iguana_info *coin,char *addr)
{
char *retstr; int64_t total = 0;
if ( (retstr= jumblr_getreceivedbyaddress(myinfo,coin,addr)) != 0 )
{
total = atof(retstr) * SATOSHIDEN;
free(retstr);
}
return(total);
}
int64_t jumblr_balance(struct supernet_info *myinfo,struct iguana_info *coin,char *addr)
{
char *retstr; double val; cJSON *retjson; int32_t i,n; int64_t balance = 0;
if ( jumblr_addresstype(myinfo,coin,addr) == 't' )
{
if ( coin->FULLNODE < 0 && iguana_isnotarychain(coin->symbol) < 0 )
{
if ( (retstr= jumblr_listunspent(myinfo,coin,addr)) != 0 )
{
printf("jumblr.[%s].(%s)\n",coin->symbol,retstr);
if ( (retjson= cJSON_Parse(retstr)) != 0 )
{
if ( (n= cJSON_GetArraySize(retjson)) > 0 )
for (i=0; i<n; i++)
balance += SATOSHIDEN * jdouble(jitem(retjson,i),"amount");
free_json(retjson);
}
free(retstr);
}
}
else if ( (retstr= dex_getbalance(myinfo,coin,0,0,coin->symbol,addr)) != 0 )
{
//printf("DEX retstr.(%s)\n",retstr);
if ( (retjson= cJSON_Parse(retstr)) != 0 )
{
balance = jdouble(retjson,"balance") * SATOSHIDEN;
//printf("GOT BALANCE %s %.8f\n",coin->symbol,dstr(balance));
free_json(retjson);
}
free(retstr);
}
}
else if ( (retstr= jumblr_zgetbalance(myinfo,coin,addr)) != 0 )
{
if ( (val= atof(retstr)) > SMALLVAL )
balance = val * SATOSHIDEN;
free(retstr);
}
return(balance);
}
int32_t jumblr_itemset(struct jumblr_item *ptr,cJSON *item,char *status)
{
cJSON *params,*amounts,*dest; char *from,*addr; int32_t i,n; int64_t amount;
/*"params" : {
"fromaddress" : "RDhEGYScNQYetCyG75Kf8Fg61UWPdwc1C5",
"amounts" : [
{
"address" : "zc9s3UdkDFTnnwHrMCr1vYy2WmkjhmTxXNiqC42s7BjeKBVUwk766TTSsrRPKfnX31Bbu8wbrTqnjDqskYGwx48FZMPHvft",
"amount" : 3.00000000
}
],
"minconf" : 1,
"fee" : 0.00010000
}*/
if ( (params= jobj(item,"params")) != 0 )
{
//printf("params.(%s)\n",jprint(params,0));
if ( (from= jstr(params,"fromaddress")) != 0 )
{
safecopy(ptr->src,from,sizeof(ptr->src));
}
if ( (amounts= jarray(&n,params,"amounts")) != 0 )
{
for (i=0; i<n; i++)
{
dest = jitem(amounts,i);
//printf("%s ",jprint(dest,0));
if ( (addr= jstr(dest,"address")) != 0 && (amount= jdouble(dest,"amount")*SATOSHIDEN) > 0 )
{
if ( strcmp(addr,JUMBLR_ADDR) == 0 )
ptr->fee = amount;
else
{
ptr->amount = amount;
safecopy(ptr->dest,addr,sizeof(ptr->dest));
}
}
}
}
ptr->txfee = jdouble(params,"fee") * SATOSHIDEN;
}
return(1);
}
void jumblr_opidupdate(struct supernet_info *myinfo,struct iguana_info *coin,struct jumblr_item *ptr)
{
char *retstr,*status,KMDjumblr[64],KMDdeposit[64],BTCaddr[64]; cJSON *retjson,*item;
if ( ptr->status == 0 )
{
if ( (retstr= jumblr_zgetoperationstatus(myinfo,coin,ptr->opid)) != 0 )
{
if ( (retjson= cJSON_Parse(retstr)) != 0 )
{
if ( cJSON_GetArraySize(retjson) == 1 )
{
item = jitem(retjson,0);
//printf("%s\n",jprint(item,0));
if ( (status= jstr(item,"status")) != 0 )
{
if ( strcmp(status,"success") == 0 )
{
ptr->status = jumblr_itemset(ptr,item,status);
jumblr_privkey(myinfo,BTCaddr,0,KMDdeposit,JUMBLR_DEPOSITPREFIX);
jumblr_privkey(myinfo,BTCaddr,0,KMDjumblr,"");
if ( (jumblr_addresstype(myinfo,coin,ptr->src) == 't' && jumblr_addresstype(myinfo,coin,ptr->src) == 'z' && strcmp(ptr->src,KMDdeposit) != 0) || (jumblr_addresstype(myinfo,coin,ptr->src) == 'z' && jumblr_addresstype(myinfo,coin,ptr->src) == 't' && strcmp(ptr->dest,KMDjumblr) != 0) )
{
printf("a non-jumblr t->z pruned\n");
free(jumblr_zgetoperationresult(myinfo,coin,ptr->opid));
ptr->status = -1;
}
}
else if ( strcmp(status,"failed") == 0 )
{
printf("%s failed\n",ptr->opid);
free(jumblr_zgetoperationresult(myinfo,coin,ptr->opid));
ptr->status = -1;
}
}
}
free_json(retjson);
}
free(retstr);
}
}
}
void jumblr_prune(struct supernet_info *myinfo,struct iguana_info *coin,struct jumblr_item *ptr)
{
struct jumblr_item *tmp; char oldsrc[128]; int32_t flag = 1;
printf("PRUNE %s\n",ptr->opid);
strcpy(oldsrc,ptr->src);
free(jumblr_zgetoperationresult(myinfo,coin,ptr->opid));
while ( flag != 0 )
{
flag = 0;
HASH_ITER(hh,myinfo->jumblrs,ptr,tmp)
{
if ( strcmp(oldsrc,ptr->dest) == 0 )
{
printf("prune %s (%s -> %s) matched oldsrc\n",ptr->opid,ptr->src,ptr->dest);
free(jumblr_zgetoperationresult(myinfo,coin,ptr->opid));
strcpy(oldsrc,ptr->src);
flag = 1;
break;
}
}
}
}
void jumblr_opidsupdate(struct supernet_info *myinfo,struct iguana_info *coin)
{
char *retstr; cJSON *array; int32_t i,n; struct jumblr_item *ptr;
if ( (retstr= jumblr_zlistoperationids(myinfo,coin)) != 0 )
{
if ( (array= cJSON_Parse(retstr)) != 0 )
{
if ( (n= cJSON_GetArraySize(array)) > 0 )
{
for (i=0; i<n; i++)
{
if ( (ptr= jumblr_opidadd(myinfo,coin,jstri(array,i))) != 0 )
{
if ( ptr->status == 0 )
jumblr_opidupdate(myinfo,coin,ptr);
//printf("%d: %s -> %s %.8f\n",ptr->status,ptr->src,ptr->dest,dstr(ptr->amount));
if ( jumblr_addresstype(myinfo,coin,ptr->src) == 'z' && jumblr_addresstype(myinfo,coin,ptr->dest) == 't' )
jumblr_prune(myinfo,coin,ptr);
}
}
}
free_json(array);
}
free(retstr);
}
}
int64_t jumblr_DEXsplit(struct supernet_info *myinfo,struct iguana_info *coin,bits256 *splittxidp,char *coinaddr,bits256 txid,int32_t vout,int64_t remaining,double bigprice,double middleprice,double smallprice,double fees[4],cJSON *privkeys,double esttxfee)
{
int64_t values[4],outputs[64],value,total,estfee; int32_t i,n,success=0,completed,sendflag,numoutputs = 0; char *retstr; cJSON *retjson,*utxo,*item;
total = 0;
estfee = SATOSHIDEN * esttxfee;
memset(values,0,sizeof(values));
memset(outputs,0,sizeof(outputs));
if ( bigprice > SMALLVAL )
values[0] = SATOSHIDEN * bigprice;
if ( middleprice > SMALLVAL )
values[1] = SATOSHIDEN * middleprice;
if ( smallprice > SMALLVAL )
values[2] = SATOSHIDEN * smallprice;
for (i=0; i<4; i++)
{
if ( fees[i] > SMALLVAL )
values[3+i] = SATOSHIDEN * fees[i];
}
for (i=0; i<7; i++)
{
if ( (value= values[i]) != 0 )
{
n = 0;
while ( n < 10 && remaining > value && numoutputs < sizeof(outputs)/sizeof(*outputs) )
{
outputs[numoutputs++] = value;
remaining -= value;
total += value;
printf("%.8f ",dstr(value));
n++;
}
}
}
char str[65]; printf("numoutputs.%d total %.8f %s/v%d\n",numoutputs,dstr(total),bits256_str(str,txid),vout);
if ( numoutputs > 1 ) // no point to make just one
{
if ( (retstr= _dex_gettxout(myinfo,coin->symbol,txid,vout)) != 0 )
{
item = cJSON_Parse(retstr);
jaddbits256(item,"txid",txid);
jaddnum(item,"vout",vout);
free(retstr);
if ( item != 0 )
{
utxo = cJSON_CreateArray();
jaddi(utxo,item);
sendflag = 0;
///printf("jitem.(%s)\n",jprint(utxo,0));
if ( (retstr= iguana_utxorawtx(myinfo,coin,0,coinaddr,coinaddr,outputs,numoutputs,0,&completed,sendflag,utxo,privkeys)) != 0 )
{
if ( completed != 0 )
{
if ( (retjson= cJSON_Parse(retstr)) != 0 )
{
if ( jobj(retjson,"error") == 0 && jobj(retjson,"sent") != 0 )
{
*splittxidp = jbits256(retjson,"sent");
success = 1;
printf("DEXsplit success %.8f\n",dstr(total));
}
free_json(retjson);
}
}
free(retstr);
}
free_json(utxo);
}
}
}
return(success * total);
}
double jumblr_DEXutxosize(double *targetvolBp,double *targetvolMp,double *targetvolSp,int32_t isbob,double kmdprice)
{
double fee,depositfactor = (isbob == 0) ? 1. : 1.2;
fee = JUMBLR_INCR * JUMBLR_FEE;
*targetvolBp = depositfactor * kmdprice * ((JUMBLR_INCR + 3*fee)*100 + 3*JUMBLR_TXFEE);
*targetvolMp = depositfactor * kmdprice * ((JUMBLR_INCR + 3*fee)*10 + 3*JUMBLR_TXFEE);
*targetvolSp = depositfactor * kmdprice * ((JUMBLR_INCR + 3*fee) + 3*JUMBLR_TXFEE);
return(depositfactor);
}
int32_t jumblr_DEXutxoind(int32_t *shouldsplitp,double targetvolB,double targetvolM,double targetvolS,double amount,double margin,double dexfeeratio,double esttxfee)
{
*shouldsplitp = 0;
if ( amount >= targetvolB )
{
if ( amount > margin * (targetvolB + targetvolS) )
*shouldsplitp = 1;
return(0);
}
else
{
if ( amount >= targetvolM )
{
if ( amount > margin * (targetvolM + targetvolS) )
*shouldsplitp = 1;
return(1);
}
else
{
if ( amount >= targetvolS )
{
if ( amount > margin * targetvolS )
*shouldsplitp = 1;
return(2);
}
else if ( amount >= targetvolB/dexfeeratio )
{
if ( amount > margin * targetvolB/dexfeeratio )
*shouldsplitp = 1;
return(3);
}
else if ( amount >= targetvolM/dexfeeratio )
{
if ( amount > margin * targetvolM/dexfeeratio )
*shouldsplitp = 1;
return(4);
}
else if ( amount >= targetvolS/dexfeeratio )
{
if ( amount > margin * targetvolS/dexfeeratio )
*shouldsplitp = 1;
return(5);
}
else if ( amount >= esttxfee )
{
if ( amount > esttxfee*4 )
*shouldsplitp = 1;
return(6);
}
else return(-1);
}
}
}
int32_t jumblr_DEXutxoupdate(struct supernet_info *myinfo,struct iguana_info *coin,int32_t *shouldsplitp,bits256 *splittxidp,char *coinaddr,bits256 privkey,bits256 txid,int32_t vout,uint64_t value,int32_t isbob,double kmdprice,double estfee)
{
double fees[4],targetvolB,amount,targetvolM,targetvolS,depositfactor,dexfeeratio,margin; int32_t ind = -1,i; cJSON *privkeys; char wifstr[128];
*shouldsplitp = 0;
margin = 1.1;
depositfactor = (isbob == 0) ? 1. : 1.2;
dexfeeratio = 500.;
amount = dstr(value);
memset(splittxidp,0,sizeof(*splittxidp));
depositfactor = jumblr_DEXutxosize(&targetvolB,&targetvolM,&targetvolS,isbob,kmdprice);
printf("depositfactor %.8f targetvols %.8f %.8f %.8f\n",depositfactor,targetvolB,targetvolM,targetvolS);
fees[0] = (margin * targetvolB) / dexfeeratio;
fees[1] = (margin * targetvolM) / dexfeeratio;
fees[2] = (margin * targetvolS) / dexfeeratio;
fees[3] = (strcmp("BTC",coin->symbol) == 0) ? 50000 : 10000;
for (i=0; i<4; i++)
if ( fees[i] < 10000 )
fees[i] = 10000;
if ( (ind= jumblr_DEXutxoind(shouldsplitp,targetvolB,targetvolM,targetvolS,amount,margin,dexfeeratio,fees[3])) >= 0 )
{
printf("shouldsplit.%d ind.%d\n",*shouldsplitp,ind);
if ( *shouldsplitp != 0 )
{
privkeys = cJSON_CreateArray();
bitcoin_priv2wif(wifstr,privkey,coin->chain->wiftype);
jaddistr(privkeys,wifstr);
if ( jumblr_DEXsplit(myinfo,coin,splittxidp,coinaddr,txid,vout,value,margin * targetvolB,margin * targetvolM,margin * targetvolS,fees,privkeys,estfee) > 0 )
ind = -1;
else *shouldsplitp = 0;
free_json(privkeys);
}
} // else printf("negative ind\n");
return(ind);
}
/*struct DEXcoin_info
{
bits256 deposit_privkey,jumblr_privkey;
struct iguana_info *coin;
cJSON *utxos,*spentutxos,*bigutxos,*normalutxos,*smallutxos,*feeutxos,*otherutxos;
double btcprice,USD_average,DEXpending,maxbid,minask,avail,KMDavail;
uint32_t lasttime;
char CMCname[32],symbol[16],depositaddr[64],KMDdepositaddr[64],KMDjumblraddr[64],jumblraddr[64];
};*/
int32_t jumblr_utxotxidpending(struct supernet_info *myinfo,bits256 *splittxidp,int32_t *indp,struct iguana_info *coin,bits256 txid,int32_t vout)
{
int32_t i;
memset(splittxidp,0,sizeof(*splittxidp));
for (i=0; i<coin->DEXinfo.numpending; i++)
{
if ( coin->DEXinfo.pending[i].vout == vout && bits256_cmp(coin->DEXinfo.pending[i].txid,txid) == 0 )
{
*indp = coin->DEXinfo.pending[i].ind;
*splittxidp = coin->DEXinfo.pending[i].splittxid;
// printf("jumblr_utxotxidpending found txid in slot.%d\n",i);
return(i);
}
}
// printf("jumblr_utxotxidpending cant find txid\n");
return(-1);
}
void jumblr_utxotxidpendingadd(struct supernet_info *myinfo,char *dest,struct iguana_info *coin,bits256 txid,int32_t vout,uint64_t value,bits256 splittxid,int32_t ind,double price,double estfee,int32_t shouldsplit)
{
struct jumblr_pending pend; cJSON *vals,*retjson; bits256 hash; char *retstr;
memset(&pend,0,sizeof(pend));
pend.splittxid = splittxid;
pend.txid = txid;
pend.vout = vout;
pend.ind = ind;
if ( 0 && myinfo->IAMLP == 0 && shouldsplit == 0 && ind < 3 )
{
static uint32_t num;
if ( num == 0 && price > SMALLVAL )
{
num++;
vals = cJSON_CreateObject();
jaddstr(vals,"source",coin->symbol);
jaddstr(vals,"dest",dest);
jaddnum(vals,"amount",price * 100);//dstr(value) - estfee);
jaddnum(vals,"minprice",price);
jaddnum(vals,"usejumblr",1);
memset(hash.bytes,0,sizeof(hash));
if ( (retstr= InstantDEX_request(myinfo,coin,0,0,hash,vals,"")) != 0 )
{
if ( (retjson= cJSON_Parse(retstr)) != 0 )
{
printf("request.(%s) -> (%s)\n",jprint(vals,0),retstr);
free_json(retjson);
}
free(retstr);
}
free_json(vals);
}
}
coin->DEXinfo.pending = realloc(coin->DEXinfo.pending,sizeof(*coin->DEXinfo.pending) * (1 + coin->DEXinfo.numpending));
coin->DEXinfo.pending[coin->DEXinfo.numpending++] = pend;
}
void jumblr_utxoupdate(struct supernet_info *myinfo,char *dest,struct iguana_info *coin,double price,char *coinaddr,bits256 privkey,double estfee)
{
char *retstr; cJSON *array,*item; int32_t shouldsplit,i,n,vout,ind; bits256 txid,splittxid; uint64_t value;
if ( (retstr= jumblr_listunspent(myinfo,coin,coinaddr)) != 0 )
{
//printf("%s.(%s)\n",coin->symbol,retstr);
if ( (array= cJSON_Parse(retstr)) != 0 )
{
if ( (n= cJSON_GetArraySize(array)) > 0 )
{
for (i=0; i<n; i++)
{
if ( (item= jitem(array,i)) == 0 )
continue;
txid = jbits256(item,"txid");
vout = jint(item,"vout");
value = SATOSHIDEN * jdouble(item,"amount");
//printf("price %.8f %llx/v%d %.8f %d of %d\n",price,(long long)txid.txid,vout,dstr(value),i,n);
if ( jumblr_utxotxidpending(myinfo,&splittxid,&ind,coin,txid,vout) < 0 )
{
ind = jumblr_DEXutxoupdate(myinfo,coin,&shouldsplit,&splittxid,coinaddr,privkey,txid,vout,value,myinfo->IAMLP,price,estfee);
jumblr_utxotxidpendingadd(myinfo,dest,coin,txid,vout,value,splittxid,ind,price,estfee,shouldsplit);
}
else
{
// update status of utxo
}
}
}
free_json(array);
}
free(retstr);
}
}
void jumblr_iteration(struct supernet_info *myinfo,struct iguana_info *coin,int32_t selector,int32_t modval)
{
//static uint32_t lasttime;
char BTCaddr[64],KMDaddr[64],*zaddr,*retstr; int32_t iter,counter,chosen_one,n; bits256 privkey; uint64_t amount=0,total=0; double fee; struct jumblr_item *ptr,*tmp; uint8_t r,s;
if ( myinfo->IAMNOTARY != 0 )
return;
fee = JUMBLR_INCR * JUMBLR_FEE;
OS_randombytes(&r,sizeof(r));
//r = 0;
// randomize size chosen and order of chunks
if ( strcmp(coin->symbol,"KMD") == 0 && coin->FULLNODE < 0 )
{
s = (selector + (r>>1)) % 3;
//printf("JUMBLR selector.%d modval.%d r.%d\n",selector,modval,r&7);
switch ( s )
{
case 0: // public -> z, need to importprivkey
jumblr_privkey(myinfo,BTCaddr,0,KMDaddr,JUMBLR_DEPOSITPREFIX);
if ( (total= jumblr_balance(myinfo,coin,KMDaddr)) >= (JUMBLR_INCR + 3*(fee+JUMBLR_TXFEE))*SATOSHIDEN )
{
if ( (r & 1) == 0 )
{
if ( (zaddr= jumblr_zgetnewaddress(myinfo,coin)) != 0 )
{
amount = 0;
if ( total >= SATOSHIDEN * ((JUMBLR_INCR + 3*fee)*100 + 3*JUMBLR_TXFEE) )
amount = SATOSHIDEN * ((JUMBLR_INCR + 3*fee)*100 + 3*JUMBLR_TXFEE);
if ( (r & 2) != 0 && total >= SATOSHIDEN * ((JUMBLR_INCR + 3*fee)*10 + 3*JUMBLR_TXFEE) )
amount = SATOSHIDEN * ((JUMBLR_INCR + 3*fee)*10 + 3*JUMBLR_TXFEE);
if ( (r & 4) != 0 )
amount = SATOSHIDEN * ((JUMBLR_INCR + 3*fee) + 3*JUMBLR_TXFEE);
if ( amount > 0 && (retstr= jumblr_sendt_to_z(myinfo,coin,KMDaddr,zaddr,dstr(amount))) != 0 )
{
printf("sendt_to_z.(%s)\n",retstr);
free(retstr);
}
free(zaddr);
} else printf("no zaddr from jumblr_zgetnewaddress\n");
}
} else printf("%s total %.8f vs %.8f\n",KMDaddr,dstr(total),(JUMBLR_INCR + 3*(fee+JUMBLR_TXFEE)));
break;
case 1: // z -> z
jumblr_opidsupdate(myinfo,coin);
chosen_one = -1;
for (iter=counter=0; iter<2; iter++)
{
counter = n = 0;
HASH_ITER(hh,myinfo->jumblrs,ptr,tmp)
{
if ( jumblr_addresstype(myinfo,coin,ptr->src) == 't' && jumblr_addresstype(myinfo,coin,ptr->dest) == 'z' )
{
if ( (r & 1) == 0 && ptr->spent == 0 && (total= jumblr_balance(myinfo,coin,ptr->dest)) >= (fee + JUMBLR_FEE)*SATOSHIDEN )
{
if ( iter == 1 && counter == chosen_one )
{
if ( (zaddr= jumblr_zgetnewaddress(myinfo,coin)) != 0 )
{
if ( (retstr= jumblr_sendz_to_z(myinfo,coin,ptr->dest,zaddr,dstr(total))) != 0 )
{
printf("n.%d counter.%d chosen_one.%d sendz_to_z.(%s)\n",n,counter,chosen_one,retstr);
free(retstr);
}
ptr->spent = (uint32_t)time(NULL);
free(zaddr);
break;
}
}
counter++;
}
}
n++;
}
if ( counter == 0 )
break;
if ( iter == 0 )
{
OS_randombytes((uint8_t *)&chosen_one,sizeof(chosen_one));
if ( chosen_one < 0 )
chosen_one = -chosen_one;
chosen_one %= counter;
printf("jumblr z->z chosen_one.%d of %d, from %d\n",chosen_one,counter,n);
}
}
break;
case 2: // z -> public
if ( myinfo->runsilent == 0 )
{
jumblr_opidsupdate(myinfo,coin);
chosen_one = -1;
for (iter=0; iter<2; iter++)
{
counter = n = 0;
HASH_ITER(hh,myinfo->jumblrs,ptr,tmp)
{
if ( jumblr_addresstype(myinfo,coin,ptr->src) == 'z' && jumblr_addresstype(myinfo,coin,ptr->dest) == 'z' )
{
if ( (r & 1) == 0 && ptr->spent == 0 && (total= jumblr_balance(myinfo,coin,ptr->dest)) >= (fee + JUMBLR_FEE)*SATOSHIDEN )
{
if ( iter == 1 && n == chosen_one )
{
privkey = jumblr_privkey(myinfo,BTCaddr,0,KMDaddr,"");
if ( (retstr= jumblr_sendz_to_t(myinfo,coin,ptr->dest,KMDaddr,dstr(total))) != 0 )
{
printf("sendz_to_t.(%s)\n",retstr);
free(retstr);
}
ptr->spent = (uint32_t)time(NULL);
break;
}
counter++;
}
}
n++;
}
if ( counter == 0 )
break;
if ( iter == 0 )
{
OS_randombytes((uint8_t *)&chosen_one,sizeof(chosen_one));
if ( chosen_one < 0 )
chosen_one = -chosen_one;
chosen_one %= counter;
printf("jumblr z->t chosen_one.%d of %d, from %d\n",chosen_one,counter,n);
}
}
}
break;
}
}
}

685
basilisk/smartaddress.c

@ -0,0 +1,685 @@
/******************************************************************************
* 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. *
* *
******************************************************************************/
// included from basilisk.c
// deposit address <coin> -> corresponding KMD address, if KMD deposit starts JUMBLR
// jumblr address <coin> is the destination of JUMBLR and JUMBLR BTC (would need tracking to map back to non-BTC)
// <symbol> address <coin> is DEX'ed for <SYMBOL>
// return value convention: -1 error, 0 partial match, >= 1 exact match
int32_t smartaddress_type(char *typestr)
{
char upper[64];
if ( strcmp(typestr,"deposit") != 0 && strcmp(typestr,"jumblr") != 0 && strcmp(typestr,"dividend") != 0 && strcmp(typestr,"pangea") != 0 )
{
upper[sizeof(upper)-1] = 0;
strncpy(upper,typestr,sizeof(upper)-1);
touppercase(upper);
if ( iguana_coinfind(upper) != 0 )
return(0);
else return(-1);
}
return(1);
}
bits256 jumblr_privkey(struct supernet_info *myinfo,char *coinaddr,uint8_t pubtype,char *KMDaddr,char *prefix)
{
bits256 privkey,pubkey; uint8_t pubkey33[33]; char passphrase[sizeof(myinfo->jumblr_passphrase) + 64];
sprintf(passphrase,"%s%s",prefix,myinfo->jumblr_passphrase);
if ( myinfo->jumblr_passphrase[0] == 0 )
strcpy(myinfo->jumblr_passphrase,"password");
conv_NXTpassword(privkey.bytes,pubkey.bytes,(uint8_t *)passphrase,(int32_t)strlen(passphrase));
bitcoin_pubkey33(myinfo->ctx,pubkey33,privkey);
bitcoin_address(coinaddr,pubtype,pubkey33,33);
bitcoin_address(KMDaddr,60,pubkey33,33);
//printf("(%s) -> (%s %s)\n",passphrase,coinaddr,KMDaddr);
return(privkey);
}
cJSON *smartaddress_extrajson(struct smartaddress *ap)
{
cJSON *retjson = cJSON_CreateObject();
if ( strcmp(ap->typestr,"dividend") == 0 )
{
}
return(retjson);
}
cJSON *smartaddress_json(struct smartaddress *ap)
{
char coinaddr[64],symbol[64]; uint8_t desttype,tmp,rmd160[20]; int32_t j,n; struct iguana_info *coin,*dest; cJSON *array,*item,*retjson; double amount;
retjson = cJSON_CreateObject();
jaddstr(retjson,"type",ap->typestr);
strcpy(symbol,ap->typestr), touppercase(symbol);
if ( (dest= iguana_coinfind(symbol)) != 0 )
desttype = dest->chain->pubtype;
else desttype = 60;
if ( (n= ap->numsymbols) > 0 )
{
array = cJSON_CreateArray();
for (j=0; j<n; j++)
{
if ( (coin= iguana_coinfind(ap->symbols[j].symbol)) != 0 )
{
bitcoin_address(coinaddr,coin->chain->pubtype,ap->pubkey33,33);
item = cJSON_CreateObject();
jaddstr(item,"coin",coin->symbol);
jaddstr(item,"address",coinaddr);
if ( (amount= ap->symbols[j].srcavail) != 0 )
jaddnum(item,"sourceamount",amount);
if ( dest != 0 )
{
bitcoin_addr2rmd160(&tmp,rmd160,coinaddr);
bitcoin_address(coinaddr,desttype,rmd160,20);
jaddstr(item,"dest",coinaddr);
if ( (amount= ap->symbols[j].destamount) != 0 )
jaddnum(item,"destamount",amount);
if ( coin->DEXinfo.depositaddr[0] != 0 )
{
jaddstr(item,"jumblr_deposit",coin->DEXinfo.depositaddr);
jaddnum(item,"deposit_avail",coin->DEXinfo.avail);
}
if ( coin->DEXinfo.jumblraddr[0] != 0 )
{
jaddstr(item,"jumblr",coin->DEXinfo.jumblraddr);
jaddnum(item,"jumblr_avail",coin->DEXinfo.jumblravail);
}
if ( ap->symbols[j].maxbid != 0. )
jaddnum(item,"maxbid",ap->symbols[j].maxbid);
if ( ap->symbols[j].minask != 0. )
jaddnum(item,"minask",ap->symbols[j].minask);
}
jadd(item,"extra",smartaddress_extrajson(ap));
jaddi(array,item);
}
}
jadd(retjson,"coins",array);
}
return(retjson);
}
void smartaddress_symboladd(struct smartaddress *ap,char *symbol,double maxbid,double minask)
{
char tmp[64]; struct smartaddress_symbol *sp;
strcpy(tmp,ap->typestr), touppercase(tmp);
if ( strcmp(tmp,symbol) != 0 )
{
ap->symbols = realloc(ap->symbols,(ap->numsymbols+1) * sizeof(*ap->symbols));
sp = &ap->symbols[ap->numsymbols++];
memset(sp,0,sizeof(*sp));
safecopy(sp->symbol,symbol,sizeof(sp->symbol));
sp->maxbid = maxbid;
sp->minask = minask;
printf("symboladd.%d (%s) <- (%s %f %f)\n",ap->numsymbols,ap->typestr,symbol,maxbid,minask);
}
}
struct smartaddress *smartaddressptr(struct smartaddress_symbol **ptrp,struct supernet_info *myinfo,char *_type,char *_symbol)
{
char type[64],symbol[64]; int32_t i,j,n; struct smartaddress *ap;
if ( ptrp != 0 )
*ptrp = 0;
strcpy(type,_type), tolowercase(type);
strcpy(symbol,_symbol), touppercase(symbol);
for (i=0; i<myinfo->numsmartaddrs; i++)
{
ap = &myinfo->smartaddrs[i];
if ( strcmp(type,ap->typestr) == 0 )
{
n = ap->numsymbols;
for (j=0; j<n; j++)
{
if ( strcmp(ap->symbols[j].symbol,symbol) == 0 )
{
if ( ptrp != 0 )
*ptrp = &ap->symbols[j];
return(ap);
}
}
}
}
return(0);
}
void smartaddress_minmaxupdate(struct supernet_info *myinfo,char *_type,char *_symbol,double maxbid,double minask)
{
struct smartaddress *ap; struct smartaddress_symbol *sp;
if ( (ap= smartaddressptr(&sp,myinfo,_type,_symbol)) != 0 && sp != 0 )
{
dxblend(&sp->maxbid,maxbid,0.5);
dxblend(&sp->minask,minask,0.5);
}
}
void smartaddress_availupdate(struct supernet_info *myinfo,char *_type,char *_symbol,double srcavail,double destamount)
{
struct smartaddress *ap; struct smartaddress_symbol *sp;
if ( (ap= smartaddressptr(&sp,myinfo,_type,_symbol)) != 0 && sp != 0 )
{
if ( srcavail > SMALLVAL )
sp->srcavail = srcavail;
if ( destamount > SMALLVAL )
sp->destamount = destamount;
}
}
int32_t _smartaddress_add(struct supernet_info *myinfo,bits256 privkey,char *type,char *symbol,double maxbid,double minask)
{
char coinaddr[64]; uint8_t addrtype,rmd160[20]; struct smartaddress *ap; int32_t i,j,n;
if ( myinfo->numsmartaddrs < sizeof(myinfo->smartaddrs)/sizeof(*myinfo->smartaddrs) )
{
for (i=0; i<myinfo->numsmartaddrs; i++)
{
ap = &myinfo->smartaddrs[i];
if ( strcmp(type,ap->typestr) == 0 && bits256_cmp(ap->privkey,privkey) == 0 )
{
n = ap->numsymbols;
for (j=0; j<n; j++)
{
if ( strcmp(ap->symbols[j].symbol,symbol) == 0 )
{
ap->symbols[j].maxbid = maxbid;
ap->symbols[j].minask = minask;
if ( maxbid > SMALLVAL && minask > SMALLVAL && smartaddress_type(type) == 0 )
smartaddress_minmaxupdate(myinfo,symbol,type,1./minask,1./maxbid);
return(0);
}
}
smartaddress_symboladd(ap,symbol,maxbid,minask);
return(i+1);
}
}
ap = &myinfo->smartaddrs[myinfo->numsmartaddrs];
if ( smartaddress_type(symbol) < 0 )
return(-1);
strcpy(ap->typestr,type);
smartaddress_symboladd(ap,"KMD",0.,0.);
smartaddress_symboladd(ap,"BTC",0.,0.);
ap->privkey = privkey;
bitcoin_pubkey33(myinfo->ctx,ap->pubkey33,privkey);
calc_rmd160_sha256(ap->rmd160,ap->pubkey33,33);
ap->pubkey = curve25519(privkey,curve25519_basepoint9());
char str[65]; printf("pubkey.(%s) ",bits256_str(str,ap->pubkey));
bitcoin_address(coinaddr,0,ap->pubkey33,33);
for (i=0; i<20; i++)
printf("%02x",ap->rmd160[i]);
bitcoin_addr2rmd160(&addrtype,rmd160,coinaddr);
printf(", ");
for (i=0; i<20; i++)
printf("%02x",rmd160[i]);
printf (" <- rmd160 for %d %s\n",myinfo->numsmartaddrs,coinaddr);
return(++myinfo->numsmartaddrs + 1);
}
printf("too many smartaddresses %d vs %d\n",myinfo->numsmartaddrs,(int32_t)(sizeof(myinfo->smartaddrs)/sizeof(*myinfo->smartaddrs)));
return(-1);
}
int32_t smartaddress_add(struct supernet_info *myinfo,bits256 privkey,char *type,char *symbol,double maxbid,double minask)
{
int32_t retval;
portable_mutex_lock(&myinfo->smart_mutex);
retval = _smartaddress_add(myinfo,privkey,type,symbol,maxbid,minask);
portable_mutex_unlock(&myinfo->smart_mutex);
return(retval);
}
int32_t smartaddress_symbolmatch(char *typestr,double *bidaskp,struct smartaddress *ap,char *symbol)
{
int32_t j,n;
strcpy(typestr,ap->typestr);
if ( (n= ap->numsymbols) > 0 )
{
for (j=0; j<n; j++)
{
if ( strcmp(ap->symbols[j].symbol,symbol) == 0 )
{
bidaskp[0] = ap->symbols[j].maxbid;
bidaskp[1] = ap->symbols[j].minask;
return(j);
}
}
}
return(-1);
}
int32_t smartaddress(struct supernet_info *myinfo,char *typestr,double *bidaskp,bits256 *privkeyp,char *symbol,char *coinaddr)
{
int32_t i,j,retval = -1; uint8_t addrtype,rmd160[20]; struct smartaddress *ap;
memset(privkeyp,0,sizeof(*privkeyp));
memset(bidaskp,0,sizeof(*bidaskp) * 2);
bitcoin_addr2rmd160(&addrtype,rmd160,coinaddr);
portable_mutex_lock(&myinfo->smart_mutex);
for (i=0; i<myinfo->numsmartaddrs; i++)
if ( memcmp(myinfo->smartaddrs[i].rmd160,rmd160,20) == 0 )
{
ap = &myinfo->smartaddrs[i];
*privkeyp = ap->privkey;
if ( (j= smartaddress_symbolmatch(typestr,bidaskp,ap,symbol)) >= 0 )
retval = 0;
else retval = (i+1);
break;
}
portable_mutex_unlock(&myinfo->smart_mutex);
for (i=0; i<20; i++)
printf("%02x",rmd160[i]);
printf(" <- rmd160 smartaddress cant find (%s) of %d\n",coinaddr,myinfo->numsmartaddrs);
return(retval);
}
int32_t smartaddress_pubkey(struct supernet_info *myinfo,char *typestr,double *bidaskp,bits256 *privkeyp,char *symbol,bits256 pubkey)
{
int32_t i,j,retval = -1; struct smartaddress *ap;
memset(privkeyp,0,sizeof(*privkeyp));
memset(bidaskp,0,sizeof(*bidaskp) * 2);
if ( bits256_cmp(myinfo->myaddr.persistent,pubkey) == 0 )
{
*privkeyp = myinfo->persistent_priv;
return(myinfo->numsmartaddrs);
}
portable_mutex_lock(&myinfo->smart_mutex);
for (i=0; i<myinfo->numsmartaddrs; i++)
if ( bits256_cmp(myinfo->smartaddrs[i].pubkey,pubkey) == 0 )
{
ap = &myinfo->smartaddrs[i];
*privkeyp = ap->privkey;
if ( (j= smartaddress_symbolmatch(typestr,bidaskp,ap,symbol)) >= 0 )
retval = 0;
else retval = (i+1);
break;
}
portable_mutex_unlock(&myinfo->smart_mutex);
//char str[65]; if ( retval < 0 )
// printf("smartaddress_pubkey no match for %s\n",bits256_str(str,pubkey));
return(retval);
}
int32_t smartaddress_pubkey33(struct supernet_info *myinfo,char *typestr,double *bidaskp,bits256 *privkeyp,char *symbol,uint8_t *pubkey33)
{
int32_t i,j,retval = -1; struct smartaddress *ap;
memset(privkeyp,0,sizeof(*privkeyp));
memset(bidaskp,0,sizeof(*bidaskp) * 2);
portable_mutex_lock(&myinfo->smart_mutex);
for (i=0; i<myinfo->numsmartaddrs; i++)
if ( memcmp(myinfo->smartaddrs[i].pubkey33,pubkey33,33) == 0 )
{
ap = &myinfo->smartaddrs[i];
*privkeyp = ap->privkey;
if ( (j= smartaddress_symbolmatch(typestr,bidaskp,ap,symbol)) >= 0 )
retval = 0;
else retval = (i+1);
break;
}
portable_mutex_unlock(&myinfo->smart_mutex);
return(retval);
}
void smartaddress_CMCname(char *CMCname,char *symbol)
{
if ( strcmp(symbol,"KMD") == 0 )
strcpy(CMCname,"komodo");
else if ( strcmp(symbol,"BTC") == 0 )
strcpy(CMCname,"bitcoin");
}
void smartaddress_coinupdate(struct supernet_info *myinfo,char *symbol,double BTC2KMD,double KMDavail,double KMD2USD)
{
int32_t r; double avebid,aveask,highbid,lowask,CMC_average,changes[3]; struct iguana_info *coin; struct DEXcoin_info *ptr;
if ( (coin= iguana_coinfind(symbol)) != 0 )
{
ptr = &coin->DEXinfo;
ptr->coin = coin;
if ( coin->CMCname[0] == 0 )
smartaddress_CMCname(coin->CMCname,symbol);
r = (((symbol[0]^symbol[1]^symbol[2])&0x7f) % 15) - 7; // 53 to 67 seconds
if ( time(NULL) > (ptr->lasttime + 60 + r) )
{
if ( strcmp(symbol,ptr->symbol) != 0 )
{
safecopy(ptr->symbol,symbol,sizeof(ptr->symbol));
safecopy(ptr->CMCname,coin->CMCname,sizeof(ptr->CMCname));
}
ptr->deposit_privkey = jumblr_privkey(myinfo,ptr->depositaddr,coin->chain->pubtype,ptr->KMDdepositaddr,JUMBLR_DEPOSITPREFIX);
ptr->jumblr_privkey = jumblr_privkey(myinfo,ptr->jumblraddr,coin->chain->pubtype,ptr->KMDjumblraddr,"");
ptr->avail = dstr(jumblr_balance(myinfo,coin,ptr->depositaddr));
ptr->jumblravail = dstr(jumblr_balance(myinfo,ptr->coin,ptr->jumblraddr));
if ( strcmp(symbol,"USD") == 0 )
{
if ( KMD2USD > SMALLVAL )
{
ptr->kmdprice = 1./ KMD2USD;
if ( (ptr->BTC2KMD= BTC2KMD) > SMALLVAL )
ptr->btcprice = ptr->kmdprice * BTC2KMD;
}
printf("USD btcprice %.8f kmdprice %.8f\n",ptr->btcprice,ptr->kmdprice);
}
else
{
if ( strcmp(symbol,"BTC") == 0 )
ptr->btcprice = 1.;
else if ( coin->CMCname[0] != 0 && (ptr->btcprice == 0. || (ptr->counter++ % 10) == 0) )
ptr->btcprice = get_theoretical(&avebid,&aveask,&highbid,&lowask,&CMC_average,changes,coin->CMCname,symbol,"BTC",&ptr->USD_average);
if ( strcmp("KMD",symbol) == 0 )
ptr->kmdprice = 1.;
else if ( (ptr->BTC2KMD= BTC2KMD) > SMALLVAL )
ptr->kmdprice = ptr->btcprice / BTC2KMD;
}
ptr->lasttime = (uint32_t)time(NULL);
printf("%s avail %.8f KMDavail %.8f btcprice %.8f deposit.(%s %s) -> jumblr.(%s %s)\n",symbol,ptr->avail,KMDavail,ptr->btcprice,ptr->depositaddr,ptr->KMDdepositaddr,ptr->jumblraddr,ptr->KMDjumblraddr);
}
} // else printf("skip\n");
}
void smartaddress_dex(struct supernet_info *myinfo,char *type,int32_t selector,struct iguana_info *basecoin,char *coinaddr,double maxavail,struct iguana_info *relcoin,double maxbid,double minask,cJSON *extraobj,double maxvol)
{
double minamount,minbtc,price,avail,vol,btc2kmd,basebtc,relbtc,baseusd,relusd; char *retstr; cJSON *vals; bits256 hash; struct smartaddress *ap;
basebtc = basecoin->DEXinfo.btcprice;
relbtc = relcoin->DEXinfo.btcprice;
baseusd = basecoin->DEXinfo.USD_average;
relusd = relcoin->DEXinfo.USD_average;
if ( (btc2kmd= basecoin->DEXinfo.BTC2KMD) < SMALLVAL && (btc2kmd= relcoin->DEXinfo.BTC2KMD) < SMALLVAL )
return;
minamount = price = 0.;
if ( basebtc < SMALLVAL && relbtc < SMALLVAL )
return;
if ( myinfo->DEXratio < .95 || myinfo->DEXratio > 1.01 )
myinfo->DEXratio = 0.995;
if ( basebtc < SMALLVAL || relbtc < SMALLVAL )
{
if ( (price= maxbid) > SMALLVAL )
{
if ( basebtc < SMALLVAL )
basebtc = price * relbtc, printf("calculated basebtc %.8f from (%.8f * %.8f)\n",basebtc,price,relbtc);
else if ( relbtc < SMALLVAL )
relbtc = basebtc / price, printf("calculated relbtc %.8f from (%.8f / %.8f)\n",relbtc,basebtc,price); // price * relbtc == basebtc
}
} else price = myinfo->DEXratio * (basebtc / relbtc);
minbtc = btc2kmd * (JUMBLR_INCR + 3*(JUMBLR_INCR * JUMBLR_FEE + JUMBLR_TXFEE));
if ( minamount == 0. && basebtc > SMALLVAL )
minamount = (minbtc / basebtc);
printf("DEX %s/%s maxavail %.8f minbtc %.8f btcprice %.8f -> minamount %.8f price %.8f vs maxbid %.8f DEXratio %.5f DEXpending %.8f\n",basecoin->symbol,relcoin->symbol,maxavail,minbtc,basecoin->DEXinfo.btcprice,minamount,price,maxbid,myinfo->DEXratio,basecoin->DEXinfo.DEXpending);
if ( minamount > SMALLVAL && maxavail > minamount + basecoin->DEXinfo.DEXpending && (maxbid == 0. || price <= maxbid) )
{
avail = (maxavail - basecoin->DEXinfo.DEXpending);
/*if ( avail >= (100. * minamount) )
vol = (100. * minamount);
else if ( avail >= (10. * minamount) )
vol = (10. * minamount);
else*/ if ( avail >= minamount )
vol = minamount;
else vol = 0.;
if ( vol > 0. )
{
vals = cJSON_CreateObject();
jaddstr(vals,"source",basecoin->symbol);
jaddstr(vals,"dest",relcoin->symbol);
jaddnum(vals,"amount",vol);
jaddnum(vals,"minprice",price);
if ( (ap= smartaddressptr(0,myinfo,type,basecoin->symbol)) != 0 )
jaddbits256(vals,"srchash",ap->pubkey);
if ( selector != 0 )
{
jaddnum(vals,"usejumblr",selector);
jaddnum(vals,"DEXselector",selector);
}
memset(hash.bytes,0,sizeof(hash));
basecoin->DEXinfo.DEXpending += vol;
if ( (retstr= InstantDEX_request(myinfo,basecoin,0,0,hash,vals,"")) != 0 )
{
printf("request.(%s) -> (%s)\n",jprint(vals,0),retstr);
free(retstr);
}
free_json(vals);
} else printf("avail %.8f < minamount %.8f\n",avail,minamount);
} //else printf("failed if check %d %d %d %d\n",minamount > SMALLVAL,maxavail > minamount + basecoin->DEXinfo.DEXpending,maxbid == 0,price <= maxbid);
/*
minbtc = (basecoin->DEXinfo.btcprice * 1.2) * (JUMBLR_INCR + 3*(JUMBLR_INCR * JUMBLR_FEE + JUMBLR_TXFEE));
btcavail = dstr(jumblr_balance(myinfo,coinbtc,kmdcoin->DEXinfo.depositaddr));
avail = (btcavail - coinbtc->DEXinfo.DEXpending);
printf("BTC.%d deposits %.8f, min %.8f avail %.8f pending %.8f\n",toKMD,btcavail,minbtc,avail,coinbtc->DEXinfo.DEXpending);
if ( toKMD == 0 && coinbtc != 0 && btcavail > (minbtc + coinbtc->DEXinfo.DEXpending) )
{
if ( vol > 0. )
{
vals = cJSON_CreateObject();
jaddstr(vals,"source","BTC");
jaddstr(vals,"dest","KMD");
jaddnum(vals,"amount",vol);
jaddnum(vals,"minprice",0.985/kmdcoin->DEXinfo.btcprice);
jaddnum(vals,"usejumblr",1);
jaddnum(vals,"DEXselector",1);
memset(hash.bytes,0,sizeof(hash));
coinbtc->DEXinfo.DEXpending += vol;
if ( (retstr= InstantDEX_request(myinfo,coinbtc,0,0,hash,vals,"")) != 0 )
{
printf("request.(%s) -> (%s)\n",jprint(vals,0),retstr);
free(retstr);
}
free_json(vals);
// curl --url "http://127.0.0.1:7778" --data "{\"agent\":\"InstantDEX\",\"method\":\"request\",\"vals\":{\"source\":\"KMD\",\"amount\":20,\"dest\":\"USD\",\"minprice\":0.08}}"
}
} //else printf("btcavail %.8f pending %.8f\n",btcavail,pending);
minkmd = 100.;
avail = (kmdcoin->DEXinfo.KMDavail - kmdcoin->DEXinfo.DEXpending);
printf("KMD.%d deposits %.8f, min %.8f, avail %.8f pending %.8f\n",toKMD,kmdcoin->DEXinfo.KMDavail,minkmd,avail,kmdcoin->DEXinfo.DEXpending);
if ( toKMD != 0 && coinbtc != 0 && kmdcoin->DEXinfo.KMDavail > (minkmd + kmdcoin->DEXinfo.DEXpending) )
{
if ( avail > 100.*JUMBLR_INCR )
vol = 100.*JUMBLR_INCR;
else if ( avail > 10.*JUMBLR_INCR )
vol = 10.*JUMBLR_INCR;
else if ( avail >= JUMBLR_INCR )
vol = JUMBLR_INCR;
else vol = 0.;
if ( vol > 0. )
{
vals = cJSON_CreateObject();
jaddstr(vals,"source","KMD");
jaddstr(vals,"dest","BTC");
jaddnum(vals,"amount",vol);
//jaddnum(vals,"destamount",JUMBLR_INCR*kmdcoin->DEXinfo.btcprice);
jaddnum(vals,"minprice",0.985 * kmdcoin->DEXinfo.btcprice);
jaddnum(vals,"usejumblr",2);
memset(hash.bytes,0,sizeof(hash));
kmdcoin->DEXinfo.DEXpending += vol;
jaddnum(vals,"DEXselector",2);
if ( (retstr= InstantDEX_request(myinfo,coinbtc,0,0,hash,vals,"")) != 0 )
{
printf("request.(%s) -> (%s)\n",jprint(vals,0),retstr);
free(retstr);
}
free_json(vals);
}
} else printf("kmdavail %.8f pending %.8f\n",kmdcoin->DEXinfo.avail,kmdcoin->DEXinfo.DEXpending);*/
}
void smartaddress_depositjumblr(struct supernet_info *myinfo,char *symbol,char *coinaddr,double maxbid,double minask,cJSON *extraobj)
{
struct iguana_info *basecoin,*relcoin;
if ( (basecoin= iguana_coinfind(symbol)) != 0 && (relcoin= iguana_coinfind("KMD")) != 0 )
{
if ( strcmp(coinaddr,basecoin->DEXinfo.depositaddr) == 0 )
smartaddress_dex(myinfo,"deposit",1,basecoin,coinaddr,basecoin->DEXinfo.avail,relcoin,maxbid,minask,extraobj,0.);
else printf("smartaddress_jumblr.%s: mismatch deposit address (%s) vs (%s)\n",symbol,coinaddr,basecoin->DEXinfo.depositaddr);
}
}
double smartaddress_jumblrcredit(struct supernet_info *myinfo,char *symbol)
{
return(0.); // default to BTC conversion for now
}
void smartaddress_jumblr(struct supernet_info *myinfo,char *symbol,char *coinaddr,double maxbid,double minask,cJSON *extraobj)
{
struct iguana_info *basecoin,*relcoin; double credits = 0.;
if ( strcmp("BTC",symbol) != 0 )
{
if ( (credits= smartaddress_jumblrcredit(myinfo,symbol)) <= 0. )
return;
}
if ( (basecoin= iguana_coinfind("KMD")) != 0 && (relcoin= iguana_coinfind(symbol)) != 0 )
{
if ( strcmp(coinaddr,basecoin->DEXinfo.jumblraddr) == 0 )
smartaddress_dex(myinfo,"jumblr",2,basecoin,coinaddr,basecoin->DEXinfo.jumblravail,relcoin,maxbid,minask,extraobj,credits);
else printf("smartaddress_jumblr.%s: mismatch jumblr address (%s) vs (%s)\n",symbol,coinaddr,basecoin->DEXinfo.jumblraddr);
}
}
void smartaddress_dividend(struct supernet_info *myinfo,char *symbol,char *coinaddr,double maxbid,double minask,cJSON *extraobj)
{
// support list of weighted addresses, including snapshots
}
void smartaddress_pangea(struct supernet_info *myinfo,char *symbol,char *coinaddr,double maxbid,double minask,cJSON *extraobj)
{
// table deposit
}
void smartaddress_action(struct supernet_info *myinfo,int32_t selector,char *typestr,char *symbol,char *coinaddr,double maxbid,double minask,cJSON *extraobj)
{
char rel[64]; struct iguana_info *basecoin,*relcoin; double avail;
if ( strcmp(typestr,"deposit") == 0 && selector == 0 )
smartaddress_depositjumblr(myinfo,symbol,coinaddr,maxbid,minask,extraobj);
else if ( strcmp(typestr,"jumblr") == 0 && selector == 0 )
smartaddress_jumblr(myinfo,symbol,coinaddr,maxbid,minask,extraobj);
else if ( strcmp(typestr,"dividend") == 0 && selector == 0 )
smartaddress_dividend(myinfo,symbol,coinaddr,maxbid,minask,extraobj);
else if ( strcmp(typestr,"pangea") == 0 && selector == 0 )
smartaddress_pangea(myinfo,symbol,coinaddr,maxbid,minask,extraobj);
else
{
safecopy(rel,typestr,sizeof(rel));
touppercase(rel);
if ( (relcoin= iguana_coinfind(rel)) != 0 && (basecoin= iguana_coinfind(symbol)) != 0 )
{
if ( myinfo->numswaps == 0 )//|| (basecoin->FULLNODE < 0 && relcoin->FULLNODE < 0) )
{
if ( (avail= dstr(jumblr_balance(myinfo,basecoin,coinaddr))) > SMALLVAL )
{
smartaddress_availupdate(myinfo,typestr,symbol,avail,SMALLVAL*0.99);
smartaddress_dex(myinfo,typestr,0,basecoin,coinaddr,avail,relcoin,maxbid,minask,extraobj,0.);
}
}
}
}
}
void smartaddress_update(struct supernet_info *myinfo,int32_t selector)
{
double maxbid,minask; uint8_t addrtype,rmd160[20]; char *smartstr,*typestr,*symbol,*address,coinaddr[64]; cJSON *smartarray,*extraobj,*item,*array,*coinitem; int32_t iter,i,n,j,m; struct iguana_info *kmdcoin,*coinbtc = 0;
//printf("smartaddress_update numswaps.%d notary.%d IAMLP.%d %p %p %f\n",myinfo->numswaps,myinfo->IAMNOTARY,myinfo->IAMLP,kmdcoin,coinbtc,kmdcoin->DEXinfo.btcprice);
if ( myinfo->IAMNOTARY != 0 || myinfo->IAMLP != 0 || myinfo->secret[0] == 0 )
return;
kmdcoin = iguana_coinfind("KMD");
coinbtc = iguana_coinfind("BTC");
if ( kmdcoin == 0 || coinbtc == 0 )
return;
smartaddress_coinupdate(myinfo,"KMD",0.,0.,0.); // must be first
if ( kmdcoin->DEXinfo.btcprice > SMALLVAL )
{
if ( (smartstr= InstantDEX_smartaddresses(myinfo,0,0,0)) != 0 )
{
if ( (smartarray= cJSON_Parse(smartstr)) != 0 )
{
if ( (n= cJSON_GetArraySize(smartarray)) > 0 )
{
for (iter=0; iter<2; iter++)
{
for (i=0; i<n; i++)
{
item = jitem(smartarray,i);
if ( (typestr= jstr(item,"type")) != 0 && (array= jarray(&m,item,"coins")) != 0 )
{
for (j=0; j<m; j++)
{
coinitem = jitem(array,j);
if ( (symbol= jstr(coinitem,"coin")) == 0 )
continue;
if ( iter == 0 )
smartaddress_coinupdate(myinfo,symbol,kmdcoin->DEXinfo.btcprice,kmdcoin->DEXinfo.avail,kmdcoin->DEXinfo.USD_average);
else
{
printf("Action.%s (%s)\n",typestr,jprint(coinitem,0));
if ( (address= jstr(coinitem,"address")) != 0 )
{
if ( strcmp(typestr,"jumblr") == 0 )
{
bitcoin_addr2rmd160(&addrtype,rmd160,address);
bitcoin_address(coinaddr,kmdcoin->chain->pubtype,rmd160,20);
} else strcpy(coinaddr,address);
maxbid = jdouble(coinitem,"maxbid");
minask = jdouble(coinitem,"minask");
extraobj = jobj(coinitem,"extra");
smartaddress_action(myinfo,selector,typestr,symbol,coinaddr,maxbid,minask,extraobj);
}
}
}
}
}
}
}
free_json(smartarray);
}
free(smartstr);
}
}
}
#include "../includes/iguana_apidefs.h"
#include "../includes/iguana_apideclares.h"
#include "../includes/iguana_apideclares2.h"
ZERO_ARGS(InstantDEX,smartaddresses)
{
int32_t i; cJSON *retjson = cJSON_CreateArray();
portable_mutex_lock(&myinfo->smart_mutex);
for (i=0; i<myinfo->numsmartaddrs; i++)
jaddi(retjson,smartaddress_json(&myinfo->smartaddrs[i]));
portable_mutex_unlock(&myinfo->smart_mutex);
return(jprint(retjson,1));
}
TWO_STRINGS_AND_TWO_DOUBLES(InstantDEX,smartaddress,type,symbol,maxbid,minask)
{
char prefix[64],coinaddr[64],KMDaddr[64],typestr[64]; double bidask[2]; uint8_t pubkey33[33]; bits256 privkey;
if ( smartaddress_type(type) < 0 )
return(clonestr("{\"error\":\"non-supported smartaddress type\"}"));
if ( iguana_coinfind(symbol) == 0 )
return(clonestr("{\"error\":\"non-supported smartaddress symbol\"}"));
if ( strcmp(type,"deposit") == 0 || strcmp(type,"jumblr") == 0 )
{
if ( smartaddress_pubkey(myinfo,typestr,bidask,&privkey,symbol,strcmp(type,"deposit") == 0 ? myinfo->jumblr_depositkey : myinfo->jumblr_pubkey) < 0 )
return(clonestr("{\"error\":\"unexpected missing smartaddress deposit/jumblr\"}"));
}
else
{
strcpy(prefix,type);
tolowercase(prefix);
if ( strcmp(prefix,"btc") == 0 || strcmp(prefix,"kmd") == 0 )
return(clonestr("{\"success\":\"no need add BTC or KMD to smartaddress\"}"));
strcat(prefix," ");
privkey = jumblr_privkey(myinfo,coinaddr,0,KMDaddr,prefix);
}
if ( (coin= iguana_coinfind(symbol)) == 0 )
return(clonestr("{\"error\":\"non-supported smartaddress symbol\"}"));
bitcoin_pubkey33(myinfo->ctx,pubkey33,privkey);
bitcoin_address(coinaddr,coin->chain->pubtype,pubkey33,33);
smartaddress_add(myinfo,privkey,type,symbol,maxbid,minask);
return(InstantDEX_smartaddresses(myinfo,0,0,0));
}
#include "../includes/iguana_apiundefs.h"

1072
basilisk/tradebots_SVM.h

File diff suppressed because it is too large

1237
basilisk/tradebots_liquidity.c

File diff suppressed because it is too large

108
basilisk/tradebots_marketmaker.c

@ -0,0 +1,108 @@
/******************************************************************************
* 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. *
* *
******************************************************************************/
// included from basilisk.c
// "currency":{"value":%.8f, "pending":%.8f}
cJSON *tradebot_balancediff(cJSON *item,cJSON *anchoritem) // only item might be null
{
double current[2],past[2]; int32_t i; cJSON *diffitem = jduplicate(anchoritem);
memset(current,0,sizeof(current));
memset(past,0,sizeof(past));
if ( jobj(diffitem,"value") != 0 )
jdelete(diffitem,"value");
if ( jobj(diffitem,"pending") != 0 )
jdelete(diffitem,"pending");
for (i=0; i<2; i++)
{
if ( current[i] != 0. || past[i] != 0. )
jaddnum(diffitem,i == 0 ? "value" : "pending",current[i] - past[i]);
}
return(diffitem);
}
cJSON *tradebot_balancesdiff(struct supernet_info *myinfo,cJSON *current,cJSON *anchor)
{
cJSON *item,*anchoritem,*diffitem,*array; int32_t i,n; char *field;
if ( anchor == 0 )
return(jduplicate(current));
array = cJSON_CreateObject();
n = cJSON_GetArraySize(current);
for (i=0; i<n; i++)
{
item = jitem(current,i);
field = jfieldname(item);
if ( (anchoritem= jobj(anchor,field)) != 0 )
diffitem = tradebot_balancediff(item,anchoritem);
else diffitem = jduplicate(item);
jadd(array,field,diffitem);
}
n = cJSON_GetArraySize(anchor);
for (i=0; i<n; i++)
{
item = jitem(current,i);
field = jfieldname(item);
if ( jobj(array,field) == 0 )
jadd(array,field,tradebot_balancediff(0,item));
}
return(array);
}
// get balances from all exchanges, wallets, pending
double tradebot_balance(struct supernet_info *myinfo,char *base)
{
cJSON *json; double value = 0.; int32_t i; struct iguana_info *coin = iguana_coinfind(base);
if ( coin != 0 && (json= iguana_getinfo(myinfo,coin)) != 0 )
{
value = jdouble(json,"balance");
free_json(json);
}
for (i=0; i<myinfo->numexchanges; i++)
{
value += 0;//InstantDEX_balance(myinfo,0,0,0,exchange,base);
}
return(value);
}
void tradebot_pendingadd(struct supernet_info *myinfo,cJSON *tradejson,char *base,double basevolume,char *rel,double relvolume)
{
portable_mutex_lock(&myinfo->pending_mutex);
// add to myinfo->trades
portable_mutex_unlock(&myinfo->pending_mutex);
}
void tradebot_pendingremove(struct supernet_info *myinfo,char *base,double basevolume,char *rel,double relvolume)
{
portable_mutex_lock(&myinfo->pending_mutex);
// remove from myinfo->trades
portable_mutex_unlock(&myinfo->pending_mutex);
}
double tradebot_pending(struct supernet_info *myinfo,char *base)
{
double pending = 0.; struct pending_trade *tp,*tmp;
portable_mutex_lock(&myinfo->pending_mutex);
HASH_ITER(hh,myinfo->trades,tp,tmp)
{
if ( strcmp(base,tp->base) == 0 )
pending += tp->dir * tp->basevolume;
else if ( strcmp(base,tp->rel) == 0 )
pending -= tp->dir * tp->relvolume;
}
portable_mutex_unlock(&myinfo->pending_mutex);
return(pending);
}

128
crypto777/OS_nonportable.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -13,7 +13,24 @@
* *
******************************************************************************/
/**
* - we need to include WinSock2.h header to correctly use windows structure
* as the application is still using 32bit structure from mingw so, we need to
* add the include based on checking
*
* @author - fadedreamz@gmail.com
* @remarks - #if (defined(_M_X64) || defined(__amd64__)) && defined(WIN32)
* is equivalent to #if defined(_M_X64) as _M_X64 is defined for MSVC only
*
* @remarks - we need this because in win64 we are using windows provided pollfd structure
* 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
#include "OS_portable.h"
@ -47,6 +64,85 @@ void *OS_nonportable_tmpalloc(char *dirname,char *name,struct OS_memspace *mem,l
#include <tlhelp32.h>
#include <time.h>
/*#include <intrin.h>
static uint32_t __inline __builtin_clzll(uint64_t x) {
unsigned long r = 0;
_BitScanReverse64(&r, x);
return (63-r);
}*/
void usleep(int32_t micros)
{
if ( micros < 1000 )
Sleep(1);
else Sleep(micros / 1000);
}
int
mkstemp (template)
char *template;
{
static const char letters[]
= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
static uint64_t value;
#ifdef HAVE_GETTIMEOFDAY
struct timeval tv;
#endif
char *XXXXXX;
size_t len;
int count;
len = strlen (template);
if ((int) len < 6
|| strncmp (&template[len - 6], "XXXXXX", 6))
{
return -1;
}
XXXXXX = &template[len - 6];
#ifdef HAVE_GETTIMEOFDAY
/* Get some more or less random data. */
gettimeofday (&tv, NULL);
value += ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
#else
value += getpid ();
#endif
for (count = 0; count < TMP_MAX; ++count)
{
uint64_t v = value;
int fd;
/* Fill in the random bits. */
XXXXXX[0] = letters[v % 62];
v /= 62;
XXXXXX[1] = letters[v % 62];
v /= 62;
XXXXXX[2] = letters[v % 62];
v /= 62;
XXXXXX[3] = letters[v % 62];
v /= 62;
XXXXXX[4] = letters[v % 62];
v /= 62;
XXXXXX[5] = letters[v % 62];
fd = open (template, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
if (fd >= 0)
/* The file does not exist. */
return fd;
/* This is a random value. It is only necessary that the next
TMP_MAX values generated by adding 7777 to VALUE are different
with (module 2^32). */
value += 7777;
}
/* We return the null string if we can't find a unique file name. */
template[0] = '\0';
return -1;
}
#include "../OSlibs/win/mman.h"
@ -496,10 +592,10 @@ char *OS_nonportable_path(char *str)
return(str);
}
void *OS_nonportable_mapfile(char *fname,uint64_t *filesizep,int32_t enablewrite)
void *OS_nonportable_mapfile(char *fname,long *filesizep,int32_t enablewrite)
{
int32_t fd,rwflags,flags = MAP_FILE|MAP_SHARED;
uint64_t filesize;
long filesize;
void *ptr = 0;
*filesizep = 0;
if ( enablewrite != 0 )
@ -511,7 +607,7 @@ void *OS_nonportable_mapfile(char *fname,uint64_t *filesizep,int32_t enablewrite
return(0);
}
if ( *filesizep == 0 )
filesize = (uint64_t)lseek(fd,0,SEEK_END);
filesize = (long)lseek(fd,0,SEEK_END);
else filesize = *filesizep;
rwflags = PROT_READ;
if ( enablewrite != 0 )
@ -528,15 +624,23 @@ void *OS_nonportable_mapfile(char *fname,uint64_t *filesizep,int32_t enablewrite
return(ptr);
}
int32_t OS_nonportable_renamefile(char *fname,char *newfname)
int32_t OS_nonportable_removefile(char *fname)
{
char cmdstr[1024],tmp[512];
char tmp[512];
strcpy(tmp,fname);
OS_nonportable_path(tmp);
sprintf(cmdstr,"del %s",tmp);
if ( system(cmdstr) != 0 )
printf("error deleting file.(%s)\n",cmdstr);
else return(1);
OS_portable_path(tmp);
return((DeleteFileA(tmp) == 0) ? -1 : 0);
}
int32_t OS_nonportable_renamefile(char *fname,char *newfname)
{
char tmp[1024],tmp2[1024]; int32_t retval,retvaldel;
strcpy(tmp,fname), strcpy(tmp2,newfname);
OS_nonportable_path(tmp), OS_nonportable_path(tmp2);
retvaldel = OS_nonportable_removefile(tmp2);
retval = MoveFileA(tmp,tmp2);
//printf("call Movefile(%s -> %s) retval.%d retvaldel.%d %d\n",tmp,tmp2,retval,retvaldel,GetLastError());
return((retval == 0) ? -1 : 0);
}
int32_t OS_nonportable_launch(char *args[])

43
crypto777/OS_portable.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -30,7 +30,7 @@ void OS_portable_init()
void OS_portable_randombytes(unsigned char *x,long xlen)
{
#ifdef _WIN32
return(OS_nonportable_randombytes(x,xlen));
OS_nonportable_randombytes(x,xlen);
#else
static int fd = -1;
int32_t i;
@ -48,7 +48,7 @@ void OS_portable_randombytes(unsigned char *x,long xlen)
sleep(1);
continue;
}
if ( 0 )
if ( (0) )
{
int32_t j;
for (j=0; j<i; j++)
@ -94,16 +94,21 @@ char *OS_portable_path(char *str)
#endif
}
FILE *OS_appendfile(char *origfname)
{
char fname[1024]; FILE *fp;
strcpy(fname,origfname);
OS_portable_path(fname);
if ( (fp= fopen(fname,"rb+")) == 0 )
fp = fopen(fname,"wb");
else fseek(fp,0,SEEK_END);
return(fp);
}
int32_t OS_portable_renamefile(char *fname,char *newfname)
{
#ifdef _WIN32
char cmdstr[1024],tmp[512];
strcpy(tmp,fname);
OS_portable_path(tmp);
sprintf(cmdstr,"del %s",tmp);
if ( system(cmdstr) != 0 )
printf("error deleting file.(%s)\n",cmdstr);
else return(1);
return(OS_nonportable_renamefile(fname,newfname));
#else
return(rename(fname,newfname));
#endif
@ -112,13 +117,7 @@ int32_t OS_portable_renamefile(char *fname,char *newfname)
int32_t OS_portable_removefile(char *fname)
{
#ifdef _WIN32
char cmdstr[1024],tmp[512];
strcpy(tmp,fname);
OS_portable_path(tmp);
sprintf(cmdstr,"del %s",tmp);
if ( system(cmdstr) != 0 )
printf("error deleting file.(%s)\n",cmdstr);
else return(1);
return(OS_nonportable_removefile(fname));
#else
return(remove(fname));
#endif
@ -131,7 +130,7 @@ int32_t OS_portable_rmdir(char *dirname,int32_t diralso)
strcpy(tmp,dirname);
OS_portable_path(tmp);
#ifdef _WIN32
sprintf(cmdstr,"del %s\*.*",tmp);
sprintf(cmdstr,"rmdir %s",tmp);
if ( system(cmdstr) != 0 )
printf("error deleting dir.(%s)\n",cmdstr);
else return(1);
@ -169,7 +168,7 @@ void *OS_portable_mapfile(char *fname,long *filesizep,int32_t enablewrite)
return(OS_nonportable_mapfile(fname,filesizep,enablewrite));
#else
int32_t fd,rwflags,flags = MAP_FILE|MAP_SHARED;
uint64_t filesize;
long filesize;
void *ptr = 0;
*filesizep = 0;
if ( enablewrite != 0 )
@ -181,7 +180,7 @@ void *OS_portable_mapfile(char *fname,long *filesizep,int32_t enablewrite)
return(0);
}
if ( *filesizep == 0 )
filesize = (uint64_t)lseek(fd,0,SEEK_END);
filesize = (long)lseek(fd,0,SEEK_END);
else filesize = *filesizep;
rwflags = PROT_READ;
if ( enablewrite != 0 )
@ -250,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 )

110
crypto777/OS_portable.h

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -17,11 +17,21 @@
// iguana_OS has functions that invoke system calls. Whenever possible stdio and similar functions are use and most functions are fully portable and in this file. For things that require OS specific, the call is routed to iguana_OS_portable_* Usually, all but one OS can be handled with the same code, so iguana_OS_portable.c has most of this shared logic and an #ifdef iguana_OS_nonportable.c
#ifdef __APPLE__
//#define LIQUIDITY_PROVIDER 1
#endif
#ifdef NATIVE_WINDOWS
//#define uint64_t unsigned __int64
#define PACKED
#else
#define PACKED __attribute__((packed))
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define HAVE_STRUCT_TIMESPEC
#include <unistd.h>
#include <ctype.h>
#include <fcntl.h>
#include <math.h>
@ -30,28 +40,30 @@
#include <sys/types.h>
#include <time.h>
#ifdef __MINGW
#ifdef _WIN32
#define sleep(x) Sleep(1000*(x))
#include "../OSlibs/win/mingw.h"
#include "../OSlibs/win/mman.h"
#define PTW32_STATIC_LIB
#include "../OSlibs/win/pthread.h"
#ifndef NATIVE_WINDOWS
#define EADDRINUSE WSAEADDRINUSE
#endif
#else
//#include <sys/poll.h>
#include <sys/time.h>
#include <time.h>
#include <poll.h>
#include <netdb.h>
#define HAVE_STRUCT_TIMESPEC
#include <pthread.h>
//#include <netinet/in.h>
//#include "in.h"
#include <sys/mman.h>
#include <sys/socket.h>
//#include <winsock2.h>
#include <unistd.h>
#define closesocket close
#endif
#ifndef MIN
#define MIN(x, y) ( ((x)<(y))?(x):(y) )
#endif
@ -117,10 +129,13 @@ int32_t hseek(HUFF *hp,int32_t offset,int32_t mode);
#define portable_mutex_unlock pthread_mutex_unlock
#define OS_thread_create pthread_create
#define issue_curl(cmdstr) bitcoind_RPC(0,"curl",cmdstr,0,0,0)
#define issue_curl(cmdstr) bitcoind_RPC(0,"curl",cmdstr,0,0,0,0)
#define issue_curlt(cmdstr,timeout) bitcoind_RPC(0,"curl",cmdstr,0,0,0,timeout)
struct allocitem { uint32_t allocsize,type; } PACKED;
struct queueitem { struct queueitem *next,*prev; uint32_t allocsize,type; } PACKED;
struct stritem { struct queueitem DL; void **retptrp; uint32_t expiration; char str[]; };
struct allocitem { uint32_t allocsize,type; } __attribute__((packed));
struct queueitem { struct queueitem *next,*prev; uint32_t allocsize,type; } __attribute__((packed));
typedef struct queue
{
struct queueitem *list;
@ -128,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];
@ -183,6 +207,8 @@ int32_t OS_nonportable_init();
void OS_portable_init();
void OS_init();
int32_t sortds(double *buf,uint32_t num,int32_t size);
int32_t revsortds(double *buf,uint32_t num,int32_t size);
double OS_portable_milliseconds();
void OS_portable_randombytes(uint8_t *x,long xlen);
@ -192,8 +218,8 @@ void OS_remove_directory(char *dirname);
int32_t OS_portable_renamefile(char *fname,char *newfname);
int32_t OS_portable_removefile(char *fname);
void *OS_portable_mapfile(char *fname,long *filesizep,int32_t enablewrite);
int32_t OS_portable_syncmap(struct OS_mappedptr *mp,long len);
void *OS_portable_tmpalloc(char *dirname,char *name,struct OS_memspace *mem,long origsize);
//int32_t OS_portable_syncmap(struct OS_mappedptr *mp,long len);
//void *OS_portable_tmpalloc(char *dirname,char *name,struct OS_memspace *mem,long origsize);
int32_t is_DST(int32_t datenum);
int32_t extract_datenum(int32_t *yearp,int32_t *monthp,int32_t *dayp,int32_t datenum);
@ -203,47 +229,54 @@ int32_t ecb_decrdate(int32_t *yearp,int32_t *monthp,int32_t *dayp,char *date,int
int32_t conv_date(int32_t *secondsp,char *buf);
uint32_t OS_conv_datenum(int32_t datenum,int32_t hour,int32_t minute,int32_t second);
int32_t OS_conv_unixtime(struct tai *t,int32_t *secondsp,time_t timestamp);
double OS_milliseconds();
void OS_randombytes(uint8_t *x,long xlen);
int32_t OS_truncate(char *fname,long filesize);
char *OS_compatible_path(char *str);
int32_t OS_renamefile(char *fname,char *newfname);
int32_t OS_removefile(char *fname,int32_t scrubflag);
void OS_ensure_directory(char *dirname);
int64_t OS_filesize(char *fname);
FILE *OS_appendfile(char *origfname);
int32_t OS_compare_files(char *fname,char *fname2);
int64_t OS_copyfile(char *src,char *dest,int32_t cmpflag);
int32_t OS_releasemap(void *ptr,uint64_t filesize);
void _OS_closemap(struct OS_mappedptr *mp);
void *OS_loadfile(char *fname,char **bufp,long *lenp,long *allocsizep);
void *OS_filestr(long *allocsizep,char *fname);
void OS_closemap(struct OS_mappedptr *mp);
long OS_ensurefilesize(char *fname,long filesize,int32_t truncateflag);
int32_t OS_openmap(struct OS_mappedptr *mp);
void *OS_mappedptr(void **ptrp,struct OS_mappedptr *mp,uint64_t allocsize,int32_t rwflag,char *fname);
void *OS_mappedptr(void **ptrp,struct OS_mappedptr *mp,unsigned long allocsize,int32_t rwflag,char *fname);
void *OS_filealloc(struct OS_mappedptr *M,char *fname,struct OS_memspace *mem,long size);
void *OS_nonportable_mapfile(char *fname,long *filesizep,int32_t enablewrite);
int32_t OS_nonportable_removefile(char *fname);
unsigned long OS_filesize(char *fname);
void OS_ensure_directory(char *dirname);
long OS_ensurefilesize(char *fname,long filesize,int32_t truncateflag);
int32_t OS_truncate(char *fname,long filesize);
int32_t OS_renamefile(char *fname,char *newfname);
int32_t OS_removefile(char *fname,int32_t scrubflag);
void *OS_mapfile(char *fname,long *filesizep,int32_t enablewrite);
void *OS_loadfile(char *fname,char **bufp,long *lenp,long *allocsizep);
void *OS_filestr(long *allocsizep,char *fname);
int32_t OS_releasemap(void *ptr,unsigned long filesize);
int32_t OS_syncmap(struct OS_mappedptr *mp,long len);
void *OS_tmpalloc(char *dirname,char *name,struct OS_memspace *mem,long origsize);
double OS_milliseconds();
void OS_randombytes(uint8_t *x,long xlen);
//int32_t OS_syncmap(struct OS_mappedptr *mp,long len);
//void *OS_tmpalloc(char *dirname,char *name,struct OS_memspace *mem,long origsize);
long myallocated(uint8_t type,long change);
void *mycalloc(uint8_t type,int32_t n,long itemsize);
void myfree(void *_ptr,long allocsize);
void free_queueitem(void *itemdata);
//void free_queueitem(void *itemdata);
void *myrealloc(uint8_t type,void *oldptr,long oldsize,long newsize);
void *myaligned_alloc(uint64_t allocsize);
int32_t myaligned_free(void *ptr,long size);
void *queueitem(char *str);
void queue_enqueue(char *name,queue_t *queue,struct queueitem *origitem,int32_t offsetflag);
void *queue_dequeue(queue_t *queue,int32_t offsetflag);
struct queueitem *queueitem(char *str);
void queue_enqueue(char *name,queue_t *queue,struct queueitem *origitem);//,int32_t offsetflag);
void *queue_dequeue(queue_t *queue);//,int32_t offsetflag);
void *queue_delete(queue_t *queue,struct queueitem *copy,int32_t copysize,int32_t freeitem);
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);
@ -293,6 +326,7 @@ int32_t btc_convaddr(char *hexaddr,char *addr58);
uint64_t RS_decode(char *rs);
int32_t RS_encode(char *rsaddr,uint64_t id);
char *cmc_ticker(char *base);
void calc_sha1(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_md2(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
@ -327,7 +361,7 @@ char *hmac_tiger_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_whirlpool_str(char *dest,char *key,int32_t key_size,char *message);
int nn_base64_encode(const uint8_t *in,size_t in_len,char *out,size_t out_len);
int nn_base64_decode(const char *in,size_t in_len,uint8_t *out,size_t out_len);
void calc_rmd160_sha256(uint8_t rmd160[20],uint8_t *data,int32_t datalen);
void sha256_sha256(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void rmd160ofsha256(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_md5str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
@ -338,6 +372,8 @@ void calc_base64_encodestr(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_base64_decodestr(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_hexstr(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_unhexstr(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
int32_t safecopy(char *dest,char *src,long len);
double dxblend(double *destp,double val,double decay);
uint64_t calc_ipbits(char *ip_port);
void expand_ipbits(char *ipaddr,uint64_t ipbits);
@ -345,9 +381,13 @@ void escape_code(char *escaped,char *str);
void SaM_PrepareIndices();
// iguana_serdes.c
#define IGUANA_LOG2PACKETSIZE 21
#ifndef IGUANA_LOG2PACKETSIZE
#define IGUANA_LOG2PACKETSIZE 22
#endif
#ifndef IGUANA_MAXPACKETSIZE
#define IGUANA_MAXPACKETSIZE (1 << IGUANA_LOG2PACKETSIZE)
struct iguana_msghdr { uint8_t netmagic[4]; char command[12]; uint8_t serdatalen[4],hash[4]; } __attribute__((packed));
#endif
struct iguana_msghdr { uint8_t netmagic[4]; char command[12]; uint8_t serdatalen[4],hash[4]; } PACKED;
int32_t iguana_rwnum(int32_t rwflag,uint8_t *serialized,int32_t len,void *endianedp);
int32_t iguana_validatehdr(char *symbol,struct iguana_msghdr *H);
@ -360,6 +400,7 @@ int32_t iguana_rwvarint(int32_t rwflag,uint8_t *serialized,uint64_t *varint64p);
int32_t iguana_rwvarint32(int32_t rwflag,uint8_t *serialized,uint32_t *int32p);
int32_t iguana_rwvarstr(int32_t rwflag,uint8_t *serialized,int32_t maxlen,char *endianedp);
int32_t iguana_rwmem(int32_t rwflag,uint8_t *serialized,int32_t len,void *endianedp);
#define bits256_nonz(a) (((a).ulongs[0] | (a).ulongs[1] | (a).ulongs[2] | (a).ulongs[3]) != 0)
bits256 bits256_ave(bits256 a,bits256 b);
bits256 bits256_doublesha256(char *hashstr,uint8_t *data,int32_t datalen);
@ -380,6 +421,7 @@ int32_t revsort32(uint32_t *buf,uint32_t num,int32_t size);
bits256 bits256_sha256(bits256 data);
void bits256_rmd160(uint8_t rmd160[20],bits256 data);
void bits256_rmd160_sha256(uint8_t rmd160[20],bits256 data);
double get_theoretical(double *avebidp,double *aveaskp,double *highbidp,double *lowaskp,double *CMC_averagep,double changes[3],char *name,char *base,char *rel,double *USD_averagep);
extern char *Iguana_validcommands[];
extern bits256 GENESIS_PUBKEY,GENESIS_PRIVKEY;

33
crypto777/OS_time.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -21,7 +21,7 @@
#define TAI_PACK 8
#define TAI_UTC_DIFF ((uint64_t)4611686018427387914ULL)
//#define UTC_ADJUST -36
//#define UTC_ADJUST -37
#define tai_approx(t) ((double) ((t)->x))
#define tai_less(t,u) ((t)->x < (u)->x)
@ -56,7 +56,7 @@ struct tm *gmtime_r(const time_t *timep,struct tm *result)
/*typedef struct timeval {
long tv_sec;
long tv_usec;
} timeval;
} timeval;*/
int gettimeofday(struct timeval * tp, struct timezone * tzp)
{
@ -75,7 +75,7 @@ int gettimeofday(struct timeval * tp, struct timezone * tzp)
tp->tv_sec = (long) ((time - EPOCH) / 10000000L);
tp->tv_usec = (long) (system_time.wMilliseconds * 1000);
return 0;
}*/
}
#endif
double OS_portable_milliseconds()
@ -300,7 +300,7 @@ void tai_add(struct tai *t,struct tai *u,struct tai *v) { t->x = u->x + v->x; }
void tai_sub(struct tai *t,struct tai *u,struct tai *v) { t->x = u->x - v->x; }
// {"leapseconds":["+1972-06-30", "+1972-12-31", "+1973-12-31", "+1974-12-31", "+1975-12-31", "+1976-12-31", "+1977-12-31", "+1982-06-30", "+1983-06-30", "+1985-06-30", "+1987-12-31", "+1989-12-31", "+1990-12-31", "+1992-06-30", "+1993-06-30", "+1994-06-30", "+1995-12-31", "+1997-06-30", "+1998-12-31", "+2005-12-31", "+2008-12-31", "+2012-06-30", "+2015-06-30"]}
char *leapseconds[] = { "+1972-06-30", "+1972-12-31", "+1973-12-31", "+1974-12-31", "+1975-12-31", "+1976-12-31", "+1977-12-31", "+1982-06-30", "+1983-06-30", "+1985-06-30", "+1987-12-31", "+1989-12-31", "+1990-12-31", "+1992-06-30", "+1993-06-30", "+1994-06-30", "+1995-12-31", "+1997-06-30", "+1998-12-31", "+2005-12-31", "+2008-12-31", "+2012-06-30", "+2015-06-30" };
char *leapseconds[] = { "+1972-06-30", "+1972-12-31", "+1973-12-31", "+1974-12-31", "+1975-12-31", "+1976-12-31", "+1977-12-31", "+1982-06-30", "+1983-06-30", "+1985-06-30", "+1987-12-31", "+1989-12-31", "+1990-12-31", "+1992-06-30", "+1993-06-30", "+1994-06-30", "+1995-12-31", "+1997-06-30", "+1998-12-31", "+2005-12-31", "+2008-12-31", "+2012-06-30", "+2015-06-30", "+2016-12-31" };
struct tai leaptais[sizeof(leapseconds)/sizeof(*leapseconds)];
char *dayname[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" } ;
@ -355,9 +355,9 @@ struct tai tai_now()
{
First_TAI = t, First_utc = (uint32_t)now;
#ifndef DISABLE_LEAPS
UTC_ADJUST = -36;
UTC_ADJUST = -37;
#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);
}
@ -536,7 +536,7 @@ uint32_t OS_conv_datenum(int32_t datenum,int32_t hour,int32_t minute,int32_t sec
}
return(0);
}
else
/*else
{
#ifdef __PNACL
return(0);
@ -547,12 +547,12 @@ uint32_t OS_conv_datenum(int32_t datenum,int32_t hour,int32_t minute,int32_t sec
t.tm_hour = hour, t.tm_min = minute, t.tm_sec = second;
return((uint32_t)timegm(&t));
#endif
}
}*/
}
int32_t OS_conv_unixtime(struct tai *tp,int32_t *secondsp,time_t timestamp) // gmtime -> datenum + number of seconds
{
struct tm tm,*ptr; int32_t datenum; uint32_t checktime; char buf[64]; struct tai t; struct taitime ct;
struct tai t; struct taitime ct;
if ( 1 )
{
*tp = t = utc2tai((uint32_t)timestamp);
@ -560,8 +560,9 @@ int32_t OS_conv_unixtime(struct tai *tp,int32_t *secondsp,time_t timestamp) // g
*secondsp = (ct.hour*3600 + ct.minute*60 + ct.second);
return(calc_datenum(ct.date.year,ct.date.month,ct.date.day));
}
else
/*else
{
struct tm tm,*ptr; int32_t datenum; uint32_t checktime; char buf[64];
if ( (ptr= gmtime(&timestamp)) != 0 )
tm = *ptr;;
strftime(buf,sizeof(buf), "%Y-%m-%dT%H:%M:%SZ",&tm); //printf("%s\n",buf);
@ -572,13 +573,13 @@ int32_t OS_conv_unixtime(struct tai *tp,int32_t *secondsp,time_t timestamp) // g
return(-1);
}
return(datenum);
}
}*/
}
int32_t conv_date(int32_t *secondsp,char *date)
{
char origdate[64],tmpdate[64]; int32_t year,month,day,hour,min,sec,len;
strcpy(origdate,date), strcpy(tmpdate,date), tmpdate[8 + 2] = 0;
char origdate[512],tmpdate[512]; int32_t year,month,day,hour,min,sec,len;
safecopy(origdate,date,sizeof(origdate)), safecopy(tmpdate,date,sizeof(tmpdate)), tmpdate[8 + 2] = 0;
year = atoi(tmpdate), month = atoi(tmpdate+5), day = atoi(tmpdate+8);
*secondsp = 0;
if ( (len= (int32_t)strlen(date)) <= 10 )
@ -590,8 +591,8 @@ int32_t conv_date(int32_t *secondsp,char *date)
if ( hour >= 0 && hour < 24 && min >= 0 && min < 60 && sec >= 0 && sec < 60 )
*secondsp = (3600*hour + 60*min + sec);
else printf("ERROR: seconds.%d %d %d %d, len.%d\n",*secondsp,hour,min,sec,len);
}
//printf("(%s) -> Y.%d M.%d D.%d %d:%d:%d\n",date,year,month,day,hour,min,sec);
//printf("(%s) -> Y.%d M.%d D.%d %d:%d:%d\n",date,year,month,day,hour,min,sec);
} //else printf("short len.(%s) from (%s)\n",date,origdate);
sprintf(origdate,"%d-%02d-%02d",year,month,day); //2015-07-25T22:34:31Z
if ( strcmp(tmpdate,origdate) != 0 )
{

7
crypto777/SaM.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -46,7 +46,7 @@ struct SaM_info { bits384 bits; TRIT trits[SAM_STATE_SIZE],hash[SAM_HASH_SIZE];
struct SaMhdr { bits384 sig; uint32_t timestamp,nonce; uint8_t numrounds,leverage; };
void SaM_Initialize(struct SaM_info *state);
int32_t SaM_Absorb(struct SaM_info *state,const uint8_t *input,const uint32_t inputSize,const uint8_t *input2,const uint32_t inputSize2);
int32_t SaM_Absorb(struct SaM_info *state,const uint8_t *input,uint32_t inputSize,const uint8_t *input2,uint32_t inputSize2);
bits384 SaM_emit(struct SaM_info *state);
bits384 SaM_encrypt(uint8_t *dest,uint8_t *src,int32_t len,bits384 password,uint32_t timestamp);
uint64_t SaM_threshold(int32_t leverage);
@ -285,7 +285,7 @@ int32_t SaM_test()
memset(histo,0,sizeof(histo));
for (i=0; i<5; i++)
{
if ( 0 && (i % 100) == 99 )
if ( (0) && (i % 100) == 99 )
{
for (j=0; j<32; j++)
seed.bytes[j] = rand() >> 8;
@ -340,6 +340,7 @@ bits384 SaM_encrypt(uint8_t *dest,uint8_t *src,int32_t len,bits384 password,uint
{
bits384 xorpad; int32_t i; struct SaM_info XORpad;
SaM_Initialize(&XORpad), SaM_Absorb(&XORpad,password.bytes,sizeof(password),(void *)&timestamp,sizeof(timestamp));
memset(xorpad.bytes,0,sizeof(xorpad));
while ( len >= 0 )
{
SaM_emit(&XORpad);

157
crypto777/bitcoind_RPC.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -13,20 +13,28 @@
* *
******************************************************************************/
#include "OS_portable.h"
#ifdef __APPLE__
#ifndef FROM_JS
#include "OS_portable.h"
#define LIQUIDITY_PROVIDER 1
#endif
/*#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);*/
int32_t bitcoind_RPC_inittime;
#if LIQUIDITY_PROVIDER
#ifdef _WIN32
#include <curl.h>
#include <easy.h>
#else
#include <curl/curl.h>
#include <curl/easy.h>
#endif
// return data from the server
#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32)
@ -38,8 +46,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);
/************************************************************************
@ -62,16 +73,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(500);
#endif
//printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC.%s.[%s]\n",debugstr,command,rpcstr);
if ( command == 0 || rpcstr == 0 || rpcstr[0] == 0 )
{
printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC.%s.[%s]\n",debugstr,command,rpcstr);
if ( strcmp(command,"signrawtransaction") != 0 && strcmp(command,"getrawtransaction") != 0 )
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);
}
@ -81,7 +96,8 @@ 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);
//printf("%s %s rpc retstr.%p\n",command,params,retstr);
len = strlen(retstr);
if ( retstr[0] == '"' && retstr[len-1] == '"' )
{
@ -91,8 +107,17 @@ char *post_process_bitcoind_RPC(char *debugstr,char *command,char *rpcstr,char *
}
}
else if ( (error->type&0xff) != cJSON_NULL || (result->type&0xff) != cJSON_NULL )
printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC (%s) error.%s\n",debugstr,command,rpcstr);
free(rpcstr);
{
if ( strcmp(command,"getrawtransaction") != 0 && strcmp(command,"signrawtransaction") != 0 && strcmp(command,"sendrawtransaction") != 0 )
printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC (%s) error.%s\n",debugstr,command,rpcstr);
retstr = rpcstr;
rpcstr = 0;
}
if ( rpcstr != 0 )
{
//printf("free rpcstr.%p\n",rpcstr);
free(rpcstr);
}
} else retstr = rpcstr;
free_json(json);
//fprintf(stderr,"<<<<<<<<<<< bitcoind_RPC: postprocess returns.(%s)\n",retstr);
@ -106,6 +131,8 @@ char *post_process_bitcoind_RPC(char *debugstr,char *command,char *rpcstr,char *
*
************************************************************************/
static int32_t USE_JAY;
char *Jay_NXTrequest(char *command,char *params)
{
char *retstr = 0;
@ -114,17 +141,18 @@ char *Jay_NXTrequest(char *command,char *params)
return(retstr);
}
char *bitcoind_RPC(char **retstrp,char *debugstr,char *url,char *userpass,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;
curl_global_init(CURL_GLOBAL_ALL); //init the curl session
}
if ( USE_JAY != 0 && (strncmp(url,"http://127.0.0.1:7876/nxt",strlen("http://127.0.0.1:7876/nxt")) == 0 || strncmp(url,"https://127.0.0.1:7876/nxt",strlen("https://127.0.0.1:7876/nxt")) == 0) )
if ( (0) && (USE_JAY != 0 && (strncmp(url,"http://127.0.0.1:7876/nxt",strlen("http://127.0.0.1:7876/nxt")) == 0 || strncmp(url,"https://127.0.0.1:7876/nxt",strlen("https://127.0.0.1:7876/nxt")) == 0)) )
{
if ( (databuf= Jay_NXTrequest(command,params)) != 0 )
return(databuf);
@ -134,24 +162,45 @@ char *bitcoind_RPC(char **retstrp,char *debugstr,char *url,char *userpass,char *
specialcase = 1;
else specialcase = 0;
if ( url[0] == 0 )
strcpy(url,"http://127.0.0.1:7876/nxt");
if ( specialcase != 0 && 0 )
printf("<<<<<<<<<<< bitcoind_RPC: debug.(%s) url.(%s) command.(%s) params.(%s)\n",debugstr,url,command,params);
strcpy(url,"http://127.0.0.1:7776");
if ( specialcase != 0 && (0) )
printf("<<<<<<<<<<< bitcoind_RPC: userpass.(%s) url.(%s) command.(%s) params.(%s)\n",userpass,url,command,params);
try_again:
if ( retstrp != 0 )
*retstrp = 0;
starttime = OS_milliseconds();
curl_handle = curl_easy_init();
init_string(&s);
headers = curl_slist_append(0,"Expect:");
curl_easy_setopt(curl_handle,CURLOPT_USERAGENT,"mozilla/4.0");//"Mozilla/4.0 (compatible; )");
curl_easy_setopt(curl_handle,CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl_handle,CURLOPT_URL, url);
curl_easy_setopt(curl_handle,CURLOPT_WRITEFUNCTION, (void *)accumulate); // send all data to this function
curl_easy_setopt(curl_handle,CURLOPT_WRITEDATA, &s); // we pass our 's' struct to the callback
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 )
{
if ( bitcoind_RPC_inittime != 0 )
{
#ifndef _WIN32
curl_easy_setopt(curl_handle,CURLOPT_TIMEOUT,1);
#else
curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT_MS, timeout*100);
#endif
} else curl_easy_setopt(curl_handle,CURLOPT_TIMEOUT,timeout); // causes problems with iguana timeouts
}
if ( strncmp(url,"https",5) == 0 )
{
curl_easy_setopt(curl_handle,CURLOPT_SSL_VERIFYPEER,0);
@ -173,9 +222,12 @@ try_again:
bracket0 = (char *)"[";
bracket1 = (char *)"]";
}
char agentstr[64];
databuf = (char *)malloc(256 + strlen(command) + strlen(params));
sprintf(databuf,"{\"id\":\"jl777\",\"method\":\"%s\",\"params\":%s%s%s}",command,bracket0,params,bracket1);
if ( debugstr[0] != 0 )
sprintf(agentstr,"\"agent\":\"%s\",",debugstr);
else agentstr[0] = 0;
sprintf(databuf,"{\"id\":\"jl777\",%s\"method\":\"%s\",\"params\":%s%s%s}",agentstr,command,bracket0,params,bracket1);
//printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf);
//
} //else if ( specialcase != 0 ) fprintf(stderr,"databuf.(%s)\n",params);
@ -193,23 +245,24 @@ try_again:
free(databuf);
databuf = 0;
}
retstr = chunk.memory; // retstr = s.ptr;
if ( res != CURLE_OK )
{
numretries++;
if ( specialcase != 0 )
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);
//printf("<<<<<<<<<<< bitcoind_RPC.(%s): BTCD.%s timeout params.(%s) s.ptr.(%s) err.%d\n",url,command,params,retstr,res);
free(retstr);
return(0);
}
else if ( numretries >= 5 )
else if ( numretries >= 4 )
{
printf("Maximum number of retries exceeded!\n");
free(s.ptr);
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(retstr);
return(0);
}
printf( "curl_easy_perform() failed: %s %s.(%s %s), retries: %d\n",curl_easy_strerror(res),debugstr,url,command,numretries);
free(s.ptr);
free(retstr);
sleep((1<<numretries));
goto try_again;
@ -220,29 +273,27 @@ try_again:
{
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));
//printf("%s <- %s\n",url,command);
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);
if ( (0) && specialcase != 0 )
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");
free(s.ptr);
return(0);
}
/************************************************************************
@ -284,13 +335,24 @@ 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);
//printf("mem->memory.%p len.%d\n",mem->memory,(int32_t)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 )
@ -365,3 +427,4 @@ void *curl_post(void **cHandlep,char *url,char *userpass,char *postfields,char *
return(clonestr("{\"error\":\"curl is disabled\"}"));
}
#endif
#endif

156
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;
}
@ -76,14 +111,14 @@ void cJSON_InitHooks(cJSON_Hooks* hooks)
return;
}
cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc;
cJSON_free = (hooks->free_fn)?hooks->free_fn:free;
cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc;
cJSON_free = (hooks->free_fn)?hooks->free_fn:free;
}
/* Internal constructor. */
static cJSON *cJSON_New_Item(void)
{
cJSON* node = (cJSON*)cJSON_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;
@ -546,7 +583,7 @@ static char *print_object(cJSON *item,int32_t depth,int32_t fmt)
/* Get Array size/item / object item. */
int32_t cJSON_GetArraySize(cJSON *array) {cJSON *c; if ( array == 0 ) return(0); c=array->child;int32_t i=0;while(c)i++,c=c->next;return i;}
cJSON *cJSON_GetArrayItem(cJSON *array,int32_t item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;}
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;}
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) { if ( object == 0 ) return(0); cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;}
/* Utility for array list handling. */
static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;}
@ -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;}
@ -634,7 +669,7 @@ void cJSON_Minify(char *json)
// the following written by jl777
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -837,7 +872,7 @@ char *jprint(cJSON *json,int32_t freeflag)
initflag = 1;
}*/
if ( json == 0 )
return(clonestr("{}"));
return(clonestr((char *)"{}"));
//portable_mutex_lock(&mutex);
//usleep(5000);
str = cJSON_Print(json), _stripwhite(str,' ');
@ -858,7 +893,7 @@ bits256 get_API_bits256(cJSON *obj)
}
return(hash);
}
bits256 jbits256(cJSON *json,char *field) { if ( field == 0 ) return(get_API_bits256(json)); return(get_API_bits256(cJSON_GetObjectItem(json,field))); }
bits256 jbits256(cJSON *json,char *field) { if ( field == 0 ) return(get_API_bits256(json)); return(get_API_bits256(json != 0 ? cJSON_GetObjectItem(json,field) : 0)); }
bits256 jbits256i(cJSON *json,int32_t i) { return(get_API_bits256(cJSON_GetArrayItem(json,i))); }
void jaddbits256(cJSON *json,char *field,bits256 hash) { char str[65]; bits256_str(str,hash), jaddstr(json,field,str); }
void jaddibits256(cJSON *json,bits256 hash) { char str[65]; bits256_str(str,hash), jaddistr(json,str); }
@ -896,10 +931,14 @@ int32_t jnum(cJSON *obj,char *field)
void ensure_jsonitem(cJSON *json,char *field,char *value)
{
cJSON *obj = cJSON_GetObjectItem(json,field);
if ( obj == 0 )
cJSON_AddItemToObject(json,field,cJSON_CreateString(value));
else cJSON_ReplaceItemInObject(json,field,cJSON_CreateString(value));
cJSON *obj;
if ( json != 0 )
{
obj = cJSON_GetObjectItem(json,field);
if ( obj == 0 )
cJSON_AddItemToObject(json,field,cJSON_CreateString(value));
else cJSON_ReplaceItemInObject(json,field,cJSON_CreateString(value));
}
}
int32_t in_jsonarray(cJSON *array,char *value)
@ -1092,12 +1131,12 @@ uint64_t calc_nxt64bits(const char *NXTaddr)
c = NXTaddr[i];
if ( c < '0' || c > '9' )
{
printf("calc_nxt64bits: illegal char.(%c %d) in (%s).%d\n",c,c,NXTaddr,(int32_t)i);
//printf("calc_nxt64bits: illegal char.(%c %d) in (%s).%d\n",c,c,NXTaddr,(int32_t)i);
#ifdef __APPLE__
//while ( 1 )
{
//sleep(60);
printf("calc_nxt64bits: illegal char.(%c %d) in (%s).%d\n",c,c,NXTaddr,(int32_t)i);
//printf("calc_nxt64bits: illegal char.(%c %d) in (%s).%d\n",c,c,NXTaddr,(int32_t)i);
}
#endif
return(0);
@ -1125,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)

38
crypto777/curve25519.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -16,11 +16,11 @@
#include "../includes/curve25519.h"
#undef force_inline
#define force_inline __attribute__((always_inline))
//#undef force_inline
//#define force_inline __attribute__((always_inline))
// Sum two numbers: output += in
static inline bits320 force_inline fsum(bits320 output,bits320 in)
static inline bits320 fsum(bits320 output,bits320 in)
{
int32_t i;
for (i=0; i<5; i++)
@ -28,7 +28,7 @@ static inline bits320 force_inline fsum(bits320 output,bits320 in)
return(output);
}
static inline void force_inline fdifference_backwards(uint64_t *out,const uint64_t *in)
static inline void fdifference_backwards(uint64_t *out,const uint64_t *in)
{
static const uint64_t two54m152 = (((uint64_t)1) << 54) - 152; // 152 is 19 << 3
static const uint64_t two54m8 = (((uint64_t)1) << 54) - 8;
@ -38,14 +38,14 @@ static inline void force_inline fdifference_backwards(uint64_t *out,const uint64
out[i] = in[i] + two54m8 - out[i];
}
inline void force_inline store_limb(uint8_t *out,uint64_t in)
void store_limb(uint8_t *out,uint64_t in)
{
int32_t i;
for (i=0; i<8; i++,in>>=8)
out[i] = (in & 0xff);
}
static inline uint64_t force_inline load_limb(uint8_t *in)
static inline uint64_t load_limb(uint8_t *in)
{
return
((uint64_t)in[0]) |
@ -75,7 +75,7 @@ bits320 fexpand(bits256 basepoint)
typedef unsigned uint128_t __attribute__((mode(TI)));
// Multiply a number by a scalar: output = in * scalar
static inline bits320 force_inline fscalar_product(const bits320 in,const uint64_t scalar)
static inline bits320 fscalar_product(const bits320 in,const uint64_t scalar)
{
int32_t i; uint128_t a = 0; bits320 output;
a = ((uint128_t)in.ulongs[0]) * scalar;
@ -119,7 +119,7 @@ bits320 fmul(const bits320 in2,const bits320 in)
return(out);
}
inline bits320 force_inline fsquare_times(const bits320 in,uint64_t count)
bits320 fsquare_times(const bits320 in,uint64_t count)
{
uint128_t t[5]; uint64_t r0,r1,r2,r3,r4,c,d0,d1,d2,d4,d419; bits320 out;
r0 = in.ulongs[0], r1 = in.ulongs[1], r2 = in.ulongs[2], r3 = in.ulongs[3], r4 = in.ulongs[4];
@ -149,7 +149,7 @@ inline bits320 force_inline fsquare_times(const bits320 in,uint64_t count)
return(out);
}
static inline void force_inline fcontract_iter(uint128_t t[5],int32_t flag)
static inline void fcontract_iter(uint128_t t[5],int32_t flag)
{
int32_t i; uint64_t mask = 0x7ffffffffffffLL;
for (i=0; i<4; i++)
@ -711,7 +711,7 @@ bits320 bits320_limbs(limb limbs[10])
return(output);
}
static inline bits320 force_inline fscalar_product(const bits320 in,const uint64_t scalar)
static inline bits320 fscalar_product(const bits320 in,const uint64_t scalar)
{
limb output[10],input[10]; int32_t i;
for (i=0; i<10; i++)
@ -720,7 +720,7 @@ static inline bits320 force_inline fscalar_product(const bits320 in,const uint64
return(bits320_limbs(output));
}
static inline bits320 force_inline fsquare_times(const bits320 in,uint64_t count)
static inline bits320 fsquare_times(const bits320 in,uint64_t count)
{
limb output[10],input[10]; int32_t i;
for (i=0; i<10; i++)
@ -776,7 +776,7 @@ bits256 curve25519(bits256 mysecret,bits256 theirpublic)
// x2 z2: long form && x3 z3: long form
// x z: short form, destroyed && xprime zprime: short form, destroyed
// qmqp: short form, preserved
static inline void force_inline
static inline void
fmonty(bits320 *x2, bits320 *z2, // output 2Q
bits320 *x3, bits320 *z3, // output Q + Q'
bits320 *x, bits320 *z, // input Q
@ -804,7 +804,7 @@ fmonty(bits320 *x2, bits320 *z2, // output 2Q
// long. Perform the swap iff @swap is non-zero.
// This function performs the swap without leaking any side-channel information.
// -----------------------------------------------------------------------------
static inline void force_inline swap_conditional(bits320 *a,bits320 *b,uint64_t iswap)
static inline void swap_conditional(bits320 *a,bits320 *b,uint64_t iswap)
{
int32_t i; const uint64_t swap = -iswap;
for (i=0; i<5; ++i)
@ -846,7 +846,7 @@ void cmult(bits320 *resultx,bits320 *resultz,bits256 secret,const bits320 q)
}
// Shamelessly copied from donna's code that copied djb's code, changed a little
inline bits320 force_inline crecip(const bits320 z)
inline bits320 crecip(const bits320 z)
{
bits320 a,t0,b,c;
/* 2 */ a = fsquare_times(z, 1); // a = 2
@ -1792,7 +1792,7 @@ void acct777_rwsig(int32_t rwflag,uint8_t *serialized,struct acct777_sig *sig)
int32_t acct777_sigcheck(struct acct777_sig *sig)
{
#define IGUANA_GENESIS 1453075200
#define IGUANA_MAXPACKETSIZE (1024 * 1024 * 2)
#define IGUANA_MAXPACKETSIZE (1024 * 1024 * 4)
#define TEN_YEARS (10 * 365 * 24 * 3600)
if ( sig->allocsize < sizeof(*sig) || sig->allocsize > IGUANA_MAXPACKETSIZE )
{
@ -1839,7 +1839,11 @@ uint64_t acct777_validate(struct acct777_sig *sig,bits256 privkey,bits256 pubkey
struct acct777_sig checksig; uint64_t signerbits; int32_t datalen; uint8_t *serialized;
datalen = (int32_t)(sig->allocsize - sizeof(*sig));
checksig = *sig;
#if defined(_M_X64)
serialized = (uint8_t *)((unsigned char *)sig + sizeof(*sig));
#else
serialized = (uint8_t *)((long)sig + sizeof(*sig));
#endif
//{ int32_t i; for (i=0; i<datalen; i++) printf("%02x",serialized[i]); printf(" VALIDATE.%d?\n",datalen); }
acct777_sign(&checksig,privkey,pubkey,sig->timestamp,serialized,datalen);
if ( memcmp(checksig.sigbits.bytes,sig->sigbits.bytes,sizeof(checksig.sigbits)) != 0 )
@ -1888,4 +1892,4 @@ uint8_t *_SuperNET_decipher(uint8_t nonce[crypto_box_NONCEBYTES],uint8_t *cipher
return(0);
}
#undef force_inline
//#undef force_inline

4
crypto777/hmac/sha224.c

@ -26,7 +26,7 @@ const struct ltc_hash_descriptor sha224_desc =
9,
&sha224_init,
&sha256_process,
&sha256i_process,
&sha224_done,
&sha224_test,
NULL
@ -69,7 +69,7 @@ int sha224_done(hash_state * md, unsigned char *out)
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
err = sha256_done(md, buf);
err = sha256i_done(md, buf);
XMEMCPY(out, buf, 28);
#ifdef LTC_CLEAN_STACK
zeromem(buf, sizeof(buf));

86
crypto777/hmac/sha256.c

@ -17,24 +17,6 @@
//#ifdef LTC_SHA256
const struct ltc_hash_descriptor sha256_desc =
{
"sha256",
0,
32,
64,
/* OID */
{ 2, 16, 840, 1, 101, 3, 4, 2, 1, },
9,
&sha256_init,
&sha256_process,
&sha256_done,
&sha256_test,
NULL
};
#ifdef LTC_SMALL_CODE
/* the K array */
static const ulong32 K[64] = {
@ -203,7 +185,7 @@ static int sha256_compress(hash_state * md, unsigned char *buf)
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int sha256_init(hash_state * md)
int sha256i_init(hash_state * md)
{
LTC_ARGCHK(md != NULL);
@ -227,7 +209,7 @@ int sha256_init(hash_state * md)
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
HASH_PROCESS(sha256_process, sha256_compress, sha256, 64)
HASH_PROCESS(sha256i_process, sha256_compress, sha256, 64)
/**
Terminate the hash to get the digest
@ -235,7 +217,7 @@ HASH_PROCESS(sha256_process, sha256_compress, sha256, 64)
@param out [out] The destination of the hash (32 bytes)
@return CRYPT_OK if successful
*/
int sha256_done(hash_state * md, unsigned char *out)
int sha256i_done(hash_state * md, unsigned char *out)
{
int i;
@ -287,9 +269,9 @@ int sha256_done(hash_state * md, unsigned char *out)
void calc_sha256(char hashstr[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t *src,int32_t len)
{
hash_state md;
sha256_init(&md);
sha256_process(&md,src,len);
sha256_done(&md,hash);
sha256i_init(&md);
sha256i_process(&md,src,len);
sha256i_done(&md,hash);
if ( hashstr != 0 )
{
int32_t init_hexbytes_noT(char *hexbytes,uint8_t *message,long len);
@ -300,11 +282,11 @@ void calc_sha256(char hashstr[(256 >> 3) * 2 + 1],uint8_t hash[256 >> 3],uint8_t
void calc_sha256cat(uint8_t hash[256 >> 3],uint8_t *src,int32_t len,uint8_t *src2,int32_t len2)
{
hash_state md;
sha256_init(&md);
sha256_process(&md,src,len);
sha256i_init(&md);
sha256i_process(&md,src,len);
if ( src2 != 0 )
sha256_process(&md,src2,len2);
sha256_done(&md,hash);
sha256i_process(&md,src2,len2);
sha256i_done(&md,hash);
}
void update_sha256(uint8_t hash[256 >> 3],struct sha256_state *state,uint8_t *src,int32_t len)
@ -312,14 +294,14 @@ void update_sha256(uint8_t hash[256 >> 3],struct sha256_state *state,uint8_t *sr
hash_state md;
memset(&md,0,sizeof(md));
if ( src == 0 )
sha256_init(&md);
sha256i_init(&md);
else
{
md.sha256 = *state;
sha256_process(&md,src,len);
sha256i_process(&md,src,len);
}
*state = md.sha256;
sha256_done(&md,hash);
sha256i_done(&md,hash);
}
/*void calc_OP_HASH160(char hexstr[41],uint8_t hash160[20],char *pubkey)
@ -334,9 +316,9 @@ void update_sha256(uint8_t hash[256 >> 3],struct sha256_state *state,uint8_t *sr
return;
}
decode_hex(buf,len,pubkey);
sha256_init(&md);
sha256_process(&md,buf,len);
sha256_done(&md,sha256);
sha256i_init(&md);
sha256i_process(&md,buf,len);
sha256i_done(&md,sha256);
rmd160_init(&md);
rmd160_process(&md,sha256,256 >> 3);
@ -389,9 +371,9 @@ int sha256_test(void)
char *str;
for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
sha256_init(&md);
sha256_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
sha256_done(&md, tmp);
sha256i_init(&md);
sha256i_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
sha256i_done(&md, tmp);
if (XMEMCMP(tmp, tests[i].hash, 32) != 0) {
for (j=0; j<32; j++)
printf("%02x",tmp[j]);
@ -400,16 +382,16 @@ int sha256_test(void)
strcpy(str,(char*)tests[i].msg);
reverse_hexstr(str);
printf("reversed.(%s)\n",str);
sha256_init(&md);
sha256_process(&md, (unsigned char*)str, (unsigned long)strlen(str));
sha256_done(&md, tmp);
sha256i_init(&md);
sha256i_process(&md, (unsigned char*)str, (unsigned long)strlen(str));
sha256i_done(&md, tmp);
for (j=0; j<32; j++)
printf("%02x",tmp[j]);
printf(" <- sha256(%s)\n",str);
decode_hex(buf,(int)strlen(tests[i].msg),tests[i].msg);
sha256_init(&md);
sha256_process(&md, (unsigned char*)buf, (unsigned long)strlen(tests[i].msg)/2);
sha256_done(&md, tmp);
sha256i_init(&md);
sha256i_process(&md, (unsigned char*)buf, (unsigned long)strlen(tests[i].msg)/2);
sha256i_done(&md, tmp);
for (j=0; j<32; j++)
printf("%02x",tmp[j]);
printf(" <- sha256(binary %s)\n",tests[i].msg);
@ -436,6 +418,24 @@ int sha256_test(void)
#undef Maj
const struct ltc_hash_descriptor sha256_desc =
{
"sha256",
0,
32,
64,
/* OID */
{ 2, 16, 840, 1, 101, 3, 4, 2, 1, },
9,
&sha256i_init,
&sha256i_process,
&sha256i_done,
&sha256_test,
NULL
};
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/sha2/sha256.c,v $ */
/* $Revision: 1.11 $ */

8
crypto777/hmac/tomcrypt_hash.h

@ -228,9 +228,9 @@ extern const struct ltc_hash_descriptor sha384_desc;
#endif
#ifdef LTC_SHA256
int sha256_init(hash_state * md);
int sha256_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha256_done(hash_state * md, unsigned char *hash);
int sha256i_init(hash_state * md);
int sha256i_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha256i_done(hash_state * md, unsigned char *hash);
int sha256_test(void);
extern const struct ltc_hash_descriptor sha256_desc;
@ -239,7 +239,7 @@ extern const struct ltc_hash_descriptor sha256_desc;
#error LTC_SHA256 is required for LTC_SHA224
#endif
int sha224_init(hash_state * md);
#define sha224_process sha256_process
#define sha224_process sha256i_process
int sha224_done(hash_state * md, unsigned char *hash);
int sha224_test(void);
extern const struct ltc_hash_descriptor sha224_desc;

26
crypto777/hmac_sha512.c

@ -506,7 +506,7 @@ char *hmac_sha512_str(char *dest,char *key,int32_t key_size,char *message)
hmac_memory(&sha512_desc,(void *)key,key_size,(void *)message,strlen(message),checkbuf,&size);
init_hexbytes_noT(dest,mac,SHA512_DIGEST_SIZE);
init_hexbytes_noT(dest2,checkbuf,SHA512_DIGEST_SIZE);
//if ( memcmp(checkbuf,mac,SHA512_DIGEST_SIZE) != 0 )
if ( memcmp(checkbuf,mac,SHA512_DIGEST_SIZE) != 0 )
printf("hmac_512 : %s vs %s\n",dest,dest2);
return(dest);
}
@ -621,4 +621,28 @@ char *hmac_whirlpool_str(char *dest,char *key,int32_t key_size,char *message)
return(dest);
}
void calc_md2str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
bits128 x;
calc_md2(hexstr,buf,msg,len);
decode_hex(buf,sizeof(x),hexstr);
//memcpy(buf,x.bytes,sizeof(x));
}
void calc_md4str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
bits128 x;
calc_md4(hexstr,buf,msg,len);
decode_hex(buf,sizeof(x),hexstr);
//memcpy(buf,x.bytes,sizeof(x));
}
void calc_md5str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
bits128 x;
calc_md5(hexstr,msg,len);
decode_hex(buf,sizeof(x),hexstr);
//memcpy(buf,x.bytes,sizeof(x));
}

314
crypto777/iguana_OS.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -30,7 +30,7 @@
char *OS_mvstr()
{
#ifdef __WIN32
#ifdef _WIN32
return("rename");
#else
return("mv");
@ -41,7 +41,7 @@ void OS_randombytes(unsigned char *x,long xlen)
{
OS_portable_randombytes(x,xlen);
}
static double _kb(double n) { return(n / 1024.); }
static double _mb(double n) { return(n / (1024.*1024.)); }
static double _gb(double n) { return(n / (1024.*1024.*1024.)); }
@ -94,6 +94,7 @@ long myallocated(uint8_t type,long change)
void *mycalloc(uint8_t type,int32_t n,long itemsize)
{
#ifdef USE_MYCALLOC
//static portable_mutex_t MEMmutex;
struct allocitem *item; int64_t allocsize = ((uint64_t)n * itemsize);
if ( type == 0 && n == 0 && itemsize == 0 )
@ -107,38 +108,47 @@ void *mycalloc(uint8_t type,int32_t n,long itemsize)
while ( (item= calloc(1,sizeof(struct allocitem) + allocsize + 16)) == 0 )
{
char str[65];
printf("mycalloc: need to wait for memory.(%d,%ld) %s to be available\n",n,itemsize,mbstr(str,allocsize));
printf("mycalloc.%c: need to wait for memory.(%d,%ld) %s to be available\n",type,n,itemsize,mbstr(str,allocsize));
sleep(1);
}
//printf("calloc origptr.%p retptr.%p size.%ld\n",item,(void *)(long)item + sizeof(*item),allocsize);
item->allocsize = (uint32_t)allocsize;
item->type = type;
//portable_mutex_unlock(&MEMmutex);
return((void *)(long)item + sizeof(*item));
return((void *)((long)item + sizeof(*item)));
#else
return(calloc(n,itemsize));
#endif
}
void *queueitem(char *str)
struct queueitem *queueitem(char *str)
{
struct queueitem *item; int32_t n,allocsize; char *data; uint8_t type = 'y';
//portable_mutex_lock(&MEMmutex);
n = (uint32_t)strlen(str) + 1;
allocsize = (uint32_t)(sizeof(struct queueitem) + n);
myallocated(type,allocsize);
while ( (item= calloc(1,allocsize)) == 0 )
{
char str[65];
printf("queueitem: need to wait for memory.(%d,%ld) %s to be available\n",n,(long)sizeof(*item),mbstr(str,allocsize));
sleep(1);
}
item->allocsize = (uint32_t)allocsize;
item->type = type;
data = (void *)(long)((long)item + sizeof(*item));
memcpy(data,str,n);
//printf("(%c) queueitem.%p itemdata.%p n.%d allocsize.%d\n",type,item,data,n,allocsize);
//portable_mutex_unlock(&MEMmutex);
return(data);
/*struct queueitem *item; int32_t n,allocsize; char *data; uint8_t type = 'y';
//portable_mutex_lock(&MEMmutex);
n = (uint32_t)strlen(str) + 1;
allocsize = (uint32_t)(sizeof(struct queueitem) + n);
myallocated(type,allocsize);
while ( (item= calloc(1,allocsize)) == 0 )
{
char str[65];
printf("queueitem: need to wait for memory.(%d,%ld) %s to be available\n",n,(long)sizeof(*item),mbstr(str,allocsize));
sleep(1);
}
item->allocsize = (uint32_t)allocsize;
item->type = type;
data = (void *)(long)((long)item + sizeof(*item));
memcpy(data,str,n);
//printf("(%c) queueitem.%p itemdata.%p n.%d allocsize.%d\n",type,item,data,n,allocsize);
//portable_mutex_unlock(&MEMmutex);
return(data);*/
struct stritem *sitem; int32_t len;
len = (int32_t)strlen(str);
sitem = calloc(1,sizeof(*sitem) + len + 16);
memcpy(sitem->str,str,len);
return(&sitem->DL);
}
#ifdef USE_MYCALLOC
void _myfree(uint8_t type,int32_t origallocsize,void *origptr,int32_t allocsize)
{
//portable_mutex_lock(&MEMmutex);
@ -171,12 +181,12 @@ void myfree(void *_ptr,long allocsize)
_myfree(item->type,item->allocsize,item,(uint32_t)allocsize);
}
void free_queueitem(void *itemdata)
{
struct queueitem *item = (void *)((long)itemdata - sizeof(struct queueitem));
//printf("freeq item.%p itemdata.%p size.%d\n",item,itemdata,item->allocsize);
_myfree(item->type,item->allocsize,item,item->allocsize);
}
/*void free_queueitem(void *itemdata)
{
struct queueitem *item = (void *)((long)itemdata - sizeof(struct queueitem));
//printf("freeq item.%p itemdata.%p size.%d\n",item,itemdata,item->allocsize);
_myfree(item->type,item->allocsize,item,item->allocsize);
}*/
void *myrealloc(uint8_t type,void *oldptr,long oldsize,long newsize)
{
@ -190,16 +200,35 @@ void *myrealloc(uint8_t type,void *oldptr,long oldsize,long newsize)
}
return(newptr);
}
#else
void myfree(void *_ptr,long allocsize)
{
free(_ptr);
}
void *myrealloc(uint8_t type,void *oldptr,long oldsize,long newsize)
{
return(realloc(oldptr,newsize));
}
#endif
static uint64_t _align16(uint64_t ptrval) { if ( (ptrval & 15) != 0 ) ptrval += 16 - (ptrval & 15); return(ptrval); }
void *myaligned_alloc(uint64_t allocsize)
{
void *ptr,*realptr; uint64_t tmp;
#if defined(_M_X64)
realptr = mycalloc('A', 1, (uint64_t)(allocsize + 16 + sizeof(realptr)));
#else
realptr = mycalloc('A',1,(long)(allocsize + 16 + sizeof(realptr)));
#endif
tmp = _align16((long)realptr + sizeof(ptr));
memcpy(&ptr,&tmp,sizeof(ptr));
#if defined(_M_X64)
memcpy((void *)((unsigned char *)ptr - sizeof(realptr)), &realptr, sizeof(realptr));
#else
memcpy((void *)((long)ptr - sizeof(realptr)),&realptr,sizeof(realptr));
#endif
//printf("aligned_alloc(%llu) realptr.%p -> ptr.%p, diff.%ld\n",(long long)allocsize,realptr,ptr,((long)ptr - (long)realptr));
return(ptr);
}
@ -235,25 +264,20 @@ void lock_queue(queue_t *queue)
portable_mutex_lock(&queue->mutex);
}
void queue_enqueue(char *name,queue_t *queue,struct queueitem *origitem,int32_t offsetflag)
void queue_enqueue(char *name,queue_t *queue,struct queueitem *item)//,int32_t offsetflag)
{
struct queueitem *item;
//struct queueitem *item;
if ( queue->name[0] == 0 && name != 0 && name[0] != 0 )
strcpy(queue->name,name);//,sizeof(queue->name));
if ( origitem == 0 )
{
printf("FATAL type error: queueing empty value\n");//, getchar();
return;
}
//fprintf(stderr,"enqueue.(%s) %p offset.%d\n",queue->name,origitem,offsetflag);
//fprintf(stderr,"enqueue.(%s) %p\n",queue->name,item);
lock_queue(queue);
item = (struct queueitem *)((long)origitem - offsetflag*sizeof(struct queueitem));
//item = (struct queueitem *)((long)origitem - offsetflag*sizeof(struct queueitem));
DL_APPEND(queue->list,item);
portable_mutex_unlock(&queue->mutex);
//printf("queue_enqueue name.(%s) origitem.%p append.%p list.%p\n",name,origitem,item,queue->list);
}
void *queue_dequeue(queue_t *queue,int32_t offsetflag)
void *queue_dequeue(queue_t *queue)//,int32_t offsetflag)
{
struct queueitem *item = 0;
lock_queue(queue);
@ -264,19 +288,20 @@ void *queue_dequeue(queue_t *queue,int32_t offsetflag)
DL_DELETE(queue->list,item);
}
portable_mutex_unlock(&queue->mutex);
if ( item != 0 && offsetflag != 0 )
return((void *)((long)item + sizeof(struct queueitem)));
else return(item);
//if ( item != 0 && offsetflag != 0 )
// return((void *)((long)item + sizeof(struct queueitem)));
//else
return(item);
}
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) )
@ -284,8 +309,8 @@ void *queue_delete(queue_t *queue,struct queueitem *copy,int32_t copysize,int32_
DL_DELETE(queue->list,item);
portable_mutex_unlock(&queue->mutex);
//printf("name.(%s) deleted item.%p list.%p\n",queue->name,item,queue->list);
if ( freeitem != 0 )
myfree(item,copysize);
//if ( freeitem != 0 )
// myfree(item,copysize);
return(item);
}
}
@ -296,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));
@ -313,15 +338,15 @@ 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);
queue_enqueue(queue->name,clone,ptr,0);
queue_enqueue(queue->name,clone,ptr);
}
//printf("name.(%s) dequeue.%p list.%p\n",queue->name,item,queue->list);
}
@ -354,8 +379,11 @@ void iguana_memreset(struct OS_memspace *mem)
void iguana_mempurge(struct OS_memspace *mem)
{
if ( mem->allocated > 0 && mem->ptr != 0 && mem->totalsize > 0 )
if ( mem->allocated != 0 && mem->ptr != 0 )//&& mem->totalsize > 0 )
{
//printf("mempurge.(%s) %ld\n",mem->name,(long)mem->totalsize);
myfree(mem->ptr,mem->totalsize), mem->ptr = 0;
}
iguana_memreset(mem);
mem->totalsize = 0;
}
@ -375,7 +403,7 @@ void *iguana_meminit(struct OS_memspace *mem,char *name,void *ptr,int64_t totals
{
//static long alloc;
//alloc += totalsize;
//char str[65]; printf("iguana_meminit alloc %s\n",mbstr(str,alloc));
//char str[65]; printf("iguana_meminit.(%s) alloc %s\n",name,mbstr(str,totalsize));
if ( (mem->ptr= mycalloc('d',1,totalsize)) == 0 )
{
printf("iguana_meminit: cant get %d bytes\n",(int32_t)totalsize);
@ -394,6 +422,7 @@ void *iguana_meminit(struct OS_memspace *mem,char *name,void *ptr,int64_t totals
mem->totalsize = totalsize;
}
mem->threadsafe = threadsafe;
mem->alignflag = 4;
iguana_memreset(mem);
if ( mem->totalsize == 0 )
printf("meminit.%s ILLEGAL STATE null size\n",mem->name), getchar();
@ -426,7 +455,16 @@ void *iguana_memalloc(struct OS_memspace *mem,long size,int32_t clearflag)
#endif
if ( (mem->used + size) <= mem->totalsize )
{
ptr = (void *)(long)((long)(mem->ptr + mem->used));
/*
* solution to calculate memory address in a portable way
* in all platform sizeof(char) / sizeof(uchar) == 1
* @author - fadedreamz@gmail.com
*/
#if defined(_M_X64)
ptr = (void *)((unsigned char *)mem->ptr + mem->used);
#else
ptr = (void *)(long)(((long)mem->ptr + mem->used));
#endif
mem->used += size;
if ( size*clearflag != 0 )
memset(ptr,0,size);
@ -536,10 +574,12 @@ void OS_remove_directory(char *dirname)
FILE *fp; char buf[1024];
sprintf(buf,"%s/.tmpmarker",dirname);
if ( (fp= fopen(OS_compatible_path(buf),"rb")) != 0 )
{
OS_removefile(buf,0);
else fclose(fp);
//printf("skip rmdir.(%s)\n",dirname);
return;
fclose(fp);
}
//printf("skip rmdir.(%s)\n",dirname);
return;
sprintf(buf,"rmdir %s",dirname);
if ( system(buf) != 0 )
{
@ -549,16 +589,13 @@ return;
{
//printf("error doing (%s)\n",buf);
}
//sprintf(buf,"rmdir %s",dirname);
//if ( system(buf) != 0 )
// printf("second error doing (%s)\n",buf);
}
}
void OS_ensure_directory(char *dirname)
{
FILE *fp; int32_t retval; char fname[512];
if ( 0 && OS_removefile(dirname,0) < 0 )
if ( (0) && OS_removefile(dirname,0) < 0 )
{
sprintf(fname,"tmp/%d",rand());
OS_renamefile(dirname,fname);
@ -581,9 +618,9 @@ void OS_ensure_directory(char *dirname)
} else fclose(fp);//, printf("%s exists\n",fname);
}
int64_t OS_filesize(char *fname)
unsigned long OS_filesize(char *fname)
{
FILE *fp; uint64_t fsize = 0;
FILE *fp; unsigned long fsize = 0;
if ( (fp= fopen(fname,"rb")) != 0 )
{
fseek(fp,0,SEEK_END);
@ -622,7 +659,11 @@ int64_t OS_copyfile(char *src,char *dest,int32_t cmpflag)
{
if ( (destfp= fopen(OS_compatible_path(dest),"wb")) != 0 )
{
#ifdef _WIN32
allocsize = 1024 * 1024 * 8L;
#else
allocsize = 1024 * 1024 * 128L;
#endif
buf = mycalloc('F',1,allocsize);
while ( (len= fread(buf,1,allocsize,srcfp)) > 0 )
if ( (long)fwrite(buf,1,len,destfp) != len )
@ -638,7 +679,7 @@ int64_t OS_copyfile(char *src,char *dest,int32_t cmpflag)
return(len);
}
int32_t OS_releasemap(void *ptr,uint64_t filesize)
int32_t OS_releasemap(void *ptr,unsigned long filesize)
{
int32_t retval;
if ( ptr == 0 )
@ -725,7 +766,7 @@ long OS_ensurefilesize(char *fname,long filesize,int32_t truncateflag)
int32_t OS_openmap(struct OS_mappedptr *mp)
{
uint64_t allocsize = mp->allocsize;
unsigned long allocsize = mp->allocsize;
if ( mp->actually_allocated != 0 )
{
if ( mp->fileptr == 0 )
@ -754,9 +795,9 @@ int32_t OS_openmap(struct OS_mappedptr *mp)
return(0);
}
void *OS_mappedptr(void **ptrp,struct OS_mappedptr *mp,uint64_t allocsize,int32_t rwflag,char *fname)
void *OS_mappedptr(void **ptrp,struct OS_mappedptr *mp,unsigned long allocsize,int32_t rwflag,char *fname)
{
uint64_t filesize;
unsigned long filesize;
mp->actually_allocated = 0;//!os_supports_mappedfiles();
if ( fname != 0 )
{
@ -836,7 +877,7 @@ void *OS_loadfile(char *fname,char **bufp,long *lenp,long *allocsizep)
{
fclose(fp);
*lenp = 0;
printf("OS_loadfile null size.(%s)\n",fname);
//printf("OS_loadfile null size.(%s)\n",fname);
return(0);
}
if ( filesize > buflen-1 )
@ -860,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
@ -873,15 +918,15 @@ void *OS_mapfile(char *fname,long *filesizep,int32_t enablewrite) // win and pna
return(OS_portable_mapfile(fname,filesizep,enablewrite));
}
int32_t OS_syncmap(struct OS_mappedptr *mp,long len) // pnacl doesnt implement sync
{
return(OS_portable_syncmap(mp,len));
}
void *OS_tmpalloc(char *dirname,char *name,struct OS_memspace *mem,long origsize) // no syncmap no tmpalloc
{
return(OS_portable_tmpalloc(dirname,name,mem,origsize));
}
/*int32_t OS_syncmap(struct OS_mappedptr *mp,long len) // pnacl doesnt implement sync
{
return(OS_portable_syncmap(mp,len));
}
void *OS_tmpalloc(char *dirname,char *name,struct OS_memspace *mem,long origsize) // no syncmap no tmpalloc
{
return(OS_portable_tmpalloc(dirname,name,mem,origsize));
}*/
void OS_init()
{
@ -890,7 +935,7 @@ void OS_init()
decode_hex(GENESIS_PUBKEY.bytes,sizeof(GENESIS_PUBKEY),GENESIS_PUBKEYSTR);
decode_hex(GENESIS_PRIVKEY.bytes,sizeof(GENESIS_PRIVKEY),GENESIS_PRIVKEYSTR);
SaM_PrepareIndices();
return(OS_portable_init());
OS_portable_init();
}
int32_t OS_getline(int32_t waitflag,char *line,int32_t max,char *dispstr)
@ -928,3 +973,108 @@ int32_t OS_getline(int32_t waitflag,char *line,int32_t max,char *dispstr)
line[strlen(line)-1] = 0;
return((int32_t)strlen(line));
}
//////////// test suite for:
/*
int64_t OS_filesize(char *fname);
void OS_ensure_directory(char *dirname);
long OS_ensurefilesize(char *fname,long filesize,int32_t truncateflag);
int32_t OS_truncate(char *fname,long filesize);
int32_t OS_renamefile(char *fname,char *newfname);
int32_t OS_removefile(char *fname,int32_t scrubflag);
void *OS_mapfile(char *fname,long *filesizep,int32_t enablewrite);
int32_t OS_releasemap(void *ptr,uint64_t filesize);
double OS_milliseconds();
void OS_randombytes(uint8_t *x,long xlen);
*/
int32_t iguana_OStests()
{
static uint16_t pairs[0x100][0x100],mappairs[0x100][0x100];
uint8_t buf[4096],*bufptr; int32_t val,min,minij,maxij,max,i,j,histo[0x100],retval = 0,n=0; double startmilli,endmilli; FILE *fp; char *name,*name2,*dirname; long filesize; void *fileptr;
startmilli = OS_milliseconds();
printf("\n>>>>>>>>>> starting tests. Please count the seconds (or use stopwatch)\n");
name = "OStests";
name2 = "OStests2";
dirname = "tmp";
fp = fopen(name,"wb");
memset(histo,0,sizeof(histo));
memset(pairs,0,sizeof(pairs));
memset(mappairs,0,sizeof(mappairs));
for (i=0; i<4096; i++)
{
OS_randombytes(buf,sizeof(buf));
for (j=0; j<sizeof(buf); j++)
{
if ( (n++ % 100000) == 0 )
printf("%02x ",buf[j]);
if ( fp != 0 )
fputc(buf[j],fp);
histo[buf[j]]++;
if ( j > 0 )
pairs[buf[j-1]][buf[j]]++;
}
}
fclose(fp);
printf("\nend of random bytes\n\n");
if ( OS_filesize(name) != n )
printf("FAIL OS_filesize %lld != %d error and if OS_filesize doesnt work, nothing else will work\n",(long long)OS_filesize(name),n), retval--;
else
{
printf("PASS OS_filesize.(%s) matches %d\n",name,n);
OS_renamefile(name,name2);
if ( OS_filesize(name2) != n )
printf("FAIL OS_renamefile returns filesize %lld != %d\n",(long long)OS_filesize(name2),n), retval--;
else printf("PASS OS_renamefile (%s) -> (%s) worked\n",name,name2);
if ( (fileptr= OS_mapfile(name2,&filesize,0)) == 0 )
printf("FAIL OS_mapfile.(%s) returns null\n",name2), retval--;
else if ( filesize != n )
printf("FAIL OS_mapfile.(%s) returns %ld != %d\n",name2,filesize,n), retval--;
else
{
bufptr = fileptr;
for (i=0; i<4096; i++)
{
memcpy(buf,bufptr,sizeof(buf));
bufptr += sizeof(buf);
for (j=1; j<sizeof(buf); j++)
mappairs[buf[j-1]][buf[j]]++;
}
if ( memcmp(pairs,mappairs,sizeof(pairs)) != 0 )
printf("FAIL OS_mapfile.(%s) %ld data error pairs[][] != mappairs[][]\n",name2,filesize), retval--;
else printf("PASS OS_mapfile.(%s) %ld regenerated identical pairs[][]\n",name2,filesize);
if ( OS_releasemap(fileptr,filesize) != 0 )
printf("FAIL OS_releasemap.(%s) %ld returns error\n",name2,filesize), retval--;
else printf("PASS OS_releasemap.(%s) %ld returns success\n",name2,filesize);
}
OS_removefile(name2,0);
if ( OS_filesize(name2) == n )
printf("FAIL OS_removefile.(%s) didnt work\n",name2), retval--;
else if ( (fp= fopen(name2,"rb")) != 0 )
printf("FAIL OS_removefile.(%s) didnt work fopen fp.%p\n",name2,fp), fclose(fp), retval--;
else printf("PASS OS_removefile.(%s) worked\n",name2);
}
minij = min = (1 << 30);
maxij = max = -1;
for (i=0; i<0x100; i++)
{
if ( (val= histo[i]) > max )
max = val;
else if ( val < min )
min = val;
for (j=0; j<0x100; j++)
{
if ( (val= pairs[i][j]) > maxij )
maxij = val;
else if ( val < minij )
minij = val;
}
}
endmilli = OS_milliseconds();
printf("\n\nDid that take %.3f seconds? If not, there is a problem with OS_milliseconds\n\nMake sure above numbers look random and the min/max are within specified range:\n<3%% %.2f%% min %d max %d | <75%% %.3f%% minij %d maxij %d\n",(endmilli - startmilli)/1000.,100*(double)max/min - 100.,min,max,100*(double)maxij/minij - 100.,minij,maxij);
return(retval);
}

8
crypto777/iguana_serdes.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -13,10 +13,11 @@
* *
******************************************************************************/
#ifndef FROM_JS
#include "OS_portable.h"
#include "../includes/curve25519.h"
// threadsafe
// threadsafe
int32_t iguana_rwnum(int32_t rwflag,uint8_t *serialized,int32_t len,void *endianedp)
{
int32_t i; uint64_t x;
@ -79,7 +80,7 @@ int32_t iguana_sethdr(struct iguana_msghdr *H,const uint8_t netmagic[4],char *co
iguana_rwnum(1,H->serdatalen,sizeof(int32_t),&datalen);
if ( data != 0 )
{
hash2 = bits256_doublesha256(0,data,datalen);
hash2 = bits256_doublesha256(0,data,datalen); // GRS?
iguana_rwbignum(1,tmp.bytes,sizeof(tmp),hash2.bytes);
for (i=0; i<4; i++)
H->hash[i] = tmp.bytes[i];
@ -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

241
crypto777/iguana_utils.c

@ -1,5 +1,5 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* Copyright © 2014-2017 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
@ -182,7 +182,7 @@ void calc_OP_HASH160(char hexstr[41],uint8_t rmd160[20],char *pubkey)
}
decode_hex(buf,len,pubkey);
calc_rmd160_sha256(rmd160,buf,len);
if ( 0 )
if ( (0) )
{
int i;
for (i=0; i<20; i++)
@ -193,6 +193,14 @@ void calc_OP_HASH160(char hexstr[41],uint8_t rmd160[20],char *pubkey)
init_hexbytes_noT(hexstr,rmd160,20);
}
double _xblend(float *destp,double val,double decay)
{
double oldval;
if ( (oldval = *destp) != 0. )
return((oldval * decay) + ((1. - decay) * val));
else return(val);
}
double _dxblend(double *destp,double val,double decay)
{
double oldval;
@ -263,12 +271,12 @@ int32_t iguana_numthreads(struct iguana_info *coin,int32_t mask)
void iguana_launcher(void *ptr)
{
struct iguana_thread *t = ptr; struct iguana_info *coin;
coin = t->coin;
struct iguana_thread *t = ptr; //struct iguana_info *coin;
//coin = t->coin;
t->funcp(t->arg);
if ( coin != 0 )
coin->Terminated[t->type % (sizeof(coin->Terminated)/sizeof(*coin->Terminated))]++;
queue_enqueue("TerminateQ",&TerminateQ,&t->DL,0);
//if ( coin != 0 )
// coin->Terminated[t->type % (sizeof(coin->Terminated)/sizeof(*coin->Terminated))]++;
queue_enqueue("TerminateQ",&TerminateQ,&t->DL);
}
void iguana_terminate(struct iguana_thread *t)
@ -295,8 +303,8 @@ 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);
while ( (t= queue_dequeue(&TerminateQ,0)) != 0 )
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 )
printf("terminated.%d launched.%d terminate.%p\n",coin->Terminated[t->type],coin->Launched[t->type],t);
@ -359,11 +367,15 @@ int32_t decode_hex(unsigned char *bytes,int32_t n,char *hex)
{
int32_t adjust,i = 0;
//printf("decode.(%s)\n",hex);
if ( is_hexstr(hex,n) == 0 )
if ( is_hexstr(hex,n) <= 0 )
{
memset(bytes,0,n);
return(n);
}
if ( hex[n-1] == '\n' || hex[n-1] == '\r' )
hex[--n] = 0;
if ( hex[n-1] == '\n' || hex[n-1] == '\r' )
hex[--n] = 0;
if ( n == 0 || (hex[n*2+1] == 0 && hex[n*2] != 0) )
{
if ( n > 0 )
@ -424,9 +436,9 @@ char *clonestr(char *str)
if ( str == 0 || str[0] == 0 )
{
printf("warning cloning nullstr.%p\n",str);
#ifdef __APPLE__
while ( 1 ) sleep(1);
#endif
//#ifdef __APPLE__
// while ( 1 ) sleep(1);
//#endif
str = (char *)"<nullstr>";
}
clone = (char *)malloc(strlen(str)+16);
@ -434,7 +446,6 @@ char *clonestr(char *str)
return(clone);
}
int32_t safecopy(char *dest,char *src,long len)
{
int32_t i = -1;
@ -447,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
@ -510,11 +522,24 @@ static int _increasing_double(const void *a,const void *b)
{
#define double_a (*(double *)a)
#define double_b (*(double *)b)
if ( double_b > double_a )
return(-1);
else if ( double_b < double_a )
return(1);
return(0);
if ( double_b > double_a )
return(-1);
else if ( double_b < double_a )
return(1);
return(0);
#undef double_a
#undef double_b
}
static int _decreasing_double(const void *a,const void *b)
{
#define double_a (*(double *)a)
#define double_b (*(double *)b)
if ( double_b > double_a )
return(1);
else if ( double_b < double_a )
return(-1);
return(0);
#undef double_a
#undef double_b
}
@ -560,8 +585,14 @@ static int _decreasing_uint32(const void *a,const void *b)
int32_t sortds(double *buf,uint32_t num,int32_t size)
{
qsort(buf,num,size,_increasing_double);
return(0);
qsort(buf,num,size,_increasing_double);
return(0);
}
int32_t revsortds(double *buf,uint32_t num,int32_t size)
{
qsort(buf,num,size,_decreasing_double);
return(0);
}
int32_t sort64s(uint64_t *buf,uint32_t num,int32_t size)
@ -961,6 +992,7 @@ int32_t RS_encode(char *rsaddr,uint64_t id)
rsaddr[j++] = '-';
}
rsaddr[j] = 0;
//printf("%llu -> NXT RS (%s)\n",(long long)id,rsaddr);
return(0);
}
@ -1074,30 +1106,6 @@ void rmd160ofsha256(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
calc_rmd160(hexstr,buf,sha256,sizeof(sha256));
}
void calc_md2str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
bits128 x;
calc_md2(hexstr,buf,msg,len);
decode_hex(buf,sizeof(x),hexstr);
memcpy(buf,x.bytes,sizeof(x));
}
void calc_md4str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
bits128 x;
calc_md4(hexstr,buf,msg,len);
decode_hex(buf,sizeof(x),hexstr);
memcpy(buf,x.bytes,sizeof(x));
}
void calc_md5str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
bits128 x;
calc_md5(hexstr,msg,len);
decode_hex(buf,sizeof(x),hexstr);
memcpy(buf,x.bytes,sizeof(x));
}
void calc_crc32str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
uint32_t crc; uint8_t serialized[sizeof(crc)];
@ -1115,6 +1123,7 @@ void calc_NXTaddr(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
uint8_t mysecret[32]; uint64_t nxt64bits;
nxt64bits = conv_NXTpassword(mysecret,buf,msg,len);
//printf("call RSencode with %llu\n",(long long)nxt64bits);
RS_encode(hexstr,nxt64bits);
}
@ -1134,3 +1143,145 @@ void calc_rmd160_sha256(uint8_t rmd160[20],uint8_t *data,int32_t datalen)
vcalc_sha256(0,hash.bytes,data,datalen);
calc_rmd160(0,rmd160,hash.bytes,sizeof(hash));
}
char *cmc_ticker(char *base)
{
char url[512];
sprintf(url,"https://api.coinmarketcap.com/v1/ticker/%s/",base);
return(issue_curl(url));
}
char *bittrex_orderbook(char *base,char *rel,int32_t maxdepth)
{
char market[64],url[512];
sprintf(market,"%s-%s",rel,base);
sprintf(url,"http://bittrex.com/api/v1.1/public/getorderbook?market=%s&type=both&depth=%d",market,maxdepth);
return(issue_curl(url));
}
double calc_theoretical(double weighted,double CMC_average,double changes[3])
{
double theoretical = 0.; //adjusted = 0.,
if ( weighted > SMALLVAL && CMC_average > SMALLVAL )
{
theoretical = (weighted + CMC_average) * 0.5;
/*if ( changes[0] > SMALLVAL && changes[1] > SMALLVAL && changes[2] > SMALLVAL )
{
if ( changes[0] > changes[1] && changes[1] > changes[2] ) // breakout
{
adjusted = theoretical * (1. - (changes[0] + changes[1]) * .005);
}
}
else if ( changes[0] < -SMALLVAL && changes[1] < -SMALLVAL && changes[2] < -SMALLVAL ) //
{
if ( changes[0] < changes[1] && changes[1] < changes[2] ) // waterfall
{
adjusted = theoretical * (1. - (changes[0] + changes[1]) * .005);
}
}
if ( adjusted != 0. && theoretical != 0. )
theoretical = (theoretical + adjusted) * 0.5;*/
}
//printf("adjusted %.8f theoretical %.8f (%.8f + wt %.8f)\n",adjusted,theoretical,CMC_average,weighted);
return(theoretical);
}
double calc_weighted(double *avebidp,double *aveaskp,double *bids,double *bidvols,int32_t numbids,double *asks,double *askvols,int32_t numasks,double limit)
{
int32_t i; double weighted = 0.,bidsum = 0., asksum = 0.,totalbids = 0.,totalasks = 0.;
bidsum = bids[0] * bidvols[0], totalbids = bidvols[0];
asksum = asks[0] * askvols[0], totalasks = askvols[0];
for (i=1; i<numbids; i++)
{
if ( totalbids > limit )
break;
bidsum += bids[i] * bidvols[i];
totalbids += bidvols[i];
}
for (i=1; i<numasks; i++)
{
if ( totalasks > limit )
break;
asksum += asks[i] * askvols[i];
totalasks += askvols[i];
}
if ( totalbids != 0. && totalasks != 0. )
{
*avebidp = (bidsum / totalbids);
*aveaskp = (asksum / totalasks);
weighted = (*avebidp + *aveaskp) * 0.5;
}
//printf("weighted %f\n",weighted);
return(weighted);
}
double weighted_orderbook(double *avebidp,double *aveaskp,double *highbidp,double *lowaskp,char *orderbookstr,double limit)
{
cJSON *bookjson,*bid,*ask,*resobj,*item; int32_t i,numbids,numasks; double bidvols[50],bids[50],askvols[50],asks[50],weighted = 0.;
if ( orderbookstr != 0 )
{
if ( (bookjson= cJSON_Parse(orderbookstr)) != 0 )
{
if ( (resobj= jobj(bookjson,"result")) != 0 )
{
bid = jarray(&numbids,resobj,"buy");
if ( numbids > sizeof(bids)/sizeof(*bids) )
numbids = (int32_t)(sizeof(bids)/sizeof(*bids));
ask = jarray(&numasks,resobj,"sell");
if ( numasks > sizeof(asks)/sizeof(*asks) )
numasks = (int32_t)(sizeof(asks)/sizeof(*asks));
if ( bid != 0 && ask != 0 )
{
for (i=0; i<numbids; i++)
{
item = jitem(bid,i);
bidvols[i] = jdouble(item,"Quantity");
bids[i] = jdouble(item,"Rate");
}
for (i=0; i<numasks; i++)
{
item = jitem(ask,i);
askvols[i] = jdouble(item,"Quantity");
asks[i] = jdouble(item,"Rate");
}
*highbidp = bids[0];
*lowaskp = asks[0];
weighted = calc_weighted(avebidp,aveaskp,bids,bidvols,numbids,asks,askvols,numasks,limit);
//printf("weighted %.8f (%.8f %.8f)\n",weighted,*highbidp,*lowaskp);
}
}
free_json(bookjson);
}
}
return(weighted);
}
double get_theoretical(double *avebidp,double *aveaskp,double *highbidp,double *lowaskp,double *CMC_averagep,double changes[3],char *name,char *base,char *rel,double *USD_averagep)
{
static int32_t counter;
char *cmcstr; cJSON *cmcjson,*item; double weighted,theoretical = 0.;
*avebidp = *aveaskp = *highbidp = *lowaskp = *CMC_averagep = 0.;
if ( (cmcstr= cmc_ticker(name)) != 0 )
{
if ( (cmcjson= cJSON_Parse(cmcstr)) != 0 )
{
if ( is_cJSON_Array(cmcjson) == 0 )
item = cmcjson;
else item = jitem(cmcjson,0);
*CMC_averagep = jdouble(item,"price_btc");
*USD_averagep = jdouble(item,"price_usd");
changes[0] = jdouble(item,"percent_change_1h");
changes[1] = jdouble(item,"percent_change_24h");
changes[2] = jdouble(item,"percent_change_7d");
weighted = weighted_orderbook(avebidp,aveaskp,highbidp,lowaskp,bittrex_orderbook(base,rel,25),1./(*CMC_averagep));
if ( *CMC_averagep > SMALLVAL && weighted > SMALLVAL )
theoretical = calc_theoretical(weighted,*CMC_averagep,changes);
if ( (0) && counter++ < 100 )
printf("HBLA.[%.8f %.8f] AVE.[%.8f %.8f] (%s) CMC %f %f %f %f\n",*highbidp,*lowaskp,*avebidp,*aveaskp,jprint(item,0),*CMC_averagep,changes[0],changes[1],changes[2]);
free_json(cmcjson);
}
free(cmcstr);
}
return(theoretical);
}

11
crypto777/inet.c

@ -24,7 +24,9 @@
#ifdef _WIN32
#define in6_addr sockaddr
#define in_addr_t struct sockaddr_storage
#ifndef NATIVE_WINDOWS
#define EAFNOSUPPORT WSAEAFNOSUPPORT
#endif
struct sockaddr_in6 {
short sin6_family;
@ -371,7 +373,7 @@ uint64_t _calc_ipbits(char *ip_port)
port = parse_ipaddr(ipaddr,ip_port);
memset(&addr,0,sizeof(addr));
portable_pton(ip_port[0] == '[' ? AF_INET6 : AF_INET,ipaddr,&addr);
if ( 0 )
if ( (0) )
{
int i;
for (i=0; i<16; i++)
@ -470,7 +472,7 @@ uint32_t conv_domainname(char *ipaddr,char *domain)
int32_t ipv4only = 1;
uint32_t ipbits;
struct sockaddr_in ss;
if ( 0 && conv_domain((struct sockaddr_storage *)&ss,(const char *)domain,ipv4only) == 0 )
if ( (0) && conv_domain((struct sockaddr_storage *)&ss,(const char *)domain,ipv4only) == 0 )
{
ipbits = *(uint32_t *)&ss.sin_addr;
expand_ipbits(ipaddr,ipbits);
@ -603,7 +605,10 @@ uint16_t parse_endpoint(int32_t *ip6flagp,char *transport,char *ipbuf,char *retb
ipbits = calc_ipbits(ipaddr);
expand_ipbits(tmp,ipbits);
if ( strcmp(tmp,ipaddr) != 0 )
ipaddr = 0, sprintf(retbuf,"{\"result\":\"illegal ipaddr\",\"endpoint\":\"%s\",\"ipaddr\":\"%s\",\"checkaddr\":\"%s\"}",endpoint,ipaddr,tmp);
{
sprintf(retbuf,"{\"result\":\"illegal ipaddr\",\"endpoint\":\"%s\",\"ipaddr\":\"%s\",\"checkaddr\":\"%s\"}",endpoint,ipaddr,tmp);
ipaddr = 0;
}
}
if ( inet != 0 && ipaddr != 0 && port != 0 )
{

5
crypto777/jpeg/jconfig.h

@ -20,6 +20,7 @@
/* Define "boolean" as unsigned char, not int, on Windows systems. */
#ifdef _WIN32
#define USE_MSDOS_MEMMGR
#ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
typedef unsigned char boolean;
#endif
@ -29,7 +30,11 @@ typedef unsigned char boolean;
#ifdef JPEG_INTERNALS
/* #undef RIGHT_SHIFT_IS_UNSIGNED */
#ifdef WIN32
#define INLINE
#else
#define INLINE __inline__
#endif
/* These are for configuring the JPEG memory manager. */
/* #undef DEFAULT_MAX_MEM */
/* #undef NO_MKTEMP */

1
crypto777/jpeg/jmemsys.h

@ -154,6 +154,7 @@ typedef struct backing_store_struct {
/* For the MS-DOS manager (jmemdos.c), we need: */
handle_union handle; /* reference to backing-store storage object */
char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
FILE *temp_file;
#else
#ifdef USE_MAC_MEMMGR
/* For the Mac manager (jmemmac.c), we need: */

8
crypto777/jpeg/unix/jmemname.c

@ -11,7 +11,9 @@
* Also, the problem of determining the amount of memory available
* is shoved onto the user.
*/
#ifndef _WIN32
#include <unistd.h>
#endif
#define JPEG_INTERNALS
#include "../jinclude.h"
@ -68,7 +70,11 @@ extern void free JPP((void *ptr));
*/
#ifndef TEMP_DIRECTORY /* can override from jconfig.h or Makefile */
#define TEMP_DIRECTORY "/usr/tmp/" /* recommended setting for Unix */
#ifdef _WIN32
#define TEMP_DIRECTORY "" /* recommended setting for Unix */
#else
#define TEMP_DIRECTORY "/tmp/" /* recommended setting for Unix */
#endif
#endif
static int next_file_num; /* to distinguish among several temp files */

2
crypto777/m_LP

@ -1,4 +1,4 @@
git pull
rm *.o
gcc -c -DLIQUIDITY_PROVIDER=1 -O2 *.c jpeg/*.c jpeg/unix/*.c -I/usr/lib/x86_64-linux-gnu/curl
rm -f ../agents/libcrypto777.a; ar rcu ../agents/libcrypto777.a *.o
rm -f ../agents/libcrypto777.a; ar rc ../agents/libcrypto777.a *.o

30
crypto777/m_LP_StaticNanoMsg

@ -0,0 +1,30 @@
# Very basic makefile for compiling iguana in Linux with StaticNanoMsg
# derived from m_LP (used to compile iguana for linux)
# author: fadedreamz
SRCS=$(wildcard *.c)
SRCS+=$(wildcard jpeg/*.c)
SRCS+=$(wildcard jpeg/unix/*.c)
OBJS=$(SRCS:%.c=%.o)
INCLUDE_DIRS+=-I/usr/lib/x86_64-linux-gnu/curl
PREPROCESSORS+=-DLIQUIDITY_PROVIDER=1 -DUSE_STATIC_NANOMSG
CFLAGS+=-O2 $(PREPROCESSORS) $(INCLUDE_DIRS)
update_repo:
git pull
clean:
-rm $(OBJS)
all: update_repo $(OBJS) static
@echo ' ================'
@echo '| crypto777 [OK] |'
@echo ' ================'
static: $(OBJS)
ar rc ../agents/libcrypto777.a $(OBJS)
.PHONY: update_repo clean all static

4
crypto777/m_osx_release

@ -0,0 +1,4 @@
git pull
rm *.o
gcc -mmacosx-version-min=10.6 -c -DLIQUIDITY_PROVIDER=1 -O2 *.c jpeg/*.c jpeg/unix/*.c -I/usr/lib/x86_64-linux-gnu/curl
rm -f ../agents/libcrypto777.a; ar rc ../agents/libcrypto777.a *.o

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");
}
}
}

136
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,58 +236,58 @@ 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");
//sleep(1);
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);
sleep(1);
PNACL_message("socktypes init\n");
nn_global_add_transport(nn_inproc);
nn_global_add_transport(nn_ws);
//nn_global_add_transport(nn_tcpmux);
//sleep(1);
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");
//sleep(1);
PNACL_msg("nn_xpair_socktype init\n");
nn_global_add_socktype(nn_xpair_socktype);
PNACL_message("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);
//nn_global_add_socktype(nn_xreq_socktype);
//nn_global_add_socktype(nn_respondent_socktype);
//nn_global_add_socktype(nn_surveyor_socktype);
//nn_global_add_socktype(nn_xrespondent_socktype);
//nn_global_add_socktype(nn_xsurveyor_socktype);
//nn_global_add_socktype(nn_pub_socktype);
//nn_global_add_socktype(nn_sub_socktype);
//nn_global_add_socktype(nn_xpub_socktype);
//nn_global_add_socktype(nn_xsub_socktype);
//nn_global_add_socktype(nn_push_socktype);
//nn_global_add_socktype(nn_xpush_socktype);
//nn_global_add_socktype(nn_pull_socktype);
//nn_global_add_socktype(nn_xpull_socktype);
//nn_global_add_socktype(nn_bus_socktype);
//nn_global_add_socktype(nn_xbus_socktype);
sleep(1);
PNACL_message("do pool 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);
nn_global_add_socktype(nn_xreq_socktype);
nn_global_add_socktype(nn_respondent_socktype);
nn_global_add_socktype(nn_surveyor_socktype);
nn_global_add_socktype(nn_xrespondent_socktype);
nn_global_add_socktype(nn_xsurveyor_socktype);
nn_global_add_socktype(nn_pub_socktype);
nn_global_add_socktype(nn_sub_socktype);
nn_global_add_socktype(nn_xpub_socktype);
nn_global_add_socktype(nn_xsub_socktype);
nn_global_add_socktype(nn_push_socktype);
nn_global_add_socktype(nn_xpush_socktype);
nn_global_add_socktype(nn_pull_socktype);
nn_global_add_socktype(nn_xpull_socktype);
nn_global_add_socktype(nn_bus_socktype);
nn_global_add_socktype(nn_xbus_socktype);
//sleep(1);
PNACL_msg("do pool init\n");
nn_pool_init(&SELF.pool); // Start the worker threads
sleep(1);
PNACL_message("do FSM init\n");
//sleep(1);
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,16 +46,10 @@
#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

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);

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

Loading…
Cancel
Save