Browse Source

test

release/v0.1
jl777 9 years ago
parent
commit
c5c68c7f20
  1. 9
      crypto777/tools/common.mk
  2. 107
      crypto777/tools/fix_deps.py
  3. 276
      crypto777/tools/nacl_config.py
  4. 22
      iguana/SuperNET.c
  5. 19
      iguana/SuperNET.h
  6. 72
      iguana/exchanges/bitcoin.c
  7. 26
      iguana/exchanges777.h
  8. 8
      iguana/help/header.html
  9. 12
      iguana/iguana_chains.c
  10. 1
      iguana/iguana_exchanges.c
  11. 198
      iguana/iguana_instantdex.c
  12. 3
      iguana/iguana_rpc.c
  13. 4
      iguana/main.c
  14. 7
      iguana/swaps/iguana_BTCswap.c
  15. 9
      iguana/tools/common.mk
  16. 107
      iguana/tools/fix_deps.py
  17. 275
      iguana/tools/getos.py
  18. 276
      iguana/tools/nacl_config.py
  19. 6
      includes/iguana_apideclares.h
  20. 21
      tools/common.mk
  21. 107
      tools/fix_deps.py
  22. 276
      tools/nacl_config.py

9
crypto777/tools/common.mk

@ -32,9 +32,12 @@ TOP_MAKE := $(word 1,$(MAKEFILE_LIST))
#
# Figure out which OS we are running on.
#
GETOS := python $(NACL_SDK_ROOT)/tools/getos.py
NACL_CONFIG := python $(NACL_SDK_ROOT)/tools/nacl_config.py
FIXDEPS := python $(NACL_SDK_ROOT)/tools/fix_deps.py -c
#GETOS := python $(NACL_SDK_ROOT)/tools/getos.py
#NACL_CONFIG := python $(NACL_SDK_ROOT)/tools/nacl_config.py
#FIXDEPS := python $(NACL_SDK_ROOT)/tools/fix_deps.py -c
GETOS := python tools/getos.py
NACL_CONFIG := python tools/nacl_config.py
FIXDEPS := python tools/fix_deps.py -c
OSNAME := $(shell $(GETOS))

107
crypto777/tools/fix_deps.py

@ -0,0 +1,107 @@
#!/usr/bin/env python
# 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.
"""Fixup GCC-generated dependency files.
Modify GCC generated dependency files so they are more suitable for including
in a GNU Makefile. Without the fixups, deleting or renaming headers can cause
the build to be broken.
See http://mad-scientist.net/make/autodep.html for more details of the problem.
"""
import argparse
import os
import sys
TAG_LINE = '# Updated by fix_deps.py\n'
class Error(Exception):
pass
def ParseLine(line, new_target):
"""Parse one line of a GCC-generated deps file.
Each line contains an optional target and then a list
of space seperated dependencies. Spaces within filenames
are escaped with a backslash.
"""
filenames = []
if new_target and ':' in line:
line = line.split(':', 1)[1]
line = line.strip()
line = line.rstrip('\\')
while True:
# Find the next non-escaped space
line = line.strip()
pos = line.find(' ')
while pos > 0 and line[pos-1] == '\\':
pos = line.find(' ', pos+1)
if pos == -1:
filenames.append(line)
break
filenames.append(line[:pos])
line = line[pos+1:]
return filenames
def FixupDepFile(filename, output_filename=None):
if not os.path.exists(filename):
raise Error('File not found: %s' % filename)
if output_filename is None:
output_filename = filename
outlines = [TAG_LINE]
deps = []
new_target = True
with open(filename) as infile:
for line in infile:
if line == TAG_LINE:
raise Error('Already processed: %s' % filename)
outlines.append(line)
deps += ParseLine(line, new_target)
new_target = line.endswith('\\')
# For every depenency found output a dummy target with no rules
for dep in deps:
outlines.append('%s:\n' % dep)
with open(output_filename, 'w') as outfile:
for line in outlines:
outfile.write(line)
def main(argv):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-o', '--output', help='Output filename (defaults to '
'input name with .deps extension')
parser.add_argument('-c', '--clean', action='store_true',
help='Remove input file after writing output')
parser.add_argument('dep_file')
options = parser.parse_args(argv)
output_filename = options.output
if not output_filename:
output_filename = os.path.splitext(options.dep_file)[0] + '.deps'
FixupDepFile(options.dep_file, output_filename)
if options.clean and options.dep_file != output_filename:
os.remove(options.dep_file)
return 0
if __name__ == '__main__':
try:
sys.exit(main(sys.argv[1:]))
except Error as e:
sys.stderr.write('%s: %s\n' % (os.path.basename(__file__), e))
sys.exit(1)

276
crypto777/tools/nacl_config.py

@ -0,0 +1,276 @@
#!/usr/bin/env python
# Copyright 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.
"""A helper script to print paths of NaCl binaries, includes, libs, etc.
It is similar in behavior to pkg-config or sdl-config.
"""
import argparse
import os
import posixpath
import sys
import getos
if sys.version_info < (2, 7, 0):
sys.stderr.write("python 2.7 or later is required run this script\n")
sys.exit(1)
VALID_ARCHES = ('arm', 'x86_32', 'x86_64', 'i686')
VALID_PNACL_ARCHES = (None, 'pnacl')
ARCH_NAME = {
'arm': 'arm',
'x86_32': 'i686',
'i686': 'i686',
'x86_64': 'x86_64'
}
ARCH_ALT_NAME = {
'arm': 'arm',
'x86_32': 'x86_32',
'i686': 'x86_32',
'x86_64': 'x86_64'
}
ARCH_BASE_NAME = {
'arm': 'arm',
'x86_32': 'x86',
'i686': 'x86',
'x86_64': 'x86'
}
NACL_TOOLCHAINS = ('newlib', 'glibc', 'pnacl', 'bionic', 'clang-newlib')
HOST_TOOLCHAINS = ('linux', 'mac', 'win')
VALID_TOOLCHAINS = list(HOST_TOOLCHAINS) + list(NACL_TOOLCHAINS) + ['host']
# This is not an exhaustive list of tools, just the ones that need to be
# special-cased.
# e.g. For PNaCL cc => pnacl-clang
# For NaCl cc => pnacl-gcc
#
# Most tools will be passed through directly.
# e.g. For PNaCl foo => pnacl-foo
# For NaCl foo => x86_64-nacl-foo.
CLANG_TOOLS = {
'cc': 'clang',
'c++': 'clang++',
'gcc': 'clang',
'g++': 'clang++',
'ld': 'clang++'
}
GCC_TOOLS = {
'cc': 'gcc',
'c++': 'g++',
'gcc': 'gcc',
'g++': 'g++',
'ld': 'g++'
}
class Error(Exception):
pass
def Expect(condition, message):
if not condition:
raise Error(message)
def ExpectToolchain(toolchain, expected_toolchains):
Expect(toolchain in expected_toolchains,
'Expected toolchain to be one of [%s], not %s.' % (
', '.join(expected_toolchains), toolchain))
def ExpectArch(arch, expected_arches):
Expect(arch in expected_arches,
'Expected arch to be one of [%s], not %s.' % (
', '.join(map(str, expected_arches)), arch))
def CheckValidToolchainArch(toolchain, arch, arch_required=False):
if toolchain or arch or arch_required:
ExpectToolchain(toolchain, VALID_TOOLCHAINS)
if toolchain in HOST_TOOLCHAINS:
Expect(arch is None,
'Expected no arch for host toolchain %r. Got %r.' % (
toolchain, arch))
elif toolchain == 'pnacl':
Expect(arch is None or arch == 'pnacl',
'Expected no arch for toolchain %r. Got %r.' % (toolchain, arch))
elif arch_required:
Expect(arch is not None,
'Expected arch to be one of [%s] for toolchain %r.\n'
'Use the -a or --arch flags to specify one.\n' % (
', '.join(VALID_ARCHES), toolchain))
if arch:
if toolchain == 'pnacl':
ExpectArch(arch, VALID_PNACL_ARCHES)
else:
ExpectArch(arch, VALID_ARCHES)
if arch == 'arm':
Expect(toolchain in ['newlib', 'bionic', 'clang-newlib'],
'The arm arch only supports newlib.')
def GetArchName(arch):
return ARCH_NAME.get(arch)
def GetArchAltName(arch):
return ARCH_ALT_NAME.get(arch)
def GetArchBaseName(arch):
return ARCH_BASE_NAME.get(arch)
def CanonicalizeToolchain(toolchain):
if toolchain == 'host':
return getos.GetPlatform()
return toolchain
def GetPosixSDKPath():
sdk_path = getos.GetSDKPath()
if getos.GetPlatform() == 'win':
return sdk_path.replace('\\', '/')
else:
return sdk_path
def GetToolchainDir(toolchain, arch=None):
ExpectToolchain(toolchain, NACL_TOOLCHAINS)
root = GetPosixSDKPath()
platform = getos.GetPlatform()
if toolchain in ('pnacl', 'clang-newlib'):
subdir = '%s_pnacl' % platform
else:
assert arch is not None
subdir = '%s_%s_%s' % (platform, GetArchBaseName(arch), toolchain)
return posixpath.join(root, 'toolchain', subdir)
def GetToolchainArchDir(toolchain, arch):
ExpectToolchain(toolchain, NACL_TOOLCHAINS)
assert arch is not None
toolchain_dir = GetToolchainDir(toolchain, arch)
arch_dir = '%s-nacl' % GetArchName(arch)
return posixpath.join(toolchain_dir, arch_dir)
def GetToolchainBinDir(toolchain, arch=None):
ExpectToolchain(toolchain, NACL_TOOLCHAINS)
return posixpath.join(GetToolchainDir(toolchain, arch), 'bin')
def GetSDKIncludeDirs(toolchain):
root = GetPosixSDKPath()
base_include = posixpath.join(root, 'include')
if toolchain == 'clang-newlib':
toolchain = 'newlib'
return [base_include, posixpath.join(base_include, toolchain)]
def GetSDKLibDir():
return posixpath.join(GetPosixSDKPath(), 'lib')
# Commands
def GetToolPath(toolchain, arch, tool):
if tool == 'gdb':
# Always use the same gdb; it supports multiple toolchains/architectures.
# NOTE: this is always a i686 executable. i686-nacl-gdb is a symlink to
# x86_64-nacl-gdb.
return posixpath.join(GetToolchainBinDir('newlib', 'x86_64'),
'x86_64-nacl-gdb')
if toolchain == 'pnacl':
CheckValidToolchainArch(toolchain, arch)
tool = CLANG_TOOLS.get(tool, tool)
full_tool_name = 'pnacl-%s' % tool
else:
CheckValidToolchainArch(toolchain, arch, arch_required=True)
ExpectArch(arch, VALID_ARCHES)
if toolchain == 'clang-newlib':
tool = CLANG_TOOLS.get(tool, tool)
else:
tool = GCC_TOOLS.get(tool, tool)
full_tool_name = '%s-nacl-%s' % (GetArchName(arch), tool)
return posixpath.join(GetToolchainBinDir(toolchain, arch), full_tool_name)
def GetCFlags(toolchain):
ExpectToolchain(toolchain, VALID_TOOLCHAINS)
return ' '.join('-I%s' % dirname for dirname in GetSDKIncludeDirs(toolchain))
def GetIncludeDirs(toolchain):
ExpectToolchain(toolchain, VALID_TOOLCHAINS)
return ' '.join(GetSDKIncludeDirs(toolchain))
def GetLDFlags():
return '-L%s' % GetSDKLibDir()
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-t', '--toolchain', help='toolchain name. This can also '
'be specified with the NACL_TOOLCHAIN environment '
'variable.')
parser.add_argument('-a', '--arch', help='architecture name. This can also '
'be specified with the NACL_ARCH environment variable.')
group = parser.add_argument_group('Commands')
group.add_argument('--tool', help='get tool path')
group.add_argument('--cflags',
help='output all preprocessor and compiler flags',
action='store_true')
group.add_argument('--libs', '--ldflags', help='output all linker flags',
action='store_true')
group.add_argument('--include-dirs',
help='output include dirs, separated by spaces',
action='store_true')
options = parser.parse_args(args)
# Get toolchain/arch from environment, if not specified on commandline
options.toolchain = options.toolchain or os.getenv('NACL_TOOLCHAIN')
options.arch = options.arch or os.getenv('NACL_ARCH')
options.toolchain = CanonicalizeToolchain(options.toolchain)
CheckValidToolchainArch(options.toolchain, options.arch)
if options.cflags:
print GetCFlags(options.toolchain)
elif options.include_dirs:
print GetIncludeDirs(options.toolchain)
elif options.libs:
print GetLDFlags()
elif options.tool:
print GetToolPath(options.toolchain, options.arch, options.tool)
else:
parser.error('Expected a command. Run with --help for more information.')
return 0
if __name__ == '__main__':
try:
sys.exit(main(sys.argv[1:]))
except Error as e:
sys.stderr.write(str(e) + '\n')
sys.exit(1)

22
iguana/SuperNET.c

@ -91,7 +91,7 @@ int32_t SuperNET_confirmip(struct supernet_info *myinfo,uint32_t ipbits)
return(total);
}
void SuperNET_myipaddr(struct supernet_info *myinfo,struct iguana_info *coin,struct iguana_peer *addr,char *myipaddr,char *remoteaddr)
void SuperNET_checkipaddr(struct supernet_info *myinfo,struct iguana_info *coin,struct iguana_peer *addr,char *myipaddr,char *remoteaddr)
{
uint32_t myipbits = (uint32_t)calc_ipbits(myipaddr);
if ( addr->myipbits == 0 )
@ -773,7 +773,7 @@ char *SuperNET_p2p(struct iguana_info *coin,struct iguana_peer *addr,int32_t *de
if ( 0 && jstr(json,"method") != 0 && strcmp(jstr(json,"method"),"getpeers") != 0 )
printf("GOT >>>>>>>> SUPERNET P2P.(%s) from.%s %s valid.%d:%d\n",jprint(json,0),coin->symbol,addr->ipaddr,addr->validpub,addr->othervalid);
if ( (myipaddr= jstr(json,"yourip")) != 0 )
SuperNET_myipaddr(SuperNET_MYINFO(0),coin,addr,myipaddr,ipaddr);
SuperNET_checkipaddr(SuperNET_MYINFO(0),coin,addr,myipaddr,ipaddr);
jaddstr(json,"fromp2p",coin->symbol);
method = jstr(json,"method");
if ( method != 0 && strcmp(method,"stop") == 0 )
@ -1241,6 +1241,24 @@ STRING_ARG(SuperNET,wif2priv,wif)
return(jprint(retjson,1));
}
ZERO_ARGS(SuperNET,myipaddr)
{
cJSON *retjson = cJSON_CreateObject();
jaddstr(retjson,"result",myinfo->ipaddr);
return(jprint(retjson,1));
}
STRING_ARG(SuperNET,setmyipaddr,ipaddr)
{
cJSON *retjson = cJSON_CreateObject();
if ( is_ipaddr(ipaddr) != 0 )
{
strcpy(myinfo->ipaddr,ipaddr);
jaddstr(retjson,"result",myinfo->ipaddr);
} else jaddstr(retjson,"error","illegal ipaddr");
return(jprint(retjson,1));
}
STRING_ARG(SuperNET,utime2utc,utime)
{
uint32_t utc = 0; cJSON *retjson = cJSON_CreateObject();

19
iguana/SuperNET.h

@ -84,27 +84,11 @@ struct supernet_info
int32_t LBsock,PUBsock,reqsock,subsock,networktimeout,maxdelay;
uint16_t LBport,PUBport,reqport,subport;
struct nn_pollfd pfd[SUPERNET_MAXAGENTS]; //struct relay_info active;
struct supernet_agent agents[SUPERNET_MAXAGENTS]; queue_t acceptQ,acceptableQ;
struct supernet_agent agents[SUPERNET_MAXAGENTS]; queue_t acceptQ;
int32_t numagents,numexchanges;
struct exchange_info *tradingexchanges[SUPERNET_MAXEXCHANGES];
char handle[1024];
};
#define NXT_ASSETID ('N' + ((uint64_t)'X'<<8) + ((uint64_t)'T'<<16)) // 5527630
#define INSTANTDEX_ACCT "4383817337783094122"
union _NXT_tx_num { int64_t amountNQT; int64_t quantityQNT; };
struct NXT_tx
{
bits256 refhash,sighash,fullhash;
uint64_t senderbits,recipientbits,assetidbits,txid,priceNQT,quoteid;
int64_t feeNQT;
union _NXT_tx_num U;
int32_t deadline,type,subtype,verify,number;
uint32_t timestamp;
char comment[4096];
};
uint64_t set_NXTtx(struct supernet_info *myinfo,struct NXT_tx *tx,uint64_t assetidbits,int64_t amount,uint64_t other64bits,int32_t feebits);
cJSON *gen_NXT_tx_json(struct supernet_info *myinfo,char *fullhash,struct NXT_tx *utx,char *reftxid,double myshare);
int32_t calc_raw_NXTtx(struct supernet_info *myinfo,char *fullhash,char *utxbytes,char *sighash,uint64_t assetidbits,int64_t amount,uint64_t other64bits);
/*struct supernet_endpoint
{
@ -183,7 +167,6 @@ double instantdex_aveprice(struct supernet_info *myinfo,struct exchange_quote *s
void SuperNET_setkeys(struct supernet_info *myinfo,void *pass,int32_t passlen,int32_t dosha256);
char *InstantDEX_hexmsg(struct supernet_info *myinfo,void *data,int32_t len,char *remoteaddr);
double instantdex_acceptable(struct supernet_info *myinfo,cJSON *array,char *refstr,char *base,char *rel,double volume);
#endif

72
iguana/exchanges/bitcoin.c

@ -350,6 +350,7 @@ int32_t bitcoin_MofNspendscript(uint8_t p2sh_rmd160[20],uint8_t *script,int32_t
{
if ( (plen= bitcoin_pubkeylen(vp->signers[i].pubkey)) < 0 )
return(-1);
script[n++] = plen;
memcpy(&script[n],vp->signers[i].pubkey,plen);
n += plen;
}
@ -620,7 +621,18 @@ int32_t iguana_calcrmd160(struct iguana_info *coin,struct vin_info *vp,uint8_t *
scriptlen = iguana_scriptgen(coin,&vp->M,&vp->N,vp->coinaddr,script,asmstr,vp->rmd160,vp->type,(const struct vin_info *)vp,vout);
if ( scriptlen != pk_scriptlen || memcmp(script,pk_script,scriptlen) != 0 )
{
printf("iguana_calcrmd160 type.%d error regenerating scriptlen.%d vs %d\n",vp->type,scriptlen,pk_scriptlen);
if ( vp->type != IGUANA_SCRIPT_OPRETURN )
{
int32_t i;
printf("\n--------------------\n");
for (i=0; i<scriptlen; i++)
printf("%02x ",script[i]);
printf("script.%d\n",scriptlen);
for (i=0; i<pk_scriptlen; i++)
printf("%02x ",pk_script[i]);
printf("original script.%d\n",pk_scriptlen);
printf("iguana_calcrmd160 type.%d error regenerating scriptlen.%d vs %d\n\n",vp->type,scriptlen,pk_scriptlen);
}
}
}
return(vp->type);
@ -1340,23 +1352,21 @@ rawtxstr = refstr;
#define FUNCS bitcoin ## _funcs
#define BASERELS bitcoin ## _baserels
static char *BASERELS[][2] = { {"btc","nxt"}, {"btc","btcd"}, {"btc","ltc"}, {"btc","vrc"}, {"btc","doge"} };
static char *BASERELS[][2] = { {"btcd","btc"}, {"nxt","btc"}, {"asset","btc"} };
#include "exchange_supports.h"
double UPDATE(struct exchange_info *exchange,char *base,char *rel,struct exchange_quote *quotes,int32_t maxdepth,double commission,cJSON *argjson,int32_t invert)
{
char url[1024],lrel[16],lbase[16];
strcpy(lrel,rel), strcpy(lbase,base);
tolowercase(lrel), tolowercase(lbase);
sprintf(url,"http://api.quadrigacx.com/v2/order_book?book=%s_%s",lbase,lrel);
return(exchanges777_standardprices(exchange,commission,base,rel,url,quotes,0,0,maxdepth,0,invert));
}
cJSON *SIGNPOST(void **cHandlep,int32_t dotrade,char **retstrp,struct exchange_info *exchange,char *payload,char *path)
double UPDATE(struct exchange_info *exchange,char *base,char *rel,struct exchange_quote *bidasks,int32_t maxdepth,double commission,cJSON *argjson,int32_t invert)
{
if ( retstrp != 0 )
*retstrp = clonestr("{\"error\":\"bitcoin is not yet\"}");
return(cJSON_Parse("{}"));
cJSON *retjson,*bids,*asks; double hbla;
bids = cJSON_CreateArray();
asks = cJSON_CreateArray();
instantdex_acceptablefind(exchange,bids,asks,0,base,rel);
retjson = cJSON_CreateObject();
cJSON_AddItemToObject(retjson,"bids",bids);
cJSON_AddItemToObject(retjson,"asks",asks);
hbla = exchanges777_json_orderbook(exchange,commission,base,rel,bidasks,maxdepth,retjson,0,"bids","asks",0,0,invert);
free_json(retjson);
return(hbla);
}
char *PARSEBALANCE(struct exchange_info *exchange,double *balancep,char *coinstr,cJSON *argjson)
@ -1374,22 +1384,40 @@ uint64_t TRADE(int32_t dotrade,char **retstrp,struct exchange_info *exchange,cha
return(0);
}
char *ORDERSTATUS(struct exchange_info *exchange,uint64_t quoteid,cJSON *argjson)
char *ORDERSTATUS(struct exchange_info *exchange,uint64_t orderid,cJSON *argjson)
{
return(clonestr("{\"error\":\"bitcoin is not yet\"}"));
struct instantdex_accept *ap; cJSON *retjson;
if ( (ap= instantdex_acceptablefind(exchange,0,0,orderid,"*","*")) != 0 )
{
retjson = cJSON_CreateObject();
jadd(retjson,"result",instantdex_acceptjson(ap));
return(jprint(retjson,1));
} else return(clonestr("{\"error\":\"couldnt find orderid\"}"));
}
char *CANCELORDER(struct exchange_info *exchange,uint64_t quoteid,cJSON *argjson)
char *CANCELORDER(struct exchange_info *exchange,uint64_t orderid,cJSON *argjson)
{
return(clonestr("{\"error\":\"bitcoin is not yet\"}"));
struct instantdex_accept *ap; cJSON *retjson;
if ( (ap= instantdex_acceptablefind(exchange,0,0,orderid,"*","*")) != 0 )
{
ap->dead = (uint32_t)time(NULL);
retjson = cJSON_CreateObject();
jaddstr(retjson,"result","killed orderid, but might have pending");
jadd(retjson,"order",instantdex_acceptjson(ap));
return(jprint(retjson,1));
} else return(clonestr("{\"error\":\"couldnt find orderid\"}"));
}
char *OPENORDERS(struct exchange_info *exchange,cJSON *argjson)
{
cJSON *retjson,*array = cJSON_CreateArray();
cJSON *retjson,*bids,*asks;
bids = cJSON_CreateArray();
asks = cJSON_CreateArray();
instantdex_acceptablefind(exchange,bids,asks,0,"*","*");
retjson = cJSON_CreateObject();
instantdex_acceptable(SuperNET_MYINFO(0),array,"","*","*",0);
jadd(retjson,"result",array);
jaddstr(retjson,"result","success");
jadd(retjson,"bids",bids);
jadd(retjson,"asks",asks);
return(jprint(retjson,1));
}

26
iguana/exchanges777.h

@ -50,7 +50,7 @@ struct exchange_info
uint32_t exchangeid,pollgap,lastpoll;
uint64_t lastnonce,exchangebits; double commission;
void *privatedata;
CURL *cHandle; queue_t requestQ,pricesQ,pendingQ[2],tradebotsQ;
CURL *cHandle; queue_t requestQ,pricesQ,pendingQ[2],tradebotsQ,acceptableQ;
};
struct instantdex_msghdr
@ -60,6 +60,23 @@ struct instantdex_msghdr
uint8_t serialized[];
} __attribute__((packed));
#define NXT_ASSETID ('N' + ((uint64_t)'X'<<8) + ((uint64_t)'T'<<16)) // 5527630
#define INSTANTDEX_ACCT "4383817337783094122"
union _NXT_tx_num { int64_t amountNQT; int64_t quantityQNT; };
struct NXT_tx
{
bits256 refhash,sighash,fullhash;
uint64_t senderbits,recipientbits,assetidbits,txid,priceNQT,quoteid;
int64_t feeNQT;
union _NXT_tx_num U;
int32_t deadline,type,subtype,verify,number;
uint32_t timestamp;
char comment[4096];
};
uint64_t set_NXTtx(struct supernet_info *myinfo,struct NXT_tx *tx,uint64_t assetidbits,int64_t amount,uint64_t other64bits,int32_t feebits);
cJSON *gen_NXT_tx_json(struct supernet_info *myinfo,char *fullhash,struct NXT_tx *utx,char *reftxid,double myshare);
int32_t calc_raw_NXTtx(struct supernet_info *myinfo,char *fullhash,char *utxbytes,char *sighash,uint64_t assetidbits,int64_t amount,uint64_t other64bits);
struct exchange_request
{
struct queueitem DL;
@ -71,6 +88,13 @@ struct exchange_request
struct exchange_quote bidasks[];
};
struct instantdex_entry { char base[24],rel[24]; double price,basevolume,pendingvolume; uint32_t expiration,nonce; char myside,acceptdir; };
struct instantdex_accept { struct queueitem DL; uint64_t orderid; uint32_t dead; struct instantdex_entry A; };
struct instantdex_accept *instantdex_acceptablefind(struct exchange_info *exchange,cJSON *bids,cJSON *asks,uint64_t orderid,char *base,char *rel);
cJSON *instantdex_acceptjson(struct instantdex_accept *ap);
struct instantdex_accept *instantdex_acceptable(struct exchange_info *exchange,cJSON *array,char *refstr,char *base,char *rel,char *offerside,int32_t offerdir,double offerprice,double volume);
void *curl_post(void **cHandlep,char *url,char *userpass,char *postfields,char *hdr0,char *hdr1,char *hdr2,char *hdr3);
char *instantdex_sendcmd(struct supernet_info *myinfo,cJSON *argjson,char *cmdstr,char *ipaddr,int32_t hops);
char *exchanges777_Qprices(struct exchange_info *exchange,char *base,char *rel,int32_t maxseconds,int32_t allfields,int32_t depth,cJSON *argjson,int32_t monitor,double commission);

8
iguana/help/header.html

@ -5,7 +5,7 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>SuperNET API></title>
<title>SuperNET API Page></title>
<!-- Bootstrap -->
@ -15,8 +15,8 @@
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<script src="help/html5shiv.min.js"></script>
<script src="help/respond.min.js"></script>
<![endif]-->
<!-- Optional theme -->
@ -30,7 +30,7 @@
<div class="navbar navbar-default" role="navigation">
<div class="container" style="min-width: 90%;">
<div class="navbar-header">
<a class="navbar-brand" href="#">SuperNET API</a>
<a class="navbar-brand" href="index.html">SuperNET 7777 GUI</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">

12
iguana/iguana_chains.c

@ -82,6 +82,18 @@ static struct iguana_chain Chains[] =
},
};
/*
// PUBKEY_ADDRESS + SCRIPT_ADDRESS addrman.h
// PRIVKEY_ADDRESS use wif2priv API on any valid wif
// networkmagic pchMessageStart main.cpp
// genesis block from any blockexplorer, calendar strings can be converted by utime2utc
{
"name":"BitcoinDark","symbol":"BTCD",
"PUBKEY_ADDRESS":60,"SCRIPT_ADDRESS":85,"PRIVKEY_ADDRESS":188,
"networkmagic":"e4c2d8e6","portp2p:14631,"portrpc":14632,"txhastimestamp":1,
"genesis":{"version":1,"timestamp":1403138561,"nBits":"1e0fffff","nonce":8359109,"hash":"0000044966f40703b516c5af180582d53f783bfd319bb045e2dc3e05ea695d46","merkle":"fd1751cc6963d88feca94c0d01da8883852647a37a0a67ce254d62dd8c9d5b2b"}
}*/
bits256 iguana_chaingenesis(int32_t version,uint32_t timestamp,uint32_t bits,uint32_t nonce,bits256 merkle_root)
{
struct iguana_msgblock msg; int32_t len; bits256 hash2; uint8_t serialized[1024]; char hexstr[2049];

1
iguana/iguana_exchanges.c

@ -866,6 +866,7 @@ struct exchange_info *exchange_create(char *exchangestr,cJSON *argjson)
exchange->issue = *Exchange_funcs[i];
iguana_initQ(&exchange->pricesQ,"prices");
iguana_initQ(&exchange->requestQ,"request");
iguana_initQ(&exchange->acceptableQ,"acceptable");
iguana_initQ(&exchange->tradebotsQ,"tradebots");
iguana_initQ(&exchange->pendingQ[0],"pending0");
iguana_initQ(&exchange->pendingQ[1],"pending1");

198
iguana/iguana_instantdex.c

@ -21,15 +21,6 @@
#define INSTANTDEX_DURATION 60
#define INSTANTDEX_OFFERDURATION 3600
#define INSTANTDEX_NXTOFFER 1
#define INSTANTDEX_REQUEST 2
#define INSTANTDEX_PROPOSE 3
#define INSTANTDEX_ACCEPT 4
#define INSTANTDEX_CONFIRM 5
struct instantdex_entry { char base[24],rel[24]; double price,basevolume,pendingvolume; uint32_t expiration,nonce; char myside,acceptdir; };
struct instantdex_accept { struct queueitem DL; uint64_t txid; struct instantdex_entry A; };
cJSON *InstantDEX_argjson(char *reference,char *message,char *othercoinaddr,char *otherNXTaddr,int32_t iter,int32_t val,int32_t val2)
{
cJSON *argjson = cJSON_CreateObject();
@ -98,8 +89,8 @@ char *instantdex_sendcmd(struct supernet_info *myinfo,cJSON *argjson,char *cmdst
memset(msg,0,sizeof(*msg));
instantdexhash = calc_categoryhashes(0,"InstantDEX",0);
category_subscribe(myinfo,instantdexhash,GENESIS_PUBKEY);
if ( ipaddr == 0 || ipaddr[0] == 0 || strncmp(ipaddr,"127.0.0.1",strlen("127.0.0.1")) == 0 )
return(clonestr("{\"error\":\"no ipaddr, need to send your ipaddr for now\"}"));
//if ( ipaddr == 0 || ipaddr[0] == 0 || strncmp(ipaddr,"127.0.0.1",strlen("127.0.0.1")) == 0 )
// return(clonestr("{\"error\":\"no ipaddr, need to send your ipaddr for now\"}"));
jaddstr(argjson,"cmd",cmdstr);
for (i=0; i<sizeof(msg->cmd); i++)
if ( (msg->cmd[i]= cmdstr[i]) == 0 )
@ -214,53 +205,98 @@ double instantdex_aveprice(struct supernet_info *myinfo,struct exchange_quote *s
return(0);
}
int32_t instantdex_bidaskdir(struct instantdex_accept *ap)
{
if ( ap->A.myside == 0 && ap->A.acceptdir > 0 ) // base
return(1);
else if ( ap->A.myside == 1 && ap->A.acceptdir < 0 ) // rel
return(-1);
else return(0);
}
cJSON *instantdex_acceptjson(struct instantdex_accept *ap)
{
int32_t dir;
cJSON *item = cJSON_CreateObject();
jadd64bits(item,"orderid",ap->txid);
if ( ap->A.myside == 0 )
jaddstr(item,"myside",ap->A.base);
else if ( ap->A.myside == 0 )
jaddstr(item,"myside",ap->A.rel);
else jaddstr(item,"myside","neither");
jadd64bits(item,"orderid",ap->orderid);
if ( ap->dead != 0 )
jadd64bits(item,"dead",ap->dead);
if ( (dir= instantdex_bidaskdir(ap)) > 0 )
jaddstr(item,"type","bid");
else if ( dir < 0 )
jaddstr(item,"type","ask");
else
{
jaddstr(item,"type","strange");
jaddnum(item,"acceptdir",ap->A.acceptdir);
jaddnum(item,"myside",ap->A.myside);
}
jaddstr(item,"base",ap->A.base);
jaddstr(item,"rel",ap->A.rel);
jaddnum(item,ap->A.acceptdir > 0 ? "minprice" : "maxprice",ap->A.price);
jaddnum(item,"basevolume",ap->A.basevolume);
jaddnum(item,"price",ap->A.price);
jaddnum(item,"volume",ap->A.basevolume);
jaddnum(item,"pendingvolume",ap->A.pendingvolume);
jaddnum(item,"expiresin",ap->A.expiration - time(NULL));
return(item);
}
double instantdex_acceptable(struct supernet_info *myinfo,cJSON *array,char *refstr,char *base,char *rel,double volume)
struct instantdex_accept *instantdex_acceptablefind(struct exchange_info *exchange,cJSON *bids,cJSON *asks,uint64_t orderid,char *base,char *rel)
{
struct instantdex_accept PAD,*ap,*retap = 0; double price = 0.; uint32_t now;
struct instantdex_accept PAD,*ap,*retap = 0; uint32_t now; cJSON *item; char *type;
now = (uint32_t)time(NULL);
memset(&PAD,0,sizeof(PAD));
queue_enqueue("acceptableQ",&myinfo->acceptableQ,&PAD.DL,0);
while ( (ap= queue_dequeue(&myinfo->acceptableQ,0)) != 0 && ap != &PAD )
queue_enqueue("acceptableQ",&exchange->acceptableQ,&PAD.DL,0);
while ( (ap= queue_dequeue(&exchange->acceptableQ,0)) != 0 && ap != &PAD )
{
if ( volume > 0. && (strcmp(base,"*") == 0 || strcmp(base,ap->A.base) == 0) && (strcmp(rel,"*") == 0 || strcmp(rel,ap->A.rel) == 0) && volume < (ap->A.basevolume - ap->A.pendingvolume) )
if ( now < ap->A.expiration && ap->dead == 0 )
{
if ( ap->A.price > price )
if ( (strcmp(base,"*") == 0 || strcmp(base,ap->A.base) == 0) && (strcmp(rel,"*") == 0 || strcmp(rel,ap->A.rel) == 0) && (orderid == 0 || orderid == ap->orderid) )
{
price = ap->A.price;
retap = ap;
}
}
if ( now < ap->A.expiration )
if ( (item= instantdex_acceptjson(ap)) != 0 )
{
if ( (type= jstr(item,"type")) != 0 )
{
if ( strcmp(type,"bid") == 0 && bids != 0 )
jaddi(bids,item);
else if ( strcmp(type,"ask") != 0 && asks != 0 )
jaddi(asks,item);
}
}
queue_enqueue("acceptableQ",&exchange->acceptableQ,&ap->DL,0);
} else free(ap);
}
return(retap);
}
struct instantdex_accept *instantdex_acceptable(struct exchange_info *exchange,cJSON *array,char *refstr,char *base,char *rel,char *offerside,int32_t offerdir,double offerprice,double volume)
{
struct instantdex_accept PAD,*ap,*retap = 0; double bestprice = 0.; uint32_t now;
now = (uint32_t)time(NULL);
memset(&PAD,0,sizeof(PAD));
queue_enqueue("acceptableQ",&exchange->acceptableQ,&PAD.DL,0);
while ( (ap= queue_dequeue(&exchange->acceptableQ,0)) != 0 && ap != &PAD )
{
if ( now < ap->A.expiration && ap->dead == 0 )
{
if ( volume > 0. && (strcmp(base,"*") == 0 || strcmp(base,ap->A.base) == 0) && (strcmp(rel,"*") == 0 || strcmp(rel,ap->A.rel) == 0) && volume <= (ap->A.basevolume - ap->A.pendingvolume) && offerdir*instantdex_bidaskdir(ap) < 0 )
{
if ( offerdir == 0 || offerprice == 0. || ((offerdir > 0 && ap->A.price > offerprice) || (offerdir < 0 && ap->A.price < offerprice)) )
{
if ( (offerdir < 0 && ap->A.price < bestprice) || (offerdir > 0 && ap->A.price > bestprice) )
{
bestprice = ap->A.price;
retap = ap;
}
}
}
if ( array != 0 )
jaddi(array,instantdex_acceptjson(ap));
queue_enqueue("acceptableQ",&myinfo->acceptableQ,&ap->DL,0);
}
}
if ( retap != 0 )
{
retap->A.pendingvolume -= volume;
price = retap->A.price;
queue_enqueue("acceptableQ",&exchange->acceptableQ,&ap->DL,0);
} else free(ap);
}
return(price);
return(retap);
}
/*
@ -476,37 +512,45 @@ char *InstantDEX_hexmsg(struct supernet_info *myinfo,void *ptr,int32_t len,char
return(retstr);
}
char *instantdex_queueaccept(struct supernet_info *myinfo,char *base,char *rel,double price,double basevolume,int32_t acceptdir,char *myside,int32_t duration)
char *instantdex_queueaccept(struct exchange_info *exchange,char *base,char *rel,double price,double basevolume,int32_t acceptdir,char *myside,int32_t duration)
{
struct instantdex_accept A; bits256 hash;
memset(&A,0,sizeof(A));
OS_randombytes((uint8_t *)&A.A.nonce,sizeof(A.A.nonce));
safecopy(A.A.base,base,sizeof(A.A.base));
safecopy(A.A.rel,rel,sizeof(A.A.rel));
if ( strcmp(myside,base) == 0 )
A.A.myside = 0;
else if ( strcmp(myside,rel) == 0 )
A.A.myside = 1;
else A.A.myside = -1;
A.A.acceptdir = acceptdir;
A.A.price = price, A.A.basevolume = basevolume;
A.A.expiration = (uint32_t)time(NULL) + duration;
vcalc_sha256(0,hash.bytes,(void *)&A.A,sizeof(A.A));
A.txid = hash.txid;
queue_enqueue("acceptableQ",&myinfo->acceptableQ,&A.DL,0);
return(clonestr("{\"result\":\"added acceptable\"}"));
if ( exchange != 0 )
{
memset(&A,0,sizeof(A));
OS_randombytes((uint8_t *)&A.A.nonce,sizeof(A.A.nonce));
safecopy(A.A.base,base,sizeof(A.A.base));
safecopy(A.A.rel,rel,sizeof(A.A.rel));
if ( strcmp(myside,base) == 0 )
A.A.myside = 0;
else if ( strcmp(myside,rel) == 0 )
A.A.myside = 1;
else A.A.myside = -1;
A.A.acceptdir = acceptdir;
A.A.price = price, A.A.basevolume = basevolume;
A.A.expiration = (uint32_t)time(NULL) + duration;
vcalc_sha256(0,hash.bytes,(void *)&A.A,sizeof(A.A));
A.orderid = hash.txid;
queue_enqueue("acceptableQ",&exchange->acceptableQ,&A.DL,0);
return(clonestr("{\"result\":\"added acceptable\"}"));
}
else return(clonestr("{\"error\":\"invalid exchange\"}"));
}
#include "../includes/iguana_apidefs.h"
TWO_STRINGS_AND_TWO_DOUBLES(InstantDEX,maxaccept,base,rel,maxprice,basevolume)
{
return(instantdex_queueaccept(myinfo,base,rel,maxprice,basevolume,-1,rel,INSTANTDEX_OFFERDURATION));
if ( remoteaddr == 0 )
return(instantdex_queueaccept(exchanges777_find("bitcoin"),base,rel,maxprice,basevolume,-1,rel,INSTANTDEX_OFFERDURATION));
else return(clonestr("{\"error\":\"InstantDEX API request only local usage!\"}"));
}
TWO_STRINGS_AND_TWO_DOUBLES(InstantDEX,minaccept,base,rel,minprice,basevolume)
{
return(instantdex_queueaccept(myinfo,base,rel,minprice,basevolume,1,base,INSTANTDEX_OFFERDURATION));
if ( remoteaddr == 0 )
return(instantdex_queueaccept(exchanges777_find("bitcoin"),base,rel,minprice,basevolume,1,base,INSTANTDEX_OFFERDURATION));
else return(clonestr("{\"error\":\"InstantDEX API request only local usage!\"}"));
}
TWO_STRINGS_AND_TWO_DOUBLES(InstantDEX,BTCoffer,othercoin,otherassetid,maxprice,othervolume)
@ -574,49 +618,5 @@ STRING_AND_TWO_DOUBLES(InstantDEX,NXToffer,assetid,minprice,basevolume)
} else return(clonestr("{\"error\":\"InstantDEX API request only local usage!\"}"));
}
/*THREE_STRINGS_AND_DOUBLE(InstantDEX,request,reference,base,rel,volume) // initiator
{
int32_t hops = INSTANTDEX_HOPS; cJSON *argjson;
if ( remoteaddr == 0 )
{
argjson = cJSON_CreateObject();
jaddstr(argjson,"refstr",reference);
jaddstr(argjson,"base",base);
jaddstr(argjson,"rel",rel);
jaddnum(argjson,"volume",volume);
return(instantdex_sendcmd(myinfo,argjson,"request",myinfo->ipaddr,hops));
} else return(clonestr("{\"error\":\"InstantDEX API request only local usage!\"}"));
}
TWOSTRINGS_AND_TWOHASHES_AND_TWOINTS(InstantDEX,proposal,reference,message,basetxid,reltxid,duration,flags) // responder
{
int32_t hops = INSTANTDEX_HOPS; cJSON *argjson; char str[65],str2[65];
if ( remoteaddr == 0 )
{
argjson = InstantDEX_argjson(reference,message,bits256_str(str,basetxid),bits256_str(str2,basetxid),INSTANTDEX_PROPOSE,duration,flags);
return(instantdex_sendcmd(myinfo,argjson,"proposal",myinfo->ipaddr,hops));
} else return(clonestr("{\"error\":\"InstantDEX API proposal only local usage!\"}"));
}
/*TWOSTRINGS_AND_TWOHASHES_AND_TWOINTS(InstantDEX,accept,reference,message,basetxid,reltxid,duration,flags)
{
int32_t hops = INSTANTDEX_HOPS; cJSON *argjson;
if ( remoteaddr == 0 )
{
argjson = InstantDEX_argjson(reference,message,basetxid,reltxid,INSTANTDEX_ACCEPT,duration,flags);
return(instantdex_sendcmd(myinfo,argjson,"accept",myinfo->ipaddr,hops));
} else return(clonestr("{\"error\":\"InstantDEX API accept only local usage!\"}"));
}
TWOSTRINGS_AND_TWOHASHES_AND_TWOINTS(InstantDEX,confirm,reference,message,basetxid,reltxid,baseheight,relheight)
{
int32_t hops = INSTANTDEX_HOPS; cJSON *argjson;
if ( remoteaddr == 0 )
{
argjson = InstantDEX_argjson(reference,message,basetxid,reltxid,INSTANTDEX_CONFIRM,baseheight,relheight);
return(instantdex_sendcmd(myinfo,argjson,"confirm",myinfo->ipaddr,hops));
} else return(clonestr("{\"error\":\"InstantDEX API confirm only local usage!\"}"));
}*/
#include "../includes/iguana_apiundefs.h"

3
iguana/iguana_rpc.c

@ -721,8 +721,9 @@ char *SuperNET_rpcparse(struct supernet_info *myinfo,char *retbuf,int32_t bufsiz
//printf("url.(%s) method.(%s) helpfname.(%s)\n",&url[i],urlmethod,helpfname);
if ( strcmp(&url[i],"/") == 0 && strcmp(urlmethod,"GET") == 0 )
{
static int counter;
*jsonflagp = 1;
if ( (filestr= OS_filestr(&filesize,"index7778.html")) == 0 )
if ( counter++ == 0 || (filestr= OS_filestr(&filesize,"index7778.html")) == 0 )
{
if ( (filestr= SuperNET_htmlstr("index7778.html",retbuf,bufsize,0)) != 0 )
printf("created index7778.html size %ld\n",strlen(filestr));

4
iguana/main.c

@ -351,10 +351,10 @@ void iguana_main(void *arg)
#ifdef __APPLE__
sleep(1);
char *str;
strcpy(MYINFO.rpcsymbol,"BTC");
strcpy(MYINFO.rpcsymbol,"BTCD");
iguana_launchcoin(MYINFO.rpcsymbol,cJSON_Parse("{}"));
if ( 0 && (str= SuperNET_JSON(&MYINFO,cJSON_Parse("{\"wallet\":\"password\",\"agent\":\"iguana\",\"method\":\"addcoin\",\"services\":128,\"maxpeers\":3,\"newcoin\":\"BTC\",\"active\":0}"),0)) != 0 )
if ( 0 && (str= SuperNET_JSON(&MYINFO,cJSON_Parse("{\"wallet\":\"password\",\"agent\":\"iguana\",\"method\":\"addcoin\",\"services\":128,\"maxpeers\":3,\"newcoin\":\"BTCD\",\"active\":0}"),0)) != 0 )
{
printf("got.(%s)\n",str);
free(str);

7
iguana/swaps/iguana_BTCswap.c

@ -24,6 +24,13 @@
// confirm:
// NXT node verifies bitcoin txbytes has proper payment and cashes in with onetimepubkey
// BTC* node approves phased tx with onetimepubkey
/*if ( retap != 0 )
{
retap->A.pendingvolume -= volume;
price = retap->A.price;
}
struct instantdex_accept *instantdex_acceptable(struct supernet_info *myinfo,cJSON *array,char *refstr,char *base,char *rel,char *offerside,int32_t offerdir,double offerprice,double volume)
*/
char *instantdex_BTCswap(struct supernet_info *myinfo,char *cmdstr,struct instantdex_msghdr *msg,cJSON *argjson,char *remoteaddr,uint64_t signerbits,uint8_t *data,int32_t datalen) // receiving side
{

9
iguana/tools/common.mk

@ -32,9 +32,12 @@ TOP_MAKE := $(word 1,$(MAKEFILE_LIST))
#
# Figure out which OS we are running on.
#
GETOS := python $(NACL_SDK_ROOT)/tools/getos.py
NACL_CONFIG := python $(NACL_SDK_ROOT)/tools/nacl_config.py
FIXDEPS := python $(NACL_SDK_ROOT)/tools/fix_deps.py -c
#GETOS := python $(NACL_SDK_ROOT)/tools/getos.py
#NACL_CONFIG := python $(NACL_SDK_ROOT)/tools/nacl_config.py
#FIXDEPS := python $(NACL_SDK_ROOT)/tools/fix_deps.py -c
GETOS := python tools/getos.py
NACL_CONFIG := python tools/nacl_config.py
FIXDEPS := python tools/fix_deps.py -c
OSNAME := $(shell $(GETOS))

107
iguana/tools/fix_deps.py

@ -0,0 +1,107 @@
#!/usr/bin/env python
# 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.
"""Fixup GCC-generated dependency files.
Modify GCC generated dependency files so they are more suitable for including
in a GNU Makefile. Without the fixups, deleting or renaming headers can cause
the build to be broken.
See http://mad-scientist.net/make/autodep.html for more details of the problem.
"""
import argparse
import os
import sys
TAG_LINE = '# Updated by fix_deps.py\n'
class Error(Exception):
pass
def ParseLine(line, new_target):
"""Parse one line of a GCC-generated deps file.
Each line contains an optional target and then a list
of space seperated dependencies. Spaces within filenames
are escaped with a backslash.
"""
filenames = []
if new_target and ':' in line:
line = line.split(':', 1)[1]
line = line.strip()
line = line.rstrip('\\')
while True:
# Find the next non-escaped space
line = line.strip()
pos = line.find(' ')
while pos > 0 and line[pos-1] == '\\':
pos = line.find(' ', pos+1)
if pos == -1:
filenames.append(line)
break
filenames.append(line[:pos])
line = line[pos+1:]
return filenames
def FixupDepFile(filename, output_filename=None):
if not os.path.exists(filename):
raise Error('File not found: %s' % filename)
if output_filename is None:
output_filename = filename
outlines = [TAG_LINE]
deps = []
new_target = True
with open(filename) as infile:
for line in infile:
if line == TAG_LINE:
raise Error('Already processed: %s' % filename)
outlines.append(line)
deps += ParseLine(line, new_target)
new_target = line.endswith('\\')
# For every depenency found output a dummy target with no rules
for dep in deps:
outlines.append('%s:\n' % dep)
with open(output_filename, 'w') as outfile:
for line in outlines:
outfile.write(line)
def main(argv):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-o', '--output', help='Output filename (defaults to '
'input name with .deps extension')
parser.add_argument('-c', '--clean', action='store_true',
help='Remove input file after writing output')
parser.add_argument('dep_file')
options = parser.parse_args(argv)
output_filename = options.output
if not output_filename:
output_filename = os.path.splitext(options.dep_file)[0] + '.deps'
FixupDepFile(options.dep_file, output_filename)
if options.clean and options.dep_file != output_filename:
os.remove(options.dep_file)
return 0
if __name__ == '__main__':
try:
sys.exit(main(sys.argv[1:]))
except Error as e:
sys.stderr.write('%s: %s\n' % (os.path.basename(__file__), e))
sys.exit(1)

275
iguana/tools/getos.py

@ -0,0 +1,275 @@
#!/usr/bin/env python
# Copyright (c) 2012 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.
"""Determine OS and various other system properties.
Determine the name of the platform used and other system properties such as
the location of Chrome. This is used, for example, to determine the correct
Toolchain to invoke.
"""
import argparse
import os
import re
import subprocess
import sys
import oshelpers
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
CHROME_DEFAULT_PATH = {
'win': r'c:\Program Files (x86)\Google\Chrome\Application\chrome.exe',
'mac': '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'linux': '/usr/bin/google-chrome',
}
if sys.version_info < (2, 7, 0):
sys.stderr.write("python 2.7 or later is required run this script\n")
sys.exit(1)
class Error(Exception):
pass
def GetSDKPath():
return os.getenv('NACL_SDK_ROOT', os.path.dirname(SCRIPT_DIR))
def GetPlatform():
if sys.platform.startswith('cygwin') or sys.platform.startswith('win'):
return 'win'
elif sys.platform.startswith('darwin'):
return 'mac'
elif sys.platform.startswith('linux'):
return 'linux'
else:
raise Error("Unknown platform: %s" % sys.platform)
def UseWin64():
arch32 = os.environ.get('PROCESSOR_ARCHITECTURE')
arch64 = os.environ.get('PROCESSOR_ARCHITEW6432')
if arch32 == 'AMD64' or arch64 == 'AMD64':
return True
return False
def GetSDKVersion():
root = GetSDKPath()
readme = os.path.join(root, "README")
if not os.path.exists(readme):
raise Error("README not found in SDK root: %s" % root)
version = None
revision = None
commit_position = None
for line in open(readme):
if ':' in line:
name, value = line.split(':', 1)
if name == "Version":
version = value.strip()
if name == "Chrome Revision":
revision = value.strip()
if name == "Chrome Commit Position":
commit_position = value.strip()
if revision is None or version is None or commit_position is None:
raise Error("error parsing SDK README: %s" % readme)
try:
version = int(version)
revision = int(revision)
except ValueError:
raise Error("error parsing SDK README: %s" % readme)
return (version, revision, commit_position)
def GetSystemArch(platform):
if platform == 'win':
if UseWin64():
return 'x86_64'
return 'x86_32'
if platform in ['mac', 'linux']:
try:
pobj = subprocess.Popen(['uname', '-m'], stdout= subprocess.PIPE)
arch = pobj.communicate()[0]
arch = arch.split()[0]
if arch.startswith('arm'):
arch = 'arm'
except Exception:
arch = None
return arch
def GetChromePath(platform):
# If CHROME_PATH is defined and exists, use that.
chrome_path = os.environ.get('CHROME_PATH')
if chrome_path:
if not os.path.exists(chrome_path):
raise Error('Invalid CHROME_PATH: %s' % chrome_path)
return os.path.realpath(chrome_path)
# Otherwise look in the PATH environment variable.
basename = os.path.basename(CHROME_DEFAULT_PATH[platform])
chrome_path = oshelpers.FindExeInPath(basename)
if chrome_path:
return os.path.realpath(chrome_path)
# Finally, try the default paths to Chrome.
chrome_path = CHROME_DEFAULT_PATH[platform]
if os.path.exists(chrome_path):
return os.path.realpath(chrome_path)
raise Error('CHROME_PATH is undefined, and %s not found in PATH, nor %s.' % (
basename, chrome_path))
def GetNaClArch(platform):
if platform == 'win':
# On windows the nacl arch always matches to system arch
return GetSystemArch(platform)
elif platform == 'mac':
# On Mac the nacl arch is currently always 32-bit.
return 'x86_32'
# On linux the nacl arch matches to chrome arch, so we inspect the chrome
# binary using objdump
chrome_path = GetChromePath(platform)
# If CHROME_PATH is set to point to google-chrome or google-chrome
# was found in the PATH and we are running on UNIX then google-chrome
# is a bash script that points to 'chrome' in the same folder.
#
# When running beta or dev branch, the name is google-chrome-{beta,dev}.
if os.path.basename(chrome_path).startswith('google-chrome'):
chrome_path = os.path.join(os.path.dirname(chrome_path), 'chrome')
if not os.path.exists(chrome_path):
raise Error("File %s does not exist." % chrome_path)
if not os.access(chrome_path, os.X_OK):
raise Error("File %s is not executable" % chrome_path)
try:
pobj = subprocess.Popen(['objdump', '-f', chrome_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, stderr = pobj.communicate()
# error out here if objdump failed
if pobj.returncode:
raise Error(output + stderr.strip())
except OSError as e:
# This will happen if objdump is not installed
raise Error("Error running objdump: %s" % e)
pattern = r'(file format) ([a-zA-Z0-9_\-]+)'
match = re.search(pattern, output)
if not match:
raise Error("Error running objdump on: %s" % chrome_path)
arch = match.group(2)
if 'arm' in arch:
return 'arm'
if '64' in arch:
return 'x86_64'
return 'x86_32'
def ParseVersion(version):
"""Parses a version number of the form '<major>.<position>'.
<position> is the Cr-Commit-Position number.
"""
if '.' in version:
version = version.split('.')
else:
version = (version, '0')
try:
return tuple(int(x) for x in version)
except ValueError:
raise Error('error parsing SDK version: %s' % version)
def CheckVersion(required_version):
"""Determines whether the current SDK version meets the required version.
Args:
required_version: (major, position) pair, where position is the
Cr-Commit-Position number.
Raises:
Error: The SDK version is older than required_version.
"""
version = GetSDKVersion()[:2]
if version < required_version:
raise Error("SDK version too old (current: %d.%d, required: %d.%d)"
% (version[0], version[1], required_version[0], required_version[1]))
def main(args):
parser = argparse.ArgumentParser()
parser.add_argument('--arch', action='store_true',
help='Print architecture of current machine (x86_32, x86_64 or arm).')
parser.add_argument('--chrome', action='store_true',
help='Print the path chrome (by first looking in $CHROME_PATH and '
'then $PATH).')
parser.add_argument('--nacl-arch', action='store_true',
help='Print architecture used by NaCl on the current machine.')
parser.add_argument('--sdk-version', action='store_true',
help='Print major version of the NaCl SDK.')
parser.add_argument('--sdk-revision', action='store_true',
help='Print revision number of the NaCl SDK.')
parser.add_argument('--sdk-commit-position', action='store_true',
help='Print commit position of the NaCl SDK.')
parser.add_argument('--check-version',
metavar='MAJOR.POSITION',
help='Check that the SDK version is at least as great as the '
'version passed in. MAJOR is the major version number and POSITION '
'is the Cr-Commit-Position number.')
if len(args) > 1:
parser.error('Only one option can be specified at a time.')
options = parser.parse_args(args)
platform = GetPlatform()
if options.arch:
out = GetSystemArch(platform)
elif options.nacl_arch:
out = GetNaClArch(platform)
elif options.chrome:
out = GetChromePath(platform)
elif options.sdk_version:
out = GetSDKVersion()[0]
elif options.sdk_revision:
out = GetSDKVersion()[1]
elif options.sdk_commit_position:
out = GetSDKVersion()[2]
elif options.check_version:
required_version = ParseVersion(options.check_version)
CheckVersion(required_version)
out = None
else:
out = platform
if out:
print out
return 0
if __name__ == '__main__':
try:
sys.exit(main(sys.argv[1:]))
except Error as e:
sys.stderr.write(str(e) + '\n')
sys.exit(1)

276
iguana/tools/nacl_config.py

@ -0,0 +1,276 @@
#!/usr/bin/env python
# Copyright 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.
"""A helper script to print paths of NaCl binaries, includes, libs, etc.
It is similar in behavior to pkg-config or sdl-config.
"""
import argparse
import os
import posixpath
import sys
import getos
if sys.version_info < (2, 7, 0):
sys.stderr.write("python 2.7 or later is required run this script\n")
sys.exit(1)
VALID_ARCHES = ('arm', 'x86_32', 'x86_64', 'i686')
VALID_PNACL_ARCHES = (None, 'pnacl')
ARCH_NAME = {
'arm': 'arm',
'x86_32': 'i686',
'i686': 'i686',
'x86_64': 'x86_64'
}
ARCH_ALT_NAME = {
'arm': 'arm',
'x86_32': 'x86_32',
'i686': 'x86_32',
'x86_64': 'x86_64'
}
ARCH_BASE_NAME = {
'arm': 'arm',
'x86_32': 'x86',
'i686': 'x86',
'x86_64': 'x86'
}
NACL_TOOLCHAINS = ('newlib', 'glibc', 'pnacl', 'bionic', 'clang-newlib')
HOST_TOOLCHAINS = ('linux', 'mac', 'win')
VALID_TOOLCHAINS = list(HOST_TOOLCHAINS) + list(NACL_TOOLCHAINS) + ['host']
# This is not an exhaustive list of tools, just the ones that need to be
# special-cased.
# e.g. For PNaCL cc => pnacl-clang
# For NaCl cc => pnacl-gcc
#
# Most tools will be passed through directly.
# e.g. For PNaCl foo => pnacl-foo
# For NaCl foo => x86_64-nacl-foo.
CLANG_TOOLS = {
'cc': 'clang',
'c++': 'clang++',
'gcc': 'clang',
'g++': 'clang++',
'ld': 'clang++'
}
GCC_TOOLS = {
'cc': 'gcc',
'c++': 'g++',
'gcc': 'gcc',
'g++': 'g++',
'ld': 'g++'
}
class Error(Exception):
pass
def Expect(condition, message):
if not condition:
raise Error(message)
def ExpectToolchain(toolchain, expected_toolchains):
Expect(toolchain in expected_toolchains,
'Expected toolchain to be one of [%s], not %s.' % (
', '.join(expected_toolchains), toolchain))
def ExpectArch(arch, expected_arches):
Expect(arch in expected_arches,
'Expected arch to be one of [%s], not %s.' % (
', '.join(map(str, expected_arches)), arch))
def CheckValidToolchainArch(toolchain, arch, arch_required=False):
if toolchain or arch or arch_required:
ExpectToolchain(toolchain, VALID_TOOLCHAINS)
if toolchain in HOST_TOOLCHAINS:
Expect(arch is None,
'Expected no arch for host toolchain %r. Got %r.' % (
toolchain, arch))
elif toolchain == 'pnacl':
Expect(arch is None or arch == 'pnacl',
'Expected no arch for toolchain %r. Got %r.' % (toolchain, arch))
elif arch_required:
Expect(arch is not None,
'Expected arch to be one of [%s] for toolchain %r.\n'
'Use the -a or --arch flags to specify one.\n' % (
', '.join(VALID_ARCHES), toolchain))
if arch:
if toolchain == 'pnacl':
ExpectArch(arch, VALID_PNACL_ARCHES)
else:
ExpectArch(arch, VALID_ARCHES)
if arch == 'arm':
Expect(toolchain in ['newlib', 'bionic', 'clang-newlib'],
'The arm arch only supports newlib.')
def GetArchName(arch):
return ARCH_NAME.get(arch)
def GetArchAltName(arch):
return ARCH_ALT_NAME.get(arch)
def GetArchBaseName(arch):
return ARCH_BASE_NAME.get(arch)
def CanonicalizeToolchain(toolchain):
if toolchain == 'host':
return getos.GetPlatform()
return toolchain
def GetPosixSDKPath():
sdk_path = getos.GetSDKPath()
if getos.GetPlatform() == 'win':
return sdk_path.replace('\\', '/')
else:
return sdk_path
def GetToolchainDir(toolchain, arch=None):
ExpectToolchain(toolchain, NACL_TOOLCHAINS)
root = GetPosixSDKPath()
platform = getos.GetPlatform()
if toolchain in ('pnacl', 'clang-newlib'):
subdir = '%s_pnacl' % platform
else:
assert arch is not None
subdir = '%s_%s_%s' % (platform, GetArchBaseName(arch), toolchain)
return posixpath.join(root, 'toolchain', subdir)
def GetToolchainArchDir(toolchain, arch):
ExpectToolchain(toolchain, NACL_TOOLCHAINS)
assert arch is not None
toolchain_dir = GetToolchainDir(toolchain, arch)
arch_dir = '%s-nacl' % GetArchName(arch)
return posixpath.join(toolchain_dir, arch_dir)
def GetToolchainBinDir(toolchain, arch=None):
ExpectToolchain(toolchain, NACL_TOOLCHAINS)
return posixpath.join(GetToolchainDir(toolchain, arch), 'bin')
def GetSDKIncludeDirs(toolchain):
root = GetPosixSDKPath()
base_include = posixpath.join(root, 'include')
if toolchain == 'clang-newlib':
toolchain = 'newlib'
return [base_include, posixpath.join(base_include, toolchain)]
def GetSDKLibDir():
return posixpath.join(GetPosixSDKPath(), 'lib')
# Commands
def GetToolPath(toolchain, arch, tool):
if tool == 'gdb':
# Always use the same gdb; it supports multiple toolchains/architectures.
# NOTE: this is always a i686 executable. i686-nacl-gdb is a symlink to
# x86_64-nacl-gdb.
return posixpath.join(GetToolchainBinDir('newlib', 'x86_64'),
'x86_64-nacl-gdb')
if toolchain == 'pnacl':
CheckValidToolchainArch(toolchain, arch)
tool = CLANG_TOOLS.get(tool, tool)
full_tool_name = 'pnacl-%s' % tool
else:
CheckValidToolchainArch(toolchain, arch, arch_required=True)
ExpectArch(arch, VALID_ARCHES)
if toolchain == 'clang-newlib':
tool = CLANG_TOOLS.get(tool, tool)
else:
tool = GCC_TOOLS.get(tool, tool)
full_tool_name = '%s-nacl-%s' % (GetArchName(arch), tool)
return posixpath.join(GetToolchainBinDir(toolchain, arch), full_tool_name)
def GetCFlags(toolchain):
ExpectToolchain(toolchain, VALID_TOOLCHAINS)
return ' '.join('-I%s' % dirname for dirname in GetSDKIncludeDirs(toolchain))
def GetIncludeDirs(toolchain):
ExpectToolchain(toolchain, VALID_TOOLCHAINS)
return ' '.join(GetSDKIncludeDirs(toolchain))
def GetLDFlags():
return '-L%s' % GetSDKLibDir()
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-t', '--toolchain', help='toolchain name. This can also '
'be specified with the NACL_TOOLCHAIN environment '
'variable.')
parser.add_argument('-a', '--arch', help='architecture name. This can also '
'be specified with the NACL_ARCH environment variable.')
group = parser.add_argument_group('Commands')
group.add_argument('--tool', help='get tool path')
group.add_argument('--cflags',
help='output all preprocessor and compiler flags',
action='store_true')
group.add_argument('--libs', '--ldflags', help='output all linker flags',
action='store_true')
group.add_argument('--include-dirs',
help='output include dirs, separated by spaces',
action='store_true')
options = parser.parse_args(args)
# Get toolchain/arch from environment, if not specified on commandline
options.toolchain = options.toolchain or os.getenv('NACL_TOOLCHAIN')
options.arch = options.arch or os.getenv('NACL_ARCH')
options.toolchain = CanonicalizeToolchain(options.toolchain)
CheckValidToolchainArch(options.toolchain, options.arch)
if options.cflags:
print GetCFlags(options.toolchain)
elif options.include_dirs:
print GetIncludeDirs(options.toolchain)
elif options.libs:
print GetLDFlags()
elif options.tool:
print GetToolPath(options.toolchain, options.arch, options.tool)
else:
parser.error('Expected a command. Run with --help for more information.')
return 0
if __name__ == '__main__':
try:
sys.exit(main(sys.argv[1:]))
except Error as e:
sys.stderr.write(str(e) + '\n')
sys.exit(1)

6
includes/iguana_apideclares.h

@ -14,6 +14,8 @@
******************************************************************************/
STRING_ARG(SuperNET,bitcoinrpc,setcoin);
ZERO_ARGS(SuperNET,myipaddr);
STRING_ARG(SuperNET,setmyipaddr,ipaddr);
HASH_AND_STRING(ramchain,verifytx,txid,txbytes);
INT_ARG(ramchain,getblockhash,height);
@ -44,11 +46,11 @@ STRING_AND_INT(InstantDEX,pollgap,exchange,pollgap);
ZERO_ARGS(InstantDEX,allexchanges);
STRING_ARG(InstantDEX,allpairs,exchange);
TWO_STRINGS_AND_TWO_DOUBLES(InstantDEX,minaccept,base,rel,minprice,basevolume);
TWO_STRINGS_AND_TWO_DOUBLES(InstantDEX,maxaccept,base,rel,maxprice,basevolume);
STRING_AND_TWO_DOUBLES(InstantDEX,ALToffer,basecoin,minprice,basevolume);
STRING_AND_TWO_DOUBLES(InstantDEX,NXToffer,assetid,minprice,basevolume);
TWO_STRINGS_AND_TWO_DOUBLES(InstantDEX,BTCoffer,othercoin,otherassetid,maxprice,othervolume);
TWO_STRINGS_AND_TWO_DOUBLES(InstantDEX,minaccept,base,rel,minprice,basevolume);
TWO_STRINGS_AND_TWO_DOUBLES(InstantDEX,maxaccept,base,rel,maxprice,basevolume);
//TWOSTRINGS_AND_TWOHASHES_AND_TWOINTS(InstantDEX,proposal,reference,message,basetxid,reltxid,duration,flags);
//TWOSTRINGS_AND_TWOHASHES_AND_TWOINTS(InstantDEX,accept,reference,message,basetxid,reltxid,duration,flags);

21
tools/common.mk

@ -1,4 +1,4 @@
# Copyrigh t (c) 2012 The Chromium Authors. All rights reserved.
# Copyright (c) 2012 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.
@ -32,9 +32,12 @@ TOP_MAKE := $(word 1,$(MAKEFILE_LIST))
#
# Figure out which OS we are running on.
#
GETOS := python $(NACL_SDK_ROOT)/tools/getos.py
NACL_CONFIG := python $(NACL_SDK_ROOT)/tools/nacl_config.py
FIXDEPS := python $(NACL_SDK_ROOT)/tools/fix_deps.py -c
#GETOS := python $(NACL_SDK_ROOT)/tools/getos.py
#NACL_CONFIG := python $(NACL_SDK_ROOT)/tools/nacl_config.py
#FIXDEPS := python $(NACL_SDK_ROOT)/tools/fix_deps.py -c
GETOS := python tools/getos.py
NACL_CONFIG := python tools/nacl_config.py
FIXDEPS := python tools/fix_deps.py -c
OSNAME := $(shell $(GETOS))
@ -203,7 +206,7 @@ endif
#
# Compute path to requested NaCl Toolchain
#
TC_PATH := $(abspath $(NACL_SDK_ROOT)/../toolchain)
TC_PATH := $(abspath $(NACL_SDK_ROOT)/toolchain)
#
@ -260,8 +263,6 @@ clean:
$(RM) -f $(TARGET).nmf
$(RM) -rf $(OUTDIR)
$(RM) -rf user-data-dir
mkdir pnacl; mkdir pnacl/Release
cp Release/* nacl_io.stamp pnacl/Release;
#
@ -294,7 +295,6 @@ ifeq (,$(2))
else
+$(MAKE) -C $(2) STAMPDIR=$(abspath $(STAMPDIR)) $(abspath $(STAMPDIR)/$(1).stamp) $(3)
endif
cp pnacl/Release/*.pexe pnacl/Release/*.bc pnacl/Release/SuperNET_API.nmf Release
all: rebuild_$(1)
$(STAMPDIR)/$(1).stamp: rebuild_$(1)
@ -443,8 +443,7 @@ endif
# Variables for running examples with Chrome.
#
RUN_PY := python $(NACL_SDK_ROOT)/tools/run.py
#HTTPD_PY := python $(NACL_SDK_ROOT)/tools/httpd.py
HTTPD_PY := python tools/httpd.py
HTTPD_PY := python $(NACL_SDK_ROOT)/tools/httpd.py
# Add this to launch Chrome with additional environment variables defined.
# Each element should be specified as KEY=VALUE, with whitespace separating
@ -532,7 +531,7 @@ debug: check_for_chrome all $(PAGE)
.PHONY: serve
serve: all
echo run tools/httpd.py
$(HTTPD_PY) -C $(CURDIR)
endif
# uppercase aliases (for backward compatibility)

107
tools/fix_deps.py

@ -0,0 +1,107 @@
#!/usr/bin/env python
# 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.
"""Fixup GCC-generated dependency files.
Modify GCC generated dependency files so they are more suitable for including
in a GNU Makefile. Without the fixups, deleting or renaming headers can cause
the build to be broken.
See http://mad-scientist.net/make/autodep.html for more details of the problem.
"""
import argparse
import os
import sys
TAG_LINE = '# Updated by fix_deps.py\n'
class Error(Exception):
pass
def ParseLine(line, new_target):
"""Parse one line of a GCC-generated deps file.
Each line contains an optional target and then a list
of space seperated dependencies. Spaces within filenames
are escaped with a backslash.
"""
filenames = []
if new_target and ':' in line:
line = line.split(':', 1)[1]
line = line.strip()
line = line.rstrip('\\')
while True:
# Find the next non-escaped space
line = line.strip()
pos = line.find(' ')
while pos > 0 and line[pos-1] == '\\':
pos = line.find(' ', pos+1)
if pos == -1:
filenames.append(line)
break
filenames.append(line[:pos])
line = line[pos+1:]
return filenames
def FixupDepFile(filename, output_filename=None):
if not os.path.exists(filename):
raise Error('File not found: %s' % filename)
if output_filename is None:
output_filename = filename
outlines = [TAG_LINE]
deps = []
new_target = True
with open(filename) as infile:
for line in infile:
if line == TAG_LINE:
raise Error('Already processed: %s' % filename)
outlines.append(line)
deps += ParseLine(line, new_target)
new_target = line.endswith('\\')
# For every depenency found output a dummy target with no rules
for dep in deps:
outlines.append('%s:\n' % dep)
with open(output_filename, 'w') as outfile:
for line in outlines:
outfile.write(line)
def main(argv):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-o', '--output', help='Output filename (defaults to '
'input name with .deps extension')
parser.add_argument('-c', '--clean', action='store_true',
help='Remove input file after writing output')
parser.add_argument('dep_file')
options = parser.parse_args(argv)
output_filename = options.output
if not output_filename:
output_filename = os.path.splitext(options.dep_file)[0] + '.deps'
FixupDepFile(options.dep_file, output_filename)
if options.clean and options.dep_file != output_filename:
os.remove(options.dep_file)
return 0
if __name__ == '__main__':
try:
sys.exit(main(sys.argv[1:]))
except Error as e:
sys.stderr.write('%s: %s\n' % (os.path.basename(__file__), e))
sys.exit(1)

276
tools/nacl_config.py

@ -0,0 +1,276 @@
#!/usr/bin/env python
# Copyright 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.
"""A helper script to print paths of NaCl binaries, includes, libs, etc.
It is similar in behavior to pkg-config or sdl-config.
"""
import argparse
import os
import posixpath
import sys
import getos
if sys.version_info < (2, 7, 0):
sys.stderr.write("python 2.7 or later is required run this script\n")
sys.exit(1)
VALID_ARCHES = ('arm', 'x86_32', 'x86_64', 'i686')
VALID_PNACL_ARCHES = (None, 'pnacl')
ARCH_NAME = {
'arm': 'arm',
'x86_32': 'i686',
'i686': 'i686',
'x86_64': 'x86_64'
}
ARCH_ALT_NAME = {
'arm': 'arm',
'x86_32': 'x86_32',
'i686': 'x86_32',
'x86_64': 'x86_64'
}
ARCH_BASE_NAME = {
'arm': 'arm',
'x86_32': 'x86',
'i686': 'x86',
'x86_64': 'x86'
}
NACL_TOOLCHAINS = ('newlib', 'glibc', 'pnacl', 'bionic', 'clang-newlib')
HOST_TOOLCHAINS = ('linux', 'mac', 'win')
VALID_TOOLCHAINS = list(HOST_TOOLCHAINS) + list(NACL_TOOLCHAINS) + ['host']
# This is not an exhaustive list of tools, just the ones that need to be
# special-cased.
# e.g. For PNaCL cc => pnacl-clang
# For NaCl cc => pnacl-gcc
#
# Most tools will be passed through directly.
# e.g. For PNaCl foo => pnacl-foo
# For NaCl foo => x86_64-nacl-foo.
CLANG_TOOLS = {
'cc': 'clang',
'c++': 'clang++',
'gcc': 'clang',
'g++': 'clang++',
'ld': 'clang++'
}
GCC_TOOLS = {
'cc': 'gcc',
'c++': 'g++',
'gcc': 'gcc',
'g++': 'g++',
'ld': 'g++'
}
class Error(Exception):
pass
def Expect(condition, message):
if not condition:
raise Error(message)
def ExpectToolchain(toolchain, expected_toolchains):
Expect(toolchain in expected_toolchains,
'Expected toolchain to be one of [%s], not %s.' % (
', '.join(expected_toolchains), toolchain))
def ExpectArch(arch, expected_arches):
Expect(arch in expected_arches,
'Expected arch to be one of [%s], not %s.' % (
', '.join(map(str, expected_arches)), arch))
def CheckValidToolchainArch(toolchain, arch, arch_required=False):
if toolchain or arch or arch_required:
ExpectToolchain(toolchain, VALID_TOOLCHAINS)
if toolchain in HOST_TOOLCHAINS:
Expect(arch is None,
'Expected no arch for host toolchain %r. Got %r.' % (
toolchain, arch))
elif toolchain == 'pnacl':
Expect(arch is None or arch == 'pnacl',
'Expected no arch for toolchain %r. Got %r.' % (toolchain, arch))
elif arch_required:
Expect(arch is not None,
'Expected arch to be one of [%s] for toolchain %r.\n'
'Use the -a or --arch flags to specify one.\n' % (
', '.join(VALID_ARCHES), toolchain))
if arch:
if toolchain == 'pnacl':
ExpectArch(arch, VALID_PNACL_ARCHES)
else:
ExpectArch(arch, VALID_ARCHES)
if arch == 'arm':
Expect(toolchain in ['newlib', 'bionic', 'clang-newlib'],
'The arm arch only supports newlib.')
def GetArchName(arch):
return ARCH_NAME.get(arch)
def GetArchAltName(arch):
return ARCH_ALT_NAME.get(arch)
def GetArchBaseName(arch):
return ARCH_BASE_NAME.get(arch)
def CanonicalizeToolchain(toolchain):
if toolchain == 'host':
return getos.GetPlatform()
return toolchain
def GetPosixSDKPath():
sdk_path = getos.GetSDKPath()
if getos.GetPlatform() == 'win':
return sdk_path.replace('\\', '/')
else:
return sdk_path
def GetToolchainDir(toolchain, arch=None):
ExpectToolchain(toolchain, NACL_TOOLCHAINS)
root = GetPosixSDKPath()
platform = getos.GetPlatform()
if toolchain in ('pnacl', 'clang-newlib'):
subdir = '%s_pnacl' % platform
else:
assert arch is not None
subdir = '%s_%s_%s' % (platform, GetArchBaseName(arch), toolchain)
return posixpath.join(root, 'toolchain', subdir)
def GetToolchainArchDir(toolchain, arch):
ExpectToolchain(toolchain, NACL_TOOLCHAINS)
assert arch is not None
toolchain_dir = GetToolchainDir(toolchain, arch)
arch_dir = '%s-nacl' % GetArchName(arch)
return posixpath.join(toolchain_dir, arch_dir)
def GetToolchainBinDir(toolchain, arch=None):
ExpectToolchain(toolchain, NACL_TOOLCHAINS)
return posixpath.join(GetToolchainDir(toolchain, arch), 'bin')
def GetSDKIncludeDirs(toolchain):
root = GetPosixSDKPath()
base_include = posixpath.join(root, 'include')
if toolchain == 'clang-newlib':
toolchain = 'newlib'
return [base_include, posixpath.join(base_include, toolchain)]
def GetSDKLibDir():
return posixpath.join(GetPosixSDKPath(), 'lib')
# Commands
def GetToolPath(toolchain, arch, tool):
if tool == 'gdb':
# Always use the same gdb; it supports multiple toolchains/architectures.
# NOTE: this is always a i686 executable. i686-nacl-gdb is a symlink to
# x86_64-nacl-gdb.
return posixpath.join(GetToolchainBinDir('newlib', 'x86_64'),
'x86_64-nacl-gdb')
if toolchain == 'pnacl':
CheckValidToolchainArch(toolchain, arch)
tool = CLANG_TOOLS.get(tool, tool)
full_tool_name = 'pnacl-%s' % tool
else:
CheckValidToolchainArch(toolchain, arch, arch_required=True)
ExpectArch(arch, VALID_ARCHES)
if toolchain == 'clang-newlib':
tool = CLANG_TOOLS.get(tool, tool)
else:
tool = GCC_TOOLS.get(tool, tool)
full_tool_name = '%s-nacl-%s' % (GetArchName(arch), tool)
return posixpath.join(GetToolchainBinDir(toolchain, arch), full_tool_name)
def GetCFlags(toolchain):
ExpectToolchain(toolchain, VALID_TOOLCHAINS)
return ' '.join('-I%s' % dirname for dirname in GetSDKIncludeDirs(toolchain))
def GetIncludeDirs(toolchain):
ExpectToolchain(toolchain, VALID_TOOLCHAINS)
return ' '.join(GetSDKIncludeDirs(toolchain))
def GetLDFlags():
return '-L%s' % GetSDKLibDir()
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-t', '--toolchain', help='toolchain name. This can also '
'be specified with the NACL_TOOLCHAIN environment '
'variable.')
parser.add_argument('-a', '--arch', help='architecture name. This can also '
'be specified with the NACL_ARCH environment variable.')
group = parser.add_argument_group('Commands')
group.add_argument('--tool', help='get tool path')
group.add_argument('--cflags',
help='output all preprocessor and compiler flags',
action='store_true')
group.add_argument('--libs', '--ldflags', help='output all linker flags',
action='store_true')
group.add_argument('--include-dirs',
help='output include dirs, separated by spaces',
action='store_true')
options = parser.parse_args(args)
# Get toolchain/arch from environment, if not specified on commandline
options.toolchain = options.toolchain or os.getenv('NACL_TOOLCHAIN')
options.arch = options.arch or os.getenv('NACL_ARCH')
options.toolchain = CanonicalizeToolchain(options.toolchain)
CheckValidToolchainArch(options.toolchain, options.arch)
if options.cflags:
print GetCFlags(options.toolchain)
elif options.include_dirs:
print GetIncludeDirs(options.toolchain)
elif options.libs:
print GetLDFlags()
elif options.tool:
print GetToolPath(options.toolchain, options.arch, options.tool)
else:
parser.error('Expected a command. Run with --help for more information.')
return 0
if __name__ == '__main__':
try:
sys.exit(main(sys.argv[1:]))
except Error as e:
sys.stderr.write(str(e) + '\n')
sys.exit(1)
Loading…
Cancel
Save