Satinder Grewal 9 years ago
parent
commit
ff69c546c5
  1. 107
      crypto777/tools/fix_deps.py
  2. 276
      crypto777/tools/nacl_config.py
  3. 2
      iguana/help/header.md
  4. 289
      iguana/js/tradebot.js
  5. 1332
      iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips.html
  6. BIN
      iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/5962559
  7. BIN
      iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/884931
  8. BIN
      iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/884931(1)
  9. 7
      iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/frameworks-ee521b8e9facac68ff27e93fc3ae0f8ed811d7bf9e434e84f4b9ea227780b084.js
  10. 13
      iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/github-696336964b7c42e4c6f4dfbaf1f8e57f425cd9a9d18a12f3fe6e3dd744fd7d13.js
  11. 2
      iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/github-e3dd2ae433414e240167f740f90ff2599e28804648787933de7c0183fae81c29.css
  12. 2
      iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/github2-fd8d48abb9063f51f186b0da98caa88d32b7ca8baecaa10d8a91c18a6f129b7f.css
  13. BIN
      iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/octocat-spinner-128.gif
  14. BIN
      iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/octocat-spinner-32.gif
  15. 48
      iguana/swaps/iguana_ALTswap.c
  16. 259
      iguana/swaps/iguana_BTCswap.c
  17. 48
      iguana/swaps/iguana_NXTswap.c
  18. 49
      iguana/swaps/iguana_PAXswap.c
  19. 107
      iguana/tools/fix_deps.py
  20. 275
      iguana/tools/getos.py
  21. 276
      iguana/tools/nacl_config.py
  22. 107
      tools/fix_deps.py
  23. 276
      tools/nacl_config.py

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)

2
iguana/help/header.md

@ -1,2 +0,0 @@

289
iguana/js/tradebot.js

@ -0,0 +1,289 @@
//THREE_STRINGS_AND_DOUBLE(tradebot,monitor,exchange,base,rel,commission);
var Tradebot_monitor_api=function(){
var exchange=$('#Tradebot_exchange').val();
var base=$('#Tradebot_base').val();
var rel=$('#Tradebot_rel').val();
var commission=$('#Tradebot_commission').val();
var request='{"agent":"tradebot","method":"monitor","exchange":"'+exchange+'","base":"'+base+'","rel":"'+rel+'", "commission":'+commission+'}';
SPNAPI.makeRequest(request, function(request,response){
show_tradebot_resposnse(response);
}
);
//console.log("Monitor called");
};
var set_Tradebot_monitor_table=function(){
var html='<tr><td align="center" > Base:</td><td align="center" ><input type="text" id="Tradebot_base"/></td></tr><tr><td align="center" >Rel:</td><td align="center" ><input type="text" id="Tradebot_rel"/></td></tr><tr><td align="center" >Commission:</td><td align="center" ><input type="text" id="Tradebot_commission"/></td></tr><tr><td align="center" > Exchange:</td><td align="center" ><select name="Tradebot_exchange" id="Tradebot_exchange"></select></td></tr><tr><td colspan="2" align="center"> <button class="btn btn-primary Tradebot_monitor" >Monitor Tradebot</button></td></tr>';
$('#tradebot_input').html(html);
if(exchanges!==""){
$('#Tradebot_exchange').html(exchanges);
}
};
//STRING_AND_DOUBLE(tradebot,monitorall,exchange,commission);
var Tradebot_monitorall_api=function(){
var exchange=$('#Tradebot_exchange').val();
var commission=$('#Tradebot_commission').val();
var request='{"agent":"tradebot","method":"monitorall","exchange":"'+exchange+'","commission":'+commission+'}';
SPNAPI.makeRequest(request, function(request,response){
show_tradebot_resposnse(response);
}
);
};
var set_Tradebot_monitorall_table=function(){
var html='<tr><td align="center" >Commission:</td><td align="center" ><input type="text" id="Tradebot_commission"/></td></tr><tr><td align="center" > Exchange:</td><td align="center" ><select name="Tradebot_exchange" id="Tradebot_exchange"></select></td></tr><tr><td colspan="2" align="center"> <button class="btn btn-primary Tradebot_monitorall" >Monitor all Exchanges</button></td></tr>';
$('#tradebot_input').html(html);
if(exchanges!==""){
$('#Tradebot_exchange').html(exchanges);
}
};
//THREE_STRINGS(tradebot,unmonitor,exchange,base,rel);
var Tradebot_unmonitor_api=function(){
var exchange=$('#Tradebot_exchange').val();
var base=$('#Tradebot_base').val();
var rel=$('#Tradebot_rel').val();
//var commission=$('#Tradebot_commission').val();
var request='{"agent":"tradebot","method":"unmonitor","exchange":"'+exchange+'","base":"'+base+'","rel":"'+rel+'"}';
SPNAPI.makeRequest(request, function(request,response){
show_tradebot_resposnse(response);
}
);
//console.log("Monitor called");
};
var set_Tradebot_unmonitor_table=function(){
var html='<tr><td align="center" > Base:</td><td align="center" ><input type="text" id="Tradebot_base"/></td></tr><tr><td align="center" >Rel:</td><td align="center" ><input type="text" id="Tradebot_rel"/></td></tr><tr><td align="center" > Exchange:</td><td align="center" ><select name="Tradebot_exchange" id="Tradebot_exchange"></select></td></tr><tr><td colspan="2" align="center"> <button class="btn btn-primary Tradebot_unmonitor_api" >UnMonitor Tradebot</button></td></tr>';
$('#tradebot_input').html(html);
if(exchanges!==""){
$('#Tradebot_exchange').html(exchanges);
}
};
//THREE_STRINGS_AND_THREE_DOUBLES(tradebot,accumulate,exchange,base,rel,price,volume,duration);
var Tradebot_accumulate_api=function(){
var exchange=$('#Tradebot_exchange').val();
var base=$('#Tradebot_base').val();
var rel=$('#Tradebot_rel').val();
var price=$('#Tradebot_price').val();
var volume=$('#Tradebot_volume').val();
var duration=$('#Tradebot_duration').val();
var request='{"agent":"tradebot","method":"accumulate","exchange":"'+exchange+'","base":"'+base+'","rel":"'+rel+'", "price":'+price+',"volume":'+volume+',"duration":'+duration+' }';
SPNAPI.makeRequest(request, function(request,response){
show_tradebot_resposnse(response);
}
);
};
var set_Tradebot_accumulate_table=function(){
var html='<tr><td align="center" > Base:</td><td align="center" ><input type="text" id="Tradebot_base"/></td></tr><tr><td align="center" >Rel:</td><td align="center" ><input type="text" id="Tradebot_rel"/></td></tr><tr><td align="center" >Price:</td><td align="center" ><input type="text" id="Tradebot_price"/></td></tr><tr><td align="center" >Volume:</td><td align="center" ><input type="text" id="Tradebot_volume"/></td></tr><tr><td align="center" >Duration:</td><td align="center" ><input type="text" id="Tradebot_duration"/></td></tr><tr><td align="center" > Exchange:</td><td align="center" ><select name="Tradebot_exchange" id="Tradebot_exchange"></select></td></tr><tr><td colspan="2" align="center"> <button class="btn btn-primary Tradebot_accumulate" >Accumulate Tradebot</button></td></tr>';
$('#tradebot_input').html(html);
if(exchanges!==""){
$('#Tradebot_exchange').html(exchanges);
}
};
//THREE_STRINGS_AND_THREE_DOUBLES(tradebot,divest,exchange,base,rel,price,volume,duration);
var Tradebot_divest_api=function(){
var exchange=$('#Tradebot_exchange').val();
var base=$('#Tradebot_base').val();
var rel=$('#Tradebot_rel').val();
var price=$('#Tradebot_price').val();
var volume=$('#Tradebot_volume').val();
var duration=$('#Tradebot_duration').val();
var request='{"agent":"tradebot","method":"divest","exchange":"'+exchange+'","base":"'+base+'","rel":"'+rel+'", "price":'+price+',"volume":'+volume+',"duration":'+duration+' }';
SPNAPI.makeRequest(request, function(request,response){
show_tradebot_resposnse(response);
}
);
};
var set_Tradebot_divest_table=function(){
var html='<tr><td align="center" > Base:</td><td align="center" ><input type="text" id="Tradebot_base"/></td></tr><tr><td align="center" >Rel:</td><td align="center" ><input type="text" id="Tradebot_rel"/></td></tr><tr><td align="center" >Price:</td><td align="center" ><input type="text" id="Tradebot_price"/></td></tr><tr><td align="center" >Volume:</td><td align="center" ><input type="text" id="Tradebot_volume"/></td></tr><tr><td align="center" >Duration:</td><td align="center" ><input type="text" id="Tradebot_duration"/></td></tr><tr><td align="center" > Exchange:</td><td align="center" ><select name="Tradebot_exchange" id="Tradebot_exchange"></select></td></tr><tr><td colspan="2" align="center"> <button class="btn btn-primary Tradebot_divest" >Divest Tradebot</button></td></tr>';
$('#tradebot_input').html(html);
if(exchanges!==""){
$('#Tradebot_exchange').html(exchanges);
}
};
//STRING_ARG(tradebot,activebots,exchange);
var Tradebot_activebots_api=function(){
var exchange=$('#Tradebot_exchange').val();
var request='{"agent":"tradebot","method":"activebots","exchange":"'+exchange+'"}';
SPNAPI.makeRequest(request, function(request,response){
show_tradebot_resposnse(response);
}
);
};
var set_Tradebot_activebots_table=function(){
var html='<tr><td align="center" > Exchange:</td><td align="center" ><select name="Tradebot_exchange" id="Tradebot_exchange"></select></td></tr><tr><td colspan="2" align="center"> <button class="btn btn-primary Tradebot_activebots" >Get active Tradebot</button></td></tr>';
$('#tradebot_input').html(html);
if(exchanges!==""){
$('#Tradebot_exchange').html(exchanges);
}
};
//TWO_STRINGS(tradebot,status,exchange,botid);
var Tradebot_status_api=function(){
var exchange=$('#Tradebot_exchange').val();
var botid=$('#Tradebot_botid').val();
var request='{"agent":"tradebot","method":"status","exchange":"'+exchange+'","botid":"'+botid+'"}';
SPNAPI.makeRequest(request, function(request,response){
show_tradebot_resposnse(response);
}
);
};
var set_Tradebot_status_table=function(){
var html='<tr><td align="center" >Botid:</td><td align="center" ><input type="text" id="Tradebot_botid"/></td></tr><tr><td align="center" > Exchange:</td><td align="center" ><select name="Tradebot_exchange" id="Tradebot_exchange"></select></td></tr><tr><td colspan="2" align="center"> <button class="btn btn-primary Tradebot_status" >Check status of Tradebot</button></td></tr>';
$('#tradebot_input').html(html);
if(exchanges!==""){
$('#Tradebot_exchange').html(exchanges);}
};
//TWO_STRINGS(tradebot,pause,exchange,botid);
var Tradebot_pause_api=function(){
var exchange=$('#Tradebot_exchange').val();
var botid=$('#Tradebot_botid').val();
var request='{"agent":"tradebot","method":"pause","exchange":"'+exchange+'","botid":"'+botid+'"}';
SPNAPI.makeRequest(request, function(request,response){
show_tradebot_resposnse(response);
}
);
};
var set_Tradebot_pause_table=function(){
var html='<tr><td align="center" >Botid:</td><td align="center" ><input type="text" id="Tradebot_botid"/></td></tr><tr><td align="center" > Exchange:</td><td align="center" ><select name="Tradebot_exchange" id="Tradebot_exchange"></select></td></tr><tr><td colspan="2" align="center"> <button class="btn btn-primary Tradebot_pause" >Pause Tradebot</button></td></tr>';
$('#tradebot_input').html(html);
if(exchanges!==""){
$('#Tradebot_exchange').html(exchanges);
}
};
//TWO_STRINGS(tradebot,stop,exchange,botid);
var Tradebot_stop_api=function(){
var exchange=$('#Tradebot_exchange').val();
var botid=$('#Tradebot_botid').val();
var request='{"agent":"tradebot","method":"stop","exchange":"'+exchange+'","botid":"'+botid+'"}';
SPNAPI.makeRequest(request, function(request,response){
show_tradebot_resposnse(response);
}
);
};
var set_Tradebot_stop_table=function(){
var html='<tr><td align="center" >Botid:</td><td align="center" ><input type="text" id="Tradebot_botid"/></td></tr><tr><td align="center" > Exchange:</td><td align="center" ><select name="Tradebot_exchange" id="Tradebot_exchange"></select></td></tr><tr><td colspan="2" align="center"> <button class="btn btn-primary Tradebot_stop" >Stop Tradebot</button></td></tr>';
$('#tradebot_input').html(html);
if(exchanges!==""){
$('#Tradebot_exchange').html(exchanges);
}
};
//TWO_STRINGS(tradebot,resume,exchange,botid);
var Tradebot_resume_api=function(){
var exchange=$('#Tradebot_exchange').val();
var botid=$('#Tradebot_botid').val();
var request='{"agent":"tradebot","method":"resume","exchange":"'+exchange+'","botid":"'+botid+'"}';
SPNAPI.makeRequest(request, function(request,response){
show_tradebot_resposnse(response);
}
);
};
var set_Tradebot_resume_table=function(){
var html='<tr><td align="center" >Botid:</td><td align="center" ><input type="text" id="Tradebot_botid"/></td></tr><tr><td align="center" > Exchange:</td><td align="center" ><select name="Tradebot_exchange" id="Tradebot_exchange"></select></td></tr><tr><td colspan="2" align="center"> <button class="btn btn-primary Tradebot_resume" >Resume Tradebot</button></td></tr>';
$('#tradebot_input').html(html);
if(exchanges!==""){
$('#Tradebot_exchange').html(exchanges);
}
};
var tradebot_set_method_table=function (method){
if(method==="monitor"){
set_Tradebot_monitor_table();
}else if(method==="monitorall"){
set_Tradebot_monitorall_table();
}else if(method==="unmonitor"){
set_Tradebot_unmonitor_table();
}else if(method==="accumulate"){
set_Tradebot_accumulate_table();
}else if(method==="divest"){
set_Tradebot_divest_table();
}
else if(method==="activebots"){
set_Tradebot_activebots_table();
}
else if(method==="status"){
set_Tradebot_status_table();
}
else if(method==="pause"){
set_Tradebot_pause_table();
}
else if(method==="stop"){
set_Tradebot_stop_table();
}
else if(method==="resume"){
set_Tradebot_resume_table();
}
else{
console.log("wrong method value");
}
$('#trade_output').html("");
};
var show_tradebot_resposnse=function(response){
$('#trade_output').html("");
response=JSON.parse(response);
for(var i in response){
if(i==='tag') continue;
var value="";
if(response[i] instanceof Array){
value=value+"<ul>";
for(var x in response[i]){
value=value+"<li>"+response[i][x]+"<li>";
}
value=value+"</ul>";
}else{value=response[i];}
$('#trade_output').append("<tr><td align='center'>"+i+"</td><td align='center'>"+value+"</td></tr>");
}
};

1332
iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips.html

File diff suppressed because it is too large

BIN
iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/5962559

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/884931

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/884931(1)

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

7
iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/frameworks-ee521b8e9facac68ff27e93fc3ae0f8ed811d7bf9e434e84f4b9ea227780b084.js

File diff suppressed because one or more lines are too long

13
iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/github-696336964b7c42e4c6f4dfbaf1f8e57f425cd9a9d18a12f3fe6e3dd744fd7d13.js

File diff suppressed because one or more lines are too long

2
iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/github-e3dd2ae433414e240167f740f90ff2599e28804648787933de7c0183fae81c29.css

File diff suppressed because one or more lines are too long

2
iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/github2-fd8d48abb9063f51f186b0da98caa88d32b7ca8baecaa10d8a91c18a6f129b7f.css

File diff suppressed because one or more lines are too long

BIN
iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/octocat-spinner-128.gif

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
iguana/swaps/bips_bip-atom.mediawiki at bip4x · TierNolan_bips_files/octocat-spinner-32.gif

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

48
iguana/swaps/iguana_ALTswap.c

@ -0,0 +1,48 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
// BTCoffer:
// sends NXT assetid, volume and desired
// request:
// other node sends (othercoin, othercoinaddr, otherNXT and reftx that expires well before phasedtx)
// proposal:
// NXT node submits phasedtx that refers to it, but it wont confirm
// approve:
// other node verifies unconfirmed has phasedtx and broadcasts cltv, also to NXT node, releases trigger
// confirm:
// NXT node verifies bitcoin txbytes has proper payment and cashes in with onetimepubkey
// BTC* node approves phased tx with onetimepubkey
char *instantdex_ALTswap(struct supernet_info *myinfo,struct exchange_info *exchange,struct instantdex_accept *ap,char *cmdstr,struct instantdex_msghdr *msg,cJSON *argjson,char *remoteaddr,uint64_t signerbits,uint8_t *data,int32_t datalen) // receiving side
{
char *retstr = 0;
if ( strcmp(cmdstr,"offer") == 0 )
{
}
else if ( strcmp(cmdstr,"proposal") == 0 )
{
}
else if ( strcmp(cmdstr,"accept") == 0 )
{
}
else if ( strcmp(cmdstr,"confirm") == 0 )
{
}
else retstr = clonestr("{\"error\":\"ALT swap got unrecognized command\"}");
return(retstr);
}

259
iguana/swaps/iguana_BTCswap.c

@ -0,0 +1,259 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
#include "../exchanges/bitcoin.h"
// https://github.com/TierNolan/bips/blob/bip4x/bip-atom.mediawiki
uint64_t instantdex_relsatoshis(uint64_t price,uint64_t volume)
{
if ( volume > price )
return(price * dstr(volume));
else return(dstr(price) * volume);
}
bits256 instantdex_sharedpub256(uint8_t pubkey[33],bits256 privkey,bits256 hash,int32_t n)
{
bits256 tmppriv,shared,iters; int32_t i;
iters = shared = curve25519_shared(privkey,hash);
for (i=0; i<n; i++)
iters = curve25519(iters,curve25519(iters,curve25519_basepoint9()));
vcalc_sha256cat(tmppriv.bytes,shared.bytes,sizeof(shared),iters.bytes,sizeof(iters));
return(bitcoin_pubkey33(pubkey,tmppriv));
}
int32_t instantdex_pubkeyargs(cJSON *argjson,int32_t numpubs,bits256 privkey,bits256 hash,int32_t firstbyte)
{
char buf[3]; int32_t i,n; bits256 tmp; uint8_t pubkey[33];
sprintf(buf,"%c0",'A' - 0x02 + firstbyte);
for (i=n=0; i<numpubs*100&&n<numpubs; i++)
{
tmp = instantdex_sharedpub256(pubkey,privkey,hash,i+1);
if ( pubkey[0] != firstbyte )
continue;
buf[1] = '0' + n++;
jaddbits256(argjson,buf,tmp);
}
return(n);
}
int32_t bitcoin_2of2spendscript(int32_t *paymentlenp,uint8_t *paymentscript,uint8_t *msigscript,bits256 pub0,bits256 pub1)
{
struct vin_info V; uint8_t p2sh_rmd160[20]; int32_t p2shlen;
memset(&V,0,sizeof(V));
V.M = V.N = 2;
memcpy(V.signers[0].pubkey+1,pub0.bytes,sizeof(pub0)), V.signers[0].pubkey[0] = 0x02;
memcpy(V.signers[1].pubkey+1,pub1.bytes,sizeof(pub1)), V.signers[1].pubkey[0] = 0x03;
p2shlen = bitcoin_MofNspendscript(p2sh_rmd160,msigscript,0,&V);
*paymentlenp = bitcoin_p2shspend(paymentscript,0,p2sh_rmd160);
return(p2shlen);
}
/*struct bitcoin_unspent { bits256 txid,privkey; uint64_t value; int32_t vout; };
struct bitcoin_spend
{
char changeaddr[64];
int32_t numinputs;
uint64_t txfee,input_satoshis,satoshis;
struct bitcoin_unspent inputs[];
};*/
char *instantdex_bailintx(struct iguana_info *coin,bits256 *txidp,struct bitcoin_spend *spend,bits256 A0,bits256 B0,uint8_t x[20],int32_t isbob)
{
/*Input value: B + 2*fb + change
Input source: (From Bob's coins, multiple inputs are allowed)
Output 0 value: B
ScriptPubKey 0: OP_HASH160 Hash160(P2SH Redeem) OP_EQUAL
Output 1 value: fb
ScriptPubKey 1: OP_HASH160 Hash160(x) OP_EQUALVERIFY pub-A1 OP_CHECKSIG
Output 2 value: change
ScriptPubKey 2: <= 100 bytes
P2SH Redeem: OP_2 pub-A1 pub-B1 OP_2 OP_CHECKMULTISIG
Name: Alice.Bail.In
Input value: A + 2*fa + change
Input source: (From Alice's altcoins, multiple inputs are allowed)
Output 0 value: A
ScriptPubKey 0: OP_HASH160 Hash160(P2SH Redeem) OP_EQUAL
Output 1 value: fa
ScriptPubKey 1: OP_HASH160 Hash160(x) OP_EQUAL
Output 2 value: change
ScriptPubKey 2: <= 100 bytes*/
uint64_t change; char *rawtxstr,*signedtx; struct vin_info *V; bits256 txid,signedtxid;
int32_t p2shlen,i; cJSON *txobj; int32_t scriptv0len,scriptv1len,scriptv2len;
uint8_t p2shscript[256],scriptv0[128],scriptv1[128],changescript[128],pubkey[35];
p2shlen = bitcoin_2of2spendscript(&scriptv0len,scriptv0,p2shscript,A0,B0);
txobj = bitcoin_createtx(coin,0);
bitcoin_addoutput(coin,txobj,scriptv0,scriptv0len,spend->satoshis);
if ( isbob != 0 )
{
scriptv1len = bitcoin_revealsecret160(scriptv1,0,x);
scriptv1len = bitcoin_pubkeyspend(scriptv1,scriptv1len,pubkey);
} else scriptv1len = bitcoin_p2shspend(scriptv1,0,x);
bitcoin_addoutput(coin,txobj,scriptv1,scriptv1len,spend->txfee);
if ( (scriptv2len= bitcoin_changescript(coin,changescript,0,&change,spend->changeaddr,spend->input_satoshis,spend->satoshis,spend->txfee)) > 0 )
bitcoin_addoutput(coin,txobj,changescript,scriptv2len,change);
for (i=0; i<spend->numinputs; i++)
bitcoin_addinput(coin,txobj,spend->inputs[i].txid,spend->inputs[i].vout,0xffffffff);
rawtxstr = bitcoin_json2hex(coin,&txid,txobj);
char str[65]; printf("%s_bailin.%s (%s)\n",isbob!=0?"bob":"alice",bits256_str(str,txid),rawtxstr);
V = calloc(spend->numinputs,sizeof(*V));
for (i=0; i<spend->numinputs; i++)
V[i].signers[0].privkey = spend->inputs[i].privkey;
bitcoin_verifytx(coin,&signedtxid,&signedtx,rawtxstr,V);
free(rawtxstr), free(V);
if ( signedtx != 0 )
printf("signed bob_bailin.%s (%s)\n",bits256_str(str,signedtxid),signedtx);
else printf("error generating signedtx\n");
free_json(txobj);
*txidp = txid;
return(signedtx);
}
int32_t instantdex_calcx20(char hexstr[41],uint8_t *p2shscript,uint8_t firstbyte,bits256 pub3)
{
uint8_t pubkey[33],script[64],rmd160[20]; int32_t n; bits256 hash;
memcpy(pubkey+1,pub3.bytes,sizeof(pub3)), pubkey[0] = firstbyte;
n = bitcoin_pubkeyspend(p2shscript,0,pubkey);
vcalc_sha256(0,hash.bytes,script,n);
calc_rmd160(0,rmd160,hash.bytes,sizeof(hash.bytes));
init_hexbytes_noT(hexstr,rmd160,sizeof(rmd160));
return(n);
}
char *instantdex_btcoffer(struct supernet_info *myinfo,struct exchange_info *exchange,char *othercoin,double othervolume,double maxprice) // Bob sending to network (Alice)
{
char *str,coinaddr[64],xstr[41]; uint8_t xscript[64]; struct iguana_info *other;
struct instantdex_accept A; cJSON *newjson; bits256 hash,pub3;
if ( othercoin == 0 || (other= iguana_coinfind(othercoin)) == 0 )
return(clonestr("{\"error\":\"invalid othercoin\"}"));
hash = instantdex_acceptset(&A,othercoin,"BTC",INSTANTDEX_OFFERDURATION,1,-1,maxprice,othervolume,myinfo->myaddr.nxt64bits);
newjson = instantdex_acceptsendjson(&A);
if ( instantdex_pubkeyargs(newjson,4,myinfo->persistent_priv,hash,0x03) != 4 )
return(clonestr("{\"error\":\"highly unlikely run of 02 pubkeys\"}"));
pub3 = jbits256(newjson,"B3");
jdelete(newjson,"B3");
instantdex_calcx20(xstr,xscript,0x03,pub3);
jaddstr(newjson,"x",xstr);
if ( coinaddr[0] != 0 )
jaddstr(newjson,othercoin,coinaddr);
if ( maxprice > 0. )
{
if ( (str= InstantDEX_maxaccept(myinfo,0,newjson,0,othercoin,"BTC",maxprice,othervolume)) != 0 )
free(str);
}
return(instantdex_sendcmd(myinfo,newjson,"BTCoffer",myinfo->ipaddr,INSTANTDEX_HOPS));
}
char *instantdex_BTCswap(struct supernet_info *myinfo,struct exchange_info *exchange,struct instantdex_accept *A,char *cmdstr,struct instantdex_msghdr *msg,cJSON *argjson,char *remoteaddr,uint64_t signerbits,uint8_t *data,int32_t datalen) // receiving side
{
uint8_t script[999],p2sh_rmd160[20],secret160[20],pubkey[36],addrtype;
bits256 hash,bailintxid,A0,B0; struct bitcoin_spend SPEND;
struct instantdex_accept *ap; uint64_t satoshis,othersatoshis,orderid;
char p2sh_coinaddr[64],*senderaddr,otheraddr[64],base[24],coinaddr[64],*retstr,*bailintx;
int32_t scriptlen,locktime,offerdir = 0; struct iguana_info *coinbtc,*other; cJSON *newjson;
retstr = 0;
memset(&SPEND,0,sizeof(SPEND));
if ( exchange == 0 )
return(clonestr("{\"error\":\"instantdex_BTCswap null exchange ptr\"}"));
offerdir = instantdex_bidaskdir(A);
if ( (other= iguana_coinfind(A->A.base)) == 0 || (coinbtc= iguana_coinfind("BTC")) == 0 )
return(clonestr("{\"error\":\"instantdex_BTCswap cant find btc or other coin info\"}"));
locktime = (uint32_t)(A->A.expiration + INSTANTDEX_OFFERDURATION);
if ( A->A.rel == 0 || strcmp(A->A.rel,"BTC") != 0 )
return(clonestr("{\"error\":\"instantdex_BTCswap offer non BTC rel\"}"));
if ( strcmp(cmdstr,"offer") == 0 ) // sender is Bob, receiver is network (Alice)
{
// should add to orderbook if not accepted
if ( A->A.expiration < (time(NULL) + INSTANTDEX_DURATION) )
return(clonestr("{\"error\":\"instantdex_BTCswap offer too close to expiration\"}"));
printf("got offer.(%s) offerside.%d offerdir.%d\n",jprint(argjson,0),A->A.myside,A->A.acceptdir);
if ( (ap= instantdex_acceptable(exchange,A,myinfo->myaddr.nxt64bits)) != 0 )
{
ap->pendingvolume64 -= A->A.basevolume64;
satoshis = instantdex_relsatoshis(A->A.price64,A->A.basevolume64);
newjson = cJSON_CreateObject();
if ( instantdex_pubkeyargs(argjson,3,myinfo->persistent_priv,hash,0x02) != 3 )
return(clonestr("{\"error\":\"highly unlikely run of 03 pubkeys\"}"));
jadd64bits(newjson,"id",A->orderid);
jadd64bits(newjson,"BTC",satoshis);
jadd64bits(newjson,"v",A->A.basevolume64);
jaddstr(newjson,"b",other->symbol);
jaddstr(newjson,other->symbol,otheraddr);
jaddstr(newjson,"p2sh",p2sh_coinaddr);
bailintx = instantdex_bailintx(coinbtc,&bailintxid,&SPEND,A0,B0,secret160,1);
jaddstr(newjson,"bailin",bailintx);
jaddbits256(newjson,"bailintxid",bailintxid);
free(bailintx);
return(instantdex_sendcmd(myinfo,newjson,"proposal",myinfo->ipaddr,INSTANTDEX_HOPS));
} else printf("no matching trade.(%s)\n",jprint(argjson,0));
}
else if ( strcmp(cmdstr,"proposal") == 0 ) // sender is Alice, receiver is Bob
{
satoshis = j64bits(argjson,"BTC");
orderid = j64bits(argjson,"id");
othersatoshis = j64bits(argjson,"v");
senderaddr = myinfo->myaddr.BTC;
if ( jobj(argjson,other->symbol) != 0 )
safecopy(otheraddr,jstr(argjson,other->symbol),sizeof(otheraddr));
if ( jobj(argjson,"b") != 0 )
safecopy(base,jstr(argjson,"b"),sizeof(base));
printf("proposal orderid.%llu BTC satoshis %.8f for %s vol %.8f ps2h.%s\n",A->orderid,dstr(satoshis),base,dstr(othersatoshis),p2sh_coinaddr);
if ( A->orderid != orderid )
{
printf("orderid mismatch %llu vs %llu\n",(long long)orderid,(long long)A->orderid);
return(clonestr("{\"error\":\"instantdex_BTCswap orderid mismatch\"}"));
}
if ( senderaddr == 0 || strcmp(A->A.base,base) != 0 || strcmp(A->A.rel,"BTC") != 0 )
{
printf("senderaddr.%p base.(%s vs %s) rel.(%s vs %s)\n",senderaddr,A->A.base,base,A->A.rel,"BTC");
return(clonestr("{\"error\":\"instantdex_BTCswap base or rel mismatch\"}"));
}
bitcoin_pubkey33(pubkey,myinfo->persistent_priv);
bitcoin_address(coinaddr,other->chain->pubtype,pubkey,sizeof(pubkey));
bitcoin_addr2rmd160(&addrtype,secret160,coinaddr);
scriptlen = bitcoin_cltvscript(coinbtc->chain->p2shtype,p2sh_coinaddr,p2sh_rmd160,script,0,senderaddr,otheraddr,secret160,locktime);
if ( jobj(argjson,"p2sh") != 0 )
{
if ( strcmp(jstr(argjson,"p2sh"),p2sh_coinaddr) != 0 )
{
printf("mismatched p2sh.(%s) vs (%s)\n",jstr(argjson,"p2sh"),p2sh_coinaddr);
return(clonestr("{\"error\":\"instantdex_BTCswap base or rel mismatch\"}"));
}
}
if ( satoshis != instantdex_relsatoshis(A->A.price64,A->A.basevolume64) )
{
printf("satoshis mismatch %llu vs %llu\n",(long long)satoshis,(long long)instantdex_relsatoshis(A->A.price64,A->A.basevolume64));
return(clonestr("{\"error\":\"instantdex_BTCswap satoshis mismatch\"}"));
}
if ( othersatoshis != A->A.basevolume64 )
{
printf("othersatoshis mismatch %llu vs %llu\n",(long long)satoshis,(long long)A->A.basevolume64);
return(clonestr("{\"error\":\"instantdex_BTCswap satoshis mismatch\"}"));
}
// return(instantdex_sendcmd(myinfo,newjson,"accept",myinfo->ipaddr,INSTANTDEX_HOPS));
}
else if ( strcmp(cmdstr,"accept") == 0 ) // sender is Bob, receiver is Alice
{
}
else if ( strcmp(cmdstr,"confirm") == 0 ) // both send and receive
{
}
else retstr = clonestr("{\"error\":\"BTC swap got unrecognized command\"}");
if ( retstr == 0 )
retstr = clonestr("{\"error\":\"BTC swap null retstr\"}");
return(retstr);
}

48
iguana/swaps/iguana_NXTswap.c

@ -0,0 +1,48 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
// BTCoffer:
// sends NXT assetid, volume and desired
// request:
// other node sends (othercoin, othercoinaddr, otherNXT and reftx that expires well before phasedtx)
// proposal:
// NXT node submits phasedtx that refers to it, but it wont confirm
// approve:
// other node verifies unconfirmed has phasedtx and broadcasts cltv, also to NXT node, releases trigger
// confirm:
// NXT node verifies bitcoin txbytes has proper payment and cashes in with onetimepubkey
// BTC* node approves phased tx with onetimepubkey
char *instantdex_NXTswap(struct supernet_info *myinfo,struct exchange_info *exchange,struct instantdex_accept *ap,char *cmdstr,struct instantdex_msghdr *msg,cJSON *argjson,char *remoteaddr,uint64_t signerbits,uint8_t *data,int32_t datalen) // receiving side
{
char *retstr = 0;
if ( strcmp(cmdstr,"offer") == 0 )
{
}
else if ( strcmp(cmdstr,"proposal") == 0 )
{
}
else if ( strcmp(cmdstr,"accept") == 0 )
{
}
else if ( strcmp(cmdstr,"confirm") == 0 )
{
}
else retstr = clonestr("{\"error\":\"NXT swap got unrecognized command\"}");
return(retstr);
}

49
iguana/swaps/iguana_PAXswap.c

@ -0,0 +1,49 @@
/******************************************************************************
* Copyright © 2014-2016 The SuperNET Developers. *
* *
* See the AUTHORS, DEVELOPER-AGREEMENT and LICENSE files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* SuperNET software, including this file may be copied, modified, propagated *
* or distributed except according to the terms contained in the LICENSE file *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
// BTCoffer:
// sends NXT assetid, volume and desired
// request:
// other node sends (othercoin, othercoinaddr, otherNXT and reftx that expires well before phasedtx)
// proposal:
// NXT node submits phasedtx that refers to it, but it wont confirm
// approve:
// other node verifies unconfirmed has phasedtx and broadcasts cltv, also to NXT node, releases trigger
// confirm:
// NXT node verifies bitcoin txbytes has proper payment and cashes in with onetimepubkey
// BTC* node approves phased tx with onetimepubkey
char *instantdex_PAXswap(struct supernet_info *myinfo,struct exchange_info *exchange,struct instantdex_accept *ap,char *cmdstr,struct instantdex_msghdr *msg,cJSON *argjson,char *remoteaddr,uint64_t signerbits,uint8_t *data,int32_t datalen) // receiving side
{
char *retstr = 0;
return(clonestr("{\"error\":\"PAX swap is not yet\"}"));
if ( strcmp(cmdstr,"offer") == 0 )
{
}
else if ( strcmp(cmdstr,"proposal") == 0 )
{
}
else if ( strcmp(cmdstr,"accept") == 0 )
{
}
else if ( strcmp(cmdstr,"confirm") == 0 )
{
}
else retstr = clonestr("{\"error\":\"PAX swap got unrecognized command\"}");
return(retstr);
}

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)

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