Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • cellframe/cellframe-sdk
  • MIKA83/cellframe-sdk
2 results
Show changes
Showing
with 4075 additions and 1 deletion
/*
* Authors:
* Dmitriy A. Gearasimov <gerasimov.dmitriy@demlabs.net>
* DeM Labs Inc. https://demlabs.net
* CellFrame https://cellframe.net
* Sources https://gitlab.demlabs.net/cellframe
* Copyright (c) 2017-2019
* All rights reserved.
This file is part of CellFrame SDK the open source project
CellFrame SDK is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CellFrame SDK 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 any CellFrame SDK based project. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dap_common.h"
#include "dap_enc_key.h"
#include "dap_sign.h"
#include "dap_chain_datum_tx_receipt.h"
#define LOG_TAG "dap_chain_datum_tx_receipt"
/**
* @brief dap_chain_datum_tx_receipt_create
* @param a_srv_uid
* @param a_units_type
* @param a_units
* @param a_value_datoshi
* @param a_ext
* @param a_ext_size
* @return
*/
dap_chain_datum_tx_receipt_t * dap_chain_datum_tx_receipt_create( dap_chain_net_srv_uid_t a_srv_uid,
dap_chain_net_srv_price_unit_uid_t a_units_type,
uint64_t a_units, uint64_t a_value_datoshi,
const void * a_ext, size_t a_ext_size)
{
dap_chain_datum_tx_receipt_t * l_ret = DAP_NEW_Z_SIZE(dap_chain_datum_tx_receipt_t, dap_chain_datum_tx_receipt_get_size_hdr() +a_ext_size );
l_ret->type = TX_ITEM_TYPE_RECEIPT;
l_ret->receipt_info.units_type = a_units_type;
l_ret->receipt_info.srv_uid = a_srv_uid;
l_ret->receipt_info.units = a_units;
l_ret->receipt_info.value_datoshi = a_value_datoshi;
l_ret->size = dap_chain_datum_tx_receipt_get_size_hdr()+a_ext_size;
if( a_ext_size && a_ext){
l_ret->exts_size = a_ext_size;
memcpy(l_ret->exts_n_signs, a_ext, a_ext_size);
}
return l_ret;
}
size_t dap_chain_datum_tx_receipt_sign_add(dap_chain_datum_tx_receipt_t ** a_receipt, size_t a_receipt_size, dap_enc_key_t *a_key )
{
dap_chain_datum_tx_receipt_t *l_receipt = *a_receipt;
if ( ! *a_receipt ){
log_it( L_ERROR, "NULL receipt, can't add sign");
return 0;
}
dap_sign_t * l_sign = dap_sign_create(a_key,&l_receipt->receipt_info,sizeof (l_receipt->receipt_info),0);
size_t l_sign_size = l_sign? dap_sign_get_size( l_sign ) : 0;
if ( ! l_sign || ! l_sign_size ){
log_it( L_ERROR, "Can't sign the receipt, may be smth with key?");
return 0;
}
l_receipt= (dap_chain_datum_tx_receipt_t*) DAP_REALLOC(l_receipt, a_receipt_size+l_sign_size);
memcpy(l_receipt->exts_n_signs + l_receipt->exts_size, l_sign, l_sign_size);
a_receipt_size += l_sign_size;
l_receipt->size = a_receipt_size;
l_receipt->exts_size += l_sign_size;
DAP_DELETE( l_sign );
*a_receipt = l_receipt;
return a_receipt_size;
}
/**
* @brief dap_chain_datum_tx_receipt_sign_get
* @param l_receipt
* @param a_sign_position
* @return
*/
dap_sign_t* dap_chain_datum_tx_receipt_sign_get(dap_chain_datum_tx_receipt_t * l_receipt, size_t l_receipt_size, uint16_t a_sign_position)
{
if ( !l_receipt || l_receipt_size != l_receipt->size || l_receipt_size <= sizeof (l_receipt->receipt_info)+1)
return NULL;
dap_sign_t * l_sign = (dap_sign_t *)l_receipt->exts_n_signs;//+l_receipt->exts_size);
for ( ; a_sign_position && l_receipt_size > (size_t) ( (byte_t *) l_sign - (byte_t *) l_receipt ) ; a_sign_position-- ){
l_sign =(dap_sign_t *) (((byte_t*) l_sign)+ dap_sign_get_size( l_sign ));
}
// not enough signs in receipt
if(a_sign_position>0)
return NULL;
// too big sign size
if((l_sign->header.sign_size + ((byte_t*) l_sign - (byte_t*) l_receipt->exts_n_signs)) >= l_receipt->exts_size)
return NULL;
return l_sign;
}
/**
* @brief dap_chain_datum_tx_receipt_signs_count
* @param a_receipt
* @param a_receipt_size
* @return
*/
uint16_t dap_chain_datum_tx_receipt_signs_count(dap_chain_datum_tx_receipt_t * a_receipt, size_t a_receipt_size)
{
uint16_t l_ret = 0;
if(!a_receipt)
return 0;
dap_sign_t *l_sign;
for (l_sign = (dap_sign_t *)a_receipt->exts_n_signs; a_receipt_size > (size_t) ( (byte_t *) l_sign - (byte_t *) a_receipt ) ;
l_sign =(dap_sign_t *) (((byte_t*) l_sign)+ dap_sign_get_size( l_sign )) ){
l_ret++;
}
if(a_receipt_size != (size_t) ((byte_t *) l_sign - (byte_t *) a_receipt) )
log_it(L_ERROR, "Receipt 0x%x (size=%ud) is corrupted", a_receipt, a_receipt_size);
return l_ret;
}
/*
* Authors:
* Dmitriy A. Gearasimov <kahovski@gmail.com>
* DeM Labs Inc. https://demlabs.net
* DeM Labs Open source community https://github.com/demlabsinc
* Copyright (c) 2017-2019
* All rights reserved.
This file is part of DAP (Deus Applications Prototypes) the open source project
DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
DAP 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 any DAP based project. If not, see <http://www.gnu.org/licenses/>.
*/
#include <dap_chain_datum_tx_token.h>
Subproject commit 8adfc9ceb403d4cf708717165c24cbd1c6a6d830
# Prerequisites
*.d
*.autosave
# Object files
*.o
*.ko
*.obj
*.elf
# Linker output
*.ilk
*.map
*.exp
# Precompiled Headers
*.gch
*.pch
# Libraries
*.lib
*.a
*.la
*.lo
# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
# Debug files
*.dSYM/
*.su
*.idb
*.pdb
# Kernel Module Compile Results
*.mod*
*.cmd
.tmp_versions/
modules.order
Module.symvers
Mkfile.old
dkms.conf
/build/
/.cproject
/.project
language: c
compiler: gcc
dist: xenial
notifications:
email: false
before_install:
- git submodule init
- git submodule update --recursive
script:
- mkdir build
- cd build
- cmake -DBUILD_DAP_CHAIN_CRYPTO_TESTS=ON ../
- make
- ctest --verbose
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- libev-dev
- libjson-c-dev
- libmagic-dev
- libmemcached-dev
- libldb-dev
- libtalloc-dev
- libtevent-dev
cmake_minimum_required(VERSION 2.8)
project (dap_chain_crypto)
set(DAP_CHAIN_CRYPTO_SRCS
dap_hash_slow.c
)
set(DAP_CHAIN_CRYPTO_HEADERS
dap_hash_slow.h
)
if(NOT SUBMODULES_NO_BUILD)
# Check whether we're on a 32-bit or 64-bit system
if(CMAKE_SIZEOF_VOID_P EQUAL "8")
set(DEFAULT_BUILD_64 ON)
else()
set(DEFAULT_BUILD_64 OFF)
endif()
option(BUILD_64 "Build for 64-bit? 'OFF' builds for 32-bit." ${DEFAULT_BUILD_64})
# set(_CCOPT "-Wall -O2 -pg -fPIC -fno-pie -no-pie")
# set(_LOPT "-pg")
# set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -pg")
# set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${_CCOPT}")
# set(CMAKE_LINKER_FLAGS "${CMAKE_LINKER_FLAGS} ${_LOPT}")
if (NOT (TARGET dap_core))
add_subdirectory(libdap)
endif()
if (NOT (TARGET dap_crypto))
add_subdirectory(libdap-crypto)
endif()
if (NOT (TARGET dap_chain))
add_subdirectory(libdap-chain)
endif()
if (NOT (TARGET dap_chain_mempool))
add_subdirectory(libdap-chain-mempool)
endif()
if (NOT (TARGET dap_server_core))
add_subdirectory(libdap-server-core)
endif()
if (NOT (TARGET dap_chain_net))
add_subdirectory(libdap-chain-net)
endif()
if (NOT (TARGET dap_chain_global_db) AND NOT ANDROID)
add_subdirectory(libdap-chain-global-db)
endif()
if (NOT (TARGET dap_client))
add_subdirectory(libdap-client)
endif()
if (NOT (TARGET dap_server))
add_subdirectory(libdap-server)
endif()
if (NOT (TARGET dap_udp_server))
add_subdirectory(libdap-server-udp)
endif()
if (NOT (TARGET libdap-stream))
add_subdirectory(libdap-stream)
endif()
if (NOT (TARGET dap_stream_ch))
add_subdirectory(libdap-stream-ch)
endif()
if (NOT (TARGET dap_stream_ch_chain))
add_subdirectory(libdap-stream-ch-chain)
endif()
if (NOT (TARGET dap_stream_ch_chain_net))
add_subdirectory(libdap-stream-ch-chain-net)
endif()
if (NOT (TARGET dap_chain_wallet))
add_subdirectory(libdap-chain-wallet)
endif()
if (NOT (TARGET dap_chain_net_srv))
add_subdirectory(libdap-chain-net-srv)
endif()
if (NOT (TARGET dap_server_http_db_auth) AND NOT ANDROID)
add_subdirectory(libdap-server-http-db-auth)
endif()
if (NOT (TARGET dap_chain_gdb))
add_subdirectory(libdap-chain-gdb)
endif()
endif()
add_subdirectory(monero_crypto)
include_directories("${monero_crypto_INCLUDE_DIRS}")
add_definitions ("${monero_crypto_DEFINITIONS}")
add_library(${PROJECT_NAME} STATIC ${DAP_CHAIN_CRYPTO_SRCS} ${DAP_CHAIN_CRYPTO_HEADERS})
target_include_directories(dap_chain_crypto INTERFACE .)
target_link_libraries(dap_chain_crypto dap_core dap_crypto dap_chain monero_crypto)
set(${PROJECT_NAME}_DEFINITIONS CACHE INTERNAL "${PROJECT_NAME}: Definitions" FORCE)
set(${PROJECT_NAME}_INCLUDE_DIRS ${PROJECT_SOURCE_DIR} CACHE INTERNAL "${PROJECT_NAME}: Include Directories" FORCE)
if (${BUILD_DAP_CHAIN_CRYPTO_TESTS} MATCHES ON)
enable_testing()
add_subdirectory(test)
endif()
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
# libdap-chain-crypto
DapChain Cryptography and hash functions
/*
* Authors:
* Dmitriy A. Gearasimov <kahovski@gmail.com>
* DeM Labs Inc. https://demlabs.net
* DeM Labs Open source community https://github.com/demlabsinc
* Copyright (c) 2017-2018
* All rights reserved.
This file is part of DAP (Deus Applications Prototypes) the open source project
DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
DAP 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 any DAP based project. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dap_hash_slow.h"
/*
* Authors:
* Dmitriy A. Gearasimov <kahovski@gmail.com>
* DeM Labs Inc. https://demlabs.net
* DeM Labs Open source community https://github.com/demlabsinc
* Copyright (c) 2017-2018
* All rights reserved.
This file is part of DAP (Deus Applications Prototypes) the open source project
DAP (Deus Applicaions Prototypes) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
DAP 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 any DAP based project. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "hash-ops.h"
#define DAP_HASH_SLOW_SIZE HASH_SIZE
/**
* @brief dap_hash_slow
* @param a_in
* @param a_in_length
* @param a_out Must be allocated with enought space
*/
static inline void dap_hash_slow(const void *a_in, size_t a_in_length, char * a_out)
{
cn_slow_hash(a_in,a_in_length,a_out);
}
static inline size_t dap_hash_slow_size() { return DAP_HASH_SLOW_SIZE; }
//cn_slow_hash(data, length, reinterpret_cast<char *>(&hash));
# HashFusion Makefile
# April 2017
#
# Author: brian.monahan@hpe.com
#
# (c) Copyright 2017 Hewlett Packard Enterprise Development LP
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
SHELL = /bin/sh
PWD = $(shell pwd)
CC ?= gcc # gcc clang
# Variables
PROG := hmt
# Source Directories
LIBDIR := $(PWD)/lib
APPDIR := $(PWD)/app
# Set source directory paths
VPATH = $(LIBDIR) $(APPDIR)
# Binary/Object Directories
BINDIR := $(PWD)/bin
OBJDIR := $(PWD)/obj
# Library paths and compiler options
CRYPTO := -L/usr/local/lib -L/usr/local/ssl/lib -lcrypto
LDOPTS := -ldl -lm $(CRYPTO) # -lm -lssl
INCLUDES := -iquote$(LIBDIR) -I/usr/local/ssl/include
CODEOPTS := -D SUPPRESS_REQUIRES_CHECKING -D SUPPRESS_NEEDS_CHECKING -D USE_MALLOC_AND_FREE #
COPTS := -O3 -finline-functions $(CODEOPTS) # -finline-functions -O2 -O3
CFLAGS := -std=c99 $(COPTS) -Werror -Winline $(INCLUDES) # -Wall -g
APPS := $(wildcard $(APPDIR)/*.c)
LIBS := $(wildcard $(LIBDIR)/*.c)
ALL_APPS := $(PROG)
OBJS := $(LIBS:$(LIBDIR)/%.c=$(OBJDIR)/%.o) # standard lib objects
# Empty .SUFFIXES rule to defeat built-in rules
.SUFFIXES: ;
# PHONY targets (i.e. commands)
.PHONY: help build rebuild clean
help :
@echo
@echo " clean : Cleans directory"
@echo " build : Build $(PROG)"
@echo " rebuild : First clean directory then build"
build :
@make clean
@make hmt
clean :
@echo "Cleaning ..."
@rm -rf $(BINDIR)
@rm -rf $(OBJDIR)
@mkdir -p $(BINDIR)
@mkdir -p $(OBJDIR)
@rm -f *.exe *.plist *.o *.s *.bc *.stackdump a.out
hmt :: $(OBJDIR)/hmt.o $(OBJS)
@echo
@echo Linking objects for: $@
@$(CC) -o $@ $^ $(LDOPTS)
@mkdir -p $(BINDIR)
@mv $@ $(BINDIR)
@echo Contents of: $(BINDIR)
@ls -l $(BINDIR)
@echo
$(OBJDIR)/%.o :: %.c utils.h
@echo Compiling lib object $@
@mkdir -p $(OBJDIR)
@$(CC) -o $@ $(CFLAGS) -c $<
/* hmt.c
Hash Fusion/Merkle Tree testing application
Application for examining/comparing the effect of different configurations and settings.
The basic experiment consists of:
1) Generating a sequence of data blocks
2) Calculating a hash of the given blocks (computed in sequence).
(a) This could use accumulation structure to build hash (albeit trivial).
(b) No accumulation - simply directly add to end.
3) Randomising the blocks.
4) Rehashing the sequence of blocks, using a given accumulation structure
to build the hash.
5) Compare blocks ... (should be identical)
The properties that can be varied include
- The kind of accumulation structure used.
- The first hash could be accumulated sequentially without using accumulation sequence.
- Number of repetitions to obtain an time average (+ indication of variance.)
- blocksize used
- Number of blocks + range of number of blocks
- Output format: console output/CSV output /JSON output
Author: brian.monahan@hpe.com
(c) Copyright 2017 Hewlett Packard Enterprise Development LP
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "utils.h"
#include "alloc.h"
#include "random.h"
#include "testLib.h"
#include "stringbuffer.h"
////////////////////////////////////////////////////////////////////////////////
// Types and Structs
////////////////////////////////////////////////////////////////////////////////
typedef enum {
HASHFUSION_ONLY_TESTMODE = 2000, // HashFusion only
MERKLETREE_ONLY_TESTMODE, // Merkle Tree only
DEFAULT_TESTMODE // Default only
} TestMode_t;
typedef enum {
CONSOLE_OUTPUT_MODE = 2010, // Console putput mode
CSV_OUTPUT_MODE, // CSV output mode
JSON_OUTPUT_MODE // JSON output mode
} OutputMode_t;
typedef enum {
HASHFUSION_METHOD, // HashFusion method
MERKLETREE_METHOD, // Merkle Tree method
} MethodType_t;
typedef struct reportObj Report_t;
struct reportObj {
MethodType_t method;
int seed;
int blocksize;
int numBlocks;
int dataSize;
int runs;
HFuseAccum_t accumType;
double initialTime;
double initialDataRate;
double destTime;
double destDataRate;
};
////////////////////////////////////////////////////////////////////////////////
// Control Properties
////////////////////////////////////////////////////////////////////////////////
static unsigned int argSeed = 27652761;
static int argTotalBlocks = 50;
static int argBlockSize = 1024;
static int argRuns = 1;
static TestMode_t argTestMode = DEFAULT_TESTMODE; // Test mode
static Boolean_t argSendOnly = FALSE; // Send only? Otherwise do both send/receive
static HFuseAccum_t argAccumKind = TREE_SET_ACCUM_HF; // LINEAR_LIST_ACCUM_HF; DIRECT_ACCUM_HF;
static OutputMode_t argOutputMode = CONSOLE_OUTPUT_MODE;
// Total data (in bytes)
static long totalData = 0;
// Digests (hash fusion)
static Digest_t *resultDigest_src_hf = NULL;
static Digest_t *resultDigest_dest_hf = NULL;
static double srcTimeInSecs_hf = 0.0;
static double destTimeInSecs_hf = 0.0;
// Merkle Tree info
static Digest_t *resultDigest_src_mt = NULL;
static Digest_t *resultDigest_dest_mt = NULL;
static double srcTimeInSecs_mt = 0.0;
static double destTimeInSecs_mt = 0.0;
// Report objects
#define UPDATE_REPORT(rep, fld, val) { if ((rep) != NULL) {rep->fld = (val); }}
static Report_t *report_hf = NULL;
static Report_t *report_mt = NULL;
////////////////////////////////////////////////////////////////////////////////
// Display Enum types
////////////////////////////////////////////////////////////////////////////////
static char *show_TestMode(TestMode_t val) {
switch (val) {
case HASHFUSION_ONLY_TESTMODE: return "HASHFUSION_ONLY_TESTMODE";
case MERKLETREE_ONLY_TESTMODE: return "MERKLETREE_ONLY_TESTMODE";
case DEFAULT_TESTMODE: return "DEFAULT_TESTMODE";
default:
diagnostic("show_TestMode: Expected a TestMode_t value - got instead: %i", val);
error_exit();
}
}
static char *show_OutputMode(OutputMode_t val) {
switch (val) {
case CONSOLE_OUTPUT_MODE: return "CONSOLE_OUTPUT_MODE";
case CSV_OUTPUT_MODE: return "CSV_OUTPUT_MODE";
case JSON_OUTPUT_MODE: return "JSON_OUTPUT_MODE";
default:
diagnostic("show_OutputMode: Expected a OutputMode_t value - got instead: %i", val);
error_exit();
}
}
static char *show_MethodType(MethodType_t val) {
switch (val) {
case HASHFUSION_METHOD: return "HASHFUSION_METHOD";
case MERKLETREE_METHOD: return "MERKLETREE_METHOD";
default:
diagnostic("show_MethodType: Expected a MethodType_t value - got instead: %i", val);
error_exit();
}
}
////////////////////////////////////////////////////////////////////////////////
// Usage
////////////////////////////////////////////////////////////////////////////////
#undef NL
#undef SP
#define NL "\n"
#define SP " "
static void usage() {
char *usageString =
"Usage: hmt <options>" NL
NL
" This app provides command-line performance tests of hash-fusion code" NL
" compared with using Merkle Trees." NL
NL
" The basic experiment consists of:" NL
" 1) Generating a sequence of randomised data blocks" NL
" 2) Calculating hash of the given block (computed in sequence)." NL
" 3) Randomise the order of the blocks so that they are presented in randomised sequence." NL
" 4) Rehash the out-of-order sequence of blocks by using a specified accumulation structure." NL
" to build the required in-order hash." NL
" 5) Compare the two hashes ... (hashes should be identical)" NL
" 6) Report statistics (e.g. timing averages)" NL
NL
" The following options are supported:" NL
NL
" -a <accum-type> : Accumulation structure (either d: direct, l: linear, t: tree)" NL
" (default: t)." NL
NL
" -s <seed-value> : Seed value for generating random data. Setting this to" NL
" zero provides a seed determined by date/time" NL
" (default: 27652761)." NL
NL
" -h : HashFusion only." NL
NL
" -m : Merkle Tree only." NL
NL
" -r <runs> : Number of runs (default: 1)." NL
NL
" -n <blocks> : Number of blocks. (default: 50)" NL
NL
" -b <block-size> : Size of each data block (default: 1024 bytes)." NL
NL
" -csv : CSV format report output -- reports stats using csv output format." NL
" This format will output the column header line once." NL
NL
" -json : JSON format report output." NL
NL
" The block-size and number of blocks options can use a multiplier code (k = 1024)." NL
NL
" When using the 'direct' accumulation structure, it doesn't make sense to deal with out-of-order" NL
" data. In this case, only the first two (and final) steps are performed." NL
NL
" Examples:" NL
" hmt -s 236483624 -b 8k -n 22k -r 20" NL
" -- Use seed 236483624, blocksize = 8192, number of blocks = 22528, runs = 20" NL
" and default binary tree accumulation structure" NL
NL
" hmt -s 4526263 -b 4k -n 2k -r 30 -a l" NL
" -- Use seed 4526263, blocksize = 4096, number of blocks = 2048, runs = 30" NL
" and use the linear list accumulation structure" NL
NL
" hmt -b 6035 -h -n 16k -r 25" NL
" -- Use default seed, blocksize = 6035, perform HashFusion only, number " NL
" of blocks = 16384, and runs = 25" NL
;
printf("%s", usageString);
exit(0);
}
////////////////////////////////////////////////////////////////////////////////
// Process arguments
////////////////////////////////////////////////////////////////////////////////
// Argument codes
#define ARG_SEED 's'
#define ARG_BLOCK_SIZE 'b'
#define ARG_NUM_BLOCKS '#'
#define ARG_RUNS 'r'
#define ARG_ACCUM_TYPE 'a'
static void processArgs(int argc, char *argv[]) {
char *argStr = NULL;
char code;
char str[STD_BUFSIZE];
int intVal;
// This encodes if the current arg is expected to encode data ...
Boolean_t isDataArg = FALSE;
Byte_t dataArgCode = 0;
if (argc == 1) {
usage();
}
for (int i=1; i < argc; i++) {
argStr = argv[i];
toLowerCase(argStr); // lower case the argument string ...
//printf("%i. %s\n", i, argStr);
if (dataArgCode != 0) {
switch (dataArgCode) {
case ARG_SEED:
if (sscanf(argStr, "%i", &argSeed) == 1) {
if (argSeed < 0) argSeed = -argSeed;
}
else {
diagnostic("Expected an integer ... got instead: %s", argStr);
error_exit();
}
break;
case ARG_BLOCK_SIZE:
if (sscanf(argStr, "%i%c", &argBlockSize, &code) == 2) {
switch (code) {
case 'k': argBlockSize *= 1024; break;
default:
diagnostic("Expected an integer followed by multiplier (k) ... got instead: %s", argStr);
error_exit();
}
}
else if (sscanf(argStr, "%i", &argBlockSize) > 0) {
// SKIP - NO CODE
}
else {
diagnostic("Expected an integer ... got instead: %s", argStr);
error_exit();
}
// Limit value of argBlockSize
argBlockSize = minmax(1, argBlockSize, 128 * 1024);
break;
case ARG_NUM_BLOCKS:
if (sscanf(argStr, "%i%c", &argTotalBlocks, &code) == 2) {
switch (code) {
case 'k': argTotalBlocks *= 1024; break;
default:
diagnostic("Expected an integer followed by multiplier (k) ... got instead: %s", argStr);
error_exit();
}
}
else if (sscanf(argStr, "%i", &argTotalBlocks) > 0) {
// SKIP - NO CODE
}
else {
diagnostic("Expected an integer ... got instead: %s", argStr);
error_exit();
}
// Limit value of argTotalBlocks
argTotalBlocks = minmax(1, argTotalBlocks, 32 * 1024);
break;
case ARG_RUNS:
if (sscanf(argStr, "%i", &argRuns) == 1) {
argRuns = min(argRuns, 100);
if (argRuns < 1) {
diagnostic("Number of runs should be positive: %s", argStr);
error_exit();
}
}
else {
diagnostic("Expected an integer ... got instead: %s", argStr);
error_exit();
}
// Limit value of argRuns
argRuns = minmax(1, argRuns, 256);
break;
case ARG_ACCUM_TYPE:
if (sscanf(argStr, "%c", &code) == 1) {
argSendOnly = FALSE;
switch (code) {
case 'd': argAccumKind = DIRECT_ACCUM_HF; argSendOnly = TRUE; break;
case 'l': argAccumKind = LINEAR_LIST_ACCUM_HF; break;
case 't': argAccumKind = TREE_SET_ACCUM_HF; break;
default:
diagnostic("Expected a code specifying accumulation structure (e.g. d, l or t) ... got instead: %s", argStr);
error_exit();
}
}
else {
diagnostic("Expected a character specifying accumulation structure (e.g. d, l or t) ... got instead: %s", argStr);
error_exit();
}
break;
default:
diagnostic("Unexpected data element: %s", argStr);
error_exit();
}
dataArgCode = 0;
continue;
}
dataArgCode = 0;
// seed option
if (strncmp("-s", argStr, 2) == 0) {
dataArgCode = ARG_SEED;
continue;
}
// block-size option
if (strncmp("-b", argStr, 2) == 0) {
dataArgCode = ARG_BLOCK_SIZE;
continue;
}
// hash-fusion only option
if (strncmp("-h", argStr, 2) == 0) {
argTestMode = HASHFUSION_ONLY_TESTMODE;
report_hf = ALLOC_OBJ(Report_t);
continue;
}
// merkle tree only option
if (strncmp("-m", argStr, 2) == 0) {
argTestMode = MERKLETREE_ONLY_TESTMODE;
report_mt = ALLOC_OBJ(Report_t);
continue;
}
// number of blocks option
if (strncmp("-n", argStr, 2) == 0 || strncmp("-#", argStr, 2) == 0) {
dataArgCode = ARG_NUM_BLOCKS;
continue;
}
if (strncmp("-r", argStr, 2) == 0) {
dataArgCode = ARG_RUNS;
continue;
}
// accumulation type option
if (strncmp("-a", argStr, 2) == 0) {
dataArgCode = ARG_ACCUM_TYPE;
continue;
}
// csv format option
if (strncmp("-c", argStr, 2) == 0) {
argOutputMode = CSV_OUTPUT_MODE;
continue;
}
// json format option
if (strncmp("-j", argStr, 2) == 0) {
argOutputMode = JSON_OUTPUT_MODE;
continue;
}
// unrecognised option & help option
if (strncmp("-", argStr, 1) == 0) {
usage();
}
// Error - unexpected argument
diagnostic("Unexpected argument: %s", argStr);
error_exit();
}
// Ensure definition of reports in default testmode ...
if (argTestMode == DEFAULT_TESTMODE) {
report_hf = ALLOC_OBJ(Report_t);
report_mt = ALLOC_OBJ(Report_t);
}
/*
if (DONT) {
printf("\nApplication state set to:\n");
printf(" argSeed = %i\n", argSeed);
printf(" argTotalBlocks = %i\n", argTotalBlocks);
printf(" argBlockSize = %i\n", argBlockSize);
printf(" argRuns = %i\n", argRuns);
printf(" argAccumKind = %s\n", show_HFuseAccum(argAccumKind));
printf(" argTestMode = %s\n", show_TestMode(argTestMode));
printf(" argOutputMode = %s\n", show_OutputMode(argOutputMode));
printf(" argSendOnly = %s\n", showBoolean(argSendOnly));
printf("\n");
//exit(0);
}
*/
//exit(0);
}
////////////////////////////////////////////////////////////////////////////////
// Output reporting
////////////////////////////////////////////////////////////////////////////////
static void consoleOut(const char *fmt, ...) {
if (argOutputMode != CONSOLE_OUTPUT_MODE) return;
va_list args;
va_start(args, fmt);
vfprintf(stdout, fmt, args);
va_end(args);
}
static char statsReportBuf[MSG_BUFSIZE+1];
static Report_t *new_Report() {
return ALLOC_OBJ(Report_t);
}
static char csvHeader[] = "Method, Seed, Blocksize, NumBlocks, Datasize, Runs, AccumType, "
"Initial Time, Initial Data Rate, Destination Time, Destination Data Rate\n";
static Boolean_t csvHeaderShown = FALSE;
static void csvOut(Report_t *rep) {
if (rep == NULL) return;
if (argOutputMode != CSV_OUTPUT_MODE) return;
if (!csvHeaderShown) {
printf("%s", csvHeader);
csvHeaderShown = TRUE;
}
printf("\"%s\", ", show_MethodType(rep->method));
printf("%i, ", rep->seed);
printf("%i, ", rep->blocksize);
printf("%i, ", rep->numBlocks);
printf("%i, ", rep->dataSize);
printf("%i, ", rep->runs);
printf("\"%s\", ", (rep->accumType == 0 ? "" : show_HFuseAccum(rep->accumType)));
printf("%5f, ", rep->initialTime);
printf("%5f, ", rep->initialDataRate);
printf("%5f, ", rep->destTime);
printf("%5f\n", rep->destDataRate);
}
static void jsonOut(Report_t *rep) {
if (rep == NULL) return;
if (argOutputMode != JSON_OUTPUT_MODE) return;
printf("{method:\"%s\", ", show_MethodType(rep->method));
printf("seed:%i, ", rep->seed);
printf("blocksize:%i, ", rep->blocksize);
printf("numblocks:%i, ", rep->numBlocks);
printf("datasize:%i, ", rep->dataSize);
printf("runs:%i, ", rep->runs);
printf("accum-type:\"%s\", ", (rep->accumType == 0 ? "" : show_HFuseAccum(rep->accumType)));
printf("initial-time:%5f, ", rep->initialTime);
printf("initial-data-rate:%5f, ", rep->initialDataRate);
printf("dest-time:%5f, ", rep->destTime);
printf("dest-data-rate:%5f}", rep->destDataRate);
}
////////////////////////////////////////////////////////////////////////////////
// Methods
////////////////////////////////////////////////////////////////////////////////
void runSrc_FusionStruct() {
// Compute digest value
Digest_t *curDigest = calcDigest_FusionStruct(NULL);
if (getHashState_DG(curDigest) != HST_FINAL) {
diagnostic("runSrc_FusionStruct: digest was not finalised: digest state = %s", showHashState_DG(curDigest));
error_exit();
}
if (resultDigest_src_hf == NULL) {
// Transfer curDigest to resultDigest_src_hf
resultDigest_src_hf = curDigest;
curDigest = NULL;
}
else if (!isEqual_DG(resultDigest_src_hf, curDigest)) {
StringBuf_t *sBuf = new_SB();
addItems_SB(sBuf, "runSrc_FusionStruct: digests not equal:\n");
addItems_SB(sBuf, " resultDigest_src_hf digest = 0x%s\n", showHexHashValue_DG(resultDigest_src_hf));
addItems_SB(sBuf, " current digest = 0x%s", showHexHashValue_DG(curDigest));
error_exit_SB(sBuf);
}
// Deallocate the current digest ...
deallocate_DG(curDigest);
}
void runDest_FusionStruct() {
// Compute digest value
Digest_t *curDigest = calcDigest_FusionStruct(destBlocksPerm);
if (getHashState_DG(curDigest) != HST_FINAL) {
diagnostic("runDest_FusionStruct: digest was not finalised: digest state = %s", showHashState_DG(curDigest));
error_exit();
}
if (resultDigest_dest_hf == NULL) {
// Transfer curDigest to resultDigest_dest_hf
resultDigest_dest_hf = curDigest;
curDigest = NULL;
}
else if (!isEqual_DG(resultDigest_dest_hf, curDigest)) {
StringBuf_t *sBuf = new_SB();
addItems_SB(sBuf, "runDest_FusionStruct: digests not equal:\n");
addItems_SB(sBuf, " resultDigest_dest_hf digest = 0x%s\n", showHexHashValue_DG(resultDigest_dest_hf));
addItems_SB(sBuf, " current digest = 0x%s", showHexHashValue_DG(curDigest));
error_exit_SB(sBuf);
}
// Deallocate the current digest ...
deallocate_DG(curDigest);
}
static void runSrc_MerkleTree() {
// Compute digest value
Digest_t *curDigest = calcDigest_MerkleTree(NULL);
if (getHashState_DG(curDigest) != HST_FINAL) {
diagnostic("runSrc_MerkleTree: digest was not finalised: digest state = %s", showHashState_DG(curDigest));
error_exit();
}
if (resultDigest_src_mt == NULL) {
// Transfer curDigest to resultDigest_src_mt
resultDigest_src_mt = curDigest;
curDigest = NULL;
}
else if (!isEqual_DG(resultDigest_src_mt, curDigest)) {
StringBuf_t *sBuf = new_SB();
addItems_SB(sBuf, "runSrc_MerkleTree: digests not equal:\n");
addItems_SB(sBuf, " resultDigest_src_mt digest = 0x%s\n", showHexHashValue_DG(resultDigest_src_mt));
addItems_SB(sBuf, " current digest = 0x%s", showHexHashValue_DG(curDigest));
error_exit_SB(sBuf);
}
// Deallocate the current digest ...
deallocate_DG(curDigest);
}
void runDest_MerkleTree() {
// Compute digest value
Digest_t *curDigest = calcDigest_MerkleTree(destBlocksPerm);
if (getHashState_DG(curDigest) != HST_FINAL) {
diagnostic("runDest_FusionStruct: digest was not finalised: digest state = %s", showHashState_DG(curDigest));
error_exit();
}
if (resultDigest_dest_mt == NULL) {
// Transfer curDigest to resultDigest_dest_mt
resultDigest_dest_mt = curDigest;
curDigest = NULL;
}
else if (!isEqual_DG(resultDigest_dest_mt, curDigest)) {
StringBuf_t *sBuf = new_SB();
addItems_SB(sBuf, "runDest_MerkleTree: digests not equal:\n");
addItems_SB(sBuf, " resultDigest_dest_mt digest = 0x%s\n", showHexHashValue_DG(resultDigest_dest_mt));
addItems_SB(sBuf, " current digest = 0x%s", showHexHashValue_DG(curDigest));
error_exit_SB(sBuf);
}
// Deallocate the current digest ...
deallocate_DG(curDigest);
}
// This code ensures that various memory caches have been flushed/overwritten.
static unsigned int *memFlushBuf = NULL;
static void flushMemoryCaches() {
int memSize = 5 * 1024 * 1024;
memFlushBuf = ALLOC_ARR(memSize, unsigned int);
// load the memory with random data
for (int i = 0; i < memSize; i++) {
memFlushBuf[i] = nextRandom();
}
// Do some meaningless computation that uses the memory ...
unsigned int limit = pow2(17) + 5;
unsigned int sum = 0;
for (int i = memSize-1; 0 <= i; i--) {
sum += memFlushBuf[i];
if (sum >= limit) {
sum = 0;
}
}
free(memFlushBuf);
memFlushBuf = NULL;
}
////////////////////////////////////////////////////////////////////////////////
// Run tests
////////////////////////////////////////////////////////////////////////////////
static void produceResults() {
// Produce results ...
if (argTestMode != MERKLETREE_ONLY_TESTMODE) {
double srcDataRate_hf = totalData/(1024 * 1024 * srcTimeInSecs_hf);
consoleOut("\n\nHashFusion:\n");
consoleOut(" Source build-time: %.5f secs (data rate: %.5f MB/sec)\n", srcTimeInSecs_hf, srcDataRate_hf);
// update report
UPDATE_REPORT(report_hf, initialDataRate, srcDataRate_hf);
if (!argSendOnly) {
double destDataRate_hf = totalData/(1024 * 1024 * destTimeInSecs_hf);
consoleOut(" Dest. build-time: %.5f secs (data rate: %.5f MB/sec)\n", destTimeInSecs_hf, destDataRate_hf);
// update report
UPDATE_REPORT(report_hf, destDataRate, destDataRate_hf);
}
}
if (argTestMode != HASHFUSION_ONLY_TESTMODE) {
double srcDataRate_mt = totalData/(1024 * 1024 * srcTimeInSecs_mt);
consoleOut("\n\nMerkle hash tree:\n");
consoleOut(" Source build-time: %.5f secs (data rate: %.5f MB/sec)\n", srcTimeInSecs_mt, srcDataRate_mt);
// update report
UPDATE_REPORT(report_mt, initialDataRate, srcDataRate_mt);
if (!argSendOnly) {
double destDataRate_mt = totalData/(1024 * 1024 * destTimeInSecs_mt);
consoleOut(" Dest. build-time: %.5f secs (data rate: %.5f MB/sec)\n", destTimeInSecs_mt, destDataRate_mt);
// update report
UPDATE_REPORT(report_mt, destDataRate, destDataRate_mt);
}
}
// stats output
csvOut(report_hf);
csvOut(report_mt);
jsonOut(report_hf);
jsonOut(report_mt);
}
void runTest () {
consoleOut("Hashfusion-Merkle tree Testing tool (HMT)\n");
consoleOut("-- Testing pure data transfer with randomisation\n");
//debugOn = FALSE;
//checkAllocation_MM = FALSE;
//checkDeallocation_MM = FALSE;
setSeed(argSeed);
consoleOut("-- Current seed value: %i\n", getSeed() );
blockSize = argBlockSize;
totalBlocks = argTotalBlocks;
argRuns = max(1, argRuns);
accumKind = argAccumKind;
totalData = (long)(blockSize * totalBlocks);
// Update report values
//
// MethodType_t method;
// int seed;
// int blocksize;
// int numBlocks;
// int dataSize;
// int runs;
// HFuseAccum_t accumType;
// double initialTime;
// double initialDataRate;
// double destTime;
// double destDataRate;
//
UPDATE_REPORT(report_hf, method, HASHFUSION_METHOD);
UPDATE_REPORT(report_mt, method, MERKLETREE_METHOD);
UPDATE_REPORT(report_hf, seed, argSeed);
UPDATE_REPORT(report_mt, seed, argSeed);
UPDATE_REPORT(report_hf, blocksize, blockSize);
UPDATE_REPORT(report_mt, blocksize, blockSize);
UPDATE_REPORT(report_hf, numBlocks, totalBlocks);
UPDATE_REPORT(report_mt, numBlocks, totalBlocks);
UPDATE_REPORT(report_hf, dataSize, totalData);
UPDATE_REPORT(report_mt, dataSize, totalData);
UPDATE_REPORT(report_hf, runs, argRuns);
UPDATE_REPORT(report_mt, runs, argRuns);
UPDATE_REPORT(report_hf, accumType, accumKind);
UPDATE_REPORT(report_mt, accumType, NULL_VAL); // accumType not relevant to Merkle Tree
// Output accumulation info
switch (accumKind) {
case DIRECT_ACCUM_HF: consoleOut("-- Using Direct accumulation (%i).\n", accumKind); break;
case LINEAR_LIST_ACCUM_HF: consoleOut("-- Using Linear list accumulation structure (%i).\n", accumKind); break;
case TREE_SET_ACCUM_HF: consoleOut("-- Using Red-Black tree set accumulation structure (%i).\n", accumKind); break;
default:
diagnostic("runTest: accumKind not set to good value: %i", accumKind);
error_exit();
}
consoleOut("\nInitialising data blocks ...\n");
consoleOut(" -- Block size: %i\n", blockSize);
consoleOut(" -- Number of (randomised) data blocks: %i\n", totalBlocks);
consoleOut(" -- Amount of data: %li bytes\n", totalData);
initialiseTestData();
populateBlocks();
// Build the source hash structure
consoleOut("\nBuilding source hash structures ... (Runs: %i)\n", argRuns);
double totalSrcTimeInSecs_hf = 0;
double totalSrcTimeInSecs_mt = 0;
if (argTestMode != MERKLETREE_ONLY_TESTMODE) {
consoleOut(" -- Using HashFusion ...\n");
totalSrcTimeInSecs_hf = timeFunction2( argRuns, flushMemoryCaches, runSrc_FusionStruct );
}
if (argTestMode != HASHFUSION_ONLY_TESTMODE) {
consoleOut(" -- Using MerkelTree ...\n");
totalSrcTimeInSecs_mt = timeFunction2( argRuns, flushMemoryCaches, runSrc_MerkleTree );
}
// calc average
srcTimeInSecs_hf = totalSrcTimeInSecs_hf/argRuns;
srcTimeInSecs_mt = totalSrcTimeInSecs_mt/argRuns;
// update reports for initialTime
UPDATE_REPORT(report_hf, initialTime, srcTimeInSecs_hf);
UPDATE_REPORT(report_mt, initialTime, srcTimeInSecs_mt);
if (argSendOnly) {
produceResults();
return;
}
// Simulates the act of receiving the data in some order at the destination
consoleOut("\nRandomise destination order ...\n");
randomiseDestOrder();
consoleOut("\nDestination Order of Data Blocks\n");
int showBlocks = min(5, totalBlocks);
for (int i = 0; i < showBlocks; i++) {
consoleOut(" destBlocksPerm[%i] = %i\n", i, destBlocksPerm[i]);
}
if (showBlocks != totalBlocks) {
int i = totalBlocks-1;
consoleOut(" ...\n");
consoleOut(" destBlocksPerm[%i] = %i\n", i, destBlocksPerm[i]);
}
// Run the destination Hash Fusion structure
consoleOut("\nBuilding the destination hash structure ... (Runs: %i)\n", argRuns);
double totalDestTimeInSecs_hf = 0;
double totalDestTimeInSecs_mt = 0;
if (argTestMode != MERKLETREE_ONLY_TESTMODE) {
consoleOut(" -- Using HashFusion ...\n");
totalDestTimeInSecs_hf = timeFunction2( argRuns, flushMemoryCaches, runDest_FusionStruct );
}
if (argTestMode != HASHFUSION_ONLY_TESTMODE) {
consoleOut(" -- Using MerkelTree ...\n");
totalDestTimeInSecs_mt = timeFunction2( argRuns, flushMemoryCaches, runDest_MerkleTree );
}
// calc average
destTimeInSecs_hf = totalDestTimeInSecs_hf/argRuns;
destTimeInSecs_mt = totalDestTimeInSecs_mt/argRuns;
// Update reports for destTime
UPDATE_REPORT(report_hf, destTime, destTimeInSecs_hf);
UPDATE_REPORT(report_mt, destTime, destTimeInSecs_mt);
// Console Results
if (argTestMode == DEFAULT_TESTMODE) {
// Compare results
consoleOut("\nComparing results ...\n");
if (resultDigest_src_hf != NULL && resultDigest_dest_hf != NULL && isEqual_DG(resultDigest_src_hf, resultDigest_dest_hf)) {
consoleOut("\nSUCCESS! same hashes - using HashFusion:\n 0x%s\n", showHexHashValue_DG(resultDigest_src_hf));
}
else {
consoleOut("\nFAILED! Different HashFusion hashes:\n");
consoleOut(" Source hash value = 0x%s\n", showHexHashValue_DG(resultDigest_src_hf));
consoleOut(" Destination hash value = 0x%s\n", showHexHashValue_DG(resultDigest_dest_hf));
exit(1);
}
if (resultDigest_src_mt != NULL && resultDigest_dest_mt != NULL && isEqual_DG(resultDigest_src_mt, resultDigest_dest_mt)) {
consoleOut("\nSUCCESS! same hashes - using Merkle hash tree:\n 0x%s\n", showHexHashValue_DG(resultDigest_src_mt));
}
else {
consoleOut("\nFAILED! Different Merkle Tree hashes:\n");
consoleOut(" Source hash value = 0x%s\n", showHexHashValue_DG(resultDigest_src_mt));
consoleOut(" Destination hash value = 0x%s\n", showHexHashValue_DG(resultDigest_dest_mt));
exit(1);
}
}
produceResults();
}
//void localTest();
int main(int argc, char *argv[]) {
//localTest();
processArgs(argc, argv);
runTest();
}
/*******************************************************************************
// Deprecated/Test code
static void processArgs(int argc, char *argv[]) {
char *argStr = NULL;
char rest[10];
int val;
double dbl;
char code[1];
for (int i=1; i < argc; i++) {
argStr = argv[i];
consoleOut("%i. %s", i, argStr);
// Use a character to get option char
// if (sscanf(argStr, "-%c", code) > 0) {
// switch (code[0]) {
// case 'a': consoleOut("\tFOUND -f"); break;
// }
// }
if (sscanf(argStr, "%i", &val) > 0) {
consoleOut("\tINT VALUE: %i", val);
}
if (sscanf(argStr, "%lf", &dbl) > 0) {
consoleOut("\tDOUBLE VALUE: %lf", dbl);
}
if (sscanf(argStr, "-%s", rest) > 0) {
consoleOut("\tARG: %s", rest);
}
if (strncmp("-f", argStr, 2) == 0) {
consoleOut("\tstrcmp matched -f");
}
consoleOut("\n");
}
}
********************************************************************************/
/*******************************************************************************
alloc.c
Very simple free-list based storage management
The implementation can be switched to a straightforward malloc/free
version (see USE_MALLOC_AND_FREE).
Author: brian.monahan@hpe.com
(c) Copyright 2017 Hewlett Packard Enterprise Development LP
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utils.h"
#include "alloc.h"
typedef struct pair Pair_t;
struct memMgr {
size_t blockSize; // allocation size
VoidFn_t initFn; // object initialiser function
VoidFn_t finalFn; // object finaliser function
int allocated; // objects allocated
int length; // current length of allocation structure
Pair_t *freeList; // allocation structure
};
struct pair {
void *object; // object pointer
Pair_t *nextItem; // next item
};
// Global old cells list
// - Allows old pairs to be reused ...
static Pair_t *oldPairsList;
// Global allocation structure for free-lists (!)
// - allows free-lists themselves to be allocated and deallocated.
static MemMgr_t *freeList_List = NULL;
// Static Method prototypes
static void ensureMemMgmt(void *obj);
static void dispose_MemMgr_Entries(MemMgr_t *fLst);
////////////////////////////////////////////////////////////////////////////////
// Methods
////////////////////////////////////////////////////////////////////////////////
// creates a newly allocated allocation structure ...
MemMgr_t *new_MM(size_t blockSize) {
req_Pos(blockSize);
// bootstrap allocation of allocation structures
if (freeList_List == NULL) {
// create freeList_List
freeList_List = ALLOC_OBJ(MemMgr_t); // Allocate MemMgr_t object
ensureMemMgmt(freeList_List); // Initialise freeList_List
freeList_List->blockSize = sizeof(MemMgr_t); // set blockSize for MemMgr_t objects
setInitialiser_MM(freeList_List, ensureMemMgmt); // set initialier for MemMgr_t objects
}
// Allocate allocation structure ...
MemMgr_t *newList = allocateObject_MM(freeList_List);
newList->blockSize = blockSize;
return newList;
}
// sets the object initialiser
// - this is run on all allocated objects ...
// either freshly created or reallocated.
void setInitialiser_MM(MemMgr_t *fLst, VoidFn_t initFn) {
req_NonNull(fLst);
fLst->initFn = initFn;
}
// sets the object finaliser
// - this is run when allocation structures are disposed of.
void setFinaliser_MM(MemMgr_t *fLst, VoidFn_t finalFn) {
req_NonNull(fLst);
fLst->finalFn = finalFn;
}
// get length of allocation structure
int getLength_MM(MemMgr_t *fLst) {
req_NonNull(fLst);
return fLst->length;
}
// get blockSize
size_t getBlockSize_MM(MemMgr_t *fLst) {
req_NonNull(fLst);
return fLst->blockSize;
}
// get number of allocated objects
int getAllocated_MM(MemMgr_t *fLst) {
req_NonNull(fLst);
return fLst->allocated;
}
// Resets a allocation structure
// - disposes of allocation structure objects if the newBlockSize is different from current blocksize.
// - finaliser is run on all allocation structures elements.
void reset_MM(MemMgr_t *fLst, size_t newBlockSize) {
req_NonNull(fLst);
req_Pos(newBlockSize);
// check if block size has changed ...
if (newBlockSize == fLst->blockSize) {
// no change needed to fLst object
return;
}
// clears the current objects on allocation structure
dispose_MemMgr_Entries(fLst);
// initialise allocation structure - as though it were freshly allocated
ensureMemMgmt(fLst);
// sets the blocksize
fLst->blockSize = newBlockSize;
}
// recycles a allocation structure ...
void recycle_MM(MemMgr_t *obj) {
MemMgr_t *fLst = (MemMgr_t *)obj;
// dispose of the allocation structure entries
// - this will activate the object finalisers ...
dispose_MemMgr_Entries(fLst);
// recycle the MemMgr_t object on the freeList_List
deallocateObject_MM(freeList_List, sizeof(MemMgr_t), fLst);
}
/*******************************************************************************
Checking integrity
*******************************************************************************/
// Apply check on allocation
// - This check applies to all free-lists
Boolean_t checkAllocation_MM = FALSE;
// Apply check on deallocation
// - This check applies to all free-lists
Boolean_t checkDeallocation_MM = FALSE;
// Check allocation/deallocation integrity
// - checks if the given object is currently recycled ...
// - this is a hard error if so ...
Boolean_t checkIfRecycled_MM(MemMgr_t *fLst, void *obj) {
req_NonNull(fLst);
Pair_t *nextPair = fLst->freeList;
while (nextPair != NULL) {
if (nextPair->object == obj) {
return TRUE;
}
nextPair = nextPair->nextItem;
}
return FALSE;
}
/*******************************************************************************
Static Methods
*******************************************************************************/
static void ensureMemMgmt(void *obj) {
MemMgr_t *fLst = (MemMgr_t *)obj;
//fLst->blockSize
fLst->initFn = NULL;
fLst->finalFn = NULL;
fLst->allocated = 0;
fLst->length = 0;
fLst->freeList = NULL;
}
static void dispose_MemMgr_Entries(MemMgr_t *fLst) {
req_NonNull(fLst);
Pair_t* cells = fLst->freeList; // ensures that we only act upon an allocation structure ...
if (cells == NULL) {
// Nothing to do ...
return;
}
VoidFn_t finalFn =
(fLst->finalFn == NULL ? free : fLst->finalFn);
Pair_t *curPair = cells;
Pair_t *prevPair = NULL;
// move all cells to oldPairsList and reset any objects
while (curPair != NULL) {
// Make prevPair equal to the curPair.
prevPair = curPair;
// Set curPair to the next cell pointed at by prevPair
curPair = prevPair->nextItem;
// Finalise the object (if any) pointed at by prevPair;
finalFn(prevPair->object);
prevPair->object = NULL;
// Add prevPair to oldPairsList
prevPair->nextItem = oldPairsList;
oldPairsList = prevPair;
}
}
////////////////////////////////////////////////////////////////////////////////
// Allocation and Deallocation Methods
////////////////////////////////////////////////////////////////////////////////
#ifdef USE_MALLOC_AND_FREE
/////////////////////////////////////////////////////////////////////////////
// Straightforward allocation using malloc/free
/////////////////////////////////////////////////////////////////////////////
// Allocates an object
// - runs the object initialiser function (if non-null).
void *allocateObject_MM(MemMgr_t *fLst) {
req_NonNull(fLst);
// allocates fresh object memory
// - guaranteed to be zeroed (IMPORTANT!!)
void *resultObj = ALLOC_BLK(fLst->blockSize);
fLst->allocated += 1;
// run the object initialiser ... if initialiser function is non-null
if (fLst->initFn != NULL) {
fLst->initFn(resultObj);
}
return resultObj;
}
// Deallocates object by adding it to the allocation structure
// - the object is NOT finalised here ... only when allocation structures are disposed of/recycled.
// - the objSize parameter provides a simple check that the object is being returned
// to the correct memory pool.
void deallocateObject_MM(MemMgr_t *fLst, size_t objSize, void *obj) {
if (obj == NULL) return;
req_NonNull(fLst);
req_EQ(objSize, fLst->blockSize); // heuristic integrity check that sizes are correct (not perfect)
free(obj);
}
#else
/////////////////////////////////////////////////////////////////////////////
// Allocation using allocation structures
/////////////////////////////////////////////////////////////////////////////
// Allocates an object (from allocation structure when possible)
// - runs the object initialiser function (if non-null).
void *allocateObject_MM(MemMgr_t *fLst) {
req_NonNull(fLst);
void *resultObj = NULL;
Pair_t *freePairs = fLst->freeList;
if (freePairs == NULL) {
// allocates fresh object memory
// - guaranteed to be zeroed (IMPORTANT!!)
resultObj = ALLOC_BLK(fLst->blockSize);
fLst->allocated += 1;
}
else {
needs_Pos("length of allocation structure is not > 0", fLst->length);
// take the top free cell from free cells
Pair_t *topPair = freePairs;
// extract object from top cell..
resultObj = topPair->object;
// Ensure that the top cell releases object
topPair->object = NULL;
// update allocation structure entry (i.e. remove topPair from allocation structure)
fLst->freeList = topPair->nextItem;
// reduce length of allocation structure
fLst->length -= 1;
// make topPair point at the current old cells list
topPair->nextItem = oldPairsList;
// move top cell to the top of old cells list
oldPairsList = topPair;
}
// run the object initialiser ... if initialiser function is non-null
if (fLst->initFn != NULL) {
fLst->initFn(resultObj);
}
// check that allocated object is *not* curently deallocated ...
if (checkAllocation_MM) {
if (checkIfRecycled_MM(fLst, resultObj)) {
diagnostic("allocateObject_MM: Allocated object is currently deallocated: MemMgmt: 0x%lu, Object: 0x%lu"
, (Ptr_t)fLst
, (Ptr_t)resultObj
);
error_exit();
}
}
return resultObj;
}
// Deallocates object by adding it to the allocation structure
// - the object is NOT finalised here ... only when allocation structures are
// disposed of/recycled.
// - the object may contain info such as associated memory pointers/sizes to
// be retained for reuse e.g. bytevectors.
// - the objSize parameter provides a heuristic check that the right kind of
// object is being returned into the correct memory pool.
void deallocateObject_MM(MemMgr_t *fLst, size_t objSize, void *obj) {
if (obj == NULL) return;
req_NonNull(fLst);
req_EQ(objSize, fLst->blockSize); // heuristic integrity check that sizes are correct (not perfect)
// check that object is *not* already deallocated ...
if (checkDeallocation_MM) {
if (checkIfRecycled_MM(fLst, obj)) {
diagnostic("deallocateObject_MM: Attempted double deallocation of object: MemMgmt: 0x%lu, Object: 0x%lu"
, (Ptr_t)fLst
, (Ptr_t)obj
);
error_exit();
}
}
Pair_t *freePairs = fLst->freeList;
Pair_t *topPair = NULL;
// ensure topPair exists ...
if (oldPairsList != NULL) {
// found existing pair
// take top pair from oldPairsList
topPair = oldPairsList;
// make old pairs the next cell of top cell
oldPairsList = topPair->nextItem;
}
else {
// allocate fresh cell to top cell
topPair = ALLOC_OBJ(Pair_t);
}
// Bind obj to topPair
topPair->object = obj;
// make top cell link to free cells
topPair->nextItem = freePairs;
// make allocation structure point at top cell
fLst->freeList = topPair;
// increment length of allocation structure
fLst->length += 1;
}
#endif
#ifndef __ALLOC_H__
#define __ALLOC_H__
#include "utils.h"
/*******************************************************************************
alloc.h
Very basic memory management (using free-lists)
The implementation can be switched to provide a straightforward malloc/free
version (see USE_MALLOC_AND_FREE)
(c) Copyright 2017 Hewlett Packard Enterprise Development LP
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
// Uncomment the following line to use straightforward malloc/free allocation:
//#define USE_MALLOC_AND_FREE
// Allocation structure structure
typedef struct memMgr MemMgr_t;
/*******************************************************************************
Methods
*******************************************************************************/
// creates a fresh allocation structure ...
MemMgr_t *new_MM(size_t blockSize);
// sets the object initialiser
void setInitialiser_MM(MemMgr_t *fLst, VoidFn_t initFn);
// sets the object finaliser
void setFinaliser_MM(MemMgr_t *fLst, VoidFn_t finalFn);
// get size of allocation structure
int getLength_MM(MemMgr_t *fLst);
// get number of allocated objects
int getAllocated_MM(MemMgr_t *fLst);
// get blockSize i.e. the size of memory to allocate
size_t getBlockSize_MM(MemMgr_t *fLst);
// allocates an object (from allocation structure if possible)
void *allocateObject_MM(MemMgr_t *fLst);
// deallocates object
// - the objSize parameter is used to check that the object is being returned
// to the right memory pool.
void deallocateObject_MM(MemMgr_t *fLst, size_t objSize, void *obj);
// Resets an allocation manager
// - disposes of allocation structure objects if the newBlockSize is different from current blocksize.
// - finaliser is run on all allocation structures elements.
void reset_MM(MemMgr_t *fLst, size_t newBlockSize);
// recycles a allocation structure ...
void recycle_MM(MemMgr_t *fLst);
/*******************************************************************************
Checking integrity
*******************************************************************************/
// Apply check on allocation
// - This check applies to all free-lists
Boolean_t checkAllocation_MM;
// Apply check on deallocation
// - This check applies to all free-lists
Boolean_t checkDeallocation_MM;
// Check allocation/deallocation integrity
// - checks if the given object is currently recycled ...
// - this is a hard error if so ...
Boolean_t checkIfRecycled_MM(MemMgr_t *fLst, void *obj);
#endif
#ifndef __ARENA_H__
#define __ARENA_H__
#include "utils.h"
/*******************************************************************************
arena.h
Arena-based memory management
An arena is a block of memory divided into a series of fixed-size blocks.
Each block can have a reference count. Allocation is cheap.
Memory is never physically deallocated - it means that it is unreserved.
This means that the memory is available for reallocation to an owner
for some use/purpose. The use of deallocated/unallocated memory is considered
erroneous until that memory is reallocated.
The implementation can be switched to provide a straightforward malloc/free
version (see USE_MALLOC_AND_FREE_ARENA)
Author: brian.monahan@hpe.com
(c) Copyright 2017 Hewlett Packard Enterprise Development LP
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
// Uncomment the following line to use straightforward malloc/free allocation:
//#define USE_MALLOC_AND_FREE_ARENA
// Arena Memory Manager
typedef struct arenaObj ArenaMemMgr_t;
// Arena Allocation Policy
typedef enum {
REFERENCE_BLOCKS_POLICY_AMM, // blocks are objects - use reference counting.
TEMPORARY_BLOCKS_POLICY_AMM, // blocks represented temporary memory - ignore reference counting.
PERMANENT_BLOCKS_POLICY_AMM // blocks are permanent and are never recycled/deallocated - ignores reference counting.
} ArenaPolicy_t;
// Allocates a new arena with blockSize, numBlocks and policy:
// - blockSize : size of block (i.e. allocation unit)
// - numBlocks : total number of blocks to be allocated.
// - policy : allocation policy to be used by arena.
ArenaMemMgr_t *new_AMM(int blockSize, int numBlocks, ArenaPolicy_t policy);
// Deallocate the specified arena
// - This returns TRUE if deallocation was successful
// - If there are blocks still allocated, then deallocation of the arena
// will not succeed.
Boolean_t deallocateArena_AMM(ArenaMemMgr_t *arena);
// Allocates the next block of memory ...
void *allocateBlock_AMM(ArenaMemMgr_t *arena);
// Deallocates the given block of memory
// - Decrements the reference count (if this is meaningful)
void deallocateBlock_AMM(ArenaMemMgr_t *arena, void *block);
// Get the arena allocation policy for arena
ArenaPolicy_t getPolicy_AMM(ArenaMemMgr_t *arena);
// Get the size of blocks allocated by arena
int getBlockSize_AMM(ArenaMemMgr_t *arena);
// Total number of blocks for arena: total = free + allocated
int getTotalBlocks_AMM(ArenaMemMgr_t *arena);
// Number of blocks free for allocation by arena
int getFreeBlocks_AMM(ArenaMemMgr_t *arena);
// Number of allocated blocks by arena
int getAllocatedBlocks_AMM(ArenaMemMgr_t *arena);
// Increment reference to block (if possible)
// - This fails if the block was not allocated within the arena.
//
void incrRefCount_AMM(ArenaMemMgr_t *arena, void *block);
#endif
/*******************************************************************************
bytevector.c
Basic bytevectors ...
- data length is always less than memory available (capacity), unless both are zero.
The key invariant is:
(length == 0 && capacity == 0) || (0 <= length < capacity)
Bytevectors support foreign data pointers;
- foreign data is treated as immutable.
- However, data content pointer can be exported
- This enables unmanaged data access/update of content.
Bytevectors can be set to "append only"
- resetting will
Bytevectors are allocated via free-list ...
Author: brian.monahan@hpe.com
(c) Copyright 2017 Hewlett Packard Enterprise Development LP
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utils.h"
#include "alloc.h"
#include "random.h"
#include "bytevector.h"
// The bytevector structure ...
struct bytevector {
int capacity; // amount of memory available.
size_t length; // extent of data in use.
Boolean_t appendOnly; // indicates append-only.
Boolean_t isForeign; // indicates if pointer is foreign (if so, then the data is internally immutable.)
Byte_t *content; // content pointer
};
// Bytevector Memory Management
MemMgr_t *bytevecMemMgmt = NULL;
// static method prototypes
static void ensureMemMgmt();
static void dispose_BV(void *obj);
static void addContent(ByteVec_t *vec, int dataLen, Byte_t *data);
// Allocates a standard size bytevector (with default capacity)
ByteVec_t *new_BV() {
return allocate_BV(DEFAULT_BYTEVECTOR_CAPACITY);
}
// Allocates a bytevector of specified capacity
// - Setting zero capacity does not allocate any storage.
ByteVec_t *allocate_BV(int capacity) {
// ensure the allocation structure is initialised
ensureMemMgmt();
// Gets allocated result ...
ByteVec_t *result = allocateObject_MM(bytevecMemMgmt);
if (result->capacity == 0) {
// allocated object has no attached content memory ...
// - this is also the case if the object were freshly allocated and not recycled.
if (capacity == 0) {
// empty bytevector
// - no storage allocated ...
result->capacity = 0;
result->length = 0;
result->appendOnly = FALSE;
result->isForeign = FALSE;
result->content = NULL;
}
else {
// non-empty bytevector - of zero length
result->capacity = capacity;
result->length = 0;
result->appendOnly = FALSE;
result->isForeign = FALSE;
result->content = ALLOC_BLK(result->capacity); // guaranteed zero'd
}
}
else {
// allocated result has attached memory ... (i.e. recycled)
// - attached memory was scrubbed at deallocation time
ensureCapacity_BV(result, capacity);
// set attributes
result->capacity = capacity;
result->length = 0;
result->appendOnly = FALSE;
result->isForeign = FALSE;
}
return result;
}
// Deallocates bytevector
// - if the given bytevector contains foreign data, this returns the data content pointer.
// - Otherwise, returns NULL.
// - the bytevector is recycled (with attached memory already zeroed) for reuse.
Byte_t *deallocate_BV(ByteVec_t *vec) {
if (vec == NULL) {
return NULL;
}
Byte_t *result = NULL;
if (vec->isForeign) {
// export the content
result = vec->content;
// decouple foreign content from bytevector
vec->capacity = 0;
vec->content = NULL;
}
else if (vec->capacity > 0) {
// scrub the attached memory ...
NULLIFY(vec->content, vec->capacity);
}
// reset the object
vec->length = 0;
vec->appendOnly = FALSE;
vec->isForeign = FALSE;
// ensure the allocation structure is initialised
ensureMemMgmt();
// Now recycle the bytevector itself
// - by adding it to the bytevector allocation structure ...
deallocateObject_MM(bytevecMemMgmt, sizeof(ByteVec_t), (void *)vec);
return result;
}
// Resets the given bytevector to empty state (i.e. zero length)
// - does not remove non-foreign allocated memory - instead this is zeroed.
// - if bytevector contains foreign data, then the pointer is returned,
// and the state of the bytevector is reset to non-foreign.
// - resets the appendOnly attribute to FALSE
Byte_t *reset_BV(ByteVec_t *vec) {
req_NonNull(vec);
// this is used to report any foreign pointer ...
Byte_t *foreignPtr = NULL;
// sets the length to zero ...
vec->length = 0;
// always set the appendOnly attribute to false
// - if append only semantics is required, this must be set again
// following any reset.
vec->appendOnly = FALSE;
// Process foreign vectors
if (vec->isForeign) {
// return foreign content pointer
foreignPtr = vec->content;
// Now set vec to empty
vec->capacity = 0; // no capacity
vec->isForeign = FALSE; // vec is no longer foreign
vec->content = NULL; // no memory
}
else if (vec->capacity > 0) {
// fill content with zero ...
NULLIFY(vec->content, vec->capacity);
}
// return any foreign pointer
return foreignPtr;
}
// synonym for reset_BV ...
Byte_t *wipe_BV(ByteVec_t *vec) {
return reset_BV(vec);
}
int getCapacity_BV(ByteVec_t *vec) {
req_NonNull(vec);
return vec->capacity;
}
size_t getLength_BV(ByteVec_t *vec) {
req_NonNull(vec);
return vec->length;
}
void setLength_BV(ByteVec_t *vec, size_t length) {
req_NonNull(vec);
if (vec->isForeign) {
// For foreign data, assert the capacity according to given length.
vec->capacity = length +1;
}
else if (vec->appendOnly && length < vec->length) {
diagnostic("setLength_BV: Bytevector is set to append only - cannot reduce length from %i to smaller length %i"
, length
, vec->length);
error_exit();
}
else if (vec->capacity <= length) {
diagnostic("setLength_BV: new length (%i) exceeds or equals capacity (%i)", length, vec->capacity);
error_exit();
}
vec->length = length;
}
// sets the bytevector to be append only
// - once set, this attribute can only be removed by resetting the entire byte vector using reset_BV
void setAppendOnly_BV(ByteVec_t *vec) {
req_NonNull(vec);
vec->appendOnly = TRUE;
}
Boolean_t isEmpty_BV(ByteVec_t *vec) {
req_NonNull(vec);
return (vec->length == 0 || vec->content == NULL);
}
Byte_t *getContent_BV(ByteVec_t *vec) {
req_NonNull(vec);
return vec->content;
}
Boolean_t hasForeignData_BV(ByteVec_t *vec) {
req_NonNull(vec);
return vec->isForeign;
}
// Imports existing data (i.e. foreign pointer);
// - This data is regarded as fixed and unmodifiable.
// - As a consequence, bytevectors containing foreign data are not extendable and
// cannot be wiped or updated.
void importForeignContent_BV(ByteVec_t *vec, int dataLen, Byte_t *foreignData) {
req_NonNull(vec);
if (vec->isForeign) {
diagnostic("bytevector.importForeignContent_BV: Bytevector already contains foreign data - and cannot be extended.");
codeError_exit();
}
if (foreignData == NULL && dataLen > 0) {
diagnostic("bytevector.importForeignContent_BV: Inconsistent content assignment (content = NULL, but length > 0)");
codeError_exit();
}
// release any existing data
free(vec->content);
// update bytevector's attributes
vec->length = dataLen;
vec->capacity = dataLen + 1;
vec->isForeign = TRUE;
vec->content = foreignData;
}
// loads indicated content into byte vector
// - sets bytes from data array
// - uses existing data memory in bytevector where possible,
// - otherwise, extends memory to contain additional content
void setContent_BV(ByteVec_t *vec, int dataLen, Byte_t *data) {
req_NonNull(vec);
if (vec->isForeign) {
diagnostic("bytevector.setContent_BV: Bytevector contains foreign data - and cannot be extended.");
codeError_exit();
}
if (data == NULL && dataLen > 0) {
diagnostic("bytevector.setContent_BV: Inconsistent content assignment (content = NULL, but length > 0)");
codeError_exit();
}
if (vec->appendOnly) {
diagnostic("bytevector.setContent_BV: Bytevector set to append only - cannot set the content arbitrarily.");
codeError_exit();
}
// reset te bytevector ...
// - ensures that previous data gets zero'ed.
reset_BV(vec);
// now add the content ...
addContent(vec, dataLen, data);
}
// appends indicated content into byte vector
// - appends bytes from data array to end of bytevector
// - uses existing data memory in bytevector where possible,
// - otherwise, extends memory to contain additional content
void appendContent_BV(ByteVec_t *vec, int dataLen, Byte_t *data) {
req_NonNull(vec);
if (vec->isForeign) {
diagnostic("bytevector.appendContent_BV: Bytevector contains foreign data - and cannot be extended.");
codeError_exit();
}
if (data == NULL && dataLen > 0) {
diagnostic("bytevector.appendContent_BV: Inconsistent content assignment (content = NULL, but length > 0)");
codeError_exit();
}
// now add the content ...
addContent(vec, dataLen, data);
}
// Internal operation to add data
static void addContent(ByteVec_t *vec, int dataLen, Byte_t *data) {
int vecDataLen = vec->length; // current data length
int newDataLen = vecDataLen + dataLen; // updated data length
if (newDataLen >= vec->capacity) {
ensureCapacity_BV(vec, newDataLen+1); // guarantees that newDataLen < new capacity of vec
}
// copy any new data into vector
if (dataLen > 0) {
memcpy(vec->content + vecDataLen, data, dataLen);
}
// record new data length.
vec->length = newDataLen;
// ensures that sentinel byte is 0 (i.e. safe for C-strings)
vec->content[newDataLen] = 0;
}
void ensureCapacity_BV(ByteVec_t *vec, int capacity) {
req_NonNull(vec);
req_PosZero(capacity);
// return if capacity requested is zero ...
if (capacity == 0) return;
if (vec->isForeign) {
diagnostic("bytevector.ensureCapacity_BV: Bytevector contains foreign data - and cannot be extended.");
codeError_exit();
}
int vecCapacity = vec->capacity;
Byte_t *vecContent = vec->content;
size_t vecLength = vec->length;
// check if extra capacity needed ...
if (capacity <= vecCapacity) {
return;
}
// needs some extra memory ...
int newCapacity = capacity + vecCapacity;
Byte_t *newContent = (Byte_t *)ALLOC_BLK(newCapacity);
//Byte_t *newContent = (Byte_t *)REALLOC_BLK(vecContent, newCapacity); // using this caused data corruption to vec->length (!!)
if (vecLength > 0) {
// copying previous content into new memory ...
memcpy(newContent, vecContent, vecLength);
}
// update vec ...
vec->capacity = newCapacity;
vec->content = newContent;
vec->length = vecLength;
// free previous memory
free(vecContent);
}
// Clones source bytevector into given destination vector.
// - copies content from source to destination
// - both vectors must already exist.
// - destination must not already contain foreign data.
void clone_BV(ByteVec_t *dest, ByteVec_t *source) {
req_NonNull(dest);
req_NonNull(source);
if (dest->isForeign) {
diagnostic("bytevector.clone_BV: Destination bytevector contains foreign data - and cannot be modified/extended.");
codeError_exit();
}
int dataLen = source->length;
// ensure sufficient capacity to contain the data in the source.
ensureCapacity_BV(dest, dataLen+1);
if (dataLen > 0) {
// copy source data into the destination ...
memcpy(dest->content, source->content, dataLen);
}
// update the length of the destination ...
dest->length = dataLen;
}
// Checks that the bytevectors are equal in _value_ (on content) ...
// - Both must be equally defined i.e. both = NULL or both != NULL
// - byte comparison of content up to length
Boolean_t isEqual_BV(ByteVec_t *vec1, ByteVec_t *vec2) {
if (vec1 == NULL) {
return (vec2 == NULL);
}
else if (vec2 == NULL) {
// i.e. vec1 != NULL and vec2 == NULL
return FALSE;
}
// Know here that: vec1 != NULL and vec2 != NULL
// check length of content
int vecLen1 = vec1->length;
int vecLen2 = vec2->length;
if (vecLen1 != vecLen2) {
// vec1 and vec2 have different lengths
return FALSE;
}
// compare memory
return asBoolean(memcmp(vec1->content, vec2->content, vecLen1) == 0);
}
// Generate a randomised bytevector of specified length
void random_BV(ByteVec_t *vec, int dataLen) {
req_NonNull(vec);
req_PosZero(dataLen);
// check for foreign data
if (vec->isForeign) {
diagnostic("bytevector.random_BV: Destination bytevector contains foreign data - and cannot be modified.");
codeError_exit();
}
// ensure the capacity ...
ensureCapacity_BV(vec, dataLen+1);
Byte_t *arr = vec->content;
for (int i = 0; i < dataLen; i++) {
arr[i] = nextRandom_BYTE();
}
// set the length
vec->length = dataLen;
}
Byte_t getByte_BV(ByteVec_t *vec, int i) {
req_NonNull(vec);
req_NonNull(vec->content);
req_LE(0, i);
req_LT(i, vec->length);
return (vec->content)[i];
}
void setByte_BV(ByteVec_t *vec, int idx, Byte_t newVal) {
req_NonNull(vec);
req_LE(0, idx);
if (vec->isForeign) {
diagnostic("bytevector.setByte_BV: Bytevector contains foreign data - and cannot be modified.");
codeError_exit();
}
if (vec->appendOnly) {
diagnostic("bytevector.setByte_BV: Bytevector set to append only - no arbitrart modification.");
codeError_exit();
}
// check if update requires memory expansion.
if (vec->length <= idx) {
int newLength = idx+1;
int newCapacity = newLength+1;
ensureCapacity_BV(vec, newCapacity); // expand memory to include index ...
vec->length = newLength; // make length = one greater than index
}
// sets content at index to newVal
(vec->content)[idx] = newVal;
}
// Joins two bytevectors together as a new, freshly allocated bytevector.
ByteVec_t *join_BV(ByteVec_t *a, ByteVec_t *b) {
req_NonNull(a);
req_NonNull(b);
int aDataLen = a->length;
int bDataLen = b->length;
int newDataLen = aDataLen + bDataLen;
int newCapacity = newDataLen + 1;
ByteVec_t *result = allocate_BV(newCapacity);
Byte_t *data = result->content;
// copy the data ...
if (aDataLen > 0) {
memcpy(data, a->content, aDataLen);
}
if (bDataLen > 0) {
memcpy(data+aDataLen, b->content, bDataLen);
}
// update the length of the result ...
result->length = newDataLen;
return result;
}
void joinInto_BV(ByteVec_t *dest, ByteVec_t *a, ByteVec_t *b) {
req_NonNull(a);
req_NonNull(b);
req_Distinct(a, dest);
req_Distinct(b, dest);
req_NonNull(dest);
// clear the existing content in dest
wipe_BV(dest);
appendContent_BV(dest, a->length, a->content);
appendContent_BV(dest, b->length, b->content);
}
void appendInto_BV(ByteVec_t *dest, ByteVec_t *source) {
req_NonNull(source);
req_NonNull(dest);
req_Distinct(source, dest);
if (dest->isForeign) {
diagnostic("bytevector.appendInto_BV: Destination bytevector contains foreign data - and cannot be modified.");
codeError_exit();
}
appendContent_BV(dest, source->length, source->content);
}
/*******************************************************************************
Fingerprinting
*******************************************************************************/
// Extracts a short fingerprint of the bytevector
// - the output string is volatile
// - 4 <= fpLength <= 16, with default value: 7
static char fpBuf[LINE_BUFSIZE+1];
static int DEFAULT_FP_LENGTH = 7;
char *showFingerprint_BV(ByteVec_t *vec, int fpLength) {
if (vec == NULL) return NULL_STR;
char *sPtr = fpBuf;
Byte_t *bytes = vec->content;
if (bytes == NULL) return NULL_STR;
// constrain the fpLength
fpLength = (fpLength <= 0 ? DEFAULT_FP_LENGTH : fpLength);
fpLength = minmax(4, fpLength, 16);
fpLength = min(fpLength, vec->length);
// pack content as hex into hashBuffer
int sz = 0;
char *sep = "";
for(int i = 0; i < fpLength; i++) {
sz = sprintf(sPtr, "%s%02x", sep, bytes[i]);
sPtr += sz;
sep = ":";
}
sprintf(sPtr, " ... [%lu bytes]", vec->length);
return fpBuf;
}
/*******************************************************************************
Show methods
*******************************************************************************/
static ByteVec_t *showBuffer = NULL;
// local prototypes
static char *auxShow_BV(ByteVec_t *vec, const char *fmt, int width, char *indent);
// Show bytevector
// - uses decimal repn.
char *show_BV(ByteVec_t *vec, int width, char *indent) {
return auxShow_BV(vec, "%3i ", width, indent);
}
// Show bytevector
// - uses hex repn.
char *showHex_BV(ByteVec_t *vec, int width, char *indent) {
return auxShow_BV(vec, "%02x ", width, indent);
}
static char *auxShow_BV(ByteVec_t *vec, const char *fmt, int width, char *indent) {
req_NonNull(vec);
req_NonEmptyStr((char *)fmt);
// ensure that indent is a string ...
indent = (isa_Null(indent) ? " " : indent);
// ensure that width is at least 5 items wide
width = max(width, 5);
// current byte
Byte_t curByte = 0;
// lengths
int indentLen = strlen(indent);
int vecLen = vec->length;
// display characteristics
int linecount = 0;
int widthcount = 0;
// local string buffer
char strBuf[17]; // fmt must define strings that are less than 16 chars in width
int bufSz = 0; // number of chars in strBuf
// initialise showBuffer
if (showBuffer == NULL) {
int allocation = max(DEFAULT_BYTEVECTOR_CAPACITY, 10 * (vec->length));
showBuffer = allocate_BV(allocation);
}
else {
reset_BV(showBuffer);
}
// add content to showBuffer
// - this will automatically extend as needed ...
for (int i=0; i < vecLen; i++) {
if (widthcount == 0) {
appendContent_BV(showBuffer, indentLen, (Byte_t *)indent);
}
curByte = getByte_BV(vec, i);
bufSz = sprintf(strBuf, fmt, curByte);
// add content to showBuffer
appendContent_BV(showBuffer, bufSz, (Byte_t *)strBuf);
widthcount += 1;
if (widthcount >= width) {
widthcount = 0;
linecount += 1;
appendContent_BV(showBuffer, 1, (Byte_t *)"\n");
if (linecount >= 10) {
appendContent_BV(showBuffer, 1, (Byte_t *)"\n");
}
}
}
if (widthcount != 0) {
// add a newline to terminate current line
appendContent_BV(showBuffer, 1, (Byte_t *)"\n");
}
return (char *)showBuffer->content;
}
/*******************************************************************************
Static Methods
*******************************************************************************/
// Initialisation of allocation structure
static void ensureMemMgmt() {
if (bytevecMemMgmt == NULL) {
bytevecMemMgmt = new_MM(sizeof(ByteVec_t));
setFinaliser_MM(bytevecMemMgmt, dispose_BV);
}
}
// Disposal of bytevector object ...
static void dispose_BV(void *obj) {
if (obj == NULL) return;
ByteVec_t *vec = (ByteVec_t *)obj;
// First free the content ...
free(vec->content);
// Now free the bytevector structure itself ...
free(vec);
}
#ifndef __BYTEVECTOR_H__
#define __BYTEVECTOR_H__
#include "utils.h"
/*******************************************************************************
bytevector.h
Basic bytevectors ...
Author: brian.monahan@hpe.com
(c) Copyright 2017 Hewlett Packard Enterprise Development LP
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
typedef struct bytevector ByteVec_t;
#define DEFAULT_BYTEVECTOR_CAPACITY 16
// Allocates a standard size bytevector (with default capacity)
// - uses the default bytevector capacity as initial capacity
// - use ensureCapacity_BV to explicitly extend bytevector capacity.
ByteVec_t *new_BV();
// Allocates a bytevector of specified capacity
// - Setting zero capacity does not allocate any storage.
ByteVec_t *allocate_BV(int capacity);
// Deallocates bytevector
// - if the given bytevector contains foreign data, this returns the data pointer.
// - Otherwise, returns NULL.
// - the bytevector is recycled (with attached zeroed memory) into a allocation structure.
Byte_t *deallocate_BV(ByteVec_t *vec);
// Resets the given bytevector to empty state (i.e. zero length)
// - does not remove non-foreign allocated memory - instead this is zeroed.
// - if bytevector contains foreign data, then the pointer is returned,
// and the state of the bytevector is reset to non-foreign.
// - resets the appendOnly attribute to FALSE
Byte_t *reset_BV(ByteVec_t *vec);
Byte_t *wipe_BV(ByteVec_t *vec); // synonym for reset_BV
// gets the memory size allocated
int getCapacity_BV(ByteVec_t *vec);
// gets the data length (always less than the memory size)
size_t getLength_BV(ByteVec_t *vec);
// sets the data length
// - must remain strictly less than the capacity.
// - if bytevector is set append only, then length cannot be decreased.
void setLength_BV(ByteVec_t *vec, size_t length);
// sets the bytevector to be append only
// - once set, this attribute can only be removed by resetting the entire byte vector
void setAppendOnly_BV(ByteVec_t *vec);
// ensures that memory capacity equals or exceeds the given value.
// - if current capacity already equals or exceeds given value then no change.
// - extension involves reallocating memory.
void ensureCapacity_BV(ByteVec_t *vec, int capacity);
// indicates if given bytevector is "empty" ...
// - i.e. doesn't contain data.
Boolean_t isEmpty_BV(ByteVec_t *vec);
// exports pointer to internal data vector
// - this permits the memory to be manipulated externally (UNSAFE).
// - the external pointer returned can become stale due to further
// extension of the bytevector.
// - use setLength to update the length ...
Byte_t *getContent_BV(ByteVec_t *vec);
// Clones source bytevector into given destination vector.
// - copies content from source to destination
// - both vectors must already exist.
// - destination must not already contain foreign data.
void clone_BV(ByteVec_t *dest, ByteVec_t *source);
// Checks that the bytevectors are equal in _value_ (on content) ...
// - Both must be equally defined i.e. both = NULL or both != NULL
// - byte comparison of content up to length
Boolean_t isEqual_BV(ByteVec_t *vec1, ByteVec_t *vec2);
// indicates if givne bytevector contains foreign data.
// - The bytevector cannot be modified or changed once it contains foreign data.
Boolean_t hasForeignData_BV(ByteVec_t *vec);
// Imports existing data (i.e. foreign pointer);
// - This data is regarded as fixed and unmodifiable.
// - As a consequence, bytevectors containing foreign data are not extendable and
// cannot be wiped or updated.
void importForeignContent_BV(ByteVec_t *vec, int dataLen, Byte_t *data);
// loads indicated content into byte vector
// - sets bytes from data array
// - uses existing data memory in bytevector where possible,
// - otherwise, extends memory to contain additional content
void setContent_BV(ByteVec_t *vec, int dataLen, Byte_t *data);
// appends indicated content into byte vector
// - appends bytes from data array to end of bytevector
// - uses existing data memory in bytevector where possible,
// - otherwise, extends memory to contain additional content
void appendContent_BV(ByteVec_t *vec, int dataLen, Byte_t *data);
// Generate a randomised bytevector of specified length
void random_BV(ByteVec_t *vec, int dataLen);
// gets current value at given index idx
// - idx always less than current data length
Byte_t getByte_BV(ByteVec_t *vec, int idx);
// sets current value at given index idx
// - setting values can force memory extension.
void setByte_BV(ByteVec_t *vec, int idx, Byte_t newVal);
// Joins two bytevectors together as a new, freshly allocated bytevector.
ByteVec_t *join_BV(ByteVec_t *a, ByteVec_t *b);
// Joins content from two bytevectors a and b into dest bytevector
// - Uses the already allocated memory in dest.
// - Will enlarge allocated memory of dest to ensure sufficient memory ...
// - Dest bytevector must be distinct from given sources
void joinInto_BV(ByteVec_t *dest, ByteVec_t *a, ByteVec_t *b);
// Appends content from source bytevector into dest bytevector
// - Uses already allocated memory in dest
// - Will enlarge allocated memory of dest to ensure sufficient memory ...
void appendInto_BV(ByteVec_t *dest, ByteVec_t *source);
// Shows a short hex fingerprint of the bytevector
// - the output string is volatile
// - 4 <= fpLength <= 16, with default value: 7
char *showFingerprint_BV(ByteVec_t *vec, int fpLength);
// Show bytevector content
// - uses decimal repn.
char *show_BV(ByteVec_t *vec, int width, char *indent);
// Show bytevector content
// - uses hex repn.
char *showHex_BV(ByteVec_t *vec, int width, char *indent);
#endif
#ifndef __DEBUG_H__
#define __DEBUG_H__
/*******************************************************************************
debug.h
Debugging using print statements/testing...
Including this file enables debugging ...
Author: brian.monahan@hpe.com
(c) Copyright 2017 Hewlett Packard Enterprise Development LP
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#undef debug
#undef xdebug
#undef DEBUG_CODE
#undef XDEBUG_CODE
#define debug __DEBUG
#define xdebug __XDEBUG
#define DEBUG_CODE
#ifndef DEBUG_LIMIT
#define DEBUG_LIMIT 1000
#endif
#endif
/*******************************************************************************
exptLib.c
Experimental management framework utilities
- Managing key identifiers (numbers)
- Managing values
Author: brian.monahan@hpe.com
(c) Copyright 2017 Hewlett Packard Enterprise Development LP
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include "exptLib.h"
#include "random.h"
/*******************************************************************************
Variables and Arrays
*******************************************************************************/
static Boolean_t seenKey[MAX_KEY_VALUE]; // 0 .. MAX_KEY_VALUE - with valid keys being 1 .. MAX_KEY_VALUE
static Key_t keyIndex[MAX_KEYS];
// Invariant: availKeys + numKeys == MAX_KEYS
static int availKeys = MAX_KEYS; // 1 .. MAX_KEYS -- number of available keys
static int numKeys = 0; // number of keys in use
// object map
static void *objIndex[MAX_KEY_VALUE]; // Object mapping
/*******************************************************************************
Methods
*******************************************************************************/
// generate new key
Key_t freshKey() {
if (availKeys <= 0) return NULL_KEY;
int possKey = nextRandom_Range(1, MAX_KEY_VALUE);
int key = 0;
// scan keys to find the next available
for (int i=1; i <= MAX_KEY_VALUE; i++) {
if (!seenKey[possKey]) {
key = possKey;
registerKey(key);
return key;
}
// increment possKey
possKey += 1;
if (possKey > MAX_KEY_VALUE) possKey = 1;
}
return NULL_KEY;
}
// gets a randomly selected registered key - and then unregistering it from the key index
Key_t getKey() {
if (numKeys <= 0) return NULL_KEY;
int index = nextRandom_Range(0, numKeys-1);
Key_t key = keyIndex[index];
seenKey[key] = FALSE;
if (numKeys > 0) {
numKeys -= 1;
availKeys += 1;
keyIndex[index] = keyIndex[numKeys];
keyIndex[numKeys] = NULL_KEY;
}
else {
numKeys = 0;
availKeys = MAX_KEYS;
}
return key;
}
// Add value to the store
void addValue(Key_t key, void *value) {
if (key < 1 || key > MAX_KEY_VALUE) return;
objIndex[key] = value;
}
// checks if key currently allocated/in use
Boolean_t allocatedKey(Key_t key) {
if (key < 1 || key > MAX_KEY_VALUE) return FALSE;
return seenKey[key];
}
// Fetch associated value ...
void *fetchValue(Key_t key) {
if (key < 1 || key > MAX_KEY_VALUE) return NULL;
return objIndex[key];
}
// Registers a key as being in use ...
// - return TRUE if registration was OK.
Boolean_t registerKey(Key_t key) {
if (availKeys <= 0) return FALSE;
if (key < 1 || key > MAX_KEY_VALUE) return FALSE;
if (seenKey[key]) return FALSE;
// selecting key
seenKey[key] = TRUE;
keyIndex[numKeys] = key;
availKeys -= 1;
numKeys += 1;
return TRUE;
}
// Unregisters a key as being in use ...
// - return TRUE if deregistration was OK.
Boolean_t unregisterKey(Key_t key) {
if (numKeys < 1) return FALSE;
if (key < 1 || key > MAX_KEY_VALUE) return FALSE;
if (!seenKey[key]) return FALSE;
// deselecting key
availKeys += 1; // increase number of keys
numKeys -= 1; // decrease the number of used keys
Key_t lastKey = keyIndex[numKeys];
// mark key as not seen
seenKey[key] = FALSE;
// locate index for key ...
int index = 0;
while (keyIndex[index] != key) {
index += 1;
if (index >= MAX_KEYS) return TRUE;
}
keyIndex[index] = lastKey;
keyIndex[numKeys] = NULL_KEY;
return TRUE;
}
int getKeysInUse() {
return numKeys;
}
#ifndef __EXPT_LIB_H__
#define __EXPT_LIB_H__
#include "utils.h"
/*******************************************************************************
exptLib.h
Experimental framework
- Managing key identifiers (as numbers)
Author: brian.monahan@hpe.com
(c) Copyright 2017 Hewlett Packard Enterprise Development LP
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#define MAX_KEYS 10000
#define MAX_KEY_VALUE 100000
/*******************************************************************************
Key Management Methods
*******************************************************************************/
// Generate a fresh randomly generated key
Key_t freshKey();
// Add value to the store
void addValue(Key_t key, void *value);
// Checks if key currently allocated/in use
Boolean_t allocatedKey(Key_t key);
// Gets a randomly selected registered key - and then unregisters it from the key index
Key_t getKey();
// Fetch associated value ...
void *fetchValue(Key_t key);
// Registers a key as being in use ...
// - return TRUE if registration was OK.
Boolean_t registerKey(Key_t key);
// Unregisters a key as being in use ...
// - return TRUE if deregistration was OK.
Boolean_t unregisterKey(Key_t key);
// Number of keys in use
int getKeysInUse();
#endif