Browse Source

initial commit

release/v0.1
jl777 9 years ago
parent
commit
38a3f146ac
  1. 2
      .gitignore
  2. 582
      InstantDEX/InstantDEX.c
  3. 223
      InstantDEX/InstantDEX_quote.h
  4. 47
      InstantDEX/Makefile
  5. 1407
      InstantDEX/exchange_trades.h
  6. 1208
      InstantDEX/exchangeparse.h
  7. 259
      InstantDEX/exchanges/bitfinex.c
  8. 170
      InstantDEX/exchanges/bitstamp.c
  9. 247
      InstantDEX/exchanges/bittrex.c
  10. 321
      InstantDEX/exchanges/btc38.c
  11. 215
      InstantDEX/exchanges/btce.c
  12. 53
      InstantDEX/exchanges/checkbalance.c
  13. 229
      InstantDEX/exchanges/coinbase.c
  14. 183
      InstantDEX/exchanges/huobi.c
  15. 285
      InstantDEX/exchanges/lakebtc.c
  16. 239
      InstantDEX/exchanges/okcoin.c
  17. 233
      InstantDEX/exchanges/poloniex.c
  18. 183
      InstantDEX/exchanges/quadriga.c
  19. 36
      InstantDEX/main.c
  20. 17
      InstantDEX/manifest.json
  21. 3456
      InstantDEX/orderbooks.h
  22. 880
      InstantDEX/quotes.h
  23. 1496
      InstantDEX/subatomic.h
  24. 323
      InstantDEX/tradebots.h
  25. 1583
      InstantDEX/trades.h
  26. 2
      LEGAL/AUTHORS
  27. 339
      LEGAL/COPYING
  28. 67
      LEGAL/DEVELOPER-AGREEMENT
  29. 32
      LEGAL/LICENSE
  30. 21
      LEGAL/THIRDPARTY-LICENSES
  31. 78
      Makefile
  32. 15
      README.md
  33. 48
      SuperNET/Makefile
  34. 23
      SuperNET/SuperNET.c
  35. 31
      SuperNET/main.c
  36. 17
      SuperNET/manifest.json
  37. 1772
      confs/BTCD_hdrs.txt
  38. 49
      confs/BTCD_peers.txt
  39. 195
      confs/BTC_hdrs.txt
  40. 137
      confs/BTC_peers.txt
  41. 40
      crypto777/Makefile
  42. 133
      crypto777/OS_nonportable.c
  43. 207
      crypto777/OS_portable.c
  44. 259
      crypto777/OS_portable.h
  45. 529
      crypto777/OS_time.c
  46. 951
      crypto777/SaM.c
  47. 338
      crypto777/bitcoind_RPC.c
  48. 1054
      crypto777/cJSON.c
  49. 892
      crypto777/curve25519-donna.c
  50. 1695
      crypto777/curve25519.c
  51. 30
      crypto777/hmac/crypt_argchk.c
  52. 65
      crypto777/hmac/hash_memory.c
  53. 103
      crypto777/hmac/hmac_done.c
  54. 87
      crypto777/hmac/hmac_file.c
  55. 108
      crypto777/hmac/hmac_init.c
  56. 83
      crypto777/hmac/hmac_memory.c
  57. 92
      crypto777/hmac/hmac_memory_multi.c
  58. 39
      crypto777/hmac/hmac_process.c
  59. 318
      crypto777/hmac/hmac_test.c
  60. 262
      crypto777/hmac/md2.c
  61. 325
      crypto777/hmac/md4.c
  62. 380
      crypto777/hmac/md5.c
  63. 434
      crypto777/hmac/rmd128.c
  64. 483
      crypto777/hmac/rmd160.c
  65. 454
      crypto777/hmac/rmd256.c
  66. 519
      crypto777/hmac/rmd320.c
  67. 302
      crypto777/hmac/sha1.c
  68. 137
      crypto777/hmac/sha224.c
  69. 442
      crypto777/hmac/sha256.c
  70. 148
      crypto777/hmac/sha384.c
  71. 319
      crypto777/hmac/sha512.c
  72. 825
      crypto777/hmac/tiger.c
  73. 95
      crypto777/hmac/tomcrypt.h
  74. 38
      crypto777/hmac/tomcrypt_argchk.h
  75. 140
      crypto777/hmac/tomcrypt_cfg.h
  76. 891
      crypto777/hmac/tomcrypt_cipher.h
  77. 407
      crypto777/hmac/tomcrypt_custom.h
  78. 379
      crypto777/hmac/tomcrypt_hash.h
  79. 382
      crypto777/hmac/tomcrypt_mac.h
  80. 426
      crypto777/hmac/tomcrypt_macros.h
  81. 500
      crypto777/hmac/tomcrypt_math.h
  82. 23
      crypto777/hmac/tomcrypt_misc.h
  83. 552
      crypto777/hmac/tomcrypt_pk.h
  84. 89
      crypto777/hmac/tomcrypt_pkcs.h
  85. 199
      crypto777/hmac/tomcrypt_prng.h
  86. 325
      crypto777/hmac/whirl.c
  87. 586
      crypto777/hmac/whirltab.c
  88. 618
      crypto777/hmac_sha512.c
  89. 832
      crypto777/iguana_OS.c
  90. 819
      crypto777/iguana_utils.c
  91. 605
      crypto777/inet.c
  92. 1094
      crypto777/jpeg/Makefile
  93. 739
      crypto777/jpeg/ansi2knr.c
  94. 134
      crypto777/jpeg/cderror.h
  95. 181
      crypto777/jpeg/cdjpeg.c
  96. 187
      crypto777/jpeg/cdjpeg.h
  97. 643
      crypto777/jpeg/cjpeg.c
  98. 402
      crypto777/jpeg/ckconfig.c
  99. 617
      crypto777/jpeg/djpeg.c
  100. 433
      crypto777/jpeg/example.c

2
.gitignore

@ -0,0 +1,2 @@
*.o

582
InstantDEX/InstantDEX.c

@ -0,0 +1,582 @@
/******************************************************************************
* Copyright © 2014-2015 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 _issue_curl(curl_handle,label,url) bitcoind_RPC(curl_handle,label,url,0,0,0)
#define INSTANTDEX_MINVOL 75
#define INSTANTDEX_MINVOLPERC ((double)INSTANTDEX_MINVOL / 100.)
#define INSTANTDEX_PRICESLIPPAGE 0.001
#define FINISH_HEIGHT 7
#define INSTANTDEX_TRIGGERDEADLINE 120
#define JUMPTRADE_SECONDS 100
#define INSTANTDEX_ACCT "4383817337783094122"
#define INSTANTDEX_FEE ((long)(2.5 * SATOSHIDEN))
#include "../iguana777.h"
#include "InstantDEX_quote.h"
#define INSTANTDEX_LOCALAPI "allorderbooks", "orderbook", "lottostats", "LSUM", "makebasket", "disable", "enable", "peggyrates", "tradesequence", "placebid", "placeask", "orderstatus", "openorders", "cancelorder", "tradehistory", "balance", "allexchanges",
typedef char *(*json_handler)(int32_t localaccess,int32_t valid,char *sender,cJSON **objs,int32_t numobjs,char *origargstr);
queue_t InstantDEXQ,TelepathyQ,Pending_offersQ;
cJSON *InstantDEX_lottostats();
//#include "NXT_tx.h"
#include "trades.h"
#include "quotes.h"
#include "subatomic.h"
#include "orderbooks.h"
#include "exchangeparse.h"
#include "exchange_trades.h"
#include "exchanges/poloniex.c"
#include "exchanges/bittrex.c"
#include "exchanges/btce.c"
#include "exchanges/bitfinex.c"
#include "exchanges/btc38.c"
#include "exchanges/huobi.c"
#include "exchanges/lakebtc.c"
#include "exchanges/quadriga.c"
#include "exchanges/okcoin.c"
#include "exchanges/coinbase.c"
#include "exchanges/bitstamp.c"
// {"plugin":"InstantDEX","method":"orderbook","baseid":"8688289798928624137","rel":"USD","exchange":"active","allfields":1}
// {"plugin":"InstantDEX","method":"orderbook","baseid":"17554243582654188572","rel":"12071612744977229797","exchange":"active","allfields":1}
// {"plugin":"InstantDEX","method":"orderbook","baseid":"6918149200730574743","rel":"XMR","exchange":"active","allfields":1}
void idle()
{
char *jsonstr,*str; cJSON *json; int32_t n = 0; uint32_t nonce;
/*printf("INSTANTDEX.readyflag.%d\n",INSTANTDEX.readyflag);
while ( INSTANTDEX.readyflag == 0 )
sleep(1);
printf("INSTANTDEX.readyflag.%d\n",INSTANTDEX.readyflag);*/
while ( 1 )
{
if ( n == 0 )
sleep(1);
n = 0;
if ( (jsonstr= queue_dequeue(&InstantDEXQ,1)) != 0 )
{
printf("Dequeued InstantDEX.(%s)\n",jsonstr);
if ( (json= cJSON_Parse(jsonstr)) != 0 )
{
//fprintf(stderr,"dequeued\n");
if ( (str= busdata_sync(&nonce,jsonstr,"allnodes",0)) != 0 )
{
//fprintf(stderr,"busdata.(%s)\n",str);
free(str);
}
free_json(json);
n++;
} else printf("error parsing (%s) from InstantDEXQ\n",jsonstr);
free_queueitem(jsonstr);
}
}
}
uint32_t _get_NXTheight(uint32_t *firsttimep)
{
static uint32_t last,lastheight,lastNXTtime;
cJSON *json; uint32_t height = 0; char cmd[256],*jsonstr;
if ( time(NULL) > last+10 )
{
sprintf(cmd,"requestType=getState");
if ( (jsonstr= issue_NXTPOST(cmd)) != 0 )
{
//printf("(%s) -> (%s)\n",cmd,jsonstr);
if ( (json= cJSON_Parse(jsonstr)) != 0 )
{
if ( firsttimep != 0 )
lastNXTtime = *firsttimep = (uint32_t)get_cJSON_int(json,"time");
height = (int32_t)get_cJSON_int(json,"numberOfBlocks");
if ( height > 0 )
height--;
lastheight = height;
free_json(json);
}
free(jsonstr);
}
last = (uint32_t)time(NULL);
}
else
{
height = lastheight;
if ( firsttimep != 0 )
*firsttimep = lastNXTtime;
}
return(height);
}
void idle2()
{
static double lastmilli;
uint32_t NXTblock;
//while ( INSTANTDEX.readyflag == 0 )
// sleep(1);
while ( 1 )
{
if ( milliseconds() < (lastmilli + 5000) )
sleep(1);
NXTblock = _get_NXTheight(0);
if ( 1 && NXTblock != prices777_NXTBLOCK )
{
prices777_NXTBLOCK = NXTblock;
InstantDEX_update(IGUANA_NXTADDR,IGUANA_NXTACCTSECRET);//,SUPERNET.);
//fprintf(stderr,"done idle NXT\n");
}
lastmilli = milliseconds();
}
}
cJSON *InstantDEX_lottostats()
{
char cmdstr[1024],NXTaddr[64],buf[1024],*jsonstr; struct destbuf receiverstr;
cJSON *json,*array,*txobj; int32_t i,n,totaltickets = 0; uint64_t amount,senderbits; uint32_t timestamp = 0;
if ( timestamp == 0 )
timestamp = 38785003;
sprintf(cmdstr,"requestType=getBlockchainTransactions&account=%s&timestamp=%u&type=0&subtype=0",INSTANTDEX_ACCT,timestamp);
//printf("cmd.(%s)\n",cmdstr);
if ( (jsonstr= issue_NXTPOST(cmdstr)) != 0 )
{
// printf("jsonstr.(%s)\n",jsonstr);
// mm string.({"requestProcessingTime":33,"transactions":[{"fullHash":"2a2aab3b84dadf092cf4cedcd58a8b5a436968e836338e361c45651bce0ef97e","confirmations":203,"signatureHash":"52a4a43d9055fe4861b3d13fbd03a42fecb8c9ad4ac06a54da7806a8acd9c5d1","transaction":"711527527619439146","amountNQT":"1100000000","transactionIndex":2,"ecBlockHeight":360943,"block":"6797727125503999830","recipientRS":"NXT-74VC-NKPE-RYCA-5LMPT","type":0,"feeNQT":"100000000","recipient":"4383817337783094122","version":1,"sender":"423766016895692955","timestamp":38929220,"ecBlockId":"10121077683890606382","height":360949,"subtype":0,"senderPublicKey":"4e5bbad625df3d536fa90b1e6a28c3f5a56e1fcbe34132391c8d3fd7f671cb19","deadline":1440,"blockTimestamp":38929430,"senderRS":"NXT-8E6V-YBWH-5VMR-26ESD","signature":"4318f36d9cf68ef0a8f58303beb0ed836b670914065a868053da5fe8b096bc0c268e682c0274e1614fc26f81be4564ca517d922deccf169eafa249a88de58036"}]})
if ( (json= cJSON_Parse(jsonstr)) != 0 )
{
if ( (array= cJSON_GetObjectItem(json,"transactions")) != 0 && is_cJSON_Array(array) != 0 && (n= cJSON_GetArraySize(array)) > 0 )
{
for (i=0; i<n; i++)
{
txobj = cJSON_GetArrayItem(array,i);
copy_cJSON(&receiverstr,cJSON_GetObjectItem(txobj,"recipient"));
if ( strcmp(receiverstr.buf,INSTANTDEX_ACCT) == 0 )
{
if ( (senderbits = get_API_nxt64bits(cJSON_GetObjectItem(txobj,"sender"))) != 0 )
{
expand_nxt64bits(NXTaddr,senderbits);
amount = get_API_nxt64bits(cJSON_GetObjectItem(txobj,"amountNQT"));
if ( amount == INSTANTDEX_FEE )
totaltickets++;
else if ( amount >= 2*INSTANTDEX_FEE )
totaltickets += 2;
}
}
}
}
free_json(json);
}
free(jsonstr);
}
sprintf(buf,"{\"result\":\"lottostats\",\"totaltickets\":\"%d\"}",totaltickets);
return(cJSON_Parse(buf));
}
void set_best_amounts(int64_t *baseamountp,int64_t *relamountp,double price,double volume)
{
double checkprice,checkvol,distA,distB,metric,bestmetric = (1. / SMALLVAL);
uint64_t baseamount,relamount,bestbaseamount = 0,bestrelamount = 0;
int32_t i,j;
baseamount = volume * SATOSHIDEN;
relamount = ((price * volume) * SATOSHIDEN);
//*baseamountp = baseamount, *relamountp = relamount;
//return;
for (i=-1; i<=1; i++)
for (j=-1; j<=1; j++)
{
checkprice = prices777_price_volume(&checkvol,baseamount+i,relamount+j);
distA = (checkprice - price);
distA *= distA;
distB = (checkvol - volume);
distB *= distB;
metric = sqrt(distA + distB);
if ( metric < bestmetric )
{
bestmetric = metric;
bestbaseamount = baseamount + i;
bestrelamount = relamount + j;
//printf("i.%d j.%d metric. %f\n",i,j,metric);
}
}
*baseamountp = bestbaseamount;
*relamountp = bestrelamount;
}
int32_t bidask_parse(int32_t localaccess,struct destbuf *exchangestr,struct destbuf *name,struct destbuf *base,struct destbuf *rel,struct destbuf *gui,struct InstantDEX_quote *iQ,cJSON *json)
{
uint64_t basemult,relmult,baseamount,relamount; double price,volume; int32_t exchangeid,keysize,flag; char key[1024],buf[64],*methodstr;
memset(iQ,0,sizeof(*iQ));
iQ->s.baseid = j64bits(json,"baseid"); iQ->s.relid = j64bits(json,"relid");
iQ->s.baseamount = j64bits(json,"baseamount"), iQ->s.relamount = j64bits(json,"relamount");
iQ->s.vol = jdouble(json,"volume"); iQ->s.price = jdouble(json,"price");
copy_cJSON(exchangestr,jobj(json,"exchange"));
if ( exchangestr->buf[0] == 0 || find_exchange(&exchangeid,exchangestr->buf) == 0 )
exchangeid = -1;
iQ->exchangeid = exchangeid;
copy_cJSON(base,jobj(json,"base"));
copy_cJSON(rel,jobj(json,"rel"));
copy_cJSON(name,jobj(json,"name"));
methodstr = jstr(json,"method");
if ( methodstr != 0 && (strcmp(methodstr,"placeask") == 0 || strcmp(methodstr,"ask") == 0) )
iQ->s.isask = 1;
if ( iQ->s.vol < 0. )
{
iQ->s.vol = -iQ->s.vol;
iQ->s.isask ^= 1;
}
if ( methodstr != 0 && strcmp(exchangestr->buf,"wallet") == 0 && (iQ->s.baseid == NXT_ASSETID || strcmp(base->buf,"NXT") == 0) )
{
flag = 1;
if ( strcmp(methodstr,"placeask") == 0 )
methodstr = "placebid";
else if ( strcmp(methodstr,"placebid") == 0 )
methodstr = "placeask";
else if ( strcmp(methodstr,"ask") == 0 )
methodstr = "bid";
else if ( strcmp(methodstr,"bid") == 0 )
methodstr = "ask";
else flag = 0;
if ( flag != 0 )
{
iQ->s.baseid = iQ->s.relid, iQ->s.relid = NXT_ASSETID;
strcpy(base->buf,rel->buf), strcpy(rel->buf,"NXT");
baseamount = iQ->s.baseamount;
iQ->s.baseamount = iQ->s.relamount, iQ->s.relamount = baseamount;
name->buf[0] = 0;
if ( iQ->s.vol > SMALLVAL && iQ->s.price > SMALLVAL )
{
iQ->s.vol *= iQ->s.price;
iQ->s.price = 1. / iQ->s.price;
}
iQ->s.isask ^= 1;
printf("INVERT\n");
}
}
if ( (iQ->s.timestamp= juint(json,"timestamp")) == 0 )
iQ->s.timestamp = (uint32_t)time(NULL);
copy_cJSON(gui,jobj(json,"gui")), strncpy(iQ->gui,gui->buf,sizeof(iQ->gui)-1);
iQ->s.automatch = juint(json,"automatch");
iQ->s.minperc = juint(json,"minperc");
if ( (iQ->s.duration= juint(json,"duration")) == 0 || iQ->s.duration > ORDERBOOK_EXPIRATION )
iQ->s.duration = ORDERBOOK_EXPIRATION;
InstantDEX_name(key,&keysize,exchangestr->buf,name->buf,base->buf,&iQ->s.baseid,rel->buf,&iQ->s.relid);
//printf(">>>>>>>>>>>> BASE.(%s) REL.(%s)\n",base->buf,rel->buf);
iQ->s.basebits = stringbits(base->buf);
iQ->s.relbits = stringbits(rel->buf);
safecopy(iQ->base,base->buf,sizeof(iQ->base));
safecopy(iQ->rel,rel->buf,sizeof(iQ->rel));
iQ->s.offerNXT = j64bits(json,"offerNXT");
iQ->s.quoteid = j64bits(json,"quoteid");
if ( strcmp(exchangestr->buf,"jumblr") == 0 || strcmp(exchangestr->buf,"pangea") == 0 )
{
if ( strcmp(exchangestr->buf,"pangea") == 0 )
{
if ( juint(json,"rakemillis") != 0 )
iQ->s.minperc = juint(json,"rakemillis");
if ( j64bits(json,"bigblind") != 0 )
{
iQ->s.baseamount = j64bits(json,"bigblind");
iQ->s.vol = ((double)iQ->s.baseamount / SATOSHIDEN);
}
if ( j64bits(json,"ante") != 0 )
iQ->s.relamount = j64bits(json,"ante");
iQ->s.minbuyin = juint(json,"minbuyin");
iQ->s.maxbuyin = juint(json,"maxbuyin");
/*if ( (iQ->s.maxrake= j64bits(json,"maxrake")) != 0 )
{
if ( strcmp(base->buf,"BTC") == 0 && iQ->s.maxrake < SATOSHIDEN/10 )
iQ->s.maxrake = SATOSHIDEN/10;
else if ( iQ->s.maxrake < 10*SATOSHIDEN )
iQ->s.maxrake = 10*SATOSHIDEN;
}*/
}
if ( iQ->s.price == 0. )
iQ->s.price = 1.;
if ( iQ->s.vol == 0. )
iQ->s.vol = 1.;
if ( iQ->s.baseamount == 0 )
iQ->s.baseamount = iQ->s.vol * SATOSHIDEN;
if ( localaccess != 0 && strcmp(exchangestr->buf,"jumblr") == 0 )
{
#ifdef later
struct coin777 *coin; int32_t maxamount;
if ( (coin= coin777_find(base->buf,0)) != 0 )
{
if ( coin->jvin == 0 && coin->jvinaddr[0] == 0 )
{
coin->jvin = -1;
printf("initial state for jumblr.%s detected\n",coin->name);
sleep(5);
}
if ( coin->jvin < 0 )
{
printf("no %s unspents available for jumblr/pangea jvin.%d %.8f\n",coin->name,coin->jvin,dstr(coin->junspent));
return(-1);
}
maxamount = coin->junspent - coin->mgw.txfee*2 - (coin->junspent>>10);
if ( iQ->s.baseamount > maxamount )
iQ->s.baseamount = maxamount;
else if ( iQ->s.baseamount < coin->mgw.txfee )
{
printf("jumblr/pangea amount %.8f less than txfee %.8f\n",dstr(iQ->s.baseamount),dstr(coin->mgw.txfee));
return(-1);
}
}
else
{
printf("%s not initialized for jumblr\n",base->buf);
return(-1);
}
#endif
}
}
else
{
if ( iQ->s.baseamount == 0 || iQ->s.relamount == 0 )
{
if ( iQ->s.price <= SMALLVAL || iQ->s.vol <= SMALLVAL )
return(-1);
set_best_amounts(&iQ->s.baseamount,&iQ->s.relamount,iQ->s.price,iQ->s.vol);
}
}
if ( iQ->s.quoteid == 0 )
iQ->s.quoteid = calc_quoteid(iQ);
else if ( iQ->s.quoteid != calc_quoteid(iQ) )
{
printf("bidask_parse quoteid.%llu != calc.%llu\n",(long long)iQ->s.quoteid,(long long)calc_quoteid(iQ));
return(-1);
}
if ( iQ->s.price > SMALLVAL && iQ->s.vol > SMALLVAL && iQ->s.baseid != 0 && iQ->s.relid != 0 )
{
buf[0] = 0, _set_assetname(&basemult,buf,0,iQ->s.baseid);
printf("baseid.%llu -> %s mult.%llu\n",(long long)iQ->s.baseid,buf,(long long)basemult);
buf[0] = 0, _set_assetname(&relmult,buf,0,iQ->s.relid);
printf("relid.%llu -> %s mult.%llu\n",(long long)iQ->s.relid,buf,(long long)relmult);
//basemult = get_assetmult(iQ->baseid), relmult = get_assetmult(iQ->relid);
baseamount = (iQ->s.baseamount + basemult/2) / basemult, baseamount *= basemult;
relamount = (iQ->s.relamount + relmult/2) / relmult, relamount *= relmult;
if ( iQ->s.price != 0. && iQ->s.vol != 0 )
{
price = prices777_price_volume(&volume,baseamount,relamount);
if ( fabs(iQ->s.price - price)/price > 0.001 )
{
printf("cant create accurate price ref.(%f %f) -> (%f %f)\n",iQ->s.price,iQ->s.vol,price,volume);
return(-1);
}
}
}
return(0);
}
char *InstantDEX(char *jsonstr,char *remoteaddr,int32_t localaccess)
{
char *prices777_allorderbooks();
char *InstantDEX_tradehistory(cJSON *json,int32_t firsti,int32_t endi);
char *InstantDEX_cancelorder(cJSON *json,char *activenxt,char *secret,uint64_t sequenceid,uint64_t quoteid);
struct destbuf exchangestr,method,gui,name,base,rel; double balance;
char *retstr = 0,key[512],retbuf[1024],*activenxt,*secret,*coinstr; struct InstantDEX_quote iQ; struct exchange_info *exchange;
cJSON *json; uint64_t assetbits,sequenceid; uint32_t maxdepth; int32_t invert=0,keysize,allfields; struct prices777 *prices = 0;
//printf("INSTANTDEX.(%s)\n",jsonstr);
//if ( INSTANTDEX.readyflag == 0 )
// return(0);
if ( jsonstr != 0 && (json= cJSON_Parse(jsonstr)) != 0 )
{
// test: asset/asset, asset/external, external/external, autofill and automatch
// peggy integration
if ( bidask_parse(localaccess,&exchangestr,&name,&base,&rel,&gui,&iQ,json) < 0 && (strcmp(exchangestr.buf,"jumblr") == 0 || strcmp(exchangestr.buf,"pangea") == 0) )
{
//return(clonestr("{\"error\":\"invalid parameters\"}"));
}
if ( iQ.s.offerNXT == 0 )
iQ.s.offerNXT = IGUANA_MY64BITS;
printf("isask.%d base.(%s) rel.(%s)\n",iQ.s.isask,base.buf,rel.buf);
copy_cJSON(&method,jobj(json,"method"));
if ( (sequenceid= j64bits(json,"orderid")) == 0 )
sequenceid = j64bits(json,"sequenceid");
allfields = juint(json,"allfields");
if ( (maxdepth= juint(json,"maxdepth")) <= 0 )
maxdepth = MAX_DEPTH;
if ( exchangestr.buf[0] == 0 )
{
if ( iQ.s.baseid != 0 && iQ.s.relid != 0 )
strcpy(exchangestr.buf,"nxtae");
else strcpy(exchangestr.buf,"basket");
}
assetbits = InstantDEX_name(key,&keysize,exchangestr.buf,name.buf,base.buf,&iQ.s.baseid,rel.buf,&iQ.s.relid);
//printf("2nd isask.%d base.(%s) rel.(%s)\n",iQ.s.isask,base.buf,rel.buf);
exchange = exchange_find(exchangestr.buf);
secret = jstr(json,"secret"), activenxt = jstr(json,"activenxt");
if ( secret == 0 )
{
secret = IGUANA_NXTACCTSECRET;
activenxt = IGUANA_NXTADDR;
}
if ( strcmp(method.buf,"exit") == 0 )
{
printf("getchar and then exit\n");
getchar();
exit(0);
}
if ( strcmp(method.buf,"orderstatus") == 0 )
retstr = InstantDEX_orderstatus(json,sequenceid,iQ.s.quoteid);
else if ( strcmp(method.buf,"cancelorder") == 0 )
retstr = InstantDEX_cancelorder(json,jstr(json,"activenxt"),jstr(json,"secret"),sequenceid,iQ.s.quoteid);
else if ( strcmp(method.buf,"openorders") == 0 )
retstr = InstantDEX_openorders(json,IGUANA_NXTADDR,juint(json,"allorders"));
else if ( strcmp(method.buf,"tradehistory") == 0 )
retstr = InstantDEX_tradehistory(json,juint(json,"firsti"),juint(json,"endi"));
else if ( strcmp(method.buf,"withdraw") == 0 )
retstr = InstantDEX_withdraw(json);
else if ( strcmp(method.buf,"balance") == 0 )
{
if ( exchange != 0 && exchange->issue.trade != 0 )
{
if ( exchange->issue.balances != 0 )
{
if ( exchange->balancejson != 0 )
free_json(exchange->balancejson), exchange->balancejson = 0;
exchange->lastbalancetime = (uint32_t)time(NULL);
if ( (exchange->balancejson= (*exchange->issue.balances)(&exchange->cHandle,exchange)) != 0 )
{
if ( (coinstr= jstr(json,"base")) != 0 )
retstr = (*exchange->issue.parsebalance)(exchange,&balance,coinstr);
else retstr = jprint(exchange->balancejson,0);
} else retstr = clonestr("{\"error\":\"balances null return\"}");
} else retstr = clonestr("{\"error\":\"no balances function\"}");
} else retstr = clonestr("{\"error\":\"cant find exchange trade or balances function\"}");
printf("%s ptr.%p trade.%p\n",exchangestr.buf,exchange,exchange!=0?exchange->issue.trade:0);
}
else if ( strcmp(method.buf,"allorderbooks") == 0 )
retstr = prices777_allorderbooks();
else if ( strcmp(method.buf,"allexchanges") == 0 )
retstr = jprint(exchanges_json(),1);
else if ( strcmp(method.buf,"lottostats") == 0 )
retstr = jprint(InstantDEX_lottostats(),1);
/* else if ( strcmp(method.buf,"tradesequence") == 0 )
{
//printf("call tradesequence.(%s)\n",jsonstr);
int32_t dotrade,numtrades; struct prices777_order trades[256]; struct pending_trade *pend;
dotrade = juint(json,"dotrade");
retstr = InstantDEX_tradesequence(0,0,0,&numtrades,trades,(int32_t)(sizeof(trades)/sizeof(*trades)),dotrade,activenxt,secret,json);
if ( dotrade != 0 )
{
pend = calloc(1,sizeof(*pend));
pend->dir = iQ.s.isask == 0 ? 1 : -1, pend->price = iQ.s.price, pend->volume = iQ.s.vol, pend->orderid = iQ.s.quoteid;
pend->tradesjson = json;
pend->type = 'S';
pend->timestamp = (uint32_t)time(NULL);
//InstantDEX_history(0,pend,0);
queue_enqueue("PendingQ",&Pending_offersQ.pingpong[0],&pend->DL,0);
}
}*/
else if ( strcmp(method.buf,"makebasket") == 0 )
{
if ( (prices= prices777_makebasket(0,json,1,"basket",0,0)) != 0 )
retstr = clonestr("{\"result\":\"basket made\"}");
else retstr = clonestr("{\"error\":\"couldnt make basket\"}");
}
else if ( strcmp(method.buf,"peggyrates") == 0 )
{
//if ( SUPERNET.peggy != 0 )
// retstr = peggyrates(juint(json,"timestamp"),jstr(json,"name"));
//else retstr = clonestr("{\"error\":\"peggy disabled\"}");
}
else if ( strcmp(method.buf,"LSUM") == 0 )
{
sprintf(retbuf,"{\"result\":\"%s\",\"amount\":%d}",(rand() & 1) ? "BUY" : "SELL",(rand() % 100) * 100000);
retstr = clonestr(retbuf);
}
else if ( strcmp(method.buf,"placebid") == 0 || strcmp(method.buf,"placeask") == 0 )
return(InstantDEX_placebidask(0,sequenceid,exchangestr.buf,name.buf,base.buf,rel.buf,&iQ,jstr(json,"extra"),secret,activenxt,json));
else if ( strcmp(exchangestr.buf,"active") == 0 && strcmp(method.buf,"orderbook") == 0 )
retstr = prices777_activebooks(name.buf,base.buf,rel.buf,iQ.s.baseid,iQ.s.relid,maxdepth,allfields,strcmp(exchangestr.buf,"active") == 0 || juint(json,"tradeable"));
else if ( (prices= prices777_find(&invert,iQ.s.baseid,iQ.s.relid,exchangestr.buf)) == 0 )
{
if ( (prices= prices777_poll(exchangestr.buf,name.buf,base.buf,iQ.s.baseid,rel.buf,iQ.s.relid)) != 0 )
{
if ( prices777_equiv(prices->baseid) == prices777_equiv(iQ.s.baseid) && prices777_equiv(prices->relid) == prices777_equiv(iQ.s.relid) )
invert = 0;
else if ( prices777_equiv(prices->baseid) == prices777_equiv(iQ.s.relid) && prices777_equiv(prices->relid) == prices777_equiv(iQ.s.baseid) )
invert = 1;
else invert = 0, printf("baserel not matching (%s %s) %llu %llu vs (%s %s) %llu %llu\n",prices->base,prices->rel,(long long)prices->baseid,(long long)prices->relid,base.buf,rel.buf,(long long)iQ.s.baseid,(long long)iQ.s.relid);
}
}
if ( retstr == 0 && prices != 0 )
{
if ( strcmp(method.buf,"disablequotes") == 0 )
{
if ( prices != 0 )
{
if ( strcmp(prices->exchange,"unconf") == 0 )
return(clonestr("{\"error\":\"cannot disable unconf\"}"));
prices->disabled = 1;
return(clonestr("{\"result\":\"success\"}"));
}
else return(clonestr("{\"error\":\"no prices to disable\"}"));
}
else if ( strcmp(method.buf,"enablequotes") == 0 )
{
if ( prices != 0 )
{
prices->disabled = 0;
return(clonestr("{\"result\":\"success\"}"));
}
else return(clonestr("{\"error\":\"no prices to enable\"}"));
}
else if ( strcmp(method.buf,"orderbook") == 0 )
{
if ( maxdepth < MAX_DEPTH )
return(prices777_orderbook_jsonstr(invert,IGUANA_MY64BITS,prices,&prices->O,maxdepth,allfields));
else if ( (retstr= prices->orderbook_jsonstrs[invert][allfields]) == 0 )
{
retstr = prices777_orderbook_jsonstr(invert,IGUANA_MY64BITS,prices,&prices->O,MAX_DEPTH,allfields);
portable_mutex_lock(&prices->mutex);
if ( prices->orderbook_jsonstrs[invert][allfields] != 0 )
free(prices->orderbook_jsonstrs[invert][allfields]);
prices->orderbook_jsonstrs[invert][allfields] = retstr;
portable_mutex_unlock(&prices->mutex);
if ( retstr == 0 )
retstr = clonestr("{}");
}
if ( retstr != 0 )
retstr = clonestr(retstr);
}
//else if ( strcmp(method.buf,"tradebot") == 0 )
// retstr = InstantDEX_tradebot(prices,json,&iQ,invert);
}
//if ( Debuglevel > 2 )
printf("(%s) %p exchange.(%s) base.(%s) %llu rel.(%s) %llu | name.(%s) %llu\n",retstr!=0?retstr:"",prices,exchangestr.buf,base.buf,(long long)iQ.s.baseid,rel.buf,(long long)iQ.s.relid,name.buf,(long long)assetbits);
}
return(retstr);
}
char *bidask_func(int32_t localaccess,int32_t valid,char *sender,cJSON *json,char *origargstr)
{
struct destbuf gui,exchangestr,name,base,rel,offerNXT; struct InstantDEX_quote iQ;
copy_cJSON(&offerNXT,jobj(json,"offerNXT"));
//printf("got (%s)\n",origargstr);
if ( strcmp(IGUANA_NXTADDR,offerNXT.buf) != 0 )
{
if ( bidask_parse(localaccess,&exchangestr,&name,&base,&rel,&gui,&iQ,json) == 0 )
return(InstantDEX_placebidask(sender,j64bits(json,"orderid"),exchangestr.buf,name.buf,base.buf,rel.buf,&iQ,jstr(json,"extra"),jstr(json,"secret"),jstr(json,"activenxt"),json));
else printf("error with incoming bidask\n");
} else fprintf(stderr,"got my bidask from network (%s)\n",origargstr);
return(clonestr("{\"result\":\"got loopback bidask\"}"));
}

223
InstantDEX/InstantDEX_quote.h

@ -0,0 +1,223 @@
//
// sha256.h
// crypto777
//
// Created by James on 4/9/15.
// Copyright (c) 2015 jl777. All rights reserved.
//
#ifndef crypto777_InstantDEX_quote_h
#define crypto777_InstantDEX_quote_h
#include <stdint.h>
#include "../includes/uthash.h"
#define NXT_ASSETID ('N' + ((uint64_t)'X'<<8) + ((uint64_t)'T'<<16)) // 5527630
#define MAX_BUYNXT 10
#define MIN_NQTFEE 100000000
#define NXT_TOKEN_LEN 160
#define GENESISACCT "1739068987193023818" // NXT-MRCC-2YLS-8M54-3CMAJ
#define GENESISPUBKEYSTR "1259ec21d31a30898d7cd1609f80d9668b4778e3d97e941044b39f0c44d2e51b"
#define GENESISPRIVKEYSTR "1259ec21d31a30898d7cd1609f80d9668b4778e3d97e941044b39f0c44d2e51b"
#define GENESIS_SECRET "It was a bright cold day in April, and the clocks were striking thirteen."
#define GENESISBLOCK "2680262203532249785"
#define NXT_GENESISTIME 1385294400
#define DEFAULT_NXT_DEADLINE 720
#define issue_curl(cmdstr) bitcoind_RPC(0,"curl",cmdstr,0,0,0)
#define issue_NXT(cmdstr) bitcoind_RPC(0,"NXT",cmdstr,0,0,0)
#define issue_NXTPOST(cmdstr) bitcoind_RPC(0,"curl",NXTAPIURL,0,0,cmdstr)
#define fetch_URL(url) bitcoind_RPC(0,"fetch",url,0,0,0)
#define INSTANTDEX_TRIGGERDEADLINE 120
#define _issue_curl(curl_handle,label,url) bitcoind_RPC(curl_handle,label,url,0,0,0)
#define ORDERBOOK_EXPIRATION 3600
#define INSTANTDEX_MINVOL 75
#define INSTANTDEX_MINVOLPERC ((double)INSTANTDEX_MINVOL / 100.)
#define INSTANTDEX_PRICESLIPPAGE 0.001
#define INSTANTDEX_TRIGGERDEADLINE 120
#define JUMPTRADE_SECONDS 100
#define INSTANTDEX_ACCT "4383817337783094122"
#define INSTANTDEX_FEE ((long)(2.5 * SATOSHIDEN))
#define INSTANTDEX_NAME "InstantDEX"
#define INSTANTDEX_NXTAENAME "nxtae"
#define INSTANTDEX_NXTAEUNCONF "unconf"
#define INSTANTDEX_BASKETNAME "basket"
#define INSTANTDEX_ACTIVENAME "active"
#define INSTANTDEX_EXCHANGEID 0
#define INSTANTDEX_UNCONFID 1
#define INSTANTDEX_NXTAEID 2
#define MAX_EXCHANGES 64
#define ORDERBOOK_EXPIRATION 3600
#define NXT_ASSETID ('N' + ((uint64_t)'X'<<8) + ((uint64_t)'T'<<16)) // 5527630
#define BTC_ASSETID ('B' + ((uint64_t)'T'<<8) + ((uint64_t)'C'<<16)) // 4412482
#define LTC_ASSETID ('L' + ((uint64_t)'T'<<8) + ((uint64_t)'C'<<16))
#define PPC_ASSETID ('P' + ((uint64_t)'P'<<8) + ((uint64_t)'C'<<16))
#define NMC_ASSETID ('N' + ((uint64_t)'M'<<8) + ((uint64_t)'C'<<16))
#define DASH_ASSETID ('D' + ((uint64_t)'A'<<8) + ((uint64_t)'S'<<16) + ((uint64_t)'H'<<24))
#define BTCD_ASSETID ('B' + ((uint64_t)'T'<<8) + ((uint64_t)'C'<<16) + ((uint64_t)'D'<<24))
#define USD_ASSETID ('U' + ((uint64_t)'S'<<8) + ((uint64_t)'D'<<16))
#define CNY_ASSETID ('C' + ((uint64_t)'N'<<8) + ((uint64_t)'Y'<<16))
#define EUR_ASSETID ('E' + ((uint64_t)'U'<<8) + ((uint64_t)'R'<<16))
#define RUR_ASSETID ('R' + ((uint64_t)'U'<<8) + ((uint64_t)'R'<<16))
struct InstantDEX_shared
{
double price,vol;
uint64_t quoteid,offerNXT,basebits,relbits,baseid,relid; int64_t baseamount,relamount;
uint32_t timestamp;
uint16_t duration:14,wallet:1,a:1,isask:1,expired:1,closed:1,swap:1,responded:1,matched:1,feepaid:1,automatch:1,pending:1,minperc:7;
uint16_t minbuyin,maxbuyin;
};
struct InstantDEX_quote
{
UT_hash_handle hh;
struct InstantDEX_shared s; // must be here
char exchangeid,gui[9],base[8],rel[8];
char walletstr[];
};
struct InstantDEX_quote *delete_iQ(uint64_t quoteid);
struct InstantDEX_quote *find_iQ(uint64_t quoteid);
struct InstantDEX_quote *create_iQ(struct InstantDEX_quote *iQ,char *walletstr);
uint64_t calc_quoteid(struct InstantDEX_quote *iQ);
cJSON *set_walletstr(cJSON *walletitem,char *walletstr,struct InstantDEX_quote *iQ);
cJSON *InstantDEX_specialorders(uint64_t *quoteidp,uint64_t nxt64bits,char *base,char *special,uint64_t baseamount,int32_t addrtype);
int32_t bidask_parse(int32_t localaccess,struct destbuf *exchangestr,struct destbuf *name,struct destbuf *base,struct destbuf *rel,struct destbuf *gui,struct InstantDEX_quote *iQ,cJSON *json);
int32_t coin777_addrtype(uint8_t *p2shtypep,char *coinstr);
struct prices777_order
{
struct InstantDEX_shared s; cJSON *retitem; struct prices777 *source; struct pending_trade *pend;
uint64_t id; double wt,ratio; uint16_t slot_ba;
};
struct prices777_basket
{
struct prices777 *prices; double wt;
int32_t groupid,groupsize,aski,bidi;
char base[64],rel[64];
};
struct prices777_orderentry { struct prices777_order bid,ask; };
#define MAX_GROUPS 8
#define _MAX_DEPTH 100
struct prices777_basketinfo
{
int32_t numbids,numasks; uint32_t timestamp;
struct prices777_orderentry book[MAX_GROUPS+1][_MAX_DEPTH];
};
struct NXTtx { uint64_t txid; char fullhash[MAX_JSON_FIELD],utxbytes[MAX_JSON_FIELD],utxbytes2[MAX_JSON_FIELD],txbytes[MAX_JSON_FIELD],sighash[MAX_JSON_FIELD]; };
struct pending_trade
{
struct queueitem DL;
struct NXTtx trigger; struct prices777_order order;
uint64_t triggertxid,txid,quoteid,orderid,my64bits;
struct prices777 *prices; void *cHandlep; struct exchange_info *exchange; void *bot;
char *triggertx,*txbytes,extra[128]; uint8_t nxtsecret[2048]; cJSON *tradesjson,*item;
double price,volume; uint32_t timestamp,finishtime,expiration;
int32_t dir,type,version,size,dotrade,queueflag,*curlingp;
};
struct prices777
{
char url[512],exchange[64],base[64],rel[64],lbase[64],lrel[64],key[512],oppokey[512],contract[64],origbase[64],origrel[64];
uint64_t contractnum,ap_mult,baseid,relid,basemult,relmult; double lastupdate,decay,oppodecay,lastprice,lastbid,lastask;
uint32_t pollnxtblock,exchangeid,numquotes,updated,lasttimestamp,RTflag,disabled,dirty; int32_t keysize,oppokeysize;
portable_mutex_t mutex;
char *orderbook_jsonstrs[2][2];
struct prices777_basketinfo O,O2; double groupwts[MAX_GROUPS + 1];
uint8_t changed,type; uint8_t **dependents; int32_t numdependents,numgroups,basketsize; double commission;
void *tradebot;
struct prices777_basket basket[];
};
struct exchange_info;
struct exchange_funcs
{
char *exchange;
double (*update)(struct prices777 *prices,int32_t maxdepth);
int32_t (*supports)(char *base,char *rel);
uint64_t (*trade)(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume);
char *(*orderstatus)(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid);
char *(*cancelorder)(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid);
char *(*openorders)(void **cHandlep,struct exchange_info *exchange,cJSON *argjson);
char *(*tradehistory)(void **cHandlep,struct exchange_info *exchange,cJSON *argjson);
cJSON *(*balances)(void **cHandlep,struct exchange_info *exchange);
char *(*parsebalance)(struct exchange_info *exchange,double *balancep,char *coinstr);
char *(*withdraw)(void **cHandlep,struct exchange_info *exchange,cJSON *argjson);
};
#define EXCHANGE_FUNCS(xchg,name) { name, prices777_ ## xchg, xchg ## _supports, xchg ## _trade, xchg ## _orderstatus, xchg ## _cancelorder, xchg ## _openorders, xchg ## _tradehistory, xchg ## _balances, xchg ## _parsebalance, xchg ## _withdraw }
struct exchange_info
{
struct exchange_funcs issue;
char name[16],apikey[MAX_JSON_FIELD],apisecret[MAX_JSON_FIELD],userid[MAX_JSON_FIELD];
cJSON *balancejson;
uint32_t num,exchangeid,pollgap,refcount,polling,lastbalancetime;
uint64_t nxt64bits,lastnonce; double lastupdate,commission;
void *cHandle;
portable_mutex_t mutex;
};
#define calc_predisplinex(startweekind,clumpsize,weekind) (((weekind) - (startweekind))/(clumpsize))
#define _extrapolate_Spline(Splines,gap) ((double)(Splines)[0] + ((gap) * ((double)(Splines)[1] + ((gap) * ((double)(Splines)[2] + ((gap) * (double)(Splines)[3]))))))
#define _extrapolate_Slope(Splines,gap) ((double)(Splines)[1] + ((gap) * ((double)(Splines)[2] + ((gap) * (double)(Splines)[3]))))
#define PRICE_BLEND(oldval,newval,decay,oppodecay) ((oldval == 0.) ? newval : ((oldval * decay) + (oppodecay * newval)))
#define PRICE_BLEND64(oldval,newval,decay,oppodecay) ((oldval == 0) ? newval : ((oldval * decay) + (oppodecay * newval) + 0.499))
struct prices777 *prices777_initpair(int32_t needfunc,char *exchange,char *base,char *rel,double decay,char *name,uint64_t baseid,uint64_t relid,int32_t basketsize);
struct exchange_info *get_exchange(int32_t exchangeid);
char *exchange_str(int32_t exchangeid);
struct exchange_info *exchange_find(char *exchangestr);
void prices777_exchangeloop(void *ptr);
uint64_t InstantDEX_name(char *key,int32_t *keysizep,char *exchange,char *name,char *base,uint64_t *baseidp,char *rel,uint64_t *relidp);
struct prices777 *prices777_find(int32_t *invertedp,uint64_t baseid,uint64_t relid,char *exchange);
struct exchange_info *find_exchange(int32_t *exchangeidp,char *exchangestr);
double prices777_InstantDEX(struct prices777 *prices,int32_t maxdepth);
uint64_t prices777_equiv(uint64_t assetid);
char *prices777_trade(int32_t *curlingp,void *bot,struct pending_trade **pendp,void **cHandlep,int32_t dotrade,cJSON *item,char *activenxt,char *secret,struct prices777 *prices,int32_t dir,double price,double volume,struct InstantDEX_quote *iQ,struct prices777_order *order,uint64_t orderid,char *extra);
double prices777_price_volume(double *volumep,uint64_t baseamount,uint64_t relamount);
struct prices777 *prices777_poll(char *exchangestr,char *name,char *base,uint64_t refbaseid,char *rel,uint64_t refrelid);
void set_best_amounts(int64_t *baseamountp,int64_t *relamountp,double price,double volume);
int32_t _set_assetname(uint64_t *multp,char *buf,char *jsonstr,uint64_t assetid);
char *InstantDEX_withdraw(cJSON *argjson);
cJSON *exchanges_json();
char *InstantDEX_tradesequence(int32_t curlings[],void *bot,void *cHandles[],int32_t *nump,struct prices777_order *trades,int32_t maxtrades,int32_t dotrade,char *activenxt,char *secret,cJSON *json);
struct prices777 *prices777_makebasket(char *basketstr,cJSON *_basketjson,int32_t addbasket,char *typestr,struct prices777 *ptrs[],int32_t num);
char *prices777_activebooks(char *name,char *_base,char *_rel,uint64_t baseid,uint64_t relid,int32_t maxdepth,int32_t allflag,int32_t tradeable);
char *prices777_orderbook_jsonstr(int32_t invert,uint64_t nxt64bits,struct prices777 *prices,struct prices777_basketinfo *OB,int32_t maxdepth,int32_t allflag);
int32_t get_assetname(char *name,uint64_t assetid);
int32_t is_mscoin(char *assetidstr);
uint32_t _get_NXTheight(uint32_t *firsttimep);
char *fill_nxtae(int32_t dotrade,uint64_t *txidp,uint64_t nxt64bits,char *secret,int32_t dir,double price,double volume,uint64_t baseid,uint64_t relid);
uint64_t get_assetmult(uint64_t assetid);
int32_t InstantDEX_verify(uint64_t destNXTaddr,uint64_t sendasset,uint64_t sendqty,cJSON *txobj,uint64_t recvasset,uint64_t recvqty);
int32_t verify_NXTtx(cJSON *json,uint64_t refasset,uint64_t qty,uint64_t destNXTbits);
uint64_t assetmult(char *assetidstr);
int64_t get_asset_quantity(int64_t *unconfirmedp,char *NXTaddr,char *assetidstr);
uint64_t calc_asset_qty(uint64_t *availp,uint64_t *priceNQTp,char *NXTaddr,int32_t checkflag,uint64_t assetid,double price,double vol);
cJSON *InstantDEX_orderbook(struct prices777 *prices);
char *hmac_sha512_str(char dest[(512>>3)*2 + 1],char *key,unsigned int key_size,char *message);
char *hmac_sha384_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_sha1_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_sha256_str(char *dest,char *key,int32_t key_size,char *message);
extern uint32_t MAX_DEPTH;
extern char NXTAPIURL[],IGUANA_NXTACCTSECRET[],IGUANA_NXTADDR[];
extern int32_t FIRST_EXTERNAL,IGUANA_disableNXT,Debuglevel,prices777_NXTBLOCK;
extern uint64_t IGUANA_MY64BITS;
#endif

47
InstantDEX/Makefile

@ -0,0 +1,47 @@
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# GNU Makefile based on shared rules provided by the Native Client SDK.
# See README.Makefiles for more details.
VALID_TOOLCHAINS := pnacl newlib glibc clang-newlib mac
NACL_SDK_ROOT ?= $(abspath $(CURDIR))
TARGET = InstantDEX
EXTRA= -D__PNACL
include $(NACL_SDK_ROOT)/tools/common.mk
CHROME_ARGS += --allow-nacl-socket-api=127.0.0.1
DEPS = nacl_io
LIBS = crypto777 curl ssl crypto z glibc-compat nacl_spawn ppapi nacl_io ppapi_simple # cli_main ppapi_cpp ppapi_simple
CFLAGS = -Wall -D__PNACL -fno-strict-aliasing $(EXTRA)
LFLAGS = libs
SOURCES = main.c InstantDEX.c
# Build rules generated by macros from common.mk:
$(foreach dep,$(DEPS),$(eval $(call DEPEND_RULE,$(dep))))
$(foreach src,$(SOURCES),$(eval $(call COMPILE_RULE,$(src),$(CFLAGS))))
# The PNaCl workflow uses both an unstripped and finalized/stripped binary.
# On NaCl, only produce a stripped binary for Release configs (not Debug).
ifneq (,$(or $(findstring pnacl,$(TOOLCHAIN)),$(findstring Release,$(CONFIG))))
$(eval $(call LINK_RULE,$(TARGET)_unstripped,$(SOURCES) $(LOCALLIBS),$(LIBS),$(DEPS)));
$(eval $(call STRIP_RULE,$(TARGET),$(TARGET)_unstripped))
else
$(eval $(call LINK_RULE,$(TARGET),$(SOURCES),$(LIBS),$(DEPS)))
endif
$(eval $(call NMF_RULE,$(TARGET),))

1407
InstantDEX/exchange_trades.h

File diff suppressed because it is too large

1208
InstantDEX/exchangeparse.h

File diff suppressed because it is too large

259
InstantDEX/exchanges/bitfinex.c

@ -0,0 +1,259 @@
/******************************************************************************
* Copyright © 2014-2015 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 EXCHANGE_NAME "bitfinex"
#define UPDATE prices777_ ## bitfinex
#define SUPPORTS bitfinex ## _supports
#define SIGNPOST bitfinex ## _signpost
#define TRADE bitfinex ## _trade
#define ORDERSTATUS bitfinex ## _orderstatus
#define CANCELORDER bitfinex ## _cancelorder
#define OPENORDERS bitfinex ## _openorders
#define TRADEHISTORY bitfinex ## _tradehistory
#define BALANCES bitfinex ## _balances
#define PARSEBALANCE bitfinex ## _parsebalance
#define WITHDRAW bitfinex ## _withdraw
#define CHECKBALANCE bitfinex ## _checkbalance
double UPDATE(struct prices777 *prices,int32_t maxdepth)
{
if ( prices->url[0] == 0 )
sprintf(prices->url,"https://api.bitfinex.com/v1/book/%s%s",prices->base,prices->rel);
return(prices777_standard(EXCHANGE_NAME,prices->url,prices,"price","amount",maxdepth,0));
}
int32_t SUPPORTS(char *base,char *rel)
{
char *baserels[][2] = { {"btc","usd"}, {"ltc","usd"}, {"ltc","btc"} };
return(baserel_polarity(baserels,(int32_t)(sizeof(baserels)/sizeof(*baserels)),base,rel));
}
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr)
{
//[[{"type":"deposit","currency":"btc","amount":"0.0","available":"0.0"},{"type":"deposit","currency":"usd","amount":"0.0","available":"0.0"},{"type":"exchange","currency":"btc","amount":"0.01065851","available":"0.01065851"},{"type":"exchange","currency":"usd","amount":"23386.37278962","available":"0.00378962"},{"type":"trading","currency":"btc","amount":"0.0","available":"0.0"},{"type":"trading","currency":"usd","amount":"0.0","available":"0.0"}]]
int32_t i,n,ind; char field[64],*str,*typestr,*itemstr = 0; cJSON *item,*obj,*array; double amounts[3],avail[3],val0,val1;
*balancep = 0.;
strcpy(field,coinstr), tolowercase(field);
memset(amounts,0,sizeof(amounts));
memset(avail,0,sizeof(avail));
if ( exchange->balancejson != 0 && is_cJSON_Array(exchange->balancejson) != 0 && (n= cJSON_GetArraySize(exchange->balancejson)) > 0 )
{
for (i=0; i<n; i++)
{
if ( (item= jitem(exchange->balancejson,i)) != 0 )
{
if ( (str= jstr(item,"currency")) != 0 && strcmp(field,str) == 0 )
{
val0 = jdouble(item,"amount");
val1 = jdouble(item,"available");
if ( (typestr= jstr(item,"type")) != 0 )
{
if ( strcmp(typestr,"deposit") == 0 )
ind = 0;
else if ( strcmp(typestr,"exchange") == 0 )
ind = 1;
else if ( strcmp(typestr,"trading") == 0 )
ind = 2;
else ind = -1;
if ( ind >= 0 )
{
amounts[ind] = val0;
avail[ind] = val1;
}
}
}
}
}
if ( (obj= cJSON_CreateObject()) != 0 )
{
touppercase(field);
*balancep = avail[0] + avail[1] + avail[2];
jaddstr(obj,"base",field);
jaddnum(obj,"balance",*balancep);
jaddnum(obj,"total",amounts[0]+amounts[1]+amounts[2]);
array = cJSON_CreateArray(), jaddinum(array,avail[0]), jaddinum(array,amounts[0]), jadd(obj,"deposit",array);
array = cJSON_CreateArray(), jaddinum(array,avail[1]), jaddinum(array,amounts[1]), jadd(obj,"exchange",array);
array = cJSON_CreateArray(), jaddinum(array,avail[2]), jaddinum(array,amounts[2]), jadd(obj,"trading",array);
itemstr = jprint(obj,1);
}
}
if ( itemstr == 0 )
return(clonestr("{\"error\":\"cant find coin balance\"}"));
return(itemstr);
}
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *payload,char *method)
{
char dest[1025],url[1024],hdr1[512],hdr2[512],hdr3[512],hdr4[512],req[1024],*sig,*data = 0; cJSON *json;
hdr1[0] = hdr2[0] = hdr3[0] = hdr4[0] = 0;
json = 0;
nn_base64_encode((void *)payload,strlen(payload),req,sizeof(req));
if ( (sig= hmac_sha384_str(dest,exchange->apisecret,(int32_t)strlen(exchange->apisecret),req)) != 0 )
{
sprintf(hdr1,"X-BFX-APIKEY:%s",exchange->apikey);
sprintf(hdr2,"X-BFX-PAYLOAD:%s",req);
sprintf(hdr3,"X-BFX-SIGNATURE:%s",sig);
//printf("req.(%s) H0.(%s) H1.(%s) H2.(%s)\n",req,hdr1,hdr2,hdr3);
sprintf(url,"https://api.bitfinex.com/v1/%s",method);
if ( dotrade == 0 )
data = exchange_would_submit(req,hdr1,hdr2,hdr3,hdr4);
else if ( (data= curl_post(cHandlep,url,0,req,hdr1,hdr2,hdr3,hdr4)) != 0 )
json = cJSON_Parse(data);
if ( retstrp != 0 )
*retstrp = data;
else if ( data != 0 )
free(data);
}
return(json);
}
cJSON *BALANCES(void **cHandlep,struct exchange_info *exchange)
{
char payload[1024],*method;
method = "balances";
sprintf(payload,"{\"request\":\"/v1/%s\",\"nonce\":\"%llu\"}",method,(long long)exchange_nonce(exchange));
return(SIGNPOST(cHandlep,1,0,exchange,payload,method));
}
#include "checkbalance.c"
uint64_t TRADE(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume)
{
char payload[1024],pairstr[512],*typestr,*method,*extra; cJSON *json; uint64_t txid = 0;
if ( (extra= *retstrp) != 0 )
*retstrp = 0;
if ( (dir= flipstr_for_exchange(exchange,pairstr,"%s%s",dir,&price,&volume,base,rel)) == 0 )
{
printf("cant find baserel (%s/%s)\n",base,rel);
return(0);
}
method = "order/new";
//Either "market" / "limit" / "stop" / "trailing-stop" / "fill-or-kill" / "exchange market" / "exchange limit" / "exchange stop" / "exchange trailing-stop" / "exchange fill-or-kill". (type starting by "exchange " are exchange orders, others are margin trading orders)
if ( (typestr= extra) == 0 )
typestr = "exchange limit";
sprintf(payload,"{\"request\":\"/v1/%s\",\"nonce\":\"%llu\",\"exchange\":\"bitfinex\",\"side\":\"%s\",\"type\":\"%s\",\"price\":\"%.8f\",\"amount\":\"%.8f\",\"symbol\":\"%s\"}",method,(long long)exchange_nonce(exchange),dir>0?"buy":"sell",typestr,price,volume,pairstr);
if ( CHECKBALANCE(retstrp,dotrade,exchange,dir,base,rel,price,volume) == 0 && (json= SIGNPOST(cHandlep,dotrade,retstrp,exchange,payload,method)) != 0 )
{
if ( (txid= j64bits(json,"order_id")) == 0 )
{
if ( dir != 0 )
printf("bitfinex: no txid error\n");
}
free_json(json);
}
return(txid);
}
char *ORDERSTATUS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char payload[1024],*method,*retstr = 0; cJSON *json;
method = "order/status";
sprintf(payload,"{\"request\":\"/v1/%s\",\"nonce\":\"%llu\",\"order_id\":%llu}",method,(long long)exchange_nonce(exchange),(long long)quoteid);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,method)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized orderstatus
}
char *CANCELORDER(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char payload[1024],*method,*retstr = 0; cJSON *json;
method = "order/cancel";
sprintf(payload,"{\"request\":\"/v1/%s\",\"nonce\":\"%llu\",\"order_id\":%llu}",method,(long long)exchange_nonce(exchange),(long long)quoteid);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,method)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized cancelorder
}
char *OPENORDERS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],*method,*retstr = 0; cJSON *json;
method = "orders";
sprintf(payload,"{\"request\":\"/v1/%s\",\"nonce\":\"%llu\"}",method,(long long)exchange_nonce(exchange));
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,method)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized open orders
}
char *TRADEHISTORY(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],baserel[16],*method,*base,*rel,*retstr = 0; uint32_t timestamp; cJSON *json;
method = "mytrades";
base = jstr(argjson,"base");
rel = jstr(argjson,"rel");
if ( base == 0 || rel == 0 )
{
base = "BTC";
rel = "USD";
}
sprintf(baserel,"%s%s",base,rel);
timestamp = juint(argjson,"start");
sprintf(payload,"{\"request\":\"/v1/%s\",\"nonce\":\"%llu\",\"symbol\":\"%s\",\"timestamp\":%u}",method,(long long)exchange_nonce(exchange),baserel,timestamp);
//printf("TRADEHISTORY.(%s)\n",payload);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,method)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized tradehistory
}
char *WITHDRAW(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],*method,*base,*destaddr,*type,*retstr = 0; cJSON *json; double amount;
amount = jdouble(argjson,"amount");
if ( (destaddr= jstr(argjson,"destaddr")) == 0 || amount < SMALLVAL )
return(clonestr("{\"error\":\"no destaddr specified or amount too small\"}"));
if ( (base= jstr(argjson,"base")) == 0 )
base = "bitcoin";
else if ( strcmp(base,"BTC") == 0 )
base = "bitcoin";
else if ( strcmp(base,"LTC") == 0 )
base = "litecoin";
else if ( strcmp(base,"DRK") == 0 )
base = "darkcoin";
else return(clonestr("{\"error\":\"invalid base specified\"}"));
if ( (type= jstr(argjson,"extra")) == 0 )
type = "exchange";
else if ( strcmp(type,"exchange") != 0 && strcmp(type,"trading") != 0 && strcmp(type,"deposit") != 0 )
return(clonestr("{\"error\":\"invalid wallet type specified\"}"));
method = "withdraw";
sprintf(payload,"{\"request\":\"/v1/%s\",\"nonce\":\"%llu\",\"amount\":\"%.6f\",\"withdraw_type\":\"%s\",\"walletselected\":\"%s\",\"address\":\"%s\"}",method,(long long)exchange_nonce(exchange),amount,base,type,destaddr);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,method)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized withdraw
}
struct exchange_funcs bitfinex_funcs = EXCHANGE_FUNCS(bitfinex,EXCHANGE_NAME);
#undef UPDATE
#undef SUPPORTS
#undef SIGNPOST
#undef TRADE
#undef ORDERSTATUS
#undef CANCELORDER
#undef OPENORDERS
#undef TRADEHISTORY
#undef BALANCES
#undef PARSEBALANCE
#undef WITHDRAW
#undef EXCHANGE_NAME
#undef CHECKBALANCE

170
InstantDEX/exchanges/bitstamp.c

@ -0,0 +1,170 @@
/******************************************************************************
* Copyright © 2014-2015 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 EXCHANGE_NAME "bitstamp"
#define UPDATE prices777_ ## bitstamp
#define SUPPORTS bitstamp ## _supports
#define SIGNPOST bitstamp ## _signpost
#define TRADE bitstamp ## _trade
#define ORDERSTATUS bitstamp ## _orderstatus
#define CANCELORDER bitstamp ## _cancelorder
#define OPENORDERS bitstamp ## _openorders
#define TRADEHISTORY bitstamp ## _tradehistory
#define BALANCES bitstamp ## _balances
#define PARSEBALANCE bitstamp ## _parsebalance
#define WITHDRAW bitstamp ## _withdraw
#define EXCHANGE_AUTHURL "https://www.bitstamp.net/api"
#define CHECKBALANCE bitstamp ## _checkbalance
double UPDATE(struct prices777 *prices,int32_t maxdepth)
{
if ( prices->url[0] == 0 )
sprintf(prices->url,"https://www.bitstamp.net/api/order_book/");
return(prices777_standard("bitstamp",prices->url,prices,0,0,maxdepth,0));
}
int32_t SUPPORTS(char *base,char *rel)
{
char *baserels[][2] = { {"btc","usd"} };
return(baserel_polarity(baserels,(int32_t)(sizeof(baserels)/sizeof(*baserels)),base,rel));
}
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *method,char *payload)
{
/*signature is a HMAC-SHA256 encoded message containing: nonce, customer ID (can be found here) and API key. The HMAC-SHA256 code must be generated using a secret key that was generated with your API key. This code must be converted to it's hexadecimal representation (64 uppercase characters).Example (Python):
message = nonce + customer_id + api_key
signature = hmac.new(API_SECRET, msg=message, digestmod=hashlib.sha256).hexdigest().upper()
key - API key
signature - signature
nonce - nonce
*/
char dest[1025],url[1024],req[1024],hdr1[512],hdr2[512],hdr3[512],hdr4[512],*sig,*data = 0;
cJSON *json; uint64_t nonce;
hdr1[0] = hdr2[0] = hdr3[0] = hdr4[0] = 0;
nonce = exchange_nonce(exchange);
sprintf(req,"%llu%s%s",(long long)nonce,exchange->userid,exchange->apikey);
json = 0;
if ( (sig= hmac_sha256_str(dest,exchange->apisecret,(int32_t)strlen(exchange->apisecret),req)) != 0 )
{
//touppercase(sig);
//printf("req.(%s) sig.(%s)\n",req,sig);
//sprintf(req,"{\"key\":\"%s\",\"signature\":\"%s\",\"nonce\":%llu%s}",exchange->apikey,sig,(long long)nonce,payload);
sprintf(req,"key=%s&signature=%s&nonce=%llu%s",exchange->apikey,sig,(long long)nonce,payload);
//printf("submit.(%s)\n",req);
sprintf(url,"%s/%s/",EXCHANGE_AUTHURL,method);
if ( dotrade == 0 )
data = exchange_would_submit(req,hdr1,hdr2,hdr3,hdr4);
else if ( (data= curl_post(cHandlep,url,0,req,req,hdr2,hdr3,hdr4)) != 0 )
json = cJSON_Parse(data);
}
if ( retstrp != 0 )
*retstrp = data;
else if ( data != 0 )
free(data);
return(json);
}
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr)
{
char field[128],*itemstr = 0; cJSON *obj,*item;
*balancep = 0.;
strcpy(field,coinstr);
tolowercase(field);
if ( exchange->balancejson != 0 && (obj= jobj(exchange->balancejson,"return")) != 0 && (item= jobj(obj,"funds")) != 0 )
{
*balancep = jdouble(item,field);
obj = cJSON_CreateObject();
touppercase(field);
jaddstr(obj,"base",field);
jaddnum(obj,"balance",*balancep);
itemstr = jprint(obj,1);
}
if ( itemstr == 0 )
return(clonestr("{\"error\":\"cant find coin balance\"}"));
return(itemstr);
}
cJSON *BALANCES(void **cHandlep,struct exchange_info *exchange)
{
return(SIGNPOST(cHandlep,1,0,exchange,"balance",""));
}
#include "checkbalance.c"
uint64_t TRADE(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume)
{
char payload[1024],url[512],pairstr[512],*extra; cJSON *json; uint64_t txid = 0;
if ( (extra= *retstrp) != 0 )
*retstrp = 0;
if ( (dir= flipstr_for_exchange(exchange,pairstr,"%s%s",dir,&price,&volume,base,rel)) == 0 )
{
printf("cant find baserel (%s/%s)\n",base,rel);
return(0);
}
sprintf(url,"%s/%s/",EXCHANGE_AUTHURL,dir>0 ? "buy" : "sell");
if ( CHECKBALANCE(retstrp,dotrade,exchange,dir,base,rel,price,volume) == 0 && (json= SIGNPOST(cHandlep,dotrade,retstrp,exchange,url,payload)) != 0 )
{
// parse json and set txid
free_json(json);
}
return(txid);
}
char *ORDERSTATUS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char jsonbuf[128];
sprintf(jsonbuf,"&id=%llu",(long long)quoteid);
return(jprint(SIGNPOST(cHandlep,1,0,exchange,"order_status",jsonbuf),1));
}
char *CANCELORDER(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char jsonbuf[128];
sprintf(jsonbuf,"&id=%llu",(long long)quoteid);
return(jprint(SIGNPOST(cHandlep,1,0,exchange,"cancel_order",jsonbuf),1));
}
char *OPENORDERS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
return(jprint(SIGNPOST(cHandlep,1,0,exchange,"open_orders",""),1));
}
char *TRADEHISTORY(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
return(jprint(SIGNPOST(cHandlep,1,0,exchange,"user_transactions",""),1));
}
char *WITHDRAW(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
return(clonestr("{\"error\":\"withdraw not yet\"}"));
}
struct exchange_funcs bitstamp_funcs = EXCHANGE_FUNCS(bitstamp,EXCHANGE_NAME);
#undef UPDATE
#undef SUPPORTS
#undef SIGNPOST
#undef TRADE
#undef ORDERSTATUS
#undef CANCELORDER
#undef OPENORDERS
#undef TRADEHISTORY
#undef BALANCES
#undef PARSEBALANCE
#undef WITHDRAW
#undef EXCHANGE_NAME
#undef EXCHANGE_AUTHURL
#undef CHECKBALANCE

247
InstantDEX/exchanges/bittrex.c

@ -0,0 +1,247 @@
/******************************************************************************
* Copyright © 2014-2015 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 EXCHANGE_NAME "bittrex"
#define UPDATE prices777_ ## bittrex
#define SUPPORTS bittrex ## _supports
#define SIGNPOST bittrex ## _signpost
#define TRADE bittrex ## _trade
#define ORDERSTATUS bittrex ## _orderstatus
#define CANCELORDER bittrex ## _cancelorder
#define OPENORDERS bittrex ## _openorders
#define TRADEHISTORY bittrex ## _tradehistory
#define BALANCES bittrex ## _balances
#define PARSEBALANCE bittrex ## _parsebalance
#define WITHDRAW bittrex ## _withdraw
#define CHECKBALANCE bittrex ## _checkbalance
double UPDATE(struct prices777 *prices,int32_t maxdepth)
{
cJSON *json,*obj; char *jsonstr,market[128]; double hbla = 0.;
if ( prices->url[0] == 0 )
{
sprintf(market,"%s-%s",prices->rel,prices->base);
sprintf(prices->url,"https://bittrex.com/api/v1.1/public/getorderbook?market=%s&type=both&depth=%d",market,maxdepth);
}
jsonstr = issue_curl(prices->url);
if ( jsonstr != 0 )
{
if ( (json = cJSON_Parse(jsonstr)) != 0 )
{
if ( (obj= cJSON_GetObjectItem(json,"success")) != 0 && is_cJSON_True(obj) != 0 )
hbla = prices777_json_orderbook("bittrex",prices,maxdepth,json,"result","buy","sell","Rate","Quantity");
free_json(json);
}
free(jsonstr);
}
return(hbla);
}
int32_t SUPPORTS(char *base,char *rel)
{
if ( strlen(base) > 5 || strlen(rel) > 5 || strcmp(rel,"CNY") == 0 || strcmp(base,"CNY") == 0 || strcmp(rel,"USD") == 0 || strcmp(base,"USD") == 0 )
return(0);
if ( strcmp(rel,"BTC") == 0 )
return(1);
else if ( strcmp(base,"BTC") == 0 )
return(-1);
else return(0);
}
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *url,char *payload)
{
char dest[SHA512_DIGEST_SIZE*2+1],hdr1[512],hdr2[512],hdr3[512],hdr4[512],*data,*sig; cJSON *json;
hdr1[0] = hdr2[0] = hdr3[0] = hdr4[0] = 0;
json = 0;
if ( (sig= hmac_sha512_str(dest,exchange->apisecret,(int32_t)strlen(exchange->apisecret),payload)) != 0 )
sprintf(hdr1,"apisign:%s",sig);
if ( dotrade == 0 )
data = exchange_would_submit(payload,hdr1,hdr2,hdr3,hdr4);
else if ( (data= curl_post(cHandlep,url,0,payload,hdr1,hdr2,hdr3,hdr4)) != 0 )
json = cJSON_Parse(data);
if ( retstrp != 0 )
*retstrp = data;
else if ( data != 0 )
free(data);
return(json);
}
cJSON *BALANCES(void **cHandlep,struct exchange_info *exchange)
{
char payload[1024];
sprintf(payload,"https://bittrex.com/api/v1.1/account/getbalances?apikey=%s&nonce=%llu",exchange->apikey,(long long)exchange_nonce(exchange));
return(SIGNPOST(cHandlep,1,0,exchange,payload,payload));
}
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr)
{
int32_t i,n; char *str,*itemstr = 0; cJSON *item,*array,*obj; double total,pending;
*balancep = 0.;
if ( exchange->balancejson != 0 && (array= jarray(&n,exchange->balancejson,"result")) != 0 )
{
for (i=0; i<n; i++)
{
if ( (item= jitem(array,i)) != 0 )
{
if ( (str= jstr(item,"Currency")) != 0 && strcmp(coinstr,str) == 0 )
{
itemstr = jprint(item,0);
*balancep = jdouble(item,"Available");
total = jdouble(item,"Balance");
pending = jdouble(item,"Pending");
if ( (obj= cJSON_Parse(itemstr)) != 0 )
{
jaddnum(obj,"balance",*balancep);
jaddnum(obj,"total",total);
jaddnum(obj,"pending",pending);
if ( (str= jstr(obj,"CryptoAddress")) != 0 )
jaddstr(obj,"deposit_address",str);
free(itemstr);
itemstr = jprint(obj,1);
}
break;
}
}
}
}
if ( itemstr == 0 )
return(clonestr("{\"error\":\"cant find coin balance, are you sure it isnt empty account?\"}"));
return(itemstr);
}
#include "checkbalance.c"
uint64_t TRADE(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume)
{
char payload[1024],pairstr[512],*extra; cJSON *json,*resultobj; uint64_t txid = 0; int32_t i,j,n;
struct destbuf uuidstr; uint8_t databuf[512];
if ( (extra= *retstrp) != 0 )
*retstrp = 0;
if ( (dir= flip_for_exchange(pairstr,"%s-%s","BTC",dir,&price,&volume,base,rel)) == 0 )
{
return(0);
}
sprintf(payload,"https://bittrex.com/api/v1.1/market/%slimit?apikey=%s&nonce=%llu&market=%s&rate=%.8f&quantity=%.8f",dir>0?"buy":"sell",exchange->apikey,(long long)exchange_nonce(exchange),pairstr,price,volume);
if ( CHECKBALANCE(retstrp,dotrade,exchange,dir,base,rel,price,volume) == 0 && (json= SIGNPOST(cHandlep,dotrade,retstrp,exchange,payload,payload)) != 0 )
{
if ( is_cJSON_True(cJSON_GetObjectItem(json,"success")) != 0 && (resultobj= cJSON_GetObjectItem(json,"result")) != 0 )
{
copy_cJSON(&uuidstr,cJSON_GetObjectItem(resultobj,"uuid"));
for (i=j=0; uuidstr.buf[i]!=0; i++)
if ( uuidstr.buf[i] != '-' )
uuidstr.buf[j++] = uuidstr.buf[i];
uuidstr.buf[j] = 0;
n = (int32_t)strlen(uuidstr.buf);
printf("-> uuidstr.(%s).%d\n",uuidstr.buf,n);
decode_hex(databuf,n/2,uuidstr.buf);
if ( n >= 16 )
for (i=0; i<8; i++)
databuf[i] ^= databuf[8 + i];
memcpy(&txid,databuf,8);
printf("-> %llx\n",(long long)txid);
}
free_json(json);
}
return(txid);
}
char *ORDERSTATUS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char payload[1024],*retstr = 0; cJSON *json;
sprintf(payload,"https://bittrex.com/api/v1.1/account/getorder?apikey=%s&nonce=%llu&uuid=%llu",exchange->apikey,(long long)exchange_nonce(exchange),(long long)quoteid);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized orderstatus
}
char *CANCELORDER(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char payload[1024],*retstr = 0; cJSON *json;
sprintf(payload,"https://bittrex.com/api/v1.1/market/cancel?apikey=%s&nonce=%llu&uuid=%llu",exchange->apikey,(long long)exchange_nonce(exchange),(long long)quoteid);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized cancelorder
}
char *OPENORDERS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],market[64],*base,*rel,*retstr = 0; cJSON *json;
sprintf(payload,"https://bittrex.com/api/v1.1/market/getopenorders?apikey=%s&nonce=%llu",exchange->apikey,(long long)exchange_nonce(exchange));
if ( (base= jstr(argjson,"base")) != 0 && (rel= jstr(argjson,"rel")) != 0 )
{
sprintf(market,"%s-%s",rel,base);
sprintf(payload + strlen(payload),"&market=%s",market);
}
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized open orders
}
char *TRADEHISTORY(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],market[64],*base,*rel,*retstr = 0; cJSON *json;
sprintf(payload,"https://bittrex.com/api/v1.1/account/getorderhistory?apikey=%s&nonce=%llu",exchange->apikey,(long long)exchange_nonce(exchange));
if ( (base= jstr(argjson,"base")) != 0 && (rel= jstr(argjson,"rel")) != 0 )
{
sprintf(market,"%s-%s",rel,base);
sprintf(payload + strlen(payload),"&market=%s",market);
}
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized tradehistory
}
char *WITHDRAW(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],*destaddr,*paymentid,*base,*retstr = 0; cJSON *json; double amount;
if ( (base= jstr(argjson,"base")) == 0 )
return(clonestr("{\"error\":\"base not specified\"}"));
if ( (destaddr= jstr(argjson,"destaddr")) == 0 )
return(clonestr("{\"error\":\"destaddr not specified\"}"));
if ( (amount= jdouble(argjson,"amount")) < SMALLVAL )
return(clonestr("{\"error\":\"amount not specified\"}"));
paymentid = jstr(argjson,"paymentid");
sprintf(payload,"https://bittrex.com/api/v1.1/account/withdraw?apikey=%s&nonce=%llu&currency=%s&amount=%.4f&address=%s",exchange->apikey,(long long)exchange_nonce(exchange),base,amount,destaddr);
if ( paymentid != 0 )
sprintf(payload + strlen(payload),"&paymentid=%s",paymentid);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized withdraw
}
struct exchange_funcs bittrex_funcs = EXCHANGE_FUNCS(bittrex,EXCHANGE_NAME);
#undef UPDATE
#undef SUPPORTS
#undef SIGNPOST
#undef TRADE
#undef ORDERSTATUS
#undef CANCELORDER
#undef OPENORDERS
#undef TRADEHISTORY
#undef BALANCES
#undef PARSEBALANCE
#undef WITHDRAW
#undef EXCHANGE_NAME
#undef CHECKBALANCE

321
InstantDEX/exchanges/btc38.c

@ -0,0 +1,321 @@
/******************************************************************************
* Copyright © 2014-2015 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 EXCHANGE_NAME "btc38"
#define UPDATE prices777_ ## btc38
#define SUPPORTS btc38 ## _supports
#define SIGNPOST btc38 ## _signpost
#define TRADE btc38 ## _trade
#define ORDERSTATUS btc38 ## _orderstatus
#define CANCELORDER btc38 ## _cancelorder
#define OPENORDERS btc38 ## _openorders
#define TRADEHISTORY btc38 ## _tradehistory
#define BALANCES btc38 ## _balances
#define PARSEBALANCE btc38 ## _parsebalance
#define WITHDRAW btc38 ## _withdraw
#define EXCHANGE_AUTHURL "http://www.btc38.com/trade/t_api"
#define CHECKBALANCE btc38 ## _checkbalance
double UPDATE(struct prices777 *prices,int32_t maxdepth)
{
if ( prices->url[0] == 0 )
{
if ( strcmp(prices->lbase,"cny") == 0 && strcmp(prices->lrel,"btc") == 0 )
sprintf(prices->url,"http://api.btc38.com/v1/depth.php?c=%s&mk_type=%s","btc","cny");
else sprintf(prices->url,"http://api.btc38.com/v1/depth.php?c=%s&mk_type=%s",prices->lbase,prices->lrel);
}
return(prices777_standard("btc38",prices->url,prices,0,0,maxdepth,0));
}
int32_t SUPPORTS(char *_base,char *_rel)
{
char *cnypairs[] = { "BTC", "LTC", "DOGE", "XRP", "BTS", "STR", "NXT", "BLK", "BC", "VPN", "BILS", "BOST", "PPC", "APC", "ZCC", "XPM", "DGC", "MEC", "WDC", "QRK", "BEC", "ANC", "UNC", "RIC", "SRC", "TAG" };
char *btcpairs[] = { "TMC", "LTC", "DOGE", "XRP", "BTS", "XEM", "VPN", "XCN", "VOOT", "SYS", "NRS", "NAS", "SYNC", "MED", "EAC" };
int32_t i; char base[64],rel[64];
strcpy(base,_base), strcpy(rel,_rel);
touppercase(base), touppercase(rel);
if ( strlen(base) > 5 || strlen(rel) > 5 )
return(0);
if ( strcmp(base,"BTC") == 0 && strcmp(rel,"CNY") == 0 )
return(1);
else if ( strcmp(base,"CNY") == 0 && strcmp(rel,"BTC") == 0 )
return(-1);
else if ( strcmp(base,"BTC") == 0 )
{
for (i=0; i<sizeof(btcpairs)/sizeof(*btcpairs); i++)
if ( strcmp(btcpairs[i],rel) == 0 )
return(-1);
}
else if ( strcmp(rel,"BTC") == 0 )
{
for (i=0; i<sizeof(btcpairs)/sizeof(*btcpairs); i++)
if ( strcmp(btcpairs[i],base) == 0 )
return(1);
}
else if ( strcmp(base,"CNY") == 0 )
{
for (i=0; i<sizeof(cnypairs)/sizeof(*cnypairs); i++)
if ( strcmp(cnypairs[i],rel) == 0 )
return(-1);
}
else if ( strcmp(rel,"CNY") == 0 )
{
for (i=0; i<sizeof(cnypairs)/sizeof(*cnypairs); i++)
if ( strcmp(cnypairs[i],base) == 0 )
return(1);
}
printf("BTC38 doesnt support (%s/%s)\n",base,rel);
return(0);
}
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *payload,char *path)
{
char cmdbuf[2048],url[1024],buf[1024],hdr1[512],hdr2[512],hdr3[512],hdr4[512],digest[33],*data;
cJSON *json; uint64_t nonce;
hdr1[0] = hdr2[0] = hdr3[0] = hdr4[0] = 0;
json = 0;
nonce = exchange_nonce(exchange);
sprintf(buf,"%s_%s_%s_%llu",exchange->apikey,exchange->userid,exchange->apisecret,(long long)nonce);
//printf("MD5.(%s)\n",buf);
calc_md5(digest,buf,(int32_t)strlen(buf));
sprintf(cmdbuf,"key=%s&time=%llu&md5=%s%s",exchange->apikey,(long long)nonce,digest,payload);
sprintf(url,"%s/%s",EXCHANGE_AUTHURL,path);
if ( dotrade == 0 )
data = exchange_would_submit(payload,hdr1,hdr2,hdr3,hdr4);
else if ( (data= curl_post(cHandlep,url,0,cmdbuf,hdr1,hdr2,hdr3,hdr4)) != 0 )
json = cJSON_Parse(data);
if ( retstrp != 0 )
*retstrp = data;
else if ( data != 0 )
free(data);
return(json);
}
/* $ Stamp = $ date-> getTimestamp ();
type, 1 for the purchase of Entry, 2 entry order to sell, can not be empty / the type of the order
$ Mdt = "_ public here to write here write here to write user ID_ private _" $ stamp.;
$ Mdt = md5 ($ mdt);
$ Data = array ("key" => "here to write public", "time" => $ stamp, "md5" => $ mdt, "type" => 1, "mk_type" => "cny",
"Price" => "0.0001", "amount" => "100", "coinname" => "XRP");
// $ Data_string = json_encode ($ data);
$ Ch = curl_init ();
curl_setopt ($ ch, CURLOPT_URL, 'http://www.btc38.com/trade/t_api/submitOrder.php');
curl_setopt ($ ch, CURLOPT_POST, 1);
curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ data);
curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ ch, CURLOPT_HEADER, 0); */
/*
static CURL *cHandle;
char *data,*path,url[1024],cmdbuf[8192],buf[512],digest[33],market[16],base[64],rel[64],coinname[16],fmtstr[512],*pricefmt,*volfmt = "%.3f";
cJSON *json,*resultobj; uint64_t nonce,txid = 0;
if ( _base != 0 && _rel != 0 )
{
strcpy(base,_base), strcpy(rel,_rel);
touppercase(base), touppercase(rel);
if ( btc38_supports(base,rel) == 0 )
{
*retstrp = clonestr("{\"error\":\"invalid contract pair\"}");
return(0);
}
}
nonce = exchange_nonce(exchange);
sprintf(buf,"%s_%s_%s_%llu",exchange->apikey,exchange->userid,exchange->apisecret,(long long)nonce);
//printf("MD5.(%s)\n",buf);
calc_md5(digest,buf,(int32_t)strlen(buf));
*retstrp = 0;
if ( dir == 0 )
{
path = "getMyBalance.php";
sprintf(cmdbuf,"key=%s&time=%llu&md5=%s",exchange->apikey,(long long)nonce,digest);
}
else
{
if ( (data= curl_post(&cHandle,url,0,cmdbuf,0,0,0,0)) != 0 )
{
//printf("submit cmd.(%s) [%s]\n",cmdbuf,data);
if ( (json= cJSON_Parse(data)) != 0 )
{
if ( juint(json,"success") > 0 && (resultobj= cJSON_GetObjectItem(json,"return")) != 0 )
{
if ( (txid= get_API_nxt64bits(cJSON_GetObjectItem(resultobj,"order_id"))) == 0 )
{
if ( get_API_nxt64bits(cJSON_GetObjectItem(resultobj,"remains")) == 0 )
txid = _crc32(0,cmdbuf,strlen(cmdbuf));
}
}
free_json(json);
}
} else fprintf(stderr,"submit err cmd.(%s)\n",cmdbuf);
if ( retstrp != 0 && data != 0 )
{
if ( (json= cJSON_Parse(data)) == 0 )
{
json = cJSON_CreateObject();
jaddstr(json,"result",data);
data = jprint(json,1);
} else free_json(json);
//printf("btc38 returning.(%s) in %p\n",data,data);
*retstrp = data;
}
else if ( data != 0 )
free(data);
return(txid);
*/
cJSON *BALANCES(void **cHandlep,struct exchange_info *exchange)
{
return(SIGNPOST(cHandlep,1,0,exchange,"","getMyBalance.php"));
}
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr)
{
char field[128],*str,*itemstr = 0; cJSON *obj; double lockbalance,imma;
*balancep = 0.;
strcpy(field,coinstr);
tolowercase(field);
strcat(field,"_balance");
if ( exchange->balancejson != 0 && (str= jstr(exchange->balancejson,field)) != 0 )
{
*balancep = jdouble(exchange->balancejson,field);
strcpy(field,coinstr), tolowercase(field), strcat(field,"_balance_lock");
lockbalance = jdouble(exchange->balancejson,field);
strcpy(field,coinstr), tolowercase(field), strcat(field,"_balance_imma");
imma = jdouble(exchange->balancejson,field);
obj = cJSON_CreateObject();
jaddnum(obj,"balance",*balancep);
jaddnum(obj,"locked_balance",lockbalance);
jaddnum(obj,"imma_balance",imma);
itemstr = jprint(obj,1);
}
if ( itemstr == 0 )
return(clonestr("{\"error\":\"cant find coin balance\"}"));
return(itemstr);
}
#include "checkbalance.c"
uint64_t TRADE(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume)
{
char payload[1024],market[16],coinname[16],fmtstr[512],*pricefmt,*extra,*volfmt = "%.3f";
cJSON *json,*resultobj; uint64_t txid = 0;
if ( (extra= *retstrp) != 0 )
*retstrp = 0;
if ( (dir= cny_flip(market,coinname,base,rel,dir,&price,&volume)) == 0 )
{
fprintf(stderr,"btc38_trade illegal base.(%s) or rel.(%s)\n",base,rel);
return(0);
}
if ( strcmp(market,"cny") == 0 )
pricefmt = "%.5f";
else pricefmt = "%.6f";
//sprintf(fmtstr,"key=%%s&time=%%llu&md5=%%s&type=%%s&mk_type=%%s&coinname=%%s&price=%s&amount=%s",pricefmt,volfmt);
//sprintf(payload,fmtstr,exchange->apikey,(long long)nonce,digest,dir>0?"1":"2",market,coinname,price,volume);
sprintf(fmtstr,"&type=%%s&mk_type=%%s&coinname=%%s&price=%s&amount=%s",pricefmt,volfmt);
sprintf(payload,fmtstr,dir>0?"1":"2",market,coinname,price,volume);
if ( CHECKBALANCE(retstrp,dotrade,exchange,dir,base,rel,price,volume) == 0 && (json= SIGNPOST(cHandlep,dotrade,retstrp,exchange,payload,"submitOrder.php")) != 0 )
{
if ( juint(json,"success") > 0 && (resultobj= jobj(json,"return")) != 0 )
{
if ( (txid= j64bits(resultobj,"order_id")) == 0 )
{
if ( j64bits(resultobj,"remains") == 0 )
txid = calc_crc32(0,payload,strlen(payload));
}
}
free_json(json);
if ( retstrp != 0 && *retstrp != 0 )
{
if ( (json= cJSON_Parse(*retstrp)) == 0 )
{
json = cJSON_CreateObject();
jaddstr(json,"result",*retstrp);
free(*retstrp);
*retstrp = jprint(json,1);
} else free_json(json);
}
}
return(txid);
}
char *CANCELORDER(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char payload[1024],*rel,*retstr = 0; cJSON *json;
if ( (rel= jstr(argjson,"rel")) == 0 )
rel = "cny";
sprintf(payload,"&mk_type=%s&order_id=%llu",rel,(long long)quoteid);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,"cancelOrder.php")) != 0 )
{
free_json(json);
}
return(retstr); // return standardized cancelorder
}
char *OPENORDERS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],*base,*rel,*retstr = 0; cJSON *json;
if ( (rel= jstr(argjson,"rel")) == 0 )
rel = "cny";
sprintf(payload,"&mk_type=%s",rel);
if ( (base= jstr(argjson,"base")) != 0 )
sprintf(payload + strlen(payload),"&coinname=%s",base);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,"getOrderList.php")) != 0 )
{
free_json(json);
}
return(retstr); // return standardized open orders
}
char *TRADEHISTORY(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
return(clonestr("{\"error\":\"btc38 doesnt seem to have trade history api!\"}"));
}
char *WITHDRAW(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
return(clonestr("{\"error\":\"btc38 doesnt seem to have withdraw api!\"}"));
}
char *ORDERSTATUS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char *status,*retstr;
status = OPENORDERS(cHandlep,exchange,argjson);
if ( (retstr= exchange_extractorderid(0,status,quoteid,"order_id")) != 0 )
{
free(status);
return(retstr);
}
free(status);
return(clonestr("{\"result\":\"order not pending\"}"));
}
struct exchange_funcs btc38_funcs = EXCHANGE_FUNCS(btc38,EXCHANGE_NAME);
#undef UPDATE
#undef SUPPORTS
#undef SIGNPOST
#undef TRADE
#undef ORDERSTATUS
#undef CANCELORDER
#undef OPENORDERS
#undef TRADEHISTORY
#undef BALANCES
#undef PARSEBALANCE
#undef WITHDRAW
#undef EXCHANGE_NAME
#undef EXCHANGE_AUTHURL
#undef CHECKBALANCE

215
InstantDEX/exchanges/btce.c

@ -0,0 +1,215 @@
/******************************************************************************
* Copyright © 2014-2015 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 EXCHANGE_NAME "btce"
#define UPDATE prices777_ ## btce
#define SUPPORTS btce ## _supports
#define SIGNPOST btce ## _signpost
#define TRADE btce ## _trade
#define ORDERSTATUS btce ## _orderstatus
#define CANCELORDER btce ## _cancelorder
#define OPENORDERS btce ## _openorders
#define TRADEHISTORY btce ## _tradehistory
#define BALANCES btce ## _balances
#define PARSEBALANCE btce ## _parsebalance
#define WITHDRAW btce ## _withdraw
#define EXCHANGE_AUTHURL "https://btc-e.com/tapi"
#define CHECKBALANCE btce ## _checkbalance
double UPDATE(struct prices777 *prices,int32_t maxdepth)
{
char field[64];
sprintf(field,"%s_%s",prices->lbase,prices->lrel);
if ( prices->url[0] == 0 )
sprintf(prices->url,"https://btc-e.com/api/3/depth/%s",field);
return(prices777_standard("btce",prices->url,prices,0,0,maxdepth,field));
}
int32_t SUPPORTS(char *base,char *rel)
{
char *baserels[][2] = { {"btc","usd"}, {"btc","rur"}, {"btc","eur"}, {"ltc","btc"}, {"ltc","usd"}, {"ltc","rur"}, {"ltc","eur"}, {"nmc","btc"}, {"nmc","usd"}, {"nvc","btc"}, {"nvc","usd"}, {"eur","usd"}, {"eur","rur"}, {"ppc","btc"}, {"ppc","usd"} };
return(baserel_polarity(baserels,(int32_t)(sizeof(baserels)/sizeof(*baserels)),base,rel));
}
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *url,char *payload)
{
char dest[SHA512_DIGEST_SIZE*2+1],hdr1[512],hdr2[512],hdr3[512],hdr4[512],*data,*sig; cJSON *json;
hdr1[0] = hdr2[0] = hdr3[0] = hdr4[0] = 0;
json = 0;
if ( (sig= hmac_sha512_str(dest,exchange->apisecret,(int32_t)strlen(exchange->apisecret),payload)) != 0 )
sprintf(hdr1,"Sign:%s",sig);
else hdr1[0] = 0;
sprintf(hdr2,"Key:%s",exchange->apikey);
if ( dotrade == 0 )
data = exchange_would_submit(payload,hdr1,hdr2,hdr3,hdr4);
else if ( (data= curl_post(cHandlep,url,0,payload,hdr1,hdr2,hdr3,hdr4)) != 0 )
json = cJSON_Parse(data);
if ( retstrp != 0 )
*retstrp = data;
else if ( data != 0 )
free(data);
return(json);
}
cJSON *BALANCES(void **cHandlep,struct exchange_info *exchange)
{
char payload[1024];
sprintf(payload,"method=getInfo&nonce=%llu",(long long)exchange_nonce(exchange));
return(SIGNPOST(cHandlep,1,0,exchange,EXCHANGE_AUTHURL,payload));
}
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr)
{
//btce.({"success":1,"return":{"funds":{"usd":73.02571846,"btc":0,"ltc":0,"nmc":0,"rur":0,"eur":0,"nvc":0.0000322,"trc":0,"ppc":0.00000002,"ftc":0,"xpm":2.28605349,"cnh":0,"gbp":0},"rights":{"info":1,"trade":1,"withdraw":0},"transaction_count":0,"open_orders":3,"server_time":1441918649}})
char field[128],*itemstr = 0; cJSON *obj,*item;
*balancep = 0.;
strcpy(field,coinstr);
tolowercase(field);
if ( exchange->balancejson != 0 && (obj= jobj(exchange->balancejson,"return")) != 0 && (item= jobj(obj,"funds")) != 0 )
{
*balancep = jdouble(item,field);
obj = cJSON_CreateObject();
touppercase(field);
jaddstr(obj,"base",field);
jaddnum(obj,"balance",*balancep);
itemstr = jprint(obj,1);
}
if ( itemstr == 0 )
return(clonestr("{\"error\":\"cant find coin balance\"}"));
return(itemstr);
}
#include "checkbalance.c"
uint64_t TRADE(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume)
{
char payload[1024],pairstr[512],*extra; cJSON *json,*resultobj; uint64_t txid = 0;
if ( (extra= *retstrp) != 0 )
*retstrp = 0;
if ( (dir= flipstr_for_exchange(exchange,pairstr,"%s_%s",dir,&price,&volume,base,rel)) == 0 )
{
printf("cant find baserel (%s/%s)\n",base,rel);
return(0);
}
sprintf(payload,"method=Trade&nonce=%llu&pair=%s&type=%s&rate=%.3f&amount=%.6f",(long long)exchange_nonce(exchange),pairstr,dir>0?"buy":"sell",price,volume);
if ( CHECKBALANCE(retstrp,dotrade,exchange,dir,base,rel,price,volume) == 0 && (json= SIGNPOST(cHandlep,dotrade,retstrp,exchange,EXCHANGE_AUTHURL,payload)) != 0 )
{
//{ "success":1, "return":{ "received":0.1, "remains":0, "order_id":0, "funds":{ "usd":325, "btc":2.498, } } }
if ( juint(json,"success") > 0 && (resultobj= jobj(json,"return")) != 0 )
{
if ( (txid= j64bits(resultobj,"order_id")) == 0 )
{
if ( j64bits(resultobj,"remains") == 0 )
txid = calc_crc32(0,payload,strlen(payload));
}
}
free_json(json);
}
return(txid);
}
char *ORDERSTATUS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char payload[1024],*retstr = 0; cJSON *json;
sprintf(payload,"method=OrderInfo&nonce=%llu&order_id=%llu",(long long)exchange_nonce(exchange),(long long)quoteid);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,EXCHANGE_AUTHURL,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized orderstatus
}
char *CANCELORDER(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char payload[1024],*retstr = 0; cJSON *json;
sprintf(payload,"method=CancelOrder&nonce=%llu&order_id=%llu",(long long)exchange_nonce(exchange),(long long)quoteid);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,EXCHANGE_AUTHURL,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized cancelorder
}
char *OPENORDERS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],market[64],*base,*rel,*retstr = 0; cJSON *json;
sprintf(payload,"method=ActiveOrders&nonce=%llu",(long long)exchange_nonce(exchange));
if ( (base= jstr(argjson,"base")) != 0 && (rel= jstr(argjson,"rel")) != 0 )
{
sprintf(market,"%s_%s",base,rel);
tolowercase(market);
sprintf(payload + strlen(payload),"&pair=%s",market);
}
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,EXCHANGE_AUTHURL,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized open orders
}
char *TRADEHISTORY(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],market[64],*base,*rel,*retstr = 0; cJSON *json; uint32_t starttime,endtime;
sprintf(payload,"method=TradeHistory&nonce=%llu",(long long)exchange_nonce(exchange));
if ( (starttime= juint(argjson,"start")) != 0 )
sprintf(payload + strlen(payload),"&since=%u",starttime);
if ( (endtime= juint(argjson,"end")) != 0 )
sprintf(payload + strlen(payload),"&end=%u",endtime);
if ( (base= jstr(argjson,"base")) != 0 && (rel= jstr(argjson,"rel")) != 0 )
{
sprintf(market,"%s_%s",base,rel);
tolowercase(market);
sprintf(payload + strlen(payload),"&pair=%s",market);
}
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,EXCHANGE_AUTHURL,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized tradehistory
}
char *WITHDRAW(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],*base,*destaddr,*retstr = 0; cJSON *json; double amount;
if ( (base= jstr(argjson,"base")) == 0 )
return(clonestr("{\"error\":\"base not specified\"}"));
if ( (destaddr= jstr(argjson,"destaddr")) == 0 )
return(clonestr("{\"error\":\"destaddr not specified\"}"));
if ( (amount= jdouble(argjson,"amount")) < SMALLVAL )
return(clonestr("{\"error\":\"amount not specified\"}"));
sprintf(payload,"method=WithdrawCoin&nonce=%llu&coinName=%s&amount=%.6f&address=%s",(long long)exchange_nonce(exchange),base,amount,destaddr);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,EXCHANGE_AUTHURL,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized withdraw
}
struct exchange_funcs btce_funcs = EXCHANGE_FUNCS(btce,EXCHANGE_NAME);
#undef UPDATE
#undef SUPPORTS
#undef SIGNPOST
#undef TRADE
#undef ORDERSTATUS
#undef CANCELORDER
#undef OPENORDERS
#undef TRADEHISTORY
#undef BALANCES
#undef PARSEBALANCE
#undef WITHDRAW
#undef EXCHANGE_NAME
#undef EXCHANGE_AUTHURL
#undef CHECKBALANCE

53
InstantDEX/exchanges/checkbalance.c

@ -0,0 +1,53 @@
/******************************************************************************
* Copyright © 2014-2015 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. *
* *
******************************************************************************/
int32_t CHECKBALANCE(char **retstrp,int32_t skipflag,struct exchange_info *exchange,int32_t dir,char *base,char *rel,double price,double volume)
{
cJSON *json; char *coinstr,*balancestr,*resultstr,*resultval; double balance; int32_t retval = -1;
if ( skipflag == 0 )
{
coinstr = (dir > 0) ? rel : base;
if ( (balancestr= PARSEBALANCE(exchange,&balance,coinstr)) != 0 )
{
json = cJSON_Parse(balancestr);
free(balancestr);
printf("%s balance.%s %f vs %f\n",exchange->name,coinstr,balance,dir > 0 ? volume : volume * price);
if ( (dir > 0 && balance < volume) || (dir < 0 && balance < (volume * price)) )
{
resultstr = "error";
resultval = "not enough balance";
}
else
{
resultval = "balance";
resultstr = "success";
retval = 0;
}
if ( retstrp != 0 )
{
if ( json == 0 )
json = cJSON_CreateObject();
jaddstr(json,"coin",coinstr);
jaddnum(json,"balance",balance);
jaddnum(json,"required",volume * (dir < 0 ? price : 1.));
jaddstr(json,resultstr,resultval);
*retstrp = jprint(json,1);
}
else if ( json != 0 )
free_json(json);
}
} else retval = 0;
return(retval);
}

229
InstantDEX/exchanges/coinbase.c

@ -0,0 +1,229 @@
/******************************************************************************
* Copyright © 2014-2015 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 EXCHANGE_NAME "coinbase"
#define UPDATE prices777_ ## coinbase
#define SUPPORTS coinbase ## _supports
#define SIGNPOST coinbase ## _signpost
#define TRADE coinbase ## _trade
#define ORDERSTATUS coinbase ## _orderstatus
#define CANCELORDER coinbase ## _cancelorder
#define OPENORDERS coinbase ## _openorders
#define TRADEHISTORY coinbase ## _tradehistory
#define BALANCES coinbase ## _balances
#define PARSEBALANCE coinbase ## _parsebalance
#define WITHDRAW coinbase ## _withdraw
#define EXCHANGE_AUTHURL "https://api.exchange.coinbase.com"
#define CHECKBALANCE coinbase ## _checkbalance
double UPDATE(struct prices777 *prices,int32_t maxdepth)
{
if ( prices->url[0] == 0 )
sprintf(prices->url,"https://api.exchange.coinbase.com/products/%s-%s/book?level=2",prices->base,prices->rel);
return(prices777_standard("coinbase",prices->url,prices,0,0,maxdepth,0));
}
int32_t SUPPORTS(char *base,char *rel)
{
char *baserels[][2] = { {"btc","usd"} };
return(baserel_polarity(baserels,(int32_t)(sizeof(baserels)/sizeof(*baserels)),base,rel));
}
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *payload,uint64_t nonce,char *path,char *method)
{
/*All REST requests must contain the following headers:
CB-ACCESS-KEY The api key as a string.
CB-ACCESS-SIGN The base64-encoded signature (see Signing a Message).
CB-ACCESS-TIMESTAMP A timestamp for your request.
CB-ACCESS-PASSPHRASE The passphrase you specified when creating the API key.
All request bodies should have content type application/json and be valid JSON.
Signing a Message
The CB-ACCESS-SIGN header is generated by creating a sha256 HMAC using the base64-decoded
secret key on the prehash string timestamp + method + requestPath + body (where + represents string concatenation)
and base64-encode the output. The timestamp value is the same as the CB-ACCESS-TIMESTAMP header.
The body is the request body string or omitted if there is no request body (typically for GET requests).
The method should be UPPER CASE
Remember to first base64-decode the alphanumeric secret string (resulting in 64 bytes) before using it as the key for HMAC. Also, base64-encode the digest output before sending in the header.
*/
/* def __call__(self, request):
timestamp = str(time.time())
message = timestamp + request.method + request.path_url + (request.body or '')
hmac_key = base64.b64decode(self.secret_key)
signature = hmac.new(hmac_key, message, hashlib.sha256)
signature_b64 = signature.digest().encode('base64').rstrip('\n')
request.headers.update({
'CB-ACCESS-SIGN': signature_b64,
'CB-ACCESS-TIMESTAMP': timestamp,
'CB-ACCESS-KEY': self.api_key,
'CB-ACCESS-PASSPHRASE': self.passphrase,
'Content-Type': 'application/json'
})*/
char url[1024],hdr1[512],hdr2[512],hdr3[512],hdr4[512],dest[1024]; cJSON *json; int32_t n;
char prehash64[512],prehash[512],decodedsecret[512],sig64[512],*sig,*data = 0;
hdr1[0] = hdr2[0] = hdr3[0] = hdr4[0] = 0;
json = 0;
n = nn_base64_decode((void *)exchange->apisecret,strlen(exchange->apisecret),(void *)decodedsecret,sizeof(decodedsecret));
sprintf(prehash,"%llu%s/%s%s",(long long)nonce,method,path,payload);
nn_base64_encode((void *)prehash,strlen(prehash),prehash64,sizeof(prehash64));
if ( (sig= hmac_sha256_str(dest,decodedsecret,n,prehash64)) != 0 )
{
nn_base64_encode((void *)sig,strlen(sig),sig64,sizeof(sig64));
//CB-ACCESS-KEY The api key as a string.
//CB-ACCESS-SIGN The base64-encoded signature (see Signing a Message).
//CB-ACCESS-TIMESTAMP A timestamp for your request.
//CB-ACCESS-PASSPHRASE The passphrase you specified when creating the API key.
sprintf(hdr1,"CB-ACCESS-KEY:%s",exchange->apikey);
sprintf(hdr2,"CB-ACCESS-SIGN:%s",sig64);
sprintf(hdr3,"CB-ACCESS-TIMESTAMP:%llu",(long long)nonce);
//sprintf(hdr4,"CB-ACCESS-PASSPHRASE:%s; content-type:application/json; charset=utf-8",exchange->userid);
sprintf(hdr4,"CB-ACCESS-PASSPHRASE:%s",exchange->userid);
sprintf(url,"%s/%s",EXCHANGE_AUTHURL,path);
if ( dotrade == 0 )
data = exchange_would_submit(payload,hdr1,hdr2,hdr3,hdr4);
else if ( (data= curl_post(cHandlep,url,0,payload,hdr1,hdr2,hdr3,hdr4)) != 0 )
json = cJSON_Parse(data);
}
if ( retstrp != 0 )
*retstrp = data;
else if ( data != 0 )
free(data);
return(json);
}
cJSON *BALANCES(void **cHandlep,struct exchange_info *exchange)
{
return(SIGNPOST(cHandlep,1,0,exchange,"",exchange_nonce(exchange),"accounts","GET"));
}
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr)
{
char field[128],*itemstr = 0; cJSON *obj,*item;
*balancep = 0.;
strcpy(field,coinstr);
tolowercase(field);
if ( exchange->balancejson != 0 && (obj= jobj(exchange->balancejson,"return")) != 0 && (item= jobj(obj,"funds")) != 0 )
{
*balancep = jdouble(item,field);
obj = cJSON_CreateObject();
touppercase(field);
jaddstr(obj,"base",field);
jaddnum(obj,"balance",*balancep);
itemstr = jprint(obj,1);
}
if ( itemstr == 0 )
return(clonestr("{\"error\":\"cant find coin balance\"}"));
return(itemstr);
}
#include "checkbalance.c"
uint64_t TRADE(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume)
{
char payload[1024],pairstr[512],method[32],*path,*extra;
cJSON *json; uint64_t nonce,txid = 0;
if ( (extra= *retstrp) != 0 )
*retstrp = 0;
path = "trade", strcpy(method,"POST");
if ( (dir= flip_for_exchange(pairstr,"%s_%s","BTC",dir,&price,&volume,base,rel)) == 0 )
{
printf("cant find baserel (%s/%s)\n",base,rel);
return(0);
}
nonce = exchange_nonce(exchange);
sprintf(payload,"method=Trade&nonce=%llu&pair=%s&type=%s&rate=%.6f&amount=%.6f",(long long)nonce,pairstr,dir>0?"buy":"sell",price,volume);
if ( CHECKBALANCE(retstrp,dotrade,exchange,dir,base,rel,price,volume) == 0 && (json= SIGNPOST(cHandlep,dotrade,retstrp,exchange,payload,nonce,path,method)) != 0 )
{
// parse json and set txid
free_json(json);
}
return(txid);
}
char *ORDERSTATUS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char payload[1024],*retstr = 0; cJSON *json;
// generate payload
if ( (json= SIGNPOST(cHandlep,1,0,exchange,payload,exchange_nonce(exchange),"accounts","GET")) != 0 )
{
free_json(json);
}
return(retstr); // return standardized orderstatus
}
char *CANCELORDER(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char payload[1024],*retstr = 0; cJSON *json;
// generate payload
if ( (json= SIGNPOST(cHandlep,1,0,exchange,payload,exchange_nonce(exchange),"accounts","GET")) != 0 )
{
free_json(json);
}
return(retstr); // return standardized cancelorder
}
char *OPENORDERS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],*retstr = 0; cJSON *json;
// generate payload
if ( (json= SIGNPOST(cHandlep,1,0,exchange,payload,exchange_nonce(exchange),"accounts","GET")) != 0 )
{
free_json(json);
}
return(retstr); // return standardized open orders
}
char *TRADEHISTORY(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],*retstr = 0; cJSON *json;
// generate payload
if ( (json= SIGNPOST(cHandlep,1,0,exchange,payload,exchange_nonce(exchange),"accounts","GET")) != 0 )
{
free_json(json);
}
return(retstr); // return standardized tradehistory
}
char *WITHDRAW(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],*retstr = 0; cJSON *json;
// generate payload
if ( (json= SIGNPOST(cHandlep,1,0,exchange,payload,exchange_nonce(exchange),"accounts","GET")) != 0 )
{
free_json(json);
}
return(retstr); // return standardized withdraw
}
struct exchange_funcs coinbase_funcs = EXCHANGE_FUNCS(coinbase,EXCHANGE_NAME);
#undef UPDATE
#undef SUPPORTS
#undef SIGNPOST
#undef TRADE
#undef ORDERSTATUS
#undef CANCELORDER
#undef OPENORDERS
#undef TRADEHISTORY
#undef BALANCES
#undef PARSEBALANCE
#undef WITHDRAW
#undef EXCHANGE_NAME
#undef EXCHANGE_AUTHURL
#undef CHECKBALANCE

183
InstantDEX/exchanges/huobi.c

@ -0,0 +1,183 @@
/******************************************************************************
* Copyright © 2014-2015 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 EXCHANGE_NAME "huobi"
#define UPDATE prices777_ ## huobi
#define SUPPORTS huobi ## _supports
#define SIGNPOST huobi ## _signpost
#define TRADE huobi ## _trade
#define ORDERSTATUS huobi ## _orderstatus
#define CANCELORDER huobi ## _cancelorder
#define OPENORDERS huobi ## _openorders
#define TRADEHISTORY huobi ## _tradehistory
#define BALANCES huobi ## _balances
#define PARSEBALANCE huobi ## _parsebalance
#define WITHDRAW huobi ## _withdraw
#define CHECKBALANCE huobi ## _checkbalance
double UPDATE(struct prices777 *prices,int32_t maxdepth)
{
if ( prices->url[0] == 0 )
sprintf(prices->url,"http://api.huobi.com/staticmarket/depth_%s_json.js ",prices->lbase);
return(prices777_standard("huobi",prices->url,prices,0,0,maxdepth,0));
}
int32_t SUPPORTS(char *base,char *rel)
{
char *baserels[][2] = { {"btc","cny"}, {"ltc","cny"} };
return(baserel_polarity(baserels,(int32_t)(sizeof(baserels)/sizeof(*baserels)),base,rel));
}
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *payload)
{
char *data; cJSON *json;
json = 0;
//if ( (data= curl_post(&cHandle,"https://api.huobi.com/apiv3",0,payload,"Content-Type:application/x-www-form-urlencoded",0,0,0)) != 0 )
if ( dotrade == 0 )
data = exchange_would_submit(payload,"","","","");
else if ( (data= curl_post(cHandlep,"https://api.huobi.com/apiv3",0,payload,"",0,0,0)) != 0 )
json = cJSON_Parse(data);
if ( retstrp != 0 )
*retstrp = data;
else if ( data != 0 )
free(data);
return(json);
}
cJSON *huobi_issue_auth(void **cHandlep,struct exchange_info *exchange,char *method,char *buf)
{
char payload[1024],digest[33],tmp[1024]; uint64_t nonce;
nonce = exchange_nonce(exchange);
sprintf(tmp,"access_key=%s&created=%llu&method=%s%s",exchange->apikey,(long long)nonce,method,buf);
sprintf(payload,"%s&secret_key=%s",tmp,exchange->apisecret);
//printf("tmp.(%s) payload.(%s)\n",tmp,payload);
calc_md5(digest,payload,(int32_t)strlen(payload));
sprintf(payload,"%s&sign=%s",tmp,digest);
//printf("-> (%s)\n",payload);
return(SIGNPOST(cHandlep,1,0,exchange,payload));
}
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr)
{
char field[128],*itemstr = 0; cJSON *obj,*item;
*balancep = 0.;
strcpy(field,coinstr);
tolowercase(field);
if ( exchange->balancejson != 0 && (obj= jobj(exchange->balancejson,"return")) != 0 && (item= jobj(obj,"funds")) != 0 )
{
*balancep = jdouble(item,field);
obj = cJSON_CreateObject();
touppercase(field);
jaddstr(obj,"base",field);
jaddnum(obj,"balance",*balancep);
itemstr = jprint(obj,1);
}
if ( itemstr == 0 )
return(clonestr("{\"error\":\"cant find coin balance\"}"));
return(itemstr);
}
cJSON *BALANCES(void **cHandlep,struct exchange_info *exchange)
{
return(huobi_issue_auth(cHandlep,exchange,"get_account_info",""));
}
#include "checkbalance.c"
uint64_t TRADE(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume)
{
char payload[1024],pairstr[64],pricestr[64],*extra,*method; cJSON *json; int32_t type; uint64_t txid = 0;
if ( (extra= *retstrp) != 0 )
*retstrp = 0;
if ( (dir= flipstr_for_exchange(exchange,pairstr,"%s%s",dir,&price,&volume,base,rel)) == 0 )
{
printf("cant find baserel (%s/%s)\n",base,rel);
return(0);
}
if ( extra != 0 && strcmp(extra,"market") == 0 )
method = (dir > 0) ? "buy_market" : "sell_market";
else method = (dir > 0) ? "buy" : "sell", sprintf(pricestr,"&price=%.2f",price);
if ( strcmp(pairstr,"btccny") == 0 )
type = 1;
else if ( strcmp(pairstr,"ltccny") == 0 )
type = 2;
else
{
printf("cant find baserel (%s/%s)\n",base,rel);
return(0);
}
sprintf(payload,"&amount=%.4f&coin_type=%d%s",volume,type,pricestr);
if ( CHECKBALANCE(retstrp,dotrade,exchange,dir,base,rel,price,volume) == 0 && (json= huobi_issue_auth(cHandlep,exchange,method,payload)) != 0 )
{
txid = j64bits(json,"order_id");
free_json(json);
}
return(txid);
}
char *ORDERSTATUS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char payload[1024];
sprintf(payload,"&id=%llu&coin_type=1",(long long)quoteid);
return(jprint(huobi_issue_auth(cHandlep,exchange,"order_info",payload),1));
}
char *CANCELORDER(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char payload[1024];
sprintf(payload,"&id=%llu&coin_type=1",(long long)quoteid);
return(jprint(huobi_issue_auth(cHandlep,exchange,"cancel_order",payload),1));
}
char *OPENORDERS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
return(jprint(huobi_issue_auth(cHandlep,exchange,"get_orders","&coin_type=1"),1));
}
char *TRADEHISTORY(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
return(clonestr("{\"error\":\"huobi doesnt seem to have trade history api!\"}"));
}
char *WITHDRAW(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],*base,*destaddr,*method; double amount;
if ( (base= jstr(argjson,"base")) == 0 || strcmp(base,"BTC") != 0 )
return(clonestr("{\"error\":\"base not specified or base != BTC\"}"));
if ( (destaddr= jstr(argjson,"destaddr")) == 0 )
return(clonestr("{\"error\":\"destaddr not specified\"}"));
if ( (amount= jdouble(argjson,"amount")) < SMALLVAL )
return(clonestr("{\"error\":\"amount not specified\"}"));
method = "withdraw_coin";
sprintf(payload,"&coin_type=1&withdraw_address=%s&withdraw_amount=%.4f",destaddr,amount);
return(jprint(huobi_issue_auth(cHandlep,exchange,method,payload),1));
}
struct exchange_funcs huobi_funcs = EXCHANGE_FUNCS(huobi,EXCHANGE_NAME);
#undef UPDATE
#undef SUPPORTS
#undef SIGNPOST
#undef TRADE
#undef ORDERSTATUS
#undef CANCELORDER
#undef OPENORDERS
#undef TRADEHISTORY
#undef BALANCES
#undef PARSEBALANCE
#undef WITHDRAW
#undef EXCHANGE_NAME
#undef CHECKBALANCE

285
InstantDEX/exchanges/lakebtc.c

@ -0,0 +1,285 @@
/******************************************************************************
* Copyright © 2014-2015 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 EXCHANGE_NAME "lakebtc"
#define UPDATE prices777_ ## lakebtc
#define SUPPORTS lakebtc ## _supports
#define SIGNPOST lakebtc ## _signpost
#define TRADE lakebtc ## _trade
#define ORDERSTATUS lakebtc ## _orderstatus
#define CANCELORDER lakebtc ## _cancelorder
#define OPENORDERS lakebtc ## _openorders
#define TRADEHISTORY lakebtc ## _tradehistory
#define BALANCES lakebtc ## _balances
#define PARSEBALANCE lakebtc ## _parsebalance
#define WITHDRAW lakebtc ## _withdraw
#define CHECKBALANCE lakebtc ## _checkbalance
double UPDATE(struct prices777 *prices,int32_t maxdepth)
{
if ( prices->url[0] == 0 )
{
if ( strcmp(prices->rel,"USD") == 0 )
sprintf(prices->url,"https://www.LakeBTC.com/api_v1/bcorderbook");
else if ( strcmp(prices->rel,"CNY") == 0 )
sprintf(prices->url,"https://www.LakeBTC.com/api_v1/bcorderbook_cny");
else printf("illegal lakebtc pair.(%s/%s)\n",prices->base,prices->rel);
}
return(prices777_standard("lakebtc",prices->url,prices,0,0,maxdepth,0));
}
int32_t SUPPORTS(char *base,char *rel)
{
char *baserels[][2] = { {"btc","usd"}, {"btc","cny"} };
int32_t polarity;
polarity = baserel_polarity(baserels,(int32_t)(sizeof(baserels)/sizeof(*baserels)),base,rel);
printf("lakebtc.(%s %s) polarity.%d\n",base,rel,polarity);
return(polarity);
}
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *payload,char *hdr1,uint64_t tonce)
{
char hdr2[512],cmdbuf[1024],buf64[1024],hdr3[512],dest[1025],hdr4[512],*sig,*data = 0; cJSON *json;
hdr2[0] = hdr3[0] = hdr4[0] = 0;
json = 0;
if ( (sig= hmac_sha1_str(dest,exchange->apisecret,(int32_t)strlen(exchange->apisecret),hdr1)) != 0 )
{
sprintf(cmdbuf,"%s:%s",exchange->userid,sig);
nn_base64_encode((void *)cmdbuf,strlen(cmdbuf),buf64,sizeof(buf64));
sprintf(hdr1,"Authorization:Basic %s",buf64);
sprintf(hdr2,"Json-Rpc-Tonce: %llu",(long long)tonce);
if ( dotrade == 0 )
data = exchange_would_submit(payload,hdr1,hdr2,hdr3,hdr4);
else if ( (data= curl_post(cHandlep,"https://www.LakeBTC.com/api_v1",0,payload,hdr1,hdr2,hdr3,hdr4)) != 0 )
json = cJSON_Parse(data);
}
if ( retstrp != 0 )
*retstrp = data;
else if ( data != 0 )
free(data);
return(json);
}
/* LakeBTC provides trading JSON-RPC API interface. HMAC (Hash-based Message Authentication Code) is employed as our authentication mechanisms. You need at 0.1 BTC in your account to retrieve your private key.
Besides your private key, the client needs to prepare the following attributes
tonce (timestamp in microseconds, i.e., unixtime × 1000000, make sure your clock is correctly adjusted)
accesskey (your registered email address at LakeBTC)
requestmethod (post)
id (JSON-RPC request id, an integer)
method (JSON-RPC method)
params (JSON-RPC parameters)
Concatenate the above parameters with &, in that order. Parameters can be blank. For example, $signature =
tonce=1389067414466757&accesskey=foo@bar.com&requestmethod=post&id=123&method=ticker&params=
Create HMAC signature with your private key by using SHA1. $hash =
hash_hmac('sha1', $signature, $privatetkey) #php
Join your email and the hash signature with colon (:), and sign with Base64. $b64 =
base64_encode("foo@bar.com:<hash>") #php YXRjQHF3amlhbi5jb206ZmEzM2UzYzg5MDZjg5MzdiYzFiYw==
Set HTTP Header. Note tonce is the same as that in Step 2.
Json-Rpc-Tonce: 1389067414466757 #HTTP HEADER
Authorization: Basic YXRjQHF3amlhbi5jb206ZmEzM2UzYzg5MDZjg5MzdiYzFiYw== #HTTP HEADER
POST params data in JSON format to this url:
https://www.LakeBTC.com/api_v1
API Methods
getAccountInfo
method=getAccountInfo
params= (i.e., blank)
static CURL *cHandle;
char *data,*method,buf64[4096],paramstr[128],jsonbuf[1024],base[64],rel[64],pairstr[64],params[1024],dest[512],url[1024],cmdbuf[8192],*sig,hdr1[4096],hdr2[4096],buf[4096]; cJSON *json; uint64_t tonce,nonce,txid = 0;
*retstrp = 0;
params[0] = 0;
nonce = exchange_nonce(exchange);
tonce = (nonce * 1000000 + ((uint64_t)milliseconds() % 1000) * 1000);
if ( dir == 0 )
{
method = "getAccountInfo";
sprintf(buf,"tonce=%llu&accesskey=%s&requestmethod=post&id=1&method=%s&params=",(long long)tonce,exchange->userid,method);
sprintf(jsonbuf,"{\"method\":\"%s\",\"params\":[\"%s\"],\"id\":1}",method,params);
}
else
{
if ( (dir= flipstr_for_exchange(exchange,pairstr,"%s_%s",dir,&price,&volume,base,rel)) == 0 )
{
printf("cant find baserel (%s/%s)\n",base,rel);
return(0);
}
method = (dir > 0) ? "buyOrder" : "sellOrder";
touppercase(rel);
sprintf(paramstr,"%.2f,%.4f,%s",price,volume,rel);
sprintf(buf,"tonce=%llu&accesskey=%s&requestmethod=post&id=1&method=%s&params=%s",(long long)tonce,exchange->userid,method,paramstr);
sprintf(jsonbuf,"{\"method\":\"%s\",\"params\":[\"%s\"],\"id\":1}",method,paramstr);
}
if ( (sig= hmac_sha1_str(dest,exchange->apisecret,(int32_t)strlen(exchange->apisecret),buf)) != 0 )
{
sprintf(cmdbuf,"%s:%s",exchange->userid,sig);
nn_base64_encode((void *)cmdbuf,strlen(cmdbuf),buf64,sizeof(buf64));
sprintf(url,"https://www.lakebtc.com/api_v1");
sprintf(hdr1,"Authorization:Basic %s",buf64);
sprintf(hdr2,"Json-Rpc-Tonce: %llu",(long long)tonce);
if ( (data= curl_post(&cHandle,url,0,jsonbuf,hdr1,hdr2,0,0)) != 0 )
{
//printf("submit cmd.(%s) [%s]\n",jsonbuf,data);
if ( (json= cJSON_Parse(data)) != 0 )
{
txid = j64bits(json,"order_id");
free_json(json);
}
} else fprintf(stderr,"submit err cmd.(%s)\n",cmdbuf);
if ( retstrp != 0 )
*retstrp = data;
else if ( data != 0 )
free(data);
}
*/
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr)
{
//lakebtc.({"balance":{"BTC":0.1},"locked":{"BTC":0.0},"profile":{"email":"jameslee777@yahoo.com","id":"U137561934","btc_deposit_addres":"1RyKrNJjezeFfvYaicnJEozHfhWfYzbuh"}})
char field[128],*str,*itemstr = 0; cJSON *obj=0,*item=0,*prof=0; double locked = 0;
*balancep = 0.;
strcpy(field,coinstr);
touppercase(field);
if ( exchange->balancejson != 0 && (obj= jobj(exchange->balancejson,"balance")) != 0 && (item= jobj(exchange->balancejson,"locked")) != 0 && (prof= jobj(exchange->balancejson,"profile")) != 0 )
{
*balancep = jdouble(obj,field);
locked = jdouble(item,field);
obj = cJSON_CreateObject();
jaddstr(obj,"base",field);
jaddnum(obj,"balance",*balancep);
jaddnum(obj,"locked",locked);
if ( (str= jstr(prof,"btc_deposit_addres")) != 0 )
jaddstr(obj,"deposit_address",str);
itemstr = jprint(obj,1);
}
if ( itemstr == 0 )
return(clonestr("{\"error\":\"cant find coin balance\"}"));
return(itemstr);
}
cJSON *BALANCES(void **cHandlep,struct exchange_info *exchange)
{
char payload[1024],jsonbuf[1024],*method; uint64_t tonce;
method = "getAccountInfo";
tonce = (exchange_nonce(exchange) * 1000000 + ((uint64_t)milliseconds() % 1000) * 1000);
sprintf(payload,"tonce=%llu&accesskey=%s&requestmethod=post&id=1&method=%s&params=",(long long)tonce,exchange->userid,method);
sprintf(jsonbuf,"{\"method\":\"%s\",\"params\":[\"%s\"],\"id\":1}",method,"");
return(SIGNPOST(cHandlep,1,0,exchange,jsonbuf,payload,tonce));
}
#include "checkbalance.c"
uint64_t TRADE(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume)
{
char payload[1024],jsonbuf[1024],pairstr[64],paramstr[512],*extra,*method;
cJSON *json; uint64_t tonce,txid = 0;
if ( (extra= *retstrp) != 0 )
*retstrp = 0;
tonce = (exchange_nonce(exchange) * 1000000 + ((uint64_t)milliseconds() % 1000) * 1000);
if ( (dir= flipstr_for_exchange(exchange,pairstr,"%s_%s",dir,&price,&volume,base,rel)) == 0 )
{
printf("cant find baserel (%s/%s)\n",base,rel);
return(0);
}
method = (dir > 0) ? "buyOrder" : "sellOrder";
touppercase(rel);
sprintf(paramstr,"%.2f,%.4f,%s",price,volume,rel);
sprintf(payload,"tonce=%llu&accesskey=%s&requestmethod=post&id=1&method=%s&params=%s",(long long)tonce,exchange->userid,method,paramstr);
sprintf(jsonbuf,"{\"method\":\"%s\",\"params\":[\"%s\"],\"id\":1}",method,paramstr);
if ( CHECKBALANCE(retstrp,dotrade,exchange,dir,base,rel,price,volume) == 0 && (json= SIGNPOST(cHandlep,dotrade,retstrp,exchange,jsonbuf,payload,tonce)) != 0 )
{
txid = j64bits(json,"order_id");
free_json(json);
}
return(txid);
}
char *CANCELORDER(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char payload[1024],jsonbuf[1024],*method,*retstr = 0; cJSON *json; uint64_t tonce;
method = "cancelOrder";
tonce = (exchange_nonce(exchange) * 1000000 + ((uint64_t)milliseconds() % 1000) * 1000);
sprintf(jsonbuf,"{\"method\":\"%s\",\"params\":[\"%llu\"],\"id\":1}",method,(long long)quoteid);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,jsonbuf,tonce)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized cancelorder
}
char *OPENORDERS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],jsonbuf[1024],*method,*retstr = 0; cJSON *json; uint64_t tonce;
method = "getOrders";
tonce = (exchange_nonce(exchange) * 1000000 + ((uint64_t)milliseconds() % 1000) * 1000);
sprintf(jsonbuf,"{\"method\":\"%s\",\"params\":[\"%s\"],\"id\":1}",method,"");
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,jsonbuf,tonce)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized open orders
}
char *TRADEHISTORY(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],jsonbuf[1024],timestr[64],*method,*retstr = 0;
cJSON *json; uint64_t tonce; uint32_t starttime;
method = "getTrades";
if ( (starttime= juint(argjson,"start")) != 0 )
sprintf(timestr,"%u",starttime);
else timestr[0] = 0;
tonce = (exchange_nonce(exchange) * 1000000 + ((uint64_t)milliseconds() % 1000) * 1000);
sprintf(jsonbuf,"{\"method\":\"%s\",\"params\":[%s],\"id\":1}",method,timestr);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,payload,jsonbuf,tonce)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized tradehistory
}
char *ORDERSTATUS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char *status,*retstr;
status = OPENORDERS(cHandlep,exchange,argjson);
if ( (retstr= exchange_extractorderid(0,status,quoteid,"id")) != 0 )
{
free(status);
return(retstr);
}
free(status);
return(clonestr("{\"error\":\"cant find quoteid\"}"));
}
char *WITHDRAW(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
return(clonestr("{\"error\":\"lakebtc doesnt seem to have withdraw api!\"}"));
}
struct exchange_funcs lakebtc_funcs = EXCHANGE_FUNCS(lakebtc,EXCHANGE_NAME);
#undef UPDATE
#undef SUPPORTS
#undef SIGNPOST
#undef TRADE
#undef ORDERSTATUS
#undef CANCELORDER
#undef OPENORDERS
#undef TRADEHISTORY
#undef BALANCES
#undef PARSEBALANCE
#undef WITHDRAW
#undef EXCHANGE_NAME
#undef CHECKBALANCE

239
InstantDEX/exchanges/okcoin.c

@ -0,0 +1,239 @@
/******************************************************************************
* Copyright © 2014-2015 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 EXCHANGE_NAME "okcoin"
#define UPDATE prices777_ ## okcoin
#define SUPPORTS okcoin ## _supports
#define SIGNPOST okcoin ## _signpost
#define TRADE okcoin ## _trade
#define ORDERSTATUS okcoin ## _orderstatus
#define CANCELORDER okcoin ## _cancelorder
#define OPENORDERS okcoin ## _openorders
#define TRADEHISTORY okcoin ## _tradehistory
#define BALANCES okcoin ## _balances
#define PARSEBALANCE okcoin ## _parsebalance
#define WITHDRAW okcoin ## _withdraw
#define EXCHANGE_AUTHURL "https://www.okcoin.com/api/v1"
#define CHECKBALANCE okcoin ## _checkbalance
double UPDATE(struct prices777 *prices,int32_t maxdepth)
{
if ( prices->url[0] == 0 )
sprintf(prices->url,"https://www.okcoin.com/api/v1/depth.do?symbol=%s_%s",prices->lbase,prices->lrel);
if ( strcmp(prices->rel,"USD") != 0 && strcmp(prices->rel,"BTC") != 0 )
{
fprintf(stderr,">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> FATAL ERROR OKCOIN.(%s) only supports USD\n",prices->url);
printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> FATAL ERROR OKCOIN.(%s) only supports USD\n",prices->url);
exit(-1);
return(0);
}
return(prices777_standard("okcoin",prices->url,prices,0,0,maxdepth,0));
}
int32_t SUPPORTS(char *base,char *rel)
{
char *baserels[][2] = { {"btc","usd"}, {"ltc","usd"} };
return(baserel_polarity(baserels,(int32_t)(sizeof(baserels)/sizeof(*baserels)),base,rel));
}
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *url,char *payload)
{
char hdr1[512],hdr2[512],hdr3[512],hdr4[512],*data; cJSON *json;
hdr1[0] = hdr2[0] = hdr3[0] = hdr4[0] = 0;
json = 0;
if ( dotrade == 0 )
data = exchange_would_submit(payload,hdr1,hdr2,hdr3,hdr4);
else if ( (data= curl_post(cHandlep,url,0,payload,hdr1,hdr2,hdr3,hdr4)) != 0 )
json = cJSON_Parse(data);
if ( retstrp != 0 )
*retstrp = data;
else if ( data != 0 )
free(data);
return(json);
}
/*
static CURL *cHandle;
char *data,*path,*typestr,*extra,pricestr[64],base[64],rel[64],pairstr[64],url[1024],cmdbuf[8192],buf[512],digest[33]; cJSON *json; uint64_t nonce,txid = 0;
nonce = exchange_nonce(exchange);
if ( (extra= *retstrp) != 0 )
*retstrp = 0;
if ( dir == 0 )
{
path = "userinfo.do";
sprintf(buf,"api_key=%s&secret_key=%s",exchange->apikey,exchange->apisecret);
calc_md5(digest,buf,(int32_t)strlen(buf));
touppercase(digest);
sprintf(cmdbuf,"api_key=%s&sign=%s",exchange->apikey,digest);
}
else
{
path = "trade.do";
if ( (dir= flipstr_for_exchange(exchange,pairstr,"%s_%s",dir,&price,&volume,base,rel)) == 0 )
{
printf("cant find baserel (%s/%s)\n",base,rel);
return(0);
}
if ( extra != 0 && strcmp(extra,"market") == 0 )
typestr = (dir > 0) ? "buy_market" : "sell_market", sprintf(pricestr,"&price=%.2f",price); // docs say market orders put volume in price
else typestr = (dir > 0) ? "buy" : "sell", sprintf(pricestr,"&price=%.2f",price);
sprintf(buf,"amount=%.4f&api_key=%s%ssymbol=%s&type=%s&secret_key=%s",volume,exchange->apikey,pricestr,pairstr,typestr,exchange->apisecret);
calc_md5(digest,buf,(int32_t)strlen(buf));
touppercase(digest);
sprintf(cmdbuf,"amount=%.4f&api_key=%s%s&symbol=%s&type=%s&sign=%s",volume,exchange->apikey,pricestr,pairstr,typestr,digest);
}
//printf("MD5.(%s)\n",buf);
sprintf(url,"https://www.okcoin.com/api/v1/%s",path);
if ( (data= curl_post(&cHandle,url,0,cmdbuf,0,0,0,0)) != 0 ) // "{\"Content-type\":\"application/x-www-form-urlencoded\"}","{\"User-Agent\":\"OKCoin Javascript API Client\"}"
{
//printf("submit cmd.(%s) [%s]\n",cmdbuf,data);
if ( (json= cJSON_Parse(data)) != 0 )
{
txid = j64bits(json,"order_id");
free_json(json);
}
} else fprintf(stderr,"submit err cmd.(%s)\n",cmdbuf);
*/
cJSON *okcoin_issue_auth(void **cHandlep,struct exchange_info *exchange,char *method,char *buf)
{
char payload[1024],tmp[1024],digest[512],url[512];
sprintf(tmp,"api_key=%s%s",exchange->apikey,buf);
sprintf(payload,"%s&secret_key=%s",tmp,exchange->apisecret);
//printf("tmp.(%s) payload.(%s)\n",tmp,payload);
calc_md5(digest,payload,(int32_t)strlen(payload));
touppercase(digest);
sprintf(payload,"%s&sign=%s",tmp,digest);
sprintf(url,"%s/%s",EXCHANGE_AUTHURL,method);
return(SIGNPOST(cHandlep,1,0,exchange,url,payload));
}
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr)
{
//okcoin.({"info":{"funds":{"asset":{"net":"0","total":"0"},"free":{"btc":"0","ltc":"0","usd":"0"},"freezed":{"btc":"0","ltc":"0","usd":"0"}}},"result":true})
char field[128],*itemstr = 0; cJSON *obj,*item,*avail,*locked; double lockval = 0;
*balancep = 0.;
strcpy(field,coinstr);
tolowercase(field);
if ( exchange->balancejson != 0 && (obj= jobj(exchange->balancejson,"info")) != 0 && (item= jobj(obj,"funds")) != 0 )
{
if ( (avail= jobj(item,"free")) != 0 )
*balancep = jdouble(avail,field);
if ( (locked= jobj(item,"freezed")) != 0 )
lockval = jdouble(locked,field);
obj = cJSON_CreateObject();
touppercase(field);
jaddstr(obj,"base",field);
jaddnum(obj,"balance",*balancep);
jaddnum(obj,"locked",lockval);
itemstr = jprint(obj,1);
}
if ( itemstr == 0 )
return(clonestr("{\"error\":\"cant find coin balance\"}"));
return(itemstr);
}
cJSON *BALANCES(void **cHandlep,struct exchange_info *exchange)
{
return(okcoin_issue_auth(cHandlep,exchange,"userinfo.do",""));
}
#include "checkbalance.c"
uint64_t TRADE(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume)
{
char payload[1024],buf[1024],url[1024],digest[512],pairstr[512],pricestr[64],*extra,*typestr;
cJSON *json; uint64_t txid = 0;
if ( (extra= *retstrp) != 0 )
*retstrp = 0;
if ( (dir= flipstr_for_exchange(exchange,pairstr,"%s_%s",dir,&price,&volume,base,rel)) == 0 )
{
printf("cant find baserel (%s/%s)\n",base,rel);
return(0);
}
if ( extra != 0 && strcmp(extra,"market") == 0 )
typestr = (dir > 0) ? "buy_market" : "sell_market", sprintf(pricestr,"&price=%.2f",price); // docs say market orders put volume in price
else typestr = (dir > 0) ? "buy" : "sell";
sprintf(pricestr,"&price=%.2f",price);
sprintf(buf,"amount=%.4f&api_key=%s%ssymbol=%s&type=%s&secret_key=%s",volume,exchange->apikey,pricestr,pairstr,typestr,exchange->apisecret);
calc_md5(digest,buf,(int32_t)strlen(buf));
touppercase(digest);
sprintf(payload,"amount=%.4f&api_key=%s%s&symbol=%s&type=%s&sign=%s",volume,exchange->apikey,pricestr,pairstr,typestr,digest);
sprintf(url,"%s/%s",EXCHANGE_AUTHURL,"trade.do");
if ( CHECKBALANCE(retstrp,dotrade,exchange,dir,base,rel,price,volume) == 0 && (json= SIGNPOST(cHandlep,dotrade,retstrp,exchange,url,payload)) != 0 )
{
txid = j64bits(json,"order_id");
free_json(json);
}
return(txid);
}
char *ORDERSTATUS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char buf[64];
sprintf(buf,"&symbol=btc_usd&order_id=%llu",(long long)quoteid);
return(jprint(okcoin_issue_auth(cHandlep,exchange,"order_info.do",buf),1));
}
char *CANCELORDER(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char buf[64];
sprintf(buf,"&symbol=btc_usd&order_id=%llu",(long long)quoteid);
return(jprint(okcoin_issue_auth(cHandlep,exchange,"cancel_order.do",buf),1));
}
char *OPENORDERS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
return(jprint(okcoin_issue_auth(cHandlep,exchange,"orders_info.do",""),1));
}
char *TRADEHISTORY(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
return(jprint(okcoin_issue_auth(cHandlep,exchange,"orders_history.do","&status=1&symbol=btc_usd&current_page=0&page_length=200"),1));
}
char *WITHDRAW(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],*base,*destaddr,*method,*tradepassword; double amount;
if ( (base= jstr(argjson,"base")) == 0 || strcmp(base,"BTC") != 0 )
return(clonestr("{\"error\":\"base not specified or base != BTC\"}"));
if ( (destaddr= jstr(argjson,"destaddr")) == 0 )
return(clonestr("{\"error\":\"destaddr not specified\"}"));
if ( (amount= jdouble(argjson,"amount")) < SMALLVAL )
return(clonestr("{\"error\":\"amount not specified\"}"));
if ( (tradepassword= jstr(argjson,"tradepassword")) == 0 )
return(clonestr("{\"error\":\"tradepassword not specified\"}"));
method = "withdraw_coin";
sprintf(payload,"&symbol=btc_usd&chargefee=0.0001&withdraw_address=%s&withdraw_amount=%.4f&trade_pwd=%s",destaddr,amount,tradepassword);
return(jprint(okcoin_issue_auth(cHandlep,exchange,method,payload),1));
}
struct exchange_funcs okcoin_funcs = EXCHANGE_FUNCS(okcoin,EXCHANGE_NAME);
#undef UPDATE
#undef SUPPORTS
#undef SIGNPOST
#undef TRADE
#undef ORDERSTATUS
#undef CANCELORDER
#undef OPENORDERS
#undef TRADEHISTORY
#undef BALANCES
#undef PARSEBALANCE
#undef WITHDRAW
#undef EXCHANGE_NAME
#undef EXCHANGE_AUTHURL
#undef CHECKBALANCE

233
InstantDEX/exchanges/poloniex.c

@ -0,0 +1,233 @@
/******************************************************************************
* Copyright © 2014-2015 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 EXCHANGE_NAME "poloniex"
#define UPDATE prices777_ ## poloniex
#define SUPPORTS poloniex ## _supports
#define SIGNPOST poloniex ## _signpost
#define TRADE poloniex ## _trade
#define ORDERSTATUS poloniex ## _orderstatus
#define CANCELORDER poloniex ## _cancelorder
#define OPENORDERS poloniex ## _openorders
#define TRADEHISTORY poloniex ## _tradehistory
#define BALANCES poloniex ## _balances
#define PARSEBALANCE poloniex ## _parsebalance
#define WITHDRAW poloniex ## _withdraw
#define EXCHANGE_AUTHURL "https://poloniex.com/tradingApi"
#define CHECKBALANCE poloniex ## _checkbalance
double UPDATE(struct prices777 *prices,int32_t maxdepth)
{
char market[128];
if ( prices->url[0] == 0 )
{
sprintf(market,"%s_%s",prices->rel,prices->base);
sprintf(prices->url,"https://poloniex.com/public?command=returnOrderBook&currencyPair=%s&depth=%d",market,maxdepth);
}
return(prices777_standard(EXCHANGE_NAME,prices->url,prices,0,0,maxdepth,0));
}
int32_t SUPPORTS(char *base,char *rel)
{
//char *baserels[][2] = { {"btc","usd"} };
//return(baserel_polarity(baserels,(int32_t)(sizeof(baserels)/sizeof(*baserels)),base,rel));
if ( strlen(base) > 5 || strlen(rel) > 5 || strcmp(rel,"CNY") == 0 || strcmp(base,"CNY") == 0 || strcmp(rel,"USD") == 0 || strcmp(base,"USD") == 0 )
return(0);
if ( strcmp(rel,"BTC") == 0 )
return(1);
else if ( strcmp(base,"BTC") == 0 )
return(-1);
else return(0);
}
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *url,char *payload)
{
char dest[SHA512_DIGEST_SIZE*2+1],hdr1[512],hdr2[512],hdr3[512],hdr4[512],*data,*sig; cJSON *json;
hdr1[0] = hdr2[0] = hdr3[0] = hdr4[0] = 0;
json = 0;
if ( (sig= hmac_sha512_str(dest,exchange->apisecret,(int32_t)strlen(exchange->apisecret),payload)) != 0 )
sprintf(hdr1,"Sign:%s",sig);
else hdr1[0] = 0;
sprintf(hdr2,"Key:%s",exchange->apikey);
if ( dotrade == 0 )
data = exchange_would_submit(payload,hdr1,hdr2,hdr3,hdr4);
else if ( (data= curl_post(cHandlep,url,0,payload,hdr1,hdr2,hdr3,hdr4)) != 0 )
json = cJSON_Parse(data);
if ( retstrp != 0 )
*retstrp = data;
else if ( data != 0 )
free(data);
return(json);
}
cJSON *BALANCES(void **cHandlep,struct exchange_info *exchange)
{
char payload[1024];
sprintf(payload,"command=returnCompleteBalances&nonce=%llu",(long long)exchange_nonce(exchange));
return(SIGNPOST(cHandlep,1,0,exchange,EXCHANGE_AUTHURL,payload));
}
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr)
{
char *itemstr = 0; cJSON *item,*obj; double onorders,btcvalue;
*balancep = 0.;
if ( exchange->balancejson != 0 && (item= jobj(exchange->balancejson,coinstr)) != 0 )
{
itemstr = jprint(item,0);
*balancep = jdouble(item,"available");
onorders = jdouble(item,"onOrders");
btcvalue = jdouble(item,"btcValue");
if ( (obj= cJSON_Parse(itemstr)) != 0 )
{
free(itemstr);
jaddstr(obj,"base",coinstr);
jaddnum(obj,"balance",*balancep);
jaddnum(obj,"onOrders",onorders);
jaddnum(obj,"btcvalue",btcvalue);
itemstr = jprint(obj,1);
}
}
if ( itemstr == 0 )
return(clonestr("{\"error\":\"cant find coin balance\"}"));
return(itemstr);
}
#include "checkbalance.c"
uint64_t TRADE(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume)
{
char payload[1024],pairstr[64],*extra,*typestr; cJSON *json; uint64_t nonce,txid = 0;
nonce = exchange_nonce(exchange);
if ( (extra= *retstrp) != 0 )
*retstrp = 0;
dir = flip_for_exchange(pairstr,"%s_%s","BTC",dir,&price,&volume,base,rel);
if ( extra != 0 && strcmp(extra,"margin") == 0 )
typestr = (dir > 0) ? "marginBuy":"marginSell";
else typestr = (dir > 0) ? "buy":"sell";
sprintf(payload,"command=%s&nonce=%lld&currencyPair=%s&rate=%.8f&amount=%.8f",typestr,(long long)nonce,pairstr,price,volume);
if ( CHECKBALANCE(retstrp,dotrade,exchange,dir,base,rel,price,volume) == 0 && (json= SIGNPOST(cHandlep,dotrade,retstrp,exchange,EXCHANGE_AUTHURL,payload)) != 0 )
{
txid = (get_API_nxt64bits(cJSON_GetObjectItem(json,"orderNumber")) << 32) | get_API_nxt64bits(cJSON_GetObjectItem(json,"tradeID"));
free_json(json);
}
return(txid);
}
void poloniex_setpair(char *pair,cJSON *argjson)
{
char *base,*rel;
base = jstr(argjson,"base");
rel = jstr(argjson,"rel");
if ( base == 0 || rel == 0 )
strcpy(pair,"all");
else sprintf(pair,"%s_%s",rel,base);
}
char *CANCELORDER(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char payload[1024],*retstr = 0; cJSON *json;
sprintf(payload,"command=cancelOrder&nonce=%llu&orderNumber=%llu",(long long)exchange_nonce(exchange),(long long)quoteid);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,EXCHANGE_AUTHURL,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized cancelorder
}
char *OPENORDERS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],pair[64],*retstr = 0; cJSON *json;
poloniex_setpair(pair,argjson);
sprintf(payload,"command=returnOpenOrders&nonce=%llu&currencyPair=%s",(long long)exchange_nonce(exchange),pair);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,EXCHANGE_AUTHURL,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized open orders
}
char *TRADEHISTORY(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],pair[64],*retstr = 0; cJSON *json; uint32_t timestamp,endstamp;
poloniex_setpair(pair,argjson);
timestamp = juint(argjson,"start");
endstamp = juint(argjson,"end");
sprintf(payload,"command=returnTradeHistory&nonce=%llu&currencyPair=%s",(long long)exchange_nonce(exchange),pair);
if ( timestamp != 0 )
sprintf(payload + strlen(payload),"&start=%u",timestamp);
if ( endstamp != 0 )
sprintf(payload + strlen(payload),"&end=%u",endstamp);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,EXCHANGE_AUTHURL,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized tradehistory
}
char *ORDERSTATUS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char *status,*retstr; uint32_t iter;
for (iter=0; iter<2; iter++)
{
if ( iter == 0 )
status = OPENORDERS(cHandlep,exchange,argjson);
else status = TRADEHISTORY(cHandlep,exchange,argjson);
if ( (retstr= exchange_extractorderid(iter,status,quoteid,"orderNumber")) != 0 )
{
free(status);
return(retstr);
}
free(status);
}
return(clonestr("{\"error\":\"cant find quoteid\"}"));
}
char *WITHDRAW(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char payload[1024],*destaddr,*paymentid,*base,*retstr = 0; cJSON *json; double amount;
if ( (base= jstr(argjson,"base")) == 0 )
return(clonestr("{\"error\":\"base not specified\"}"));
if ( (destaddr= jstr(argjson,"destaddr")) == 0 )
return(clonestr("{\"error\":\"destaddr not specified\"}"));
if ( (amount= jdouble(argjson,"amount")) < SMALLVAL )
return(clonestr("{\"error\":\"amount not specified\"}"));
paymentid = jstr(argjson,"paymentid");
sprintf(payload,"command=withdraw&nonce=%llu&currency=%s&amount=%.6f&address=%s",(long long)exchange_nonce(exchange),base,amount,destaddr);
if ( paymentid != 0 )
sprintf(payload + strlen(payload),"&paymentId=%s",paymentid);
if ( (json= SIGNPOST(cHandlep,1,&retstr,exchange,EXCHANGE_AUTHURL,payload)) != 0 )
{
free_json(json);
}
return(retstr); // return standardized withdraw
}
struct exchange_funcs poloniex_funcs = EXCHANGE_FUNCS(poloniex,EXCHANGE_NAME);
#undef UPDATE
#undef SUPPORTS
#undef SIGNPOST
#undef TRADE
#undef ORDERSTATUS
#undef CANCELORDER
#undef OPENORDERS
#undef TRADEHISTORY
#undef BALANCES
#undef PARSEBALANCE
#undef WITHDRAW
#undef EXCHANGE_NAME
#undef EXCHANGE_AUTHURL
#undef CHECKBALANCE

183
InstantDEX/exchanges/quadriga.c

@ -0,0 +1,183 @@
/******************************************************************************
* Copyright © 2014-2015 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 EXCHANGE_NAME "quadriga"
#define UPDATE prices777_ ## quadriga
#define SUPPORTS quadriga ## _supports
#define SIGNPOST quadriga ## _signpost
#define TRADE quadriga ## _trade
#define ORDERSTATUS quadriga ## _orderstatus
#define CANCELORDER quadriga ## _cancelorder
#define OPENORDERS quadriga ## _openorders
#define TRADEHISTORY quadriga ## _tradehistory
#define BALANCES quadriga ## _balances
#define PARSEBALANCE quadriga ## _parsebalance
#define WITHDRAW quadriga ## _withdraw
#define CHECKBALANCE quadriga ## _checkbalance
double UPDATE(struct prices777 *prices,int32_t maxdepth)
{
if ( prices->url[0] == 0 )
sprintf(prices->url,"https://api.quadrigacx.com/v2/order_book?book=%s_%s",prices->lbase,prices->lrel);
return(prices777_standard("quadriga",prices->url,prices,0,0,maxdepth,0));
}
int32_t SUPPORTS(char *base,char *rel)
{
char *baserels[][2] = { {"btc","usd"}, {"btc","cad"} };
return(baserel_polarity(baserels,(int32_t)(sizeof(baserels)/sizeof(*baserels)),base,rel));
}
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *payload,char *path)
{
char url[1024],req[1024],md5secret[128],tmp[1024],dest[1025],hdr1[512],hdr2[512],hdr3[512],hdr4[512],*sig,*data = 0;
cJSON *json; uint64_t nonce;
hdr1[0] = hdr2[0] = hdr3[0] = hdr4[0] = 0;
json = 0;
nonce = exchange_nonce(exchange) * 1000 + ((uint64_t)milliseconds() % 1000);
sprintf(tmp,"%llu%s%s",(long long)nonce,exchange->userid,exchange->apikey);
calc_md5(md5secret,exchange->apisecret,(int32_t)strlen(exchange->apisecret));
if ( (sig= hmac_sha256_str(dest,md5secret,(int32_t)strlen(md5secret),tmp)) != 0 )
{
sprintf(req,"{\"key\":\"%s\",%s\"nonce\":%llu,\"signature\":\"%s\"}",exchange->apikey,payload,(long long)nonce,sig);
sprintf(hdr1,"Content-Type:application/json");
sprintf(hdr2,"charset=utf-8");
sprintf(hdr3,"Content-Length:%ld",(long)strlen(req));
sprintf(url,"https://api.quadrigacx.com/v2/%s",path);
if ( dotrade == 0 )
data = exchange_would_submit(req,hdr1,hdr2,hdr3,hdr4);
else if ( (data= curl_post(cHandlep,url,0,req,hdr1,hdr2,hdr3,hdr4)) != 0 )
json = cJSON_Parse(data);
}
if ( retstrp != 0 )
*retstrp = data;
else if ( data != 0 )
free(data);
return(json);
}
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr)
{
//[{"btc_available":"0.00000000","btc_reserved":"0.00000000","btc_balance":"0.00000000","cad_available":"0.00","cad_reserved":"0.00","cad_balance":"0.00","usd_available":"0.00","usd_reserved":"0.00","usd_balance":"0.00","xau_available":"0.000000","xau_reserved":"0.000000","xau_balance":"0.000000","fee":"0.5000"}]
char field[128],*str,*itemstr = 0; cJSON *obj; double reserv,total;
*balancep = 0.;
strcpy(field,coinstr);
tolowercase(field);
strcat(field,"_available");
if ( exchange->balancejson != 0 && (str= jstr(exchange->balancejson,field)) != 0 )
{
*balancep = jdouble(exchange->balancejson,field);
strcpy(field,coinstr), tolowercase(field), strcat(field,"_reserved");
reserv = jdouble(exchange->balancejson,field);
strcpy(field,coinstr), tolowercase(field), strcat(field,"_balance");
total = jdouble(exchange->balancejson,field);
obj = cJSON_CreateObject();
jaddnum(obj,"balance",*balancep);
jaddnum(obj,"locked_balance",reserv);
jaddnum(obj,"total",total);
itemstr = jprint(obj,1);
}
if ( itemstr == 0 )
return(clonestr("{\"error\":\"cant find coin balance\"}"));
return(itemstr);
}
cJSON *BALANCES(void **cHandlep,struct exchange_info *exchange)
{
return(SIGNPOST(cHandlep,1,0,exchange,"","balance"));
}
#include "checkbalance.c"
uint64_t TRADE(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *base,char *rel,int32_t dir,double price,double volume)
{
char payload[1024],pairstr[64],*extra,*path; cJSON *json; uint64_t txid = 0;
if ( (extra= *retstrp) != 0 )
*retstrp = 0;
if ( (dir= flipstr_for_exchange(exchange,pairstr,"%s_%s",dir,&price,&volume,base,rel)) == 0 )
{
printf("cant find baserel (%s/%s)\n",base,rel);
return(0);
}
path = (dir > 0) ? "buy" : "sell";
//key - API key
//signature - signature
//nonce - nonce
//amount - amount of major currency
//price - price to buy at
//book - optional, if not specified, will default to btc_cad
sprintf(payload,"\"amount\":%.6f,\"price\":%.3f,\"book\":\"%s_%s\",",volume,price,base,rel);
if ( CHECKBALANCE(retstrp,dotrade,exchange,dir,base,rel,price,volume) == 0 && (json= SIGNPOST(cHandlep,dotrade,retstrp,exchange,payload,path)) != 0 )
{
// parse json and set txid
free_json(json);
}
return(txid);
}
char *ORDERSTATUS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char buf[64];
sprintf(buf,"\"id\":%llu,",(long long)quoteid);
return(jprint(SIGNPOST(cHandlep,1,0,exchange,buf,"lookup_order"),1));
}
char *CANCELORDER(void **cHandlep,struct exchange_info *exchange,cJSON *argjson,uint64_t quoteid)
{
char buf[64];
sprintf(buf,"\"id\":%llu,",(long long)quoteid);
return(jprint(SIGNPOST(cHandlep,1,0,exchange,buf,"cancel_order"),1));
}
char *OPENORDERS(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
return(jprint(SIGNPOST(cHandlep,1,0,exchange,"","open_orders"),1));
}
char *TRADEHISTORY(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
return(jprint(SIGNPOST(cHandlep,1,0,exchange,"","user_transactions"),1));
}
char *WITHDRAW(void **cHandlep,struct exchange_info *exchange,cJSON *argjson)
{
char buf[1024],*base,*destaddr; double amount;
if ( (base= jstr(argjson,"base")) == 0 || strcmp(base,"BTC") != 0 )
return(clonestr("{\"error\":\"base not specified or base != BTC\"}"));
if ( (destaddr= jstr(argjson,"destaddr")) == 0 )
return(clonestr("{\"error\":\"destaddr not specified\"}"));
if ( (amount= jdouble(argjson,"amount")) < SMALLVAL )
return(clonestr("{\"error\":\"amount not specified\"}"));
sprintf(buf,"\"amount\":%.4f,\"address\":\"%s\",",amount,destaddr);
printf("submit.(%s)\n",buf);
return(jprint(SIGNPOST(cHandlep,1,0,exchange,"","bitcoin_withdrawal"),1));
}
struct exchange_funcs quadriga_funcs = EXCHANGE_FUNCS(quadriga,EXCHANGE_NAME);
#undef UPDATE
#undef SUPPORTS
#undef SIGNPOST
#undef TRADE
#undef ORDERSTATUS
#undef CANCELORDER
#undef OPENORDERS
#undef TRADEHISTORY
#undef BALANCES
#undef PARSEBALANCE
#undef WITHDRAW
#undef EXCHANGE_NAME
#undef CHECKBALANCE

36
InstantDEX/main.c

@ -0,0 +1,36 @@
/******************************************************************************
* Copyright © 2014-2015 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 CHROMEAPP_NAME InstantDEX
#define CHROMEAPP_STR "InstantDEX"
#define CHROMEAPP_CONF "InstantDEX.conf"
#define CHROMEAPP_MAIN InstantDEX_main
#define CHROMEAPP_JSON InstantDEX_JSON
#define CHROMEAPP_HANDLER Handler_InstantDEX
#include "../pnacl_main.h"
// ALL globals must be here!
void InstantDEX_main(void *arg)
{
while ( 1 )
sleep(777);
}
char *InstantDEX_JSON(char *jsonstr)
{
return(clonestr("{\"error\":\"InstantDEX is just a stub for now\"}"));
}

17
InstantDEX/manifest.json

@ -0,0 +1,17 @@
{
"name": "InstantDEX",
"uri": "InstantDEX.pexe",
"short_name": "InstantDEX",
"version": "44.1.2",
"manifest_version": 2,
"description": "InstantDEX",
"offline_enabled": true,
"icons": { "128": "icon128.png" },
"app":
{
"name": "InstantDEX",
"background": { "scripts": ["background.js"] },
"sockets": { "tcp": { "connect": "" }, "tcpServer": { "listen": "127.0.0.1:*" } },
"permissions": [ "unlimitedStorage", "filesystem", "storage", "system.storage", "system.display", "system.network","system.cpu" ]
}
}

3456
InstantDEX/orderbooks.h

File diff suppressed because it is too large

880
InstantDEX/quotes.h

@ -0,0 +1,880 @@
/******************************************************************************
* Copyright © 2014-2015 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
#ifndef xcode_quotes_h
#define xcode_quotes_h
#ifdef oldway
int32_t make_jumpiQ(uint64_t refbaseid,uint64_t refrelid,int32_t flip,struct InstantDEX_quote *iQ,struct InstantDEX_quote *baseiQ,struct InstantDEX_quote *reliQ,char *gui,int32_t duration)
{
uint64_t baseamount,relamount,frombase,fromrel,tobase,torel;
double vol;
char exchange[64];
uint32_t timestamp;
frombase = baseiQ->baseamount, fromrel = baseiQ->relamount;
tobase = reliQ->baseamount, torel = reliQ->relamount;
if ( make_jumpquote(refbaseid,refrelid,&baseamount,&relamount,&frombase,&fromrel,&tobase,&torel) == 0. )
return(0);
if ( (timestamp= reliQ->timestamp) > baseiQ->timestamp )
timestamp = baseiQ->timestamp;
iQ_exchangestr(exchange,iQ);
create_InstantDEX_quote(iQ,timestamp,0,calc_quoteid(baseiQ) ^ calc_quoteid(reliQ),0.,0.,refbaseid,baseamount,refrelid,relamount,exchange,0,gui,baseiQ,reliQ,duration);
if ( Debuglevel > 2 )
printf("jump%s: %f (%llu/%llu) %llu %llu (%f %f) %llu %llu\n",flip==0?"BID":"ASK",calc_price_volume(&vol,iQ->baseamount,iQ->relamount),(long long)baseamount,(long long)relamount,(long long)frombase,(long long)fromrel,calc_price_volume(&vol,frombase,fromrel),calc_price_volume(&vol,tobase,torel),(long long)tobase,(long long)torel);
iQ->isask = flip;
iQ->minperc = baseiQ->minperc;
if ( reliQ->minperc > iQ->minperc )
iQ->minperc = reliQ->minperc;
return(1);
}
#else
struct InstantDEX_quote *AllQuotes;
void clear_InstantDEX_quoteflags(struct InstantDEX_quote *iQ)
{
//duration:14,wallet:1,a:1,isask:1,expired:1,closed:1,swap:1,responded:1,matched:1,feepaid:1,automatch:1,pending:1,minperc:7;
iQ->s.a = iQ->s.expired = iQ->s.swap = iQ->s.feepaid = 0;
iQ->s.closed = iQ->s.pending = iQ->s.responded = iQ->s.matched = 0;
}
void cancel_InstantDEX_quote(struct InstantDEX_quote *iQ) { iQ->s.closed = 1; }
int32_t InstantDEX_uncalcsize() { struct InstantDEX_quote iQ; return(sizeof(iQ.hh) + sizeof(iQ.s.quoteid) + sizeof(iQ.s.price) + sizeof(iQ.s.vol)); }
int32_t iQcmp(struct InstantDEX_quote *iQA,struct InstantDEX_quote *iQB)
{
if ( iQA->s.isask == iQB->s.isask && iQA->s.baseid == iQB->s.baseid && iQA->s.relid == iQB->s.relid && iQA->s.baseamount == iQB->s.baseamount && iQA->s.relamount == iQB->s.relamount )
return(0);
else if ( iQA->s.isask != iQB->s.isask && iQA->s.baseid == iQB->s.relid && iQA->s.relid == iQB->s.baseid && iQA->s.baseamount == iQB->s.relamount && iQA->s.relamount == iQB->s.baseamount )
return(0);
return(-1);
}
uint64_t calc_txid(unsigned char *buf,int32_t len)
{
bits256 hash;
vcalc_sha256(0,hash.bytes,buf,len);
return(hash.txid);
}
uint64_t calc_quoteid(struct InstantDEX_quote *iQ)
{
struct InstantDEX_quote Q;
if ( iQ == 0 )
return(0);
if ( iQ->s.duration == 0 || iQ->s.duration > ORDERBOOK_EXPIRATION )
iQ->s.duration = ORDERBOOK_EXPIRATION;
if ( iQ->s.quoteid == 0 )
{
Q = *iQ;
clear_InstantDEX_quoteflags(&Q);
if ( Q.s.isask != 0 )
{
Q.s.baseid = iQ->s.relid, Q.s.baseamount = iQ->s.relamount;
Q.s.relid = iQ->s.baseid, Q.s.relamount = iQ->s.baseamount;
Q.s.isask = Q.s.minperc = 0;
}
return(calc_txid((uint8_t *)((long)&Q + InstantDEX_uncalcsize()),sizeof(Q) - InstantDEX_uncalcsize()));
} return(iQ->s.quoteid);
}
struct InstantDEX_quote *find_iQ(uint64_t quoteid)
{
struct InstantDEX_quote *iQ;
HASH_FIND(hh,AllQuotes,&quoteid,sizeof(quoteid),iQ);
return(iQ);
}
struct InstantDEX_quote *delete_iQ(uint64_t quoteid)
{
struct InstantDEX_quote *iQ;
if ( (iQ= find_iQ(quoteid)) != 0 )
{
HASH_DELETE(hh,AllQuotes,iQ);
}
return(iQ);
}
struct InstantDEX_quote *findquoteid(uint64_t quoteid,int32_t evenclosed)
{
struct InstantDEX_quote *iQ;
if ( (iQ= find_iQ(quoteid)) != 0 )
{
if ( evenclosed != 0 || iQ->s.closed == 0 )
{
if ( calc_quoteid(iQ) == quoteid )
return(iQ);
else printf("calc_quoteid %llu vs %llu\n",(long long)calc_quoteid(iQ),(long long)quoteid);
} //else printf("quoteid.%llu closed.%d\n",(long long)quoteid,iQ->closed);
} else printf("couldnt find %llu\n",(long long)quoteid);
return(0);
}
int32_t cancelquote(char *NXTaddr,uint64_t quoteid)
{
struct InstantDEX_quote *iQ;
if ( (iQ= findquoteid(quoteid,0)) != 0 && iQ->s.offerNXT == calc_nxt64bits(NXTaddr) && iQ->exchangeid == INSTANTDEX_EXCHANGEID )
{
cancel_InstantDEX_quote(iQ);
return(1);
}
return(0);
}
struct InstantDEX_quote *create_iQ(struct InstantDEX_quote *iQ,char *walletstr)
{
struct InstantDEX_quote *newiQ,*tmp; struct prices777 *prices; int32_t inverted; long len = 0;
if ( walletstr != 0 && (len= strlen(walletstr)) > 0 )
iQ->s.wallet = 1, len++;
calc_quoteid(iQ);
printf("createiQ %llu/%llu %f %f quoteid.%llu offerNXT.%llu wallet.%d (%s)\n",(long long)iQ->s.baseid,(long long)iQ->s.relid,iQ->s.price,iQ->s.vol,(long long)iQ->s.quoteid,(long long)iQ->s.offerNXT,iQ->s.wallet,walletstr!=0?walletstr:"");
if ( (newiQ= find_iQ(iQ->s.quoteid)) != 0 )
return(newiQ);
newiQ = calloc(1,sizeof(*newiQ) + len);
*newiQ = *iQ;
if ( len != 0 )
memcpy(newiQ->walletstr,walletstr,len);
HASH_ADD(hh,AllQuotes,s.quoteid,sizeof(newiQ->s.quoteid),newiQ);
if ( (prices= prices777_find(&inverted,iQ->s.baseid,iQ->s.relid,INSTANTDEX_NAME)) != 0 )
prices->dirty++;
{
struct InstantDEX_quote *checkiQ;
if ( (checkiQ= find_iQ(iQ->s.quoteid)) == 0 || iQcmp(iQ,checkiQ) != 0 )//memcmp((uint8_t *)((long)checkiQ + sizeof(checkiQ->hh) + sizeof(checkiQ->quoteid)),(uint8_t *)((long)iQ + sizeof(iQ->hh) + sizeof(iQ->quoteid)),sizeof(*iQ) - sizeof(iQ->hh) - sizeof(iQ->quoteid)) != 0 )
{
int32_t i;
for (i=(sizeof(iQ->hh) - sizeof(iQ->s.quoteid)); i<sizeof(*iQ) - sizeof(iQ->hh) - sizeof(iQ->s.quoteid); i++)
printf("%02x ",((uint8_t *)iQ)[i]);
printf("iQ\n");
for (i=(sizeof(checkiQ->hh) + sizeof(checkiQ->s.quoteid)); i<sizeof(*checkiQ) - sizeof(checkiQ->hh) - sizeof(checkiQ->s.quoteid); i++)
printf("%02x ",((uint8_t *)checkiQ)[i]);
printf("checkiQ\n");
printf("error finding iQ after adding %llu vs %llu\n",(long long)checkiQ->s.quoteid,(long long)iQ->s.quoteid);
}
}
HASH_ITER(hh,AllQuotes,iQ,tmp)
{
if ( iQ->s.expired != 0 )
{
printf("quoteid.%llu expired, purging\n",(long long)iQ->s.expired);
delete_iQ(iQ->s.quoteid);
}
}
return(newiQ);
}
#ifdef later
cJSON *pangea_walletitem(cJSON *walletitem,struct coin777 *coin,int32_t rakemillis,int64_t bigblind,int64_t ante,int32_t minbuyin,int32_t maxbuyin)
{
char *addr; struct destbuf pubkey;
if ( walletitem == 0 )
walletitem = cJSON_CreateObject();
//printf("call get_acct_coinaddr.%s (%s) (%s)\n",coin->name,coin->serverport,coin->userpass);
if ( coin->pangeapubkey[0] == 0 || coin->pangeacoinaddr[0] == 0 )
{
if ( strcmp("NXT",coin->name) == 0 )
{
}
else if ( (addr= get_acct_coinaddr(coin->pangeacoinaddr,coin->name,coin->serverport,coin->userpass,"pangea")) != 0 )
{
//printf("get_pubkey\n");
get_pubkey(&pubkey,coin->name,coin->serverport,coin->userpass,coin->pangeacoinaddr);
strcpy(coin->pangeapubkey,pubkey.buf);
}
}
jaddstr(walletitem,"pubkey",coin->pangeapubkey);
jaddstr(walletitem,"coinaddr",coin->pangeacoinaddr);
jaddnum(walletitem,"rakemillis",rakemillis);
jaddnum(walletitem,"minbuyin",minbuyin);
jaddnum(walletitem,"maxbuyin",maxbuyin);
jadd64bits(walletitem,"bigblind",bigblind);
jadd64bits(walletitem,"ante",ante);
return(walletitem);
}
cJSON *set_walletstr(cJSON *walletitem,char *walletstr,struct InstantDEX_quote *iQ)
{
char pubkeystr[128],pkhash[128],base[64],rel[64],fieldA[64],fieldB[64],fieldpkhash[64],*pubA,*pubB,*pkhashstr,*str,*exchangestr;
struct coin777 *coin; int32_t flip = 0;
if ( walletstr != 0 && walletitem == 0 )
walletitem = cJSON_Parse(walletstr);
if ( walletitem == 0 )
walletitem = cJSON_CreateObject();
unstringbits(base,iQ->s.basebits), unstringbits(rel,iQ->s.relbits);
flip = (iQ->s.offerNXT != IGUANA_MY64BITS);
if ( strcmp(base,"NXT") != 0 )
coin = coin777_find(base,1);
else if ( strcmp(rel,"NXT") != 0 )
coin = coin777_find(rel,1), flip ^= 1;
else coin = 0;
if ( coin != 0 )
{
if ( (exchangestr= exchange_str(iQ->exchangeid)) != 0 && strcmp(exchangestr,"pangea") == 0 )
pangea_walletitem(walletitem,coin,iQ->s.minperc,iQ->s.baseamount,iQ->s.relamount,iQ->s.minbuyin,iQ->s.maxbuyin);
else
{
//printf("START.(%s)\n",jprint(walletitem,0));
if ( (iQ->s.isask ^ flip) == 0 )
{
sprintf(fieldA,"%spubA",coin->name);
if ( (pubA= jstr(walletitem,fieldA)) != 0 )
cJSON_DeleteItemFromObject(walletitem,fieldA);
jaddstr(walletitem,fieldA,coin->atomicsendpubkey);
//printf("replaceA\n");
}
else
{
sprintf(fieldB,"%spubB",coin->name);
if ( (pubB= jstr(walletitem,fieldB)) != 0 )
cJSON_DeleteItemFromObject(walletitem,fieldB);
jaddstr(walletitem,fieldB,coin->atomicrecvpubkey);
sprintf(fieldpkhash,"%spkhash",coin->name);
if ( (pkhashstr= jstr(walletitem,fieldpkhash)) != 0 )
cJSON_DeleteItemFromObject(walletitem,fieldpkhash);
subatomic_pubkeyhash(pubkeystr,pkhash,coin,iQ->s.quoteid);
jaddstr(walletitem,fieldpkhash,pkhash);
//printf("replaceB\n");
}
}
str = jprint(walletitem,0);
strcpy(walletstr,str);
free(str);
return(walletitem);
}
return(0);
}
#endif
char *InstantDEX_str(char *walletstr,char *buf,int32_t extraflag,struct InstantDEX_quote *iQ)
{
cJSON *json; char _buf[4096],base[64],rel[64],*str;
unstringbits(base,iQ->s.basebits), unstringbits(rel,iQ->s.relbits);
if ( buf == 0 )
buf = _buf;
sprintf(buf,"{\"quoteid\":\"%llu\",\"base\":\"%s\",\"baseid\":\"%llu\",\"baseamount\":\"%llu\",\"rel\":\"%s\",\"relid\":\"%llu\",\"relamount\":\"%llu\",\"price\":%.8f,\"volume\":%.8f,\"offerNXT\":\"%llu\",\"timestamp\":\"%u\",\"isask\":\"%u\",\"exchange\":\"%s\",\"gui\":\"%s\"}",(long long)iQ->s.quoteid,base,(long long)iQ->s.baseid,(long long)iQ->s.baseamount,rel,(long long)iQ->s.relid,(long long)iQ->s.relamount,iQ->s.price,iQ->s.vol,(long long)iQ->s.offerNXT,iQ->s.timestamp,iQ->s.isask,exchange_str(iQ->exchangeid),iQ->gui);
if ( extraflag != 0 )
{
sprintf(buf + strlen(buf) - 1,",\"plugin\":\"relay\",\"destplugin\":\"InstantDEX\",\"method\":\"busdata\",\"submethod\":\"%s\"}",(iQ->s.isask != 0) ? "ask" : "bid");
}
//printf("InstantDEX_str.(%s)\n",buf);
if ( (json= cJSON_Parse(buf)) != 0 )
{
#ifdef later
char _buf[4096],_walletstr[256],base[64],rel[64],*exchange,*str; cJSON *walletitem,*json; struct coin777 *coin;
if ( walletstr == 0 )
{
walletstr = _walletstr;
walletstr[0] = 0;
}
if ( (exchange= exchange_str(iQ->exchangeid)) != 0 )
{
coin = coin777_find(base,0);
if ( strcmp(exchange,"wallet") == 0 )
walletitem = set_walletstr(0,walletstr,iQ);
else if ( strcmp(exchange,"pangea") == 0 && walletstr[0] == 0 && coin != 0 )
walletitem = pangea_walletitem(0,coin,iQ->s.minperc,iQ->s.baseamount,iQ->s.relamount,iQ->s.minbuyin,iQ->s.maxbuyin);
else walletitem = 0;
if ( walletitem != 0 )
{
jadd(json,"wallet",walletitem);
strcpy(walletstr,jprint(walletitem,0));
}
//printf("exchange.(%s) iswallet.%d (%s) base.(%s) coin.%p (%s)\n",exchange,iQ->s.wallet,walletstr,base,coin,jprint(json,0));
} else printf("InstantDEX_str cant find exchangeid.%d\n",iQ->exchangeid);
#endif
str = jprint(json,1);
strcpy(buf,str);
//printf("str.(%s) %p\n",buf,buf);
free(str);
} else printf("InstantDEX_str cant parse.(%s)\n",buf);
if ( buf == _buf )
return(clonestr(buf));
else return(buf);
}
uint64_t _get_AEquote(char *str,uint64_t orderid)
{
cJSON *json;
uint64_t nxt64bits = 0;
char cmd[256],*jsonstr;
sprintf(cmd,"requestType=get%sOrder&order=%llu",str,(long long)orderid);
if ( (jsonstr= issue_NXTPOST(cmd)) != 0 )
{
//printf("(%s) -> (%s)\n",cmd,jsonstr);
if ( (json= cJSON_Parse(jsonstr)) != 0 )
{
nxt64bits = get_API_nxt64bits(cJSON_GetObjectItem(json,"account"));
free_json(json);
}
free(jsonstr);
}
return(nxt64bits);
}
char *cancel_NXTorderid(char *NXTaddr,char *nxtsecret,uint64_t orderid)
{
uint64_t nxt64bits; char cmd[1025],secret[8192],*str = "Bid",*retstr = 0;
if ( (nxt64bits= _get_AEquote(str,orderid)) == 0 )
str = "Ask", nxt64bits = _get_AEquote(str,orderid);
if ( nxt64bits == calc_nxt64bits(NXTaddr) )
{
escape_code(secret,nxtsecret);
sprintf(cmd,"requestType=cancel%sOrder&secretPhrase=%s&feeNQT=%lld&deadline=%d&order=%llu",str,secret,(long long)MIN_NQTFEE,DEFAULT_NXT_DEADLINE,(long long)orderid);
retstr = issue_NXTPOST(cmd);
//printf("(%s) -> (%s)\n",cmd,retstr);
}
return(retstr);
}
char *InstantDEX_cancelorder(cJSON *argjson,char *activenxt,char *secret,uint64_t orderid,uint64_t quoteid)
{
struct InstantDEX_quote *iQ; cJSON *json,*array,*item; char numstr[64],*retstr,*exchangestr;
uint64_t quoteids[256]; int32_t i,exchangeid,n=0; struct exchange_info *exchange;
if ( (exchangestr= jstr(argjson,"exchange")) != 0 && (exchange= find_exchange(&exchangeid,exchangestr)) != 0 )
{
if ( exchange->issue.cancelorder != 0 )
{
if ( (retstr= (*exchange->issue.cancelorder)(&exchange->cHandle,exchange,argjson,quoteid)) == 0 )
retstr = clonestr("{\"result\":\"nothing returned from exchange\"}");
return(retstr);
}
else return(clonestr("{\"error\":\"no cancelorder function\"}"));
}
memset(quoteids,0,sizeof(quoteids));
json = cJSON_CreateObject(), array = cJSON_CreateArray();
if ( quoteid != 0 )
quoteids[n++] = quoteid;
//n += InstantDEX_quoteids(quoteids+n,orderid);
for (i=0; i<n; i++)
{
quoteid = quoteids[i];
if ( (retstr= cancel_NXTorderid(activenxt,secret,quoteid)) != 0 )
{
if ( (iQ= findquoteid(quoteid,0)) != 0 && iQ->s.offerNXT == calc_nxt64bits(activenxt) )
cancel_InstantDEX_quote(iQ);
if ( (item= cJSON_Parse(retstr)) != 0 )
jaddi(array,item);
free(retstr);
}
cancelquote(activenxt,quoteid);
}
if ( orderid != 0 )
{
if ( cancelquote(activenxt,orderid) != 0 )
sprintf(numstr,"%llu",(long long)orderid), jaddstr(json,"ordercanceled",numstr);
}
return(jprint(json,1));
}
char *InstantDEX_orderstatus(cJSON *argjson,uint64_t orderid,uint64_t quoteid)
{
struct InstantDEX_quote *iQ = 0; char *exchangestr,*str; struct exchange_info *exchange; int32_t exchangeid;
if ( (exchangestr= jstr(argjson,"exchange")) != 0 && (exchange= find_exchange(&exchangeid,exchangestr)) != 0 )
{
if ( exchange->issue.orderstatus != 0 )
{
if ( (str= (*exchange->issue.orderstatus)(&exchange->cHandle,exchange,argjson,quoteid)) == 0 )
str = clonestr("{\"result\":\"nothing returned from exchange\"}");
return(str);
}
else return(clonestr("{\"error\":\"no orderstatus function\"}"));
}
if ( (iQ= find_iQ(orderid)) != 0 || (iQ= find_iQ(quoteid)) != 0 )
return(InstantDEX_str(0,0,0,iQ));
return(clonestr("{\"error\":\"couldnt find orderid\"}"));
}
char *InstantDEX_openorders(cJSON *argjson,char *NXTaddr,int32_t allorders)
{
struct InstantDEX_quote *iQ,*tmp; char buf[4096],*exchangestr,*jsonstr,*str; uint32_t now,duration;
cJSON *json,*array,*item; uint64_t nxt64bits; struct exchange_info *exchange; int32_t exchangeid;
if ( (exchangestr= jstr(argjson,"exchange")) != 0 && (exchange= find_exchange(&exchangeid,exchangestr)) != 0 )
{
if ( exchange->issue.openorders != 0 )
{
if ( (str= (*exchange->issue.openorders)(&exchange->cHandle,exchange,argjson)) == 0 )
str = clonestr("{\"result\":\"nothing returned from exchange\"}");
return(str);
}
else return(clonestr("{\"error\":\"no orderstatus function\"}"));
}
nxt64bits = calc_nxt64bits(NXTaddr);
now = (uint32_t)time(NULL);
json = cJSON_CreateObject(), array = cJSON_CreateArray();
HASH_ITER(hh,AllQuotes,iQ,tmp)
{
if ( (duration= iQ->s.duration) == 0 )
duration = ORDERBOOK_EXPIRATION;
if ( iQ->s.timestamp > (now + duration) )
iQ->s.expired = iQ->s.closed = 1;
if ( iQ->s.offerNXT == nxt64bits && (allorders != 0 || iQ->s.closed == 0) )
{
if ( (jsonstr= InstantDEX_str(0,buf,0,iQ)) != 0 && (item= cJSON_Parse(jsonstr)) != 0 )
jaddi(array,item);
}
}
jadd(json,"openorders",array);
return(jprint(json,1));
}
cJSON *InstantDEX_specialorders(uint64_t *quoteidp,uint64_t nxt64bits,char *base,char *special,uint64_t baseamount,int32_t addrtype)
{
struct InstantDEX_quote *iQ,*tmp; int32_t exchangeid; uint32_t i,n,now,duration,ismine = 0;
uint64_t basebits; cJSON *item=0,*array = 0; char *coinaddr=0,*pubkey,checkaddr[128];
now = (uint32_t)time(NULL);
basebits = stringbits(base);
if ( special == 0 || find_exchange(&exchangeid,special) == 0 )
exchangeid = 0;
n = 0;
*quoteidp = 0;
HASH_ITER(hh,AllQuotes,iQ,tmp)
{
//printf("iter Q.%llu b.%llu\n",(long long)iQ->s.quoteid,(long long)iQ->s.basebits);
if ( (duration= iQ->s.duration) == 0 )
duration = ORDERBOOK_EXPIRATION;
if ( iQ->s.timestamp > (now + duration) )
{
iQ->s.expired = iQ->s.closed = 1;
printf("expire order %llu\n",(long long)iQ->s.quoteid);
continue;
}
if ( iQ->s.basebits == basebits && (exchangeid == 0 || iQ->exchangeid == exchangeid) )
{
//printf("matched basebits\n");
if ( strcmp(special,"pangea") == 0 )
{
checkaddr[0] = 0;
if ( iQ->s.wallet != 0 && (item= cJSON_Parse(iQ->walletstr)) != 0 && (coinaddr= jstr(item,"coinaddr")) != 0 && coinaddr[0] != 0 && (pubkey= jstr(item,"pubkey")) != 0 && pubkey[0] != 0 )
btc_coinaddr(coinaddr,addrtype,pubkey);
if ( item != 0 )
free_json(item);
if ( coinaddr == 0 || strcmp(coinaddr,checkaddr) != 0 )
{
printf("mismatched pangea coinaddr (%s) vs (%s) or baseamount %.8f vs %.8f\n",coinaddr,checkaddr,dstr(baseamount),dstr(iQ->s.baseamount));
continue;
}
}
if ( n > 0 )
{
for (i=0; i<n; i++)
{
if ( iQ->s.offerNXT == j64bits(jitem(array,i),0) )
break;
}
//printf("found duplicate\n");
} else i = 0;
if ( i == n )
{
if ( iQ->s.offerNXT == nxt64bits )
{
ismine = 1;
if ( *quoteidp == 0 )
*quoteidp = iQ->s.quoteid;
}
if ( array == 0 )
array = cJSON_CreateArray();
jaddi64bits(array,iQ->s.offerNXT);
//printf("add %llu\n",(long long)iQ->s.offerNXT);
}
} //else printf("quote.%llu basebits.%llu\n",(long long)iQ->s.quoteid,(long long)iQ->s.basebits);
}
if ( ismine == 0 )
free_json(array), array = 0;
//printf("ismine.%d n.%d array.%d\n",ismine,n,array==0?0:cJSON_GetArraySize(array));
return(array);
}
int _decreasing_quotes(const void *a,const void *b)
{
#define order_a ((struct InstantDEX_quote *)a)
#define order_b ((struct InstantDEX_quote *)b)
if ( order_b->s.price > order_a->s.price )
return(1);
else if ( order_b->s.price < order_a->s.price )
return(-1);
return(0);
#undef order_a
#undef order_b
}
int _increasing_quotes(const void *a,const void *b)
{
#define order_a ((struct InstantDEX_quote *)a)
#define order_b ((struct InstantDEX_quote *)b)
if ( order_b->s.price > order_a->s.price )
return(-1);
else if ( order_b->s.price < order_a->s.price )
return(1);
return(0);
#undef order_a
#undef order_b
}
cJSON *prices777_orderjson(struct InstantDEX_quote *iQ)
{
cJSON *item = cJSON_CreateArray();
jaddinum(item,iQ->s.price);
jaddinum(item,iQ->s.vol);
jaddi64bits(item,iQ->s.quoteid);
return(item);
}
cJSON *InstantDEX_orderbook(struct prices777 *prices)
{
struct InstantDEX_quote *ptr,iQ,*tmp,*askvals=0,*bidvals=0; cJSON *json,*bids,*asks; uint32_t now,duration;
int32_t i,isask,iter,n,m,numbids,numasks,invert;
json = cJSON_CreateObject(), bids = cJSON_CreateArray(), asks = cJSON_CreateArray();
now = (uint32_t)time(NULL);
for (iter=numbids=numasks=n=m=0; iter<2; iter++)
{
HASH_ITER(hh,AllQuotes,ptr,tmp)
{
iQ = *ptr;
if ( (duration= iQ.s.duration) == 0 )
duration = ORDERBOOK_EXPIRATION;
if ( iQ.s.timestamp > (now + duration) )
{
iQ.s.expired = iQ.s.closed = 1;
continue;
}
if ( Debuglevel > 2 )
printf("iterate quote.%llu\n",(long long)iQ.s.quoteid);
if ( prices777_equiv(ptr->s.baseid) == prices777_equiv(prices->baseid) && prices777_equiv(ptr->s.relid) == prices777_equiv(prices->relid) )
invert = 0;
else if ( prices777_equiv(ptr->s.relid) == prices777_equiv(prices->baseid) && prices777_equiv(ptr->s.baseid) == prices777_equiv(prices->relid) )
invert = 1;
else continue;
if ( ptr->s.pending != 0 )
continue;
isask = iQ.s.isask;
if ( invert != 0 )
isask ^= 1;
if ( invert != 0 )
{
if ( iQ.s.price > SMALLVAL )
iQ.s.vol *= iQ.s.price, iQ.s.price = 1. / iQ.s.price;
else iQ.s.price = prices777_price_volume(&iQ.s.vol,iQ.s.relamount,iQ.s.baseamount);
}
else if ( iQ.s.price <= SMALLVAL )
iQ.s.price = prices777_price_volume(&iQ.s.vol,iQ.s.baseamount,iQ.s.relamount);
if ( iter == 0 )
{
if ( isask != 0 )
numasks++;
else numbids++;
}
else
{
if ( isask == 0 && n < numbids )
bidvals[n++] = iQ;
else if ( isask != 0 && m < numasks )
askvals[m++] = iQ;
}
}
if ( iter == 0 )
{
if ( numbids > 0 )
bidvals = calloc(numbids,sizeof(*bidvals));
if ( numasks > 0 )
askvals = calloc(numasks,sizeof(*askvals));
}
}
if ( numbids > 0 )
{
if ( n > 0 )
{
qsort(bidvals,n,sizeof(*bidvals),_decreasing_quotes);
for (i=0; i<n; i++)
jaddi(bids,prices777_orderjson(&bidvals[i]));
}
free(bidvals);
}
if ( numasks > 0 )
{
if ( m > 0 )
{
qsort(askvals,m,sizeof(*askvals),_increasing_quotes);
for (i=0; i<m; i++)
jaddi(asks,prices777_orderjson(&askvals[i]));
}
free(askvals);
}
jadd(json,"bids",bids), jadd(json,"asks",asks);
return(json);
}
double ordermetric(double price,double vol,int32_t dir,double refprice,double refvol)
{
double metric = 0.;
if ( vol > (refvol * INSTANTDEX_MINVOLPERC) )//&& refvol > (vol * iQ->s.minperc * .01) )
{
if ( vol < refvol )
metric = (vol / refvol);
else metric = 1.;
if ( dir > 0 && price < (refprice * (1. + INSTANTDEX_PRICESLIPPAGE) + SMALLVAL) )
metric *= (1. + (refprice - price)/refprice);
else if ( dir < 0 && price > (refprice * (1. - INSTANTDEX_PRICESLIPPAGE) - SMALLVAL) )
metric *= (1. + (price - refprice)/refprice);
else metric = 0.;
if ( metric != 0. )
{
printf("price %.8f vol %.8f | %.8f > %.8f? %.8f > %.8f?\n",price,vol,vol,(refvol * INSTANTDEX_MINVOLPERC),refvol,(vol * INSTANTDEX_MINVOLPERC));
printf("price %f against %f or %f\n",price,(refprice * (1. + INSTANTDEX_PRICESLIPPAGE) + SMALLVAL),(refprice * (1. - INSTANTDEX_PRICESLIPPAGE) - SMALLVAL));
printf("metric %f\n",metric);
}
}
return(metric);
}
char *autofill(char *remoteaddr,struct InstantDEX_quote *refiQ,char *NXTaddr,char *NXTACCTSECRET)
{
double price,volume,revprice,revvol,metric,bestmetric = 0.; int32_t dir,inverted; uint64_t nxt64bits; char *retstr=0;
struct InstantDEX_quote *iQ,*tmp,*bestiQ; struct prices777 *prices; uint32_t duration,now = (uint32_t)time(NULL);
return(0);
nxt64bits = calc_nxt64bits(NXTaddr);
memset(&bestiQ,0,sizeof(bestiQ));
dir = (refiQ->s.isask != 0) ? -1 : 1;
HASH_ITER(hh,AllQuotes,iQ,tmp)
{
if ( (duration= refiQ->s.duration) == 0 )
duration = ORDERBOOK_EXPIRATION;
if ( iQ->s.timestamp > (now + duration) )
iQ->s.expired = iQ->s.closed = 1;
if ( iQ->s.offerNXT == nxt64bits && iQ->s.closed == 0 && iQ->s.pending == 0 )
{
if ( iQ->s.baseid == refiQ->s.baseid && iQ->s.relid == refiQ->s.relid && iQ->s.isask != refiQ->s.isask && (metric= ordermetric(iQ->s.price,iQ->s.vol,dir,refiQ->s.price,refiQ->s.vol)) > bestmetric )
{
bestmetric = metric;
bestiQ = iQ;
}
else if ( iQ->s.baseid == refiQ->s.relid && iQ->s.relid == refiQ->s.baseid && iQ->s.isask == refiQ->s.isask && iQ->s.price > SMALLVAL )
{
revvol = (iQ->s.price * iQ->s.vol), revprice = (1. / iQ->s.price);
if ( (metric= ordermetric(revprice,revvol,dir,refiQ->s.price,refiQ->s.vol)) > bestmetric )
{
bestmetric = metric;
bestiQ = iQ;
}
}
}
}
if ( bestmetric > 0. )
{
if ( (prices= prices777_find(&inverted,bestiQ->s.baseid,bestiQ->s.relid,exchange_str(bestiQ->exchangeid))) != 0 )
{
printf("isask.%d %f %f -> bestmetric %f inverted.%d autofill dir.%d price %f vol %f\n",bestiQ->s.isask,bestiQ->s.price,bestiQ->s.vol,bestmetric,inverted,dir,refiQ->s.price,refiQ->s.vol);
if ( bestiQ->s.isask != 0 )
dir = -1;
else dir = 1;
if ( inverted != 0 )
{
dir *= -1;
volume = (bestiQ->s.price * bestiQ->s.vol);
price = 1. / bestiQ->s.price;
printf("price inverted (%f %f) -> (%f %f)\n",bestiQ->s.price,bestiQ->s.vol,price,volume);
} else price = bestiQ->s.price, volume = bestiQ->s.vol;
retstr = prices777_trade(0,0,0,0,1,0,NXTaddr,NXTACCTSECRET,prices,dir,price,volume,bestiQ,0,bestiQ->s.quoteid,0);
}
}
return(retstr);
}
char *automatch(struct prices777 *prices,int32_t dir,double refprice,double refvol,char *NXTaddr,char *NXTACCTSECRET)
{
int32_t i,n=0; struct prices777_order order,bestorder; char *retstr = 0; double metric,bestmetric = 0.;
return(0);
memset(&bestorder,0,sizeof(bestorder));
if ( dir > 0 )
n = prices->O.numasks;
else if ( dir < 0 )
n = prices->O.numbids;
if ( n > 0 )
{
for (i=0; i<n; i++)
{
order = (dir > 0) ? prices->O.book[MAX_GROUPS][i].ask : prices->O.book[MAX_GROUPS][i].bid;
if ( (metric= ordermetric(order.s.price,order.s.vol,dir,refprice,refvol)) > bestmetric )
{
bestmetric = metric;
bestorder = order;
}
}
}
//printf("n.%d\n",n);
if ( bestorder.source != 0 )
retstr = prices777_trade(0,0,0,0,1,0,NXTaddr,NXTACCTSECRET,bestorder.source,bestorder.s.isask!=0?-1:1,bestorder.s.price,bestorder.s.vol,0,&bestorder,bestorder.s.quoteid,0);
return(retstr);
}
int offer_checkitem(struct pending_trade *pend,cJSON *item)
{
uint64_t quoteid; struct InstantDEX_quote *iQ;
if ( (quoteid= j64bits(item,"quoteid")) != 0 && (iQ= find_iQ(quoteid)) != 0 && iQ->s.closed != 0 )
return(0);
return(-1);
}
void trades_update()
{
#ifdef later
int32_t iter; struct pending_trade *pend;
for (iter=0; iter<2; iter++)
{
while ( (pend= queue_dequeue(&Pending_offersQ.pingpong[iter],0)) != 0 )
{
if ( time(NULL) > pend->expiration )
{
printf("now.%ld vs timestamp.%u vs expiration %u | ",(long)time(NULL),pend->timestamp,pend->expiration);
printf("offer_statemachine %llu/%llu %d %f %f\n",(long long)pend->orderid,(long long)pend->quoteid,pend->dir,pend->price,pend->volume);
//InstantDEX_history(1,pend,retstr);
if ( pend->bot == 0 )
free_pending(pend);
else pend->finishtime = (uint32_t)time(NULL);
}
else
{
printf("InstantDEX_update requeue %llu/%llu %d %f %f\n",(long long)pend->orderid,(long long)pend->quoteid,pend->dir,pend->price,pend->volume);
queue_enqueue("requeue",&Pending_offersQ.pingpong[iter ^ 1],&pend->DL,0);
}
}
}
#endif
}
void InstantDEX_update(char *NXTaddr,char *NXTACCTSECRET)
{
int32_t dir; double price,volume; uint32_t now; char *retstr = 0;
int32_t inverted; struct InstantDEX_quote *iQ,*tmp; struct prices777 *prices; uint64_t nxt64bits = calc_nxt64bits(NXTaddr);
now = (uint32_t)time(NULL);
HASH_ITER(hh,AllQuotes,iQ,tmp)
{
if ( iQ->s.timestamp > (now + ORDERBOOK_EXPIRATION) )
iQ->s.expired = iQ->s.closed = 1;
if ( iQ->s.offerNXT == nxt64bits && iQ->s.closed == 0 && iQ->s.pending == 0 )
{
if ( (prices= prices777_find(&inverted,iQ->s.baseid,iQ->s.relid,exchange_str(iQ->exchangeid))) != 0 )
{
if ( iQ->s.isask != 0 )
dir = -1;
else dir = 1;
if ( inverted != 0 )
{
dir *= -1;
volume = (iQ->s.price * iQ->s.vol);
price = 1. / iQ->s.price;
printf("price inverted (%f %f) -> (%f %f)\n",iQ->s.price,iQ->s.vol,price,volume);
} else price = iQ->s.price, volume = iQ->s.vol;
if ( (retstr= automatch(prices,dir,price,volume,NXTaddr,NXTACCTSECRET)) != 0 )
{
printf("automatched %s isask.%d %f %f (%s)\n",prices->contract,iQ->s.isask,iQ->s.price,iQ->s.vol,retstr);
free(retstr);
}
}
}
}
trades_update();
}
int32_t is_specialexchange(char *exchangestr)
{
if ( strcmp(exchangestr,"InstantDEX") == 0 || strcmp(exchangestr,"jumblr") == 0 || strcmp(exchangestr,"pangea") == 0 || strcmp(exchangestr,"peggy") == 0 || strcmp(exchangestr,"wallet") == 0 || strcmp(exchangestr,"active") == 0 || strncmp(exchangestr,"basket",strlen("basket")) == 0 )
return(1);
return(0);
}
char *InstantDEX_placebidask(char *remoteaddr,uint64_t orderid,char *exchangestr,char *name,char *base,char *rel,struct InstantDEX_quote *iQ,char *extra,char *secret,char *activenxt,cJSON *origjson)
{
struct exchange_info *exchange; cJSON *obj;
char walletstr[256],*str,*retstr = 0; int32_t inverted,dir; struct prices777 *prices; double price,volume;
if ( secret == 0 || activenxt == 0 )
{
secret = IGUANA_NXTACCTSECRET;
activenxt = IGUANA_NXTADDR;
}
//printf("placebidask.(%s)\n",jprint(origjson,0));
if ( (obj= jobj(origjson,"wallet")) != 0 )
{
str = jprint(obj,1);
safecopy(walletstr,str,sizeof(walletstr));
free(str), str = 0;
}
else walletstr[0] = 0;
if ( exchangestr != 0 && (exchange= exchange_find(exchangestr)) != 0 )
iQ->exchangeid = exchange->exchangeid;
if ( iQ->exchangeid < 0 || (exchangestr= exchange_str(iQ->exchangeid)) == 0 )
{
printf("exchangestr.%s id.%d\n",exchangestr,iQ->exchangeid);
return(clonestr("{\"error\":\"exchange not active, check SuperNET.conf exchanges array\"}\n"));
}
//printf("walletstr.(%s)\n",walletstr);
if ( (prices= prices777_find(&inverted,iQ->s.baseid,iQ->s.relid,exchangestr)) == 0 )
prices = prices777_poll(exchangestr,name,base,iQ->s.baseid,rel,iQ->s.relid);
if ( prices != 0 )
{
price = iQ->s.price, volume = iQ->s.vol;
if ( price < SMALLVAL || volume < SMALLVAL )
{
printf("price %f volume %f error\n",price,volume);
return(clonestr("{\"error\":\"prices777_trade invalid price or volume\"}\n"));
}
if ( iQ->s.isask != 0 )
dir = -1;
else dir = 1;
if ( inverted != 0 )
{
dir *= -1;
volume *= price;
price = 1. / price;
printf("price inverted (%f %f) -> (%f %f)\n",iQ->s.price,iQ->s.vol,price,volume);
}
//printf("dir.%d price %f vol %f isask.%d remoteaddr.%p\n",dir,price,volume,iQ->s.isask,remoteaddr);
if ( remoteaddr == 0 )
{
if ( is_specialexchange(exchangestr) == 0 )
return(prices777_trade(0,0,0,0,1,0,activenxt,secret,prices,dir,price,volume,iQ,0,iQ->s.quoteid,extra));
//printf("check automatch\n");
//if ( strcmp(exchangestr,"wallet") != 0 && strcmp(exchangestr,"jumblr") != 0 && strcmp(exchangestr,"pangea") != 0 && iQ->s.automatch != 0 && (SUPERNET.automatch & 1) != 0 && (retstr= automatch(prices,dir,volume,price,activenxt,secret)) != 0 )
// return(retstr);
if ( strcmp(IGUANA_NXTACCTSECRET,secret) != 0 )
return(clonestr("{\"error\":\"cant do queued requests with non-default accounts\"}"));
retstr = InstantDEX_str(walletstr,0,1,iQ);
//printf("create_iQ.(%llu) quoteid.%llu walletstr.(%s) %p\n",(long long)iQ->s.offerNXT,(long long)iQ->s.quoteid,walletstr,walletstr);
iQ = create_iQ(iQ,walletstr);
printf("local got create_iQ.(%llu) quoteid.%llu wallet.(%s) baseamount %llu iswallet.%d\n",(long long)iQ->s.offerNXT,(long long)iQ->s.quoteid,walletstr,(long long)iQ->s.baseamount,iQ->s.wallet);
prices777_InstantDEX(prices,MAX_DEPTH);
queue_enqueue("InstantDEX",&InstantDEXQ,queueitem(retstr),0);
}
else
{
iQ = create_iQ(iQ,walletstr);
if ( (retstr= autofill(remoteaddr,iQ,activenxt,secret)) == 0 )
{
//printf("create_iQ.(%llu) quoteid.%llu\n",(long long)iQ->s.offerNXT,(long long)iQ->s.quoteid);
if ( strcmp(IGUANA_NXTACCTSECRET,secret) != 0 )
return(clonestr("{\"error\":\"cant do queued requests with non-default accounts\"}"));
prices777_InstantDEX(prices,MAX_DEPTH);
printf("remote got create_iQ.(%llu) quoteid.%llu wallet.(%s) baseamount %llu\n",(long long)iQ->s.offerNXT,(long long)iQ->s.quoteid,walletstr,(long long)iQ->s.baseamount);
}
return(retstr);
}
} else printf("cant find prices\n");
if ( retstr == 0 )
retstr = clonestr("{\"error\":\"cant get prices ptr\"}");
return(retstr);
}
#endif
#endif

1496
InstantDEX/subatomic.h

File diff suppressed because it is too large

323
InstantDEX/tradebots.h

@ -0,0 +1,323 @@
/******************************************************************************
* Copyright © 2014-2015 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
#ifndef xcode_tradebots_h
#define xcode_tradebots_h
#define TRADEBOT_DEFAULT_DURATION (600)
struct tradebot_info
{
char buf[512],name[64],*prevobookstr,NXTADDR[64],NXTACCTSECRET[64];
uint32_t starttime,expiration,finishtime,startedtrades,apitag;
int32_t numtrades,havetrade,numlinks;
double price,volume;
struct prices777_order trades[256]; void *cHandles[256]; int32_t curlings[256];
struct tradebot_info *linkedbots[8];
struct apitag_info *api;
struct tradebot_info *oppo;
struct InstantDEX_quote iQ;
};
// ./SNapi "{\"allfields\":1,\"agent\":\"InstantDEX\",\"method\":\"orderbook\",\"exchange\":\"active\",\"base\":\"NXT\",\"rel\":\"BTC\"}"
// test balance verifier
// test tradeleg verifier
// test pass through quotes
// user lockin addrs
// atomic swaps using 2of3 msig
// broadcast request to all marketmakers
// pick best response and do BTC <-> NXT and NXT <-> ABC
int32_t tradebot_havealltrades(struct tradebot_info *bot)
{
int32_t i;
if ( bot->havetrade != 0 )
{
if ( bot->numlinks > 0 )
{
for (i=0; i<bot->numlinks; i++)
if ( bot->linkedbots[i] == 0 || bot->linkedbots[i]->havetrade == 0 )
return(0);
}
return(1);
}
return(0);
}
struct tradebot_info *tradebot_compile(cJSON *argjson,struct InstantDEX_quote *iQ,struct apitag_info *api)
{
static uint64_t lastmonce;
uint64_t monce; char *name,*tmp,*tmp2; int32_t duration; struct tradebot_info *bot = calloc(1,sizeof(*bot));
monce = (long long)(1000*time(NULL) + milliseconds());
if ( monce == lastmonce )
monce++;
lastmonce = monce;
bot->iQ = *iQ;
bot->api = api;
if ( (duration= juint(argjson,"duration")) == 0 )
duration = TRADEBOT_DEFAULT_DURATION;
bot->expiration = (uint32_t)time(NULL) + duration;
if ( (name= jstr(argjson,"name")) != 0 )
safecopy(bot->name,name,sizeof(bot->name));
else sprintf(bot->name,"bot.%llu",monce);
if ( (tmp= jstr(argjson,"botnxt")) == 0 || (tmp2= jstr(argjson,"secret")) == 0 )
{
safecopy(bot->NXTADDR,SUPERNET.NXTADDR,sizeof(bot->NXTADDR));
safecopy(bot->NXTACCTSECRET,SUPERNET.NXTACCTSECRET,sizeof(bot->NXTACCTSECRET));
}
else
{
safecopy(bot->NXTADDR,tmp,sizeof(bot->NXTADDR));
safecopy(bot->NXTACCTSECRET,tmp2,sizeof(bot->NXTACCTSECRET));
}
//bot->arbmargin = jdouble(argjson,"arbmargin");
return(bot);
}
int32_t tradebot_acceptable(struct tradebot_info *bot,cJSON *item)
{
double price,volume; int32_t dir,i,n; cJSON *trades,*trade;
if ( bot->iQ.s.isask != 0 )
dir = -1;
else dir = 1;
bot->price = price = jdouble(item,"price");
bot->volume = volume = jdouble(item,"volume");
if ( (trades= jarray(&n,item,"trades")) != 0 )
{
/*{
"plugin": "InstantDEX",
"method": "tradesequence",
"dotrade": 1,
"price": 0.00001858,
"volume": 484.39181916,
"trades": [
{
"basket": "bid",
"price": 0.00001858,
"volume": 484.39181916,
"group": 0,
"exchange": "bittrex",
"base": "NXT",
"rel": "BTC",
"trade": "sell",
"name": "NXT/BTC",
"orderprice": 0.00001858,
"ordervolume": 484.39181916
}
]
}*/
if ( n == 1 && is_cJSON_Array(jitem(trades,0)) != 0 )
{
//printf("NESTED ARRAY DETECTED\n");
trades = jitem(trades,0);
n = cJSON_GetArraySize(trades);
}
sprintf(bot->buf,"[%s %s%s %.8f %.4f] <- ",bot->iQ.s.isask != 0 ? "sell" : "buy ",bot->iQ.base,bot->iQ.rel,price,volume);
for (i=0; i<n; i++)
{
trade = jitem(trades,i);
sprintf(bot->buf+strlen(bot->buf),"[%s %s %.8f %.4f] ",jstr(trade,"exchange"),jstr(trade,"trade"),jdouble(trade,"orderprice"),jdouble(trade,"ordervolume"));
}
sprintf(bot->buf+strlen(bot->buf),"n.%d\n",n);
if ( bot->iQ.s.isask == 0 && bot->oppo != 0 && bot->price > 0. && bot->oppo->price > 0 )
{
//if ( bot->price < bot->oppo->price )
{
printf("%s%s%.8f -> %.8f = gain %.3f%%\n\n",bot->buf,bot->oppo->buf,bot->price,bot->oppo->price,(bot->oppo->price/bot->price - 1)*100);
}
}
}
//printf("%s: dir.%d price %.8f vol %f vs bot price %.8f vol %f\n",bot->name,dir,price,volume,bot->iQ.s.price,bot->iQ.s.vol);
//if ( (dir > 0 && price < bot->iQ.s.price) || (dir < 0 && price >= bot->iQ.s.price) )
return(1);
return(0);
}
int32_t tradebot_isvalidtrade(struct tradebot_info *bot,struct prices777_order *order,cJSON *retjson)
{
cJSON *array,*item; char *resultval; double balance,required; int32_t i,n,valid = 0;
if ( (array= jarray(&n,retjson,"traderesults")) != 0 )
{
for (i=0; i<n; i++)
{
item = jitem(array,i);
if ( jstr(item,"error") == 0 && (resultval= jstr(item,"success")) != 0 )
{
balance = jdouble(item,"balance");
required = jdouble(item,"required");
printf("[%s %f R%f] ",resultval,balance,required);
valid++;
}
}
//printf("valid.%d of %d\n",valid,n);
if ( valid == n )
return(0);
}
return(-1);
}
int32_t tradebot_tradedone(struct tradebot_info *bot,struct prices777_order *order)
{
struct pending_trade *pend;
if ( (pend= order->pend) != 0 && pend->finishtime != 0 )
return(1);
else return(0);
}
int32_t tradebot_haspending(struct tradebot_info *bot)
{
int32_t i,finished;
for (i=finished=0; i<bot->numtrades; i++)
{
if ( tradebot_tradedone(bot,&bot->trades[i]) > 0 )
finished++;
}
return(finished < bot->numtrades);
}
void tradebot_free(struct tradebot_info *bot)
{
int32_t i; struct pending_trade *pend;
for (i=0; i<bot->numtrades; i++)
{
if ( (pend= bot->trades[i].pend) != 0 )
free_pending(pend);
if ( bot->trades[i].retitem != 0 )
free_json(bot->trades[i].retitem);
if ( bot->cHandles[i] != 0 )
{
while ( bot->curlings[i] != 0 )
{
fprintf(stderr,"%s: wait for curlrequest[%d] to finish\n",bot->name,i);
sleep(3);
}
curlhandle_free(bot->cHandles[i]);
}
}
if ( bot->prevobookstr != 0 )
free(bot->prevobookstr);
free(bot);
}
void Tradebot_loop(void *ptr)
{
int32_t i,n,dotrade; char *obookstr,*retstr; cJSON *json,*array,*item,*retjson,*submit;
char jsonstr[1024]; struct tradebot_info *bot = ptr;
printf("START Tradebot.(%s)\n",bot->name);
while ( bot->finishtime == 0 && time(NULL) < bot->expiration )
{
if ( bot->startedtrades == 0 )
{
sprintf(jsonstr,"{\"allfields\":1,\"agent\":\"InstantDEX\",\"method\":\"orderbook\",\"exchange\":\"active\",\"base\":\"%s\",\"rel\":\"%s\"}",bot->iQ.base,bot->iQ.rel);
if ( (json= cJSON_Parse(jsonstr)) == 0 )
{
printf("cant parse.(%s)\n",jsonstr);
exit(-1);
}
obookstr = SuperNET_SNapi(bot->api,json,0,1);
//printf("GOT.(%s)\n",obookstr);
free_json(json);
if ( bot->prevobookstr == 0 || strcmp(obookstr,bot->prevobookstr) != 0 )
{
if ( bot->prevobookstr != 0 )
free(bot->prevobookstr);
bot->prevobookstr = obookstr;
//printf("UPDATE.(%s)\n",obookstr);
submit = 0;
if ( (json= cJSON_Parse(obookstr)) != 0 )
{
array = (bot->iQ.s.isask != 0) ? jarray(&n,json,"bids") : jarray(&n,json,"asks");
if ( array != 0 && n > 0 )
{
dotrade = 0;
for (i=0; i<1; i++)
{
item = jitem(array,i);
if ( tradebot_acceptable(bot,item) > 0 )
{
submit = cJSON_Duplicate(item,1);
if ( jobj(submit,"dotrade") == 0 )
jaddnum(submit,"dotrade",0);
else cJSON_ReplaceItemInObject(submit,"dotrade",cJSON_CreateNumber(0));
retstr = SuperNET_SNapi(bot->api,submit,0,1);
free_json(submit);
//retstr = InstantDEX_tradesequence(bot->curlings,bot,bot->cHandles,&bot->numtrades,bot->trades,(int32_t)( sizeof(bot->trades)/sizeof(*bot->trades)),dotrade,bot->NXTADDR,bot->NXTACCTSECRET,item);
if ( retstr != 0 )
{
if ( (retjson= cJSON_Parse(retstr)) != 0 )
{
if ( tradebot_isvalidtrade(bot,&bot->trades[i],retjson) > 0 )
bot->havetrade = 1;
free_json(retjson);
}
free(retstr);
if ( bot->havetrade == 0 )
continue;
}
}
break;
}
if ( 0 && submit != 0 && tradebot_havealltrades(bot) != 0 )
{
dotrade = 1;
cJSON_ReplaceItemInObject(submit,"dotrade",cJSON_CreateNumber(1));
bot->startedtrades = (uint32_t)time(NULL);
retstr = InstantDEX_tradesequence(bot->curlings,bot,bot->cHandles,&bot->numtrades,bot->trades,(int32_t)(sizeof(bot->trades)/sizeof(*bot->trades)),dotrade,bot->NXTADDR,bot->NXTACCTSECRET,item);
printf("TRADE RESULT.(%s)\n",retstr);
break;
}
}
free_json(json);
}
}
}
else if ( bot->startedtrades != 0 )
{
if ( tradebot_haspending(bot) > 0 && bot->finishtime == 0 )
bot->finishtime = (uint32_t)time(NULL);
}
usleep(5000000);
}
while ( tradebot_haspending(bot) != 0 )
sleep(60);
printf("FINISHED Tradebot.(%s) at %u finishtime.%u expiration.%u\n",bot->name,(uint32_t)time(NULL),bot->finishtime,bot->expiration);
tradebot_free(bot);
}
char *Tradebot_parser(cJSON *argjson,struct InstantDEX_quote *iQ,struct apitag_info *api)
{
char *submethod,*exchange; struct tradebot_info *bot,*oppobot;
printf("InstantDEX_tradebot.(%s) (%s/%s)\n",jprint(argjson,0),iQ->base,iQ->rel);
if ( (submethod= jstr(argjson,"submethod")) != 0 && (exchange= jstr(argjson,"exchange")) != 0 && strcmp(exchange,"active") == 0 && iQ != 0 )
{
if ( strcmp(submethod,"simplebot") == 0 )
{
if ( (bot= tradebot_compile(argjson,iQ,api)) == 0 )
return(clonestr("{\"error\":\"tradebot compiler error\"}"));
iQ->s.isask ^= 1;
if ( (oppobot= tradebot_compile(argjson,iQ,api)) == 0 )
return(clonestr("{\"error\":\"tradebot compiler error\"}"));
bot->oppo = oppobot;
oppobot->oppo = bot;
iguana_launch("bot",(void *)Tradebot_loop,bot);
iguana_launch("oppobot",(void *)Tradebot_loop,oppobot);
return(clonestr("{\"result\":\"tradebot started\"}"));
} else return(clonestr("{\"error\":\"unrecognized tradebot command\"}"));
return(clonestr("{\"result\":\"tradebot command processed\"}"));
} else return(clonestr("{\"error\":\"no prices777 or no tradebot submethod or not active exchange\"}"));
}
#endif

1583
InstantDEX/trades.h

File diff suppressed because it is too large

2
LEGAL/AUTHORS

@ -0,0 +1,2 @@
jl777 NXT-SQ9J-JCAN-8XVY-5XN7K

339
LEGAL/COPYING

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

67
LEGAL/DEVELOPER-AGREEMENT

@ -0,0 +1,67 @@
This document describes the agreement between the SuperNET developers
regarding copyright and licensing policies.
0. License.
The SuperNET software is distributed under the GPL version 2, with the exception of
the code that allows SuperNET agents to be created. Agent reference code uses the MIT
license to allow fully unencumbered development of SuperNET agents. Independently created
SuperNET agents can even be closed source and be made available via the service provider
functionality within SuperNET. Also, service providers are free to decide on what
type of fees to charge for their services.
1. Individual copyright.
Each core developer retains full copyright over his contributions to
the code. The aggregate "Copyright © The SuperNET Developers" notice
can still be used in some places for brevity, but the metadata
maintained by the version control software (currently Git) about the
origin and subsequent modifications of each file shall be used as a
definitive record of the specific copyright holders for that file or
modification (if original enough to be copyrightable).
2. Outside contributions.
Contributions of non-committers (those without write access to the
repository) shall only be accepted if submitted under the MIT license,
or if placed in the public domain. Contributions of non-committers that
do not specify a license shall be deemed to be public domain work.
3. Closed source releases.
Each copyright holder grants a non-transferable permission to the SuperNET
development team to use his code in closed source experimental
releases, provided that those are clearly labeled as experimental, for
testing purposes only, and are in a reasonable timeframe (not to exceed
six months) superseded by open source non-experimental releases with
essentially the same functionality.
4. Re-licensing.
Re-licensing of the SuperNET software under a different license requires the
agreement of all copyright holders whose work is being re-licensed. To
ensure that an unreachable copyright holder cannot prevent the active
development team from making licensing decisions, each copyright holder
who leaves the development team shall provide an NXT account number in
the AUTHORS file, at which he can be contacted to discuss such
decisions. Lack of such contact info, or lack of any type of response to
a re-licensing permission request after more than 28 days, as recorded
in the NXT blockchain, shall be interpreted as an irrevocable permission
to the then active development team to perform the specific re-licensing
for which such a permission has been sought.
5. Pseudonymous developers.
Developers may choose to contribute under a fictitious name. Such
developers shall provide verifiable crypto addresses in the AUTHORS file
A verified signature with such addresses shall be considered
sufficient, for making legally binding statements, or as a proof of
copyright ownership, by such pseudonymous developers.

32
LEGAL/LICENSE

@ -0,0 +1,32 @@
Copyright © 2013-2015 The SuperNET Developers.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2,
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License version 2 for more details.
You should have received a copy of the GNU General Public License version 2
along with this program in the file COPYING. If not, see
<https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt>.
The SuperNET development team will consider granting exceptions to allow use of
this software under a different license on a case by case basis. Please see the
DEVELOPER-AGREEMENT file describing the developer agreement on copyright
and licensing policies, and the AUTHORS file for individual copyright holder
information.
This software uses third party libraries, distributed under licenses described
in THIRDPARTY-LICENSES.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

21
LEGAL/THIRDPARTY-LICENSES

@ -0,0 +1,21 @@
The following third party projects are incorporated into SuperNET and their respective licenses are adopted for each of these projects. Please see the files for each project for the exact details of their licensing. Most of them are in the public domain, MIT license or GPL.
libtom: Tom St Denis, tomstdenis@gmail.com, http://libtom.org
tweetnacl: http://tweetnacl.cr.yp.to/
curve25519: http://code.google.com/p/curve25519-donna/ and http://cr.yp.to/ecdh.html
libtai: also from DJB http://tweetnacl.cr.yp.to/
SaM and vps: from Come-from-Beyond
cJSON: Copyright (c) 2009 Dave Gamble http://sourceforge.net/projects/cjson/
uthash/utlist: Copyright (c) 2003-2014, Troy D. Hanson http://troydhanson.github.com/uthash/
inet.c: Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") Copyright (c) 1996-1999 by Internet Software Consortium.
libgfshare: Copyright Daniel Silverstone <dsilvers@digital-scurf.org>
misc: there might be some other third party files not listed above, in such cases the relevant copyright header in the top of these files govern

78
Makefile

@ -0,0 +1,78 @@
CRYPTO777 = agents/libcrypto777.a
IGUANA = agents/iguana
INSTANTDEX = agents/InstantDEX
PAX = agents/PAX
PRICES = agents/prices
PANGEA = agents/pangea
TRADEBOTS = agents/tradebots
SUPERNET = agents/SuperNET
DEPS =
CFLAGS = -Wall -Wno-deprecated -Wno-unused-function -fno-strict-aliasing
LIBS = ../agents/libcrypto777.a -lcurl -lssl -lcrypto -lpthread -lz -lm
CC = gcc
OS := $(shell uname -s)
ifeq ($(OSNAME),Linux)
CFLAGS += -Wno-unused-but-set-variable
endif
CFLAGS += -O2
all: $(CRYPTO777) $(IGUANA) $(TRADEBOTS) $(SUPERNET) # $(INSTANTDEX) $(PAX) $(PRICES) $(PANGEA)
$(CRYPTO777): crypto777/OS_nonportable.c crypto777/OS_portable.c crypto777/OS_time.c crypto777/iguana_OS.c crypto777/OS_portable.h crypto777/iguana_utils.c crypto777/bitcoind_RPC.c crypto777/cJSON.c crypto777/curve25519-donna.c crypto777/curve25519.c crypto777/hmac_sha512.c crypto777/inet.c crypto777/libgfshare.c crypto777/ramcoder.c crypto777/SaM.c 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/jmemmgr.c crypto777/jpeg/jmemnobs.c; \
cd crypto777; gcc -c -O2 *.c jpeg/jaricom.c jpeg/jcapimin.c jpeg/jcapistd.c jpeg/jcarith.c jpeg/jccoefct.c jpeg/jccolor.c \
jpeg/jcdctmgr.c jpeg/jchuff.c jpeg/jcinit.c jpeg/jcmainct.c jpeg/jcmarker.c jpeg/jcmaster.c \
jpeg/jcomapi.c jpeg/jcparam.c jpeg/jcprepct.c jpeg/jcsample.c jpeg/jctrans.c jpeg/jdapimin.c \
jpeg/jdapistd.c jpeg/jdarith.c jpeg/jdatadst.c jpeg/jdatasrc.c jpeg/jdcoefct.c jpeg/jdcolor.c \
jpeg/jddctmgr.c jpeg/jdhuff.c jpeg/jdinput.c jpeg/jdmainct.c jpeg/jdmarker.c jpeg/jdmaster.c \
jpeg/jdmerge.c jpeg/jdpostct.c jpeg/jdsample.c jpeg/jdtrans.c jpeg/jerror.c jpeg/jfdctflt.c \
jpeg/jfdctfst.c jpeg/jfdctint.c jpeg/jidctflt.c jpeg/jidctfst.c jpeg/jidctint.c jpeg/jquant1.c \
jpeg/jquant2.c jpeg/jutils.c jpeg/jmemmgr.c jpeg/jmemnobs.c; \
ar rcu ../agents/libcrypto777.a *.o jpeg/*.o; cd ..
$(IGUANA): ;\
cd iguana; $(CC) -o ../agents/iguana *.c $(LIBS); make; cd ..
$(SUPERNET): ;\
cd SuperNET; $(CC) -o ../agents/SuperNET *.c $(LIBS); make; cd ..
$(INSTANTDEX): ;\
cd InstantDEX; $(CC) -o ../agents/InstantDEX *.c $(LIBS); make; cd ..
$(PANGEA): ;\
cd pangea; $(CC) -o ../agents/pangea *.c $(LIBS); make; cd ..
$(TRADEBOTS): ;\
cd tradebots; $(CC) -o ../agents/tradebots *.c $(LIBS); make; cd ..
$(PRICES): ;\
cd pangea; $(CC) -o ../agents/pangea *.c $(LIBS); make; cd ..
$(PAX): ;\
cd peggy; $(CC) -o ../agents/PAX *.c $(LIBS); make; cd ..
iguana: $(IGUANA)
SN: $(SuperNET)
idex: $(InstantDEX)
PAX: $(PAX)
prices: $(PRICES)
pangea: $(PANGEA)
lib: $(CRYPTO777)
doesntexist:
clean: doesntexist; \
rm agents/*; cd crypto777; rm *.o jpeg/*.o; make clean; cd ..; cd iguana; make clean; cd ..; cd SuperNET; make clean; cd ..; cd InstantDEX; make clean; cd ..; cd pangea; make clean; cd ..; cd prices; make clean; cd ..; cd tradebots; make clean; cd ..

15
README.md

@ -1 +1,14 @@
# SuperNET iguana is easy to build. just make sure you have the dev versions of openssl and curl installed
gcc -O2 -o iguana *.c InstantDEX/*.c -lssl -lcrypto -lpthread -lcurl -lm
the above builds native iguana on unix/osx
then just run it and browse to http://127.0.0.1:7778/?method
you can use the gui to find the URL you need for an operation, then add /json to get just the json and not the entire webpage. alternatively a POST (ie via curl --data) with the JSON request will just return json
http://127.0.0.1:7778/ramchain/block/height/0 -> full webpage
http://127.0.0.1:7778/json/ramchain/block/height/0 -> JSON only
the superugly GUI is not stateless, there is a default coin that is used for any coin based API.

48
SuperNET/Makefile

@ -0,0 +1,48 @@
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# GNU Makefile based on shared rules provided by the Native Client SDK.
# See README.Makefiles for more details.
VALID_TOOLCHAINS := pnacl newlib glibc clang-newlib mac
NACL_SDK_ROOT ?= $(abspath $(CURDIR))
TARGET = SuperNET
EXTRA= -D__PNACL
include $(NACL_SDK_ROOT)/tools/common.mk
CHROME_ARGS += --allow-nacl-socket-api=127.0.0.1
DEPS = nacl_io
LIBS = crypto777 curl ssl crypto z glibc-compat nacl_spawn ppapi nacl_io ppapi_simple # cli_main ppapi_cpp ppapi_simple
CFLAGS = -Wall -D__PNACL -fno-strict-aliasing $(EXTRA)
LFLAGS = libs
SOURCES = main.c SuperNET.c
# Build rules generated by macros from common.mk:
$(foreach dep,$(DEPS),$(eval $(call DEPEND_RULE,$(dep))))
$(foreach src,$(SOURCES),$(eval $(call COMPILE_RULE,$(src),$(CFLAGS))))
# The PNaCl workflow uses both an unstripped and finalized/stripped binary.
# On NaCl, only produce a stripped binary for Release configs (not Debug).
ifneq (,$(or $(findstring pnacl,$(TOOLCHAIN)),$(findstring Release,$(CONFIG))))
$(eval $(call LINK_RULE,$(TARGET)_unstripped,$(SOURCES) $(LOCALLIBS),$(LIBS),$(DEPS)));
$(eval $(call STRIP_RULE,$(TARGET),$(TARGET)_unstripped))
else
$(eval $(call LINK_RULE,$(TARGET),$(SOURCES),$(LIBS),$(DEPS)))
endif
$(eval $(call NMF_RULE,$(TARGET),))

23
SuperNET/SuperNET.c

@ -0,0 +1,23 @@
/******************************************************************************
* Copyright © 2014-2015 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
#include "../crypto777/OS_portable.h"
char *SuperNET_JSON(char *jsonstr)
{
return(clonestr("{\"error\":\"SuperNET is just a stub for now\"}"));
}

31
SuperNET/main.c

@ -0,0 +1,31 @@
/******************************************************************************
* Copyright © 2014-2015 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 CHROMEAPP_NAME SuperNET
#define CHROMEAPP_STR "SuperNET"
#define CHROMEAPP_CONF "SuperNET.conf"
#define CHROMEAPP_MAIN SuperNET_main
#define CHROMEAPP_JSON SuperNET_JSON
#define CHROMEAPP_HANDLER Handler_SuperNET
#include "../pnacl_main.h"
// ALL globals must be here!
void SuperNET_main(void *arg)
{
while ( 1 )
sleep(777);
}

17
SuperNET/manifest.json

@ -0,0 +1,17 @@
{
"name": "SuperNET",
"uri": "SuperNET.pexe",
"short_name": "SuperNET",
"version": "44.1.2",
"manifest_version": 2,
"description": "SuperNET",
"offline_enabled": true,
"icons": { "128": "icon128.png" },
"app":
{
"name": "SuperNET",
"background": { "scripts": ["background.js"] },
"sockets": { "tcp": { "connect": "" }, "tcpServer": { "listen": "127.0.0.1:*" } },
"permissions": [ "unlimitedStorage", "filesystem", "storage", "system.storage", "system.display", "system.network","system.cpu" ]
}
}

1772
confs/BTCD_hdrs.txt

File diff suppressed because it is too large

49
confs/BTCD_peers.txt

@ -0,0 +1,49 @@
78.47.58.62
67.212.70.88
94.102.50.69
50.179.58.158
194.135.94.30
109.236.85.42
104.236.127.154
68.45.147.145
37.59.14.7
78.47.115.250
188.40.138.8
62.75.143.120
82.241.71.230
217.23.6.2
73.28.172.128
45.55.149.34
192.0.242.54
81.181.155.53
91.66.185.97
85.25.217.233
144.76.239.66
95.80.9.112
80.162.193.118
173.65.129.85
2.26.173.58
78.14.250.69
188.226.253.77
58.107.67.39
124.191.37.212
176.226.137.238
69.145.25.85
24.168.14.28
73.201.180.47
76.188.171.53
63.247.147.166
121.108.241.247
36.74.36.125
106.186.119.171
188.166.91.37
223.134.228.208
89.248.160.244
178.33.209.212
71.53.156.38
88.198.10.165
24.117.221.0
74.14.104.57
158.69.27.82
110.174.129.213
75.130.163.51

195
confs/BTC_hdrs.txt

@ -0,0 +1,195 @@
386001
0 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
2000 00000000dfd5d65c9d8561b4b8f60a63018fe3933ecb131fb37f905f87da951a
4000 00000000922e2aa9e84a474350a3555f49f06061fd49df50a9352f156692a842
6000 00000000dbbb79792303bdd1c6c4d7ab9c21bba0667213c2eca955e11230c5a5
8000 0000000094fbacdffec05aea9847000522a258c269ae37a74a818afb96fc27d9
10000 0000000099c744455f58e6c6e98b671e1bf7f37346bfd4cf5d0274ad8ee660cb
12000 0000000011d1d9f1af3e1d038cebba251f933102dbe181d46a7966191b3299ee
14000 000000002d9050318ec8112057423e30b9570b39998aacd00ca648216525fce3
16000 00000000679a1ab3af6da03f13a0bc96d7215e65458b2d2edfa030b5b431e8b3
18000 00000000f914f0d0692e56bd06565ac4de668251b6a29fe0535d1e0031cfd0de
20000 00000000770ebe897270ca5f6d539d8afb4ea4f4e757761a34ca82e17207d886
22000 000000004625a14242beccb38c63a1f770a76ee5788764e6c0abd4129bbc1b9d
24000 00000000f04fccc81f37002707e9501a3f7bdcf25f65531f386a2da8af20122e
26000 000000006d6c151db6d4d67356d590a897a11cd7d8111ee989de6f2f548410bf
28000 00000000172c5ed49d7dfc29bf9a18a53fa2d050fa37aa210d6d4080fd0c7e67
30000 00000000de1250dc2df5cf4d877e055f338d6ed1ab504d5b71c097cdccd00e13
32000 00000000049172ba3ec1b673cf13e3d0049c1c07bb103ed3fa300e3833480055
34000 00000000495968d19210d3be15bd24fdc19805a0ef15026b0bb4482b04a9da3c
36000 0000000080c3deea35dc3df90a5fbe5f27db52f5e01018ae7d62f8b454c71335
38000 000000002dfebce284d1e08b6cf04452530891579b7377669865889498de8f3f
40000 00000000504d5fa0ad2cb90af16052a4eb2aea70fa1cba653b90a4583c5193e4
42000 000000000f80c09687893406279f62da437a6a0b95b8dc096b30c10ce088fc64
44000 000000000122898b31073a770a97cf599c00672fc8d6ae15652235862f8b76d8
46000 000000001dd39771dbe4f9fc6da07327f13f894dd2c1a46cdfcedf930fbbc52b
48000 000000000f3d40ea2bfa8d779010e52cff4720c072ec4b12ed576cf5cf93c947
50000 000000001aeae195809d120b5d66a39c83eb48792e068f8ea1fea19d84a4278a
52000 00000000082bc4398c4aa5bd8d9fc452d60d533ef68baabf594c9e7d6649049f
54000 00000000144197f54afa21ae7db2bc93eee604432101fc0ebe7966a52bb27e61
56000 000000000dfa452ea45e0426dd8914c35e24dfd4399037c5e6deb9f18f58d6d3
58000 0000000013e3791d288d9db814c52fbdf240b2206eb8e19d7dc80013c60c0c00
60000 000000000b554c46f8eb7264d7d5e334382c6fc3098dabf734de37962ccd7495
62000 0000000006dd4bc72daabef992f860e703820de119af3e24a1ea6f6c81521011
64000 0000000003d7055b51d7b9ab693de84c03201fe0396af61dbb30bf31445d3f55
66000 00000000071d7e8a0f4895e60c1073df9311d65a85244be1ee6369c9506281af
68000 0000000000d991791fdfdbccbbc2a73d2f86ccf78e2d0a7ce7675f40b5986b3e
70000 00000000002b8cd0faa58444df3ba2a22af2b5838c7e4a5b687444f913a575c2
72000 0000000000eb357d4c6fef6ad9a6fade126985ad36042a99cf215a4454545977
74000 0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20
76000 0000000000571138ff757a28ddf9b56f28c4a461e170660bb5ae79a556069bb6
78000 00000000001f3fe62641b473673c9ababbe207046a109f0861af95c905a918fa
80000 000000000043a8c0fd1d6f726790caa2a406010d19efd2780db27bdbbd93baf6
82000 00000000000c9d1c4acc114afb58d55db5ec44a963263cf6247220b7a3f85c5c
84000 00000000001385326e30864192ba84ed2f9cbfadf0698655b1c25f93c92f22ad
86000 000000000000ff4e1adb14f07774dad6b34968a5e19d1a2fe1fc9157e7c2b85d
88000 00000000000ae9e98b82b39a912cdc0ebed97c26376780ac996c84d9ec3264a4
90000 0000000000071694daf735a6b5da101d77a04c7e6008c680e461f0025ba7b7af
92000 0000000000001df90b0c523a4d7e4731336b00cf4ba9d8e02d111523df80998c
94000 000000000002a4c42580d51f0ddfd867eaaa790781c484c633a69167d17b48ec
96000 000000000002c86b568cdd2d0f4b0430cccf42bcde3361f63a32e23b5d839e99
98000 000000000002272a6dfb695d9db936d813bf0055ae92e920c2791d4c5f7290f1
100000 000000000003ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506
102000 00000000000335c47dd6ae953912d172a4d9839355f2083165043bb6f43c2f58
104000 000000000000a9887c91956b638bb3c0651321fdb24715354c3fc6633f5a16a3
106000 00000000000058d919f52d255f394ed0aa3a344432676fd30f1aab4e10c22fad
108000 00000000000167cea0b43ff7ce22f330d3e302832187eb31c61b15bb1511e118
110000 000000000001bbda3f22ef8e476b470a2d3ae16821c23a6d22db77318d0799a9
112000 0000000000001d69b3899a49f37799c375a7471829953d5470f468f48ff70432
114000 0000000000003195a1e6dc48a540264d37e9ef79b552bd78ea4b93a3b6e7e449
116000 00000000000007ff257fb2edd3fdbd7b00c127a66dae1288fc5e26c402d13bf7
118000 000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553
120000 0000000000000e07595fca57b37fea8522e95e0f6891779cfd34d7e537524471
122000 0000000000002fe5f29af38282ac1c8f4ea2bf8a0855946150130419491b6c05
124000 00000000000023e9a0523cfac29afe07a07acf81e273cd892c51ff8318846620
126000 000000000000166b7d480aada35af1e6f9a2835d68f9c2fbd272073dc6c9d5fb
128000 00000000000003b8ddd8692769e1965554a8bb030863e0566a28bc0dc952864e
130000 00000000000011906b491883ab0f16f0e690b133ca860b199b775c3cf6581c21
132000 00000000000000a7a0483857f0d951983ff2834a47c38fdcc22563ac0f8f707b
134000 00000000000007e3e442ce1423496a064a7c34342ba98be164ac0c9f9b872213
136000 00000000000004da0d6d69fd474fa08fe2ff3111ff1e9e01f72899dcd9d897f0
138000 0000000000000044c7b6a5511c0b2ae64ec545abccac8053f31cf7bba23bb886
140000 000000000000086e28cf4717a80066def0ec26c53d660582bd997221fef297db
142000 00000000000006379826f5f10cd23739b9c29f87ca10f199f9f4b72006311f85
144000 0000000000000681a73f1bb50454cee419048d24e1091bcddadded89df53fd07
146000 0000000000000188cbeebda87456f040370995dc11eb3a1e76b1577b6e0b588d
148000 00000000000008be94b219a94752bde6a6a1c5b9d72abf2aaab53df7d93c5fa6
150000 0000000000000a3290f20e75860d505ce0e948a1d1d846bec7e39015d242884b
152000 0000000000000aca2b3a267dab498adc48afd15b60cbf21fa58dc26c86a6dc13
154000 0000000000000a7446d1a63b8229670aa02d1d9fdfd729b89107fe5d88dacd8e
156000 00000000000002adfcffbd5f09744ae3b930597dd0ea684cd37b816783ba3762
158000 00000000000000e50d56f13c7ce64183386abcac63462ca745b711be27568f52
160000 000000000000066c6e629b2fb49c7fcc52b82fe9833f328e0c3943856facf231
162000 00000000000001a83f5b20cd132f38f792fc02a17eb14d494c780ea9d1c82acc
164000 00000000000005a38f162cf308edea0a0a5d000bdb2073cba2386ebb1df7a2cf
166000 00000000000003b3402f35327d144a465f3768d6e6cb06cd8a2d8fc1328b2477
168000 000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763
170000 000000000000051f68f43e9d455e72d9c4e4ce52e8a00c5e24c07340632405cb
172000 0000000000000837e82c3a4ebe35a1d1d943e056234dba7c629922c6d4052d4c
174000 0000000000000504d3e701deb624eee4370f50c3d688fd1c27be5bbef07d76dd
176000 00000000000004659b5b8602b2132b62973994079a1c828df6ef8d6427e4686b
178000 00000000000009eae2697a7aaf57e730b707b9f4530449c16d924d534d41f297
180000 00000000000004ff83b6c10460b239ef4a6aa320e5fffd6c7bcedefa8c78593c
182000 000000000000068dce12903c1447e4c5b60311b61e443a25d5fc82c77f4f9a8f
184000 000000000000060405a235c6b968ccb18fd6b3800ae9742c2524e28863367359
186000 000000000000072ede9629fd1fd1af3cc2baa0e637f1959f34884be0e160dd1c
188000 000000000000004cf0c72d6dedfde88ca4c3dae129563210072ee68acded0ab1
190000 0000000000000708bf3b261ffc963b6a768d915f9cfc9ec0a6c2a09969efad1a
192000 00000000000000af130d565291ba49208c546685c69b48a293aaf06387fc22ef
194000 000000000000046242d4984ecf2217e9afa113f2835bffbff118f2df4d80b216
196000 00000000000006ae59396d4a289e83fe1b9967630752a5799f064620af7836a9
198000 000000000000000f2ad431ff18ab1673d911395c8fa1f6801e054c5dcb54f8fb
200000 000000000000034a7dedef4a161fa058a2d67a173a90155f3a2fe6fc132e0ebf
202000 00000000000003282fe1d5533e4275fd9f51e6ba0352ec01f32914e9fbaeaf55
204000 0000000000000423eb625dc140272ab97fea3ba6baf1dc56de77deabcc492872
206000 0000000000000130b815d40fd6d8851438cd21ac9e428615ba03a1285ef1374c
208000 000000000000001db5a1515a5f8534c941b1628f60466e6b709b3b320254afff
210000 000000000000048b95347e83192f69cf0366076336c639f9b7228e9ba171342e
212000 00000000000003d906e4131c39f7655b72df40146d2967f5d75113a09610de61
214000 00000000000003e6427f9fafa8b0e1af0859f15cea90d911f64445d296a2781a
216000 00000000000001f79a2db15d0ec6d951729e044749372caf504679bba5b1e65e
218000 0000000000000569070e338293af66258adba29dcdd5f33212314dff752ff458
220000 000000000000002fdd2c741ed50bc3975a640ca419081711f30f553939641303
222000 00000000000002c752a481ce0c45450ab046e640d38d6532178721e7700d8148
224000 0000000000000107ee276d037218bf1780dbf6d4256bd7e05c66ca133bbc9ac5
226000 000000000000012c614cf477c3b155d339f29d565c0258f9846c2f4dd402ff9b
228000 00000000000000efc4311c93fafbccedb6fdc682b566cba9519f1736b9788a67
230000 000000000000012cfb19f5662707816e122ad60dd9b1cd646c6c9899be2c9667
232000 000000000000018f47636e1c3a946db77624880ae484ffb0233f5aac6316b3bb
234000 00000000000000597f9263ea97bed4d3b10fbd55733a73bd1027f1a9b6c1451a
236000 00000000000000f2f5e55e89dde082cecc9b4a46a10bbb4197f5e35b16612db5
238000 000000000000010014007d4b51ab60063684665401e448c6b0b1971a7398a442
240000 000000000000000e7ad69c72afc00dc4e05fc15ae3061c47d3591d07c09f2928
242000 00000000000000c95233d37a8c78dff10afecb14060347151b7eb7a04a2a5a3c
244000 000000000000006ded1526017d5b87ca22e1bd0da3921872cc99e9ec77ee5166
246000 000000000000004c318a3ad2ebac28d140fada215b11f5b7d8e9151ff0b000af
248000 000000000000004d945017c14b75a3a58a2aa6772cacbfcaf907b3bee6d7f344
250000 000000000000003887df1f29024b06fc2200b55f8af8f35453d7be294df2d214
252000 00000000000000200e99940b296ded4ce16462bba1950453b29abf313ba7cc47
254000 000000000000004753be91559a2c74c6cb8a5d2be6db1df2ca0b2385697e53ff
256000 00000000000000252b217c0ce5c4d96b825b90dacbe8e4dcf5f6a8ba6749f3c2
258000 00000000000000159f682a983465761f471dd24300746efe8db5642411f1b631
260000 000000000000001fb91fbcebaaba0e2d926f04908d798a8b598c3bd962951080
262000 000000000000001002ac67e026c523c3779b1ff2e3b9e2b7bfa6022ee1afae2a
264000 000000000000000d05c31485c532503939ca0b88d7e322dff79900ee6cdd5ed4
266000 0000000000000009d755c65d58c7c1fde9167ba632a85574de3bb11c8a862e35
268000 000000000000000048974ba0669938f7f8463650cd5c48c027aafd88c00a46af
270000 0000000000000002a775aec59dc6a9e4bb1c025cf1b8c2195dd9dc3998c827c5
272000 00000000000000050a89e2ffb28757d35e14615f23b981eca68906c8c71f65f2
274000 0000000000000003fe2d3425e9f9b906f02f40b3db90d908ba0fbd1e44cf43f8
276000 0000000000000004b8ed801f8a09ba8c1248a5b1dd1533a35124a80438573f59
278000 0000000000000001bcadd1e4b4d01063a17347dfca126c63893d2aa37d82eb7f
280000 0000000000000001c091ada69f444dc0282ecaabe4808ddbb2532e5555db0c03
282000 0000000000000002337ad25e6a9767420766309cfea79f13dd9c910bcf5ca063
284000 0000000000000000eac86582f121e5431734e2ea36bf73347022c99c1adae37f
286000 00000000000000004388ae444347bde423f2f3aa6ef335b50909f5bc27d31ea3
288000 00000000000000003c395f08779c3ac1301488b8a18c0999c008129a55610785
290000 0000000000000000fa0b2badd05db0178623ebf8dd081fe7eb874c26e27d0b3b
292000 0000000000000000620671231acb6a68134a0396235dcb0e53f4fc82bbaa1184
294000 0000000000000000cb2540b3f00ce422887904c75b24bf75b8a73817302a4138
296000 00000000000000009570102278e59ecf045c16ec8c8a5ea85bf823d0ec72e3d0
298000 000000000000000047d2f2eb7278e3f4aded9acaf502f5ec27bab5018b5871f2
300000 000000000000000082ccf8f1557c5d40b21edabb18d2d691cfbf87118bac7254
302000 0000000000000000072268c9bb18603566ed5012378c29bb4d37e34cead7448d
304000 00000000000000003558a1ceec3f5338c0e887b4171410195a7fa0a81bcaa628
306000 00000000000000002bb3265a8bf67ec2aa436c297ac7e56fcedd4dbaecccacc0
308000 00000000000000001d55aa114bddd81938d09e2dccd432dec59a4078ca0bc0f4
310000 0000000000000000125a28cc9e9209ddb75718f599a8039f6c9e7d9f1fb021e0
312000 00000000000000002bd1fa27964e31fe9861b40940e7ece2cfa359765b219a49
314000 000000000000000008ae6cb20997f3c4aacc50ee2f0d08a0c3691907fe7357a3
316000 00000000000000000d77a89ab1069e47d1213ae509de95ee0d9ab095a725f7d7
318000 00000000000000002583a647dc5f084a312e12bb90a70c3fe1eb1e4d419f35b6
320000 000000000000000015aab005b28a326ade60f07515c33517ea5cb598f28fb7ea
322000 0000000000000000177da809382f93ca1c4336811e4a910050689d317d62264e
324000 00000000000000000b9880c40075d763b2a5f04fc01444a6278c5d2d442cda0b
326000 00000000000000001e95e7216072cd53353b964054b592f7ce84d3743aab125a
328000 000000000000000009cb9a303d105e7b96b36546a3196f6f79ece4b43712cbb2
330000 00000000000000000faabab19f17c0178c754dbed023e6c871dcaf74159c5f02
332000 00000000000000001799255bc0c35f91f7d4fddfbf7e84dedf94fc59cde9b7f2
334000 000000000000000008d1ff7b7673837e9d7e1324dc7ab8498405ea583f43f53d
336000 0000000000000000125e3e6f327edcd7163b486efc16e79b8a996270127b54df
338000 00000000000000001983dc4a87df627b63cdce28e5321cb867fbbb74c0e87e8e
340000 00000000000000000d9b2508615d569e18f00c034d71474fc44a43af8d4a5003
342000 0000000000000000007220892af98a563a1c891c756e94be3f14edddcf637c3e
344000 000000000000000005f0a16f5a9f95eeb95c5eed0eb221e8f5dc5a9943a03aee
346000 0000000000000000068d33fd865621cb7eedbf05c6b235191fa1cb8ee2c797d7
348000 00000000000000001598a651988bb3a45237c4f801cf8049be20f74aed8e827a
350000 0000000000000000053cf64f0400bb38e0c4b3872c38795ddde27acb40a112bb
352000 00000000000000001635a4b5f27d2ec458f7bca550d71f490b93e98e7a07cbca
354000 00000000000000000cf8af9be2709e9d7adf2c33b3789aeeff517987f4be22e8
356000 0000000000000000138ce5493b612b0e90b66e2a76714088d6b3e6a4770215af
358000 0000000000000000073aceefab8c381c3c4edb4f87a6d5d2ae32184278218429
360000 00000000000000000ca6e07cf681390ff888b7f96790286a440da0f2b87c8ea6
362000 00000000000000000bfcad6c331dd152cfc713e9e0790978a10e0bfda3e030d5
364000 00000000000000000e20bcf213a0bbd6be88d5fede6b060c737f7f8b7f1df504
366000 0000000000000000138e108e780fdb71eb4cad533b46445ab6befbf9687f561f
368000 00000000000000000d39970aac12754eb89c2dcfda539b65562e5c3fec102c24
370000 000000000000000002cad3026f68357229dd6eaa6bcef6fe5166e1e53b039b8c
372000 0000000000000000028093cc8035a6bc4e0d1b40932c2f8b50312a3fc86bf3da
374000 00000000000000001016aa3783721673bebbcd1efa49946b52cceb09a81465a6
376000 0000000000000000106e9e99cf4fce4e8a4abc97f3e883956e26d76b3a1133ce
378000 00000000000000000516cd5b5f4b7e528d6e61c643595cc818f1d02f53da4281
380000 00000000000000000b06cee3cee10d2617e2024a996f5c613f7d786b15a571ff
382000 000000000000000003cf98590769bde40ffcd6800733ab47dd406d8203e65a89
384000 000000000000000005dc7ea53e2f6eeb09798cc9d2214f09d249661c36c288b3
386000 00000000000000000d94c8c0b0ddec874d2a597e988154733d9ea614292c08bb

137
confs/BTC_peers.txt

@ -0,0 +1,137 @@
108.58.252.82
74.207.233.193
130.211.146.81
71.193.19.234
173.66.1.180
104.158.113.201
108.207.245.69
107.4.134.66
96.231.100.124
209.6.208.31
69.141.89.74
82.20.129.167
5.9.222.226
149.210.234.41
168.235.85.242
52.91.247.30
191.237.64.28
173.236.101.34
73.189.2.240
106.186.113.184
173.64.13.6
73.166.27.56
70.106.255.189
168.62.188.213
71.234.225.255
24.41.10.204
72.175.146.90
184.107.155.82
162.220.47.150
12.23.127.150
169.228.66.43
192.227.137.5
71.205.232.181
207.182.151.130
46.4.22.45
198.50.238.171
174.59.182.120
66.172.10.4
75.73.82.209
91.121.108.61
24.6.74.4
37.187.78.27
96.32.46.235
107.170.13.184
148.251.151.48
178.62.70.16
144.76.185.151
144.76.92.199
91.121.210.159
76.105.242.7
54.84.231.113
89.187.134.220
64.15.77.36
212.51.147.153
216.15.33.203
74.100.90.30
185.18.6.3
104.131.65.197
89.248.174.54
128.8.124.7
54.232.245.146
67.205.101.120
72.207.119.149
192.95.27.144
69.61.93.240
209.91.190.202
50.35.82.152
66.175.220.212
23.239.22.219
73.229.104.201
207.244.73.8
78.129.251.170
139.162.211.181
172.245.5.156
98.144.123.251
177.238.90.180
198.71.92.236
73.254.38.48
75.189.201.141
52.24.104.64
71.231.209.66
87.224.35.189
73.162.143.196
82.204.103.94
91.148.210.17
94.242.229.158
188.121.252.243
70.39.8.97
95.97.112.190
109.228.152.9
91.209.77.101
217.76.121.251
79.136.29.43
178.212.136.92
178.255.41.123
84.212.200.24
91.145.49.56
162.220.246.101
95.167.109.125
153.163.32.61
78.67.29.111
92.247.229.163
210.195.201.103
95.84.162.95
106.38.234.67
186.88.0.18
121.208.106.80
120.55.193.136
124.171.128.201
54.94.163.92
98.217.125.225
104.156.97.121
162.255.117.230
129.13.252.36
79.120.12.63
108.5.176.30
69.144.244.229
76.22.18.34
115.29.186.22
78.46.193.75
213.91.211.17
164.177.179.162
134.249.141.40
69.140.88.12
178.212.136.108
109.120.250.3
154.127.61.55
123.120.167.101
73.210.74.120
82.136.95.220
124.122.212.150
81.191.80.160
96.58.196.51
77.23.111.25
14.175.245.51
76.164.234.12
92.156.214.192

40
crypto777/Makefile

@ -0,0 +1,40 @@
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# GNU Makefile based on shared rules provided by the Native Client SDK.
# See README.Makefiles for more details.
VALID_TOOLCHAINS := pnacl newlib glibc clang-newlib mac
NACL_SDK_ROOT ?= $(abspath $(CURDIR))
TARGET = crypto777
EXTRA= -D__PNACL
include $(NACL_SDK_ROOT)/tools/common.mk
CHROME_ARGS += --allow-nacl-socket-api=127.0.0.1
DEPS = nacl_io
LIBS =
CFLAGS = -Wall -D__PNACL -fno-strict-aliasing $(EXTRA)
LFLAGS = libs
SOURCES = cJSON.c ramcoder.c iguana_OS.c OS_portable.c OS_time.c OS_nonportable.c hmac_sha512.c SaM.c bitcoind_RPC.c inet.c iguana_utils.c curve25519.c curve25519-donna.c jpeg/jaricom.c jpeg/jcapimin.c jpeg/jcapistd.c jpeg/jcarith.c jpeg/jccoefct.c jpeg/jccolor.c \
jpeg/jcdctmgr.c jpeg/jchuff.c jpeg/jcinit.c jpeg/jcmainct.c jpeg/jcmarker.c jpeg/jcmaster.c \
jpeg/jcomapi.c jpeg/jcparam.c jpeg/jcprepct.c jpeg/jcsample.c jpeg/jctrans.c jpeg/jdapimin.c \
jpeg/jdapistd.c jpeg/jdarith.c jpeg/jdatadst.c jpeg/jdatasrc.c jpeg/jdcoefct.c jpeg/jdcolor.c \
jpeg/jddctmgr.c jpeg/jdhuff.c jpeg/jdinput.c jpeg/jdmainct.c jpeg/jdmarker.c jpeg/jdmaster.c \
jpeg/jdmerge.c jpeg/jdpostct.c jpeg/jdsample.c jpeg/jdtrans.c jpeg/jerror.c jpeg/jfdctflt.c \
jpeg/jfdctfst.c jpeg/jfdctint.c jpeg/jidctflt.c jpeg/jidctfst.c jpeg/jidctint.c jpeg/jquant1.c \
jpeg/jquant2.c jpeg/jutils.c jpeg/jmemmgr.c jpeg/jmemnobs.c
# Build rules generated by macros from common.mk:
$(foreach dep,$(DEPS),$(eval $(call DEPEND_RULE,$(dep))))
$(foreach src,$(SOURCES),$(eval $(call COMPILE_RULE,$(src),$(CFLAGS))))
$(eval $(call LIB_RULE,$(TARGET),$(SOURCES)))

133
crypto777/OS_nonportable.c

@ -0,0 +1,133 @@
/******************************************************************************
* Copyright © 2014-2015 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
#include "OS_portable.h"
#ifdef __PNACL
int32_t OS_nonportable_syncmap(struct OS_mappedptr *mp,long len)
{
printf("no way to sync mapped mem in pnacl\n");
return(-1);
}
void *OS_nonportable_tmpalloc(char *dirname,char *name,struct OS_memspace *mem,long origsize)
{
printf("no way to do tmpallocs in pnacl\n");
return(0);
}
#elif _WIN32
#include <sys/mman.h>
#include <io.h>
#include <share.h>
#include <errno.h>
#include <string.h>
#include <windows.h>
#include <inttypes.h>
#include <winsock2.h>
#include <in6addr.h>
#include <ws2tcpip.h>
#include <errno.h>
#include <fcntl.h> /* _O_BINARY */
#include <stdlib.h>
#include <wincrypt.h>
#include <stdio.h>
#include <process.h>
#include <tlhelp32.h>
#include <time.h>
char *OS_nonportable_path(char *str)
{
int32_t i;
for (i=0; str[i]!=0; i++)
if ( str[i] == '/' )
str[i] = '\\';
return(str);
}
void *OS_nonportable_mapfile(char *fname,uint64_t *filesizep,int32_t enablewrite)
{
int32_t fd,rwflags,flags = MAP_FILE|MAP_SHARED;
uint64_t filesize;
void *ptr = 0;
*filesizep = 0;
if ( enablewrite != 0 )
fd = _sopen(fname, _O_RDWR | _O_BINARY, _SH_DENYNO);
else fd = _sopen(fname, _O_RDONLY | _O_BINARY, _SH_DENYNO);
if ( fd < 0 )
{
//printf("map_file: error opening enablewrite.%d %s\n",enablewrite,fname);
return(0);
}
if ( *filesizep == 0 )
filesize = (uint64_t)lseek(fd,0,SEEK_END);
else filesize = *filesizep;
rwflags = PROT_READ;
if ( enablewrite != 0 )
rwflags |= PROT_WRITE;
ptr = mmap(0,filesize,rwflags,flags,fd,0);
_close(fd);
if ( ptr == 0 || ptr == MAP_FAILED )
{
printf("map_file.write%d: mapping %s failed? mp %p\n",enablewrite,fname,ptr);
return(0);
}
*filesizep = filesize;
return(ptr);
}
int32_t OS_nonportable_renamefile(char *fname,char *newfname)
{
char cmdstr[1024],tmp[512];
strcpt(tmp,fname);
OS_nonportable_path(tmp);
sprintf(cmdstr,"del %s",tmp);
if ( system() != 0 )
printf("error deleting file.(%s)\n",cmdstr);
else return(1);
}
int32_t OS_nonportable_launch(char *args[])
{
int32_t pid;
pid = _spawnl( _P_NOWAIT, args[0], args[0], NULL, NULL );
return pid;
}
void OS_nonportable_randombytes(unsigned char *x,long xlen)
{
HCRYPTPROV prov = 0;
CryptAcquireContextW(&prov, NULL, NULL,PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
CryptGenRandom(prov, xlen, x);
CryptReleaseContext(prov, 0);
}
int32_t OS_nonportable_init()
{
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR)
{
printf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)\n", ret);
//printf("%s\n", strError.c_str());
return -1;
}
return(0);
}
#endif

207
crypto777/OS_portable.c

@ -0,0 +1,207 @@
/******************************************************************************
* Copyright © 2014-2015 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
#include "OS_portable.h"
#include <sys/stat.h>
#ifndef MAP_FILE
#define MAP_FILE 0
#endif
void OS_portable_init()
{
#ifdef _WIN32
OS_nonportable_init();
#endif
}
// from tweetnacl
void OS_portable_randombytes(unsigned char *x,long xlen)
{
#ifdef _WIN32
return(OS_nonportable_randombytes(x,xlen));
#else
static int fd = -1;
int32_t i;
if (fd == -1) {
for (;;) {
fd = open("/dev/urandom",O_RDONLY);
if (fd != -1) break;
sleep(1);
}
}
while (xlen > 0) {
if (xlen < 1048576) i = (int32_t)xlen; else i = 1048576;
i = (int32_t)read(fd,x,i);
if (i < 1) {
sleep(1);
continue;
}
if ( 0 )
{
int32_t j;
for (j=0; j<i; j++)
printf("%02x ",x[j]);
printf("-> %p\n",x);
}
x += i;
xlen -= i;
}
#endif
}
int32_t OS_portable_truncate(char *fname,long filesize)
{
return(truncate(fname,filesize));
}
char *OS_portable_path(char *str)
{
#ifdef _WIN32
return(OS_nonportable_path(str));
#else
return(str);
#endif
}
int32_t OS_portable_renamefile(char *fname,char *newfname)
{
#ifdef _WIN32
char cmdstr[1024],tmp[512];
strcpt(tmp,fname);
iguana_compatible_path(tmp);
sprintf(cmdstr,"del %s",tmp);
if ( system() != 0 )
printf("error deleting file.(%s)\n",cmdstr);
else return(1);
#else
return(rename(fname,newfname));
#endif
}
int32_t OS_portable_removefile(char *fname)
{
#ifdef _WIN32
char cmdstr[1024],tmp[512];
strcpt(tmp,fname);
iguana_compatible_path(tmp);
sprintf(cmdstr,"del %s",tmp);
if ( system() != 0 )
printf("error deleting file.(%s)\n",cmdstr);
else return(1);
#else
return(remove(fname));
#endif
}
void *OS_portable_mapfile(char *fname,long *filesizep,int32_t enablewrite)
{
#ifdef _WIN32
return(OS_nonportable_mapfile(fname,filesizep,enablewrite);
#else
int32_t fd,rwflags,flags = MAP_FILE|MAP_SHARED;
uint64_t filesize;
void *ptr = 0;
*filesizep = 0;
if ( enablewrite != 0 )
fd = open(fname,O_RDWR);
else fd = open(fname,O_RDONLY);
if ( fd < 0 )
{
//printf("map_file: error opening enablewrite.%d %s\n",enablewrite,fname);
return(0);
}
if ( *filesizep == 0 )
filesize = (uint64_t)lseek(fd,0,SEEK_END);
else filesize = *filesizep;
rwflags = PROT_READ;
if ( enablewrite != 0 )
rwflags |= PROT_WRITE;
//#if __i386__ || _WIN32 || __PNACL
ptr = mmap(0,filesize,rwflags,flags,fd,0);
//#else
// void *mmap64(void *addr,size_t len,int32_t prot,int32_t flags,int32_t fildes,off_t off);
// ptr = mmap64(0,filesize,rwflags,flags,fd,0);
//#endif
close(fd);
if ( ptr == 0 || ptr == MAP_FAILED )
{
printf("map_file.write%d: mapping %s failed? mp %p\n",enablewrite,fname,ptr);
return(0);
}
*filesizep = filesize;
//printf("mapped %ld -> %p\n",(long)filesize,ptr);
return(ptr);
#endif
}
int32_t OS_portable_syncmap(struct OS_mappedptr *mp,long len)
{
#ifndef __PNACL
int32_t err = -1;
if ( mp->actually_allocated != 0 )
return(0);
if ( mp->fileptr != 0 && mp->dirty != 0 )
{
if ( len == 0 )
len = mp->allocsize;
err = msync(mp->fileptr,len,MS_SYNC);
if ( err != 0 )
printf("sync (%s) len %llu, err %d errno.%d\n",mp->fname,(long long)len,err,errno);
//Sync_total += len;
mp->dirty = 0;
}
return(err);
#else
return(OS_nonportable_syncmap(mp,len));
#endif
}
void *OS_portable_tmpalloc(char *dirname,char *name,struct OS_memspace *mem,long origsize)
{
#ifdef __PNACL
return(OS_nonportable_tmpalloc(dirname,name,mem,origsize));
#else
char fname[1024]; void *ptr; long size;
if ( mem->threadsafe != 0 )
portable_mutex_lock(&mem->mutex);
if ( origsize != 0 && (mem->M.fileptr == 0 || (mem->used + origsize) > mem->totalsize) )
{
//coin->TMPallocated += origsize;
memset(&mem->M,0,sizeof(mem->M));
sprintf(fname,"tmp/%s/%s.%d",dirname,name,mem->counter), OS_compatible_path(fname);
mem->counter++;
if ( mem->totalsize == 0 )
{
mem->totalsize = (1024 * 1024 * 16);
}
//if ( coin->R.RSPACE.size == 0 )
// coin->R.RSPACE.size = mem->size;
if ( mem->totalsize > origsize )
size = mem->totalsize;
else size = origsize;
fprintf(stderr,"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");
}
ptr = iguana_memalloc(mem,origsize,1);
if ( mem->threadsafe != 0 )
portable_mutex_unlock(&mem->mutex);
return(ptr);
#endif
}

259
crypto777/OS_portable.h

@ -0,0 +1,259 @@
/******************************************************************************
* Copyright © 2014-2015 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
#ifndef OS_PORTABLEH
#define OS_PORTABLEH
// 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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <fcntl.h>
#include <math.h>
#include <pthread.h>
#include <poll.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/mman.h>
#include "../includes/libgfshare.h"
#include "../includes/utlist.h"
#include "../includes/uthash.h"
#ifndef MAP_FILE
#define MAP_FILE 0
#endif
#define SATOSHIDEN ((uint64_t)100000000L)
#define dstr(x) ((double)(x) / SATOSHIDEN)
#define SMALLVAL 0.000000000000001
#define SETBIT(bits,bitoffset) (((uint8_t *)bits)[(bitoffset) >> 3] |= (1 << ((bitoffset) & 7)))
#define GETBIT(bits,bitoffset) (((uint8_t *)bits)[(bitoffset) >> 3] & (1 << ((bitoffset) & 7)))
#define CLEARBIT(bits,bitoffset) (((uint8_t *)bits)[(bitoffset) >> 3] &= ~(1 << ((bitoffset) & 7)))
#define portable_mutex_t pthread_mutex_t
#define portable_mutex_init(ptr) pthread_mutex_init(ptr,NULL)
#define portable_mutex_lock pthread_mutex_lock
#define portable_mutex_unlock pthread_mutex_unlock
#define OS_thread_create pthread_create
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;
portable_mutex_t mutex;
char name[64],initflag;
} queue_t;
struct OS_mappedptr
{
char fname[512];
void *fileptr,*pending;
long allocsize,changedsize;
int32_t rwflag,dirty,actually_allocated;
uint32_t closetime,opentime;
};
struct OS_memspace
{
portable_mutex_t mutex; long used,totalsize; struct OS_mappedptr M; char name[64]; void *ptr;
int32_t alignflag,counter,maxheight,openfiles,lastcounter,threadsafe,allocated:1,mapped:1,external:1;
#ifdef IGUANA_PEERALLOC
int32_t outofptrs,numptrs,availptrs;
void *ptrs[4096]; int32_t allocsizes[4096],maxsizes[4096];
#endif
};
struct tai { uint64_t x; double millis; };
struct taidate { int32_t year,month,day; };
struct taitime { struct taidate date; int32_t hour,minute,second; uint32_t offset; double millis; };
int32_t leapsecs_sub(struct tai *);
struct tai tai_now();
uint32_t tai2utc(struct tai t);
struct taidate taidate_frommjd(int32_t day,int32_t *pwday,int32_t *pyday);
struct taitime tai2time(struct tai t,int32_t *pwday,int32_t *pyday);
struct taidate tai2date(struct tai t);
int32_t taidate_str(char *s,struct taidate cd);
char *taitime_str(char *s,struct taitime ct);
int32_t taidate_mjd(struct taidate cd);
uint32_t tai2utime(struct tai t);
struct tai taitime2tai(struct taitime ct);
char *tai_str(char *str,struct tai t);
char *utc_str(char *str,struct tai t);
int32_t msync(void *addr,size_t len,int32_t flags);
#ifdef __PNACL
int32_t OS_nonportable_syncmap(struct OS_mappedptr *mp,long len);
void *OS_nonportable_tmpalloc(char *dirname,char *name,struct OS_memspace *mem,long origsize);
#elif _WIN32
char *OS_portable_path(char *str);
int32_t OS_nonportable_renamefile(char *fname,char *newfname);
int32_t OS_nonportable_launch(char *args[]);
void OS_nonportable_randombytes(unsigned char *x,long xlen);
int32_t OS_nonportable_init();
#endif
void OS_portable_init();
void OS_init();
double OS_portable_milliseconds();
void OS_portable_randombytes(unsigned char *x,long xlen);
int32_t OS_portable_truncate(char *fname,long filesize);
char *OS_portable_path(char *str);
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 is_DST(int32_t datenum);
int32_t extract_datenum(int32_t *yearp,int32_t *monthp,int32_t *dayp,int32_t datenum);
int32_t expand_datenum(char *date,int32_t datenum);
int32_t calc_datenum(int32_t year,int32_t month,int32_t day);
int32_t ecb_decrdate(int32_t *yearp,int32_t *monthp,int32_t *dayp,char *date,int32_t datenum);
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(int32_t *secondsp,time_t timestamp);
double OS_milliseconds();
void OS_randombytes(unsigned char *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);
uint64_t OS_filesize(char *fname);
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_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_filealloc(struct OS_mappedptr *M,char *fname,struct OS_memspace *mem,long size);
void *OS_mapfile(char *fname,long *filesizep,int32_t enablewrite);
void *OS_loadfile(char *fname,char **bufp,int64_t *lenp,int64_t *allocsizep);
void *OS_filestr(int64_t *allocsizep,char *fname);
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 *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);
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);
void iguana_memreset(struct OS_memspace *mem);
void iguana_mempurge(struct OS_memspace *mem);
void *iguana_meminit(struct OS_memspace *mem,char *name,void *ptr,int64_t totalsize,int32_t threadsafe);
void *iguana_memalloc(struct OS_memspace *mem,long size,int32_t clearflag);
int64_t iguana_memfree(struct OS_memspace *mem,void *ptr,int32_t size);
// generic functions
int32_t unhex(char c);
void touppercase(char *str);
uint32_t is_ipaddr(char *str);
void iguana_bitmap(char *space,int32_t max,char *name);
double _pairaved(double valA,double valB);
int32_t unstringbits(char *buf,uint64_t bits);
uint64_t stringbits(char *str);
int32_t is_decimalstr(char *str);
void tolowercase(char *str);
char *clonestr(char *str);
long _stripwhite(char *buf,int accept);
int32_t is_DST(int32_t datenum);
int32_t extract_datenum(int32_t *yearp,int32_t *monthp,int32_t *dayp,int32_t datenum);
int32_t expand_datenum(char *date,int32_t datenum);
int32_t calc_datenum(int32_t year,int32_t month,int32_t day);
int32_t ecb_decrdate(int32_t *yearp,int32_t *monthp,int32_t *dayp,char *date,int32_t datenum);
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(int32_t *secondsp,time_t timestamp);
int32_t btc_coinaddr(char *coinaddr,uint8_t addrtype,char *pubkeystr);
void reverse_hexstr(char *str);
int32_t init_hexbytes_noT(char *hexbytes,uint8_t *message,long len);
uint64_t RS_decode(char *rs);
int32_t RS_encode(char *rsaddr,uint64_t id);
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);
void calc_md4(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);
void calc_sha224(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_sha384(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_sha512(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_sha224(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_rmd160(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_rmd128(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_rmd256(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_rmd320(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_tiger(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_whirlpool(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
char *hmac_sha1_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_md2_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_md4_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_md5_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_sha224_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_sha256_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_sha384_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_sha512_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_rmd128_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_rmd160_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_rmd256_str(char *dest,char *key,int32_t key_size,char *message);
char *hmac_rmd320_str(char *dest,char *key,int32_t key_size,char *message);
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 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);
void calc_crc32str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_NXTaddr(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
void calc_curve25519_str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len);
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);
#endif

529
crypto777/OS_time.c

@ -0,0 +1,529 @@
/******************************************************************************
* Copyright © 2014-2015 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. *
* *
******************************************************************************/
// DJB's libtai was modified for the tai code
#include "OS_portable.h"
#define TAI_PACK 8
//#define UTC_ADJUST -36
#define tai_approx(t) ((double) ((t)->x))
#define tai_less(t,u) ((t)->x < (u)->x)
int32_t leapsecs_sub(struct tai *);
static struct tai First_TAI;
uint32_t First_utc;
int32_t UTC_ADJUST;
struct taidate taidate_frommjd(int32_t day,int32_t *pwday,int32_t *pyday)
{
int32_t year,month,yday; struct taidate cd;
year = day / 146097L;
day %= 146097L;
day += 678881L;
while (day >= 146097L) { day -= 146097L; ++year; }
// year * 146097 + day - 678881 is MJD; 0 <= day < 146097
// 2000-03-01, MJD 51604, is year 5, day 0
if ( pwday != 0 )
*pwday = (day + 3) % 7;
year *= 4;
if (day == 146096L) { year += 3; day = 36524L; }
else { year += day / 36524L; day %= 36524L; }
year *= 25;
year += day / 1461;
day %= 1461;
year *= 4;
yday = (day < 306);
if (day == 1460) { year += 3; day = 365; }
else { year += day / 365; day %= 365; }
yday += day;
day *= 10;
month = (day + 5) / 306;
day = (day + 5) % 306;
day /= 10;
if (month >= 10) { yday -= 306; ++year; month -= 10; }
else { yday += 59; month += 2; }
cd.year = year;
cd.month = month + 1;
cd.day = day + 1;
if ( pyday != 0 )
*pyday = yday;
return(cd);
}
struct taitime tai2time(struct tai t,int32_t *pwday,int32_t *pyday)
{
uint64_t u,tmp; int32_t leap,s; double diff; struct taitime ct;
leap = leapsecs_sub(&t);
u = t.x;
u += (58486 + 60); // was off by a minute
s = u % 86400ULL;
memset(&ct,0,sizeof(ct));
ct.second = (s % 60) + leap; s /= 60;
ct.minute = s % 60; s /= 60;
ct.hour = s;
u /= 86400ULL;
ct.date = taidate_frommjd((int32_t)(u - 53375995543064ULL),pwday,pyday);
ct.offset = 0;
if ( First_TAI.x != 0 && t.x > First_TAI.x )
{
tmp = (t.x - First_TAI.x);
diff = (t.millis - First_TAI.millis);
if ( diff < tmp*1000 )
tmp = 0, printf("TAI diff %f vs tmp.%lld\n",diff,(long long)tmp);
else tmp = diff * 1000000000.;
//printf("tmp.%llu \n",(long long)tmp);
tmp %= (uint64_t)1000000000000;
ct.millis = ((double)tmp / 1000000000.);
}
//printf("TAI millis: %lld -1st.%lld %f - %f -> %f | %f\n",(long long)t.x,(long long)First_TAI.x,t.millis,First_TAI.millis,t.millis-First_TAI.millis,ct.millis);
return(ct);
}
struct taidate tai2date(struct tai t)
{
struct taitime ct = tai2time(t,0,0);
return(ct.date);
}
/*int32_t taitime_scan(char *s,struct taitime *ct)
{
int32_t z,c,sign; char *t = s;
t += taidate_scan(t,&ct->date);
while ((*t == ' ') || (*t == '\t') || (*t == 'T')) ++t;
z = 0; while ((c = (uint8_t) (*t - '0')) <= 9) { z = z * 10 + c; ++t; }
ct->hour = z;
if (*t++ != ':') return 0;
z = 0; while ((c = (uint8_t) (*t - '0')) <= 9) { z = z * 10 + c; ++t; }
ct->minute = z;
if (*t != ':')
ct->second = 0;
else
{
++t;
z = 0; while ((c = (uint8_t) (*t - '0')) <= 9) { z = z * 10 + c; ++t; }
ct->second = z;
}
while ((*t == ' ') || (*t == '\t')) ++t;
if (*t == '+') sign = 1; else if (*t == '-') sign = -1; else return 0;
++t;
c = (uint8_t) (*t++ - '0'); if (c > 9) return 0; z = c;
c = (uint8_t) (*t++ - '0'); if (c > 9) return 0; z = z * 10 + c;
c = (uint8_t) (*t++ - '0'); if (c > 9) return 0; z = z * 6 + c;
c = (uint8_t) (*t++ - '0'); if (c > 9) return 0; z = z * 10 + c;
ct->offset = z * sign;
printf("t.%p s.%p\n",t,s);
return((int32_t)((long)t - (long)s));
}*/
int32_t taidate_str(char *s,struct taidate cd)
{
int32_t x,len,i = 0;
x = cd.year; if (x < 0) x = -x; do { ++i; x /= 10; } while(x);
len = (cd.year < 0) + i + 6;
if ( s != 0 )
{
x = cd.year;
if (x < 0) { x = -x; *s++ = '-'; }
s += i; do { *--s = '0' + (x % 10); x /= 10; } while(x); s += i;
x = cd.month;
s[0] = '-'; s[2] = '0' + (x % 10); x /= 10; s[1] = '0' + (x % 10);
x = cd.day;
s[3] = '-'; s[5] = '0' + (x % 10); x /= 10; s[4] = '0' + (x % 10);
s[len] = 0;
}
return(len);
}
char *taitime_str(char *s,struct taitime ct)
{
int32_t result,x,len;
result = taidate_str(s,ct.date);
len = result + 15;
if ( s != 0 )
{
s += result;
x = ct.hour;
s[0] = ' ';
s[2] = '0' + (x % 10); x /= 10;
s[1] = '0' + (x % 10);
s += 3;
x = ct.minute;
s[0] = ':';
s[2] = '0' + (x % 10); x /= 10;
s[1] = '0' + (x % 10);
s += 3;
x = ct.second;
s[0] = ':';
s[2] = '0' + (x % 10); x /= 10;
s[1] = '0' + (x % 10);
s += 3;
s[0] = ' ';
x = ct.offset;
if (x < 0) { s[1] = '-'; x = -x; } else s[1] = '+';
s[5] = '0' + (x % 10); x /= 10;
s[4] = '0' + (x % 6); x /= 6;
s[3] = '0' + (x % 10); x /= 10;
s[2] = '0' + (x % 10);
s[len] = 0;
}
return(s);
}
void tai_pack(char *s,struct tai *t)
{
uint64_t x;
x = t->x;
s[7] = x & 255; x >>= 8;
s[6] = x & 255; x >>= 8;
s[5] = x & 255; x >>= 8;
s[4] = x & 255; x >>= 8;
s[3] = x & 255; x >>= 8;
s[2] = x & 255; x >>= 8;
s[1] = x & 255; x >>= 8;
s[0] = x;
}
void tai_unpack(char *s,struct tai *t)
{
uint64_t x;
x = (uint8_t) s[0];
x <<= 8; x += (uint8_t) s[1];
x <<= 8; x += (uint8_t) s[2];
x <<= 8; x += (uint8_t) s[3];
x <<= 8; x += (uint8_t) s[4];
x <<= 8; x += (uint8_t) s[5];
x <<= 8; x += (uint8_t) s[6];
x <<= 8; x += (uint8_t) s[7];
t->x = x;
}
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" };
struct tai leaptais[sizeof(leapseconds)/sizeof(*leapseconds)];
char *dayname[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" } ;
static int32_t times365[4] = { 0, 365, 730, 1095 } ;
static int32_t times36524[4] = { 0, 36524, 73048, 109572 } ;
static int32_t montab[12] = { 0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337 } ;
// month length after february is (306 * m + 5) / 10
int32_t taidate_mjd(struct taidate cd)
{
int32_t y,m,d;
d = cd.day - 678882L;
m = cd.month - 1;
y = cd.year;
d += 146097L * (y / 400);
y %= 400;
if (m >= 2) m -= 2; else { m += 10; --y; }
y += (m / 12);
m %= 12;
if (m < 0) { m += 12; --y; }
d += montab[m];
d += 146097L * (y / 400);
y %= 400;
if (y < 0) { y += 400; d -= 146097L; }
d += times365[y & 3];
y >>= 2;
d += 1461L * (y % 25);
y /= 25;
d += times36524[y & 3];
return d;
}
uint32_t tai2utc(struct tai t) { t.x -= 4611686018427387914ULL; return((uint32_t)t.x); }
uint32_t tai2utime(struct tai t)
{
uint64_t mjd; struct taitime ct = tai2time(t,0,0);
mjd = taidate_mjd(ct.date);
return((uint32_t)(mjd * 24*3600 + ct.hour*3600 + ct.minute*60 + ct.second));
}
struct tai tai_now()
{
struct tai t;
t.x = 4611686018427387914ULL + (uint64_t)time(NULL);
t.millis = OS_milliseconds();
if ( First_TAI.x == 0 )
{
First_TAI = t, First_utc = (uint32_t)time(NULL);
UTC_ADJUST = -36;
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);
}
struct tai leapsecs_add(struct tai t,int32_t hit)
{
int32_t i; uint64_t u;
u = t.x;
if ( t.x > leaptais[sizeof(leaptais)/sizeof(*leaptais)-1].x )
u += (sizeof(leaptais)/sizeof(*leaptais) - 1);
else
{
for (i=0; i<sizeof(leaptais)/sizeof(*leaptais); i++)
{
if ( u < leaptais[i].x ) break;
if ( !hit || (u > leaptais[i].x) ) ++u;
}
}
t.x = u;
return(t);
}
struct tai taitime2tai(struct taitime ct)
{
int32_t day,s; struct tai t;
day = taidate_mjd(ct.date);
s = ct.hour * 60 + ct.minute;
s = (s - ct.offset) * 60 + ct.second;
t.x = day * 86400ULL + 4611686014920671114ULL + (uint64_t)s;
t.millis = ct.millis;
return(leapsecs_add(t,ct.second == 60));
}
struct tai taidate_scan(char *s,int32_t numleaps)
{
int32_t z,c,sign = 1; char *t = s; struct taidate cd; struct tai st;
st.x = 0;
if (*t == '-') { ++t; sign = -1; }
else if ( *t == '+' )
t++;
z = 0; while ((c = (uint8_t) (*t - '0')) <= 9) { z = z * 10 + c; ++t; }
cd.year = z * sign;
if (*t++ != '-') return(st);
z = 0; while ((c = (uint8_t) (*t - '0')) <= 9) { z = z * 10 + c; ++t; }
cd.month = z;
if (*t++ != '-') return(st);
z = 0; while ((c = (uint8_t) (*t - '0')) <= 9) { z = z * 10 + c; ++t; }
cd.day = z;
//printf("year.%d month.%d day.%d numleaps.%d\n",cd.year,cd.month,cd.day,numleaps);
st.x = (taidate_mjd(cd) + 1) * 86400ULL + 4611686014920671114ULL + numleaps;
return(st);
}
int32_t leapsecs_sub(struct tai *lt)
{
char out[101],x[TAI_PACK]; double packerr;
int32_t weekday,yearday,i,j,s; uint64_t u; struct tai t,t2; struct taitime ct2;
if ( leaptais[0].x == 0 )
{
for (i=0; i<sizeof(leapseconds)/sizeof(*leapseconds); i++)
{
t = taidate_scan(leapseconds[i],i);
if ( t.x == 0 )
printf("unable to parse.(%s)\n",leapseconds[i]);
else
{
//t = taitime2tai(ct);
leaptais[i] = t;
ct2 = tai2time(t,&weekday,&yearday);
tai_pack(x,&t);
tai_unpack(x,&t2);
tai_sub(&t2,&t2,&t);
packerr = tai_approx(&t2);
for (j=0; j<TAI_PACK; j++)
printf("%2.2x",(uint32_t)(uint8_t)x[j]);
if ( packerr != 0 )
printf(" packerr=%f",packerr);
taitime_str(out,ct2);
printf(" %03d %s %s",yearday,dayname[weekday],out);
printf("\n");
}
}
}
u = lt->x;
if ( u > leaptais[sizeof(leaptais)/sizeof(*leaptais)-1].x )
lt->x -= (sizeof(leaptais)/sizeof(*leaptais) - 1);
else
{
s = 0;
for (i=0; i<sizeof(leaptais)/sizeof(*leaptais); i++)
{
if ( u < leaptais[i].x )
break;
++s;
if ( u == leaptais[i].x )
{
lt->x = u - s;
return(1);
}
}
lt->x = u - s;
}
return(0);
}
char *tai_str(char *str,struct tai t)
{
struct taitime ct;
ct = tai2time(t,0,0);
sprintf(str,"%d-%02d-%02d %02d:%02d:%02d %03.3f",ct.date.year,ct.date.month,ct.date.day,ct.hour,ct.minute,ct.second,ct.millis);
return(str);
}
char *utc_str(char *str,struct tai t)
{
t.x += UTC_ADJUST;
return(tai_str(str,t));
}
#ifdef ENABLE_TEST
#include <unistd.h>
int main(int argc, const char * argv[])
{
int i; char str[111],str2[111],str3[111],str4[111]; struct taitime ct;
struct tai t,start = tai_now();
for (i=0; i<100; i++)
{
sleep(1);
t = tai_now();
taidate_str(str2,tai2date(t));
printf("(%s) time.%s date.%s %ld start.%ld %s %u %u\n",tai_str(str3,t),taitime_str(str,ct),str2,(long)tai2utime(t),(long)tai2utime(start),utime_str(str4,t),tai2utc(t),(uint32_t)time(NULL));
}
// insert code here...
printf("Hello, World!\n");
return 0;
}
#endif
int32_t conv_date(int32_t *secondsp,char *buf);
double OS_portable_milliseconds()
{
struct timeval tv; double millis;
gettimeofday(&tv,NULL);
millis = ((double)tv.tv_sec * 1000. + (double)tv.tv_usec / 1000.);
//printf("tv_sec.%ld usec.%d %f\n",tv.tv_sec,tv.tv_usec,millis);
return(millis);
}
uint32_t OS_conv_datenum(int32_t datenum,int32_t hour,int32_t minute,int32_t second) // datenum+H:M:S -> unix time
{
#ifdef __PNACL
return(0);
#else
struct tm t;
memset(&t,0,sizeof(t));
t.tm_year = (datenum / 10000) - 1900, t.tm_mon = ((datenum / 100) % 100) - 1, t.tm_mday = (datenum % 100);
t.tm_hour = hour, t.tm_min = minute, t.tm_sec = second;
return((uint32_t)timegm(&t));
#endif
}
double OS_milliseconds()
{
return(OS_portable_milliseconds());
}
int32_t OS_conv_unixtime(int32_t *secondsp,time_t timestamp) // gmtime -> datenum + number of seconds
{
struct tm t; int32_t datenum; uint32_t checktime; char buf[64];
t = *gmtime(&timestamp);
strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ",&t); //printf("%s\n",buf);
datenum = conv_date(secondsp,buf);
if ( (checktime= OS_conv_datenum(datenum,*secondsp/3600,(*secondsp%3600)/60,*secondsp%60)) != timestamp )
{
printf("error: timestamp.%u -> (%d + %d) -> %u\n",(uint32_t)timestamp,datenum,*secondsp,checktime);
return(-1);
}
return(datenum);
}
int32_t is_DST(int32_t datenum)
{
int32_t year,month,day;
year = datenum / 10000, month = (datenum / 100) % 100, day = (datenum % 100);
if ( month >= 4 && month <= 9 )
return(1);
else if ( month == 3 && day >= 29 )
return(1);
else if ( month == 10 && day < 25 )
return(1);
return(0);
}
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;
year = atoi(tmpdate), month = atoi(tmpdate+5), day = atoi(tmpdate+8);
*secondsp = 0;
if ( (len= (int32_t)strlen(date)) <= 10 )
hour = min = sec = 0;
if ( len >= 18 )
{
tmpdate[11 + 2] = 0, tmpdate[14 + 2] = 0, tmpdate[17 + 2] = 0;
hour = atoi(tmpdate+11), min = atoi(tmpdate + 14), sec = atoi(tmpdate+17);
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);
}
sprintf(origdate,"%d-%02d-%02d",year,month,day); //2015-07-25T22:34:31Z
if ( strcmp(tmpdate,origdate) != 0 )
{
printf("conv_date date conversion error (%s) -> (%s)\n",origdate,date);
return(-1);
}
return((year * 10000) + (month * 100) + day);
}
int32_t extract_datenum(int32_t *yearp,int32_t *monthp,int32_t *dayp,int32_t datenum)
{
*yearp = datenum / 10000, *monthp = (datenum / 100) % 100, *dayp = (datenum % 100);
if ( *yearp >= 2000 && *yearp <= 2038 && *monthp >= 1 && *monthp <= 12 && *dayp >= 1 && *dayp <= 31 )
return(datenum);
else return(-1);
}
int32_t expand_datenum(char *date,int32_t datenum) { int32_t year,month,day; date[0] = 0; if ( extract_datenum(&year,&month,&day,datenum) != datenum) return(-1); sprintf(date,"%d-%02d-%02d",year,month,day); return(0); }
int32_t calc_datenum(int32_t year,int32_t month,int32_t day) { return((year * 10000) + (month * 100) + day); }
int32_t ecb_decrdate(int32_t *yearp,int32_t *monthp,int32_t *dayp,char *date,int32_t datenum)
{
static int lastday[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int32_t year,month,day;
year = datenum / 10000, month = (datenum / 100) % 100, day = (datenum % 100);
//printf("%d -> %d %d %d\n",datenum,year,month,day);
if ( --day <= 0 )
{
if ( --month <= 0 )
{
if ( --year < 2000 )
{
printf("reached epoch start\n");
return(-1);
}
month = 12;
}
day = lastday[month];
if ( month == 2 && (year % 4) == 0 )
day++;
}
sprintf(date,"%d-%02d-%02d",year,month,day);
//printf("%d -> %d %d %d (%s)\n",datenum,year,month,day,date);
*yearp = year, *monthp = month, *dayp = day;
return((year * 10000) + (month * 100) + day);
}

951
crypto777/SaM.c

@ -0,0 +1,951 @@
/******************************************************************************
* Copyright © 2014-2015 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. *
* *
******************************************************************************/
// based on SaM code by Come-from-Beyond
#ifdef DEFINES_ONLY
#ifndef crypto777_SaM_h
#define crypto777_SaM_h
#include <stdio.h>
#include <memory.h>
#include <time.h>
#define TRIT signed char
#define TRIT_FALSE 1
#define TRIT_UNKNOWN 0
#define TRIT_TRUE -1
#define SAM_HASH_SIZE 243
#define SAM_STATE_SIZE (SAM_HASH_SIZE * 3)
#define SAM_NUMBER_OF_ROUNDS 9
#define SAM_DELTA 254
#define SAMHIT_LIMIT ((uint64_t)1594323 * 4782969) //7625597484987LL // 3 ** 27
#define MAX_CRYPTO777_HIT (((uint64_t)1 << 62) / 1000)
//#include "bits777.c"
//#include "utils777.c"
#include <stdlib.h>
#include "../includes/curve25519.h"
#define MAX_INPUT_SIZE ((int32_t)(65536 - sizeof(bits256) - 2*sizeof(uint32_t)))
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);
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);
uint64_t SaM(bits384 *sigp,uint8_t *input,int32_t inputSize,uint8_t *input2,int32_t inputSize2);
uint32_t SaM_nonce(void *data,int32_t datalen,int32_t leverage,int32_t maxmillis,uint32_t nonce);
//uint64_t SaMnonce(bits384 *sigp,uint32_t *noncep,uint8_t *buf,int32_t len,uint64_t threshold,uint32_t rseed,int32_t maxmillis);
#endif
#else
#ifndef crypto777_SaM_c
#define crypto777_SaM_c
#ifndef crypto777_SaM_h
#define DEFINES_ONLY
#include "SaM.c"
#undef DEFINES_ONLY
#endif
static int32_t SAM_INDICES[SAM_STATE_SIZE];
void SaM_PrepareIndices()
{
int32_t i,nextIndex,currentIndex = 0;
for (i=0; i<SAM_STATE_SIZE; i++)
{
nextIndex = (currentIndex + SAM_DELTA) % SAM_STATE_SIZE;
SAM_INDICES[i] = nextIndex;
currentIndex = nextIndex;
}
}
TRIT SaM_Bias(const TRIT a, const TRIT b) { return a == 0 ? 0 : (a == -b ? a : -a); }
TRIT SaM_Sum(const TRIT a, const TRIT b) { return a == b ? -a : (a + b); }
void SaM_SplitAndMerge(struct SaM_info *state)
{
static const TRIT SAMSUM[3][3] = { { 1, -1, 0, }, { -1, 0, 1, }, { 0, 1, -1, } };
static const TRIT SAMBIAS[3][3] = { { 1, 1, -1, }, { 0, 0, 0, }, { 1, -1, -1, } };
struct SaM_info leftPart,rightPart;
int32_t i,nextIndex,round,currentIndex = 0;
for (round=0; round<SAM_NUMBER_OF_ROUNDS; round++)
{
for (i=0; i<SAM_STATE_SIZE; i++)
{
nextIndex = SAM_INDICES[i];
//leftPart.trits[i] = SaM_Bias(state->trits[currentIndex],state->trits[nextIndex]);
//rightPart.trits[i] = SaM_Bias(state->trits[nextIndex],state->trits[currentIndex]);
leftPart.trits[i] = SAMBIAS[state->trits[currentIndex]+1][1+state->trits[nextIndex]];
rightPart.trits[i] = SAMBIAS[state->trits[nextIndex]+1][1+state->trits[currentIndex]];
currentIndex = nextIndex;
}
for (i=0; i<SAM_STATE_SIZE; i++)
{
nextIndex = SAM_INDICES[i];
//state->trits[i] = SaM_Sum(leftPart.trits[currentIndex],rightPart.trits[nextIndex]);
state->trits[i] = SAMSUM[leftPart.trits[currentIndex]+1][1+rightPart.trits[nextIndex]];
currentIndex = nextIndex;
}
}
}
void SaM_Initialize(struct SaM_info *state)
{
int32_t i;
for (i=SAM_HASH_SIZE; i<SAM_STATE_SIZE; i++)
state->trits[i] = (i & 1) ? TRIT_FALSE : TRIT_TRUE;
}
void SaM_Squeeze(struct SaM_info *state,TRIT *output)
{
memcpy(output,state->trits,SAM_HASH_SIZE * sizeof(TRIT));
SaM_SplitAndMerge(state);
}
void _SaM_Absorb(struct SaM_info *state,const TRIT *input,const int32_t inputSize)
{
int32_t size,i,remainder = inputSize;
do
{
size = remainder >= SAM_HASH_SIZE ? SAM_HASH_SIZE : remainder;
memcpy(state->trits,&input[inputSize - remainder],size);
remainder -= SAM_HASH_SIZE;
if ( size < SAM_HASH_SIZE )
for (i=size; i<SAM_HASH_SIZE; i++)
state->trits[i] = (i & 1) ? TRIT_FALSE : TRIT_TRUE;
SaM_SplitAndMerge(state);
} while ( remainder > 0 );
}
int32_t SaM_Absorb(struct SaM_info *state,const uint8_t *input,uint32_t inputSize,const uint8_t *input2,uint32_t inputSize2)
{
//TRIT output[(MAX_INPUT_SIZE + sizeof(struct SaMhdr)) << 3];
TRIT *trits,tritbuf[4096];
int32_t i,size,n = 0;
/*if ( inputSize + inputSize2 > sizeof(output) )
{
printf("SaM overflow (%d + %d) > %ld\n",inputSize,inputSize2,sizeof(output));
if ( inputSize > MAX_INPUT_SIZE )
inputSize = MAX_INPUT_SIZE;
inputSize2 = 0;
}*/
size = (inputSize + inputSize2) << 3;
trits = (size < sizeof(tritbuf)) ? tritbuf : malloc(size);
if ( input != 0 && inputSize != 0 )
{
for (i=0; i<(inputSize << 3); i++)
trits[n++] = ((input[i >> 3] & (1 << (i & 7))) != 0);
}
if ( input2 != 0 && inputSize2 != 0 )
{
for (i=0; i<(inputSize2 << 3); i++)
trits[n++] = ((input2[i >> 3] & (1 << (i & 7))) != 0);
}
_SaM_Absorb(state,trits,n);
if ( trits != tritbuf )
free(trits);
return(n);
}
static TRIT InputA[] = { 0 }; // zero len
static TRIT OutputA[] = { 1, -1, 1, 1, -1, -1, 0, -1, 0, 0, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0, 0, 0, 1, 1, -1, -1, 0, 0, 1, -1, -1, 0, 0, -1, 1, -1, 0, 0, -1, -1, -1, -1, 0, 0, 0, -1, 1, 0, 1, 0, -1, -1, -1, -1, 0, 1, -1, 1, -1, 0, 1, 1, 0, 0, -1, 0, 1, 1, -1, 1, 0, 0, 0, 1, 0, -1, 1, 1, 0, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 0, 1, -1, 1, -1, 0, 0, 1, 1, 1, 1, -1, 1, 1, -1, 0, 0, 1, 1, 0, 0, -1, 1, 1, -1, 0, 0, -1, 0, 0, 1, 0, 0, 0, -1, 1, -1, 0, 1, -1, 0, -1, 1, 1, 1, -1, 0, 1, 1, -1, -1, 0, 0, 1, -1, -1, -1, 0, -1, -1, 1, 1, 0, 1, 0, 1, -1, 1, -1, -1, 0, 0, -1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, -1, 1, -1, 0, 0, 1, 0, -1, -1, -1, 1, -1, 1, -1, -1, 1, 0, 1, -1, 1, -1, 1, -1, 1, 0, 1, 0, 1, -1, -1, -1, -1, 1, 0, 0, -1, -1, 1, 0, 1, 1, -1, 1, -1, -1, -1, 0, 0, -1, 0, 1, 1, 1, 0, 1, 1, -1, 1, 1, 0, 1, 1, 1, 0, -1, 0, 0, -1, -1, -1 };
static TRIT InputB[] = { 0 };
static TRIT OutputB[] = { -1, -1, -1, 1, 0, 0, 1, 1, 0, 1, 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, 1, 0, -1, 1, 0, 1, 0, 1, -1, 0, -1, 0, 0, -1, 1, -1, -1, 0, 0, 1, -1, -1, 0, 0, -1, 1, 1, 0, 1, 0, 0, 1, -1, 1, 0, -1, -1, 1, -1, 0, -1, 1, -1, 0, 0, 0, 1, -1, 0, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, 1, 0, 1, -1, -1, -1, 0, 1, 0, 0, -1, 1, 1, 0, 0, -1, 1, 1, 0, -1, -1, 0, 0, 0, -1, 1, 0, -1, 0, -1, 0, -1, 0, -1, 0, 1, 0, 1, 0, -1, 1, 0, -1, 1, 1, -1, 1, 0, 1, -1, -1, 1, 1, 0, -1, 0, -1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, -1, -1, 1, 0, 0, 0, 0, -1, -1, 1, 1, 1, -1, 1, 0, -1, 1, 0, 1, 0, 0, -1, -1, 1, 1, 0, 0, 1, 0, 0, 0, 0, -1, 1, 0, 0, 1, 1, 0, -1, 1, -1, 1, 0, -1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, -1, 1, -1, 1, 1, 1, -1, 0, 1, 0, -1, 1, 0, 1, 1, 0, -1, 1, 1, -1, 0, -1, 1, 1, 0, -1, -1, -1, -1, 1, 0, 0, -1, -1, -1, 0, 1 };
static TRIT InputC[] = { 1 };
static TRIT OutputC[] = { 1, -1, 1, 1, -1, -1, 0, -1, 0, 0, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0, 0, 0, 1, 1, -1, -1, 0, 0, 1, -1, -1, 0, 0, -1, 1, -1, 0, 0, -1, -1, -1, -1, 0, 0, 0, -1, 1, 0, 1, 0, -1, -1, -1, -1, 0, 1, -1, 1, -1, 0, 1, 1, 0, 0, -1, 0, 1, 1, -1, 1, 0, 0, 0, 1, 0, -1, 1, 1, 0, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 0, 1, -1, 1, -1, 0, 0, 1, 1, 1, 1, -1, 1, 1, -1, 0, 0, 1, 1, 0, 0, -1, 1, 1, -1, 0, 0, -1, 0, 0, 1, 0, 0, 0, -1, 1, -1, 0, 1, -1, 0, -1, 1, 1, 1, -1, 0, 1, 1, -1, -1, 0, 0, 1, -1, -1, -1, 0, -1, -1, 1, 1, 0, 1, 0, 1, -1, 1, -1, -1, 0, 0, -1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, -1, 1, -1, 0, 0, 1, 0, -1, -1, -1, 1, -1, 1, -1, -1, 1, 0, 1, -1, 1, -1, 1, -1, 1, 0, 1, 0, 1, -1, -1, -1, -1, 1, 0, 0, -1, -1, 1, 0, 1, 1, -1, 1, -1, -1, -1, 0, 0, -1, 0, 1, 1, 1, 0, 1, 1, -1, 1, 1, 0, 1, 1, 1, 0, -1, 0, 0, -1, -1, -1 };
static TRIT InputD[] = { -1 };
static TRIT OutputD[] = { -1, 0, 0, 1, 1, 0, -1, 1, 1, 0, 1, 0, -1, 1, -1, 0, 0, 1, 0, -1, 0, -1, 1, 1, 1, 1, -1, 1, -1, 1, -1, 0, 0, 0, -1, -1, 1, 1, -1, 1, -1, 0, -1, 1, -1, 0, 0, -1, 0, 0, 0, -1, -1, 0, -1, 1, -1, 1, 1, 0, -1, 1, -1, 0, 0, 1, -1, 1, -1, 0, 0, 1, 1, -1, -1, -1, -1, 1, 0, 0, -1, 0, 0, -1, 0, 0, 1, -1, -1, -1, -1, 1, 1, 0, 0, -1, 1, -1, 1, 0, 0, -1, 1, -1, 0, 1, 1, -1, 1, -1, 0, -1, -1, 0, 0, 0, -1, 0, 0, -1, 1, -1, 0, -1, 1, -1, 1, 1, -1, -1, 0, 0, 0, -1, 1, -1, 1, -1, 1, 1, 1, 1, -1, 0, -1, 0, 1, 0, 0, -1, 1, -1, 0, 1, 0, 1, 1, -1, 0, 1, 1, 0, 0, -1, -1, -1, -1, 0, 1, 0, -1, -1, 0, 0, 1, 1, 1, 0, 0, -1, 1, -1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, -1, -1, 0, -1, -1, 0, -1, -1, 1, 0, 0, -1, -1, 1, 0, 0, 0, 1, 1, 0, -1, 1, -1, -1, 1, -1, -1, 1, 1, 0, 1, 0, 0, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 0, 0, -1, -1, 1, 1 };
static TRIT InputE[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
static TRIT OutputE[] = { 0, 1, 0, 1, -1, -1, 1, -1, -1, 0, 0, 1, 1, -1, -1, -1, 0, 1, 0, 0, -1, -1, 1, 1, 1, -1, 0, -1, -1, -1, -1, -1, 1, -1, -1, -1, 0, 0, 1, 1, 0, 1, -1, -1, 0, -1, -1, 1, 1, 1, -1, 1, 1, 0, -1, 0, 1, -1, 1, -1, 1, 1, -1, 1, 0, -1, -1, -1, 0, 0, 1, 1, 0, -1, 0, 0, -1, 0, 0, 1, 1, -1, 0, 1, -1, -1, 1, -1, 1, -1, 0, 1, -1, 1, 0, 1, -1, -1, -1, 0, 1, -1, 0, 1, -1, 1, 0, -1, 1, -1, 1, 0, -1, -1, 1, 0, 1, 0, 0, 1, 1, 1, -1, 1, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, 1, 0, 0, 1, 0, -1, -1, 0, 0, -1, -1, 1, -1, 0, -1, 1, -1, 0, 1, -1, 0, 1, 1, -1, 1, -1, 1, -1, 0, 0, 0, -1, 0, -1, 1, -1, 1, 1, 1, 1, 1, 0, -1, 0, -1, -1, 0, 0, -1, -1, 1, -1, -1, -1, 1, 0, 0, 0, 1, 0, 1, 0, 1, -1, 0, -1, -1, 1, -1, -1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, -1, -1, -1, -1, 1, 0, -1, 0, 0 };
bits384 SaM_emit(struct SaM_info *state)
{
// i.12 531441 81bf1 0.68% numbits.19 mask.7ffff -> bias -0.0005870312
TRIT *ptr;
uint64_t bits64;
uint32_t i,j,rawbits,bits19[20],mask = 0x7ffff;
SaM_Squeeze(state,state->hash);
ptr = state->hash;
for (i=0; i<SAM_HASH_SIZE/12; i++)
{
for (j=rawbits=0; j<12; j++)
rawbits = (rawbits * 3 + *ptr++ + 1);
bits19[i] = ((((uint64_t)rawbits<<19)/531441) & mask); // 3^12 == 531441 //bits19[i] = (rawbits & mask);
//printf("%05x ",bits19[i]);
}
for (i*=12,rawbits=0; i<SAM_HASH_SIZE; i++) // 3 trits -> 27
rawbits = (rawbits * 3 + *ptr++ + 1);
rawbits = (((rawbits<<4)/27) & 0xf);
//printf("%x -> Sam_emit\n",rawbits);
for (bits64=i=0; i<20; i++)
{
memcpy(&state->bits.bytes[i*sizeof(uint16_t)],&bits19[i],sizeof(uint16_t));
bits64 = (bits64 << 3) | ((bits19[i] >> 16) & 7);
}
bits64 = (bits64 << 4) | (rawbits & 0xf);
memcpy(&state->bits.bytes[40],&bits64,sizeof(uint64_t));
return(state->bits);
}
int32_t _SaM_test(char *msg,TRIT *testvector,int32_t n,TRIT *checkvals)
{
struct SaM_info state; int32_t i,errs;
SaM_Initialize(&state);
_SaM_Absorb(&state,testvector,n);
SaM_emit(&state);
for (i=errs=0; i<243; i++)
{
if ( state.hash[i] != checkvals[i] )
errs++;
}
if ( errs != 0 )
{
for (i=0; i<243; i++)
printf("%2d, ",state.hash[i]);
printf("\nSaM_test.%s errs.%d vs output\n",msg,errs);
}
return(errs);
}
int32_t bitweight(uint64_t x)
{
int i,wt = 0;
for (i=0; i<64; i++)
if ( (1LL << i) & x )
wt++;
return(wt);
}
#define SETBIT(bits,bitoffset) (((uint8_t *)bits)[(bitoffset) >> 3] |= (1 << ((bitoffset) & 7)))
#define GETBIT(bits,bitoffset) (((uint8_t *)bits)[(bitoffset) >> 3] & (1 << ((bitoffset) & 7)))
#define CLEARBIT(bits,bitoffset) (((uint8_t *)bits)[(bitoffset) >> 3] &= ~(1 << ((bitoffset) & 7)))
int32_t SaM_test()
{
int32_t i,j,wt,iter,totalset,totalclr,setcount[48*8],clrcount[48*8],histo[16]; bits256 seed;
struct SaM_info state;
uint8_t buf[4096*2],bits[2][10][48];
double startmilli = time(NULL) * 1000;
for (i=0; i<1000; i++)
{
_SaM_test("A",InputA,0,OutputA);
_SaM_test("B",InputB,sizeof(InputB),OutputB);
_SaM_test("C",InputC,sizeof(InputC),OutputC);
_SaM_test("D",InputD,sizeof(InputD),OutputD);
_SaM_test("E",InputE,sizeof(InputE),OutputE);
}
printf("per SaM %.3f\n",((time(NULL) * 1000) - startmilli) / (5 * i));
memset(seed.bytes,0,sizeof(seed));
memcpy(seed.bytes,(uint8_t *)"12345678901",11);
for (i=0; i<243*2; i++)
buf[i] = 0;
OS_randombytes(buf,sizeof(buf));
for (iter=0; iter<2; iter++)
{
memset(&state,0,sizeof(state));
SaM_Initialize(&state);
SaM_Absorb(&state,buf,243*2,0,0);
memset(setcount,0,sizeof(setcount));
memset(clrcount,0,sizeof(clrcount));
memset(histo,0,sizeof(histo));
for (i=0; i<5; i++)
{
if ( 0 && (i % 100) == 99 )
{
for (j=0; j<32; j++)
seed.bytes[j] = rand() >> 8;
SaM_Absorb(&state,seed.bytes,sizeof(seed),0,0);
}
memset(bits[iter][i],0,sizeof(bits[iter][i]));
SaM_emit(&state);
memcpy(bits[iter][i],state.bits.bytes,sizeof(bits[iter][i]));
for (j=0; j<48; j++)
{
histo[bits[iter][i][j] & 0xf]++;
histo[(bits[iter][i][j]>>4) & 0xf]++;
printf("%02x ",bits[iter][i][j]);
}
printf("\n");
for (j=0; j<48*8; j++)
{
if ( GETBIT(bits[iter][i],j) != 0 )
setcount[j]++;
else clrcount[j]++;
}
}
for (i=0; i<16; i++)
printf("%8d ",histo[i]);
printf("hex histogram\n");
seed.bytes[0] ^= 1;
buf[0] ^= 1;
}
for (i=0; i<5; i++)
{
for (j=wt=0; j<48; j++)
{
wt += bitweight(bits[0][i][j] ^ bits[1][i][j]);
printf("%02x",bits[0][i][j] ^ bits[1][i][j]);
}
printf(" i.%d diff.%d\n",i,wt);
}
//set.19090245 clr.19309755 -0.0057
//total set.19200072 clr.19199928 0.0000037500
// total set.19191713 clr.19208287 -0.0004316146
for (totalset=totalclr=j=0; j<48*8; j++)
{
totalset += setcount[j];
totalclr += clrcount[j];
printf("%.2f ",(double)(setcount[j]-clrcount[j])/i);
}
printf("total set.%d clr.%d %.10f\n",totalset,totalclr,(double)(totalset-totalclr)/(totalset+totalclr));
return(0);
}
bits384 SaM_encrypt(uint8_t *dest,uint8_t *src,int32_t len,bits384 password,uint32_t timestamp)
{
bits384 xorpad; int32_t i; struct SaM_info XORpad;
SaM_Initialize(&XORpad), SaM_Absorb(&XORpad,password.bytes,sizeof(password),(void *)&timestamp,sizeof(timestamp));
while ( len >= 0 )
{
SaM_emit(&XORpad);
for (i=0; i<sizeof(xorpad) && len>=0; i++,len--)
{
xorpad.bytes[i] = (XORpad.bits.bytes[i] ^ *src++);
if ( dest != 0 )
*dest++ = xorpad.bytes[i];
}
}
return(xorpad);
}
uint64_t SaM_hit(struct SaM_info *state)
{
int32_t i; uint64_t hit = 0;
for (i=0; i<27; i++)
hit = (hit * 3 + state->hash[i] + 1);
return(hit);
}
uint64_t SaM(bits384 *sigp,uint8_t *input,int32_t inputSize,uint8_t *input2,int32_t inputSize2)
{
int32_t verify_SaM(TRIT *newhash,uint8_t *buf,const int n);
struct SaM_info state;
SaM_Initialize(&state);
SaM_Absorb(&state,input,inputSize,input2,inputSize2);
//printf("len.%d: ",inputSize+inputSize2);
*sigp = SaM_emit(&state);
//if ( 0 && input2 == 0 && numrounds == SAM_MAGIC_NUMBER )
// verify_SaM(state.hash,(uint8_t *)input,inputSize);
return(SaM_hit(&state));
}
uint64_t SaM_threshold(int32_t leverage)
{
int32_t i;
uint64_t threshold,divisor = 1;
if ( leverage > 26 )
leverage = 26;
for (i=0; i<leverage; i++)
divisor *= 3;
threshold = (SAMHIT_LIMIT / divisor);
return(threshold);
}
#include <stdlib.h>
uint32_t SaM_nonce(void *data,int32_t datalen,int32_t leverage,int32_t maxmillis,uint32_t nonce)
{
double milliseconds();
uint64_t hit,threshold; bits384 sig; double endmilli;
if ( leverage != 0 )
{
threshold = SaM_threshold(leverage);
if ( maxmillis == 0 )
{
if ( (hit= SaM(&sig,data,datalen,(void *)&nonce,sizeof(nonce))) >= threshold )
{
printf("nonce failure hit.%llu >= threshold.%llu | leverage.%d nonce.%u\n",(long long)hit,(long long)threshold,leverage,nonce);
if ( (threshold - hit) > ((uint64_t)1L << 32) )
return(0xffffffff);
else return((uint32_t)(threshold - hit));
}
}
else
{
endmilli = (milliseconds() + maxmillis);
while ( milliseconds() < endmilli )
{
OS_randombytes((void *)&nonce,sizeof(nonce));
if ( (hit= SaM(&sig,data,datalen,(void *)&nonce,sizeof(nonce))) < threshold )
{
printf("-> nonce.%u leverage.%d | hit.%llu < threshold.%llu\n",nonce,leverage,(long long)hit,(long long)threshold);
SaM_nonce(data,datalen,leverage,0,nonce);
return(nonce);
}
}
}
}
return(0);
}
/*uint64_t SaMnonce(bits384 *sigp,uint32_t *noncep,uint8_t *buf,int32_t len,uint64_t threshold,uint32_t rseed,int32_t maxmillis)
{
uint64_t hit = SAMHIT_LIMIT;
double startmilli = 0;
if ( maxmillis == 0 )
{
hit = calc_SaM(sigp,buf,len,0,0);
if ( hit >= threshold )
{
printf("nonce failure hit.%llu >= threshold.%llu\n",(long long)hit,(long long)threshold);
return(threshold - hit);
}
else return(0);
}
else startmilli = milliseconds();
while ( hit >= threshold )
{
if ( rseed == 0 )
randombytes((uint8_t *)noncep,sizeof(*noncep));
else _randombytes((uint8_t *)noncep,sizeof(*noncep),rseed);
hit = calc_SaM(sigp,buf,len,0,0);
//printf("%llu %.2f%% (%s) len.%d numrounds.%lld threshold.%llu seed.%u\n",(long long)hit,100.*(double)hit/threshold,(char *)buf,len,(long long)numrounds,(long long)threshold,rseed);
if ( maxmillis != 0 && milliseconds() > (startmilli + maxmillis) )
return(0);
if ( rseed != 0 )
rseed = (uint32_t)(sigp->txid ^ hit);
}
//printf("%5.1f %14llu %7.2f%% numrounds.%lld threshold.%llu seed.%u\n",milliseconds()-startmilli,(long long)hit,100.*(double)hit/threshold,(long long)numrounds,(long long)threshold,rseed);
return(hit);
}*/
#ifdef include_vps
// from Come-from-Beyond
#define HASH_SIZE 32
#define DAILY 0
#define WEEKLY 1
#define MONTHLY 2
#define YEARLY 3
#define MAX_NUMBER_OF_POOLS 1000
#define MAX_NUMBER_OF_TOKENS 1000
#define MAX_NUMBER_OF_UNITS 1000000
#define MAX_NUMBER_OF_SUPERVISORS 1000000
#define MAX_TOKEN_LIFESPAN 36500
unsigned int numberOfPools = 0;
struct Pool {
signed long reserve;
unsigned long quorum, decisionThreshold;
} pools[MAX_NUMBER_OF_POOLS];
unsigned int numberOfTokens = 0;
struct Token {
BOOL enabled;
unsigned int pool;
unsigned long curSupply, maxSupply; // Defines max %% of total coin supply that can be locked
signed int fadeRate; // Per day in 1/1000th (zero - to keep value const; negative - for deflation; positive - for inflation)
unsigned int decreaseLimits[YEARLY + 1], increaseLimits[YEARLY + 1]; // In 1/1000th
unsigned long unitSize; // Locked amount
unsigned short minLockPeriod, maxLockPeriod; // In days
unsigned char minExtraLockPeriod, maxExtraLockPeriod; // In days
unsigned char redemptionGap; // In days
unsigned long day0Offset; // UNIX time
unsigned long prices[MAX_TOKEN_LIFESPAN]; // In main currency units
} tokens[MAX_NUMBER_OF_TOKENS];
unsigned int numberOfUnits = 0;
struct Unit {
unsigned long id;
unsigned int token;
unsigned long account;
signed int fadeRate;
unsigned long size;
unsigned long timestamp;
unsigned char lockPeriodHash[HASH_SIZE];
unsigned short minLockPeriod, maxLockPeriod;
unsigned char extraLockPeriod;
unsigned char redemptionGap;
} units[MAX_NUMBER_OF_UNITS];
unsigned int numberOfSupervisors = 0;
struct Supervisor {
unsigned long id;
signed long rating;
unsigned int activity;
} supervisors[MAX_NUMBER_OF_SUPERVISORS];
struct Vote {
unsigned long supervisorId;
unsigned long price;
unsigned long tolerance;
unsigned long weight;
unsigned long bet;
};
unsigned char random() {
return 42; // TODO: Replace with a better RNG
}
void hash(unsigned char* data, unsigned int dataSize, unsigned char* hash) {
// TODO: Invoke SHA-256
}
unsigned int addPool(unsigned long quorum, unsigned long decisionThreshold) {
// Returns the index of the new pool
if (numberOfPools >= MAX_NUMBER_OF_POOLS) {
// TODO: Throw exception
}
pools[numberOfPools].reserve = 0;
pools[numberOfPools].quorum = quorum;
pools[numberOfPools].decisionThreshold = decisionThreshold;
return numberOfPools++;
}
unsigned int addToken(unsigned int pool,
unsigned long maxSupply,
signed int fadeRate,
unsigned int* decreaseLimits, unsigned int* increaseLimits,
unsigned long unitSize,
unsigned short minLockPeriod, unsigned short maxLockPeriod,
unsigned char minExtraLockPeriod, unsigned char maxExtraLockPeriod,
unsigned char redemptionGap,
unsigned long day0Offset,
unsigned long initialPrice) {
// Returns the index of the new token
if (numberOfTokens >= MAX_NUMBER_OF_TOKENS) {
// TODO: Throw exception
}
if (pool >= numberOfPools) {
// TODO: Throw exception
}
if (minLockPeriod > maxLockPeriod || minExtraLockPeriod > maxExtraLockPeriod) {
// TODO: Throw exception
}
tokens[numberOfTokens].enabled = TRUE;
tokens[numberOfTokens].pool = pool;
tokens[numberOfTokens].curSupply = 0;
tokens[numberOfTokens].maxSupply = maxSupply;
tokens[numberOfTokens].fadeRate = fadeRate;
memcpy(tokens[numberOfTokens].decreaseLimits, decreaseLimits, sizeof(tokens[numberOfTokens].decreaseLimits));
memcpy(tokens[numberOfTokens].increaseLimits, increaseLimits, sizeof(tokens[numberOfTokens].increaseLimits));
tokens[numberOfTokens].unitSize = unitSize;
tokens[numberOfTokens].minLockPeriod = minLockPeriod;
tokens[numberOfTokens].maxLockPeriod = maxLockPeriod;
tokens[numberOfTokens].minExtraLockPeriod = minExtraLockPeriod;
tokens[numberOfTokens].maxExtraLockPeriod = maxExtraLockPeriod;
tokens[numberOfTokens].redemptionGap = redemptionGap;
tokens[numberOfTokens].day0Offset = day0Offset;
memset(tokens[numberOfTokens].prices, 0, sizeof(tokens[numberOfTokens].prices));
tokens[numberOfTokens].prices[0] = initialPrice;
return numberOfTokens++;
}
void enableToken(unsigned int token) {
tokens[token].enabled = TRUE;
}
void disableToken(unsigned int token) {
tokens[token].enabled = FALSE;
}
void changeFadeRate(unsigned int token, signed int newFadeRate) {
tokens[token].fadeRate = newFadeRate;
}
void changeUnitSize(unsigned int token, unsigned long newUnitSize) {
tokens[token].unitSize = newUnitSize;
}
void changeLockPeriods(unsigned int token, unsigned short newMinLockPeriod, unsigned short newMaxLockPeriod) {
tokens[token].minLockPeriod = newMinLockPeriod;
tokens[token].maxLockPeriod = newMaxLockPeriod;
}
void changeExtraLockPeriods(unsigned int token, unsigned char newMinExtraLockPeriod, unsigned char newMaxExtraLockPeriod) {
tokens[token].minExtraLockPeriod = newMinExtraLockPeriod;
tokens[token].maxExtraLockPeriod = newMaxExtraLockPeriod;
}
void changeRedemptionGap(unsigned int token, unsigned char newRedemptionGap) {
tokens[token].redemptionGap = newRedemptionGap;
}
void getLockPeriodHashAndPrefix(unsigned short lockPeriod, unsigned char* lockPeriodHash, unsigned char* lockPeriodPrefix) {
unsigned char buffer[HASH_SIZE];
int i;
for (i = 0; i < HASH_SIZE - sizeof(lockPeriod); i++) {
buffer[i] = random();
}
*((unsigned short*)&buffer[i]) = lockPeriod; // WARNING: Depends on endianness!
hash(buffer, sizeof(buffer), lockPeriodHash);
memcpy(lockPeriodPrefix, buffer, i);
}
unsigned long getLastPrice(unsigned int token, unsigned long time) {
for (int i = (time - tokens[token].day0Offset) / (24 * 60 * 60 * 1000) + 1; i-- > 0;) {
if (tokens[token].prices[i] > 0) {
return tokens[token].prices[i];
}
}
}
unsigned int addUnit(unsigned long id,
unsigned int token,
unsigned long account,
unsigned long time,
unsigned char* lockPeriodHash,
unsigned short minLockPeriod, unsigned short maxLockPeriod,
unsigned long seed,
unsigned long mainCurrencyUnitSize) {
// Returns the index of the new unit
if (numberOfUnits >= MAX_NUMBER_OF_UNITS) {
// TODO: Throw exception
}
if (token >= numberOfTokens) {
// TODO: Throw exception
}
if (tokens[token].enabled == FALSE) {
// TODO: Throw exception
}
units[numberOfUnits].id = id;
units[numberOfUnits].token = token;
units[numberOfUnits].account = account;
units[numberOfUnits].fadeRate = tokens[token].fadeRate;
units[numberOfUnits].size = tokens[token].unitSize;
units[numberOfUnits].timestamp = time;
memcpy(units[numberOfUnits].lockPeriodHash, lockPeriodHash, HASH_SIZE);
units[numberOfUnits].minLockPeriod = minLockPeriod;
units[numberOfUnits].maxLockPeriod = maxLockPeriod;
units[numberOfUnits].extraLockPeriod = seed % (tokens[token].maxExtraLockPeriod - tokens[token].minExtraLockPeriod + 1) + tokens[token].minExtraLockPeriod;
units[numberOfUnits].redemptionGap = tokens[token].redemptionGap;
pools[tokens[token].pool].reserve += units[numberOfUnits].size * getLastPrice(token, time) / mainCurrencyUnitSize; // WARNING: May overflow!
return numberOfUnits++;
}
unsigned long redeemUnit(unsigned long id, unsigned long account, unsigned short lockPeriod, unsigned char* lockPeriodPrefix, unsigned long time, unsigned long mainCurrencyUnitSize) {
// Returns amount to add to the account balance
for (int i = 0; i < numberOfUnits; i++) {
if (units[i].id == id) {
if (units[i].account == account) {
unsigned char buffer[HASH_SIZE];
memcpy(buffer, lockPeriodPrefix, HASH_SIZE - sizeof(lockPeriod));
*((unsigned short*)&buffer[HASH_SIZE - sizeof(lockPeriod)]) = lockPeriod; // WARNING: Depends on endianness!
unsigned char lockPeriodHash[HASH_SIZE];
hash(buffer, sizeof(buffer), lockPeriodHash);
for (int j = 0; j < HASH_SIZE; j++) {
if (lockPeriodHash[j] != units[i].lockPeriodHash[j]) {
return 0;
}
}
if (lockPeriod < units[i].minLockPeriod || lockPeriod > units[i].maxLockPeriod) {
return 0;
}
unsigned int delta = (time - units[i].timestamp) / (24 * 60 * 60 * 1000);
if (delta < lockPeriod + units[i].extraLockPeriod || delta > lockPeriod + units[i].extraLockPeriod + units[i].redemptionGap) {
return 0;
}
unsigned long amount = units[i].size * getLastPrice(units[i].token, units[i].timestamp + (lockPeriod + units[i].extraLockPeriod) * 24 * 60 * 60 * 1000) / mainCurrencyUnitSize; // WARNING: May overflow!
for (int j = lockPeriod + units[i].extraLockPeriod; j-- > 0; ) {
amount = amount * (1000 - units[i].fadeRate) / 1000; // WARNING: Do not use floating-point math!
}
if (pools[tokens[units[i].token].pool].reserve < amount) {
amount = pools[tokens[units[i].token].pool].reserve;
}
pools[tokens[units[i].token].pool].reserve -= amount;
memcpy(&units[i], &units[--numberOfUnits], sizeof(Unit));
return amount;
}
break;
}
}
return 0;
}
void salvageExpiredUnits(unsigned long time) {
for (int i = numberOfUnits; i-- > 0; ) {
if ((time - units[i].timestamp) / (24 * 60 * 60 * 1000) > units[i].maxLockPeriod + units[i].extraLockPeriod + units[i].redemptionGap) {
memcpy(&units[i], &units[--numberOfUnits], sizeof(Unit));
}
}
}
unsigned int addSupervisor(unsigned long id) {
// Returns the index of the new supervisor
if (numberOfSupervisors >= MAX_NUMBER_OF_SUPERVISORS) {
// TODO: Throw exception
}
supervisors[numberOfSupervisors].id = id;
supervisors[numberOfSupervisors].rating = 0;
supervisors[numberOfSupervisors].activity = 0;
return numberOfSupervisors++;
}
Supervisor* getSupervisor(unsigned long id) {
for (int i = 0; i < numberOfSupervisors; i++) {
if (supervisors[i].id == id) {
return &supervisors[i];
}
}
return NULL;
}
BOOL castSupervisorVotes(unsigned int token, unsigned long time, Vote* votes, unsigned int numberOfVotes, unsigned long* prizes) {
// Returns if a new price has been set
unsigned long totalWeight = 0;
unsigned long totalBet = 0;
for (int i = 0; i < numberOfVotes; i++) {
totalWeight += votes[i].weight;
getSupervisor(votes[i].supervisorId)->activity++;
totalBet += votes[i].bet;
}
if (totalWeight < pools[tokens[token].pool].quorum) {
return FALSE;
}
unsigned long prices[MAX_NUMBER_OF_SUPERVISORS];
unsigned long weights[MAX_NUMBER_OF_SUPERVISORS];
for (int i = 0; i < numberOfVotes; i++) {
int j;
for (j = 0; j < i; j++) {
if (prices[j] > votes[i].price) {
break;
}
memmove(&prices[j + 1], &prices[j], (i - j) * sizeof(Vote));
memmove(&weights[j + 1], &weights[j], (i - j) * sizeof(Vote));
prices[j] = votes[i].price;
weights[j] = votes[i].weight;
}
}
unsigned long newPrice = 0;
for (int i = 0; i < numberOfVotes; i++) {
unsigned long weight = 0;
unsigned long bet = 0;
for (int j = 0; j < numberOfVotes; j++) {
signed long delta = votes[i].price - votes[j].price;
if (delta < 0) {
delta = -delta;
}
if (delta <= votes[j].tolerance) {
weight += votes[j].weight;
bet += votes[j].bet;
}
}
if (weight > totalWeight / 2) {
newPrice = votes[i].price;
unsigned long totalPrize = 0;
for (int j = 0; j < numberOfVotes; j++) {
signed long delta = votes[i].price - votes[j].price;
if (delta < 0) {
delta = -delta;
}
if (delta <= votes[j].tolerance) {
getSupervisor(votes[j].supervisorId)->rating++;
if (prizes != NULL) {
prizes[j] = votes[j].bet + (votes[j].bet * (totalBet - bet) / bet);
totalPrize += prizes[j];
}
} else {
if (prizes != NULL) {
prizes[j] = 0;
}
}
}
if (prizes != NULL) {
pools[tokens[token].pool].reserve += totalBet - totalPrize;
}
break;
}
}
if (newPrice == 0) {
return FALSE;
} else {
unsigned long lastPrice = getLastPrice(token, time);
if (newPrice < lastPrice) {
if ((lastPrice - newPrice) * 1000 / lastPrice > tokens[token].decreaseLimits[DAILY]) {
newPrice = lastPrice - tokens[token].decreaseLimits[DAILY] * lastPrice / 1000;
}
lastPrice = getLastPrice(token, time - 7L * 24 * 60 * 60 * 1000);
if ((lastPrice - newPrice) * 1000 / lastPrice > tokens[token].decreaseLimits[WEEKLY]) {
newPrice = lastPrice - tokens[token].decreaseLimits[WEEKLY] * lastPrice / 1000;
}
lastPrice = getLastPrice(token, time - 30L * 24 * 60 * 60 * 1000);
if ((lastPrice - newPrice) * 1000 / lastPrice > tokens[token].decreaseLimits[MONTHLY]) {
newPrice = lastPrice - tokens[token].decreaseLimits[MONTHLY] * lastPrice / 1000;
}
lastPrice = getLastPrice(token, time - 365L * 24 * 60 * 60 * 1000);
if ((lastPrice - newPrice) * 1000 / lastPrice > tokens[token].decreaseLimits[YEARLY]) {
newPrice = lastPrice - tokens[token].decreaseLimits[YEARLY] * lastPrice / 1000;
}
} else {
if ((newPrice - lastPrice) * 1000 / lastPrice > tokens[token].increaseLimits[DAILY]) {
newPrice = lastPrice + tokens[token].increaseLimits[DAILY] * lastPrice / 1000;
}
lastPrice = getLastPrice(token, time - 7L * 24 * 60 * 60 * 1000);
if ((newPrice - lastPrice) * 1000 / lastPrice > tokens[token].increaseLimits[WEEKLY]) {
newPrice = lastPrice + tokens[token].increaseLimits[WEEKLY] * lastPrice / 1000;
}
lastPrice = getLastPrice(token, time - 30L * 24 * 60 * 60 * 1000);
if ((newPrice - lastPrice) * 1000 / lastPrice > tokens[token].increaseLimits[MONTHLY]) {
newPrice = lastPrice + tokens[token].increaseLimits[MONTHLY] * lastPrice / 1000;
}
lastPrice = getLastPrice(token, time - 365L * 24 * 60 * 60 * 1000);
if ((newPrice - lastPrice) * 1000 / lastPrice > tokens[token].increaseLimits[YEARLY]) {
newPrice = lastPrice + tokens[token].increaseLimits[YEARLY] * lastPrice / 1000;
}
}
tokens[token].prices[(time - tokens[token].day0Offset) / (24 * 60 * 60 * 1000)] = newPrice;
return TRUE;
}
}
#endif
#endif
#endif

338
crypto777/bitcoind_RPC.c

@ -0,0 +1,338 @@
/******************************************************************************
* Copyright © 2014-2015 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
#include "OS_portable.h"
#include "../includes/cJSON.h"
#include <curl/curl.h>
#include <curl/easy.h>
// return data from the server
struct return_string {
char *ptr;
size_t len;
};
size_t accumulate(void *ptr, size_t size, size_t nmemb, struct return_string *s);
void init_string(struct return_string *s);
/************************************************************************
*
* return the current system time in milliseconds
*
************************************************************************/
#define EXTRACT_BITCOIND_RESULT // if defined, ensures error is null and returns the "result" field
#ifdef EXTRACT_BITCOIND_RESULT
/************************************************************************
*
* perform post processing of the results
*
************************************************************************/
char *post_process_bitcoind_RPC(char *debugstr,char *command,char *rpcstr,char *params)
{
long i,j,len;
char *retstr = 0;
cJSON *json,*result,*error;
printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC.%s.[%s]\n",debugstr,command,rpcstr);
if ( command == 0 || rpcstr == 0 || rpcstr[0] == 0 )
{
printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC.%s.[%s]\n",debugstr,command,rpcstr);
return(rpcstr);
}
json = cJSON_Parse(rpcstr);
if ( json == 0 )
{
printf("<<<<<<<<<<< bitcoind_RPC: %s post_process_bitcoind_RPC.%s can't parse.(%s) params.(%s)\n",debugstr,command,rpcstr,params);
free(rpcstr);
return(0);
}
result = cJSON_GetObjectItem(json,"result");
error = cJSON_GetObjectItem(json,"error");
if ( error != 0 && result != 0 )
{
if ( (error->type&0xff) == cJSON_NULL && (result->type&0xff) != cJSON_NULL )
{
retstr = cJSON_Print(result);
len = strlen(retstr);
if ( retstr[0] == '"' && retstr[len-1] == '"' )
{
for (i=1,j=0; i<len-1; i++,j++)
retstr[j] = retstr[i];
retstr[j] = 0;
}
}
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);
} else retstr = rpcstr;
free_json(json);
//fprintf(stderr,"<<<<<<<<<<< bitcoind_RPC: postprocess returns.(%s)\n",retstr);
return(retstr);
}
#endif
/************************************************************************
*
* perform the query
*
************************************************************************/
char *Jay_NXTrequest(char *command,char *params)
{
char *retstr = 0;
// issue JS Jay request
// wait till it is done
return(retstr);
}
char *bitcoind_RPC(char **retstrp,char *debugstr,char *url,char *userpass,char *command,char *params)
{
static int count,count2; static double elapsedsum,elapsedsum2; extern int32_t USE_JAY;
struct curl_slist *headers = NULL; struct return_string s; CURLcode res; CURL *curl_handle;
char *bracket0,*bracket1,*databuf = 0; long len; int32_t specialcase,numretries; double starttime;
if ( 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);
}
numretries = 0;
if ( debugstr != 0 && strcmp(debugstr,"BTCD") == 0 && command != 0 && strcmp(command,"SuperNET") == 0 )
specialcase = 1;
else specialcase = 0;
if ( url[0] == 0 )
strcpy(url,"http://127.0.0.1:7876/nxt");
if ( specialcase != 0 && 0 )
printf("<<<<<<<<<<< bitcoind_RPC: debug.(%s) url.(%s) command.(%s) params.(%s)\n",debugstr,url,command,params);
try_again:
if ( retstrp != 0 )
*retstrp = 0;
starttime = OS_milliseconds();
curl_handle = curl_easy_init();
init_string(&s);
headers = curl_slist_append(0,"Expect:");
curl_easy_setopt(curl_handle,CURLOPT_USERAGENT,"mozilla/4.0");//"Mozilla/4.0 (compatible; )");
curl_easy_setopt(curl_handle,CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl_handle,CURLOPT_URL, url);
curl_easy_setopt(curl_handle,CURLOPT_WRITEFUNCTION, (void *)accumulate); // send all data to this function
curl_easy_setopt(curl_handle,CURLOPT_WRITEDATA, &s); // we pass our 's' struct to the callback
curl_easy_setopt(curl_handle,CURLOPT_NOSIGNAL, 1L); // supposed to fix "Alarm clock" and long jump crash
curl_easy_setopt(curl_handle,CURLOPT_NOPROGRESS, 1L); // no progress callback
if ( strncmp(url,"https",5) == 0 )
{
curl_easy_setopt(curl_handle,CURLOPT_SSL_VERIFYPEER,0);
curl_easy_setopt(curl_handle,CURLOPT_SSL_VERIFYHOST,0);
}
if ( userpass != 0 )
curl_easy_setopt(curl_handle,CURLOPT_USERPWD, userpass);
databuf = 0;
if ( params != 0 )
{
if ( command != 0 && specialcase == 0 )
{
len = strlen(params);
if ( len > 0 && params[0] == '[' && params[len-1] == ']' ) {
bracket0 = bracket1 = (char *)"";
}
else
{
bracket0 = (char *)"[";
bracket1 = (char *)"]";
}
databuf = (char *)malloc(256 + strlen(command) + strlen(params));
sprintf(databuf,"{\"id\":\"jl777\",\"method\":\"%s\",\"params\":%s%s%s}",command,bracket0,params,bracket1);
//printf("url.(%s) userpass.(%s) databuf.(%s)\n",url,userpass,databuf);
//
} //else if ( specialcase != 0 ) fprintf(stderr,"databuf.(%s)\n",params);
curl_easy_setopt(curl_handle,CURLOPT_POST,1L);
if ( databuf != 0 )
curl_easy_setopt(curl_handle,CURLOPT_POSTFIELDS,databuf);
else curl_easy_setopt(curl_handle,CURLOPT_POSTFIELDS,params);
}
//laststart = milliseconds();
res = curl_easy_perform(curl_handle);
curl_slist_free_all(headers);
curl_easy_cleanup(curl_handle);
if ( databuf != 0 ) // clean up temporary buffer
{
free(databuf);
databuf = 0;
}
if ( res != CURLE_OK )
{
numretries++;
if ( specialcase != 0 )
{
printf("<<<<<<<<<<< bitcoind_RPC.(%s): BTCD.%s timeout params.(%s) s.ptr.(%s) err.%d\n",url,command,params,s.ptr,res);
free(s.ptr);
return(0);
}
else if ( numretries >= 2 )
{
printf("Maximum number of retries exceeded!\n");
free(s.ptr);
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);
sleep((1<<numretries));
goto try_again;
}
else
{
if ( command != 0 && specialcase == 0 )
{
count++;
elapsedsum += (OS_milliseconds() - starttime);
if ( (count % 10000) == 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);
}
return(post_process_bitcoind_RPC(debugstr,command,s.ptr,params));
}
else
{
if ( 0 && specialcase != 0 )
fprintf(stderr,"<<<<<<<<<<< bitcoind_RPC: BTCD.(%s) -> (%s)\n",params,s.ptr);
count2++;
elapsedsum2 += (OS_milliseconds() - starttime);
if ( (count2 % 10000) == 0)
printf("%d: ave %9.6f | elapsed %.3f millis | NXT calls.(%s) cmd.(%s)\n",count2,elapsedsum2/count2,(double)(OS_milliseconds() - starttime),url,command);
return(s.ptr);
}
}
printf("bitcoind_RPC: impossible case\n");
free(s.ptr);
return(0);
}
/************************************************************************
*
* Initialize the string handler so that it is thread safe
*
************************************************************************/
void init_string(struct return_string *s)
{
s->len = 0;
s->ptr = (char *)calloc(1,s->len+1);
if ( s->ptr == NULL )
{
fprintf(stderr,"init_string malloc() failed\n");
exit(-1);
}
s->ptr[0] = '\0';
}
/************************************************************************
*
* Use the "writer" to accumulate text until done
*
************************************************************************/
size_t accumulate(void *ptr,size_t size,size_t nmemb,struct return_string *s)
{
size_t new_len = s->len + size*nmemb;
s->ptr = (char *)realloc(s->ptr,new_len+1);
if ( s->ptr == NULL )
{
fprintf(stderr, "accumulate realloc() failed\n");
exit(-1);
}
memcpy(s->ptr+s->len,ptr,size*nmemb);
s->ptr[new_len] = '\0';
s->len = new_len;
return(size * nmemb);
}
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);
struct MemoryStruct *mem = (struct MemoryStruct *)data;
mem->memory = (ptr != 0) ? realloc(mem->memory,mem->size + realsize + 1) : malloc(mem->size + realsize + 1);
if ( mem->memory != 0 )
{
if ( ptr != 0 )
memcpy(&(mem->memory[mem->size]),ptr,realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
}
return(realsize);
}
void *curl_post(CURL **cHandlep,char *url,char *userpass,char *postfields,char *hdr0,char *hdr1,char *hdr2,char *hdr3)
{
struct MemoryStruct chunk; CURL *cHandle; long code; struct curl_slist *headers = 0;
if ( (cHandle= *cHandlep) == NULL )
*cHandlep = cHandle = curl_easy_init();
else curl_easy_reset(cHandle);
//#ifdef DEBUG
//curl_easy_setopt(cHandle,CURLOPT_VERBOSE, 1);
//#endif
curl_easy_setopt(cHandle,CURLOPT_USERAGENT,"mozilla/4.0");//"Mozilla/4.0 (compatible; )");
curl_easy_setopt(cHandle,CURLOPT_SSL_VERIFYPEER,0);
//curl_easy_setopt(cHandle,CURLOPT_SSLVERSION,1);
curl_easy_setopt(cHandle,CURLOPT_URL,url);
curl_easy_setopt(cHandle,CURLOPT_CONNECTTIMEOUT,10);
if ( userpass != 0 && userpass[0] != 0 )
curl_easy_setopt(cHandle,CURLOPT_USERPWD,userpass);
if ( postfields != 0 && postfields[0] != 0 )
{
curl_easy_setopt(cHandle,CURLOPT_POST,1);
curl_easy_setopt(cHandle,CURLOPT_POSTFIELDS,postfields);
}
if ( hdr0 != NULL && hdr0[0] != 0 )
{
//printf("HDR0.(%s) HDR1.(%s) HDR2.(%s) HDR3.(%s)\n",hdr0!=0?hdr0:"",hdr1!=0?hdr1:"",hdr2!=0?hdr2:"",hdr3!=0?hdr3:"");
headers = curl_slist_append(headers,hdr0);
if ( hdr1 != 0 && hdr1[0] != 0 )
headers = curl_slist_append(headers,hdr1);
if ( hdr2 != 0 && hdr2[0] != 0 )
headers = curl_slist_append(headers,hdr2);
if ( hdr3 != 0 && hdr3[0] != 0 )
headers = curl_slist_append(headers,hdr3);
} //headers = curl_slist_append(0,"Expect:");
if ( headers != 0 )
curl_easy_setopt(cHandle,CURLOPT_HTTPHEADER,headers);
//res = curl_easy_perform(cHandle);
memset(&chunk,0,sizeof(chunk));
curl_easy_setopt(cHandle,CURLOPT_WRITEFUNCTION,WriteMemoryCallback);
curl_easy_setopt(cHandle,CURLOPT_WRITEDATA,(void *)&chunk);
curl_easy_perform(cHandle);
curl_easy_getinfo(cHandle,CURLINFO_RESPONSE_CODE,&code);
if ( code != 200 )
printf("error: (%s) server responded with code %ld\n",url,code);
if ( headers != 0 )
curl_slist_free_all(headers);
return(chunk.memory);
}
void curlhandle_free(void *curlhandle)
{
curl_easy_cleanup(curlhandle);
}

1054
crypto777/cJSON.c

File diff suppressed because it is too large

892
crypto777/curve25519-donna.c

@ -0,0 +1,892 @@
/* Copyright 2008, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* curve25519-donna: Curve25519 elliptic curve, public key function
*
* http://code.google.com/p/curve25519-donna/
*
* Adam Langley <agl@imperialviolet.org>
*
* Derived from public domain C code by Daniel J. Bernstein <djb@cr.yp.to>
*
* More information about curve25519 can be found here
* http://cr.yp.to/ecdh.html
*
* djb's sample implementation of curve25519 is written in a special assembly
* language called qhasm and uses the floating point registers.
*
* This is, almost, a clean room reimplementation from the curve25519 paper. It
* uses many of the tricks described therein. Only the crecip function is taken
* from the sample implementation. */
#include <string.h>
#include <stdint.h>
#include "../includes/curve25519.h"
#ifdef _MSC_VER
#define inline __inline
#endif
typedef uint8_t u8;
typedef int32_t s32;
typedef int64_t limb;
/* Field element representation:
*
* Field elements are written as an array of signed, 64-bit limbs, least
* significant first. The value of the field element is:
* x[0] + 2^26·x[1] + x^51·x[2] + 2^102·x[3] + ...
*
* i.e. the limbs are 26, 25, 26, 25, ... bits wide. */
/* Sum two numbers: output += in */
static void fsum(limb *output, const limb *in) {
unsigned i;
for (i = 0; i < 10; i += 2) {
output[0+i] = output[0+i] + in[0+i];
output[1+i] = output[1+i] + in[1+i];
}
}
/* Find the difference of two numbers: output = in - output
* (note the order of the arguments!). */
void fdifference_backwards(limb *output, const limb *in) {
unsigned i;
for (i = 0; i < 10; ++i) {
output[i] = in[i] - output[i];
}
}
/* Multiply a number by a scalar: output = in * scalar */
static void fscalar_product(limb *output, const limb *in, const limb scalar) {
unsigned i;
for (i = 0; i < 10; ++i) {
output[i] = in[i] * scalar;
}
}
/* Multiply two numbers: output = in2 * in
*
* output must be distinct to both inputs. The inputs are reduced coefficient
* form, the output is not.
*
* output[x] <= 14 * the largest product of the input limbs. */
static void fproduct(limb *output, const limb *in2, const limb *in) {
output[0] = ((limb) ((s32) in2[0])) * ((s32) in[0]);
output[1] = ((limb) ((s32) in2[0])) * ((s32) in[1]) +
((limb) ((s32) in2[1])) * ((s32) in[0]);
output[2] = 2 * ((limb) ((s32) in2[1])) * ((s32) in[1]) +
((limb) ((s32) in2[0])) * ((s32) in[2]) +
((limb) ((s32) in2[2])) * ((s32) in[0]);
output[3] = ((limb) ((s32) in2[1])) * ((s32) in[2]) +
((limb) ((s32) in2[2])) * ((s32) in[1]) +
((limb) ((s32) in2[0])) * ((s32) in[3]) +
((limb) ((s32) in2[3])) * ((s32) in[0]);
output[4] = ((limb) ((s32) in2[2])) * ((s32) in[2]) +
2 * (((limb) ((s32) in2[1])) * ((s32) in[3]) +
((limb) ((s32) in2[3])) * ((s32) in[1])) +
((limb) ((s32) in2[0])) * ((s32) in[4]) +
((limb) ((s32) in2[4])) * ((s32) in[0]);
output[5] = ((limb) ((s32) in2[2])) * ((s32) in[3]) +
((limb) ((s32) in2[3])) * ((s32) in[2]) +
((limb) ((s32) in2[1])) * ((s32) in[4]) +
((limb) ((s32) in2[4])) * ((s32) in[1]) +
((limb) ((s32) in2[0])) * ((s32) in[5]) +
((limb) ((s32) in2[5])) * ((s32) in[0]);
output[6] = 2 * (((limb) ((s32) in2[3])) * ((s32) in[3]) +
((limb) ((s32) in2[1])) * ((s32) in[5]) +
((limb) ((s32) in2[5])) * ((s32) in[1])) +
((limb) ((s32) in2[2])) * ((s32) in[4]) +
((limb) ((s32) in2[4])) * ((s32) in[2]) +
((limb) ((s32) in2[0])) * ((s32) in[6]) +
((limb) ((s32) in2[6])) * ((s32) in[0]);
output[7] = ((limb) ((s32) in2[3])) * ((s32) in[4]) +
((limb) ((s32) in2[4])) * ((s32) in[3]) +
((limb) ((s32) in2[2])) * ((s32) in[5]) +
((limb) ((s32) in2[5])) * ((s32) in[2]) +
((limb) ((s32) in2[1])) * ((s32) in[6]) +
((limb) ((s32) in2[6])) * ((s32) in[1]) +
((limb) ((s32) in2[0])) * ((s32) in[7]) +
((limb) ((s32) in2[7])) * ((s32) in[0]);
output[8] = ((limb) ((s32) in2[4])) * ((s32) in[4]) +
2 * (((limb) ((s32) in2[3])) * ((s32) in[5]) +
((limb) ((s32) in2[5])) * ((s32) in[3]) +
((limb) ((s32) in2[1])) * ((s32) in[7]) +
((limb) ((s32) in2[7])) * ((s32) in[1])) +
((limb) ((s32) in2[2])) * ((s32) in[6]) +
((limb) ((s32) in2[6])) * ((s32) in[2]) +
((limb) ((s32) in2[0])) * ((s32) in[8]) +
((limb) ((s32) in2[8])) * ((s32) in[0]);
output[9] = ((limb) ((s32) in2[4])) * ((s32) in[5]) +
((limb) ((s32) in2[5])) * ((s32) in[4]) +
((limb) ((s32) in2[3])) * ((s32) in[6]) +
((limb) ((s32) in2[6])) * ((s32) in[3]) +
((limb) ((s32) in2[2])) * ((s32) in[7]) +
((limb) ((s32) in2[7])) * ((s32) in[2]) +
((limb) ((s32) in2[1])) * ((s32) in[8]) +
((limb) ((s32) in2[8])) * ((s32) in[1]) +
((limb) ((s32) in2[0])) * ((s32) in[9]) +
((limb) ((s32) in2[9])) * ((s32) in[0]);
output[10] = 2 * (((limb) ((s32) in2[5])) * ((s32) in[5]) +
((limb) ((s32) in2[3])) * ((s32) in[7]) +
((limb) ((s32) in2[7])) * ((s32) in[3]) +
((limb) ((s32) in2[1])) * ((s32) in[9]) +
((limb) ((s32) in2[9])) * ((s32) in[1])) +
((limb) ((s32) in2[4])) * ((s32) in[6]) +
((limb) ((s32) in2[6])) * ((s32) in[4]) +
((limb) ((s32) in2[2])) * ((s32) in[8]) +
((limb) ((s32) in2[8])) * ((s32) in[2]);
output[11] = ((limb) ((s32) in2[5])) * ((s32) in[6]) +
((limb) ((s32) in2[6])) * ((s32) in[5]) +
((limb) ((s32) in2[4])) * ((s32) in[7]) +
((limb) ((s32) in2[7])) * ((s32) in[4]) +
((limb) ((s32) in2[3])) * ((s32) in[8]) +
((limb) ((s32) in2[8])) * ((s32) in[3]) +
((limb) ((s32) in2[2])) * ((s32) in[9]) +
((limb) ((s32) in2[9])) * ((s32) in[2]);
output[12] = ((limb) ((s32) in2[6])) * ((s32) in[6]) +
2 * (((limb) ((s32) in2[5])) * ((s32) in[7]) +
((limb) ((s32) in2[7])) * ((s32) in[5]) +
((limb) ((s32) in2[3])) * ((s32) in[9]) +
((limb) ((s32) in2[9])) * ((s32) in[3])) +
((limb) ((s32) in2[4])) * ((s32) in[8]) +
((limb) ((s32) in2[8])) * ((s32) in[4]);
output[13] = ((limb) ((s32) in2[6])) * ((s32) in[7]) +
((limb) ((s32) in2[7])) * ((s32) in[6]) +
((limb) ((s32) in2[5])) * ((s32) in[8]) +
((limb) ((s32) in2[8])) * ((s32) in[5]) +
((limb) ((s32) in2[4])) * ((s32) in[9]) +
((limb) ((s32) in2[9])) * ((s32) in[4]);
output[14] = 2 * (((limb) ((s32) in2[7])) * ((s32) in[7]) +
((limb) ((s32) in2[5])) * ((s32) in[9]) +
((limb) ((s32) in2[9])) * ((s32) in[5])) +
((limb) ((s32) in2[6])) * ((s32) in[8]) +
((limb) ((s32) in2[8])) * ((s32) in[6]);
output[15] = ((limb) ((s32) in2[7])) * ((s32) in[8]) +
((limb) ((s32) in2[8])) * ((s32) in[7]) +
((limb) ((s32) in2[6])) * ((s32) in[9]) +
((limb) ((s32) in2[9])) * ((s32) in[6]);
output[16] = ((limb) ((s32) in2[8])) * ((s32) in[8]) +
2 * (((limb) ((s32) in2[7])) * ((s32) in[9]) +
((limb) ((s32) in2[9])) * ((s32) in[7]));
output[17] = ((limb) ((s32) in2[8])) * ((s32) in[9]) +
((limb) ((s32) in2[9])) * ((s32) in[8]);
output[18] = 2 * ((limb) ((s32) in2[9])) * ((s32) in[9]);
}
/* Reduce a long form to a short form by taking the input mod 2^255 - 19.
*
* On entry: |output[i]| < 14*2^54
* On exit: |output[0..8]| < 280*2^54 */
static void freduce_degree(limb *output) {
/* Each of these shifts and adds ends up multiplying the value by 19.
*
* For output[0..8], the absolute entry value is < 14*2^54 and we add, at
* most, 19*14*2^54 thus, on exit, |output[0..8]| < 280*2^54. */
output[8] += output[18] << 4;
output[8] += output[18] << 1;
output[8] += output[18];
output[7] += output[17] << 4;
output[7] += output[17] << 1;
output[7] += output[17];
output[6] += output[16] << 4;
output[6] += output[16] << 1;
output[6] += output[16];
output[5] += output[15] << 4;
output[5] += output[15] << 1;
output[5] += output[15];
output[4] += output[14] << 4;
output[4] += output[14] << 1;
output[4] += output[14];
output[3] += output[13] << 4;
output[3] += output[13] << 1;
output[3] += output[13];
output[2] += output[12] << 4;
output[2] += output[12] << 1;
output[2] += output[12];
output[1] += output[11] << 4;
output[1] += output[11] << 1;
output[1] += output[11];
output[0] += output[10] << 4;
output[0] += output[10] << 1;
output[0] += output[10];
}
#if (-1 & 3) != 3
#error "This code only works on a two's complement system"
#endif
/* return v / 2^26, using only shifts and adds.
*
* On entry: v can take any value. */
static inline limb
div_by_2_26(const limb v)
{
/* High word of v; no shift needed. */
const uint32_t highword = (uint32_t) (((uint64_t) v) >> 32);
/* Set to all 1s if v was negative; else set to 0s. */
const int32_t sign = ((int32_t) highword) >> 31;
/* Set to 0x3ffffff if v was negative; else set to 0. */
const int32_t roundoff = ((uint32_t) sign) >> 6;
/* Should return v / (1<<26) */
return (v + roundoff) >> 26;
}
/* return v / (2^25), using only shifts and adds.
*
* On entry: v can take any value. */
static inline limb
div_by_2_25(const limb v)
{
/* High word of v; no shift needed*/
const uint32_t highword = (uint32_t) (((uint64_t) v) >> 32);
/* Set to all 1s if v was negative; else set to 0s. */
const int32_t sign = ((int32_t) highword) >> 31;
/* Set to 0x1ffffff if v was negative; else set to 0. */
const int32_t roundoff = ((uint32_t) sign) >> 7;
/* Should return v / (1<<25) */
return (v + roundoff) >> 25;
}
/* Reduce all coefficients of the short form input so that |x| < 2^26.
*
* On entry: |output[i]| < 280*2^54 */
static void freduce_coefficients(limb *output) {
unsigned i;
output[10] = 0;
for (i = 0; i < 10; i += 2) {
limb over = div_by_2_26(output[i]);
/* The entry condition (that |output[i]| < 280*2^54) means that over is, at
* most, 280*2^28 in the first iteration of this loop. This is added to the
* next limb and we can approximate the resulting bound of that limb by
* 281*2^54. */
output[i] -= over << 26;
output[i+1] += over;
/* For the first iteration, |output[i+1]| < 281*2^54, thus |over| <
* 281*2^29. When this is added to the next limb, the resulting bound can
* be approximated as 281*2^54.
*
* For subsequent iterations of the loop, 281*2^54 remains a conservative
* bound and no overflow occurs. */
over = div_by_2_25(output[i+1]);
output[i+1] -= over << 25;
output[i+2] += over;
}
/* Now |output[10]| < 281*2^29 and all other coefficients are reduced. */
output[0] += output[10] << 4;
output[0] += output[10] << 1;
output[0] += output[10];
output[10] = 0;
/* Now output[1..9] are reduced, and |output[0]| < 2^26 + 19*281*2^29
* So |over| will be no more than 2^16. */
{
limb over = div_by_2_26(output[0]);
output[0] -= over << 26;
output[1] += over;
}
/* Now output[0,2..9] are reduced, and |output[1]| < 2^25 + 2^16 < 2^26. The
* bound on |output[1]| is sufficient to meet our needs. */
}
/* A helpful wrapper around fproduct: output = in * in2.
*
* On entry: |in[i]| < 2^27 and |in2[i]| < 2^27.
*
* output must be distinct to both inputs. The output is reduced degree
* (indeed, one need only provide storage for 10 limbs) and |output[i]| < 2^26. */
static void fmul32(limb *output, const limb *in, const limb *in2)
{
limb t[19];
fproduct(t, in, in2);
/* |t[i]| < 14*2^54 */
freduce_degree(t);
freduce_coefficients(t);
/* |t[i]| < 2^26 */
memcpy(output, t, sizeof(limb) * 10);
}
/* Square a number: output = in**2
*
* output must be distinct from the input. The inputs are reduced coefficient
* form, the output is not.
*
* output[x] <= 14 * the largest product of the input limbs. */
static void fsquare_inner(limb *output, const limb *in) {
output[0] = ((limb) ((s32) in[0])) * ((s32) in[0]);
output[1] = 2 * ((limb) ((s32) in[0])) * ((s32) in[1]);
output[2] = 2 * (((limb) ((s32) in[1])) * ((s32) in[1]) +
((limb) ((s32) in[0])) * ((s32) in[2]));
output[3] = 2 * (((limb) ((s32) in[1])) * ((s32) in[2]) +
((limb) ((s32) in[0])) * ((s32) in[3]));
output[4] = ((limb) ((s32) in[2])) * ((s32) in[2]) +
4 * ((limb) ((s32) in[1])) * ((s32) in[3]) +
2 * ((limb) ((s32) in[0])) * ((s32) in[4]);
output[5] = 2 * (((limb) ((s32) in[2])) * ((s32) in[3]) +
((limb) ((s32) in[1])) * ((s32) in[4]) +
((limb) ((s32) in[0])) * ((s32) in[5]));
output[6] = 2 * (((limb) ((s32) in[3])) * ((s32) in[3]) +
((limb) ((s32) in[2])) * ((s32) in[4]) +
((limb) ((s32) in[0])) * ((s32) in[6]) +
2 * ((limb) ((s32) in[1])) * ((s32) in[5]));
output[7] = 2 * (((limb) ((s32) in[3])) * ((s32) in[4]) +
((limb) ((s32) in[2])) * ((s32) in[5]) +
((limb) ((s32) in[1])) * ((s32) in[6]) +
((limb) ((s32) in[0])) * ((s32) in[7]));
output[8] = ((limb) ((s32) in[4])) * ((s32) in[4]) +
2 * (((limb) ((s32) in[2])) * ((s32) in[6]) +
((limb) ((s32) in[0])) * ((s32) in[8]) +
2 * (((limb) ((s32) in[1])) * ((s32) in[7]) +
((limb) ((s32) in[3])) * ((s32) in[5])));
output[9] = 2 * (((limb) ((s32) in[4])) * ((s32) in[5]) +
((limb) ((s32) in[3])) * ((s32) in[6]) +
((limb) ((s32) in[2])) * ((s32) in[7]) +
((limb) ((s32) in[1])) * ((s32) in[8]) +
((limb) ((s32) in[0])) * ((s32) in[9]));
output[10] = 2 * (((limb) ((s32) in[5])) * ((s32) in[5]) +
((limb) ((s32) in[4])) * ((s32) in[6]) +
((limb) ((s32) in[2])) * ((s32) in[8]) +
2 * (((limb) ((s32) in[3])) * ((s32) in[7]) +
((limb) ((s32) in[1])) * ((s32) in[9])));
output[11] = 2 * (((limb) ((s32) in[5])) * ((s32) in[6]) +
((limb) ((s32) in[4])) * ((s32) in[7]) +
((limb) ((s32) in[3])) * ((s32) in[8]) +
((limb) ((s32) in[2])) * ((s32) in[9]));
output[12] = ((limb) ((s32) in[6])) * ((s32) in[6]) +
2 * (((limb) ((s32) in[4])) * ((s32) in[8]) +
2 * (((limb) ((s32) in[5])) * ((s32) in[7]) +
((limb) ((s32) in[3])) * ((s32) in[9])));
output[13] = 2 * (((limb) ((s32) in[6])) * ((s32) in[7]) +
((limb) ((s32) in[5])) * ((s32) in[8]) +
((limb) ((s32) in[4])) * ((s32) in[9]));
output[14] = 2 * (((limb) ((s32) in[7])) * ((s32) in[7]) +
((limb) ((s32) in[6])) * ((s32) in[8]) +
2 * ((limb) ((s32) in[5])) * ((s32) in[9]));
output[15] = 2 * (((limb) ((s32) in[7])) * ((s32) in[8]) +
((limb) ((s32) in[6])) * ((s32) in[9]));
output[16] = ((limb) ((s32) in[8])) * ((s32) in[8]) +
4 * ((limb) ((s32) in[7])) * ((s32) in[9]);
output[17] = 2 * ((limb) ((s32) in[8])) * ((s32) in[9]);
output[18] = 2 * ((limb) ((s32) in[9])) * ((s32) in[9]);
}
/* fsquare sets output = in^2.
*
* On entry: The |in| argument is in reduced coefficients form and |in[i]| <
* 2^27.
*
* On exit: The |output| argument is in reduced coefficients form (indeed, one
* need only provide storage for 10 limbs) and |out[i]| < 2^26. */
static void
fsquare(limb *output, const limb *in) {
limb t[19];
fsquare_inner(t, in);
/* |t[i]| < 14*2^54 because the largest product of two limbs will be <
* 2^(27+27) and fsquare_inner adds together, at most, 14 of those
* products. */
freduce_degree(t);
freduce_coefficients(t);
/* |t[i]| < 2^26 */
memcpy(output, t, sizeof(limb) * 10);
}
/* Take a little-endian, 32-byte number and expand it into polynomial form */
static void fexpand32(limb *output, const u8 *input)
{
#define F(n,start,shift,mask) \
output[n] = ((((limb) input[start + 0]) | \
((limb) input[start + 1]) << 8 | \
((limb) input[start + 2]) << 16 | \
((limb) input[start + 3]) << 24) >> shift) & mask;
F(0, 0, 0, 0x3ffffff);
F(1, 3, 2, 0x1ffffff);
F(2, 6, 3, 0x3ffffff);
F(3, 9, 5, 0x1ffffff);
F(4, 12, 6, 0x3ffffff);
F(5, 16, 0, 0x1ffffff);
F(6, 19, 1, 0x3ffffff);
F(7, 22, 3, 0x1ffffff);
F(8, 25, 4, 0x3ffffff);
F(9, 28, 6, 0x1ffffff);
#undef F
}
#if (-32 >> 1) != -16
#error "This code only works when >> does sign-extension on negative numbers"
#endif
/* s32_eq returns 0xffffffff iff a == b and zero otherwise. */
static s32 s32_eq(s32 a, s32 b) {
a = ~(a ^ b);
a &= a << 16;
a &= a << 8;
a &= a << 4;
a &= a << 2;
a &= a << 1;
return a >> 31;
}
/* s32_gte returns 0xffffffff if a >= b and zero otherwise, where a and b are
* both non-negative. */
static s32 s32_gte(s32 a, s32 b) {
a -= b;
/* a >= 0 iff a >= b. */
return ~(a >> 31);
}
/* Take a fully reduced polynomial form number and contract it into a
* little-endian, 32-byte array.
*
* On entry: |input_limbs[i]| < 2^26 */
static void fcontract32(u8 *output, limb *input_limbs)
{
int i;
int j;
s32 input[10];
s32 mask,carry;
/* |input_limbs[i]| < 2^26, so it's valid to convert to an s32. */
for (i = 0; i < 10; i++) {
input[i] = (s32)input_limbs[i];
}
for (j = 0; j < 2; ++j) {
for (i = 0; i < 9; ++i) {
if ((i & 1) == 1) {
/* This calculation is a time-invariant way to make input[i]
* non-negative by borrowing from the next-larger limb. */
mask = input[i] >> 31;
carry = -((input[i] & mask) >> 25);
input[i] = input[i] + (carry << 25);
input[i+1] = input[i+1] - carry;
} else {
mask = input[i] >> 31;
carry = -((input[i] & mask) >> 26);
input[i] = input[i] + (carry << 26);
input[i+1] = input[i+1] - carry;
}
}
/* There's no greater limb for input[9] to borrow from, but we can multiply
* by 19 and borrow from input[0], which is valid mod 2^255-19. */
{
mask = input[9] >> 31;
carry = -((input[9] & mask) >> 25);
input[9] = input[9] + (carry << 25);
input[0] = input[0] - (carry * 19);
}
/* After the first iteration, input[1..9] are non-negative and fit within
* 25 or 26 bits, depending on position. However, input[0] may be
* negative. */
}
/* The first borrow-propagation pass above ended with every limb
except (possibly) input[0] non-negative.
If input[0] was negative after the first pass, then it was because of a
carry from input[9]. On entry, input[9] < 2^26 so the carry was, at most,
one, since (2**26-1) >> 25 = 1. Thus input[0] >= -19.
In the second pass, each limb is decreased by at most one. Thus the second
borrow-propagation pass could only have wrapped around to decrease
input[0] again if the first pass left input[0] negative *and* input[1]
through input[9] were all zero. In that case, input[1] is now 2^25 - 1,
and this last borrow-propagation step will leave input[1] non-negative. */
{
mask = input[0] >> 31;
carry = -((input[0] & mask) >> 26);
input[0] = input[0] + (carry << 26);
input[1] = input[1] - carry;
}
/* All input[i] are now non-negative. However, there might be values between
* 2^25 and 2^26 in a limb which is, nominally, 25 bits wide. */
for (j = 0; j < 2; j++) {
for (i = 0; i < 9; i++) {
if ((i & 1) == 1) {
carry = input[i] >> 25;
input[i] &= 0x1ffffff;
input[i+1] += carry;
} else {
carry = input[i] >> 26;
input[i] &= 0x3ffffff;
input[i+1] += carry;
}
}
{
carry = input[9] >> 25;
input[9] &= 0x1ffffff;
input[0] += 19*carry;
}
}
/* If the first carry-chain pass, just above, ended up with a carry from
* input[9], and that caused input[0] to be out-of-bounds, then input[0] was
* < 2^26 + 2*19, because the carry was, at most, two.
*
* If the second pass carried from input[9] again then input[0] is < 2*19 and
* the input[9] -> input[0] carry didn't push input[0] out of bounds. */
/* It still remains the case that input might be between 2^255-19 and 2^255.
* In this case, input[1..9] must take their maximum value and input[0] must
* be >= (2^255-19) & 0x3ffffff, which is 0x3ffffed. */
mask = s32_gte(input[0], 0x3ffffed);
for (i = 1; i < 10; i++) {
if ((i & 1) == 1) {
mask &= s32_eq(input[i], 0x1ffffff);
} else {
mask &= s32_eq(input[i], 0x3ffffff);
}
}
/* mask is either 0xffffffff (if input >= 2^255-19) and zero otherwise. Thus
* this conditionally subtracts 2^255-19. */
input[0] -= mask & 0x3ffffed;
for (i = 1; i < 10; i++) {
if ((i & 1) == 1) {
input[i] -= mask & 0x1ffffff;
} else {
input[i] -= mask & 0x3ffffff;
}
}
input[1] <<= 2;
input[2] <<= 3;
input[3] <<= 5;
input[4] <<= 6;
input[6] <<= 1;
input[7] <<= 3;
input[8] <<= 4;
input[9] <<= 6;
#define F(i, s) \
output[s+0] |= input[i] & 0xff; \
output[s+1] = (input[i] >> 8) & 0xff; \
output[s+2] = (input[i] >> 16) & 0xff; \
output[s+3] = (input[i] >> 24) & 0xff;
output[0] = 0;
output[16] = 0;
F(0,0);
F(1,3);
F(2,6);
F(3,9);
F(4,12);
F(5,16);
F(6,19);
F(7,22);
F(8,25);
F(9,28);
#undef F
}
/* Input: Q, Q', Q-Q'
* Output: 2Q, Q+Q'
*
* x2 z3: long form
* x3 z3: long form
* x z: short form, destroyed
* xprime zprime: short form, destroyed
* qmqp: short form, preserved
*
* On entry and exit, the absolute value of the limbs of all inputs and outputs
* are < 2^26. */
static void fmonty(limb *x2, limb *z2, /* output 2Q */
limb *x3, limb *z3, /* output Q + Q' */
limb *x, limb *z, /* input Q */
limb *xprime, limb *zprime, /* input Q' */
const limb *qmqp /* input Q - Q' */) {
limb origx[10], origxprime[10], zzz[19], xx[19], zz[19], xxprime[19],
zzprime[19], zzzprime[19], xxxprime[19];
memcpy(origx, x, 10 * sizeof(limb));
fsum(x, z);
/* |x[i]| < 2^27 */
fdifference_backwards(z, origx); /* does x - z */
/* |z[i]| < 2^27 */
memcpy(origxprime, xprime, sizeof(limb) * 10);
fsum(xprime, zprime);
/* |xprime[i]| < 2^27 */
fdifference_backwards(zprime, origxprime);
/* |zprime[i]| < 2^27 */
fproduct(xxprime, xprime, z);
/* |xxprime[i]| < 14*2^54: the largest product of two limbs will be <
* 2^(27+27) and fproduct adds together, at most, 14 of those products.
* (Approximating that to 2^58 doesn't work out.) */
fproduct(zzprime, x, zprime);
/* |zzprime[i]| < 14*2^54 */
freduce_degree(xxprime);
freduce_coefficients(xxprime);
/* |xxprime[i]| < 2^26 */
freduce_degree(zzprime);
freduce_coefficients(zzprime);
/* |zzprime[i]| < 2^26 */
memcpy(origxprime, xxprime, sizeof(limb) * 10);
fsum(xxprime, zzprime);
/* |xxprime[i]| < 2^27 */
fdifference_backwards(zzprime, origxprime);
/* |zzprime[i]| < 2^27 */
fsquare(xxxprime, xxprime);
/* |xxxprime[i]| < 2^26 */
fsquare(zzzprime, zzprime);
/* |zzzprime[i]| < 2^26 */
fproduct(zzprime, zzzprime, qmqp);
/* |zzprime[i]| < 14*2^52 */
freduce_degree(zzprime);
freduce_coefficients(zzprime);
/* |zzprime[i]| < 2^26 */
memcpy(x3, xxxprime, sizeof(limb) * 10);
memcpy(z3, zzprime, sizeof(limb) * 10);
fsquare(xx, x);
/* |xx[i]| < 2^26 */
fsquare(zz, z);
/* |zz[i]| < 2^26 */
fproduct(x2, xx, zz);
/* |x2[i]| < 14*2^52 */
freduce_degree(x2);
freduce_coefficients(x2);
/* |x2[i]| < 2^26 */
fdifference_backwards(zz, xx); // does zz = xx - zz
/* |zz[i]| < 2^27 */
memset(zzz + 10, 0, sizeof(limb) * 9);
fscalar_product(zzz, zz, 121665);
/* |zzz[i]| < 2^(27+17) */
/* No need to call freduce_degree here:
fscalar_product doesn't increase the degree of its input. */
freduce_coefficients(zzz);
/* |zzz[i]| < 2^26 */
fsum(zzz, xx);
/* |zzz[i]| < 2^27 */
fproduct(z2, zz, zzz);
/* |z2[i]| < 14*2^(26+27) */
freduce_degree(z2);
freduce_coefficients(z2);
/* |z2|i| < 2^26 */
}
/* Conditionally swap two reduced-form limb arrays if 'iswap' is 1, but leave
* them unchanged if 'iswap' is 0. Runs in data-invariant time to avoid
* side-channel attacks.
*
* NOTE that this function requires that 'iswap' be 1 or 0; other values give
* wrong results. Also, the two limb arrays must be in reduced-coefficient,
* reduced-degree form: the values in a[10..19] or b[10..19] aren't swapped,
* and all all values in a[0..9],b[0..9] must have magnitude less than
* INT32_MAX. */
static void
swap_conditional(limb a[19], limb b[19], limb iswap) {
unsigned i;
const s32 swap = (s32) -iswap;
for (i = 0; i < 10; ++i) {
const s32 x = swap & ( ((s32)a[i]) ^ ((s32)b[i]) );
a[i] = ((s32)a[i]) ^ x;
b[i] = ((s32)b[i]) ^ x;
}
}
/* Calculates nQ where Q is the x-coordinate of a point on the curve
*
* resultx/resultz: the x coordinate of the resulting curve point (short form)
* n: a little endian, 32-byte number
* q: a point of the curve (short form) */
static void
cmult32(limb *resultx, limb *resultz, const u8 *n, const limb *q) {
limb a[19] = {0}, b[19] = {1}, c[19] = {1}, d[19] = {0};
limb *nqpqx = a, *nqpqz = b, *nqx = c, *nqz = d, *t;
limb e[19] = {0}, f[19] = {1}, g[19] = {0}, h[19] = {1};
limb *nqpqx2 = e, *nqpqz2 = f, *nqx2 = g, *nqz2 = h;
unsigned i, j;
memcpy(nqpqx, q, sizeof(limb) * 10);
for (i = 0; i < 32; ++i) {
u8 byte = n[31 - i];
for (j = 0; j < 8; ++j) {
const limb bit = byte >> 7;
swap_conditional(nqx, nqpqx, bit);
swap_conditional(nqz, nqpqz, bit);
fmonty(nqx2, nqz2,
nqpqx2, nqpqz2,
nqx, nqz,
nqpqx, nqpqz,
q);
swap_conditional(nqx2, nqpqx2, bit);
swap_conditional(nqz2, nqpqz2, bit);
t = nqx;
nqx = nqx2;
nqx2 = t;
t = nqz;
nqz = nqz2;
nqz2 = t;
t = nqpqx;
nqpqx = nqpqx2;
nqpqx2 = t;
t = nqpqz;
nqpqz = nqpqz2;
nqpqz2 = t;
byte <<= 1;
}
}
memcpy(resultx, nqx, sizeof(limb) * 10);
memcpy(resultz, nqz, sizeof(limb) * 10);
}
// -----------------------------------------------------------------------------
// Shamelessly copied from djb's code
// -----------------------------------------------------------------------------
static void
crecip32(limb *out, const limb *z) {
limb z2[10];
limb z9[10];
limb z11[10];
limb z2_5_0[10];
limb z2_10_0[10];
limb z2_20_0[10];
limb z2_50_0[10];
limb z2_100_0[10];
limb t0[10];
limb t1[10];
int i;
/* 2 */ fsquare(z2,z);
/* 4 */ fsquare(t1,z2);
/* 8 */ fsquare(t0,t1);
/* 9 */ fmul32(z9,t0,z);
/* 11 */ fmul32(z11,z9,z2);
/* 22 */ fsquare(t0,z11);
/* 2^5 - 2^0 = 31 */ fmul32(z2_5_0,t0,z9);
/* 2^6 - 2^1 */ fsquare(t0,z2_5_0);
/* 2^7 - 2^2 */ fsquare(t1,t0);
/* 2^8 - 2^3 */ fsquare(t0,t1);
/* 2^9 - 2^4 */ fsquare(t1,t0);
/* 2^10 - 2^5 */ fsquare(t0,t1);
/* 2^10 - 2^0 */ fmul32(z2_10_0,t0,z2_5_0);
/* 2^11 - 2^1 */ fsquare(t0,z2_10_0);
/* 2^12 - 2^2 */ fsquare(t1,t0);
/* 2^20 - 2^10 */ for (i = 2;i < 10;i += 2) { fsquare(t0,t1); fsquare(t1,t0); }
/* 2^20 - 2^0 */ fmul32(z2_20_0,t1,z2_10_0);
/* 2^21 - 2^1 */ fsquare(t0,z2_20_0);
/* 2^22 - 2^2 */ fsquare(t1,t0);
/* 2^40 - 2^20 */ for (i = 2;i < 20;i += 2) { fsquare(t0,t1); fsquare(t1,t0); }
/* 2^40 - 2^0 */ fmul32(t0,t1,z2_20_0);
/* 2^41 - 2^1 */ fsquare(t1,t0);
/* 2^42 - 2^2 */ fsquare(t0,t1);
/* 2^50 - 2^10 */ for (i = 2;i < 10;i += 2) { fsquare(t1,t0); fsquare(t0,t1); }
/* 2^50 - 2^0 */ fmul32(z2_50_0,t0,z2_10_0);
/* 2^51 - 2^1 */ fsquare(t0,z2_50_0);
/* 2^52 - 2^2 */ fsquare(t1,t0);
/* 2^100 - 2^50 */ for (i = 2;i < 50;i += 2) { fsquare(t0,t1); fsquare(t1,t0); }
/* 2^100 - 2^0 */ fmul32(z2_100_0,t1,z2_50_0);
/* 2^101 - 2^1 */ fsquare(t1,z2_100_0);
/* 2^102 - 2^2 */ fsquare(t0,t1);
/* 2^200 - 2^100 */ for (i = 2;i < 100;i += 2) { fsquare(t1,t0); fsquare(t0,t1); }
/* 2^200 - 2^0 */ fmul32(t1,t0,z2_100_0);
/* 2^201 - 2^1 */ fsquare(t0,t1);
/* 2^202 - 2^2 */ fsquare(t1,t0);
/* 2^250 - 2^50 */ for (i = 2;i < 50;i += 2) { fsquare(t0,t1); fsquare(t1,t0); }
/* 2^250 - 2^0 */ fmul32(t0,t1,z2_50_0);
/* 2^251 - 2^1 */ fsquare(t1,t0);
/* 2^252 - 2^2 */ fsquare(t0,t1);
/* 2^253 - 2^3 */ fsquare(t1,t0);
/* 2^254 - 2^4 */ fsquare(t0,t1);
/* 2^255 - 2^5 */ fsquare(t1,t0);
/* 2^255 - 21 */ fmul32(out,t1,z11);
}
int
curve25519_donna(u8 *mypublic, const u8 *secret, const u8 *basepoint) {
limb bp[10], x[10], z[11], zmone[10];
uint8_t e[32];
int i;
for (i = 0; i < 32; ++i) e[i] = secret[i];
e[0] &= 248;
e[31] &= 127;
e[31] |= 64;
fexpand32(bp, basepoint);
cmult32(x, z, e, bp);
crecip32(zmone, z);
fmul32(z, x, zmone);
fcontract32(mypublic, z);
return 0;
}
bits256 xoverz_donna(bits256 a)
{
limb x[10],zmone[10],z[10],bp[10],out[11]; bits256 result,basepoint;
memset(basepoint.bytes,0,sizeof(basepoint)), basepoint.bytes[0] = 9;
fexpand32(bp,basepoint.bytes);
cmult32(x,z,a.bytes,bp);
crecip32(zmone,z);
fmul32(out,x,zmone);
fcontract32(result.bytes,out);
return(result);
}
bits256 fmul_donna(bits256 a,bits256 b)
{
limb avals[10],bvals[10],z[11]; bits256 result;
fexpand32(avals,a.bytes);
fexpand32(bvals,b.bytes);
fmul32(z,avals,bvals);
fcontract32(result.bytes,z);
return(result);
}
bits256 crecip_donna(bits256 a)
{
limb avals[10],zmone[10]; bits256 result;
fexpand32(avals,a.bytes);
crecip32(zmone,avals);
fcontract32(result.bytes,zmone);
return(result);
}

1695
crypto777/curve25519.c

File diff suppressed because it is too large

30
crypto777/hmac/crypt_argchk.c

@ -0,0 +1,30 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
#include <signal.h>
/**
@file crypt_argchk.c
Perform argument checking, Tom St Denis
*/
#if (ARGTYPE == 0)
void crypt_argchk(char *v, char *s, int d)
{
fprintf(stderr, "LTC_ARGCHK '%s' failure on line %d of file %s\n",
v, d, s);
(void)raise(SIGABRT);
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_argchk.c,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2006/12/28 01:27:24 $ */

65
crypto777/hmac/hash_memory.c

@ -0,0 +1,65 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@file hash_memory.c
Hash memory helper, Tom St Denis
*/
/**
Hash a block of memory and store the digest.
@param hash The index of the hash you wish to use
@param in The data you wish to hash
@param inlen The length of the data to hash (octets)
@param out [out] Where to store the digest
@param outlen [in/out] Max size and resulting size of the digest
@return CRYPT_OK if successful
*/
int hash_memory(const struct ltc_hash_descriptor *hash, const unsigned char *in, unsigned long inlen, unsigned char *out, unsigned long *outlen)
{
hash_state *md;
int err;
LTC_ARGCHK(in != NULL);
LTC_ARGCHK(out != NULL);
LTC_ARGCHK(outlen != NULL);
if (*outlen < hash->hashsize) {
*outlen = hash->hashsize;
return CRYPT_BUFFER_OVERFLOW;
}
md = XMALLOC(sizeof(hash_state));
if (md == NULL) {
return CRYPT_MEM;
}
if ((err = hash->init(md)) != CRYPT_OK) {
goto LBL_ERR;
}
if ((err = hash->process(md, in, inlen)) != CRYPT_OK) {
goto LBL_ERR;
}
err = hash->done(md, out);
*outlen = hash->hashsize;
LBL_ERR:
#ifdef LTC_CLEAN_STACK
zeromem(md, sizeof(hash_state));
#endif
XFREE(md);
return err;
}
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/helper/hash_memory.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:23 $ */

103
crypto777/hmac/hmac_done.c

@ -0,0 +1,103 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@file hmac_done.c
LTC_HMAC support, terminate stream, Tom St Denis/Dobes Vandermeer
*/
#ifdef LTC_HMAC
#define LTC_HMAC_BLOCKSIZE hash->blocksize
/**
Terminate an LTC_HMAC session
@param hmac The LTC_HMAC state
@param out [out] The destination of the LTC_HMAC authentication tag
@param outlen [in/out] The max size and resulting size of the LTC_HMAC authentication tag
@return CRYPT_OK if successful
*/
int hmac_done(hmac_state *hmac,const struct ltc_hash_descriptor *hash,unsigned char *out,unsigned long *outlen)
{
unsigned char *buf, *isha;
unsigned long hashsize, i;
int err;
LTC_ARGCHK(hmac != NULL);
LTC_ARGCHK(out != NULL);
/* get the hash message digest size */
hashsize = hash->hashsize;
/* allocate buffers */
buf = XMALLOC(LTC_HMAC_BLOCKSIZE);
isha = XMALLOC(hashsize);
if (buf == NULL || isha == NULL) {
if (buf != NULL) {
XFREE(buf);
}
if (isha != NULL) {
XFREE(isha);
}
return CRYPT_MEM;
}
/* Get the hash of the first LTC_HMAC vector plus the data */
if ((err = hash->done(&hmac->md, isha)) != CRYPT_OK) {
goto LBL_ERR;
}
/* Create the second LTC_HMAC vector vector for step (3) */
for(i=0; i < LTC_HMAC_BLOCKSIZE; i++) {
buf[i] = hmac->key[i] ^ 0x5C;
}
/* Now calculate the "outer" hash for step (5), (6), and (7) */
if ((err = hash->init(&hmac->md)) != CRYPT_OK) {
goto LBL_ERR;
}
if ((err = hash->process(&hmac->md, buf, LTC_HMAC_BLOCKSIZE)) != CRYPT_OK) {
goto LBL_ERR;
}
if ((err = hash->process(&hmac->md, isha, hashsize)) != CRYPT_OK) {
goto LBL_ERR;
}
if ((err = hash->done(&hmac->md, buf)) != CRYPT_OK) {
goto LBL_ERR;
}
/* copy to output */
for (i = 0; i < hashsize && i < *outlen; i++) {
out[i] = buf[i];
}
*outlen = i;
err = CRYPT_OK;
LBL_ERR:
XFREE(hmac->key);
#ifdef LTC_CLEAN_STACK
zeromem(isha, hashsize);
zeromem(buf, hashsize);
zeromem(hmac, sizeof(*hmac));
#endif
XFREE(isha);
XFREE(buf);
return err;
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/mac/hmac/hmac_done.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2007/05/12 14:37:41 $ */

87
crypto777/hmac/hmac_file.c

@ -0,0 +1,87 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@file hmac_file.c
LTC_HMAC support, process a file, Tom St Denis/Dobes Vandermeer
*/
#ifdef LTC_HMAC
/**
LTC_HMAC a file
@param hash The index of the hash you wish to use
@param fname The name of the file you wish to LTC_HMAC
@param key The secret key
@param keylen The length of the secret key
@param out [out] The LTC_HMAC authentication tag
@param outlen [in/out] The max size and resulting size of the authentication tag
@return CRYPT_OK if successful, CRYPT_NOP if file support has been disabled
*/
int hmac_file(const struct ltc_hash_descriptor *hash, const char *fname, const unsigned char *key, unsigned long keylen,unsigned char *out, unsigned long *outlen)
{
#ifdef LTC_NO_FILE
return CRYPT_NOP;
#else
hmac_state hmac;
FILE *in;
unsigned char buf[512];
size_t x;
int err;
LTC_ARGCHK(fname != NULL);
LTC_ARGCHK(key != NULL);
LTC_ARGCHK(out != NULL);
LTC_ARGCHK(outlen != NULL);
if ((err = hmac_init(&hmac, hash, key, keylen)) != CRYPT_OK) {
return err;
}
in = fopen(fname, "rb");
if (in == NULL) {
return CRYPT_FILE_NOTFOUND;
}
/* process the file contents */
do {
x = fread(buf, 1, sizeof(buf), in);
if ((err = hmac_process(&hmac, hash, buf, (unsigned long)x)) != CRYPT_OK) {
/* we don't trap this error since we're already returning an error! */
fclose(in);
return err;
}
} while (x == sizeof(buf));
if (fclose(in) != 0) {
return CRYPT_ERROR;
}
/* get final hmac */
if ((err = hmac_done(&hmac, hash, out, outlen)) != CRYPT_OK) {
return err;
}
#ifdef LTC_CLEAN_STACK
/* clear memory */
zeromem(buf, sizeof(buf));
#endif
return CRYPT_OK;
#endif
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/mac/hmac/hmac_file.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2007/05/12 14:37:41 $ */

108
crypto777/hmac/hmac_init.c

@ -0,0 +1,108 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@file hmac_init.c
LTC_HMAC support, initialize state, Tom St Denis/Dobes Vandermeer
*/
#ifdef LTC_HMAC
#define LTC_HMAC_BLOCKSIZE hash->blocksize
/**
Initialize an LTC_HMAC context.
@param hmac The LTC_HMAC state
@param hash The index of the hash you want to use
@param key The secret key
@param keylen The length of the secret key (octets)
@return CRYPT_OK if successful
*/
int hmac_init(hmac_state *hmac,const struct ltc_hash_descriptor *hash, const unsigned char *key, unsigned long keylen)
{
unsigned char *buf;
unsigned long hashsize;
unsigned long i, z;
int err;
LTC_ARGCHK(hmac != NULL);
LTC_ARGCHK(key != NULL);
//hmac->hash = hash;
hashsize = hash->hashsize;
/* valid key length? */
if (keylen == 0) {
return CRYPT_INVALID_KEYSIZE;
}
/* allocate ram for buf */
buf = XMALLOC(LTC_HMAC_BLOCKSIZE);
if (buf == NULL) {
return CRYPT_MEM;
}
/* allocate memory for key */
hmac->key = XMALLOC(LTC_HMAC_BLOCKSIZE);
if (hmac->key == NULL) {
XFREE(buf);
return CRYPT_MEM;
}
/* (1) make sure we have a large enough key */
if(keylen > LTC_HMAC_BLOCKSIZE) {
z = LTC_HMAC_BLOCKSIZE;
if ((err = hash_memory(hash, key, keylen, hmac->key, &z)) != CRYPT_OK) {
goto LBL_ERR;
}
if(hashsize < LTC_HMAC_BLOCKSIZE) {
zeromem((hmac->key) + hashsize, (size_t)(LTC_HMAC_BLOCKSIZE - hashsize));
}
keylen = hashsize;
} else {
XMEMCPY(hmac->key, key, (size_t)keylen);
if(keylen < LTC_HMAC_BLOCKSIZE) {
zeromem((hmac->key) + keylen, (size_t)(LTC_HMAC_BLOCKSIZE - keylen));
}
}
/* Create the initial vector for step (3) */
for(i=0; i < LTC_HMAC_BLOCKSIZE; i++) {
buf[i] = hmac->key[i] ^ 0x36;
}
/* Pre-pend that to the hash data */
if ((err = hash->init(&hmac->md)) != CRYPT_OK) {
goto LBL_ERR;
}
if ((err = hash->process(&hmac->md, buf, LTC_HMAC_BLOCKSIZE)) != CRYPT_OK) {
goto LBL_ERR;
}
goto done;
LBL_ERR:
/* free the key since we failed */
XFREE(hmac->key);
done:
#ifdef LTC_CLEAN_STACK
zeromem(buf, LTC_HMAC_BLOCKSIZE);
#endif
XFREE(buf);
return err;
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/mac/hmac/hmac_init.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2007/05/12 14:37:41 $ */

83
crypto777/hmac/hmac_memory.c

@ -0,0 +1,83 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@file hmac_memory.c
LTC_HMAC support, process a block of memory, Tom St Denis/Dobes Vandermeer
*/
#ifdef LTC_HMAC
/**
LTC_HMAC a block of memory to produce the authentication tag
@param hash The index of the hash to use
@param key The secret key
@param keylen The length of the secret key (octets)
@param in The data to LTC_HMAC
@param inlen The length of the data to LTC_HMAC (octets)
@param out [out] Destination of the authentication tag
@param outlen [in/out] Max size and resulting size of authentication tag
@return CRYPT_OK if successful
*/
int hmac_memory(const struct ltc_hash_descriptor *hash,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen)
{
hmac_state *hmac;
int err;
LTC_ARGCHK(key != NULL);
LTC_ARGCHK(in != NULL);
LTC_ARGCHK(out != NULL);
LTC_ARGCHK(outlen != NULL);
/* is there a descriptor? */
if (hash->hmac_block != NULL) {
return hash->hmac_block(key, keylen, in, inlen, out, outlen);
}
/* nope, so call the hmac functions */
/* allocate ram for hmac state */
hmac = XMALLOC(sizeof(hmac_state));
if (hmac == NULL) {
return CRYPT_MEM;
}
if ((err = hmac_init(hmac, hash, key, keylen)) != CRYPT_OK) {
goto LBL_ERR;
}
if ((err = hmac_process(hmac, hash, in, inlen)) != CRYPT_OK) {
goto LBL_ERR;
}
if ((err = hmac_done(hmac, hash, out, outlen)) != CRYPT_OK) {
goto LBL_ERR;
}
err = CRYPT_OK;
LBL_ERR:
#ifdef LTC_CLEAN_STACK
zeromem(hmac, sizeof(hmac_state));
#endif
XFREE(hmac);
return err;
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/mac/hmac/hmac_memory.c,v $ */
/* $Revision: 1.8 $ */
/* $Date: 2007/05/12 14:37:41 $ */

92
crypto777/hmac/hmac_memory_multi.c

@ -0,0 +1,92 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
#include <stdarg.h>
/**
@file hmac_memory_multi.c
LTC_HMAC support, process multiple blocks of memory, Tom St Denis/Dobes Vandermeer
*/
#ifdef LTC_HMAC
/**
LTC_HMAC multiple blocks of memory to produce the authentication tag
@param hash The index of the hash to use
@param key The secret key
@param keylen The length of the secret key (octets)
@param out [out] Destination of the authentication tag
@param outlen [in/out] Max size and resulting size of authentication tag
@param in The data to LTC_HMAC
@param inlen The length of the data to LTC_HMAC (octets)
@param ... tuples of (data,len) pairs to LTC_HMAC, terminated with a (NULL,x) (x=don't care)
@return CRYPT_OK if successful
*/
int hmac_memory_multi(struct ltc_hash_descriptor *hash,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...)
{
hmac_state *hmac;
int err;
va_list args;
const unsigned char *curptr;
unsigned long curlen;
LTC_ARGCHK(key != NULL);
LTC_ARGCHK(in != NULL);
LTC_ARGCHK(out != NULL);
LTC_ARGCHK(outlen != NULL);
/* allocate ram for hmac state */
hmac = XMALLOC(sizeof(hmac_state));
if (hmac == NULL) {
return CRYPT_MEM;
}
if ((err = hmac_init(hmac, hash, key, keylen)) != CRYPT_OK) {
goto LBL_ERR;
}
va_start(args, inlen);
curptr = in;
curlen = inlen;
for (;;) {
/* process buf */
if ((err = hmac_process(hmac, hash, curptr, curlen)) != CRYPT_OK) {
goto LBL_ERR;
}
/* step to next */
curptr = va_arg(args, const unsigned char*);
if (curptr == NULL) {
break;
}
curlen = va_arg(args, unsigned long);
}
if ((err = hmac_done(hmac, hash, out, outlen)) != CRYPT_OK) {
goto LBL_ERR;
}
LBL_ERR:
#ifdef LTC_CLEAN_STACK
zeromem(hmac, sizeof(hmac_state));
#endif
XFREE(hmac);
va_end(args);
return err;
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/mac/hmac/hmac_memory_multi.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2007/05/12 14:37:41 $ */

39
crypto777/hmac/hmac_process.c

@ -0,0 +1,39 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@file hmac_process.c
LTC_HMAC support, process data, Tom St Denis/Dobes Vandermeer
*/
#ifdef LTC_HMAC
/**
Process data through LTC_HMAC
@param hmac The hmac state
@param in The data to send through LTC_HMAC
@param inlen The length of the data to LTC_HMAC (octets)
@return CRYPT_OK if successful
*/
int hmac_process(hmac_state *hmac,const struct ltc_hash_descriptor *hash,const unsigned char *in, unsigned long inlen)
{
LTC_ARGCHK(hmac != NULL);
LTC_ARGCHK(in != NULL);
return hash->process(&hmac->md, in, inlen);
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/mac/hmac/hmac_process.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2007/05/12 14:37:41 $ */

318
crypto777/hmac/hmac_test.c

@ -0,0 +1,318 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@file hmac_test.c
LTC_HMAC support, self-test, Tom St Denis/Dobes Vandermeer
*/
#ifdef LTC_HMAC
#define LTC_HMAC_BLOCKSIZE hash_descriptor[hash].blocksize
/*
TEST CASES SOURCE:
Network Working Group P. Cheng
Request for Comments: 2202 IBM
Category: Informational R. Glenn
NIST
September 1997
Test Cases for LTC_HMAC-LTC_MD5 and LTC_HMAC-LTC_SHA-1
*/
/**
LTC_HMAC self-test
@return CRYPT_OK if successful, CRYPT_NOP if tests have been disabled.
*/
#ifdef notow
int hmac_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
unsigned char digest[MAXBLOCKSIZE];
int i;
static const struct hmac_test_case {
int num;
char *algo;
unsigned char key[128];
unsigned long keylen;
unsigned char data[128];
unsigned long datalen;
unsigned char digest[MAXBLOCKSIZE];
} cases[] = {
/*
3. Test Cases for LTC_HMAC-LTC_SHA-1
test_case = 1
key = 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c
key_len = 20
data = "Hi Ther 20
digest = 0x4c1a03424b55e07fe7f27be1d58bb9324a9a5a04
digest-96 = 0x4c1a03424b55e07fe7f27be1
*/
{ 5, "sha1",
{0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
0x0c, 0x0c, 0x0c, 0x0c}, 20,
"Test With Truncation", 20,
{0x4c, 0x1a, 0x03, 0x42, 0x4b, 0x55, 0xe0, 0x7f, 0xe7, 0xf2,
0x7b, 0xe1, 0xd5, 0x8b, 0xb9, 0x32, 0x4a, 0x9a, 0x5a, 0x04} },
/*
test_case = 6
key = 0xaa repeated 80 times
key_len = 80
data = "Test Using Larger Than Block-Size Key - Hash Key First"
data_len = 54
digest = 0xaa4ae5e15272d00e95705637ce8a3b55ed402112
*/
{ 6, "sha1",
{0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa}, 80,
"Test Using Larger Than Block-Size Key - Hash Key First", 54,
{0xaa, 0x4a, 0xe5, 0xe1, 0x52, 0x72, 0xd0, 0x0e,
0x95, 0x70, 0x56, 0x37, 0xce, 0x8a, 0x3b, 0x55,
0xed, 0x40, 0x21, 0x12} },
/*
test_case = 7
key = 0xaa repeated 80 times
key_len = 80
data = "Test Using Larger Than Block-Size Key and Larger
Than One Block-Size Data"
data_len = 73
digest = 0xe8e99d0f45237d786d6bbaa7965c7808bbff1a91
*/
{ 7, "sha1",
{0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa}, 80,
"Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data", 73,
{0xe8, 0xe9, 0x9d, 0x0f, 0x45, 0x23, 0x7d, 0x78, 0x6d,
0x6b, 0xba, 0xa7, 0x96, 0x5c, 0x78, 0x08, 0xbb, 0xff, 0x1a, 0x91} },
/*
2. Test Cases for LTC_HMAC-LTC_MD5
test_case = 1
key = 0x0b 0b 0b 0b
0b 0b 0b 0b
0b 0b 0b 0b
0b 0b 0b 0b
key_len = 16
data = "Hi There"
data_len = 8
digest = 0x92 94 72 7a
36 38 bb 1c
13 f4 8e f8
15 8b fc 9d
*/
{ 1, "md5",
{0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b}, 16,
"Hi There", 8,
{0x92, 0x94, 0x72, 0x7a, 0x36, 0x38, 0xbb, 0x1c,
0x13, 0xf4, 0x8e, 0xf8, 0x15, 0x8b, 0xfc, 0x9d} },
/*
test_case = 2
key = "Jefe"
key_len = 4
data = "what do ya want for nothing?"
data_len = 28
digest = 0x750c783e6ab0b503eaa86e310a5db738
*/
{ 2, "md5",
"Jefe", 4,
"what do ya want for nothing?", 28,
{0x75, 0x0c, 0x78, 0x3e, 0x6a, 0xb0, 0xb5, 0x03,
0xea, 0xa8, 0x6e, 0x31, 0x0a, 0x5d, 0xb7, 0x38} },
/*
test_case = 3
key = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
key_len 16
data = 0xdd repeated 50 times
data_len = 50
digest = 0x56be34521d144c88dbb8c733f0e8b3f6
*/
{ 3, "md5",
{0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa}, 16,
{0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd}, 50,
{0x56, 0xbe, 0x34, 0x52, 0x1d, 0x14, 0x4c, 0x88,
0xdb, 0xb8, 0xc7, 0x33, 0xf0, 0xe8, 0xb3, 0xf6} },
/*
test_case = 4
key = 0x0102030405060708090a0b0c0d0e0f10111213141516171819
key_len 25
data = 0xcd repeated 50 times
data_len = 50
digest = 0x697eaf0aca3a3aea3a75164746ffaa79
*/
{ 4, "md5",
{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
0x15, 0x16, 0x17, 0x18, 0x19}, 25,
{0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd}, 50,
{0x69, 0x7e, 0xaf, 0x0a, 0xca, 0x3a, 0x3a, 0xea,
0x3a, 0x75, 0x16, 0x47, 0x46, 0xff, 0xaa, 0x79} },
/*
test_case = 5
key = 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c
key_len = 16
data = "Test With Truncation"
data_len = 20
digest = 0x56461ef2342edc00f9bab995690efd4c
digest-96 0x56461ef2342edc00f9bab995
*/
{ 5, "md5",
{0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c}, 16,
"Test With Truncation", 20,
{0x56, 0x46, 0x1e, 0xf2, 0x34, 0x2e, 0xdc, 0x00,
0xf9, 0xba, 0xb9, 0x95, 0x69, 0x0e, 0xfd, 0x4c} },
/*
test_case = 6
key = 0xaa repeated 80 times
key_len = 80
data = "Test Using Larger Than Block-Size Key - Hash
Key First"
data_len = 54
digest = 0x6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd
*/
{ 6, "md5",
{0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa}, 80,
"Test Using Larger Than Block-Size Key - Hash Key First", 54,
{0x6b, 0x1a, 0xb7, 0xfe, 0x4b, 0xd7, 0xbf, 0x8f,
0x0b, 0x62, 0xe6, 0xce, 0x61, 0xb9, 0xd0, 0xcd} },
/*
test_case = 7
key = 0xaa repeated 80 times
key_len = 80
data = "Test Using Larger Than Block-Size Key and Larger
Than One Block-Size Data"
data_len = 73
digest = 0x6f630fad67cda0ee1fb1f562db3aa53e
*/
{ 7, "md5",
{0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa}, 80,
"Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data", 73,
{0x6f, 0x63, 0x0f, 0xad, 0x67, 0xcd, 0xa0, 0xee,
0x1f, 0xb1, 0xf5, 0x62, 0xdb, 0x3a, 0xa5, 0x3e} }
};
unsigned long outlen;
int err;
int tested=0,failed=0;
for(i=0; i < (int)(sizeof(cases) / sizeof(cases[0])); i++) {
int hash = find_hash(cases[i].algo);
if (hash == -1) continue;
++tested;
outlen = sizeof(digest);
if((err = hmac_memory(hash, cases[i].key, cases[i].keylen, cases[i].data, cases[i].datalen, digest, &outlen)) != CRYPT_OK) {
#if 0
printf("LTC_HMAC-%s test #%d, %s\n", cases[i].algo, cases[i].num, error_to_string(err));
#endif
return err;
}
if(XMEMCMP(digest, cases[i].digest, (size_t)hash_descriptor[hash].hashsize) != 0) {
failed++;
#if 0
unsigned int j;
printf("\nLTC_HMAC-%s test #%d:\n", cases[i].algo, cases[i].num);
printf( "Result: 0x");
for(j=0; j < hash_descriptor[hash].hashsize; j++) {
printf("%2x ", digest[j]);
}
printf("\nCorrect: 0x");
for(j=0; j < hash_descriptor[hash].hashsize; j++) {
printf("%2x ", cases[i].digest[j]);
}
printf("\n");
return CRYPT_ERROR;
#endif
} else {
/* printf("LTC_HMAC-%s test #%d: Passed\n", cases[i].algo, cases[i].num); */
}
}
if (failed != 0) {
return CRYPT_FAIL_TESTVECTOR;
} else if (tested == 0) {
return CRYPT_NOP;
} else {
return CRYPT_OK;
}
#endif
}
#endif
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/mac/hmac/hmac_test.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:37:41 $ */

262
crypto777/hmac/md2.c

@ -0,0 +1,262 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@param md2.c
LTC_MD2 (RFC 1319) hash function implementation by Tom St Denis
*/
#ifdef LTC_MD2
const struct ltc_hash_descriptor md2_desc =
{
"md2",
7,
16,
16,
/* OID */
{ 1, 2, 840, 113549, 2, 2, },
6,
&md2_init,
&md2_process,
&md2_done,
&md2_test,
NULL
};
static const unsigned char PI_SUBST[256] = {
41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6,
19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188,
76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24,
138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251,
245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63,
148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50,
39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165,
181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210,
150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157,
112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27,
96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15,
85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197,
234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65,
129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123,
8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233,
203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228,
166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237,
31, 26, 219, 153, 141, 51, 159, 17, 131, 20
};
/* adds 16 bytes to the checksum */
static void md2_update_chksum(hash_state *md)
{
int j;
unsigned char L;
L = md->md2.chksum[15];
for (j = 0; j < 16; j++) {
/* caution, the RFC says its "C[j] = S[M[i*16+j] xor L]" but the reference source code [and test vectors] say
otherwise.
*/
L = (md->md2.chksum[j] ^= PI_SUBST[(int)(md->md2.buf[j] ^ L)] & 255);
}
}
static void md2_compress(hash_state *md)
{
int j, k;
unsigned char t;
/* copy block */
for (j = 0; j < 16; j++) {
md->md2.X[16+j] = md->md2.buf[j];
md->md2.X[32+j] = md->md2.X[j] ^ md->md2.X[16+j];
}
t = (unsigned char)0;
/* do 18 rounds */
for (j = 0; j < 18; j++) {
for (k = 0; k < 48; k++) {
t = (md->md2.X[k] ^= PI_SUBST[(int)(t & 255)]);
}
t = (t + (unsigned char)j) & 255;
}
}
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int md2_init(hash_state *md)
{
LTC_ARGCHK(md != NULL);
/* LTC_MD2 uses a zero'ed state... */
zeromem(md->md2.X, sizeof(md->md2.X));
zeromem(md->md2.chksum, sizeof(md->md2.chksum));
zeromem(md->md2.buf, sizeof(md->md2.buf));
md->md2.curlen = 0;
return CRYPT_OK;
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
int md2_process(hash_state *md, const unsigned char *in, unsigned long inlen)
{
unsigned long n;
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(in != NULL);
if (md-> md2 .curlen > sizeof(md-> md2 .buf)) {
return CRYPT_INVALID_ARG;
}
while (inlen > 0) {
n = MIN(inlen, (16 - md->md2.curlen));
XMEMCPY(md->md2.buf + md->md2.curlen, in, (size_t)n);
md->md2.curlen += n;
in += n;
inlen -= n;
/* is 16 bytes full? */
if (md->md2.curlen == 16) {
md2_compress(md);
md2_update_chksum(md);
md->md2.curlen = 0;
}
}
return CRYPT_OK;
}
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (16 bytes)
@return CRYPT_OK if successful
*/
int md2_done(hash_state * md, unsigned char *out)
{
unsigned long i, k;
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
if (md->md2.curlen >= sizeof(md->md2.buf)) {
return CRYPT_INVALID_ARG;
}
/* pad the message */
k = 16 - md->md2.curlen;
for (i = md->md2.curlen; i < 16; i++) {
md->md2.buf[i] = (unsigned char)k;
}
/* hash and update */
md2_compress(md);
md2_update_chksum(md);
/* hash checksum */
XMEMCPY(md->md2.buf, md->md2.chksum, 16);
md2_compress(md);
/* output is lower 16 bytes of X */
XMEMCPY(out, md->md2.X, 16);
#ifdef LTC_CLEAN_STACK
zeromem(md, sizeof(hash_state));
#endif
return CRYPT_OK;
}
void calc_md2(char *str,uint8_t *digest,uint8_t *message,int32_t len)
{
int init_hexbytes_noT(char *hexbytes,unsigned char *message,long len);
hash_state md;
md2_init(&md);
md2_process(&md,message,len);
md2_done(&md,digest);
if ( str != 0 )
init_hexbytes_noT(str,digest,16);
}
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int md2_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct {
char *msg;
unsigned char md[16];
} tests[] = {
{ "",
{0x83,0x50,0xe5,0xa3,0xe2,0x4c,0x15,0x3d,
0xf2,0x27,0x5c,0x9f,0x80,0x69,0x27,0x73
}
},
{ "a",
{0x32,0xec,0x01,0xec,0x4a,0x6d,0xac,0x72,
0xc0,0xab,0x96,0xfb,0x34,0xc0,0xb5,0xd1
}
},
{ "message digest",
{0xab,0x4f,0x49,0x6b,0xfb,0x2a,0x53,0x0b,
0x21,0x9f,0xf3,0x30,0x31,0xfe,0x06,0xb0
}
},
{ "abcdefghijklmnopqrstuvwxyz",
{0x4e,0x8d,0xdf,0xf3,0x65,0x02,0x92,0xab,
0x5a,0x41,0x08,0xc3,0xaa,0x47,0x94,0x0b
}
},
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
{0xda,0x33,0xde,0xf2,0xa4,0x2d,0xf1,0x39,
0x75,0x35,0x28,0x46,0xc3,0x03,0x38,0xcd
}
},
{ "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
{0xd5,0x97,0x6f,0x79,0xd8,0x3d,0x3a,0x0d,
0xc9,0x80,0x6c,0x3c,0x66,0xf3,0xef,0xd8
}
}
};
int i;
hash_state md;
unsigned char buf[16];
for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
md2_init(&md);
md2_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
md2_done(&md, buf);
if (XMEMCMP(buf, tests[i].md, 16) != 0) {
return CRYPT_FAIL_TESTVECTOR;
}
}
return CRYPT_OK;
#endif
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/md2.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */

325
crypto777/hmac/md4.c

@ -0,0 +1,325 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@param md4.c
Submitted by Dobes Vandermeer (dobes@smartt.com)
*/
#ifdef LTC_MD4
const struct ltc_hash_descriptor md4_desc =
{
"md4",
6,
16,
64,
/* OID */
{ 1, 2, 840, 113549, 2, 4, },
6,
&md4_init,
&md4_process,
&md4_done,
&md4_test,
NULL
};
#define S11 3
#define S12 7
#define S13 11
#define S14 19
#define S21 3
#define S22 5
#define S23 9
#define S24 13
#define S31 3
#define S32 9
#define S33 11
#define S34 15
/* F, G and H are basic LTC_MD4 functions. */
#define F(x, y, z) (z ^ (x & (y ^ z)))
#define G(x, y, z) ((x & y) | (z & (x | y)))
#define H(x, y, z) ((x) ^ (y) ^ (z))
/* ROTATE_LEFT rotates x left n bits. */
#define ROTATE_LEFT(x, n) ROLc(x, n)
/* FF, GG and HH are transformations for rounds 1, 2 and 3 */
/* Rotation is separate from addition to prevent recomputation */
#define FF(a, b, c, d, x, s) { \
(a) += F ((b), (c), (d)) + (x); \
(a) = ROTATE_LEFT ((a), (s)); \
}
#define GG(a, b, c, d, x, s) { \
(a) += G ((b), (c), (d)) + (x) + 0x5a827999UL; \
(a) = ROTATE_LEFT ((a), (s)); \
}
#define HH(a, b, c, d, x, s) { \
(a) += H ((b), (c), (d)) + (x) + 0x6ed9eba1UL; \
(a) = ROTATE_LEFT ((a), (s)); \
}
#ifdef LTC_CLEAN_STACK
static int _md4_compress(hash_state *md, unsigned char *buf)
#else
static int md4_compress(hash_state *md, unsigned char *buf)
#endif
{
ulong32 x[16], a, b, c, d;
int i;
/* copy state */
a = md->md4.state[0];
b = md->md4.state[1];
c = md->md4.state[2];
d = md->md4.state[3];
/* copy the state into 512-bits into W[0..15] */
for (i = 0; i < 16; i++) {
LOAD32L(x[i], buf + (4*i));
}
/* Round 1 */
FF (a, b, c, d, x[ 0], S11); /* 1 */
FF (d, a, b, c, x[ 1], S12); /* 2 */
FF (c, d, a, b, x[ 2], S13); /* 3 */
FF (b, c, d, a, x[ 3], S14); /* 4 */
FF (a, b, c, d, x[ 4], S11); /* 5 */
FF (d, a, b, c, x[ 5], S12); /* 6 */
FF (c, d, a, b, x[ 6], S13); /* 7 */
FF (b, c, d, a, x[ 7], S14); /* 8 */
FF (a, b, c, d, x[ 8], S11); /* 9 */
FF (d, a, b, c, x[ 9], S12); /* 10 */
FF (c, d, a, b, x[10], S13); /* 11 */
FF (b, c, d, a, x[11], S14); /* 12 */
FF (a, b, c, d, x[12], S11); /* 13 */
FF (d, a, b, c, x[13], S12); /* 14 */
FF (c, d, a, b, x[14], S13); /* 15 */
FF (b, c, d, a, x[15], S14); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[ 0], S21); /* 17 */
GG (d, a, b, c, x[ 4], S22); /* 18 */
GG (c, d, a, b, x[ 8], S23); /* 19 */
GG (b, c, d, a, x[12], S24); /* 20 */
GG (a, b, c, d, x[ 1], S21); /* 21 */
GG (d, a, b, c, x[ 5], S22); /* 22 */
GG (c, d, a, b, x[ 9], S23); /* 23 */
GG (b, c, d, a, x[13], S24); /* 24 */
GG (a, b, c, d, x[ 2], S21); /* 25 */
GG (d, a, b, c, x[ 6], S22); /* 26 */
GG (c, d, a, b, x[10], S23); /* 27 */
GG (b, c, d, a, x[14], S24); /* 28 */
GG (a, b, c, d, x[ 3], S21); /* 29 */
GG (d, a, b, c, x[ 7], S22); /* 30 */
GG (c, d, a, b, x[11], S23); /* 31 */
GG (b, c, d, a, x[15], S24); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[ 0], S31); /* 33 */
HH (d, a, b, c, x[ 8], S32); /* 34 */
HH (c, d, a, b, x[ 4], S33); /* 35 */
HH (b, c, d, a, x[12], S34); /* 36 */
HH (a, b, c, d, x[ 2], S31); /* 37 */
HH (d, a, b, c, x[10], S32); /* 38 */
HH (c, d, a, b, x[ 6], S33); /* 39 */
HH (b, c, d, a, x[14], S34); /* 40 */
HH (a, b, c, d, x[ 1], S31); /* 41 */
HH (d, a, b, c, x[ 9], S32); /* 42 */
HH (c, d, a, b, x[ 5], S33); /* 43 */
HH (b, c, d, a, x[13], S34); /* 44 */
HH (a, b, c, d, x[ 3], S31); /* 45 */
HH (d, a, b, c, x[11], S32); /* 46 */
HH (c, d, a, b, x[ 7], S33); /* 47 */
HH (b, c, d, a, x[15], S34); /* 48 */
/* Update our state */
md->md4.state[0] = md->md4.state[0] + a;
md->md4.state[1] = md->md4.state[1] + b;
md->md4.state[2] = md->md4.state[2] + c;
md->md4.state[3] = md->md4.state[3] + d;
return CRYPT_OK;
}
#ifdef LTC_CLEAN_STACK
static int md4_compress(hash_state *md, unsigned char *buf)
{
int err;
err = _md4_compress(md, buf);
burn_stack(sizeof(ulong32) * 20 + sizeof(int));
return err;
}
#endif
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int md4_init(hash_state * md)
{
LTC_ARGCHK(md != NULL);
md->md4.state[0] = 0x67452301UL;
md->md4.state[1] = 0xefcdab89UL;
md->md4.state[2] = 0x98badcfeUL;
md->md4.state[3] = 0x10325476UL;
md->md4.length = 0;
md->md4.curlen = 0;
return CRYPT_OK;
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
HASH_PROCESS(md4_process, md4_compress, md4, 64)
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (16 bytes)
@return CRYPT_OK if successful
*/
int md4_done(hash_state * md, unsigned char *out)
{
int i;
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
if (md->md4.curlen >= sizeof(md->md4.buf)) {
return CRYPT_INVALID_ARG;
}
/* increase the length of the message */
md->md4.length += md->md4.curlen * 8;
/* append the '1' bit */
md->md4.buf[md->md4.curlen++] = (unsigned char)0x80;
/* if the length is currently above 56 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (md->md4.curlen > 56) {
while (md->md4.curlen < 64) {
md->md4.buf[md->md4.curlen++] = (unsigned char)0;
}
md4_compress(md, md->md4.buf);
md->md4.curlen = 0;
}
/* pad upto 56 bytes of zeroes */
while (md->md4.curlen < 56) {
md->md4.buf[md->md4.curlen++] = (unsigned char)0;
}
/* store length */
STORE64L(md->md4.length, md->md4.buf+56);
md4_compress(md, md->md4.buf);
/* copy output */
for (i = 0; i < 4; i++) {
STORE32L(md->md4.state[i], out+(4*i));
}
#ifdef LTC_CLEAN_STACK
zeromem(md, sizeof(hash_state));
#endif
return CRYPT_OK;
}
void calc_md4(char *str,uint8_t *digest,uint8_t *message,int32_t len)
{
int init_hexbytes_noT(char *hexbytes,unsigned char *message,long len);
hash_state md;
md4_init(&md);
md4_process(&md,message,len);
md4_done(&md,digest);
if ( str != 0 )
init_hexbytes_noT(str,digest,16);
}
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int md4_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct md4_test_case {
char *input;
unsigned char digest[16];
} cases[] = {
{ "",
{0x31, 0xd6, 0xcf, 0xe0, 0xd1, 0x6a, 0xe9, 0x31,
0xb7, 0x3c, 0x59, 0xd7, 0xe0, 0xc0, 0x89, 0xc0} },
{ "a",
{0xbd, 0xe5, 0x2c, 0xb3, 0x1d, 0xe3, 0x3e, 0x46,
0x24, 0x5e, 0x05, 0xfb, 0xdb, 0xd6, 0xfb, 0x24} },
{ "abc",
{0xa4, 0x48, 0x01, 0x7a, 0xaf, 0x21, 0xd8, 0x52,
0x5f, 0xc1, 0x0a, 0xe8, 0x7a, 0xa6, 0x72, 0x9d} },
{ "message digest",
{0xd9, 0x13, 0x0a, 0x81, 0x64, 0x54, 0x9f, 0xe8,
0x18, 0x87, 0x48, 0x06, 0xe1, 0xc7, 0x01, 0x4b} },
{ "abcdefghijklmnopqrstuvwxyz",
{0xd7, 0x9e, 0x1c, 0x30, 0x8a, 0xa5, 0xbb, 0xcd,
0xee, 0xa8, 0xed, 0x63, 0xdf, 0x41, 0x2d, 0xa9} },
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
{0x04, 0x3f, 0x85, 0x82, 0xf2, 0x41, 0xdb, 0x35,
0x1c, 0xe6, 0x27, 0xe1, 0x53, 0xe7, 0xf0, 0xe4} },
{ "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
{0xe3, 0x3b, 0x4d, 0xdc, 0x9c, 0x38, 0xf2, 0x19,
0x9c, 0x3e, 0x7b, 0x16, 0x4f, 0xcc, 0x05, 0x36} },
};
int i;
hash_state md;
unsigned char digest[16];
for(i = 0; i < (int)(sizeof(cases) / sizeof(cases[0])); i++) {
md4_init(&md);
md4_process(&md, (unsigned char *)cases[i].input, (unsigned long)strlen(cases[i].input));
md4_done(&md, digest);
if (XMEMCMP(digest, cases[i].digest, 16) != 0) {
return CRYPT_FAIL_TESTVECTOR;
}
}
return CRYPT_OK;
#endif
}
#undef F
#undef G
#undef H
#undef FF
#undef GG
#undef HH
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/md4.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */

380
crypto777/hmac/md5.c

@ -0,0 +1,380 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@file md5.c
LTC_MD5 hash function by Tom St Denis
*/
#ifdef LTC_MD5
const struct ltc_hash_descriptor md5_desc =
{
"md5",
3,
16,
64,
/* OID */
{ 1, 2, 840, 113549, 2, 5, },
6,
&md5_init,
&md5_process,
&md5_done,
&md5_test,
NULL
};
#define F(x,y,z) (z ^ (x & (y ^ z)))
#define G(x,y,z) (y ^ (z & (y ^ x)))
#define H(x,y,z) (x^y^z)
#define I(x,y,z) (y^(x|(~z)))
#ifdef LTC_SMALL_CODE
#define FF(a,b,c,d,M,s,t) \
a = (a + F(b,c,d) + M + t); a = ROL(a, s) + b;
#define GG(a,b,c,d,M,s,t) \
a = (a + G(b,c,d) + M + t); a = ROL(a, s) + b;
#define HH(a,b,c,d,M,s,t) \
a = (a + H(b,c,d) + M + t); a = ROL(a, s) + b;
#define II(a,b,c,d,M,s,t) \
a = (a + I(b,c,d) + M + t); a = ROL(a, s) + b;
static const unsigned char Worder[64] = {
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,
5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,
0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9
};
static const unsigned char Rorder[64] = {
7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,
5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,
4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,
6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21
};
static const ulong32 Korder[64] = {
0xd76aa478UL, 0xe8c7b756UL, 0x242070dbUL, 0xc1bdceeeUL, 0xf57c0fafUL, 0x4787c62aUL, 0xa8304613UL, 0xfd469501UL,
0x698098d8UL, 0x8b44f7afUL, 0xffff5bb1UL, 0x895cd7beUL, 0x6b901122UL, 0xfd987193UL, 0xa679438eUL, 0x49b40821UL,
0xf61e2562UL, 0xc040b340UL, 0x265e5a51UL, 0xe9b6c7aaUL, 0xd62f105dUL, 0x02441453UL, 0xd8a1e681UL, 0xe7d3fbc8UL,
0x21e1cde6UL, 0xc33707d6UL, 0xf4d50d87UL, 0x455a14edUL, 0xa9e3e905UL, 0xfcefa3f8UL, 0x676f02d9UL, 0x8d2a4c8aUL,
0xfffa3942UL, 0x8771f681UL, 0x6d9d6122UL, 0xfde5380cUL, 0xa4beea44UL, 0x4bdecfa9UL, 0xf6bb4b60UL, 0xbebfbc70UL,
0x289b7ec6UL, 0xeaa127faUL, 0xd4ef3085UL, 0x04881d05UL, 0xd9d4d039UL, 0xe6db99e5UL, 0x1fa27cf8UL, 0xc4ac5665UL,
0xf4292244UL, 0x432aff97UL, 0xab9423a7UL, 0xfc93a039UL, 0x655b59c3UL, 0x8f0ccc92UL, 0xffeff47dUL, 0x85845dd1UL,
0x6fa87e4fUL, 0xfe2ce6e0UL, 0xa3014314UL, 0x4e0811a1UL, 0xf7537e82UL, 0xbd3af235UL, 0x2ad7d2bbUL, 0xeb86d391UL
};
#else
#define FF(a,b,c,d,M,s,t) \
a = (a + F(b,c,d) + M + t); a = ROLc(a, s) + b;
#define GG(a,b,c,d,M,s,t) \
a = (a + G(b,c,d) + M + t); a = ROLc(a, s) + b;
#define HH(a,b,c,d,M,s,t) \
a = (a + H(b,c,d) + M + t); a = ROLc(a, s) + b;
#define II(a,b,c,d,M,s,t) \
a = (a + I(b,c,d) + M + t); a = ROLc(a, s) + b;
#endif
#ifdef LTC_CLEAN_STACK
static int _md5_compress(hash_state *md, unsigned char *buf)
#else
static int md5_compress(hash_state *md, unsigned char *buf)
#endif
{
ulong32 i, W[16], a, b, c, d;
#ifdef LTC_SMALL_CODE
ulong32 t;
#endif
/* copy the state into 512-bits into W[0..15] */
for (i = 0; i < 16; i++) {
LOAD32L(W[i], buf + (4*i));
}
/* copy state */
a = md->md5.state[0];
b = md->md5.state[1];
c = md->md5.state[2];
d = md->md5.state[3];
#ifdef LTC_SMALL_CODE
for (i = 0; i < 16; ++i) {
FF(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
t = d; d = c; c = b; b = a; a = t;
}
for (; i < 32; ++i) {
GG(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
t = d; d = c; c = b; b = a; a = t;
}
for (; i < 48; ++i) {
HH(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
t = d; d = c; c = b; b = a; a = t;
}
for (; i < 64; ++i) {
II(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
t = d; d = c; c = b; b = a; a = t;
}
#else
FF(a,b,c,d,W[0],7,0xd76aa478UL)
FF(d,a,b,c,W[1],12,0xe8c7b756UL)
FF(c,d,a,b,W[2],17,0x242070dbUL)
FF(b,c,d,a,W[3],22,0xc1bdceeeUL)
FF(a,b,c,d,W[4],7,0xf57c0fafUL)
FF(d,a,b,c,W[5],12,0x4787c62aUL)
FF(c,d,a,b,W[6],17,0xa8304613UL)
FF(b,c,d,a,W[7],22,0xfd469501UL)
FF(a,b,c,d,W[8],7,0x698098d8UL)
FF(d,a,b,c,W[9],12,0x8b44f7afUL)
FF(c,d,a,b,W[10],17,0xffff5bb1UL)
FF(b,c,d,a,W[11],22,0x895cd7beUL)
FF(a,b,c,d,W[12],7,0x6b901122UL)
FF(d,a,b,c,W[13],12,0xfd987193UL)
FF(c,d,a,b,W[14],17,0xa679438eUL)
FF(b,c,d,a,W[15],22,0x49b40821UL)
GG(a,b,c,d,W[1],5,0xf61e2562UL)
GG(d,a,b,c,W[6],9,0xc040b340UL)
GG(c,d,a,b,W[11],14,0x265e5a51UL)
GG(b,c,d,a,W[0],20,0xe9b6c7aaUL)
GG(a,b,c,d,W[5],5,0xd62f105dUL)
GG(d,a,b,c,W[10],9,0x02441453UL)
GG(c,d,a,b,W[15],14,0xd8a1e681UL)
GG(b,c,d,a,W[4],20,0xe7d3fbc8UL)
GG(a,b,c,d,W[9],5,0x21e1cde6UL)
GG(d,a,b,c,W[14],9,0xc33707d6UL)
GG(c,d,a,b,W[3],14,0xf4d50d87UL)
GG(b,c,d,a,W[8],20,0x455a14edUL)
GG(a,b,c,d,W[13],5,0xa9e3e905UL)
GG(d,a,b,c,W[2],9,0xfcefa3f8UL)
GG(c,d,a,b,W[7],14,0x676f02d9UL)
GG(b,c,d,a,W[12],20,0x8d2a4c8aUL)
HH(a,b,c,d,W[5],4,0xfffa3942UL)
HH(d,a,b,c,W[8],11,0x8771f681UL)
HH(c,d,a,b,W[11],16,0x6d9d6122UL)
HH(b,c,d,a,W[14],23,0xfde5380cUL)
HH(a,b,c,d,W[1],4,0xa4beea44UL)
HH(d,a,b,c,W[4],11,0x4bdecfa9UL)
HH(c,d,a,b,W[7],16,0xf6bb4b60UL)
HH(b,c,d,a,W[10],23,0xbebfbc70UL)
HH(a,b,c,d,W[13],4,0x289b7ec6UL)
HH(d,a,b,c,W[0],11,0xeaa127faUL)
HH(c,d,a,b,W[3],16,0xd4ef3085UL)
HH(b,c,d,a,W[6],23,0x04881d05UL)
HH(a,b,c,d,W[9],4,0xd9d4d039UL)
HH(d,a,b,c,W[12],11,0xe6db99e5UL)
HH(c,d,a,b,W[15],16,0x1fa27cf8UL)
HH(b,c,d,a,W[2],23,0xc4ac5665UL)
II(a,b,c,d,W[0],6,0xf4292244UL)
II(d,a,b,c,W[7],10,0x432aff97UL)
II(c,d,a,b,W[14],15,0xab9423a7UL)
II(b,c,d,a,W[5],21,0xfc93a039UL)
II(a,b,c,d,W[12],6,0x655b59c3UL)
II(d,a,b,c,W[3],10,0x8f0ccc92UL)
II(c,d,a,b,W[10],15,0xffeff47dUL)
II(b,c,d,a,W[1],21,0x85845dd1UL)
II(a,b,c,d,W[8],6,0x6fa87e4fUL)
II(d,a,b,c,W[15],10,0xfe2ce6e0UL)
II(c,d,a,b,W[6],15,0xa3014314UL)
II(b,c,d,a,W[13],21,0x4e0811a1UL)
II(a,b,c,d,W[4],6,0xf7537e82UL)
II(d,a,b,c,W[11],10,0xbd3af235UL)
II(c,d,a,b,W[2],15,0x2ad7d2bbUL)
II(b,c,d,a,W[9],21,0xeb86d391UL)
#endif
md->md5.state[0] = md->md5.state[0] + a;
md->md5.state[1] = md->md5.state[1] + b;
md->md5.state[2] = md->md5.state[2] + c;
md->md5.state[3] = md->md5.state[3] + d;
return CRYPT_OK;
}
#ifdef LTC_CLEAN_STACK
static int md5_compress(hash_state *md, unsigned char *buf)
{
int err;
err = _md5_compress(md, buf);
burn_stack(sizeof(ulong32) * 21);
return err;
}
#endif
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int md5_init(hash_state * md)
{
LTC_ARGCHK(md != NULL);
md->md5.state[0] = 0x67452301UL;
md->md5.state[1] = 0xefcdab89UL;
md->md5.state[2] = 0x98badcfeUL;
md->md5.state[3] = 0x10325476UL;
md->md5.curlen = 0;
md->md5.length = 0;
return CRYPT_OK;
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
HASH_PROCESS(md5_process, md5_compress, md5, 64)
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (16 bytes)
@return CRYPT_OK if successful
*/
int md5_done(hash_state * md, unsigned char *out)
{
int i;
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
if (md->md5.curlen >= sizeof(md->md5.buf)) {
return CRYPT_INVALID_ARG;
}
/* increase the length of the message */
md->md5.length += md->md5.curlen * 8;
/* append the '1' bit */
md->md5.buf[md->md5.curlen++] = (unsigned char)0x80;
/* if the length is currently above 56 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (md->md5.curlen > 56) {
while (md->md5.curlen < 64) {
md->md5.buf[md->md5.curlen++] = (unsigned char)0;
}
md5_compress(md, md->md5.buf);
md->md5.curlen = 0;
}
/* pad upto 56 bytes of zeroes */
while (md->md5.curlen < 56) {
md->md5.buf[md->md5.curlen++] = (unsigned char)0;
}
/* store length */
STORE64L(md->md5.length, md->md5.buf+56);
md5_compress(md, md->md5.buf);
/* copy output */
for (i = 0; i < 4; i++) {
STORE32L(md->md5.state[i], out+(4*i));
}
#ifdef LTC_CLEAN_STACK
zeromem(md, sizeof(hash_state));
#endif
return CRYPT_OK;
}
#include "../OS_portable.h"
#include "../../includes/curve25519.h"
bits128 calc_md5(char digeststr[33],void *buf,int32_t len)
{
int32_t init_hexbytes_noT(char *hexbytes,unsigned char *message,long len);
hash_state md; bits128 digest;
md5_init(&md);
md5_process(&md,buf,len);
md5_done(&md,digest.bytes);
if ( digeststr != 0 )
init_hexbytes_noT(digeststr,digest.bytes,sizeof(digest));
return(digest);
}
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int md5_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct {
char *msg;
unsigned char hash[16];
} tests[] = {
{ "",
{ 0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04,
0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e } },
{ "a",
{0x0c, 0xc1, 0x75, 0xb9, 0xc0, 0xf1, 0xb6, 0xa8,
0x31, 0xc3, 0x99, 0xe2, 0x69, 0x77, 0x26, 0x61 } },
{ "abc",
{ 0x90, 0x01, 0x50, 0x98, 0x3c, 0xd2, 0x4f, 0xb0,
0xd6, 0x96, 0x3f, 0x7d, 0x28, 0xe1, 0x7f, 0x72 } },
{ "message digest",
{ 0xf9, 0x6b, 0x69, 0x7d, 0x7c, 0xb7, 0x93, 0x8d,
0x52, 0x5a, 0x2f, 0x31, 0xaa, 0xf1, 0x61, 0xd0 } },
{ "abcdefghijklmnopqrstuvwxyz",
{ 0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00,
0x7d, 0xfb, 0x49, 0x6c, 0xca, 0x67, 0xe1, 0x3b } },
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
{ 0xd1, 0x74, 0xab, 0x98, 0xd2, 0x77, 0xd9, 0xf5,
0xa5, 0x61, 0x1c, 0x2c, 0x9f, 0x41, 0x9d, 0x9f } },
{ "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
{ 0x57, 0xed, 0xf4, 0xa2, 0x2b, 0xe3, 0xc9, 0x55,
0xac, 0x49, 0xda, 0x2e, 0x21, 0x07, 0xb6, 0x7a } },
{ NULL, { 0 } }
};
int i;
unsigned char tmp[16];
hash_state md;
for (i = 0; tests[i].msg != NULL; i++) {
md5_init(&md);
md5_process(&md, (unsigned char *)tests[i].msg, (unsigned long)strlen(tests[i].msg));
md5_done(&md, tmp);
if (XMEMCMP(tmp, tests[i].hash, 16) != 0) {
return CRYPT_FAIL_TESTVECTOR;
}
}
return CRYPT_OK;
#endif
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/md5.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */

434
crypto777/hmac/rmd128.c

@ -0,0 +1,434 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@param rmd128.c
RMD128 Hash function
*/
/* Implementation of LTC_RIPEMD-128 based on the source by Antoon Bosselaers, ESAT-COSIC
*
* This source has been radically overhauled to be portable and work within
* the LibTomCrypt API by Tom St Denis
*/
#ifdef LTC_RIPEMD128
const struct ltc_hash_descriptor rmd128_desc =
{
"rmd128",
8,
16,
64,
/* OID */
{ 1, 0, 10118, 3, 0, 50 },
6,
&rmd128_init,
&rmd128_process,
&rmd128_done,
&rmd128_test,
NULL
};
/* the four basic functions F(), G() and H() */
#define F(x, y, z) ((x) ^ (y) ^ (z))
#define G(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define H(x, y, z) (((x) | ~(y)) ^ (z))
#define I(x, y, z) (((x) & (z)) | ((y) & ~(z)))
/* the eight basic operations FF() through III() */
#define FF(a, b, c, d, x, s) \
(a) += F((b), (c), (d)) + (x);\
(a) = ROLc((a), (s));
#define GG(a, b, c, d, x, s) \
(a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
(a) = ROLc((a), (s));
#define HH(a, b, c, d, x, s) \
(a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
(a) = ROLc((a), (s));
#define II(a, b, c, d, x, s) \
(a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
(a) = ROLc((a), (s));
#define FFF(a, b, c, d, x, s) \
(a) += F((b), (c), (d)) + (x);\
(a) = ROLc((a), (s));
#define GGG(a, b, c, d, x, s) \
(a) += G((b), (c), (d)) + (x) + 0x6d703ef3UL;\
(a) = ROLc((a), (s));
#define HHH(a, b, c, d, x, s) \
(a) += H((b), (c), (d)) + (x) + 0x5c4dd124UL;\
(a) = ROLc((a), (s));
#define III(a, b, c, d, x, s) \
(a) += I((b), (c), (d)) + (x) + 0x50a28be6UL;\
(a) = ROLc((a), (s));
#ifdef LTC_CLEAN_STACK
static int _rmd128_compress(hash_state *md, unsigned char *buf)
#else
static int rmd128_compress(hash_state *md, unsigned char *buf)
#endif
{
ulong32 aa,bb,cc,dd,aaa,bbb,ccc,ddd,X[16];
int i;
/* load words X */
for (i = 0; i < 16; i++){
LOAD32L(X[i], buf + (4 * i));
}
/* load state */
aa = aaa = md->rmd128.state[0];
bb = bbb = md->rmd128.state[1];
cc = ccc = md->rmd128.state[2];
dd = ddd = md->rmd128.state[3];
/* round 1 */
FF(aa, bb, cc, dd, X[ 0], 11);
FF(dd, aa, bb, cc, X[ 1], 14);
FF(cc, dd, aa, bb, X[ 2], 15);
FF(bb, cc, dd, aa, X[ 3], 12);
FF(aa, bb, cc, dd, X[ 4], 5);
FF(dd, aa, bb, cc, X[ 5], 8);
FF(cc, dd, aa, bb, X[ 6], 7);
FF(bb, cc, dd, aa, X[ 7], 9);
FF(aa, bb, cc, dd, X[ 8], 11);
FF(dd, aa, bb, cc, X[ 9], 13);
FF(cc, dd, aa, bb, X[10], 14);
FF(bb, cc, dd, aa, X[11], 15);
FF(aa, bb, cc, dd, X[12], 6);
FF(dd, aa, bb, cc, X[13], 7);
FF(cc, dd, aa, bb, X[14], 9);
FF(bb, cc, dd, aa, X[15], 8);
/* round 2 */
GG(aa, bb, cc, dd, X[ 7], 7);
GG(dd, aa, bb, cc, X[ 4], 6);
GG(cc, dd, aa, bb, X[13], 8);
GG(bb, cc, dd, aa, X[ 1], 13);
GG(aa, bb, cc, dd, X[10], 11);
GG(dd, aa, bb, cc, X[ 6], 9);
GG(cc, dd, aa, bb, X[15], 7);
GG(bb, cc, dd, aa, X[ 3], 15);
GG(aa, bb, cc, dd, X[12], 7);
GG(dd, aa, bb, cc, X[ 0], 12);
GG(cc, dd, aa, bb, X[ 9], 15);
GG(bb, cc, dd, aa, X[ 5], 9);
GG(aa, bb, cc, dd, X[ 2], 11);
GG(dd, aa, bb, cc, X[14], 7);
GG(cc, dd, aa, bb, X[11], 13);
GG(bb, cc, dd, aa, X[ 8], 12);
/* round 3 */
HH(aa, bb, cc, dd, X[ 3], 11);
HH(dd, aa, bb, cc, X[10], 13);
HH(cc, dd, aa, bb, X[14], 6);
HH(bb, cc, dd, aa, X[ 4], 7);
HH(aa, bb, cc, dd, X[ 9], 14);
HH(dd, aa, bb, cc, X[15], 9);
HH(cc, dd, aa, bb, X[ 8], 13);
HH(bb, cc, dd, aa, X[ 1], 15);
HH(aa, bb, cc, dd, X[ 2], 14);
HH(dd, aa, bb, cc, X[ 7], 8);
HH(cc, dd, aa, bb, X[ 0], 13);
HH(bb, cc, dd, aa, X[ 6], 6);
HH(aa, bb, cc, dd, X[13], 5);
HH(dd, aa, bb, cc, X[11], 12);
HH(cc, dd, aa, bb, X[ 5], 7);
HH(bb, cc, dd, aa, X[12], 5);
/* round 4 */
II(aa, bb, cc, dd, X[ 1], 11);
II(dd, aa, bb, cc, X[ 9], 12);
II(cc, dd, aa, bb, X[11], 14);
II(bb, cc, dd, aa, X[10], 15);
II(aa, bb, cc, dd, X[ 0], 14);
II(dd, aa, bb, cc, X[ 8], 15);
II(cc, dd, aa, bb, X[12], 9);
II(bb, cc, dd, aa, X[ 4], 8);
II(aa, bb, cc, dd, X[13], 9);
II(dd, aa, bb, cc, X[ 3], 14);
II(cc, dd, aa, bb, X[ 7], 5);
II(bb, cc, dd, aa, X[15], 6);
II(aa, bb, cc, dd, X[14], 8);
II(dd, aa, bb, cc, X[ 5], 6);
II(cc, dd, aa, bb, X[ 6], 5);
II(bb, cc, dd, aa, X[ 2], 12);
/* parallel round 1 */
III(aaa, bbb, ccc, ddd, X[ 5], 8);
III(ddd, aaa, bbb, ccc, X[14], 9);
III(ccc, ddd, aaa, bbb, X[ 7], 9);
III(bbb, ccc, ddd, aaa, X[ 0], 11);
III(aaa, bbb, ccc, ddd, X[ 9], 13);
III(ddd, aaa, bbb, ccc, X[ 2], 15);
III(ccc, ddd, aaa, bbb, X[11], 15);
III(bbb, ccc, ddd, aaa, X[ 4], 5);
III(aaa, bbb, ccc, ddd, X[13], 7);
III(ddd, aaa, bbb, ccc, X[ 6], 7);
III(ccc, ddd, aaa, bbb, X[15], 8);
III(bbb, ccc, ddd, aaa, X[ 8], 11);
III(aaa, bbb, ccc, ddd, X[ 1], 14);
III(ddd, aaa, bbb, ccc, X[10], 14);
III(ccc, ddd, aaa, bbb, X[ 3], 12);
III(bbb, ccc, ddd, aaa, X[12], 6);
/* parallel round 2 */
HHH(aaa, bbb, ccc, ddd, X[ 6], 9);
HHH(ddd, aaa, bbb, ccc, X[11], 13);
HHH(ccc, ddd, aaa, bbb, X[ 3], 15);
HHH(bbb, ccc, ddd, aaa, X[ 7], 7);
HHH(aaa, bbb, ccc, ddd, X[ 0], 12);
HHH(ddd, aaa, bbb, ccc, X[13], 8);
HHH(ccc, ddd, aaa, bbb, X[ 5], 9);
HHH(bbb, ccc, ddd, aaa, X[10], 11);
HHH(aaa, bbb, ccc, ddd, X[14], 7);
HHH(ddd, aaa, bbb, ccc, X[15], 7);
HHH(ccc, ddd, aaa, bbb, X[ 8], 12);
HHH(bbb, ccc, ddd, aaa, X[12], 7);
HHH(aaa, bbb, ccc, ddd, X[ 4], 6);
HHH(ddd, aaa, bbb, ccc, X[ 9], 15);
HHH(ccc, ddd, aaa, bbb, X[ 1], 13);
HHH(bbb, ccc, ddd, aaa, X[ 2], 11);
/* parallel round 3 */
GGG(aaa, bbb, ccc, ddd, X[15], 9);
GGG(ddd, aaa, bbb, ccc, X[ 5], 7);
GGG(ccc, ddd, aaa, bbb, X[ 1], 15);
GGG(bbb, ccc, ddd, aaa, X[ 3], 11);
GGG(aaa, bbb, ccc, ddd, X[ 7], 8);
GGG(ddd, aaa, bbb, ccc, X[14], 6);
GGG(ccc, ddd, aaa, bbb, X[ 6], 6);
GGG(bbb, ccc, ddd, aaa, X[ 9], 14);
GGG(aaa, bbb, ccc, ddd, X[11], 12);
GGG(ddd, aaa, bbb, ccc, X[ 8], 13);
GGG(ccc, ddd, aaa, bbb, X[12], 5);
GGG(bbb, ccc, ddd, aaa, X[ 2], 14);
GGG(aaa, bbb, ccc, ddd, X[10], 13);
GGG(ddd, aaa, bbb, ccc, X[ 0], 13);
GGG(ccc, ddd, aaa, bbb, X[ 4], 7);
GGG(bbb, ccc, ddd, aaa, X[13], 5);
/* parallel round 4 */
FFF(aaa, bbb, ccc, ddd, X[ 8], 15);
FFF(ddd, aaa, bbb, ccc, X[ 6], 5);
FFF(ccc, ddd, aaa, bbb, X[ 4], 8);
FFF(bbb, ccc, ddd, aaa, X[ 1], 11);
FFF(aaa, bbb, ccc, ddd, X[ 3], 14);
FFF(ddd, aaa, bbb, ccc, X[11], 14);
FFF(ccc, ddd, aaa, bbb, X[15], 6);
FFF(bbb, ccc, ddd, aaa, X[ 0], 14);
FFF(aaa, bbb, ccc, ddd, X[ 5], 6);
FFF(ddd, aaa, bbb, ccc, X[12], 9);
FFF(ccc, ddd, aaa, bbb, X[ 2], 12);
FFF(bbb, ccc, ddd, aaa, X[13], 9);
FFF(aaa, bbb, ccc, ddd, X[ 9], 12);
FFF(ddd, aaa, bbb, ccc, X[ 7], 5);
FFF(ccc, ddd, aaa, bbb, X[10], 15);
FFF(bbb, ccc, ddd, aaa, X[14], 8);
/* combine results */
ddd += cc + md->rmd128.state[1]; /* final result for MDbuf[0] */
md->rmd128.state[1] = md->rmd128.state[2] + dd + aaa;
md->rmd128.state[2] = md->rmd128.state[3] + aa + bbb;
md->rmd128.state[3] = md->rmd128.state[0] + bb + ccc;
md->rmd128.state[0] = ddd;
return CRYPT_OK;
}
#ifdef LTC_CLEAN_STACK
static int rmd128_compress(hash_state *md, unsigned char *buf)
{
int err;
err = _rmd128_compress(md, buf);
burn_stack(sizeof(ulong32) * 24 + sizeof(int));
return err;
}
#endif
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int rmd128_init(hash_state * md)
{
LTC_ARGCHK(md != NULL);
md->rmd128.state[0] = 0x67452301UL;
md->rmd128.state[1] = 0xefcdab89UL;
md->rmd128.state[2] = 0x98badcfeUL;
md->rmd128.state[3] = 0x10325476UL;
md->rmd128.curlen = 0;
md->rmd128.length = 0;
return CRYPT_OK;
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
HASH_PROCESS(rmd128_process, rmd128_compress, rmd128, 64)
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (16 bytes)
@return CRYPT_OK if successful
*/
int rmd128_done(hash_state * md, unsigned char *out)
{
int i;
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
if (md->rmd128.curlen >= sizeof(md->rmd128.buf)) {
return CRYPT_INVALID_ARG;
}
/* increase the length of the message */
md->rmd128.length += md->rmd128.curlen * 8;
/* append the '1' bit */
md->rmd128.buf[md->rmd128.curlen++] = (unsigned char)0x80;
/* if the length is currently above 56 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (md->rmd128.curlen > 56) {
while (md->rmd128.curlen < 64) {
md->rmd128.buf[md->rmd128.curlen++] = (unsigned char)0;
}
rmd128_compress(md, md->rmd128.buf);
md->rmd128.curlen = 0;
}
/* pad upto 56 bytes of zeroes */
while (md->rmd128.curlen < 56) {
md->rmd128.buf[md->rmd128.curlen++] = (unsigned char)0;
}
/* store length */
STORE64L(md->rmd128.length, md->rmd128.buf+56);
rmd128_compress(md, md->rmd128.buf);
/* copy output */
for (i = 0; i < 4; i++) {
STORE32L(md->rmd128.state[i], out+(4*i));
}
#ifdef LTC_CLEAN_STACK
zeromem(md, sizeof(hash_state));
#endif
return CRYPT_OK;
}
void calc_rmd128(char *str,uint8_t *digest,uint8_t *message,int32_t len)
{
int init_hexbytes_noT(char *hexbytes,unsigned char *message,long len);
hash_state md;
rmd128_init(&md);
rmd128_process(&md,message,len);
rmd128_done(&md,digest);
if ( str != 0 )
init_hexbytes_noT(str,digest,16);
}
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int rmd128_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct {
char *msg;
unsigned char md[16];
} tests[] = {
{ "",
{ 0xcd, 0xf2, 0x62, 0x13, 0xa1, 0x50, 0xdc, 0x3e,
0xcb, 0x61, 0x0f, 0x18, 0xf6, 0xb3, 0x8b, 0x46 }
},
{ "a",
{ 0x86, 0xbe, 0x7a, 0xfa, 0x33, 0x9d, 0x0f, 0xc7,
0xcf, 0xc7, 0x85, 0xe7, 0x2f, 0x57, 0x8d, 0x33 }
},
{ "abc",
{ 0xc1, 0x4a, 0x12, 0x19, 0x9c, 0x66, 0xe4, 0xba,
0x84, 0x63, 0x6b, 0x0f, 0x69, 0x14, 0x4c, 0x77 }
},
{ "message digest",
{ 0x9e, 0x32, 0x7b, 0x3d, 0x6e, 0x52, 0x30, 0x62,
0xaf, 0xc1, 0x13, 0x2d, 0x7d, 0xf9, 0xd1, 0xb8 }
},
{ "abcdefghijklmnopqrstuvwxyz",
{ 0xfd, 0x2a, 0xa6, 0x07, 0xf7, 0x1d, 0xc8, 0xf5,
0x10, 0x71, 0x49, 0x22, 0xb3, 0x71, 0x83, 0x4e }
},
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
{ 0xd1, 0xe9, 0x59, 0xeb, 0x17, 0x9c, 0x91, 0x1f,
0xae, 0xa4, 0x62, 0x4c, 0x60, 0xc5, 0xc7, 0x02 }
}
};
int x;
unsigned char buf[16];
hash_state md;
for (x = 0; x < (int)(sizeof(tests)/sizeof(tests[0])); x++) {
rmd128_init(&md);
rmd128_process(&md, (unsigned char *)tests[x].msg, strlen(tests[x].msg));
rmd128_done(&md, buf);
if (XMEMCMP(buf, tests[x].md, 16) != 0) {
#if 0
printf("Failed test %d\n", x);
#endif
return CRYPT_FAIL_TESTVECTOR;
}
}
return CRYPT_OK;
#endif
}
#undef FF
#undef GG
#undef HH
#undef II
#undef FFF
#undef GGG
#undef HHH
#undef III
#undef F
#undef G
#undef H
#undef I
#undef J
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/rmd128.c,v $ */
/* $Revision: 1.11 $ */
/* $Date: 2007/05/12 14:25:28 $ */

483
crypto777/hmac/rmd160.c

@ -0,0 +1,483 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
#include <string.h>
/**
@file rmd160.c
RMD160 hash function
*/
/* Implementation of LTC_RIPEMD-160 based on the source by Antoon Bosselaers, ESAT-COSIC
*
* This source has been radically overhauled to be portable and work within
* the LibTomCrypt API by Tom St Denis
*/
//#ifdef LTC_RIPEMD160
const struct ltc_hash_descriptor rmd160_desc =
{
"rmd160",
9,
20,
64,
/* OID */
{ 1, 3, 36, 3, 2, 1, },
6,
&rmd160_init,
&rmd160_process,
&rmd160_done,
&rmd160_test,
NULL
};
/* the five basic functions F(), G() and H() */
#define F(x, y, z) ((x) ^ (y) ^ (z))
#define G(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define H(x, y, z) (((x) | ~(y)) ^ (z))
#define I(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define J(x, y, z) ((x) ^ ((y) | ~(z)))
/* the ten basic operations FF() through III() */
#define FF(a, b, c, d, e, x, s) \
(a) += F((b), (c), (d)) + (x);\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define GG(a, b, c, d, e, x, s) \
(a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define HH(a, b, c, d, e, x, s) \
(a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define II(a, b, c, d, e, x, s) \
(a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define JJ(a, b, c, d, e, x, s) \
(a) += J((b), (c), (d)) + (x) + 0xa953fd4eUL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define FFF(a, b, c, d, e, x, s) \
(a) += F((b), (c), (d)) + (x);\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define GGG(a, b, c, d, e, x, s) \
(a) += G((b), (c), (d)) + (x) + 0x7a6d76e9UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define HHH(a, b, c, d, e, x, s) \
(a) += H((b), (c), (d)) + (x) + 0x6d703ef3UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define III(a, b, c, d, e, x, s) \
(a) += I((b), (c), (d)) + (x) + 0x5c4dd124UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define JJJ(a, b, c, d, e, x, s) \
(a) += J((b), (c), (d)) + (x) + 0x50a28be6UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#ifdef LTC_CLEAN_STACK
static int _rmd160_compress(hash_state *md, unsigned char *buf)
#else
static int rmd160_compress(hash_state *md, unsigned char *buf)
#endif
{
ulong32 aa,bb,cc,dd,ee,aaa,bbb,ccc,ddd,eee,X[16];
int i;
/* load words X */
for (i = 0; i < 16; i++){
LOAD32L(X[i], buf + (4 * i));
}
/* load state */
aa = aaa = md->rmd160.state[0];
bb = bbb = md->rmd160.state[1];
cc = ccc = md->rmd160.state[2];
dd = ddd = md->rmd160.state[3];
ee = eee = md->rmd160.state[4];
/* round 1 */
FF(aa, bb, cc, dd, ee, X[ 0], 11);
FF(ee, aa, bb, cc, dd, X[ 1], 14);
FF(dd, ee, aa, bb, cc, X[ 2], 15);
FF(cc, dd, ee, aa, bb, X[ 3], 12);
FF(bb, cc, dd, ee, aa, X[ 4], 5);
FF(aa, bb, cc, dd, ee, X[ 5], 8);
FF(ee, aa, bb, cc, dd, X[ 6], 7);
FF(dd, ee, aa, bb, cc, X[ 7], 9);
FF(cc, dd, ee, aa, bb, X[ 8], 11);
FF(bb, cc, dd, ee, aa, X[ 9], 13);
FF(aa, bb, cc, dd, ee, X[10], 14);
FF(ee, aa, bb, cc, dd, X[11], 15);
FF(dd, ee, aa, bb, cc, X[12], 6);
FF(cc, dd, ee, aa, bb, X[13], 7);
FF(bb, cc, dd, ee, aa, X[14], 9);
FF(aa, bb, cc, dd, ee, X[15], 8);
/* round 2 */
GG(ee, aa, bb, cc, dd, X[ 7], 7);
GG(dd, ee, aa, bb, cc, X[ 4], 6);
GG(cc, dd, ee, aa, bb, X[13], 8);
GG(bb, cc, dd, ee, aa, X[ 1], 13);
GG(aa, bb, cc, dd, ee, X[10], 11);
GG(ee, aa, bb, cc, dd, X[ 6], 9);
GG(dd, ee, aa, bb, cc, X[15], 7);
GG(cc, dd, ee, aa, bb, X[ 3], 15);
GG(bb, cc, dd, ee, aa, X[12], 7);
GG(aa, bb, cc, dd, ee, X[ 0], 12);
GG(ee, aa, bb, cc, dd, X[ 9], 15);
GG(dd, ee, aa, bb, cc, X[ 5], 9);
GG(cc, dd, ee, aa, bb, X[ 2], 11);
GG(bb, cc, dd, ee, aa, X[14], 7);
GG(aa, bb, cc, dd, ee, X[11], 13);
GG(ee, aa, bb, cc, dd, X[ 8], 12);
/* round 3 */
HH(dd, ee, aa, bb, cc, X[ 3], 11);
HH(cc, dd, ee, aa, bb, X[10], 13);
HH(bb, cc, dd, ee, aa, X[14], 6);
HH(aa, bb, cc, dd, ee, X[ 4], 7);
HH(ee, aa, bb, cc, dd, X[ 9], 14);
HH(dd, ee, aa, bb, cc, X[15], 9);
HH(cc, dd, ee, aa, bb, X[ 8], 13);
HH(bb, cc, dd, ee, aa, X[ 1], 15);
HH(aa, bb, cc, dd, ee, X[ 2], 14);
HH(ee, aa, bb, cc, dd, X[ 7], 8);
HH(dd, ee, aa, bb, cc, X[ 0], 13);
HH(cc, dd, ee, aa, bb, X[ 6], 6);
HH(bb, cc, dd, ee, aa, X[13], 5);
HH(aa, bb, cc, dd, ee, X[11], 12);
HH(ee, aa, bb, cc, dd, X[ 5], 7);
HH(dd, ee, aa, bb, cc, X[12], 5);
/* round 4 */
II(cc, dd, ee, aa, bb, X[ 1], 11);
II(bb, cc, dd, ee, aa, X[ 9], 12);
II(aa, bb, cc, dd, ee, X[11], 14);
II(ee, aa, bb, cc, dd, X[10], 15);
II(dd, ee, aa, bb, cc, X[ 0], 14);
II(cc, dd, ee, aa, bb, X[ 8], 15);
II(bb, cc, dd, ee, aa, X[12], 9);
II(aa, bb, cc, dd, ee, X[ 4], 8);
II(ee, aa, bb, cc, dd, X[13], 9);
II(dd, ee, aa, bb, cc, X[ 3], 14);
II(cc, dd, ee, aa, bb, X[ 7], 5);
II(bb, cc, dd, ee, aa, X[15], 6);
II(aa, bb, cc, dd, ee, X[14], 8);
II(ee, aa, bb, cc, dd, X[ 5], 6);
II(dd, ee, aa, bb, cc, X[ 6], 5);
II(cc, dd, ee, aa, bb, X[ 2], 12);
/* round 5 */
JJ(bb, cc, dd, ee, aa, X[ 4], 9);
JJ(aa, bb, cc, dd, ee, X[ 0], 15);
JJ(ee, aa, bb, cc, dd, X[ 5], 5);
JJ(dd, ee, aa, bb, cc, X[ 9], 11);
JJ(cc, dd, ee, aa, bb, X[ 7], 6);
JJ(bb, cc, dd, ee, aa, X[12], 8);
JJ(aa, bb, cc, dd, ee, X[ 2], 13);
JJ(ee, aa, bb, cc, dd, X[10], 12);
JJ(dd, ee, aa, bb, cc, X[14], 5);
JJ(cc, dd, ee, aa, bb, X[ 1], 12);
JJ(bb, cc, dd, ee, aa, X[ 3], 13);
JJ(aa, bb, cc, dd, ee, X[ 8], 14);
JJ(ee, aa, bb, cc, dd, X[11], 11);
JJ(dd, ee, aa, bb, cc, X[ 6], 8);
JJ(cc, dd, ee, aa, bb, X[15], 5);
JJ(bb, cc, dd, ee, aa, X[13], 6);
/* parallel round 1 */
JJJ(aaa, bbb, ccc, ddd, eee, X[ 5], 8);
JJJ(eee, aaa, bbb, ccc, ddd, X[14], 9);
JJJ(ddd, eee, aaa, bbb, ccc, X[ 7], 9);
JJJ(ccc, ddd, eee, aaa, bbb, X[ 0], 11);
JJJ(bbb, ccc, ddd, eee, aaa, X[ 9], 13);
JJJ(aaa, bbb, ccc, ddd, eee, X[ 2], 15);
JJJ(eee, aaa, bbb, ccc, ddd, X[11], 15);
JJJ(ddd, eee, aaa, bbb, ccc, X[ 4], 5);
JJJ(ccc, ddd, eee, aaa, bbb, X[13], 7);
JJJ(bbb, ccc, ddd, eee, aaa, X[ 6], 7);
JJJ(aaa, bbb, ccc, ddd, eee, X[15], 8);
JJJ(eee, aaa, bbb, ccc, ddd, X[ 8], 11);
JJJ(ddd, eee, aaa, bbb, ccc, X[ 1], 14);
JJJ(ccc, ddd, eee, aaa, bbb, X[10], 14);
JJJ(bbb, ccc, ddd, eee, aaa, X[ 3], 12);
JJJ(aaa, bbb, ccc, ddd, eee, X[12], 6);
/* parallel round 2 */
III(eee, aaa, bbb, ccc, ddd, X[ 6], 9);
III(ddd, eee, aaa, bbb, ccc, X[11], 13);
III(ccc, ddd, eee, aaa, bbb, X[ 3], 15);
III(bbb, ccc, ddd, eee, aaa, X[ 7], 7);
III(aaa, bbb, ccc, ddd, eee, X[ 0], 12);
III(eee, aaa, bbb, ccc, ddd, X[13], 8);
III(ddd, eee, aaa, bbb, ccc, X[ 5], 9);
III(ccc, ddd, eee, aaa, bbb, X[10], 11);
III(bbb, ccc, ddd, eee, aaa, X[14], 7);
III(aaa, bbb, ccc, ddd, eee, X[15], 7);
III(eee, aaa, bbb, ccc, ddd, X[ 8], 12);
III(ddd, eee, aaa, bbb, ccc, X[12], 7);
III(ccc, ddd, eee, aaa, bbb, X[ 4], 6);
III(bbb, ccc, ddd, eee, aaa, X[ 9], 15);
III(aaa, bbb, ccc, ddd, eee, X[ 1], 13);
III(eee, aaa, bbb, ccc, ddd, X[ 2], 11);
/* parallel round 3 */
HHH(ddd, eee, aaa, bbb, ccc, X[15], 9);
HHH(ccc, ddd, eee, aaa, bbb, X[ 5], 7);
HHH(bbb, ccc, ddd, eee, aaa, X[ 1], 15);
HHH(aaa, bbb, ccc, ddd, eee, X[ 3], 11);
HHH(eee, aaa, bbb, ccc, ddd, X[ 7], 8);
HHH(ddd, eee, aaa, bbb, ccc, X[14], 6);
HHH(ccc, ddd, eee, aaa, bbb, X[ 6], 6);
HHH(bbb, ccc, ddd, eee, aaa, X[ 9], 14);
HHH(aaa, bbb, ccc, ddd, eee, X[11], 12);
HHH(eee, aaa, bbb, ccc, ddd, X[ 8], 13);
HHH(ddd, eee, aaa, bbb, ccc, X[12], 5);
HHH(ccc, ddd, eee, aaa, bbb, X[ 2], 14);
HHH(bbb, ccc, ddd, eee, aaa, X[10], 13);
HHH(aaa, bbb, ccc, ddd, eee, X[ 0], 13);
HHH(eee, aaa, bbb, ccc, ddd, X[ 4], 7);
HHH(ddd, eee, aaa, bbb, ccc, X[13], 5);
/* parallel round 4 */
GGG(ccc, ddd, eee, aaa, bbb, X[ 8], 15);
GGG(bbb, ccc, ddd, eee, aaa, X[ 6], 5);
GGG(aaa, bbb, ccc, ddd, eee, X[ 4], 8);
GGG(eee, aaa, bbb, ccc, ddd, X[ 1], 11);
GGG(ddd, eee, aaa, bbb, ccc, X[ 3], 14);
GGG(ccc, ddd, eee, aaa, bbb, X[11], 14);
GGG(bbb, ccc, ddd, eee, aaa, X[15], 6);
GGG(aaa, bbb, ccc, ddd, eee, X[ 0], 14);
GGG(eee, aaa, bbb, ccc, ddd, X[ 5], 6);
GGG(ddd, eee, aaa, bbb, ccc, X[12], 9);
GGG(ccc, ddd, eee, aaa, bbb, X[ 2], 12);
GGG(bbb, ccc, ddd, eee, aaa, X[13], 9);
GGG(aaa, bbb, ccc, ddd, eee, X[ 9], 12);
GGG(eee, aaa, bbb, ccc, ddd, X[ 7], 5);
GGG(ddd, eee, aaa, bbb, ccc, X[10], 15);
GGG(ccc, ddd, eee, aaa, bbb, X[14], 8);
/* parallel round 5 */
FFF(bbb, ccc, ddd, eee, aaa, X[12] , 8);
FFF(aaa, bbb, ccc, ddd, eee, X[15] , 5);
FFF(eee, aaa, bbb, ccc, ddd, X[10] , 12);
FFF(ddd, eee, aaa, bbb, ccc, X[ 4] , 9);
FFF(ccc, ddd, eee, aaa, bbb, X[ 1] , 12);
FFF(bbb, ccc, ddd, eee, aaa, X[ 5] , 5);
FFF(aaa, bbb, ccc, ddd, eee, X[ 8] , 14);
FFF(eee, aaa, bbb, ccc, ddd, X[ 7] , 6);
FFF(ddd, eee, aaa, bbb, ccc, X[ 6] , 8);
FFF(ccc, ddd, eee, aaa, bbb, X[ 2] , 13);
FFF(bbb, ccc, ddd, eee, aaa, X[13] , 6);
FFF(aaa, bbb, ccc, ddd, eee, X[14] , 5);
FFF(eee, aaa, bbb, ccc, ddd, X[ 0] , 15);
FFF(ddd, eee, aaa, bbb, ccc, X[ 3] , 13);
FFF(ccc, ddd, eee, aaa, bbb, X[ 9] , 11);
FFF(bbb, ccc, ddd, eee, aaa, X[11] , 11);
/* combine results */
ddd += cc + md->rmd160.state[1]; /* final result for md->rmd160.state[0] */
md->rmd160.state[1] = md->rmd160.state[2] + dd + eee;
md->rmd160.state[2] = md->rmd160.state[3] + ee + aaa;
md->rmd160.state[3] = md->rmd160.state[4] + aa + bbb;
md->rmd160.state[4] = md->rmd160.state[0] + bb + ccc;
md->rmd160.state[0] = ddd;
return CRYPT_OK;
}
#ifdef LTC_CLEAN_STACK
static int rmd160_compress(hash_state *md, unsigned char *buf)
{
int err;
err = _rmd160_compress(md, buf);
burn_stack(sizeof(ulong32) * 26 + sizeof(int));
return err;
}
#endif
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int rmd160_init(hash_state * md)
{
LTC_ARGCHK(md != NULL);
md->rmd160.state[0] = 0x67452301UL;
md->rmd160.state[1] = 0xefcdab89UL;
md->rmd160.state[2] = 0x98badcfeUL;
md->rmd160.state[3] = 0x10325476UL;
md->rmd160.state[4] = 0xc3d2e1f0UL;
md->rmd160.curlen = 0;
md->rmd160.length = 0;
return CRYPT_OK;
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
HASH_PROCESS(rmd160_process, rmd160_compress, rmd160, 64)
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (20 bytes)
@return CRYPT_OK if successful
*/
int rmd160_done(hash_state * md, unsigned char *out)
{
int i;
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
if (md->rmd160.curlen >= sizeof(md->rmd160.buf)) {
return CRYPT_INVALID_ARG;
}
/* increase the length of the message */
md->rmd160.length += md->rmd160.curlen * 8;
/* append the '1' bit */
md->rmd160.buf[md->rmd160.curlen++] = (unsigned char)0x80;
/* if the length is currently above 56 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (md->rmd160.curlen > 56) {
while (md->rmd160.curlen < 64) {
md->rmd160.buf[md->rmd160.curlen++] = (unsigned char)0;
}
rmd160_compress(md, md->rmd160.buf);
md->rmd160.curlen = 0;
}
/* pad upto 56 bytes of zeroes */
while (md->rmd160.curlen < 56) {
md->rmd160.buf[md->rmd160.curlen++] = (unsigned char)0;
}
/* store length */
STORE64L(md->rmd160.length, md->rmd160.buf+56);
rmd160_compress(md, md->rmd160.buf);
/* copy output */
for (i = 0; i < 5; i++) {
STORE32L(md->rmd160.state[i], out+(4*i));
}
#ifdef LTC_CLEAN_STACK
zeromem(md, sizeof(hash_state));
#endif
return CRYPT_OK;
}
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int rmd160_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct {
char *msg;
unsigned char md[20];
} tests[] = {
{ "",
{ 0x9c, 0x11, 0x85, 0xa5, 0xc5, 0xe9, 0xfc, 0x54, 0x61, 0x28,
0x08, 0x97, 0x7e, 0xe8, 0xf5, 0x48, 0xb2, 0x25, 0x8d, 0x31 }
},
{ "a",
{ 0x0b, 0xdc, 0x9d, 0x2d, 0x25, 0x6b, 0x3e, 0xe9, 0xda, 0xae,
0x34, 0x7b, 0xe6, 0xf4, 0xdc, 0x83, 0x5a, 0x46, 0x7f, 0xfe }
},
{ "abc",
{ 0x8e, 0xb2, 0x08, 0xf7, 0xe0, 0x5d, 0x98, 0x7a, 0x9b, 0x04,
0x4a, 0x8e, 0x98, 0xc6, 0xb0, 0x87, 0xf1, 0x5a, 0x0b, 0xfc }
},
{ "message digest",
{ 0x5d, 0x06, 0x89, 0xef, 0x49, 0xd2, 0xfa, 0xe5, 0x72, 0xb8,
0x81, 0xb1, 0x23, 0xa8, 0x5f, 0xfa, 0x21, 0x59, 0x5f, 0x36 }
},
{ "abcdefghijklmnopqrstuvwxyz",
{ 0xf7, 0x1c, 0x27, 0x10, 0x9c, 0x69, 0x2c, 0x1b, 0x56, 0xbb,
0xdc, 0xeb, 0x5b, 0x9d, 0x28, 0x65, 0xb3, 0x70, 0x8d, 0xbc }
},
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
{ 0x12, 0xa0, 0x53, 0x38, 0x4a, 0x9c, 0x0c, 0x88, 0xe4, 0x05,
0xa0, 0x6c, 0x27, 0xdc, 0xf4, 0x9a, 0xda, 0x62, 0xeb, 0x2b }
}
};
int x;
unsigned char buf[20];
hash_state md;
for (x = 0; x < (int)(sizeof(tests)/sizeof(tests[0])); x++) {
rmd160_init(&md);
rmd160_process(&md, (unsigned char *)tests[x].msg, strlen(tests[x].msg));
rmd160_done(&md, buf);
if (XMEMCMP(buf, tests[x].md, 20) != 0) {
#if 0
printf("Failed test %d\n", x);
#endif
return CRYPT_FAIL_TESTVECTOR;
}
}
return CRYPT_OK;
#endif
}
#undef FF
#undef GG
#undef HH
#undef II
#undef FFF
#undef GGG
#undef HHH
#undef III
#undef F
#undef G
#undef H
#undef I
#undef J
//#endif
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/rmd160.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */

454
crypto777/hmac/rmd256.c

@ -0,0 +1,454 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@param rmd256.c
RLTC_MD256 Hash function
*/
#ifdef LTC_RIPEMD256
const struct ltc_hash_descriptor rmd256_desc =
{
"rmd256",
8,
32,
64,
/* OID */
{ 1, 3, 36, 3, 2, 3 },
6,
&rmd256_init,
&rmd256_process,
&rmd256_done,
&rmd256_test,
NULL
};
/* the four basic functions F(), G() and H() */
#define F(x, y, z) ((x) ^ (y) ^ (z))
#define G(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define H(x, y, z) (((x) | ~(y)) ^ (z))
#define I(x, y, z) (((x) & (z)) | ((y) & ~(z)))
/* the eight basic operations FF() through III() */
#define FF(a, b, c, d, x, s) \
(a) += F((b), (c), (d)) + (x);\
(a) = ROLc((a), (s));
#define GG(a, b, c, d, x, s) \
(a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
(a) = ROLc((a), (s));
#define HH(a, b, c, d, x, s) \
(a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
(a) = ROLc((a), (s));
#define II(a, b, c, d, x, s) \
(a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
(a) = ROLc((a), (s));
#define FFF(a, b, c, d, x, s) \
(a) += F((b), (c), (d)) + (x);\
(a) = ROLc((a), (s));
#define GGG(a, b, c, d, x, s) \
(a) += G((b), (c), (d)) + (x) + 0x6d703ef3UL;\
(a) = ROLc((a), (s));
#define HHH(a, b, c, d, x, s) \
(a) += H((b), (c), (d)) + (x) + 0x5c4dd124UL;\
(a) = ROLc((a), (s));
#define III(a, b, c, d, x, s) \
(a) += I((b), (c), (d)) + (x) + 0x50a28be6UL;\
(a) = ROLc((a), (s));
#ifdef LTC_CLEAN_STACK
static int _rmd256_compress(hash_state *md, unsigned char *buf)
#else
static int rmd256_compress(hash_state *md, unsigned char *buf)
#endif
{
ulong32 aa,bb,cc,dd,aaa,bbb,ccc,ddd,tmp,X[16];
int i;
/* load words X */
for (i = 0; i < 16; i++){
LOAD32L(X[i], buf + (4 * i));
}
/* load state */
aa = md->rmd256.state[0];
bb = md->rmd256.state[1];
cc = md->rmd256.state[2];
dd = md->rmd256.state[3];
aaa = md->rmd256.state[4];
bbb = md->rmd256.state[5];
ccc = md->rmd256.state[6];
ddd = md->rmd256.state[7];
/* round 1 */
FF(aa, bb, cc, dd, X[ 0], 11);
FF(dd, aa, bb, cc, X[ 1], 14);
FF(cc, dd, aa, bb, X[ 2], 15);
FF(bb, cc, dd, aa, X[ 3], 12);
FF(aa, bb, cc, dd, X[ 4], 5);
FF(dd, aa, bb, cc, X[ 5], 8);
FF(cc, dd, aa, bb, X[ 6], 7);
FF(bb, cc, dd, aa, X[ 7], 9);
FF(aa, bb, cc, dd, X[ 8], 11);
FF(dd, aa, bb, cc, X[ 9], 13);
FF(cc, dd, aa, bb, X[10], 14);
FF(bb, cc, dd, aa, X[11], 15);
FF(aa, bb, cc, dd, X[12], 6);
FF(dd, aa, bb, cc, X[13], 7);
FF(cc, dd, aa, bb, X[14], 9);
FF(bb, cc, dd, aa, X[15], 8);
/* parallel round 1 */
III(aaa, bbb, ccc, ddd, X[ 5], 8);
III(ddd, aaa, bbb, ccc, X[14], 9);
III(ccc, ddd, aaa, bbb, X[ 7], 9);
III(bbb, ccc, ddd, aaa, X[ 0], 11);
III(aaa, bbb, ccc, ddd, X[ 9], 13);
III(ddd, aaa, bbb, ccc, X[ 2], 15);
III(ccc, ddd, aaa, bbb, X[11], 15);
III(bbb, ccc, ddd, aaa, X[ 4], 5);
III(aaa, bbb, ccc, ddd, X[13], 7);
III(ddd, aaa, bbb, ccc, X[ 6], 7);
III(ccc, ddd, aaa, bbb, X[15], 8);
III(bbb, ccc, ddd, aaa, X[ 8], 11);
III(aaa, bbb, ccc, ddd, X[ 1], 14);
III(ddd, aaa, bbb, ccc, X[10], 14);
III(ccc, ddd, aaa, bbb, X[ 3], 12);
III(bbb, ccc, ddd, aaa, X[12], 6);
tmp = aa; aa = aaa; aaa = tmp;
/* round 2 */
GG(aa, bb, cc, dd, X[ 7], 7);
GG(dd, aa, bb, cc, X[ 4], 6);
GG(cc, dd, aa, bb, X[13], 8);
GG(bb, cc, dd, aa, X[ 1], 13);
GG(aa, bb, cc, dd, X[10], 11);
GG(dd, aa, bb, cc, X[ 6], 9);
GG(cc, dd, aa, bb, X[15], 7);
GG(bb, cc, dd, aa, X[ 3], 15);
GG(aa, bb, cc, dd, X[12], 7);
GG(dd, aa, bb, cc, X[ 0], 12);
GG(cc, dd, aa, bb, X[ 9], 15);
GG(bb, cc, dd, aa, X[ 5], 9);
GG(aa, bb, cc, dd, X[ 2], 11);
GG(dd, aa, bb, cc, X[14], 7);
GG(cc, dd, aa, bb, X[11], 13);
GG(bb, cc, dd, aa, X[ 8], 12);
/* parallel round 2 */
HHH(aaa, bbb, ccc, ddd, X[ 6], 9);
HHH(ddd, aaa, bbb, ccc, X[11], 13);
HHH(ccc, ddd, aaa, bbb, X[ 3], 15);
HHH(bbb, ccc, ddd, aaa, X[ 7], 7);
HHH(aaa, bbb, ccc, ddd, X[ 0], 12);
HHH(ddd, aaa, bbb, ccc, X[13], 8);
HHH(ccc, ddd, aaa, bbb, X[ 5], 9);
HHH(bbb, ccc, ddd, aaa, X[10], 11);
HHH(aaa, bbb, ccc, ddd, X[14], 7);
HHH(ddd, aaa, bbb, ccc, X[15], 7);
HHH(ccc, ddd, aaa, bbb, X[ 8], 12);
HHH(bbb, ccc, ddd, aaa, X[12], 7);
HHH(aaa, bbb, ccc, ddd, X[ 4], 6);
HHH(ddd, aaa, bbb, ccc, X[ 9], 15);
HHH(ccc, ddd, aaa, bbb, X[ 1], 13);
HHH(bbb, ccc, ddd, aaa, X[ 2], 11);
tmp = bb; bb = bbb; bbb = tmp;
/* round 3 */
HH(aa, bb, cc, dd, X[ 3], 11);
HH(dd, aa, bb, cc, X[10], 13);
HH(cc, dd, aa, bb, X[14], 6);
HH(bb, cc, dd, aa, X[ 4], 7);
HH(aa, bb, cc, dd, X[ 9], 14);
HH(dd, aa, bb, cc, X[15], 9);
HH(cc, dd, aa, bb, X[ 8], 13);
HH(bb, cc, dd, aa, X[ 1], 15);
HH(aa, bb, cc, dd, X[ 2], 14);
HH(dd, aa, bb, cc, X[ 7], 8);
HH(cc, dd, aa, bb, X[ 0], 13);
HH(bb, cc, dd, aa, X[ 6], 6);
HH(aa, bb, cc, dd, X[13], 5);
HH(dd, aa, bb, cc, X[11], 12);
HH(cc, dd, aa, bb, X[ 5], 7);
HH(bb, cc, dd, aa, X[12], 5);
/* parallel round 3 */
GGG(aaa, bbb, ccc, ddd, X[15], 9);
GGG(ddd, aaa, bbb, ccc, X[ 5], 7);
GGG(ccc, ddd, aaa, bbb, X[ 1], 15);
GGG(bbb, ccc, ddd, aaa, X[ 3], 11);
GGG(aaa, bbb, ccc, ddd, X[ 7], 8);
GGG(ddd, aaa, bbb, ccc, X[14], 6);
GGG(ccc, ddd, aaa, bbb, X[ 6], 6);
GGG(bbb, ccc, ddd, aaa, X[ 9], 14);
GGG(aaa, bbb, ccc, ddd, X[11], 12);
GGG(ddd, aaa, bbb, ccc, X[ 8], 13);
GGG(ccc, ddd, aaa, bbb, X[12], 5);
GGG(bbb, ccc, ddd, aaa, X[ 2], 14);
GGG(aaa, bbb, ccc, ddd, X[10], 13);
GGG(ddd, aaa, bbb, ccc, X[ 0], 13);
GGG(ccc, ddd, aaa, bbb, X[ 4], 7);
GGG(bbb, ccc, ddd, aaa, X[13], 5);
tmp = cc; cc = ccc; ccc = tmp;
/* round 4 */
II(aa, bb, cc, dd, X[ 1], 11);
II(dd, aa, bb, cc, X[ 9], 12);
II(cc, dd, aa, bb, X[11], 14);
II(bb, cc, dd, aa, X[10], 15);
II(aa, bb, cc, dd, X[ 0], 14);
II(dd, aa, bb, cc, X[ 8], 15);
II(cc, dd, aa, bb, X[12], 9);
II(bb, cc, dd, aa, X[ 4], 8);
II(aa, bb, cc, dd, X[13], 9);
II(dd, aa, bb, cc, X[ 3], 14);
II(cc, dd, aa, bb, X[ 7], 5);
II(bb, cc, dd, aa, X[15], 6);
II(aa, bb, cc, dd, X[14], 8);
II(dd, aa, bb, cc, X[ 5], 6);
II(cc, dd, aa, bb, X[ 6], 5);
II(bb, cc, dd, aa, X[ 2], 12);
/* parallel round 4 */
FFF(aaa, bbb, ccc, ddd, X[ 8], 15);
FFF(ddd, aaa, bbb, ccc, X[ 6], 5);
FFF(ccc, ddd, aaa, bbb, X[ 4], 8);
FFF(bbb, ccc, ddd, aaa, X[ 1], 11);
FFF(aaa, bbb, ccc, ddd, X[ 3], 14);
FFF(ddd, aaa, bbb, ccc, X[11], 14);
FFF(ccc, ddd, aaa, bbb, X[15], 6);
FFF(bbb, ccc, ddd, aaa, X[ 0], 14);
FFF(aaa, bbb, ccc, ddd, X[ 5], 6);
FFF(ddd, aaa, bbb, ccc, X[12], 9);
FFF(ccc, ddd, aaa, bbb, X[ 2], 12);
FFF(bbb, ccc, ddd, aaa, X[13], 9);
FFF(aaa, bbb, ccc, ddd, X[ 9], 12);
FFF(ddd, aaa, bbb, ccc, X[ 7], 5);
FFF(ccc, ddd, aaa, bbb, X[10], 15);
FFF(bbb, ccc, ddd, aaa, X[14], 8);
tmp = dd; dd = ddd; ddd = tmp;
/* combine results */
md->rmd256.state[0] += aa;
md->rmd256.state[1] += bb;
md->rmd256.state[2] += cc;
md->rmd256.state[3] += dd;
md->rmd256.state[4] += aaa;
md->rmd256.state[5] += bbb;
md->rmd256.state[6] += ccc;
md->rmd256.state[7] += ddd;
return CRYPT_OK;
}
#ifdef LTC_CLEAN_STACK
static int rmd256_compress(hash_state *md, unsigned char *buf)
{
int err;
err = _rmd256_compress(md, buf);
burn_stack(sizeof(ulong32) * 25 + sizeof(int));
return err;
}
#endif
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int rmd256_init(hash_state * md)
{
LTC_ARGCHK(md != NULL);
md->rmd256.state[0] = 0x67452301UL;
md->rmd256.state[1] = 0xefcdab89UL;
md->rmd256.state[2] = 0x98badcfeUL;
md->rmd256.state[3] = 0x10325476UL;
md->rmd256.state[4] = 0x76543210UL;
md->rmd256.state[5] = 0xfedcba98UL;
md->rmd256.state[6] = 0x89abcdefUL;
md->rmd256.state[7] = 0x01234567UL;
md->rmd256.curlen = 0;
md->rmd256.length = 0;
return CRYPT_OK;
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
HASH_PROCESS(rmd256_process, rmd256_compress, rmd256, 64)
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (16 bytes)
@return CRYPT_OK if successful
*/
int rmd256_done(hash_state * md, unsigned char *out)
{
int i;
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
if (md->rmd256.curlen >= sizeof(md->rmd256.buf)) {
return CRYPT_INVALID_ARG;
}
/* increase the length of the message */
md->rmd256.length += md->rmd256.curlen * 8;
/* append the '1' bit */
md->rmd256.buf[md->rmd256.curlen++] = (unsigned char)0x80;
/* if the length is currently above 56 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (md->rmd256.curlen > 56) {
while (md->rmd256.curlen < 64) {
md->rmd256.buf[md->rmd256.curlen++] = (unsigned char)0;
}
rmd256_compress(md, md->rmd256.buf);
md->rmd256.curlen = 0;
}
/* pad upto 56 bytes of zeroes */
while (md->rmd256.curlen < 56) {
md->rmd256.buf[md->rmd256.curlen++] = (unsigned char)0;
}
/* store length */
STORE64L(md->rmd256.length, md->rmd256.buf+56);
rmd256_compress(md, md->rmd256.buf);
/* copy output */
for (i = 0; i < 8; i++) {
STORE32L(md->rmd256.state[i], out+(4*i));
}
#ifdef LTC_CLEAN_STACK
zeromem(md, sizeof(hash_state));
#endif
return CRYPT_OK;
}
void calc_rmd256(char *str,uint8_t *digest,uint8_t *message,int32_t len)
{
int init_hexbytes_noT(char *hexbytes,unsigned char *message,long len);
hash_state md;
rmd256_init(&md);
rmd256_process(&md,message,len);
rmd256_done(&md,digest);
if ( str != 0 )
init_hexbytes_noT(str,digest,32);
}
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int rmd256_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct {
char *msg;
unsigned char md[32];
} tests[] = {
{ "",
{ 0x02, 0xba, 0x4c, 0x4e, 0x5f, 0x8e, 0xcd, 0x18,
0x77, 0xfc, 0x52, 0xd6, 0x4d, 0x30, 0xe3, 0x7a,
0x2d, 0x97, 0x74, 0xfb, 0x1e, 0x5d, 0x02, 0x63,
0x80, 0xae, 0x01, 0x68, 0xe3, 0xc5, 0x52, 0x2d }
},
{ "a",
{ 0xf9, 0x33, 0x3e, 0x45, 0xd8, 0x57, 0xf5, 0xd9,
0x0a, 0x91, 0xba, 0xb7, 0x0a, 0x1e, 0xba, 0x0c,
0xfb, 0x1b, 0xe4, 0xb0, 0x78, 0x3c, 0x9a, 0xcf,
0xcd, 0x88, 0x3a, 0x91, 0x34, 0x69, 0x29, 0x25 }
},
{ "abc",
{ 0xaf, 0xbd, 0x6e, 0x22, 0x8b, 0x9d, 0x8c, 0xbb,
0xce, 0xf5, 0xca, 0x2d, 0x03, 0xe6, 0xdb, 0xa1,
0x0a, 0xc0, 0xbc, 0x7d, 0xcb, 0xe4, 0x68, 0x0e,
0x1e, 0x42, 0xd2, 0xe9, 0x75, 0x45, 0x9b, 0x65 }
},
{ "message digest",
{ 0x87, 0xe9, 0x71, 0x75, 0x9a, 0x1c, 0xe4, 0x7a,
0x51, 0x4d, 0x5c, 0x91, 0x4c, 0x39, 0x2c, 0x90,
0x18, 0xc7, 0xc4, 0x6b, 0xc1, 0x44, 0x65, 0x55,
0x4a, 0xfc, 0xdf, 0x54, 0xa5, 0x07, 0x0c, 0x0e }
},
{ "abcdefghijklmnopqrstuvwxyz",
{ 0x64, 0x9d, 0x30, 0x34, 0x75, 0x1e, 0xa2, 0x16,
0x77, 0x6b, 0xf9, 0xa1, 0x8a, 0xcc, 0x81, 0xbc,
0x78, 0x96, 0x11, 0x8a, 0x51, 0x97, 0x96, 0x87,
0x82, 0xdd, 0x1f, 0xd9, 0x7d, 0x8d, 0x51, 0x33 }
},
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
{ 0x57, 0x40, 0xa4, 0x08, 0xac, 0x16, 0xb7, 0x20,
0xb8, 0x44, 0x24, 0xae, 0x93, 0x1c, 0xbb, 0x1f,
0xe3, 0x63, 0xd1, 0xd0, 0xbf, 0x40, 0x17, 0xf1,
0xa8, 0x9f, 0x7e, 0xa6, 0xde, 0x77, 0xa0, 0xb8 }
}
};
int x;
unsigned char buf[32];
hash_state md;
for (x = 0; x < (int)(sizeof(tests)/sizeof(tests[0])); x++) {
rmd256_init(&md);
rmd256_process(&md, (unsigned char *)tests[x].msg, strlen(tests[x].msg));
rmd256_done(&md, buf);
if (XMEMCMP(buf, tests[x].md, 32) != 0) {
#if 0
printf("Failed test %d\n", x);
#endif
return CRYPT_FAIL_TESTVECTOR;
}
}
return CRYPT_OK;
#endif
}
#undef FF
#undef GG
#undef HH
#undef II
#undef FFF
#undef GGG
#undef HHH
#undef III
#undef F
#undef G
#undef H
#undef I
#undef J
#endif

519
crypto777/hmac/rmd320.c

@ -0,0 +1,519 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@file rmd320.c
RMD320 hash function
*/
#ifdef LTC_RIPEMD320
const struct ltc_hash_descriptor rmd320_desc =
{
"rmd320",
9,
40,
64,
/* OID */
{ 0 },
0,
&rmd320_init,
&rmd320_process,
&rmd320_done,
&rmd320_test,
NULL
};
/* the five basic functions F(), G() and H() */
#define F(x, y, z) ((x) ^ (y) ^ (z))
#define G(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define H(x, y, z) (((x) | ~(y)) ^ (z))
#define I(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define J(x, y, z) ((x) ^ ((y) | ~(z)))
/* the ten basic operations FF() through III() */
#define FF(a, b, c, d, e, x, s) \
(a) += F((b), (c), (d)) + (x);\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define GG(a, b, c, d, e, x, s) \
(a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define HH(a, b, c, d, e, x, s) \
(a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define II(a, b, c, d, e, x, s) \
(a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define JJ(a, b, c, d, e, x, s) \
(a) += J((b), (c), (d)) + (x) + 0xa953fd4eUL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define FFF(a, b, c, d, e, x, s) \
(a) += F((b), (c), (d)) + (x);\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define GGG(a, b, c, d, e, x, s) \
(a) += G((b), (c), (d)) + (x) + 0x7a6d76e9UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define HHH(a, b, c, d, e, x, s) \
(a) += H((b), (c), (d)) + (x) + 0x6d703ef3UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define III(a, b, c, d, e, x, s) \
(a) += I((b), (c), (d)) + (x) + 0x5c4dd124UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#define JJJ(a, b, c, d, e, x, s) \
(a) += J((b), (c), (d)) + (x) + 0x50a28be6UL;\
(a) = ROLc((a), (s)) + (e);\
(c) = ROLc((c), 10);
#ifdef LTC_CLEAN_STACK
static int _rmd320_compress(hash_state *md, unsigned char *buf)
#else
static int rmd320_compress(hash_state *md, unsigned char *buf)
#endif
{
ulong32 aa,bb,cc,dd,ee,aaa,bbb,ccc,ddd,eee,tmp,X[16];
int i;
/* load words X */
for (i = 0; i < 16; i++){
LOAD32L(X[i], buf + (4 * i));
}
/* load state */
aa = md->rmd320.state[0];
bb = md->rmd320.state[1];
cc = md->rmd320.state[2];
dd = md->rmd320.state[3];
ee = md->rmd320.state[4];
aaa = md->rmd320.state[5];
bbb = md->rmd320.state[6];
ccc = md->rmd320.state[7];
ddd = md->rmd320.state[8];
eee = md->rmd320.state[9];
/* round 1 */
FF(aa, bb, cc, dd, ee, X[ 0], 11);
FF(ee, aa, bb, cc, dd, X[ 1], 14);
FF(dd, ee, aa, bb, cc, X[ 2], 15);
FF(cc, dd, ee, aa, bb, X[ 3], 12);
FF(bb, cc, dd, ee, aa, X[ 4], 5);
FF(aa, bb, cc, dd, ee, X[ 5], 8);
FF(ee, aa, bb, cc, dd, X[ 6], 7);
FF(dd, ee, aa, bb, cc, X[ 7], 9);
FF(cc, dd, ee, aa, bb, X[ 8], 11);
FF(bb, cc, dd, ee, aa, X[ 9], 13);
FF(aa, bb, cc, dd, ee, X[10], 14);
FF(ee, aa, bb, cc, dd, X[11], 15);
FF(dd, ee, aa, bb, cc, X[12], 6);
FF(cc, dd, ee, aa, bb, X[13], 7);
FF(bb, cc, dd, ee, aa, X[14], 9);
FF(aa, bb, cc, dd, ee, X[15], 8);
/* parallel round 1 */
JJJ(aaa, bbb, ccc, ddd, eee, X[ 5], 8);
JJJ(eee, aaa, bbb, ccc, ddd, X[14], 9);
JJJ(ddd, eee, aaa, bbb, ccc, X[ 7], 9);
JJJ(ccc, ddd, eee, aaa, bbb, X[ 0], 11);
JJJ(bbb, ccc, ddd, eee, aaa, X[ 9], 13);
JJJ(aaa, bbb, ccc, ddd, eee, X[ 2], 15);
JJJ(eee, aaa, bbb, ccc, ddd, X[11], 15);
JJJ(ddd, eee, aaa, bbb, ccc, X[ 4], 5);
JJJ(ccc, ddd, eee, aaa, bbb, X[13], 7);
JJJ(bbb, ccc, ddd, eee, aaa, X[ 6], 7);
JJJ(aaa, bbb, ccc, ddd, eee, X[15], 8);
JJJ(eee, aaa, bbb, ccc, ddd, X[ 8], 11);
JJJ(ddd, eee, aaa, bbb, ccc, X[ 1], 14);
JJJ(ccc, ddd, eee, aaa, bbb, X[10], 14);
JJJ(bbb, ccc, ddd, eee, aaa, X[ 3], 12);
JJJ(aaa, bbb, ccc, ddd, eee, X[12], 6);
tmp = aa; aa = aaa; aaa = tmp;
/* round 2 */
GG(ee, aa, bb, cc, dd, X[ 7], 7);
GG(dd, ee, aa, bb, cc, X[ 4], 6);
GG(cc, dd, ee, aa, bb, X[13], 8);
GG(bb, cc, dd, ee, aa, X[ 1], 13);
GG(aa, bb, cc, dd, ee, X[10], 11);
GG(ee, aa, bb, cc, dd, X[ 6], 9);
GG(dd, ee, aa, bb, cc, X[15], 7);
GG(cc, dd, ee, aa, bb, X[ 3], 15);
GG(bb, cc, dd, ee, aa, X[12], 7);
GG(aa, bb, cc, dd, ee, X[ 0], 12);
GG(ee, aa, bb, cc, dd, X[ 9], 15);
GG(dd, ee, aa, bb, cc, X[ 5], 9);
GG(cc, dd, ee, aa, bb, X[ 2], 11);
GG(bb, cc, dd, ee, aa, X[14], 7);
GG(aa, bb, cc, dd, ee, X[11], 13);
GG(ee, aa, bb, cc, dd, X[ 8], 12);
/* parallel round 2 */
III(eee, aaa, bbb, ccc, ddd, X[ 6], 9);
III(ddd, eee, aaa, bbb, ccc, X[11], 13);
III(ccc, ddd, eee, aaa, bbb, X[ 3], 15);
III(bbb, ccc, ddd, eee, aaa, X[ 7], 7);
III(aaa, bbb, ccc, ddd, eee, X[ 0], 12);
III(eee, aaa, bbb, ccc, ddd, X[13], 8);
III(ddd, eee, aaa, bbb, ccc, X[ 5], 9);
III(ccc, ddd, eee, aaa, bbb, X[10], 11);
III(bbb, ccc, ddd, eee, aaa, X[14], 7);
III(aaa, bbb, ccc, ddd, eee, X[15], 7);
III(eee, aaa, bbb, ccc, ddd, X[ 8], 12);
III(ddd, eee, aaa, bbb, ccc, X[12], 7);
III(ccc, ddd, eee, aaa, bbb, X[ 4], 6);
III(bbb, ccc, ddd, eee, aaa, X[ 9], 15);
III(aaa, bbb, ccc, ddd, eee, X[ 1], 13);
III(eee, aaa, bbb, ccc, ddd, X[ 2], 11);
tmp = bb; bb = bbb; bbb = tmp;
/* round 3 */
HH(dd, ee, aa, bb, cc, X[ 3], 11);
HH(cc, dd, ee, aa, bb, X[10], 13);
HH(bb, cc, dd, ee, aa, X[14], 6);
HH(aa, bb, cc, dd, ee, X[ 4], 7);
HH(ee, aa, bb, cc, dd, X[ 9], 14);
HH(dd, ee, aa, bb, cc, X[15], 9);
HH(cc, dd, ee, aa, bb, X[ 8], 13);
HH(bb, cc, dd, ee, aa, X[ 1], 15);
HH(aa, bb, cc, dd, ee, X[ 2], 14);
HH(ee, aa, bb, cc, dd, X[ 7], 8);
HH(dd, ee, aa, bb, cc, X[ 0], 13);
HH(cc, dd, ee, aa, bb, X[ 6], 6);
HH(bb, cc, dd, ee, aa, X[13], 5);
HH(aa, bb, cc, dd, ee, X[11], 12);
HH(ee, aa, bb, cc, dd, X[ 5], 7);
HH(dd, ee, aa, bb, cc, X[12], 5);
/* parallel round 3 */
HHH(ddd, eee, aaa, bbb, ccc, X[15], 9);
HHH(ccc, ddd, eee, aaa, bbb, X[ 5], 7);
HHH(bbb, ccc, ddd, eee, aaa, X[ 1], 15);
HHH(aaa, bbb, ccc, ddd, eee, X[ 3], 11);
HHH(eee, aaa, bbb, ccc, ddd, X[ 7], 8);
HHH(ddd, eee, aaa, bbb, ccc, X[14], 6);
HHH(ccc, ddd, eee, aaa, bbb, X[ 6], 6);
HHH(bbb, ccc, ddd, eee, aaa, X[ 9], 14);
HHH(aaa, bbb, ccc, ddd, eee, X[11], 12);
HHH(eee, aaa, bbb, ccc, ddd, X[ 8], 13);
HHH(ddd, eee, aaa, bbb, ccc, X[12], 5);
HHH(ccc, ddd, eee, aaa, bbb, X[ 2], 14);
HHH(bbb, ccc, ddd, eee, aaa, X[10], 13);
HHH(aaa, bbb, ccc, ddd, eee, X[ 0], 13);
HHH(eee, aaa, bbb, ccc, ddd, X[ 4], 7);
HHH(ddd, eee, aaa, bbb, ccc, X[13], 5);
tmp = cc; cc = ccc; ccc = tmp;
/* round 4 */
II(cc, dd, ee, aa, bb, X[ 1], 11);
II(bb, cc, dd, ee, aa, X[ 9], 12);
II(aa, bb, cc, dd, ee, X[11], 14);
II(ee, aa, bb, cc, dd, X[10], 15);
II(dd, ee, aa, bb, cc, X[ 0], 14);
II(cc, dd, ee, aa, bb, X[ 8], 15);
II(bb, cc, dd, ee, aa, X[12], 9);
II(aa, bb, cc, dd, ee, X[ 4], 8);
II(ee, aa, bb, cc, dd, X[13], 9);
II(dd, ee, aa, bb, cc, X[ 3], 14);
II(cc, dd, ee, aa, bb, X[ 7], 5);
II(bb, cc, dd, ee, aa, X[15], 6);
II(aa, bb, cc, dd, ee, X[14], 8);
II(ee, aa, bb, cc, dd, X[ 5], 6);
II(dd, ee, aa, bb, cc, X[ 6], 5);
II(cc, dd, ee, aa, bb, X[ 2], 12);
/* parallel round 4 */
GGG(ccc, ddd, eee, aaa, bbb, X[ 8], 15);
GGG(bbb, ccc, ddd, eee, aaa, X[ 6], 5);
GGG(aaa, bbb, ccc, ddd, eee, X[ 4], 8);
GGG(eee, aaa, bbb, ccc, ddd, X[ 1], 11);
GGG(ddd, eee, aaa, bbb, ccc, X[ 3], 14);
GGG(ccc, ddd, eee, aaa, bbb, X[11], 14);
GGG(bbb, ccc, ddd, eee, aaa, X[15], 6);
GGG(aaa, bbb, ccc, ddd, eee, X[ 0], 14);
GGG(eee, aaa, bbb, ccc, ddd, X[ 5], 6);
GGG(ddd, eee, aaa, bbb, ccc, X[12], 9);
GGG(ccc, ddd, eee, aaa, bbb, X[ 2], 12);
GGG(bbb, ccc, ddd, eee, aaa, X[13], 9);
GGG(aaa, bbb, ccc, ddd, eee, X[ 9], 12);
GGG(eee, aaa, bbb, ccc, ddd, X[ 7], 5);
GGG(ddd, eee, aaa, bbb, ccc, X[10], 15);
GGG(ccc, ddd, eee, aaa, bbb, X[14], 8);
tmp = dd; dd = ddd; ddd = tmp;
/* round 5 */
JJ(bb, cc, dd, ee, aa, X[ 4], 9);
JJ(aa, bb, cc, dd, ee, X[ 0], 15);
JJ(ee, aa, bb, cc, dd, X[ 5], 5);
JJ(dd, ee, aa, bb, cc, X[ 9], 11);
JJ(cc, dd, ee, aa, bb, X[ 7], 6);
JJ(bb, cc, dd, ee, aa, X[12], 8);
JJ(aa, bb, cc, dd, ee, X[ 2], 13);
JJ(ee, aa, bb, cc, dd, X[10], 12);
JJ(dd, ee, aa, bb, cc, X[14], 5);
JJ(cc, dd, ee, aa, bb, X[ 1], 12);
JJ(bb, cc, dd, ee, aa, X[ 3], 13);
JJ(aa, bb, cc, dd, ee, X[ 8], 14);
JJ(ee, aa, bb, cc, dd, X[11], 11);
JJ(dd, ee, aa, bb, cc, X[ 6], 8);
JJ(cc, dd, ee, aa, bb, X[15], 5);
JJ(bb, cc, dd, ee, aa, X[13], 6);
/* parallel round 5 */
FFF(bbb, ccc, ddd, eee, aaa, X[12] , 8);
FFF(aaa, bbb, ccc, ddd, eee, X[15] , 5);
FFF(eee, aaa, bbb, ccc, ddd, X[10] , 12);
FFF(ddd, eee, aaa, bbb, ccc, X[ 4] , 9);
FFF(ccc, ddd, eee, aaa, bbb, X[ 1] , 12);
FFF(bbb, ccc, ddd, eee, aaa, X[ 5] , 5);
FFF(aaa, bbb, ccc, ddd, eee, X[ 8] , 14);
FFF(eee, aaa, bbb, ccc, ddd, X[ 7] , 6);
FFF(ddd, eee, aaa, bbb, ccc, X[ 6] , 8);
FFF(ccc, ddd, eee, aaa, bbb, X[ 2] , 13);
FFF(bbb, ccc, ddd, eee, aaa, X[13] , 6);
FFF(aaa, bbb, ccc, ddd, eee, X[14] , 5);
FFF(eee, aaa, bbb, ccc, ddd, X[ 0] , 15);
FFF(ddd, eee, aaa, bbb, ccc, X[ 3] , 13);
FFF(ccc, ddd, eee, aaa, bbb, X[ 9] , 11);
FFF(bbb, ccc, ddd, eee, aaa, X[11] , 11);
tmp = ee; ee = eee; eee = tmp;
/* combine results */
md->rmd320.state[0] += aa;
md->rmd320.state[1] += bb;
md->rmd320.state[2] += cc;
md->rmd320.state[3] += dd;
md->rmd320.state[4] += ee;
md->rmd320.state[5] += aaa;
md->rmd320.state[6] += bbb;
md->rmd320.state[7] += ccc;
md->rmd320.state[8] += ddd;
md->rmd320.state[9] += eee;
return CRYPT_OK;
}
#ifdef LTC_CLEAN_STACK
static int rmd320_compress(hash_state *md, unsigned char *buf)
{
int err;
err = _rmd320_compress(md, buf);
burn_stack(sizeof(ulong32) * 27 + sizeof(int));
return err;
}
#endif
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int rmd320_init(hash_state * md)
{
LTC_ARGCHK(md != NULL);
md->rmd320.state[0] = 0x67452301UL;
md->rmd320.state[1] = 0xefcdab89UL;
md->rmd320.state[2] = 0x98badcfeUL;
md->rmd320.state[3] = 0x10325476UL;
md->rmd320.state[4] = 0xc3d2e1f0UL;
md->rmd320.state[5] = 0x76543210UL;
md->rmd320.state[6] = 0xfedcba98UL;
md->rmd320.state[7] = 0x89abcdefUL;
md->rmd320.state[8] = 0x01234567UL;
md->rmd320.state[9] = 0x3c2d1e0fUL;
md->rmd320.curlen = 0;
md->rmd320.length = 0;
return CRYPT_OK;
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
HASH_PROCESS(rmd320_process, rmd320_compress, rmd320, 64)
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (20 bytes)
@return CRYPT_OK if successful
*/
int rmd320_done(hash_state * md, unsigned char *out)
{
int i;
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
if (md->rmd320.curlen >= sizeof(md->rmd320.buf)) {
return CRYPT_INVALID_ARG;
}
/* increase the length of the message */
md->rmd320.length += md->rmd320.curlen * 8;
/* append the '1' bit */
md->rmd320.buf[md->rmd320.curlen++] = (unsigned char)0x80;
/* if the length is currently above 56 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (md->rmd320.curlen > 56) {
while (md->rmd320.curlen < 64) {
md->rmd320.buf[md->rmd320.curlen++] = (unsigned char)0;
}
rmd320_compress(md, md->rmd320.buf);
md->rmd320.curlen = 0;
}
/* pad upto 56 bytes of zeroes */
while (md->rmd320.curlen < 56) {
md->rmd320.buf[md->rmd320.curlen++] = (unsigned char)0;
}
/* store length */
STORE64L(md->rmd320.length, md->rmd320.buf+56);
rmd320_compress(md, md->rmd320.buf);
/* copy output */
for (i = 0; i < 10; i++) {
STORE32L(md->rmd320.state[i], out+(4*i));
}
#ifdef LTC_CLEAN_STACK
zeromem(md, sizeof(hash_state));
#endif
return CRYPT_OK;
}
void calc_rmd320(char *str,uint8_t *digest,uint8_t *message,int32_t len)
{
int init_hexbytes_noT(char *hexbytes,unsigned char *message,long len);
hash_state md;
rmd320_init(&md);
rmd320_process(&md,message,len);
rmd320_done(&md,digest);
if ( str != 0 )
init_hexbytes_noT(str,digest,40);
}
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int rmd320_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct {
char *msg;
unsigned char md[40];
} tests[] = {
{ "",
{ 0x22, 0xd6, 0x5d, 0x56, 0x61, 0x53, 0x6c, 0xdc, 0x75, 0xc1,
0xfd, 0xf5, 0xc6, 0xde, 0x7b, 0x41, 0xb9, 0xf2, 0x73, 0x25,
0xeb, 0xc6, 0x1e, 0x85, 0x57, 0x17, 0x7d, 0x70, 0x5a, 0x0e,
0xc8, 0x80, 0x15, 0x1c, 0x3a, 0x32, 0xa0, 0x08, 0x99, 0xb8 }
},
{ "a",
{ 0xce, 0x78, 0x85, 0x06, 0x38, 0xf9, 0x26, 0x58, 0xa5, 0xa5,
0x85, 0x09, 0x75, 0x79, 0x92, 0x6d, 0xda, 0x66, 0x7a, 0x57,
0x16, 0x56, 0x2c, 0xfc, 0xf6, 0xfb, 0xe7, 0x7f, 0x63, 0x54,
0x2f, 0x99, 0xb0, 0x47, 0x05, 0xd6, 0x97, 0x0d, 0xff, 0x5d }
},
{ "abc",
{ 0xde, 0x4c, 0x01, 0xb3, 0x05, 0x4f, 0x89, 0x30, 0xa7, 0x9d,
0x09, 0xae, 0x73, 0x8e, 0x92, 0x30, 0x1e, 0x5a, 0x17, 0x08,
0x5b, 0xef, 0xfd, 0xc1, 0xb8, 0xd1, 0x16, 0x71, 0x3e, 0x74,
0xf8, 0x2f, 0xa9, 0x42, 0xd6, 0x4c, 0xdb, 0xc4, 0x68, 0x2d }
},
{ "message digest",
{ 0x3a, 0x8e, 0x28, 0x50, 0x2e, 0xd4, 0x5d, 0x42, 0x2f, 0x68,
0x84, 0x4f, 0x9d, 0xd3, 0x16, 0xe7, 0xb9, 0x85, 0x33, 0xfa,
0x3f, 0x2a, 0x91, 0xd2, 0x9f, 0x84, 0xd4, 0x25, 0xc8, 0x8d,
0x6b, 0x4e, 0xff, 0x72, 0x7d, 0xf6, 0x6a, 0x7c, 0x01, 0x97 }
},
{ "abcdefghijklmnopqrstuvwxyz",
{ 0xca, 0xbd, 0xb1, 0x81, 0x0b, 0x92, 0x47, 0x0a, 0x20, 0x93,
0xaa, 0x6b, 0xce, 0x05, 0x95, 0x2c, 0x28, 0x34, 0x8c, 0xf4,
0x3f, 0xf6, 0x08, 0x41, 0x97, 0x51, 0x66, 0xbb, 0x40, 0xed,
0x23, 0x40, 0x04, 0xb8, 0x82, 0x44, 0x63, 0xe6, 0xb0, 0x09 }
},
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
{ 0xd0, 0x34, 0xa7, 0x95, 0x0c, 0xf7, 0x22, 0x02, 0x1b, 0xa4,
0xb8, 0x4d, 0xf7, 0x69, 0xa5, 0xde, 0x20, 0x60, 0xe2, 0x59,
0xdf, 0x4c, 0x9b, 0xb4, 0xa4, 0x26, 0x8c, 0x0e, 0x93, 0x5b,
0xbc, 0x74, 0x70, 0xa9, 0x69, 0xc9, 0xd0, 0x72, 0xa1, 0xac }
}
};
int x;
unsigned char buf[40];
hash_state md;
for (x = 0; x < (int)(sizeof(tests)/sizeof(tests[0])); x++) {
rmd320_init(&md);
rmd320_process(&md, (unsigned char *)tests[x].msg, strlen(tests[x].msg));
rmd320_done(&md, buf);
if (XMEMCMP(buf, tests[x].md, 40) != 0) {
#if 0
printf("Failed test %d\n", x);
#endif
return CRYPT_FAIL_TESTVECTOR;
}
}
return CRYPT_OK;
#endif
}
#undef FF
#undef GG
#undef HH
#undef II
#undef FFF
#undef GGG
#undef HHH
#undef III
#undef F
#undef G
#undef H
#undef I
#undef J
#endif

302
crypto777/hmac/sha1.c

@ -0,0 +1,302 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#define LTC_SHA1
#include "tomcrypt.h"
/**
@file sha1.c
LTC_SHA1 code by Tom St Denis
*/
#ifdef LTC_SHA1
const struct ltc_hash_descriptor sha1_desc =
{
"sha1",
2,
20,
64,
/* OID */
{ 1, 3, 14, 3, 2, 26, },
6,
&sha1_init,
&sha1_process,
&sha1_done,
&sha1_test,
NULL
};
#define F0(x,y,z) (z ^ (x & (y ^ z)))
#define F1(x,y,z) (x ^ y ^ z)
#define F2(x,y,z) ((x & y) | (z & (x | y)))
#define F3(x,y,z) (x ^ y ^ z)
#ifdef LTC_CLEAN_STACK
static int _sha1_compress(hash_state *md, unsigned char *buf)
#else
static int sha1_compress(hash_state *md, unsigned char *buf)
#endif
{
ulong32 a,b,c,d,e,W[80],i;
#ifdef LTC_SMALL_CODE
ulong32 t;
#endif
/* copy the state into 512-bits into W[0..15] */
for (i = 0; i < 16; i++) {
LOAD32H(W[i], buf + (4*i));
}
/* copy state */
a = md->sha1.state[0];
b = md->sha1.state[1];
c = md->sha1.state[2];
d = md->sha1.state[3];
e = md->sha1.state[4];
/* expand it */
for (i = 16; i < 80; i++) {
W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
}
/* compress */
/* round one */
#define FF0(a,b,c,d,e,i) e = (ROLc(a, 5) + F0(b,c,d) + e + W[i] + 0x5a827999UL); b = ROLc(b, 30);
#define FF1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30);
#define FF2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30);
#define FF3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30);
#ifdef LTC_SMALL_CODE
for (i = 0; i < 20; ) {
FF0(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
}
for (; i < 40; ) {
FF1(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
}
for (; i < 60; ) {
FF2(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
}
for (; i < 80; ) {
FF3(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
}
#else
for (i = 0; i < 20; ) {
FF0(a,b,c,d,e,i++);
FF0(e,a,b,c,d,i++);
FF0(d,e,a,b,c,i++);
FF0(c,d,e,a,b,i++);
FF0(b,c,d,e,a,i++);
}
/* round two */
for (; i < 40; ) {
FF1(a,b,c,d,e,i++);
FF1(e,a,b,c,d,i++);
FF1(d,e,a,b,c,i++);
FF1(c,d,e,a,b,i++);
FF1(b,c,d,e,a,i++);
}
/* round three */
for (; i < 60; ) {
FF2(a,b,c,d,e,i++);
FF2(e,a,b,c,d,i++);
FF2(d,e,a,b,c,i++);
FF2(c,d,e,a,b,i++);
FF2(b,c,d,e,a,i++);
}
/* round four */
for (; i < 80; ) {
FF3(a,b,c,d,e,i++);
FF3(e,a,b,c,d,i++);
FF3(d,e,a,b,c,i++);
FF3(c,d,e,a,b,i++);
FF3(b,c,d,e,a,i++);
}
#endif
#undef FF0
#undef FF1
#undef FF2
#undef FF3
/* store */
md->sha1.state[0] = md->sha1.state[0] + a;
md->sha1.state[1] = md->sha1.state[1] + b;
md->sha1.state[2] = md->sha1.state[2] + c;
md->sha1.state[3] = md->sha1.state[3] + d;
md->sha1.state[4] = md->sha1.state[4] + e;
return CRYPT_OK;
}
#ifdef LTC_CLEAN_STACK
static int sha1_compress(hash_state *md, unsigned char *buf)
{
int err;
err = _sha1_compress(md, buf);
burn_stack(sizeof(ulong32) * 87);
return err;
}
#endif
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int sha1_init(hash_state * md)
{
LTC_ARGCHK(md != NULL);
md->sha1.state[0] = 0x67452301UL;
md->sha1.state[1] = 0xefcdab89UL;
md->sha1.state[2] = 0x98badcfeUL;
md->sha1.state[3] = 0x10325476UL;
md->sha1.state[4] = 0xc3d2e1f0UL;
md->sha1.curlen = 0;
md->sha1.length = 0;
return CRYPT_OK;
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
HASH_PROCESS(sha1_process, sha1_compress, sha1, 64)
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (20 bytes)
@return CRYPT_OK if successful
*/
int sha1_done(hash_state * md, unsigned char *out)
{
int i;
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
if (md->sha1.curlen >= sizeof(md->sha1.buf)) {
return CRYPT_INVALID_ARG;
}
/* increase the length of the message */
md->sha1.length += md->sha1.curlen * 8;
/* append the '1' bit */
md->sha1.buf[md->sha1.curlen++] = (unsigned char)0x80;
/* if the length is currently above 56 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (md->sha1.curlen > 56) {
while (md->sha1.curlen < 64) {
md->sha1.buf[md->sha1.curlen++] = (unsigned char)0;
}
sha1_compress(md, md->sha1.buf);
md->sha1.curlen = 0;
}
/* pad upto 56 bytes of zeroes */
while (md->sha1.curlen < 56) {
md->sha1.buf[md->sha1.curlen++] = (unsigned char)0;
}
/* store length */
STORE64H(md->sha1.length, md->sha1.buf+56);
sha1_compress(md, md->sha1.buf);
/* copy output */
for (i = 0; i < 5; i++) {
STORE32H(md->sha1.state[i], out+(4*i));
}
#ifdef LTC_CLEAN_STACK
zeromem(md, sizeof(hash_state));
#endif
return CRYPT_OK;
}
void calc_sha1(char *str,uint8_t *digest,uint8_t *message,int32_t len)
{
int init_hexbytes_noT(char *hexbytes,unsigned char *message,long len);
hash_state md;
sha1_init(&md);
sha1_process(&md,message,len);
sha1_done(&md,digest);
if ( str != 0 )
init_hexbytes_noT(str,digest,20);
}
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int sha1_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct {
char *msg;
unsigned char hash[20];
} tests[] = {
{ "abc",
{ 0xa9, 0x99, 0x3e, 0x36, 0x47, 0x06, 0x81, 0x6a,
0xba, 0x3e, 0x25, 0x71, 0x78, 0x50, 0xc2, 0x6c,
0x9c, 0xd0, 0xd8, 0x9d }
},
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
{ 0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E,
0xBA, 0xAE, 0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5,
0xE5, 0x46, 0x70, 0xF1 }
}
};
int i;
unsigned char tmp[20];
hash_state md;
for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
sha1_init(&md);
sha1_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
sha1_done(&md, tmp);
if (XMEMCMP(tmp, tests[i].hash, 20) != 0) {
return CRYPT_FAIL_TESTVECTOR;
}
}
return CRYPT_OK;
#endif
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/sha1.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */

137
crypto777/hmac/sha224.c

@ -0,0 +1,137 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
/**
@param sha224.c
LTC_SHA-224 new NIST standard based off of LTC_SHA-256 truncated to 224 bits (Tom St Denis)
*/
#include "tomcrypt.h"
const struct ltc_hash_descriptor sha224_desc =
{
"sha224",
10,
28,
64,
/* OID */
{ 2, 16, 840, 1, 101, 3, 4, 2, 4, },
9,
&sha224_init,
&sha256_process,
&sha224_done,
&sha224_test,
NULL
};
/* init the sha256 er... sha224 state ;-) */
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int sha224_init(hash_state * md)
{
LTC_ARGCHK(md != NULL);
md->sha256.curlen = 0;
md->sha256.length = 0;
md->sha256.state[0] = 0xc1059ed8UL;
md->sha256.state[1] = 0x367cd507UL;
md->sha256.state[2] = 0x3070dd17UL;
md->sha256.state[3] = 0xf70e5939UL;
md->sha256.state[4] = 0xffc00b31UL;
md->sha256.state[5] = 0x68581511UL;
md->sha256.state[6] = 0x64f98fa7UL;
md->sha256.state[7] = 0xbefa4fa4UL;
return CRYPT_OK;
}
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (28 bytes)
@return CRYPT_OK if successful
*/
int sha224_done(hash_state * md, unsigned char *out)
{
unsigned char buf[32];
int err;
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
err = sha256_done(md, buf);
XMEMCPY(out, buf, 28);
#ifdef LTC_CLEAN_STACK
zeromem(buf, sizeof(buf));
#endif
return err;
}
void calc_sha224(char *str,uint8_t *digest,uint8_t *message,int32_t len)
{
int init_hexbytes_noT(char *hexbytes,unsigned char *message,long len);
hash_state md;
sha224_init(&md);
sha224_process(&md,message,len);
sha224_done(&md,digest);
if ( str != 0 )
init_hexbytes_noT(str,digest,28);
}
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int sha224_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct {
char *msg;
unsigned char hash[28];
} tests[] = {
{ "abc",
{ 0x23, 0x09, 0x7d, 0x22, 0x34, 0x05, 0xd8,
0x22, 0x86, 0x42, 0xa4, 0x77, 0xbd, 0xa2,
0x55, 0xb3, 0x2a, 0xad, 0xbc, 0xe4, 0xbd,
0xa0, 0xb3, 0xf7, 0xe3, 0x6c, 0x9d, 0xa7 }
},
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
{ 0x75, 0x38, 0x8b, 0x16, 0x51, 0x27, 0x76,
0xcc, 0x5d, 0xba, 0x5d, 0xa1, 0xfd, 0x89,
0x01, 0x50, 0xb0, 0xc6, 0x45, 0x5c, 0xb4,
0xf5, 0x8b, 0x19, 0x52, 0x52, 0x25, 0x25 }
},
};
int i;
unsigned char tmp[28];
hash_state md;
for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
sha224_init(&md);
sha224_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
sha224_done(&md, tmp);
if (XMEMCMP(tmp, tests[i].hash, 28) != 0) {
return CRYPT_FAIL_TESTVECTOR;
}
}
return CRYPT_OK;
#endif
}
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/sha2/sha224.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */

442
crypto777/hmac/sha256.c

@ -0,0 +1,442 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@file sha256.c
LTC_SHA256 by Tom St Denis
*/
//#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] = {
0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,
0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,
0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,
0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,
0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,
0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,
0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,
0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,
0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,
0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
};
#endif
/* Various logical functions */
#define Ch(x,y,z) (z ^ (x & (y ^ z)))
#define Maj(x,y,z) (((x | y) & z) | (x & y))
#define S(x, n) RORc((x),(n))
#define R(x, n) (((x)&0xFFFFFFFFUL)>>(n))
#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22))
#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25))
#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3))
#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10))
/* compress 512-bits */
#ifdef LTC_CLEAN_STACK
static int _sha256_compress(hash_state * md, unsigned char *buf)
#else
static int sha256_compress(hash_state * md, unsigned char *buf)
#endif
{
ulong32 S[8], W[64], t0, t1;
#ifdef LTC_SMALL_CODE
ulong32 t;
#endif
int i;
/* copy state into S */
for (i = 0; i < 8; i++) {
S[i] = md->sha256.state[i];
}
/* copy the state into 512-bits into W[0..15] */
for (i = 0; i < 16; i++) {
LOAD32H(W[i], buf + (4*i));
}
/* fill W[16..63] */
for (i = 16; i < 64; i++) {
W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
}
/* Compress */
#ifdef LTC_SMALL_CODE
#define RND(a,b,c,d,e,f,g,h,i) \
t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \
t1 = Sigma0(a) + Maj(a, b, c); \
d += t0; \
h = t0 + t1;
for (i = 0; i < 64; ++i) {
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i);
t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4];
S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;
}
#else
#define RND(a,b,c,d,e,f,g,h,i,ki) \
t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i]; \
t1 = Sigma0(a) + Maj(a, b, c); \
d += t0; \
h = t0 + t1;
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],0,0x428a2f98);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],1,0x71374491);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],2,0xb5c0fbcf);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],3,0xe9b5dba5);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],4,0x3956c25b);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],5,0x59f111f1);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],6,0x923f82a4);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],7,0xab1c5ed5);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],8,0xd807aa98);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],9,0x12835b01);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],10,0x243185be);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],11,0x550c7dc3);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],12,0x72be5d74);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],13,0x80deb1fe);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],14,0x9bdc06a7);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],15,0xc19bf174);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],16,0xe49b69c1);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],17,0xefbe4786);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],18,0x0fc19dc6);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],19,0x240ca1cc);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],20,0x2de92c6f);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],21,0x4a7484aa);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],22,0x5cb0a9dc);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],23,0x76f988da);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],24,0x983e5152);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],25,0xa831c66d);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],26,0xb00327c8);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],27,0xbf597fc7);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],28,0xc6e00bf3);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],29,0xd5a79147);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],30,0x06ca6351);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],31,0x14292967);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],32,0x27b70a85);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],33,0x2e1b2138);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],34,0x4d2c6dfc);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],35,0x53380d13);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],36,0x650a7354);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],37,0x766a0abb);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],38,0x81c2c92e);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],39,0x92722c85);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],40,0xa2bfe8a1);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],41,0xa81a664b);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],42,0xc24b8b70);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],43,0xc76c51a3);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],44,0xd192e819);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],45,0xd6990624);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],46,0xf40e3585);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],47,0x106aa070);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],48,0x19a4c116);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],49,0x1e376c08);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],50,0x2748774c);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],51,0x34b0bcb5);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],52,0x391c0cb3);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],53,0x4ed8aa4a);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],54,0x5b9cca4f);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],55,0x682e6ff3);
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],56,0x748f82ee);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],57,0x78a5636f);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],58,0x84c87814);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],59,0x8cc70208);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],60,0x90befffa);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],61,0xa4506ceb);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2);
#undef RND
#endif
/* feedback */
for (i = 0; i < 8; i++) {
md->sha256.state[i] = md->sha256.state[i] + S[i];
}
return CRYPT_OK;
}
#ifdef LTC_CLEAN_STACK
static int sha256_compress(hash_state * md, unsigned char *buf)
{
int err;
err = _sha256_compress(md, buf);
burn_stack(sizeof(ulong32) * 74);
return err;
}
#endif
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int sha256_init(hash_state * md)
{
LTC_ARGCHK(md != NULL);
md->sha256.curlen = 0;
md->sha256.length = 0;
md->sha256.state[0] = 0x6A09E667UL;
md->sha256.state[1] = 0xBB67AE85UL;
md->sha256.state[2] = 0x3C6EF372UL;
md->sha256.state[3] = 0xA54FF53AUL;
md->sha256.state[4] = 0x510E527FUL;
md->sha256.state[5] = 0x9B05688CUL;
md->sha256.state[6] = 0x1F83D9ABUL;
md->sha256.state[7] = 0x5BE0CD19UL;
return CRYPT_OK;
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
HASH_PROCESS(sha256_process, sha256_compress, sha256, 64)
/**
Terminate the hash to get the digest
@param md The hash state
@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 i;
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
if (md->sha256.curlen >= sizeof(md->sha256.buf)) {
return CRYPT_INVALID_ARG;
}
/* increase the length of the message */
md->sha256.length += md->sha256.curlen * 8;
/* append the '1' bit */
md->sha256.buf[md->sha256.curlen++] = (unsigned char)0x80;
/* if the length is currently above 56 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (md->sha256.curlen > 56) {
while (md->sha256.curlen < 64) {
md->sha256.buf[md->sha256.curlen++] = (unsigned char)0;
}
sha256_compress(md, md->sha256.buf);
md->sha256.curlen = 0;
}
/* pad upto 56 bytes of zeroes */
while (md->sha256.curlen < 56) {
md->sha256.buf[md->sha256.curlen++] = (unsigned char)0;
}
/* store length */
STORE64H(md->sha256.length, md->sha256.buf+56);
sha256_compress(md, md->sha256.buf);
/* copy output */
for (i = 0; i < 8; i++) {
STORE32H(md->sha256.state[i], out+(4*i));
}
#ifdef LTC_CLEAN_STACK
zeromem(md, sizeof(hash_state));
#endif
return CRYPT_OK;
}
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);
if ( hashstr != 0 )
{
int32_t init_hexbytes_noT(char *hexbytes,uint8_t *message,long len);
init_hexbytes_noT(hashstr,hash,256 >> 3);
}
}
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);
if ( src2 != 0 )
sha256_process(&md,src2,len2);
sha256_done(&md,hash);
}
void update_sha256(uint8_t hash[256 >> 3],struct sha256_state *state,uint8_t *src,int32_t len)
{
hash_state md;
memset(&md,0,sizeof(md));
if ( src == 0 )
sha256_init(&md);
else
{
md.sha256 = *state;
sha256_process(&md,src,len);
}
*state = md.sha256;
sha256_done(&md,hash);
}
/*void calc_OP_HASH160(char hexstr[41],uint8_t hash160[20],char *pubkey)
{
int32_t decode_hex(unsigned char *bytes,int32_t n,char *hex);
int32_t init_hexbytes_noT(char *hexbytes,uint8_t *message,long len);
uint8_t sha256[32],buf[4096]; int32_t len; hash_state md;
len = (int32_t)strlen(pubkey)/2;
if ( len > sizeof(buf) )
{
printf("calc_OP_HASH160 overflow len.%d vs %d\n",len,(int32_t)sizeof(buf));
return;
}
decode_hex(buf,len,pubkey);
sha256_init(&md);
sha256_process(&md,buf,len);
sha256_done(&md,sha256);
rmd160_init(&md);
rmd160_process(&md,sha256,256 >> 3);
rmd160_done(&md,hash160);
if ( 0 )
{
int i;
for (i=0; i<20; i++)
printf("%02x",hash160[i]);
printf("<- (%s)\n",pubkey);
}
if ( hexstr != 0 )
init_hexbytes_noT(hexstr,hash160,20);
}*/
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int sha256_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct {
char *msg;
unsigned char hash[32];
} tests[] = {
{ "abc",
{ 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,
0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,
0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }
},
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
{ 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,
0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,
0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,
0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }
},
{ "helloworld", { 0x00 } },
};
void reverse_hexstr(char *str);
int32_t decode_hex(unsigned char *bytes,int32_t n,char *hex);
int i,j;
unsigned char tmp[32],buf[512];
hash_state md;
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);
if (XMEMCMP(tmp, tests[i].hash, 32) != 0) {
for (j=0; j<32; j++)
printf("%02x",tmp[j]);
printf(" <- sha256(%s)\n",tests[i].msg);
str = malloc(strlen(tests[i].msg) + 16);
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);
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);
for (j=0; j<32; j++)
printf("%02x",tmp[j]);
printf(" <- sha256(binary %s)\n",tests[i].msg);
return CRYPT_FAIL_TESTVECTOR;
}
}
printf("tests completed\n");
return CRYPT_OK;
#endif
}
//#ifdef LTC_SHA224
//#include "sha224.c"
//#endif
//#endif
#undef S
#undef R
#undef Sigma0
#undef Sigma1
#undef Gamma0
#undef Gamma1
#undef Ch
#undef Maj
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/sha2/sha256.c,v $ */
/* $Revision: 1.11 $ */
/* $Date: 2007/05/12 14:25:28 $ */

148
crypto777/hmac/sha384.c

@ -0,0 +1,148 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
/**
@param sha384.c
LTC_SHA384 hash included in sha512.c, Tom St Denis
*/
#include "tomcrypt.h"
const struct ltc_hash_descriptor sha384_desc =
{
"sha384",
4,
48,
128,
/* OID */
{ 2, 16, 840, 1, 101, 3, 4, 2, 2, },
9,
&sha384_init,
&sha512_process,
&sha384_done,
&sha384_test,
NULL
};
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int sha384_init(hash_state * md)
{
LTC_ARGCHK(md != NULL);
md->sha512.curlen = 0;
md->sha512.length = 0;
md->sha512.state[0] = CONST64(0xcbbb9d5dc1059ed8);
md->sha512.state[1] = CONST64(0x629a292a367cd507);
md->sha512.state[2] = CONST64(0x9159015a3070dd17);
md->sha512.state[3] = CONST64(0x152fecd8f70e5939);
md->sha512.state[4] = CONST64(0x67332667ffc00b31);
md->sha512.state[5] = CONST64(0x8eb44a8768581511);
md->sha512.state[6] = CONST64(0xdb0c2e0d64f98fa7);
md->sha512.state[7] = CONST64(0x47b5481dbefa4fa4);
return CRYPT_OK;
}
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (48 bytes)
@return CRYPT_OK if successful
*/
int sha384_done(hash_state * md, unsigned char *out)
{
unsigned char buf[64];
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
if (md->sha512.curlen >= sizeof(md->sha512.buf)) {
return CRYPT_INVALID_ARG;
}
sha512_done(md, buf);
XMEMCPY(out, buf, 48);
#ifdef LTC_CLEAN_STACK
zeromem(buf, sizeof(buf));
#endif
return CRYPT_OK;
}
void calc_sha384(char *str,uint8_t *digest,uint8_t *message,int32_t len)
{
int init_hexbytes_noT(char *hexbytes,unsigned char *message,long len);
hash_state md;
sha384_init(&md);
sha384_process(&md,message,len);
sha384_done(&md,digest);
if ( str != 0 )
init_hexbytes_noT(str,digest,48);
}
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int sha384_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct {
char *msg;
unsigned char hash[48];
} tests[] = {
{ "abc",
{ 0xcb, 0x00, 0x75, 0x3f, 0x45, 0xa3, 0x5e, 0x8b,
0xb5, 0xa0, 0x3d, 0x69, 0x9a, 0xc6, 0x50, 0x07,
0x27, 0x2c, 0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63,
0x1a, 0x8b, 0x60, 0x5a, 0x43, 0xff, 0x5b, 0xed,
0x80, 0x86, 0x07, 0x2b, 0xa1, 0xe7, 0xcc, 0x23,
0x58, 0xba, 0xec, 0xa1, 0x34, 0xc8, 0x25, 0xa7 }
},
{ "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
{ 0x09, 0x33, 0x0c, 0x33, 0xf7, 0x11, 0x47, 0xe8,
0x3d, 0x19, 0x2f, 0xc7, 0x82, 0xcd, 0x1b, 0x47,
0x53, 0x11, 0x1b, 0x17, 0x3b, 0x3b, 0x05, 0xd2,
0x2f, 0xa0, 0x80, 0x86, 0xe3, 0xb0, 0xf7, 0x12,
0xfc, 0xc7, 0xc7, 0x1a, 0x55, 0x7e, 0x2d, 0xb9,
0x66, 0xc3, 0xe9, 0xfa, 0x91, 0x74, 0x60, 0x39 }
},
};
int i;
unsigned char tmp[48];
hash_state md;
for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
sha384_init(&md);
sha384_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
sha384_done(&md, tmp);
if (XMEMCMP(tmp, tests[i].hash, 48) != 0) {
return CRYPT_FAIL_TESTVECTOR;
}
}
return CRYPT_OK;
#endif
}
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/sha2/sha384.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */

319
crypto777/hmac/sha512.c

@ -0,0 +1,319 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@param sha512.c
LTC_SHA512 by Tom St Denis
*/
#ifdef LTC_SHA512
const struct ltc_hash_descriptor sha512_desc =
{
"sha512",
5,
64,
128,
/* OID */
{ 2, 16, 840, 1, 101, 3, 4, 2, 3, },
9,
&sha512_init,
&sha512_process,
&sha512_done,
&sha512_test,
NULL
};
/* the K array */
static const ulong64 K[80] = {
CONST64(0x428a2f98d728ae22), CONST64(0x7137449123ef65cd),
CONST64(0xb5c0fbcfec4d3b2f), CONST64(0xe9b5dba58189dbbc),
CONST64(0x3956c25bf348b538), CONST64(0x59f111f1b605d019),
CONST64(0x923f82a4af194f9b), CONST64(0xab1c5ed5da6d8118),
CONST64(0xd807aa98a3030242), CONST64(0x12835b0145706fbe),
CONST64(0x243185be4ee4b28c), CONST64(0x550c7dc3d5ffb4e2),
CONST64(0x72be5d74f27b896f), CONST64(0x80deb1fe3b1696b1),
CONST64(0x9bdc06a725c71235), CONST64(0xc19bf174cf692694),
CONST64(0xe49b69c19ef14ad2), CONST64(0xefbe4786384f25e3),
CONST64(0x0fc19dc68b8cd5b5), CONST64(0x240ca1cc77ac9c65),
CONST64(0x2de92c6f592b0275), CONST64(0x4a7484aa6ea6e483),
CONST64(0x5cb0a9dcbd41fbd4), CONST64(0x76f988da831153b5),
CONST64(0x983e5152ee66dfab), CONST64(0xa831c66d2db43210),
CONST64(0xb00327c898fb213f), CONST64(0xbf597fc7beef0ee4),
CONST64(0xc6e00bf33da88fc2), CONST64(0xd5a79147930aa725),
CONST64(0x06ca6351e003826f), CONST64(0x142929670a0e6e70),
CONST64(0x27b70a8546d22ffc), CONST64(0x2e1b21385c26c926),
CONST64(0x4d2c6dfc5ac42aed), CONST64(0x53380d139d95b3df),
CONST64(0x650a73548baf63de), CONST64(0x766a0abb3c77b2a8),
CONST64(0x81c2c92e47edaee6), CONST64(0x92722c851482353b),
CONST64(0xa2bfe8a14cf10364), CONST64(0xa81a664bbc423001),
CONST64(0xc24b8b70d0f89791), CONST64(0xc76c51a30654be30),
CONST64(0xd192e819d6ef5218), CONST64(0xd69906245565a910),
CONST64(0xf40e35855771202a), CONST64(0x106aa07032bbd1b8),
CONST64(0x19a4c116b8d2d0c8), CONST64(0x1e376c085141ab53),
CONST64(0x2748774cdf8eeb99), CONST64(0x34b0bcb5e19b48a8),
CONST64(0x391c0cb3c5c95a63), CONST64(0x4ed8aa4ae3418acb),
CONST64(0x5b9cca4f7763e373), CONST64(0x682e6ff3d6b2b8a3),
CONST64(0x748f82ee5defb2fc), CONST64(0x78a5636f43172f60),
CONST64(0x84c87814a1f0ab72), CONST64(0x8cc702081a6439ec),
CONST64(0x90befffa23631e28), CONST64(0xa4506cebde82bde9),
CONST64(0xbef9a3f7b2c67915), CONST64(0xc67178f2e372532b),
CONST64(0xca273eceea26619c), CONST64(0xd186b8c721c0c207),
CONST64(0xeada7dd6cde0eb1e), CONST64(0xf57d4f7fee6ed178),
CONST64(0x06f067aa72176fba), CONST64(0x0a637dc5a2c898a6),
CONST64(0x113f9804bef90dae), CONST64(0x1b710b35131c471b),
CONST64(0x28db77f523047d84), CONST64(0x32caab7b40c72493),
CONST64(0x3c9ebe0a15c9bebc), CONST64(0x431d67c49c100d4c),
CONST64(0x4cc5d4becb3e42b6), CONST64(0x597f299cfc657e2a),
CONST64(0x5fcb6fab3ad6faec), CONST64(0x6c44198c4a475817)
};
/* Various logical functions */
#define Ch(x,y,z) (z ^ (x & (y ^ z)))
#define Maj(x,y,z) (((x | y) & z) | (x & y))
#define S(x, n) ROR64c(x, n)
#define R(x, n) (((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)n))
#define Sigma0(x) (S(x, 28) ^ S(x, 34) ^ S(x, 39))
#define Sigma1(x) (S(x, 14) ^ S(x, 18) ^ S(x, 41))
#define Gamma0(x) (S(x, 1) ^ S(x, 8) ^ R(x, 7))
#define Gamma1(x) (S(x, 19) ^ S(x, 61) ^ R(x, 6))
/* compress 1024-bits */
#ifdef LTC_CLEAN_STACK
static int _sha512_compress(hash_state * md, unsigned char *buf)
#else
static int sha512_compress(hash_state * md, unsigned char *buf)
#endif
{
ulong64 S[8], W[80], t0, t1;
int i;
/* copy state into S */
for (i = 0; i < 8; i++) {
S[i] = md->sha512.state[i];
}
/* copy the state into 1024-bits into W[0..15] */
for (i = 0; i < 16; i++) {
LOAD64H(W[i], buf + (8*i));
}
/* fill W[16..79] */
for (i = 16; i < 80; i++) {
W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
}
/* Compress */
#ifdef LTC_SMALL_CODE
for (i = 0; i < 80; i++) {
t0 = S[7] + Sigma1(S[4]) + Ch(S[4], S[5], S[6]) + K[i] + W[i];
t1 = Sigma0(S[0]) + Maj(S[0], S[1], S[2]);
S[7] = S[6];
S[6] = S[5];
S[5] = S[4];
S[4] = S[3] + t0;
S[3] = S[2];
S[2] = S[1];
S[1] = S[0];
S[0] = t0 + t1;
}
#else
#define RND(a,b,c,d,e,f,g,h,i) \
t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \
t1 = Sigma0(a) + Maj(a, b, c); \
d += t0; \
h = t0 + t1;
for (i = 0; i < 80; i += 8) {
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i+0);
RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],i+1);
RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],i+2);
RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],i+3);
RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],i+4);
RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],i+5);
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],i+6);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],i+7);
}
#endif
/* feedback */
for (i = 0; i < 8; i++) {
md->sha512.state[i] = md->sha512.state[i] + S[i];
}
return CRYPT_OK;
}
/* compress 1024-bits */
#ifdef LTC_CLEAN_STACK
static int sha512_compress(hash_state * md, unsigned char *buf)
{
int err;
err = _sha512_compress(md, buf);
burn_stack(sizeof(ulong64) * 90 + sizeof(int));
return err;
}
#endif
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int sha512_init(hash_state * md)
{
LTC_ARGCHK(md != NULL);
md->sha512.curlen = 0;
md->sha512.length = 0;
md->sha512.state[0] = CONST64(0x6a09e667f3bcc908);
md->sha512.state[1] = CONST64(0xbb67ae8584caa73b);
md->sha512.state[2] = CONST64(0x3c6ef372fe94f82b);
md->sha512.state[3] = CONST64(0xa54ff53a5f1d36f1);
md->sha512.state[4] = CONST64(0x510e527fade682d1);
md->sha512.state[5] = CONST64(0x9b05688c2b3e6c1f);
md->sha512.state[6] = CONST64(0x1f83d9abfb41bd6b);
md->sha512.state[7] = CONST64(0x5be0cd19137e2179);
return CRYPT_OK;
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
HASH_PROCESS(sha512_process, sha512_compress, sha512, 128)
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (64 bytes)
@return CRYPT_OK if successful
*/
int sha512_done(hash_state * md, unsigned char *out)
{
int i;
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
if (md->sha512.curlen >= sizeof(md->sha512.buf)) {
return CRYPT_INVALID_ARG;
}
/* increase the length of the message */
md->sha512.length += md->sha512.curlen * CONST64(8);
/* append the '1' bit */
md->sha512.buf[md->sha512.curlen++] = (unsigned char)0x80;
/* if the length is currently above 112 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (md->sha512.curlen > 112) {
while (md->sha512.curlen < 128) {
md->sha512.buf[md->sha512.curlen++] = (unsigned char)0;
}
sha512_compress(md, md->sha512.buf);
md->sha512.curlen = 0;
}
/* pad upto 120 bytes of zeroes
* note: that from 112 to 120 is the 64 MSB of the length. We assume that you won't hash
* > 2^64 bits of data... :-)
*/
while (md->sha512.curlen < 120) {
md->sha512.buf[md->sha512.curlen++] = (unsigned char)0;
}
/* store length */
STORE64H(md->sha512.length, md->sha512.buf+120);
sha512_compress(md, md->sha512.buf);
/* copy output */
for (i = 0; i < 8; i++) {
STORE64H(md->sha512.state[i], out+(8*i));
}
#ifdef LTC_CLEAN_STACK
zeromem(md, sizeof(hash_state));
#endif
return CRYPT_OK;
}
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int sha512_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct {
char *msg;
unsigned char hash[64];
} tests[] = {
{ "abc",
{ 0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba,
0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31,
0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2,
0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a,
0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8,
0x36, 0xba, 0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd,
0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e,
0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f }
},
{ "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
{ 0x8e, 0x95, 0x9b, 0x75, 0xda, 0xe3, 0x13, 0xda,
0x8c, 0xf4, 0xf7, 0x28, 0x14, 0xfc, 0x14, 0x3f,
0x8f, 0x77, 0x79, 0xc6, 0xeb, 0x9f, 0x7f, 0xa1,
0x72, 0x99, 0xae, 0xad, 0xb6, 0x88, 0x90, 0x18,
0x50, 0x1d, 0x28, 0x9e, 0x49, 0x00, 0xf7, 0xe4,
0x33, 0x1b, 0x99, 0xde, 0xc4, 0xb5, 0x43, 0x3a,
0xc7, 0xd3, 0x29, 0xee, 0xb6, 0xdd, 0x26, 0x54,
0x5e, 0x96, 0xe5, 0x5b, 0x87, 0x4b, 0xe9, 0x09 }
},
};
int i;
unsigned char tmp[64];
hash_state md;
for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
sha512_init(&md);
sha512_process(&md, (unsigned char *)tests[i].msg, (unsigned long)strlen(tests[i].msg));
sha512_done(&md, tmp);
if (XMEMCMP(tmp, tests[i].hash, 64) != 0) {
return CRYPT_FAIL_TESTVECTOR;
}
}
return CRYPT_OK;
#endif
}
//#ifdef LTC_SHA384
// #include "sha384.c"
//#endif
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/sha2/sha512.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */

825
crypto777/hmac/tiger.c

@ -0,0 +1,825 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
#include "tomcrypt.h"
/**
@file tiger.c
Tiger hash function, Tom St Denis
*/
#ifdef LTC_TIGER
const struct ltc_hash_descriptor tiger_desc =
{
"tiger",
1,
24,
64,
/* OID */
{ 1, 3, 6, 1, 4, 1, 11591, 12, 2, },
9,
&tiger_init,
&tiger_process,
&tiger_done,
&tiger_test,
NULL
};
#define t1 (table)
#define t2 (table+256)
#define t3 (table+256*2)
#define t4 (table+256*3)
static const ulong64 table[4*256] = {
CONST64(0x02AAB17CF7E90C5E) /* 0 */, CONST64(0xAC424B03E243A8EC) /* 1 */,
CONST64(0x72CD5BE30DD5FCD3) /* 2 */, CONST64(0x6D019B93F6F97F3A) /* 3 */,
CONST64(0xCD9978FFD21F9193) /* 4 */, CONST64(0x7573A1C9708029E2) /* 5 */,
CONST64(0xB164326B922A83C3) /* 6 */, CONST64(0x46883EEE04915870) /* 7 */,
CONST64(0xEAACE3057103ECE6) /* 8 */, CONST64(0xC54169B808A3535C) /* 9 */,
CONST64(0x4CE754918DDEC47C) /* 10 */, CONST64(0x0AA2F4DFDC0DF40C) /* 11 */,
CONST64(0x10B76F18A74DBEFA) /* 12 */, CONST64(0xC6CCB6235AD1AB6A) /* 13 */,
CONST64(0x13726121572FE2FF) /* 14 */, CONST64(0x1A488C6F199D921E) /* 15 */,
CONST64(0x4BC9F9F4DA0007CA) /* 16 */, CONST64(0x26F5E6F6E85241C7) /* 17 */,
CONST64(0x859079DBEA5947B6) /* 18 */, CONST64(0x4F1885C5C99E8C92) /* 19 */,
CONST64(0xD78E761EA96F864B) /* 20 */, CONST64(0x8E36428C52B5C17D) /* 21 */,
CONST64(0x69CF6827373063C1) /* 22 */, CONST64(0xB607C93D9BB4C56E) /* 23 */,
CONST64(0x7D820E760E76B5EA) /* 24 */, CONST64(0x645C9CC6F07FDC42) /* 25 */,
CONST64(0xBF38A078243342E0) /* 26 */, CONST64(0x5F6B343C9D2E7D04) /* 27 */,
CONST64(0xF2C28AEB600B0EC6) /* 28 */, CONST64(0x6C0ED85F7254BCAC) /* 29 */,
CONST64(0x71592281A4DB4FE5) /* 30 */, CONST64(0x1967FA69CE0FED9F) /* 31 */,
CONST64(0xFD5293F8B96545DB) /* 32 */, CONST64(0xC879E9D7F2A7600B) /* 33 */,
CONST64(0x860248920193194E) /* 34 */, CONST64(0xA4F9533B2D9CC0B3) /* 35 */,
CONST64(0x9053836C15957613) /* 36 */, CONST64(0xDB6DCF8AFC357BF1) /* 37 */,
CONST64(0x18BEEA7A7A370F57) /* 38 */, CONST64(0x037117CA50B99066) /* 39 */,
CONST64(0x6AB30A9774424A35) /* 40 */, CONST64(0xF4E92F02E325249B) /* 41 */,
CONST64(0x7739DB07061CCAE1) /* 42 */, CONST64(0xD8F3B49CECA42A05) /* 43 */,
CONST64(0xBD56BE3F51382F73) /* 44 */, CONST64(0x45FAED5843B0BB28) /* 45 */,
CONST64(0x1C813D5C11BF1F83) /* 46 */, CONST64(0x8AF0E4B6D75FA169) /* 47 */,
CONST64(0x33EE18A487AD9999) /* 48 */, CONST64(0x3C26E8EAB1C94410) /* 49 */,
CONST64(0xB510102BC0A822F9) /* 50 */, CONST64(0x141EEF310CE6123B) /* 51 */,
CONST64(0xFC65B90059DDB154) /* 52 */, CONST64(0xE0158640C5E0E607) /* 53 */,
CONST64(0x884E079826C3A3CF) /* 54 */, CONST64(0x930D0D9523C535FD) /* 55 */,
CONST64(0x35638D754E9A2B00) /* 56 */, CONST64(0x4085FCCF40469DD5) /* 57 */,
CONST64(0xC4B17AD28BE23A4C) /* 58 */, CONST64(0xCAB2F0FC6A3E6A2E) /* 59 */,
CONST64(0x2860971A6B943FCD) /* 60 */, CONST64(0x3DDE6EE212E30446) /* 61 */,
CONST64(0x6222F32AE01765AE) /* 62 */, CONST64(0x5D550BB5478308FE) /* 63 */,
CONST64(0xA9EFA98DA0EDA22A) /* 64 */, CONST64(0xC351A71686C40DA7) /* 65 */,
CONST64(0x1105586D9C867C84) /* 66 */, CONST64(0xDCFFEE85FDA22853) /* 67 */,
CONST64(0xCCFBD0262C5EEF76) /* 68 */, CONST64(0xBAF294CB8990D201) /* 69 */,
CONST64(0xE69464F52AFAD975) /* 70 */, CONST64(0x94B013AFDF133E14) /* 71 */,
CONST64(0x06A7D1A32823C958) /* 72 */, CONST64(0x6F95FE5130F61119) /* 73 */,
CONST64(0xD92AB34E462C06C0) /* 74 */, CONST64(0xED7BDE33887C71D2) /* 75 */,
CONST64(0x79746D6E6518393E) /* 76 */, CONST64(0x5BA419385D713329) /* 77 */,
CONST64(0x7C1BA6B948A97564) /* 78 */, CONST64(0x31987C197BFDAC67) /* 79 */,
CONST64(0xDE6C23C44B053D02) /* 80 */, CONST64(0x581C49FED002D64D) /* 81 */,
CONST64(0xDD474D6338261571) /* 82 */, CONST64(0xAA4546C3E473D062) /* 83 */,
CONST64(0x928FCE349455F860) /* 84 */, CONST64(0x48161BBACAAB94D9) /* 85 */,
CONST64(0x63912430770E6F68) /* 86 */, CONST64(0x6EC8A5E602C6641C) /* 87 */,
CONST64(0x87282515337DDD2B) /* 88 */, CONST64(0x2CDA6B42034B701B) /* 89 */,
CONST64(0xB03D37C181CB096D) /* 90 */, CONST64(0xE108438266C71C6F) /* 91 */,
CONST64(0x2B3180C7EB51B255) /* 92 */, CONST64(0xDF92B82F96C08BBC) /* 93 */,
CONST64(0x5C68C8C0A632F3BA) /* 94 */, CONST64(0x5504CC861C3D0556) /* 95 */,
CONST64(0xABBFA4E55FB26B8F) /* 96 */, CONST64(0x41848B0AB3BACEB4) /* 97 */,
CONST64(0xB334A273AA445D32) /* 98 */, CONST64(0xBCA696F0A85AD881) /* 99 */,
CONST64(0x24F6EC65B528D56C) /* 100 */, CONST64(0x0CE1512E90F4524A) /* 101 */,
CONST64(0x4E9DD79D5506D35A) /* 102 */, CONST64(0x258905FAC6CE9779) /* 103 */,
CONST64(0x2019295B3E109B33) /* 104 */, CONST64(0xF8A9478B73A054CC) /* 105 */,
CONST64(0x2924F2F934417EB0) /* 106 */, CONST64(0x3993357D536D1BC4) /* 107 */,
CONST64(0x38A81AC21DB6FF8B) /* 108 */, CONST64(0x47C4FBF17D6016BF) /* 109 */,
CONST64(0x1E0FAADD7667E3F5) /* 110 */, CONST64(0x7ABCFF62938BEB96) /* 111 */,
CONST64(0xA78DAD948FC179C9) /* 112 */, CONST64(0x8F1F98B72911E50D) /* 113 */,
CONST64(0x61E48EAE27121A91) /* 114 */, CONST64(0x4D62F7AD31859808) /* 115 */,
CONST64(0xECEBA345EF5CEAEB) /* 116 */, CONST64(0xF5CEB25EBC9684CE) /* 117 */,
CONST64(0xF633E20CB7F76221) /* 118 */, CONST64(0xA32CDF06AB8293E4) /* 119 */,
CONST64(0x985A202CA5EE2CA4) /* 120 */, CONST64(0xCF0B8447CC8A8FB1) /* 121 */,
CONST64(0x9F765244979859A3) /* 122 */, CONST64(0xA8D516B1A1240017) /* 123 */,
CONST64(0x0BD7BA3EBB5DC726) /* 124 */, CONST64(0xE54BCA55B86ADB39) /* 125 */,
CONST64(0x1D7A3AFD6C478063) /* 126 */, CONST64(0x519EC608E7669EDD) /* 127 */,
CONST64(0x0E5715A2D149AA23) /* 128 */, CONST64(0x177D4571848FF194) /* 129 */,
CONST64(0xEEB55F3241014C22) /* 130 */, CONST64(0x0F5E5CA13A6E2EC2) /* 131 */,
CONST64(0x8029927B75F5C361) /* 132 */, CONST64(0xAD139FABC3D6E436) /* 133 */,
CONST64(0x0D5DF1A94CCF402F) /* 134 */, CONST64(0x3E8BD948BEA5DFC8) /* 135 */,
CONST64(0xA5A0D357BD3FF77E) /* 136 */, CONST64(0xA2D12E251F74F645) /* 137 */,
CONST64(0x66FD9E525E81A082) /* 138 */, CONST64(0x2E0C90CE7F687A49) /* 139 */,
CONST64(0xC2E8BCBEBA973BC5) /* 140 */, CONST64(0x000001BCE509745F) /* 141 */,
CONST64(0x423777BBE6DAB3D6) /* 142 */, CONST64(0xD1661C7EAEF06EB5) /* 143 */,
CONST64(0xA1781F354DAACFD8) /* 144 */, CONST64(0x2D11284A2B16AFFC) /* 145 */,
CONST64(0xF1FC4F67FA891D1F) /* 146 */, CONST64(0x73ECC25DCB920ADA) /* 147 */,
CONST64(0xAE610C22C2A12651) /* 148 */, CONST64(0x96E0A810D356B78A) /* 149 */,
CONST64(0x5A9A381F2FE7870F) /* 150 */, CONST64(0xD5AD62EDE94E5530) /* 151 */,
CONST64(0xD225E5E8368D1427) /* 152 */, CONST64(0x65977B70C7AF4631) /* 153 */,
CONST64(0x99F889B2DE39D74F) /* 154 */, CONST64(0x233F30BF54E1D143) /* 155 */,
CONST64(0x9A9675D3D9A63C97) /* 156 */, CONST64(0x5470554FF334F9A8) /* 157 */,
CONST64(0x166ACB744A4F5688) /* 158 */, CONST64(0x70C74CAAB2E4AEAD) /* 159 */,
CONST64(0xF0D091646F294D12) /* 160 */, CONST64(0x57B82A89684031D1) /* 161 */,
CONST64(0xEFD95A5A61BE0B6B) /* 162 */, CONST64(0x2FBD12E969F2F29A) /* 163 */,
CONST64(0x9BD37013FEFF9FE8) /* 164 */, CONST64(0x3F9B0404D6085A06) /* 165 */,
CONST64(0x4940C1F3166CFE15) /* 166 */, CONST64(0x09542C4DCDF3DEFB) /* 167 */,
CONST64(0xB4C5218385CD5CE3) /* 168 */, CONST64(0xC935B7DC4462A641) /* 169 */,
CONST64(0x3417F8A68ED3B63F) /* 170 */, CONST64(0xB80959295B215B40) /* 171 */,
CONST64(0xF99CDAEF3B8C8572) /* 172 */, CONST64(0x018C0614F8FCB95D) /* 173 */,
CONST64(0x1B14ACCD1A3ACDF3) /* 174 */, CONST64(0x84D471F200BB732D) /* 175 */,
CONST64(0xC1A3110E95E8DA16) /* 176 */, CONST64(0x430A7220BF1A82B8) /* 177 */,
CONST64(0xB77E090D39DF210E) /* 178 */, CONST64(0x5EF4BD9F3CD05E9D) /* 179 */,
CONST64(0x9D4FF6DA7E57A444) /* 180 */, CONST64(0xDA1D60E183D4A5F8) /* 181 */,
CONST64(0xB287C38417998E47) /* 182 */, CONST64(0xFE3EDC121BB31886) /* 183 */,
CONST64(0xC7FE3CCC980CCBEF) /* 184 */, CONST64(0xE46FB590189BFD03) /* 185 */,
CONST64(0x3732FD469A4C57DC) /* 186 */, CONST64(0x7EF700A07CF1AD65) /* 187 */,
CONST64(0x59C64468A31D8859) /* 188 */, CONST64(0x762FB0B4D45B61F6) /* 189 */,
CONST64(0x155BAED099047718) /* 190 */, CONST64(0x68755E4C3D50BAA6) /* 191 */,
CONST64(0xE9214E7F22D8B4DF) /* 192 */, CONST64(0x2ADDBF532EAC95F4) /* 193 */,
CONST64(0x32AE3909B4BD0109) /* 194 */, CONST64(0x834DF537B08E3450) /* 195 */,
CONST64(0xFA209DA84220728D) /* 196 */, CONST64(0x9E691D9B9EFE23F7) /* 197 */,
CONST64(0x0446D288C4AE8D7F) /* 198 */, CONST64(0x7B4CC524E169785B) /* 199 */,
CONST64(0x21D87F0135CA1385) /* 200 */, CONST64(0xCEBB400F137B8AA5) /* 201 */,
CONST64(0x272E2B66580796BE) /* 202 */, CONST64(0x3612264125C2B0DE) /* 203 */,
CONST64(0x057702BDAD1EFBB2) /* 204 */, CONST64(0xD4BABB8EACF84BE9) /* 205 */,
CONST64(0x91583139641BC67B) /* 206 */, CONST64(0x8BDC2DE08036E024) /* 207 */,
CONST64(0x603C8156F49F68ED) /* 208 */, CONST64(0xF7D236F7DBEF5111) /* 209 */,
CONST64(0x9727C4598AD21E80) /* 210 */, CONST64(0xA08A0896670A5FD7) /* 211 */,
CONST64(0xCB4A8F4309EBA9CB) /* 212 */, CONST64(0x81AF564B0F7036A1) /* 213 */,
CONST64(0xC0B99AA778199ABD) /* 214 */, CONST64(0x959F1EC83FC8E952) /* 215 */,
CONST64(0x8C505077794A81B9) /* 216 */, CONST64(0x3ACAAF8F056338F0) /* 217 */,
CONST64(0x07B43F50627A6778) /* 218 */, CONST64(0x4A44AB49F5ECCC77) /* 219 */,
CONST64(0x3BC3D6E4B679EE98) /* 220 */, CONST64(0x9CC0D4D1CF14108C) /* 221 */,
CONST64(0x4406C00B206BC8A0) /* 222 */, CONST64(0x82A18854C8D72D89) /* 223 */,
CONST64(0x67E366B35C3C432C) /* 224 */, CONST64(0xB923DD61102B37F2) /* 225 */,
CONST64(0x56AB2779D884271D) /* 226 */, CONST64(0xBE83E1B0FF1525AF) /* 227 */,
CONST64(0xFB7C65D4217E49A9) /* 228 */, CONST64(0x6BDBE0E76D48E7D4) /* 229 */,
CONST64(0x08DF828745D9179E) /* 230 */, CONST64(0x22EA6A9ADD53BD34) /* 231 */,
CONST64(0xE36E141C5622200A) /* 232 */, CONST64(0x7F805D1B8CB750EE) /* 233 */,
CONST64(0xAFE5C7A59F58E837) /* 234 */, CONST64(0xE27F996A4FB1C23C) /* 235 */,
CONST64(0xD3867DFB0775F0D0) /* 236 */, CONST64(0xD0E673DE6E88891A) /* 237 */,
CONST64(0x123AEB9EAFB86C25) /* 238 */, CONST64(0x30F1D5D5C145B895) /* 239 */,
CONST64(0xBB434A2DEE7269E7) /* 240 */, CONST64(0x78CB67ECF931FA38) /* 241 */,
CONST64(0xF33B0372323BBF9C) /* 242 */, CONST64(0x52D66336FB279C74) /* 243 */,
CONST64(0x505F33AC0AFB4EAA) /* 244 */, CONST64(0xE8A5CD99A2CCE187) /* 245 */,
CONST64(0x534974801E2D30BB) /* 246 */, CONST64(0x8D2D5711D5876D90) /* 247 */,
CONST64(0x1F1A412891BC038E) /* 248 */, CONST64(0xD6E2E71D82E56648) /* 249 */,
CONST64(0x74036C3A497732B7) /* 250 */, CONST64(0x89B67ED96361F5AB) /* 251 */,
CONST64(0xFFED95D8F1EA02A2) /* 252 */, CONST64(0xE72B3BD61464D43D) /* 253 */,
CONST64(0xA6300F170BDC4820) /* 254 */, CONST64(0xEBC18760ED78A77A) /* 255 */,
CONST64(0xE6A6BE5A05A12138) /* 256 */, CONST64(0xB5A122A5B4F87C98) /* 257 */,
CONST64(0x563C6089140B6990) /* 258 */, CONST64(0x4C46CB2E391F5DD5) /* 259 */,
CONST64(0xD932ADDBC9B79434) /* 260 */, CONST64(0x08EA70E42015AFF5) /* 261 */,
CONST64(0xD765A6673E478CF1) /* 262 */, CONST64(0xC4FB757EAB278D99) /* 263 */,
CONST64(0xDF11C6862D6E0692) /* 264 */, CONST64(0xDDEB84F10D7F3B16) /* 265 */,
CONST64(0x6F2EF604A665EA04) /* 266 */, CONST64(0x4A8E0F0FF0E0DFB3) /* 267 */,
CONST64(0xA5EDEEF83DBCBA51) /* 268 */, CONST64(0xFC4F0A2A0EA4371E) /* 269 */,
CONST64(0xE83E1DA85CB38429) /* 270 */, CONST64(0xDC8FF882BA1B1CE2) /* 271 */,
CONST64(0xCD45505E8353E80D) /* 272 */, CONST64(0x18D19A00D4DB0717) /* 273 */,
CONST64(0x34A0CFEDA5F38101) /* 274 */, CONST64(0x0BE77E518887CAF2) /* 275 */,
CONST64(0x1E341438B3C45136) /* 276 */, CONST64(0xE05797F49089CCF9) /* 277 */,
CONST64(0xFFD23F9DF2591D14) /* 278 */, CONST64(0x543DDA228595C5CD) /* 279 */,
CONST64(0x661F81FD99052A33) /* 280 */, CONST64(0x8736E641DB0F7B76) /* 281 */,
CONST64(0x15227725418E5307) /* 282 */, CONST64(0xE25F7F46162EB2FA) /* 283 */,
CONST64(0x48A8B2126C13D9FE) /* 284 */, CONST64(0xAFDC541792E76EEA) /* 285 */,
CONST64(0x03D912BFC6D1898F) /* 286 */, CONST64(0x31B1AAFA1B83F51B) /* 287 */,
CONST64(0xF1AC2796E42AB7D9) /* 288 */, CONST64(0x40A3A7D7FCD2EBAC) /* 289 */,
CONST64(0x1056136D0AFBBCC5) /* 290 */, CONST64(0x7889E1DD9A6D0C85) /* 291 */,
CONST64(0xD33525782A7974AA) /* 292 */, CONST64(0xA7E25D09078AC09B) /* 293 */,
CONST64(0xBD4138B3EAC6EDD0) /* 294 */, CONST64(0x920ABFBE71EB9E70) /* 295 */,
CONST64(0xA2A5D0F54FC2625C) /* 296 */, CONST64(0xC054E36B0B1290A3) /* 297 */,
CONST64(0xF6DD59FF62FE932B) /* 298 */, CONST64(0x3537354511A8AC7D) /* 299 */,
CONST64(0xCA845E9172FADCD4) /* 300 */, CONST64(0x84F82B60329D20DC) /* 301 */,
CONST64(0x79C62CE1CD672F18) /* 302 */, CONST64(0x8B09A2ADD124642C) /* 303 */,
CONST64(0xD0C1E96A19D9E726) /* 304 */, CONST64(0x5A786A9B4BA9500C) /* 305 */,
CONST64(0x0E020336634C43F3) /* 306 */, CONST64(0xC17B474AEB66D822) /* 307 */,
CONST64(0x6A731AE3EC9BAAC2) /* 308 */, CONST64(0x8226667AE0840258) /* 309 */,
CONST64(0x67D4567691CAECA5) /* 310 */, CONST64(0x1D94155C4875ADB5) /* 311 */,
CONST64(0x6D00FD985B813FDF) /* 312 */, CONST64(0x51286EFCB774CD06) /* 313 */,
CONST64(0x5E8834471FA744AF) /* 314 */, CONST64(0xF72CA0AEE761AE2E) /* 315 */,
CONST64(0xBE40E4CDAEE8E09A) /* 316 */, CONST64(0xE9970BBB5118F665) /* 317 */,
CONST64(0x726E4BEB33DF1964) /* 318 */, CONST64(0x703B000729199762) /* 319 */,
CONST64(0x4631D816F5EF30A7) /* 320 */, CONST64(0xB880B5B51504A6BE) /* 321 */,
CONST64(0x641793C37ED84B6C) /* 322 */, CONST64(0x7B21ED77F6E97D96) /* 323 */,
CONST64(0x776306312EF96B73) /* 324 */, CONST64(0xAE528948E86FF3F4) /* 325 */,
CONST64(0x53DBD7F286A3F8F8) /* 326 */, CONST64(0x16CADCE74CFC1063) /* 327 */,
CONST64(0x005C19BDFA52C6DD) /* 328 */, CONST64(0x68868F5D64D46AD3) /* 329 */,
CONST64(0x3A9D512CCF1E186A) /* 330 */, CONST64(0x367E62C2385660AE) /* 331 */,
CONST64(0xE359E7EA77DCB1D7) /* 332 */, CONST64(0x526C0773749ABE6E) /* 333 */,
CONST64(0x735AE5F9D09F734B) /* 334 */, CONST64(0x493FC7CC8A558BA8) /* 335 */,
CONST64(0xB0B9C1533041AB45) /* 336 */, CONST64(0x321958BA470A59BD) /* 337 */,
CONST64(0x852DB00B5F46C393) /* 338 */, CONST64(0x91209B2BD336B0E5) /* 339 */,
CONST64(0x6E604F7D659EF19F) /* 340 */, CONST64(0xB99A8AE2782CCB24) /* 341 */,
CONST64(0xCCF52AB6C814C4C7) /* 342 */, CONST64(0x4727D9AFBE11727B) /* 343 */,
CONST64(0x7E950D0C0121B34D) /* 344 */, CONST64(0x756F435670AD471F) /* 345 */,
CONST64(0xF5ADD442615A6849) /* 346 */, CONST64(0x4E87E09980B9957A) /* 347 */,
CONST64(0x2ACFA1DF50AEE355) /* 348 */, CONST64(0xD898263AFD2FD556) /* 349 */,
CONST64(0xC8F4924DD80C8FD6) /* 350 */, CONST64(0xCF99CA3D754A173A) /* 351 */,
CONST64(0xFE477BACAF91BF3C) /* 352 */, CONST64(0xED5371F6D690C12D) /* 353 */,
CONST64(0x831A5C285E687094) /* 354 */, CONST64(0xC5D3C90A3708A0A4) /* 355 */,
CONST64(0x0F7F903717D06580) /* 356 */, CONST64(0x19F9BB13B8FDF27F) /* 357 */,
CONST64(0xB1BD6F1B4D502843) /* 358 */, CONST64(0x1C761BA38FFF4012) /* 359 */,
CONST64(0x0D1530C4E2E21F3B) /* 360 */, CONST64(0x8943CE69A7372C8A) /* 361 */,
CONST64(0xE5184E11FEB5CE66) /* 362 */, CONST64(0x618BDB80BD736621) /* 363 */,
CONST64(0x7D29BAD68B574D0B) /* 364 */, CONST64(0x81BB613E25E6FE5B) /* 365 */,
CONST64(0x071C9C10BC07913F) /* 366 */, CONST64(0xC7BEEB7909AC2D97) /* 367 */,
CONST64(0xC3E58D353BC5D757) /* 368 */, CONST64(0xEB017892F38F61E8) /* 369 */,
CONST64(0xD4EFFB9C9B1CC21A) /* 370 */, CONST64(0x99727D26F494F7AB) /* 371 */,
CONST64(0xA3E063A2956B3E03) /* 372 */, CONST64(0x9D4A8B9A4AA09C30) /* 373 */,
CONST64(0x3F6AB7D500090FB4) /* 374 */, CONST64(0x9CC0F2A057268AC0) /* 375 */,
CONST64(0x3DEE9D2DEDBF42D1) /* 376 */, CONST64(0x330F49C87960A972) /* 377 */,
CONST64(0xC6B2720287421B41) /* 378 */, CONST64(0x0AC59EC07C00369C) /* 379 */,
CONST64(0xEF4EAC49CB353425) /* 380 */, CONST64(0xF450244EEF0129D8) /* 381 */,
CONST64(0x8ACC46E5CAF4DEB6) /* 382 */, CONST64(0x2FFEAB63989263F7) /* 383 */,
CONST64(0x8F7CB9FE5D7A4578) /* 384 */, CONST64(0x5BD8F7644E634635) /* 385 */,
CONST64(0x427A7315BF2DC900) /* 386 */, CONST64(0x17D0C4AA2125261C) /* 387 */,
CONST64(0x3992486C93518E50) /* 388 */, CONST64(0xB4CBFEE0A2D7D4C3) /* 389 */,
CONST64(0x7C75D6202C5DDD8D) /* 390 */, CONST64(0xDBC295D8E35B6C61) /* 391 */,
CONST64(0x60B369D302032B19) /* 392 */, CONST64(0xCE42685FDCE44132) /* 393 */,
CONST64(0x06F3DDB9DDF65610) /* 394 */, CONST64(0x8EA4D21DB5E148F0) /* 395 */,
CONST64(0x20B0FCE62FCD496F) /* 396 */, CONST64(0x2C1B912358B0EE31) /* 397 */,
CONST64(0xB28317B818F5A308) /* 398 */, CONST64(0xA89C1E189CA6D2CF) /* 399 */,
CONST64(0x0C6B18576AAADBC8) /* 400 */, CONST64(0xB65DEAA91299FAE3) /* 401 */,
CONST64(0xFB2B794B7F1027E7) /* 402 */, CONST64(0x04E4317F443B5BEB) /* 403 */,
CONST64(0x4B852D325939D0A6) /* 404 */, CONST64(0xD5AE6BEEFB207FFC) /* 405 */,
CONST64(0x309682B281C7D374) /* 406 */, CONST64(0xBAE309A194C3B475) /* 407 */,
CONST64(0x8CC3F97B13B49F05) /* 408 */, CONST64(0x98A9422FF8293967) /* 409 */,
CONST64(0x244B16B01076FF7C) /* 410 */, CONST64(0xF8BF571C663D67EE) /* 411 */,
CONST64(0x1F0D6758EEE30DA1) /* 412 */, CONST64(0xC9B611D97ADEB9B7) /* 413 */,
CONST64(0xB7AFD5887B6C57A2) /* 414 */, CONST64(0x6290AE846B984FE1) /* 415 */,
CONST64(0x94DF4CDEACC1A5FD) /* 416 */, CONST64(0x058A5BD1C5483AFF) /* 417 */,
CONST64(0x63166CC142BA3C37) /* 418 */, CONST64(0x8DB8526EB2F76F40) /* 419 */,
CONST64(0xE10880036F0D6D4E) /* 420 */, CONST64(0x9E0523C9971D311D) /* 421 */,
CONST64(0x45EC2824CC7CD691) /* 422 */, CONST64(0x575B8359E62382C9) /* 423 */,
CONST64(0xFA9E400DC4889995) /* 424 */, CONST64(0xD1823ECB45721568) /* 425 */,
CONST64(0xDAFD983B8206082F) /* 426 */, CONST64(0xAA7D29082386A8CB) /* 427 */,
CONST64(0x269FCD4403B87588) /* 428 */, CONST64(0x1B91F5F728BDD1E0) /* 429 */,
CONST64(0xE4669F39040201F6) /* 430 */, CONST64(0x7A1D7C218CF04ADE) /* 431 */,
CONST64(0x65623C29D79CE5CE) /* 432 */, CONST64(0x2368449096C00BB1) /* 433 */,
CONST64(0xAB9BF1879DA503BA) /* 434 */, CONST64(0xBC23ECB1A458058E) /* 435 */,
CONST64(0x9A58DF01BB401ECC) /* 436 */, CONST64(0xA070E868A85F143D) /* 437 */,
CONST64(0x4FF188307DF2239E) /* 438 */, CONST64(0x14D565B41A641183) /* 439 */,
CONST64(0xEE13337452701602) /* 440 */, CONST64(0x950E3DCF3F285E09) /* 441 */,
CONST64(0x59930254B9C80953) /* 442 */, CONST64(0x3BF299408930DA6D) /* 443 */,
CONST64(0xA955943F53691387) /* 444 */, CONST64(0xA15EDECAA9CB8784) /* 445 */,
CONST64(0x29142127352BE9A0) /* 446 */, CONST64(0x76F0371FFF4E7AFB) /* 447 */,
CONST64(0x0239F450274F2228) /* 448 */, CONST64(0xBB073AF01D5E868B) /* 449 */,
CONST64(0xBFC80571C10E96C1) /* 450 */, CONST64(0xD267088568222E23) /* 451 */,
CONST64(0x9671A3D48E80B5B0) /* 452 */, CONST64(0x55B5D38AE193BB81) /* 453 */,
CONST64(0x693AE2D0A18B04B8) /* 454 */, CONST64(0x5C48B4ECADD5335F) /* 455 */,
CONST64(0xFD743B194916A1CA) /* 456 */, CONST64(0x2577018134BE98C4) /* 457 */,
CONST64(0xE77987E83C54A4AD) /* 458 */, CONST64(0x28E11014DA33E1B9) /* 459 */,
CONST64(0x270CC59E226AA213) /* 460 */, CONST64(0x71495F756D1A5F60) /* 461 */,
CONST64(0x9BE853FB60AFEF77) /* 462 */, CONST64(0xADC786A7F7443DBF) /* 463 */,
CONST64(0x0904456173B29A82) /* 464 */, CONST64(0x58BC7A66C232BD5E) /* 465 */,
CONST64(0xF306558C673AC8B2) /* 466 */, CONST64(0x41F639C6B6C9772A) /* 467 */,
CONST64(0x216DEFE99FDA35DA) /* 468 */, CONST64(0x11640CC71C7BE615) /* 469 */,
CONST64(0x93C43694565C5527) /* 470 */, CONST64(0xEA038E6246777839) /* 471 */,
CONST64(0xF9ABF3CE5A3E2469) /* 472 */, CONST64(0x741E768D0FD312D2) /* 473 */,
CONST64(0x0144B883CED652C6) /* 474 */, CONST64(0xC20B5A5BA33F8552) /* 475 */,
CONST64(0x1AE69633C3435A9D) /* 476 */, CONST64(0x97A28CA4088CFDEC) /* 477 */,
CONST64(0x8824A43C1E96F420) /* 478 */, CONST64(0x37612FA66EEEA746) /* 479 */,
CONST64(0x6B4CB165F9CF0E5A) /* 480 */, CONST64(0x43AA1C06A0ABFB4A) /* 481 */,
CONST64(0x7F4DC26FF162796B) /* 482 */, CONST64(0x6CBACC8E54ED9B0F) /* 483 */,
CONST64(0xA6B7FFEFD2BB253E) /* 484 */, CONST64(0x2E25BC95B0A29D4F) /* 485 */,
CONST64(0x86D6A58BDEF1388C) /* 486 */, CONST64(0xDED74AC576B6F054) /* 487 */,
CONST64(0x8030BDBC2B45805D) /* 488 */, CONST64(0x3C81AF70E94D9289) /* 489 */,
CONST64(0x3EFF6DDA9E3100DB) /* 490 */, CONST64(0xB38DC39FDFCC8847) /* 491 */,
CONST64(0x123885528D17B87E) /* 492 */, CONST64(0xF2DA0ED240B1B642) /* 493 */,
CONST64(0x44CEFADCD54BF9A9) /* 494 */, CONST64(0x1312200E433C7EE6) /* 495 */,
CONST64(0x9FFCC84F3A78C748) /* 496 */, CONST64(0xF0CD1F72248576BB) /* 497 */,
CONST64(0xEC6974053638CFE4) /* 498 */, CONST64(0x2BA7B67C0CEC4E4C) /* 499 */,
CONST64(0xAC2F4DF3E5CE32ED) /* 500 */, CONST64(0xCB33D14326EA4C11) /* 501 */,
CONST64(0xA4E9044CC77E58BC) /* 502 */, CONST64(0x5F513293D934FCEF) /* 503 */,
CONST64(0x5DC9645506E55444) /* 504 */, CONST64(0x50DE418F317DE40A) /* 505 */,
CONST64(0x388CB31A69DDE259) /* 506 */, CONST64(0x2DB4A83455820A86) /* 507 */,
CONST64(0x9010A91E84711AE9) /* 508 */, CONST64(0x4DF7F0B7B1498371) /* 509 */,
CONST64(0xD62A2EABC0977179) /* 510 */, CONST64(0x22FAC097AA8D5C0E) /* 511 */,
CONST64(0xF49FCC2FF1DAF39B) /* 512 */, CONST64(0x487FD5C66FF29281) /* 513 */,
CONST64(0xE8A30667FCDCA83F) /* 514 */, CONST64(0x2C9B4BE3D2FCCE63) /* 515 */,
CONST64(0xDA3FF74B93FBBBC2) /* 516 */, CONST64(0x2FA165D2FE70BA66) /* 517 */,
CONST64(0xA103E279970E93D4) /* 518 */, CONST64(0xBECDEC77B0E45E71) /* 519 */,
CONST64(0xCFB41E723985E497) /* 520 */, CONST64(0xB70AAA025EF75017) /* 521 */,
CONST64(0xD42309F03840B8E0) /* 522 */, CONST64(0x8EFC1AD035898579) /* 523 */,
CONST64(0x96C6920BE2B2ABC5) /* 524 */, CONST64(0x66AF4163375A9172) /* 525 */,
CONST64(0x2174ABDCCA7127FB) /* 526 */, CONST64(0xB33CCEA64A72FF41) /* 527 */,
CONST64(0xF04A4933083066A5) /* 528 */, CONST64(0x8D970ACDD7289AF5) /* 529 */,
CONST64(0x8F96E8E031C8C25E) /* 530 */, CONST64(0xF3FEC02276875D47) /* 531 */,
CONST64(0xEC7BF310056190DD) /* 532 */, CONST64(0xF5ADB0AEBB0F1491) /* 533 */,
CONST64(0x9B50F8850FD58892) /* 534 */, CONST64(0x4975488358B74DE8) /* 535 */,
CONST64(0xA3354FF691531C61) /* 536 */, CONST64(0x0702BBE481D2C6EE) /* 537 */,
CONST64(0x89FB24057DEDED98) /* 538 */, CONST64(0xAC3075138596E902) /* 539 */,
CONST64(0x1D2D3580172772ED) /* 540 */, CONST64(0xEB738FC28E6BC30D) /* 541 */,
CONST64(0x5854EF8F63044326) /* 542 */, CONST64(0x9E5C52325ADD3BBE) /* 543 */,
CONST64(0x90AA53CF325C4623) /* 544 */, CONST64(0xC1D24D51349DD067) /* 545 */,
CONST64(0x2051CFEEA69EA624) /* 546 */, CONST64(0x13220F0A862E7E4F) /* 547 */,
CONST64(0xCE39399404E04864) /* 548 */, CONST64(0xD9C42CA47086FCB7) /* 549 */,
CONST64(0x685AD2238A03E7CC) /* 550 */, CONST64(0x066484B2AB2FF1DB) /* 551 */,
CONST64(0xFE9D5D70EFBF79EC) /* 552 */, CONST64(0x5B13B9DD9C481854) /* 553 */,
CONST64(0x15F0D475ED1509AD) /* 554 */, CONST64(0x0BEBCD060EC79851) /* 555 */,
CONST64(0xD58C6791183AB7F8) /* 556 */, CONST64(0xD1187C5052F3EEE4) /* 557 */,
CONST64(0xC95D1192E54E82FF) /* 558 */, CONST64(0x86EEA14CB9AC6CA2) /* 559 */,
CONST64(0x3485BEB153677D5D) /* 560 */, CONST64(0xDD191D781F8C492A) /* 561 */,
CONST64(0xF60866BAA784EBF9) /* 562 */, CONST64(0x518F643BA2D08C74) /* 563 */,
CONST64(0x8852E956E1087C22) /* 564 */, CONST64(0xA768CB8DC410AE8D) /* 565 */,
CONST64(0x38047726BFEC8E1A) /* 566 */, CONST64(0xA67738B4CD3B45AA) /* 567 */,
CONST64(0xAD16691CEC0DDE19) /* 568 */, CONST64(0xC6D4319380462E07) /* 569 */,
CONST64(0xC5A5876D0BA61938) /* 570 */, CONST64(0x16B9FA1FA58FD840) /* 571 */,
CONST64(0x188AB1173CA74F18) /* 572 */, CONST64(0xABDA2F98C99C021F) /* 573 */,
CONST64(0x3E0580AB134AE816) /* 574 */, CONST64(0x5F3B05B773645ABB) /* 575 */,
CONST64(0x2501A2BE5575F2F6) /* 576 */, CONST64(0x1B2F74004E7E8BA9) /* 577 */,
CONST64(0x1CD7580371E8D953) /* 578 */, CONST64(0x7F6ED89562764E30) /* 579 */,
CONST64(0xB15926FF596F003D) /* 580 */, CONST64(0x9F65293DA8C5D6B9) /* 581 */,
CONST64(0x6ECEF04DD690F84C) /* 582 */, CONST64(0x4782275FFF33AF88) /* 583 */,
CONST64(0xE41433083F820801) /* 584 */, CONST64(0xFD0DFE409A1AF9B5) /* 585 */,
CONST64(0x4325A3342CDB396B) /* 586 */, CONST64(0x8AE77E62B301B252) /* 587 */,
CONST64(0xC36F9E9F6655615A) /* 588 */, CONST64(0x85455A2D92D32C09) /* 589 */,
CONST64(0xF2C7DEA949477485) /* 590 */, CONST64(0x63CFB4C133A39EBA) /* 591 */,
CONST64(0x83B040CC6EBC5462) /* 592 */, CONST64(0x3B9454C8FDB326B0) /* 593 */,
CONST64(0x56F56A9E87FFD78C) /* 594 */, CONST64(0x2DC2940D99F42BC6) /* 595 */,
CONST64(0x98F7DF096B096E2D) /* 596 */, CONST64(0x19A6E01E3AD852BF) /* 597 */,
CONST64(0x42A99CCBDBD4B40B) /* 598 */, CONST64(0xA59998AF45E9C559) /* 599 */,
CONST64(0x366295E807D93186) /* 600 */, CONST64(0x6B48181BFAA1F773) /* 601 */,
CONST64(0x1FEC57E2157A0A1D) /* 602 */, CONST64(0x4667446AF6201AD5) /* 603 */,
CONST64(0xE615EBCACFB0F075) /* 604 */, CONST64(0xB8F31F4F68290778) /* 605 */,
CONST64(0x22713ED6CE22D11E) /* 606 */, CONST64(0x3057C1A72EC3C93B) /* 607 */,
CONST64(0xCB46ACC37C3F1F2F) /* 608 */, CONST64(0xDBB893FD02AAF50E) /* 609 */,
CONST64(0x331FD92E600B9FCF) /* 610 */, CONST64(0xA498F96148EA3AD6) /* 611 */,
CONST64(0xA8D8426E8B6A83EA) /* 612 */, CONST64(0xA089B274B7735CDC) /* 613 */,
CONST64(0x87F6B3731E524A11) /* 614 */, CONST64(0x118808E5CBC96749) /* 615 */,
CONST64(0x9906E4C7B19BD394) /* 616 */, CONST64(0xAFED7F7E9B24A20C) /* 617 */,
CONST64(0x6509EADEEB3644A7) /* 618 */, CONST64(0x6C1EF1D3E8EF0EDE) /* 619 */,
CONST64(0xB9C97D43E9798FB4) /* 620 */, CONST64(0xA2F2D784740C28A3) /* 621 */,
CONST64(0x7B8496476197566F) /* 622 */, CONST64(0x7A5BE3E6B65F069D) /* 623 */,
CONST64(0xF96330ED78BE6F10) /* 624 */, CONST64(0xEEE60DE77A076A15) /* 625 */,
CONST64(0x2B4BEE4AA08B9BD0) /* 626 */, CONST64(0x6A56A63EC7B8894E) /* 627 */,
CONST64(0x02121359BA34FEF4) /* 628 */, CONST64(0x4CBF99F8283703FC) /* 629 */,
CONST64(0x398071350CAF30C8) /* 630 */, CONST64(0xD0A77A89F017687A) /* 631 */,
CONST64(0xF1C1A9EB9E423569) /* 632 */, CONST64(0x8C7976282DEE8199) /* 633 */,
CONST64(0x5D1737A5DD1F7ABD) /* 634 */, CONST64(0x4F53433C09A9FA80) /* 635 */,
CONST64(0xFA8B0C53DF7CA1D9) /* 636 */, CONST64(0x3FD9DCBC886CCB77) /* 637 */,
CONST64(0xC040917CA91B4720) /* 638 */, CONST64(0x7DD00142F9D1DCDF) /* 639 */,
CONST64(0x8476FC1D4F387B58) /* 640 */, CONST64(0x23F8E7C5F3316503) /* 641 */,
CONST64(0x032A2244E7E37339) /* 642 */, CONST64(0x5C87A5D750F5A74B) /* 643 */,
CONST64(0x082B4CC43698992E) /* 644 */, CONST64(0xDF917BECB858F63C) /* 645 */,
CONST64(0x3270B8FC5BF86DDA) /* 646 */, CONST64(0x10AE72BB29B5DD76) /* 647 */,
CONST64(0x576AC94E7700362B) /* 648 */, CONST64(0x1AD112DAC61EFB8F) /* 649 */,
CONST64(0x691BC30EC5FAA427) /* 650 */, CONST64(0xFF246311CC327143) /* 651 */,
CONST64(0x3142368E30E53206) /* 652 */, CONST64(0x71380E31E02CA396) /* 653 */,
CONST64(0x958D5C960AAD76F1) /* 654 */, CONST64(0xF8D6F430C16DA536) /* 655 */,
CONST64(0xC8FFD13F1BE7E1D2) /* 656 */, CONST64(0x7578AE66004DDBE1) /* 657 */,
CONST64(0x05833F01067BE646) /* 658 */, CONST64(0xBB34B5AD3BFE586D) /* 659 */,
CONST64(0x095F34C9A12B97F0) /* 660 */, CONST64(0x247AB64525D60CA8) /* 661 */,
CONST64(0xDCDBC6F3017477D1) /* 662 */, CONST64(0x4A2E14D4DECAD24D) /* 663 */,
CONST64(0xBDB5E6D9BE0A1EEB) /* 664 */, CONST64(0x2A7E70F7794301AB) /* 665 */,
CONST64(0xDEF42D8A270540FD) /* 666 */, CONST64(0x01078EC0A34C22C1) /* 667 */,
CONST64(0xE5DE511AF4C16387) /* 668 */, CONST64(0x7EBB3A52BD9A330A) /* 669 */,
CONST64(0x77697857AA7D6435) /* 670 */, CONST64(0x004E831603AE4C32) /* 671 */,
CONST64(0xE7A21020AD78E312) /* 672 */, CONST64(0x9D41A70C6AB420F2) /* 673 */,
CONST64(0x28E06C18EA1141E6) /* 674 */, CONST64(0xD2B28CBD984F6B28) /* 675 */,
CONST64(0x26B75F6C446E9D83) /* 676 */, CONST64(0xBA47568C4D418D7F) /* 677 */,
CONST64(0xD80BADBFE6183D8E) /* 678 */, CONST64(0x0E206D7F5F166044) /* 679 */,
CONST64(0xE258A43911CBCA3E) /* 680 */, CONST64(0x723A1746B21DC0BC) /* 681 */,
CONST64(0xC7CAA854F5D7CDD3) /* 682 */, CONST64(0x7CAC32883D261D9C) /* 683 */,
CONST64(0x7690C26423BA942C) /* 684 */, CONST64(0x17E55524478042B8) /* 685 */,
CONST64(0xE0BE477656A2389F) /* 686 */, CONST64(0x4D289B5E67AB2DA0) /* 687 */,
CONST64(0x44862B9C8FBBFD31) /* 688 */, CONST64(0xB47CC8049D141365) /* 689 */,
CONST64(0x822C1B362B91C793) /* 690 */, CONST64(0x4EB14655FB13DFD8) /* 691 */,
CONST64(0x1ECBBA0714E2A97B) /* 692 */, CONST64(0x6143459D5CDE5F14) /* 693 */,
CONST64(0x53A8FBF1D5F0AC89) /* 694 */, CONST64(0x97EA04D81C5E5B00) /* 695 */,
CONST64(0x622181A8D4FDB3F3) /* 696 */, CONST64(0xE9BCD341572A1208) /* 697 */,
CONST64(0x1411258643CCE58A) /* 698 */, CONST64(0x9144C5FEA4C6E0A4) /* 699 */,
CONST64(0x0D33D06565CF620F) /* 700 */, CONST64(0x54A48D489F219CA1) /* 701 */,
CONST64(0xC43E5EAC6D63C821) /* 702 */, CONST64(0xA9728B3A72770DAF) /* 703 */,
CONST64(0xD7934E7B20DF87EF) /* 704 */, CONST64(0xE35503B61A3E86E5) /* 705 */,
CONST64(0xCAE321FBC819D504) /* 706 */, CONST64(0x129A50B3AC60BFA6) /* 707 */,
CONST64(0xCD5E68EA7E9FB6C3) /* 708 */, CONST64(0xB01C90199483B1C7) /* 709 */,
CONST64(0x3DE93CD5C295376C) /* 710 */, CONST64(0xAED52EDF2AB9AD13) /* 711 */,
CONST64(0x2E60F512C0A07884) /* 712 */, CONST64(0xBC3D86A3E36210C9) /* 713 */,
CONST64(0x35269D9B163951CE) /* 714 */, CONST64(0x0C7D6E2AD0CDB5FA) /* 715 */,
CONST64(0x59E86297D87F5733) /* 716 */, CONST64(0x298EF221898DB0E7) /* 717 */,
CONST64(0x55000029D1A5AA7E) /* 718 */, CONST64(0x8BC08AE1B5061B45) /* 719 */,
CONST64(0xC2C31C2B6C92703A) /* 720 */, CONST64(0x94CC596BAF25EF42) /* 721 */,
CONST64(0x0A1D73DB22540456) /* 722 */, CONST64(0x04B6A0F9D9C4179A) /* 723 */,
CONST64(0xEFFDAFA2AE3D3C60) /* 724 */, CONST64(0xF7C8075BB49496C4) /* 725 */,
CONST64(0x9CC5C7141D1CD4E3) /* 726 */, CONST64(0x78BD1638218E5534) /* 727 */,
CONST64(0xB2F11568F850246A) /* 728 */, CONST64(0xEDFABCFA9502BC29) /* 729 */,
CONST64(0x796CE5F2DA23051B) /* 730 */, CONST64(0xAAE128B0DC93537C) /* 731 */,
CONST64(0x3A493DA0EE4B29AE) /* 732 */, CONST64(0xB5DF6B2C416895D7) /* 733 */,
CONST64(0xFCABBD25122D7F37) /* 734 */, CONST64(0x70810B58105DC4B1) /* 735 */,
CONST64(0xE10FDD37F7882A90) /* 736 */, CONST64(0x524DCAB5518A3F5C) /* 737 */,
CONST64(0x3C9E85878451255B) /* 738 */, CONST64(0x4029828119BD34E2) /* 739 */,
CONST64(0x74A05B6F5D3CECCB) /* 740 */, CONST64(0xB610021542E13ECA) /* 741 */,
CONST64(0x0FF979D12F59E2AC) /* 742 */, CONST64(0x6037DA27E4F9CC50) /* 743 */,
CONST64(0x5E92975A0DF1847D) /* 744 */, CONST64(0xD66DE190D3E623FE) /* 745 */,
CONST64(0x5032D6B87B568048) /* 746 */, CONST64(0x9A36B7CE8235216E) /* 747 */,
CONST64(0x80272A7A24F64B4A) /* 748 */, CONST64(0x93EFED8B8C6916F7) /* 749 */,
CONST64(0x37DDBFF44CCE1555) /* 750 */, CONST64(0x4B95DB5D4B99BD25) /* 751 */,
CONST64(0x92D3FDA169812FC0) /* 752 */, CONST64(0xFB1A4A9A90660BB6) /* 753 */,
CONST64(0x730C196946A4B9B2) /* 754 */, CONST64(0x81E289AA7F49DA68) /* 755 */,
CONST64(0x64669A0F83B1A05F) /* 756 */, CONST64(0x27B3FF7D9644F48B) /* 757 */,
CONST64(0xCC6B615C8DB675B3) /* 758 */, CONST64(0x674F20B9BCEBBE95) /* 759 */,
CONST64(0x6F31238275655982) /* 760 */, CONST64(0x5AE488713E45CF05) /* 761 */,
CONST64(0xBF619F9954C21157) /* 762 */, CONST64(0xEABAC46040A8EAE9) /* 763 */,
CONST64(0x454C6FE9F2C0C1CD) /* 764 */, CONST64(0x419CF6496412691C) /* 765 */,
CONST64(0xD3DC3BEF265B0F70) /* 766 */, CONST64(0x6D0E60F5C3578A9E) /* 767 */,
CONST64(0x5B0E608526323C55) /* 768 */, CONST64(0x1A46C1A9FA1B59F5) /* 769 */,
CONST64(0xA9E245A17C4C8FFA) /* 770 */, CONST64(0x65CA5159DB2955D7) /* 771 */,
CONST64(0x05DB0A76CE35AFC2) /* 772 */, CONST64(0x81EAC77EA9113D45) /* 773 */,
CONST64(0x528EF88AB6AC0A0D) /* 774 */, CONST64(0xA09EA253597BE3FF) /* 775 */,
CONST64(0x430DDFB3AC48CD56) /* 776 */, CONST64(0xC4B3A67AF45CE46F) /* 777 */,
CONST64(0x4ECECFD8FBE2D05E) /* 778 */, CONST64(0x3EF56F10B39935F0) /* 779 */,
CONST64(0x0B22D6829CD619C6) /* 780 */, CONST64(0x17FD460A74DF2069) /* 781 */,
CONST64(0x6CF8CC8E8510ED40) /* 782 */, CONST64(0xD6C824BF3A6ECAA7) /* 783 */,
CONST64(0x61243D581A817049) /* 784 */, CONST64(0x048BACB6BBC163A2) /* 785 */,
CONST64(0xD9A38AC27D44CC32) /* 786 */, CONST64(0x7FDDFF5BAAF410AB) /* 787 */,
CONST64(0xAD6D495AA804824B) /* 788 */, CONST64(0xE1A6A74F2D8C9F94) /* 789 */,
CONST64(0xD4F7851235DEE8E3) /* 790 */, CONST64(0xFD4B7F886540D893) /* 791 */,
CONST64(0x247C20042AA4BFDA) /* 792 */, CONST64(0x096EA1C517D1327C) /* 793 */,
CONST64(0xD56966B4361A6685) /* 794 */, CONST64(0x277DA5C31221057D) /* 795 */,
CONST64(0x94D59893A43ACFF7) /* 796 */, CONST64(0x64F0C51CCDC02281) /* 797 */,
CONST64(0x3D33BCC4FF6189DB) /* 798 */, CONST64(0xE005CB184CE66AF1) /* 799 */,
CONST64(0xFF5CCD1D1DB99BEA) /* 800 */, CONST64(0xB0B854A7FE42980F) /* 801 */,
CONST64(0x7BD46A6A718D4B9F) /* 802 */, CONST64(0xD10FA8CC22A5FD8C) /* 803 */,
CONST64(0xD31484952BE4BD31) /* 804 */, CONST64(0xC7FA975FCB243847) /* 805 */,
CONST64(0x4886ED1E5846C407) /* 806 */, CONST64(0x28CDDB791EB70B04) /* 807 */,
CONST64(0xC2B00BE2F573417F) /* 808 */, CONST64(0x5C9590452180F877) /* 809 */,
CONST64(0x7A6BDDFFF370EB00) /* 810 */, CONST64(0xCE509E38D6D9D6A4) /* 811 */,
CONST64(0xEBEB0F00647FA702) /* 812 */, CONST64(0x1DCC06CF76606F06) /* 813 */,
CONST64(0xE4D9F28BA286FF0A) /* 814 */, CONST64(0xD85A305DC918C262) /* 815 */,
CONST64(0x475B1D8732225F54) /* 816 */, CONST64(0x2D4FB51668CCB5FE) /* 817 */,
CONST64(0xA679B9D9D72BBA20) /* 818 */, CONST64(0x53841C0D912D43A5) /* 819 */,
CONST64(0x3B7EAA48BF12A4E8) /* 820 */, CONST64(0x781E0E47F22F1DDF) /* 821 */,
CONST64(0xEFF20CE60AB50973) /* 822 */, CONST64(0x20D261D19DFFB742) /* 823 */,
CONST64(0x16A12B03062A2E39) /* 824 */, CONST64(0x1960EB2239650495) /* 825 */,
CONST64(0x251C16FED50EB8B8) /* 826 */, CONST64(0x9AC0C330F826016E) /* 827 */,
CONST64(0xED152665953E7671) /* 828 */, CONST64(0x02D63194A6369570) /* 829 */,
CONST64(0x5074F08394B1C987) /* 830 */, CONST64(0x70BA598C90B25CE1) /* 831 */,
CONST64(0x794A15810B9742F6) /* 832 */, CONST64(0x0D5925E9FCAF8C6C) /* 833 */,
CONST64(0x3067716CD868744E) /* 834 */, CONST64(0x910AB077E8D7731B) /* 835 */,
CONST64(0x6A61BBDB5AC42F61) /* 836 */, CONST64(0x93513EFBF0851567) /* 837 */,
CONST64(0xF494724B9E83E9D5) /* 838 */, CONST64(0xE887E1985C09648D) /* 839 */,
CONST64(0x34B1D3C675370CFD) /* 840 */, CONST64(0xDC35E433BC0D255D) /* 841 */,
CONST64(0xD0AAB84234131BE0) /* 842 */, CONST64(0x08042A50B48B7EAF) /* 843 */,
CONST64(0x9997C4EE44A3AB35) /* 844 */, CONST64(0x829A7B49201799D0) /* 845 */,
CONST64(0x263B8307B7C54441) /* 846 */, CONST64(0x752F95F4FD6A6CA6) /* 847 */,
CONST64(0x927217402C08C6E5) /* 848 */, CONST64(0x2A8AB754A795D9EE) /* 849 */,
CONST64(0xA442F7552F72943D) /* 850 */, CONST64(0x2C31334E19781208) /* 851 */,
CONST64(0x4FA98D7CEAEE6291) /* 852 */, CONST64(0x55C3862F665DB309) /* 853 */,
CONST64(0xBD0610175D53B1F3) /* 854 */, CONST64(0x46FE6CB840413F27) /* 855 */,
CONST64(0x3FE03792DF0CFA59) /* 856 */, CONST64(0xCFE700372EB85E8F) /* 857 */,
CONST64(0xA7BE29E7ADBCE118) /* 858 */, CONST64(0xE544EE5CDE8431DD) /* 859 */,
CONST64(0x8A781B1B41F1873E) /* 860 */, CONST64(0xA5C94C78A0D2F0E7) /* 861 */,
CONST64(0x39412E2877B60728) /* 862 */, CONST64(0xA1265EF3AFC9A62C) /* 863 */,
CONST64(0xBCC2770C6A2506C5) /* 864 */, CONST64(0x3AB66DD5DCE1CE12) /* 865 */,
CONST64(0xE65499D04A675B37) /* 866 */, CONST64(0x7D8F523481BFD216) /* 867 */,
CONST64(0x0F6F64FCEC15F389) /* 868 */, CONST64(0x74EFBE618B5B13C8) /* 869 */,
CONST64(0xACDC82B714273E1D) /* 870 */, CONST64(0xDD40BFE003199D17) /* 871 */,
CONST64(0x37E99257E7E061F8) /* 872 */, CONST64(0xFA52626904775AAA) /* 873 */,
CONST64(0x8BBBF63A463D56F9) /* 874 */, CONST64(0xF0013F1543A26E64) /* 875 */,
CONST64(0xA8307E9F879EC898) /* 876 */, CONST64(0xCC4C27A4150177CC) /* 877 */,
CONST64(0x1B432F2CCA1D3348) /* 878 */, CONST64(0xDE1D1F8F9F6FA013) /* 879 */,
CONST64(0x606602A047A7DDD6) /* 880 */, CONST64(0xD237AB64CC1CB2C7) /* 881 */,
CONST64(0x9B938E7225FCD1D3) /* 882 */, CONST64(0xEC4E03708E0FF476) /* 883 */,
CONST64(0xFEB2FBDA3D03C12D) /* 884 */, CONST64(0xAE0BCED2EE43889A) /* 885 */,
CONST64(0x22CB8923EBFB4F43) /* 886 */, CONST64(0x69360D013CF7396D) /* 887 */,
CONST64(0x855E3602D2D4E022) /* 888 */, CONST64(0x073805BAD01F784C) /* 889 */,
CONST64(0x33E17A133852F546) /* 890 */, CONST64(0xDF4874058AC7B638) /* 891 */,
CONST64(0xBA92B29C678AA14A) /* 892 */, CONST64(0x0CE89FC76CFAADCD) /* 893 */,
CONST64(0x5F9D4E0908339E34) /* 894 */, CONST64(0xF1AFE9291F5923B9) /* 895 */,
CONST64(0x6E3480F60F4A265F) /* 896 */, CONST64(0xEEBF3A2AB29B841C) /* 897 */,
CONST64(0xE21938A88F91B4AD) /* 898 */, CONST64(0x57DFEFF845C6D3C3) /* 899 */,
CONST64(0x2F006B0BF62CAAF2) /* 900 */, CONST64(0x62F479EF6F75EE78) /* 901 */,
CONST64(0x11A55AD41C8916A9) /* 902 */, CONST64(0xF229D29084FED453) /* 903 */,
CONST64(0x42F1C27B16B000E6) /* 904 */, CONST64(0x2B1F76749823C074) /* 905 */,
CONST64(0x4B76ECA3C2745360) /* 906 */, CONST64(0x8C98F463B91691BD) /* 907 */,
CONST64(0x14BCC93CF1ADE66A) /* 908 */, CONST64(0x8885213E6D458397) /* 909 */,
CONST64(0x8E177DF0274D4711) /* 910 */, CONST64(0xB49B73B5503F2951) /* 911 */,
CONST64(0x10168168C3F96B6B) /* 912 */, CONST64(0x0E3D963B63CAB0AE) /* 913 */,
CONST64(0x8DFC4B5655A1DB14) /* 914 */, CONST64(0xF789F1356E14DE5C) /* 915 */,
CONST64(0x683E68AF4E51DAC1) /* 916 */, CONST64(0xC9A84F9D8D4B0FD9) /* 917 */,
CONST64(0x3691E03F52A0F9D1) /* 918 */, CONST64(0x5ED86E46E1878E80) /* 919 */,
CONST64(0x3C711A0E99D07150) /* 920 */, CONST64(0x5A0865B20C4E9310) /* 921 */,
CONST64(0x56FBFC1FE4F0682E) /* 922 */, CONST64(0xEA8D5DE3105EDF9B) /* 923 */,
CONST64(0x71ABFDB12379187A) /* 924 */, CONST64(0x2EB99DE1BEE77B9C) /* 925 */,
CONST64(0x21ECC0EA33CF4523) /* 926 */, CONST64(0x59A4D7521805C7A1) /* 927 */,
CONST64(0x3896F5EB56AE7C72) /* 928 */, CONST64(0xAA638F3DB18F75DC) /* 929 */,
CONST64(0x9F39358DABE9808E) /* 930 */, CONST64(0xB7DEFA91C00B72AC) /* 931 */,
CONST64(0x6B5541FD62492D92) /* 932 */, CONST64(0x6DC6DEE8F92E4D5B) /* 933 */,
CONST64(0x353F57ABC4BEEA7E) /* 934 */, CONST64(0x735769D6DA5690CE) /* 935 */,
CONST64(0x0A234AA642391484) /* 936 */, CONST64(0xF6F9508028F80D9D) /* 937 */,
CONST64(0xB8E319A27AB3F215) /* 938 */, CONST64(0x31AD9C1151341A4D) /* 939 */,
CONST64(0x773C22A57BEF5805) /* 940 */, CONST64(0x45C7561A07968633) /* 941 */,
CONST64(0xF913DA9E249DBE36) /* 942 */, CONST64(0xDA652D9B78A64C68) /* 943 */,
CONST64(0x4C27A97F3BC334EF) /* 944 */, CONST64(0x76621220E66B17F4) /* 945 */,
CONST64(0x967743899ACD7D0B) /* 946 */, CONST64(0xF3EE5BCAE0ED6782) /* 947 */,
CONST64(0x409F753600C879FC) /* 948 */, CONST64(0x06D09A39B5926DB6) /* 949 */,
CONST64(0x6F83AEB0317AC588) /* 950 */, CONST64(0x01E6CA4A86381F21) /* 951 */,
CONST64(0x66FF3462D19F3025) /* 952 */, CONST64(0x72207C24DDFD3BFB) /* 953 */,
CONST64(0x4AF6B6D3E2ECE2EB) /* 954 */, CONST64(0x9C994DBEC7EA08DE) /* 955 */,
CONST64(0x49ACE597B09A8BC4) /* 956 */, CONST64(0xB38C4766CF0797BA) /* 957 */,
CONST64(0x131B9373C57C2A75) /* 958 */, CONST64(0xB1822CCE61931E58) /* 959 */,
CONST64(0x9D7555B909BA1C0C) /* 960 */, CONST64(0x127FAFDD937D11D2) /* 961 */,
CONST64(0x29DA3BADC66D92E4) /* 962 */, CONST64(0xA2C1D57154C2ECBC) /* 963 */,
CONST64(0x58C5134D82F6FE24) /* 964 */, CONST64(0x1C3AE3515B62274F) /* 965 */,
CONST64(0xE907C82E01CB8126) /* 966 */, CONST64(0xF8ED091913E37FCB) /* 967 */,
CONST64(0x3249D8F9C80046C9) /* 968 */, CONST64(0x80CF9BEDE388FB63) /* 969 */,
CONST64(0x1881539A116CF19E) /* 970 */, CONST64(0x5103F3F76BD52457) /* 971 */,
CONST64(0x15B7E6F5AE47F7A8) /* 972 */, CONST64(0xDBD7C6DED47E9CCF) /* 973 */,
CONST64(0x44E55C410228BB1A) /* 974 */, CONST64(0xB647D4255EDB4E99) /* 975 */,
CONST64(0x5D11882BB8AAFC30) /* 976 */, CONST64(0xF5098BBB29D3212A) /* 977 */,
CONST64(0x8FB5EA14E90296B3) /* 978 */, CONST64(0x677B942157DD025A) /* 979 */,
CONST64(0xFB58E7C0A390ACB5) /* 980 */, CONST64(0x89D3674C83BD4A01) /* 981 */,
CONST64(0x9E2DA4DF4BF3B93B) /* 982 */, CONST64(0xFCC41E328CAB4829) /* 983 */,
CONST64(0x03F38C96BA582C52) /* 984 */, CONST64(0xCAD1BDBD7FD85DB2) /* 985 */,
CONST64(0xBBB442C16082AE83) /* 986 */, CONST64(0xB95FE86BA5DA9AB0) /* 987 */,
CONST64(0xB22E04673771A93F) /* 988 */, CONST64(0x845358C9493152D8) /* 989 */,
CONST64(0xBE2A488697B4541E) /* 990 */, CONST64(0x95A2DC2DD38E6966) /* 991 */,
CONST64(0xC02C11AC923C852B) /* 992 */, CONST64(0x2388B1990DF2A87B) /* 993 */,
CONST64(0x7C8008FA1B4F37BE) /* 994 */, CONST64(0x1F70D0C84D54E503) /* 995 */,
CONST64(0x5490ADEC7ECE57D4) /* 996 */, CONST64(0x002B3C27D9063A3A) /* 997 */,
CONST64(0x7EAEA3848030A2BF) /* 998 */, CONST64(0xC602326DED2003C0) /* 999 */,
CONST64(0x83A7287D69A94086) /* 1000 */, CONST64(0xC57A5FCB30F57A8A) /* 1001 */,
CONST64(0xB56844E479EBE779) /* 1002 */, CONST64(0xA373B40F05DCBCE9) /* 1003 */,
CONST64(0xD71A786E88570EE2) /* 1004 */, CONST64(0x879CBACDBDE8F6A0) /* 1005 */,
CONST64(0x976AD1BCC164A32F) /* 1006 */, CONST64(0xAB21E25E9666D78B) /* 1007 */,
CONST64(0x901063AAE5E5C33C) /* 1008 */, CONST64(0x9818B34448698D90) /* 1009 */,
CONST64(0xE36487AE3E1E8ABB) /* 1010 */, CONST64(0xAFBDF931893BDCB4) /* 1011 */,
CONST64(0x6345A0DC5FBBD519) /* 1012 */, CONST64(0x8628FE269B9465CA) /* 1013 */,
CONST64(0x1E5D01603F9C51EC) /* 1014 */, CONST64(0x4DE44006A15049B7) /* 1015 */,
CONST64(0xBF6C70E5F776CBB1) /* 1016 */, CONST64(0x411218F2EF552BED) /* 1017 */,
CONST64(0xCB0C0708705A36A3) /* 1018 */, CONST64(0xE74D14754F986044) /* 1019 */,
CONST64(0xCD56D9430EA8280E) /* 1020 */, CONST64(0xC12591D7535F5065) /* 1021 */,
CONST64(0xC83223F1720AEF96) /* 1022 */, CONST64(0xC3A0396F7363A51F) /* 1023 */};
#ifdef _MSC_VER
#define INLINE __inline
#else
#define INLINE
#endif
/* one round of the hash function */
INLINE static void tiger_round(ulong64 *a, ulong64 *b, ulong64 *c, ulong64 x, int mul)
{
ulong64 tmp;
tmp = (*c ^= x);
*a -= t1[byte(tmp, 0)] ^ t2[byte(tmp, 2)] ^ t3[byte(tmp, 4)] ^ t4[byte(tmp, 6)];
tmp = (*b += t4[byte(tmp, 1)] ^ t3[byte(tmp, 3)] ^ t2[byte(tmp,5)] ^ t1[byte(tmp,7)]);
switch (mul) {
case 5: *b = (tmp << 2) + tmp; break;
case 7: *b = (tmp << 3) - tmp; break;
case 9: *b = (tmp << 3) + tmp; break;
}
}
/* one complete pass */
static void pass(ulong64 *a, ulong64 *b, ulong64 *c, ulong64 *x, int mul)
{
tiger_round(a,b,c,x[0],mul);
tiger_round(b,c,a,x[1],mul);
tiger_round(c,a,b,x[2],mul);
tiger_round(a,b,c,x[3],mul);
tiger_round(b,c,a,x[4],mul);
tiger_round(c,a,b,x[5],mul);
tiger_round(a,b,c,x[6],mul);
tiger_round(b,c,a,x[7],mul);
}
/* The key mixing schedule */
static void key_schedule(ulong64 *x)
{
x[0] -= x[7] ^ CONST64(0xA5A5A5A5A5A5A5A5);
x[1] ^= x[0];
x[2] += x[1];
x[3] -= x[2] ^ ((~x[1])<<19);
x[4] ^= x[3];
x[5] += x[4];
x[6] -= x[5] ^ ((~x[4])>>23);
x[7] ^= x[6];
x[0] += x[7];
x[1] -= x[0] ^ ((~x[7])<<19);
x[2] ^= x[1];
x[3] += x[2];
x[4] -= x[3] ^ ((~x[2])>>23);
x[5] ^= x[4];
x[6] += x[5];
x[7] -= x[6] ^ CONST64(0x0123456789ABCDEF);
}
#ifdef LTC_CLEAN_STACK
static int _tiger_compress(hash_state *md, unsigned char *buf)
#else
static int tiger_compress(hash_state *md, unsigned char *buf)
#endif
{
ulong64 a, b, c, x[8];
unsigned long i;
/* load words */
for (i = 0; i < 8; i++) {
LOAD64L(x[i],&buf[8*i]);
}
a = md->tiger.state[0];
b = md->tiger.state[1];
c = md->tiger.state[2];
pass(&a,&b,&c,x,5);
key_schedule(x);
pass(&c,&a,&b,x,7);
key_schedule(x);
pass(&b,&c,&a,x,9);
/* store state */
md->tiger.state[0] = a ^ md->tiger.state[0];
md->tiger.state[1] = b - md->tiger.state[1];
md->tiger.state[2] = c + md->tiger.state[2];
return CRYPT_OK;
}
#ifdef LTC_CLEAN_STACK
static int tiger_compress(hash_state *md, unsigned char *buf)
{
int err;
err = _tiger_compress(md, buf);
burn_stack(sizeof(ulong64) * 11 + sizeof(unsigned long));
return err;
}
#endif
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int tiger_init(hash_state *md)
{
LTC_ARGCHK(md != NULL);
md->tiger.state[0] = CONST64(0x0123456789ABCDEF);
md->tiger.state[1] = CONST64(0xFEDCBA9876543210);
md->tiger.state[2] = CONST64(0xF096A5B4C3B2E187);
md->tiger.curlen = 0;
md->tiger.length = 0;
return CRYPT_OK;
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
HASH_PROCESS(tiger_process, tiger_compress, tiger, 64)
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (24 bytes)
@return CRYPT_OK if successful
*/
int tiger_done(hash_state * md, unsigned char *out)
{
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
if (md->tiger.curlen >= sizeof(md->tiger.buf)) {
return CRYPT_INVALID_ARG;
}
/* increase the length of the message */
md->tiger.length += md->tiger.curlen * 8;
/* append the '1' bit */
md->tiger.buf[md->tiger.curlen++] = (unsigned char)0x01;
/* if the length is currently above 56 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal. */
if (md->tiger.curlen > 56) {
while (md->tiger.curlen < 64) {
md->tiger.buf[md->tiger.curlen++] = (unsigned char)0;
}
tiger_compress(md, md->tiger.buf);
md->tiger.curlen = 0;
}
/* pad upto 56 bytes of zeroes */
while (md->tiger.curlen < 56) {
md->tiger.buf[md->tiger.curlen++] = (unsigned char)0;
}
/* store length */
STORE64L(md->tiger.length, md->tiger.buf+56);
tiger_compress(md, md->tiger.buf);
/* copy output */
STORE64L(md->tiger.state[0], &out[0]);
STORE64L(md->tiger.state[1], &out[8]);
STORE64L(md->tiger.state[2], &out[16]);
#ifdef LTC_CLEAN_STACK
zeromem(md, sizeof(hash_state));
#endif
return CRYPT_OK;
}
void calc_tiger(char *str,uint8_t *digest,uint8_t *message,int32_t len)
{
int init_hexbytes_noT(char *hexbytes,unsigned char *message,long len);
hash_state md;
tiger_init(&md);
tiger_process(&md,message,len);
tiger_done(&md,digest);
if ( str != 0 )
init_hexbytes_noT(str,digest,24);
}
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int tiger_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct {
char *msg;
unsigned char hash[24];
} tests[] = {
{ "",
{ 0x32, 0x93, 0xac, 0x63, 0x0c, 0x13, 0xf0, 0x24,
0x5f, 0x92, 0xbb, 0xb1, 0x76, 0x6e, 0x16, 0x16,
0x7a, 0x4e, 0x58, 0x49, 0x2d, 0xde, 0x73, 0xf3 }
},
{ "abc",
{ 0x2a, 0xab, 0x14, 0x84, 0xe8, 0xc1, 0x58, 0xf2,
0xbf, 0xb8, 0xc5, 0xff, 0x41, 0xb5, 0x7a, 0x52,
0x51, 0x29, 0x13, 0x1c, 0x95, 0x7b, 0x5f, 0x93 }
},
{ "Tiger",
{ 0xdd, 0x00, 0x23, 0x07, 0x99, 0xf5, 0x00, 0x9f,
0xec, 0x6d, 0xeb, 0xc8, 0x38, 0xbb, 0x6a, 0x27,
0xdf, 0x2b, 0x9d, 0x6f, 0x11, 0x0c, 0x79, 0x37 }
},
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-",
{ 0xf7, 0x1c, 0x85, 0x83, 0x90, 0x2a, 0xfb, 0x87,
0x9e, 0xdf, 0xe6, 0x10, 0xf8, 0x2c, 0x0d, 0x47,
0x86, 0xa3, 0xa5, 0x34, 0x50, 0x44, 0x86, 0xb5 }
},
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-",
{ 0xc5, 0x40, 0x34, 0xe5, 0xb4, 0x3e, 0xb8, 0x00,
0x58, 0x48, 0xa7, 0xe0, 0xae, 0x6a, 0xac, 0x76,
0xe4, 0xff, 0x59, 0x0a, 0xe7, 0x15, 0xfd, 0x25 }
},
};
int i;
unsigned char tmp[24];
hash_state md;
for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
tiger_init(&md);
tiger_process(&md, (unsigned char *)tests[i].msg, (unsigned long)strlen(tests[i].msg));
tiger_done(&md, tmp);
if (XMEMCMP(tmp, tests[i].hash, 24) != 0) {
return CRYPT_FAIL_TESTVECTOR;
}
}
return CRYPT_OK;
#endif
}
#endif
/*
Hash of "":
24F0130C63AC9332 16166E76B1BB925F F373DE2D49584E7A
Hash of "abc":
F258C1E88414AB2A 527AB541FFC5B8BF 935F7B951C132951
Hash of "Tiger":
9F00F599072300DD 276ABB38C8EB6DEC 37790C116F9D2BDF
Hash of "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-":
87FB2A9083851CF7 470D2CF810E6DF9E B586445034A5A386
Hash of "ABCDEFGHIJKLMNOPQRSTUVWXYZ=abcdefghijklmnopqrstuvwxyz+0123456789":
467DB80863EBCE48 8DF1CD1261655DE9 57896565975F9197
Hash of "Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham":
0C410A042968868A 1671DA5A3FD29A72 5EC1E457D3CDB303
Hash of "Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham, proceedings of Fast Software Encryption 3, Cambridge.":
EBF591D5AFA655CE 7F22894FF87F54AC 89C811B6B0DA3193
Hash of "Tiger - A Fast New Hash Function, by Ross Anderson and Eli Biham, proceedings of Fast Software Encryption 3, Cambridge, 1996.":
3D9AEB03D1BD1A63 57B2774DFD6D5B24 DD68151D503974FC
Hash of "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-":
00B83EB4E53440C5 76AC6AAEE0A74858 25FD15E70A59FFE4
*/
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/tiger.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */

95
crypto777/hmac/tomcrypt.h

@ -0,0 +1,95 @@
#ifndef TOMCRYPT_H_
#define TOMCRYPT_H_
//#include <assert.h>
//#include <stdio.h>
//#include <string.h>
//#include <stdlib.h>
//#include <time.h>
//#include <ctype.h>
//#include <limits.h>
/* use configuration data */
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <memory.h>
#define ulong32 uint32_t
#define zeromem(buf,len) memset(buf,0,len)
#include "tomcrypt_custom.h"
#ifdef __cplusplus
extern "C" {
#endif
/* version */
#define CRYPT 0x0117
#define SCRYPT "1.17"
/* max size of either a cipher/hash block or symmetric key [largest of the two] */
#define MAXBLOCKSIZE 128
/* descriptor table size */
#define TAB_SIZE 32
/* error codes [will be expanded in future releases] */
enum {
CRYPT_OK=0, /* Result OK */
CRYPT_ERROR, /* Generic Error */
CRYPT_NOP, /* Not a failure but no operation was performed */
CRYPT_INVALID_KEYSIZE, /* Invalid key size given */
CRYPT_INVALID_ROUNDS, /* Invalid number of rounds */
CRYPT_FAIL_TESTVECTOR, /* Algorithm failed test vectors */
CRYPT_BUFFER_OVERFLOW, /* Not enough space for output */
CRYPT_INVALID_PACKET, /* Invalid input packet given */
CRYPT_INVALID_PRNGSIZE, /* Invalid number of bits for a PRNG */
CRYPT_ERROR_READPRNG, /* Could not read enough from PRNG */
CRYPT_INVALID_CIPHER, /* Invalid cipher specified */
CRYPT_INVALID_HASH, /* Invalid hash specified */
CRYPT_INVALID_PRNG, /* Invalid PRNG specified */
CRYPT_MEM, /* Out of memory */
CRYPT_PK_TYPE_MISMATCH, /* Not equivalent types of PK keys */
CRYPT_PK_NOT_PRIVATE, /* Requires a private PK key */
CRYPT_INVALID_ARG, /* Generic invalid argument */
CRYPT_FILE_NOTFOUND, /* File Not Found */
CRYPT_PK_INVALID_TYPE, /* Invalid type of PK key */
CRYPT_PK_INVALID_SYSTEM,/* Invalid PK system specified */
CRYPT_PK_DUP, /* Duplicate key already in key ring */
CRYPT_PK_NOT_FOUND, /* Key not found in keyring */
CRYPT_PK_INVALID_SIZE, /* Invalid size input for PK parameters */
CRYPT_INVALID_PRIME_SIZE,/* Invalid size of prime requested */
CRYPT_PK_INVALID_PADDING /* Invalid padding on input */
};
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_cipher.h"
#include "tomcrypt_hash.h"
#include "tomcrypt_mac.h"
#include "tomcrypt_prng.h"
#include "tomcrypt_pk.h"
#include "tomcrypt_math.h"
#include "tomcrypt_misc.h"
#include "tomcrypt_argchk.h"
#include "tomcrypt_pkcs.h"
#ifdef __cplusplus
}
#endif
#endif /* TOMCRYPT_H_ */
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt.h,v $ */
/* $Revision: 1.21 $ */
/* $Date: 2006/12/16 19:34:05 $ */

38
crypto777/hmac/tomcrypt_argchk.h

@ -0,0 +1,38 @@
/* Defines the LTC_ARGCHK macro used within the library */
/* ARGTYPE is defined in mycrypt_cfg.h */
#if ARGTYPE == 0
//#include <signal.h>
/* this is the default LibTomCrypt macro */
void crypt_argchk(char *v, char *s, int d);
#define LTC_ARGCHK(x) if (!(x)) { crypt_argchk(#x, __FILE__, __LINE__); }
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)
#elif ARGTYPE == 1
/* fatal type of error */
#define LTC_ARGCHK(x) assert((x))
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)
#elif ARGTYPE == 2
#define LTC_ARGCHK(x) if (!(x)) { fprintf(stderr, "\nwarning: ARGCHK failed at %s:%d\n", __FILE__, __LINE__); }
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)
#elif ARGTYPE == 3
#define LTC_ARGCHK(x)
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)
#elif ARGTYPE == 4
#define LTC_ARGCHK(x) if (!(x)) return CRYPT_INVALID_ARG;
#define LTC_ARGCHKVD(x) if (!(x)) return;
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_argchk.h,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2006/08/27 20:50:21 $ */

140
crypto777/hmac/tomcrypt_cfg.h

@ -0,0 +1,140 @@
/* This is the build config file.
*
* With this you can setup what to inlcude/exclude automatically during any build. Just comment
* out the line that #define's the word for the thing you want to remove. phew!
*/
#ifndef TOMCRYPT_CFG_H
#define TOMCRYPT_CFG_H
#if defined(_WIN32) || defined(_MSC_VER)
#define LTC_CALL __cdecl
#else
#ifndef LTC_CALL
#define LTC_CALL
#endif
#endif
#ifndef LTC_EXPORT
#define LTC_EXPORT
#endif
/* certain platforms use macros for these, making the prototypes broken */
#ifndef LTC_NO_PROTOTYPES
/* you can change how memory allocation works ... */
LTC_EXPORT void * LTC_CALL XMALLOC(size_t n);
LTC_EXPORT void * LTC_CALL XREALLOC(void *p, size_t n);
LTC_EXPORT void * LTC_CALL XCALLOC(size_t n, size_t s);
LTC_EXPORT void LTC_CALL XFREE(void *p);
LTC_EXPORT void LTC_CALL XQSORT(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *));
/* change the clock function too */
#ifndef _WIN32
LTC_EXPORT clock_t LTC_CALL XCLOCK(void);
#endif
/* various other functions */
LTC_EXPORT void * LTC_CALL XMEMCPY(void *dest, const void *src, size_t n);
LTC_EXPORT int LTC_CALL XMEMCMP(const void *s1, const void *s2, size_t n);
LTC_EXPORT void * LTC_CALL XMEMSET(void *s, int c, size_t n);
LTC_EXPORT int LTC_CALL XSTRCMP(const char *s1, const char *s2);
#endif
/* type of argument checking, 0=default, 1=fatal and 2=error+continue, 3=nothing */
#ifndef ARGTYPE
#define ARGTYPE 0
#endif
/* Controls endianess and size of registers. Leave uncommented to get platform neutral [slower] code
*
* Note: in order to use the optimized macros your platform must support unaligned 32 and 64 bit read/writes.
* The x86 platforms allow this but some others [ARM for instance] do not. On those platforms you **MUST**
* use the portable [slower] macros.
*/
/* detect x86-32 machines somewhat */
#if !defined(__STRICT_ANSI__) && (defined(INTEL_CC) || (defined(_MSC_VER) && defined(WIN32)) || (defined(__GNUC__) && (defined(__DJGPP__) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__i386__))))
#define ENDIAN_LITTLE
#define ENDIAN_32BITWORD
#define LTC_FAST
#define LTC_FAST_TYPE unsigned long
#endif
/* detects MIPS R5900 processors (PS2) */
#if (defined(__R5900) || defined(R5900) || defined(__R5900__)) && (defined(_mips) || defined(__mips__) || defined(mips))
#define ENDIAN_LITTLE
#define ENDIAN_64BITWORD
#endif
/* detect amd64 */
#if !defined(__STRICT_ANSI__) && defined(__x86_64__)
#define ENDIAN_LITTLE
#define ENDIAN_64BITWORD
#define LTC_FAST
#define LTC_FAST_TYPE unsigned long
#endif
/* detect PPC32 */
#if !defined(__STRICT_ANSI__) && defined(LTC_PPC32)
#define ENDIAN_BIG
#define ENDIAN_32BITWORD
#define LTC_FAST
#define LTC_FAST_TYPE unsigned long
#endif
/* detect sparc and sparc64 */
#if defined(__sparc__)
#define ENDIAN_BIG
#if defined(__arch64__)
#define ENDIAN_64BITWORD
#else
#define ENDIAN_32BITWORD
#endif
#endif
#ifdef LTC_NO_FAST
#ifdef LTC_FAST
#undef LTC_FAST
#endif
#endif
#define LTC_NO_ASM
/* No asm is a quick way to disable anything "not portable" */
#ifdef LTC_NO_ASM
#undef ENDIAN_LITTLE
#undef ENDIAN_BIG
#undef ENDIAN_32BITWORD
#undef ENDIAN_64BITWORD
#undef LTC_FAST
#undef LTC_FAST_TYPE
#define LTC_NO_ROLC
#define LTC_NO_BSWAP
#endif
/* #define ENDIAN_LITTLE */
/* #define ENDIAN_BIG */
/* #define ENDIAN_32BITWORD */
/* #define ENDIAN_64BITWORD */
#if (defined(ENDIAN_BIG) || defined(ENDIAN_LITTLE)) && !(defined(ENDIAN_32BITWORD) || defined(ENDIAN_64BITWORD))
#error You must specify a word size as well as endianess in tomcrypt_cfg.h
#endif
#if !(defined(ENDIAN_BIG) || defined(ENDIAN_LITTLE))
#define ENDIAN_NEUTRAL
#endif
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_cfg.h,v $ */
/* $Revision: 1.19 $ */
/* $Date: 2006/12/04 02:19:48 $ */

891
crypto777/hmac/tomcrypt_cipher.h

@ -0,0 +1,891 @@
/* ---- SYMMETRIC KEY STUFF -----
*
* We put each of the ciphers scheduled keys in their own structs then we put all of
* the key formats in one union. This makes the function prototypes easier to use.
*/
#ifdef LTC_BLOWFISH
struct blowfish_key {
ulong32 S[4][256];
ulong32 K[18];
};
#endif
#ifdef LTC_RC5
struct rc5_key {
int rounds;
ulong32 K[50];
};
#endif
#ifdef LTC_RC6
struct rc6_key {
ulong32 K[44];
};
#endif
#ifdef LTC_SAFERP
struct saferp_key {
unsigned char K[33][16];
long rounds;
};
#endif
#ifdef LTC_RIJNDAEL
struct rijndael_key {
ulong32 eK[60], dK[60];
int Nr;
};
#endif
#ifdef LTC_KSEED
struct kseed_key {
ulong32 K[32], dK[32];
};
#endif
#ifdef LTC_KASUMI
struct kasumi_key {
ulong32 KLi1[8], KLi2[8],
KOi1[8], KOi2[8], KOi3[8],
KIi1[8], KIi2[8], KIi3[8];
};
#endif
#ifdef LTC_XTEA
struct xtea_key {
unsigned long A[32], B[32];
};
#endif
#ifdef LTC_TWOFISH
#ifndef LTC_TWOFISH_SMALL
struct twofish_key {
ulong32 S[4][256], K[40];
};
#else
struct twofish_key {
ulong32 K[40];
unsigned char S[32], start;
};
#endif
#endif
#ifdef LTC_SAFER
#define LTC_SAFER_K64_DEFAULT_NOF_ROUNDS 6
#define LTC_SAFER_K128_DEFAULT_NOF_ROUNDS 10
#define LTC_SAFER_SK64_DEFAULT_NOF_ROUNDS 8
#define LTC_SAFER_SK128_DEFAULT_NOF_ROUNDS 10
#define LTC_SAFER_MAX_NOF_ROUNDS 13
#define LTC_SAFER_BLOCK_LEN 8
#define LTC_SAFER_KEY_LEN (1 + LTC_SAFER_BLOCK_LEN * (1 + 2 * LTC_SAFER_MAX_NOF_ROUNDS))
typedef unsigned char safer_block_t[LTC_SAFER_BLOCK_LEN];
typedef unsigned char safer_key_t[LTC_SAFER_KEY_LEN];
struct safer_key { safer_key_t key; };
#endif
#ifdef LTC_RC2
struct rc2_key { unsigned xkey[64]; };
#endif
#ifdef LTC_DES
struct des_key {
ulong32 ek[32], dk[32];
};
struct des3_key {
ulong32 ek[3][32], dk[3][32];
};
#endif
#ifdef LTC_CAST5
struct cast5_key {
ulong32 K[32], keylen;
};
#endif
#ifdef LTC_NOEKEON
struct noekeon_key {
ulong32 K[4], dK[4];
};
#endif
#ifdef LTC_SKIPJACK
struct skipjack_key {
unsigned char key[10];
};
#endif
#ifdef LTC_KHAZAD
struct khazad_key {
ulong64 roundKeyEnc[8 + 1];
ulong64 roundKeyDec[8 + 1];
};
#endif
#ifdef LTC_ANUBIS
struct anubis_key {
int keyBits;
int R;
ulong32 roundKeyEnc[18 + 1][4];
ulong32 roundKeyDec[18 + 1][4];
};
#endif
#ifdef LTC_MULTI2
struct multi2_key {
int N;
ulong32 uk[8];
};
#endif
typedef union Symmetric_key {
#ifdef LTC_DES
struct des_key des;
struct des3_key des3;
#endif
#ifdef LTC_RC2
struct rc2_key rc2;
#endif
#ifdef LTC_SAFER
struct safer_key safer;
#endif
#ifdef LTC_TWOFISH
struct twofish_key twofish;
#endif
#ifdef LTC_BLOWFISH
struct blowfish_key blowfish;
#endif
#ifdef LTC_RC5
struct rc5_key rc5;
#endif
#ifdef LTC_RC6
struct rc6_key rc6;
#endif
#ifdef LTC_SAFERP
struct saferp_key saferp;
#endif
#ifdef LTC_RIJNDAEL
struct rijndael_key rijndael;
#endif
#ifdef LTC_XTEA
struct xtea_key xtea;
#endif
#ifdef LTC_CAST5
struct cast5_key cast5;
#endif
#ifdef LTC_NOEKEON
struct noekeon_key noekeon;
#endif
#ifdef LTC_SKIPJACK
struct skipjack_key skipjack;
#endif
#ifdef LTC_KHAZAD
struct khazad_key khazad;
#endif
#ifdef LTC_ANUBIS
struct anubis_key anubis;
#endif
#ifdef LTC_KSEED
struct kseed_key kseed;
#endif
#ifdef LTC_KASUMI
struct kasumi_key kasumi;
#endif
#ifdef LTC_MULTI2
struct multi2_key multi2;
#endif
void *data;
} symmetric_key;
#ifdef LTC_ECB_MODE
/** A block cipher ECB structure */
typedef struct {
/** The index of the cipher chosen */
int cipher,
/** The block size of the given cipher */
blocklen;
/** The scheduled key */
symmetric_key key;
} symmetric_ECB;
#endif
#ifdef LTC_CFB_MODE
/** A block cipher CFB structure */
typedef struct {
/** The index of the cipher chosen */
int cipher,
/** The block size of the given cipher */
blocklen,
/** The padding offset */
padlen;
/** The current IV */
unsigned char IV[MAXBLOCKSIZE],
/** The pad used to encrypt/decrypt */
pad[MAXBLOCKSIZE];
/** The scheduled key */
symmetric_key key;
} symmetric_CFB;
#endif
#ifdef LTC_OFB_MODE
/** A block cipher OFB structure */
typedef struct {
/** The index of the cipher chosen */
int cipher,
/** The block size of the given cipher */
blocklen,
/** The padding offset */
padlen;
/** The current IV */
unsigned char IV[MAXBLOCKSIZE];
/** The scheduled key */
symmetric_key key;
} symmetric_OFB;
#endif
#ifdef LTC_CBC_MODE
/** A block cipher CBC structure */
typedef struct {
/** The index of the cipher chosen */
int cipher,
/** The block size of the given cipher */
blocklen;
/** The current IV */
unsigned char IV[MAXBLOCKSIZE];
/** The scheduled key */
symmetric_key key;
} symmetric_CBC;
#endif
#ifdef LTC_CTR_MODE
/** A block cipher CTR structure */
typedef struct {
/** The index of the cipher chosen */
int cipher,
/** The block size of the given cipher */
blocklen,
/** The padding offset */
padlen,
/** The mode (endianess) of the CTR, 0==little, 1==big */
mode,
/** counter width */
ctrlen;
/** The counter */
unsigned char ctr[MAXBLOCKSIZE],
/** The pad used to encrypt/decrypt */
pad[MAXBLOCKSIZE];
/** The scheduled key */
symmetric_key key;
} symmetric_CTR;
#endif
#ifdef LTC_LRW_MODE
/** A LRW structure */
typedef struct {
/** The index of the cipher chosen (must be a 128-bit block cipher) */
int cipher;
/** The current IV */
unsigned char IV[16],
/** the tweak key */
tweak[16],
/** The current pad, it's the product of the first 15 bytes against the tweak key */
pad[16];
/** The scheduled symmetric key */
symmetric_key key;
#ifdef LRW_TABLES
/** The pre-computed multiplication table */
unsigned char PC[16][256][16];
#endif
} symmetric_LRW;
#endif
#ifdef LTC_F8_MODE
/** A block cipher F8 structure */
typedef struct {
/** The index of the cipher chosen */
int cipher,
/** The block size of the given cipher */
blocklen,
/** The padding offset */
padlen;
/** The current IV */
unsigned char IV[MAXBLOCKSIZE],
MIV[MAXBLOCKSIZE];
/** Current block count */
ulong32 blockcnt;
/** The scheduled key */
symmetric_key key;
} symmetric_F8;
#endif
/** cipher descriptor table, last entry has "name == NULL" to mark the end of table */
extern struct ltc_cipher_descriptor {
/** name of cipher */
char *name;
/** internal ID */
unsigned char ID;
/** min keysize (octets) */
int min_key_length,
/** max keysize (octets) */
max_key_length,
/** block size (octets) */
block_length,
/** default number of rounds */
default_rounds;
/** Setup the cipher
@param key The input symmetric key
@param keylen The length of the input key (octets)
@param num_rounds The requested number of rounds (0==default)
@param skey [out] The destination of the scheduled key
@return CRYPT_OK if successful
*/
int (*setup)(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
/** Encrypt a block
@param pt The plaintext
@param ct [out] The ciphertext
@param skey The scheduled key
@return CRYPT_OK if successful
*/
int (*ecb_encrypt)(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
/** Decrypt a block
@param ct The ciphertext
@param pt [out] The plaintext
@param skey The scheduled key
@return CRYPT_OK if successful
*/
int (*ecb_decrypt)(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
/** Test the block cipher
@return CRYPT_OK if successful, CRYPT_NOP if self-testing has been disabled
*/
int (*test)(void);
/** Terminate the context
@param skey The scheduled key
*/
void (*done)(symmetric_key *skey);
/** Determine a key size
@param keysize [in/out] The size of the key desired and the suggested size
@return CRYPT_OK if successful
*/
int (*keysize)(int *keysize);
/** Accelerators **/
/** Accelerated ECB encryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_ecb_encrypt)(const unsigned char *pt, unsigned char *ct, unsigned long blocks, symmetric_key *skey);
/** Accelerated ECB decryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_ecb_decrypt)(const unsigned char *ct, unsigned char *pt, unsigned long blocks, symmetric_key *skey);
/** Accelerated CBC encryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_cbc_encrypt)(const unsigned char *pt, unsigned char *ct, unsigned long blocks, unsigned char *IV, symmetric_key *skey);
/** Accelerated CBC decryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_cbc_decrypt)(const unsigned char *ct, unsigned char *pt, unsigned long blocks, unsigned char *IV, symmetric_key *skey);
/** Accelerated CTR encryption
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param mode little or big endian counter (mode=0 or mode=1)
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_ctr_encrypt)(const unsigned char *pt, unsigned char *ct, unsigned long blocks, unsigned char *IV, int mode, symmetric_key *skey);
/** Accelerated LRW
@param pt Plaintext
@param ct Ciphertext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param tweak The LRW tweak
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_lrw_encrypt)(const unsigned char *pt, unsigned char *ct, unsigned long blocks, unsigned char *IV, const unsigned char *tweak, symmetric_key *skey);
/** Accelerated LRW
@param ct Ciphertext
@param pt Plaintext
@param blocks The number of complete blocks to process
@param IV The initial value (input/output)
@param tweak The LRW tweak
@param skey The scheduled key context
@return CRYPT_OK if successful
*/
int (*accel_lrw_decrypt)(const unsigned char *ct, unsigned char *pt, unsigned long blocks, unsigned char *IV, const unsigned char *tweak, symmetric_key *skey);
/** Accelerated CCM packet (one-shot)
@param key The secret key to use
@param keylen The length of the secret key (octets)
@param uskey A previously scheduled key [optional can be NULL]
@param nonce The session nonce [use once]
@param noncelen The length of the nonce
@param header The header for the session
@param headerlen The length of the header (octets)
@param pt [out] The plaintext
@param ptlen The length of the plaintext (octets)
@param ct [out] The ciphertext
@param tag [out] The destination tag
@param taglen [in/out] The max size and resulting size of the authentication tag
@param direction Encrypt or Decrypt direction (0 or 1)
@return CRYPT_OK if successful
*/
int (*accel_ccm_memory)(
const unsigned char *key, unsigned long keylen,
symmetric_key *uskey,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
/** Accelerated GCM packet (one shot)
@param key The secret key
@param keylen The length of the secret key
@param IV The initial vector
@param IVlen The length of the initial vector
@param adata The additional authentication data (header)
@param adatalen The length of the adata
@param pt The plaintext
@param ptlen The length of the plaintext (ciphertext length is the same)
@param ct The ciphertext
@param tag [out] The MAC tag
@param taglen [in/out] The MAC tag length
@param direction Encrypt or Decrypt mode (GCM_ENCRYPT or GCM_DECRYPT)
@return CRYPT_OK on success
*/
int (*accel_gcm_memory)(
const unsigned char *key, unsigned long keylen,
const unsigned char *IV, unsigned long IVlen,
const unsigned char *adata, unsigned long adatalen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
/** Accelerated one shot LTC_OMAC
@param key The secret key
@param keylen The key length (octets)
@param in The message
@param inlen Length of message (octets)
@param out [out] Destination for tag
@param outlen [in/out] Initial and final size of out
@return CRYPT_OK on success
*/
int (*omac_memory)(
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
/** Accelerated one shot XCBC
@param key The secret key
@param keylen The key length (octets)
@param in The message
@param inlen Length of message (octets)
@param out [out] Destination for tag
@param outlen [in/out] Initial and final size of out
@return CRYPT_OK on success
*/
int (*xcbc_memory)(
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
/** Accelerated one shot F9
@param key The secret key
@param keylen The key length (octets)
@param in The message
@param inlen Length of message (octets)
@param out [out] Destination for tag
@param outlen [in/out] Initial and final size of out
@return CRYPT_OK on success
@remark Requires manual padding
*/
int (*f9_memory)(
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
} cipher_descriptor[];
#ifdef LTC_BLOWFISH
int blowfish_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int blowfish_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int blowfish_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int blowfish_test(void);
void blowfish_done(symmetric_key *skey);
int blowfish_keysize(int *keysize);
extern const struct ltc_cipher_descriptor blowfish_desc;
#endif
#ifdef LTC_RC5
int rc5_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rc5_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int rc5_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int rc5_test(void);
void rc5_done(symmetric_key *skey);
int rc5_keysize(int *keysize);
extern const struct ltc_cipher_descriptor rc5_desc;
#endif
#ifdef LTC_RC6
int rc6_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rc6_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int rc6_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int rc6_test(void);
void rc6_done(symmetric_key *skey);
int rc6_keysize(int *keysize);
extern const struct ltc_cipher_descriptor rc6_desc;
#endif
#ifdef LTC_RC2
int rc2_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rc2_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int rc2_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int rc2_test(void);
void rc2_done(symmetric_key *skey);
int rc2_keysize(int *keysize);
extern const struct ltc_cipher_descriptor rc2_desc;
#endif
#ifdef LTC_SAFERP
int saferp_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int saferp_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int saferp_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int saferp_test(void);
void saferp_done(symmetric_key *skey);
int saferp_keysize(int *keysize);
extern const struct ltc_cipher_descriptor saferp_desc;
#endif
#ifdef LTC_SAFER
int safer_k64_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int safer_sk64_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int safer_k128_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int safer_sk128_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int safer_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *key);
int safer_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *key);
int safer_k64_test(void);
int safer_sk64_test(void);
int safer_sk128_test(void);
void safer_done(symmetric_key *skey);
int safer_64_keysize(int *keysize);
int safer_128_keysize(int *keysize);
extern const struct ltc_cipher_descriptor safer_k64_desc, safer_k128_desc, safer_sk64_desc, safer_sk128_desc;
#endif
#ifdef LTC_RIJNDAEL
/* make aes an alias */
#define aes_setup rijndael_setup
#define aes_ecb_encrypt rijndael_ecb_encrypt
#define aes_ecb_decrypt rijndael_ecb_decrypt
#define aes_test rijndael_test
#define aes_done rijndael_done
#define aes_keysize rijndael_keysize
#define aes_enc_setup rijndael_enc_setup
#define aes_enc_ecb_encrypt rijndael_enc_ecb_encrypt
#define aes_enc_keysize rijndael_enc_keysize
int rijndael_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rijndael_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int rijndael_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int rijndael_test(void);
void rijndael_done(symmetric_key *skey);
int rijndael_keysize(int *keysize);
int rijndael_enc_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rijndael_enc_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
void rijndael_enc_done(symmetric_key *skey);
int rijndael_enc_keysize(int *keysize);
extern const struct ltc_cipher_descriptor rijndael_desc, aes_desc;
extern const struct ltc_cipher_descriptor rijndael_enc_desc, aes_enc_desc;
#endif
#ifdef LTC_XTEA
int xtea_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int xtea_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int xtea_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int xtea_test(void);
void xtea_done(symmetric_key *skey);
int xtea_keysize(int *keysize);
extern const struct ltc_cipher_descriptor xtea_desc;
#endif
#ifdef LTC_TWOFISH
int twofish_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int twofish_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int twofish_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int twofish_test(void);
void twofish_done(symmetric_key *skey);
int twofish_keysize(int *keysize);
extern const struct ltc_cipher_descriptor twofish_desc;
#endif
#ifdef LTC_DES
int des_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int des_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int des_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int des_test(void);
void des_done(symmetric_key *skey);
int des_keysize(int *keysize);
int des3_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int des3_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int des3_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int des3_test(void);
void des3_done(symmetric_key *skey);
int des3_keysize(int *keysize);
extern const struct ltc_cipher_descriptor des_desc, des3_desc;
#endif
#ifdef LTC_CAST5
int cast5_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int cast5_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int cast5_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int cast5_test(void);
void cast5_done(symmetric_key *skey);
int cast5_keysize(int *keysize);
extern const struct ltc_cipher_descriptor cast5_desc;
#endif
#ifdef LTC_NOEKEON
int noekeon_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int noekeon_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int noekeon_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int noekeon_test(void);
void noekeon_done(symmetric_key *skey);
int noekeon_keysize(int *keysize);
extern const struct ltc_cipher_descriptor noekeon_desc;
#endif
#ifdef LTC_SKIPJACK
int skipjack_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int skipjack_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int skipjack_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int skipjack_test(void);
void skipjack_done(symmetric_key *skey);
int skipjack_keysize(int *keysize);
extern const struct ltc_cipher_descriptor skipjack_desc;
#endif
#ifdef LTC_KHAZAD
int khazad_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int khazad_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int khazad_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int khazad_test(void);
void khazad_done(symmetric_key *skey);
int khazad_keysize(int *keysize);
extern const struct ltc_cipher_descriptor khazad_desc;
#endif
#ifdef LTC_ANUBIS
int anubis_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int anubis_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int anubis_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int anubis_test(void);
void anubis_done(symmetric_key *skey);
int anubis_keysize(int *keysize);
extern const struct ltc_cipher_descriptor anubis_desc;
#endif
#ifdef LTC_KSEED
int kseed_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int kseed_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int kseed_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int kseed_test(void);
void kseed_done(symmetric_key *skey);
int kseed_keysize(int *keysize);
extern const struct ltc_cipher_descriptor kseed_desc;
#endif
#ifdef LTC_KASUMI
int kasumi_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int kasumi_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int kasumi_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int kasumi_test(void);
void kasumi_done(symmetric_key *skey);
int kasumi_keysize(int *keysize);
extern const struct ltc_cipher_descriptor kasumi_desc;
#endif
#ifdef LTC_MULTI2
int multi2_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int multi2_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int multi2_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int multi2_test(void);
void multi2_done(symmetric_key *skey);
int multi2_keysize(int *keysize);
extern const struct ltc_cipher_descriptor multi2_desc;
#endif
#ifdef LTC_ECB_MODE
int ecb_start(int cipher, const unsigned char *key,
int keylen, int num_rounds, symmetric_ECB *ecb);
int ecb_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_ECB *ecb);
int ecb_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_ECB *ecb);
int ecb_done(symmetric_ECB *ecb);
#endif
#ifdef LTC_CFB_MODE
int cfb_start(int cipher, const unsigned char *IV, const unsigned char *key,
int keylen, int num_rounds, symmetric_CFB *cfb);
int cfb_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CFB *cfb);
int cfb_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CFB *cfb);
int cfb_getiv(unsigned char *IV, unsigned long *len, symmetric_CFB *cfb);
int cfb_setiv(const unsigned char *IV, unsigned long len, symmetric_CFB *cfb);
int cfb_done(symmetric_CFB *cfb);
#endif
#ifdef LTC_OFB_MODE
int ofb_start(int cipher, const unsigned char *IV, const unsigned char *key,
int keylen, int num_rounds, symmetric_OFB *ofb);
int ofb_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_OFB *ofb);
int ofb_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_OFB *ofb);
int ofb_getiv(unsigned char *IV, unsigned long *len, symmetric_OFB *ofb);
int ofb_setiv(const unsigned char *IV, unsigned long len, symmetric_OFB *ofb);
int ofb_done(symmetric_OFB *ofb);
#endif
#ifdef LTC_CBC_MODE
int cbc_start(int cipher, const unsigned char *IV, const unsigned char *key,
int keylen, int num_rounds, symmetric_CBC *cbc);
int cbc_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CBC *cbc);
int cbc_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CBC *cbc);
int cbc_getiv(unsigned char *IV, unsigned long *len, symmetric_CBC *cbc);
int cbc_setiv(const unsigned char *IV, unsigned long len, symmetric_CBC *cbc);
int cbc_done(symmetric_CBC *cbc);
#endif
#ifdef LTC_CTR_MODE
#define CTR_COUNTER_LITTLE_ENDIAN 0x0000
#define CTR_COUNTER_BIG_ENDIAN 0x1000
#define LTC_CTR_RFC3686 0x2000
int ctr_start( int cipher,
const unsigned char *IV,
const unsigned char *key, int keylen,
int num_rounds, int ctr_mode,
symmetric_CTR *ctr);
int ctr_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CTR *ctr);
int ctr_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CTR *ctr);
int ctr_getiv(unsigned char *IV, unsigned long *len, symmetric_CTR *ctr);
int ctr_setiv(const unsigned char *IV, unsigned long len, symmetric_CTR *ctr);
int ctr_done(symmetric_CTR *ctr);
int ctr_test(void);
#endif
#ifdef LTC_LRW_MODE
#define LRW_ENCRYPT 0
#define LRW_DECRYPT 1
int lrw_start( int cipher,
const unsigned char *IV,
const unsigned char *key, int keylen,
const unsigned char *tweak,
int num_rounds,
symmetric_LRW *lrw);
int lrw_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_LRW *lrw);
int lrw_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_LRW *lrw);
int lrw_getiv(unsigned char *IV, unsigned long *len, symmetric_LRW *lrw);
int lrw_setiv(const unsigned char *IV, unsigned long len, symmetric_LRW *lrw);
int lrw_done(symmetric_LRW *lrw);
int lrw_test(void);
/* don't call */
int lrw_process(const unsigned char *pt, unsigned char *ct, unsigned long len, int mode, symmetric_LRW *lrw);
#endif
#ifdef LTC_F8_MODE
int f8_start( int cipher, const unsigned char *IV,
const unsigned char *key, int keylen,
const unsigned char *salt_key, int skeylen,
int num_rounds, symmetric_F8 *f8);
int f8_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_F8 *f8);
int f8_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_F8 *f8);
int f8_getiv(unsigned char *IV, unsigned long *len, symmetric_F8 *f8);
int f8_setiv(const unsigned char *IV, unsigned long len, symmetric_F8 *f8);
int f8_done(symmetric_F8 *f8);
int f8_test_mode(void);
#endif
#ifdef LTC_XTS_MODE
typedef struct {
symmetric_key key1, key2;
int cipher;
} symmetric_xts;
int xts_start( int cipher,
const unsigned char *key1,
const unsigned char *key2,
unsigned long keylen,
int num_rounds,
symmetric_xts *xts);
int xts_encrypt(
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
const unsigned char *tweak,
symmetric_xts *xts);
int xts_decrypt(
const unsigned char *ct, unsigned long ptlen,
unsigned char *pt,
const unsigned char *tweak,
symmetric_xts *xts);
void xts_done(symmetric_xts *xts);
int xts_test(void);
void xts_mult_x(unsigned char *I);
#endif
int find_cipher(const char *name);
int find_cipher_any(const char *name, int blocklen, int keylen);
int find_cipher_id(unsigned char ID);
int register_cipher(const struct ltc_cipher_descriptor *cipher);
int unregister_cipher(const struct ltc_cipher_descriptor *cipher);
int cipher_is_valid(int idx);
LTC_MUTEX_PROTO(ltc_cipher_mutex)
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_cipher.h,v $ */
/* $Revision: 1.54 $ */
/* $Date: 2007/05/12 14:37:41 $ */

407
crypto777/hmac/tomcrypt_custom.h

@ -0,0 +1,407 @@
#ifndef TOMCRYPT_CUSTOM_H_
#define TOMCRYPT_CUSTOM_H_
/* macros for various libc functions you can change for embedded targets */
#ifndef XMALLOC
#ifdef malloc
#define LTC_NO_PROTOTYPES
#endif
#define XMALLOC malloc
#endif
#ifndef XREALLOC
#ifdef realloc
#define LTC_NO_PROTOTYPES
#endif
#define XREALLOC realloc
#endif
#ifndef XCALLOC
#ifdef calloc
#define LTC_NO_PROTOTYPES
#endif
#define XCALLOC calloc
#endif
#ifndef XFREE
#ifdef free
#define LTC_NO_PROTOTYPES
#endif
#define XFREE free
#endif
#ifndef XMEMSET
#ifdef memset
#define LTC_NO_PROTOTYPES
#endif
#define XMEMSET memset
#endif
#ifndef XMEMCPY
#ifdef memcpy
#define LTC_NO_PROTOTYPES
#endif
#define XMEMCPY memcpy
#endif
#ifndef XMEMCMP
#ifdef memcmp
#define LTC_NO_PROTOTYPES
#endif
#define XMEMCMP memcmp
#endif
#ifndef XSTRCMP
#ifdef strcmp
#define LTC_NO_PROTOTYPES
#endif
#define XSTRCMP strcmp
#endif
#ifndef XCLOCK
#define XCLOCK clock
#endif
#ifndef XCLOCKS_PER_SEC
#define XCLOCKS_PER_SEC CLOCKS_PER_SEC
#endif
#ifndef XQSORT
#ifdef qsort
#define LTC_NO_PROTOTYPES
#endif
#define XQSORT qsort
#endif
/* Easy button? */
#ifdef LTC_EASY
#define LTC_NO_CIPHERS
#define LTC_RIJNDAEL
#define LTC_BLOWFISH
#define LTC_DES
#define LTC_CAST5
#define LTC_NO_MODES
#define LTC_ECB_MODE
#define LTC_CBC_MODE
#define LTC_CTR_MODE
#define LTC_NO_HASHES
#define LTC_SHA1
#define LTC_SHA512
#define LTC_SHA384
#define LTC_SHA256
#define LTC_SHA224
#define LTC_NO_MACS
#define LTC_HMAC
#define LTC_OMAC
#define LTC_CCM_MODE
#define LTC_NO_PRNGS
#define LTC_SPRNG
#define LTC_YARROW
#define LTC_DEVRANDOM
#define TRY_URANDOM_FIRST
#define LTC_NO_PK
#define LTC_MRSA
#define LTC_MECC
#endif
/* Use small code where possible */
/* #define LTC_SMALL_CODE */
/* Enable self-test test vector checking */
#ifndef LTC_NO_TEST
#define LTC_TEST
#endif
/* clean the stack of functions which put private information on stack */
/* #define LTC_CLEAN_STACK */
/* disable all file related functions */
/* #define LTC_NO_FILE */
/* disable all forms of ASM */
/* #define LTC_NO_ASM */
/* disable FAST mode */
/* #define LTC_NO_FAST */
/* disable BSWAP on x86 */
/* #define LTC_NO_BSWAP */
/* ---> Symmetric Block Ciphers <--- */
#ifndef LTC_NO_CIPHERS
#define LTC_BLOWFISH
#define LTC_RC2
#define LTC_RC5
#define LTC_RC6
#define LTC_SAFERP
#define LTC_RIJNDAEL
#define LTC_XTEA
/* _TABLES tells it to use tables during setup, _SMALL means to use the smaller scheduled key format
* (saves 4KB of ram), _ALL_TABLES enables all tables during setup */
#define LTC_TWOFISH
#ifndef LTC_NO_TABLES
#define LTC_TWOFISH_TABLES
/* #define LTC_TWOFISH_ALL_TABLES */
#else
#define LTC_TWOFISH_SMALL
#endif
/* #define LTC_TWOFISH_SMALL */
/* LTC_DES includes EDE triple-LTC_DES */
#define LTC_DES
#define LTC_CAST5
#define LTC_NOEKEON
#define LTC_SKIPJACK
#define LTC_SAFER
#define LTC_KHAZAD
#define LTC_ANUBIS
#define LTC_ANUBIS_TWEAK
#define LTC_KSEED
#define LTC_KASUMI
#endif /* LTC_NO_CIPHERS */
/* ---> Block Cipher Modes of Operation <--- */
#ifndef LTC_NO_MODES
#define LTC_CFB_MODE
#define LTC_OFB_MODE
#define LTC_ECB_MODE
#define LTC_CBC_MODE
#define LTC_CTR_MODE
/* F8 chaining mode */
#define LTC_F8_MODE
/* LRW mode */
#define LTC_LRW_MODE
#ifndef LTC_NO_TABLES
/* like GCM mode this will enable 16 8x128 tables [64KB] that make
* seeking very fast.
*/
#define LRW_TABLES
#endif
/* XTS mode */
#define LTC_XTS_MODE
#endif /* LTC_NO_MODES */
/* ---> One-Way Hash Functions <--- */
#ifndef LTC_NO_HASHES
#define LTC_CHC_HASH
#define LTC_WHIRLPOOL
#define LTC_SHA512
#define LTC_SHA384
#define LTC_SHA256
#define LTC_SHA224
#define LTC_TIGER
#define LTC_SHA1
#define LTC_MD5
#define LTC_MD4
#define LTC_MD2
#define LTC_RIPEMD128
#define LTC_RIPEMD160
#define LTC_RIPEMD256
#define LTC_RIPEMD320
#endif /* LTC_NO_HASHES */
/* ---> MAC functions <--- */
#ifndef LTC_NO_MACS
#define LTC_HMAC
#define LTC_OMAC
#define LTC_PMAC
#define LTC_XCBC
#define LTC_F9_MODE
#define LTC_PELICAN
#if defined(LTC_PELICAN) && !defined(LTC_RIJNDAEL)
#error Pelican-MAC requires LTC_RIJNDAEL
#endif
/* ---> Encrypt + Authenticate Modes <--- */
#define LTC_EAX_MODE
#if defined(LTC_EAX_MODE) && !(defined(LTC_CTR_MODE) && defined(LTC_OMAC))
#error LTC_EAX_MODE requires CTR and LTC_OMAC mode
#endif
#define LTC_OCB_MODE
#define LTC_CCM_MODE
#define LTC_GCM_MODE
/* Use 64KiB tables */
#ifndef LTC_NO_TABLES
#define LTC_GCM_TABLES
#endif
/* USE SSE2? requires GCC works on x86_32 and x86_64*/
#ifdef LTC_GCM_TABLES
/* #define LTC_GCM_TABLES_SSE2 */
#endif
#endif /* LTC_NO_MACS */
/* Various tidbits of modern neatoness */
#define LTC_BASE64
/* --> Pseudo Random Number Generators <--- */
#ifndef LTC_NO_PRNGS
/* Yarrow */
#define LTC_YARROW
/* which descriptor of AES to use? */
/* 0 = rijndael_enc 1 = aes_enc, 2 = rijndael [full], 3 = aes [full] */
#define LTC_YARROW_AES 0
#if defined(LTC_YARROW) && !defined(LTC_CTR_MODE)
#error LTC_YARROW requires LTC_CTR_MODE chaining mode to be defined!
#endif
/* a PRNG that simply reads from an available system source */
#define LTC_SPRNG
/* The LTC_RC4 stream cipher */
#define LTC_RC4
/* Fortuna PRNG */
#define LTC_FORTUNA
/* reseed every N calls to the read function */
#define LTC_FORTUNA_WD 10
/* number of pools (4..32) can save a bit of ram by lowering the count */
#define LTC_FORTUNA_POOLS 32
/* Greg's LTC_SOBER128 PRNG ;-0 */
#define LTC_SOBER128
/* the *nix style /dev/random device */
#define LTC_DEVRANDOM
/* try /dev/urandom before trying /dev/random */
#define TRY_URANDOM_FIRST
#endif /* LTC_NO_PRNGS */
/* ---> math provider? <--- */
#ifndef LTC_NO_MATH
/* LibTomMath */
/* #define LTM_LTC_DESC */
/* TomsFastMath */
/* #define TFM_LTC_DESC */
#endif /* LTC_NO_MATH */
/* ---> Public Key Crypto <--- */
#ifndef LTC_NO_PK
/* Include RSA support */
#define LTC_MRSA
/* Include Katja (a Rabin variant like RSA) */
/* #define MKAT */
/* Digital Signature Algorithm */
#define LTC_MDSA
/* ECC */
#define LTC_MECC
/* use Shamir's trick for point mul (speeds up signature verification) */
#define LTC_ECC_SHAMIR
#if defined(TFM_LTC_DESC) && defined(LTC_MECC)
#define LTC_MECC_ACCEL
#endif
/* do we want fixed point ECC */
/* #define LTC_MECC_FP */
/* Timing Resistant? */
/* #define LTC_ECC_TIMING_RESISTANT */
#endif /* LTC_NO_PK */
/* LTC_PKCS #1 (RSA) and #5 (Password Handling) stuff */
#ifndef LTC_NO_PKCS
#define LTC_PKCS_1
#define LTC_PKCS_5
/* Include ASN.1 DER (required by DSA/RSA) */
#define LTC_DER
#endif /* LTC_NO_PKCS */
/* cleanup */
#ifdef LTC_MECC
/* Supported ECC Key Sizes */
#ifndef LTC_NO_CURVES
#define ECC112
#define ECC128
#define ECC160
#define ECC192
#define ECC224
#define ECC256
#define ECC384
#define ECC521
#endif
#endif
#if defined(LTC_MECC) || defined(LTC_MRSA) || defined(LTC_MDSA) || defined(MKATJA)
/* Include the MPI functionality? (required by the PK algorithms) */
#define MPI
#endif
#ifdef LTC_MRSA
#define LTC_PKCS_1
#endif
#if defined(LTC_DER) && !defined(MPI)
#error ASN.1 DER requires MPI functionality
#endif
#if (defined(LTC_MDSA) || defined(LTC_MRSA) || defined(LTC_MECC) || defined(MKATJA)) && !defined(LTC_DER)
#error PK requires ASN.1 DER functionality, make sure LTC_DER is enabled
#endif
/* THREAD management */
#ifdef LTC_PTHREAD
//#include <pthread.h>
#define LTC_MUTEX_GLOBAL(x) pthread_mutex_t x = PTHREAD_MUTEX_INITIALIZER;
#define LTC_MUTEX_PROTO(x) extern pthread_mutex_t x;
#define LTC_MUTEX_TYPE(x) pthread_mutex_t x;
#define LTC_MUTEX_INIT(x) pthread_mutex_init(x, NULL);
#define LTC_MUTEX_LOCK(x) pthread_mutex_lock(x);
#define LTC_MUTEX_UNLOCK(x) pthread_mutex_unlock(x);
#else
/* default no functions */
#define LTC_MUTEX_GLOBAL(x)
#define LTC_MUTEX_PROTO(x)
#define LTC_MUTEX_TYPE(x)
#define LTC_MUTEX_INIT(x)
#define LTC_MUTEX_LOCK(x)
#define LTC_MUTEX_UNLOCK(x)
#endif
/* Debuggers */
/* define this if you use Valgrind, note: it CHANGES the way SOBER-128 and LTC_RC4 work (see the code) */
/* #define LTC_VALGRIND */
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_custom.h,v $ */
/* $Revision: 1.73 $ */
/* $Date: 2007/05/12 14:37:41 $ */

379
crypto777/hmac/tomcrypt_hash.h

@ -0,0 +1,379 @@
/* ---- HASH FUNCTIONS ---- */
#ifdef LTC_SHA512
struct sha512_state {
ulong64 length, state[8];
unsigned long curlen;
unsigned char buf[128];
};
#endif
#ifdef LTC_SHA256
#endif
#ifdef LTC_SHA1
struct sha1_state {
ulong64 length;
ulong32 state[5], curlen;
unsigned char buf[64];
};
#endif
#ifdef LTC_MD5
struct md5_state {
ulong64 length;
ulong32 state[4], curlen;
unsigned char buf[64];
};
#endif
#ifdef LTC_MD4
struct md4_state {
ulong64 length;
ulong32 state[4], curlen;
unsigned char buf[64];
};
#endif
#ifdef LTC_TIGER
struct tiger_state {
ulong64 state[3], length;
unsigned long curlen;
unsigned char buf[64];
};
#endif
#ifdef LTC_MD2
struct md2_state {
unsigned char chksum[16], X[48], buf[16];
unsigned long curlen;
};
#endif
#ifdef LTC_RIPEMD128
struct rmd128_state {
ulong64 length;
unsigned char buf[64];
ulong32 curlen, state[4];
};
#endif
#ifdef LTC_RIPEMD160
struct rmd160_state {
ulong64 length;
unsigned char buf[64];
ulong32 curlen, state[5];
};
#endif
#ifdef LTC_RIPEMD256
struct rmd256_state {
ulong64 length;
unsigned char buf[64];
ulong32 curlen, state[8];
};
#endif
#ifdef LTC_RIPEMD320
struct rmd320_state {
ulong64 length;
unsigned char buf[64];
ulong32 curlen, state[10];
};
#endif
#ifdef LTC_WHIRLPOOL
struct whirlpool_state {
ulong64 length, state[8];
unsigned char buf[64];
ulong32 curlen;
};
#endif
#ifdef LTC_CHC_HASH
struct chc_state {
ulong64 length;
unsigned char state[MAXBLOCKSIZE], buf[MAXBLOCKSIZE];
ulong32 curlen;
};
#endif
typedef union Hash_state {
char dummy[1];
#ifdef LTC_CHC_HASH
struct chc_state chc;
#endif
#ifdef LTC_WHIRLPOOL
struct whirlpool_state whirlpool;
#endif
#ifdef LTC_SHA512
struct sha512_state sha512;
#endif
#ifdef LTC_SHA256
//#include "../sha256.h"
struct sha256_state { uint64_t length; uint32_t state[8],curlen; uint8_t buf[64]; } sha256;
//struct sha256_state sha256;
#endif
#ifdef LTC_SHA1
struct sha1_state sha1;
#endif
#ifdef LTC_MD5
struct md5_state md5;
#endif
#ifdef LTC_MD4
struct md4_state md4;
#endif
#ifdef LTC_MD2
struct md2_state md2;
#endif
#ifdef LTC_TIGER
struct tiger_state tiger;
#endif
#ifdef LTC_RIPEMD128
struct rmd128_state rmd128;
#endif
#ifdef LTC_RIPEMD160
struct rmd160_state rmd160;
#endif
#ifdef LTC_RIPEMD256
struct rmd256_state rmd256;
#endif
#ifdef LTC_RIPEMD320
struct rmd320_state rmd320;
#endif
void *data;
} hash_state;
/** hash descriptor */
extern struct ltc_hash_descriptor {
/** name of hash */
char *name;
/** internal ID */
unsigned char ID;
/** Size of digest in octets */
unsigned long hashsize;
/** Input block size in octets */
unsigned long blocksize;
/** ASN.1 OID */
unsigned long OID[16];
/** Length of DER encoding */
unsigned long OIDlen;
/** Init a hash state
@param hash The hash to initialize
@return CRYPT_OK if successful
*/
int (*init)(hash_state *hash);
/** Process a block of data
@param hash The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
int (*process)(hash_state *hash, const unsigned char *in, unsigned long inlen);
/** Produce the digest and store it
@param hash The hash state
@param out [out] The destination of the digest
@return CRYPT_OK if successful
*/
int (*done)(hash_state *hash, unsigned char *out);
/** Self-test
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int (*test)(void);
/* accelerated hmac callback: if you need to-do multiple packets just use the generic hmac_memory and provide a hash callback */
int (*hmac_block)(const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
} hash_descriptor[];
#ifdef LTC_CHC_HASH
int chc_register(int cipher);
int chc_init(hash_state * md);
int chc_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int chc_done(hash_state * md, unsigned char *hash);
int chc_test(void);
extern const struct ltc_hash_descriptor chc_desc;
#endif
#ifdef LTC_WHIRLPOOL
int whirlpool_init(hash_state * md);
int whirlpool_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int whirlpool_done(hash_state * md, unsigned char *hash);
int whirlpool_test(void);
extern const struct ltc_hash_descriptor whirlpool_desc;
#endif
#ifdef LTC_SHA512
int sha512_init(hash_state * md);
int sha512_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha512_done(hash_state * md, unsigned char *hash);
int sha512_test(void);
extern const struct ltc_hash_descriptor sha512_desc;
#endif
#ifdef LTC_SHA384
#ifndef LTC_SHA512
#error LTC_SHA512 is required for LTC_SHA384
#endif
int sha384_init(hash_state * md);
#define sha384_process sha512_process
int sha384_done(hash_state * md, unsigned char *hash);
int sha384_test(void);
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 sha256_test(void);
extern const struct ltc_hash_descriptor sha256_desc;
#ifdef LTC_SHA224
#ifndef LTC_SHA256
#error LTC_SHA256 is required for LTC_SHA224
#endif
int sha224_init(hash_state * md);
#define sha224_process sha256_process
int sha224_done(hash_state * md, unsigned char *hash);
int sha224_test(void);
extern const struct ltc_hash_descriptor sha224_desc;
#endif
#endif
#ifdef LTC_SHA1
int sha1_init(hash_state * md);
int sha1_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha1_done(hash_state * md, unsigned char *hash);
int sha1_test(void);
extern const struct ltc_hash_descriptor sha1_desc;
#endif
#ifdef LTC_MD5
int md5_init(hash_state * md);
int md5_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int md5_done(hash_state * md, unsigned char *hash);
int md5_test(void);
extern const struct ltc_hash_descriptor md5_desc;
#endif
#ifdef LTC_MD4
int md4_init(hash_state * md);
int md4_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int md4_done(hash_state * md, unsigned char *hash);
int md4_test(void);
extern const struct ltc_hash_descriptor md4_desc;
#endif
#ifdef LTC_MD2
int md2_init(hash_state * md);
int md2_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int md2_done(hash_state * md, unsigned char *hash);
int md2_test(void);
extern const struct ltc_hash_descriptor md2_desc;
#endif
#ifdef LTC_TIGER
int tiger_init(hash_state * md);
int tiger_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int tiger_done(hash_state * md, unsigned char *hash);
int tiger_test(void);
extern const struct ltc_hash_descriptor tiger_desc;
#endif
#ifdef LTC_RIPEMD128
int rmd128_init(hash_state * md);
int rmd128_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd128_done(hash_state * md, unsigned char *hash);
int rmd128_test(void);
extern const struct ltc_hash_descriptor rmd128_desc;
#endif
#ifdef LTC_RIPEMD160
int rmd160_init(hash_state * md);
int rmd160_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd160_done(hash_state * md, unsigned char *hash);
int rmd160_test(void);
extern const struct ltc_hash_descriptor rmd160_desc;
#endif
#ifdef LTC_RIPEMD256
int rmd256_init(hash_state * md);
int rmd256_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd256_done(hash_state * md, unsigned char *hash);
int rmd256_test(void);
extern const struct ltc_hash_descriptor rmd256_desc;
#endif
#ifdef LTC_RIPEMD320
int rmd320_init(hash_state * md);
int rmd320_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd320_done(hash_state * md, unsigned char *hash);
int rmd320_test(void);
extern const struct ltc_hash_descriptor rmd320_desc;
#endif
int find_hash(const char *name);
int find_hash_id(unsigned char ID);
int find_hash_oid(const unsigned long *ID, unsigned long IDlen);
int find_hash_any(const char *name, int digestlen);
int register_hash(const struct ltc_hash_descriptor *hash);
int unregister_hash(const struct ltc_hash_descriptor *hash);
int hash_is_valid(int idx);
LTC_MUTEX_PROTO(ltc_hash_mutex)
int hash_memory(const struct ltc_hash_descriptor *hash,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int hash_memory_multi(struct ltc_hash_descriptor *hash, unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int hash_filehandle(struct ltc_hash_descriptor *hash, FILE *in, unsigned char *out, unsigned long *outlen);
int hash_file(struct ltc_hash_descriptor *hash, const char *fname, unsigned char *out, unsigned long *outlen);
/* a simple macro for making hash "process" functions */
#define HASH_PROCESS(func_name, compress_name, state_var, block_size) \
int func_name (hash_state * md, const unsigned char *in, unsigned long inlen) \
{ \
unsigned long n; \
int err; \
LTC_ARGCHK(md != NULL); \
LTC_ARGCHK(in != NULL); \
if (md-> state_var .curlen > sizeof(md-> state_var .buf)) { \
return CRYPT_INVALID_ARG; \
} \
while (inlen > 0) { \
if (md-> state_var .curlen == 0 && inlen >= block_size) { \
if ((err = compress_name (md, (unsigned char *)in)) != CRYPT_OK) { \
return err; \
} \
md-> state_var .length += block_size * 8; \
in += block_size; \
inlen -= block_size; \
} else { \
n = MIN(inlen, (block_size - md-> state_var .curlen)); \
memcpy(md-> state_var .buf + md-> state_var.curlen, in, (size_t)n); \
md-> state_var .curlen += n; \
in += n; \
inlen -= n; \
if (md-> state_var .curlen == block_size) { \
if ((err = compress_name (md, md-> state_var .buf)) != CRYPT_OK) { \
return err; \
} \
md-> state_var .length += 8*block_size; \
md-> state_var .curlen = 0; \
} \
} \
} \
return CRYPT_OK; \
}
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_hash.h,v $ */
/* $Revision: 1.22 $ */
/* $Date: 2007/05/12 14:32:35 $ */

382
crypto777/hmac/tomcrypt_mac.h

@ -0,0 +1,382 @@
#ifdef LTC_HMAC
typedef struct Hmac_state {
hash_state md;
struct ltc_hash_descriptor *hash;
hash_state hashstate;
unsigned char *key;
} hmac_state;
int hmac_init(hmac_state *hmac, const struct ltc_hash_descriptor *hash, const unsigned char *key, unsigned long keylen);
int hmac_process(hmac_state *hmac, const struct ltc_hash_descriptor *hash,const unsigned char *in, unsigned long inlen);
int hmac_done(hmac_state *hmac,const struct ltc_hash_descriptor *hash, unsigned char *out, unsigned long *outlen);
int hmac_test(void);
int hmac_memory(const struct ltc_hash_descriptor *hash,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int hmac_memory_multi(struct ltc_hash_descriptor *hash,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int hmac_file(const struct ltc_hash_descriptor *hash, const char *fname, const unsigned char *key, unsigned long keylen,unsigned char *out, unsigned long *outlen);
#endif
#ifdef LTC_OMAC
typedef struct {
int cipher_idx,
buflen,
blklen;
unsigned char block[MAXBLOCKSIZE],
prev[MAXBLOCKSIZE],
Lu[2][MAXBLOCKSIZE];
symmetric_key key;
} omac_state;
int omac_init(omac_state *omac, int cipher, const unsigned char *key, unsigned long keylen);
int omac_process(omac_state *omac, const unsigned char *in, unsigned long inlen);
int omac_done(omac_state *omac, unsigned char *out, unsigned long *outlen);
int omac_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int omac_memory_multi(int cipher,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int omac_file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
int omac_test(void);
#endif /* LTC_OMAC */
#ifdef LTC_PMAC
typedef struct {
unsigned char Ls[32][MAXBLOCKSIZE], /* L shifted by i bits to the left */
Li[MAXBLOCKSIZE], /* value of Li [current value, we calc from previous recall] */
Lr[MAXBLOCKSIZE], /* L * x^-1 */
block[MAXBLOCKSIZE], /* currently accumulated block */
checksum[MAXBLOCKSIZE]; /* current checksum */
symmetric_key key; /* scheduled key for cipher */
unsigned long block_index; /* index # for current block */
int cipher_idx, /* cipher idx */
block_len, /* length of block */
buflen; /* number of bytes in the buffer */
} pmac_state;
int pmac_init(pmac_state *pmac, int cipher, const unsigned char *key, unsigned long keylen);
int pmac_process(pmac_state *pmac, const unsigned char *in, unsigned long inlen);
int pmac_done(pmac_state *pmac, unsigned char *out, unsigned long *outlen);
int pmac_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *msg, unsigned long msglen,
unsigned char *out, unsigned long *outlen);
int pmac_memory_multi(int cipher,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int pmac_file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
int pmac_test(void);
/* internal functions */
int pmac_ntz(unsigned long x);
void pmac_shift_xor(pmac_state *pmac);
#endif /* PMAC */
#ifdef LTC_EAX_MODE
#if !(defined(LTC_OMAC) && defined(LTC_CTR_MODE))
#error LTC_EAX_MODE requires LTC_OMAC and CTR
#endif
typedef struct {
unsigned char N[MAXBLOCKSIZE];
symmetric_CTR ctr;
omac_state headeromac, ctomac;
} eax_state;
int eax_init(eax_state *eax, int cipher, const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen);
int eax_encrypt(eax_state *eax, const unsigned char *pt, unsigned char *ct, unsigned long length);
int eax_decrypt(eax_state *eax, const unsigned char *ct, unsigned char *pt, unsigned long length);
int eax_addheader(eax_state *eax, const unsigned char *header, unsigned long length);
int eax_done(eax_state *eax, unsigned char *tag, unsigned long *taglen);
int eax_encrypt_authenticate_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
int eax_decrypt_verify_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
unsigned char *tag, unsigned long taglen,
int *stat);
int eax_test(void);
#endif /* EAX MODE */
#ifdef LTC_OCB_MODE
typedef struct {
unsigned char L[MAXBLOCKSIZE], /* L value */
Ls[32][MAXBLOCKSIZE], /* L shifted by i bits to the left */
Li[MAXBLOCKSIZE], /* value of Li [current value, we calc from previous recall] */
Lr[MAXBLOCKSIZE], /* L * x^-1 */
R[MAXBLOCKSIZE], /* R value */
checksum[MAXBLOCKSIZE]; /* current checksum */
symmetric_key key; /* scheduled key for cipher */
unsigned long block_index; /* index # for current block */
int cipher, /* cipher idx */
block_len; /* length of block */
} ocb_state;
int ocb_init(ocb_state *ocb, int cipher,
const unsigned char *key, unsigned long keylen, const unsigned char *nonce);
int ocb_encrypt(ocb_state *ocb, const unsigned char *pt, unsigned char *ct);
int ocb_decrypt(ocb_state *ocb, const unsigned char *ct, unsigned char *pt);
int ocb_done_encrypt(ocb_state *ocb,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
int ocb_done_decrypt(ocb_state *ocb,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
const unsigned char *tag, unsigned long taglen, int *stat);
int ocb_encrypt_authenticate_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce,
const unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen);
int ocb_decrypt_verify_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *nonce,
const unsigned char *ct, unsigned long ctlen,
unsigned char *pt,
const unsigned char *tag, unsigned long taglen,
int *stat);
int ocb_test(void);
/* internal functions */
void ocb_shift_xor(ocb_state *ocb, unsigned char *Z);
int ocb_ntz(unsigned long x);
int s_ocb_done(ocb_state *ocb, const unsigned char *pt, unsigned long ptlen,
unsigned char *ct, unsigned char *tag, unsigned long *taglen, int mode);
#endif /* LTC_OCB_MODE */
#ifdef LTC_CCM_MODE
#define CCM_ENCRYPT 0
#define CCM_DECRYPT 1
int ccm_memory(int cipher,
const unsigned char *key, unsigned long keylen,
symmetric_key *uskey,
const unsigned char *nonce, unsigned long noncelen,
const unsigned char *header, unsigned long headerlen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
int ccm_test(void);
#endif /* LTC_CCM_MODE */
#if defined(LRW_MODE) || defined(LTC_GCM_MODE)
void gcm_gf_mult(const unsigned char *a, const unsigned char *b, unsigned char *c);
#endif
/* table shared between GCM and LRW */
#if defined(LTC_GCM_TABLES) || defined(LRW_TABLES) || ((defined(LTC_GCM_MODE) || defined(LTC_GCM_MODE)) && defined(LTC_FAST))
extern const unsigned char gcm_shift_table[];
#endif
#ifdef LTC_GCM_MODE
#define GCM_ENCRYPT 0
#define GCM_DECRYPT 1
#define LTC_GCM_MODE_IV 0
#define LTC_GCM_MODE_AAD 1
#define LTC_GCM_MODE_TEXT 2
typedef struct {
symmetric_key K;
unsigned char H[16], /* multiplier */
X[16], /* accumulator */
Y[16], /* counter */
Y_0[16], /* initial counter */
buf[16]; /* buffer for stuff */
int cipher, /* which cipher */
ivmode, /* Which mode is the IV in? */
mode, /* mode the GCM code is in */
buflen; /* length of data in buf */
ulong64 totlen, /* 64-bit counter used for IV and AAD */
pttotlen; /* 64-bit counter for the PT */
#ifdef LTC_GCM_TABLES
unsigned char PC[16][256][16] /* 16 tables of 8x128 */
#ifdef LTC_GCM_TABLES_SSE2
__attribute__ ((aligned (16)))
#endif
;
#endif
} gcm_state;
void gcm_mult_h(gcm_state *gcm, unsigned char *I);
int gcm_init(gcm_state *gcm, int cipher,
const unsigned char *key, int keylen);
int gcm_reset(gcm_state *gcm);
int gcm_add_iv(gcm_state *gcm,
const unsigned char *IV, unsigned long IVlen);
int gcm_add_aad(gcm_state *gcm,
const unsigned char *adata, unsigned long adatalen);
int gcm_process(gcm_state *gcm,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
int direction);
int gcm_done(gcm_state *gcm,
unsigned char *tag, unsigned long *taglen);
int gcm_memory( int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *IV, unsigned long IVlen,
const unsigned char *adata, unsigned long adatalen,
unsigned char *pt, unsigned long ptlen,
unsigned char *ct,
unsigned char *tag, unsigned long *taglen,
int direction);
int gcm_test(void);
#endif /* LTC_GCM_MODE */
#ifdef LTC_PELICAN
typedef struct pelican_state
{
symmetric_key K;
unsigned char state[16];
int buflen;
} pelican_state;
int pelican_init(pelican_state *pelmac, const unsigned char *key, unsigned long keylen);
int pelican_process(pelican_state *pelmac, const unsigned char *in, unsigned long inlen);
int pelican_done(pelican_state *pelmac, unsigned char *out);
int pelican_test(void);
int pelican_memory(const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out);
#endif
#ifdef LTC_XCBC
/* add this to "keylen" to xcbc_init to use a pure three-key XCBC MAC */
#define LTC_XCBC_PURE 0x8000UL
typedef struct {
unsigned char K[3][MAXBLOCKSIZE],
IV[MAXBLOCKSIZE];
symmetric_key key;
int cipher,
buflen,
blocksize;
} xcbc_state;
int xcbc_init(xcbc_state *xcbc, int cipher, const unsigned char *key, unsigned long keylen);
int xcbc_process(xcbc_state *xcbc, const unsigned char *in, unsigned long inlen);
int xcbc_done(xcbc_state *xcbc, unsigned char *out, unsigned long *outlen);
int xcbc_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int xcbc_memory_multi(int cipher,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int xcbc_file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
int xcbc_test(void);
#endif
#ifdef LTC_F9_MODE
typedef struct {
unsigned char akey[MAXBLOCKSIZE],
ACC[MAXBLOCKSIZE],
IV[MAXBLOCKSIZE];
symmetric_key key;
int cipher,
buflen,
keylen,
blocksize;
} f9_state;
int f9_init(f9_state *f9, int cipher, const unsigned char *key, unsigned long keylen);
int f9_process(f9_state *f9, const unsigned char *in, unsigned long inlen);
int f9_done(f9_state *f9, unsigned char *out, unsigned long *outlen);
int f9_memory(int cipher,
const unsigned char *key, unsigned long keylen,
const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int f9_memory_multi(int cipher,
const unsigned char *key, unsigned long keylen,
unsigned char *out, unsigned long *outlen,
const unsigned char *in, unsigned long inlen, ...);
int f9_file(int cipher,
const unsigned char *key, unsigned long keylen,
const char *filename,
unsigned char *out, unsigned long *outlen);
int f9_test(void);
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_mac.h,v $ */
/* $Revision: 1.23 $ */
/* $Date: 2007/05/12 14:37:41 $ */

426
crypto777/hmac/tomcrypt_macros.h

@ -0,0 +1,426 @@
/* fix for MSVC ...evil! */
#ifdef _MSC_VER
#define CONST64(n) n ## ui64
typedef unsigned __int64 ulong64;
#else
#define CONST64(n) n ## ULL
#define ulong64 uint64_t
//typedef unsigned long long ulong64;
#endif
/* this is the "32-bit at least" data type
* Re-define it to suit your platform but it must be at least 32-bits
#if defined(__x86_64__) || (defined(__sparc__) && defined(__arch64__))
typedef unsigned ulong32;
#else
#define ulong32 uint32_t
//typedef unsigned long ulong32;
#endif*/
/* ---- HELPER MACROS ---- */
#ifdef ENDIAN_NEUTRAL
#define STORE32L(x, y) \
{ (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
#define LOAD32L(x, y) \
{ x = (ulong32)(((unsigned long)((y)[3] & 255)<<24) | \
((unsigned long)((y)[2] & 255)<<16) | \
((unsigned long)((y)[1] & 255)<<8) | \
((unsigned long)((y)[0] & 255))); }
#define STORE64L(x, y) \
{ (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255); \
(y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255); \
(y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
#define LOAD64L(x, y) \
{ x = (((ulong64)((y)[7] & 255))<<56)|(((ulong64)((y)[6] & 255))<<48)| \
(((ulong64)((y)[5] & 255))<<40)|(((ulong64)((y)[4] & 255))<<32)| \
(((ulong64)((y)[3] & 255))<<24)|(((ulong64)((y)[2] & 255))<<16)| \
(((ulong64)((y)[1] & 255))<<8)|(((ulong64)((y)[0] & 255))); }
#define STORE32H(x, y) \
{ (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255); \
(y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); }
#define LOAD32H(x, y) \
{ x = (ulong32)(((unsigned long)((y)[0] & 255)<<24) | \
((unsigned long)((y)[1] & 255)<<16) | \
((unsigned long)((y)[2] & 255)<<8) | \
((unsigned long)((y)[3] & 255))); }
#define STORE64H(x, y) \
{ (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255); \
(y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255); \
(y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255); \
(y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }
#define LOAD64H(x, y) \
{ x = (((ulong64)((y)[0] & 255))<<56)|(((ulong64)((y)[1] & 255))<<48) | \
(((ulong64)((y)[2] & 255))<<40)|(((ulong64)((y)[3] & 255))<<32) | \
(((ulong64)((y)[4] & 255))<<24)|(((ulong64)((y)[5] & 255))<<16) | \
(((ulong64)((y)[6] & 255))<<8)|(((ulong64)((y)[7] & 255))); }
#endif /* ENDIAN_NEUTRAL */
#ifdef ENDIAN_LITTLE
#if !defined(LTC_NO_BSWAP) && (defined(INTEL_CC) || (defined(__GNUC__) && (defined(__DJGPP__) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__i386__) || defined(__x86_64__))))
#define STORE32H(x, y) \
asm __volatile__ ( \
"bswapl %0 \n\t" \
"movl %0,(%1)\n\t" \
"bswapl %0 \n\t" \
::"r"(x), "r"(y));
#define LOAD32H(x, y) \
asm __volatile__ ( \
"movl (%1),%0\n\t" \
"bswapl %0\n\t" \
:"=r"(x): "r"(y));
#else
#define STORE32H(x, y) \
{ (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255); \
(y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); }
#define LOAD32H(x, y) \
{ x = ((unsigned long)((y)[0] & 255)<<24) | \
((unsigned long)((y)[1] & 255)<<16) | \
((unsigned long)((y)[2] & 255)<<8) | \
((unsigned long)((y)[3] & 255)); }
#endif
/* x86_64 processor */
#if !defined(LTC_NO_BSWAP) && (defined(__GNUC__) && defined(__x86_64__))
#define STORE64H(x, y) \
asm __volatile__ ( \
"bswapq %0 \n\t" \
"movq %0,(%1)\n\t" \
"bswapq %0 \n\t" \
::"r"(x), "r"(y));
#define LOAD64H(x, y) \
asm __volatile__ ( \
"movq (%1),%0\n\t" \
"bswapq %0\n\t" \
:"=r"(x): "r"(y));
#else
#define STORE64H(x, y) \
{ (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255); \
(y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255); \
(y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255); \
(y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }
#define LOAD64H(x, y) \
{ x = (((ulong64)((y)[0] & 255))<<56)|(((ulong64)((y)[1] & 255))<<48) | \
(((ulong64)((y)[2] & 255))<<40)|(((ulong64)((y)[3] & 255))<<32) | \
(((ulong64)((y)[4] & 255))<<24)|(((ulong64)((y)[5] & 255))<<16) | \
(((ulong64)((y)[6] & 255))<<8)|(((ulong64)((y)[7] & 255))); }
#endif
#ifdef ENDIAN_32BITWORD
#define STORE32L(x, y) \
{ ulong32 __t = (x); XMEMCPY(y, &__t, 4); }
#define LOAD32L(x, y) \
XMEMCPY(&(x), y, 4);
#define STORE64L(x, y) \
{ (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255); \
(y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255); \
(y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
#define LOAD64L(x, y) \
{ x = (((ulong64)((y)[7] & 255))<<56)|(((ulong64)((y)[6] & 255))<<48)| \
(((ulong64)((y)[5] & 255))<<40)|(((ulong64)((y)[4] & 255))<<32)| \
(((ulong64)((y)[3] & 255))<<24)|(((ulong64)((y)[2] & 255))<<16)| \
(((ulong64)((y)[1] & 255))<<8)|(((ulong64)((y)[0] & 255))); }
#else /* 64-bit words then */
#define STORE32L(x, y) \
{ ulong32 __t = (x); XMEMCPY(y, &__t, 4); }
#define LOAD32L(x, y) \
{ XMEMCPY(&(x), y, 4); x &= 0xFFFFFFFF; }
#define STORE64L(x, y) \
{ ulong64 __t = (x); XMEMCPY(y, &__t, 8); }
#define LOAD64L(x, y) \
{ XMEMCPY(&(x), y, 8); }
#endif /* ENDIAN_64BITWORD */
#endif /* ENDIAN_LITTLE */
#ifdef ENDIAN_BIG
#define STORE32L(x, y) \
{ (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
#define LOAD32L(x, y) \
{ x = ((unsigned long)((y)[3] & 255)<<24) | \
((unsigned long)((y)[2] & 255)<<16) | \
((unsigned long)((y)[1] & 255)<<8) | \
((unsigned long)((y)[0] & 255)); }
#define STORE64L(x, y) \
{ (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255); \
(y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255); \
(y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
(y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
#define LOAD64L(x, y) \
{ x = (((ulong64)((y)[7] & 255))<<56)|(((ulong64)((y)[6] & 255))<<48) | \
(((ulong64)((y)[5] & 255))<<40)|(((ulong64)((y)[4] & 255))<<32) | \
(((ulong64)((y)[3] & 255))<<24)|(((ulong64)((y)[2] & 255))<<16) | \
(((ulong64)((y)[1] & 255))<<8)|(((ulong64)((y)[0] & 255))); }
#ifdef ENDIAN_32BITWORD
#define STORE32H(x, y) \
{ ulong32 __t = (x); XMEMCPY(y, &__t, 4); }
#define LOAD32H(x, y) \
XMEMCPY(&(x), y, 4);
#define STORE64H(x, y) \
{ (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255); \
(y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255); \
(y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255); \
(y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }
#define LOAD64H(x, y) \
{ x = (((ulong64)((y)[0] & 255))<<56)|(((ulong64)((y)[1] & 255))<<48)| \
(((ulong64)((y)[2] & 255))<<40)|(((ulong64)((y)[3] & 255))<<32)| \
(((ulong64)((y)[4] & 255))<<24)|(((ulong64)((y)[5] & 255))<<16)| \
(((ulong64)((y)[6] & 255))<<8)| (((ulong64)((y)[7] & 255))); }
#else /* 64-bit words then */
#define STORE32H(x, y) \
{ ulong32 __t = (x); XMEMCPY(y, &__t, 4); }
#define LOAD32H(x, y) \
{ XMEMCPY(&(x), y, 4); x &= 0xFFFFFFFF; }
#define STORE64H(x, y) \
{ ulong64 __t = (x); XMEMCPY(y, &__t, 8); }
#define LOAD64H(x, y) \
{ XMEMCPY(&(x), y, 8); }
#endif /* ENDIAN_64BITWORD */
#endif /* ENDIAN_BIG */
#define BSWAP(x) ( ((x>>24)&0x000000FFUL) | ((x<<24)&0xFF000000UL) | \
((x>>8)&0x0000FF00UL) | ((x<<8)&0x00FF0000UL) )
/* 32-bit Rotates */
#if defined(_MSC_VER)
/* instrinsic rotate */
#include <stdlib.h>
#pragma intrinsic(_lrotr,_lrotl)
#define ROR(x,n) _lrotr(x,n)
#define ROL(x,n) _lrotl(x,n)
#define RORc(x,n) _lrotr(x,n)
#define ROLc(x,n) _lrotl(x,n)
#elif !defined(__STRICT_ANSI__) && defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) && !defined(INTEL_CC) && !defined(LTC_NO_ASM)
static inline unsigned ROL(unsigned word, int i)
{
asm ("roll %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
static inline unsigned ROR(unsigned word, int i)
{
asm ("rorl %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
#ifndef LTC_NO_ROLC
static inline unsigned ROLc(unsigned word, const int i)
{
asm ("roll %2,%0"
:"=r" (word)
:"0" (word),"I" (i));
return word;
}
static inline unsigned RORc(unsigned word, const int i)
{
asm ("rorl %2,%0"
:"=r" (word)
:"0" (word),"I" (i));
return word;
}
#else
#define ROLc ROL
#define RORc ROR
#endif
#elif !defined(__STRICT_ANSI__) && defined(LTC_PPC32)
static inline unsigned ROL(unsigned word, int i)
{
asm ("rotlw %0,%0,%2"
:"=r" (word)
:"0" (word),"r" (i));
return word;
}
static inline unsigned ROR(unsigned word, int i)
{
asm ("rotlw %0,%0,%2"
:"=r" (word)
:"0" (word),"r" (32-i));
return word;
}
#ifndef LTC_NO_ROLC
static inline unsigned ROLc(unsigned word, const int i)
{
asm ("rotlwi %0,%0,%2"
:"=r" (word)
:"0" (word),"I" (i));
return word;
}
static inline unsigned RORc(unsigned word, const int i)
{
asm ("rotrwi %0,%0,%2"
:"=r" (word)
:"0" (word),"I" (i));
return word;
}
#else
#define ROLc ROL
#define RORc ROR
#endif
#else
/* rotates the hard way */
#define ROL(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#define ROR(x, y) ( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | ((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#define ROLc(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#define RORc(x, y) ( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | ((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#endif
/* 64-bit Rotates */
#if !defined(__STRICT_ANSI__) && defined(__GNUC__) && defined(__x86_64__) && !defined(LTC_NO_ASM)
static inline unsigned long ROL64(unsigned long word, int i)
{
asm("rolq %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
static inline unsigned long ROR64(unsigned long word, int i)
{
asm("rorq %%cl,%0"
:"=r" (word)
:"0" (word),"c" (i));
return word;
}
#ifndef LTC_NO_ROLC
static inline unsigned long ROL64c(unsigned long word, const int i)
{
asm("rolq %2,%0"
:"=r" (word)
:"0" (word),"J" (i));
return word;
}
static inline unsigned long ROR64c(unsigned long word, const int i)
{
asm("rorq %2,%0"
:"=r" (word)
:"0" (word),"J" (i));
return word;
}
#else /* LTC_NO_ROLC */
#define ROL64c ROL64
#define ROR64c ROR64
#endif
#else /* Not x86_64 */
#define ROL64(x, y) \
( (((x)<<((ulong64)(y)&63)) | \
(((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)64-((y)&63)))) & CONST64(0xFFFFFFFFFFFFFFFF))
#define ROR64(x, y) \
( ((((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)(y)&CONST64(63))) | \
((x)<<((ulong64)(64-((y)&CONST64(63)))))) & CONST64(0xFFFFFFFFFFFFFFFF))
#define ROL64c(x, y) \
( (((x)<<((ulong64)(y)&63)) | \
(((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)64-((y)&63)))) & CONST64(0xFFFFFFFFFFFFFFFF))
#define ROR64c(x, y) \
( ((((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)(y)&CONST64(63))) | \
((x)<<((ulong64)(64-((y)&CONST64(63)))))) & CONST64(0xFFFFFFFFFFFFFFFF))
#endif
#ifndef MAX
#define MAX(x, y) ( ((x)>(y))?(x):(y) )
#endif
#ifndef MIN
#define MIN(x, y) ( ((x)<(y))?(x):(y) )
#endif
/* extract a byte portably */
#ifdef _MSC_VER
#define byte(x, n) ((unsigned char)((x) >> (8 * (n))))
#else
#define byte(x, n) (((x) >> (8 * (n))) & 255)
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_macros.h,v $ */
/* $Revision: 1.15 $ */
/* $Date: 2006/11/29 23:43:57 $ */

500
crypto777/hmac/tomcrypt_math.h

@ -0,0 +1,500 @@
/** math functions **/
#define LTC_MP_LT -1
#define LTC_MP_EQ 0
#define LTC_MP_GT 1
#define LTC_MP_NO 0
#define LTC_MP_YES 1
#ifndef LTC_MECC
typedef void ecc_point;
#endif
#ifndef LTC_MRSA
typedef void rsa_key;
#endif
/** math descriptor */
typedef struct {
/** Name of the math provider */
char *name;
/** Bits per digit, amount of bits must fit in an unsigned long */
int bits_per_digit;
/* ---- init/deinit functions ---- */
/** initialize a bignum
@param a The number to initialize
@return CRYPT_OK on success
*/
int (*init)(void **a);
/** init copy
@param dst The number to initialize and write to
@param src The number to copy from
@return CRYPT_OK on success
*/
int (*init_copy)(void **dst, void *src);
/** deinit
@param a The number to free
@return CRYPT_OK on success
*/
void (*deinit)(void *a);
/* ---- data movement ---- */
/** negate
@param src The number to negate
@param dst The destination
@return CRYPT_OK on success
*/
int (*neg)(void *src, void *dst);
/** copy
@param src The number to copy from
@param dst The number to write to
@return CRYPT_OK on success
*/
int (*copy)(void *src, void *dst);
/* ---- trivial low level functions ---- */
/** set small constant
@param a Number to write to
@param n Source upto bits_per_digit (actually meant for very small constants)
@return CRYPT_OK on succcess
*/
int (*set_int)(void *a, unsigned long n);
/** get small constant
@param a Number to read, only fetches upto bits_per_digit from the number
@return The lower bits_per_digit of the integer (unsigned)
*/
unsigned long (*get_int)(void *a);
/** get digit n
@param a The number to read from
@param n The number of the digit to fetch
@return The bits_per_digit sized n'th digit of a
*/
unsigned long (*get_digit)(void *a, int n);
/** Get the number of digits that represent the number
@param a The number to count
@return The number of digits used to represent the number
*/
int (*get_digit_count)(void *a);
/** compare two integers
@param a The left side integer
@param b The right side integer
@return LTC_MP_LT if a < b, LTC_MP_GT if a > b and LTC_MP_EQ otherwise. (signed comparison)
*/
int (*compare)(void *a, void *b);
/** compare against int
@param a The left side integer
@param b The right side integer (upto bits_per_digit)
@return LTC_MP_LT if a < b, LTC_MP_GT if a > b and LTC_MP_EQ otherwise. (signed comparison)
*/
int (*compare_d)(void *a, unsigned long n);
/** Count the number of bits used to represent the integer
@param a The integer to count
@return The number of bits required to represent the integer
*/
int (*count_bits)(void * a);
/** Count the number of LSB bits which are zero
@param a The integer to count
@return The number of contiguous zero LSB bits
*/
int (*count_lsb_bits)(void *a);
/** Compute a power of two
@param a The integer to store the power in
@param n The power of two you want to store (a = 2^n)
@return CRYPT_OK on success
*/
int (*twoexpt)(void *a , int n);
/* ---- radix conversions ---- */
/** read ascii string
@param a The integer to store into
@param str The string to read
@param radix The radix the integer has been represented in (2-64)
@return CRYPT_OK on success
*/
int (*read_radix)(void *a, const char *str, int radix);
/** write number to string
@param a The integer to store
@param str The destination for the string
@param radix The radix the integer is to be represented in (2-64)
@return CRYPT_OK on success
*/
int (*write_radix)(void *a, char *str, int radix);
/** get size as unsigned char string
@param a The integer to get the size (when stored in array of octets)
@return The length of the integer
*/
unsigned long (*unsigned_size)(void *a);
/** store an integer as an array of octets
@param src The integer to store
@param dst The buffer to store the integer in
@return CRYPT_OK on success
*/
int (*unsigned_write)(void *src, unsigned char *dst);
/** read an array of octets and store as integer
@param dst The integer to load
@param src The array of octets
@param len The number of octets
@return CRYPT_OK on success
*/
int (*unsigned_read)(void *dst, unsigned char *src, unsigned long len);
/* ---- basic math ---- */
/** add two integers
@param a The first source integer
@param b The second source integer
@param c The destination of "a + b"
@return CRYPT_OK on success
*/
int (*add)(void *a, void *b, void *c);
/** add two integers
@param a The first source integer
@param b The second source integer (single digit of upto bits_per_digit in length)
@param c The destination of "a + b"
@return CRYPT_OK on success
*/
int (*addi)(void *a, unsigned long b, void *c);
/** subtract two integers
@param a The first source integer
@param b The second source integer
@param c The destination of "a - b"
@return CRYPT_OK on success
*/
int (*sub)(void *a, void *b, void *c);
/** subtract two integers
@param a The first source integer
@param b The second source integer (single digit of upto bits_per_digit in length)
@param c The destination of "a - b"
@return CRYPT_OK on success
*/
int (*subi)(void *a, unsigned long b, void *c);
/** multiply two integers
@param a The first source integer
@param b The second source integer (single digit of upto bits_per_digit in length)
@param c The destination of "a * b"
@return CRYPT_OK on success
*/
int (*mul)(void *a, void *b, void *c);
/** multiply two integers
@param a The first source integer
@param b The second source integer (single digit of upto bits_per_digit in length)
@param c The destination of "a * b"
@return CRYPT_OK on success
*/
int (*muli)(void *a, unsigned long b, void *c);
/** Square an integer
@param a The integer to square
@param b The destination
@return CRYPT_OK on success
*/
int (*sqr)(void *a, void *b);
/** Divide an integer
@param a The dividend
@param b The divisor
@param c The quotient (can be NULL to signify don't care)
@param d The remainder (can be NULL to signify don't care)
@return CRYPT_OK on success
*/
int (*mpdiv)(void *a, void *b, void *c, void *d);
/** divide by two
@param a The integer to divide (shift right)
@param b The destination
@return CRYPT_OK on success
*/
int (*div_2)(void *a, void *b);
/** Get remainder (small value)
@param a The integer to reduce
@param b The modulus (upto bits_per_digit in length)
@param c The destination for the residue
@return CRYPT_OK on success
*/
int (*modi)(void *a, unsigned long b, unsigned long *c);
/** gcd
@param a The first integer
@param b The second integer
@param c The destination for (a, b)
@return CRYPT_OK on success
*/
int (*gcd)(void *a, void *b, void *c);
/** lcm
@param a The first integer
@param b The second integer
@param c The destination for [a, b]
@return CRYPT_OK on success
*/
int (*lcm)(void *a, void *b, void *c);
/** Modular multiplication
@param a The first source
@param b The second source
@param c The modulus
@param d The destination (a*b mod c)
@return CRYPT_OK on success
*/
int (*mulmod)(void *a, void *b, void *c, void *d);
/** Modular squaring
@param a The first source
@param b The modulus
@param c The destination (a*a mod b)
@return CRYPT_OK on success
*/
int (*sqrmod)(void *a, void *b, void *c);
/** Modular inversion
@param a The value to invert
@param b The modulus
@param c The destination (1/a mod b)
@return CRYPT_OK on success
*/
int (*invmod)(void *, void *, void *);
/* ---- reduction ---- */
/** setup montgomery
@param a The modulus
@param b The destination for the reduction digit
@return CRYPT_OK on success
*/
int (*montgomery_setup)(void *a, void **b);
/** get normalization value
@param a The destination for the normalization value
@param b The modulus
@return CRYPT_OK on success
*/
int (*montgomery_normalization)(void *a, void *b);
/** reduce a number
@param a The number [and dest] to reduce
@param b The modulus
@param c The value "b" from montgomery_setup()
@return CRYPT_OK on success
*/
int (*montgomery_reduce)(void *a, void *b, void *c);
/** clean up (frees memory)
@param a The value "b" from montgomery_setup()
@return CRYPT_OK on success
*/
void (*montgomery_deinit)(void *a);
/* ---- exponentiation ---- */
/** Modular exponentiation
@param a The base integer
@param b The power (can be negative) integer
@param c The modulus integer
@param d The destination
@return CRYPT_OK on success
*/
int (*exptmod)(void *a, void *b, void *c, void *d);
/** Primality testing
@param a The integer to test
@param b The destination of the result (FP_YES if prime)
@return CRYPT_OK on success
*/
int (*isprime)(void *a, int *b);
/* ---- (optional) ecc point math ---- */
/** ECC GF(p) point multiplication (from the NIST curves)
@param k The integer to multiply the point by
@param G The point to multiply
@param R The destination for kG
@param modulus The modulus for the field
@param map Boolean indicated whether to map back to affine or not (can be ignored if you work in affine only)
@return CRYPT_OK on success
*/
int (*ecc_ptmul)(void *k, ecc_point *G, ecc_point *R, void *modulus, int map);
/** ECC GF(p) point addition
@param P The first point
@param Q The second point
@param R The destination of P + Q
@param modulus The modulus
@param mp The "b" value from montgomery_setup()
@return CRYPT_OK on success
*/
int (*ecc_ptadd)(ecc_point *P, ecc_point *Q, ecc_point *R, void *modulus, void *mp);
/** ECC GF(p) point double
@param P The first point
@param R The destination of 2P
@param modulus The modulus
@param mp The "b" value from montgomery_setup()
@return CRYPT_OK on success
*/
int (*ecc_ptdbl)(ecc_point *P, ecc_point *R, void *modulus, void *mp);
/** ECC mapping from projective to affine, currently uses (x,y,z) => (x/z^2, y/z^3, 1)
@param P The point to map
@param modulus The modulus
@param mp The "b" value from montgomery_setup()
@return CRYPT_OK on success
@remark The mapping can be different but keep in mind a ecc_point only has three
integers (x,y,z) so if you use a different mapping you have to make it fit.
*/
int (*ecc_map)(ecc_point *P, void *modulus, void *mp);
/** Computes kA*A + kB*B = C using Shamir's Trick
@param A First point to multiply
@param kA What to multiple A by
@param B Second point to multiply
@param kB What to multiple B by
@param C [out] Destination point (can overlap with A or B
@param modulus Modulus for curve
@return CRYPT_OK on success
*/
int (*ecc_mul2add)(ecc_point *A, void *kA,
ecc_point *B, void *kB,
ecc_point *C,
void *modulus);
/* ---- (optional) rsa optimized math (for internal CRT) ---- */
/** RSA Key Generation
@param prng An active PRNG state
@param wprng The index of the PRNG desired
@param size The size of the modulus (key size) desired (octets)
@param e The "e" value (public key). e==65537 is a good choice
@param key [out] Destination of a newly created private key pair
@return CRYPT_OK if successful, upon error all allocated ram is freed
*/
int (*rsa_keygen)(prng_state *prng, int wprng, int size, long e, rsa_key *key);
/** RSA exponentiation
@param in The octet array representing the base
@param inlen The length of the input
@param out The destination (to be stored in an octet array format)
@param outlen The length of the output buffer and the resulting size (zero padded to the size of the modulus)
@param which PK_PUBLIC for public RSA and PK_PRIVATE for private RSA
@param key The RSA key to use
@return CRYPT_OK on success
*/
int (*rsa_me)(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int which,
rsa_key *key);
} ltc_math_descriptor;
extern ltc_math_descriptor ltc_mp;
int ltc_init_multi(void **a, ...);
void ltc_deinit_multi(void *a, ...);
#ifdef LTM_DESC
extern const ltc_math_descriptor ltm_desc;
#endif
#ifdef TFM_DESC
extern const ltc_math_descriptor tfm_desc;
#endif
#ifdef GMP_DESC
extern const ltc_math_descriptor gmp_desc;
#endif
#if !defined(DESC_DEF_ONLY) && defined(LTC_SOURCE)
#define MP_DIGIT_BIT ltc_mp.bits_per_digit
/* some handy macros */
#define mp_init(a) ltc_mp.init(a)
#define mp_init_multi ltc_init_multi
#define mp_clear(a) ltc_mp.deinit(a)
#define mp_clear_multi ltc_deinit_multi
#define mp_init_copy(a, b) ltc_mp.init_copy(a, b)
#define mp_neg(a, b) ltc_mp.neg(a, b)
#define mp_copy(a, b) ltc_mp.copy(a, b)
#define mp_set(a, b) ltc_mp.set_int(a, b)
#define mp_set_int(a, b) ltc_mp.set_int(a, b)
#define mp_get_int(a) ltc_mp.get_int(a)
#define mp_get_digit(a, n) ltc_mp.get_digit(a, n)
#define mp_get_digit_count(a) ltc_mp.get_digit_count(a)
#define mp_cmp(a, b) ltc_mp.compare(a, b)
#define mp_cmp_d(a, b) ltc_mp.compare_d(a, b)
#define mp_count_bits(a) ltc_mp.count_bits(a)
#define mp_cnt_lsb(a) ltc_mp.count_lsb_bits(a)
#define mp_2expt(a, b) ltc_mp.twoexpt(a, b)
#define mp_read_radix(a, b, c) ltc_mp.read_radix(a, b, c)
#define mp_toradix(a, b, c) ltc_mp.write_radix(a, b, c)
#define mp_unsigned_bin_size(a) ltc_mp.unsigned_size(a)
#define mp_to_unsigned_bin(a, b) ltc_mp.unsigned_write(a, b)
#define mp_read_unsigned_bin(a, b, c) ltc_mp.unsigned_read(a, b, c)
#define mp_add(a, b, c) ltc_mp.add(a, b, c)
#define mp_add_d(a, b, c) ltc_mp.addi(a, b, c)
#define mp_sub(a, b, c) ltc_mp.sub(a, b, c)
#define mp_sub_d(a, b, c) ltc_mp.subi(a, b, c)
#define mp_mul(a, b, c) ltc_mp.mul(a, b, c)
#define mp_mul_d(a, b, c) ltc_mp.muli(a, b, c)
#define mp_sqr(a, b) ltc_mp.sqr(a, b)
#define mp_div(a, b, c, d) ltc_mp.mpdiv(a, b, c, d)
#define mp_div_2(a, b) ltc_mp.div_2(a, b)
#define mp_mod(a, b, c) ltc_mp.mpdiv(a, b, NULL, c)
#define mp_mod_d(a, b, c) ltc_mp.modi(a, b, c)
#define mp_gcd(a, b, c) ltc_mp.gcd(a, b, c)
#define mp_lcm(a, b, c) ltc_mp.lcm(a, b, c)
#define mp_mulmod(a, b, c, d) ltc_mp.mulmod(a, b, c, d)
#define mp_sqrmod(a, b, c) ltc_mp.sqrmod(a, b, c)
#define mp_invmod(a, b, c) ltc_mp.invmod(a, b, c)
#define mp_montgomery_setup(a, b) ltc_mp.montgomery_setup(a, b)
#define mp_montgomery_normalization(a, b) ltc_mp.montgomery_normalization(a, b)
#define mp_montgomery_reduce(a, b, c) ltc_mp.montgomery_reduce(a, b, c)
#define mp_montgomery_free(a) ltc_mp.montgomery_deinit(a)
#define mp_exptmod(a,b,c,d) ltc_mp.exptmod(a,b,c,d)
#define mp_prime_is_prime(a, b, c) ltc_mp.isprime(a, c)
#define mp_iszero(a) (mp_cmp_d(a, 0) == LTC_MP_EQ ? LTC_MP_YES : LTC_MP_NO)
#define mp_isodd(a) (mp_get_digit_count(a) > 0 ? (mp_get_digit(a, 0) & 1 ? LTC_MP_YES : LTC_MP_NO) : LTC_MP_NO)
#define mp_exch(a, b) do { void *ABC__tmp = a; a = b; b = ABC__tmp; } while(0);
#define mp_tohex(a, b) mp_toradix(a, b, 16)
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_math.h,v $ */
/* $Revision: 1.44 $ */
/* $Date: 2007/05/12 14:32:35 $ */

23
crypto777/hmac/tomcrypt_misc.h

@ -0,0 +1,23 @@
/* ---- LTC_BASE64 Routines ---- */
#ifdef LTC_BASE64
int base64_encode(const unsigned char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
int base64_decode(const unsigned char *in, unsigned long len,
unsigned char *out, unsigned long *outlen);
#endif
/* ---- MEM routines ---- */
//void zeromem(void *dst, size_t len);
void burn_stack(unsigned long len);
const char *error_to_string(int err);
extern const char *crypt_build_settings;
/* ---- HMM ---- */
int crypt_fsa(void *mp, ...);
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_misc.h,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2007/05/12 14:32:35 $ */

552
crypto777/hmac/tomcrypt_pk.h

@ -0,0 +1,552 @@
/* ---- NUMBER THEORY ---- */
enum {
PK_PUBLIC=0,
PK_PRIVATE=1
};
int rand_prime(void *N, long len, prng_state *prng, int wprng);
/* ---- RSA ---- */
#ifdef LTC_MRSA
/* Min and Max RSA key sizes (in bits) */
#define MIN_RSA_SIZE 1024
#define MAX_RSA_SIZE 4096
/** RSA LTC_PKCS style key */
typedef struct Rsa_key {
/** Type of key, PK_PRIVATE or PK_PUBLIC */
int type;
/** The public exponent */
void *e;
/** The private exponent */
void *d;
/** The modulus */
void *N;
/** The p factor of N */
void *p;
/** The q factor of N */
void *q;
/** The 1/q mod p CRT param */
void *qP;
/** The d mod (p - 1) CRT param */
void *dP;
/** The d mod (q - 1) CRT param */
void *dQ;
} rsa_key;
int rsa_make_key(prng_state *prng, int wprng, int size, long e, rsa_key *key);
int rsa_exptmod(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int which,
rsa_key *key);
void rsa_free(rsa_key *key);
/* These use LTC_PKCS #1 v2.0 padding */
#define rsa_encrypt_key(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _prng, _prng_idx, _hash_idx, _key) \
rsa_encrypt_key_ex(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _prng, _prng_idx, _hash_idx, LTC_LTC_PKCS_1_OAEP, _key)
#define rsa_decrypt_key(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _hash_idx, _stat, _key) \
rsa_decrypt_key_ex(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _hash_idx, LTC_LTC_PKCS_1_OAEP, _stat, _key)
#define rsa_sign_hash(_in, _inlen, _out, _outlen, _prng, _prng_idx, _hash_idx, _saltlen, _key) \
rsa_sign_hash_ex(_in, _inlen, _out, _outlen, LTC_LTC_PKCS_1_PSS, _prng, _prng_idx, _hash_idx, _saltlen, _key)
#define rsa_verify_hash(_sig, _siglen, _hash, _hashlen, _hash_idx, _saltlen, _stat, _key) \
rsa_verify_hash_ex(_sig, _siglen, _hash, _hashlen, LTC_LTC_PKCS_1_PSS, _hash_idx, _saltlen, _stat, _key)
/* These can be switched between LTC_PKCS #1 v2.x and LTC_PKCS #1 v1.5 paddings */
int rsa_encrypt_key_ex(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
const unsigned char *lparam, unsigned long lparamlen,
prng_state *prng, int prng_idx, int hash_idx, int padding, rsa_key *key);
int rsa_decrypt_key_ex(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
const unsigned char *lparam, unsigned long lparamlen,
int hash_idx, int padding,
int *stat, rsa_key *key);
int rsa_sign_hash_ex(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
int padding,
prng_state *prng, int prng_idx,
int hash_idx, unsigned long saltlen,
rsa_key *key);
int rsa_verify_hash_ex(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int padding,
int hash_idx, unsigned long saltlen,
int *stat, rsa_key *key);
/* LTC_PKCS #1 import/export */
int rsa_export(unsigned char *out, unsigned long *outlen, int type, rsa_key *key);
int rsa_import(const unsigned char *in, unsigned long inlen, rsa_key *key);
#endif
/* ---- Katja ---- */
#ifdef MKAT
/* Min and Max KAT key sizes (in bits) */
#define MIN_KAT_SIZE 1024
#define MAX_KAT_SIZE 4096
/** Katja LTC_PKCS style key */
typedef struct KAT_key {
/** Type of key, PK_PRIVATE or PK_PUBLIC */
int type;
/** The private exponent */
void *d;
/** The modulus */
void *N;
/** The p factor of N */
void *p;
/** The q factor of N */
void *q;
/** The 1/q mod p CRT param */
void *qP;
/** The d mod (p - 1) CRT param */
void *dP;
/** The d mod (q - 1) CRT param */
void *dQ;
/** The pq param */
void *pq;
} katja_key;
int katja_make_key(prng_state *prng, int wprng, int size, katja_key *key);
int katja_exptmod(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int which,
katja_key *key);
void katja_free(katja_key *key);
/* These use LTC_PKCS #1 v2.0 padding */
int katja_encrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
const unsigned char *lparam, unsigned long lparamlen,
prng_state *prng, int prng_idx, int hash_idx, katja_key *key);
int katja_decrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
const unsigned char *lparam, unsigned long lparamlen,
int hash_idx, int *stat,
katja_key *key);
/* LTC_PKCS #1 import/export */
int katja_export(unsigned char *out, unsigned long *outlen, int type, katja_key *key);
int katja_import(const unsigned char *in, unsigned long inlen, katja_key *key);
#endif
/* ---- ECC Routines ---- */
#ifdef LTC_MECC
/* size of our temp buffers for exported keys */
#define ECC_BUF_SIZE 256
/* max private key size */
#define ECC_MAXSIZE 66
/** Structure defines a NIST GF(p) curve */
typedef struct {
/** The size of the curve in octets */
int size;
/** name of curve */
char *name;
/** The prime that defines the field the curve is in (encoded in hex) */
char *prime;
/** The fields B param (hex) */
char *B;
/** The order of the curve (hex) */
char *order;
/** The x co-ordinate of the base point on the curve (hex) */
char *Gx;
/** The y co-ordinate of the base point on the curve (hex) */
char *Gy;
} ltc_ecc_set_type;
/** A point on a ECC curve, stored in Jacbobian format such that (x,y,z) => (x/z^2, y/z^3, 1) when interpretted as affine */
typedef struct {
/** The x co-ordinate */
void *x;
/** The y co-ordinate */
void *y;
/** The z co-ordinate */
void *z;
} ecc_point;
/** An ECC key */
typedef struct {
/** Type of key, PK_PRIVATE or PK_PUBLIC */
int type;
/** Index into the ltc_ecc_sets[] for the parameters of this curve; if -1, then this key is using user supplied curve in dp */
int idx;
/** pointer to domain parameters; either points to NIST curves (identified by idx >= 0) or user supplied curve */
const ltc_ecc_set_type *dp;
/** The public key */
ecc_point pubkey;
/** The private key */
void *k;
} ecc_key;
/** the ECC params provided */
extern const ltc_ecc_set_type ltc_ecc_sets[];
int ecc_test(void);
void ecc_sizes(int *low, int *high);
int ecc_get_size(ecc_key *key);
int ecc_make_key(prng_state *prng, int wprng, int keysize, ecc_key *key);
int ecc_make_key_ex(prng_state *prng, int wprng, ecc_key *key, const ltc_ecc_set_type *dp);
void ecc_free(ecc_key *key);
int ecc_export(unsigned char *out, unsigned long *outlen, int type, ecc_key *key);
int ecc_import(const unsigned char *in, unsigned long inlen, ecc_key *key);
int ecc_import_ex(const unsigned char *in, unsigned long inlen, ecc_key *key, const ltc_ecc_set_type *dp);
int ecc_ansi_x963_export(ecc_key *key, unsigned char *out, unsigned long *outlen);
int ecc_ansi_x963_import(const unsigned char *in, unsigned long inlen, ecc_key *key);
int ecc_ansi_x963_import_ex(const unsigned char *in, unsigned long inlen, ecc_key *key, ltc_ecc_set_type *dp);
int ecc_shared_secret(ecc_key *private_key, ecc_key *public_key,
unsigned char *out, unsigned long *outlen);
int ecc_encrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_state *prng, int wprng, int hash,
ecc_key *key);
int ecc_decrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
ecc_key *key);
int ecc_sign_hash(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_state *prng, int wprng, ecc_key *key);
int ecc_verify_hash(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int *stat, ecc_key *key);
/* low level functions */
ecc_point *ltc_ecc_new_point(void);
void ltc_ecc_del_point(ecc_point *p);
int ltc_ecc_is_valid_idx(int n);
/* point ops (mp == montgomery digit) */
#if !defined(LTC_MECC_ACCEL) || defined(LTM_LTC_DESC) || defined(GMP_LTC_DESC)
/* R = 2P */
int ltc_ecc_projective_dbl_point(ecc_point *P, ecc_point *R, void *modulus, void *mp);
/* R = P + Q */
int ltc_ecc_projective_add_point(ecc_point *P, ecc_point *Q, ecc_point *R, void *modulus, void *mp);
#endif
#if defined(LTC_MECC_FP)
/* optimized point multiplication using fixed point cache (HAC algorithm 14.117) */
int ltc_ecc_fp_mulmod(void *k, ecc_point *G, ecc_point *R, void *modulus, int map);
/* functions for saving/loading/freeing/adding to fixed point cache */
int ltc_ecc_fp_save_state(unsigned char **out, unsigned long *outlen);
int ltc_ecc_fp_restore_state(unsigned char *in, unsigned long inlen);
void ltc_ecc_fp_free(void);
int ltc_ecc_fp_add_point(ecc_point *g, void *modulus, int lock);
/* lock/unlock all points currently in fixed point cache */
void ltc_ecc_fp_tablelock(int lock);
#endif
/* R = kG */
int ltc_ecc_mulmod(void *k, ecc_point *G, ecc_point *R, void *modulus, int map);
#ifdef LTC_ECC_SHAMIR
/* kA*A + kB*B = C */
int ltc_ecc_mul2add(ecc_point *A, void *kA,
ecc_point *B, void *kB,
ecc_point *C,
void *modulus);
#ifdef LTC_MECC_FP
/* Shamir's trick with optimized point multiplication using fixed point cache */
int ltc_ecc_fp_mul2add(ecc_point *A, void *kA,
ecc_point *B, void *kB,
ecc_point *C, void *modulus);
#endif
#endif
/* map P to affine from projective */
int ltc_ecc_map(ecc_point *P, void *modulus, void *mp);
#endif
#ifdef LTC_MDSA
/* Max diff between group and modulus size in bytes */
#define LTC_MDSA_DELTA 512
/* Max DSA group size in bytes (default allows 4k-bit groups) */
#define LTC_MDSA_MAX_GROUP 512
/** DSA key structure */
typedef struct {
/** The key type, PK_PRIVATE or PK_PUBLIC */
int type;
/** The order of the sub-group used in octets */
int qord;
/** The generator */
void *g;
/** The prime used to generate the sub-group */
void *q;
/** The large prime that generats the field the contains the sub-group */
void *p;
/** The private key */
void *x;
/** The public key */
void *y;
} dsa_key;
int dsa_make_key(prng_state *prng, int wprng, int group_size, int modulus_size, dsa_key *key);
void dsa_free(dsa_key *key);
int dsa_sign_hash_raw(const unsigned char *in, unsigned long inlen,
void *r, void *s,
prng_state *prng, int wprng, dsa_key *key);
int dsa_sign_hash(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_state *prng, int wprng, dsa_key *key);
int dsa_verify_hash_raw( void *r, void *s,
const unsigned char *hash, unsigned long hashlen,
int *stat, dsa_key *key);
int dsa_verify_hash(const unsigned char *sig, unsigned long siglen,
const unsigned char *hash, unsigned long hashlen,
int *stat, dsa_key *key);
int dsa_encrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
prng_state *prng, int wprng, int hash,
dsa_key *key);
int dsa_decrypt_key(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen,
dsa_key *key);
int dsa_import(const unsigned char *in, unsigned long inlen, dsa_key *key);
int dsa_export(unsigned char *out, unsigned long *outlen, int type, dsa_key *key);
int dsa_verify_key(dsa_key *key, int *stat);
int dsa_shared_secret(void *private_key, void *base,
dsa_key *public_key,
unsigned char *out, unsigned long *outlen);
#endif
#ifdef LTC_DER
/* DER handling */
enum {
LTC_ASN1_EOL,
LTC_ASN1_BOOLEAN,
LTC_ASN1_INTEGER,
LTC_ASN1_SHORT_INTEGER,
LTC_ASN1_BIT_STRING,
LTC_ASN1_OCTET_STRING,
LTC_ASN1_NULL,
LTC_ASN1_OBJECT_IDENTIFIER,
LTC_ASN1_IA5_STRING,
LTC_ASN1_PRINTABLE_STRING,
LTC_ASN1_UTF8_STRING,
LTC_ASN1_UTCTIME,
LTC_ASN1_CHOICE,
LTC_ASN1_SEQUENCE,
LTC_ASN1_SET,
LTC_ASN1_SETOF
};
/** A LTC ASN.1 list type */
typedef struct ltc_asn1_list_ {
/** The LTC ASN.1 enumerated type identifier */
int type;
/** The data to encode or place for decoding */
void *data;
/** The size of the input or resulting output */
unsigned long size;
/** The used flag, this is used by the CHOICE ASN.1 type to indicate which choice was made */
int used;
/** prev/next entry in the list */
struct ltc_asn1_list_ *prev, *next, *child, *parent;
} ltc_asn1_list;
#define LTC_SET_ASN1(list, index, Type, Data, Size) \
do { \
int LTC_MACRO_temp = (index); \
ltc_asn1_list *LTC_MACRO_list = (list); \
LTC_MACRO_list[LTC_MACRO_temp].type = (Type); \
LTC_MACRO_list[LTC_MACRO_temp].data = (void*)(Data); \
LTC_MACRO_list[LTC_MACRO_temp].size = (Size); \
LTC_MACRO_list[LTC_MACRO_temp].used = 0; \
} while (0);
/* SEQUENCE */
int der_encode_sequence_ex(ltc_asn1_list *list, unsigned long inlen,
unsigned char *out, unsigned long *outlen, int type_of);
#define der_encode_sequence(list, inlen, out, outlen) der_encode_sequence_ex(list, inlen, out, outlen, LTC_ASN1_SEQUENCE)
int der_decode_sequence_ex(const unsigned char *in, unsigned long inlen,
ltc_asn1_list *list, unsigned long outlen, int ordered);
#define der_decode_sequence(in, inlen, list, outlen) der_decode_sequence_ex(in, inlen, list, outlen, 1)
int der_length_sequence(ltc_asn1_list *list, unsigned long inlen,
unsigned long *outlen);
/* SET */
#define der_decode_set(in, inlen, list, outlen) der_decode_sequence_ex(in, inlen, list, outlen, 0)
#define der_length_set der_length_sequence
int der_encode_set(ltc_asn1_list *list, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_encode_setof(ltc_asn1_list *list, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
/* VA list handy helpers with triplets of <type, size, data> */
int der_encode_sequence_multi(unsigned char *out, unsigned long *outlen, ...);
int der_decode_sequence_multi(const unsigned char *in, unsigned long inlen, ...);
/* FLEXI DECODER handle unknown list decoder */
int der_decode_sequence_flexi(const unsigned char *in, unsigned long *inlen, ltc_asn1_list **out);
void der_free_sequence_flexi(ltc_asn1_list *list);
void der_sequence_free(ltc_asn1_list *in);
/* BOOLEAN */
int der_length_boolean(unsigned long *outlen);
int der_encode_boolean(int in,
unsigned char *out, unsigned long *outlen);
int der_decode_boolean(const unsigned char *in, unsigned long inlen,
int *out);
/* INTEGER */
int der_encode_integer(void *num, unsigned char *out, unsigned long *outlen);
int der_decode_integer(const unsigned char *in, unsigned long inlen, void *num);
int der_length_integer(void *num, unsigned long *len);
/* INTEGER -- handy for 0..2^32-1 values */
int der_decode_short_integer(const unsigned char *in, unsigned long inlen, unsigned long *num);
int der_encode_short_integer(unsigned long num, unsigned char *out, unsigned long *outlen);
int der_length_short_integer(unsigned long num, unsigned long *outlen);
/* BIT STRING */
int der_encode_bit_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_bit_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_length_bit_string(unsigned long nbits, unsigned long *outlen);
/* OCTET STRING */
int der_encode_octet_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_octet_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_length_octet_string(unsigned long noctets, unsigned long *outlen);
/* OBJECT IDENTIFIER */
int der_encode_object_identifier(unsigned long *words, unsigned long nwords,
unsigned char *out, unsigned long *outlen);
int der_decode_object_identifier(const unsigned char *in, unsigned long inlen,
unsigned long *words, unsigned long *outlen);
int der_length_object_identifier(unsigned long *words, unsigned long nwords, unsigned long *outlen);
unsigned long der_object_identifier_bits(unsigned long x);
/* IA5 STRING */
int der_encode_ia5_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_ia5_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_length_ia5_string(const unsigned char *octets, unsigned long noctets, unsigned long *outlen);
int der_ia5_char_encode(int c);
int der_ia5_value_decode(int v);
/* Printable STRING */
int der_encode_printable_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_printable_string(const unsigned char *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_length_printable_string(const unsigned char *octets, unsigned long noctets, unsigned long *outlen);
int der_printable_char_encode(int c);
int der_printable_value_decode(int v);
/* UTF-8 */
#if (defined(SIZE_MAX) || __STDC_VERSION__ >= 199901L || defined(WCHAR_MAX) || defined(_WCHAR_T) || defined(_WCHAR_T_DEFINED) || defined (__WCHAR_TYPE__)) && !defined(LTC_NO_WCHAR)
#include <wchar.h>
#else
typedef ulong32 wchar_t;
#endif
int der_encode_utf8_string(const wchar_t *in, unsigned long inlen,
unsigned char *out, unsigned long *outlen);
int der_decode_utf8_string(const unsigned char *in, unsigned long inlen,
wchar_t *out, unsigned long *outlen);
unsigned long der_utf8_charsize(const wchar_t c);
int der_length_utf8_string(const wchar_t *in, unsigned long noctets, unsigned long *outlen);
/* CHOICE */
int der_decode_choice(const unsigned char *in, unsigned long *inlen,
ltc_asn1_list *list, unsigned long outlen);
/* UTCTime */
typedef struct {
unsigned YY, /* year */
MM, /* month */
DD, /* day */
hh, /* hour */
mm, /* minute */
ss, /* second */
off_dir, /* timezone offset direction 0 == +, 1 == - */
off_hh, /* timezone offset hours */
off_mm; /* timezone offset minutes */
} ltc_utctime;
int der_encode_utctime(ltc_utctime *utctime,
unsigned char *out, unsigned long *outlen);
int der_decode_utctime(const unsigned char *in, unsigned long *inlen,
ltc_utctime *out);
int der_length_utctime(ltc_utctime *utctime, unsigned long *outlen);
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_pk.h,v $ */
/* $Revision: 1.81 $ */
/* $Date: 2007/05/12 14:32:35 $ */

89
crypto777/hmac/tomcrypt_pkcs.h

@ -0,0 +1,89 @@
/* LTC_PKCS Header Info */
/* ===> LTC_PKCS #1 -- RSA Cryptography <=== */
#ifdef LTC_PKCS_1
enum ltc_pkcs_1_v1_5_blocks
{
LTC_LTC_PKCS_1_EMSA = 1, /* Block type 1 (LTC_PKCS #1 v1.5 signature padding) */
LTC_LTC_PKCS_1_EME = 2 /* Block type 2 (LTC_PKCS #1 v1.5 encryption padding) */
};
enum ltc_pkcs_1_paddings
{
LTC_LTC_PKCS_1_V1_5 = 1, /* LTC_PKCS #1 v1.5 padding (\sa ltc_pkcs_1_v1_5_blocks) */
LTC_LTC_PKCS_1_OAEP = 2, /* LTC_PKCS #1 v2.0 encryption padding */
LTC_LTC_PKCS_1_PSS = 3 /* LTC_PKCS #1 v2.1 signature padding */
};
int pkcs_1_mgf1( int hash_idx,
const unsigned char *seed, unsigned long seedlen,
unsigned char *mask, unsigned long masklen);
int pkcs_1_i2osp(void *n, unsigned long modulus_len, unsigned char *out);
int pkcs_1_os2ip(void *n, unsigned char *in, unsigned long inlen);
/* *** v1.5 padding */
int pkcs_1_v1_5_encode(const unsigned char *msg,
unsigned long msglen,
int block_type,
unsigned long modulus_bitlen,
prng_state *prng,
int prng_idx,
unsigned char *out,
unsigned long *outlen);
int pkcs_1_v1_5_decode(const unsigned char *msg,
unsigned long msglen,
int block_type,
unsigned long modulus_bitlen,
unsigned char *out,
unsigned long *outlen,
int *is_valid);
/* *** v2.1 padding */
int pkcs_1_oaep_encode(const unsigned char *msg, unsigned long msglen,
const unsigned char *lparam, unsigned long lparamlen,
unsigned long modulus_bitlen, prng_state *prng,
int prng_idx, int hash_idx,
unsigned char *out, unsigned long *outlen);
int pkcs_1_oaep_decode(const unsigned char *msg, unsigned long msglen,
const unsigned char *lparam, unsigned long lparamlen,
unsigned long modulus_bitlen, int hash_idx,
unsigned char *out, unsigned long *outlen,
int *res);
int pkcs_1_pss_encode(const unsigned char *msghash, unsigned long msghashlen,
unsigned long saltlen, prng_state *prng,
int prng_idx, int hash_idx,
unsigned long modulus_bitlen,
unsigned char *out, unsigned long *outlen);
int pkcs_1_pss_decode(const unsigned char *msghash, unsigned long msghashlen,
const unsigned char *sig, unsigned long siglen,
unsigned long saltlen, int hash_idx,
unsigned long modulus_bitlen, int *res);
#endif /* LTC_PKCS_1 */
/* ===> LTC_PKCS #5 -- Password Based Cryptography <=== */
#ifdef LTC_PKCS_5
/* Algorithm #1 (old) */
int pkcs_5_alg1(const unsigned char *password, unsigned long password_len,
const unsigned char *salt,
int iteration_count, int hash_idx,
unsigned char *out, unsigned long *outlen);
/* Algorithm #2 (new) */
int pkcs_5_alg2(const unsigned char *password, unsigned long password_len,
const unsigned char *salt, unsigned long salt_len,
int iteration_count, int hash_idx,
unsigned char *out, unsigned long *outlen);
#endif /* LTC_PKCS_5 */
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_pkcs.h,v $ */
/* $Revision: 1.8 $ */
/* $Date: 2007/05/12 14:32:35 $ */

199
crypto777/hmac/tomcrypt_prng.h

@ -0,0 +1,199 @@
/* ---- PRNG Stuff ---- */
#ifdef LTC_YARROW
struct yarrow_prng {
int cipher, hash;
unsigned char pool[MAXBLOCKSIZE];
symmetric_CTR ctr;
LTC_MUTEX_TYPE(prng_lock)
};
#endif
#ifdef LTC_RC4
struct rc4_prng {
int x, y;
unsigned char buf[256];
};
#endif
#ifdef LTC_FORTUNA
struct fortuna_prng {
hash_state pool[LTC_FORTUNA_POOLS]; /* the pools */
symmetric_key skey;
unsigned char K[32], /* the current key */
IV[16]; /* IV for CTR mode */
unsigned long pool_idx, /* current pool we will add to */
pool0_len, /* length of 0'th pool */
wd;
ulong64 reset_cnt; /* number of times we have reset */
LTC_MUTEX_TYPE(prng_lock)
};
#endif
#ifdef LTC_SOBER128
struct sober128_prng {
ulong32 R[17], /* Working storage for the shift register */
initR[17], /* saved register contents */
konst, /* key dependent constant */
sbuf; /* partial word encryption buffer */
int nbuf, /* number of part-word stream bits buffered */
flag, /* first add_entropy call or not? */
set; /* did we call add_entropy to set key? */
};
#endif
typedef union Prng_state {
char dummy[1];
#ifdef LTC_YARROW
struct yarrow_prng yarrow;
#endif
#ifdef LTC_RC4
struct rc4_prng rc4;
#endif
#ifdef LTC_FORTUNA
struct fortuna_prng fortuna;
#endif
#ifdef LTC_SOBER128
struct sober128_prng sober128;
#endif
} prng_state;
/** PRNG descriptor */
extern struct ltc_prng_descriptor {
/** Name of the PRNG */
char *name;
/** size in bytes of exported state */
int export_size;
/** Start a PRNG state
@param prng [out] The state to initialize
@return CRYPT_OK if successful
*/
int (*start)(prng_state *prng);
/** Add entropy to the PRNG
@param in The entropy
@param inlen Length of the entropy (octets)\
@param prng The PRNG state
@return CRYPT_OK if successful
*/
int (*add_entropy)(const unsigned char *in, unsigned long inlen, prng_state *prng);
/** Ready a PRNG state to read from
@param prng The PRNG state to ready
@return CRYPT_OK if successful
*/
int (*ready)(prng_state *prng);
/** Read from the PRNG
@param out [out] Where to store the data
@param outlen Length of data desired (octets)
@param prng The PRNG state to read from
@return Number of octets read
*/
unsigned long (*read)(unsigned char *out, unsigned long outlen, prng_state *prng);
/** Terminate a PRNG state
@param prng The PRNG state to terminate
@return CRYPT_OK if successful
*/
int (*done)(prng_state *prng);
/** Export a PRNG state
@param out [out] The destination for the state
@param outlen [in/out] The max size and resulting size of the PRNG state
@param prng The PRNG to export
@return CRYPT_OK if successful
*/
int (*pexport)(unsigned char *out, unsigned long *outlen, prng_state *prng);
/** Import a PRNG state
@param in The data to import
@param inlen The length of the data to import (octets)
@param prng The PRNG to initialize/import
@return CRYPT_OK if successful
*/
int (*pimport)(const unsigned char *in, unsigned long inlen, prng_state *prng);
/** Self-test the PRNG
@return CRYPT_OK if successful, CRYPT_NOP if self-testing has been disabled
*/
int (*test)(void);
} prng_descriptor[];
#ifdef LTC_YARROW
int yarrow_start(prng_state *prng);
int yarrow_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int yarrow_ready(prng_state *prng);
unsigned long yarrow_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int yarrow_done(prng_state *prng);
int yarrow_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int yarrow_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int yarrow_test(void);
extern const struct ltc_prng_descriptor yarrow_desc;
#endif
#ifdef LTC_FORTUNA
int fortuna_start(prng_state *prng);
int fortuna_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int fortuna_ready(prng_state *prng);
unsigned long fortuna_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int fortuna_done(prng_state *prng);
int fortuna_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int fortuna_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int fortuna_test(void);
extern const struct ltc_prng_descriptor fortuna_desc;
#endif
#ifdef LTC_RC4
int rc4_start(prng_state *prng);
int rc4_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int rc4_ready(prng_state *prng);
unsigned long rc4_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int rc4_done(prng_state *prng);
int rc4_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int rc4_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int rc4_test(void);
extern const struct ltc_prng_descriptor rc4_desc;
#endif
#ifdef LTC_SPRNG
int sprng_start(prng_state *prng);
int sprng_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sprng_ready(prng_state *prng);
unsigned long sprng_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int sprng_done(prng_state *prng);
int sprng_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int sprng_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sprng_test(void);
extern const struct ltc_prng_descriptor sprng_desc;
#endif
#ifdef LTC_SOBER128
int sober128_start(prng_state *prng);
int sober128_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sober128_ready(prng_state *prng);
unsigned long sober128_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int sober128_done(prng_state *prng);
int sober128_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int sober128_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sober128_test(void);
extern const struct ltc_prng_descriptor sober128_desc;
#endif
int find_prng(const char *name);
int register_prng(const struct ltc_prng_descriptor *prng);
int unregister_prng(const struct ltc_prng_descriptor *prng);
int prng_is_valid(int idx);
LTC_MUTEX_PROTO(ltc_prng_mutex)
/* Slow RNG you **might** be able to use to seed a PRNG with. Be careful as this
* might not work on all platforms as planned
*/
unsigned long rng_get_bytes(unsigned char *out,
unsigned long outlen,
void (*callback)(void));
int rng_make_prng(int bits, int wprng, prng_state *prng, void (*callback)(void));
/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_prng.h,v $ */
/* $Revision: 1.9 $ */
/* $Date: 2007/05/12 14:32:35 $ */

325
crypto777/hmac/whirl.c

@ -0,0 +1,325 @@
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://libtom.org
*/
/**
@file whirl.c
LTC_WHIRLPOOL (using their new sbox) hash function by Tom St Denis
*/
#include "tomcrypt.h"
#ifdef LTC_WHIRLPOOL
const struct ltc_hash_descriptor whirlpool_desc =
{
"whirlpool",
11,
64,
64,
/* OID */
{ 1, 0, 10118, 3, 0, 55 },
6,
&whirlpool_init,
&whirlpool_process,
&whirlpool_done,
&whirlpool_test,
NULL
};
/* the sboxes */
#include "whirltab.c"
/* get a_{i,j} */
#define GB(a,i,j) ((a[(i) & 7] >> (8 * (j))) & 255)
/* shortcut macro to perform three functions at once */
#define theta_pi_gamma(a, i) \
SB0(GB(a, i-0, 7)) ^ \
SB1(GB(a, i-1, 6)) ^ \
SB2(GB(a, i-2, 5)) ^ \
SB3(GB(a, i-3, 4)) ^ \
SB4(GB(a, i-4, 3)) ^ \
SB5(GB(a, i-5, 2)) ^ \
SB6(GB(a, i-6, 1)) ^ \
SB7(GB(a, i-7, 0))
#ifdef LTC_CLEAN_STACK
static int _whirlpool_compress(hash_state *md, unsigned char *buf)
#else
static int whirlpool_compress(hash_state *md, unsigned char *buf)
#endif
{
ulong64 K[2][8], T[3][8];
int x, y;
/* load the block/state */
for (x = 0; x < 8; x++) {
K[0][x] = md->whirlpool.state[x];
LOAD64H(T[0][x], buf + (8 * x));
T[2][x] = T[0][x];
T[0][x] ^= K[0][x];
}
/* do rounds 1..10 */
for (x = 0; x < 10; x += 2) {
/* odd round */
/* apply main transform to K[0] into K[1] */
for (y = 0; y < 8; y++) {
K[1][y] = theta_pi_gamma(K[0], y);
}
/* xor the constant */
K[1][0] ^= cont[x];
/* apply main transform to T[0] into T[1] */
for (y = 0; y < 8; y++) {
T[1][y] = theta_pi_gamma(T[0], y) ^ K[1][y];
}
/* even round */
/* apply main transform to K[1] into K[0] */
for (y = 0; y < 8; y++) {
K[0][y] = theta_pi_gamma(K[1], y);
}
/* xor the constant */
K[0][0] ^= cont[x+1];
/* apply main transform to T[1] into T[0] */
for (y = 0; y < 8; y++) {
T[0][y] = theta_pi_gamma(T[1], y) ^ K[0][y];
}
}
/* store state */
for (x = 0; x < 8; x++) {
md->whirlpool.state[x] ^= T[0][x] ^ T[2][x];
}
return CRYPT_OK;
}
#ifdef LTC_CLEAN_STACK
static int whirlpool_compress(hash_state *md, unsigned char *buf)
{
int err;
err = _whirlpool_compress(md, buf);
burn_stack((5 * 8 * sizeof(ulong64)) + (2 * sizeof(int)));
return err;
}
#endif
/**
Initialize the hash state
@param md The hash state you wish to initialize
@return CRYPT_OK if successful
*/
int whirlpool_init(hash_state * md)
{
LTC_ARGCHK(md != NULL);
zeromem(&md->whirlpool, sizeof(md->whirlpool));
return CRYPT_OK;
}
/**
Process a block of memory though the hash
@param md The hash state
@param in The data to hash
@param inlen The length of the data (octets)
@return CRYPT_OK if successful
*/
HASH_PROCESS(whirlpool_process, whirlpool_compress, whirlpool, 64)
/**
Terminate the hash to get the digest
@param md The hash state
@param out [out] The destination of the hash (64 bytes)
@return CRYPT_OK if successful
*/
int whirlpool_done(hash_state * md, unsigned char *out)
{
int i;
LTC_ARGCHK(md != NULL);
LTC_ARGCHK(out != NULL);
if (md->whirlpool.curlen >= sizeof(md->whirlpool.buf)) {
return CRYPT_INVALID_ARG;
}
/* increase the length of the message */
md->whirlpool.length += md->whirlpool.curlen * 8;
/* append the '1' bit */
md->whirlpool.buf[md->whirlpool.curlen++] = (unsigned char)0x80;
/* if the length is currently above 32 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (md->whirlpool.curlen > 32) {
while (md->whirlpool.curlen < 64) {
md->whirlpool.buf[md->whirlpool.curlen++] = (unsigned char)0;
}
whirlpool_compress(md, md->whirlpool.buf);
md->whirlpool.curlen = 0;
}
/* pad upto 56 bytes of zeroes (should be 32 but we only support 64-bit lengths) */
while (md->whirlpool.curlen < 56) {
md->whirlpool.buf[md->whirlpool.curlen++] = (unsigned char)0;
}
/* store length */
STORE64H(md->whirlpool.length, md->whirlpool.buf+56);
whirlpool_compress(md, md->whirlpool.buf);
/* copy output */
for (i = 0; i < 8; i++) {
STORE64H(md->whirlpool.state[i], out+(8*i));
}
#ifdef LTC_CLEAN_STACK
zeromem(md, sizeof(*md));
#endif
return CRYPT_OK;
}
void calc_whirlpool(char *str,uint8_t *digest,uint8_t *message,int32_t len)
{
int init_hexbytes_noT(char *hexbytes,unsigned char *message,long len);
hash_state md;
whirlpool_init(&md);
whirlpool_process(&md,message,len);
whirlpool_done(&md,digest);
if ( str != 0 )
init_hexbytes_noT(str,digest,64);
}
/**
Self-test the hash
@return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int whirlpool_test(void)
{
#ifndef LTC_TEST
return CRYPT_NOP;
#else
static const struct {
int len;
unsigned char msg[128], hash[64];
} tests[] = {
/* NULL Message */
{
0,
{ 0x00 },
{ 0x19, 0xFA, 0x61, 0xD7, 0x55, 0x22, 0xA4, 0x66, 0x9B, 0x44, 0xE3, 0x9C, 0x1D, 0x2E, 0x17, 0x26,
0xC5, 0x30, 0x23, 0x21, 0x30, 0xD4, 0x07, 0xF8, 0x9A, 0xFE, 0xE0, 0x96, 0x49, 0x97, 0xF7, 0xA7,
0x3E, 0x83, 0xBE, 0x69, 0x8B, 0x28, 0x8F, 0xEB, 0xCF, 0x88, 0xE3, 0xE0, 0x3C, 0x4F, 0x07, 0x57,
0xEA, 0x89, 0x64, 0xE5, 0x9B, 0x63, 0xD9, 0x37, 0x08, 0xB1, 0x38, 0xCC, 0x42, 0xA6, 0x6E, 0xB3 }
},
/* 448-bits of 0 bits */
{
56,
{ 0x00 },
{ 0x0B, 0x3F, 0x53, 0x78, 0xEB, 0xED, 0x2B, 0xF4, 0xD7, 0xBE, 0x3C, 0xFD, 0x81, 0x8C, 0x1B, 0x03,
0xB6, 0xBB, 0x03, 0xD3, 0x46, 0x94, 0x8B, 0x04, 0xF4, 0xF4, 0x0C, 0x72, 0x6F, 0x07, 0x58, 0x70,
0x2A, 0x0F, 0x1E, 0x22, 0x58, 0x80, 0xE3, 0x8D, 0xD5, 0xF6, 0xED, 0x6D, 0xE9, 0xB1, 0xE9, 0x61,
0xE4, 0x9F, 0xC1, 0x31, 0x8D, 0x7C, 0xB7, 0x48, 0x22, 0xF3, 0xD0, 0xE2, 0xE9, 0xA7, 0xE7, 0xB0 }
},
/* 520-bits of 0 bits */
{
65,
{ 0x00 },
{ 0x85, 0xE1, 0x24, 0xC4, 0x41, 0x5B, 0xCF, 0x43, 0x19, 0x54, 0x3E, 0x3A, 0x63, 0xFF, 0x57, 0x1D,
0x09, 0x35, 0x4C, 0xEE, 0xBE, 0xE1, 0xE3, 0x25, 0x30, 0x8C, 0x90, 0x69, 0xF4, 0x3E, 0x2A, 0xE4,
0xD0, 0xE5, 0x1D, 0x4E, 0xB1, 0xE8, 0x64, 0x28, 0x70, 0x19, 0x4E, 0x95, 0x30, 0xD8, 0xD8, 0xAF,
0x65, 0x89, 0xD1, 0xBF, 0x69, 0x49, 0xDD, 0xF9, 0x0A, 0x7F, 0x12, 0x08, 0x62, 0x37, 0x95, 0xB9 }
},
/* 512-bits, leading set */
{
64,
{ 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x10, 0x3E, 0x00, 0x55, 0xA9, 0xB0, 0x90, 0xE1, 0x1C, 0x8F, 0xDD, 0xEB, 0xBA, 0x06, 0xC0, 0x5A,
0xCE, 0x8B, 0x64, 0xB8, 0x96, 0x12, 0x8F, 0x6E, 0xED, 0x30, 0x71, 0xFC, 0xF3, 0xDC, 0x16, 0x94,
0x67, 0x78, 0xE0, 0x72, 0x23, 0x23, 0x3F, 0xD1, 0x80, 0xFC, 0x40, 0xCC, 0xDB, 0x84, 0x30, 0xA6,
0x40, 0xE3, 0x76, 0x34, 0x27, 0x1E, 0x65, 0x5C, 0xA1, 0x67, 0x4E, 0xBF, 0xF5, 0x07, 0xF8, 0xCB }
},
/* 512-bits, leading set of second byte */
{
64,
{ 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x35, 0x7B, 0x42, 0xEA, 0x79, 0xBC, 0x97, 0x86, 0x97, 0x5A, 0x3C, 0x44, 0x70, 0xAA, 0xB2, 0x3E,
0x62, 0x29, 0x79, 0x7B, 0xAD, 0xBD, 0x54, 0x36, 0x5B, 0x54, 0x96, 0xE5, 0x5D, 0x9D, 0xD7, 0x9F,
0xE9, 0x62, 0x4F, 0xB4, 0x22, 0x66, 0x93, 0x0A, 0x62, 0x8E, 0xD4, 0xDB, 0x08, 0xF9, 0xDD, 0x35,
0xEF, 0x1B, 0xE1, 0x04, 0x53, 0xFC, 0x18, 0xF4, 0x2C, 0x7F, 0x5E, 0x1F, 0x9B, 0xAE, 0x55, 0xE0 }
},
/* 512-bits, leading set of last byte */
{
64,
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80 },
{ 0x8B, 0x39, 0x04, 0xDD, 0x19, 0x81, 0x41, 0x26, 0xFD, 0x02, 0x74, 0xAB, 0x49, 0xC5, 0x97, 0xF6,
0xD7, 0x75, 0x33, 0x52, 0xA2, 0xDD, 0x91, 0xFD, 0x8F, 0x9F, 0x54, 0x05, 0x4C, 0x54, 0xBF, 0x0F,
0x06, 0xDB, 0x4F, 0xF7, 0x08, 0xA3, 0xA2, 0x8B, 0xC3, 0x7A, 0x92, 0x1E, 0xEE, 0x11, 0xED, 0x7B,
0x6A, 0x53, 0x79, 0x32, 0xCC, 0x5E, 0x94, 0xEE, 0x1E, 0xA6, 0x57, 0x60, 0x7E, 0x36, 0xC9, 0xF7 }
},
};
int i;
unsigned char tmp[64];
hash_state md;
for (i = 0; i < (int)(sizeof(tests)/sizeof(tests[0])); i++) {
whirlpool_init(&md);
whirlpool_process(&md, (unsigned char *)tests[i].msg, tests[i].len);
whirlpool_done(&md, tmp);
if (XMEMCMP(tmp, tests[i].hash, 64) != 0) {
#if 0
printf("\nFailed test %d\n", i);
for (i = 0; i < 64; ) {
printf("%02x ", tmp[i]);
if (!(++i & 15)) printf("\n");
}
#endif
return CRYPT_FAIL_TESTVECTOR;
}
}
return CRYPT_OK;
#endif
}
#endif
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/whirl/whirl.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:21:44 $ */

586
crypto777/hmac/whirltab.c

@ -0,0 +1,586 @@
/**
@file whirltab.c
LTC_WHIRLPOOL tables, Tom St Denis
*/
#include "tomcrypt_macros.h"
#include <stdint.h>
static const uint64_t sbox0[] = {
CONST64(0x18186018c07830d8), CONST64(0x23238c2305af4626), CONST64(0xc6c63fc67ef991b8), CONST64(0xe8e887e8136fcdfb),
CONST64(0x878726874ca113cb), CONST64(0xb8b8dab8a9626d11), CONST64(0x0101040108050209), CONST64(0x4f4f214f426e9e0d),
CONST64(0x3636d836adee6c9b), CONST64(0xa6a6a2a6590451ff), CONST64(0xd2d26fd2debdb90c), CONST64(0xf5f5f3f5fb06f70e),
CONST64(0x7979f979ef80f296), CONST64(0x6f6fa16f5fcede30), CONST64(0x91917e91fcef3f6d), CONST64(0x52525552aa07a4f8),
CONST64(0x60609d6027fdc047), CONST64(0xbcbccabc89766535), CONST64(0x9b9b569baccd2b37), CONST64(0x8e8e028e048c018a),
CONST64(0xa3a3b6a371155bd2), CONST64(0x0c0c300c603c186c), CONST64(0x7b7bf17bff8af684), CONST64(0x3535d435b5e16a80),
CONST64(0x1d1d741de8693af5), CONST64(0xe0e0a7e05347ddb3), CONST64(0xd7d77bd7f6acb321), CONST64(0xc2c22fc25eed999c),
CONST64(0x2e2eb82e6d965c43), CONST64(0x4b4b314b627a9629), CONST64(0xfefedffea321e15d), CONST64(0x575741578216aed5),
CONST64(0x15155415a8412abd), CONST64(0x7777c1779fb6eee8), CONST64(0x3737dc37a5eb6e92), CONST64(0xe5e5b3e57b56d79e),
CONST64(0x9f9f469f8cd92313), CONST64(0xf0f0e7f0d317fd23), CONST64(0x4a4a354a6a7f9420), CONST64(0xdada4fda9e95a944),
CONST64(0x58587d58fa25b0a2), CONST64(0xc9c903c906ca8fcf), CONST64(0x2929a429558d527c), CONST64(0x0a0a280a5022145a),
CONST64(0xb1b1feb1e14f7f50), CONST64(0xa0a0baa0691a5dc9), CONST64(0x6b6bb16b7fdad614), CONST64(0x85852e855cab17d9),
CONST64(0xbdbdcebd8173673c), CONST64(0x5d5d695dd234ba8f), CONST64(0x1010401080502090), CONST64(0xf4f4f7f4f303f507),
CONST64(0xcbcb0bcb16c08bdd), CONST64(0x3e3ef83eedc67cd3), CONST64(0x0505140528110a2d), CONST64(0x676781671fe6ce78),
CONST64(0xe4e4b7e47353d597), CONST64(0x27279c2725bb4e02), CONST64(0x4141194132588273), CONST64(0x8b8b168b2c9d0ba7),
CONST64(0xa7a7a6a7510153f6), CONST64(0x7d7de97dcf94fab2), CONST64(0x95956e95dcfb3749), CONST64(0xd8d847d88e9fad56),
CONST64(0xfbfbcbfb8b30eb70), CONST64(0xeeee9fee2371c1cd), CONST64(0x7c7ced7cc791f8bb), CONST64(0x6666856617e3cc71),
CONST64(0xdddd53dda68ea77b), CONST64(0x17175c17b84b2eaf), CONST64(0x4747014702468e45), CONST64(0x9e9e429e84dc211a),
CONST64(0xcaca0fca1ec589d4), CONST64(0x2d2db42d75995a58), CONST64(0xbfbfc6bf9179632e), CONST64(0x07071c07381b0e3f),
CONST64(0xadad8ead012347ac), CONST64(0x5a5a755aea2fb4b0), CONST64(0x838336836cb51bef), CONST64(0x3333cc3385ff66b6),
CONST64(0x636391633ff2c65c), CONST64(0x02020802100a0412), CONST64(0xaaaa92aa39384993), CONST64(0x7171d971afa8e2de),
CONST64(0xc8c807c80ecf8dc6), CONST64(0x19196419c87d32d1), CONST64(0x494939497270923b), CONST64(0xd9d943d9869aaf5f),
CONST64(0xf2f2eff2c31df931), CONST64(0xe3e3abe34b48dba8), CONST64(0x5b5b715be22ab6b9), CONST64(0x88881a8834920dbc),
CONST64(0x9a9a529aa4c8293e), CONST64(0x262698262dbe4c0b), CONST64(0x3232c8328dfa64bf), CONST64(0xb0b0fab0e94a7d59),
CONST64(0xe9e983e91b6acff2), CONST64(0x0f0f3c0f78331e77), CONST64(0xd5d573d5e6a6b733), CONST64(0x80803a8074ba1df4),
CONST64(0xbebec2be997c6127), CONST64(0xcdcd13cd26de87eb), CONST64(0x3434d034bde46889), CONST64(0x48483d487a759032),
CONST64(0xffffdbffab24e354), CONST64(0x7a7af57af78ff48d), CONST64(0x90907a90f4ea3d64), CONST64(0x5f5f615fc23ebe9d),
CONST64(0x202080201da0403d), CONST64(0x6868bd6867d5d00f), CONST64(0x1a1a681ad07234ca), CONST64(0xaeae82ae192c41b7),
CONST64(0xb4b4eab4c95e757d), CONST64(0x54544d549a19a8ce), CONST64(0x93937693ece53b7f), CONST64(0x222288220daa442f),
CONST64(0x64648d6407e9c863), CONST64(0xf1f1e3f1db12ff2a), CONST64(0x7373d173bfa2e6cc), CONST64(0x12124812905a2482),
CONST64(0x40401d403a5d807a), CONST64(0x0808200840281048), CONST64(0xc3c32bc356e89b95), CONST64(0xecec97ec337bc5df),
CONST64(0xdbdb4bdb9690ab4d), CONST64(0xa1a1bea1611f5fc0), CONST64(0x8d8d0e8d1c830791), CONST64(0x3d3df43df5c97ac8),
CONST64(0x97976697ccf1335b), CONST64(0x0000000000000000), CONST64(0xcfcf1bcf36d483f9), CONST64(0x2b2bac2b4587566e),
CONST64(0x7676c57697b3ece1), CONST64(0x8282328264b019e6), CONST64(0xd6d67fd6fea9b128), CONST64(0x1b1b6c1bd87736c3),
CONST64(0xb5b5eeb5c15b7774), CONST64(0xafaf86af112943be), CONST64(0x6a6ab56a77dfd41d), CONST64(0x50505d50ba0da0ea),
CONST64(0x45450945124c8a57), CONST64(0xf3f3ebf3cb18fb38), CONST64(0x3030c0309df060ad), CONST64(0xefef9bef2b74c3c4),
CONST64(0x3f3ffc3fe5c37eda), CONST64(0x55554955921caac7), CONST64(0xa2a2b2a2791059db), CONST64(0xeaea8fea0365c9e9),
CONST64(0x656589650fecca6a), CONST64(0xbabad2bab9686903), CONST64(0x2f2fbc2f65935e4a), CONST64(0xc0c027c04ee79d8e),
CONST64(0xdede5fdebe81a160), CONST64(0x1c1c701ce06c38fc), CONST64(0xfdfdd3fdbb2ee746), CONST64(0x4d4d294d52649a1f),
CONST64(0x92927292e4e03976), CONST64(0x7575c9758fbceafa), CONST64(0x06061806301e0c36), CONST64(0x8a8a128a249809ae),
CONST64(0xb2b2f2b2f940794b), CONST64(0xe6e6bfe66359d185), CONST64(0x0e0e380e70361c7e), CONST64(0x1f1f7c1ff8633ee7),
CONST64(0x6262956237f7c455), CONST64(0xd4d477d4eea3b53a), CONST64(0xa8a89aa829324d81), CONST64(0x96966296c4f43152),
CONST64(0xf9f9c3f99b3aef62), CONST64(0xc5c533c566f697a3), CONST64(0x2525942535b14a10), CONST64(0x59597959f220b2ab),
CONST64(0x84842a8454ae15d0), CONST64(0x7272d572b7a7e4c5), CONST64(0x3939e439d5dd72ec), CONST64(0x4c4c2d4c5a619816),
CONST64(0x5e5e655eca3bbc94), CONST64(0x7878fd78e785f09f), CONST64(0x3838e038ddd870e5), CONST64(0x8c8c0a8c14860598),
CONST64(0xd1d163d1c6b2bf17), CONST64(0xa5a5aea5410b57e4), CONST64(0xe2e2afe2434dd9a1), CONST64(0x616199612ff8c24e),
CONST64(0xb3b3f6b3f1457b42), CONST64(0x2121842115a54234), CONST64(0x9c9c4a9c94d62508), CONST64(0x1e1e781ef0663cee),
CONST64(0x4343114322528661), CONST64(0xc7c73bc776fc93b1), CONST64(0xfcfcd7fcb32be54f), CONST64(0x0404100420140824),
CONST64(0x51515951b208a2e3), CONST64(0x99995e99bcc72f25), CONST64(0x6d6da96d4fc4da22), CONST64(0x0d0d340d68391a65),
CONST64(0xfafacffa8335e979), CONST64(0xdfdf5bdfb684a369), CONST64(0x7e7ee57ed79bfca9), CONST64(0x242490243db44819),
CONST64(0x3b3bec3bc5d776fe), CONST64(0xabab96ab313d4b9a), CONST64(0xcece1fce3ed181f0), CONST64(0x1111441188552299),
CONST64(0x8f8f068f0c890383), CONST64(0x4e4e254e4a6b9c04), CONST64(0xb7b7e6b7d1517366), CONST64(0xebeb8beb0b60cbe0),
CONST64(0x3c3cf03cfdcc78c1), CONST64(0x81813e817cbf1ffd), CONST64(0x94946a94d4fe3540), CONST64(0xf7f7fbf7eb0cf31c),
CONST64(0xb9b9deb9a1676f18), CONST64(0x13134c13985f268b), CONST64(0x2c2cb02c7d9c5851), CONST64(0xd3d36bd3d6b8bb05),
CONST64(0xe7e7bbe76b5cd38c), CONST64(0x6e6ea56e57cbdc39), CONST64(0xc4c437c46ef395aa), CONST64(0x03030c03180f061b),
CONST64(0x565645568a13acdc), CONST64(0x44440d441a49885e), CONST64(0x7f7fe17fdf9efea0), CONST64(0xa9a99ea921374f88),
CONST64(0x2a2aa82a4d825467), CONST64(0xbbbbd6bbb16d6b0a), CONST64(0xc1c123c146e29f87), CONST64(0x53535153a202a6f1),
CONST64(0xdcdc57dcae8ba572), CONST64(0x0b0b2c0b58271653), CONST64(0x9d9d4e9d9cd32701), CONST64(0x6c6cad6c47c1d82b),
CONST64(0x3131c43195f562a4), CONST64(0x7474cd7487b9e8f3), CONST64(0xf6f6fff6e309f115), CONST64(0x464605460a438c4c),
CONST64(0xacac8aac092645a5), CONST64(0x89891e893c970fb5), CONST64(0x14145014a04428b4), CONST64(0xe1e1a3e15b42dfba),
CONST64(0x16165816b04e2ca6), CONST64(0x3a3ae83acdd274f7), CONST64(0x6969b9696fd0d206), CONST64(0x09092409482d1241),
CONST64(0x7070dd70a7ade0d7), CONST64(0xb6b6e2b6d954716f), CONST64(0xd0d067d0ceb7bd1e), CONST64(0xeded93ed3b7ec7d6),
CONST64(0xcccc17cc2edb85e2), CONST64(0x424215422a578468), CONST64(0x98985a98b4c22d2c), CONST64(0xa4a4aaa4490e55ed),
CONST64(0x2828a0285d885075), CONST64(0x5c5c6d5cda31b886), CONST64(0xf8f8c7f8933fed6b), CONST64(0x8686228644a411c2)
};
#ifdef LTC_SMALL_CODE
#define SB0(x) sbox0[x]
#define SB1(x) ROR64c(sbox0[x], 8)
#define SB2(x) ROR64c(sbox0[x], 16)
#define SB3(x) ROR64c(sbox0[x], 24)
#define SB4(x) ROR64c(sbox0[x], 32)
#define SB5(x) ROR64c(sbox0[x], 40)
#define SB6(x) ROR64c(sbox0[x], 48)
#define SB7(x) ROR64c(sbox0[x], 56)
#else
#define SB0(x) sbox0[x]
#define SB1(x) sbox1[x]
#define SB2(x) sbox2[x]
#define SB3(x) sbox3[x]
#define SB4(x) sbox4[x]
#define SB5(x) sbox5[x]
#define SB6(x) sbox6[x]
#define SB7(x) sbox7[x]
static const ulong64 sbox1[] = {
CONST64(0xd818186018c07830), CONST64(0x2623238c2305af46), CONST64(0xb8c6c63fc67ef991), CONST64(0xfbe8e887e8136fcd),
CONST64(0xcb878726874ca113), CONST64(0x11b8b8dab8a9626d), CONST64(0x0901010401080502), CONST64(0x0d4f4f214f426e9e),
CONST64(0x9b3636d836adee6c), CONST64(0xffa6a6a2a6590451), CONST64(0x0cd2d26fd2debdb9), CONST64(0x0ef5f5f3f5fb06f7),
CONST64(0x967979f979ef80f2), CONST64(0x306f6fa16f5fcede), CONST64(0x6d91917e91fcef3f), CONST64(0xf852525552aa07a4),
CONST64(0x4760609d6027fdc0), CONST64(0x35bcbccabc897665), CONST64(0x379b9b569baccd2b), CONST64(0x8a8e8e028e048c01),
CONST64(0xd2a3a3b6a371155b), CONST64(0x6c0c0c300c603c18), CONST64(0x847b7bf17bff8af6), CONST64(0x803535d435b5e16a),
CONST64(0xf51d1d741de8693a), CONST64(0xb3e0e0a7e05347dd), CONST64(0x21d7d77bd7f6acb3), CONST64(0x9cc2c22fc25eed99),
CONST64(0x432e2eb82e6d965c), CONST64(0x294b4b314b627a96), CONST64(0x5dfefedffea321e1), CONST64(0xd5575741578216ae),
CONST64(0xbd15155415a8412a), CONST64(0xe87777c1779fb6ee), CONST64(0x923737dc37a5eb6e), CONST64(0x9ee5e5b3e57b56d7),
CONST64(0x139f9f469f8cd923), CONST64(0x23f0f0e7f0d317fd), CONST64(0x204a4a354a6a7f94), CONST64(0x44dada4fda9e95a9),
CONST64(0xa258587d58fa25b0), CONST64(0xcfc9c903c906ca8f), CONST64(0x7c2929a429558d52), CONST64(0x5a0a0a280a502214),
CONST64(0x50b1b1feb1e14f7f), CONST64(0xc9a0a0baa0691a5d), CONST64(0x146b6bb16b7fdad6), CONST64(0xd985852e855cab17),
CONST64(0x3cbdbdcebd817367), CONST64(0x8f5d5d695dd234ba), CONST64(0x9010104010805020), CONST64(0x07f4f4f7f4f303f5),
CONST64(0xddcbcb0bcb16c08b), CONST64(0xd33e3ef83eedc67c), CONST64(0x2d0505140528110a), CONST64(0x78676781671fe6ce),
CONST64(0x97e4e4b7e47353d5), CONST64(0x0227279c2725bb4e), CONST64(0x7341411941325882), CONST64(0xa78b8b168b2c9d0b),
CONST64(0xf6a7a7a6a7510153), CONST64(0xb27d7de97dcf94fa), CONST64(0x4995956e95dcfb37), CONST64(0x56d8d847d88e9fad),
CONST64(0x70fbfbcbfb8b30eb), CONST64(0xcdeeee9fee2371c1), CONST64(0xbb7c7ced7cc791f8), CONST64(0x716666856617e3cc),
CONST64(0x7bdddd53dda68ea7), CONST64(0xaf17175c17b84b2e), CONST64(0x454747014702468e), CONST64(0x1a9e9e429e84dc21),
CONST64(0xd4caca0fca1ec589), CONST64(0x582d2db42d75995a), CONST64(0x2ebfbfc6bf917963), CONST64(0x3f07071c07381b0e),
CONST64(0xacadad8ead012347), CONST64(0xb05a5a755aea2fb4), CONST64(0xef838336836cb51b), CONST64(0xb63333cc3385ff66),
CONST64(0x5c636391633ff2c6), CONST64(0x1202020802100a04), CONST64(0x93aaaa92aa393849), CONST64(0xde7171d971afa8e2),
CONST64(0xc6c8c807c80ecf8d), CONST64(0xd119196419c87d32), CONST64(0x3b49493949727092), CONST64(0x5fd9d943d9869aaf),
CONST64(0x31f2f2eff2c31df9), CONST64(0xa8e3e3abe34b48db), CONST64(0xb95b5b715be22ab6), CONST64(0xbc88881a8834920d),
CONST64(0x3e9a9a529aa4c829), CONST64(0x0b262698262dbe4c), CONST64(0xbf3232c8328dfa64), CONST64(0x59b0b0fab0e94a7d),
CONST64(0xf2e9e983e91b6acf), CONST64(0x770f0f3c0f78331e), CONST64(0x33d5d573d5e6a6b7), CONST64(0xf480803a8074ba1d),
CONST64(0x27bebec2be997c61), CONST64(0xebcdcd13cd26de87), CONST64(0x893434d034bde468), CONST64(0x3248483d487a7590),
CONST64(0x54ffffdbffab24e3), CONST64(0x8d7a7af57af78ff4), CONST64(0x6490907a90f4ea3d), CONST64(0x9d5f5f615fc23ebe),
CONST64(0x3d202080201da040), CONST64(0x0f6868bd6867d5d0), CONST64(0xca1a1a681ad07234), CONST64(0xb7aeae82ae192c41),
CONST64(0x7db4b4eab4c95e75), CONST64(0xce54544d549a19a8), CONST64(0x7f93937693ece53b), CONST64(0x2f222288220daa44),
CONST64(0x6364648d6407e9c8), CONST64(0x2af1f1e3f1db12ff), CONST64(0xcc7373d173bfa2e6), CONST64(0x8212124812905a24),
CONST64(0x7a40401d403a5d80), CONST64(0x4808082008402810), CONST64(0x95c3c32bc356e89b), CONST64(0xdfecec97ec337bc5),
CONST64(0x4ddbdb4bdb9690ab), CONST64(0xc0a1a1bea1611f5f), CONST64(0x918d8d0e8d1c8307), CONST64(0xc83d3df43df5c97a),
CONST64(0x5b97976697ccf133), CONST64(0x0000000000000000), CONST64(0xf9cfcf1bcf36d483), CONST64(0x6e2b2bac2b458756),
CONST64(0xe17676c57697b3ec), CONST64(0xe68282328264b019), CONST64(0x28d6d67fd6fea9b1), CONST64(0xc31b1b6c1bd87736),
CONST64(0x74b5b5eeb5c15b77), CONST64(0xbeafaf86af112943), CONST64(0x1d6a6ab56a77dfd4), CONST64(0xea50505d50ba0da0),
CONST64(0x5745450945124c8a), CONST64(0x38f3f3ebf3cb18fb), CONST64(0xad3030c0309df060), CONST64(0xc4efef9bef2b74c3),
CONST64(0xda3f3ffc3fe5c37e), CONST64(0xc755554955921caa), CONST64(0xdba2a2b2a2791059), CONST64(0xe9eaea8fea0365c9),
CONST64(0x6a656589650fecca), CONST64(0x03babad2bab96869), CONST64(0x4a2f2fbc2f65935e), CONST64(0x8ec0c027c04ee79d),
CONST64(0x60dede5fdebe81a1), CONST64(0xfc1c1c701ce06c38), CONST64(0x46fdfdd3fdbb2ee7), CONST64(0x1f4d4d294d52649a),
CONST64(0x7692927292e4e039), CONST64(0xfa7575c9758fbcea), CONST64(0x3606061806301e0c), CONST64(0xae8a8a128a249809),
CONST64(0x4bb2b2f2b2f94079), CONST64(0x85e6e6bfe66359d1), CONST64(0x7e0e0e380e70361c), CONST64(0xe71f1f7c1ff8633e),
CONST64(0x556262956237f7c4), CONST64(0x3ad4d477d4eea3b5), CONST64(0x81a8a89aa829324d), CONST64(0x5296966296c4f431),
CONST64(0x62f9f9c3f99b3aef), CONST64(0xa3c5c533c566f697), CONST64(0x102525942535b14a), CONST64(0xab59597959f220b2),
CONST64(0xd084842a8454ae15), CONST64(0xc57272d572b7a7e4), CONST64(0xec3939e439d5dd72), CONST64(0x164c4c2d4c5a6198),
CONST64(0x945e5e655eca3bbc), CONST64(0x9f7878fd78e785f0), CONST64(0xe53838e038ddd870), CONST64(0x988c8c0a8c148605),
CONST64(0x17d1d163d1c6b2bf), CONST64(0xe4a5a5aea5410b57), CONST64(0xa1e2e2afe2434dd9), CONST64(0x4e616199612ff8c2),
CONST64(0x42b3b3f6b3f1457b), CONST64(0x342121842115a542), CONST64(0x089c9c4a9c94d625), CONST64(0xee1e1e781ef0663c),
CONST64(0x6143431143225286), CONST64(0xb1c7c73bc776fc93), CONST64(0x4ffcfcd7fcb32be5), CONST64(0x2404041004201408),
CONST64(0xe351515951b208a2), CONST64(0x2599995e99bcc72f), CONST64(0x226d6da96d4fc4da), CONST64(0x650d0d340d68391a),
CONST64(0x79fafacffa8335e9), CONST64(0x69dfdf5bdfb684a3), CONST64(0xa97e7ee57ed79bfc), CONST64(0x19242490243db448),
CONST64(0xfe3b3bec3bc5d776), CONST64(0x9aabab96ab313d4b), CONST64(0xf0cece1fce3ed181), CONST64(0x9911114411885522),
CONST64(0x838f8f068f0c8903), CONST64(0x044e4e254e4a6b9c), CONST64(0x66b7b7e6b7d15173), CONST64(0xe0ebeb8beb0b60cb),
CONST64(0xc13c3cf03cfdcc78), CONST64(0xfd81813e817cbf1f), CONST64(0x4094946a94d4fe35), CONST64(0x1cf7f7fbf7eb0cf3),
CONST64(0x18b9b9deb9a1676f), CONST64(0x8b13134c13985f26), CONST64(0x512c2cb02c7d9c58), CONST64(0x05d3d36bd3d6b8bb),
CONST64(0x8ce7e7bbe76b5cd3), CONST64(0x396e6ea56e57cbdc), CONST64(0xaac4c437c46ef395), CONST64(0x1b03030c03180f06),
CONST64(0xdc565645568a13ac), CONST64(0x5e44440d441a4988), CONST64(0xa07f7fe17fdf9efe), CONST64(0x88a9a99ea921374f),
CONST64(0x672a2aa82a4d8254), CONST64(0x0abbbbd6bbb16d6b), CONST64(0x87c1c123c146e29f), CONST64(0xf153535153a202a6),
CONST64(0x72dcdc57dcae8ba5), CONST64(0x530b0b2c0b582716), CONST64(0x019d9d4e9d9cd327), CONST64(0x2b6c6cad6c47c1d8),
CONST64(0xa43131c43195f562), CONST64(0xf37474cd7487b9e8), CONST64(0x15f6f6fff6e309f1), CONST64(0x4c464605460a438c),
CONST64(0xa5acac8aac092645), CONST64(0xb589891e893c970f), CONST64(0xb414145014a04428), CONST64(0xbae1e1a3e15b42df),
CONST64(0xa616165816b04e2c), CONST64(0xf73a3ae83acdd274), CONST64(0x066969b9696fd0d2), CONST64(0x4109092409482d12),
CONST64(0xd77070dd70a7ade0), CONST64(0x6fb6b6e2b6d95471), CONST64(0x1ed0d067d0ceb7bd), CONST64(0xd6eded93ed3b7ec7),
CONST64(0xe2cccc17cc2edb85), CONST64(0x68424215422a5784), CONST64(0x2c98985a98b4c22d), CONST64(0xeda4a4aaa4490e55),
CONST64(0x752828a0285d8850), CONST64(0x865c5c6d5cda31b8), CONST64(0x6bf8f8c7f8933fed), CONST64(0xc28686228644a411)
};
static const ulong64 sbox2[] = {
CONST64(0x30d818186018c078), CONST64(0x462623238c2305af), CONST64(0x91b8c6c63fc67ef9), CONST64(0xcdfbe8e887e8136f),
CONST64(0x13cb878726874ca1), CONST64(0x6d11b8b8dab8a962), CONST64(0x0209010104010805), CONST64(0x9e0d4f4f214f426e),
CONST64(0x6c9b3636d836adee), CONST64(0x51ffa6a6a2a65904), CONST64(0xb90cd2d26fd2debd), CONST64(0xf70ef5f5f3f5fb06),
CONST64(0xf2967979f979ef80), CONST64(0xde306f6fa16f5fce), CONST64(0x3f6d91917e91fcef), CONST64(0xa4f852525552aa07),
CONST64(0xc04760609d6027fd), CONST64(0x6535bcbccabc8976), CONST64(0x2b379b9b569baccd), CONST64(0x018a8e8e028e048c),
CONST64(0x5bd2a3a3b6a37115), CONST64(0x186c0c0c300c603c), CONST64(0xf6847b7bf17bff8a), CONST64(0x6a803535d435b5e1),
CONST64(0x3af51d1d741de869), CONST64(0xddb3e0e0a7e05347), CONST64(0xb321d7d77bd7f6ac), CONST64(0x999cc2c22fc25eed),
CONST64(0x5c432e2eb82e6d96), CONST64(0x96294b4b314b627a), CONST64(0xe15dfefedffea321), CONST64(0xaed5575741578216),
CONST64(0x2abd15155415a841), CONST64(0xeee87777c1779fb6), CONST64(0x6e923737dc37a5eb), CONST64(0xd79ee5e5b3e57b56),
CONST64(0x23139f9f469f8cd9), CONST64(0xfd23f0f0e7f0d317), CONST64(0x94204a4a354a6a7f), CONST64(0xa944dada4fda9e95),
CONST64(0xb0a258587d58fa25), CONST64(0x8fcfc9c903c906ca), CONST64(0x527c2929a429558d), CONST64(0x145a0a0a280a5022),
CONST64(0x7f50b1b1feb1e14f), CONST64(0x5dc9a0a0baa0691a), CONST64(0xd6146b6bb16b7fda), CONST64(0x17d985852e855cab),
CONST64(0x673cbdbdcebd8173), CONST64(0xba8f5d5d695dd234), CONST64(0x2090101040108050), CONST64(0xf507f4f4f7f4f303),
CONST64(0x8bddcbcb0bcb16c0), CONST64(0x7cd33e3ef83eedc6), CONST64(0x0a2d050514052811), CONST64(0xce78676781671fe6),
CONST64(0xd597e4e4b7e47353), CONST64(0x4e0227279c2725bb), CONST64(0x8273414119413258), CONST64(0x0ba78b8b168b2c9d),
CONST64(0x53f6a7a7a6a75101), CONST64(0xfab27d7de97dcf94), CONST64(0x374995956e95dcfb), CONST64(0xad56d8d847d88e9f),
CONST64(0xeb70fbfbcbfb8b30), CONST64(0xc1cdeeee9fee2371), CONST64(0xf8bb7c7ced7cc791), CONST64(0xcc716666856617e3),
CONST64(0xa77bdddd53dda68e), CONST64(0x2eaf17175c17b84b), CONST64(0x8e45474701470246), CONST64(0x211a9e9e429e84dc),
CONST64(0x89d4caca0fca1ec5), CONST64(0x5a582d2db42d7599), CONST64(0x632ebfbfc6bf9179), CONST64(0x0e3f07071c07381b),
CONST64(0x47acadad8ead0123), CONST64(0xb4b05a5a755aea2f), CONST64(0x1bef838336836cb5), CONST64(0x66b63333cc3385ff),
CONST64(0xc65c636391633ff2), CONST64(0x041202020802100a), CONST64(0x4993aaaa92aa3938), CONST64(0xe2de7171d971afa8),
CONST64(0x8dc6c8c807c80ecf), CONST64(0x32d119196419c87d), CONST64(0x923b494939497270), CONST64(0xaf5fd9d943d9869a),
CONST64(0xf931f2f2eff2c31d), CONST64(0xdba8e3e3abe34b48), CONST64(0xb6b95b5b715be22a), CONST64(0x0dbc88881a883492),
CONST64(0x293e9a9a529aa4c8), CONST64(0x4c0b262698262dbe), CONST64(0x64bf3232c8328dfa), CONST64(0x7d59b0b0fab0e94a),
CONST64(0xcff2e9e983e91b6a), CONST64(0x1e770f0f3c0f7833), CONST64(0xb733d5d573d5e6a6), CONST64(0x1df480803a8074ba),
CONST64(0x6127bebec2be997c), CONST64(0x87ebcdcd13cd26de), CONST64(0x68893434d034bde4), CONST64(0x903248483d487a75),
CONST64(0xe354ffffdbffab24), CONST64(0xf48d7a7af57af78f), CONST64(0x3d6490907a90f4ea), CONST64(0xbe9d5f5f615fc23e),
CONST64(0x403d202080201da0), CONST64(0xd00f6868bd6867d5), CONST64(0x34ca1a1a681ad072), CONST64(0x41b7aeae82ae192c),
CONST64(0x757db4b4eab4c95e), CONST64(0xa8ce54544d549a19), CONST64(0x3b7f93937693ece5), CONST64(0x442f222288220daa),
CONST64(0xc86364648d6407e9), CONST64(0xff2af1f1e3f1db12), CONST64(0xe6cc7373d173bfa2), CONST64(0x248212124812905a),
CONST64(0x807a40401d403a5d), CONST64(0x1048080820084028), CONST64(0x9b95c3c32bc356e8), CONST64(0xc5dfecec97ec337b),
CONST64(0xab4ddbdb4bdb9690), CONST64(0x5fc0a1a1bea1611f), CONST64(0x07918d8d0e8d1c83), CONST64(0x7ac83d3df43df5c9),
CONST64(0x335b97976697ccf1), CONST64(0x0000000000000000), CONST64(0x83f9cfcf1bcf36d4), CONST64(0x566e2b2bac2b4587),
CONST64(0xece17676c57697b3), CONST64(0x19e68282328264b0), CONST64(0xb128d6d67fd6fea9), CONST64(0x36c31b1b6c1bd877),
CONST64(0x7774b5b5eeb5c15b), CONST64(0x43beafaf86af1129), CONST64(0xd41d6a6ab56a77df), CONST64(0xa0ea50505d50ba0d),
CONST64(0x8a5745450945124c), CONST64(0xfb38f3f3ebf3cb18), CONST64(0x60ad3030c0309df0), CONST64(0xc3c4efef9bef2b74),
CONST64(0x7eda3f3ffc3fe5c3), CONST64(0xaac755554955921c), CONST64(0x59dba2a2b2a27910), CONST64(0xc9e9eaea8fea0365),
CONST64(0xca6a656589650fec), CONST64(0x6903babad2bab968), CONST64(0x5e4a2f2fbc2f6593), CONST64(0x9d8ec0c027c04ee7),
CONST64(0xa160dede5fdebe81), CONST64(0x38fc1c1c701ce06c), CONST64(0xe746fdfdd3fdbb2e), CONST64(0x9a1f4d4d294d5264),
CONST64(0x397692927292e4e0), CONST64(0xeafa7575c9758fbc), CONST64(0x0c3606061806301e), CONST64(0x09ae8a8a128a2498),
CONST64(0x794bb2b2f2b2f940), CONST64(0xd185e6e6bfe66359), CONST64(0x1c7e0e0e380e7036), CONST64(0x3ee71f1f7c1ff863),
CONST64(0xc4556262956237f7), CONST64(0xb53ad4d477d4eea3), CONST64(0x4d81a8a89aa82932), CONST64(0x315296966296c4f4),
CONST64(0xef62f9f9c3f99b3a), CONST64(0x97a3c5c533c566f6), CONST64(0x4a102525942535b1), CONST64(0xb2ab59597959f220),
CONST64(0x15d084842a8454ae), CONST64(0xe4c57272d572b7a7), CONST64(0x72ec3939e439d5dd), CONST64(0x98164c4c2d4c5a61),
CONST64(0xbc945e5e655eca3b), CONST64(0xf09f7878fd78e785), CONST64(0x70e53838e038ddd8), CONST64(0x05988c8c0a8c1486),
CONST64(0xbf17d1d163d1c6b2), CONST64(0x57e4a5a5aea5410b), CONST64(0xd9a1e2e2afe2434d), CONST64(0xc24e616199612ff8),
CONST64(0x7b42b3b3f6b3f145), CONST64(0x42342121842115a5), CONST64(0x25089c9c4a9c94d6), CONST64(0x3cee1e1e781ef066),
CONST64(0x8661434311432252), CONST64(0x93b1c7c73bc776fc), CONST64(0xe54ffcfcd7fcb32b), CONST64(0x0824040410042014),
CONST64(0xa2e351515951b208), CONST64(0x2f2599995e99bcc7), CONST64(0xda226d6da96d4fc4), CONST64(0x1a650d0d340d6839),
CONST64(0xe979fafacffa8335), CONST64(0xa369dfdf5bdfb684), CONST64(0xfca97e7ee57ed79b), CONST64(0x4819242490243db4),
CONST64(0x76fe3b3bec3bc5d7), CONST64(0x4b9aabab96ab313d), CONST64(0x81f0cece1fce3ed1), CONST64(0x2299111144118855),
CONST64(0x03838f8f068f0c89), CONST64(0x9c044e4e254e4a6b), CONST64(0x7366b7b7e6b7d151), CONST64(0xcbe0ebeb8beb0b60),
CONST64(0x78c13c3cf03cfdcc), CONST64(0x1ffd81813e817cbf), CONST64(0x354094946a94d4fe), CONST64(0xf31cf7f7fbf7eb0c),
CONST64(0x6f18b9b9deb9a167), CONST64(0x268b13134c13985f), CONST64(0x58512c2cb02c7d9c), CONST64(0xbb05d3d36bd3d6b8),
CONST64(0xd38ce7e7bbe76b5c), CONST64(0xdc396e6ea56e57cb), CONST64(0x95aac4c437c46ef3), CONST64(0x061b03030c03180f),
CONST64(0xacdc565645568a13), CONST64(0x885e44440d441a49), CONST64(0xfea07f7fe17fdf9e), CONST64(0x4f88a9a99ea92137),
CONST64(0x54672a2aa82a4d82), CONST64(0x6b0abbbbd6bbb16d), CONST64(0x9f87c1c123c146e2), CONST64(0xa6f153535153a202),
CONST64(0xa572dcdc57dcae8b), CONST64(0x16530b0b2c0b5827), CONST64(0x27019d9d4e9d9cd3), CONST64(0xd82b6c6cad6c47c1),
CONST64(0x62a43131c43195f5), CONST64(0xe8f37474cd7487b9), CONST64(0xf115f6f6fff6e309), CONST64(0x8c4c464605460a43),
CONST64(0x45a5acac8aac0926), CONST64(0x0fb589891e893c97), CONST64(0x28b414145014a044), CONST64(0xdfbae1e1a3e15b42),
CONST64(0x2ca616165816b04e), CONST64(0x74f73a3ae83acdd2), CONST64(0xd2066969b9696fd0), CONST64(0x124109092409482d),
CONST64(0xe0d77070dd70a7ad), CONST64(0x716fb6b6e2b6d954), CONST64(0xbd1ed0d067d0ceb7), CONST64(0xc7d6eded93ed3b7e),
CONST64(0x85e2cccc17cc2edb), CONST64(0x8468424215422a57), CONST64(0x2d2c98985a98b4c2), CONST64(0x55eda4a4aaa4490e),
CONST64(0x50752828a0285d88), CONST64(0xb8865c5c6d5cda31), CONST64(0xed6bf8f8c7f8933f), CONST64(0x11c28686228644a4)
};
static const ulong64 sbox3[] = {
CONST64(0x7830d818186018c0), CONST64(0xaf462623238c2305), CONST64(0xf991b8c6c63fc67e), CONST64(0x6fcdfbe8e887e813),
CONST64(0xa113cb878726874c), CONST64(0x626d11b8b8dab8a9), CONST64(0x0502090101040108), CONST64(0x6e9e0d4f4f214f42),
CONST64(0xee6c9b3636d836ad), CONST64(0x0451ffa6a6a2a659), CONST64(0xbdb90cd2d26fd2de), CONST64(0x06f70ef5f5f3f5fb),
CONST64(0x80f2967979f979ef), CONST64(0xcede306f6fa16f5f), CONST64(0xef3f6d91917e91fc), CONST64(0x07a4f852525552aa),
CONST64(0xfdc04760609d6027), CONST64(0x766535bcbccabc89), CONST64(0xcd2b379b9b569bac), CONST64(0x8c018a8e8e028e04),
CONST64(0x155bd2a3a3b6a371), CONST64(0x3c186c0c0c300c60), CONST64(0x8af6847b7bf17bff), CONST64(0xe16a803535d435b5),
CONST64(0x693af51d1d741de8), CONST64(0x47ddb3e0e0a7e053), CONST64(0xacb321d7d77bd7f6), CONST64(0xed999cc2c22fc25e),
CONST64(0x965c432e2eb82e6d), CONST64(0x7a96294b4b314b62), CONST64(0x21e15dfefedffea3), CONST64(0x16aed55757415782),
CONST64(0x412abd15155415a8), CONST64(0xb6eee87777c1779f), CONST64(0xeb6e923737dc37a5), CONST64(0x56d79ee5e5b3e57b),
CONST64(0xd923139f9f469f8c), CONST64(0x17fd23f0f0e7f0d3), CONST64(0x7f94204a4a354a6a), CONST64(0x95a944dada4fda9e),
CONST64(0x25b0a258587d58fa), CONST64(0xca8fcfc9c903c906), CONST64(0x8d527c2929a42955), CONST64(0x22145a0a0a280a50),
CONST64(0x4f7f50b1b1feb1e1), CONST64(0x1a5dc9a0a0baa069), CONST64(0xdad6146b6bb16b7f), CONST64(0xab17d985852e855c),
CONST64(0x73673cbdbdcebd81), CONST64(0x34ba8f5d5d695dd2), CONST64(0x5020901010401080), CONST64(0x03f507f4f4f7f4f3),
CONST64(0xc08bddcbcb0bcb16), CONST64(0xc67cd33e3ef83eed), CONST64(0x110a2d0505140528), CONST64(0xe6ce78676781671f),
CONST64(0x53d597e4e4b7e473), CONST64(0xbb4e0227279c2725), CONST64(0x5882734141194132), CONST64(0x9d0ba78b8b168b2c),
CONST64(0x0153f6a7a7a6a751), CONST64(0x94fab27d7de97dcf), CONST64(0xfb374995956e95dc), CONST64(0x9fad56d8d847d88e),
CONST64(0x30eb70fbfbcbfb8b), CONST64(0x71c1cdeeee9fee23), CONST64(0x91f8bb7c7ced7cc7), CONST64(0xe3cc716666856617),
CONST64(0x8ea77bdddd53dda6), CONST64(0x4b2eaf17175c17b8), CONST64(0x468e454747014702), CONST64(0xdc211a9e9e429e84),
CONST64(0xc589d4caca0fca1e), CONST64(0x995a582d2db42d75), CONST64(0x79632ebfbfc6bf91), CONST64(0x1b0e3f07071c0738),
CONST64(0x2347acadad8ead01), CONST64(0x2fb4b05a5a755aea), CONST64(0xb51bef838336836c), CONST64(0xff66b63333cc3385),
CONST64(0xf2c65c636391633f), CONST64(0x0a04120202080210), CONST64(0x384993aaaa92aa39), CONST64(0xa8e2de7171d971af),
CONST64(0xcf8dc6c8c807c80e), CONST64(0x7d32d119196419c8), CONST64(0x70923b4949394972), CONST64(0x9aaf5fd9d943d986),
CONST64(0x1df931f2f2eff2c3), CONST64(0x48dba8e3e3abe34b), CONST64(0x2ab6b95b5b715be2), CONST64(0x920dbc88881a8834),
CONST64(0xc8293e9a9a529aa4), CONST64(0xbe4c0b262698262d), CONST64(0xfa64bf3232c8328d), CONST64(0x4a7d59b0b0fab0e9),
CONST64(0x6acff2e9e983e91b), CONST64(0x331e770f0f3c0f78), CONST64(0xa6b733d5d573d5e6), CONST64(0xba1df480803a8074),
CONST64(0x7c6127bebec2be99), CONST64(0xde87ebcdcd13cd26), CONST64(0xe468893434d034bd), CONST64(0x75903248483d487a),
CONST64(0x24e354ffffdbffab), CONST64(0x8ff48d7a7af57af7), CONST64(0xea3d6490907a90f4), CONST64(0x3ebe9d5f5f615fc2),
CONST64(0xa0403d202080201d), CONST64(0xd5d00f6868bd6867), CONST64(0x7234ca1a1a681ad0), CONST64(0x2c41b7aeae82ae19),
CONST64(0x5e757db4b4eab4c9), CONST64(0x19a8ce54544d549a), CONST64(0xe53b7f93937693ec), CONST64(0xaa442f222288220d),
CONST64(0xe9c86364648d6407), CONST64(0x12ff2af1f1e3f1db), CONST64(0xa2e6cc7373d173bf), CONST64(0x5a24821212481290),
CONST64(0x5d807a40401d403a), CONST64(0x2810480808200840), CONST64(0xe89b95c3c32bc356), CONST64(0x7bc5dfecec97ec33),
CONST64(0x90ab4ddbdb4bdb96), CONST64(0x1f5fc0a1a1bea161), CONST64(0x8307918d8d0e8d1c), CONST64(0xc97ac83d3df43df5),
CONST64(0xf1335b97976697cc), CONST64(0x0000000000000000), CONST64(0xd483f9cfcf1bcf36), CONST64(0x87566e2b2bac2b45),
CONST64(0xb3ece17676c57697), CONST64(0xb019e68282328264), CONST64(0xa9b128d6d67fd6fe), CONST64(0x7736c31b1b6c1bd8),
CONST64(0x5b7774b5b5eeb5c1), CONST64(0x2943beafaf86af11), CONST64(0xdfd41d6a6ab56a77), CONST64(0x0da0ea50505d50ba),
CONST64(0x4c8a574545094512), CONST64(0x18fb38f3f3ebf3cb), CONST64(0xf060ad3030c0309d), CONST64(0x74c3c4efef9bef2b),
CONST64(0xc37eda3f3ffc3fe5), CONST64(0x1caac75555495592), CONST64(0x1059dba2a2b2a279), CONST64(0x65c9e9eaea8fea03),
CONST64(0xecca6a656589650f), CONST64(0x686903babad2bab9), CONST64(0x935e4a2f2fbc2f65), CONST64(0xe79d8ec0c027c04e),
CONST64(0x81a160dede5fdebe), CONST64(0x6c38fc1c1c701ce0), CONST64(0x2ee746fdfdd3fdbb), CONST64(0x649a1f4d4d294d52),
CONST64(0xe0397692927292e4), CONST64(0xbceafa7575c9758f), CONST64(0x1e0c360606180630), CONST64(0x9809ae8a8a128a24),
CONST64(0x40794bb2b2f2b2f9), CONST64(0x59d185e6e6bfe663), CONST64(0x361c7e0e0e380e70), CONST64(0x633ee71f1f7c1ff8),
CONST64(0xf7c4556262956237), CONST64(0xa3b53ad4d477d4ee), CONST64(0x324d81a8a89aa829), CONST64(0xf4315296966296c4),
CONST64(0x3aef62f9f9c3f99b), CONST64(0xf697a3c5c533c566), CONST64(0xb14a102525942535), CONST64(0x20b2ab59597959f2),
CONST64(0xae15d084842a8454), CONST64(0xa7e4c57272d572b7), CONST64(0xdd72ec3939e439d5), CONST64(0x6198164c4c2d4c5a),
CONST64(0x3bbc945e5e655eca), CONST64(0x85f09f7878fd78e7), CONST64(0xd870e53838e038dd), CONST64(0x8605988c8c0a8c14),
CONST64(0xb2bf17d1d163d1c6), CONST64(0x0b57e4a5a5aea541), CONST64(0x4dd9a1e2e2afe243), CONST64(0xf8c24e616199612f),
CONST64(0x457b42b3b3f6b3f1), CONST64(0xa542342121842115), CONST64(0xd625089c9c4a9c94), CONST64(0x663cee1e1e781ef0),
CONST64(0x5286614343114322), CONST64(0xfc93b1c7c73bc776), CONST64(0x2be54ffcfcd7fcb3), CONST64(0x1408240404100420),
CONST64(0x08a2e351515951b2), CONST64(0xc72f2599995e99bc), CONST64(0xc4da226d6da96d4f), CONST64(0x391a650d0d340d68),
CONST64(0x35e979fafacffa83), CONST64(0x84a369dfdf5bdfb6), CONST64(0x9bfca97e7ee57ed7), CONST64(0xb44819242490243d),
CONST64(0xd776fe3b3bec3bc5), CONST64(0x3d4b9aabab96ab31), CONST64(0xd181f0cece1fce3e), CONST64(0x5522991111441188),
CONST64(0x8903838f8f068f0c), CONST64(0x6b9c044e4e254e4a), CONST64(0x517366b7b7e6b7d1), CONST64(0x60cbe0ebeb8beb0b),
CONST64(0xcc78c13c3cf03cfd), CONST64(0xbf1ffd81813e817c), CONST64(0xfe354094946a94d4), CONST64(0x0cf31cf7f7fbf7eb),
CONST64(0x676f18b9b9deb9a1), CONST64(0x5f268b13134c1398), CONST64(0x9c58512c2cb02c7d), CONST64(0xb8bb05d3d36bd3d6),
CONST64(0x5cd38ce7e7bbe76b), CONST64(0xcbdc396e6ea56e57), CONST64(0xf395aac4c437c46e), CONST64(0x0f061b03030c0318),
CONST64(0x13acdc565645568a), CONST64(0x49885e44440d441a), CONST64(0x9efea07f7fe17fdf), CONST64(0x374f88a9a99ea921),
CONST64(0x8254672a2aa82a4d), CONST64(0x6d6b0abbbbd6bbb1), CONST64(0xe29f87c1c123c146), CONST64(0x02a6f153535153a2),
CONST64(0x8ba572dcdc57dcae), CONST64(0x2716530b0b2c0b58), CONST64(0xd327019d9d4e9d9c), CONST64(0xc1d82b6c6cad6c47),
CONST64(0xf562a43131c43195), CONST64(0xb9e8f37474cd7487), CONST64(0x09f115f6f6fff6e3), CONST64(0x438c4c464605460a),
CONST64(0x2645a5acac8aac09), CONST64(0x970fb589891e893c), CONST64(0x4428b414145014a0), CONST64(0x42dfbae1e1a3e15b),
CONST64(0x4e2ca616165816b0), CONST64(0xd274f73a3ae83acd), CONST64(0xd0d2066969b9696f), CONST64(0x2d12410909240948),
CONST64(0xade0d77070dd70a7), CONST64(0x54716fb6b6e2b6d9), CONST64(0xb7bd1ed0d067d0ce), CONST64(0x7ec7d6eded93ed3b),
CONST64(0xdb85e2cccc17cc2e), CONST64(0x578468424215422a), CONST64(0xc22d2c98985a98b4), CONST64(0x0e55eda4a4aaa449),
CONST64(0x8850752828a0285d), CONST64(0x31b8865c5c6d5cda), CONST64(0x3fed6bf8f8c7f893), CONST64(0xa411c28686228644)
};
static const ulong64 sbox4[] = {
CONST64(0xc07830d818186018), CONST64(0x05af462623238c23), CONST64(0x7ef991b8c6c63fc6), CONST64(0x136fcdfbe8e887e8),
CONST64(0x4ca113cb87872687), CONST64(0xa9626d11b8b8dab8), CONST64(0x0805020901010401), CONST64(0x426e9e0d4f4f214f),
CONST64(0xadee6c9b3636d836), CONST64(0x590451ffa6a6a2a6), CONST64(0xdebdb90cd2d26fd2), CONST64(0xfb06f70ef5f5f3f5),
CONST64(0xef80f2967979f979), CONST64(0x5fcede306f6fa16f), CONST64(0xfcef3f6d91917e91), CONST64(0xaa07a4f852525552),
CONST64(0x27fdc04760609d60), CONST64(0x89766535bcbccabc), CONST64(0xaccd2b379b9b569b), CONST64(0x048c018a8e8e028e),
CONST64(0x71155bd2a3a3b6a3), CONST64(0x603c186c0c0c300c), CONST64(0xff8af6847b7bf17b), CONST64(0xb5e16a803535d435),
CONST64(0xe8693af51d1d741d), CONST64(0x5347ddb3e0e0a7e0), CONST64(0xf6acb321d7d77bd7), CONST64(0x5eed999cc2c22fc2),
CONST64(0x6d965c432e2eb82e), CONST64(0x627a96294b4b314b), CONST64(0xa321e15dfefedffe), CONST64(0x8216aed557574157),
CONST64(0xa8412abd15155415), CONST64(0x9fb6eee87777c177), CONST64(0xa5eb6e923737dc37), CONST64(0x7b56d79ee5e5b3e5),
CONST64(0x8cd923139f9f469f), CONST64(0xd317fd23f0f0e7f0), CONST64(0x6a7f94204a4a354a), CONST64(0x9e95a944dada4fda),
CONST64(0xfa25b0a258587d58), CONST64(0x06ca8fcfc9c903c9), CONST64(0x558d527c2929a429), CONST64(0x5022145a0a0a280a),
CONST64(0xe14f7f50b1b1feb1), CONST64(0x691a5dc9a0a0baa0), CONST64(0x7fdad6146b6bb16b), CONST64(0x5cab17d985852e85),
CONST64(0x8173673cbdbdcebd), CONST64(0xd234ba8f5d5d695d), CONST64(0x8050209010104010), CONST64(0xf303f507f4f4f7f4),
CONST64(0x16c08bddcbcb0bcb), CONST64(0xedc67cd33e3ef83e), CONST64(0x28110a2d05051405), CONST64(0x1fe6ce7867678167),
CONST64(0x7353d597e4e4b7e4), CONST64(0x25bb4e0227279c27), CONST64(0x3258827341411941), CONST64(0x2c9d0ba78b8b168b),
CONST64(0x510153f6a7a7a6a7), CONST64(0xcf94fab27d7de97d), CONST64(0xdcfb374995956e95), CONST64(0x8e9fad56d8d847d8),
CONST64(0x8b30eb70fbfbcbfb), CONST64(0x2371c1cdeeee9fee), CONST64(0xc791f8bb7c7ced7c), CONST64(0x17e3cc7166668566),
CONST64(0xa68ea77bdddd53dd), CONST64(0xb84b2eaf17175c17), CONST64(0x02468e4547470147), CONST64(0x84dc211a9e9e429e),
CONST64(0x1ec589d4caca0fca), CONST64(0x75995a582d2db42d), CONST64(0x9179632ebfbfc6bf), CONST64(0x381b0e3f07071c07),
CONST64(0x012347acadad8ead), CONST64(0xea2fb4b05a5a755a), CONST64(0x6cb51bef83833683), CONST64(0x85ff66b63333cc33),
CONST64(0x3ff2c65c63639163), CONST64(0x100a041202020802), CONST64(0x39384993aaaa92aa), CONST64(0xafa8e2de7171d971),
CONST64(0x0ecf8dc6c8c807c8), CONST64(0xc87d32d119196419), CONST64(0x7270923b49493949), CONST64(0x869aaf5fd9d943d9),
CONST64(0xc31df931f2f2eff2), CONST64(0x4b48dba8e3e3abe3), CONST64(0xe22ab6b95b5b715b), CONST64(0x34920dbc88881a88),
CONST64(0xa4c8293e9a9a529a), CONST64(0x2dbe4c0b26269826), CONST64(0x8dfa64bf3232c832), CONST64(0xe94a7d59b0b0fab0),
CONST64(0x1b6acff2e9e983e9), CONST64(0x78331e770f0f3c0f), CONST64(0xe6a6b733d5d573d5), CONST64(0x74ba1df480803a80),
CONST64(0x997c6127bebec2be), CONST64(0x26de87ebcdcd13cd), CONST64(0xbde468893434d034), CONST64(0x7a75903248483d48),
CONST64(0xab24e354ffffdbff), CONST64(0xf78ff48d7a7af57a), CONST64(0xf4ea3d6490907a90), CONST64(0xc23ebe9d5f5f615f),
CONST64(0x1da0403d20208020), CONST64(0x67d5d00f6868bd68), CONST64(0xd07234ca1a1a681a), CONST64(0x192c41b7aeae82ae),
CONST64(0xc95e757db4b4eab4), CONST64(0x9a19a8ce54544d54), CONST64(0xece53b7f93937693), CONST64(0x0daa442f22228822),
CONST64(0x07e9c86364648d64), CONST64(0xdb12ff2af1f1e3f1), CONST64(0xbfa2e6cc7373d173), CONST64(0x905a248212124812),
CONST64(0x3a5d807a40401d40), CONST64(0x4028104808082008), CONST64(0x56e89b95c3c32bc3), CONST64(0x337bc5dfecec97ec),
CONST64(0x9690ab4ddbdb4bdb), CONST64(0x611f5fc0a1a1bea1), CONST64(0x1c8307918d8d0e8d), CONST64(0xf5c97ac83d3df43d),
CONST64(0xccf1335b97976697), CONST64(0x0000000000000000), CONST64(0x36d483f9cfcf1bcf), CONST64(0x4587566e2b2bac2b),
CONST64(0x97b3ece17676c576), CONST64(0x64b019e682823282), CONST64(0xfea9b128d6d67fd6), CONST64(0xd87736c31b1b6c1b),
CONST64(0xc15b7774b5b5eeb5), CONST64(0x112943beafaf86af), CONST64(0x77dfd41d6a6ab56a), CONST64(0xba0da0ea50505d50),
CONST64(0x124c8a5745450945), CONST64(0xcb18fb38f3f3ebf3), CONST64(0x9df060ad3030c030), CONST64(0x2b74c3c4efef9bef),
CONST64(0xe5c37eda3f3ffc3f), CONST64(0x921caac755554955), CONST64(0x791059dba2a2b2a2), CONST64(0x0365c9e9eaea8fea),
CONST64(0x0fecca6a65658965), CONST64(0xb9686903babad2ba), CONST64(0x65935e4a2f2fbc2f), CONST64(0x4ee79d8ec0c027c0),
CONST64(0xbe81a160dede5fde), CONST64(0xe06c38fc1c1c701c), CONST64(0xbb2ee746fdfdd3fd), CONST64(0x52649a1f4d4d294d),
CONST64(0xe4e0397692927292), CONST64(0x8fbceafa7575c975), CONST64(0x301e0c3606061806), CONST64(0x249809ae8a8a128a),
CONST64(0xf940794bb2b2f2b2), CONST64(0x6359d185e6e6bfe6), CONST64(0x70361c7e0e0e380e), CONST64(0xf8633ee71f1f7c1f),
CONST64(0x37f7c45562629562), CONST64(0xeea3b53ad4d477d4), CONST64(0x29324d81a8a89aa8), CONST64(0xc4f4315296966296),
CONST64(0x9b3aef62f9f9c3f9), CONST64(0x66f697a3c5c533c5), CONST64(0x35b14a1025259425), CONST64(0xf220b2ab59597959),
CONST64(0x54ae15d084842a84), CONST64(0xb7a7e4c57272d572), CONST64(0xd5dd72ec3939e439), CONST64(0x5a6198164c4c2d4c),
CONST64(0xca3bbc945e5e655e), CONST64(0xe785f09f7878fd78), CONST64(0xddd870e53838e038), CONST64(0x148605988c8c0a8c),
CONST64(0xc6b2bf17d1d163d1), CONST64(0x410b57e4a5a5aea5), CONST64(0x434dd9a1e2e2afe2), CONST64(0x2ff8c24e61619961),
CONST64(0xf1457b42b3b3f6b3), CONST64(0x15a5423421218421), CONST64(0x94d625089c9c4a9c), CONST64(0xf0663cee1e1e781e),
CONST64(0x2252866143431143), CONST64(0x76fc93b1c7c73bc7), CONST64(0xb32be54ffcfcd7fc), CONST64(0x2014082404041004),
CONST64(0xb208a2e351515951), CONST64(0xbcc72f2599995e99), CONST64(0x4fc4da226d6da96d), CONST64(0x68391a650d0d340d),
CONST64(0x8335e979fafacffa), CONST64(0xb684a369dfdf5bdf), CONST64(0xd79bfca97e7ee57e), CONST64(0x3db4481924249024),
CONST64(0xc5d776fe3b3bec3b), CONST64(0x313d4b9aabab96ab), CONST64(0x3ed181f0cece1fce), CONST64(0x8855229911114411),
CONST64(0x0c8903838f8f068f), CONST64(0x4a6b9c044e4e254e), CONST64(0xd1517366b7b7e6b7), CONST64(0x0b60cbe0ebeb8beb),
CONST64(0xfdcc78c13c3cf03c), CONST64(0x7cbf1ffd81813e81), CONST64(0xd4fe354094946a94), CONST64(0xeb0cf31cf7f7fbf7),
CONST64(0xa1676f18b9b9deb9), CONST64(0x985f268b13134c13), CONST64(0x7d9c58512c2cb02c), CONST64(0xd6b8bb05d3d36bd3),
CONST64(0x6b5cd38ce7e7bbe7), CONST64(0x57cbdc396e6ea56e), CONST64(0x6ef395aac4c437c4), CONST64(0x180f061b03030c03),
CONST64(0x8a13acdc56564556), CONST64(0x1a49885e44440d44), CONST64(0xdf9efea07f7fe17f), CONST64(0x21374f88a9a99ea9),
CONST64(0x4d8254672a2aa82a), CONST64(0xb16d6b0abbbbd6bb), CONST64(0x46e29f87c1c123c1), CONST64(0xa202a6f153535153),
CONST64(0xae8ba572dcdc57dc), CONST64(0x582716530b0b2c0b), CONST64(0x9cd327019d9d4e9d), CONST64(0x47c1d82b6c6cad6c),
CONST64(0x95f562a43131c431), CONST64(0x87b9e8f37474cd74), CONST64(0xe309f115f6f6fff6), CONST64(0x0a438c4c46460546),
CONST64(0x092645a5acac8aac), CONST64(0x3c970fb589891e89), CONST64(0xa04428b414145014), CONST64(0x5b42dfbae1e1a3e1),
CONST64(0xb04e2ca616165816), CONST64(0xcdd274f73a3ae83a), CONST64(0x6fd0d2066969b969), CONST64(0x482d124109092409),
CONST64(0xa7ade0d77070dd70), CONST64(0xd954716fb6b6e2b6), CONST64(0xceb7bd1ed0d067d0), CONST64(0x3b7ec7d6eded93ed),
CONST64(0x2edb85e2cccc17cc), CONST64(0x2a57846842421542), CONST64(0xb4c22d2c98985a98), CONST64(0x490e55eda4a4aaa4),
CONST64(0x5d8850752828a028), CONST64(0xda31b8865c5c6d5c), CONST64(0x933fed6bf8f8c7f8), CONST64(0x44a411c286862286)
};
static const ulong64 sbox5[] = {
CONST64(0x18c07830d8181860), CONST64(0x2305af462623238c), CONST64(0xc67ef991b8c6c63f), CONST64(0xe8136fcdfbe8e887),
CONST64(0x874ca113cb878726), CONST64(0xb8a9626d11b8b8da), CONST64(0x0108050209010104), CONST64(0x4f426e9e0d4f4f21),
CONST64(0x36adee6c9b3636d8), CONST64(0xa6590451ffa6a6a2), CONST64(0xd2debdb90cd2d26f), CONST64(0xf5fb06f70ef5f5f3),
CONST64(0x79ef80f2967979f9), CONST64(0x6f5fcede306f6fa1), CONST64(0x91fcef3f6d91917e), CONST64(0x52aa07a4f8525255),
CONST64(0x6027fdc04760609d), CONST64(0xbc89766535bcbcca), CONST64(0x9baccd2b379b9b56), CONST64(0x8e048c018a8e8e02),
CONST64(0xa371155bd2a3a3b6), CONST64(0x0c603c186c0c0c30), CONST64(0x7bff8af6847b7bf1), CONST64(0x35b5e16a803535d4),
CONST64(0x1de8693af51d1d74), CONST64(0xe05347ddb3e0e0a7), CONST64(0xd7f6acb321d7d77b), CONST64(0xc25eed999cc2c22f),
CONST64(0x2e6d965c432e2eb8), CONST64(0x4b627a96294b4b31), CONST64(0xfea321e15dfefedf), CONST64(0x578216aed5575741),
CONST64(0x15a8412abd151554), CONST64(0x779fb6eee87777c1), CONST64(0x37a5eb6e923737dc), CONST64(0xe57b56d79ee5e5b3),
CONST64(0x9f8cd923139f9f46), CONST64(0xf0d317fd23f0f0e7), CONST64(0x4a6a7f94204a4a35), CONST64(0xda9e95a944dada4f),
CONST64(0x58fa25b0a258587d), CONST64(0xc906ca8fcfc9c903), CONST64(0x29558d527c2929a4), CONST64(0x0a5022145a0a0a28),
CONST64(0xb1e14f7f50b1b1fe), CONST64(0xa0691a5dc9a0a0ba), CONST64(0x6b7fdad6146b6bb1), CONST64(0x855cab17d985852e),
CONST64(0xbd8173673cbdbdce), CONST64(0x5dd234ba8f5d5d69), CONST64(0x1080502090101040), CONST64(0xf4f303f507f4f4f7),
CONST64(0xcb16c08bddcbcb0b), CONST64(0x3eedc67cd33e3ef8), CONST64(0x0528110a2d050514), CONST64(0x671fe6ce78676781),
CONST64(0xe47353d597e4e4b7), CONST64(0x2725bb4e0227279c), CONST64(0x4132588273414119), CONST64(0x8b2c9d0ba78b8b16),
CONST64(0xa7510153f6a7a7a6), CONST64(0x7dcf94fab27d7de9), CONST64(0x95dcfb374995956e), CONST64(0xd88e9fad56d8d847),
CONST64(0xfb8b30eb70fbfbcb), CONST64(0xee2371c1cdeeee9f), CONST64(0x7cc791f8bb7c7ced), CONST64(0x6617e3cc71666685),
CONST64(0xdda68ea77bdddd53), CONST64(0x17b84b2eaf17175c), CONST64(0x4702468e45474701), CONST64(0x9e84dc211a9e9e42),
CONST64(0xca1ec589d4caca0f), CONST64(0x2d75995a582d2db4), CONST64(0xbf9179632ebfbfc6), CONST64(0x07381b0e3f07071c),
CONST64(0xad012347acadad8e), CONST64(0x5aea2fb4b05a5a75), CONST64(0x836cb51bef838336), CONST64(0x3385ff66b63333cc),
CONST64(0x633ff2c65c636391), CONST64(0x02100a0412020208), CONST64(0xaa39384993aaaa92), CONST64(0x71afa8e2de7171d9),
CONST64(0xc80ecf8dc6c8c807), CONST64(0x19c87d32d1191964), CONST64(0x497270923b494939), CONST64(0xd9869aaf5fd9d943),
CONST64(0xf2c31df931f2f2ef), CONST64(0xe34b48dba8e3e3ab), CONST64(0x5be22ab6b95b5b71), CONST64(0x8834920dbc88881a),
CONST64(0x9aa4c8293e9a9a52), CONST64(0x262dbe4c0b262698), CONST64(0x328dfa64bf3232c8), CONST64(0xb0e94a7d59b0b0fa),
CONST64(0xe91b6acff2e9e983), CONST64(0x0f78331e770f0f3c), CONST64(0xd5e6a6b733d5d573), CONST64(0x8074ba1df480803a),
CONST64(0xbe997c6127bebec2), CONST64(0xcd26de87ebcdcd13), CONST64(0x34bde468893434d0), CONST64(0x487a75903248483d),
CONST64(0xffab24e354ffffdb), CONST64(0x7af78ff48d7a7af5), CONST64(0x90f4ea3d6490907a), CONST64(0x5fc23ebe9d5f5f61),
CONST64(0x201da0403d202080), CONST64(0x6867d5d00f6868bd), CONST64(0x1ad07234ca1a1a68), CONST64(0xae192c41b7aeae82),
CONST64(0xb4c95e757db4b4ea), CONST64(0x549a19a8ce54544d), CONST64(0x93ece53b7f939376), CONST64(0x220daa442f222288),
CONST64(0x6407e9c86364648d), CONST64(0xf1db12ff2af1f1e3), CONST64(0x73bfa2e6cc7373d1), CONST64(0x12905a2482121248),
CONST64(0x403a5d807a40401d), CONST64(0x0840281048080820), CONST64(0xc356e89b95c3c32b), CONST64(0xec337bc5dfecec97),
CONST64(0xdb9690ab4ddbdb4b), CONST64(0xa1611f5fc0a1a1be), CONST64(0x8d1c8307918d8d0e), CONST64(0x3df5c97ac83d3df4),
CONST64(0x97ccf1335b979766), CONST64(0x0000000000000000), CONST64(0xcf36d483f9cfcf1b), CONST64(0x2b4587566e2b2bac),
CONST64(0x7697b3ece17676c5), CONST64(0x8264b019e6828232), CONST64(0xd6fea9b128d6d67f), CONST64(0x1bd87736c31b1b6c),
CONST64(0xb5c15b7774b5b5ee), CONST64(0xaf112943beafaf86), CONST64(0x6a77dfd41d6a6ab5), CONST64(0x50ba0da0ea50505d),
CONST64(0x45124c8a57454509), CONST64(0xf3cb18fb38f3f3eb), CONST64(0x309df060ad3030c0), CONST64(0xef2b74c3c4efef9b),
CONST64(0x3fe5c37eda3f3ffc), CONST64(0x55921caac7555549), CONST64(0xa2791059dba2a2b2), CONST64(0xea0365c9e9eaea8f),
CONST64(0x650fecca6a656589), CONST64(0xbab9686903babad2), CONST64(0x2f65935e4a2f2fbc), CONST64(0xc04ee79d8ec0c027),
CONST64(0xdebe81a160dede5f), CONST64(0x1ce06c38fc1c1c70), CONST64(0xfdbb2ee746fdfdd3), CONST64(0x4d52649a1f4d4d29),
CONST64(0x92e4e03976929272), CONST64(0x758fbceafa7575c9), CONST64(0x06301e0c36060618), CONST64(0x8a249809ae8a8a12),
CONST64(0xb2f940794bb2b2f2), CONST64(0xe66359d185e6e6bf), CONST64(0x0e70361c7e0e0e38), CONST64(0x1ff8633ee71f1f7c),
CONST64(0x6237f7c455626295), CONST64(0xd4eea3b53ad4d477), CONST64(0xa829324d81a8a89a), CONST64(0x96c4f43152969662),
CONST64(0xf99b3aef62f9f9c3), CONST64(0xc566f697a3c5c533), CONST64(0x2535b14a10252594), CONST64(0x59f220b2ab595979),
CONST64(0x8454ae15d084842a), CONST64(0x72b7a7e4c57272d5), CONST64(0x39d5dd72ec3939e4), CONST64(0x4c5a6198164c4c2d),
CONST64(0x5eca3bbc945e5e65), CONST64(0x78e785f09f7878fd), CONST64(0x38ddd870e53838e0), CONST64(0x8c148605988c8c0a),
CONST64(0xd1c6b2bf17d1d163), CONST64(0xa5410b57e4a5a5ae), CONST64(0xe2434dd9a1e2e2af), CONST64(0x612ff8c24e616199),
CONST64(0xb3f1457b42b3b3f6), CONST64(0x2115a54234212184), CONST64(0x9c94d625089c9c4a), CONST64(0x1ef0663cee1e1e78),
CONST64(0x4322528661434311), CONST64(0xc776fc93b1c7c73b), CONST64(0xfcb32be54ffcfcd7), CONST64(0x0420140824040410),
CONST64(0x51b208a2e3515159), CONST64(0x99bcc72f2599995e), CONST64(0x6d4fc4da226d6da9), CONST64(0x0d68391a650d0d34),
CONST64(0xfa8335e979fafacf), CONST64(0xdfb684a369dfdf5b), CONST64(0x7ed79bfca97e7ee5), CONST64(0x243db44819242490),
CONST64(0x3bc5d776fe3b3bec), CONST64(0xab313d4b9aabab96), CONST64(0xce3ed181f0cece1f), CONST64(0x1188552299111144),
CONST64(0x8f0c8903838f8f06), CONST64(0x4e4a6b9c044e4e25), CONST64(0xb7d1517366b7b7e6), CONST64(0xeb0b60cbe0ebeb8b),
CONST64(0x3cfdcc78c13c3cf0), CONST64(0x817cbf1ffd81813e), CONST64(0x94d4fe354094946a), CONST64(0xf7eb0cf31cf7f7fb),
CONST64(0xb9a1676f18b9b9de), CONST64(0x13985f268b13134c), CONST64(0x2c7d9c58512c2cb0), CONST64(0xd3d6b8bb05d3d36b),
CONST64(0xe76b5cd38ce7e7bb), CONST64(0x6e57cbdc396e6ea5), CONST64(0xc46ef395aac4c437), CONST64(0x03180f061b03030c),
CONST64(0x568a13acdc565645), CONST64(0x441a49885e44440d), CONST64(0x7fdf9efea07f7fe1), CONST64(0xa921374f88a9a99e),
CONST64(0x2a4d8254672a2aa8), CONST64(0xbbb16d6b0abbbbd6), CONST64(0xc146e29f87c1c123), CONST64(0x53a202a6f1535351),
CONST64(0xdcae8ba572dcdc57), CONST64(0x0b582716530b0b2c), CONST64(0x9d9cd327019d9d4e), CONST64(0x6c47c1d82b6c6cad),
CONST64(0x3195f562a43131c4), CONST64(0x7487b9e8f37474cd), CONST64(0xf6e309f115f6f6ff), CONST64(0x460a438c4c464605),
CONST64(0xac092645a5acac8a), CONST64(0x893c970fb589891e), CONST64(0x14a04428b4141450), CONST64(0xe15b42dfbae1e1a3),
CONST64(0x16b04e2ca6161658), CONST64(0x3acdd274f73a3ae8), CONST64(0x696fd0d2066969b9), CONST64(0x09482d1241090924),
CONST64(0x70a7ade0d77070dd), CONST64(0xb6d954716fb6b6e2), CONST64(0xd0ceb7bd1ed0d067), CONST64(0xed3b7ec7d6eded93),
CONST64(0xcc2edb85e2cccc17), CONST64(0x422a578468424215), CONST64(0x98b4c22d2c98985a), CONST64(0xa4490e55eda4a4aa),
CONST64(0x285d8850752828a0), CONST64(0x5cda31b8865c5c6d), CONST64(0xf8933fed6bf8f8c7), CONST64(0x8644a411c2868622)
};
static const ulong64 sbox6[] = {
CONST64(0x6018c07830d81818), CONST64(0x8c2305af46262323), CONST64(0x3fc67ef991b8c6c6), CONST64(0x87e8136fcdfbe8e8),
CONST64(0x26874ca113cb8787), CONST64(0xdab8a9626d11b8b8), CONST64(0x0401080502090101), CONST64(0x214f426e9e0d4f4f),
CONST64(0xd836adee6c9b3636), CONST64(0xa2a6590451ffa6a6), CONST64(0x6fd2debdb90cd2d2), CONST64(0xf3f5fb06f70ef5f5),
CONST64(0xf979ef80f2967979), CONST64(0xa16f5fcede306f6f), CONST64(0x7e91fcef3f6d9191), CONST64(0x5552aa07a4f85252),
CONST64(0x9d6027fdc0476060), CONST64(0xcabc89766535bcbc), CONST64(0x569baccd2b379b9b), CONST64(0x028e048c018a8e8e),
CONST64(0xb6a371155bd2a3a3), CONST64(0x300c603c186c0c0c), CONST64(0xf17bff8af6847b7b), CONST64(0xd435b5e16a803535),
CONST64(0x741de8693af51d1d), CONST64(0xa7e05347ddb3e0e0), CONST64(0x7bd7f6acb321d7d7), CONST64(0x2fc25eed999cc2c2),
CONST64(0xb82e6d965c432e2e), CONST64(0x314b627a96294b4b), CONST64(0xdffea321e15dfefe), CONST64(0x41578216aed55757),
CONST64(0x5415a8412abd1515), CONST64(0xc1779fb6eee87777), CONST64(0xdc37a5eb6e923737), CONST64(0xb3e57b56d79ee5e5),
CONST64(0x469f8cd923139f9f), CONST64(0xe7f0d317fd23f0f0), CONST64(0x354a6a7f94204a4a), CONST64(0x4fda9e95a944dada),
CONST64(0x7d58fa25b0a25858), CONST64(0x03c906ca8fcfc9c9), CONST64(0xa429558d527c2929), CONST64(0x280a5022145a0a0a),
CONST64(0xfeb1e14f7f50b1b1), CONST64(0xbaa0691a5dc9a0a0), CONST64(0xb16b7fdad6146b6b), CONST64(0x2e855cab17d98585),
CONST64(0xcebd8173673cbdbd), CONST64(0x695dd234ba8f5d5d), CONST64(0x4010805020901010), CONST64(0xf7f4f303f507f4f4),
CONST64(0x0bcb16c08bddcbcb), CONST64(0xf83eedc67cd33e3e), CONST64(0x140528110a2d0505), CONST64(0x81671fe6ce786767),
CONST64(0xb7e47353d597e4e4), CONST64(0x9c2725bb4e022727), CONST64(0x1941325882734141), CONST64(0x168b2c9d0ba78b8b),
CONST64(0xa6a7510153f6a7a7), CONST64(0xe97dcf94fab27d7d), CONST64(0x6e95dcfb37499595), CONST64(0x47d88e9fad56d8d8),
CONST64(0xcbfb8b30eb70fbfb), CONST64(0x9fee2371c1cdeeee), CONST64(0xed7cc791f8bb7c7c), CONST64(0x856617e3cc716666),
CONST64(0x53dda68ea77bdddd), CONST64(0x5c17b84b2eaf1717), CONST64(0x014702468e454747), CONST64(0x429e84dc211a9e9e),
CONST64(0x0fca1ec589d4caca), CONST64(0xb42d75995a582d2d), CONST64(0xc6bf9179632ebfbf), CONST64(0x1c07381b0e3f0707),
CONST64(0x8ead012347acadad), CONST64(0x755aea2fb4b05a5a), CONST64(0x36836cb51bef8383), CONST64(0xcc3385ff66b63333),
CONST64(0x91633ff2c65c6363), CONST64(0x0802100a04120202), CONST64(0x92aa39384993aaaa), CONST64(0xd971afa8e2de7171),
CONST64(0x07c80ecf8dc6c8c8), CONST64(0x6419c87d32d11919), CONST64(0x39497270923b4949), CONST64(0x43d9869aaf5fd9d9),
CONST64(0xeff2c31df931f2f2), CONST64(0xabe34b48dba8e3e3), CONST64(0x715be22ab6b95b5b), CONST64(0x1a8834920dbc8888),
CONST64(0x529aa4c8293e9a9a), CONST64(0x98262dbe4c0b2626), CONST64(0xc8328dfa64bf3232), CONST64(0xfab0e94a7d59b0b0),
CONST64(0x83e91b6acff2e9e9), CONST64(0x3c0f78331e770f0f), CONST64(0x73d5e6a6b733d5d5), CONST64(0x3a8074ba1df48080),
CONST64(0xc2be997c6127bebe), CONST64(0x13cd26de87ebcdcd), CONST64(0xd034bde468893434), CONST64(0x3d487a7590324848),
CONST64(0xdbffab24e354ffff), CONST64(0xf57af78ff48d7a7a), CONST64(0x7a90f4ea3d649090), CONST64(0x615fc23ebe9d5f5f),
CONST64(0x80201da0403d2020), CONST64(0xbd6867d5d00f6868), CONST64(0x681ad07234ca1a1a), CONST64(0x82ae192c41b7aeae),
CONST64(0xeab4c95e757db4b4), CONST64(0x4d549a19a8ce5454), CONST64(0x7693ece53b7f9393), CONST64(0x88220daa442f2222),
CONST64(0x8d6407e9c8636464), CONST64(0xe3f1db12ff2af1f1), CONST64(0xd173bfa2e6cc7373), CONST64(0x4812905a24821212),
CONST64(0x1d403a5d807a4040), CONST64(0x2008402810480808), CONST64(0x2bc356e89b95c3c3), CONST64(0x97ec337bc5dfecec),
CONST64(0x4bdb9690ab4ddbdb), CONST64(0xbea1611f5fc0a1a1), CONST64(0x0e8d1c8307918d8d), CONST64(0xf43df5c97ac83d3d),
CONST64(0x6697ccf1335b9797), CONST64(0x0000000000000000), CONST64(0x1bcf36d483f9cfcf), CONST64(0xac2b4587566e2b2b),
CONST64(0xc57697b3ece17676), CONST64(0x328264b019e68282), CONST64(0x7fd6fea9b128d6d6), CONST64(0x6c1bd87736c31b1b),
CONST64(0xeeb5c15b7774b5b5), CONST64(0x86af112943beafaf), CONST64(0xb56a77dfd41d6a6a), CONST64(0x5d50ba0da0ea5050),
CONST64(0x0945124c8a574545), CONST64(0xebf3cb18fb38f3f3), CONST64(0xc0309df060ad3030), CONST64(0x9bef2b74c3c4efef),
CONST64(0xfc3fe5c37eda3f3f), CONST64(0x4955921caac75555), CONST64(0xb2a2791059dba2a2), CONST64(0x8fea0365c9e9eaea),
CONST64(0x89650fecca6a6565), CONST64(0xd2bab9686903baba), CONST64(0xbc2f65935e4a2f2f), CONST64(0x27c04ee79d8ec0c0),
CONST64(0x5fdebe81a160dede), CONST64(0x701ce06c38fc1c1c), CONST64(0xd3fdbb2ee746fdfd), CONST64(0x294d52649a1f4d4d),
CONST64(0x7292e4e039769292), CONST64(0xc9758fbceafa7575), CONST64(0x1806301e0c360606), CONST64(0x128a249809ae8a8a),
CONST64(0xf2b2f940794bb2b2), CONST64(0xbfe66359d185e6e6), CONST64(0x380e70361c7e0e0e), CONST64(0x7c1ff8633ee71f1f),
CONST64(0x956237f7c4556262), CONST64(0x77d4eea3b53ad4d4), CONST64(0x9aa829324d81a8a8), CONST64(0x6296c4f431529696),
CONST64(0xc3f99b3aef62f9f9), CONST64(0x33c566f697a3c5c5), CONST64(0x942535b14a102525), CONST64(0x7959f220b2ab5959),
CONST64(0x2a8454ae15d08484), CONST64(0xd572b7a7e4c57272), CONST64(0xe439d5dd72ec3939), CONST64(0x2d4c5a6198164c4c),
CONST64(0x655eca3bbc945e5e), CONST64(0xfd78e785f09f7878), CONST64(0xe038ddd870e53838), CONST64(0x0a8c148605988c8c),
CONST64(0x63d1c6b2bf17d1d1), CONST64(0xaea5410b57e4a5a5), CONST64(0xafe2434dd9a1e2e2), CONST64(0x99612ff8c24e6161),
CONST64(0xf6b3f1457b42b3b3), CONST64(0x842115a542342121), CONST64(0x4a9c94d625089c9c), CONST64(0x781ef0663cee1e1e),
CONST64(0x1143225286614343), CONST64(0x3bc776fc93b1c7c7), CONST64(0xd7fcb32be54ffcfc), CONST64(0x1004201408240404),
CONST64(0x5951b208a2e35151), CONST64(0x5e99bcc72f259999), CONST64(0xa96d4fc4da226d6d), CONST64(0x340d68391a650d0d),
CONST64(0xcffa8335e979fafa), CONST64(0x5bdfb684a369dfdf), CONST64(0xe57ed79bfca97e7e), CONST64(0x90243db448192424),
CONST64(0xec3bc5d776fe3b3b), CONST64(0x96ab313d4b9aabab), CONST64(0x1fce3ed181f0cece), CONST64(0x4411885522991111),
CONST64(0x068f0c8903838f8f), CONST64(0x254e4a6b9c044e4e), CONST64(0xe6b7d1517366b7b7), CONST64(0x8beb0b60cbe0ebeb),
CONST64(0xf03cfdcc78c13c3c), CONST64(0x3e817cbf1ffd8181), CONST64(0x6a94d4fe35409494), CONST64(0xfbf7eb0cf31cf7f7),
CONST64(0xdeb9a1676f18b9b9), CONST64(0x4c13985f268b1313), CONST64(0xb02c7d9c58512c2c), CONST64(0x6bd3d6b8bb05d3d3),
CONST64(0xbbe76b5cd38ce7e7), CONST64(0xa56e57cbdc396e6e), CONST64(0x37c46ef395aac4c4), CONST64(0x0c03180f061b0303),
CONST64(0x45568a13acdc5656), CONST64(0x0d441a49885e4444), CONST64(0xe17fdf9efea07f7f), CONST64(0x9ea921374f88a9a9),
CONST64(0xa82a4d8254672a2a), CONST64(0xd6bbb16d6b0abbbb), CONST64(0x23c146e29f87c1c1), CONST64(0x5153a202a6f15353),
CONST64(0x57dcae8ba572dcdc), CONST64(0x2c0b582716530b0b), CONST64(0x4e9d9cd327019d9d), CONST64(0xad6c47c1d82b6c6c),
CONST64(0xc43195f562a43131), CONST64(0xcd7487b9e8f37474), CONST64(0xfff6e309f115f6f6), CONST64(0x05460a438c4c4646),
CONST64(0x8aac092645a5acac), CONST64(0x1e893c970fb58989), CONST64(0x5014a04428b41414), CONST64(0xa3e15b42dfbae1e1),
CONST64(0x5816b04e2ca61616), CONST64(0xe83acdd274f73a3a), CONST64(0xb9696fd0d2066969), CONST64(0x2409482d12410909),
CONST64(0xdd70a7ade0d77070), CONST64(0xe2b6d954716fb6b6), CONST64(0x67d0ceb7bd1ed0d0), CONST64(0x93ed3b7ec7d6eded),
CONST64(0x17cc2edb85e2cccc), CONST64(0x15422a5784684242), CONST64(0x5a98b4c22d2c9898), CONST64(0xaaa4490e55eda4a4),
CONST64(0xa0285d8850752828), CONST64(0x6d5cda31b8865c5c), CONST64(0xc7f8933fed6bf8f8), CONST64(0x228644a411c28686)
};
static const ulong64 sbox7[] = {
CONST64(0x186018c07830d818), CONST64(0x238c2305af462623), CONST64(0xc63fc67ef991b8c6), CONST64(0xe887e8136fcdfbe8),
CONST64(0x8726874ca113cb87), CONST64(0xb8dab8a9626d11b8), CONST64(0x0104010805020901), CONST64(0x4f214f426e9e0d4f),
CONST64(0x36d836adee6c9b36), CONST64(0xa6a2a6590451ffa6), CONST64(0xd26fd2debdb90cd2), CONST64(0xf5f3f5fb06f70ef5),
CONST64(0x79f979ef80f29679), CONST64(0x6fa16f5fcede306f), CONST64(0x917e91fcef3f6d91), CONST64(0x525552aa07a4f852),
CONST64(0x609d6027fdc04760), CONST64(0xbccabc89766535bc), CONST64(0x9b569baccd2b379b), CONST64(0x8e028e048c018a8e),
CONST64(0xa3b6a371155bd2a3), CONST64(0x0c300c603c186c0c), CONST64(0x7bf17bff8af6847b), CONST64(0x35d435b5e16a8035),
CONST64(0x1d741de8693af51d), CONST64(0xe0a7e05347ddb3e0), CONST64(0xd77bd7f6acb321d7), CONST64(0xc22fc25eed999cc2),
CONST64(0x2eb82e6d965c432e), CONST64(0x4b314b627a96294b), CONST64(0xfedffea321e15dfe), CONST64(0x5741578216aed557),
CONST64(0x155415a8412abd15), CONST64(0x77c1779fb6eee877), CONST64(0x37dc37a5eb6e9237), CONST64(0xe5b3e57b56d79ee5),
CONST64(0x9f469f8cd923139f), CONST64(0xf0e7f0d317fd23f0), CONST64(0x4a354a6a7f94204a), CONST64(0xda4fda9e95a944da),
CONST64(0x587d58fa25b0a258), CONST64(0xc903c906ca8fcfc9), CONST64(0x29a429558d527c29), CONST64(0x0a280a5022145a0a),
CONST64(0xb1feb1e14f7f50b1), CONST64(0xa0baa0691a5dc9a0), CONST64(0x6bb16b7fdad6146b), CONST64(0x852e855cab17d985),
CONST64(0xbdcebd8173673cbd), CONST64(0x5d695dd234ba8f5d), CONST64(0x1040108050209010), CONST64(0xf4f7f4f303f507f4),
CONST64(0xcb0bcb16c08bddcb), CONST64(0x3ef83eedc67cd33e), CONST64(0x05140528110a2d05), CONST64(0x6781671fe6ce7867),
CONST64(0xe4b7e47353d597e4), CONST64(0x279c2725bb4e0227), CONST64(0x4119413258827341), CONST64(0x8b168b2c9d0ba78b),
CONST64(0xa7a6a7510153f6a7), CONST64(0x7de97dcf94fab27d), CONST64(0x956e95dcfb374995), CONST64(0xd847d88e9fad56d8),
CONST64(0xfbcbfb8b30eb70fb), CONST64(0xee9fee2371c1cdee), CONST64(0x7ced7cc791f8bb7c), CONST64(0x66856617e3cc7166),
CONST64(0xdd53dda68ea77bdd), CONST64(0x175c17b84b2eaf17), CONST64(0x47014702468e4547), CONST64(0x9e429e84dc211a9e),
CONST64(0xca0fca1ec589d4ca), CONST64(0x2db42d75995a582d), CONST64(0xbfc6bf9179632ebf), CONST64(0x071c07381b0e3f07),
CONST64(0xad8ead012347acad), CONST64(0x5a755aea2fb4b05a), CONST64(0x8336836cb51bef83), CONST64(0x33cc3385ff66b633),
CONST64(0x6391633ff2c65c63), CONST64(0x020802100a041202), CONST64(0xaa92aa39384993aa), CONST64(0x71d971afa8e2de71),
CONST64(0xc807c80ecf8dc6c8), CONST64(0x196419c87d32d119), CONST64(0x4939497270923b49), CONST64(0xd943d9869aaf5fd9),
CONST64(0xf2eff2c31df931f2), CONST64(0xe3abe34b48dba8e3), CONST64(0x5b715be22ab6b95b), CONST64(0x881a8834920dbc88),
CONST64(0x9a529aa4c8293e9a), CONST64(0x2698262dbe4c0b26), CONST64(0x32c8328dfa64bf32), CONST64(0xb0fab0e94a7d59b0),
CONST64(0xe983e91b6acff2e9), CONST64(0x0f3c0f78331e770f), CONST64(0xd573d5e6a6b733d5), CONST64(0x803a8074ba1df480),
CONST64(0xbec2be997c6127be), CONST64(0xcd13cd26de87ebcd), CONST64(0x34d034bde4688934), CONST64(0x483d487a75903248),
CONST64(0xffdbffab24e354ff), CONST64(0x7af57af78ff48d7a), CONST64(0x907a90f4ea3d6490), CONST64(0x5f615fc23ebe9d5f),
CONST64(0x2080201da0403d20), CONST64(0x68bd6867d5d00f68), CONST64(0x1a681ad07234ca1a), CONST64(0xae82ae192c41b7ae),
CONST64(0xb4eab4c95e757db4), CONST64(0x544d549a19a8ce54), CONST64(0x937693ece53b7f93), CONST64(0x2288220daa442f22),
CONST64(0x648d6407e9c86364), CONST64(0xf1e3f1db12ff2af1), CONST64(0x73d173bfa2e6cc73), CONST64(0x124812905a248212),
CONST64(0x401d403a5d807a40), CONST64(0x0820084028104808), CONST64(0xc32bc356e89b95c3), CONST64(0xec97ec337bc5dfec),
CONST64(0xdb4bdb9690ab4ddb), CONST64(0xa1bea1611f5fc0a1), CONST64(0x8d0e8d1c8307918d), CONST64(0x3df43df5c97ac83d),
CONST64(0x976697ccf1335b97), CONST64(0x0000000000000000), CONST64(0xcf1bcf36d483f9cf), CONST64(0x2bac2b4587566e2b),
CONST64(0x76c57697b3ece176), CONST64(0x82328264b019e682), CONST64(0xd67fd6fea9b128d6), CONST64(0x1b6c1bd87736c31b),
CONST64(0xb5eeb5c15b7774b5), CONST64(0xaf86af112943beaf), CONST64(0x6ab56a77dfd41d6a), CONST64(0x505d50ba0da0ea50),
CONST64(0x450945124c8a5745), CONST64(0xf3ebf3cb18fb38f3), CONST64(0x30c0309df060ad30), CONST64(0xef9bef2b74c3c4ef),
CONST64(0x3ffc3fe5c37eda3f), CONST64(0x554955921caac755), CONST64(0xa2b2a2791059dba2), CONST64(0xea8fea0365c9e9ea),
CONST64(0x6589650fecca6a65), CONST64(0xbad2bab9686903ba), CONST64(0x2fbc2f65935e4a2f), CONST64(0xc027c04ee79d8ec0),
CONST64(0xde5fdebe81a160de), CONST64(0x1c701ce06c38fc1c), CONST64(0xfdd3fdbb2ee746fd), CONST64(0x4d294d52649a1f4d),
CONST64(0x927292e4e0397692), CONST64(0x75c9758fbceafa75), CONST64(0x061806301e0c3606), CONST64(0x8a128a249809ae8a),
CONST64(0xb2f2b2f940794bb2), CONST64(0xe6bfe66359d185e6), CONST64(0x0e380e70361c7e0e), CONST64(0x1f7c1ff8633ee71f),
CONST64(0x62956237f7c45562), CONST64(0xd477d4eea3b53ad4), CONST64(0xa89aa829324d81a8), CONST64(0x966296c4f4315296),
CONST64(0xf9c3f99b3aef62f9), CONST64(0xc533c566f697a3c5), CONST64(0x25942535b14a1025), CONST64(0x597959f220b2ab59),
CONST64(0x842a8454ae15d084), CONST64(0x72d572b7a7e4c572), CONST64(0x39e439d5dd72ec39), CONST64(0x4c2d4c5a6198164c),
CONST64(0x5e655eca3bbc945e), CONST64(0x78fd78e785f09f78), CONST64(0x38e038ddd870e538), CONST64(0x8c0a8c148605988c),
CONST64(0xd163d1c6b2bf17d1), CONST64(0xa5aea5410b57e4a5), CONST64(0xe2afe2434dd9a1e2), CONST64(0x6199612ff8c24e61),
CONST64(0xb3f6b3f1457b42b3), CONST64(0x21842115a5423421), CONST64(0x9c4a9c94d625089c), CONST64(0x1e781ef0663cee1e),
CONST64(0x4311432252866143), CONST64(0xc73bc776fc93b1c7), CONST64(0xfcd7fcb32be54ffc), CONST64(0x0410042014082404),
CONST64(0x515951b208a2e351), CONST64(0x995e99bcc72f2599), CONST64(0x6da96d4fc4da226d), CONST64(0x0d340d68391a650d),
CONST64(0xfacffa8335e979fa), CONST64(0xdf5bdfb684a369df), CONST64(0x7ee57ed79bfca97e), CONST64(0x2490243db4481924),
CONST64(0x3bec3bc5d776fe3b), CONST64(0xab96ab313d4b9aab), CONST64(0xce1fce3ed181f0ce), CONST64(0x1144118855229911),
CONST64(0x8f068f0c8903838f), CONST64(0x4e254e4a6b9c044e), CONST64(0xb7e6b7d1517366b7), CONST64(0xeb8beb0b60cbe0eb),
CONST64(0x3cf03cfdcc78c13c), CONST64(0x813e817cbf1ffd81), CONST64(0x946a94d4fe354094), CONST64(0xf7fbf7eb0cf31cf7),
CONST64(0xb9deb9a1676f18b9), CONST64(0x134c13985f268b13), CONST64(0x2cb02c7d9c58512c), CONST64(0xd36bd3d6b8bb05d3),
CONST64(0xe7bbe76b5cd38ce7), CONST64(0x6ea56e57cbdc396e), CONST64(0xc437c46ef395aac4), CONST64(0x030c03180f061b03),
CONST64(0x5645568a13acdc56), CONST64(0x440d441a49885e44), CONST64(0x7fe17fdf9efea07f), CONST64(0xa99ea921374f88a9),
CONST64(0x2aa82a4d8254672a), CONST64(0xbbd6bbb16d6b0abb), CONST64(0xc123c146e29f87c1), CONST64(0x535153a202a6f153),
CONST64(0xdc57dcae8ba572dc), CONST64(0x0b2c0b582716530b), CONST64(0x9d4e9d9cd327019d), CONST64(0x6cad6c47c1d82b6c),
CONST64(0x31c43195f562a431), CONST64(0x74cd7487b9e8f374), CONST64(0xf6fff6e309f115f6), CONST64(0x4605460a438c4c46),
CONST64(0xac8aac092645a5ac), CONST64(0x891e893c970fb589), CONST64(0x145014a04428b414), CONST64(0xe1a3e15b42dfbae1),
CONST64(0x165816b04e2ca616), CONST64(0x3ae83acdd274f73a), CONST64(0x69b9696fd0d20669), CONST64(0x092409482d124109),
CONST64(0x70dd70a7ade0d770), CONST64(0xb6e2b6d954716fb6), CONST64(0xd067d0ceb7bd1ed0), CONST64(0xed93ed3b7ec7d6ed),
CONST64(0xcc17cc2edb85e2cc), CONST64(0x4215422a57846842), CONST64(0x985a98b4c22d2c98), CONST64(0xa4aaa4490e55eda4),
CONST64(0x28a0285d88507528), CONST64(0x5c6d5cda31b8865c), CONST64(0xf8c7f8933fed6bf8), CONST64(0x86228644a411c286)
};
#endif
static const ulong64 cont[] = {
CONST64(0x1823c6e887b8014f),
CONST64(0x36a6d2f5796f9152),
CONST64(0x60bc9b8ea30c7b35),
CONST64(0x1de0d7c22e4bfe57),
CONST64(0x157737e59ff04ada),
CONST64(0x58c9290ab1a06b85),
CONST64(0xbd5d10f4cb3e0567),
CONST64(0xe427418ba77d95d8),
CONST64(0xfbee7c66dd17479e),
CONST64(0xca2dbf07ad5a8333),
CONST64(0x6302aa71c81949d9),
};
/* $Source: /cvs/libtom/libtomcrypt/src/hashes/whirl/whirltab.c,v $ */
/* $Revision: 1.3 $ */
/* $Date: 2007/05/12 14:21:44 $ */

618
crypto777/hmac_sha512.c

@ -0,0 +1,618 @@
/*
* FIPS 180-2 SHA-224/256/384/512 implementation
* Last update: 02/02/2007
* Issue date: 04/30/2005
*
* Copyright (C) 2005, 2007 Olivier Gay <olivier.gay@a3.epfl.ch>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#define SHA512_DIGEST_SIZE (512 / 8)
#include <string.h>
#include <stdint.h>
#define SHA512_BLOCK_SIZE (1024 / 8)
typedef struct {
unsigned int tot_len;
unsigned int len;
unsigned char block[2 * SHA512_BLOCK_SIZE];
unsigned long long h[8];
} sha512_ctx;
typedef struct {
sha512_ctx ctx_inside;
sha512_ctx ctx_outside;
/* for hmac_reinit */
sha512_ctx ctx_inside_reinit;
sha512_ctx ctx_outside_reinit;
unsigned char block_ipad[SHA512_BLOCK_SIZE];
unsigned char block_opad[SHA512_BLOCK_SIZE];
} hmac_sha512_ctx;
#define SHFR(x, n) (x >> n)
#define ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n)))
#define CH(x, y, z) ((x & y) ^ (~x & z))
#define MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z))
#define SHA512_F1(x) (ROTR(x, 28) ^ ROTR(x, 34) ^ ROTR(x, 39))
#define SHA512_F2(x) (ROTR(x, 14) ^ ROTR(x, 18) ^ ROTR(x, 41))
#define SHA512_F3(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHFR(x, 7))
#define SHA512_F4(x) (ROTR(x, 19) ^ ROTR(x, 61) ^ SHFR(x, 6))
#define UNPACK32(x, str) \
{ \
*((str) + 3) = (unsigned char) ((x) ); \
*((str) + 2) = (unsigned char) ((x) >> 8); \
*((str) + 1) = (unsigned char) ((x) >> 16); \
*((str) + 0) = (unsigned char) ((x) >> 24); \
}
#define UNPACK64(x, str) \
{ \
*((str) + 7) = (unsigned char) ((x) ); \
*((str) + 6) = (unsigned char) ((x) >> 8); \
*((str) + 5) = (unsigned char) ((x) >> 16); \
*((str) + 4) = (unsigned char) ((x) >> 24); \
*((str) + 3) = (unsigned char) ((x) >> 32); \
*((str) + 2) = (unsigned char) ((x) >> 40); \
*((str) + 1) = (unsigned char) ((x) >> 48); \
*((str) + 0) = (unsigned char) ((x) >> 56); \
}
#define PACK64(str, x) \
{ \
*(x) = ((unsigned long long) *((str) + 7) ) \
| ((unsigned long long) *((str) + 6) << 8) \
| ((unsigned long long) *((str) + 5) << 16) \
| ((unsigned long long) *((str) + 4) << 24) \
| ((unsigned long long) *((str) + 3) << 32) \
| ((unsigned long long) *((str) + 2) << 40) \
| ((unsigned long long) *((str) + 1) << 48) \
| ((unsigned long long) *((str) + 0) << 56); \
}
/* Macros used for loops unrolling */
#define SHA512_SCR(i) \
{ \
w[i] = SHA512_F4(w[i - 2]) + w[i - 7] \
+ SHA512_F3(w[i - 15]) + w[i - 16]; \
}
#define SHA512_EXP(a, b, c, d, e, f, g ,h, j) \
{ \
t1 = wv[h] + SHA512_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) \
+ sha512_k[j] + w[j]; \
t2 = SHA512_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \
wv[d] += t1; \
wv[h] = t1 + t2; \
}
static unsigned long long sha512_h0[8] = {
0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL,
0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL,
0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL
};
static unsigned long long sha512_k[80] = {
0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL
};
static void sha512_transf(sha512_ctx * ctx, const unsigned char *message,
unsigned int block_nb)
{
unsigned long long w[80];
unsigned long long wv[8];
unsigned long long t1, t2;
const unsigned char *sub_block;
int i, j;
for (i = 0; i < (int)block_nb; i++) {
sub_block = message + (i << 7);
PACK64(&sub_block[0], &w[0]);
PACK64(&sub_block[8], &w[1]);
PACK64(&sub_block[16], &w[2]);
PACK64(&sub_block[24], &w[3]);
PACK64(&sub_block[32], &w[4]);
PACK64(&sub_block[40], &w[5]);
PACK64(&sub_block[48], &w[6]);
PACK64(&sub_block[56], &w[7]);
PACK64(&sub_block[64], &w[8]);
PACK64(&sub_block[72], &w[9]);
PACK64(&sub_block[80], &w[10]);
PACK64(&sub_block[88], &w[11]);
PACK64(&sub_block[96], &w[12]);
PACK64(&sub_block[104], &w[13]);
PACK64(&sub_block[112], &w[14]);
PACK64(&sub_block[120], &w[15]);
SHA512_SCR(16);
SHA512_SCR(17);
SHA512_SCR(18);
SHA512_SCR(19);
SHA512_SCR(20);
SHA512_SCR(21);
SHA512_SCR(22);
SHA512_SCR(23);
SHA512_SCR(24);
SHA512_SCR(25);
SHA512_SCR(26);
SHA512_SCR(27);
SHA512_SCR(28);
SHA512_SCR(29);
SHA512_SCR(30);
SHA512_SCR(31);
SHA512_SCR(32);
SHA512_SCR(33);
SHA512_SCR(34);
SHA512_SCR(35);
SHA512_SCR(36);
SHA512_SCR(37);
SHA512_SCR(38);
SHA512_SCR(39);
SHA512_SCR(40);
SHA512_SCR(41);
SHA512_SCR(42);
SHA512_SCR(43);
SHA512_SCR(44);
SHA512_SCR(45);
SHA512_SCR(46);
SHA512_SCR(47);
SHA512_SCR(48);
SHA512_SCR(49);
SHA512_SCR(50);
SHA512_SCR(51);
SHA512_SCR(52);
SHA512_SCR(53);
SHA512_SCR(54);
SHA512_SCR(55);
SHA512_SCR(56);
SHA512_SCR(57);
SHA512_SCR(58);
SHA512_SCR(59);
SHA512_SCR(60);
SHA512_SCR(61);
SHA512_SCR(62);
SHA512_SCR(63);
SHA512_SCR(64);
SHA512_SCR(65);
SHA512_SCR(66);
SHA512_SCR(67);
SHA512_SCR(68);
SHA512_SCR(69);
SHA512_SCR(70);
SHA512_SCR(71);
SHA512_SCR(72);
SHA512_SCR(73);
SHA512_SCR(74);
SHA512_SCR(75);
SHA512_SCR(76);
SHA512_SCR(77);
SHA512_SCR(78);
SHA512_SCR(79);
wv[0] = ctx->h[0];
wv[1] = ctx->h[1];
wv[2] = ctx->h[2];
wv[3] = ctx->h[3];
wv[4] = ctx->h[4];
wv[5] = ctx->h[5];
wv[6] = ctx->h[6];
wv[7] = ctx->h[7];
j = 0;
do {
SHA512_EXP(0, 1, 2, 3, 4, 5, 6, 7, j);
j++;
SHA512_EXP(7, 0, 1, 2, 3, 4, 5, 6, j);
j++;
SHA512_EXP(6, 7, 0, 1, 2, 3, 4, 5, j);
j++;
SHA512_EXP(5, 6, 7, 0, 1, 2, 3, 4, j);
j++;
SHA512_EXP(4, 5, 6, 7, 0, 1, 2, 3, j);
j++;
SHA512_EXP(3, 4, 5, 6, 7, 0, 1, 2, j);
j++;
SHA512_EXP(2, 3, 4, 5, 6, 7, 0, 1, j);
j++;
SHA512_EXP(1, 2, 3, 4, 5, 6, 7, 0, j);
j++;
} while (j < 80);
ctx->h[0] += wv[0];
ctx->h[1] += wv[1];
ctx->h[2] += wv[2];
ctx->h[3] += wv[3];
ctx->h[4] += wv[4];
ctx->h[5] += wv[5];
ctx->h[6] += wv[6];
ctx->h[7] += wv[7];
}
}
static void _sha512_init(sha512_ctx * ctx)
{
ctx->h[0] = sha512_h0[0];
ctx->h[1] = sha512_h0[1];
ctx->h[2] = sha512_h0[2];
ctx->h[3] = sha512_h0[3];
ctx->h[4] = sha512_h0[4];
ctx->h[5] = sha512_h0[5];
ctx->h[6] = sha512_h0[6];
ctx->h[7] = sha512_h0[7];
ctx->len = 0;
ctx->tot_len = 0;
}
static void sha512_update(sha512_ctx * ctx, const unsigned char *message,
unsigned int len)
{
unsigned int block_nb;
unsigned int new_len, rem_len, tmp_len;
const unsigned char *shifted_message;
tmp_len = SHA512_BLOCK_SIZE - ctx->len;
rem_len = len < tmp_len ? len : tmp_len;
memcpy(&ctx->block[ctx->len], message, rem_len);
if (ctx->len + len < SHA512_BLOCK_SIZE) {
ctx->len += len;
return;
}
new_len = len - rem_len;
block_nb = new_len / SHA512_BLOCK_SIZE;
shifted_message = message + rem_len;
sha512_transf(ctx, ctx->block, 1);
sha512_transf(ctx, shifted_message, block_nb);
rem_len = new_len % SHA512_BLOCK_SIZE;
memcpy(ctx->block, &shifted_message[block_nb << 7], rem_len);
ctx->len = rem_len;
ctx->tot_len += (block_nb + 1) << 7;
}
static void sha512_final(sha512_ctx * ctx, unsigned char *digest)
{
unsigned int block_nb;
unsigned int pm_len;
unsigned int len_b;
block_nb = 1 + ((SHA512_BLOCK_SIZE - 17)
< (ctx->len % SHA512_BLOCK_SIZE));
len_b = (ctx->tot_len + ctx->len) << 3;
pm_len = block_nb << 7;
memset(ctx->block + ctx->len, 0, pm_len - ctx->len);
ctx->block[ctx->len] = 0x80;
UNPACK32(len_b, ctx->block + pm_len - 4);
sha512_transf(ctx, ctx->block, block_nb);
UNPACK64(ctx->h[0], &digest[0]);
UNPACK64(ctx->h[1], &digest[8]);
UNPACK64(ctx->h[2], &digest[16]);
UNPACK64(ctx->h[3], &digest[24]);
UNPACK64(ctx->h[4], &digest[32]);
UNPACK64(ctx->h[5], &digest[40]);
UNPACK64(ctx->h[6], &digest[48]);
UNPACK64(ctx->h[7], &digest[56]);
}
void sha512(const unsigned char *message, unsigned int len,unsigned char *digest)
{
sha512_ctx ctx;
_sha512_init(&ctx);
sha512_update(&ctx, message, len);
sha512_final(&ctx, digest);
}
int32_t init_hexbytes_noT(char *hexbytes,uint8_t *message,long len);
void calc_sha512(char *str,uint8_t *digest,uint8_t *message,int32_t len)
{
sha512_ctx ctx;
_sha512_init(&ctx);
sha512_update(&ctx, message, len);
sha512_final(&ctx, digest);
if ( str != 0 )
init_hexbytes_noT(str,digest,512>>3);
}
static void hmac_sha512_init(hmac_sha512_ctx * ctx, const unsigned char *key,unsigned int key_size)
{
unsigned int fill;
unsigned int num;
const unsigned char *key_used;
unsigned char key_temp[SHA512_DIGEST_SIZE];
int i;
if (key_size == SHA512_BLOCK_SIZE) {
key_used = key;
num = SHA512_BLOCK_SIZE;
} else {
if (key_size > SHA512_BLOCK_SIZE) {
num = SHA512_DIGEST_SIZE;
sha512(key, key_size, key_temp);
key_used = key_temp;
} else { /* key_size > SHA512_BLOCK_SIZE */
key_used = key;
num = key_size;
}
fill = SHA512_BLOCK_SIZE - num;
memset(ctx->block_ipad + num, 0x36, fill);
memset(ctx->block_opad + num, 0x5c, fill);
}
for (i = 0; i < (int)num; i++) {
ctx->block_ipad[i] = key_used[i] ^ 0x36;
ctx->block_opad[i] = key_used[i] ^ 0x5c;
}
_sha512_init(&ctx->ctx_inside);
sha512_update(&ctx->ctx_inside, ctx->block_ipad, SHA512_BLOCK_SIZE);
_sha512_init(&ctx->ctx_outside);
sha512_update(&ctx->ctx_outside, ctx->block_opad, SHA512_BLOCK_SIZE);
/* for hmac_reinit */
memcpy(&ctx->ctx_inside_reinit, &ctx->ctx_inside, sizeof(sha512_ctx));
memcpy(&ctx->ctx_outside_reinit, &ctx->ctx_outside, sizeof(sha512_ctx));
}
static void hmac_sha512_update(hmac_sha512_ctx * ctx, const unsigned char *message,
unsigned int message_len)
{
sha512_update(&ctx->ctx_inside, message, message_len);
}
static void hmac_sha512_final(hmac_sha512_ctx * ctx, unsigned char *mac,
unsigned int mac_size)
{
unsigned char digest_inside[SHA512_DIGEST_SIZE];
unsigned char mac_temp[SHA512_DIGEST_SIZE];
sha512_final(&ctx->ctx_inside, digest_inside);
sha512_update(&ctx->ctx_outside, digest_inside, SHA512_DIGEST_SIZE);
sha512_final(&ctx->ctx_outside, mac_temp);
memcpy(mac, mac_temp, mac_size);
}
void hmac_sha512(const unsigned char *key, unsigned int key_size,
const unsigned char *message, unsigned int message_len,
unsigned char *mac, unsigned mac_size)
{
hmac_sha512_ctx ctx;
hmac_sha512_init(&ctx, key, key_size);
hmac_sha512_update(&ctx, message, message_len);
hmac_sha512_final(&ctx, mac, mac_size);
}
int init_hexbytes_noT(char *hexbytes,unsigned char *message,long len);
#ifndef libtom_hmac
#define libtom_hmac
#include "hmac/crypt_argchk.c"
#include "hmac/hash_memory.c"
#include "hmac/hmac_init.c"
#include "hmac/hmac_process.c"
#include "hmac/hmac_done.c"
#include "hmac/hmac_file.c"
#include "hmac/hmac_memory.c"
#include "hmac/rmd128.c"
#include "hmac/rmd160.c"
#include "hmac/rmd256.c"
#include "hmac/rmd320.c"
#include "hmac/tiger.c"
#include "hmac/md2.c"
#include "hmac/md4.c"
#include "hmac/md5.c"
#include "hmac/sha1.c"
#include "hmac/whirl.c"
#include "hmac/sha224.c"
#include "hmac/sha256.c"
#include "hmac/sha384.c"
#include "hmac/sha512.c"
#endif
char *hmac_sha512_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[SHA512_DIGEST_SIZE],checkbuf[SHA512_DIGEST_SIZE*2 + 1]; char dest2[SHA512_DIGEST_SIZE*2 + 1]; unsigned long size = sizeof(checkbuf);
//int i;
hmac_sha512((const unsigned char *)key,key_size,(const unsigned char *)message,(int)strlen(message),mac,SHA512_DIGEST_SIZE);
//for (i=0; i<SHA512_DIGEST_SIZE; i++)
// sprintf(&dest[i*2],"%02x", mac[i]);
//dest[2 * SHA512_DIGEST_SIZE] = '\0';
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 )
printf("hmac_512 error: %s vs %s\n",dest,dest2);
return(dest);
}
char *hmac_sha384_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&sha384_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_sha256_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&sha256_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_sha224_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&sha224_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_rmd320_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&rmd320_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_rmd256_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&rmd256_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_rmd160_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&rmd160_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_rmd128_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&rmd128_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_sha1_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&sha1_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_md2_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&md2_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_md4_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&md4_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_md5_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&md5_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_tiger_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&tiger_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}
char *hmac_whirlpool_str(char *dest,char *key,int32_t key_size,char *message)
{
unsigned char mac[1024]; unsigned long size = sizeof(mac);
hmac_memory(&whirlpool_desc,(void *)key,key_size,(void *)message,strlen(message),mac,&size);
init_hexbytes_noT(dest,mac,(int32_t)size);
return(dest);
}

832
crypto777/iguana_OS.c

@ -0,0 +1,832 @@
/******************************************************************************
* Copyright © 2014-2015 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. *
* *
******************************************************************************/
// 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
// time functions are treated separately due to the confusions even in unix
#include "OS_portable.h"
#include <sys/stat.h>
#ifndef MAP_FILE
#define MAP_FILE 0
#endif
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.)); }
char *mbstr(char *str,double n)
{
if ( n < 1024*1024*10 )
sprintf(str,"%.3fkb",_kb(n));
else if ( n < 1024*1024*1024 )
sprintf(str,"%.1fMB",_mb(n));
else
sprintf(str,"%.2fGB",_gb(n));
return(str);
}
long myallocated(uint8_t type,long change)
{
static int64_t Total_allocated,HWM_allocated,Type_allocated[256];
int32_t i; int64_t total = 0; char buf[2049],str[65];
buf[0] = 0;
if ( type == 0 && change <= 0 )
{
for (i=0; i<256; i++)
{
if ( Type_allocated[i] != 0 )
{
total += Type_allocated[i];
if ( change == 0 )
sprintf(buf+strlen(buf),"(%c %s) ",i,mbstr(str,Type_allocated[i]));
}
}
if ( change == 0 )
{
sprintf(buf + strlen(buf),"-> total %lld %s",(long long)total,mbstr(str,total));
printf("%s\n",buf);
}
}
else
{
Type_allocated[type] += change;
Total_allocated += change;
if ( Total_allocated > HWM_allocated )
{
printf("HWM allocated %ld %s\n",(long)Total_allocated,mbstr(str,Total_allocated));
HWM_allocated = Total_allocated * 1.5;
}
}
return(total);
}
void *mycalloc(uint8_t type,int32_t n,long itemsize)
{
//static portable_mutex_t MEMmutex;
struct allocitem *item; int64_t allocsize = ((uint64_t)n * itemsize);
if ( type == 0 && n == 0 && itemsize == 0 )
{
//portable_mutex_init(&MEMmutex);
myfree(mycalloc('t',1024,1024 * 32),1024*1024*32);
return(0);
}
//portable_mutex_lock(&MEMmutex);
myallocated(type,allocsize);
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));
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));
}
void *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 *)((uint64_t)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);
}
void _myfree(uint8_t type,int32_t origallocsize,void *origptr,int32_t allocsize)
{
//portable_mutex_lock(&MEMmutex);
if ( allocsize == origallocsize )
{
myallocated(type,-allocsize);
// Type_allocated[type & 0xff] -= allocsize;
// Total_allocated -= allocsize;
//printf("myfree.%p size.%d %d type %x\n",origptr,allocsize,origallocsize,type);
free(origptr);
}
else
{
printf("myfree size error %d vs %d at %p\n",allocsize,origallocsize,origptr);
getchar();
}
//portable_mutex_unlock(&MEMmutex);
}
void myfree(void *_ptr,long allocsize)
{
struct allocitem *item = (void *)((long)_ptr - sizeof(struct allocitem));
_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 *myrealloc(uint8_t type,void *oldptr,long oldsize,long newsize)
{
void *newptr;
newptr = mycalloc(type,1,newsize);
//printf("newptr.%p type.%c oldsize.%ld newsize.%ld\n",newptr,type,oldsize,newsize);
if ( oldptr != 0 )
{
memcpy(newptr,oldptr,oldsize < newsize ? oldsize : newsize);
myfree(oldptr,oldsize);
}
return(newptr);
}
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;
realptr = mycalloc('A',1,(long)(allocsize + 16 + sizeof(realptr)));
tmp = _align16((long)realptr + sizeof(ptr));
memcpy(&ptr,&tmp,sizeof(ptr));
memcpy((void *)((long)ptr - sizeof(realptr)),&realptr,sizeof(realptr));
//printf("aligned_alloc(%llu) realptr.%p -> ptr.%p, diff.%ld\n",(long long)allocsize,realptr,ptr,((long)ptr - (long)realptr));
return(ptr);
}
int32_t myaligned_free(void *ptr,long size)
{
void *realptr;
long diff;
if ( ((long)ptr & 0xf) != 0 )
{
printf("misaligned ptr.%p being aligned_free\n",ptr);
return(-1);
}
memcpy(&realptr,(void *)((long)ptr - sizeof(realptr)),sizeof(realptr));
diff = ((long)ptr - (long)realptr);
if ( diff < (long)sizeof(ptr) || diff > 32 )
{
printf("ptr %p and realptr %p too far apart %ld\n",ptr,realptr,diff);
return(-2);
}
//printf("aligned_free: ptr %p -> realptr %p %ld\n",ptr,realptr,diff);
myfree(realptr,size + 16 + sizeof(realptr));
return(0);
}
void lock_queue(queue_t *queue)
{
if ( queue->initflag == 0 )
{
portable_mutex_init(&queue->mutex);
queue->initflag = 1;
}
portable_mutex_lock(&queue->mutex);
}
void queue_enqueue(char *name,queue_t *queue,struct queueitem *origitem,int32_t offsetflag)
{
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;
}
lock_queue(queue);
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)
{
struct queueitem *item = 0;
lock_queue(queue);
if ( queue->list != 0 )
{
item = queue->list;
DL_DELETE(queue->list,item);
//printf("queue_dequeue name.(%s) dequeue.%p list.%p\n",queue->name,item,queue->list);
}
portable_mutex_unlock(&queue->mutex);
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 queueitem *item = 0;
lock_queue(queue);
if ( queue->list != 0 )
{
DL_FOREACH(queue->list,item)
{
if ( item == copy || memcmp((void *)((long)item + sizeof(struct queueitem)),(void *)((long)item + sizeof(struct queueitem)),copysize) == 0 )
{
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);
return(item);
}
}
}
portable_mutex_unlock(&queue->mutex);
return(0);
}
void *queue_free(queue_t *queue)
{
struct queueitem *item = 0;
lock_queue(queue);
if ( queue->list != 0 )
{
DL_FOREACH(queue->list,item)
{
DL_DELETE(queue->list,item);
myfree(item,sizeof(struct queueitem));
}
//printf("name.(%s) dequeue.%p list.%p\n",queue->name,item,queue->list);
}
portable_mutex_unlock(&queue->mutex);
return(0);
}
void *queue_clone(queue_t *clone,queue_t *queue,int32_t size)
{
struct queueitem *ptr,*item = 0;
lock_queue(queue);
if ( queue->list != 0 )
{
DL_FOREACH(queue->list,item)
{
ptr = mycalloc('c',1,sizeof(*ptr));
memcpy(ptr,item,size);
queue_enqueue(queue->name,clone,ptr,0);
}
//printf("name.(%s) dequeue.%p list.%p\n",queue->name,item,queue->list);
}
portable_mutex_unlock(&queue->mutex);
return(0);
}
int32_t queue_size(queue_t *queue)
{
int32_t count = 0;
struct queueitem *tmp;
lock_queue(queue);
DL_COUNT(queue->list,tmp,count);
portable_mutex_unlock(&queue->mutex);
return count;
}
void iguana_memreset(struct OS_memspace *mem)
{
mem->used = 0;
#ifdef IGUANA_PEERALLOC
mem->availptrs = mem->outofptrs = mem->numptrs = 0;
memset(mem->ptrs,0,sizeof(mem->ptrs));
memset(mem->maxsizes,0,sizeof(mem->maxsizes));
memset(mem->allocsizes,0,sizeof(mem->allocsizes));
#endif
if ( mem->threadsafe != 0 )
portable_mutex_init(&mem->mutex);
}
void iguana_mempurge(struct OS_memspace *mem)
{
if ( mem->allocated != 0 && mem->ptr != 0 && mem->totalsize > 0 )
myfree(mem->ptr,mem->totalsize), mem->ptr = 0;
iguana_memreset(mem);
mem->totalsize = 0;
}
void *iguana_meminit(struct OS_memspace *mem,char *name,void *ptr,int64_t totalsize,int32_t threadsafe)
{
strcpy(mem->name,name);
if ( ptr == 0 )
{
if ( mem->ptr != 0 && mem->totalsize < totalsize )
{
iguana_mempurge(mem);
mem->totalsize = 0;
//printf("memptr.%p totalsize.%ld vs totalsize.%ld\n",mem->ptr,(long)mem->totalsize,(long)totalsize);
} //else printf("mem->ptr.%p mem->totalsize %ld\n",mem->ptr,(long)mem->totalsize);
if ( mem->ptr == 0 )
{
//static long alloc;
//alloc += totalsize;
//char str[65]; printf("iguana_meminit alloc %s\n",mbstr(str,alloc));
if ( (mem->ptr= mycalloc('d',1,totalsize)) == 0 )
{
printf("iguana_meminit: cant get %d bytes\n",(int32_t)totalsize);
exit(-1);
return(0);
}
mem->totalsize = totalsize;
} //else printf("memptr.%p\n",mem->ptr);
//printf("meminit.(%s) %d vs %ld\n",mem->name,(int32_t)totalsize,(long)mem->totalsize);
mem->allocated = 1;
}
else
{
iguana_mempurge(mem);
mem->ptr = ptr;
mem->totalsize = totalsize;
}
mem->threadsafe = threadsafe;
iguana_memreset(mem);
if ( mem->totalsize == 0 )
printf("meminit.%s ILLEGAL STATE null size\n",mem->name), getchar();
return(mem->ptr);
}
int64_t iguana_memallocated(struct OS_memspace *mem)
{
int64_t avail = (mem->totalsize - mem->used);
#ifdef IGUANA_PEERALLOC
int32_t i;
for (i=0; i<mem->numptrs; i++)
if ( mem->allocsizes[i] == 0 )
avail += mem->maxsizes[i];
#endif
return(avail);
}
void *iguana_memalloc(struct OS_memspace *mem,long size,int32_t clearflag)
{
int32_t modval; void *ptr = 0;
//printf("iguana_memalloc.%s size.%ld used.%llu of %llu, numptrs.%d avail.%d %lld\n",mem->name,size,(long long)mem->used,(long long)mem->totalsize,mem->numptrs,mem->availptrs,(long long)iguana_memallocated(mem));
//if ( mem->threadsafe != 0 )
// portable_mutex_lock(&mem->mutex);
#ifdef IGUANA_PEERALLOC
if ( mem->availptrs == mem->numptrs && mem->used > (mem->totalsize >> 1) )
iguana_memreset(mem);
#endif
if ( (mem->used + size) <= mem->totalsize )
{
ptr = (void *)((uint64_t)mem->ptr + (uint64_t)mem->used);
mem->used += size;
if ( size*clearflag != 0 )
memset(ptr,0,size);
if ( mem->alignflag != 0 )
{
if ( (modval= (mem->used % mem->alignflag)) != 0 )
mem->used += mem->alignflag - modval;
}
#ifdef IGUANA_PEERALLOC
if ( mem->numptrs < sizeof(mem->ptrs)/sizeof(*mem->ptrs) )
{
mem->allocsizes[mem->numptrs] = mem->maxsizes[mem->numptrs] = (int32_t)size;
mem->ptrs[mem->numptrs++] = ptr;
}
else
{
mem->outofptrs++;
printf("iguana_memalloc: numptrs.%d outofptrs.%d\n",mem->numptrs,mem->outofptrs);
}
#endif
//printf(">>>>>>>>> USED.%s alloc %ld used %ld alloc.%ld -> %s %p\n",mem->name,size,(long)mem->used,(long)mem->totalsize,mem->name,ptr);
} else printf("error memalloc mem.%p %s alloc %ld used %ld totalsize.%ld -> %s %p\n",mem,mem->name,size,(long)mem->used,(long)mem->totalsize,mem->name,ptr), getchar();//exit(-1);
//if ( mem->threadsafe != 0 )
// portable_mutex_unlock(&mem->mutex);
return(ptr);
}
int64_t iguana_memfree(struct OS_memspace *mem,void *ptr,int32_t size)
{
#ifdef IGUANA_PEERALLOC
int32_t i; int64_t avail = -1;
if ( mem->threadsafe != 0 )
portable_mutex_lock(&mem->mutex);
for (i=0; i<mem->numptrs; i++)
{
if ( ptr == mem->ptrs[i] )
{
if ( mem->allocsizes[i] == size )
{
mem->availptrs++;
mem->allocsizes[i] = 0;
avail = (mem->totalsize - mem->used);
//printf("avail %llu\n",(long long)avail);
} else printf("iguana_memfree.%s: mismatched size %d for ptr.%p %d\n",mem->name,size,ptr,mem->allocsizes[i]);
if ( mem->threadsafe != 0 )
portable_mutex_unlock(&mem->mutex);
return(avail);
}
}
if ( mem->threadsafe != 0 )
portable_mutex_unlock(&mem->mutex);
printf("iguana_memfree: cant find ptr.%p %d\n",ptr,size);
return(avail);
#else
printf("iguana_free not supported without #define IGUANA_PEERALLOC\n");
return(0);
#endif
}
int32_t OS_truncate(char *fname,long filesize)
{
return(OS_portable_truncate(fname,filesize));
}
char *OS_compatible_path(char *str)
{
return(OS_portable_path(str));
}
int32_t OS_renamefile(char *fname,char *newfname)
{
return(OS_portable_renamefile(fname,newfname));
}
int32_t OS_removefile(char *fname,int32_t scrubflag)
{
FILE *fp; long i,fpos; char tmp[512];
strcpy(tmp,fname);
OS_compatible_path(tmp);
if ( (fp= fopen(tmp,"rb+")) != 0 )
{
//printf("delete(%s)\n",fname);
if ( scrubflag != 0 )
{
fseek(fp,0,SEEK_END);
fpos = ftell(fp);
rewind(fp);
for (i=0; i<fpos; i++)
fputc(0xff,fp);
fflush(fp);
}
fclose(fp);
if ( (fp= fopen(tmp,"wb")) != 0 )
fclose(fp);
return(OS_portable_removefile(fname));
}
return(0);
}
void OS_ensure_directory(char *dirname)
{
FILE *fp; int32_t retval; char fname[512];
if ( OS_removefile(dirname,0) < 0 )
{
sprintf(fname,"tmp/%d",rand());
OS_renamefile(dirname,fname);
}
sprintf(fname,"%s/.tmpmarker",dirname);
if ( (fp= fopen(OS_compatible_path(fname),"rb")) == 0 )
{
if ( (fp= fopen(OS_compatible_path(dirname),"rb")) == 0 )
{
retval = mkdir(dirname
#ifndef _WIN32
,511
#endif
);
printf("mkdir.(%s) retval.%d errno.%d %s\n",dirname,retval,errno,strerror(errno));
} else fclose(fp), printf("dirname.(%s) exists\n",dirname);
if ( (fp= fopen(fname,"wb")) != 0 )
fclose(fp), printf("created.(%s)\n",fname);
else printf("cant create.(%s) errno.%d %s\n",fname,errno,strerror(errno));
} else fclose(fp), printf("%s exists\n",fname);
}
uint64_t OS_filesize(char *fname)
{
FILE *fp; uint64_t fsize = 0;
if ( (fp= fopen(fname,"rb")) != 0 )
{
fseek(fp,0,SEEK_END);
fsize = ftell(fp);
fclose(fp);
}
return(fsize);
}
int32_t OS_compare_files(char *fname,char *fname2)
{
int32_t offset,errs = 0;
long len,len2;
char buf[8192],buf2[8192];
FILE *fp,*fp2;
if ( (fp= fopen(OS_compatible_path(fname),"rb")) != 0 )
{
if ( (fp2= fopen(OS_compatible_path(fname2),"rb")) != 0 )
{
while ( (len= fread(buf,1,sizeof(buf),fp)) > 0 && (len2= fread(buf2,1,sizeof(buf2),fp2)) == len )
if ( (offset= memcmp(buf,buf2,len)) != 0 )
printf("compare error at offset.%d: (%s) src.%ld vs. (%s) dest.%ld\n",offset,fname,ftell(fp),fname2,ftell(fp2)), errs++;
fclose(fp2);
}
fclose(fp);
}
return(errs);
}
int64_t OS_copyfile(char *src,char *dest,int32_t cmpflag)
{
int64_t allocsize,len = -1;
char *buf;
FILE *srcfp,*destfp;
if ( (srcfp= fopen(OS_compatible_path(src),"rb")) != 0 )
{
if ( (destfp= fopen(OS_compatible_path(dest),"wb")) != 0 )
{
allocsize = 1024 * 1024 * 128L;
buf = mycalloc('F',1,allocsize);
while ( (len= fread(buf,1,allocsize,srcfp)) > 0 )
if ( (long)fwrite(buf,1,len,destfp) != len )
printf("write error at (%s) src.%ld vs. (%s) dest.%ld\n",src,ftell(srcfp),dest,ftell(destfp));
len = ftell(destfp);
fclose(destfp);
myfree(buf,allocsize);
}
fclose(srcfp);
}
if ( len < 0 || (cmpflag != 0 && OS_compare_files(src,dest) != 0) )
printf("Error copying files (%s) -> (%s)\n",src,dest), len = -1;
return(len);
}
int32_t OS_releasemap(void *ptr,uint64_t filesize)
{
int32_t retval;
if ( ptr == 0 )
{
printf("release_map_file: null ptr\n");
return(-1);
}
retval = munmap(ptr,filesize);
if ( retval != 0 )
printf("release_map_file: munmap error %p %llu: err %d\n",ptr,(long long)filesize,retval);
return(retval);
}
void _OS_closemap(struct OS_mappedptr *mp)
{
if ( mp->actually_allocated != 0 && mp->fileptr != 0 )
myaligned_free(mp->fileptr,mp->allocsize);
else if ( mp->fileptr != 0 )
OS_releasemap(mp->fileptr,mp->allocsize);
mp->fileptr = 0;
mp->closetime = (uint32_t)time(NULL);
mp->opentime = 0;
}
void OS_closemap(struct OS_mappedptr *mp)
{
struct OS_mappedptr tmp;
tmp = *mp;
_OS_closemap(mp);
memset(mp,0,sizeof(*mp));
mp->actually_allocated = tmp.actually_allocated;
mp->allocsize = tmp.allocsize;
mp->rwflag = tmp.rwflag;
strcpy(mp->fname,tmp.fname);
}
long OS_ensurefilesize(char *fname,long filesize,int32_t truncateflag)
{
FILE *fp;
char *zeroes;
long i,n,allocsize = 0;
//printf("ensure_filesize.(%s) %ld %s | ",fname,filesize,mbstr(filesize));
if ( (fp= fopen(OS_compatible_path(fname),"rb")) != 0 )
{
fseek(fp,0,SEEK_END);
allocsize = ftell(fp);
fclose(fp);
//printf("(%s) exists size.%ld\n",fname,allocsize);
}
else
{
//printf("try to create.(%s)\n",fname);
if ( (fp= fopen(OS_compatible_path(fname),"wb")) != 0 )
fclose(fp);
}
if ( allocsize < filesize )
{
//printf("filesize.%ld is less than %ld\n",filesize,allocsize);
if ( (fp= fopen(OS_compatible_path(fname),"ab")) != 0 )
{
zeroes = myaligned_alloc(16L*1024*1024);
memset(zeroes,0,16*1024*1024);
n = filesize - allocsize;
while ( n > 16*1024*1024 )
{
fwrite(zeroes,1,16*1024*1024,fp);
n -= 16*1024*1024;
fprintf(stderr,"+");
}
for (i=0; i<n; i++)
fputc(0,fp);
fclose(fp);
myaligned_free(zeroes,16L*1024*1024);
}
return(filesize);
}
else if ( allocsize*truncateflag > filesize )
{
OS_truncate(fname,filesize);
return(filesize);
}
else return(allocsize);
}
int32_t OS_openmap(struct OS_mappedptr *mp)
{
uint64_t allocsize = mp->allocsize;
if ( mp->actually_allocated != 0 )
{
if ( mp->fileptr == 0 )
mp->fileptr = myaligned_alloc(mp->allocsize);
else memset(mp->fileptr,0,mp->allocsize);
return(0);
}
else
{
if ( mp->fileptr != 0 )
{
//printf("opening already open mappedptr, pending %p\n",mp->pending);
OS_closemap(mp);
}
mp->allocsize = allocsize;
// printf("calling map_file with expected %ld\n",mp->allocsize);
mp->fileptr = OS_mapfile(mp->fname,&mp->allocsize,mp->rwflag);
if ( mp->fileptr == 0 || mp->allocsize != allocsize )
{
//printf("error mapping(%s) ptr %p mapped %ld vs allocsize %ld\n",mp->fname,mp->fileptr,mp->allocsize,allocsize);
return(-1);
}
mp->closetime = 0;
mp->opentime = (uint32_t)time(NULL);
}
return(0);
}
void *OS_mappedptr(void **ptrp,struct OS_mappedptr *mp,uint64_t allocsize,int32_t rwflag,char *fname)
{
uint64_t filesize;
mp->actually_allocated = 0;//!os_supports_mappedfiles();
if ( fname != 0 )
{
if ( strcmp(mp->fname,fname) == 0 )
{
if ( mp->fileptr != 0 )
{
OS_releasemap(mp->fileptr,mp->allocsize);
mp->fileptr = 0;
}
OS_openmap(mp);
if ( ptrp != 0 )
(*ptrp) = mp->fileptr;
return(mp->fileptr);
}
strcpy(mp->fname,fname);
}
else mp->actually_allocated = 1;
mp->rwflag = rwflag;
mp->allocsize = allocsize;
if ( rwflag != 0 && mp->actually_allocated == 0 && allocsize != 0 )
allocsize = OS_ensurefilesize(fname,allocsize,0);
if ( OS_openmap(mp) != 0 )
{
char str[65];
//printf("init_mappedptr %s.rwflag.%d | ",fname,rwflag);
if ( allocsize != 0 )
printf("error mapping(%s) rwflag.%d ptr %p mapped %llu vs allocsize %llu %s\n",fname,rwflag,mp->fileptr,(long long)mp->allocsize,(long long)allocsize,mbstr(str,allocsize));
else allocsize = mp->allocsize;
if ( rwflag != 0 && allocsize != mp->allocsize )
{
filesize = mp->allocsize;
if ( mp->fileptr != 0 )
OS_releasemap(mp->fileptr,mp->allocsize);
mp->allocsize = allocsize;
mp->changedsize = (allocsize - filesize);
OS_openmap(mp);
if ( mp->fileptr == 0 || mp->allocsize != allocsize )
{
printf("SECOND error mapping(%s) ptr %p mapped %llu vs allocsize %llu\n",fname,mp->fileptr,(long long)mp->allocsize,(long long)allocsize);
exit(-1);
}
}
}
if ( ptrp != 0 )
(*ptrp) = mp->fileptr;
return(mp->fileptr);
}
void *OS_filealloc(struct OS_mappedptr *M,char *fname,struct OS_memspace *mem,long size)
{
//printf("mem->used %ld size.%ld | size.%ld\n",mem->used,size,mem->size);
//printf("filemalloc.(%s) new space.%ld %s\n",fname,mem->size,mbstr(size));
memset(M,0,sizeof(*M));
mem->totalsize = size;
if ( OS_mappedptr(0,M,mem->totalsize,1,fname) == 0 )
{
printf("couldnt create mapped file.(%s)\n",fname);
exit(-1);
}
mem->ptr = M->fileptr;
mem->used = 0;
return(M->fileptr);
}
void *OS_loadfile(char *fname,char **bufp,int64_t *lenp,int64_t *allocsizep)
{
FILE *fp;
int64_t filesize,buflen = *allocsizep;
char *buf = *bufp;
*lenp = 0;
if ( (fp= fopen(OS_compatible_path(fname),"rb")) != 0 )
{
fseek(fp,0,SEEK_END);
filesize = ftell(fp);
if ( filesize == 0 )
{
fclose(fp);
*lenp = 0;
return(0);
}
if ( filesize > buflen-1 )
{
*allocsizep = filesize+1;
*bufp = buf = realloc(buf,(long)*allocsizep);
}
rewind(fp);
if ( buf == 0 )
printf("Null buf ???\n");
else
{
if ( fread(buf,1,(long)filesize,fp) != (unsigned long)filesize )
printf("error reading filesize.%ld\n",(long)filesize);
buf[filesize] = 0;
}
fclose(fp);
*lenp = filesize;
}
return(buf);
}
void *OS_filestr(int64_t *allocsizep,char *fname)
{
int64_t filesize = 0; char *buf = 0;
*allocsizep = 0;
return(OS_loadfile(fname,&buf,&filesize,allocsizep));
}
// following functions cant be fully implemented in one or more OS
void *OS_mapfile(char *fname,long *filesizep,int32_t enablewrite) // win and pnacl dont have mmap64
{
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));
}
void OS_init()
{
return(OS_portable_init());
}

819
crypto777/iguana_utils.c

@ -0,0 +1,819 @@
/******************************************************************************
* Copyright © 2014-2015 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
#include "../iguana/iguana777.h"
bits256 bits256_doublesha256(char *hashstr,uint8_t *data,int32_t datalen)
{
bits256 hash,hash2; int32_t i;
vcalc_sha256(0,hash.bytes,data,datalen);
vcalc_sha256(0,hash2.bytes,hash.bytes,sizeof(hash));
for (i=0; i<sizeof(hash); i++)
hash.bytes[i] = hash2.bytes[sizeof(hash) - 1 - i];
if ( hashstr != 0 )
init_hexbytes_noT(hashstr,hash.bytes,sizeof(hash));
return(hash);
}
char *bits256_str(char hexstr[65],bits256 x)
{
init_hexbytes_noT(hexstr,x.bytes,sizeof(x));
return(hexstr);
}
char *bits256_lstr(char hexstr[65],bits256 x)
{
bits256 revx; int32_t i;
for (i=0; i<32; i++)
revx.bytes[i] = x.bytes[31-i];
init_hexbytes_noT(hexstr,revx.bytes,sizeof(revx));
return(hexstr);
}
bits256 bits256_add(bits256 a,bits256 b)
{
int32_t i; bits256 sum; uint64_t x,carry = 0;
memset(sum.bytes,0,sizeof(sum));
for (i=0; i<4; i++)
{
x = a.ulongs[i] + b.ulongs[i];
sum.ulongs[i] = (x + carry);
if ( x < a.ulongs[i] || x < b.ulongs[i] )
carry = 1;
else carry = 0;
}
return(sum);
}
int32_t bits256_cmp(bits256 a,bits256 b)
{
int32_t i;
for (i=0; i<4; i++)
{
if ( a.ulongs[i] > b.ulongs[i] )
return(1);
else if ( a.ulongs[i] < b.ulongs[i] )
return(-1);
}
return(0);
}
bits256 bits256_lshift(bits256 x)
{
int32_t i,carry,prevcarry = 0; uint64_t mask = (1LL << 63);
for (i=0; i<4; i++)
{
carry = ((mask & x.ulongs[i]) != 0);
x.ulongs[i] = (x.ulongs[i] << 1) | prevcarry;
prevcarry = carry;
}
return(x);
}
bits256 bits256_from_compact(uint32_t c)
{
uint32_t nbytes,nbits,i; bits256 x;
memset(x.bytes,0,sizeof(x));
nbytes = (c >> 24) & 0xFF;
nbits = (8 * (nbytes - 3));
x.ulongs[0] = c & 0xFFFFFF;
for (i=0; i<nbits; i++) // horrible inefficient
x = bits256_lshift(x);
return(x);
}
void calc_OP_HASH160(char hexstr[41],uint8_t hash160[20],char *pubkey)
{
uint8_t sha256[32],buf[4096]; int32_t len;
len = (int32_t)strlen(pubkey)/2;
if ( len > sizeof(buf) )
{
printf("calc_OP_HASH160 overflow len.%d vs %d\n",len,(int32_t)sizeof(buf));
return;
}
decode_hex(buf,len,pubkey);
vcalc_sha256(0,sha256,buf,len);
calc_rmd160(0,hash160,sha256,sizeof(sha256));
if ( 0 )
{
int i;
for (i=0; i<20; i++)
printf("%02x",hash160[i]);
printf("<- (%s)\n",pubkey);
}
if ( hexstr != 0 )
init_hexbytes_noT(hexstr,hash160,20);
}
double _dxblend(double *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 newval,slope;
if ( isnan(*destp) != 0 )
*destp = 0.;
if ( isnan(val) != 0 )
return(0.);
if ( *destp == 0 )
{
*destp = val;
return(0);
}
newval = _dxblend(destp,val,decay);
if ( newval < SMALLVAL && newval > -SMALLVAL )
{
// non-zero marker for actual values close to or even equal to zero
if ( newval < 0. )
newval = -SMALLVAL;
else newval = SMALLVAL;
}
if ( *destp != 0. && newval != 0. )
slope = (newval - *destp);
else slope = 0.;
*destp = newval;
return(slope);
}
/*queue_t TerminateQ; int32_t TerminateQ_queued;
void iguana_terminator(void *arg)
{
struct iguana_thread *t; uint32_t lastdisp = 0; int32_t terminated = 0;
printf("iguana_terminator\n");
while ( 1 )
{
if ( (t= queue_dequeue(&TerminateQ,0)) != 0 )
{
printf("terminate.%p\n",t);
iguana_terminate(t);
terminated++;
continue;
}
sleep(1);
if ( time(NULL) > lastdisp+60 )
{
lastdisp = (uint32_t)time(NULL);
printf("TerminateQ %d terminated of %d queued\n",terminated,TerminateQ_queued);
}
}
}*/
int32_t iguana_numthreads(struct iguana_info *coin,int32_t mask)
{
int32_t i,sum = 0;
for (i=0; i<8; i++)
if ( ((1 << i) & mask) != 0 )
sum += (coin->Launched[i] - coin->Terminated[i]);
return(sum);
}
void iguana_launcher(void *ptr)
{
struct iguana_thread *t = ptr; struct iguana_info *coin;
coin = t->coin;
t->funcp(t->arg);
coin->Terminated[t->type % (sizeof(coin->Terminated)/sizeof(*coin->Terminated))]++;
queue_enqueue("TerminateQ",&coin->TerminateQ,&t->DL,0);
}
void iguana_terminate(struct iguana_info *coin,struct iguana_thread *t)
{
int32_t retval;
retval = pthread_join(t->handle,NULL);
if ( retval != 0 )
printf("error.%d terminating t.%p thread.%s\n",retval,t,t->name);
myfree(t,sizeof(*t));
}
struct iguana_thread *iguana_launch(struct iguana_info *coin,char *name,iguana_func funcp,void *arg,uint8_t type)
{
int32_t retval; struct iguana_thread *t;
t = mycalloc('Z',1,sizeof(*t));
strcpy(t->name,name);
t->coin = coin;
t->funcp = funcp;
t->arg = arg;
t->type = (type % (sizeof(coin->Terminated)/sizeof(*coin->Terminated)));
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(&coin->TerminateQ,0)) != 0 )
{
if ( (rand() % 100000) == 0 )
printf("terminated.%d launched.%d terminate.%p\n",coin->Terminated[t->type],coin->Launched[t->type],t);
iguana_terminate(coin,t);
}
return(t);
}
char hexbyte(int32_t c)
{
c &= 0xf;
if ( c < 10 )
return('0'+c);
else if ( c < 16 )
return('a'+c-10);
else return(0);
}
int32_t _unhex(char c)
{
if ( c >= '0' && c <= '9' )
return(c - '0');
else if ( c >= 'a' && c <= 'f' )
return(c - 'a' + 10);
else if ( c >= 'A' && c <= 'F' )
return(c - 'A' + 10);
return(-1);
}
int32_t is_hexstr(char *str,int32_t n)
{
int32_t i;
if ( str == 0 || str[0] == 0 )
return(0);
for (i=0; str[i]!=0&&(i<n||n==0); i++)
if ( _unhex(str[i]) < 0 )
return(0);
return(1);
}
int32_t unhex(char c)
{
int32_t hex;
if ( (hex= _unhex(c)) < 0 )
{
//printf("unhex: illegal hexchar.(%c)\n",c);
}
return(hex);
}
unsigned char _decode_hex(char *hex) { return((unhex(hex[0])<<4) | unhex(hex[1])); }
int32_t decode_hex(unsigned char *bytes,int32_t n,char *hex)
{
int32_t adjust,i = 0;
//printf("decode.(%s)\n",hex);
if ( is_hexstr(hex,64) == 0 )
{
memset(bytes,0,n);
return(n);
}
if ( n == 0 || (hex[n*2+1] == 0 && hex[n*2] != 0) )
{
bytes[0] = unhex(hex[0]);
printf("decode_hex n.%d hex[0] (%c) -> %d hex.(%s) [n*2+1: %d] [n*2: %d %c] len.%ld\n",n,hex[0],bytes[0],hex,hex[n*2+1],hex[n*2],hex[n*2],(long)strlen(hex));
#ifdef __APPLE__
getchar();
#endif
bytes++;
hex++;
adjust = 1;
} else adjust = 0;
if ( n > 0 )
{
for (i=0; i<n; i++)
bytes[i] = _decode_hex(&hex[i*2]);
}
//bytes[i] = 0;
return(n + adjust);
}
int32_t init_hexbytes_noT(char *hexbytes,unsigned char *message,long len)
{
int32_t i;
if ( len == 0 )
{
hexbytes[0] = 0;
return(1);
}
for (i=0; i<len; i++)
{
hexbytes[i*2] = hexbyte((message[i]>>4) & 0xf);
hexbytes[i*2 + 1] = hexbyte(message[i] & 0xf);
//printf("i.%d (%02x) [%c%c]\n",i,message[i],hexbytes[i*2],hexbytes[i*2+1]);
}
hexbytes[len*2] = 0;
//printf("len.%ld\n",len*2+1);
return((int32_t)len*2+1);
}
void touppercase(char *str)
{
int32_t i;
if ( str == 0 || str[0] == 0 )
return;
for (i=0; str[i]!=0; i++)
str[i] = toupper(((int32_t)str[i]));
}
long _stripwhite(char *buf,int accept)
{
int32_t i,j,c;
if ( buf == 0 || buf[0] == 0 )
return(0);
for (i=j=0; buf[i]!=0; i++)
{
buf[j] = c = buf[i];
if ( c == accept || (c != ' ' && c != '\n' && c != '\r' && c != '\t' && c != '\b') )
j++;
}
buf[j] = 0;
return(j);
}
char *clonestr(char *str)
{
char *clone;
if ( str == 0 || str[0] == 0 )
{
printf("warning cloning nullstr.%p\n",str);
#ifdef __APPLE__
while ( 1 ) sleep(1);
#endif
str = (char *)"<nullstr>";
}
clone = (char *)malloc(strlen(str)+16);
strcpy(clone,str);
return(clone);
}
int32_t safecopy(char *dest,char *src,long len)
{
int32_t i = -1;
if ( dest != 0 )
memset(dest,0,len);
if ( src != 0 && dest != 0 )
{
for (i=0; i<len&&src[i]!=0; i++)
dest[i] = src[i];
if ( i == len )
{
printf("safecopy: %s too long %ld\n",src,len);
#ifdef __APPLE__
//getchar();
#endif
return(-1);
}
dest[i] = 0;
}
return(i);
}
void escape_code(char *escaped,char *str)
{
int32_t i,j,c; char esc[16];
for (i=j=0; str[i]!=0; i++)
{
if ( ((c= str[i]) >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') )
escaped[j++] = c;
else
{
sprintf(esc,"%%%02X",c);
//sprintf(esc,"\\\\%c",c);
strcpy(escaped + j,esc);
j += strlen(esc);
}
}
escaped[j] = 0;
//printf("escape_code: (%s) -> (%s)\n",str,escaped);
}
int32_t is_zeroes(char *str)
{
int32_t i;
if ( str == 0 || str[0] == 0 )
return(1);
for (i=0; str[i]!=0; i++)
if ( str[i] != '0' )
return(0);
return(1);
}
int64_t conv_floatstr(char *numstr)
{
double val,corr;
val = atof(numstr);
corr = (val < 0.) ? -0.50000000001 : 0.50000000001;
return((int64_t)(val * SATOSHIDEN + corr));
}
int32_t has_backslash(char *str)
{
int32_t i;
if ( str == 0 || str[0] == 0 )
return(0);
for (i=0; str[i]!=0; i++)
if ( str[i] == '\\' )
return(1);
return(0);
}
/*int32_t iguana_sortbignum(void *buf,int32_t size,uint32_t num,int32_t structsize,int32_t dir)
{
int32_t retval = 0;
if ( dir > 0 )
{
if ( size == 32 )
qsort(buf,num,structsize,_increasing_bits256);
else if ( size == 20 )
qsort(buf,num,structsize,_increasing_rmd160);
else retval = -1;
}
else
{
if ( size == 32 )
qsort(buf,num,structsize,_decreasing_bits256);
else if ( size == 20 )
qsort(buf,num,structsize,_decreasing_rmd160);
else retval = -1;
}
if ( retval < 0 )
printf("iguana_sortbignum only does bits256 and rmd160 for now\n");
return(retval);
}
*/
void tolowercase(char *str)
{
int32_t i;
if ( str == 0 || str[0] == 0 )
return;
for (i=0; str[i]!=0; i++)
str[i] = tolower(((int32_t)str[i]));
}
int32_t is_decimalstr(char *str)
{
int32_t i;
if ( str == 0 || str[0] == 0 )
return(0);
for (i=0; str[i]!=0; i++)
if ( str[i] < '0' || str[i] > '9' )
return(0);
return(i);
}
int32_t unstringbits(char *buf,uint64_t bits)
{
int32_t i;
for (i=0; i<8; i++,bits>>=8)
if ( (buf[i]= (char)(bits & 0xff)) == 0 )
break;
buf[i] = 0;
return(i);
}
uint64_t stringbits(char *str)
{
uint64_t bits = 0;
if ( str == 0 )
return(0);
int32_t i,n = (int32_t)strlen(str);
if ( n > 8 )
n = 8;
for (i=n-1; i>=0; i--)
bits = (bits << 8) | (str[i] & 0xff);
//printf("(%s) -> %llx %llu\n",str,(long long)bits,(long long)bits);
return(bits);
}
char *unstringify(char *str)
{
int32_t i,j,n;
if ( str == 0 )
return(0);
else if ( str[0] == 0 )
return(str);
n = (int32_t)strlen(str);
if ( str[0] == '"' && str[n-1] == '"' )
str[n-1] = 0, i = 1;
else i = 0;
for (j=0; str[i]!=0; i++)
{
if ( str[i] == '\\' && (str[i+1] == 't' || str[i+1] == 'n' || str[i+1] == 'b' || str[i+1] == 'r') )
i++;
else if ( str[i] == '\\' && str[i+1] == '"' )
str[j++] = '"', i++;
else str[j++] = str[i];
}
str[j] = 0;
return(str);
}
void reverse_hexstr(char *str)
{
int i,n;
char *rev;
n = (int32_t)strlen(str);
rev = (char *)malloc(n + 1);
for (i=0; i<n; i+=2)
{
rev[n-2-i] = str[i];
rev[n-1-i] = str[i+1];
}
rev[n] = 0;
strcpy(str,rev);
free(rev);
}
int32_t nn_base64_decode (const char *in, size_t in_len,uint8_t *out, size_t out_len)
{
uint32_t ii,io,rem,v; uint8_t ch;
// Unrolled lookup of ASCII code points. 0xFF represents a non-base64 valid character.
const uint8_t DECODEMAP [256] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0x3E, 0xFF, 0xFF, 0xFF, 0x3F,
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B,
0x3C, 0x3D, 0xFF, 0xFF, 0xFF, 0x3E, 0xFF, 0xFF,
0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20,
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30,
0x31, 0x32, 0x33, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
for (io = 0, ii = 0, v = 0, rem = 0; ii < in_len; ii++) {
if (isspace ((uint32_t)in [ii]))
continue;
if (in [ii] == '=')
break;
ch = DECODEMAP [(uint32_t)in [ii]];
/* Discard invalid characters as per RFC 2045. */
if (ch == 0xFF)
break;
v = (v << 6) | ch;
rem += 6;
if (rem >= 8) {
rem -= 8;
if (io >= out_len)
return -ENOBUFS;
out [io++] = (v >> rem) & 255;
}
}
if (rem >= 8) {
rem -= 8;
if (io >= out_len)
return -ENOBUFS;
out [io++] = (v >> rem) & 255;
}
return io;
}
int32_t nn_base64_encode (const uint8_t *in, size_t in_len,char *out, size_t out_len)
{
uint32_t ii,io,rem,v; uint8_t ch;
const uint8_t ENCODEMAP [64] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
for (io = 0, ii = 0, v = 0, rem = 0; ii < in_len; ii++) {
ch = in [ii];
v = (v << 8) | ch;
rem += 8;
while (rem >= 6) {
rem -= 6;
if (io >= out_len)
return -ENOBUFS;
out [io++] = ENCODEMAP [(v >> rem) & 63];
}
}
if (rem) {
v <<= (6 - rem);
if (io >= out_len)
return -ENOBUFS;
out [io++] = ENCODEMAP [v & 63];
}
/* Pad to a multiple of 3. */
while (io & 3) {
if (io >= out_len)
return -ENOBUFS;
out [io++] = '=';
}
if (io >= out_len)
return -ENOBUFS;
out [io] = '\0';
return io;
}
/*
NXT address converter,
Ported from original javascript (nxtchg)
To C by Jones
*/
int32_t gexp[] = {1, 2, 4, 8, 16, 5, 10, 20, 13, 26, 17, 7, 14, 28, 29, 31, 27, 19, 3, 6, 12, 24, 21, 15, 30, 25, 23, 11, 22, 9, 18, 1};
int32_t glog[] = {0, 0, 1, 18, 2, 5, 19, 11, 3, 29, 6, 27, 20, 8, 12, 23, 4, 10, 30, 17, 7, 22, 28, 26, 21, 25, 9, 16, 13, 14, 24, 15};
int32_t cwmap[] = {3, 2, 1, 0, 7, 6, 5, 4, 13, 14, 15, 16, 12, 8, 9, 10, 11};
char alphabet[] = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
int32_t gmult(int32_t a,int32_t b)
{
if ( a == 0 || b == 0 )
return 0;
int32_t idx = (glog[a] + glog[b]) % 31;
return gexp[idx];
}
int32_t letterval(char letter)
{
int32_t ret = 0;
if ( letter < '9' )
ret = letter - '2';
else
{
ret = letter - 'A' + 8;
if ( letter > 'I' )
ret--;
if ( letter > 'O' )
ret--;
}
return ret;
}
uint64_t RS_decode(char *rs)
{
int32_t code[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int32_t i,p = 4;
if ( strncmp("NXT-",rs,4) != 0 )
return(0);
for (i=0; i<17; i++)
{
code[cwmap[i]] = letterval(rs[p]);
p++;
if ( rs[p] == '-' )
p++;
}
uint64_t out = 0;
for (i=12; i>=0; i--)
out = out * 32 + code[i];
return out;
}
int32_t RS_encode(char *rsaddr,uint64_t id)
{
int32_t a,code[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int32_t inp[32],out[32],i,j,fb,pos = 0,len = 0;
char acc[64];
rsaddr[0] = 0;
memset(inp,0,sizeof(inp));
memset(out,0,sizeof(out));
memset(acc,0,sizeof(acc));
expand_nxt64bits(acc,id);
//sprintf(acc,"%llu",(long long)id);
for (a=0; *(acc+a) != '\0'; a++)
len++;
if ( len == 20 && *acc != '1' )
{
printf("error (%s) doesnt start with 1",acc);
return(-1);
}
for (i=0; i<len; i++)
inp[i] = (int32_t)*(acc+i) - (int32_t)'0';
int32_t divide = 0;
int32_t newlen = 0;
do // base 10 to base 32 conversion
{
divide = 0;
newlen = 0;
for (i=0; i<len; i++)
{
divide = divide * 10 + inp[i];
if (divide >= 32)
{
inp[newlen++] = divide >> 5;
divide &= 31;
}
else if ( newlen > 0 )
inp[newlen++] = 0;
}
len = newlen;
out[pos++] = divide;
} while ( newlen != 0 );
for (i=0; i<13; i++) // copy to code in reverse, pad with 0's
code[i] = (--pos >= 0 ? out[i] : 0);
int32_t p[] = {0, 0, 0, 0};
for (i=12; i>=0; i--)
{
fb = code[i] ^ p[3];
p[3] = p[2] ^ gmult(30, fb);
p[2] = p[1] ^ gmult(6, fb);
p[1] = p[0] ^ gmult(9, fb);
p[0] = gmult(17, fb);
}
code[13] = p[0];
code[14] = p[1];
code[15] = p[2];
code[16] = p[3];
strcpy(rsaddr,"NXT-");
j=4;
for (i=0; i<17; i++)
{
rsaddr[j++] = alphabet[code[cwmap[i]]];
if ( (j % 5) == 3 && j < 20 )
rsaddr[j++] = '-';
}
rsaddr[j] = 0;
return(0);
}
void calc_base64_encodestr(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
nn_base64_encode(msg,len,hexstr,64);
}
void calc_base64_decodestr(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
nn_base64_decode((void *)msg,len,(void *)hexstr,1024);
}
void sha256_sha256(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
bits256_doublesha256(hexstr,msg,len);
}
void rmd160ofsha256(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
uint8_t sha256[32];
vcalc_sha256(0,sha256,(void *)msg,len);
calc_rmd160(hexstr,buf,sha256,sizeof(sha256));
}
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 = calc_crc32(0,msg,len);
init_hexbytes_noT(hexstr,(uint8_t *)&crc,sizeof(crc));
}
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);
RS_encode(hexstr,nxt64bits);
}
void calc_curve25519_str(char *hexstr,uint8_t *buf,uint8_t *msg,int32_t len)
{
bits256 x = curve25519(*(bits256 *)msg,curve25519_basepoint9());
init_hexbytes_noT(hexstr,x.bytes,sizeof(x));
}

605
crypto777/inet.c

@ -0,0 +1,605 @@
/*
* Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
* Copyright (c) 1996-1999 by Internet Software Consortium.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifdef DEFINES_ONLY
#ifndef crypto777_inet_h
#define crypto777_inet_h
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
#ifdef _WIN32
#include <nonportable.h>
#else
#include "../includes/nonportable.h"
#endif
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#else
#ifndef crypto777_system777_c
#define crypto777_system777_c
#ifndef crypto777_system777_h
#define DEFINES_ONLY
#include "inet.c"
#undef DEFINES_ONLY
#endif
static int inet_ntop4(unsigned char *src, char *dst, size_t size);
static int inet_ntop6(unsigned char *src, char *dst, size_t size);
static int inet_pton4(char *src, unsigned char *dst);
static int inet_pton6(char *src, unsigned char *dst);
int32_t portable_ntop(int af, void* src, char* dst, size_t size)
{
switch (af) {
case AF_INET:
return (inet_ntop4(src, dst, size));
case AF_INET6:
return (inet_ntop6(src, dst, size));
default:
return -1;
}
/* NOTREACHED */
}
static int inet_ntop4(unsigned char *src, char *dst, size_t size) {
static const char fmt[] = "%u.%u.%u.%u";
char tmp[sizeof "255.255.255.255"];
int l;
#ifndef _WIN32
l = snprintf(tmp, sizeof(tmp), fmt, src[0], src[1], src[2], src[3]);
#else
l = _snprintf(tmp, sizeof(tmp), fmt, src[0], src[1], src[2], src[3]);
#endif
if (l <= 0 || (size_t) l >= size) {
return -1;
}
strncpy(dst, tmp, size);
dst[size - 1] = '\0';
return 0;
}
static int inet_ntop6(unsigned char *src, char *dst, size_t size) {
/*
* Note that int32_t and int16_t need only be "at least" large enough
* to contain a value of the specified size. On some systems, like
* Crays, there is no such thing as an integer variable with 16 bits.
* Keep this in mind if you think this function should have been coded
* to use pointer overlays. All the world's not a VAX.
*/
char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp;
struct { int base, len; } best, cur;
unsigned int words[sizeof(struct in6_addr) / sizeof(uint16_t)];
int i;
/*
* Preprocess:
* Copy the input (bytewise) array into a wordwise array.
* Find the longest run of 0x00's in src[] for :: shorthanding.
*/
memset(words, '\0', sizeof words);
for (i = 0; i < (int) sizeof(struct in6_addr); i++)
words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
best.base = -1;
best.len = 0;
cur.base = -1;
cur.len = 0;
for (i = 0; i < (int)(sizeof(struct in6_addr) / sizeof(uint16_t)); i++) {
if (words[i] == 0) {
if (cur.base == -1)
cur.base = i, cur.len = 1;
else
cur.len++;
} else {
if (cur.base != -1) {
if (best.base == -1 || cur.len > best.len)
best = cur;
cur.base = -1;
}
}
}
if (cur.base != -1) {
if (best.base == -1 || cur.len > best.len)
best = cur;
}
if (best.base != -1 && best.len < 2)
best.base = -1;
/*
* Format the result.
*/
tp = tmp;
for (i = 0; i < (int)(sizeof(struct in6_addr) / sizeof(uint16_t)); i++) {
/* Are we inside the best run of 0x00's? */
if (best.base != -1 && i >= best.base &&
i < (best.base + best.len)) {
if (i == best.base)
*tp++ = ':';
continue;
}
/* Are we following an initial run of 0x00s or any real hex? */
if (i != 0)
*tp++ = ':';
/* Is this address an encapsulated IPv4? */
if (i == 6 && best.base == 0 && (best.len == 6 ||
(best.len == 7 && words[7] != 0x0001) ||
(best.len == 5 && words[5] == 0xffff))) {
int err = inet_ntop4(src+12, tp, sizeof tmp - (tp - tmp));
if (err)
return err;
tp += strlen(tp);
break;
}
tp += sprintf(tp, "%x", words[i]);
}
/* Was it a trailing run of 0x00's? */
if (best.base != -1 && (best.base + best.len) == (sizeof(struct in6_addr) / sizeof(uint16_t)))
*tp++ = ':';
*tp++ = '\0';
/*
* Check for overflow, copy, and we're done.
*/
if ((size_t)(tp - tmp) > size) {
return ENOSPC;
}
strcpy(dst, tmp);
return 0;
}
int portable_pton(int af, char* src, void* dst)
{
switch (af) {
case AF_INET:
return (inet_pton4(src, dst));
case AF_INET6:
return (inet_pton6(src, dst));
default:
return EAFNOSUPPORT;
}
/* NOTREACHED */
}
static int inet_pton4(char *src, unsigned char *dst) {
static const char digits[] = "0123456789";
int saw_digit, octets, ch;
unsigned char tmp[sizeof(struct in_addr)], *tp;
char savestr[64];
strcpy(savestr,src);
//printf("inet_pton4(%s)\n",src);
saw_digit = 0;
octets = 0;
*(tp = tmp) = 0;
while ((ch = (uint8_t)*src++) != '\0')
{
char *pch;
if ( (pch = strchr(digits, ch)) != NULL )
{
unsigned int nw = (unsigned int)(*tp * 10 + (pch - digits));
if (saw_digit && *tp == 0)
{
printf("inet_pton4 0\n");
return EINVAL;
}
if ( nw > 255 )
{
printf("inet_pton4 1\n");
return EINVAL;
}
*tp = nw;
if (!saw_digit) {
if (++octets > 4)
{
printf("inet_pton4 2\n");
return EINVAL;
}
saw_digit = 1;
}
} else if (ch == '.' && saw_digit) {
if (octets == 4)
{
printf("inet_pton4 3\n");
return EINVAL;
}
*++tp = 0;
saw_digit = 0;
} else
{
printf("inet_pton4 4 error.(%s)\n",savestr); getchar();
return EINVAL;
}
}
if (octets < 4)
{
printf("inet_pton4 5 error.(%s)\n",savestr); getchar();
return EINVAL;
}
memcpy(dst, tmp, sizeof(struct in_addr));
//printf("not errors %08x\n",*(int32_t *)dst);
return 0;
}
static int inet_pton6(char *src, unsigned char *dst) {
static char xdigits_l[] = "0123456789abcdef",
xdigits_u[] = "0123456789ABCDEF";
unsigned char tmp[sizeof(struct in6_addr)], *tp, *endp, *colonp;
char *xdigits, *curtok;
int ch, seen_xdigits;
unsigned int val;
memset((tp = tmp), '\0', sizeof tmp);
endp = tp + sizeof tmp;
colonp = NULL;
/* Leading :: requires some special handling. */
if (*src == ':')
if (*++src != ':')
return EINVAL;
curtok = src;
seen_xdigits = 0;
val = 0;
while ((ch = *src++) != '\0' && ch != '%') {
char *pch;
if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL)
pch = strchr((xdigits = xdigits_u), ch);
if (pch != NULL) {
val <<= 4;
val |= (pch - xdigits);
if (++seen_xdigits > 4)
return EINVAL;
continue;
}
if (ch == ':') {
curtok = src;
if (!seen_xdigits) {
if (colonp)
return EINVAL;
colonp = tp;
continue;
} else if (*src == '\0') {
return EINVAL;
}
if (tp + sizeof(uint16_t) > endp)
return EINVAL;
*tp++ = (unsigned char) (val >> 8) & 0xff;
*tp++ = (unsigned char) val & 0xff;
seen_xdigits = 0;
val = 0;
continue;
}
if (ch == '.' && ((tp + sizeof(struct in_addr)) <= endp)) {
int err;
/* Scope id present, parse ipv4 addr without it */
pch = strchr(curtok, '%');
if (pch != NULL) {
char tmp2[sizeof "255.255.255.255"];
memcpy(tmp2, curtok, pch - curtok);
curtok = tmp2;
src = pch;
}
err = inet_pton4(curtok, tp);
if (err == 0) {
tp += sizeof(struct in_addr);
seen_xdigits = 0;
break; /*%< '\\0' was seen by inet_pton4(). */
}
}
return EINVAL;
}
if (seen_xdigits) {
if (tp + sizeof(uint16_t) > endp)
return EINVAL;
*tp++ = (unsigned char) (val >> 8) & 0xff;
*tp++ = (unsigned char) val & 0xff;
}
if (colonp != NULL) {
/*
* Since some memmove()'s erroneously fail to handle
* overlapping regions, we'll do the shift by hand.
*/
int n = (int)(tp - colonp);
int i;
if (tp == endp)
return EINVAL;
for (i = 1; i <= n; i++) {
endp[- i] = colonp[n - i];
colonp[n - i] = 0;
}
tp = endp;
}
if (tp != endp)
return EINVAL;
memcpy(dst, tmp, sizeof tmp);
return 0;
}
int32_t parse_ipaddr(char *ipaddr,char *ip_port)
{
int32_t j,port = 0;
if ( ip_port != 0 && ip_port[0] != 0 )
{
strcpy(ipaddr,ip_port);
for (j=0; ipaddr[j]!=0&&j<60; j++)
if ( ipaddr[j] == ':' )
{
port = atoi(ipaddr+j+1);
break;
}
ipaddr[j] = 0;
//printf("%p.(%s) -> (%s:%d)\n",ip_port,ip_port,ipaddr,port);
} else strcpy(ipaddr,"127.0.0.1");
return(port);
}
uint64_t _calc_ipbits(char *ip_port)
{
int32_t port;
char ipaddr[64];
struct sockaddr_in addr;
port = parse_ipaddr(ipaddr,ip_port);
memset(&addr,0,sizeof(addr));
portable_pton(ip_port[0] == '[' ? AF_INET6 : AF_INET,ipaddr,&addr);
if ( 0 )
{
int i;
for (i=0; i<16; i++)
printf("%02x ",((uint8_t *)&addr)[i]);
printf("<- %s %x\n",ip_port,*(uint32_t *)&addr);
}
return(*(uint32_t *)&addr | ((uint64_t)port << 32));
}
void expand_ipbits(char *ipaddr,uint64_t ipbits)
{
uint16_t port;
struct sockaddr_in addr;
memset(&addr,0,sizeof(addr));
*(uint32_t *)&addr = (uint32_t)ipbits;
portable_ntop(AF_INET,&addr,ipaddr,64);
if ( (port= (uint16_t)(ipbits>>32)) != 0 )
sprintf(ipaddr + strlen(ipaddr),":%d",port);
//sprintf(ipaddr,"%d.%d.%d.%d",(ipbits>>24)&0xff,(ipbits>>16)&0xff,(ipbits>>8)&0xff,(ipbits&0xff));
}
uint64_t calc_ipbits(char *ip_port)
{
uint64_t ipbits; char ipaddr[64];
ipbits = _calc_ipbits(ip_port);
expand_ipbits(ipaddr,ipbits);
if ( ipbits != 0 && strcmp(ipaddr,ip_port) != 0 )
printf("calc_ipbits error: (%s) -> %llx -> (%s)\n",ip_port,(long long)ipbits,ipaddr);
return(ipbits);
}
char *ipbits_str(char ipaddr[64],uint64_t ipbits)
{
expand_ipbits(ipaddr,ipbits);
return(ipaddr);
}
uint32_t is_ipaddr(char *str)
{
uint64_t ipbits; char ipaddr[64];
if ( str != 0 && str[0] != 0 && (ipbits= calc_ipbits(str)) != 0 )
{
expand_ipbits(ipaddr,(uint32_t)ipbits);
if ( strncmp(ipaddr,str,strlen(ipaddr)) == 0 )
return((uint32_t)ipbits);
}
// printf("(%s) is not ipaddr\n",str);
return(0);
}
/*int32_t conv_domain(struct sockaddr_storage *ss,const char *addr,int32_t ipv4only)
{
//struct nn_dns dns; struct nn_dns_result dns_result;
size_t addrlen,sslen;
const char *semicolon,*hostname,*colon,*end;
addrlen = strlen(addr);
semicolon = strchr(addr,';');
hostname = semicolon ? semicolon + 1 : addr;
colon = strrchr(addr,':');
end = addr + addrlen;
if ( nn_slow(!colon) ) // Parse the port
return -EINVAL;
if ( nn_slow(nn_port_resolve (colon + 1, end - colon - 1) < 0) )
return -EINVAL;
// Check whether the host portion of the address is either a literal or a valid hostname.
if ( nn_dns_check_hostname(hostname,colon - hostname) < 0 && nn_literal_resolve(hostname,colon - hostname,ipv4only,ss,&sslen) < 0 )
return -EINVAL;
if ( semicolon != 0 && nn_iface_resolve(addr,semicolon - addr,ipv4only,ss,&sslen) < 0 ) // If local address is specified, check whether it is valid
return -ENODEV;
//memset(&dns_result,0,sizeof(dns_result));
// nn_dns_start(&dns,addr,addrlen,ipv4only,&dns_result);
// while ( *(uint32_t *)&dns_result.addr == 0 )
// usleep(10000);
return(0);
}*/
uint32_t conv_domainname(char *ipaddr,char *domain)
{
int32_t conv_domain(struct sockaddr_storage *ss,const char *addr,int32_t ipv4only);
int32_t ipv4only = 1;
uint32_t ipbits;
struct sockaddr_in ss;
if ( 0 && conv_domain((struct sockaddr_storage *)&ss,(const char *)domain,ipv4only) == 0 )
{
ipbits = *(uint32_t *)&ss.sin_addr;
expand_ipbits(ipaddr,ipbits);
if ( (uint32_t)calc_ipbits(ipaddr) == ipbits )
return(ipbits);
//printf("conv_domainname (%s) -> (%s)\n",domain,ipaddr);
} //else printf("error conv_domain.(%s)\n",domain);
return(0);
}
int32_t notlocalip(char *ipaddr)
{
if ( ipaddr == 0 || ipaddr[0] == 0 || strcmp("127.0.0.1",ipaddr) == 0 || strncmp("192.168",ipaddr,7) == 0 )
return(0);
else return(1);
}
int32_t is_remote_access(char *previpaddr)
{
if ( notlocalip(previpaddr) != 0 )
return(1);
else return(0);
}
/*struct sockaddr_in conv_ipbits(uint64_t ipbits)
{
char ipaddr[64];
uint16_t port;
struct hostent *host;
struct sockaddr_in server_addr;
port = (uint16_t)(ipbits>>32);
ipbits = (uint32_t)ipbits;
expand_ipbits(ipaddr,ipbits);
host = (struct hostent *)gethostbyname(ipaddr);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr = *((struct in_addr *)host->h_addr);
memset(&(server_addr.sin_zero),0,8);
return(server_addr);
}*/
char *conv_ipv6(char *ipv6addr)
{
unsigned char IPV4CHECK[10]; // 80 ZERO BITS for testing
char ipv4str[4096];
struct sockaddr_in6 ipv6sa;
in_addr_t *ipv4bin;
unsigned char *bytes;
int32_t isok;
memset(IPV4CHECK,0,sizeof(IPV4CHECK));
strcpy(ipv4str,ipv6addr);
//isok = !uv_inet_pton(AF_INET,(const char*)ipv6addr,&ipv6sa.sin6_addr);
//printf("isok.%d\n",isok);
isok = portable_pton(AF_INET6,ipv6addr,&ipv6sa.sin6_addr);
if ( isok == 0 )
{
bytes = ((struct sockaddr_in6 *)&ipv6sa)->sin6_addr.s6_addr;
if ( memcmp(bytes,IPV4CHECK,sizeof(IPV4CHECK)) != 0 ) // check its IPV4 really
{
bytes += 12;
ipv4bin = (in_addr_t *)bytes;
#ifndef _WIN32
if ( portable_ntop(AF_INET,ipv4bin,ipv4str,sizeof(ipv4str)) == 0 )
#endif
isok = 0;
} else isok = 0;
}
if ( isok != 0 )
strcpy(ipv6addr,ipv4str);
return(ipv6addr); // it is ipv4 now
}
uint16_t parse_endpoint(int32_t *ip6flagp,char *transport,char *ipbuf,char *retbuf,char *endpoint,uint16_t default_port)
{
//int32_t myatoi(char *str,int32_t range);
char *valids[] = { "tcp", "ws", "ipc", "inproc", "tcpmux" };
char tmp[128],*inet = 0,*ipaddr = 0; uint64_t ipbits; int32_t i,j,n,port = 0;
ipbuf[0] = retbuf[0] = 0;
*ip6flagp = 0;
if ( endpoint != 0 && strlen(endpoint) > 6 )
{
for (i=0; i<sizeof(valids)/sizeof(*valids); i++)
if ( strncmp(endpoint,valids[i],strlen(valids[i])) == 0 )
{
n = (int32_t)strlen(valids[i]);
ipaddr = &endpoint[n];
if ( ipaddr[0] == '[' )
{
*ip6flagp = 1;
inet = "ip6";
for (j=n-1; j>0; j--)
{
if ( ipaddr[j] == ':' )
{
if ( (port= atoi(ipaddr + j + 1)) < 0 || port >= (1 << 16) )
{
if ( ipaddr[j-1] == ']' )
ipaddr[j] = 0;
else ipaddr = 0;
break;
}
}
else if ( ipaddr[j] == ']' )
{
if ( j == n-1 )
port = default_port;
break;
}
}
}
else
{
inet = "ip4";
for (j=n-1; j>0; j--)
{
if ( ipaddr[j] == ':' )
{
if ( (port= atoi(ipaddr + j + 1)) < 0 || port >= (1 << 16) )
ipaddr = 0;
break;
}
}
}
if ( ipaddr != 0 )
{
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);
}
if ( inet != 0 && ipaddr != 0 && port != 0 )
{
sprintf(retbuf,"{\"result\":\"ip6 endpoint\",\"endpoint\":\"%s\",\"transport\":\"%s\",\"ipaddr\":\"%s\",\"port\":%d}",endpoint,valids[i],ipaddr,port);
if ( transport[0] == 0 )
strcpy(transport,valids[i]);
strcpy(ipbuf,ipaddr);
return(port);
}
}
sprintf(retbuf,"{\"result\":\"illegal endpoint\",\"endpoint\":\"%s\"}",endpoint);
} else sprintf(retbuf,"{\"error\":\"no mode specified\"}");
*ip6flagp = 0;
return(0);
}
#endif
#endif

1094
crypto777/jpeg/Makefile

File diff suppressed because it is too large

739
crypto777/jpeg/ansi2knr.c

@ -0,0 +1,739 @@
/* Copyright (C) 1989, 2000 Aladdin Enterprises. All rights reserved. */
/*$Id: ansi2knr.c,v 1.14 2003/09/06 05:36:56 eggert Exp $*/
/* Convert ANSI C function definitions to K&R ("traditional C") syntax */
/*
ansi2knr is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY. No author or distributor accepts responsibility to anyone for the
consequences of using it or for whether it serves any particular purpose or
works at all, unless he says so in writing. Refer to the GNU General Public
License (the "GPL") for full details.
Everyone is granted permission to copy, modify and redistribute ansi2knr,
but only under the conditions described in the GPL. A copy of this license
is supposed to have been given to you along with ansi2knr so you can know
your rights and responsibilities. It should be in a file named COPYLEFT,
or, if there is no file named COPYLEFT, a file named COPYING. Among other
things, the copyright notice and this notice must be preserved on all
copies.
We explicitly state here what we believe is already implied by the GPL: if
the ansi2knr program is distributed as a separate set of sources and a
separate executable file which are aggregated on a storage medium together
with another program, this in itself does not bring the other program under
the GPL, nor does the mere fact that such a program or the procedures for
constructing it invoke the ansi2knr executable bring any other part of the
program under the GPL.
*/
/*
* Usage:
ansi2knr [--filename FILENAME] [INPUT_FILE [OUTPUT_FILE]]
* --filename provides the file name for the #line directive in the output,
* overriding input_file (if present).
* If no input_file is supplied, input is read from stdin.
* If no output_file is supplied, output goes to stdout.
* There are no error messages.
*
* ansi2knr recognizes function definitions by seeing a non-keyword
* identifier at the left margin, followed by a left parenthesis, with a
* right parenthesis as the last character on the line, and with a left
* brace as the first token on the following line (ignoring possible
* intervening comments and/or preprocessor directives), except that a line
* consisting of only
* identifier1(identifier2)
* will not be considered a function definition unless identifier2 is
* the word "void", and a line consisting of
* identifier1(identifier2, <<arbitrary>>)
* will not be considered a function definition.
* ansi2knr will recognize a multi-line header provided that no intervening
* line ends with a left or right brace or a semicolon. These algorithms
* ignore whitespace, comments, and preprocessor directives, except that
* the function name must be the first thing on the line. The following
* constructs will confuse it:
* - Any other construct that starts at the left margin and
* follows the above syntax (such as a macro or function call).
* - Some macros that tinker with the syntax of function headers.
*/
/*
* The original and principal author of ansi2knr is L. Peter Deutsch
* <ghost@aladdin.com>. Other authors are noted in the change history
* that follows (in reverse chronological order):
lpd 2000-04-12 backs out Eggert's changes because of bugs:
- concatlits didn't declare the type of its bufend argument;
- concatlits didn't recognize when it was inside a comment;
- scanstring could scan backward past the beginning of the string; when
- the check for \ + newline in scanstring was unnecessary.
2000-03-05 Paul Eggert <eggert@twinsun.com>
Add support for concatenated string literals.
* ansi2knr.c (concatlits): New decl.
(main): Invoke concatlits to concatenate string literals.
(scanstring): Handle backslash-newline correctly. Work with
character constants. Fix bug when scanning backwards through
backslash-quote. Check for unterminated strings.
(convert1): Parse character constants, too.
(appendline, concatlits): New functions.
* ansi2knr.1: Document this.
lpd 1999-08-17 added code to allow preprocessor directives
wherever comments are allowed
lpd 1999-04-12 added minor fixes from Pavel Roskin
<pavel_roskin@geocities.com> for clean compilation with
gcc -W -Wall
lpd 1999-03-22 added hack to recognize lines consisting of
identifier1(identifier2, xxx) as *not* being procedures
lpd 1999-02-03 made indentation of preprocessor commands consistent
lpd 1999-01-28 fixed two bugs: a '/' in an argument list caused an
endless loop; quoted strings within an argument list
confused the parser
lpd 1999-01-24 added a check for write errors on the output,
suggested by Jim Meyering <meyering@ascend.com>
lpd 1998-11-09 added further hack to recognize identifier(void)
as being a procedure
lpd 1998-10-23 added hack to recognize lines consisting of
identifier1(identifier2) as *not* being procedures
lpd 1997-12-08 made input_file optional; only closes input and/or
output file if not stdin or stdout respectively; prints
usage message on stderr rather than stdout; adds
--filename switch (changes suggested by
<ceder@lysator.liu.se>)
lpd 1996-01-21 added code to cope with not HAVE_CONFIG_H and with
compilers that don't understand void, as suggested by
Tom Lane
lpd 1996-01-15 changed to require that the first non-comment token
on the line following a function header be a left brace,
to reduce sensitivity to macros, as suggested by Tom Lane
<tgl@sss.pgh.pa.us>
lpd 1995-06-22 removed #ifndefs whose sole purpose was to define
undefined preprocessor symbols as 0; changed all #ifdefs
for configuration symbols to #ifs
lpd 1995-04-05 changed copyright notice to make it clear that
including ansi2knr in a program does not bring the entire
program under the GPL
lpd 1994-12-18 added conditionals for systems where ctype macros
don't handle 8-bit characters properly, suggested by
Francois Pinard <pinard@iro.umontreal.ca>;
removed --varargs switch (this is now the default)
lpd 1994-10-10 removed CONFIG_BROKETS conditional
lpd 1994-07-16 added some conditionals to help GNU `configure',
suggested by Francois Pinard <pinard@iro.umontreal.ca>;
properly erase prototype args in function parameters,
contributed by Jim Avera <jima@netcom.com>;
correct error in writeblanks (it shouldn't erase EOLs)
lpd 1989-xx-xx original version
*/
/* Most of the conditionals here are to make ansi2knr work with */
/* or without the GNU configure machinery. */
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdio.h>
#include <ctype.h>
#if HAVE_CONFIG_H
/*
For properly autoconfiguring ansi2knr, use AC_CONFIG_HEADER(config.h).
This will define HAVE_CONFIG_H and so, activate the following lines.
*/
# if STDC_HEADERS || HAVE_STRING_H
# include <string.h>
# else
# include <strings.h>
# endif
#else /* not HAVE_CONFIG_H */
/* Otherwise do it the hard way */
# ifdef BSD
# include <strings.h>
# else
# ifdef VMS
extern int strlen(), strncmp();
# else
# include <string.h>
# endif
# endif
#endif /* not HAVE_CONFIG_H */
#if STDC_HEADERS
# include <stdlib.h>
#else
/*
malloc and free should be declared in stdlib.h,
but if you've got a K&R compiler, they probably aren't.
*/
# ifdef MSDOS
# include <malloc.h>
# else
# ifdef VMS
extern char *malloc();
extern void free();
# else
extern char *malloc();
extern int free();
# endif
# endif
#endif
/* Define NULL (for *very* old compilers). */
#ifndef NULL
# define NULL (0)
#endif
/*
* The ctype macros don't always handle 8-bit characters correctly.
* Compensate for this here.
*/
#ifdef isascii
# undef HAVE_ISASCII /* just in case */
# define HAVE_ISASCII 1
#else
#endif
#if STDC_HEADERS || !HAVE_ISASCII
# define is_ascii(c) 1
#else
# define is_ascii(c) isascii(c)
#endif
#define is_space(c) (is_ascii(c) && isspace(c))
#define is_alpha(c) (is_ascii(c) && isalpha(c))
#define is_alnum(c) (is_ascii(c) && isalnum(c))
/* Scanning macros */
#define isidchar(ch) (is_alnum(ch) || (ch) == '_')
#define isidfirstchar(ch) (is_alpha(ch) || (ch) == '_')
/* Forward references */
char *ppdirforward();
char *ppdirbackward();
char *skipspace();
char *scanstring();
int writeblanks();
int test1();
int convert1();
/* The main program */
int
main(argc, argv)
int argc;
char *argv[];
{ FILE *in = stdin;
FILE *out = stdout;
char *filename = 0;
char *program_name = argv[0];
char *output_name = 0;
#define bufsize 5000 /* arbitrary size */
char *buf;
char *line;
char *more;
char *usage =
"Usage: ansi2knr [--filename FILENAME] [INPUT_FILE [OUTPUT_FILE]]\n";
/*
* In previous versions, ansi2knr recognized a --varargs switch.
* If this switch was supplied, ansi2knr would attempt to convert
* a ... argument to va_alist and va_dcl; if this switch was not
* supplied, ansi2knr would simply drop any such arguments.
* Now, ansi2knr always does this conversion, and we only
* check for this switch for backward compatibility.
*/
int convert_varargs = 1;
int output_error;
while ( argc > 1 && argv[1][0] == '-' ) {
if ( !strcmp(argv[1], "--varargs") ) {
convert_varargs = 1;
argc--;
argv++;
continue;
}
if ( !strcmp(argv[1], "--filename") && argc > 2 ) {
filename = argv[2];
argc -= 2;
argv += 2;
continue;
}
fprintf(stderr, "%s: Unrecognized switch: %s\n", program_name,
argv[1]);
fprintf(stderr, usage);
exit(1);
}
switch ( argc )
{
default:
fprintf(stderr, usage);
exit(0);
case 3:
output_name = argv[2];
out = fopen(output_name, "w");
if ( out == NULL ) {
fprintf(stderr, "%s: Cannot open output file %s\n",
program_name, output_name);
exit(1);
}
/* falls through */
case 2:
in = fopen(argv[1], "r");
if ( in == NULL ) {
fprintf(stderr, "%s: Cannot open input file %s\n",
program_name, argv[1]);
exit(1);
}
if ( filename == 0 )
filename = argv[1];
/* falls through */
case 1:
break;
}
if ( filename )
fprintf(out, "#line 1 \"%s\"\n", filename);
buf = malloc(bufsize);
if ( buf == NULL )
{
fprintf(stderr, "Unable to allocate read buffer!\n");
exit(1);
}
line = buf;
while ( fgets(line, (unsigned)(buf + bufsize - line), in) != NULL )
{
test: line += strlen(line);
switch ( test1(buf) )
{
case 2: /* a function header */
convert1(buf, out, 1, convert_varargs);
break;
case 1: /* a function */
/* Check for a { at the start of the next line. */
more = ++line;
f: if ( line >= buf + (bufsize - 1) ) /* overflow check */
goto wl;
if ( fgets(line, (unsigned)(buf + bufsize - line), in) == NULL )
goto wl;
switch ( *skipspace(ppdirforward(more), 1) )
{
case '{':
/* Definitely a function header. */
convert1(buf, out, 0, convert_varargs);
fputs(more, out);
break;
case 0:
/* The next line was blank or a comment: */
/* keep scanning for a non-comment. */
line += strlen(line);
goto f;
default:
/* buf isn't a function header, but */
/* more might be. */
fputs(buf, out);
strcpy(buf, more);
line = buf;
goto test;
}
break;
case -1: /* maybe the start of a function */
if ( line != buf + (bufsize - 1) ) /* overflow check */
continue;
/* falls through */
default: /* not a function */
wl: fputs(buf, out);
break;
}
line = buf;
}
if ( line != buf )
fputs(buf, out);
free(buf);
if ( output_name ) {
output_error = ferror(out);
output_error |= fclose(out);
} else { /* out == stdout */
fflush(out);
output_error = ferror(out);
}
if ( output_error ) {
fprintf(stderr, "%s: error writing to %s\n", program_name,
(output_name ? output_name : "stdout"));
exit(1);
}
if ( in != stdin )
fclose(in);
return 0;
}
/*
* Skip forward or backward over one or more preprocessor directives.
*/
char *
ppdirforward(p)
char *p;
{
for (; *p == '#'; ++p) {
for (; *p != '\r' && *p != '\n'; ++p)
if (*p == 0)
return p;
if (*p == '\r' && p[1] == '\n')
++p;
}
return p;
}
char *
ppdirbackward(p, limit)
char *p;
char *limit;
{
char *np = p;
for (;; p = --np) {
if (*np == '\n' && np[-1] == '\r')
--np;
for (; np > limit && np[-1] != '\r' && np[-1] != '\n'; --np)
if (np[-1] == 0)
return np;
if (*np != '#')
return p;
}
}
/*
* Skip over whitespace, comments, and preprocessor directives,
* in either direction.
*/
char *
skipspace(p, dir)
char *p;
int dir; /* 1 for forward, -1 for backward */
{
for ( ; ; ) {
while ( is_space(*p) )
p += dir;
if ( !(*p == '/' && p[dir] == '*') )
break;
p += dir; p += dir;
while ( !(*p == '*' && p[dir] == '/') ) {
if ( *p == 0 )
return p; /* multi-line comment?? */
p += dir;
}
p += dir; p += dir;
}
return p;
}
/* Scan over a quoted string, in either direction. */
char *
scanstring(p, dir)
char *p;
int dir;
{
for (p += dir; ; p += dir)
if (*p == '"' && p[-dir] != '\\')
return p + dir;
}
/*
* Write blanks over part of a string.
* Don't overwrite end-of-line characters.
*/
int
writeblanks(start, end)
char *start;
char *end;
{ char *p;
for ( p = start; p < end; p++ )
if ( *p != '\r' && *p != '\n' )
*p = ' ';
return 0;
}
/*
* Test whether the string in buf is a function definition.
* The string may contain and/or end with a newline.
* Return as follows:
* 0 - definitely not a function definition;
* 1 - definitely a function definition;
* 2 - definitely a function prototype (NOT USED);
* -1 - may be the beginning of a function definition,
* append another line and look again.
* The reason we don't attempt to convert function prototypes is that
* Ghostscript's declaration-generating macros look too much like
* prototypes, and confuse the algorithms.
*/
int
test1(buf)
char *buf;
{ char *p = buf;
char *bend;
char *endfn;
int contin;
if ( !isidfirstchar(*p) )
return 0; /* no name at left margin */
bend = skipspace(ppdirbackward(buf + strlen(buf) - 1, buf), -1);
switch ( *bend )
{
case ';': contin = 0 /*2*/; break;
case ')': contin = 1; break;
case '{': return 0; /* not a function */
case '}': return 0; /* not a function */
default: contin = -1;
}
while ( isidchar(*p) )
p++;
endfn = p;
p = skipspace(p, 1);
if ( *p++ != '(' )
return 0; /* not a function */
p = skipspace(p, 1);
if ( *p == ')' )
return 0; /* no parameters */
/* Check that the apparent function name isn't a keyword. */
/* We only need to check for keywords that could be followed */
/* by a left parenthesis (which, unfortunately, is most of them). */
{ static char *words[] =
{ "asm", "auto", "case", "char", "const", "double",
"extern", "float", "for", "if", "int", "long",
"register", "return", "short", "signed", "sizeof",
"static", "switch", "typedef", "unsigned",
"void", "volatile", "while", 0
};
char **key = words;
char *kp;
unsigned len = endfn - buf;
while ( (kp = *key) != 0 )
{ if ( strlen(kp) == len && !strncmp(kp, buf, len) )
return 0; /* name is a keyword */
key++;
}
}
{
char *id = p;
int len;
/*
* Check for identifier1(identifier2) and not
* identifier1(void), or identifier1(identifier2, xxxx).
*/
while ( isidchar(*p) )
p++;
len = p - id;
p = skipspace(p, 1);
if (*p == ',' ||
(*p == ')' && (len != 4 || strncmp(id, "void", 4)))
)
return 0; /* not a function */
}
/*
* If the last significant character was a ), we need to count
* parentheses, because it might be part of a formal parameter
* that is a procedure.
*/
if (contin > 0) {
int level = 0;
for (p = skipspace(buf, 1); *p; p = skipspace(p + 1, 1))
level += (*p == '(' ? 1 : *p == ')' ? -1 : 0);
if (level > 0)
contin = -1;
}
return contin;
}
/* Convert a recognized function definition or header to K&R syntax. */
int
convert1(buf, out, header, convert_varargs)
char *buf;
FILE *out;
int header; /* Boolean */
int convert_varargs; /* Boolean */
{ char *endfn;
char *p;
/*
* The breaks table contains pointers to the beginning and end
* of each argument.
*/
char **breaks;
unsigned num_breaks = 2; /* for testing */
char **btop;
char **bp;
char **ap;
char *vararg = 0;
/* Pre-ANSI implementations don't agree on whether strchr */
/* is called strchr or index, so we open-code it here. */
for ( endfn = buf; *(endfn++) != '('; )
;
top: p = endfn;
breaks = (char **)malloc(sizeof(char *) * num_breaks * 2);
if ( breaks == NULL )
{ /* Couldn't allocate break table, give up */
fprintf(stderr, "Unable to allocate break table!\n");
fputs(buf, out);
return -1;
}
btop = breaks + num_breaks * 2 - 2;
bp = breaks;
/* Parse the argument list */
do
{ int level = 0;
char *lp = NULL;
char *rp = NULL;
char *end = NULL;
if ( bp >= btop )
{ /* Filled up break table. */
/* Allocate a bigger one and start over. */
free((char *)breaks);
num_breaks <<= 1;
goto top;
}
*bp++ = p;
/* Find the end of the argument */
for ( ; end == NULL; p++ )
{ switch(*p)
{
case ',':
if ( !level ) end = p;
break;
case '(':
if ( !level ) lp = p;
level++;
break;
case ')':
if ( --level < 0 ) end = p;
else rp = p;
break;
case '/':
if (p[1] == '*')
p = skipspace(p, 1) - 1;
break;
case '"':
p = scanstring(p, 1) - 1;
break;
default:
;
}
}
/* Erase any embedded prototype parameters. */
if ( lp && rp )
writeblanks(lp + 1, rp);
p--; /* back up over terminator */
/* Find the name being declared. */
/* This is complicated because of procedure and */
/* array modifiers. */
for ( ; ; )
{ p = skipspace(p - 1, -1);
switch ( *p )
{
case ']': /* skip array dimension(s) */
case ')': /* skip procedure args OR name */
{ int level = 1;
while ( level )
switch ( *--p )
{
case ']': case ')':
level++;
break;
case '[': case '(':
level--;
break;
case '/':
if (p > buf && p[-1] == '*')
p = skipspace(p, -1) + 1;
break;
case '"':
p = scanstring(p, -1) + 1;
break;
default: ;
}
}
if ( *p == '(' && *skipspace(p + 1, 1) == '*' )
{ /* We found the name being declared */
while ( !isidfirstchar(*p) )
p = skipspace(p, 1) + 1;
goto found;
}
break;
default:
goto found;
}
}
found: if ( *p == '.' && p[-1] == '.' && p[-2] == '.' )
{ if ( convert_varargs )
{ *bp++ = "va_alist";
vararg = p-2;
}
else
{ p++;
if ( bp == breaks + 1 ) /* sole argument */
writeblanks(breaks[0], p);
else
writeblanks(bp[-1] - 1, p);
bp--;
}
}
else
{ while ( isidchar(*p) ) p--;
*bp++ = p+1;
}
p = end;
}
while ( *p++ == ',' );
*bp = p;
/* Make a special check for 'void' arglist */
if ( bp == breaks+2 )
{ p = skipspace(breaks[0], 1);
if ( !strncmp(p, "void", 4) )
{ p = skipspace(p+4, 1);
if ( p == breaks[2] - 1 )
{ bp = breaks; /* yup, pretend arglist is empty */
writeblanks(breaks[0], p + 1);
}
}
}
/* Put out the function name and left parenthesis. */
p = buf;
while ( p != endfn ) putc(*p, out), p++;
/* Put out the declaration. */
if ( header )
{ fputs(");", out);
for ( p = breaks[0]; *p; p++ )
if ( *p == '\r' || *p == '\n' )
putc(*p, out);
}
else
{ for ( ap = breaks+1; ap < bp; ap += 2 )
{ p = *ap;
while ( isidchar(*p) )
putc(*p, out), p++;
if ( ap < bp - 1 )
fputs(", ", out);
}
fputs(") ", out);
/* Put out the argument declarations */
for ( ap = breaks+2; ap <= bp; ap += 2 )
(*ap)[-1] = ';';
if ( vararg != 0 )
{ *vararg = 0;
fputs(breaks[0], out); /* any prior args */
fputs("va_dcl", out); /* the final arg */
fputs(bp[0], out);
}
else
fputs(breaks[0], out);
}
free((char *)breaks);
return 0;
}

134
crypto777/jpeg/cderror.h

@ -0,0 +1,134 @@
/*
* cderror.h
*
* Copyright (C) 1994-1997, Thomas G. Lane.
* Modified 2009 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file defines the error and message codes for the cjpeg/djpeg
* applications. These strings are not needed as part of the JPEG library
* proper.
* Edit this file to add new codes, or to translate the message strings to
* some other language.
*/
/*
* To define the enum list of message codes, include this file without
* defining macro JMESSAGE. To create a message string table, include it
* again with a suitable JMESSAGE definition (see jerror.c for an example).
*/
#ifndef JMESSAGE
#ifndef CDERROR_H
#define CDERROR_H
/* First time through, define the enum list */
#define JMAKE_ENUM_LIST
#else
/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
#define JMESSAGE(code,string)
#endif /* CDERROR_H */
#endif /* JMESSAGE */
#ifdef JMAKE_ENUM_LIST
typedef enum {
#define JMESSAGE(code,string) code ,
#endif /* JMAKE_ENUM_LIST */
JMESSAGE(JMSG_FIRSTADDONCODE=1000, NULL) /* Must be first entry! */
#ifdef BMP_SUPPORTED
JMESSAGE(JERR_BMP_BADCMAP, "Unsupported BMP colormap format")
JMESSAGE(JERR_BMP_BADDEPTH, "Only 8- and 24-bit BMP files are supported")
JMESSAGE(JERR_BMP_BADHEADER, "Invalid BMP file: bad header length")
JMESSAGE(JERR_BMP_BADPLANES, "Invalid BMP file: biPlanes not equal to 1")
JMESSAGE(JERR_BMP_COLORSPACE, "BMP output must be grayscale or RGB")
JMESSAGE(JERR_BMP_COMPRESSED, "Sorry, compressed BMPs not yet supported")
JMESSAGE(JERR_BMP_EMPTY, "Empty BMP image")
JMESSAGE(JERR_BMP_NOT, "Not a BMP file - does not start with BM")
JMESSAGE(JTRC_BMP, "%ux%u 24-bit BMP image")
JMESSAGE(JTRC_BMP_MAPPED, "%ux%u 8-bit colormapped BMP image")
JMESSAGE(JTRC_BMP_OS2, "%ux%u 24-bit OS2 BMP image")
JMESSAGE(JTRC_BMP_OS2_MAPPED, "%ux%u 8-bit colormapped OS2 BMP image")
#endif /* BMP_SUPPORTED */
#ifdef GIF_SUPPORTED
JMESSAGE(JERR_GIF_BUG, "GIF output got confused")
JMESSAGE(JERR_GIF_CODESIZE, "Bogus GIF codesize %d")
JMESSAGE(JERR_GIF_COLORSPACE, "GIF output must be grayscale or RGB")
JMESSAGE(JERR_GIF_IMAGENOTFOUND, "Too few images in GIF file")
JMESSAGE(JERR_GIF_NOT, "Not a GIF file")
JMESSAGE(JTRC_GIF, "%ux%ux%d GIF image")
JMESSAGE(JTRC_GIF_BADVERSION,
"Warning: unexpected GIF version number '%c%c%c'")
JMESSAGE(JTRC_GIF_EXTENSION, "Ignoring GIF extension block of type 0x%02x")
JMESSAGE(JTRC_GIF_NONSQUARE, "Caution: nonsquare pixels in input")
JMESSAGE(JWRN_GIF_BADDATA, "Corrupt data in GIF file")
JMESSAGE(JWRN_GIF_CHAR, "Bogus char 0x%02x in GIF file, ignoring")
JMESSAGE(JWRN_GIF_ENDCODE, "Premature end of GIF image")
JMESSAGE(JWRN_GIF_NOMOREDATA, "Ran out of GIF bits")
#endif /* GIF_SUPPORTED */
#ifdef PPM_SUPPORTED
JMESSAGE(JERR_PPM_COLORSPACE, "PPM output must be grayscale or RGB")
JMESSAGE(JERR_PPM_NONNUMERIC, "Nonnumeric data in PPM file")
JMESSAGE(JERR_PPM_NOT, "Not a PPM/PGM file")
JMESSAGE(JTRC_PGM, "%ux%u PGM image")
JMESSAGE(JTRC_PGM_TEXT, "%ux%u text PGM image")
JMESSAGE(JTRC_PPM, "%ux%u PPM image")
JMESSAGE(JTRC_PPM_TEXT, "%ux%u text PPM image")
#endif /* PPM_SUPPORTED */
#ifdef RLE_SUPPORTED
JMESSAGE(JERR_RLE_BADERROR, "Bogus error code from RLE library")
JMESSAGE(JERR_RLE_COLORSPACE, "RLE output must be grayscale or RGB")
JMESSAGE(JERR_RLE_DIMENSIONS, "Image dimensions (%ux%u) too large for RLE")
JMESSAGE(JERR_RLE_EMPTY, "Empty RLE file")
JMESSAGE(JERR_RLE_EOF, "Premature EOF in RLE header")
JMESSAGE(JERR_RLE_MEM, "Insufficient memory for RLE header")
JMESSAGE(JERR_RLE_NOT, "Not an RLE file")
JMESSAGE(JERR_RLE_TOOMANYCHANNELS, "Cannot handle %d output channels for RLE")
JMESSAGE(JERR_RLE_UNSUPPORTED, "Cannot handle this RLE setup")
JMESSAGE(JTRC_RLE, "%ux%u full-color RLE file")
JMESSAGE(JTRC_RLE_FULLMAP, "%ux%u full-color RLE file with map of length %d")
JMESSAGE(JTRC_RLE_GRAY, "%ux%u grayscale RLE file")
JMESSAGE(JTRC_RLE_MAPGRAY, "%ux%u grayscale RLE file with map of length %d")
JMESSAGE(JTRC_RLE_MAPPED, "%ux%u colormapped RLE file with map of length %d")
#endif /* RLE_SUPPORTED */
#ifdef TARGA_SUPPORTED
JMESSAGE(JERR_TGA_BADCMAP, "Unsupported Targa colormap format")
JMESSAGE(JERR_TGA_BADPARMS, "Invalid or unsupported Targa file")
JMESSAGE(JERR_TGA_COLORSPACE, "Targa output must be grayscale or RGB")
JMESSAGE(JTRC_TGA, "%ux%u RGB Targa image")
JMESSAGE(JTRC_TGA_GRAY, "%ux%u grayscale Targa image")
JMESSAGE(JTRC_TGA_MAPPED, "%ux%u colormapped Targa image")
#else
JMESSAGE(JERR_TGA_NOTCOMP, "Targa support was not compiled")
#endif /* TARGA_SUPPORTED */
JMESSAGE(JERR_BAD_CMAP_FILE,
"Color map file is invalid or of unsupported format")
JMESSAGE(JERR_TOO_MANY_COLORS,
"Output file format cannot handle %d colormap entries")
JMESSAGE(JERR_UNGETC_FAILED, "ungetc failed")
#ifdef TARGA_SUPPORTED
JMESSAGE(JERR_UNKNOWN_FORMAT,
"Unrecognized input file format --- perhaps you need -targa")
#else
JMESSAGE(JERR_UNKNOWN_FORMAT, "Unrecognized input file format")
#endif
JMESSAGE(JERR_UNSUPPORTED_FORMAT, "Unsupported output file format")
#ifdef JMAKE_ENUM_LIST
JMSG_LASTADDONCODE
} ADDON_MESSAGE_CODE;
#undef JMAKE_ENUM_LIST
#endif /* JMAKE_ENUM_LIST */
/* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
#undef JMESSAGE

181
crypto777/jpeg/cdjpeg.c

@ -0,0 +1,181 @@
/*
* cdjpeg.c
*
* Copyright (C) 1991-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains common support routines used by the IJG application
* programs (cjpeg, djpeg, jpegtran).
*/
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#include <ctype.h> /* to declare isupper(), tolower() */
#ifdef NEED_SIGNAL_CATCHER
#include <signal.h> /* to declare signal() */
#endif
#ifdef USE_SETMODE
#include <fcntl.h> /* to declare setmode()'s parameter macros */
/* If you have setmode() but not <io.h>, just delete this line: */
#include <io.h> /* to declare setmode() */
#endif
/*
* Signal catcher to ensure that temporary files are removed before aborting.
* NB: for Amiga Manx C this is actually a global routine named _abort();
* we put "#define signal_catcher _abort" in jconfig.h. Talk about bogus...
*/
#ifdef NEED_SIGNAL_CATCHER
static j_common_ptr sig_cinfo;
void /* must be global for Manx C */
signal_catcher (int signum)
{
if (sig_cinfo != NULL) {
if (sig_cinfo->err != NULL) /* turn off trace output */
sig_cinfo->err->trace_level = 0;
jpeg_destroy(sig_cinfo); /* clean up memory allocation & temp files */
}
exit(EXIT_FAILURE);
}
GLOBAL(void)
enable_signal_catcher (j_common_ptr cinfo)
{
sig_cinfo = cinfo;
#ifdef SIGINT /* not all systems have SIGINT */
signal(SIGINT, signal_catcher);
#endif
#ifdef SIGTERM /* not all systems have SIGTERM */
signal(SIGTERM, signal_catcher);
#endif
}
#endif
/*
* Optional progress monitor: display a percent-done figure on stderr.
*/
#ifdef PROGRESS_REPORT
METHODDEF(void)
progress_monitor (j_common_ptr cinfo)
{
cd_progress_ptr prog = (cd_progress_ptr) cinfo->progress;
int total_passes = prog->pub.total_passes + prog->total_extra_passes;
int percent_done = (int) (prog->pub.pass_counter*100L/prog->pub.pass_limit);
if (percent_done != prog->percent_done) {
prog->percent_done = percent_done;
if (total_passes > 1) {
fprintf(stderr, "\rPass %d/%d: %3d%% ",
prog->pub.completed_passes + prog->completed_extra_passes + 1,
total_passes, percent_done);
} else {
fprintf(stderr, "\r %3d%% ", percent_done);
}
fflush(stderr);
}
}
GLOBAL(void)
start_progress_monitor (j_common_ptr cinfo, cd_progress_ptr progress)
{
/* Enable progress display, unless trace output is on */
if (cinfo->err->trace_level == 0) {
progress->pub.progress_monitor = progress_monitor;
progress->completed_extra_passes = 0;
progress->total_extra_passes = 0;
progress->percent_done = -1;
cinfo->progress = &progress->pub;
}
}
GLOBAL(void)
end_progress_monitor (j_common_ptr cinfo)
{
/* Clear away progress display */
if (cinfo->err->trace_level == 0) {
fprintf(stderr, "\r \r");
fflush(stderr);
}
}
#endif
/*
* Case-insensitive matching of possibly-abbreviated keyword switches.
* keyword is the constant keyword (must be lower case already),
* minchars is length of minimum legal abbreviation.
*/
GLOBAL(boolean)
keymatch (char * arg, const char * keyword, int minchars)
{
register int ca, ck;
register int nmatched = 0;
while ((ca = *arg++) != '\0') {
if ((ck = *keyword++) == '\0')
return FALSE; /* arg longer than keyword, no good */
if (isupper(ca)) /* force arg to lcase (assume ck is already) */
ca = tolower(ca);
if (ca != ck)
return FALSE; /* no good */
nmatched++; /* count matched characters */
}
/* reached end of argument; fail if it's too short for unique abbrev */
if (nmatched < minchars)
return FALSE;
return TRUE; /* A-OK */
}
/*
* Routines to establish binary I/O mode for stdin and stdout.
* Non-Unix systems often require some hacking to get out of text mode.
*/
GLOBAL(FILE *)
read_stdin (void)
{
FILE * input_file = stdin;
#ifdef USE_SETMODE /* need to hack file mode? */
setmode(fileno(stdin), O_BINARY);
#endif
#ifdef USE_FDOPEN /* need to re-open in binary mode? */
if ((input_file = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
fprintf(stderr, "Cannot reopen stdin\n");
exit(EXIT_FAILURE);
}
#endif
return input_file;
}
GLOBAL(FILE *)
write_stdout (void)
{
FILE * output_file = stdout;
#ifdef USE_SETMODE /* need to hack file mode? */
setmode(fileno(stdout), O_BINARY);
#endif
#ifdef USE_FDOPEN /* need to re-open in binary mode? */
if ((output_file = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) {
fprintf(stderr, "Cannot reopen stdout\n");
exit(EXIT_FAILURE);
}
#endif
return output_file;
}

187
crypto777/jpeg/cdjpeg.h

@ -0,0 +1,187 @@
/*
* cdjpeg.h
*
* Copyright (C) 1994-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains common declarations for the sample applications
* cjpeg and djpeg. It is NOT used by the core JPEG library.
*/
#define JPEG_CJPEG_DJPEG /* define proper options in jconfig.h */
#define JPEG_INTERNAL_OPTIONS /* cjpeg.c,djpeg.c need to see xxx_SUPPORTED */
#include "jinclude.h"
#include "jpeglib.h"
#include "jerror.h" /* get library error codes too */
#include "cderror.h" /* get application-specific error codes */
/*
* Object interface for cjpeg's source file decoding modules
*/
typedef struct cjpeg_source_struct * cjpeg_source_ptr;
struct cjpeg_source_struct {
JMETHOD(void, start_input, (j_compress_ptr cinfo,
cjpeg_source_ptr sinfo));
JMETHOD(JDIMENSION, get_pixel_rows, (j_compress_ptr cinfo,
cjpeg_source_ptr sinfo));
JMETHOD(void, finish_input, (j_compress_ptr cinfo,
cjpeg_source_ptr sinfo));
FILE *input_file;
JSAMPARRAY buffer;
JDIMENSION buffer_height;
};
/*
* Object interface for djpeg's output file encoding modules
*/
typedef struct djpeg_dest_struct * djpeg_dest_ptr;
struct djpeg_dest_struct {
/* start_output is called after jpeg_start_decompress finishes.
* The color map will be ready at this time, if one is needed.
*/
JMETHOD(void, start_output, (j_decompress_ptr cinfo,
djpeg_dest_ptr dinfo));
/* Emit the specified number of pixel rows from the buffer. */
JMETHOD(void, put_pixel_rows, (j_decompress_ptr cinfo,
djpeg_dest_ptr dinfo,
JDIMENSION rows_supplied));
/* Finish up at the end of the image. */
JMETHOD(void, finish_output, (j_decompress_ptr cinfo,
djpeg_dest_ptr dinfo));
/* Target file spec; filled in by djpeg.c after object is created. */
FILE * output_file;
/* Output pixel-row buffer. Created by module init or start_output.
* Width is cinfo->output_width * cinfo->output_components;
* height is buffer_height.
*/
JSAMPARRAY buffer;
JDIMENSION buffer_height;
};
/*
* cjpeg/djpeg may need to perform extra passes to convert to or from
* the source/destination file format. The JPEG library does not know
* about these passes, but we'd like them to be counted by the progress
* monitor. We use an expanded progress monitor object to hold the
* additional pass count.
*/
struct cdjpeg_progress_mgr {
struct jpeg_progress_mgr pub; /* fields known to JPEG library */
int completed_extra_passes; /* extra passes completed */
int total_extra_passes; /* total extra */
/* last printed percentage stored here to avoid multiple printouts */
int percent_done;
};
typedef struct cdjpeg_progress_mgr * cd_progress_ptr;
/* Short forms of external names for systems with brain-damaged linkers. */
#ifdef NEED_SHORT_EXTERNAL_NAMES
#define jinit_read_bmp jIRdBMP
#define jinit_write_bmp jIWrBMP
#define jinit_read_gif jIRdGIF
#define jinit_write_gif jIWrGIF
#define jinit_read_ppm jIRdPPM
#define jinit_write_ppm jIWrPPM
#define jinit_read_rle jIRdRLE
#define jinit_write_rle jIWrRLE
#define jinit_read_targa jIRdTarga
#define jinit_write_targa jIWrTarga
#define read_quant_tables RdQTables
#define read_scan_script RdScnScript
#define set_quality_ratings SetQRates
#define set_quant_slots SetQSlots
#define set_sample_factors SetSFacts
#define read_color_map RdCMap
#define enable_signal_catcher EnSigCatcher
#define start_progress_monitor StProgMon
#define end_progress_monitor EnProgMon
#define read_stdin RdStdin
#define write_stdout WrStdout
#endif /* NEED_SHORT_EXTERNAL_NAMES */
/* Module selection routines for I/O modules. */
EXTERN(cjpeg_source_ptr) jinit_read_bmp JPP((j_compress_ptr cinfo));
EXTERN(djpeg_dest_ptr) jinit_write_bmp JPP((j_decompress_ptr cinfo,
boolean is_os2));
EXTERN(cjpeg_source_ptr) jinit_read_gif JPP((j_compress_ptr cinfo));
EXTERN(djpeg_dest_ptr) jinit_write_gif JPP((j_decompress_ptr cinfo));
EXTERN(cjpeg_source_ptr) jinit_read_ppm JPP((j_compress_ptr cinfo));
EXTERN(djpeg_dest_ptr) jinit_write_ppm JPP((j_decompress_ptr cinfo));
EXTERN(cjpeg_source_ptr) jinit_read_rle JPP((j_compress_ptr cinfo));
EXTERN(djpeg_dest_ptr) jinit_write_rle JPP((j_decompress_ptr cinfo));
EXTERN(cjpeg_source_ptr) jinit_read_targa JPP((j_compress_ptr cinfo));
EXTERN(djpeg_dest_ptr) jinit_write_targa JPP((j_decompress_ptr cinfo));
/* cjpeg support routines (in rdswitch.c) */
EXTERN(boolean) read_quant_tables JPP((j_compress_ptr cinfo, char * filename,
boolean force_baseline));
EXTERN(boolean) read_scan_script JPP((j_compress_ptr cinfo, char * filename));
EXTERN(boolean) set_quality_ratings JPP((j_compress_ptr cinfo, char *arg,
boolean force_baseline));
EXTERN(boolean) set_quant_slots JPP((j_compress_ptr cinfo, char *arg));
EXTERN(boolean) set_sample_factors JPP((j_compress_ptr cinfo, char *arg));
/* djpeg support routines (in rdcolmap.c) */
EXTERN(void) read_color_map JPP((j_decompress_ptr cinfo, FILE * infile));
/* common support routines (in cdjpeg.c) */
EXTERN(void) enable_signal_catcher JPP((j_common_ptr cinfo));
EXTERN(void) start_progress_monitor JPP((j_common_ptr cinfo,
cd_progress_ptr progress));
EXTERN(void) end_progress_monitor JPP((j_common_ptr cinfo));
EXTERN(boolean) keymatch JPP((char * arg, const char * keyword, int minchars));
EXTERN(FILE *) read_stdin JPP((void));
EXTERN(FILE *) write_stdout JPP((void));
/* miscellaneous useful macros */
#ifdef DONT_USE_B_MODE /* define mode parameters for fopen() */
#define READ_BINARY "r"
#define WRITE_BINARY "w"
#else
#ifdef VMS /* VMS is very nonstandard */
#define READ_BINARY "rb", "ctx=stm"
#define WRITE_BINARY "wb", "ctx=stm"
#else /* standard ANSI-compliant case */
#define READ_BINARY "rb"
#define WRITE_BINARY "wb"
#endif
#endif
#ifndef EXIT_FAILURE /* define exit() codes if not provided */
#define EXIT_FAILURE 1
#endif
#ifndef EXIT_SUCCESS
#ifdef VMS
#define EXIT_SUCCESS 1 /* VMS is very nonstandard */
#else
#define EXIT_SUCCESS 0
#endif
#endif
#ifndef EXIT_WARNING
#ifdef VMS
#define EXIT_WARNING 1 /* VMS is very nonstandard */
#else
#define EXIT_WARNING 2
#endif
#endif

643
crypto777/jpeg/cjpeg.c

@ -0,0 +1,643 @@
/*
* cjpeg.c
*
* Copyright (C) 1991-1998, Thomas G. Lane.
* Modified 2003-2011 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains a command-line user interface for the JPEG compressor.
* It should work on any system with Unix- or MS-DOS-style command lines.
*
* Two different command line styles are permitted, depending on the
* compile-time switch TWO_FILE_COMMANDLINE:
* cjpeg [options] inputfile outputfile
* cjpeg [options] [inputfile]
* In the second style, output is always to standard output, which you'd
* normally redirect to a file or pipe to some other program. Input is
* either from a named file or from standard input (typically redirected).
* The second style is convenient on Unix but is unhelpful on systems that
* don't support pipes. Also, you MUST use the first style if your system
* doesn't do binary I/O to stdin/stdout.
* To simplify script writing, the "-outfile" switch is provided. The syntax
* cjpeg [options] -outfile outputfile inputfile
* works regardless of which command line style is used.
*/
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#include "jversion.h" /* for version message */
#ifdef USE_CCOMMAND /* command-line reader for Macintosh */
#ifdef __MWERKS__
#include <SIOUX.h> /* Metrowerks needs this */
#include <console.h> /* ... and this */
#endif
#ifdef THINK_C
#include <console.h> /* Think declares it here */
#endif
#endif
/* Create the add-on message string table. */
#define JMESSAGE(code,string) string ,
static const char * const cdjpeg_message_table[] = {
#include "cderror.h"
NULL
};
/*
* This routine determines what format the input file is,
* and selects the appropriate input-reading module.
*
* To determine which family of input formats the file belongs to,
* we may look only at the first byte of the file, since C does not
* guarantee that more than one character can be pushed back with ungetc.
* Looking at additional bytes would require one of these approaches:
* 1) assume we can fseek() the input file (fails for piped input);
* 2) assume we can push back more than one character (works in
* some C implementations, but unportable);
* 3) provide our own buffering (breaks input readers that want to use
* stdio directly, such as the RLE library);
* or 4) don't put back the data, and modify the input_init methods to assume
* they start reading after the start of file (also breaks RLE library).
* #1 is attractive for MS-DOS but is untenable on Unix.
*
* The most portable solution for file types that can't be identified by their
* first byte is to make the user tell us what they are. This is also the
* only approach for "raw" file types that contain only arbitrary values.
* We presently apply this method for Targa files. Most of the time Targa
* files start with 0x00, so we recognize that case. Potentially, however,
* a Targa file could start with any byte value (byte 0 is the length of the
* seldom-used ID field), so we provide a switch to force Targa input mode.
*/
static boolean is_targa; /* records user -targa switch */
LOCAL(cjpeg_source_ptr)
select_file_type (j_compress_ptr cinfo, FILE * infile)
{
int c;
if (is_targa) {
#ifdef TARGA_SUPPORTED
return jinit_read_targa(cinfo);
#else
ERREXIT(cinfo, JERR_TGA_NOTCOMP);
#endif
}
if ((c = getc(infile)) == EOF)
ERREXIT(cinfo, JERR_INPUT_EMPTY);
if (ungetc(c, infile) == EOF)
ERREXIT(cinfo, JERR_UNGETC_FAILED);
switch (c) {
#ifdef BMP_SUPPORTED
case 'B':
return jinit_read_bmp(cinfo);
#endif
#ifdef GIF_SUPPORTED
case 'G':
return jinit_read_gif(cinfo);
#endif
#ifdef PPM_SUPPORTED
case 'P':
return jinit_read_ppm(cinfo);
#endif
#ifdef RLE_SUPPORTED
case 'R':
return jinit_read_rle(cinfo);
#endif
#ifdef TARGA_SUPPORTED
case 0x00:
return jinit_read_targa(cinfo);
#endif
default:
ERREXIT(cinfo, JERR_UNKNOWN_FORMAT);
break;
}
return NULL; /* suppress compiler warnings */
}
/*
* Argument-parsing code.
* The switch parser is designed to be useful with DOS-style command line
* syntax, ie, intermixed switches and file names, where only the switches
* to the left of a given file name affect processing of that file.
* The main program in this file doesn't actually use this capability...
*/
static const char * progname; /* program name for error messages */
static char * outfilename; /* for -outfile switch */
LOCAL(void)
usage (void)
/* complain about bad command line */
{
fprintf(stderr, "usage: %s [switches] ", progname);
#ifdef TWO_FILE_COMMANDLINE
fprintf(stderr, "inputfile outputfile\n");
#else
fprintf(stderr, "[inputfile]\n");
#endif
fprintf(stderr, "Switches (names may be abbreviated):\n");
fprintf(stderr, " -quality N[,...] Compression quality (0..100; 5-95 is useful range)\n");
fprintf(stderr, " -grayscale Create monochrome JPEG file\n");
fprintf(stderr, " -rgb Create RGB JPEG file\n");
#ifdef ENTROPY_OPT_SUPPORTED
fprintf(stderr, " -optimize Optimize Huffman table (smaller file, but slow compression)\n");
#endif
#ifdef C_PROGRESSIVE_SUPPORTED
fprintf(stderr, " -progressive Create progressive JPEG file\n");
#endif
#ifdef DCT_SCALING_SUPPORTED
fprintf(stderr, " -scale M/N Scale image by fraction M/N, eg, 1/2\n");
#endif
#ifdef TARGA_SUPPORTED
fprintf(stderr, " -targa Input file is Targa format (usually not needed)\n");
#endif
fprintf(stderr, "Switches for advanced users:\n");
#ifdef C_ARITH_CODING_SUPPORTED
fprintf(stderr, " -arithmetic Use arithmetic coding\n");
#endif
#ifdef DCT_SCALING_SUPPORTED
fprintf(stderr, " -block N DCT block size (1..16; default is 8)\n");
#endif
#ifdef DCT_ISLOW_SUPPORTED
fprintf(stderr, " -dct int Use integer DCT method%s\n",
(JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
#endif
#ifdef DCT_IFAST_SUPPORTED
fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n",
(JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
#endif
#ifdef DCT_FLOAT_SUPPORTED
fprintf(stderr, " -dct float Use floating-point DCT method%s\n",
(JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
#endif
fprintf(stderr, " -nosmooth Don't use high-quality downsampling\n");
fprintf(stderr, " -restart N Set restart interval in rows, or in blocks with B\n");
#ifdef INPUT_SMOOTHING_SUPPORTED
fprintf(stderr, " -smooth N Smooth dithered input (N=1..100 is strength)\n");
#endif
fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
fprintf(stderr, " -outfile name Specify name for output file\n");
fprintf(stderr, " -verbose or -debug Emit debug output\n");
fprintf(stderr, "Switches for wizards:\n");
fprintf(stderr, " -baseline Force baseline quantization tables\n");
fprintf(stderr, " -qtables file Use quantization tables given in file\n");
fprintf(stderr, " -qslots N[,...] Set component quantization tables\n");
fprintf(stderr, " -sample HxV[,...] Set component sampling factors\n");
#ifdef C_MULTISCAN_FILES_SUPPORTED
fprintf(stderr, " -scans file Create multi-scan JPEG per script file\n");
#endif
exit(EXIT_FAILURE);
}
LOCAL(int)
parse_switches (j_compress_ptr cinfo, int argc, char **argv,
int last_file_arg_seen, boolean for_real)
/* Parse optional switches.
* Returns argv[] index of first file-name argument (== argc if none).
* Any file names with indexes <= last_file_arg_seen are ignored;
* they have presumably been processed in a previous iteration.
* (Pass 0 for last_file_arg_seen on the first or only iteration.)
* for_real is FALSE on the first (dummy) pass; we may skip any expensive
* processing.
*/
{
int argn;
char * arg;
boolean force_baseline;
boolean simple_progressive;
char * qualityarg = NULL; /* saves -quality parm if any */
char * qtablefile = NULL; /* saves -qtables filename if any */
char * qslotsarg = NULL; /* saves -qslots parm if any */
char * samplearg = NULL; /* saves -sample parm if any */
char * scansarg = NULL; /* saves -scans parm if any */
/* Set up default JPEG parameters. */
force_baseline = FALSE; /* by default, allow 16-bit quantizers */
simple_progressive = FALSE;
is_targa = FALSE;
outfilename = NULL;
cinfo->err->trace_level = 0;
/* Scan command line options, adjust parameters */
for (argn = 1; argn < argc; argn++) {
arg = argv[argn];
if (*arg != '-') {
/* Not a switch, must be a file name argument */
if (argn <= last_file_arg_seen) {
outfilename = NULL; /* -outfile applies to just one input file */
continue; /* ignore this name if previously processed */
}
break; /* else done parsing switches */
}
arg++; /* advance past switch marker character */
if (keymatch(arg, "arithmetic", 1)) {
/* Use arithmetic coding. */
#ifdef C_ARITH_CODING_SUPPORTED
cinfo->arith_code = TRUE;
#else
fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
progname);
exit(EXIT_FAILURE);
#endif
} else if (keymatch(arg, "baseline", 2)) {
/* Force baseline-compatible output (8-bit quantizer values). */
force_baseline = TRUE;
} else if (keymatch(arg, "block", 2)) {
/* Set DCT block size. */
#if defined DCT_SCALING_SUPPORTED && JPEG_LIB_VERSION_MAJOR >= 8 && \
(JPEG_LIB_VERSION_MAJOR > 8 || JPEG_LIB_VERSION_MINOR >= 3)
int val;
if (++argn >= argc) /* advance to next argument */
usage();
if (sscanf(argv[argn], "%d", &val) != 1)
usage();
if (val < 1 || val > 16)
usage();
cinfo->block_size = val;
#else
fprintf(stderr, "%s: sorry, block size setting not supported\n",
progname);
exit(EXIT_FAILURE);
#endif
} else if (keymatch(arg, "dct", 2)) {
/* Select DCT algorithm. */
if (++argn >= argc) /* advance to next argument */
usage();
if (keymatch(argv[argn], "int", 1)) {
cinfo->dct_method = JDCT_ISLOW;
} else if (keymatch(argv[argn], "fast", 2)) {
cinfo->dct_method = JDCT_IFAST;
} else if (keymatch(argv[argn], "float", 2)) {
cinfo->dct_method = JDCT_FLOAT;
} else
usage();
} else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
/* Enable debug printouts. */
/* On first -d, print version identification */
static boolean printed_version = FALSE;
if (! printed_version) {
fprintf(stderr, "Independent JPEG Group's CJPEG, version %s\n%s\n",
JVERSION, JCOPYRIGHT);
printed_version = TRUE;
}
cinfo->err->trace_level++;
} else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
/* Force a monochrome JPEG file to be generated. */
jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
} else if (keymatch(arg, "rgb", 3)) {
/* Force an RGB JPEG file to be generated. */
jpeg_set_colorspace(cinfo, JCS_RGB);
} else if (keymatch(arg, "maxmemory", 3)) {
/* Maximum memory in Kb (or Mb with 'm'). */
long lval;
char ch = 'x';
if (++argn >= argc) /* advance to next argument */
usage();
if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
usage();
if (ch == 'm' || ch == 'M')
lval *= 1000L;
cinfo->mem->max_memory_to_use = lval * 1000L;
} else if (keymatch(arg, "nosmooth", 3)) {
/* Suppress fancy downsampling */
cinfo->do_fancy_downsampling = FALSE;
} else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
/* Enable entropy parm optimization. */
#ifdef ENTROPY_OPT_SUPPORTED
cinfo->optimize_coding = TRUE;
#else
fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
progname);
exit(EXIT_FAILURE);
#endif
} else if (keymatch(arg, "outfile", 4)) {
/* Set output file name. */
if (++argn >= argc) /* advance to next argument */
usage();
outfilename = argv[argn]; /* save it away for later use */
} else if (keymatch(arg, "progressive", 1)) {
/* Select simple progressive mode. */
#ifdef C_PROGRESSIVE_SUPPORTED
simple_progressive = TRUE;
/* We must postpone execution until num_components is known. */
#else
fprintf(stderr, "%s: sorry, progressive output was not compiled\n",
progname);
exit(EXIT_FAILURE);
#endif
} else if (keymatch(arg, "quality", 1)) {
/* Quality ratings (quantization table scaling factors). */
if (++argn >= argc) /* advance to next argument */
usage();
qualityarg = argv[argn];
} else if (keymatch(arg, "qslots", 2)) {
/* Quantization table slot numbers. */
if (++argn >= argc) /* advance to next argument */
usage();
qslotsarg = argv[argn];
/* Must delay setting qslots until after we have processed any
* colorspace-determining switches, since jpeg_set_colorspace sets
* default quant table numbers.
*/
} else if (keymatch(arg, "qtables", 2)) {
/* Quantization tables fetched from file. */
if (++argn >= argc) /* advance to next argument */
usage();
qtablefile = argv[argn];
/* We postpone actually reading the file in case -quality comes later. */
} else if (keymatch(arg, "restart", 1)) {
/* Restart interval in MCU rows (or in MCUs with 'b'). */
long lval;
char ch = 'x';
if (++argn >= argc) /* advance to next argument */
usage();
if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
usage();
if (lval < 0 || lval > 65535L)
usage();
if (ch == 'b' || ch == 'B') {
cinfo->restart_interval = (unsigned int) lval;
cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
} else {
cinfo->restart_in_rows = (int) lval;
/* restart_interval will be computed during startup */
}
} else if (keymatch(arg, "sample", 2)) {
/* Set sampling factors. */
if (++argn >= argc) /* advance to next argument */
usage();
samplearg = argv[argn];
/* Must delay setting sample factors until after we have processed any
* colorspace-determining switches, since jpeg_set_colorspace sets
* default sampling factors.
*/
} else if (keymatch(arg, "scale", 4)) {
/* Scale the image by a fraction M/N. */
if (++argn >= argc) /* advance to next argument */
usage();
if (sscanf(argv[argn], "%d/%d",
&cinfo->scale_num, &cinfo->scale_denom) != 2)
usage();
} else if (keymatch(arg, "scans", 4)) {
/* Set scan script. */
#ifdef C_MULTISCAN_FILES_SUPPORTED
if (++argn >= argc) /* advance to next argument */
usage();
scansarg = argv[argn];
/* We must postpone reading the file in case -progressive appears. */
#else
fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n",
progname);
exit(EXIT_FAILURE);
#endif
} else if (keymatch(arg, "smooth", 2)) {
/* Set input smoothing factor. */
int val;
if (++argn >= argc) /* advance to next argument */
usage();
if (sscanf(argv[argn], "%d", &val) != 1)
usage();
if (val < 0 || val > 100)
usage();
cinfo->smoothing_factor = val;
} else if (keymatch(arg, "targa", 1)) {
/* Input file is Targa format. */
is_targa = TRUE;
} else {
usage(); /* bogus switch */
}
}
/* Post-switch-scanning cleanup */
if (for_real) {
/* Set quantization tables for selected quality. */
/* Some or all may be overridden if -qtables is present. */
if (qualityarg != NULL) /* process -quality if it was present */
if (! set_quality_ratings(cinfo, qualityarg, force_baseline))
usage();
if (qtablefile != NULL) /* process -qtables if it was present */
if (! read_quant_tables(cinfo, qtablefile, force_baseline))
usage();
if (qslotsarg != NULL) /* process -qslots if it was present */
if (! set_quant_slots(cinfo, qslotsarg))
usage();
if (samplearg != NULL) /* process -sample if it was present */
if (! set_sample_factors(cinfo, samplearg))
usage();
#ifdef C_PROGRESSIVE_SUPPORTED
if (simple_progressive) /* process -progressive; -scans can override */
jpeg_simple_progression(cinfo);
#endif
#ifdef C_MULTISCAN_FILES_SUPPORTED
if (scansarg != NULL) /* process -scans if it was present */
if (! read_scan_script(cinfo, scansarg))
usage();
#endif
}
return argn; /* return index of next arg (file name) */
}
/*
* The main program.
*/
int
main (int argc, char **argv)
{
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
#ifdef PROGRESS_REPORT
struct cdjpeg_progress_mgr progress;
#endif
int file_index;
cjpeg_source_ptr src_mgr;
FILE * input_file;
FILE * output_file;
JDIMENSION num_scanlines;
/* On Mac, fetch a command line. */
#ifdef USE_CCOMMAND
argc = ccommand(&argv);
#endif
progname = argv[0];
if (progname == NULL || progname[0] == 0)
progname = "cjpeg"; /* in case C library doesn't provide it */
/* Initialize the JPEG compression object with default error handling. */
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
/* Add some application-specific error messages (from cderror.h) */
jerr.addon_message_table = cdjpeg_message_table;
jerr.first_addon_message = JMSG_FIRSTADDONCODE;
jerr.last_addon_message = JMSG_LASTADDONCODE;
/* Now safe to enable signal catcher. */
#ifdef NEED_SIGNAL_CATCHER
enable_signal_catcher((j_common_ptr) &cinfo);
#endif
/* Initialize JPEG parameters.
* Much of this may be overridden later.
* In particular, we don't yet know the input file's color space,
* but we need to provide some value for jpeg_set_defaults() to work.
*/
cinfo.in_color_space = JCS_RGB; /* arbitrary guess */
jpeg_set_defaults(&cinfo);
/* Scan command line to find file names.
* It is convenient to use just one switch-parsing routine, but the switch
* values read here are ignored; we will rescan the switches after opening
* the input file.
*/
file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
#ifdef TWO_FILE_COMMANDLINE
/* Must have either -outfile switch or explicit output file name */
if (outfilename == NULL) {
if (file_index != argc-2) {
fprintf(stderr, "%s: must name one input and one output file\n",
progname);
usage();
}
outfilename = argv[file_index+1];
} else {
if (file_index != argc-1) {
fprintf(stderr, "%s: must name one input and one output file\n",
progname);
usage();
}
}
#else
/* Unix style: expect zero or one file name */
if (file_index < argc-1) {
fprintf(stderr, "%s: only one input file\n", progname);
usage();
}
#endif /* TWO_FILE_COMMANDLINE */
/* Open the input file. */
if (file_index < argc) {
if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
exit(EXIT_FAILURE);
}
} else {
/* default input file is stdin */
input_file = read_stdin();
}
/* Open the output file. */
if (outfilename != NULL) {
if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
exit(EXIT_FAILURE);
}
} else {
/* default output file is stdout */
output_file = write_stdout();
}
#ifdef PROGRESS_REPORT
start_progress_monitor((j_common_ptr) &cinfo, &progress);
#endif
/* Figure out the input file format, and set up to read it. */
src_mgr = select_file_type(&cinfo, input_file);
src_mgr->input_file = input_file;
/* Read the input file header to obtain file size & colorspace. */
(*src_mgr->start_input) (&cinfo, src_mgr);
/* Now that we know input colorspace, fix colorspace-dependent defaults */
jpeg_default_colorspace(&cinfo);
/* Adjust default compression parameters by re-parsing the options */
file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
/* Specify data destination for compression */
jpeg_stdio_dest(&cinfo, output_file);
/* Start compressor */
jpeg_start_compress(&cinfo, TRUE);
/* Process data */
while (cinfo.next_scanline < cinfo.image_height) {
num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
(void) jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);
}
/* Finish compression and release memory */
(*src_mgr->finish_input) (&cinfo, src_mgr);
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
/* Close files, if we opened them */
if (input_file != stdin)
fclose(input_file);
if (output_file != stdout)
fclose(output_file);
#ifdef PROGRESS_REPORT
end_progress_monitor((j_common_ptr) &cinfo);
#endif
/* All done. */
exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
return 0; /* suppress no-return-value warnings */
}

402
crypto777/jpeg/ckconfig.c

@ -0,0 +1,402 @@
/*
* ckconfig.c
*
* Copyright (C) 1991-1994, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*/
/*
* This program is intended to help you determine how to configure the JPEG
* software for installation on a particular system. The idea is to try to
* compile and execute this program. If your compiler fails to compile the
* program, make changes as indicated in the comments below. Once you can
* compile the program, run it, and it will produce a "jconfig.h" file for
* your system.
*
* As a general rule, each time you try to compile this program,
* pay attention only to the *first* error message you get from the compiler.
* Many C compilers will issue lots of spurious error messages once they
* have gotten confused. Go to the line indicated in the first error message,
* and read the comments preceding that line to see what to change.
*
* Almost all of the edits you may need to make to this program consist of
* changing a line that reads "#define SOME_SYMBOL" to "#undef SOME_SYMBOL",
* or vice versa. This is called defining or undefining that symbol.
*/
/* First we must see if your system has the include files we need.
* We start out with the assumption that your system has all the ANSI-standard
* include files. If you get any error trying to include one of these files,
* undefine the corresponding HAVE_xxx symbol.
*/
#define HAVE_STDDEF_H /* replace 'define' by 'undef' if error here */
#ifdef HAVE_STDDEF_H /* next line will be skipped if you undef... */
#include <stddef.h>
#endif
#define HAVE_STDLIB_H /* same thing for stdlib.h */
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#include <stdio.h> /* If you ain't got this, you ain't got C. */
/* We have to see if your string functions are defined by
* strings.h (old BSD convention) or string.h (everybody else).
* We try the non-BSD convention first; define NEED_BSD_STRINGS
* if the compiler says it can't find string.h.
*/
#undef NEED_BSD_STRINGS
#ifdef NEED_BSD_STRINGS
#include <strings.h>
#else
#include <string.h>
#endif
/* On some systems (especially older Unix machines), type size_t is
* defined only in the include file <sys/types.h>. If you get a failure
* on the size_t test below, try defining NEED_SYS_TYPES_H.
*/
#undef NEED_SYS_TYPES_H /* start by assuming we don't need it */
#ifdef NEED_SYS_TYPES_H
#include <sys/types.h>
#endif
/* Usually type size_t is defined in one of the include files we've included
* above. If not, you'll get an error on the "typedef size_t my_size_t;" line.
* In that case, first try defining NEED_SYS_TYPES_H just above.
* If that doesn't work, you'll have to search through your system library
* to figure out which include file defines "size_t". Look for a line that
* says "typedef something-or-other size_t;". Then, change the line below
* that says "#include <someincludefile.h>" to instead include the file
* you found size_t in, and define NEED_SPECIAL_INCLUDE. If you can't find
* type size_t anywhere, try replacing "#include <someincludefile.h>" with
* "typedef unsigned int size_t;".
*/
#undef NEED_SPECIAL_INCLUDE /* assume we DON'T need it, for starters */
#ifdef NEED_SPECIAL_INCLUDE
#include <someincludefile.h>
#endif
typedef size_t my_size_t; /* The payoff: do we have size_t now? */
/* The next question is whether your compiler supports ANSI-style function
* prototypes. You need to know this in order to choose between using
* makefile.ansi and using makefile.unix.
* The #define line below is set to assume you have ANSI function prototypes.
* If you get an error in this group of lines, undefine HAVE_PROTOTYPES.
*/
#define HAVE_PROTOTYPES
#ifdef HAVE_PROTOTYPES
int testfunction (int arg1, int * arg2); /* check prototypes */
struct methods_struct { /* check method-pointer declarations */
int (*error_exit) (char *msgtext);
int (*trace_message) (char *msgtext);
int (*another_method) (void);
};
int testfunction (int arg1, int * arg2) /* check definitions */
{
return arg2[arg1];
}
int test2function (void) /* check void arg list */
{
return 0;
}
#endif
/* Now we want to find out if your compiler knows what "unsigned char" means.
* If you get an error on the "unsigned char un_char;" line,
* then undefine HAVE_UNSIGNED_CHAR.
*/
#define HAVE_UNSIGNED_CHAR
#ifdef HAVE_UNSIGNED_CHAR
unsigned char un_char;
#endif
/* Now we want to find out if your compiler knows what "unsigned short" means.
* If you get an error on the "unsigned short un_short;" line,
* then undefine HAVE_UNSIGNED_SHORT.
*/
#define HAVE_UNSIGNED_SHORT
#ifdef HAVE_UNSIGNED_SHORT
unsigned short un_short;
#endif
/* Now we want to find out if your compiler understands type "void".
* If you get an error anywhere in here, undefine HAVE_VOID.
*/
#define HAVE_VOID
#ifdef HAVE_VOID
/* Caution: a C++ compiler will insist on complete prototypes */
typedef void * void_ptr; /* check void * */
#ifdef HAVE_PROTOTYPES /* check ptr to function returning void */
typedef void (*void_func) (int a, int b);
#else
typedef void (*void_func) ();
#endif
#ifdef HAVE_PROTOTYPES /* check void function result */
void test3function (void_ptr arg1, void_func arg2)
#else
void test3function (arg1, arg2)
void_ptr arg1;
void_func arg2;
#endif
{
char * locptr = (char *) arg1; /* check casting to and from void * */
arg1 = (void *) locptr;
(*arg2) (1, 2); /* check call of fcn returning void */
}
#endif
/* Now we want to find out if your compiler knows what "const" means.
* If you get an error here, undefine HAVE_CONST.
*/
#define HAVE_CONST
#ifdef HAVE_CONST
static const int carray[3] = {1, 2, 3};
#ifdef HAVE_PROTOTYPES
int test4function (const int arg1)
#else
int test4function (arg1)
const int arg1;
#endif
{
return carray[arg1];
}
#endif
/* If you get an error or warning about this structure definition,
* define INCOMPLETE_TYPES_BROKEN.
*/
#undef INCOMPLETE_TYPES_BROKEN
#ifndef INCOMPLETE_TYPES_BROKEN
typedef struct undefined_structure * undef_struct_ptr;
#endif
/* If you get an error about duplicate names,
* define NEED_SHORT_EXTERNAL_NAMES.
*/
#undef NEED_SHORT_EXTERNAL_NAMES
#ifndef NEED_SHORT_EXTERNAL_NAMES
int possibly_duplicate_function ()
{
return 0;
}
int possibly_dupli_function ()
{
return 1;
}
#endif
/************************************************************************
* OK, that's it. You should not have to change anything beyond this
* point in order to compile and execute this program. (You might get
* some warnings, but you can ignore them.)
* When you run the program, it will make a couple more tests that it
* can do automatically, and then it will create jconfig.h and print out
* any additional suggestions it has.
************************************************************************
*/
#ifdef HAVE_PROTOTYPES
int is_char_signed (int arg)
#else
int is_char_signed (arg)
int arg;
#endif
{
if (arg == 189) { /* expected result for unsigned char */
return 0; /* type char is unsigned */
}
else if (arg != -67) { /* expected result for signed char */
printf("Hmm, it seems 'char' is not eight bits wide on your machine.\n");
printf("I fear the JPEG software will not work at all.\n\n");
}
return 1; /* assume char is signed otherwise */
}
#ifdef HAVE_PROTOTYPES
int is_shifting_signed (long arg)
#else
int is_shifting_signed (arg)
long arg;
#endif
/* See whether right-shift on a long is signed or not. */
{
long res = arg >> 4;
if (res == -0x7F7E80CL) { /* expected result for signed shift */
return 1; /* right shift is signed */
}
/* see if unsigned-shift hack will fix it. */
/* we can't just test exact value since it depends on width of long... */
res |= (~0L) << (32-4);
if (res == -0x7F7E80CL) { /* expected result now? */
return 0; /* right shift is unsigned */
}
printf("Right shift isn't acting as I expect it to.\n");
printf("I fear the JPEG software will not work at all.\n\n");
return 0; /* try it with unsigned anyway */
}
#ifdef HAVE_PROTOTYPES
int main (int argc, char ** argv)
#else
int main (argc, argv)
int argc;
char ** argv;
#endif
{
char signed_char_check = (char) (-67);
FILE *outfile;
/* Attempt to write jconfig.h */
if ((outfile = fopen("jconfig.h", "w")) == NULL) {
printf("Failed to write jconfig.h\n");
return 1;
}
/* Write out all the info */
fprintf(outfile, "/* jconfig.h --- generated by ckconfig.c */\n");
fprintf(outfile, "/* see jconfig.txt for explanations */\n\n");
#ifdef HAVE_PROTOTYPES
fprintf(outfile, "#define HAVE_PROTOTYPES\n");
#else
fprintf(outfile, "#undef HAVE_PROTOTYPES\n");
#endif
#ifdef HAVE_UNSIGNED_CHAR
fprintf(outfile, "#define HAVE_UNSIGNED_CHAR\n");
#else
fprintf(outfile, "#undef HAVE_UNSIGNED_CHAR\n");
#endif
#ifdef HAVE_UNSIGNED_SHORT
fprintf(outfile, "#define HAVE_UNSIGNED_SHORT\n");
#else
fprintf(outfile, "#undef HAVE_UNSIGNED_SHORT\n");
#endif
#ifdef HAVE_VOID
fprintf(outfile, "/* #define void char */\n");
#else
fprintf(outfile, "#define void char\n");
#endif
#ifdef HAVE_CONST
fprintf(outfile, "/* #define const */\n");
#else
fprintf(outfile, "#define const\n");
#endif
if (is_char_signed((int) signed_char_check))
fprintf(outfile, "#undef CHAR_IS_UNSIGNED\n");
else
fprintf(outfile, "#define CHAR_IS_UNSIGNED\n");
#ifdef HAVE_STDDEF_H
fprintf(outfile, "#define HAVE_STDDEF_H\n");
#else
fprintf(outfile, "#undef HAVE_STDDEF_H\n");
#endif
#ifdef HAVE_STDLIB_H
fprintf(outfile, "#define HAVE_STDLIB_H\n");
#else
fprintf(outfile, "#undef HAVE_STDLIB_H\n");
#endif
#ifdef NEED_BSD_STRINGS
fprintf(outfile, "#define NEED_BSD_STRINGS\n");
#else
fprintf(outfile, "#undef NEED_BSD_STRINGS\n");
#endif
#ifdef NEED_SYS_TYPES_H
fprintf(outfile, "#define NEED_SYS_TYPES_H\n");
#else
fprintf(outfile, "#undef NEED_SYS_TYPES_H\n");
#endif
fprintf(outfile, "#undef NEED_FAR_POINTERS\n");
#ifdef NEED_SHORT_EXTERNAL_NAMES
fprintf(outfile, "#define NEED_SHORT_EXTERNAL_NAMES\n");
#else
fprintf(outfile, "#undef NEED_SHORT_EXTERNAL_NAMES\n");
#endif
#ifdef INCOMPLETE_TYPES_BROKEN
fprintf(outfile, "#define INCOMPLETE_TYPES_BROKEN\n");
#else
fprintf(outfile, "#undef INCOMPLETE_TYPES_BROKEN\n");
#endif
fprintf(outfile, "\n#ifdef JPEG_INTERNALS\n\n");
if (is_shifting_signed(-0x7F7E80B1L))
fprintf(outfile, "#undef RIGHT_SHIFT_IS_UNSIGNED\n");
else
fprintf(outfile, "#define RIGHT_SHIFT_IS_UNSIGNED\n");
fprintf(outfile, "\n#endif /* JPEG_INTERNALS */\n");
fprintf(outfile, "\n#ifdef JPEG_CJPEG_DJPEG\n\n");
fprintf(outfile, "#define BMP_SUPPORTED /* BMP image file format */\n");
fprintf(outfile, "#define GIF_SUPPORTED /* GIF image file format */\n");
fprintf(outfile, "#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */\n");
fprintf(outfile, "#undef RLE_SUPPORTED /* Utah RLE image file format */\n");
fprintf(outfile, "#define TARGA_SUPPORTED /* Targa image file format */\n\n");
fprintf(outfile, "#undef TWO_FILE_COMMANDLINE /* You may need this on non-Unix systems */\n");
fprintf(outfile, "#undef NEED_SIGNAL_CATCHER /* Define this if you use jmemname.c */\n");
fprintf(outfile, "#undef DONT_USE_B_MODE\n");
fprintf(outfile, "/* #define PROGRESS_REPORT */ /* optional */\n");
fprintf(outfile, "\n#endif /* JPEG_CJPEG_DJPEG */\n");
/* Close the jconfig.h file */
fclose(outfile);
/* User report */
printf("Configuration check for Independent JPEG Group's software done.\n");
printf("\nI have written the jconfig.h file for you.\n\n");
#ifdef HAVE_PROTOTYPES
printf("You should use makefile.ansi as the starting point for your Makefile.\n");
#else
printf("You should use makefile.unix as the starting point for your Makefile.\n");
#endif
#ifdef NEED_SPECIAL_INCLUDE
printf("\nYou'll need to change jconfig.h to include the system include file\n");
printf("that you found type size_t in, or add a direct definition of type\n");
printf("size_t if that's what you used. Just add it to the end.\n");
#endif
return 0;
}

617
crypto777/jpeg/djpeg.c

@ -0,0 +1,617 @@
/*
* djpeg.c
*
* Copyright (C) 1991-1997, Thomas G. Lane.
* Modified 2009 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains a command-line user interface for the JPEG decompressor.
* It should work on any system with Unix- or MS-DOS-style command lines.
*
* Two different command line styles are permitted, depending on the
* compile-time switch TWO_FILE_COMMANDLINE:
* djpeg [options] inputfile outputfile
* djpeg [options] [inputfile]
* In the second style, output is always to standard output, which you'd
* normally redirect to a file or pipe to some other program. Input is
* either from a named file or from standard input (typically redirected).
* The second style is convenient on Unix but is unhelpful on systems that
* don't support pipes. Also, you MUST use the first style if your system
* doesn't do binary I/O to stdin/stdout.
* To simplify script writing, the "-outfile" switch is provided. The syntax
* djpeg [options] -outfile outputfile inputfile
* works regardless of which command line style is used.
*/
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#include "jversion.h" /* for version message */
#include <ctype.h> /* to declare isprint() */
#ifdef USE_CCOMMAND /* command-line reader for Macintosh */
#ifdef __MWERKS__
#include <SIOUX.h> /* Metrowerks needs this */
#include <console.h> /* ... and this */
#endif
#ifdef THINK_C
#include <console.h> /* Think declares it here */
#endif
#endif
/* Create the add-on message string table. */
#define JMESSAGE(code,string) string ,
static const char * const cdjpeg_message_table[] = {
#include "cderror.h"
NULL
};
/*
* This list defines the known output image formats
* (not all of which need be supported by a given version).
* You can change the default output format by defining DEFAULT_FMT;
* indeed, you had better do so if you undefine PPM_SUPPORTED.
*/
typedef enum {
FMT_BMP, /* BMP format (Windows flavor) */
FMT_GIF, /* GIF format */
FMT_OS2, /* BMP format (OS/2 flavor) */
FMT_PPM, /* PPM/PGM (PBMPLUS formats) */
FMT_RLE, /* RLE format */
FMT_TARGA, /* Targa format */
FMT_TIFF /* TIFF format */
} IMAGE_FORMATS;
#ifndef DEFAULT_FMT /* so can override from CFLAGS in Makefile */
#define DEFAULT_FMT FMT_PPM
#endif
static IMAGE_FORMATS requested_fmt;
/*
* Argument-parsing code.
* The switch parser is designed to be useful with DOS-style command line
* syntax, ie, intermixed switches and file names, where only the switches
* to the left of a given file name affect processing of that file.
* The main program in this file doesn't actually use this capability...
*/
static const char * progname; /* program name for error messages */
static char * outfilename; /* for -outfile switch */
LOCAL(void)
usage (void)
/* complain about bad command line */
{
fprintf(stderr, "usage: %s [switches] ", progname);
#ifdef TWO_FILE_COMMANDLINE
fprintf(stderr, "inputfile outputfile\n");
#else
fprintf(stderr, "[inputfile]\n");
#endif
fprintf(stderr, "Switches (names may be abbreviated):\n");
fprintf(stderr, " -colors N Reduce image to no more than N colors\n");
fprintf(stderr, " -fast Fast, low-quality processing\n");
fprintf(stderr, " -grayscale Force grayscale output\n");
#ifdef IDCT_SCALING_SUPPORTED
fprintf(stderr, " -scale M/N Scale output image by fraction M/N, eg, 1/8\n");
#endif
#ifdef BMP_SUPPORTED
fprintf(stderr, " -bmp Select BMP output format (Windows style)%s\n",
(DEFAULT_FMT == FMT_BMP ? " (default)" : ""));
#endif
#ifdef GIF_SUPPORTED
fprintf(stderr, " -gif Select GIF output format%s\n",
(DEFAULT_FMT == FMT_GIF ? " (default)" : ""));
#endif
#ifdef BMP_SUPPORTED
fprintf(stderr, " -os2 Select BMP output format (OS/2 style)%s\n",
(DEFAULT_FMT == FMT_OS2 ? " (default)" : ""));
#endif
#ifdef PPM_SUPPORTED
fprintf(stderr, " -pnm Select PBMPLUS (PPM/PGM) output format%s\n",
(DEFAULT_FMT == FMT_PPM ? " (default)" : ""));
#endif
#ifdef RLE_SUPPORTED
fprintf(stderr, " -rle Select Utah RLE output format%s\n",
(DEFAULT_FMT == FMT_RLE ? " (default)" : ""));
#endif
#ifdef TARGA_SUPPORTED
fprintf(stderr, " -targa Select Targa output format%s\n",
(DEFAULT_FMT == FMT_TARGA ? " (default)" : ""));
#endif
fprintf(stderr, "Switches for advanced users:\n");
#ifdef DCT_ISLOW_SUPPORTED
fprintf(stderr, " -dct int Use integer DCT method%s\n",
(JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
#endif
#ifdef DCT_IFAST_SUPPORTED
fprintf(stderr, " -dct fast Use fast integer DCT (less accurate)%s\n",
(JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
#endif
#ifdef DCT_FLOAT_SUPPORTED
fprintf(stderr, " -dct float Use floating-point DCT method%s\n",
(JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
#endif
fprintf(stderr, " -dither fs Use F-S dithering (default)\n");
fprintf(stderr, " -dither none Don't use dithering in quantization\n");
fprintf(stderr, " -dither ordered Use ordered dither (medium speed, quality)\n");
#ifdef QUANT_2PASS_SUPPORTED
fprintf(stderr, " -map FILE Map to colors used in named image file\n");
#endif
fprintf(stderr, " -nosmooth Don't use high-quality upsampling\n");
#ifdef QUANT_1PASS_SUPPORTED
fprintf(stderr, " -onepass Use 1-pass quantization (fast, low quality)\n");
#endif
fprintf(stderr, " -maxmemory N Maximum memory to use (in kbytes)\n");
fprintf(stderr, " -outfile name Specify name for output file\n");
fprintf(stderr, " -verbose or -debug Emit debug output\n");
exit(EXIT_FAILURE);
}
LOCAL(int)
parse_switches (j_decompress_ptr cinfo, int argc, char **argv,
int last_file_arg_seen, boolean for_real)
/* Parse optional switches.
* Returns argv[] index of first file-name argument (== argc if none).
* Any file names with indexes <= last_file_arg_seen are ignored;
* they have presumably been processed in a previous iteration.
* (Pass 0 for last_file_arg_seen on the first or only iteration.)
* for_real is FALSE on the first (dummy) pass; we may skip any expensive
* processing.
*/
{
int argn;
char * arg;
/* Set up default JPEG parameters. */
requested_fmt = DEFAULT_FMT; /* set default output file format */
outfilename = NULL;
cinfo->err->trace_level = 0;
/* Scan command line options, adjust parameters */
for (argn = 1; argn < argc; argn++) {
arg = argv[argn];
if (*arg != '-') {
/* Not a switch, must be a file name argument */
if (argn <= last_file_arg_seen) {
outfilename = NULL; /* -outfile applies to just one input file */
continue; /* ignore this name if previously processed */
}
break; /* else done parsing switches */
}
arg++; /* advance past switch marker character */
if (keymatch(arg, "bmp", 1)) {
/* BMP output format. */
requested_fmt = FMT_BMP;
} else if (keymatch(arg, "colors", 1) || keymatch(arg, "colours", 1) ||
keymatch(arg, "quantize", 1) || keymatch(arg, "quantise", 1)) {
/* Do color quantization. */
int val;
if (++argn >= argc) /* advance to next argument */
usage();
if (sscanf(argv[argn], "%d", &val) != 1)
usage();
cinfo->desired_number_of_colors = val;
cinfo->quantize_colors = TRUE;
} else if (keymatch(arg, "dct", 2)) {
/* Select IDCT algorithm. */
if (++argn >= argc) /* advance to next argument */
usage();
if (keymatch(argv[argn], "int", 1)) {
cinfo->dct_method = JDCT_ISLOW;
} else if (keymatch(argv[argn], "fast", 2)) {
cinfo->dct_method = JDCT_IFAST;
} else if (keymatch(argv[argn], "float", 2)) {
cinfo->dct_method = JDCT_FLOAT;
} else
usage();
} else if (keymatch(arg, "dither", 2)) {
/* Select dithering algorithm. */
if (++argn >= argc) /* advance to next argument */
usage();
if (keymatch(argv[argn], "fs", 2)) {
cinfo->dither_mode = JDITHER_FS;
} else if (keymatch(argv[argn], "none", 2)) {
cinfo->dither_mode = JDITHER_NONE;
} else if (keymatch(argv[argn], "ordered", 2)) {
cinfo->dither_mode = JDITHER_ORDERED;
} else
usage();
} else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
/* Enable debug printouts. */
/* On first -d, print version identification */
static boolean printed_version = FALSE;
if (! printed_version) {
fprintf(stderr, "Independent JPEG Group's DJPEG, version %s\n%s\n",
JVERSION, JCOPYRIGHT);
printed_version = TRUE;
}
cinfo->err->trace_level++;
} else if (keymatch(arg, "fast", 1)) {
/* Select recommended processing options for quick-and-dirty output. */
cinfo->two_pass_quantize = FALSE;
cinfo->dither_mode = JDITHER_ORDERED;
if (! cinfo->quantize_colors) /* don't override an earlier -colors */
cinfo->desired_number_of_colors = 216;
cinfo->dct_method = JDCT_FASTEST;
cinfo->do_fancy_upsampling = FALSE;
} else if (keymatch(arg, "gif", 1)) {
/* GIF output format. */
requested_fmt = FMT_GIF;
} else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
/* Force monochrome output. */
cinfo->out_color_space = JCS_GRAYSCALE;
} else if (keymatch(arg, "map", 3)) {
/* Quantize to a color map taken from an input file. */
if (++argn >= argc) /* advance to next argument */
usage();
if (for_real) { /* too expensive to do twice! */
#ifdef QUANT_2PASS_SUPPORTED /* otherwise can't quantize to supplied map */
FILE * mapfile;
if ((mapfile = fopen(argv[argn], READ_BINARY)) == NULL) {
fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
exit(EXIT_FAILURE);
}
read_color_map(cinfo, mapfile);
fclose(mapfile);
cinfo->quantize_colors = TRUE;
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif
}
} else if (keymatch(arg, "maxmemory", 3)) {
/* Maximum memory in Kb (or Mb with 'm'). */
long lval;
char ch = 'x';
if (++argn >= argc) /* advance to next argument */
usage();
if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
usage();
if (ch == 'm' || ch == 'M')
lval *= 1000L;
cinfo->mem->max_memory_to_use = lval * 1000L;
} else if (keymatch(arg, "nosmooth", 3)) {
/* Suppress fancy upsampling */
cinfo->do_fancy_upsampling = FALSE;
} else if (keymatch(arg, "onepass", 3)) {
/* Use fast one-pass quantization. */
cinfo->two_pass_quantize = FALSE;
} else if (keymatch(arg, "os2", 3)) {
/* BMP output format (OS/2 flavor). */
requested_fmt = FMT_OS2;
} else if (keymatch(arg, "outfile", 4)) {
/* Set output file name. */
if (++argn >= argc) /* advance to next argument */
usage();
outfilename = argv[argn]; /* save it away for later use */
} else if (keymatch(arg, "pnm", 1) || keymatch(arg, "ppm", 1)) {
/* PPM/PGM output format. */
requested_fmt = FMT_PPM;
} else if (keymatch(arg, "rle", 1)) {
/* RLE output format. */
requested_fmt = FMT_RLE;
} else if (keymatch(arg, "scale", 1)) {
/* Scale the output image by a fraction M/N. */
if (++argn >= argc) /* advance to next argument */
usage();
if (sscanf(argv[argn], "%d/%d",
&cinfo->scale_num, &cinfo->scale_denom) < 1)
usage();
} else if (keymatch(arg, "targa", 1)) {
/* Targa output format. */
requested_fmt = FMT_TARGA;
} else {
usage(); /* bogus switch */
}
}
return argn; /* return index of next arg (file name) */
}
/*
* Marker processor for COM and interesting APPn markers.
* This replaces the library's built-in processor, which just skips the marker.
* We want to print out the marker as text, to the extent possible.
* Note this code relies on a non-suspending data source.
*/
LOCAL(unsigned int)
jpeg_getc (j_decompress_ptr cinfo)
/* Read next byte */
{
struct jpeg_source_mgr * datasrc = cinfo->src;
if (datasrc->bytes_in_buffer == 0) {
if (! (*datasrc->fill_input_buffer) (cinfo))
ERREXIT(cinfo, JERR_CANT_SUSPEND);
}
datasrc->bytes_in_buffer--;
return GETJOCTET(*datasrc->next_input_byte++);
}
METHODDEF(boolean)
print_text_marker (j_decompress_ptr cinfo)
{
boolean traceit = (cinfo->err->trace_level >= 1);
INT32 length;
unsigned int ch;
unsigned int lastch = 0;
length = jpeg_getc(cinfo) << 8;
length += jpeg_getc(cinfo);
length -= 2; /* discount the length word itself */
if (traceit) {
if (cinfo->unread_marker == JPEG_COM)
fprintf(stderr, "Comment, length %ld:\n", (long) length);
else /* assume it is an APPn otherwise */
fprintf(stderr, "APP%d, length %ld:\n",
cinfo->unread_marker - JPEG_APP0, (long) length);
}
while (--length >= 0) {
ch = jpeg_getc(cinfo);
if (traceit) {
/* Emit the character in a readable form.
* Nonprintables are converted to \nnn form,
* while \ is converted to \\.
* Newlines in CR, CR/LF, or LF form will be printed as one newline.
*/
if (ch == '\r') {
fprintf(stderr, "\n");
} else if (ch == '\n') {
if (lastch != '\r')
fprintf(stderr, "\n");
} else if (ch == '\\') {
fprintf(stderr, "\\\\");
} else if (isprint(ch)) {
putc(ch, stderr);
} else {
fprintf(stderr, "\\%03o", ch);
}
lastch = ch;
}
}
if (traceit)
fprintf(stderr, "\n");
return TRUE;
}
/*
* The main program.
*/
int
main (int argc, char **argv)
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
#ifdef PROGRESS_REPORT
struct cdjpeg_progress_mgr progress;
#endif
int file_index;
djpeg_dest_ptr dest_mgr = NULL;
FILE * input_file;
FILE * output_file;
JDIMENSION num_scanlines;
/* On Mac, fetch a command line. */
#ifdef USE_CCOMMAND
argc = ccommand(&argv);
#endif
progname = argv[0];
if (progname == NULL || progname[0] == 0)
progname = "djpeg"; /* in case C library doesn't provide it */
/* Initialize the JPEG decompression object with default error handling. */
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
/* Add some application-specific error messages (from cderror.h) */
jerr.addon_message_table = cdjpeg_message_table;
jerr.first_addon_message = JMSG_FIRSTADDONCODE;
jerr.last_addon_message = JMSG_LASTADDONCODE;
/* Insert custom marker processor for COM and APP12.
* APP12 is used by some digital camera makers for textual info,
* so we provide the ability to display it as text.
* If you like, additional APPn marker types can be selected for display,
* but don't try to override APP0 or APP14 this way (see libjpeg.doc).
*/
jpeg_set_marker_processor(&cinfo, JPEG_COM, print_text_marker);
jpeg_set_marker_processor(&cinfo, JPEG_APP0+12, print_text_marker);
/* Now safe to enable signal catcher. */
#ifdef NEED_SIGNAL_CATCHER
enable_signal_catcher((j_common_ptr) &cinfo);
#endif
/* Scan command line to find file names. */
/* It is convenient to use just one switch-parsing routine, but the switch
* values read here are ignored; we will rescan the switches after opening
* the input file.
* (Exception: tracing level set here controls verbosity for COM markers
* found during jpeg_read_header...)
*/
file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
#ifdef TWO_FILE_COMMANDLINE
/* Must have either -outfile switch or explicit output file name */
if (outfilename == NULL) {
if (file_index != argc-2) {
fprintf(stderr, "%s: must name one input and one output file\n",
progname);
usage();
}
outfilename = argv[file_index+1];
} else {
if (file_index != argc-1) {
fprintf(stderr, "%s: must name one input and one output file\n",
progname);
usage();
}
}
#else
/* Unix style: expect zero or one file name */
if (file_index < argc-1) {
fprintf(stderr, "%s: only one input file\n", progname);
usage();
}
#endif /* TWO_FILE_COMMANDLINE */
/* Open the input file. */
if (file_index < argc) {
if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
exit(EXIT_FAILURE);
}
} else {
/* default input file is stdin */
input_file = read_stdin();
}
/* Open the output file. */
if (outfilename != NULL) {
if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
exit(EXIT_FAILURE);
}
} else {
/* default output file is stdout */
output_file = write_stdout();
}
#ifdef PROGRESS_REPORT
start_progress_monitor((j_common_ptr) &cinfo, &progress);
#endif
/* Specify data source for decompression */
jpeg_stdio_src(&cinfo, input_file);
/* Read file header, set default decompression parameters */
(void) jpeg_read_header(&cinfo, TRUE);
/* Adjust default decompression parameters by re-parsing the options */
file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
/* Initialize the output module now to let it override any crucial
* option settings (for instance, GIF wants to force color quantization).
*/
switch (requested_fmt) {
#ifdef BMP_SUPPORTED
case FMT_BMP:
dest_mgr = jinit_write_bmp(&cinfo, FALSE);
break;
case FMT_OS2:
dest_mgr = jinit_write_bmp(&cinfo, TRUE);
break;
#endif
#ifdef GIF_SUPPORTED
case FMT_GIF:
dest_mgr = jinit_write_gif(&cinfo);
break;
#endif
#ifdef PPM_SUPPORTED
case FMT_PPM:
dest_mgr = jinit_write_ppm(&cinfo);
break;
#endif
#ifdef RLE_SUPPORTED
case FMT_RLE:
dest_mgr = jinit_write_rle(&cinfo);
break;
#endif
#ifdef TARGA_SUPPORTED
case FMT_TARGA:
dest_mgr = jinit_write_targa(&cinfo);
break;
#endif
default:
ERREXIT(&cinfo, JERR_UNSUPPORTED_FORMAT);
break;
}
dest_mgr->output_file = output_file;
/* Start decompressor */
(void) jpeg_start_decompress(&cinfo);
/* Write output file header */
(*dest_mgr->start_output) (&cinfo, dest_mgr);
/* Process data */
while (cinfo.output_scanline < cinfo.output_height) {
num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
dest_mgr->buffer_height);
(*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
}
#ifdef PROGRESS_REPORT
/* Hack: count final pass as done in case finish_output does an extra pass.
* The library won't have updated completed_passes.
*/
progress.pub.completed_passes = progress.pub.total_passes;
#endif
/* Finish decompression and release memory.
* I must do it in this order because output module has allocated memory
* of lifespan JPOOL_IMAGE; it needs to finish before releasing memory.
*/
(*dest_mgr->finish_output) (&cinfo, dest_mgr);
(void) jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
/* Close files, if we opened them */
if (input_file != stdin)
fclose(input_file);
if (output_file != stdout)
fclose(output_file);
#ifdef PROGRESS_REPORT
end_progress_monitor((j_common_ptr) &cinfo);
#endif
/* All done. */
exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
return 0; /* suppress no-return-value warnings */
}

433
crypto777/jpeg/example.c

@ -0,0 +1,433 @@
/*
* example.c
*
* This file illustrates how to use the IJG code as a subroutine library
* to read or write JPEG image files. You should look at this code in
* conjunction with the documentation file libjpeg.txt.
*
* This code will not do anything useful as-is, but it may be helpful as a
* skeleton for constructing routines that call the JPEG library.
*
* We present these routines in the same coding style used in the JPEG code
* (ANSI function definitions, etc); but you are of course free to code your
* routines in a different style if you prefer.
*/
#include <stdio.h>
/*
* Include file for users of JPEG library.
* You will need to have included system headers that define at least
* the typedefs FILE and size_t before you can include jpeglib.h.
* (stdio.h is sufficient on ANSI-conforming systems.)
* You may also wish to include "jerror.h".
*/
#include "jpeglib.h"
/*
* <setjmp.h> is used for the optional error recovery mechanism shown in
* the second part of the example.
*/
#include <setjmp.h>
/******************** JPEG COMPRESSION SAMPLE INTERFACE *******************/
/* This half of the example shows how to feed data into the JPEG compressor.
* We present a minimal version that does not worry about refinements such
* as error recovery (the JPEG code will just exit() if it gets an error).
*/
/*
* IMAGE DATA FORMATS:
*
* The standard input image format is a rectangular array of pixels, with
* each pixel having the same number of "component" values (color channels).
* Each pixel row is an array of JSAMPLEs (which typically are unsigned chars).
* If you are working with color data, then the color values for each pixel
* must be adjacent in the row; for example, R,G,B,R,G,B,R,G,B,... for 24-bit
* RGB color.
*
* For this example, we'll assume that this data structure matches the way
* our application has stored the image in memory, so we can just pass a
* pointer to our image buffer. In particular, let's say that the image is
* RGB color and is described by:
*/
extern JSAMPLE * image_buffer; /* Points to large array of R,G,B-order data */
extern int image_height; /* Number of rows in image */
extern int image_width; /* Number of columns in image */
/*
* Sample routine for JPEG compression. We assume that the target file name
* and a compression quality factor are passed in.
*/
GLOBAL(void)
write_JPEG_file (char * filename, int quality)
{
/* This struct contains the JPEG compression parameters and pointers to
* working space (which is allocated as needed by the JPEG library).
* It is possible to have several such structures, representing multiple
* compression/decompression processes, in existence at once. We refer
* to any one struct (and its associated working data) as a "JPEG object".
*/
struct jpeg_compress_struct cinfo;
/* This struct represents a JPEG error handler. It is declared separately
* because applications often want to supply a specialized error handler
* (see the second half of this file for an example). But here we just
* take the easy way out and use the standard error handler, which will
* print a message on stderr and call exit() if compression fails.
* Note that this struct must live as long as the main JPEG parameter
* struct, to avoid dangling-pointer problems.
*/
struct jpeg_error_mgr jerr;
/* More stuff */
FILE * outfile; /* target file */
JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
int row_stride; /* physical row width in image buffer */
/* Step 1: allocate and initialize JPEG compression object */
/* We have to set up the error handler first, in case the initialization
* step fails. (Unlikely, but it could happen if you are out of memory.)
* This routine fills in the contents of struct jerr, and returns jerr's
* address which we place into the link field in cinfo.
*/
cinfo.err = jpeg_std_error(&jerr);
/* Now we can initialize the JPEG compression object. */
jpeg_create_compress(&cinfo);
/* Step 2: specify data destination (eg, a file) */
/* Note: steps 2 and 3 can be done in either order. */
/* Here we use the library-supplied code to send compressed data to a
* stdio stream. You can also write your own code to do something else.
* VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
* requires it in order to write binary files.
*/
if ((outfile = fopen(filename, "wb")) == NULL) {
fprintf(stderr, "can't open %s\n", filename);
exit(1);
}
jpeg_stdio_dest(&cinfo, outfile);
/* Step 3: set parameters for compression */
/* First we supply a description of the input image.
* Four fields of the cinfo struct must be filled in:
*/
cinfo.image_width = image_width; /* image width and height, in pixels */
cinfo.image_height = image_height;
cinfo.input_components = 3; /* # of color components per pixel */
cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
/* Now use the library's routine to set default compression parameters.
* (You must set at least cinfo.in_color_space before calling this,
* since the defaults depend on the source color space.)
*/
jpeg_set_defaults(&cinfo);
/* Now you can set any non-default parameters you wish to.
* Here we just illustrate the use of quality (quantization table) scaling:
*/
jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
/* Step 4: Start compressor */
/* TRUE ensures that we will write a complete interchange-JPEG file.
* Pass TRUE unless you are very sure of what you're doing.
*/
jpeg_start_compress(&cinfo, TRUE);
/* Step 5: while (scan lines remain to be written) */
/* jpeg_write_scanlines(...); */
/* Here we use the library's state variable cinfo.next_scanline as the
* loop counter, so that we don't have to keep track ourselves.
* To keep things simple, we pass one scanline per call; you can pass
* more if you wish, though.
*/
row_stride = image_width * 3; /* JSAMPLEs per row in image_buffer */
while (cinfo.next_scanline < cinfo.image_height) {
/* jpeg_write_scanlines expects an array of pointers to scanlines.
* Here the array is only one element long, but you could pass
* more than one scanline at a time if that's more convenient.
*/
row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
/* Step 6: Finish compression */
jpeg_finish_compress(&cinfo);
/* After finish_compress, we can close the output file. */
fclose(outfile);
/* Step 7: release JPEG compression object */
/* This is an important step since it will release a good deal of memory. */
jpeg_destroy_compress(&cinfo);
/* And we're done! */
}
/*
* SOME FINE POINTS:
*
* In the above loop, we ignored the return value of jpeg_write_scanlines,
* which is the number of scanlines actually written. We could get away
* with this because we were only relying on the value of cinfo.next_scanline,
* which will be incremented correctly. If you maintain additional loop
* variables then you should be careful to increment them properly.
* Actually, for output to a stdio stream you needn't worry, because
* then jpeg_write_scanlines will write all the lines passed (or else exit
* with a fatal error). Partial writes can only occur if you use a data
* destination module that can demand suspension of the compressor.
* (If you don't know what that's for, you don't need it.)
*
* If the compressor requires full-image buffers (for entropy-coding
* optimization or a multi-scan JPEG file), it will create temporary
* files for anything that doesn't fit within the maximum-memory setting.
* (Note that temp files are NOT needed if you use the default parameters.)
* On some systems you may need to set up a signal handler to ensure that
* temporary files are deleted if the program is interrupted. See libjpeg.txt.
*
* Scanlines MUST be supplied in top-to-bottom order if you want your JPEG
* files to be compatible with everyone else's. If you cannot readily read
* your data in that order, you'll need an intermediate array to hold the
* image. See rdtarga.c or rdbmp.c for examples of handling bottom-to-top
* source data using the JPEG code's internal virtual-array mechanisms.
*/
/******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/
/* This half of the example shows how to read data from the JPEG decompressor.
* It's a bit more refined than the above, in that we show:
* (a) how to modify the JPEG library's standard error-reporting behavior;
* (b) how to allocate workspace using the library's memory manager.
*
* Just to make this example a little different from the first one, we'll
* assume that we do not intend to put the whole image into an in-memory
* buffer, but to send it line-by-line someplace else. We need a one-
* scanline-high JSAMPLE array as a work buffer, and we will let the JPEG
* memory manager allocate it for us. This approach is actually quite useful
* because we don't need to remember to deallocate the buffer separately: it
* will go away automatically when the JPEG object is cleaned up.
*/
/*
* ERROR HANDLING:
*
* The JPEG library's standard error handler (jerror.c) is divided into
* several "methods" which you can override individually. This lets you
* adjust the behavior without duplicating a lot of code, which you might
* have to update with each future release.
*
* Our example here shows how to override the "error_exit" method so that
* control is returned to the library's caller when a fatal error occurs,
* rather than calling exit() as the standard error_exit method does.
*
* We use C's setjmp/longjmp facility to return control. This means that the
* routine which calls the JPEG library must first execute a setjmp() call to
* establish the return point. We want the replacement error_exit to do a
* longjmp(). But we need to make the setjmp buffer accessible to the
* error_exit routine. To do this, we make a private extension of the
* standard JPEG error handler object. (If we were using C++, we'd say we
* were making a subclass of the regular error handler.)
*
* Here's the extended error handler struct:
*/
struct my_error_mgr {
struct jpeg_error_mgr pub; /* "public" fields */
jmp_buf setjmp_buffer; /* for return to caller */
};
typedef struct my_error_mgr * my_error_ptr;
/*
* Here's the routine that will replace the standard error_exit method:
*/
METHODDEF(void)
my_error_exit (j_common_ptr cinfo)
{
/* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
my_error_ptr myerr = (my_error_ptr) cinfo->err;
/* Always display the message. */
/* We could postpone this until after returning, if we chose. */
(*cinfo->err->output_message) (cinfo);
/* Return control to the setjmp point */
longjmp(myerr->setjmp_buffer, 1);
}
/*
* Sample routine for JPEG decompression. We assume that the source file name
* is passed in. We want to return 1 on success, 0 on error.
*/
GLOBAL(int)
read_JPEG_file (char * filename)
{
/* This struct contains the JPEG decompression parameters and pointers to
* working space (which is allocated as needed by the JPEG library).
*/
struct jpeg_decompress_struct cinfo;
/* We use our private extension JPEG error handler.
* Note that this struct must live as long as the main JPEG parameter
* struct, to avoid dangling-pointer problems.
*/
struct my_error_mgr jerr;
/* More stuff */
FILE * infile; /* source file */
JSAMPARRAY buffer; /* Output row buffer */
int row_stride; /* physical row width in output buffer */
/* In this example we want to open the input file before doing anything else,
* so that the setjmp() error recovery below can assume the file is open.
* VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
* requires it in order to read binary files.
*/
if ((infile = fopen(filename, "rb")) == NULL) {
fprintf(stderr, "can't open %s\n", filename);
return 0;
}
/* Step 1: allocate and initialize JPEG decompression object */
/* We set up the normal JPEG error routines, then override error_exit. */
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
/* Establish the setjmp return context for my_error_exit to use. */
if (setjmp(jerr.setjmp_buffer)) {
/* If we get here, the JPEG code has signaled an error.
* We need to clean up the JPEG object, close the input file, and return.
*/
jpeg_destroy_decompress(&cinfo);
fclose(infile);
return 0;
}
/* Now we can initialize the JPEG decompression object. */
jpeg_create_decompress(&cinfo);
/* Step 2: specify data source (eg, a file) */
jpeg_stdio_src(&cinfo, infile);
/* Step 3: read file parameters with jpeg_read_header() */
(void) jpeg_read_header(&cinfo, TRUE);
/* We can ignore the return value from jpeg_read_header since
* (a) suspension is not possible with the stdio data source, and
* (b) we passed TRUE to reject a tables-only JPEG file as an error.
* See libjpeg.txt for more info.
*/
/* Step 4: set parameters for decompression */
/* In this example, we don't need to change any of the defaults set by
* jpeg_read_header(), so we do nothing here.
*/
/* Step 5: Start decompressor */
(void) jpeg_start_decompress(&cinfo);
/* We can ignore the return value since suspension is not possible
* with the stdio data source.
*/
/* We may need to do some setup of our own at this point before reading
* the data. After jpeg_start_decompress() we have the correct scaled
* output image dimensions available, as well as the output colormap
* if we asked for color quantization.
* In this example, we need to make an output work buffer of the right size.
*/
/* JSAMPLEs per row in output buffer */
row_stride = cinfo.output_width * cinfo.output_components;
/* Make a one-row-high sample array that will go away when done with image */
buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
/* Step 6: while (scan lines remain to be read) */
/* jpeg_read_scanlines(...); */
/* Here we use the library's state variable cinfo.output_scanline as the
* loop counter, so that we don't have to keep track ourselves.
*/
while (cinfo.output_scanline < cinfo.output_height) {
/* jpeg_read_scanlines expects an array of pointers to scanlines.
* Here the array is only one element long, but you could ask for
* more than one scanline at a time if that's more convenient.
*/
(void) jpeg_read_scanlines(&cinfo, buffer, 1);
/* Assume put_scanline_someplace wants a pointer and sample count. */
put_scanline_someplace(buffer[0], row_stride);
}
/* Step 7: Finish decompression */
(void) jpeg_finish_decompress(&cinfo);
/* We can ignore the return value since suspension is not possible
* with the stdio data source.
*/
/* Step 8: Release JPEG decompression object */
/* This is an important step since it will release a good deal of memory. */
jpeg_destroy_decompress(&cinfo);
/* After finish_decompress, we can close the input file.
* Here we postpone it until after no more JPEG errors are possible,
* so as to simplify the setjmp error logic above. (Actually, I don't
* think that jpeg_destroy can do an error exit, but why assume anything...)
*/
fclose(infile);
/* At this point you may want to check to see whether any corrupt-data
* warnings occurred (test whether jerr.pub.num_warnings is nonzero).
*/
/* And we're done! */
return 1;
}
/*
* SOME FINE POINTS:
*
* In the above code, we ignored the return value of jpeg_read_scanlines,
* which is the number of scanlines actually read. We could get away with
* this because we asked for only one line at a time and we weren't using
* a suspending data source. See libjpeg.txt for more info.
*
* We cheated a bit by calling alloc_sarray() after jpeg_start_decompress();
* we should have done it beforehand to ensure that the space would be
* counted against the JPEG max_memory setting. In some systems the above
* code would risk an out-of-memory error. However, in general we don't
* know the output image dimensions before jpeg_start_decompress(), unless we
* call jpeg_calc_output_dimensions(). See libjpeg.txt for more about this.
*
* Scanlines are returned in the same order as they appear in the JPEG file,
* which is standardly top-to-bottom. If you must emit data bottom-to-top,
* you can use one of the virtual arrays provided by the JPEG memory manager
* to invert the data. See wrbmp.c for an example.
*
* As with compression, some operating modes may require temporary files.
* On some systems you may need to set up a signal handler to ensure that
* temporary files are deleted if the program is interrupted. See libjpeg.txt.
*/

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

Loading…
Cancel
Save