Adding nsync for NLSR
diff --git a/nsync/doc/doxygen.conf b/nsync/doc/doxygen.conf
new file mode 100644
index 0000000..851bd58
--- /dev/null
+++ b/nsync/doc/doxygen.conf
@@ -0,0 +1,1515 @@
+# Doxyfile 1.6.1
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project
+#
+# All text after a hash (#) is considered a comment and will be ignored
+# The format is:
+# TAG = value [value, ...]
+# For lists items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ")
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all
+# text before the first occurrence of this tag. Doxygen uses libiconv (or the
+# iconv built into libc) for the transcoding. See
+# http://www.gnu.org/software/libiconv for the list of possible encodings.
+
+DOXYFILE_ENCODING = UTF-8
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded
+# by quotes) that should identify the project.
+
+PROJECT_NAME = "Sync "
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number.
+# This could be handy for archiving the generated documentation or
+# if some version control system is used.
+
+PROJECT_NUMBER =
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
+# base path where the generated documentation will be put.
+# If a relative path is entered, it will be relative to the location
+# where doxygen was started. If left blank the current directory will be used.
+
+OUTPUT_DIRECTORY = doc
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
+# 4096 sub-directories (in 2 levels) under the output directory of each output
+# format and will distribute the generated files over these directories.
+# Enabling this option can be useful when feeding doxygen a huge amount of
+# source files, where putting all generated files in the same directory would
+# otherwise cause performance problems for the file system.
+
+CREATE_SUBDIRS = YES
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# The default language is English, other supported languages are:
+# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
+# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
+# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
+# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
+# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak,
+# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+
+OUTPUT_LANGUAGE = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
+# include brief member descriptions after the members that are listed in
+# the file and class documentation (similar to JavaDoc).
+# Set to NO to disable this.
+
+BRIEF_MEMBER_DESC = YES
+
+# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
+# the brief description of a member or function before the detailed description.
+# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+
+REPEAT_BRIEF = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator
+# that is used to form the text in various listings. Each string
+# in this list, if found as the leading text of the brief description, will be
+# stripped from the text and the result after processing the whole list, is
+# used as the annotated text. Otherwise, the brief description is used as-is.
+# If left blank, the following values are used ("$name" is automatically
+# replaced with the name of the entity): "The $name class" "The $name widget"
+# "The $name file" "is" "provides" "specifies" "contains"
+# "represents" "a" "an" "the"
+
+ABBREVIATE_BRIEF = YES
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# Doxygen will generate a detailed section even if there is only a brief
+# description.
+
+ALWAYS_DETAILED_SEC = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+
+INLINE_INHERITED_MEMB = YES
+
+# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
+# path before files name in the file list and in the header files. If set
+# to NO the shortest path that makes the file name unique will be used.
+
+FULL_PATH_NAMES = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
+# can be used to strip a user-defined part of the path. Stripping is
+# only done if one of the specified strings matches the left-hand part of
+# the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the
+# path to strip.
+
+STRIP_FROM_PATH =
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
+# the path mentioned in the documentation of a class, which tells
+# the reader which header file to include in order to use a class.
+# If left blank only the name of the header file containing the class
+# definition is used. Otherwise one should specify the include paths that
+# are normally passed to the compiler using the -I flag.
+
+STRIP_FROM_INC_PATH =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
+# (but less readable) file names. This can be useful is your file systems
+# doesn't support long names like on DOS, Mac, or CD-ROM.
+
+SHORT_NAMES = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
+# will interpret the first line (until the first dot) of a JavaDoc-style
+# comment as the brief description. If set to NO, the JavaDoc
+# comments will behave just like regular Qt-style comments
+# (thus requiring an explicit @brief command for a brief description.)
+
+JAVADOC_AUTOBRIEF = YES
+
+# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
+# interpret the first line (until the first dot) of a Qt-style
+# comment as the brief description. If set to NO, the comments
+# will behave just like regular Qt-style comments (thus requiring
+# an explicit \brief command for a brief description.)
+
+QT_AUTOBRIEF = YES
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
+# treat a multi-line C++ special comment block (i.e. a block of //! or ///
+# comments) as a brief description. This used to be the default behaviour.
+# The new default is to treat a multi-line C++ comment block as a detailed
+# description. Set this tag to YES if you prefer the old behaviour instead.
+
+MULTILINE_CPP_IS_BRIEF = YES
+
+# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
+# member inherits the documentation from any documented member that it
+# re-implements.
+
+INHERIT_DOCS = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
+# a new page for each member. If set to NO, the documentation of a member will
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab.
+# Doxygen uses this value to replace tabs by spaces in code fragments.
+
+TAB_SIZE = 4
+
+# This tag can be used to specify a number of aliases that acts
+# as commands in the documentation. An alias has the form "name=value".
+# For example adding "sideeffect=\par Side Effects:\n" will allow you to
+# put the command \sideeffect (or @sideeffect) in the documentation, which
+# will result in a user-defined paragraph with heading "Side Effects:".
+# You can put \n's in the value part of an alias to insert newlines.
+
+ALIASES =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
+# sources only. Doxygen will then generate output that is more tailored for C.
+# For instance, some of the names that are used will be different. The list
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
+# sources only. Doxygen will then generate output that is more tailored for
+# Java. For instance, namespaces will be presented as packages, qualified
+# scopes will look different, etc.
+
+OPTIMIZE_OUTPUT_JAVA = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources only. Doxygen will then generate output that is more tailored for
+# Fortran.
+
+OPTIMIZE_FOR_FORTRAN = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for
+# VHDL.
+
+OPTIMIZE_OUTPUT_VHDL = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it parses.
+# With this tag you can assign which parser to use for a given extension.
+# Doxygen has a built-in mapping, but you can override or extend it using this tag.
+# The format is ext=language, where ext is a file extension, and language is one of
+# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP,
+# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat
+# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran),
+# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen.
+
+EXTENSION_MAPPING =
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should
+# set this tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
+# func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT = YES
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+
+CPP_CLI_SUPPORT = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
+# Doxygen will parse them like normal C++ but will assume all classes use public
+# instead of private inheritance when no explicit protection keyword is present.
+
+SIP_SUPPORT = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate getter
+# and setter methods for a property. Setting this option to YES (the default)
+# will make doxygen to replace the get and set methods by a property in the
+# documentation. This will only work if the methods are indeed getting or
+# setting a simple type. If this is not the case, or you want to show the
+# methods anyway, you should set this option to NO.
+
+IDL_PROPERTY_SUPPORT = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+
+DISTRIBUTE_GROUP_DOC = NO
+
+# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
+# the same type (for instance a group of public functions) to be put as a
+# subgroup of that type (e.g. under the Public Functions section). Set it to
+# NO to prevent subgrouping. Alternatively, this can be done per class using
+# the \nosubgrouping command.
+
+SUBGROUPING = YES
+
+# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
+# is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically
+# be useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+TYPEDEF_HIDES_STRUCT = NO
+
+# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to
+# determine which symbols to keep in memory and which to flush to disk.
+# When the cache is full, less often used symbols will be written to disk.
+# For small to medium size projects (<1000 input files) the default value is
+# probably good enough. For larger projects a too small cache size can cause
+# doxygen to be busy swapping symbols to and from disk most of the time
+# causing a significant performance penality.
+# If the system has enough physical memory increasing the cache will improve the
+# performance by keeping more symbols in memory. Note that the value works on
+# a logarithmic scale so increasing the size by one will rougly double the
+# memory usage. The cache size is given by this formula:
+# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0,
+# corresponding to a cache size of 2^16 = 65536 symbols
+
+SYMBOL_CACHE_SIZE = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available.
+# Private class members and static file members will be hidden unless
+# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
+
+EXTRACT_ALL = YES
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
+# will be included in the documentation.
+
+EXTRACT_PRIVATE = YES
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file
+# will be included in the documentation.
+
+EXTRACT_STATIC = YES
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
+# defined locally in source files will be included in the documentation.
+# If set to NO only classes defined in header files are included.
+
+EXTRACT_LOCAL_CLASSES = NO
+
+# This flag is only useful for Objective-C code. When set to YES local
+# methods, which are defined in the implementation section but not in
+# the interface are included in the documentation.
+# If set to NO (the default) only methods in the interface are included.
+
+EXTRACT_LOCAL_METHODS = YES
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base
+# name of the file that contains the anonymous namespace. By default
+# anonymous namespace are hidden.
+
+EXTRACT_ANON_NSPACES = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
+# undocumented members of documented classes, files or namespaces.
+# If set to NO (the default) these members will be included in the
+# various overviews, but no documentation section is generated.
+# This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_MEMBERS = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy.
+# If set to NO (the default) these classes will be included in the various
+# overviews. This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_CLASSES = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
+# friend (class|struct|union) declarations.
+# If set to NO (the default) these declarations will be included in the
+# documentation.
+
+HIDE_FRIEND_COMPOUNDS = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
+# documentation blocks found inside the body of a function.
+# If set to NO (the default) these blocks will be appended to the
+# function's detailed documentation block.
+
+HIDE_IN_BODY_DOCS = NO
+
+# The INTERNAL_DOCS tag determines if documentation
+# that is typed after a \internal command is included. If the tag is set
+# to NO (the default) then the documentation will be excluded.
+# Set it to YES to include the internal documentation.
+
+INTERNAL_DOCS = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
+# file names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+
+CASE_SENSE_NAMES = NO
+
+# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
+# will show members with their full class and namespace scopes in the
+# documentation. If set to YES the scope will be hidden.
+
+HIDE_SCOPE_NAMES = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
+# will put a list of the files that are included by a file in the documentation
+# of that file.
+
+SHOW_INCLUDE_FILES = YES
+
+# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
+# is inserted in the documentation for inline members.
+
+INLINE_INFO = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
+# will sort the (detailed) documentation of file and class members
+# alphabetically by member name. If set to NO the members will appear in
+# declaration order.
+
+SORT_MEMBER_DOCS = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
+# brief documentation of file, namespace and class members alphabetically
+# by member name. If set to NO (the default) the members will appear in
+# declaration order.
+
+SORT_BRIEF_DOCS = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
+# hierarchy of group names into alphabetical order. If set to NO (the default)
+# the group names will appear in their defined order.
+
+SORT_GROUP_NAMES = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
+# sorted by fully-qualified names, including namespaces. If set to
+# NO (the default), the class list will be sorted only by class name,
+# not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the
+# alphabetical list.
+
+SORT_BY_SCOPE_NAME = YES
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or
+# disable (NO) the todo list. This list is created by putting \todo
+# commands in the documentation.
+
+GENERATE_TODOLIST = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or
+# disable (NO) the test list. This list is created by putting \test
+# commands in the documentation.
+
+GENERATE_TESTLIST = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or
+# disable (NO) the bug list. This list is created by putting \bug
+# commands in the documentation.
+
+GENERATE_BUGLIST = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
+# disable (NO) the deprecated list. This list is created by putting
+# \deprecated commands in the documentation.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional
+# documentation sections, marked by \if sectionname ... \endif.
+
+ENABLED_SECTIONS =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
+# the initial value of a variable or define consists of for it to appear in
+# the documentation. If the initializer consists of more lines than specified
+# here it will be hidden. Use a value of 0 to hide initializers completely.
+# The appearance of the initializer of individual variables and defines in the
+# documentation can be controlled using \showinitializer or \hideinitializer
+# command in the documentation regardless of this setting.
+
+MAX_INITIALIZER_LINES = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
+# at the bottom of the documentation of classes and structs. If set to YES the
+# list will mention the files that were used to generate the documentation.
+
+SHOW_USED_FILES = YES
+
+# If the sources in your project are distributed over multiple directories
+# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy
+# in the documentation. The default is NO.
+
+SHOW_DIRECTORIES = NO
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
+# This will remove the Files entry from the Quick Index and from the
+# Folder Tree View (if specified). The default is YES.
+
+SHOW_FILES = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
+# Namespaces page.
+# This will remove the Namespaces entry from the Quick Index
+# and from the Folder Tree View (if specified). The default is YES.
+
+SHOW_NAMESPACES = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command <command> <input-file>, where <command> is the value of
+# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
+# provided by doxygen. Whatever the program writes to standard output
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by
+# doxygen. The layout file controls the global structure of the generated output files
+# in an output format independent way. The create the layout file that represents
+# doxygen's defaults, run doxygen with the -l option. You can optionally specify a
+# file name after the option, if omitted DoxygenLayout.xml will be used as the name
+# of the layout file.
+
+LAYOUT_FILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated
+# by doxygen. Possible values are YES and NO. If left blank NO is used.
+
+QUIET = YES
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated by doxygen. Possible values are YES and NO. If left blank
+# NO is used.
+
+WARNINGS = YES
+
+# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
+# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
+# automatically be disabled.
+
+WARN_IF_UNDOCUMENTED = YES
+
+# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some
+# parameters in a documented function, or documenting parameters that
+# don't exist or using markup commands wrongly.
+
+WARN_IF_DOC_ERROR = YES
+
+# This WARN_NO_PARAMDOC option can be abled to get warnings for
+# functions that are documented, but have no documentation for their parameters
+# or return value. If set to NO (the default) doxygen will only warn about
+# wrong or incomplete parameter documentation, but not about the absence of
+# documentation.
+
+WARN_NO_PARAMDOC = YES
+
+# The WARN_FORMAT tag determines the format of the warning messages that
+# doxygen can produce. The string should contain the $file, $line, and $text
+# tags, which will be replaced by the file and line number from which the
+# warning originated and the warning text. Optionally the format may contain
+# $version, which will be replaced by the version of the file (if it could
+# be obtained via FILE_VERSION_FILTER)
+
+WARN_FORMAT = "$file:$line: $text "
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning
+# and error messages should be written. If left blank the output is written
+# to stderr.
+
+WARN_LOGFILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain
+# documented source files. You may enter file names like "myfile.cpp" or
+# directories like "/usr/src/myproject". Separate the files or directories
+# with spaces.
+
+INPUT = doc src
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
+# also the default input encoding. Doxygen uses libiconv (or the iconv built
+# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
+# the list of possible encodings.
+
+INPUT_ENCODING = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank the following patterns are tested:
+# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx
+# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90
+
+FILE_PATTERNS = *.h \
+ *.cc
+
+# The RECURSIVE tag can be used to turn specify whether or not subdirectories
+# should be searched for input files as well. Possible values are YES and NO.
+# If left blank NO is used.
+
+RECURSIVE = YES
+
+# The EXCLUDE tag can be used to specify files and/or directories that should
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+
+EXCLUDE =
+
+# The EXCLUDE_SYMLINKS tag can be used select whether or not files or
+# directories that are symbolic links (a Unix filesystem feature) are excluded
+# from the input.
+
+EXCLUDE_SYMLINKS = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories. Note that the wildcards are matched
+# against the file with absolute path, so to exclude all test directories
+# for example use the pattern */test/*
+
+EXCLUDE_PATTERNS = */test/*
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+
+EXCLUDE_SYMBOLS =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or
+# directories that contain example code fragments that are included (see
+# the \include command).
+
+EXAMPLE_PATH =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank all files are included.
+
+EXAMPLE_PATTERNS =
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude
+# commands irrespective of the value of the RECURSIVE tag.
+# Possible values are YES and NO. If left blank NO is used.
+
+EXAMPLE_RECURSIVE = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or
+# directories that contain image that are included in the documentation (see
+# the \image command).
+
+IMAGE_PATH = doc
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command <filter> <input-file>, where <filter>
+# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
+# input file. Doxygen will then use the output that the filter program writes
+# to standard output.
+# If FILTER_PATTERNS is specified, this tag will be
+# ignored.
+
+INPUT_FILTER = "sed 's/boost::shared_ptr<\(.*\)>/\1*/'"
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis.
+# Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match.
+# The filters are a list of the form:
+# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
+# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER
+# is applied to all files.
+
+FILTER_PATTERNS =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will be used to filter the input files when producing source
+# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+
+FILTER_SOURCE_FILES = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will
+# be generated. Documented entities will be cross-referenced with these sources.
+# Note: To get rid of all source code in the generated output, make sure also
+# VERBATIM_HEADERS is set to NO.
+
+SOURCE_BROWSER = NO
+
+# Setting the INLINE_SOURCES tag to YES will include the body
+# of functions and classes directly in the documentation.
+
+INLINE_SOURCES = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
+# doxygen to hide any special comment blocks from generated source code
+# fragments. Normal C and C++ comments will always remain visible.
+
+STRIP_CODE_COMMENTS = YES
+
+# If the REFERENCED_BY_RELATION tag is set to YES
+# then for each documented function all documented
+# functions referencing it will be listed.
+
+REFERENCED_BY_RELATION = YES
+
+# If the REFERENCES_RELATION tag is set to YES
+# then for each documented function all documented entities
+# called/used by that function will be listed.
+
+REFERENCES_RELATION = YES
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
+# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
+# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
+# link to the source code.
+# Otherwise they will link to the documentation.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code
+# will point to the HTML generated by the htags(1) tool instead of doxygen
+# built-in source browser. The htags tool is part of GNU's global source
+# tagging system (see http://www.gnu.org/software/global/global.html). You
+# will need version 4.8.6 or higher.
+
+USE_HTAGS = NO
+
+# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
+# will generate a verbatim copy of the header file for each class for
+# which an include is specified. Set to NO to disable this.
+
+VERBATIM_HEADERS = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
+# of all compounds will be generated. Enable this if the project
+# contains a lot of classes, structs, unions or interfaces.
+
+ALPHABETICAL_INDEX = NO
+
+# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
+# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
+# in which this list will be split (can be a number in the range [1..20])
+
+COLS_IN_ALPHA_INDEX = 5
+
+# In case all classes in a project start with a common prefix, all
+# classes will be put under the same header in the alphabetical index.
+# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
+# should be ignored while generating the index headers.
+
+IGNORE_PREFIX =
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
+# generate HTML output.
+
+GENERATE_HTML = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `html' will be used as the default path.
+
+HTML_OUTPUT = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
+# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
+# doxygen will generate files with .html extension.
+
+HTML_FILE_EXTENSION = .html
+
+# The HTML_HEADER tag can be used to specify a personal HTML header for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard header.
+
+HTML_HEADER =
+
+# The HTML_FOOTER tag can be used to specify a personal HTML footer for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard footer.
+
+HTML_FOOTER =
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
+# style sheet that is used by each HTML page. It can be used to
+# fine-tune the look of the HTML output. If the tag is left blank doxygen
+# will generate a default style sheet. Note that doxygen will try to copy
+# the style sheet file to the HTML output directory, so don't put your own
+# stylesheet in the HTML output directory as well, or it will be erased!
+
+HTML_STYLESHEET =
+
+# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes,
+# files or namespaces will be aligned in HTML using tables. If set to
+# NO a bullet list will be used.
+
+HTML_ALIGN_MEMBERS = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded. For this to work a browser that supports
+# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox
+# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
+
+HTML_DYNAMIC_SECTIONS = NO
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files
+# will be generated that can be used as input for Apple's Xcode 3
+# integrated development environment, introduced with OSX 10.5 (Leopard).
+# To create a documentation set, doxygen will generate a Makefile in the
+# HTML output directory. Running make will produce the docset in that
+# directory and running "make install" will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
+# it at startup.
+# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information.
+
+GENERATE_DOCSET = NO
+
+# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
+# feed. A documentation feed provides an umbrella under which multiple
+# documentation sets from a single provider (such as a company or product suite)
+# can be grouped.
+
+DOCSET_FEEDNAME = "Doxygen generated docs"
+
+# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
+# should uniquely identify the documentation set bundle. This should be a
+# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
+# will append .docset to the name.
+
+DOCSET_BUNDLE_ID = org.doxygen.Project
+
+# If the GENERATE_HTMLHELP tag is set to YES, additional index files
+# will be generated that can be used as input for tools like the
+# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
+# of the generated HTML documentation.
+
+GENERATE_HTMLHELP = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
+# be used to specify the file name of the resulting .chm file. You
+# can add a path in front of the file if the result should not be
+# written to the html output directory.
+
+CHM_FILE =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
+# be used to specify the location (absolute path including file name) of
+# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
+# the HTML help compiler on the generated index.hhp.
+
+HHC_LOCATION =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
+# controls if a separate .chi index file is generated (YES) or that
+# it should be included in the master .chm file (NO).
+
+GENERATE_CHI = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
+# is used to encode HtmlHelp index (hhk), content (hhc) and project file
+# content.
+
+CHM_INDEX_ENCODING =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
+# controls whether a binary table of contents is generated (YES) or a
+# normal table of contents (NO) in the .chm file.
+
+BINARY_TOC = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members
+# to the contents of the HTML help documentation and to the tree view.
+
+TOC_EXPAND = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER
+# are set, an additional index file will be generated that can be used as input for
+# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated
+# HTML documentation.
+
+GENERATE_QHP = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
+# be used to specify the file name of the resulting .qch file.
+# The path specified is relative to the HTML output folder.
+
+QCH_FILE =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#namespace
+
+QHP_NAMESPACE =
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+
+QHP_VIRTUAL_FOLDER = doc
+
+# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add.
+# For more information please see
+# http://doc.trolltech.com/qthelpproject.html#custom-filters
+
+QHP_CUST_FILTER_NAME =
+
+# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see
+# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">Qt Help Project / Custom Filters</a>.
+
+QHP_CUST_FILTER_ATTRS =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's
+# filter section matches.
+# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">Qt Help Project / Filter Attributes</a>.
+
+QHP_SECT_FILTER_ATTRS =
+
+# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
+# be used to specify the location of Qt's qhelpgenerator.
+# If non-empty doxygen will try to run qhelpgenerator on the generated
+# .qhp file.
+
+QHG_LOCATION =
+
+# The DISABLE_INDEX tag can be used to turn on/off the condensed index at
+# top of each HTML page. The value NO (the default) enables the index and
+# the value YES disables it.
+
+DISABLE_INDEX = NO
+
+# This tag can be used to set the number of enum values (range [1..20])
+# that doxygen will group on one line in the generated HTML documentation.
+
+ENUM_VALUES_PER_LINE = 4
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information.
+# If the tag value is set to YES, a side panel will be generated
+# containing a tree-like index structure (just like the one that
+# is generated for HTML Help). For this to work a browser that supports
+# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
+# Windows users are probably better off using the HTML help feature.
+
+GENERATE_TREEVIEW = YES
+
+# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories,
+# and Class Hierarchy pages using a tree view instead of an ordered list.
+
+USE_INLINE_TREES = NO
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
+# used to set the initial width (in pixels) of the frame in which the tree
+# is shown.
+
+TREEVIEW_WIDTH = 250
+
+# Use this tag to change the font size of Latex formulas included
+# as images in the HTML documentation. The default is 10. Note that
+# when you change the font size after a successful doxygen run you need
+# to manually remove any form_*.png images from the HTML output directory
+# to force them to be regenerated.
+
+FORMULA_FONTSIZE = 10
+
+# When the SEARCHENGINE tag is enable doxygen will generate a search box for the HTML output. The underlying search engine uses javascript
+# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP) or Qt help (GENERATE_QHP)
+# there is already a search function so this one should typically
+# be disabled.
+
+SEARCHENGINE = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
+# generate Latex output.
+
+GENERATE_LATEX = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked. If left blank `latex' will be used as the default command name.
+
+LATEX_CMD_NAME = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
+# generate index for LaTeX. If left blank `makeindex' will be used as the
+# default command name.
+
+MAKEINDEX_CMD_NAME = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
+# LaTeX documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_LATEX = YES
+
+# The PAPER_TYPE tag can be used to set the paper type that is used
+# by the printer. Possible values are: a4, a4wide, letter, legal and
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE = a4wide
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES = amsmath
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
+# the generated latex document. The header should contain everything until
+# the first chapter. If it is left blank doxygen will generate a
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will
+# contain links (just like the HTML output) instead of page references
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS = YES
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
+# plain latex in the generated Makefile. Set this option to YES to get a
+# higher quality PDF documentation.
+
+USE_PDFLATEX = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
+# command to the generated LaTeX files. This will instruct LaTeX to keep
+# running if errors occur, instead of asking the user for help.
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not
+# include the index chapters (such as File Index, Compound Index, etc.)
+# in the output.
+
+LATEX_HIDE_INDICES = YES
+
+# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER.
+
+LATEX_SOURCE_CODE = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
+# The RTF output is optimized for Word 97 and may not look very pretty with
+# other RTF readers or editors.
+
+GENERATE_RTF = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `rtf' will be used as the default path.
+
+RTF_OUTPUT = rtf
+
+# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
+# RTF documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_RTF = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
+# will contain hyperlink fields. The RTF file will
+# contain links (just like the HTML output) instead of page references.
+# This makes the output suitable for online browsing using WORD or other
+# programs which support those fields.
+# Note: wordpad (write) and others do not support links.
+
+RTF_HYPERLINKS = NO
+
+# Load stylesheet definitions from file. Syntax is similar to doxygen's
+# config file, i.e. a series of assignments. You only have to provide
+# replacements, missing definitions are set to their default value.
+
+RTF_STYLESHEET_FILE =
+
+# Set optional variables used in the generation of an rtf document.
+# Syntax is similar to doxygen's config file.
+
+RTF_EXTENSIONS_FILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
+# generate man pages
+
+GENERATE_MAN = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `man' will be used as the default path.
+
+MAN_OUTPUT = man
+
+# The MAN_EXTENSION tag determines the extension that is added to
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION = .3
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
+# then it will generate one additional man file for each entity
+# documented in the real man page(s). These additional files
+# only source the real man page, but without them the man command
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES Doxygen will
+# generate an XML file that captures the structure of
+# the code including all documentation.
+
+GENERATE_XML = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `xml' will be used as the default path.
+
+XML_OUTPUT = xml
+
+# The XML_SCHEMA tag can be used to specify an XML schema,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_SCHEMA =
+
+# The XML_DTD tag can be used to specify an XML DTD,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_DTD =
+
+# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
+# dump the program listings (including syntax highlighting
+# and cross-referencing information) to the XML output. Note that
+# enabling this will significantly increase the size of the XML output.
+
+XML_PROGRAMLISTING = YES
+
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
+# generate an AutoGen Definitions (see autogen.sf.net) file
+# that captures the structure of the code including all
+# documentation. Note that this feature is still experimental
+# and incomplete at the moment.
+
+GENERATE_AUTOGEN_DEF = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES Doxygen will
+# generate a Perl module file that captures the structure of
+# the code including all documentation. Note that this
+# feature is still experimental and incomplete at the
+# moment.
+
+GENERATE_PERLMOD = NO
+
+# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
+# the necessary Makefile rules, Perl scripts and LaTeX code to be able
+# to generate PDF and DVI output from the Perl module output.
+
+PERLMOD_LATEX = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
+# nicely formatted so it can be parsed by a human reader.
+# This is useful
+# if you want to understand what is going on.
+# On the other hand, if this
+# tag is set to NO the size of the Perl module output will be much smaller
+# and Perl will parse it just the same.
+
+PERLMOD_PRETTY = YES
+
+# The names of the make variables in the generated doxyrules.make file
+# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
+# This is useful so different doxyrules.make files included by the same
+# Makefile don't overwrite each other's variables.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
+# evaluate all C-preprocessor directives found in the sources and include
+# files.
+
+ENABLE_PREPROCESSING = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
+# names in the source code. If set to NO (the default) only conditional
+# compilation will be performed. Macro expansion can be done in a controlled
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION = YES
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
+# then the macro expansion is limited to the macros specified with the
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF = YES
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
+# in the INCLUDE_PATH (see below) will be search if a #include is found.
+
+SEARCH_INCLUDES = NO
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by
+# the preprocessor.
+
+INCLUDE_PATH = /usr/include /opt/local/include
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will
+# be used.
+
+INCLUDE_FILE_PATTERNS =
+
+# The PREDEFINED tag can be used to specify one or more macro names that
+# are defined before the preprocessor is started (similar to the -D option of
+# gcc). The argument of the tag is a list of macros of the form: name
+# or name=definition (no spaces). If the definition and the = are
+# omitted =1 is assumed. To prevent a macro definition from being
+# undefined via #undef or recursively expanded use the := operator
+# instead of the = operator.
+
+PREDEFINED =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
+# this tag can be used to specify a list of macro names that should be expanded.
+# The macro definition that is found in the sources will be used.
+# Use the PREDEFINED tag if you want to use a different macro definition.
+
+EXPAND_AS_DEFINED =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
+# doxygen's preprocessor will remove all function-like macros that are alone
+# on a line, have an all uppercase name, and do not end with a semicolon. Such
+# function macros are typically used for boiler-plate code, and will confuse
+# the parser if not removed.
+
+SKIP_FUNCTION_MACROS = YES
+
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES option can be used to specify one or more tagfiles.
+# Optionally an initial location of the external documentation
+# can be added for each tagfile. The format of a tag file without
+# this location is as follows:
+#
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+#
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where "loc1" and "loc2" can be relative or absolute paths or
+# URLs. If a location is present for each tag, the installdox tool
+# does not have to be run to correct the links.
+# Note that each tag file must have a unique name
+# (where the name does NOT include the path)
+# If a tag file is not located in the directory in which doxygen
+# is run, you must also specify the path to the tagfile here.
+
+TAGFILES =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create
+# a tag file that is based on the input files it reads.
+
+GENERATE_TAGFILE =
+
+# If the ALLEXTERNALS tag is set to YES all external classes will be listed
+# in the class index. If set to NO only the inherited external classes
+# will be listed.
+
+ALLEXTERNALS = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will
+# be listed.
+
+EXTERNAL_GROUPS = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of `which perl').
+
+PERL_PATH = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
+# or super classes. Setting the tag to NO turns the diagrams off. Note that
+# this option is superseded by the HAVE_DOT option below. This is only a
+# fallback. It is recommended to install and use dot, since it yields more
+# powerful graphs.
+
+CLASS_DIAGRAMS = YES
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see
+# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH =
+
+# If set to YES, the inheritance and collaboration graphs will hide
+# inheritance and usage relations if the target is undocumented
+# or is not a class.
+
+HIDE_UNDOC_RELATIONS = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz, a graph visualization
+# toolkit from AT&T and Lucent Bell Labs. The other options in this section
+# have no effect if this option is set to NO (the default)
+
+HAVE_DOT = YES
+
+# By default doxygen will write a font called FreeSans.ttf to the output
+# directory and reference it in all dot files that doxygen generates. This
+# font does not include all possible unicode characters however, so when you need
+# these (or just want a differently looking font) you can specify the font name
+# using DOT_FONTNAME. You need need to make sure dot is able to find the font,
+# which can be done by putting it in a standard location or by setting the
+# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory
+# containing the font.
+
+DOT_FONTNAME = FreeSans
+
+# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
+# The default size is 10pt.
+
+DOT_FONTSIZE = 10
+
+# By default doxygen will tell dot to use the output directory to look for the
+# FreeSans.ttf font (which doxygen will put there itself). If you specify a
+# different font using DOT_FONTNAME you can set the path where dot
+# can find it using this tag.
+
+DOT_FONTPATH =
+
+# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect inheritance relations. Setting this tag to YES will force the
+# the CLASS_DIAGRAMS tag to NO.
+
+CLASS_GRAPH = YES
+
+# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect implementation dependencies (inheritance, containment, and
+# class references variables) of the class with other documented classes.
+
+COLLABORATION_GRAPH = YES
+
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+
+UML_LOOK = YES
+
+# If set to YES, the inheritance and collaboration graphs will show the
+# relations between templates and their instances.
+
+TEMPLATE_RELATIONS = NO
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
+# tags are set to YES then doxygen will generate a graph for each documented
+# file showing the direct and indirect include dependencies of the file with
+# other documented files.
+
+INCLUDE_GRAPH = YES
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
+# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
+# documented header file showing the documented files that directly or
+# indirectly include this file.
+
+INCLUDED_BY_GRAPH = YES
+
+# If the CALL_GRAPH and HAVE_DOT options are set to YES then
+# doxygen will generate a call dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable call graphs
+# for selected functions only using the \callgraph command.
+
+CALL_GRAPH = YES
+
+# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
+# doxygen will generate a caller dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable caller
+# graphs for selected functions only using the \callergraph command.
+
+CALLER_GRAPH = YES
+
+# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
+# will graphical hierarchy of all classes instead of a textual one.
+
+GRAPHICAL_HIERARCHY = YES
+
+# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES
+# then doxygen will show the dependencies a directory has on other directories
+# in a graphical way. The dependency relations are determined by the #include
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. Possible values are png, jpg, or gif
+# If left blank png will be used.
+
+DOT_IMAGE_FORMAT = png
+
+# The tag DOT_PATH can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+
+DOT_PATH =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the
+# \dotfile command).
+
+DOTFILE_DIRS =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
+# nodes that will be shown in the graph. If the number of nodes in a graph
+# becomes larger than this value, doxygen will truncate the graph, which is
+# visualized by representing a node as a red box. Note that doxygen if the
+# number of direct children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
+# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+
+DOT_GRAPH_MAX_NODES = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
+# graphs generated by dot. A depth value of 3 means that only nodes reachable
+# from the root by following a path via at most 3 edges will be shown. Nodes
+# that lay further from the root node will be omitted. Note that setting this
+# option to 1 or 2 may greatly reduce the computation time needed for large
+# code bases. Also note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+
+MAX_DOT_GRAPH_DEPTH = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not
+# seem to support this out of the box. Warning: Depending on the platform used,
+# enabling this option may lead to badly anti-aliased labels on the edges of
+# a graph (i.e. they become hard to read).
+
+DOT_TRANSPARENT = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10)
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS = NO
+
+# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
+# generate a legend page explaining the meaning of the various boxes and
+# arrows in the dot generated graphs.
+
+GENERATE_LEGEND = YES
+
+# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
+# remove the intermediate dot files that are used to generate
+# the various graphs.
+
+DOT_CLEANUP = YES
diff --git a/nsync/doc/doxygen_boost_dummy.h b/nsync/doc/doxygen_boost_dummy.h
new file mode 100644
index 0000000..2a01c27
--- /dev/null
+++ b/nsync/doc/doxygen_boost_dummy.h
@@ -0,0 +1,10 @@
+namespace boost {
+ template<class T> class shared_ptr { T *ptr; };
+ template<class T> class weak_ptr { T *ptr; };
+}
+
+namespace Sync {
+ struct DiffStateContainer { DiffState *multi_index_container; };
+ struct LeafContainer { Leaf *multi_index_container; }
+ struct CcnxWrapperPtr { CcnxWrapper *ptr; }
+}
diff --git a/nsync/log4cxx.properties b/nsync/log4cxx.properties
new file mode 100644
index 0000000..6252595
--- /dev/null
+++ b/nsync/log4cxx.properties
@@ -0,0 +1,22 @@
+# Set root logger level to DEBUG and its only appender to A1.
+log4j.rootLogger=ERROR, A1
+
+# A1 is set to be a ConsoleAppender.
+log4j.appender.A1=org.apache.log4j.ConsoleAppender
+
+# A1 uses PatternLayout.
+log4j.appender.A1.layout=org.apache.log4j.PatternLayout
+log4j.appender.A1.target=System.err
+#log4j.appender.A1.layout.ConversionPattern=%d{dd-MMM HH:MM:SS,SSS} %p %c %m%n
+#log4j.appender.A1.layout.ConversionPattern=%d{hh:mm:ss,SSS} %-14t %-14c %m%n
+log4j.appender.A1.layout.ConversionPattern=%d{ss,SSS} %-12c %m%n
+
+log4j.logger.SyncLogic = TRACE
+log4j.logger.SyncPolicyManager = DEBUG
+#log4j.logger.SyncInterestTable = TRACE
+#log4j.logger.AppDataFetch = TRACE
+log4j.logger.Test = TRACE
+#log4j.logger.bgpparser=TRACE
+#log4j.logger.bgpparser.AttributeType=ERROR
+#log4j.logger.bgpparser.MRTCommonHeader=ERROR
+
diff --git a/nsync/nsync.pc.in b/nsync/nsync.pc.in
new file mode 100644
index 0000000..2ed522c
--- /dev/null
+++ b/nsync/nsync.pc.in
@@ -0,0 +1,10 @@
+prefix=@PREFIX@
+libdir=@LIBDIR@
+includedir=@INCLUDEDIR@
+
+Name: nsync
+Description: nsync library
+Version: @VERSION@
+Libs: -L${libdir} -lnsync
+Cflags: -I${includedir}
+
diff --git a/nsync/src/sync-diff-leaf.cc b/nsync/src/sync-diff-leaf.cc
new file mode 100644
index 0000000..bdbbd1b
--- /dev/null
+++ b/nsync/src/sync-diff-leaf.cc
@@ -0,0 +1,74 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include "sync-diff-leaf.h"
+#include <boost/throw_exception.hpp>
+typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info;
+
+using namespace Sync::Error;
+
+namespace Sync {
+
+DiffLeaf::DiffLeaf (NameInfoConstPtr info, const SeqNo &seq)
+ : Leaf (info, seq)
+ , m_op (UPDATE)
+{
+}
+
+DiffLeaf::DiffLeaf (NameInfoConstPtr info)
+ : Leaf (info, SeqNo (0,0))
+ , m_op (REMOVE)
+{
+}
+
+std::ostream &
+operator << (std::ostream &os, Operation op)
+{
+ switch (op)
+ {
+ case UPDATE:
+ os << "update";
+ break;
+ case REMOVE:
+ os << "remove";
+ break;
+ }
+ return os;
+}
+
+std::istream &
+operator >> (std::istream &is, Operation &op)
+{
+ std::string operation;
+ is >> operation;
+ if (operation == "update")
+ op = UPDATE;
+ else if (operation == "remove")
+ op = REMOVE;
+ else
+ BOOST_THROW_EXCEPTION (SyncDiffLeafOperationParseError () << errmsg_info (operation));
+
+ return is;
+}
+
+
+}
diff --git a/nsync/src/sync-diff-leaf.h b/nsync/src/sync-diff-leaf.h
new file mode 100644
index 0000000..6e09efe
--- /dev/null
+++ b/nsync/src/sync-diff-leaf.h
@@ -0,0 +1,91 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_DIFF_LEAF_H
+#define SYNC_DIFF_LEAF_H
+
+#include "sync-leaf.h"
+#include <boost/exception/all.hpp>
+
+namespace Sync {
+
+/**
+ * @ingroup sync
+ * @brief Annotation for SYNC leaf
+ */
+enum Operation
+ {
+ UPDATE, ///< @brief Leaf was added or updated
+ REMOVE ///< @brief Leaf was removed
+ };
+
+/**
+ * @ingroup sync
+ * @brief Annotated SYNC leaf
+ */
+class DiffLeaf : public Leaf
+{
+public:
+ /**
+ * @brief Constructor to create an UPDATE diff leaf
+ * @param info Smart pointer to leaf's name
+ * @param seq Initial sequence number of the pointer
+ */
+ DiffLeaf (NameInfoConstPtr info, const SeqNo &seq);
+
+ /**
+ * @brief Constructor to create an REMOVE diff leaf
+ * @param info Smart pointer to leaf's name
+ *
+ * This constructor creates a leaf with phony sequence number
+ * with 0 session ID and 0 sequence number
+ */
+ DiffLeaf (NameInfoConstPtr info);
+
+ virtual ~DiffLeaf () { }
+
+ /**
+ * @brief Get diff leaf type
+ */
+ Operation
+ getOperation () const { return m_op; }
+
+private:
+ Operation m_op;
+};
+
+typedef boost::shared_ptr<DiffLeaf> DiffLeafPtr;
+typedef boost::shared_ptr<const DiffLeaf> DiffLeafConstPtr;
+
+std::ostream &
+operator << (std::ostream &os, Operation op);
+
+std::istream &
+operator >> (std::istream &is, Operation &op);
+
+namespace Error {
+struct SyncDiffLeafOperationParseError : virtual boost::exception, virtual std::exception { };
+} // Error
+
+} // Sync
+
+#endif // SYNC_DIFF_LEAF_H
diff --git a/nsync/src/sync-diff-state-container.h b/nsync/src/sync-diff-state-container.h
new file mode 100644
index 0000000..2ae7c59
--- /dev/null
+++ b/nsync/src/sync-diff-state-container.h
@@ -0,0 +1,72 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_DIFF_STATE_CONTAINER_H
+#define SYNC_DIFF_STATE_CONTAINER_H
+
+#include "sync-diff-state.h"
+#include "sync-digest.h"
+
+#include <boost/multi_index_container.hpp>
+#include <boost/multi_index/tag.hpp>
+// #include <boost/multi_index/ordered_index.hpp>
+// #include <boost/multi_index/composite_key.hpp>
+#include <boost/multi_index/hashed_index.hpp>
+#include <boost/multi_index/sequenced_index.hpp>
+// #include <boost/multi_index/random_access_index.hpp>
+#include <boost/multi_index/member.hpp>
+#include <boost/multi_index/mem_fun.hpp>
+
+namespace mi = boost::multi_index;
+
+namespace Sync {
+
+/// @cond include_hidden
+struct sequenced { };
+struct timed { };
+/// @endcond
+
+/**
+ * \ingroup sync
+ * @brief Container for differential states
+ */
+struct DiffStateContainer : public mi::multi_index_container<
+ DiffStatePtr,
+ mi::indexed_by<
+ // For fast access to elements using DiffState hashes
+ mi::hashed_unique<
+ mi::tag<hashed>,
+ mi::const_mem_fun<DiffState, DigestConstPtr, &DiffState::getDigest>,
+ DigestPtrHash,
+ DigestPtrEqual
+ >
+ ,
+ // sequenced index to access older/newer element (like in list)
+ mi::sequenced<mi::tag<sequenced> >
+ >
+ >
+{
+};
+
+} // Sync
+
+#endif // SYNC_DIFF_STATE_CONTAINER_H
diff --git a/nsync/src/sync-diff-state.cc b/nsync/src/sync-diff-state.cc
new file mode 100644
index 0000000..3030940
--- /dev/null
+++ b/nsync/src/sync-diff-state.cc
@@ -0,0 +1,101 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include "sync-diff-state.h"
+#include "sync-diff-leaf.h"
+
+#include <boost/make_shared.hpp>
+#include <boost/foreach.hpp>
+#include <boost/assert.hpp>
+
+using namespace boost;
+
+namespace Sync {
+
+DiffState::DiffState ()
+{
+}
+
+DiffState::~DiffState ()
+{
+}
+
+DiffStatePtr
+DiffState::diff () const
+{
+ DiffStatePtr ret = make_shared<DiffState> ();
+
+ DiffStatePtr state = m_next;
+ while (state != 0)
+ {
+ *ret += *state;
+ state = state->m_next;
+ }
+
+ return ret;
+}
+
+DiffState &
+DiffState::operator += (const DiffState &state)
+{
+ BOOST_FOREACH (LeafConstPtr _leaf, state.getLeaves ())
+ {
+ DiffLeafConstPtr leaf = dynamic_pointer_cast<const DiffLeaf> (_leaf);
+ BOOST_ASSERT (leaf != 0);
+
+ if (leaf->getOperation () == UPDATE)
+ update (leaf->getInfo (), leaf->getSeq ());
+ else if (leaf->getOperation () == REMOVE)
+ remove (leaf->getInfo ());
+ else
+ {
+ BOOST_ASSERT (false);
+ }
+ }
+
+ return *this;
+}
+
+// from State
+boost::tuple<bool/*inserted*/, bool/*updated*/, SeqNo/*oldSeqNo*/>
+DiffState::update (NameInfoConstPtr info, const SeqNo &seq)
+{
+ m_leaves.erase (info);
+
+ DiffLeafPtr leaf = make_shared<DiffLeaf> (info, cref (seq));
+ m_leaves.insert (leaf);
+
+ return make_tuple (true, false, SeqNo ());
+}
+
+bool
+DiffState::remove (NameInfoConstPtr info)
+{
+ m_leaves.erase (info);
+
+ DiffLeafPtr leaf = make_shared<DiffLeaf> (info);
+ m_leaves.insert (leaf);
+
+ return true;
+}
+
+} // ns3
diff --git a/nsync/src/sync-diff-state.h b/nsync/src/sync-diff-state.h
new file mode 100644
index 0000000..d944c3e
--- /dev/null
+++ b/nsync/src/sync-diff-state.h
@@ -0,0 +1,102 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_DIFF_STATE_H
+#define SYNC_DIFF_STATE_H
+
+#include "sync-state.h"
+#include <iostream>
+
+namespace Sync {
+
+class DiffState;
+typedef boost::shared_ptr<DiffState> DiffStatePtr;
+typedef boost::shared_ptr<DiffState> DiffStateConstPtr;
+
+/**
+ * @ingroup ccnx
+ * @brief Differential SYNC state
+ */
+class DiffState : public State
+{
+public:
+ /**
+ * @see Default constructor
+ */
+ DiffState ();
+ virtual ~DiffState ();
+
+ /**
+ * @brief Set successor for the diff state
+ * @param next successor state
+ */
+ void
+ setNext (DiffStatePtr next)
+ {
+ m_next = next;
+ }
+
+ /**
+ * @brief Set digest for the diff state (obtained from a corresponding full state)
+ * @param digest A read only smart pointer to a digest object (that should be unmodified anywhere else)
+ */
+ void
+ setDigest (DigestConstPtr digest) { m_digest = digest; }
+
+ /**
+ * @brief Get digest for the diff state
+ */
+ DigestConstPtr
+ getDigest () const { return m_digest; }
+
+ /**
+ * @brief Accumulate differences from `this' state to the most current state
+ * @returns Accumulated differences from `this' state to the most current state
+ */
+ DiffStatePtr
+ diff () const;
+
+ /**
+ * @brief Combine differences from `this' and `state'
+ * @param state Differential state to combine with
+ * @return Combined differences
+ *
+ * In case of collisions, `this' leaf will be replaced with the leaf of `state'
+ */
+ DiffState&
+ operator += (const DiffState &state);
+
+ // from State
+ virtual boost::tuple<bool/*inserted*/, bool/*updated*/, SeqNo/*oldSeqNo*/>
+ update (NameInfoConstPtr info, const SeqNo &seq);
+
+ virtual bool
+ remove (NameInfoConstPtr info);
+
+private:
+ DiffStatePtr m_next;
+ DigestConstPtr m_digest;
+};
+
+} // Sync
+
+#endif // SYNC_DIFF_STATE_H
diff --git a/nsync/src/sync-digest.cc b/nsync/src/sync-digest.cc
new file mode 100644
index 0000000..6f41d3d
--- /dev/null
+++ b/nsync/src/sync-digest.cc
@@ -0,0 +1,265 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include "sync-digest.h"
+#include <string.h>
+
+#include <boost/assert.hpp>
+#include <boost/throw_exception.hpp>
+typedef boost::error_info<struct tag_errmsg, std::string> errmsg_info_str;
+typedef boost::error_info<struct tag_errmsg, int> errmsg_info_int;
+
+// for printing, may be disabled in optimized build
+
+// #ifdef DIGEST_BASE64
+// #include <boost/archive/iterators/base64_from_binary.hpp>
+// #include <boost/archive/iterators/binary_from_base64.hpp>
+// #endif
+
+#include <boost/archive/iterators/transform_width.hpp>
+#include <boost/iterator/transform_iterator.hpp>
+#include <boost/archive/iterators/dataflow_exception.hpp>
+
+using namespace boost;
+using namespace boost::archive::iterators;
+using namespace std;
+
+// Other options: VP_md2, EVP_md5, EVP_sha, EVP_sha1, EVP_sha256, EVP_dss, EVP_dss1, EVP_mdc2, EVP_ripemd160
+#define HASH_FUNCTION EVP_sha256
+#define HASH_FUNCTION_LEN 32
+
+
+// #ifndef DIGEST_BASE64
+
+template<class CharType>
+struct hex_from_4_bit
+{
+ typedef CharType result_type;
+ CharType operator () (CharType ch) const
+ {
+ const char *lookup_table = "0123456789abcdef";
+ // cout << "New character: " << (int) ch << " (" << (char) ch << ")" << "\n";
+ BOOST_ASSERT (ch < 16);
+ return lookup_table[static_cast<size_t>(ch)];
+ }
+};
+
+typedef transform_iterator<hex_from_4_bit<std::vector<uint8_t>::const_iterator::value_type>,
+ transform_width<std::vector<uint8_t>::const_iterator, 4, 8, std::vector<uint8_t>::const_iterator::value_type> > string_from_binary;
+
+
+template<class CharType>
+struct hex_to_4_bit
+{
+ typedef CharType result_type;
+ CharType operator () (CharType ch) const
+ {
+ const signed char lookup_table [] = {
+ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1,
+ -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+ -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
+ };
+
+ // cout << "New character: " << hex << (int) ch << " (" << (char) ch << ")" << "\n";
+ signed char value = -1;
+ if ((unsigned)ch < 128)
+ value = lookup_table [(unsigned)ch];
+ if (value == -1)
+ BOOST_THROW_EXCEPTION (Sync::Error::DigestCalculationError () << errmsg_info_int ((int)ch));
+
+ return value;
+ }
+};
+
+typedef transform_width<transform_iterator<hex_to_4_bit<string::const_iterator::value_type>, string::const_iterator>, 8, 4> string_to_binary;
+
+namespace Sync {
+
+Digest::Digest ()
+{
+ m_context = EVP_MD_CTX_create ();
+
+ reset ();
+}
+
+Digest::~Digest ()
+{
+ EVP_MD_CTX_destroy (m_context);
+}
+
+bool
+Digest::empty () const
+{
+ return m_buffer.empty ();
+}
+
+bool
+Digest::isZero () const
+{
+ if (m_buffer.empty ())
+ BOOST_THROW_EXCEPTION (Error::DigestCalculationError ()
+ << errmsg_info_str ("Digest has not been yet finalized"));
+
+ return (m_buffer.size () == 1 && m_buffer[0] == 0);
+}
+
+
+void
+Digest::reset ()
+{
+ m_buffer.clear ();
+
+ int ok = EVP_DigestInit_ex (m_context, HASH_FUNCTION (), 0);
+ if (!ok)
+ BOOST_THROW_EXCEPTION (Error::DigestCalculationError ()
+ << errmsg_info_str ("EVP_DigestInit_ex returned error")
+ << errmsg_info_int (ok));
+}
+
+
+void
+Digest::finalize ()
+{
+ if (!m_buffer.empty ()) return;
+
+ m_buffer.resize (HASH_FUNCTION_LEN);
+
+ unsigned int tmp;
+ int ok = EVP_DigestFinal_ex (m_context,
+ &m_buffer[0], &tmp);
+ if (!ok)
+ BOOST_THROW_EXCEPTION (Error::DigestCalculationError ()
+ << errmsg_info_str ("EVP_DigestFinal_ex returned error")
+ << errmsg_info_int (ok));
+}
+
+std::size_t
+Digest::getHash () const
+{
+ if (isZero ()) return 0;
+
+ if (sizeof (std::size_t) > m_buffer.size ())
+ {
+ BOOST_THROW_EXCEPTION (Error::DigestCalculationError ()
+ << errmsg_info_str ("Hash is not zero and length is less than size_t")
+ << errmsg_info_int (m_buffer.size ()));
+ }
+
+ // just getting first sizeof(std::size_t) bytes
+ // not ideal, but should work pretty well
+ return *(reinterpret_cast<const std::size_t*> (&m_buffer[0]));
+}
+
+bool
+Digest::operator == (const Digest &digest) const
+{
+ if (m_buffer.empty ())
+ BOOST_THROW_EXCEPTION (Error::DigestCalculationError ()
+ << errmsg_info_str ("Digest1 is empty"));
+
+ if (digest.m_buffer.empty ())
+ BOOST_THROW_EXCEPTION (Error::DigestCalculationError ()
+ << errmsg_info_str ("Digest2 is empty"));
+
+ return m_buffer == digest.m_buffer;
+}
+
+
+void
+Digest::update (const uint8_t *buffer, size_t size)
+{
+ // cout << "Update: " << (void*)buffer << " / size: " << size << "\n";
+
+ // cannot update Digest when it has been finalized
+ if (!m_buffer.empty ())
+ BOOST_THROW_EXCEPTION (Error::DigestCalculationError ()
+ << errmsg_info_str ("Digest has been already finalized"));
+
+ bool ok = EVP_DigestUpdate (m_context, buffer, size);
+ if (!ok)
+ BOOST_THROW_EXCEPTION (Error::DigestCalculationError ()
+ << errmsg_info_str ("EVP_DigestUpdate returned error")
+ << errmsg_info_int (ok));
+}
+
+
+Digest &
+Digest::operator << (const Digest &src)
+{
+ if (src.m_buffer.empty ())
+ BOOST_THROW_EXCEPTION (Error::DigestCalculationError ()
+ << errmsg_info_str ("Digest has not been yet finalized"));
+
+ update (&src.m_buffer[0], src.m_buffer.size ());
+
+ return *this;
+}
+
+std::ostream &
+operator << (std::ostream &os, const Digest &digest)
+{
+ BOOST_ASSERT (!digest.m_buffer.empty ());
+
+ ostreambuf_iterator<char> out_it (os); // ostream iterator
+ // need to encode to base64
+ copy (string_from_binary (digest.m_buffer.begin ()),
+ string_from_binary (digest.m_buffer.end ()),
+ out_it);
+
+ return os;
+}
+
+std::istream &
+operator >> (std::istream &is, Digest &digest)
+{
+ string str;
+ is >> str; // read string first
+
+ if (str.size () == 0)
+ BOOST_THROW_EXCEPTION (Error::DigestCalculationError ()
+ << errmsg_info_str ("Input is empty"));
+
+ // uint8_t padding = (3 - str.size () % 3) % 3;
+ // for (uint8_t i = 0; i < padding; i++) str.push_back ('=');
+
+ // only empty digest object can be used for reading
+ if (!digest.m_buffer.empty ())
+ BOOST_THROW_EXCEPTION (Error::DigestCalculationError ()
+ << errmsg_info_str ("Digest has been already finalized"));
+
+ digest.m_buffer.clear ();
+
+ copy (string_to_binary (str.begin ()),
+ string_to_binary (str.end ()),
+ std::back_inserter (digest.m_buffer));
+
+ return is;
+}
+
+
+} // Sync
+
diff --git a/nsync/src/sync-digest.h b/nsync/src/sync-digest.h
new file mode 100644
index 0000000..ecc8522
--- /dev/null
+++ b/nsync/src/sync-digest.h
@@ -0,0 +1,199 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_DIGEST_H
+#define SYNC_DIGEST_H
+
+#include <boost/exception/all.hpp>
+#include <openssl/evp.h>
+#include <boost/cstdint.hpp>
+#include <vector>
+
+namespace Sync {
+
+/**
+ * @ingroup sync
+ * @brief A simple wrapper for libcrypto hash functions
+ */
+class Digest
+{
+public:
+ /**
+ * @brief Default constructor. Will initialize internal libssl structures
+ */
+ Digest ();
+
+ /**
+ * @brief Check if digest is empty
+ */
+ bool
+ empty () const;
+
+ /**
+ * @brief Reset digest to the initial state
+ */
+ void
+ reset ();
+
+ /**
+ * @brief Destructor
+ */
+ ~Digest ();
+
+ /**
+ * @brief Obtain a short version of the hash (just first sizeof(size_t) bytes
+ *
+ * Side effect: finalize() will be called on `this'
+ */
+ std::size_t
+ getHash () const;
+
+ /**
+ * @brief Finalize digest. All subsequent calls to "operator <<" will fire an exception
+ */
+ void
+ finalize ();
+
+ /**
+ * @brief Compare two full digests
+ *
+ * Side effect: Finalize will be called on `this' and `digest'
+ */
+ bool
+ operator == (const Digest &digest) const;
+
+ bool
+ operator != (const Digest &digest) const
+ { return ! (*this == digest); }
+
+
+ /**
+ * @brief Add existing digest to digest calculation
+ * @param src digest to combine with
+ *
+ * The result of this combination is hash (hash (...))
+ */
+ Digest &
+ operator << (const Digest &src);
+
+ /**
+ * @brief Add string to digest calculation
+ * @param str string to put into digest
+ */
+ inline Digest &
+ operator << (const std::string &str);
+
+ /**
+ * @brief Add uint64_t value to digest calculation
+ * @param value uint64_t value to put into digest
+ */
+ inline Digest &
+ operator << (uint64_t value);
+
+ /**
+ * @brief Checks if the stored hash is zero-root hash
+ *
+ * Zero-root hash is a valid hash that optimally represents an empty state
+ */
+ bool
+ isZero () const;
+
+private:
+ Digest &
+ operator = (Digest &digest) { (void)digest; return *this; }
+
+ /**
+ * @brief Add size bytes of buffer to the hash
+ */
+ void
+ update (const uint8_t *buffer, size_t size);
+
+ friend std::ostream &
+ operator << (std::ostream &os, const Digest &digest);
+
+ friend std::istream &
+ operator >> (std::istream &is, Digest &digest);
+
+private:
+ EVP_MD_CTX *m_context;
+ std::vector<uint8_t> m_buffer;
+};
+
+namespace Error {
+struct DigestCalculationError : virtual boost::exception, virtual std::exception { };
+}
+
+typedef boost::shared_ptr<Digest> DigestPtr;
+typedef boost::shared_ptr<const Digest> DigestConstPtr;
+
+Digest &
+Digest::operator << (const std::string &str)
+{
+ update (reinterpret_cast<const uint8_t*> (str.c_str ()), str.size ());
+ return *this;
+}
+
+inline Digest &
+Digest::operator << (uint64_t value)
+{
+ update (reinterpret_cast<const uint8_t*> (&value), sizeof (uint64_t));
+ return *this;
+}
+
+std::ostream &
+operator << (std::ostream &os, const Digest &digest);
+
+std::istream &
+operator >> (std::istream &is, Digest &digest);
+
+// template<class INT>
+// Digest &
+// Digest::operator << (INT value)
+// {
+// update (&value, sizeof (INT));
+// return *this;
+// }
+
+struct DigestPtrHash : public std::unary_function<Digest, std::size_t>
+{
+ std::size_t
+ operator() (DigestConstPtr digest) const
+ {
+ // std::cout << "digest->getHash: " << digest->getHash () << " (" << *digest << ")" << std::endl;
+ return digest->getHash ();
+ }
+};
+
+struct DigestPtrEqual : public std::unary_function<Digest, std::size_t>
+{
+ bool
+ operator() (DigestConstPtr digest1, DigestConstPtr digest2) const
+ {
+ // std::cout << boost::cref(*digest1) << " == " << boost::cref(*digest2) << " : " << (*digest1 == *digest2) << std::endl;
+ return *digest1 == *digest2;
+ }
+};
+
+
+} // Sync
+
+#endif // SYNC_DIGEST_H
diff --git a/nsync/src/sync-event.h b/nsync/src/sync-event.h
new file mode 100644
index 0000000..7808947
--- /dev/null
+++ b/nsync/src/sync-event.h
@@ -0,0 +1,35 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_EVENT_H
+#define SYNC_EVENT_H
+
+#include <boost/function.hpp>
+
+namespace Sync
+{
+
+typedef boost::function< void ( ) > Event;
+
+} // Sync
+
+#endif // SYNC_EVENT_H
diff --git a/nsync/src/sync-full-leaf.cc b/nsync/src/sync-full-leaf.cc
new file mode 100644
index 0000000..84f96e3
--- /dev/null
+++ b/nsync/src/sync-full-leaf.cc
@@ -0,0 +1,52 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include "sync-full-leaf.h"
+#include <boost/ref.hpp>
+
+using namespace boost;
+
+namespace Sync {
+
+FullLeaf::FullLeaf (NameInfoConstPtr info, const SeqNo &seq)
+ : Leaf (info, seq)
+{
+ updateDigest ();
+}
+
+void
+FullLeaf::updateDigest ()
+{
+ m_digest.reset ();
+ m_digest << getInfo ()->getDigest () << *getSeq ().getDigest ();
+ m_digest.finalize ();
+}
+
+// from Leaf
+void
+FullLeaf::setSeq (const SeqNo &seq)
+{
+ Leaf::setSeq (seq);
+ updateDigest ();
+}
+
+} // Sync
diff --git a/nsync/src/sync-full-leaf.h b/nsync/src/sync-full-leaf.h
new file mode 100644
index 0000000..08142a6
--- /dev/null
+++ b/nsync/src/sync-full-leaf.h
@@ -0,0 +1,71 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_FULL_LEAF_H
+#define SYNC_FULL_LEAF_H
+
+#include "sync-leaf.h"
+
+namespace Sync {
+
+/**
+ * @ingroup sync
+ * @brief SYNC leaf for the full state (with support of Digest calculation)
+ */
+class FullLeaf : public Leaf
+{
+public:
+ /**
+ * @brief Constructor to create an UPDATE diff leaf
+ * @param info Smart pointer to leaf's name
+ * @param seq Initial sequence number of the pointer
+ */
+ FullLeaf (NameInfoConstPtr info, const SeqNo &seq);
+ virtual ~FullLeaf () { }
+
+ /**
+ * @brief Get hash digest of the leaf
+ *
+ * The underlying Digest object is recalculated on every update or removal
+ * (including updates of child classes)
+ */
+ const Digest &
+ getDigest () const { return m_digest; }
+
+ // from Leaf
+ virtual void
+ setSeq (const SeqNo &seq);
+
+private:
+ void
+ updateDigest ();
+
+private:
+ Digest m_digest;
+};
+
+typedef boost::shared_ptr<FullLeaf> FullLeafPtr;
+typedef boost::shared_ptr<const FullLeaf> FullLeafConstPtr;
+
+} // Sync
+
+#endif // SYNC_FULL_LEAF_H
diff --git a/nsync/src/sync-full-state.cc b/nsync/src/sync-full-state.cc
new file mode 100644
index 0000000..eb9ca4c
--- /dev/null
+++ b/nsync/src/sync-full-state.cc
@@ -0,0 +1,126 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include "sync-full-state.h"
+
+#include <boost/make_shared.hpp>
+#include <boost/lambda/lambda.hpp>
+#include <boost/lambda/bind.hpp>
+#include <boost/foreach.hpp>
+#include <boost/assert.hpp>
+
+#include "sync-full-leaf.h"
+
+using namespace boost;
+namespace ll = boost::lambda;
+
+namespace Sync {
+
+
+FullState::FullState ()
+// m_lastUpdated is initialized to "not_a_date_time" in normal lib mode and to "0" time in NS-3 mode
+{
+}
+
+FullState::~FullState ()
+{
+}
+
+ndn::time::Duration
+FullState::getTimeFromLastUpdate () const
+{
+ return ndn::time::now() - m_lastUpdated;
+}
+
+DigestConstPtr
+FullState::getDigest ()
+{
+ if (!m_digest)
+ {
+ m_digest = make_shared<Digest> ();
+ if (m_leaves.get<ordered> ().size () > 0)
+ {
+ BOOST_FOREACH (LeafConstPtr leaf, m_leaves.get<ordered> ())
+ {
+ FullLeafConstPtr fullLeaf = dynamic_pointer_cast<const FullLeaf> (leaf);
+ BOOST_ASSERT (fullLeaf != 0);
+ *m_digest << fullLeaf->getDigest ();
+ }
+ m_digest->finalize ();
+ }
+ else
+ {
+ std::istringstream is ("00"); //zero state
+ is >> *m_digest;
+ }
+ }
+
+ return m_digest;
+}
+
+// from State
+boost::tuple<bool/*inserted*/, bool/*updated*/, SeqNo/*oldSeqNo*/>
+FullState::update (NameInfoConstPtr info, const SeqNo &seq)
+{
+ m_lastUpdated = ndn::time::now();
+
+
+ m_digest.reset ();
+
+ LeafContainer::iterator item = m_leaves.find (info);
+ if (item == m_leaves.end ())
+ {
+ m_leaves.insert (make_shared<FullLeaf> (info, cref (seq)));
+ return make_tuple (true, false, SeqNo ());
+ }
+ else
+ {
+ if ((*item)->getSeq () == seq || seq < (*item)->getSeq ())
+ {
+ return make_tuple (false, false, SeqNo ());
+ }
+
+ SeqNo old = (*item)->getSeq ();
+ m_leaves.modify (item,
+ ll::bind (&Leaf::setSeq, *ll::_1, seq));
+ return make_tuple (false, true, old);
+ }
+}
+
+bool
+FullState::remove (NameInfoConstPtr info)
+{
+ m_lastUpdated = ndn::time::now();
+
+ m_digest.reset ();
+
+ LeafContainer::iterator item = m_leaves.find (info);
+ if (item != m_leaves.end ())
+ {
+ m_leaves.erase (item);
+ return true;
+ }
+ else
+ return false;
+}
+
+} // Sync
diff --git a/nsync/src/sync-full-state.h b/nsync/src/sync-full-state.h
new file mode 100644
index 0000000..28e0078
--- /dev/null
+++ b/nsync/src/sync-full-state.h
@@ -0,0 +1,79 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_FULL_STATE_H
+#define SYNC_FULL_STATE_H
+
+#include <ndn-cpp-dev/util/time.hpp>
+#include "sync-state.h"
+
+namespace Sync {
+
+class FullState;
+typedef boost::shared_ptr<FullState> FullStatePtr;
+typedef boost::shared_ptr<FullState> FullStateConstPtr;
+
+
+/**
+ * \ingroup sync
+ * @brief Cumulative SYNC state
+ */
+class FullState : public State
+{
+public:
+ /**
+ * @brief Default constructor
+ */
+ FullState ();
+ virtual ~FullState ();
+
+ /**
+ * @brief Get time period since last state update
+ *
+ * This value can be used to randomize reconciliation waiting time in SyncApp
+ */
+ ndn::time::Duration
+ getTimeFromLastUpdate () const;
+
+ /**
+ * @brief Obtain a read-only copy of the digest
+ *
+ * If m_digest is 0, then it is automatically created. On every update and removal, m_digest is reset to 0
+ */
+ DigestConstPtr
+ getDigest ();
+
+ // from State
+ virtual boost::tuple<bool/*inserted*/, bool/*updated*/, SeqNo/*oldSeqNo*/>
+ update (NameInfoConstPtr info, const SeqNo &seq);
+
+ virtual bool
+ remove (NameInfoConstPtr info);
+
+private:
+ ndn::time::Point m_lastUpdated; ///< @brief Time when state was updated last time
+ DigestPtr m_digest;
+};
+
+} // Sync
+
+#endif // SYNC_STATE_H
diff --git a/nsync/src/sync-interest-container.h b/nsync/src/sync-interest-container.h
new file mode 100644
index 0000000..742f053
--- /dev/null
+++ b/nsync/src/sync-interest-container.h
@@ -0,0 +1,99 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_INTEREST_CONTAINER_H
+#define SYNC_INTEREST_CONTAINER_H
+
+#include <ndn-cpp-dev/util/time.hpp>
+
+#include "sync-digest.h"
+
+#include <boost/multi_index_container.hpp>
+#include <boost/multi_index/tag.hpp>
+// #include <boost/multi_index/ordered_index.hpp>
+// #include <boost/multi_index/composite_key.hpp>
+#include <boost/multi_index/hashed_index.hpp>
+#include <boost/multi_index/sequenced_index.hpp>
+#include <boost/multi_index/ordered_index.hpp>
+// #include <boost/multi_index/random_access_index.hpp>
+#include <boost/multi_index/member.hpp>
+#include <boost/multi_index/mem_fun.hpp>
+
+namespace mi = boost::multi_index;
+
+namespace Sync {
+
+struct Interest
+{
+ Interest (DigestConstPtr digest, const std::string &name, bool unknown=false)
+ : m_digest (digest)
+ , m_name (name)
+ , m_time (ndn::time::now())
+ , m_unknown (unknown)
+ {
+ }
+
+ DigestConstPtr m_digest;
+ std::string m_name;
+ ndn::time::Point m_time;
+ bool m_unknown;
+};
+
+/// @cond include_hidden
+struct named { };
+struct hashed;
+struct timed;
+/// @endcond
+
+/**
+ * \ingroup sync
+ * @brief Container for interests (application PIT)
+ */
+struct InterestContainer : public mi::multi_index_container<
+ Interest,
+ mi::indexed_by<
+ mi::hashed_unique<
+ mi::tag<named>,
+ BOOST_MULTI_INDEX_MEMBER(Interest, std::string, m_name)
+ >
+ ,
+
+ mi::hashed_non_unique<
+ mi::tag<hashed>,
+ BOOST_MULTI_INDEX_MEMBER(Interest, DigestConstPtr, m_digest),
+ DigestPtrHash,
+ DigestPtrEqual
+ >
+ ,
+
+ mi::ordered_non_unique<
+ mi::tag<timed>,
+ BOOST_MULTI_INDEX_MEMBER(Interest, ndn::time::Point, m_time)
+ >
+ >
+ >
+{
+};
+
+} // Sync
+
+#endif // SYNC_INTEREST_CONTAINER_H
diff --git a/nsync/src/sync-interest-table.cc b/nsync/src/sync-interest-table.cc
new file mode 100644
index 0000000..a378950
--- /dev/null
+++ b/nsync/src/sync-interest-table.cc
@@ -0,0 +1,123 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include "sync-interest-table.h"
+#include "sync-logging.h"
+using namespace std;
+
+INIT_LOGGER ("SyncInterestTable");
+
+namespace Sync
+{
+
+SyncInterestTable::SyncInterestTable (boost::asio::io_service& io, ndn::time::Duration lifetime)
+ : m_entryLifetime (lifetime)
+ , m_scheduler(io)
+{
+ m_scheduler.schedulePeriodicEvent (ndn::time::seconds (4), ndn::time::seconds (4),
+ ndn::bind(&SyncInterestTable::expireInterests, this));
+}
+
+SyncInterestTable::~SyncInterestTable ()
+{
+}
+
+Interest
+SyncInterestTable::pop ()
+{
+ if (m_table.size () == 0)
+ BOOST_THROW_EXCEPTION (Error::InterestTableIsEmpty ());
+
+ Interest ret = *m_table.begin ();
+ m_table.erase (m_table.begin ());
+
+ return ret;
+}
+
+bool
+SyncInterestTable::insert (DigestConstPtr digest, const string &name, bool unknownState/*=false*/)
+{
+ bool existent = false;
+
+ InterestContainer::index<named>::type::iterator it = m_table.get<named> ().find (name);
+ if (it != m_table.end())
+ {
+ existent = true;
+ m_table.erase (it);
+ }
+ m_table.insert (Interest (digest, name, unknownState));
+
+ return existent;
+}
+
+uint32_t
+SyncInterestTable::size () const
+{
+ return m_table.size ();
+}
+
+bool
+SyncInterestTable::remove (const string &name)
+{
+ InterestContainer::index<named>::type::iterator item = m_table.get<named> ().find (name);
+ if (item != m_table.get<named> ().end ())
+ {
+ m_table.get<named> ().erase (name);
+ return true;
+ }
+
+ return false;
+}
+
+bool
+SyncInterestTable::remove (DigestConstPtr digest)
+{
+ InterestContainer::index<hashed>::type::iterator item = m_table.get<hashed> ().find (digest);
+ if (item != m_table.get<hashed> ().end ())
+ {
+ m_table.get<hashed> ().erase (digest); // erase all records associated with the digest
+ return true;
+ }
+ return false;
+}
+
+void SyncInterestTable::expireInterests ()
+{
+ uint32_t count = 0;
+ ndn::time::Point expireTime = ndn::time::now() - m_entryLifetime;
+
+ while (m_table.size () > 0)
+ {
+ InterestContainer::index<timed>::type::iterator item = m_table.get<timed> ().begin ();
+
+ if (item->m_time <= expireTime)
+ {
+ m_table.get<timed> ().erase (item);
+ count ++;
+ }
+ else
+ break;
+ }
+}
+
+
+}
diff --git a/nsync/src/sync-interest-table.h b/nsync/src/sync-interest-table.h
new file mode 100644
index 0000000..9b7c46b
--- /dev/null
+++ b/nsync/src/sync-interest-table.h
@@ -0,0 +1,96 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_INTEREST_TABLE_H
+#define SYNC_INTEREST_TABLE_H
+
+#include <ndn-cpp-dev/util/scheduler.hpp>
+
+#include <string>
+#include <vector>
+
+#include "sync-digest.h"
+#include "sync-interest-container.h"
+
+namespace Sync {
+
+/**
+ * \ingroup sync
+ * @brief A table to keep unanswered Sync Interest
+ * all access operation to the table should grab the
+ * mutex first
+ */
+class SyncInterestTable
+{
+public:
+ SyncInterestTable (boost::asio::io_service& io, ndn::time::Duration lifetime);
+ ~SyncInterestTable ();
+
+ /**
+ * @brief Insert an interest, if interest already exists, update the
+ * timestamp
+ */
+ bool
+ insert (DigestConstPtr interest, const std::string &name, bool unknownState=false);
+
+ /**
+ * @brief Remove interest by digest (e.g., when it was satisfied)
+ */
+ bool
+ remove (DigestConstPtr interest);
+
+ /**
+ * @brief Remove interest by name (e.g., when it was satisfied)
+ */
+ bool
+ remove (const std::string &name);
+
+ /**
+ * @brief pop a non-expired Interest from PIT
+ */
+ Interest
+ pop ();
+
+ uint32_t
+ size () const;
+
+private:
+ /**
+ * @brief periodically called to expire Interest
+ */
+ void
+ expireInterests ();
+
+private:
+ ndn::time::Duration m_entryLifetime;
+ InterestContainer m_table;
+
+ ndn::Scheduler m_scheduler;
+};
+
+namespace Error {
+struct InterestTableIsEmpty : virtual boost::exception, virtual std::exception { };
+}
+
+} // Sync
+
+#endif // SYNC_INTEREST_TABLE_H
diff --git a/nsync/src/sync-leaf.cc b/nsync/src/sync-leaf.cc
new file mode 100644
index 0000000..03e2217
--- /dev/null
+++ b/nsync/src/sync-leaf.cc
@@ -0,0 +1,43 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include "sync-leaf.h"
+
+namespace Sync {
+
+Leaf::Leaf (NameInfoConstPtr info, const SeqNo &seq)
+ : m_info (info)
+ , m_seq (seq)
+{
+}
+
+Leaf::~Leaf ()
+{
+}
+
+void
+Leaf::setSeq (const SeqNo &seq)
+{
+ m_seq = std::max (m_seq, seq);
+}
+
+} // Sync
diff --git a/nsync/src/sync-leaf.h b/nsync/src/sync-leaf.h
new file mode 100644
index 0000000..345be46
--- /dev/null
+++ b/nsync/src/sync-leaf.h
@@ -0,0 +1,84 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_LEAF_H
+#define SYNC_LEAF_H
+
+#include "sync-seq-no.h"
+#include "sync-name-info.h"
+
+namespace Sync {
+
+/**
+ * \ingroup sync
+ * @brief Sync tree leaf
+ */
+class Leaf
+{
+public:
+ /**
+ * @brief Constructor
+ * @param info Smart pointer to leaf's name
+ * @param seq Initial sequence number of the pointer
+ */
+ Leaf (NameInfoConstPtr info, const SeqNo &seq);
+ virtual ~Leaf ();
+
+ /**
+ * @brief Get name of the leaf
+ */
+ NameInfoConstPtr
+ getInfo () const { return m_info; }
+
+ /**
+ * @brief Get sequence number of the leaf
+ */
+ const SeqNo&
+ getSeq () const { return m_seq; }
+
+ /**
+ * @brief Update sequence number of the leaf
+ * @param seq Sequence number
+ *
+ * Sequence number is updated to the largest value among this->m_seq and seq
+ */
+ virtual void
+ setSeq (const SeqNo &seq);
+
+private:
+ NameInfoConstPtr m_info;
+ SeqNo m_seq;
+};
+
+typedef boost::shared_ptr<Leaf> LeafPtr;
+typedef boost::shared_ptr<const Leaf> LeafConstPtr;
+
+inline std::ostream &
+operator << (std::ostream &os, const Leaf &leaf)
+{
+ os << *leaf.getInfo () << "(" << leaf.getSeq () << ")";
+ return os;
+}
+
+} // Sync
+
+#endif // SYNC_LEAF_H
diff --git a/nsync/src/sync-logging.cc b/nsync/src/sync-logging.cc
new file mode 100644
index 0000000..9048964
--- /dev/null
+++ b/nsync/src/sync-logging.cc
@@ -0,0 +1,61 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include "sync-logging.h"
+
+#ifdef HAVE_LOG4CXX
+
+#include <log4cxx/logger.h>
+#include <log4cxx/basicconfigurator.h>
+#include <log4cxx/consoleappender.h>
+#include <log4cxx/patternlayout.h>
+#include <log4cxx/level.h>
+#include <log4cxx/propertyconfigurator.h>
+#include <log4cxx/defaultconfigurator.h>
+#include <log4cxx/helpers/exception.h>
+using namespace log4cxx;
+using namespace log4cxx::helpers;
+
+#include <unistd.h>
+
+void
+INIT_LOGGERS ()
+{
+ static bool configured = false;
+
+ if (configured) return;
+
+ if (access ("log4cxx.properties", R_OK)==0)
+ PropertyConfigurator::configureAndWatch ("log4cxx.properties");
+ else
+ {
+ PatternLayoutPtr layout (new PatternLayout ("%d{HH:mm:ss} %p %c{1} - %m%n"));
+ ConsoleAppenderPtr appender (new ConsoleAppender (layout));
+
+ BasicConfigurator::configure( appender );
+ Logger::getRootLogger()->setLevel (log4cxx::Level::getInfo ());
+ }
+
+ configured = true;
+}
+
+#endif
diff --git a/nsync/src/sync-logging.h b/nsync/src/sync-logging.h
new file mode 100644
index 0000000..865204a
--- /dev/null
+++ b/nsync/src/sync-logging.h
@@ -0,0 +1,74 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_LOG_H
+#define SYNC_LOG_H
+
+#ifdef HAVE_LOG4CXX
+
+#include <log4cxx/logger.h>
+
+#define INIT_LOGGER(name) \
+ static log4cxx::LoggerPtr staticModuleLogger = log4cxx::Logger::getLogger (name);
+
+#define _LOG_DEBUG(x) \
+ LOG4CXX_DEBUG(staticModuleLogger, x);
+
+#define _LOG_TRACE(x) \
+ LOG4CXX_TRACE(staticModuleLogger, x);
+
+#define _LOG_FUNCTION(x) \
+ LOG4CXX_TRACE(staticModuleLogger, __FUNCTION__ << "(" << x << ")");
+
+#define _LOG_FUNCTION_NOARGS \
+ LOG4CXX_TRACE(staticModuleLogger, __FUNCTION__ << "()");
+
+#define _LOG_ERROR(x) \
+ LOG4CXX_ERROR(staticModuleLogger, x);
+
+void
+INIT_LOGGERS ();
+
+#else
+
+#define INIT_LOGGER(name)
+#define _LOG_FUNCTION(x)
+#define _LOG_FUNCTION_NOARGS
+#define _LOG_TRACE(x)
+#define INIT_LOGGERS(x)
+#define _LOG_ERROR(x)
+
+#ifdef _DEBUG
+
+#include <boost/date_time/posix_time/posix_time.hpp>
+#include <iostream>
+
+#define _LOG_DEBUG(x) \
+ std::clog << boost::get_system_time () << " " << boost::this_thread::get_id () << " " << x << endl;
+
+#else
+#define _LOG_DEBUG(x)
+#endif
+
+#endif // HAVE_LOG4CXX
+
+#endif // SYNC_LOG_H
diff --git a/nsync/src/sync-logic-event-container.h b/nsync/src/sync-logic-event-container.h
new file mode 100644
index 0000000..ebab72a
--- /dev/null
+++ b/nsync/src/sync-logic-event-container.h
@@ -0,0 +1,85 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_LOGIC_EVENT_CONTAINER_H
+#define SYNC_LOGIC_EVENT_CONTAINER_H
+
+#include "sync-event.h"
+
+#include <boost/function.hpp>
+#include <boost/date_time/posix_time/posix_time_types.hpp>
+
+#include <boost/multi_index_container.hpp>
+// #include <boost/multi_index/tag.hpp>
+#include <boost/multi_index/ordered_index.hpp>
+// #include <boost/multi_index/composite_key.hpp>
+// #include <boost/multi_index/hashed_index.hpp>
+// #include <boost/multi_index/random_access_index.hpp>
+#include <boost/multi_index/member.hpp>
+// #include <boost/multi_index/mem_fun.hpp>
+
+namespace mi = boost::multi_index;
+
+namespace Sync
+{
+
+struct LogicEvent
+{
+ LogicEvent (const boost::system_time &_time, Event _event, uint32_t _label)
+ : time (_time)
+ , event (_event)
+ , lbl (_label)
+ { }
+
+ boost::system_time time;
+ Event event;
+ uint32_t lbl;
+};
+
+/// @cond include_hidden
+struct byLabel { } ;
+/// @endcond
+
+/**
+ * \ingroup sync
+ * @brief ???
+ */
+struct EventsContainer : public mi::multi_index_container<
+ LogicEvent,
+ mi::indexed_by<
+
+ mi::ordered_non_unique<
+ mi::member<LogicEvent, boost::system_time, &LogicEvent::time>
+ >,
+
+ mi::ordered_non_unique<
+ mi::tag<byLabel>,
+ mi::member<LogicEvent, uint32_t, &LogicEvent::lbl>
+ >
+ >
+ >
+{
+};
+
+} // Sync
+
+#endif // SYNC_LOGIC_EVENT_CONTAINER_H
diff --git a/nsync/src/sync-logic.cc b/nsync/src/sync-logic.cc
new file mode 100644
index 0000000..ec4d63e
--- /dev/null
+++ b/nsync/src/sync-logic.cc
@@ -0,0 +1,705 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ * Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#include "sync-logic.h"
+#include "sync-diff-leaf.h"
+#include "sync-full-leaf.h"
+#include "sync-logging.h"
+#include "sync-state.h"
+
+#include <boost/foreach.hpp>
+#include <boost/lexical_cast.hpp>
+#include <vector>
+
+using namespace std;
+using namespace ndn;
+
+INIT_LOGGER ("SyncLogic");
+
+
+#ifdef _DEBUG
+#define _LOG_DEBUG_ID(v) _LOG_DEBUG(m_instanceId << " " << v)
+#else
+#define _LOG_DEBUG_ID(v) _LOG_DEBUG(v)
+#endif
+
+#define GET_RANDOM(var) var ()
+
+#define TIME_SECONDS_WITH_JITTER(sec) \
+ (time::seconds(sec) + time::milliseconds(GET_RANDOM (m_reexpressionJitter)))
+
+#define TIME_MILLISECONDS_WITH_JITTER(ms) \
+ (time::seconds(ms) + time::milliseconds(GET_RANDOM (m_reexpressionJitter)))
+
+namespace Sync {
+
+using ndn::shared_ptr;
+
+int SyncLogic::m_instanceCounter = 0;
+
+SyncLogic::SyncLogic (const Name& syncPrefix,
+ shared_ptr<Validator> validator,
+ shared_ptr<Face> face,
+ LogicUpdateCallback onUpdate,
+ LogicRemoveCallback onRemove)
+ : m_state (new FullState)
+ , m_syncInterestTable (*face->ioService(), time::seconds(m_syncInterestReexpress))
+ , m_syncPrefix (syncPrefix)
+ , m_onUpdate (onUpdate)
+ , m_onRemove (onRemove)
+ , m_perBranch (false)
+ , m_validator(validator)
+ , m_keyChain(new KeyChain())
+ , m_face(face)
+ , m_scheduler(*face->ioService())
+ , m_randomGenerator (static_cast<unsigned int> (std::time (0)))
+ , m_rangeUniformRandom (m_randomGenerator, boost::uniform_int<> (200,1000))
+ , m_reexpressionJitter (m_randomGenerator, boost::uniform_int<> (100,500))
+ , m_recoveryRetransmissionInterval (m_defaultRecoveryRetransmitInterval)
+{
+ m_syncRegisteredPrefixId = m_face->setInterestFilter (m_syncPrefix,
+ bind(&SyncLogic::onSyncInterest, this, _1, _2),
+ bind(&SyncLogic::onSyncRegisterFailed, this, _1, _2));
+
+
+ m_reexpressingInterestId = m_scheduler.scheduleEvent (time::seconds (0), // no need to add jitter
+ bind (&SyncLogic::sendSyncInterest, this));
+
+ m_instanceId = string("Instance " + boost::lexical_cast<string>(m_instanceCounter++) + " ");
+}
+
+SyncLogic::SyncLogic (const Name& syncPrefix,
+ shared_ptr<Validator> validator,
+ shared_ptr<Face> face,
+ LogicPerBranchCallback onUpdateBranch)
+ : m_state (new FullState)
+ , m_syncInterestTable (*face->ioService(), time::seconds (m_syncInterestReexpress))
+ , m_syncPrefix (syncPrefix)
+ , m_onUpdateBranch (onUpdateBranch)
+ , m_perBranch(true)
+ , m_validator(validator)
+ , m_keyChain(new KeyChain())
+ , m_face(face)
+ , m_scheduler(*face->ioService())
+ , m_randomGenerator (static_cast<unsigned int> (std::time (0)))
+ , m_rangeUniformRandom (m_randomGenerator, boost::uniform_int<> (200,1000))
+ , m_reexpressionJitter (m_randomGenerator, boost::uniform_int<> (100,500))
+ , m_recoveryRetransmissionInterval (m_defaultRecoveryRetransmitInterval)
+{
+ m_syncRegisteredPrefixId = m_face->setInterestFilter (m_syncPrefix,
+ bind(&SyncLogic::onSyncInterest, this, _1, _2),
+ bind(&SyncLogic::onSyncRegisterFailed, this, _1, _2));
+
+ m_reexpressingInterestId = m_scheduler.scheduleEvent (time::seconds (0), // no need to add jitter
+ bind (&SyncLogic::sendSyncInterest, this));
+}
+
+SyncLogic::~SyncLogic ()
+{
+ m_face->unsetInterestFilter(m_syncRegisteredPrefixId);
+ m_scheduler.cancelEvent (m_reexpressingInterestId);
+ m_scheduler.cancelEvent (m_delayedInterestProcessingId);
+}
+
+/**
+ * Two types of intersts
+ *
+ * Normal name: .../<hash>
+ * Recovery name: .../recovery/<hash>
+ */
+boost::tuple<DigestConstPtr, std::string>
+SyncLogic::convertNameToDigestAndType (const Name &name)
+{
+ BOOST_ASSERT (m_syncPrefix.isPrefixOf(name));
+
+ int nameLengthDiff = name.size() - m_syncPrefix.size();
+ BOOST_ASSERT (nameLengthDiff > 0);
+ BOOST_ASSERT (nameLengthDiff < 3);
+
+ string hash = name.get(-1).toEscapedString();
+ string interestType;
+
+ if(nameLengthDiff == 1)
+ interestType = "normal";
+ else
+ interestType = name.get(-2).toEscapedString();
+
+ _LOG_DEBUG_ID (hash << ", " << interestType);
+
+ DigestPtr digest = boost::make_shared<Digest> ();
+ istringstream is (hash);
+ is >> *digest;
+
+ return make_tuple (digest, interestType);
+}
+
+void
+SyncLogic::onSyncInterest (const Name& prefix, const ndn::Interest& interest)
+{
+ Name name = interest.getName();
+
+ _LOG_DEBUG_ID("respondSyncInterest: " << name);
+
+ try
+ {
+ _LOG_DEBUG_ID ("<< I " << name);
+
+ DigestConstPtr digest;
+ string type;
+ tie (digest, type) = convertNameToDigestAndType (name);
+
+ if (type == "normal") // kind of ineffective...
+ {
+ processSyncInterest (name, digest);
+ }
+ else if (type == "recovery")
+ {
+ processSyncRecoveryInterest (name, digest);
+ }
+ }
+ catch (Error::DigestCalculationError &e)
+ {
+ _LOG_DEBUG_ID ("Something fishy happened...");
+ // log error. ignoring it for now, later we should log it
+ return ;
+ }
+}
+
+void
+SyncLogic::onSyncRegisterFailed(const Name& prefix, const string& msg)
+{
+ _LOG_DEBUG_ID("Sync prefix registration failed! " << msg);
+}
+
+void
+SyncLogic::onSyncData(const ndn::Interest& interest, Data& data)
+{
+ OnDataValidated onValidated = bind(&SyncLogic::onSyncDataValidated, this, _1);
+ OnDataValidationFailed onValidationFailed = bind(&SyncLogic::onSyncDataValidationFailed, this, _1);
+ m_validator->validate(data, onValidated, onValidationFailed);
+}
+
+void
+SyncLogic::onSyncTimeout(const ndn::Interest& interest)
+{
+ // It is OK. Others will handle the time out situation.
+}
+
+void
+SyncLogic::onSyncDataValidationFailed(const shared_ptr<const Data>& data)
+{
+ _LOG_DEBUG_ID("Sync data cannot be verified!");
+}
+
+void
+SyncLogic::onSyncDataValidated(const shared_ptr<const Data>& data)
+{
+ Name name = data->getName();
+ const char* wireData = (const char*)data->getContent().value();
+ size_t len = data->getContent().value_size();
+
+ try
+ {
+ _LOG_DEBUG_ID ("<< D " << name);
+
+ DigestConstPtr digest;
+ string type;
+ tie (digest, type) = convertNameToDigestAndType (name);
+
+ if (type == "normal")
+ {
+ processSyncData (name, digest, wireData, len);
+ }
+ else
+ {
+ // timer is always restarted when we schedule recovery
+ m_scheduler.cancelEvent (m_reexpressingRecoveryInterestId);
+ processSyncData (name, digest, wireData, len);
+ }
+ }
+ catch (Error::DigestCalculationError &e)
+ {
+ _LOG_DEBUG_ID ("Something fishy happened...");
+ // log error. ignoring it for now, later we should log it
+ return;
+ }
+}
+
+void
+SyncLogic::processSyncInterest (const Name &name, DigestConstPtr digest, bool timedProcessing/*=false*/)
+{
+ _LOG_DEBUG_ID("processSyncInterest");
+ DigestConstPtr rootDigest;
+ {
+ rootDigest = m_state->getDigest();
+ }
+
+ // Special case when state is not empty and we have received request with zero-root digest
+ if (digest->isZero () && !rootDigest->isZero ())
+ {
+
+ SyncStateMsg ssm;
+ {
+ ssm << (*m_state);
+ }
+ sendSyncData (name, digest, ssm);
+ return;
+ }
+
+ if (*rootDigest == *digest)
+ {
+ _LOG_DEBUG_ID ("processSyncInterest (): Same state. Adding to PIT");
+ m_syncInterestTable.insert (digest, name.toUri(), false);
+ return;
+ }
+
+ DiffStateContainer::iterator stateInDiffLog = m_log.find (digest);
+
+ if (stateInDiffLog != m_log.end ())
+ {
+ DiffStateConstPtr stateDiff = (*stateInDiffLog)->diff ();
+
+ sendSyncData (name, digest, stateDiff);
+ return;
+ }
+
+ if (!timedProcessing)
+ {
+ bool exists = m_syncInterestTable.insert (digest, name.toUri(), true);
+ if (exists) // somebody else replied, so restart random-game timer
+ {
+ _LOG_DEBUG_ID ("Unknown digest, but somebody may have already replied, so restart our timer");
+ m_scheduler.cancelEvent (m_delayedInterestProcessingId);
+ }
+
+ uint32_t waitDelay = GET_RANDOM (m_rangeUniformRandom);
+ _LOG_DEBUG_ID ("Digest is not in the log. Schedule processing after small delay: " << time::milliseconds (waitDelay));
+
+ m_delayedInterestProcessingId = m_scheduler.scheduleEvent (time::milliseconds (waitDelay),
+ bind (&SyncLogic::processSyncInterest, this, name, digest, true));
+ }
+ else
+ {
+ _LOG_DEBUG_ID (" (timed processing)");
+
+ m_recoveryRetransmissionInterval = m_defaultRecoveryRetransmitInterval;
+ sendSyncRecoveryInterests (digest);
+ }
+}
+
+void
+SyncLogic::processSyncData (const Name &name, DigestConstPtr digest, const char *wireData, size_t len)
+{
+ DiffStatePtr diffLog = boost::make_shared<DiffState> ();
+ bool ownInterestSatisfied = false;
+
+ try
+ {
+
+ m_syncInterestTable.remove (name.toUri()); // Remove satisfied interest from PIT
+
+ ownInterestSatisfied = (name == m_outstandingInterestName);
+
+ DiffState diff;
+ SyncStateMsg msg;
+ if (!msg.ParseFromArray(wireData, len) || !msg.IsInitialized())
+ {
+ //Throw
+ BOOST_THROW_EXCEPTION (Error::SyncStateMsgDecodingFailure () );
+ }
+ msg >> diff;
+
+ vector<MissingDataInfo> v;
+ BOOST_FOREACH (LeafConstPtr leaf, diff.getLeaves().get<ordered>())
+ {
+ DiffLeafConstPtr diffLeaf = boost::dynamic_pointer_cast<const DiffLeaf> (leaf);
+ BOOST_ASSERT (diffLeaf != 0);
+
+ NameInfoConstPtr info = diffLeaf->getInfo();
+ if (diffLeaf->getOperation() == UPDATE)
+ {
+ SeqNo seq = diffLeaf->getSeq();
+
+ bool inserted = false;
+ bool updated = false;
+ SeqNo oldSeq;
+ {
+ boost::tie (inserted, updated, oldSeq) = m_state->update (info, seq);
+ }
+
+ if (inserted || updated)
+ {
+ diffLog->update (info, seq);
+ if (!oldSeq.isValid())
+ {
+ oldSeq = SeqNo(seq.getSession(), 0);
+ }
+ else
+ {
+ ++oldSeq;
+ }
+ // there is no need for application to process update on forwarder node
+ if (info->toString() != forwarderPrefix)
+ {
+ MissingDataInfo mdi = {info->toString(), oldSeq, seq};
+ {
+ ostringstream interestName;
+ interestName << mdi.prefix << "/" << mdi.high.getSession() << "/" << mdi.high.getSeq();
+ _LOG_DEBUG_ID("+++++++++++++++ " + interestName.str());
+ }
+ if (m_perBranch)
+ {
+ ostringstream interestName;
+ interestName << mdi.prefix << "/" << mdi.high.getSession() << "/" << mdi.high.getSeq();
+ m_onUpdateBranch(interestName.str());
+ }
+ else
+ {
+ v.push_back(mdi);
+ }
+ }
+ }
+ }
+ else if (diffLeaf->getOperation() == REMOVE)
+ {
+ if (m_state->remove (info))
+ {
+ diffLog->remove (info);
+ if (!m_perBranch)
+ {
+ m_onRemove (info->toString ());
+ }
+ }
+ }
+ else
+ {
+ }
+ }
+
+ if (!v.empty())
+ {
+ if (!m_perBranch)
+ {
+ m_onUpdate(v);
+ }
+ }
+
+ insertToDiffLog (diffLog);
+ }
+ catch (Error::SyncStateMsgDecodingFailure &e)
+ {
+ _LOG_DEBUG_ID ("Something really fishy happened during state decoding " <<
+ diagnostic_information (e));
+ diffLog.reset ();
+ // don't do anything
+ }
+
+ if ((diffLog != 0 && diffLog->getLeaves ().size () > 0) ||
+ ownInterestSatisfied)
+ {
+ _LOG_DEBUG_ID(" +++++++++++++++ state changed!!!");
+ // Do it only if everything went fine and state changed
+
+ // this is kind of wrong
+ // satisfyPendingSyncInterests (diffLog); // if there are interests in PIT, there is a point to satisfy them using new state
+
+ // if state has changed, then it is safe to express a new interest
+ time::Duration after = time::milliseconds(GET_RANDOM (m_reexpressionJitter));
+ // cout << "------------ reexpress interest after: " << after << endl;
+ EventId eventId = m_scheduler.scheduleEvent (after,
+ bind (&SyncLogic::sendSyncInterest, this));
+
+ m_scheduler.cancelEvent (m_reexpressingInterestId);
+ m_reexpressingInterestId = eventId;
+ }
+}
+
+void
+SyncLogic::processSyncRecoveryInterest (const Name &name, DigestConstPtr digest)
+{
+ _LOG_DEBUG_ID("processSyncRecoveryInterest");
+ DiffStateContainer::iterator stateInDiffLog = m_log.find (digest);
+
+ if (stateInDiffLog == m_log.end ())
+ {
+ _LOG_DEBUG_ID ("Could not find " << *digest << " in digest log");
+ return;
+ }
+
+ SyncStateMsg ssm;
+ {
+ ssm << (*m_state);
+ }
+ sendSyncData (name, digest, ssm);
+}
+
+void
+SyncLogic::satisfyPendingSyncInterests (DiffStateConstPtr diffLog)
+{
+ DiffStatePtr fullStateLog = boost::make_shared<DiffState> ();
+ {
+ BOOST_FOREACH (LeafConstPtr leaf, m_state->getLeaves ()/*.get<timed> ()*/)
+ {
+ fullStateLog->update (leaf->getInfo (), leaf->getSeq ());
+ /// @todo Impose limit on how many state info should be send out
+ }
+ }
+
+ try
+ {
+ uint32_t counter = 0;
+ while (m_syncInterestTable.size () > 0)
+ {
+ Sync::Interest interest = m_syncInterestTable.pop ();
+
+ if (!interest.m_unknown)
+ {
+ _LOG_DEBUG_ID (">> D " << interest.m_name);
+ sendSyncData (interest.m_name, interest.m_digest, diffLog);
+ }
+ else
+ {
+ _LOG_DEBUG_ID (">> D (unknown)" << interest.m_name);
+ sendSyncData (interest.m_name, interest.m_digest, fullStateLog);
+ }
+ counter ++;
+ }
+ _LOG_DEBUG_ID ("Satisfied " << counter << " pending interests");
+ }
+ catch (Error::InterestTableIsEmpty &e)
+ {
+ // ok. not really an error
+ }
+}
+
+void
+SyncLogic::insertToDiffLog (DiffStatePtr diffLog)
+{
+ diffLog->setDigest (m_state->getDigest());
+ if (m_log.size () > 0)
+ {
+ m_log.get<sequenced> ().front ()->setNext (diffLog);
+ }
+ m_log.erase (m_state->getDigest()); // remove diff state with the same digest. next pointers are still valid
+ /// @todo Optimization
+ m_log.get<sequenced> ().push_front (diffLog);
+}
+
+void
+SyncLogic::addLocalNames (const Name &prefix, uint64_t session, uint64_t seq)
+{
+ DiffStatePtr diff;
+ {
+ //cout << "Add local names" <<endl;
+ NameInfoConstPtr info = StdNameInfo::FindOrCreate(prefix.toUri());
+
+ _LOG_DEBUG_ID ("addLocalNames (): old state " << *m_state->getDigest ());
+
+ SeqNo seqN (session, seq);
+ m_state->update(info, seqN);
+
+ _LOG_DEBUG_ID ("addLocalNames (): new state " << *m_state->getDigest ());
+
+ diff = boost::make_shared<DiffState>();
+ diff->update(info, seqN);
+ insertToDiffLog (diff);
+ }
+
+ // _LOG_DEBUG_ID ("PIT size: " << m_syncInterestTable.size ());
+ satisfyPendingSyncInterests (diff);
+}
+
+void
+SyncLogic::remove(const Name &prefix)
+{
+ DiffStatePtr diff;
+ {
+ NameInfoConstPtr info = StdNameInfo::FindOrCreate(prefix.toUri());
+ m_state->remove(info);
+
+ // increment the sequence number for the forwarder node
+ NameInfoConstPtr forwarderInfo = StdNameInfo::FindOrCreate(forwarderPrefix);
+
+ LeafContainer::iterator item = m_state->getLeaves ().find (forwarderInfo);
+ SeqNo seqNo (0);
+ if (item != m_state->getLeaves ().end ())
+ {
+ seqNo = (*item)->getSeq ();
+ ++seqNo;
+ }
+ m_state->update (forwarderInfo, seqNo);
+
+ diff = boost::make_shared<DiffState>();
+ diff->remove(info);
+ diff->update(forwarderInfo, seqNo);
+
+ insertToDiffLog (diff);
+ }
+
+ satisfyPendingSyncInterests (diff);
+}
+
+void
+SyncLogic::sendSyncInterest ()
+{
+ _LOG_DEBUG_ID("sendSyncInterest");
+
+ {
+ m_outstandingInterestName = m_syncPrefix;
+ ostringstream os;
+ os << *m_state->getDigest();
+ m_outstandingInterestName.append(os.str());
+ _LOG_DEBUG_ID (">> I " << m_outstandingInterestName);
+ }
+
+ _LOG_DEBUG_ID("sendSyncInterest: " << m_outstandingInterestName);
+
+ EventId eventId = m_scheduler.scheduleEvent (time::seconds(m_syncInterestReexpress) + time::milliseconds(GET_RANDOM (m_reexpressionJitter)),
+ bind (&SyncLogic::sendSyncInterest, this));
+ m_scheduler.cancelEvent (m_reexpressingInterestId);
+ m_reexpressingInterestId = eventId;
+
+ ndn::Interest interest(m_outstandingInterestName);
+ interest.setMustBeFresh(true);
+
+ m_face->expressInterest(interest,
+ bind(&SyncLogic::onSyncData, this, _1, _2),
+ bind(&SyncLogic::onSyncTimeout, this, _1));
+}
+
+void
+SyncLogic::sendSyncRecoveryInterests (DigestConstPtr digest)
+{
+ ostringstream os;
+ os << *digest;
+
+ Name interestName = m_syncPrefix;
+ interestName.append("recovery").append(os.str());
+
+ time::Duration nextRetransmission = time::milliseconds (m_recoveryRetransmissionInterval + GET_RANDOM (m_reexpressionJitter));
+
+ m_recoveryRetransmissionInterval <<= 1;
+
+ m_scheduler.cancelEvent (m_reexpressingRecoveryInterestId);
+ if (m_recoveryRetransmissionInterval < 100*1000) // <100 seconds
+ m_reexpressingRecoveryInterestId = m_scheduler.scheduleEvent (nextRetransmission,
+ bind (&SyncLogic::sendSyncRecoveryInterests, this, digest));
+
+ ndn::Interest interest(interestName);
+ interest.setMustBeFresh(true);
+
+ m_face->expressInterest(interest,
+ bind(&SyncLogic::onSyncData, this, _1, _2),
+ bind(&SyncLogic::onSyncTimeout, this, _1));
+}
+
+
+void
+SyncLogic::sendSyncData (const Name &name, DigestConstPtr digest, StateConstPtr state)
+{
+ SyncStateMsg msg;
+ msg << (*state);
+ sendSyncData(name, digest, msg);
+}
+
+// pass in state msg instead of state, so that there is no need to lock the state until
+// this function returns
+void
+SyncLogic::sendSyncData (const Name &name, DigestConstPtr digest, SyncStateMsg &ssm)
+{
+ _LOG_DEBUG_ID (">> D " << name);
+ int size = ssm.ByteSize();
+ char *wireData = new char[size];
+ ssm.SerializeToArray(wireData, size);
+
+ Data syncData(name);
+ syncData.setContent(reinterpret_cast<const uint8_t*>(wireData), size);
+ syncData.setFreshnessPeriod(m_syncResponseFreshness);
+
+ m_keyChain->sign(syncData);
+
+ m_face->put(syncData);
+
+ delete []wireData;
+
+ // checking if our own interest got satisfied
+ bool satisfiedOwnInterest = false;
+ {
+ satisfiedOwnInterest = (m_outstandingInterestName == name);
+ }
+
+ if (satisfiedOwnInterest)
+ {
+ _LOG_DEBUG_ID ("Satisfied our own Interest. Re-expressing (hopefully with a new digest)");
+
+ time::Duration after = time::milliseconds(GET_RANDOM (m_reexpressionJitter));
+ // cout << "------------ reexpress interest after: " << after << endl;
+ EventId eventId = m_scheduler.scheduleEvent (after,
+ bind (&SyncLogic::sendSyncInterest, this));
+ m_scheduler.cancelEvent (m_reexpressingInterestId);
+ m_reexpressingInterestId = eventId;
+ }
+}
+
+string
+SyncLogic::getRootDigest()
+{
+ ostringstream os;
+ os << *m_state->getDigest();
+ return os.str();
+}
+
+size_t
+SyncLogic::getNumberOfBranches () const
+{
+ return m_state->getLeaves ().size ();
+}
+
+void
+SyncLogic::printState () const
+{
+ BOOST_FOREACH (const boost::shared_ptr<Sync::Leaf> leaf, m_state->getLeaves ())
+ {
+ std::cout << *leaf << std::endl;
+ }
+}
+
+std::map<std::string, bool>
+SyncLogic::getBranchPrefixes() const
+{
+ std::map<std::string, bool> m;
+
+ BOOST_FOREACH (const boost::shared_ptr<Sync::Leaf> leaf, m_state->getLeaves ())
+ {
+ std::string prefix = leaf->getInfo()->toString();
+ // do not return forwarder prefix
+ if (prefix != forwarderPrefix)
+ {
+ m.insert(pair<std::string, bool>(prefix, false));
+ }
+ }
+
+ return m;
+}
+
+}
diff --git a/nsync/src/sync-logic.h b/nsync/src/sync-logic.h
new file mode 100644
index 0000000..fc63fca
--- /dev/null
+++ b/nsync/src/sync-logic.h
@@ -0,0 +1,218 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ * Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#ifndef SYNC_LOGIC_H
+#define SYNC_LOGIC_H
+
+#include <boost/random.hpp>
+#include <memory>
+#include <map>
+
+#include <ndn-cpp-dev/face.hpp>
+#include <ndn-cpp-dev/security/validator.hpp>
+#include <ndn-cpp-dev/security/key-chain.hpp>
+#include <ndn-cpp-dev/util/scheduler.hpp>
+
+#include "sync-interest-table.h"
+#include "sync-diff-state.h"
+#include "sync-full-state.h"
+#include "sync-std-name-info.h"
+
+#include "sync-diff-state-container.h"
+
+#ifdef _DEBUG
+#ifdef HAVE_LOG4CXX
+#include <log4cxx/logger.h>
+#endif
+#endif
+
+namespace Sync {
+
+struct MissingDataInfo {
+ std::string prefix;
+ SeqNo low;
+ SeqNo high;
+};
+
+/**
+ * \ingroup sync
+ * @brief A wrapper for SyncApp, which handles ccnx related things (process
+ * interests and data)
+ */
+
+class SyncLogic
+{
+public:
+ //typedef boost::function< void ( const std::string &/*prefix*/, const SeqNo &/*newSeq*/, const SeqNo &/*oldSeq*/ ) > LogicUpdateCallback;
+ typedef boost::function< void (const std::vector<MissingDataInfo> & ) > LogicUpdateCallback;
+ typedef boost::function< void (const std::string &/*prefix*/ ) > LogicRemoveCallback;
+ typedef boost::function< void (const std::string &)> LogicPerBranchCallback;
+
+ /**
+ * @brief Constructor
+ * @param syncPrefix the name prefix to use for the Sync Interest
+ * @param onUpdate function that will be called when new state is detected
+ * @param onRemove function that will be called when state is removed
+ * @param ccnxHandle ccnx handle
+ * the app data when new remote names are learned
+ */
+ SyncLogic (const ndn::Name& syncPrefix,
+ ndn::shared_ptr<ndn::Validator> validator,
+ ndn::shared_ptr<ndn::Face> face,
+ LogicUpdateCallback onUpdate,
+ LogicRemoveCallback onRemove);
+
+ SyncLogic (const ndn::Name& syncPrefix,
+ ndn::shared_ptr<ndn::Validator> validator,
+ ndn::shared_ptr<ndn::Face> face,
+ LogicPerBranchCallback onUpdateBranch);
+
+ ~SyncLogic ();
+
+ /**
+ * a wrapper for the same func in SyncApp
+ */
+ void addLocalNames (const ndn::Name &prefix, uint64_t session, uint64_t seq);
+
+ /**
+ * @brief remove a participant's subtree from the sync tree
+ * @param prefix the name prefix for the participant
+ */
+ void remove (const ndn::Name &prefix);
+
+ std::string
+ getRootDigest();
+
+#ifdef _DEBUG
+ ndn::Scheduler &
+ getScheduler () { return m_scheduler; }
+#endif
+
+ void
+ printState () const;
+
+ std::map<std::string, bool>
+ getBranchPrefixes() const;
+
+private:
+ void
+ delayedChecksLoop ();
+
+ void
+ onSyncInterest (const ndn::Name& prefix, const ndn::Interest& interest);
+
+ void
+ onSyncRegisterFailed(const ndn::Name& prefix, const std::string& msg);
+
+ void
+ onSyncData(const ndn::Interest& interest, ndn::Data& data);
+
+ void
+ onSyncTimeout(const ndn::Interest& interest);
+
+ void
+ onSyncDataValidationFailed(const ndn::shared_ptr<const ndn::Data>& data);
+
+ void
+ onSyncDataValidated(const ndn::shared_ptr<const ndn::Data>& data);
+
+ void
+ processSyncInterest (const ndn::Name &name,
+ DigestConstPtr digest, bool timedProcessing=false);
+
+ void
+ processSyncData (const ndn::Name &name,
+ DigestConstPtr digest, const char *wireData, size_t len);
+
+ void
+ processSyncRecoveryInterest (const ndn::Name &name,
+ DigestConstPtr digest);
+
+ void
+ insertToDiffLog (DiffStatePtr diff);
+
+ void
+ satisfyPendingSyncInterests (DiffStateConstPtr diff);
+
+ boost::tuple<DigestConstPtr, std::string>
+ convertNameToDigestAndType (const ndn::Name &name);
+
+ void
+ sendSyncInterest ();
+
+ void
+ sendSyncRecoveryInterests (DigestConstPtr digest);
+
+ void
+ sendSyncData (const ndn::Name &name,
+ DigestConstPtr digest, StateConstPtr state);
+
+ void
+ sendSyncData (const ndn::Name &name,
+ DigestConstPtr digest, SyncStateMsg &msg);
+
+ size_t
+ getNumberOfBranches () const;
+
+private:
+ FullStatePtr m_state;
+ DiffStateContainer m_log;
+
+ ndn::Name m_outstandingInterestName;
+ SyncInterestTable m_syncInterestTable;
+
+ ndn::Name m_syncPrefix;
+ LogicUpdateCallback m_onUpdate;
+ LogicRemoveCallback m_onRemove;
+ LogicPerBranchCallback m_onUpdateBranch;
+ bool m_perBranch;
+ ndn::ptr_lib::shared_ptr<ndn::Validator> m_validator;
+ ndn::ptr_lib::shared_ptr<ndn::KeyChain> m_keyChain;
+ ndn::ptr_lib::shared_ptr<ndn::Face> m_face;
+ const ndn::RegisteredPrefixId* m_syncRegisteredPrefixId;
+
+ ndn::Scheduler m_scheduler;
+
+ boost::mt19937 m_randomGenerator;
+ boost::variate_generator<boost::mt19937&, boost::uniform_int<> > m_rangeUniformRandom;
+ boost::variate_generator<boost::mt19937&, boost::uniform_int<> > m_reexpressionJitter;
+
+ static const int m_unknownDigestStoreTime = 10; // seconds
+ static const int m_syncResponseFreshness = 1000; // MUST BE dividable by 1000!!!
+ static const int m_syncInterestReexpress = 4; // seconds
+
+ static const int m_defaultRecoveryRetransmitInterval = 200; // milliseconds
+ uint32_t m_recoveryRetransmissionInterval; // milliseconds
+
+ ndn::EventId m_delayedInterestProcessingId;
+ ndn::EventId m_reexpressingInterestId;
+ ndn::EventId m_reexpressingRecoveryInterestId;
+
+ std::string m_instanceId;
+ static int m_instanceCounter;
+};
+
+
+} // Sync
+
+#endif // SYNC_APP_WRAPPER_H
diff --git a/nsync/src/sync-name-info.cc b/nsync/src/sync-name-info.cc
new file mode 100644
index 0000000..30986cd
--- /dev/null
+++ b/nsync/src/sync-name-info.cc
@@ -0,0 +1,32 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include "sync-name-info.h"
+
+// #include <boost/lexical_cast.hpp>
+
+namespace Sync {
+
+NameInfo::NameMap NameInfo::m_names;
+size_t NameInfo::m_ids = 0;
+
+} // Sync
diff --git a/nsync/src/sync-name-info.h b/nsync/src/sync-name-info.h
new file mode 100644
index 0000000..2f7c165
--- /dev/null
+++ b/nsync/src/sync-name-info.h
@@ -0,0 +1,102 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_NAME_INFO_H
+#define SYNC_NAME_INFO_H
+
+#include <boost/shared_ptr.hpp>
+#include <boost/weak_ptr.hpp>
+#include <map>
+#include <string>
+#include "sync-digest.h"
+
+namespace Sync {
+
+/**
+ * @ingroup sync
+ * @brief Templated class for the leaf name
+ */
+class NameInfo
+{
+private:
+ typedef boost::weak_ptr<const NameInfo> const_weak_ptr;
+
+public:
+ virtual ~NameInfo () { };
+
+ /**
+ * @brief Get ID of the record (should be locally-unique, but not really necessary---this is be used for hashing purposes)
+ */
+ size_t
+ getHashId () const { return m_id; }
+
+ /**
+ * @brief Check if two names are equal
+ * @param info name to check with
+ */
+ virtual bool
+ operator == (const NameInfo &info) const = 0;
+
+ /**
+ * @brief Check if two names are in order
+ * @param info name to check with
+ */
+ virtual bool
+ operator < (const NameInfo &info) const = 0;
+
+ /**
+ * @brief Calculates digest of the name
+ */
+ const Digest &
+ getDigest () const { return m_digest; }
+
+ /**
+ * @brief Convert prefix to string
+ * @returns string representation of prefix
+ */
+ virtual std::string
+ toString () const = 0;
+
+protected:
+ // actual stuff
+ size_t m_id; ///< @brief Identifies NameInfo throughout the library (for hash container, doesn't need to be strictly unique)
+ Digest m_digest;
+
+ // static stuff
+ typedef std::map<std::string, const_weak_ptr> NameMap;
+ static size_t m_ids;
+ static NameMap m_names;
+};
+
+typedef boost::shared_ptr<NameInfo> NameInfoPtr;
+typedef boost::shared_ptr<const NameInfo> NameInfoConstPtr;
+
+inline std::ostream &
+operator << (std::ostream &os, const NameInfo &info)
+{
+ os << info.toString ();
+ return os;
+}
+
+} // Sync
+
+#endif // SYNC_NAME_INFO_H
diff --git a/nsync/src/sync-seq-no.cc b/nsync/src/sync-seq-no.cc
new file mode 100644
index 0000000..fbbc53f
--- /dev/null
+++ b/nsync/src/sync-seq-no.cc
@@ -0,0 +1,39 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include "sync-seq-no.h"
+#include <boost/make_shared.hpp>
+
+using namespace boost;
+
+namespace Sync {
+
+DigestConstPtr
+SeqNo::getDigest () const
+{
+ DigestPtr digest = make_shared<Digest> ();
+ *digest << m_session << m_seq;
+ digest->finalize ();
+ return digest;
+}
+
+} // Sync
diff --git a/nsync/src/sync-seq-no.h b/nsync/src/sync-seq-no.h
new file mode 100644
index 0000000..bf21704
--- /dev/null
+++ b/nsync/src/sync-seq-no.h
@@ -0,0 +1,198 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ * Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#ifndef SYNC_SEQ_NO_H
+#define SYNC_SEQ_NO_H
+
+#include <boost/cstdint.hpp>
+#include "sync-digest.h"
+
+namespace Sync {
+
+/**
+ * @ingroup sync
+ * @brief Sequence number abstraction
+ */
+class SeqNo
+{
+public:
+ /**
+ * @brief Default constructor. Creates an zero sequence number with zero session ID (basically is an invalid object)
+ */
+ SeqNo ()
+ : m_valid (false)
+ , m_session (0)
+ , m_seq (0)
+ {
+ }
+
+ /**
+ * @brief Copy constructor
+ * @param seq sequence number object to copy from
+ */
+ SeqNo (const SeqNo &seq)
+ {
+ *this = seq;
+ }
+
+ /**
+ * @brief Assignment operator
+ * @param seq sequence number object to copy from
+ */
+ SeqNo &
+ operator = (const SeqNo &seq)
+ {
+ m_valid = seq.m_valid;
+ m_session = seq.m_session;
+ m_seq = seq.m_seq;
+
+ return *this;
+ }
+
+ /**
+ * @brief Constructor with just sequence number. Session assumed to be zero
+ * @param seq Sequence number
+ */
+ SeqNo (uint64_t seq)
+ : m_valid (true)
+ , m_session (0)
+ , m_seq (seq)
+ { }
+
+ /**
+ * @brief Constructor with session and sequence id
+ * @param session Session ID
+ * @param seq Sequence number
+ */
+ SeqNo (uint64_t session, uint64_t seq)
+ : m_valid (true)
+ , m_session (session)
+ , m_seq (seq)
+ { }
+
+ /**
+ * @brief Get sequence number digest
+ *
+ * Digest will be calculated every time it is requested
+ */
+ DigestConstPtr
+ getDigest () const;
+
+ /**
+ * @brief Compare if one sequence number is lower
+ * @param seq Another sequence number to compare with
+ *
+ * tuple (session1, seq1) is less than (session2, seq2) in two cases:
+ * 1. session1 < session2
+ * 2. session1 == session2 and seq1 < seq2
+ */
+ bool
+ operator < (const SeqNo &seq) const
+ {
+ return m_session < seq.m_session || (m_session == seq.m_session && m_seq < seq.m_seq);
+ }
+
+ /**
+ * @brief Compare if two sequence numbers are equal
+ * @param seq Another sequence number to compare with
+ */
+ bool
+ operator == (const SeqNo &seq) const
+ {
+ return m_session == seq.m_session && m_seq == seq.m_seq;
+ }
+
+ bool
+ operator <= (const SeqNo &seq) const
+ {
+ return m_session == seq.m_session && m_seq <= seq.m_seq;
+ }
+
+ SeqNo &
+ operator ++ ()
+ {
+ if (m_valid) {
+ m_seq ++;
+ }
+ else {
+ m_valid = true;
+ }
+ return *this;
+ }
+
+ bool
+ isValid () const
+ {
+ return m_valid;
+ }
+
+ /**
+ * @brief Get session id
+ */
+ uint64_t getSession () const
+ { return m_session; }
+
+ /**
+ * @brief Get sequence number
+ */
+ uint64_t getSeq () const
+ { return m_seq; }
+
+ /**
+ * @brief Set sequence number
+ */
+ void
+ setSeq(uint64_t seq)
+ { m_seq = seq; }
+
+private:
+ bool m_valid;
+
+ /**
+ * @brief Session ID (e.g., after crash, application will choose new session ID.
+ *
+ * Note that session IDs for the same name should always increase. So, the good choice
+ * for the session ID is client's timestamp
+ */
+ uint64_t m_session;
+
+ /**
+ * @brief Sequence number
+ *
+ * Sequence number for a session always starts with 0 and goes to max value.
+ *
+ * For now, wrapping sequence number after max to zero is not supported
+ */
+ uint64_t m_seq;
+};
+
+inline std::ostream &
+operator << (std::ostream &os, const SeqNo &seqno)
+{
+ os << "<session>" << seqno.getSession () << "</session><seqno>" << seqno.getSeq () << "</seqno>";
+ return os;
+}
+
+} // Sync
+
+#endif // SYNC_SEQ_NO_H
diff --git a/nsync/src/sync-socket.cc b/nsync/src/sync-socket.cc
new file mode 100644
index 0000000..db51ce2
--- /dev/null
+++ b/nsync/src/sync-socket.cc
@@ -0,0 +1,155 @@
+/* -*- Mode: C32++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#include "sync-socket.h"
+#include "sync-logging.h"
+
+using namespace std;
+using namespace ndn;
+
+INIT_LOGGER ("SyncSocket");
+
+namespace Sync {
+
+using ndn::shared_ptr;
+
+SyncSocket::SyncSocket (const Name &syncPrefix,
+ shared_ptr<Validator> validator,
+ shared_ptr<Face> face,
+ NewDataCallback dataCallback,
+ RemoveCallback rmCallback )
+ : m_newDataCallback(dataCallback)
+ , m_validator(validator)
+ , m_keyChain(new KeyChain())
+ , m_face(face)
+ , m_ioService(face->ioService())
+ , m_syncLogic (syncPrefix,
+ validator,
+ face,
+ bind(&SyncSocket::passCallback, this, _1),
+ rmCallback)
+{}
+
+SyncSocket::~SyncSocket()
+{
+}
+
+bool
+SyncSocket::publishData(const Name &prefix, uint64_t session, const char *buf, size_t len, int freshness,uint64_t seq)
+{
+ shared_ptr<Data> data = make_shared<Data>();
+ data->setContent(reinterpret_cast<const uint8_t*>(buf), len);
+ data->setFreshnessPeriod(1000*freshness);
+
+ m_ioService->post(bind(&SyncSocket::publishDataInternal, this, data, prefix, session,seq));
+
+ return true;
+}
+
+void
+SyncSocket::publishDataInternal(shared_ptr<Data> data, const Name &prefix, uint64_t session,uint64_t seq)
+{
+ uint64_t sequence = seq;
+ Name dataName = prefix;
+ dataName.append(boost::lexical_cast<string>(session)).append(boost::lexical_cast<string>(sequence));
+ data->setName(dataName);
+
+ m_keyChain->sign(*data);
+ m_face->put(*data);
+
+ SeqNo s(session, sequence + 1);
+
+ m_sequenceLog[prefix] = s;
+ m_syncLogic.addLocalNames (prefix, session, sequence);
+}
+
+void
+SyncSocket::fetchData(const Name &prefix, const SeqNo &seq, const OnDataValidated& onValidated, int retry)
+{
+ Name interestName = prefix;
+ interestName.append(boost::lexical_cast<string>(seq.getSession())).append(boost::lexical_cast<string>(seq.getSeq()));
+
+ const OnDataValidationFailed& onValidationFailed = bind(&SyncSocket::onDataValidationFailed, this, _1);
+
+ ndn::Interest interest(interestName);
+ interest.setMustBeFresh(true);
+ m_face->expressInterest(interest,
+ bind(&SyncSocket::onData, this, _1, _2, onValidated, onValidationFailed),
+ bind(&SyncSocket::onDataTimeout, this, _1, retry, onValidated, onValidationFailed));
+
+}
+
+void
+SyncSocket::onData(const ndn::Interest& interest, Data& data,
+ const OnDataValidated& onValidated,
+ const OnDataValidationFailed& onValidationFailed)
+{
+ m_validator->validate(data, onValidated, onValidationFailed);
+}
+
+void
+SyncSocket::onDataTimeout(const ndn::Interest& interest,
+ int retry,
+ const OnDataValidated& onValidated,
+ const OnDataValidationFailed& onValidationFailed)
+{
+ if(retry > 0)
+ {
+ m_face->expressInterest(interest,
+ bind(&SyncSocket::onData,
+ this,
+ _1,
+ _2,
+ onValidated,
+ onValidationFailed),
+ bind(&SyncSocket::onDataTimeout,
+ this,
+ _1,
+ retry - 1,
+ onValidated,
+ onValidationFailed));
+
+ }
+ else
+ _LOG_DEBUG("interest eventually time out!");
+}
+
+void
+SyncSocket::onDataValidationFailed(const shared_ptr<const Data>& data)
+{
+ _LOG_DEBUG("data cannot be verified!");
+}
+
+
+uint64_t
+SyncSocket::getNextSeq (const Name &prefix, uint64_t session)
+{
+ SequenceLog::iterator i = m_sequenceLog.find (prefix);
+
+ if (i != m_sequenceLog.end ())
+ {
+ SeqNo s = i->second;
+ if (s.getSession() == session)
+ return s.getSeq();
+ }
+ return 0;
+}
+
+}//Sync
diff --git a/nsync/src/sync-socket.h b/nsync/src/sync-socket.h
new file mode 100644
index 0000000..e4eec37
--- /dev/null
+++ b/nsync/src/sync-socket.h
@@ -0,0 +1,128 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Yingdi Yu <yingdi@cs.ucla.edu>
+ */
+
+#ifndef _SYNC_SOCKET_H
+#define _SYNC_SOCKET_H
+
+#include <ndn-cpp-dev/face.hpp>
+#include <ndn-cpp-dev/security/validator.hpp>
+#include <ndn-cpp-dev/security/key-chain.hpp>
+
+#include "sync-logic.h"
+#include "sync-seq-no.h"
+
+#include <utility>
+#include <map>
+#include <vector>
+#include <sstream>
+
+namespace Sync {
+
+/**
+ * \ingroup sync
+ * @brief A simple interface to interact with client code
+ */
+class SyncSocket
+{
+public:
+ typedef ndn::function< void (const std::vector<MissingDataInfo> &, SyncSocket * ) > NewDataCallback;
+ typedef ndn::function< void (const std::string &/*prefix*/ ) > RemoveCallback;
+
+ /**
+ * @brief the constructor for SyncAppSocket; the parameter syncPrefix
+ * should be passed to the constructor of m_syncAppWrapper; the other
+ * parameter should be passed to the constructor of m_fetcher; furthermore,
+ * the fetch function of m_fetcher should be a second paramter passed to
+ * the constructor of m_syncAppWrapper, so that m_syncAppWrapper can tell
+ * m_fetcher to fetch the actual app data after it learns the names
+ *
+ * @param syncPrefix the name prefix for Sync Interest
+ * @param dataCallback the callback to process data
+ */
+ SyncSocket (const ndn::Name &syncPrefix,
+ ndn::shared_ptr<ndn::Validator> validator,
+ ndn::shared_ptr<ndn::Face> face,
+ NewDataCallback dataCallback,
+ RemoveCallback rmCallback);
+
+ ~SyncSocket ();
+
+ bool
+ publishData(const ndn::Name &prefix, uint64_t session, const char *buf, size_t len, int freshness,uint64_t seq);
+
+ void
+ remove (const ndn::Name &prefix)
+ { m_syncLogic.remove(prefix); }
+
+ void
+ fetchData(const ndn::Name &prefix, const SeqNo &seq, const ndn::OnDataValidated& onValidated, int retry = 0);
+
+ std::string
+ getRootDigest()
+ { return m_syncLogic.getRootDigest(); }
+
+ uint64_t
+ getNextSeq (const ndn::Name &prefix, uint64_t session);
+
+ SyncLogic &
+ getLogic ()
+ { return m_syncLogic; }
+
+ // make this a static function so we don't have to create socket instance without
+ // knowing the local prefix. it's a wrong place for this function anyway
+ static std::string
+ GetLocalPrefix ();
+
+private:
+ void
+ publishDataInternal(ndn::shared_ptr<ndn::Data> data, const ndn::Name &prefix, uint64_t session,uint64_t seq);
+
+ void
+ passCallback(const std::vector<MissingDataInfo> &v)
+ { m_newDataCallback(v, this); }
+
+ void
+ onData(const ndn::Interest& interest, ndn::Data& data,
+ const ndn::OnDataValidated& onValidated,
+ const ndn::OnDataValidationFailed& onValidationFailed);
+
+ void
+ onDataTimeout(const ndn::Interest& interest,
+ int retry,
+ const ndn::OnDataValidated& onValidated,
+ const ndn::OnDataValidationFailed& onValidationFailed);
+
+ void
+ onDataValidationFailed(const ndn::shared_ptr<const ndn::Data>& data);
+
+private:
+ typedef std::map<ndn::Name, SeqNo> SequenceLog;
+ NewDataCallback m_newDataCallback;
+ SequenceLog m_sequenceLog;
+ ndn::shared_ptr<ndn::Validator> m_validator;
+ ndn::shared_ptr<ndn::KeyChain> m_keyChain;
+ ndn::shared_ptr<ndn::Face> m_face;
+ ndn::shared_ptr<boost::asio::io_service> m_ioService;
+ SyncLogic m_syncLogic;
+};
+
+} // Sync
+
+#endif // SYNC_SOCKET_H
diff --git a/nsync/src/sync-state-leaf-container.h b/nsync/src/sync-state-leaf-container.h
new file mode 100644
index 0000000..48819aa
--- /dev/null
+++ b/nsync/src/sync-state-leaf-container.h
@@ -0,0 +1,101 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_STATE_LEAF_CONTAINER
+#define SYNC_STATE_LEAF_CONTAINER
+
+#include "sync-leaf.h"
+#include "sync-name-info.h"
+
+#include <boost/multi_index_container.hpp>
+// #include <boost/multi_index/tag.hpp>
+#include <boost/multi_index/ordered_index.hpp>
+// #include <boost/multi_index/composite_key.hpp>
+#include <boost/multi_index/hashed_index.hpp>
+// #include <boost/multi_index/random_access_index.hpp>
+// #include <boost/multi_index/member.hpp>
+#include <boost/multi_index/mem_fun.hpp>
+
+namespace mi = boost::multi_index;
+
+namespace Sync {
+
+struct NameInfoHash : public std::unary_function<NameInfo, std::size_t>
+{
+ std::size_t
+ operator() (NameInfoConstPtr prefix) const
+ {
+ return prefix->getHashId ();
+ }
+};
+
+struct NameInfoEqual : public std::unary_function<NameInfo, std::size_t>
+{
+ bool
+ operator() (NameInfoConstPtr prefix1, NameInfoConstPtr prefix2) const
+ {
+ return *prefix1 == *prefix2;
+ }
+};
+
+struct NameInfoCompare : public std::unary_function<NameInfo, std::size_t>
+{
+ bool
+ operator() (NameInfoConstPtr prefix1, NameInfoConstPtr prefix2) const
+ {
+ return *prefix1 < *prefix2;
+ }
+};
+
+/// @cond include_hidden
+struct hashed { };
+struct ordered { };
+/// @endcond
+
+/**
+ * \ingroup sync
+ * @brief Container for SYNC leaves
+ */
+struct LeafContainer : public mi::multi_index_container<
+ LeafPtr,
+ mi::indexed_by<
+ // For fast access to elements using NameInfo
+ mi::hashed_unique<
+ mi::tag<hashed>,
+ mi::const_mem_fun<Leaf, NameInfoConstPtr, &Leaf::getInfo>,
+ NameInfoHash,
+ NameInfoEqual
+ >,
+
+ mi::ordered_unique<
+ mi::tag<ordered>,
+ mi::const_mem_fun<Leaf, NameInfoConstPtr, &Leaf::getInfo>,
+ NameInfoCompare
+ >
+ >
+ >
+{
+};
+
+} // Sync
+
+#endif // SYNC_STATE_LEAF_CONTAINER
diff --git a/nsync/src/sync-state.cc b/nsync/src/sync-state.cc
new file mode 100644
index 0000000..6c374a4
--- /dev/null
+++ b/nsync/src/sync-state.cc
@@ -0,0 +1,172 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include "sync-state.h"
+#include "sync-diff-leaf.h"
+#include "sync-std-name-info.h"
+
+#include <boost/assert.hpp>
+#include <boost/foreach.hpp>
+#include <boost/shared_ptr.hpp>
+#include <boost/throw_exception.hpp>
+#include <boost/lexical_cast.hpp>
+
+// using namespace std;
+using namespace boost;
+
+typedef error_info<struct tag_errmsg, std::string> info_str;
+
+using namespace Sync::Error;
+
+namespace Sync {
+
+/*
+std::ostream &
+operator << (std::ostream &os, const State &state)
+{
+ os << "<state>"; DEBUG_ENDL;
+
+ BOOST_FOREACH (shared_ptr<const Leaf> leaf, state.getLeaves ().get<ordered> ())
+ {
+ shared_ptr<const DiffLeaf> diffLeaf = dynamic_pointer_cast<const DiffLeaf> (leaf);
+ if (diffLeaf != 0)
+ {
+ os << "<item action=\"" << diffLeaf->getOperation () << "\">"; DEBUG_ENDL;
+ }
+ else
+ {
+ os << "<item>"; DEBUG_ENDL;
+ }
+ os << "<name>" << *leaf->getInfo () << "</name>"; DEBUG_ENDL;
+ if (diffLeaf == 0 || (diffLeaf != 0 && diffLeaf->getOperation () == UPDATE))
+ {
+ os << "<seq>" << leaf->getSeq () << "</seq>"; DEBUG_ENDL;
+ }
+ os << "</item>"; DEBUG_ENDL;
+ }
+ os << "</state>";
+}
+*/
+
+SyncStateMsg &
+operator << (SyncStateMsg &ossm, const State &state)
+{
+ BOOST_FOREACH (shared_ptr<const Leaf> leaf, state.getLeaves ().get<ordered> ())
+ {
+ SyncState *oss = ossm.add_ss();
+ shared_ptr<const DiffLeaf> diffLeaf = dynamic_pointer_cast<const DiffLeaf> (leaf);
+ if (diffLeaf != 0 && diffLeaf->getOperation() != UPDATE)
+ {
+ oss->set_type(SyncState::DELETE);
+ }
+ else
+ {
+ oss->set_type(SyncState::UPDATE);
+ }
+
+ std::ostringstream os;
+ os << *leaf->getInfo();
+ oss->set_name(os.str());
+
+ if (diffLeaf == 0 || (diffLeaf != 0 && diffLeaf->getOperation () == UPDATE))
+ {
+ SyncState::SeqNo *seqNo = oss->mutable_seqno();
+ seqNo->set_session(leaf->getSeq().getSession());
+ seqNo->set_seq(leaf->getSeq().getSeq());
+ }
+ }
+ return ossm;
+}
+
+/*
+std::istream &
+operator >> (std::istream &in, State &state)
+{
+ TiXmlDocument doc;
+ in >> doc;
+
+ if (doc.RootElement() == 0)
+ BOOST_THROW_EXCEPTION (SyncXmlDecodingFailure () << info_str ("Empty XML"));
+
+ for (TiXmlElement *iterator = doc.RootElement()->FirstChildElement ("item");
+ iterator != 0;
+ iterator = iterator->NextSiblingElement("item"))
+ {
+ TiXmlElement *name = iterator->FirstChildElement ("name");
+ if (name == 0 || name->GetText() == 0)
+ BOOST_THROW_EXCEPTION (SyncXmlDecodingFailure () << info_str ("<name> element is missing"));
+
+ NameInfoConstPtr info = StdNameInfo::FindOrCreate (name->GetText());
+
+ if (iterator->Attribute("action") == 0 || strcmp(iterator->Attribute("action"), "update") == 0)
+ {
+ TiXmlElement *seq = iterator->FirstChildElement ("seq");
+ if (seq == 0)
+ BOOST_THROW_EXCEPTION (SyncXmlDecodingFailure () << info_str ("<seq> element is missing"));
+
+ TiXmlElement *session = seq->FirstChildElement ("session");
+ TiXmlElement *seqno = seq->FirstChildElement ("seqno");
+
+ if (session == 0 || session->GetText() == 0)
+ BOOST_THROW_EXCEPTION (SyncXmlDecodingFailure () << info_str ("<session> element is missing"));
+ if (seqno == 0 || seqno->GetText() == 0)
+ BOOST_THROW_EXCEPTION (SyncXmlDecodingFailure () << info_str ("<seqno> element is missing"));
+
+ state.update (info, SeqNo (
+ lexical_cast<uint32_t> (session->GetText()),
+ lexical_cast<uint32_t> (seqno->GetText())
+ ));
+ }
+ else
+ {
+ state.remove (info);
+ }
+ }
+
+ return in;
+}
+*/
+
+SyncStateMsg &
+operator >> (SyncStateMsg &issm, State &state)
+{
+ int n = issm.ss_size();
+ for (int i = 0; i < n; i++)
+ {
+ const SyncState &ss = issm.ss(i);
+ NameInfoConstPtr info = StdNameInfo::FindOrCreate (ss.name());
+ if (ss.type() == SyncState::UPDATE)
+ {
+ uint64_t session = lexical_cast<uint64_t>(ss.seqno().session());
+ uint64_t seq = lexical_cast<uint64_t>(ss.seqno().seq());
+ SeqNo seqNo(session, seq);
+ state.update(info, seqNo);
+ }
+ else
+ {
+ state.remove(info);
+ }
+ }
+ return issm;
+}
+
+}
diff --git a/nsync/src/sync-state.h b/nsync/src/sync-state.h
new file mode 100644
index 0000000..54ac9d9
--- /dev/null
+++ b/nsync/src/sync-state.h
@@ -0,0 +1,117 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_STATE_H
+#define SYNC_STATE_H
+
+#include "sync-state-leaf-container.h"
+#include <boost/exception/all.hpp>
+#include "boost/tuple/tuple.hpp"
+#include "sync-state.pb.h"
+
+/**
+ * \defgroup sync SYNC protocol
+ *
+ * Implementation of SYNC protocol
+ */
+namespace Sync {
+
+/**
+ * \ingroup sync
+ * @brief this prefix will be used for the dummy node which increases its sequence number whenever
+ * a remove operation happens; this is to prevent the reversion of root digest when we prune
+ * a branch, i.e. help the root digest to be forward only
+ * No corresponding data msg would be published and no attempt would be made to retrieve the
+ * data msg
+ */
+const std::string forwarderPrefix = "/d0n0t18ak/t0ps8cr8t";
+
+class State;
+typedef boost::shared_ptr<State> StatePtr;
+typedef boost::shared_ptr<State> StateConstPtr;
+
+/**
+ * \ingroup sync
+ * @brief Container for state leaves and definition of the abstract interface to work with State objects
+ */
+class State
+{
+public:
+ virtual ~State () { };
+
+ /**
+ * @brief Add or update leaf to the state tree
+ *
+ * @param info name of the leaf
+ * @param seq sequence number of the leaf
+ */
+ virtual boost::tuple<bool/*inserted*/, bool/*updated*/, SeqNo/*oldSeqNo*/>
+ update (NameInfoConstPtr info, const SeqNo &seq) = 0;
+
+ /**
+ * @brief Remove leaf from the state tree
+ * @param info name of the leaf
+ */
+ virtual bool
+ remove (NameInfoConstPtr info) = 0;
+
+ /**
+ * @brief Get state leaves
+ */
+ const LeafContainer &
+ getLeaves () const
+ { return m_leaves; }
+
+protected:
+ LeafContainer m_leaves;
+};
+
+
+/**
+ * @brief Formats a protobuf SyncStateMsg msg
+ * @param oss output SyncStateMsg msg
+ * @param state state
+ * @returns output SyncStateMsg msg
+ */
+SyncStateMsg &
+operator << (SyncStateMsg &ossm, const State &state);
+
+
+/**
+ * @brief Parse a protobuf SyncStateMsg msg
+ * @param iss input SyncStateMsg msg
+ * @param state state
+ * @returns SyncStateMsg msg
+ */
+SyncStateMsg &
+operator >> (SyncStateMsg &issm, State &state);
+
+namespace Error {
+/**
+ * @brief Will be thrown when data cannot be properly decoded to SyncStateMsg
+ */
+struct SyncStateMsgDecodingFailure : virtual boost::exception, virtual std::exception { };
+}
+
+} // Sync
+
+#endif // SYNC_STATE_H
diff --git a/nsync/src/sync-state.proto b/nsync/src/sync-state.proto
new file mode 100644
index 0000000..7cc6b18
--- /dev/null
+++ b/nsync/src/sync-state.proto
@@ -0,0 +1,24 @@
+package Sync;
+
+message SyncState
+{
+ required string name = 1;
+ enum ActionType
+ {
+ UPDATE = 0;
+ DELETE = 1;
+ OTHER = 2;
+ }
+ required ActionType type = 2;
+ message SeqNo
+ {
+ required uint64 seq = 1;
+ required uint64 session = 2;
+ }
+ optional SeqNo seqno = 3;
+}
+
+message SyncStateMsg
+{
+ repeated SyncState ss = 1;
+}
diff --git a/nsync/src/sync-std-name-info.cc b/nsync/src/sync-std-name-info.cc
new file mode 100644
index 0000000..2c0313d
--- /dev/null
+++ b/nsync/src/sync-std-name-info.cc
@@ -0,0 +1,92 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include "sync-std-name-info.h"
+
+// using namespace std;
+using namespace boost;
+
+namespace Sync {
+
+
+NameInfoConstPtr
+StdNameInfo::FindOrCreate (const std::string &key)
+{
+ // std::cout << "FindOrCreate: " << m_names.size () << "\n";
+
+ NameInfoConstPtr ret;
+
+ NameMap::iterator item = m_names.find (key);
+ if (item != m_names.end ())
+ {
+ ret = item->second.lock ();
+ BOOST_ASSERT (ret != 0);
+ }
+ else
+ {
+ ret = NameInfoPtr (new StdNameInfo (key));
+ weak_ptr<const NameInfo> value (ret);
+ std::pair<NameMap::iterator,bool> inserted =
+ m_names.insert (make_pair (key, value));
+
+ BOOST_ASSERT (inserted.second); // previous call has to insert value
+ item = inserted.first;
+ }
+
+ return ret;
+}
+
+StdNameInfo::StdNameInfo (const std::string &name)
+ : m_name (name)
+{
+ m_id = m_ids ++; // set ID for a newly inserted element
+ m_digest << name;
+ m_digest.finalize ();
+
+ // std::cout << "StdNameInfo: " << name << " = " << m_id << "\n";
+}
+
+StdNameInfo::~StdNameInfo ()
+{
+ // cout << "Destructor for " << m_name << "\n";
+ m_names.erase (toString ());
+}
+
+std::string
+StdNameInfo::toString () const
+{
+ return m_name;
+}
+
+bool
+StdNameInfo::operator == (const NameInfo &info) const
+{
+ return m_name == dynamic_cast<const StdNameInfo&> (info).m_name;
+}
+
+bool
+StdNameInfo::operator < (const NameInfo &info) const
+{
+ return m_name < dynamic_cast<const StdNameInfo&> (info).m_name;
+}
+
+} // Sync
diff --git a/nsync/src/sync-std-name-info.h b/nsync/src/sync-std-name-info.h
new file mode 100644
index 0000000..83bbebb
--- /dev/null
+++ b/nsync/src/sync-std-name-info.h
@@ -0,0 +1,74 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#ifndef SYNC_STD_NAME_INFO_H
+#define SYNC_STD_NAME_INFO_H
+
+#include "sync-name-info.h"
+#include <string>
+
+namespace Sync {
+
+class StdNameInfo : public NameInfo
+{
+public:
+ /**
+ * @brief Lookup existing or create new NameInfo object
+ * @param name routable prefix
+ */
+ static NameInfoConstPtr
+ FindOrCreate (const std::string &name);
+
+ /**
+ * @brief Destructor which will clean up m_names structure
+ */
+ virtual ~StdNameInfo ();
+
+ // from NameInfo
+ virtual bool
+ operator == (const NameInfo &info) const;
+
+ virtual bool
+ operator < (const NameInfo &info) const;
+
+ virtual std::string
+ toString () const;
+
+private:
+ // implementing a singleton pattern.
+ /**
+ * @brief Disabled default constructor. NameInfo object should be created through FindOrCreate static call.
+ */
+
+ /**
+ * @brief Disabled default
+ */
+ StdNameInfo () {}
+ StdNameInfo& operator = (const StdNameInfo &info) { (void)info; return *this; }
+ StdNameInfo (const std::string &name);
+
+ std::string m_name;
+};
+
+} // Sync
+
+#endif // SYNC_CCNX_NAME_INFO_H
diff --git a/nsync/tests/main.cc b/nsync/tests/main.cc
new file mode 100644
index 0000000..6b0a14a
--- /dev/null
+++ b/nsync/tests/main.cc
@@ -0,0 +1,13 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2013, Regents of the University of California
+ *
+ * BSD license, See the LICENSE file for more information
+ *
+ * Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#define BOOST_TEST_MAIN 1
+#define BOOST_TEST_DYN_LINK 1
+
+#include <boost/test/unit_test.hpp>
diff --git a/nsync/tests/test_data_fetch_and_publish.cc b/nsync/tests/test_data_fetch_and_publish.cc
new file mode 100644
index 0000000..c1eb5df
--- /dev/null
+++ b/nsync/tests/test_data_fetch_and_publish.cc
@@ -0,0 +1,111 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+/*
+#include <boost/test/unit_test.hpp>
+#include <boost/test/output_test_stream.hpp>
+#include <map>
+using boost::test_tools::output_test_stream;
+
+#include <boost/make_shared.hpp>
+
+#include "sync-ccnx-wrapper.h"
+#include "sync-app-data-fetch.h"
+#include "sync-app-data-publish.h"
+
+using namespace Sync;
+using namespace std;
+using namespace boost;
+
+class TestStructApp {
+public:
+ map<string, string> data;
+ void set(string str1, string str2) {
+ data.insert(make_pair(str1, str2));
+ }
+
+ void erase(string str1, string str2) {
+ data.erase(str1);
+ }
+
+ string toString(){
+ map<string, string>::iterator it = data.begin();
+ string str = "";
+ for (; it != data.end(); ++it){
+ str += "<";
+ str += it->first;
+ str += "|";
+ str += it->second;
+ str += ">";
+ }
+ return str;
+ }
+
+};
+
+BOOST_AUTO_TEST_CASE (AppDataPublishAndFetchTest)
+{
+ TestStructApp foo;
+ TestStructApp bar;
+
+ string interest = "/april/fool";
+ string seq[5] = {"0", "1", "2", "3", "4" };
+ string str[5] = {"panda", "express", "tastes", "so", "good"};
+
+ for (int i = 0; i < 5; i++) {
+ foo.set(interest + "/" + "0/" + seq[i], str[i]);
+ }
+
+ boost::function<void (string, string)> setFunc =
+ bind(&TestStructApp::set, &bar, _1, _2);
+
+ shared_ptr<CcnxWrapper> handle(new CcnxWrapper());
+
+ AppDataFetch fetcher(handle, setFunc);
+ AppDataPublish publisher(handle);
+
+ for (int i = 1; i <= 5; i++) {
+ publisher.publishData(interest, 0, str[i - 1], 5);
+ }
+
+ BOOST_CHECK_EQUAL(publisher.getNextSeq(interest, 0), 5);
+ BOOST_CHECK_EQUAL(publisher.getRecentData(interest, 0), str[4]);
+
+ fetcher.onUpdate (interest, SeqNo (0,4), SeqNo (0,-1));
+ // give time for ccnd to react
+ sleep(1);
+ BOOST_CHECK_EQUAL(foo.toString(), bar.toString());
+
+
+ boost::function<void (string, string)> eraseFunc =
+ bind(&TestStructApp::erase, &bar, _1, _2);
+ fetcher.setDataCallback(eraseFunc);
+
+ fetcher.onUpdate (interest, SeqNo (0,4), SeqNo (0,-1));
+ // give time for ccnd to react
+ sleep(1);
+ TestStructApp poo;
+
+ BOOST_CHECK_EQUAL(poo.toString(), bar.toString());
+
+}
+*/
diff --git a/nsync/tests/test_digest.cc b/nsync/tests/test_digest.cc
new file mode 100644
index 0000000..4815919
--- /dev/null
+++ b/nsync/tests/test_digest.cc
@@ -0,0 +1,104 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include <boost/test/unit_test.hpp>
+#include <boost/test/output_test_stream.hpp>
+using boost::test_tools::output_test_stream;
+
+#include "sync-digest.h"
+#include <iostream>
+#include <sstream>
+
+using namespace Sync;
+using namespace Sync::Error;
+using namespace std;
+using namespace boost;
+
+BOOST_AUTO_TEST_SUITE(DigestTests)
+
+BOOST_AUTO_TEST_CASE (BasicTest)
+{
+ Digest d0;
+ BOOST_REQUIRE (d0.empty ());
+}
+
+BOOST_AUTO_TEST_CASE (DigestGenerationTest)
+{
+ Digest d1;
+ BOOST_CHECK_NO_THROW (d1 << "1\n");
+
+ // without explicit finalizing, Digest will not be complete and printing out will cause assert
+ BOOST_CHECK (d1.empty ());
+
+ // fix hash
+ d1.finalize ();
+
+ BOOST_CHECK_NO_THROW (d1.getHash ());
+ BOOST_CHECK (!d1.empty ());
+ BOOST_CHECK (d1 == d1);
+
+ BOOST_CHECK_THROW (d1 << "2", DigestCalculationError);
+
+ output_test_stream output;
+ BOOST_CHECK_NO_THROW (output << d1);
+ // BOOST_CHECK (output.check_length (40, false) );
+ // BOOST_CHECK (output.is_equal ("e5fa44f2b31c1fb553b6021e7360d07d5d91ff5e", true)); // for sha1
+ BOOST_CHECK (output.check_length (64, false) );
+ BOOST_CHECK (output.is_equal ("4355a46b19d348dc2f57c046f8ef63d4538ebb936000f3c9ee954a27460dd865", true)); // for sha256
+}
+
+BOOST_AUTO_TEST_CASE (DigestComparison)
+{
+ Digest d1;
+ BOOST_CHECK_NO_THROW (d1 << "1\n");
+ // BOOST_CHECK_THROW (d1 == d1, DigestCalculationError);
+ BOOST_CHECK_NO_THROW (d1.finalize ());
+ BOOST_CHECK (d1 == d1);
+
+ Digest d2;
+ BOOST_CHECK_NO_THROW (d2 << "2\n");
+ BOOST_CHECK_NO_THROW (d2.finalize ());
+ BOOST_CHECK (d1 != d2);
+
+ Digest d3;
+ // istringstream is (string ("e5fa44f2b31c1fb553b6021e7360d07d5d91ff5e")); // real sha-1 for "1\n"
+ istringstream is (string ("4355a46b19d348dc2f57c046f8ef63d4538ebb936000f3c9ee954a27460dd865")); // real sha256 for "1\n"
+ BOOST_CHECK_NO_THROW (is >> d3);
+ BOOST_CHECK (!d3.empty ());
+ BOOST_CHECK (d3 == d1);
+ BOOST_CHECK (d3 != d2);
+
+ istringstream is2 (string ("25fa44f2b31c1fb553b6021e7360d07d5d91ff5e")); // some fake hash
+ BOOST_CHECK_THROW (is2 >> d3, DigestCalculationError); // >> can be used only once
+
+ Digest d4;
+ BOOST_CHECK_THROW (is2 >> d4, DigestCalculationError); // is2 is now empty. empty >> is not allowed
+
+ istringstream is3 (string ("25fa44f2b31c1fb553b6021e7360d07d5d91ff5e")); // some fake hash
+ BOOST_CHECK_NO_THROW (is3 >> d4);
+
+ BOOST_CHECK (d4 != d1);
+ BOOST_CHECK (d4 != d2);
+ BOOST_CHECK (d4 != d3);
+}
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/nsync/tests/test_interest_table.cc b/nsync/tests/test_interest_table.cc
new file mode 100644
index 0000000..9f31551
--- /dev/null
+++ b/nsync/tests/test_interest_table.cc
@@ -0,0 +1,46 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include <boost/test/unit_test.hpp>
+#include <boost/test/output_test_stream.hpp>
+#include <map>
+using boost::test_tools::output_test_stream;
+
+#include <boost/make_shared.hpp>
+
+#include "sync-interest-table.h"
+
+using namespace Sync;
+using namespace std;
+using namespace boost;
+
+BOOST_AUTO_TEST_CASE (InterestTableTest)
+{
+ // Alex: test is broken due to changes in SyncInterestTable
+ cerr << "InterestTableTest is broken" << endl;
+
+ // SyncInterestTable *table = 0;
+ // BOOST_CHECK_NO_THROW (table = new SyncInterestTable ());
+
+ // BOOST_CHECK_NO_THROW (delete table);
+}
+
diff --git a/nsync/tests/test_leaf.cc b/nsync/tests/test_leaf.cc
new file mode 100644
index 0000000..49afcc5
--- /dev/null
+++ b/nsync/tests/test_leaf.cc
@@ -0,0 +1,108 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include <boost/test/unit_test.hpp>
+#include <boost/test/output_test_stream.hpp>
+using boost::test_tools::output_test_stream;
+
+#include <boost/make_shared.hpp>
+
+#include "sync-full-leaf.h"
+#include "sync-diff-leaf.h"
+#include "sync-std-name-info.h"
+
+using namespace Sync;
+using namespace std;
+using namespace boost;
+
+BOOST_AUTO_TEST_SUITE(LeafTests)
+
+BOOST_AUTO_TEST_CASE (LeafBase)
+{
+ NameInfoConstPtr name = StdNameInfo::FindOrCreate ("/test/name");
+ BOOST_CHECK (name != 0);
+
+ // find the same name
+ BOOST_CHECK (name.get () == StdNameInfo::FindOrCreate ("/test/name").get ());
+ BOOST_CHECK_EQUAL (name.use_count (), 1);
+
+ BOOST_CHECK_NO_THROW (DiffLeaf x (name, SeqNo (12)));
+ BOOST_CHECK_EQUAL (name.use_count (), 1);
+
+ BOOST_CHECK_NO_THROW (DiffLeaf x (name));
+ BOOST_CHECK_EQUAL (name.use_count (), 1);
+
+ DiffLeaf updateLeaf (name, SeqNo (12));
+ BOOST_CHECK_EQUAL (name.use_count (), 2);
+
+ DiffLeaf removeLeaf (name);
+ BOOST_CHECK_EQUAL (name.use_count (), 3);
+
+ BOOST_CHECK_EQUAL (updateLeaf.getOperation (), UPDATE);
+ BOOST_CHECK_EQUAL (updateLeaf.getSeq ().getSession (), 0);
+ BOOST_CHECK_EQUAL (updateLeaf.getSeq ().getSeq (), 12);
+
+ BOOST_CHECK_EQUAL (removeLeaf.getOperation (), REMOVE);
+ BOOST_CHECK_EQUAL (removeLeaf.getSeq ().getSession (), 0);
+ BOOST_CHECK_EQUAL (removeLeaf.getSeq ().getSeq (), 0);
+
+ BOOST_REQUIRE_NO_THROW (FullLeaf x (name, SeqNo (12)));
+ FullLeaf fullLeaf (name, SeqNo (12));
+ BOOST_CHECK_EQUAL (name.use_count (), 4);
+}
+
+BOOST_AUTO_TEST_CASE (LeafDigest)
+{
+ BOOST_CHECK_EQUAL (StdNameInfo::FindOrCreate ("/test/name").use_count (), 1);
+ NameInfoConstPtr name = StdNameInfo::FindOrCreate ("/test/name");
+ FullLeaf fullLeaf (name, SeqNo (12));
+
+ // fullLeafDigest = hash ( hash(name), hash (session, seqNo) )
+
+ // Digest manualDigest;
+
+ // Digest manualNameDigest;
+ // manualNameDigest << "/test/name";
+ // manualNameDigest.finalize ();
+
+ // Digest manualSeqNoDigest;
+ // manualSeqNoDigest << 0 << 13;
+ // manualSeqNoDigest.finalize ();
+
+ // manualDigest << manualNameDigest << manualSeqNoDigest;
+ // manualDigest.finalize ();
+
+ // cout << manualDigest << "\n\n";
+
+ output_test_stream output;
+ output << fullLeaf.getDigest ();
+ // BOOST_CHECK (output.is_equal ("991f8cf6262dfe0f519c63f6e9b92fe69e741a9b", true)); // for sha1
+ BOOST_CHECK (output.is_equal ("526d63e6e1f05f97502fd500a1729c4907f3841483ae4561b7e6307c40188f35", true)); // for sha256
+
+ fullLeaf.setSeq (SeqNo (13));
+ output << fullLeaf.getDigest ();
+ BOOST_CHECK (!output.is_equal ("991f8cf6262dfe0f519c63f6e9b92fe69e741a9b", false));
+ // BOOST_CHECK (output.is_equal ("585a8687ab41d5c29f86e5906c8f188ddca816b3", true)); // for sha1
+ BOOST_CHECK (output.is_equal ("39fefe65b3e1021776c07d3a9a3023c6c7cdf12724ee7f3a98b813b22f46d5ec", true)); // for sha256
+}
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/nsync/tests/test_pit.cc b/nsync/tests/test_pit.cc
new file mode 100644
index 0000000..5e48180
--- /dev/null
+++ b/nsync/tests/test_pit.cc
@@ -0,0 +1,77 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include <boost/test/unit_test.hpp>
+#include <boost/test/output_test_stream.hpp>
+using boost::test_tools::output_test_stream;
+#include <vector>
+
+#include <boost/make_shared.hpp>
+
+#include "sync-interest-table.h"
+#include "sync-logging.h"
+
+using namespace Sync;
+using namespace std;
+using namespace boost;
+
+// string sitToString(SyncInterestTable *sit) {
+// vector<string> ent = sit->fetchAll();
+// sort(ent.begin(), ent.end());
+// string str = "";
+// while(!ent.empty()){
+// str += ent.back();
+// ent.pop_back();
+// }
+// return str;
+// }
+
+BOOST_AUTO_TEST_CASE (SyncInterestTableTest)
+{
+ cerr << "SyncInterestTableTest is broken" << endl;
+
+ // INIT_LOGGERS ();
+ // INIT_LOGGER ("Test.Pit");
+
+ // SyncInterestTable sit;
+ // sit.insert("/ucla.edu/0");
+ // sit.insert("/ucla.edu/1");
+ // string str = sitToString(&sit);
+ // BOOST_CHECK_EQUAL(str, "/ucla.edu/1/ucla.edu/0");
+
+ // str = sitToString(&sit);
+ // BOOST_CHECK_EQUAL(str, "");
+
+ // _LOG_DEBUG ("Adding 0 and 1");
+ // sit.insert("/ucla.edu/0");
+ // sit.insert("/ucla.edu/1");
+ // sleep(2);
+ // _LOG_DEBUG ("Adding 0 and 2");
+ // sit.insert("/ucla.edu/0");
+ // sit.insert("/ucla.edu/2");
+ // sleep(3);
+ // _LOG_DEBUG ("Checking");
+ // str = sitToString(&sit);
+ // BOOST_CHECK_EQUAL(str, "/ucla.edu/2/ucla.edu/0");
+}
+
+
diff --git a/nsync/tests/test_scheduler.cc.tmp b/nsync/tests/test_scheduler.cc.tmp
new file mode 100644
index 0000000..0d67417
--- /dev/null
+++ b/nsync/tests/test_scheduler.cc.tmp
@@ -0,0 +1,178 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include <boost/test/unit_test.hpp>
+#include <boost/test/output_test_stream.hpp>
+#include <map>
+using boost::test_tools::output_test_stream;
+
+#include <boost/make_shared.hpp>
+#include "sync-scheduler.h"
+#include "sync-logic.h"
+
+using namespace Sync;
+using namespace std;
+using namespace boost;
+
+
+
+// void funcUpdate (const std::string &, const SeqNo &newSeq, const SeqNo &oldSeq)
+// {
+// cout << "funcUpdate\n";
+// }
+
+// void funcRemove (const std::string &)
+// {
+// cout << "funcRemove\n";
+// }
+
+enum SCHEDULE_LABELS
+ {
+ TEST_LABEL,
+ ANOTHER_LABEL
+ };
+
+struct SchedulerFixture
+{
+ SchedulerFixture ()
+ : counter (0)
+ {}
+
+ int counter;
+
+ Scheduler *scheduler;
+
+ void everySecond ()
+ {
+ // cout << "." << flush;
+ counter ++;
+
+ if (counter < 9)
+ scheduler->schedule (boost::posix_time::milliseconds (100),
+ boost::bind (&SchedulerFixture::everySecond, this),
+ TEST_LABEL);
+ }
+
+ void setCounterFive ()
+ {
+ counter = 5;
+ }
+
+ void setCounterThree ()
+ {
+ counter = 3;
+ }
+};
+
+
+#ifdef _DEBUG
+
+BOOST_FIXTURE_TEST_SUITE (SchedulerTestSuite, SchedulerFixture)
+
+BOOST_AUTO_TEST_CASE (BasicTest)
+{
+ BOOST_CHECK_NO_THROW (scheduler = new Scheduler ());
+
+ scheduler->schedule (posix_time::milliseconds (100),
+ bind (&SchedulerFixture::everySecond, this),
+ TEST_LABEL);
+
+ sleep (1);
+ // cout << counter << endl;
+ BOOST_CHECK_EQUAL (counter, 9); // generally, should be 9
+
+ scheduler->schedule (posix_time::seconds (2),
+ bind (&SchedulerFixture::setCounterFive, this),
+ TEST_LABEL);
+
+ this_thread::sleep (posix_time::milliseconds (400)); // just in case
+
+ scheduler->schedule (posix_time::milliseconds (600),
+ bind (&SchedulerFixture::setCounterThree, this),
+ TEST_LABEL);
+
+ this_thread::sleep (posix_time::milliseconds (500));
+ BOOST_CHECK_EQUAL (counter, 9); // still 9
+
+ this_thread::sleep (posix_time::milliseconds (200));
+ BOOST_CHECK_EQUAL (counter, 3);
+
+ this_thread::sleep (posix_time::milliseconds (1000));
+ BOOST_CHECK_EQUAL (counter, 5);
+
+ scheduler->schedule (posix_time::milliseconds (100),
+ bind (&SchedulerFixture::setCounterThree, this),
+ ANOTHER_LABEL);
+ this_thread::sleep (posix_time::milliseconds (50));
+ scheduler->cancel (ANOTHER_LABEL);
+ this_thread::sleep (posix_time::milliseconds (150));
+ BOOST_CHECK_EQUAL (counter, 5);
+
+ BOOST_CHECK_NO_THROW (delete scheduler);
+}
+
+BOOST_AUTO_TEST_SUITE_END ()
+
+
+void funcUpdate( const std::string &/*prefix*/, const SeqNo &/*newSeq*/, const SeqNo &/*oldSeq*/ )
+{
+}
+
+void funcPass( const std::vector<MissingDataInfo> &v)
+{
+}
+
+void funcRemove( const std::string &/*prefix*/ )
+{
+}
+
+BOOST_AUTO_TEST_CASE (SyncLogicSchedulerTest)
+{
+ SyncLogic *logic = 0;
+ BOOST_CHECK_NO_THROW (logic = new SyncLogic ("/prefix", funcPass, funcRemove));
+ this_thread::sleep (posix_time::milliseconds (100));
+
+ Scheduler &scheduler = logic->getScheduler ();
+ BOOST_CHECK_EQUAL (scheduler.getEventsSize (), 1);
+
+ BOOST_CHECK_NO_THROW (logic->respondSyncInterest ("/prefix/e5fa44f2b31c1fb553b6021e7360d07d5d91ff5e"));
+ BOOST_CHECK_EQUAL (scheduler.getEventsSize (), 2);
+
+ this_thread::sleep (posix_time::milliseconds (100)); // max waiting time
+ BOOST_CHECK_EQUAL (scheduler.getEventsSize (), 1);
+
+ BOOST_CHECK_NO_THROW (logic->respondSyncInterest ("/prefix/e5fa44f2b31c1fb553b6021e7360d07d5d91ff5e"));
+ BOOST_CHECK_NO_THROW (logic->respondSyncInterest ("/prefix/e5fa44f2b31c1fb553b6021e7360d07d5d91ff5e"));
+ BOOST_CHECK_NO_THROW (logic->respondSyncInterest ("/prefix/e5fa44f2b31c1fb553b6021e7360d07d5d91ff5e"));
+ BOOST_CHECK_NO_THROW (logic->respondSyncInterest ("/prefix/e5fa44f2b31c1fb553b6021e7360d07d5d91ff5e"));
+ BOOST_CHECK_EQUAL (scheduler.getEventsSize (), 5);
+
+ this_thread::sleep (posix_time::milliseconds (19)); // min waiting time is 20
+ BOOST_CHECK_EQUAL (scheduler.getEventsSize (), 5);
+
+ this_thread::sleep (posix_time::milliseconds (100)); // max waiting time
+ BOOST_CHECK_EQUAL (scheduler.getEventsSize (), 1);
+
+ BOOST_CHECK_NO_THROW (delete logic);
+}
+
+#endif
diff --git a/nsync/tests/test_socket.cc b/nsync/tests/test_socket.cc
new file mode 100644
index 0000000..60a87f3
--- /dev/null
+++ b/nsync/tests/test_socket.cc
@@ -0,0 +1,399 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include <boost/test/unit_test.hpp>
+#include <boost/test/output_test_stream.hpp>
+using boost::test_tools::output_test_stream;
+
+#include <boost/make_shared.hpp>
+#include <boost/date_time/posix_time/posix_time.hpp>
+
+#include "sync-logging.h"
+#include "sync-socket.h"
+#include <ndn-cpp-dev/security/validator-null.hpp>
+
+extern "C" {
+#include <unistd.h>
+}
+
+using namespace Sync;
+using namespace std;
+using namespace boost;
+
+INIT_LOGGER ("Test.AppSocket");
+
+#define PRINT
+//std::cout << "Line: " << __LINE__ << std::endl;
+
+class TestSocketApp {
+public:
+ TestSocketApp()
+ : sum(0)
+ {}
+
+ map<ndn::Name, string> data;
+ void set(const ndn::shared_ptr<const ndn::Data>& dataPacket) {
+ // _LOG_FUNCTION (this << ", " << str1);
+ ndn::Name dataName(dataPacket->getName());
+ string str2(reinterpret_cast<const char*>(dataPacket->getContent().value()), dataPacket->getContent().value_size());
+ data.insert(make_pair(dataName, str2));
+ // cout << str1 << ", " << str2 << endl;
+ }
+
+ void set(ndn::Name name, const char * buf, int len) {
+ string str2(buf, len);
+ data.insert(make_pair(name, str2));
+ }
+
+ void setNum(const ndn::shared_ptr<const ndn::Data>& dataPacket) {
+ int n = dataPacket->getContent().value_size() / 4;
+ uint32_t *numbers = new uint32_t [n];
+ memcpy(numbers, dataPacket->getContent().value(), dataPacket->getContent().value_size());
+ for (int i = 0; i < n; i++) {
+ sum += numbers[i];
+ }
+ delete numbers;
+
+ }
+
+ void setNum(ndn::Name name, const char * buf, int len) {
+ int n = len / 4;
+ int *numbers = new int [n];
+ memcpy(numbers, buf, len);
+ for (int i = 0; i < n; i++) {
+ sum += numbers[i];
+ }
+ delete numbers;
+ }
+
+ uint32_t sum;
+
+ void fetchAll(const vector<MissingDataInfo> &v, SyncSocket *socket) {
+ int n = v.size();
+
+ PRINT
+
+ for (int i = 0; i < n; i++) {
+ for(SeqNo s = v[i].low; s <= v[i].high; ++s) {
+ //PRINT
+ socket->fetchData(v[i].prefix, s, bind(&TestSocketApp::set, this, _1));
+ }
+ }
+ }
+
+ void fetchNumbers(const vector<MissingDataInfo> &v, SyncSocket *socket) {
+ int n = v.size();
+
+ PRINT
+
+ // std::cout << "In fetchNumbers. size of v is: " << n << std::endl;
+ for (int i = 0; i < n; i++) {
+ // std::cout << "In fetchNumbers. v[i].low is (" <<v[i].low.getSession() <<", " << v[i].low.getSeq() << ") v[i].high is ("<<v[i].high.getSession() <<", " <<v[i].high.getSeq()<<")" << std::endl;
+ for(SeqNo s = v[i].low; s <= v[i].high; ++s) {
+ PRINT
+ socket->fetchData(v[i].prefix, s, bind(&TestSocketApp::setNum, this, _1));
+ }
+ }
+ }
+
+ void pass(const string &prefix) {
+ }
+
+ string toString(){
+ map<ndn::Name, string>::iterator it = data.begin();
+ string str = "\n";
+ for (; it != data.end(); ++it){
+ str += "<";
+ str += it->first.toUri();
+ str += "|";
+ str += it->second;
+ str += ">";
+ str += "\n";
+ }
+
+ return str;
+ }
+
+};
+
+class TestSet1{
+public:
+ TestSet1(ndn::shared_ptr<boost::asio::io_service> ioService)
+ : m_validator(new ndn::ValidatorNull())
+ , m_face1(new ndn::Face(ioService))
+ , m_face2(new ndn::Face(ioService))
+ , m_face3(new ndn::Face(ioService))
+ , m_p1("/irl.cs.ucla.edu")
+ , m_p2("/yakshi.org")
+ , m_p3("/google.com")
+ , m_syncPrefix("/let/us/sync")
+ {}
+
+ void
+ createSyncSocket1()
+ {
+ _LOG_DEBUG ("s1");
+ m_s1 = make_shared<SyncSocket>(m_syncPrefix, m_validator, m_face1,
+ bind(&TestSocketApp::fetchAll, &m_a1, _1, _2),
+ bind(&TestSocketApp::pass, &m_a1, _1));
+ }
+
+ void
+ createSyncSocket2()
+ {
+ _LOG_DEBUG ("s2");
+ m_s2 = make_shared<SyncSocket>(m_syncPrefix, m_validator, m_face2,
+ bind(&TestSocketApp::fetchAll, &m_a2, _1, _2),
+ bind(&TestSocketApp::pass, &m_a2, _1));
+ }
+
+ void
+ createSyncSocket3()
+ {
+ _LOG_DEBUG ("s3");
+ m_s3 = make_shared<SyncSocket>(m_syncPrefix, m_validator, m_face3,
+ bind(&TestSocketApp::fetchAll, &m_a3, _1, _2),
+ bind(&TestSocketApp::pass, &m_a3, _1));
+ }
+
+ void
+ publishSocket1(uint32_t session, string data)
+ {
+ _LOG_DEBUG ("s1 publish");
+ m_s1->publishData (m_p1, session, data.c_str(), data.size(), 1000);
+ }
+
+ void
+ publishSocket2(uint32_t session, string data)
+ {
+ _LOG_DEBUG ("s2 publish");
+ m_s2->publishData (m_p2, session, data.c_str(), data.size(), 1000);
+ }
+
+ void
+ publishSocket3(uint32_t session, string data)
+ {
+ _LOG_DEBUG ("s3 publish");
+ m_s3->publishData (m_p3, session, data.c_str(), data.size(), 1000);
+ }
+
+ void
+ setSocket1(string suffix, string data)
+ {
+ _LOG_DEBUG ("a1 set");
+ ndn::Name name = m_p1;
+ name.append(suffix);
+ m_a1.set (name, data.c_str(), data.size());
+ }
+
+ void
+ setSocket2(string suffix, string data)
+ {
+ _LOG_DEBUG ("a2 set");
+ ndn::Name name = m_p2;
+ name.append(suffix);
+ m_a2.set (name, data.c_str(), data.size());
+ }
+
+ void
+ setSocket3(string suffix, string data)
+ {
+ _LOG_DEBUG ("a3 set");
+ ndn::Name name = m_p3;
+ name.append(suffix);
+ m_a3.set (name, data.c_str(), data.size());
+ }
+
+ void
+ check(int round)
+ {
+ BOOST_CHECK_EQUAL(m_a1.toString(), m_a2.toString());
+ BOOST_CHECK_EQUAL(m_a2.toString(), m_a3.toString());
+ }
+
+ void
+ done()
+ {
+ m_s1.reset();
+ m_s2.reset();
+ m_s3.reset();
+ }
+
+
+ TestSocketApp m_a1, m_a2, m_a3;
+ ndn::shared_ptr<ndn::ValidatorNull> m_validator;
+ ndn::shared_ptr<ndn::Face> m_face1, m_face2, m_face3;
+ ndn::Name m_p1, m_p2, m_p3;
+ ndn::shared_ptr<SyncSocket> m_s1, m_s2, m_s3;
+ ndn::Name m_syncPrefix;
+};
+
+class TestSet2{
+public:
+ TestSet2(ndn::shared_ptr<boost::asio::io_service> ioService)
+ : m_validator(new ndn::ValidatorNull())
+ , m_face1(new ndn::Face(ioService))
+ , m_face2(new ndn::Face(ioService))
+ , m_p1("/xiaonei.com")
+ , m_p2("/mitbbs.com")
+ , m_syncPrefix("/this/is/the/prefix")
+ {}
+
+ void
+ createSyncSocket1()
+ {
+ _LOG_DEBUG ("s1");
+ m_s1 = make_shared<SyncSocket>(m_syncPrefix, m_validator, m_face1,
+ bind(&TestSocketApp::fetchNumbers, &m_a1, _1, _2),
+ bind(&TestSocketApp::pass, &m_a1, _1));
+ }
+
+ void
+ createSyncSocket2()
+ {
+ _LOG_DEBUG ("s2");
+ m_s2 = make_shared<SyncSocket>(m_syncPrefix, m_validator, m_face2,
+ bind(&TestSocketApp::fetchNumbers, &m_a2, _1, _2),
+ bind(&TestSocketApp::pass, &m_a2, _1));
+ }
+
+ void
+ publishSocket1(uint32_t session, string data)
+ {
+ _LOG_DEBUG ("s1 publish");
+ m_s1->publishData (m_p1, session, data.c_str(), data.size(), 1000);
+ }
+
+ void
+ publishSocket2(uint32_t session, string data)
+ {
+ _LOG_DEBUG ("s2 publish");
+ m_s2->publishData (m_p2, session, data.c_str(), data.size(), 1000);
+ }
+
+ void
+ setSocket1(const char* ptr, size_t size)
+ {
+ _LOG_DEBUG ("a1 setNum");
+ m_a1.setNum (m_p1, ptr, size);
+ }
+
+ void
+ setSocket2(const char* ptr, size_t size)
+ {
+ _LOG_DEBUG ("a2 setNum");
+ m_a2.setNum (m_p2, ptr, size);
+ }
+
+ void
+ check(int num)
+ {
+ _LOG_DEBUG ("codnum " << num);
+ _LOG_DEBUG ("a1 sum " << m_a1.sum);
+ _LOG_DEBUG ("a2 sum " << m_a2.sum);
+
+ BOOST_CHECK(m_a1.sum == m_a2.sum && m_a1.sum == num);
+ }
+
+ void
+ done()
+ {
+ m_s1.reset();
+ m_s2.reset();
+ }
+
+ TestSocketApp m_a1, m_a2;
+ ndn::shared_ptr<ndn::ValidatorNull> m_validator;
+ ndn::shared_ptr<ndn::Face> m_face1, m_face2;
+ ndn::Name m_p1, m_p2;
+ ndn::shared_ptr<SyncSocket> m_s1, m_s2;
+ ndn::Name m_syncPrefix;
+};
+
+BOOST_AUTO_TEST_CASE (AppSocketTest1)
+{
+ INIT_LOGGERS ();
+
+ ndn::shared_ptr<boost::asio::io_service> ioService = ndn::make_shared<boost::asio::io_service>();
+ ndn::Scheduler scheduler(*ioService);
+ TestSet1 testSet1(ioService);
+
+ scheduler.scheduleEvent(ndn::time::seconds(0.00), ndn::bind(&TestSet1::createSyncSocket1, &testSet1));
+ scheduler.scheduleEvent(ndn::time::seconds(0.05), ndn::bind(&TestSet1::createSyncSocket2, &testSet1));
+ scheduler.scheduleEvent(ndn::time::seconds(0.10), ndn::bind(&TestSet1::createSyncSocket3, &testSet1));
+ string data0 = "Very funny Scotty, now beam down my clothes";
+ scheduler.scheduleEvent(ndn::time::seconds(0.15), ndn::bind(&TestSet1::publishSocket1, &testSet1, 0, data0));
+ scheduler.scheduleEvent(ndn::time::seconds(1.15), ndn::bind(&TestSet1::setSocket1, &testSet1, "/0/0", data0));
+ scheduler.scheduleEvent(ndn::time::seconds(1.16), ndn::bind(&TestSet1::check, &testSet1, 1));
+ string data1 = "Yes, give me that ketchup";
+ string data2 = "Don't look conspicuous, it draws fire";
+ scheduler.scheduleEvent(ndn::time::seconds(1.17), ndn::bind(&TestSet1::publishSocket1, &testSet1, 0, data1));
+ scheduler.scheduleEvent(ndn::time::seconds(1.18), ndn::bind(&TestSet1::publishSocket1, &testSet1, 0, data2));
+ scheduler.scheduleEvent(ndn::time::seconds(2.15), ndn::bind(&TestSet1::setSocket1, &testSet1, "/0/1", data1));
+ scheduler.scheduleEvent(ndn::time::seconds(2.16), ndn::bind(&TestSet1::setSocket1, &testSet1, "/0/2", data2));
+ scheduler.scheduleEvent(ndn::time::seconds(2.17), ndn::bind(&TestSet1::check, &testSet1, 2));
+ string data3 = "You surf the Internet, I surf the real world";
+ string data4 = "I got a fortune cookie once that said 'You like Chinese food'";
+ string data5 = "Real men wear pink. Why? Because their wives make them";
+ scheduler.scheduleEvent(ndn::time::seconds(3.18), ndn::bind(&TestSet1::publishSocket3, &testSet1, 0, data3));
+ scheduler.scheduleEvent(ndn::time::seconds(3.20), ndn::bind(&TestSet1::publishSocket2, &testSet1, 0, data4));
+ scheduler.scheduleEvent(ndn::time::seconds(3.21), ndn::bind(&TestSet1::publishSocket2, &testSet1, 0, data5));
+ scheduler.scheduleEvent(ndn::time::seconds(4.21), ndn::bind(&TestSet1::setSocket3, &testSet1, "/0/0", data3));
+ scheduler.scheduleEvent(ndn::time::seconds(4.22), ndn::bind(&TestSet1::setSocket2, &testSet1, "/0/0", data4));
+ scheduler.scheduleEvent(ndn::time::seconds(4.23), ndn::bind(&TestSet1::setSocket2, &testSet1, "/0/1", data5));
+ scheduler.scheduleEvent(ndn::time::seconds(4.30), ndn::bind(&TestSet1::check, &testSet1, 3));
+ // not sure weither this is simultanous data generation from multiple sources
+ _LOG_DEBUG ("Simultaneous publishing");
+ string data6 = "Shakespeare says: 'Prose before hos.'";
+ string data7 = "Pick good people, talent never wears out";
+ scheduler.scheduleEvent(ndn::time::seconds(5.50), ndn::bind(&TestSet1::publishSocket1, &testSet1, 0, data6));
+ scheduler.scheduleEvent(ndn::time::seconds(5.50), ndn::bind(&TestSet1::publishSocket2, &testSet1, 0, data7));
+ scheduler.scheduleEvent(ndn::time::seconds(6.80), ndn::bind(&TestSet1::setSocket1, &testSet1, "/0/3", data6));
+ scheduler.scheduleEvent(ndn::time::seconds(6.80), ndn::bind(&TestSet1::setSocket2, &testSet1, "/0/2", data7));
+ scheduler.scheduleEvent(ndn::time::seconds(6.90), ndn::bind(&TestSet1::check, &testSet1, 4));
+ scheduler.scheduleEvent(ndn::time::seconds(7.00), ndn::bind(&TestSet1::done, &testSet1));
+
+ ioService->run();
+}
+
+BOOST_AUTO_TEST_CASE (AppSocketTest2)
+{
+ ndn::shared_ptr<boost::asio::io_service> ioService = ndn::make_shared<boost::asio::io_service>();
+ ndn::Scheduler scheduler(*ioService);
+ TestSet2 testSet2(ioService);
+
+ scheduler.scheduleEvent(ndn::time::seconds(0.00), ndn::bind(&TestSet2::createSyncSocket1, &testSet2));
+ scheduler.scheduleEvent(ndn::time::seconds(0.05), ndn::bind(&TestSet2::createSyncSocket2, &testSet2));
+ uint32_t num[5] = {0, 1, 2, 3, 4};
+ string data0((const char *) num, sizeof(num));
+ scheduler.scheduleEvent(ndn::time::seconds(0.10), ndn::bind(&TestSet2::publishSocket1, &testSet2, 0, data0));
+ scheduler.scheduleEvent(ndn::time::seconds(0.15), ndn::bind(&TestSet2::setSocket1, &testSet2, (const char *) num, sizeof (num)));
+ scheduler.scheduleEvent(ndn::time::seconds(1.00), ndn::bind(&TestSet2::check, &testSet2, 10));
+ uint32_t newNum[5] = {9, 7, 2, 1, 1};
+ string data1((const char *) newNum, sizeof(newNum));
+ scheduler.scheduleEvent(ndn::time::seconds(1.10), ndn::bind(&TestSet2::publishSocket2, &testSet2, 0, data1));
+ scheduler.scheduleEvent(ndn::time::seconds(1.15), ndn::bind(&TestSet2::setSocket2, &testSet2, (const char *) newNum, sizeof (newNum)));
+ scheduler.scheduleEvent(ndn::time::seconds(2.00), ndn::bind(&TestSet2::check, &testSet2, 30));
+ scheduler.scheduleEvent(ndn::time::seconds(7.00), ndn::bind(&TestSet2::done, &testSet2));
+
+ ioService->run();
+}
diff --git a/nsync/tests/test_state.cc.outdated b/nsync/tests/test_state.cc.outdated
new file mode 100644
index 0000000..35fc79c
--- /dev/null
+++ b/nsync/tests/test_state.cc.outdated
@@ -0,0 +1,294 @@
+/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#define BOOST_TEST_DYN_LINK 1
+#define BOOST_TEST_NO_MAIN 1
+// #define BOOST_TEST_MODULE StateTests
+#include <boost/test/unit_test.hpp>
+#include <boost/test/output_test_stream.hpp>
+using boost::test_tools::output_test_stream;
+
+#include <boost/make_shared.hpp>
+#include <boost/date_time/posix_time/posix_time.hpp>
+
+#include "sync-std-name-info.h"
+#include "sync-full-state.h"
+#include "sync-diff-state.h"
+
+using namespace Sync;
+using namespace std;
+using namespace boost;
+
+BOOST_AUTO_TEST_SUITE(StateTests)
+
+BOOST_AUTO_TEST_CASE (FullStateTest)
+{
+ BOOST_CHECK_NO_THROW (FullState ());
+ FullState state;
+ BOOST_CHECK_EQUAL (state.getLeaves ().size (), 0);
+
+ output_test_stream output;
+ output << state.getTimeFromLastUpdate ();
+ BOOST_CHECK (output.is_equal ("not-a-date-time", true));
+
+ NameInfoConstPtr name = StdNameInfo::FindOrCreate ("/test/name");
+ BOOST_CHECK_NO_THROW (state.update (name, SeqNo (12)));
+ BOOST_CHECK_NO_THROW (state.update (name, SeqNo (12)));
+ BOOST_CHECK_NO_THROW (state.update (name, SeqNo (12)));
+ BOOST_CHECK_EQUAL (state.getLeaves ().size (), 1);
+ BOOST_CHECK_EQUAL ((*state.getLeaves ().begin ())->getSeq ().getSeq (), 12);
+
+ BOOST_CHECK_NO_THROW (state.update (name, SeqNo (13)));
+ BOOST_CHECK_EQUAL ((*state.getLeaves ().begin ())->getSeq ().getSeq (), 13);
+
+ BOOST_CHECK_NO_THROW (state.remove (name));
+ BOOST_CHECK_EQUAL (state.getLeaves ().size (), 0);
+
+ BOOST_CHECK_EQUAL (state.getTimeFromLastUpdate ().total_milliseconds (), 0);
+}
+
+BOOST_AUTO_TEST_CASE (DiffStateTest)
+{
+ BOOST_CHECK_NO_THROW (DiffState ());
+ DiffState state;
+ BOOST_CHECK_EQUAL (state.getLeaves ().size (), 0);
+
+ NameInfoConstPtr name = StdNameInfo::FindOrCreate ("/test/name");
+ BOOST_CHECK_NO_THROW (state.update (name, SeqNo (12)));
+ BOOST_CHECK_NO_THROW (state.update (name, SeqNo (12)));
+ BOOST_CHECK_NO_THROW (state.update (name, SeqNo (12)));
+ BOOST_CHECK_EQUAL (state.getLeaves ().size (), 1);
+ BOOST_CHECK_EQUAL ((*state.getLeaves ().begin ())->getSeq ().getSeq (), 12);
+
+ BOOST_CHECK_NO_THROW (state.update (name, SeqNo (13)));
+ BOOST_CHECK_EQUAL ((*state.getLeaves ().begin ())->getSeq ().getSeq (), 13);
+
+ BOOST_CHECK_NO_THROW (state.remove (name));
+ BOOST_CHECK_EQUAL (state.getLeaves ().size (), 1);
+ BOOST_CHECK_EQUAL ((*state.getLeaves ().begin ())->getSeq ().getSeq (), 0);
+}
+
+BOOST_AUTO_TEST_CASE (FullStateDigestTest)
+{
+ FullState state;
+ BOOST_CHECK_EQUAL (state.getLeaves ().size (), 0);
+
+ NameInfoConstPtr name3 = StdNameInfo::FindOrCreate ("3");
+ NameInfoConstPtr name2 = StdNameInfo::FindOrCreate ("2");
+ NameInfoConstPtr name1 = StdNameInfo::FindOrCreate ("1");
+
+ state.update (name1, SeqNo (10));
+ DigestConstPtr digest1 = state.getDigest ();
+
+ state.update (name2, SeqNo (12));
+ DigestConstPtr digest2 = state.getDigest ();
+
+ BOOST_CHECK (digest1.get () != digest2.get ());
+ BOOST_CHECK (!digest1->empty ());
+ BOOST_CHECK (!digest2->empty ());
+
+ state.update (name3, SeqNo (8));
+ DigestConstPtr digest3 = state.getDigest ();
+
+ BOOST_CHECK (digest1.get () != digest2.get ());
+ BOOST_CHECK (digest2.get () != digest3.get ());
+ BOOST_CHECK (digest1.get () != digest3.get ());
+
+ BOOST_CHECK (*digest1 != *digest2);
+ BOOST_CHECK (*digest2 != *digest3);
+ BOOST_CHECK (*digest1 != *digest3);
+
+ // removing elements. Digest should get reverted to digest1
+ state.remove (name2);
+ state.remove (name3);
+ DigestConstPtr digest4 = state.getDigest ();
+ BOOST_CHECK (*digest1 == *digest4);
+
+ name2.reset (); // force destructor
+ name3.reset (); // force destructor
+ name3 = StdNameInfo::FindOrCreate ("3"); // this will enforce different (larger) hashing ID of name
+ name2 = StdNameInfo::FindOrCreate ("2"); // this will enforce different (larger) hashing ID of name
+
+ // adding in different order
+ state.update (name3, SeqNo (8));
+ state.update (name2, SeqNo (12));
+ DigestConstPtr digest5 = state.getDigest ();
+ BOOST_CHECK (*digest5 == *digest3);
+}
+
+BOOST_AUTO_TEST_CASE (FullStateXml)
+{
+ FullState state;
+
+ NameInfoConstPtr name3 = StdNameInfo::FindOrCreate ("3");
+ NameInfoConstPtr name2 = StdNameInfo::FindOrCreate ("2");
+ NameInfoConstPtr name1 = StdNameInfo::FindOrCreate ("1");
+
+ state.update (name1, SeqNo (10));
+ state.update (name2, SeqNo (12));
+ state.update (name3, SeqNo (8));
+
+ string xml1 = "<state>"
+ "<item><name>1</name><seq><session>0</session><seqno>10</seqno></seq></item>"
+ "<item><name>2</name><seq><session>0</session><seqno>12</seqno></seq></item>"
+ "<item><name>3</name><seq><session>0</session><seqno>8</seqno></seq></item>"
+ "</state>";
+ {
+ ostringstream os;
+ os << state;
+ string s = os.str ();
+ // cout << s << endl;
+ erase_all (s, "\n");
+ BOOST_CHECK_EQUAL (s, xml1);
+ }
+
+ state.remove (name2);
+ string xml2 = "<state>"
+ "<item><name>1</name><seq><session>0</session><seqno>10</seqno></seq></item>"
+ "<item><name>3</name><seq><session>0</session><seqno>8</seqno></seq></item>"
+ "</state>";
+ {
+ ostringstream os;
+ os << state;
+ string s = os.str ();
+ erase_all (s, "\n");
+ BOOST_CHECK_EQUAL (s, xml2);
+ }
+
+ FullState state2;
+ istringstream xml1_is (xml1);
+ BOOST_CHECK_NO_THROW (xml1_is >> state2);
+ {
+ ostringstream os;
+ os << state2;
+ string xml1_test = os.str ();
+ erase_all (xml1_test, "\n");
+ BOOST_CHECK_EQUAL (xml1_test, xml1);
+ }
+
+ istringstream xml2_is ("<state><item action=\"remove\"><name>2</name></item></state>");
+ BOOST_CHECK_NO_THROW (xml2_is >> state2);
+
+ {
+ ostringstream os;
+ os << state2;
+ string xml2_test = os.str ();
+ erase_all (xml2_test, "\n");
+ BOOST_CHECK_EQUAL (xml2_test, xml2);
+ }
+}
+
+BOOST_AUTO_TEST_CASE (DiffStateXml)
+{
+ DiffState state;
+
+ NameInfoConstPtr name3 = StdNameInfo::FindOrCreate ("3");
+ NameInfoConstPtr name2 = StdNameInfo::FindOrCreate ("2");
+ NameInfoConstPtr name1 = StdNameInfo::FindOrCreate ("1");
+
+ state.update (name1, SeqNo (10));
+ state.update (name2, SeqNo (12));
+ state.update (name3, SeqNo (8));
+
+ string xml1 = "<state>"
+ "<item action=\"update\"><name>1</name><seq><session>0</session><seqno>10</seqno></seq></item>"
+ "<item action=\"update\"><name>2</name><seq><session>0</session><seqno>12</seqno></seq></item>"
+ "<item action=\"update\"><name>3</name><seq><session>0</session><seqno>8</seqno></seq></item>"
+ "</state>";
+ {
+ ostringstream os;
+ os << state;
+ string xml1_test = os.str ();
+ erase_all (xml1_test, "\n");
+ BOOST_CHECK_EQUAL (xml1_test, xml1);
+ }
+
+ state.remove (name2);
+ string xml2 = "<state>"
+ "<item action=\"update\"><name>1</name><seq><session>0</session><seqno>10</seqno></seq></item>"
+ "<item action=\"remove\"><name>2</name></item>"
+ "<item action=\"update\"><name>3</name><seq><session>0</session><seqno>8</seqno></seq></item>"
+ "</state>";
+ {
+ ostringstream os;
+ os << state;
+ string xml2_test = os.str ();
+ erase_all (xml2_test, "\n");
+ BOOST_CHECK_EQUAL (xml2_test, xml2);
+ }
+
+ //////////// //////////// //////////// //////////// //////////// ////////////
+
+ DiffState state2;
+ istringstream xml1_is (xml1);
+ BOOST_CHECK_NO_THROW (xml1_is >> state2);
+
+ {
+ ostringstream os;
+ os << state2;
+ string xml1_test = os.str ();
+ erase_all (xml1_test, "\n");
+ BOOST_CHECK_EQUAL (xml1_test, xml1);
+ }
+
+ istringstream xml2_is ("<state><item action=\"remove\"><name>2</name></item></state>");
+ BOOST_CHECK_NO_THROW (xml2_is >> state2);
+
+ {
+ ostringstream os;
+ os << state2;
+ string xml2_test = os.str ();
+ erase_all (xml2_test, "\n");
+ BOOST_CHECK_EQUAL (xml2_test, xml2);
+ }
+
+}
+
+BOOST_AUTO_TEST_CASE (DiffStateDiffTest)
+{
+ DiffStatePtr root = make_shared<DiffState> ();
+
+ DiffStatePtr head = make_shared<DiffState> ();
+ root->setNext (head);
+
+ head->update (StdNameInfo::FindOrCreate ("3"), SeqNo (1));
+ head->remove (StdNameInfo::FindOrCreate ("1"));
+
+ DiffStatePtr tail = make_shared<DiffState> ();
+ head->setNext (tail);
+
+ tail->update (StdNameInfo::FindOrCreate ("3"), SeqNo (2));
+
+ {
+ ostringstream os;
+ os << *root->diff ();
+ string diffState = os.str ();
+ erase_all (diffState, "\n");
+ BOOST_CHECK_EQUAL (diffState,
+ "<state>"
+ "<item action=\"remove\"><name>1</name></item>"
+ "<item action=\"update\"><name>3</name><seq><session>0</session><seqno>2</seqno></seq></item>"
+ "</state>");
+ }
+}
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/nsync/tests/test_sync_logic.cc b/nsync/tests/test_sync_logic.cc
new file mode 100644
index 0000000..d2444e7
--- /dev/null
+++ b/nsync/tests/test_sync_logic.cc
@@ -0,0 +1,179 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+/*
+ * Copyright (c) 2012 University of California, Los Angeles
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation;
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * Author: Zhenkai Zhu <zhenkai@cs.ucla.edu>
+ * Chaoyi Bian <bcy@pku.edu.cn>
+ * Alexander Afanasyev <alexander.afanasyev@ucla.edu>
+ */
+
+#include <boost/test/unit_test.hpp>
+#include <boost/test/output_test_stream.hpp>
+#include <map>
+using boost::test_tools::output_test_stream;
+
+#include <boost/make_shared.hpp>
+
+#include <ndn-cpp-dev/security/validator-null.hpp>
+#include "sync-logic.h"
+#include "sync-seq-no.h"
+
+using namespace std;
+using namespace boost;
+using namespace Sync;
+
+struct Handler
+{
+ string instance;
+
+ Handler (const string &_instance)
+ : instance (_instance)
+ {
+ }
+
+ void wrapper (const vector<MissingDataInfo> &v) {
+ int n = v.size();
+ for (int i = 0; i < n; i++) {
+ onUpdate (v[i].prefix, v[i].high, v[i].low);
+ }
+ }
+
+ void onUpdate (const string &p/*prefix*/, const SeqNo &seq/*newSeq*/, const SeqNo &oldSeq/*oldSeq*/)
+ {
+ m_map[p] = seq.getSeq ();
+
+ // cout << instance << "\t";
+ // if (!oldSeq.isValid ())
+ // cout << "Inserted: " << p << " (" << seq << ")" << endl;
+ // else
+ // cout << "Updated: " << p << " ( " << oldSeq << ".." << seq << ")" << endl;
+ }
+
+ void onRemove (const string &p/*prefix*/)
+ {
+ // cout << instance << "\tRemoved: " << p << endl;
+ m_map.erase (p);
+ }
+
+ map<string, uint32_t> m_map;
+};
+
+class TestCore
+{
+public:
+ TestCore(ndn::shared_ptr<boost::asio::io_service> ioService)
+ : m_ioService(ioService)
+ {
+ m_l[0] = 0;
+ m_l[1] = 0;
+
+ m_validator = ndn::make_shared<ndn::ValidatorNull>();
+ }
+
+ ~TestCore()
+ {
+ if(m_l[0] != 0)
+ delete m_l[0];
+
+ if(m_l[1] != 0)
+ delete m_l[1];
+ }
+
+ void
+ finish()
+ {
+ }
+
+ void
+ createSyncLogic(int index,
+ ndn::shared_ptr<Handler> h)
+ {
+ m_faces[index] = ndn::make_shared<ndn::Face>(m_ioService);
+ m_l[index] = new SyncLogic(ndn::Name("/bcast"),
+ m_validator, m_faces[index],
+ bind (&Handler::wrapper, &*h, _1),
+ bind (&Handler::onRemove, &*h, _1));
+ }
+
+ void
+ getOldDigestForOne()
+ {
+ m_oldDigest = m_l[0]->getRootDigest();
+ }
+
+ void
+ getNewDigestForOne()
+ {
+ m_newDigest = m_l[0]->getRootDigest();
+ }
+
+ void
+ addLocalNamesForOne(ndn::Name name, uint64_t session, uint64_t seq)
+ {
+ m_l[0]->addLocalNames(name, session, seq);
+ }
+
+ void
+ removeForOne(ndn::Name name)
+ {
+ m_l[0]->remove(name);
+ }
+
+ void
+ checkDigest()
+ {
+ BOOST_CHECK(m_oldDigest != m_newDigest);
+ }
+
+
+public:
+ ndn::shared_ptr<boost::asio::io_service> m_ioService;
+ SyncLogic* m_l[2];
+ ndn::shared_ptr<ndn::Face> m_faces[2];
+ ndn::shared_ptr<ndn::ValidatorNull> m_validator;
+ string m_oldDigest;
+ string m_newDigest;
+};
+
+void
+checkMapSize(ndn::shared_ptr<Handler> h, int size)
+{ BOOST_CHECK_EQUAL (h->m_map.size (), size); }
+
+
+BOOST_AUTO_TEST_CASE (SyncLogicTest)
+{
+ ndn::shared_ptr<boost::asio::io_service> ioService = ndn::make_shared<boost::asio::io_service>();
+ ndn::Scheduler scheduler(*ioService);
+ TestCore testCore(ioService);
+
+ ndn::shared_ptr<Handler> h1 = ndn::make_shared<Handler>("1");
+ ndn::shared_ptr<Handler> h2 = ndn::make_shared<Handler>("2");
+
+ scheduler.scheduleEvent(ndn::time::seconds(0), ndn::bind(&TestCore::createSyncLogic, &testCore, 0, h1));
+ scheduler.scheduleEvent(ndn::time::seconds(0.1), ndn::bind(&TestCore::getOldDigestForOne, &testCore));
+ scheduler.scheduleEvent(ndn::time::seconds(0.2), ndn::bind(&TestCore::addLocalNamesForOne, &testCore, "/one", 1, 2));
+ scheduler.scheduleEvent(ndn::time::seconds(0.3), ndn::bind(&checkMapSize, h1, 0));
+ scheduler.scheduleEvent(ndn::time::seconds(0.4), ndn::bind(&TestCore::createSyncLogic, &testCore, 1, h2));
+ scheduler.scheduleEvent(ndn::time::seconds(0.5), ndn::bind(&checkMapSize, h1, 0));
+ scheduler.scheduleEvent(ndn::time::seconds(0.6), ndn::bind(&checkMapSize, h2, 1));
+ scheduler.scheduleEvent(ndn::time::seconds(0.7), ndn::bind(&TestCore::removeForOne, &testCore, "/one"));
+ scheduler.scheduleEvent(ndn::time::seconds(0.8), ndn::bind(&TestCore::getNewDigestForOne, &testCore));
+ scheduler.scheduleEvent(ndn::time::seconds(0.9), ndn::bind(&TestCore::checkDigest, &testCore));
+ scheduler.scheduleEvent(ndn::time::seconds(1.0), ndn::bind(&TestCore::finish, &testCore));
+
+ ioService->run();
+
+}
diff --git a/nsync/waf b/nsync/waf
new file mode 100755
index 0000000..d45d28b
--- /dev/null
+++ b/nsync/waf
Binary files differ
diff --git a/nsync/wscript b/nsync/wscript
new file mode 100644
index 0000000..4dd63e9
--- /dev/null
+++ b/nsync/wscript
@@ -0,0 +1,128 @@
+# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
+
+VERSION='0.1'
+APPNAME='nsync'
+
+from waflib import Configure, Build, Logs
+
+def options(opt):
+ opt.load('compiler_c compiler_cxx boost doxygen gnu_dirs protoc')
+ # opt.load('ndnx', tooldir=["waf-tools"])
+
+ syncopt = opt.add_option_group ("ChronoSync Options")
+
+ syncopt.add_option('--debug',action='store_true',default=False,dest='debug',help='''debugging mode''')
+ syncopt.add_option('--log4cxx', action='store_true',default=False,dest='log4cxx',help='''Compile with log4cxx''')
+ syncopt.add_option('--test', action='store_true',default=False,dest='_test',help='''build unit tests''')
+
+def configure(conf):
+ conf.load('compiler_c compiler_cxx gnu_dirs boost')
+
+ if conf.options.debug:
+ conf.define ('_DEBUG', 1)
+ conf.add_supported_cxxflags (cxxflags = ['-O0',
+ '-Wall',
+ '-Wno-unused-variable',
+ '-g3',
+ '-Wno-unused-private-field', # only clang supports
+ '-fcolor-diagnostics', # only clang supports
+ '-Qunused-arguments' # only clang supports
+ ])
+ else:
+ conf.add_supported_cxxflags (cxxflags = ['-O3', '-g'])
+
+ conf.check_cfg(package='libndn-cpp-dev', args=['--cflags', '--libs'], uselib_store='NDNCPP', mandatory=True)
+
+ conf.check_cfg(package='openssl', args=['--cflags', '--libs'], uselib_store='OPENSSL', mandatory=True)
+
+ conf.check_boost(lib='system iostreams thread unit_test_framework')
+
+ if conf.options.log4cxx:
+ conf.check_cfg(package='liblog4cxx', args=['--cflags', '--libs'], uselib_store='LOG4CXX', mandatory=True)
+
+ if conf.options._test:
+ conf.define('_TEST', 1)
+
+ try:
+ conf.load('doxygen')
+ except:
+ pass
+
+ conf.load('protoc')
+
+def build (bld):
+ libsync = bld (
+ target="nsync",
+ # vnum = "1.0.0",
+ features=['cxx', 'cxxshlib'],
+ source = bld.path.ant_glob (['src/**/*.cc', 'src/**/*.proto']),
+ use = 'BOOST NDNCPP OPENSSL',
+ includes = ['src'],
+ )
+
+ # Unit tests
+ if bld.get_define("_TEST"):
+ unittests = bld.program (
+ target="unit-tests",
+ source = bld.path.ant_glob(['tests/**/*.cc']),
+ features=['cxx', 'cxxprogram'],
+ use = 'nsync',
+ includes = ['src'],
+ )
+
+ if bld.get_define ("HAVE_LOG4CXX"):
+ libsync.use += ' LOG4CXX'
+ if bld.get_define("_TEST"):
+ unittests.use += ' LOG4CXX'
+
+ bld.install_files (
+ dest = "%s/nsync" % bld.env['INCLUDEDIR'],
+ files = bld.path.ant_glob(['src/**/*.h']),
+ cwd = bld.path.find_dir ("src"),
+ relative_trick = True,
+ )
+
+ bld.install_files (
+ dest = "%s/nsync" % bld.env['INCLUDEDIR'],
+ files = bld.path.get_bld().ant_glob(['src/**/*.h']),
+ cwd = bld.path.get_bld().find_dir ("src"),
+ relative_trick = True,
+ )
+
+ pc = bld (
+ features = "subst",
+ source='nsync.pc.in',
+ target='nsync.pc',
+ install_path = '${LIBDIR}/pkgconfig',
+ PREFIX = bld.env['PREFIX'],
+ INCLUDEDIR = "%s/nsync" % bld.env['INCLUDEDIR'],
+ VERSION = VERSION,
+ )
+
+# doxygen docs
+from waflib.Build import BuildContext
+class doxy (BuildContext):
+ cmd = "doxygen"
+ fun = "doxygen"
+
+def doxygen (bld):
+ if not bld.env.DOXYGEN:
+ bld.fatal ("ERROR: cannot build documentation (`doxygen' is not found in $PATH)")
+ bld (features="doxygen",
+ doxyfile='doc/doxygen.conf',
+ output_dir = 'doc')
+
+@Configure.conf
+def add_supported_cxxflags(self, cxxflags):
+ """
+ Check which cxxflags are supported by compiler and add them to env.CXXFLAGS variable
+ """
+ self.start_msg('Checking allowed flags for c++ compiler')
+
+ supportedFlags = []
+ for flag in cxxflags:
+ if self.check_cxx (cxxflags=[flag], mandatory=False):
+ supportedFlags += [flag]
+
+ self.end_msg (' '.join (supportedFlags))
+ self.env.CXXFLAGS += supportedFlags
diff --git a/src/nlsr.cpp b/src/nlsr.cpp
index fe4ba01..3ca2279 100644
--- a/src/nlsr.cpp
+++ b/src/nlsr.cpp
@@ -1,7 +1,6 @@
#include <ndn-cpp-dev/face.hpp>
#include <ndn-cpp-dev/security/key-chain.hpp>
#include <ndn-cpp-dev/util/scheduler.hpp>
-
#include <cstdlib>
#include <string>
#include <sstream>
@@ -108,8 +107,9 @@
//}
nlsr_.getLsdb().setLsaRefreshTime(nlsr_.getConfParameter().getLsaRefreshTime());
nlsr_.getFib().setFibEntryRefreshTime(
- 2*nlsr_.getConfParameter().getLsaRefreshTime());
+ 2*nlsr_.getConfParameter().getLsaRefreshTime());
nlsr_.getLsdb().setThisRouterPrefix(nlsr_.getConfParameter().getRouterPrefix());
+ nlsr_.getKeyManager().initKeyManager(nlsr_.getConfParameter());
/* debugging purpose start */
cout << nlsr_.getConfParameter();
nlsr_.getAdl().printAdl();
diff --git a/src/nlsr.hpp b/src/nlsr.hpp
index 2f2ee61..cbf2af9 100644
--- a/src/nlsr.hpp
+++ b/src/nlsr.hpp
@@ -16,6 +16,7 @@
#include "nlsr_npt.hpp"
#include "nlsr_fib.hpp"
#include "nlsr_logger.hpp"
+#include "nlsr_km.hpp"
//testing
#include "nlsr_test.hpp"
@@ -39,6 +40,7 @@
, im()
, dm()
, sm()
+ , km()
, nlsrLsdb()
, adjBuildCount(0)
, isBuildAdjLsaSheduled(0)
@@ -111,11 +113,16 @@
return nlsrFace;
}
- ndn::KeyChain& getKeyChain()
+ KeyManager& getKeyManager()
{
- return kChain;
+ return km;
}
+// ndn::KeyChain& getKeyChain()
+// {
+// return kChain;
+// }
+
interestManager& getIm()
{
return im;
@@ -223,10 +230,11 @@
ndn::shared_ptr<boost::asio::io_service> io;
ndn::Scheduler scheduler;
ndn::Face nlsrFace;
- ndn::KeyChain kChain;
+// ndn::KeyChain kChain;
interestManager im;
DataManager dm;
SequencingManager sm;
+ KeyManager km;
bool isDaemonProcess;
string configFileName;
int apiPort;
diff --git a/src/nlsr_im.cpp b/src/nlsr_im.cpp
index 23a56cc..2e6d6d1 100644
--- a/src/nlsr_im.cpp
+++ b/src/nlsr_im.cpp
@@ -48,7 +48,7 @@
Data data(ndn::Name(interest.getName()).appendVersion());
data.setFreshnessPeriod(1000); // 10 sec
data.setContent((const uint8_t*)"info", sizeof("info"));
- pnlsr.getKeyChain().sign(data);
+ pnlsr.getKeyManager().getKeyChain().sign(data);
cout << ">> D: " << data << endl;
pnlsr.getNlsrFace().put(data);
int status=pnlsr.getAdl().getStatusOfNeighbor(neighbor);
diff --git a/src/nlsr_km.cpp b/src/nlsr_km.cpp
new file mode 100644
index 0000000..fb4efaa
--- /dev/null
+++ b/src/nlsr_km.cpp
@@ -0,0 +1,22 @@
+#include <ndn-cpp-dev/security/identity-certificate.hpp>
+#include <ndn-cpp-dev/encoding/block.hpp>
+#include "nlsr_km.hpp"
+
+namespace nlsr
+{
+ void
+ KeyManager::initKeyManager(ConfParameter &cp)
+ {
+ ndn::Name identityName(cp.getRouterPrefix()+"/nlsr");
+ kChain.deleteIdentity(identityName);
+ ndn::Name certName = kChain.createIdentity(identityName);
+ cout<<"Certificate Name: "<<certName.toUri()<<endl;
+ ndn::Name keyName=
+ ndn::IdentityCertificate::certificateNameToPublicKeyName(certName);
+ cout<<"Key Name: "<<keyName.toUri()<<endl;
+ }
+
+}
+
+
+
diff --git a/src/nlsr_km.hpp b/src/nlsr_km.hpp
new file mode 100644
index 0000000..e93e996
--- /dev/null
+++ b/src/nlsr_km.hpp
@@ -0,0 +1,32 @@
+#ifndef NLSR_KM_HPP
+#define NLSR_KM_HPP
+
+#include <ndn-cpp-dev/face.hpp>
+#include <ndn-cpp-dev/security/key-chain.hpp>
+#include <ndn-cpp-dev/util/scheduler.hpp>
+
+#include "nlsr_conf_param.hpp"
+
+namespace nlsr
+{
+ class KeyManager
+ {
+ public:
+ KeyManager()
+ :kChain()
+ {
+ }
+
+ ndn::KeyChain& getKeyChain()
+ {
+ return kChain;
+ }
+
+ void initKeyManager(ConfParameter &cp);
+
+ private:
+ ndn::KeyChain kChain;
+ };
+}
+
+#endif