diff --git a/Project1.sln b/Project1.sln
new file mode 100644
index 0000000..9de543f
--- /dev/null
+++ b/Project1.sln
@@ -0,0 +1,28 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 14
+VisualStudioVersion = 14.0.25420.1
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Project1", "Project1\Project1.vcxproj", "{B0858739-6A62-4C9B-A8BC-C87DAFEF415D}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|x64 = Debug|x64
+ Debug|x86 = Debug|x86
+ Release|x64 = Release|x64
+ Release|x86 = Release|x86
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {B0858739-6A62-4C9B-A8BC-C87DAFEF415D}.Debug|x64.ActiveCfg = Debug|x64
+ {B0858739-6A62-4C9B-A8BC-C87DAFEF415D}.Debug|x64.Build.0 = Debug|x64
+ {B0858739-6A62-4C9B-A8BC-C87DAFEF415D}.Debug|x86.ActiveCfg = Debug|Win32
+ {B0858739-6A62-4C9B-A8BC-C87DAFEF415D}.Debug|x86.Build.0 = Debug|Win32
+ {B0858739-6A62-4C9B-A8BC-C87DAFEF415D}.Release|x64.ActiveCfg = Release|x64
+ {B0858739-6A62-4C9B-A8BC-C87DAFEF415D}.Release|x64.Build.0 = Release|x64
+ {B0858739-6A62-4C9B-A8BC-C87DAFEF415D}.Release|x86.ActiveCfg = Release|Win32
+ {B0858739-6A62-4C9B-A8BC-C87DAFEF415D}.Release|x86.Build.0 = Release|Win32
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/Project1/Project1.vcxproj b/Project1/Project1.vcxproj
new file mode 100644
index 0000000..b39806d
--- /dev/null
+++ b/Project1/Project1.vcxproj
@@ -0,0 +1,147 @@
+
+
+
+
+ Debug
+ Win32
+
+
+ Release
+ Win32
+
+
+ Debug
+ x64
+
+
+ Release
+ x64
+
+
+
+ {B0858739-6A62-4C9B-A8BC-C87DAFEF415D}
+ Project1
+ 8.1
+
+
+
+ Application
+ true
+ v140
+ MultiByte
+
+
+ Application
+ false
+ v140
+ true
+ MultiByte
+
+
+ Application
+ true
+ v140
+ MultiByte
+
+
+ Application
+ false
+ v140
+ true
+ MultiByte
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Level3
+ Disabled
+ true
+
+
+
+
+ Level3
+ Disabled
+ false
+ _CRT_SECURE_NO_WARNINGS;GENKAT;%(PreprocessorDefinitions)
+
+
+
+
+ Level3
+ MaxSpeed
+ true
+ true
+ true
+
+
+ true
+ true
+
+
+
+
+ Level3
+ MaxSpeed
+ true
+ true
+ true
+
+
+ true
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Project1/Project1.vcxproj.filters b/Project1/Project1.vcxproj.filters
new file mode 100644
index 0000000..9b092f4
--- /dev/null
+++ b/Project1/Project1.vcxproj.filters
@@ -0,0 +1,102 @@
+
+
+
+
+ {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
+ cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
+
+
+ {93995380-89BD-4b04-88EB-625FBE52EBFB}
+ h;hh;hpp;hxx;hm;inl;inc;xsd
+
+
+ {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
+ rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms
+
+
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+ Source Files
+
+
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+ Resource Files
+
+
+
\ No newline at end of file
diff --git a/Project1/amount.h b/Project1/amount.h
new file mode 100644
index 0000000..d5b276a
--- /dev/null
+++ b/Project1/amount.h
@@ -0,0 +1,72 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2009-2015 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_AMOUNT_H
+#define BITCOIN_AMOUNT_H
+
+#include "serialize.h"
+
+#include
+#include
+
+/** Amount in satoshis (Can be negative) */
+typedef int64_t CAmount;
+
+static const CAmount COIN = 100000000;
+static const CAmount CENT = 1000000;
+
+extern const std::string CURRENCY_UNIT;
+
+/** No amount larger than this (in satoshi) is valid.
+*
+* Note that this constant is *not* the total money supply, which in Bitcoin
+* currently happens to be less than 21,000,000 BTC for various reasons, but
+* rather a sanity check. As this sanity check is used by consensus-critical
+* validation code, the exact value of the MAX_MONEY constant is consensus
+* critical; in unusual circumstances like a(nother) overflow bug that allowed
+* for the creation of coins out of thin air modification could lead to a fork.
+* */
+static const CAmount MAX_MONEY = 21000000 * COIN;
+inline bool MoneyRange(const CAmount& nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
+
+/**
+* Fee rate in satoshis per kilobyte: CAmount / kB
+*/
+class CFeeRate
+{
+private:
+ CAmount nSatoshisPerK; // unit is satoshis-per-1,000-bytes
+public:
+ /** Fee rate of 0 satoshis per kB */
+ CFeeRate() : nSatoshisPerK(0) { }
+ explicit CFeeRate(const CAmount& _nSatoshisPerK) : nSatoshisPerK(_nSatoshisPerK) { }
+ /** Constructor for a fee rate in satoshis per kB. The size in bytes must not exceed (2^63 - 1)*/
+ CFeeRate(const CAmount& nFeePaid, size_t nBytes);
+ CFeeRate(const CFeeRate& other) { nSatoshisPerK = other.nSatoshisPerK; }
+ /**
+ * Return the fee in satoshis for the given size in bytes.
+ */
+ CAmount GetFee(size_t nBytes) const;
+ /**
+ * Return the fee in satoshis for a size of 1000 bytes
+ */
+ CAmount GetFeePerK() const { return GetFee(1000); }
+ friend bool operator<(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK < b.nSatoshisPerK; }
+ friend bool operator>(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK > b.nSatoshisPerK; }
+ friend bool operator==(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK == b.nSatoshisPerK; }
+ friend bool operator<=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK <= b.nSatoshisPerK; }
+ friend bool operator>=(const CFeeRate& a, const CFeeRate& b) { return a.nSatoshisPerK >= b.nSatoshisPerK; }
+ CFeeRate& operator+=(const CFeeRate& a) { nSatoshisPerK += a.nSatoshisPerK; return *this; }
+ std::string ToString() const;
+
+ ADD_SERIALIZE_METHODS;
+
+ template
+ inline void SerializationOp(Stream& s, Operation ser_action) {
+ READWRITE(nSatoshisPerK);
+ }
+};
+
+#endif // BITCOIN_AMOUNT_H
\ No newline at end of file
diff --git a/Project1/argon2.h b/Project1/argon2.h
new file mode 100644
index 0000000..364a3e6
--- /dev/null
+++ b/Project1/argon2.h
@@ -0,0 +1,435 @@
+/*
+* Argon2 reference source code package - reference C implementations
+*
+* Copyright 2015
+* Daniel Dinu, Dmitry Khovratovich, Jean-Philippe Aumasson, and Samuel Neves
+*
+* You may use this work under the terms of a Creative Commons CC0 1.0
+* License/Waiver or the Apache Public License 2.0, at your option. The terms of
+* these licenses can be found at:
+*
+* - CC0 1.0 Universal : http://creativecommons.org/publicdomain/zero/1.0
+* - Apache 2.0 : http://www.apache.org/licenses/LICENSE-2.0
+*
+* You should have received a copy of both of these licenses along with this
+* software. If not, they may be obtained at the above URLs.
+*/
+
+#ifndef ARGON2_H
+#define ARGON2_H
+
+#include
+#include
+#include
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+ /* Symbols visibility control */
+#ifdef A2_VISCTL
+#define ARGON2_PUBLIC __attribute__((visibility("default")))
+#elif _MSC_VER
+#define ARGON2_PUBLIC __declspec(dllexport)
+#else
+#define ARGON2_PUBLIC
+#endif
+
+ /*
+ * Argon2 input parameter restrictions
+ */
+
+ /* Minimum and maximum number of lanes (degree of parallelism) */
+#define ARGON2_MIN_LANES UINT32_C(1)
+#define ARGON2_MAX_LANES UINT32_C(0xFFFFFF)
+
+ /* Minimum and maximum number of threads */
+#define ARGON2_MIN_THREADS UINT32_C(1)
+#define ARGON2_MAX_THREADS UINT32_C(0xFFFFFF)
+
+ /* Number of synchronization points between lanes per pass */
+#define ARGON2_SYNC_POINTS UINT32_C(4)
+
+ /* Minimum and maximum digest size in bytes */
+#define ARGON2_MIN_OUTLEN UINT32_C(4)
+#define ARGON2_MAX_OUTLEN UINT32_C(0xFFFFFFFF)
+
+ /* Minimum and maximum number of memory blocks (each of BLOCK_SIZE bytes) */
+#define ARGON2_MIN_MEMORY (2 * ARGON2_SYNC_POINTS) /* 2 blocks per slice */
+
+#define ARGON2_MIN(a, b) ((a) < (b) ? (a) : (b))
+ /* Max memory size is addressing-space/2, topping at 2^32 blocks (4 TB) */
+#define ARGON2_MAX_MEMORY_BITS \
+ ARGON2_MIN(UINT32_C(32), (sizeof(void *) * CHAR_BIT - 10 - 1))
+#define ARGON2_MAX_MEMORY \
+ ARGON2_MIN(UINT32_C(0xFFFFFFFF), UINT64_C(1) << ARGON2_MAX_MEMORY_BITS)
+
+ /* Minimum and maximum number of passes */
+#define ARGON2_MIN_TIME UINT32_C(1)
+#define ARGON2_MAX_TIME UINT32_C(0xFFFFFFFF)
+
+ /* Minimum and maximum password length in bytes */
+#define ARGON2_MIN_PWD_LENGTH UINT32_C(0)
+#define ARGON2_MAX_PWD_LENGTH UINT32_C(0xFFFFFFFF)
+
+ /* Minimum and maximum associated data length in bytes */
+#define ARGON2_MIN_AD_LENGTH UINT32_C(0)
+#define ARGON2_MAX_AD_LENGTH UINT32_C(0xFFFFFFFF)
+
+ /* Minimum and maximum salt length in bytes */
+#define ARGON2_MIN_SALT_LENGTH UINT32_C(8)
+#define ARGON2_MAX_SALT_LENGTH UINT32_C(0xFFFFFFFF)
+
+ /* Minimum and maximum key length in bytes */
+#define ARGON2_MIN_SECRET UINT32_C(0)
+#define ARGON2_MAX_SECRET UINT32_C(0xFFFFFFFF)
+
+ /* Flags to determine which fields are securely wiped (default = no wipe). */
+#define ARGON2_DEFAULT_FLAGS UINT32_C(0)
+#define ARGON2_FLAG_CLEAR_PASSWORD (UINT32_C(1) << 0)
+#define ARGON2_FLAG_CLEAR_SECRET (UINT32_C(1) << 1)
+
+ /* Global flag to determine if we are wiping internal memory buffers. This flag
+ * is defined in core.c and deafults to 1 (wipe internal memory). */
+ extern int FLAG_clear_internal_memory;
+
+ /* Error codes */
+ typedef enum Argon2_ErrorCodes {
+ ARGON2_OK = 0,
+
+ ARGON2_OUTPUT_PTR_NULL = -1,
+
+ ARGON2_OUTPUT_TOO_SHORT = -2,
+ ARGON2_OUTPUT_TOO_LONG = -3,
+
+ ARGON2_PWD_TOO_SHORT = -4,
+ ARGON2_PWD_TOO_LONG = -5,
+
+ ARGON2_SALT_TOO_SHORT = -6,
+ ARGON2_SALT_TOO_LONG = -7,
+
+ ARGON2_AD_TOO_SHORT = -8,
+ ARGON2_AD_TOO_LONG = -9,
+
+ ARGON2_SECRET_TOO_SHORT = -10,
+ ARGON2_SECRET_TOO_LONG = -11,
+
+ ARGON2_TIME_TOO_SMALL = -12,
+ ARGON2_TIME_TOO_LARGE = -13,
+
+ ARGON2_MEMORY_TOO_LITTLE = -14,
+ ARGON2_MEMORY_TOO_MUCH = -15,
+
+ ARGON2_LANES_TOO_FEW = -16,
+ ARGON2_LANES_TOO_MANY = -17,
+
+ ARGON2_PWD_PTR_MISMATCH = -18, /* NULL ptr with non-zero length */
+ ARGON2_SALT_PTR_MISMATCH = -19, /* NULL ptr with non-zero length */
+ ARGON2_SECRET_PTR_MISMATCH = -20, /* NULL ptr with non-zero length */
+ ARGON2_AD_PTR_MISMATCH = -21, /* NULL ptr with non-zero length */
+
+ ARGON2_MEMORY_ALLOCATION_ERROR = -22,
+
+ ARGON2_FREE_MEMORY_CBK_NULL = -23,
+ ARGON2_ALLOCATE_MEMORY_CBK_NULL = -24,
+
+ ARGON2_INCORRECT_PARAMETER = -25,
+ ARGON2_INCORRECT_TYPE = -26,
+
+ ARGON2_OUT_PTR_MISMATCH = -27,
+
+ ARGON2_THREADS_TOO_FEW = -28,
+ ARGON2_THREADS_TOO_MANY = -29,
+
+ ARGON2_MISSING_ARGS = -30,
+
+ ARGON2_ENCODING_FAIL = -31,
+
+ ARGON2_DECODING_FAIL = -32,
+
+ ARGON2_THREAD_FAIL = -33,
+
+ ARGON2_DECODING_LENGTH_FAIL = -34,
+
+ ARGON2_VERIFY_MISMATCH = -35
+ } argon2_error_codes;
+
+ /* Memory allocator types --- for external allocation */
+ typedef int(*allocate_fptr)(uint8_t **memory, size_t bytes_to_allocate);
+ typedef void(*deallocate_fptr)(uint8_t *memory, size_t bytes_to_allocate);
+
+ /* Argon2 external data structures */
+
+ /*
+ *****
+ * Context: structure to hold Argon2 inputs:
+ * output array and its length,
+ * password and its length,
+ * salt and its length,
+ * secret and its length,
+ * associated data and its length,
+ * number of passes, amount of used memory (in KBytes, can be rounded up a bit)
+ * number of parallel threads that will be run.
+ * All the parameters above affect the output hash value.
+ * Additionally, two function pointers can be provided to allocate and
+ * deallocate the memory (if NULL, memory will be allocated internally).
+ * Also, three flags indicate whether to erase password, secret as soon as they
+ * are pre-hashed (and thus not needed anymore), and the entire memory
+ *****
+ * Simplest situation: you have output array out[8], password is stored in
+ * pwd[32], salt is stored in salt[16], you do not have keys nor associated
+ * data. You need to spend 1 GB of RAM and you run 5 passes of Argon2d with
+ * 4 parallel lanes.
+ * You want to erase the password, but you're OK with last pass not being
+ * erased. You want to use the default memory allocator.
+ * Then you initialize:
+ Argon2_Context(out,8,pwd,32,salt,16,NULL,0,NULL,0,5,1<<20,4,4,NULL,NULL,true,false,false,false)
+ */
+ typedef struct Argon2_Context {
+ uint8_t *out; /* output array */
+ uint32_t outlen; /* digest length */
+
+ uint8_t *pwd; /* password array */
+ uint32_t pwdlen; /* password length */
+
+ uint8_t *salt; /* salt array */
+ uint32_t saltlen; /* salt length */
+
+ uint8_t *secret; /* key array */
+ uint32_t secretlen; /* key length */
+
+ uint8_t *ad; /* associated data array */
+ uint32_t adlen; /* associated data length */
+
+ uint32_t t_cost; /* number of passes */
+ uint32_t m_cost; /* amount of memory requested (KB) */
+ uint32_t lanes; /* number of lanes */
+ uint32_t threads; /* maximum number of threads */
+
+ uint32_t version; /* version number */
+
+ allocate_fptr allocate_cbk; /* pointer to memory allocator */
+ deallocate_fptr free_cbk; /* pointer to memory deallocator */
+
+ uint32_t flags; /* array of bool options */
+ } argon2_context;
+
+ /* Argon2 primitive type */
+ typedef enum Argon2_type {
+ Argon2_d = 0,
+ Argon2_i = 1,
+ Argon2_id = 2
+ } argon2_type;
+
+ /* Version of the algorithm */
+ typedef enum Argon2_version {
+ ARGON2_VERSION_10 = 0x10,
+ ARGON2_VERSION_13 = 0x13,
+ ARGON2_VERSION_NUMBER = ARGON2_VERSION_13
+ } argon2_version;
+
+ /*
+ * Function that gives the string representation of an argon2_type.
+ * @param type The argon2_type that we want the string for
+ * @param uppercase Whether the string should have the first letter uppercase
+ * @return NULL if invalid type, otherwise the string representation.
+ */
+ ARGON2_PUBLIC const char *argon2_type2string(argon2_type type, int uppercase);
+
+ /*
+ * Function that performs memory-hard hashing with certain degree of parallelism
+ * @param context Pointer to the Argon2 internal structure
+ * @return Error code if smth is wrong, ARGON2_OK otherwise
+ */
+ ARGON2_PUBLIC int argon2_ctx(argon2_context *context, argon2_type type);
+
+ /**
+ * Hashes a password with Argon2i, producing an encoded hash
+ * @param t_cost Number of iterations
+ * @param m_cost Sets memory usage to m_cost kibibytes
+ * @param parallelism Number of threads and compute lanes
+ * @param pwd Pointer to password
+ * @param pwdlen Password size in bytes
+ * @param salt Pointer to salt
+ * @param saltlen Salt size in bytes
+ * @param hashlen Desired length of the hash in bytes
+ * @param encoded Buffer where to write the encoded hash
+ * @param encodedlen Size of the buffer (thus max size of the encoded hash)
+ * @pre Different parallelism levels will give different results
+ * @pre Returns ARGON2_OK if successful
+ */
+ ARGON2_PUBLIC int argon2i_hash_encoded(const uint32_t t_cost,
+ const uint32_t m_cost,
+ const uint32_t parallelism,
+ const void *pwd, const size_t pwdlen,
+ const void *salt, const size_t saltlen,
+ const size_t hashlen, char *encoded,
+ const size_t encodedlen);
+
+ /**
+ * Hashes a password with Argon2i, producing a raw hash by allocating memory at
+ * @hash
+ * @param t_cost Number of iterations
+ * @param m_cost Sets memory usage to m_cost kibibytes
+ * @param parallelism Number of threads and compute lanes
+ * @param pwd Pointer to password
+ * @param pwdlen Password size in bytes
+ * @param salt Pointer to salt
+ * @param saltlen Salt size in bytes
+ * @param hash Buffer where to write the raw hash - updated by the function
+ * @param hashlen Desired length of the hash in bytes
+ * @pre Different parallelism levels will give different results
+ * @pre Returns ARGON2_OK if successful
+ */
+ ARGON2_PUBLIC int argon2i_hash_raw(const uint32_t t_cost, const uint32_t m_cost,
+ const uint32_t parallelism, const void *pwd,
+ const size_t pwdlen, const void *salt,
+ const size_t saltlen, void *hash,
+ const size_t hashlen);
+
+ ARGON2_PUBLIC int argon2d_hash_encoded(const uint32_t t_cost,
+ const uint32_t m_cost,
+ const uint32_t parallelism,
+ const void *pwd, const size_t pwdlen,
+ const void *salt, const size_t saltlen,
+ const size_t hashlen, char *encoded,
+ const size_t encodedlen);
+
+ ARGON2_PUBLIC int argon2d_hash_raw(const uint32_t t_cost, const uint32_t m_cost,
+ const uint32_t parallelism, const void *pwd,
+ const size_t pwdlen, const void *salt,
+ const size_t saltlen, void *hash,
+ const size_t hashlen);
+
+ ARGON2_PUBLIC int argon2id_hash_encoded(const uint32_t t_cost,
+ const uint32_t m_cost,
+ const uint32_t parallelism,
+ const void *pwd, const size_t pwdlen,
+ const void *salt, const size_t saltlen,
+ const size_t hashlen, char *encoded,
+ const size_t encodedlen);
+
+ ARGON2_PUBLIC int argon2id_hash_raw(const uint32_t t_cost,
+ const uint32_t m_cost,
+ const uint32_t parallelism, const void *pwd,
+ const size_t pwdlen, const void *salt,
+ const size_t saltlen, void *hash,
+ const size_t hashlen);
+
+ /* generic function underlying the above ones */
+ ARGON2_PUBLIC int argon2_hash(const uint32_t t_cost, const uint32_t m_cost,
+ const uint32_t parallelism, const void *pwd,
+ const size_t pwdlen, const void *salt,
+ const size_t saltlen, void *hash,
+ const size_t hashlen, char *encoded,
+ const size_t encodedlen, argon2_type type,
+ const uint32_t version);
+
+ /**
+ * Verifies a password against an encoded string
+ * Encoded string is restricted as in validate_inputs()
+ * @param encoded String encoding parameters, salt, hash
+ * @param pwd Pointer to password
+ * @pre Returns ARGON2_OK if successful
+ */
+ ARGON2_PUBLIC int argon2i_verify(const char *encoded, const void *pwd,
+ const size_t pwdlen);
+
+ ARGON2_PUBLIC int argon2d_verify(const char *encoded, const void *pwd,
+ const size_t pwdlen);
+
+ ARGON2_PUBLIC int argon2id_verify(const char *encoded, const void *pwd,
+ const size_t pwdlen);
+
+ /* generic function underlying the above ones */
+ ARGON2_PUBLIC int argon2_verify(const char *encoded, const void *pwd,
+ const size_t pwdlen, argon2_type type);
+
+ /**
+ * Argon2d: Version of Argon2 that picks memory blocks depending
+ * on the password and salt. Only for side-channel-free
+ * environment!!
+ *****
+ * @param context Pointer to current Argon2 context
+ * @return Zero if successful, a non zero error code otherwise
+ */
+ ARGON2_PUBLIC int argon2d_ctx(argon2_context *context);
+
+ /**
+ * Argon2i: Version of Argon2 that picks memory blocks
+ * independent on the password and salt. Good for side-channels,
+ * but worse w.r.t. tradeoff attacks if only one pass is used.
+ *****
+ * @param context Pointer to current Argon2 context
+ * @return Zero if successful, a non zero error code otherwise
+ */
+ ARGON2_PUBLIC int argon2i_ctx(argon2_context *context);
+
+ /**
+ * Argon2id: Version of Argon2 where the first half-pass over memory is
+ * password-independent, the rest are password-dependent (on the password and
+ * salt). OK against side channels (they reduce to 1/2-pass Argon2i), and
+ * better with w.r.t. tradeoff attacks (similar to Argon2d).
+ *****
+ * @param context Pointer to current Argon2 context
+ * @return Zero if successful, a non zero error code otherwise
+ */
+ ARGON2_PUBLIC int argon2id_ctx(argon2_context *context);
+
+ /**
+ * Verify if a given password is correct for Argon2d hashing
+ * @param context Pointer to current Argon2 context
+ * @param hash The password hash to verify. The length of the hash is
+ * specified by the context outlen member
+ * @return Zero if successful, a non zero error code otherwise
+ */
+ ARGON2_PUBLIC int argon2d_verify_ctx(argon2_context *context, const char *hash);
+
+ /**
+ * Verify if a given password is correct for Argon2i hashing
+ * @param context Pointer to current Argon2 context
+ * @param hash The password hash to verify. The length of the hash is
+ * specified by the context outlen member
+ * @return Zero if successful, a non zero error code otherwise
+ */
+ ARGON2_PUBLIC int argon2i_verify_ctx(argon2_context *context, const char *hash);
+
+ /**
+ * Verify if a given password is correct for Argon2id hashing
+ * @param context Pointer to current Argon2 context
+ * @param hash The password hash to verify. The length of the hash is
+ * specified by the context outlen member
+ * @return Zero if successful, a non zero error code otherwise
+ */
+ ARGON2_PUBLIC int argon2id_verify_ctx(argon2_context *context,
+ const char *hash);
+
+ /* generic function underlying the above ones */
+ ARGON2_PUBLIC int argon2_verify_ctx(argon2_context *context, const char *hash,
+ argon2_type type);
+
+ /**
+ * Get the associated error message for given error code
+ * @return The error message associated with the given error code
+ */
+ ARGON2_PUBLIC const char *argon2_error_message(int error_code);
+
+ /**
+ * Returns the encoded hash length for the given input parameters
+ * @param t_cost Number of iterations
+ * @param m_cost Memory usage in kibibytes
+ * @param parallelism Number of threads; used to compute lanes
+ * @param saltlen Salt size in bytes
+ * @param hashlen Hash size in bytes
+ * @param type The argon2_type that we want the encoded length for
+ * @return The encoded hash length in bytes
+ */
+ ARGON2_PUBLIC size_t argon2_encodedlen(uint32_t t_cost, uint32_t m_cost,
+ uint32_t parallelism, uint32_t saltlen,
+ uint32_t hashlen, argon2_type type);
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif
diff --git a/Project1/block.cpp b/Project1/block.cpp
new file mode 100644
index 0000000..226c4b7
--- /dev/null
+++ b/Project1/block.cpp
@@ -0,0 +1,42 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2009-2015 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include "block.h"
+
+#include "hash.h"
+#include "tinyformat.h"
+#include "utilstrencodings.h"
+#include "common.h"
+
+uint256 CBlockHeader::GetHash() const
+{
+ return SerializeHash(*this);
+}
+
+std::string CBlock::ToString() const
+{
+ std::stringstream s;
+ s << strprintf("CBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
+ GetHash().ToString(),
+ nVersion,
+ hashPrevBlock.ToString(),
+ hashMerkleRoot.ToString(),
+ nTime, nBits, nNonce,
+ vtx.size());
+ for (unsigned int i = 0; i < vtx.size(); i++)
+ {
+ s << " " << vtx[i].ToString() << "\n";
+ }
+ return s.str();
+}
+
+int64_t GetBlockWeight(const CBlock& block)
+{
+ // This implements the weight = (stripped_size * 4) + witness_size formula,
+ // using only serialization with and without witness data. As witness_size
+ // is equal to total_size - stripped_size, this formula is identical to:
+ // weight = (stripped_size * 3) + total_size.
+ return ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * (WITNESS_SCALE_FACTOR - 1) + ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION);
+}
\ No newline at end of file
diff --git a/Project1/block.h b/Project1/block.h
new file mode 100644
index 0000000..24fa494
--- /dev/null
+++ b/Project1/block.h
@@ -0,0 +1,161 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2009-2015 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_PRIMITIVES_BLOCK_H
+#define BITCOIN_PRIMITIVES_BLOCK_H
+
+#include "transaction.h"
+#include "serialize.h"
+#include "uint256.h"
+
+/** Nodes collect new transactions into a block, hash them into a hash tree,
+* and scan through nonce values to make the block's hash satisfy proof-of-work
+* requirements. When they solve the proof-of-work, they broadcast the block
+* to everyone and the block is added to the block chain. The first transaction
+* in the block is a special one that creates a new coin owned by the creator
+* of the block.
+*/
+class CBlockHeader
+{
+public:
+ // header
+ int32_t nVersion;
+ uint256 hashPrevBlock;
+ uint256 hashMerkleRoot;
+ uint32_t nTime;
+ uint32_t nBits;
+ uint32_t nNonce;
+
+ CBlockHeader()
+ {
+ SetNull();
+ }
+
+ ADD_SERIALIZE_METHODS;
+
+ template
+ inline void SerializationOp(Stream& s, Operation ser_action) {
+ READWRITE(this->nVersion);
+ READWRITE(hashPrevBlock);
+ READWRITE(hashMerkleRoot);
+ READWRITE(nTime);
+ READWRITE(nBits);
+ READWRITE(nNonce);
+ }
+
+ void SetNull()
+ {
+ nVersion = 0;
+ hashPrevBlock.SetNull();
+ hashMerkleRoot.SetNull();
+ nTime = 0;
+ nBits = 0;
+ nNonce = 0;
+ }
+
+ bool IsNull() const
+ {
+ return (nBits == 0);
+ }
+
+ uint256 GetHash() const;
+
+ int64_t GetBlockTime() const
+ {
+ return (int64_t)nTime;
+ }
+};
+
+
+class CBlock : public CBlockHeader
+{
+public:
+ // network and disk
+ std::vector vtx;
+
+ // memory only
+ mutable bool fChecked;
+
+ CBlock()
+ {
+ SetNull();
+ }
+
+ CBlock(const CBlockHeader &header)
+ {
+ SetNull();
+ *((CBlockHeader*)this) = header;
+ }
+
+ ADD_SERIALIZE_METHODS;
+
+ template
+ inline void SerializationOp(Stream& s, Operation ser_action) {
+ READWRITE(*(CBlockHeader*)this);
+ READWRITE(vtx);
+ }
+
+ void SetNull()
+ {
+ CBlockHeader::SetNull();
+ vtx.clear();
+ fChecked = false;
+ }
+
+ CBlockHeader GetBlockHeader() const
+ {
+ CBlockHeader block;
+ block.nVersion = nVersion;
+ block.hashPrevBlock = hashPrevBlock;
+ block.hashMerkleRoot = hashMerkleRoot;
+ block.nTime = nTime;
+ block.nBits = nBits;
+ block.nNonce = nNonce;
+ return block;
+ }
+
+ std::string ToString() const;
+};
+
+/** Describes a place in the block chain to another node such that if the
+* other node doesn't have the same branch, it can find a recent common trunk.
+* The further back it is, the further before the fork it may be.
+*/
+struct CBlockLocator
+{
+ std::vector vHave;
+
+ CBlockLocator() {}
+
+ CBlockLocator(const std::vector& vHaveIn)
+ {
+ vHave = vHaveIn;
+ }
+
+ ADD_SERIALIZE_METHODS;
+
+ template
+ inline void SerializationOp(Stream& s, Operation ser_action) {
+ int nVersion = s.GetVersion();
+ if (!(s.GetType() & SER_GETHASH))
+ READWRITE(nVersion);
+ READWRITE(vHave);
+ }
+
+ void SetNull()
+ {
+ vHave.clear();
+ }
+
+ bool IsNull() const
+ {
+ return vHave.empty();
+ }
+};
+
+/** Compute the consensus-critical block weight (see BIP 141). */
+int64_t GetBlockWeight(const CBlock& tx);
+
+#endif // BITCOIN_PRIMITIVES_BLOCK_H
\ No newline at end of file
diff --git a/Project1/byteswap.h b/Project1/byteswap.h
new file mode 100644
index 0000000..a1b0349
--- /dev/null
+++ b/Project1/byteswap.h
@@ -0,0 +1,47 @@
+// Copyright (c) 2014 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_COMPAT_BYTESWAP_H
+#define BITCOIN_COMPAT_BYTESWAP_H
+
+#if defined(HAVE_CONFIG_H)
+#include "config/bitcoin-config.h"
+#endif
+
+#include
+
+#if defined(HAVE_BYTESWAP_H)
+#include
+#endif
+
+#if HAVE_DECL_BSWAP_16 == 0
+inline uint16_t bswap_16(uint16_t x)
+{
+ return (x >> 8) | ((x & 0x00ff) << 8);
+}
+#endif // HAVE_DECL_BSWAP16
+
+#if HAVE_DECL_BSWAP_32 == 0
+inline uint32_t bswap_32(uint32_t x)
+{
+ return (((x & 0xff000000U) >> 24) | ((x & 0x00ff0000U) >> 8) |
+ ((x & 0x0000ff00U) << 8) | ((x & 0x000000ffU) << 24));
+}
+#endif // HAVE_DECL_BSWAP32
+
+#if HAVE_DECL_BSWAP_64 == 0
+inline uint64_t bswap_64(uint64_t x)
+{
+ return (((x & 0xff00000000000000ull) >> 56)
+ | ((x & 0x00ff000000000000ull) >> 40)
+ | ((x & 0x0000ff0000000000ull) >> 24)
+ | ((x & 0x000000ff00000000ull) >> 8)
+ | ((x & 0x00000000ff000000ull) << 8)
+ | ((x & 0x0000000000ff0000ull) << 24)
+ | ((x & 0x000000000000ff00ull) << 40)
+ | ((x & 0x00000000000000ffull) << 56));
+}
+#endif // HAVE_DECL_BSWAP64
+
+#endif // BITCOIN_COMPAT_BYTESWAP_H
\ No newline at end of file
diff --git a/Project1/common.h b/Project1/common.h
new file mode 100644
index 0000000..7eed48b
--- /dev/null
+++ b/Project1/common.h
@@ -0,0 +1,66 @@
+// Copyright (c) 2014 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_CRYPTO_COMMON_H
+#define BITCOIN_CRYPTO_COMMON_H
+
+#if defined(HAVE_CONFIG_H)
+#include "bitcoin-config.h"
+#endif
+
+#include
+
+#include "endian.h"
+
+uint16_t static inline ReadLE16(const unsigned char* ptr)
+{
+ return le16toh(*((uint16_t*)ptr));
+}
+
+uint32_t static inline ReadLE32(const unsigned char* ptr)
+{
+ return le32toh(*((uint32_t*)ptr));
+}
+
+uint64_t static inline ReadLE64(const unsigned char* ptr)
+{
+ return le64toh(*((uint64_t*)ptr));
+}
+
+void static inline WriteLE16(unsigned char* ptr, uint16_t x)
+{
+ *((uint16_t*)ptr) = htole16(x);
+}
+
+void static inline WriteLE32(unsigned char* ptr, uint32_t x)
+{
+ *((uint32_t*)ptr) = htole32(x);
+}
+
+void static inline WriteLE64(unsigned char* ptr, uint64_t x)
+{
+ *((uint64_t*)ptr) = htole64(x);
+}
+
+uint32_t static inline ReadBE32(const unsigned char* ptr)
+{
+ return be32toh(*((uint32_t*)ptr));
+}
+
+uint64_t static inline ReadBE64(const unsigned char* ptr)
+{
+ return be64toh(*((uint64_t*)ptr));
+}
+
+void static inline WriteBE32(unsigned char* ptr, uint32_t x)
+{
+ *((uint32_t*)ptr) = htobe32(x);
+}
+
+void static inline WriteBE64(unsigned char* ptr, uint64_t x)
+{
+ *((uint64_t*)ptr) = htobe64(x);
+}
+
+#endif // BITCOIN_CRYPTO_COMMON_H
\ No newline at end of file
diff --git a/Project1/endian.h b/Project1/endian.h
new file mode 100644
index 0000000..2b8d4d8
--- /dev/null
+++ b/Project1/endian.h
@@ -0,0 +1,196 @@
+// Copyright (c) 2014-2015 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_COMPAT_ENDIAN_H
+#define BITCOIN_COMPAT_ENDIAN_H
+
+#if defined(HAVE_CONFIG_H)
+#include "config/bitcoin-config.h"
+#endif
+
+#include
+
+#include "byteswap.h"
+
+#if defined(HAVE_ENDIAN_H)
+#include
+#elif defined(HAVE_SYS_ENDIAN_H)
+#include
+#endif
+
+#if defined(WORDS_BIGENDIAN)
+
+#if HAVE_DECL_HTOBE16 == 0
+inline uint16_t htobe16(uint16_t host_16bits)
+{
+ return host_16bits;
+}
+#endif // HAVE_DECL_HTOBE16
+
+#if HAVE_DECL_HTOLE16 == 0
+inline uint16_t htole16(uint16_t host_16bits)
+{
+ return bswap_16(host_16bits);
+}
+#endif // HAVE_DECL_HTOLE16
+
+#if HAVE_DECL_BE16TOH == 0
+inline uint16_t be16toh(uint16_t big_endian_16bits)
+{
+ return big_endian_16bits;
+}
+#endif // HAVE_DECL_BE16TOH
+
+#if HAVE_DECL_LE16TOH == 0
+inline uint16_t le16toh(uint16_t little_endian_16bits)
+{
+ return bswap_16(little_endian_16bits);
+}
+#endif // HAVE_DECL_LE16TOH
+
+#if HAVE_DECL_HTOBE32 == 0
+inline uint32_t htobe32(uint32_t host_32bits)
+{
+ return host_32bits;
+}
+#endif // HAVE_DECL_HTOBE32
+
+#if HAVE_DECL_HTOLE32 == 0
+inline uint32_t htole32(uint32_t host_32bits)
+{
+ return bswap_32(host_32bits);
+}
+#endif // HAVE_DECL_HTOLE32
+
+#if HAVE_DECL_BE32TOH == 0
+inline uint32_t be32toh(uint32_t big_endian_32bits)
+{
+ return big_endian_32bits;
+}
+#endif // HAVE_DECL_BE32TOH
+
+#if HAVE_DECL_LE32TOH == 0
+inline uint32_t le32toh(uint32_t little_endian_32bits)
+{
+ return bswap_32(little_endian_32bits);
+}
+#endif // HAVE_DECL_LE32TOH
+
+#if HAVE_DECL_HTOBE64 == 0
+inline uint64_t htobe64(uint64_t host_64bits)
+{
+ return host_64bits;
+}
+#endif // HAVE_DECL_HTOBE64
+
+#if HAVE_DECL_HTOLE64 == 0
+inline uint64_t htole64(uint64_t host_64bits)
+{
+ return bswap_64(host_64bits);
+}
+#endif // HAVE_DECL_HTOLE64
+
+#if HAVE_DECL_BE64TOH == 0
+inline uint64_t be64toh(uint64_t big_endian_64bits)
+{
+ return big_endian_64bits;
+}
+#endif // HAVE_DECL_BE64TOH
+
+#if HAVE_DECL_LE64TOH == 0
+inline uint64_t le64toh(uint64_t little_endian_64bits)
+{
+ return bswap_64(little_endian_64bits);
+}
+#endif // HAVE_DECL_LE64TOH
+
+#else // WORDS_BIGENDIAN
+
+#if HAVE_DECL_HTOBE16 == 0
+inline uint16_t htobe16(uint16_t host_16bits)
+{
+ return bswap_16(host_16bits);
+}
+#endif // HAVE_DECL_HTOBE16
+
+#if HAVE_DECL_HTOLE16 == 0
+inline uint16_t htole16(uint16_t host_16bits)
+{
+ return host_16bits;
+}
+#endif // HAVE_DECL_HTOLE16
+
+#if HAVE_DECL_BE16TOH == 0
+inline uint16_t be16toh(uint16_t big_endian_16bits)
+{
+ return bswap_16(big_endian_16bits);
+}
+#endif // HAVE_DECL_BE16TOH
+
+#if HAVE_DECL_LE16TOH == 0
+inline uint16_t le16toh(uint16_t little_endian_16bits)
+{
+ return little_endian_16bits;
+}
+#endif // HAVE_DECL_LE16TOH
+
+#if HAVE_DECL_HTOBE32 == 0
+inline uint32_t htobe32(uint32_t host_32bits)
+{
+ return bswap_32(host_32bits);
+}
+#endif // HAVE_DECL_HTOBE32
+
+#if HAVE_DECL_HTOLE32 == 0
+inline uint32_t htole32(uint32_t host_32bits)
+{
+ return host_32bits;
+}
+#endif // HAVE_DECL_HTOLE32
+
+#if HAVE_DECL_BE32TOH == 0
+inline uint32_t be32toh(uint32_t big_endian_32bits)
+{
+ return bswap_32(big_endian_32bits);
+}
+#endif // HAVE_DECL_BE32TOH
+
+#if HAVE_DECL_LE32TOH == 0
+inline uint32_t le32toh(uint32_t little_endian_32bits)
+{
+ return little_endian_32bits;
+}
+#endif // HAVE_DECL_LE32TOH
+
+#if HAVE_DECL_HTOBE64 == 0
+inline uint64_t htobe64(uint64_t host_64bits)
+{
+ return bswap_64(host_64bits);
+}
+#endif // HAVE_DECL_HTOBE64
+
+#if HAVE_DECL_HTOLE64 == 0
+inline uint64_t htole64(uint64_t host_64bits)
+{
+ return host_64bits;
+}
+#endif // HAVE_DECL_HTOLE64
+
+#if HAVE_DECL_BE64TOH == 0
+inline uint64_t be64toh(uint64_t big_endian_64bits)
+{
+ return bswap_64(big_endian_64bits);
+}
+#endif // HAVE_DECL_BE64TOH
+
+#if HAVE_DECL_LE64TOH == 0
+inline uint64_t le64toh(uint64_t little_endian_64bits)
+{
+ return little_endian_64bits;
+}
+#endif // HAVE_DECL_LE64TOH
+
+#endif // WORDS_BIGENDIAN
+
+#endif // BITCOIN_COMPAT_ENDIAN_H
\ No newline at end of file
diff --git a/Project1/hash.h b/Project1/hash.h
new file mode 100644
index 0000000..5022a75
--- /dev/null
+++ b/Project1/hash.h
@@ -0,0 +1,210 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2009-2015 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_HASH_H
+#define BITCOIN_HASH_H
+
+#include "ripemd160.h"
+#include "sha256.h"
+#include "prevector.h"
+#include "serialize.h"
+#include "uint256.h"
+#include "version.h"
+
+#include
+
+typedef uint256 ChainCode;
+
+/** A hasher class for Bitcoin's 256-bit hash (double SHA-256). */
+class CHash256 {
+private:
+ CSHA256 sha;
+public:
+ static const size_t OUTPUT_SIZE = CSHA256::OUTPUT_SIZE;
+
+ void Finalize(unsigned char hash[OUTPUT_SIZE]) {
+ unsigned char buf[sha.OUTPUT_SIZE];
+ sha.Finalize(buf);
+ sha.Reset().Write(buf, sha.OUTPUT_SIZE).Finalize(hash);
+ }
+
+ CHash256& Write(const unsigned char *data, size_t len) {
+ sha.Write(data, len);
+ return *this;
+ }
+
+ CHash256& Reset() {
+ sha.Reset();
+ return *this;
+ }
+};
+
+/** A hasher class for Bitcoin's 160-bit hash (SHA-256 + RIPEMD-160). */
+class CHash160 {
+private:
+ CSHA256 sha;
+public:
+ static const size_t OUTPUT_SIZE = CRIPEMD160::OUTPUT_SIZE;
+
+ void Finalize(unsigned char hash[OUTPUT_SIZE]) {
+ unsigned char buf[sha.OUTPUT_SIZE];
+ sha.Finalize(buf);
+ CRIPEMD160().Write(buf, sha.OUTPUT_SIZE).Finalize(hash);
+ }
+
+ CHash160& Write(const unsigned char *data, size_t len) {
+ sha.Write(data, len);
+ return *this;
+ }
+
+ CHash160& Reset() {
+ sha.Reset();
+ return *this;
+ }
+};
+
+/** Compute the 256-bit hash of an object. */
+template
+inline uint256 Hash(const T1 pbegin, const T1 pend)
+{
+ static const unsigned char pblank[1] = {};
+ uint256 result;
+ CHash256().Write(pbegin == pend ? pblank : (const unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0]))
+ .Finalize((unsigned char*)&result);
+ return result;
+}
+
+/** Compute the 256-bit hash of the concatenation of two objects. */
+template
+inline uint256 Hash(const T1 p1begin, const T1 p1end,
+ const T2 p2begin, const T2 p2end) {
+ static const unsigned char pblank[1] = {};
+ uint256 result;
+ CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]))
+ .Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]))
+ .Finalize((unsigned char*)&result);
+ return result;
+}
+
+/** Compute the 256-bit hash of the concatenation of three objects. */
+template
+inline uint256 Hash(const T1 p1begin, const T1 p1end,
+ const T2 p2begin, const T2 p2end,
+ const T3 p3begin, const T3 p3end) {
+ static const unsigned char pblank[1] = {};
+ uint256 result;
+ CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]))
+ .Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]))
+ .Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0]))
+ .Finalize((unsigned char*)&result);
+ return result;
+}
+
+/** Compute the 160-bit hash an object. */
+template
+inline uint160 Hash160(const T1 pbegin, const T1 pend)
+{
+ static unsigned char pblank[1] = {};
+ uint160 result;
+ CHash160().Write(pbegin == pend ? pblank : (const unsigned char*)&pbegin[0], (pend - pbegin) * sizeof(pbegin[0]))
+ .Finalize((unsigned char*)&result);
+ return result;
+}
+
+/** Compute the 160-bit hash of a vector. */
+inline uint160 Hash160(const std::vector& vch)
+{
+ return Hash160(vch.begin(), vch.end());
+}
+
+/** Compute the 160-bit hash of a vector. */
+template
+inline uint160 Hash160(const prevector& vch)
+{
+ return Hash160(vch.begin(), vch.end());
+}
+
+/** A writer stream (for serialization) that computes a 256-bit hash. */
+class CHashWriter
+{
+private:
+ CHash256 ctx;
+
+ const int nType;
+ const int nVersion;
+public:
+
+ CHashWriter(int nTypeIn, int nVersionIn) : nType(nTypeIn), nVersion(nVersionIn) {}
+
+ int GetType() const { return nType; }
+ int GetVersion() const { return nVersion; }
+
+ void write(const char *pch, size_t size) {
+ ctx.Write((const unsigned char*)pch, size);
+ }
+
+ // invalidates the object
+ uint256 GetHash() {
+ uint256 result;
+ ctx.Finalize((unsigned char*)&result);
+ return result;
+ }
+
+ template
+ CHashWriter& operator<<(const T& obj) {
+ // Serialize to this stream
+ ::Serialize(*this, obj);
+ return (*this);
+ }
+};
+
+/** Compute the 256-bit hash of an object's serialization. */
+template
+uint256 SerializeHash(const T& obj, int nType = SER_GETHASH, int nVersion = PROTOCOL_VERSION)
+{
+ CHashWriter ss(nType, nVersion);
+ ss << obj;
+ return ss.GetHash();
+}
+
+unsigned int MurmurHash3(unsigned int nHashSeed, const std::vector& vDataToHash);
+
+void BIP32Hash(const ChainCode &chainCode, unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]);
+
+/** SipHash-2-4 */
+class CSipHasher
+{
+private:
+ uint64_t v[4];
+ uint64_t tmp;
+ int count;
+
+public:
+ /** Construct a SipHash calculator initialized with 128-bit key (k0, k1) */
+ CSipHasher(uint64_t k0, uint64_t k1);
+ /** Hash a 64-bit integer worth of data
+ * It is treated as if this was the little-endian interpretation of 8 bytes.
+ * This function can only be used when a multiple of 8 bytes have been written so far.
+ */
+ CSipHasher& Write(uint64_t data);
+ /** Hash arbitrary bytes. */
+ CSipHasher& Write(const unsigned char* data, size_t size);
+ /** Compute the 64-bit SipHash-2-4 of the data written so far. The object remains untouched. */
+ uint64_t Finalize() const;
+};
+
+/** Optimized SipHash-2-4 implementation for uint256.
+*
+* It is identical to:
+* SipHasher(k0, k1)
+* .Write(val.GetUint64(0))
+* .Write(val.GetUint64(1))
+* .Write(val.GetUint64(2))
+* .Write(val.GetUint64(3))
+* .Finalize()
+*/
+uint64_t SipHashUint256(uint64_t k0, uint64_t k1, const uint256& val);
+
+#endif // BITCOIN_HASH_H
\ No newline at end of file
diff --git a/Project1/main.cpp b/Project1/main.cpp
new file mode 100644
index 0000000..5054af0
--- /dev/null
+++ b/Project1/main.cpp
@@ -0,0 +1,2174 @@
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "common.h"
+#include "uint256.h"
+#include "merkle.h"
+#define _CRT_SECURE_NO_WARNINGS
+
+/*For memory wiping*/
+#ifdef _MSC_VER
+#include
+#include /* For SecureZeroMemory */
+#endif
+
+#define VC_GE_2005(version) (version >= 1400)
+#define BLAKE2_INLINE __inline
+#if defined(__clang__)
+#if __has_attribute(optnone)
+#define NOT_OPTIMIZED __attribute__((optnone))
+#endif
+#elif defined(__GNUC__)
+#define GCC_VERSION \
+ (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
+#if GCC_VERSION >= 40400
+#define NOT_OPTIMIZED __attribute__((optimize("O0")))
+#endif
+#endif
+#ifndef NOT_OPTIMIZED
+#define NOT_OPTIMIZED
+#endif
+
+/* Memory allocator types --- for external allocation */
+typedef int(*allocate_fptr)(uint8_t **memory, size_t bytes_to_allocate);
+typedef void(*deallocate_fptr)(uint8_t *memory, size_t bytes_to_allocate);
+
+const __m128i r16 = _mm_setr_epi8(2, 3, 4, 5, 6, 7, 0, 1, 10, 11, 12, 13, 14, 15, 8, 9);
+const __m128i r24 = _mm_setr_epi8(3, 4, 5, 6, 7, 0, 1, 2, 11, 12, 13, 14, 15, 8, 9, 10);
+__m128i t0, t1;
+
+#define _mm_roti_epi64(x, c) \
+ (-(c) == 32) ? _mm_shuffle_epi32((x), _MM_SHUFFLE(2,3,0,1)) \
+ : (-(c) == 24) ? _mm_shuffle_epi8((x), r24) \
+ : (-(c) == 16) ? _mm_shuffle_epi8((x), r16) \
+ : (-(c) == 63) ? _mm_xor_si128(_mm_srli_epi64((x), -(c)), _mm_add_epi64((x), (x))) \
+ : _mm_xor_si128(_mm_srli_epi64((x), -(c)), _mm_slli_epi64((x), 64-(-(c))))
+
+static inline __m128i fBlaMka(__m128i x, __m128i y) {
+ __m128i z = _mm_mul_epu32(x, y);
+
+ z = _mm_slli_epi64(z, 1);
+
+ z = _mm_add_epi64(z, x);
+ z = _mm_add_epi64(z, y);
+
+ return z;
+}
+
+#define G1(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h) \
+ row1l = fBlaMka(row1l, row2l); \
+ row1h = fBlaMka(row1h, row2h); \
+ \
+ row4l = _mm_xor_si128(row4l, row1l); \
+ row4h = _mm_xor_si128(row4h, row1h); \
+ \
+ row4l = _mm_roti_epi64(row4l, -32); \
+ row4h = _mm_roti_epi64(row4h, -32); \
+ \
+ row3l = fBlaMka(row3l, row4l); \
+ row3h = fBlaMka(row3h, row4h); \
+ \
+ row2l = _mm_xor_si128(row2l, row3l); \
+ row2h = _mm_xor_si128(row2h, row3h); \
+ \
+ row2l = _mm_roti_epi64(row2l, -24); \
+ row2h = _mm_roti_epi64(row2h, -24); \
+
+#define G2(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h) \
+ row1l = fBlaMka(row1l, row2l); \
+ row1h = fBlaMka(row1h, row2h); \
+ \
+ row4l = _mm_xor_si128(row4l, row1l); \
+ row4h = _mm_xor_si128(row4h, row1h); \
+ \
+ row4l = _mm_roti_epi64(row4l, -16); \
+ row4h = _mm_roti_epi64(row4h, -16); \
+ \
+ row3l = fBlaMka(row3l, row4l); \
+ row3h = fBlaMka(row3h, row4h); \
+ \
+ row2l = _mm_xor_si128(row2l, row3l); \
+ row2h = _mm_xor_si128(row2h, row3h); \
+ \
+ row2l = _mm_roti_epi64(row2l, -63); \
+ row2h = _mm_roti_epi64(row2h, -63); \
+
+
+#define DIAGONALIZE(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h) \
+ t0 = _mm_alignr_epi8(row2h, row2l, 8); \
+ t1 = _mm_alignr_epi8(row2l, row2h, 8); \
+ row2l = t0; \
+ row2h = t1; \
+ \
+ t0 = row3l; \
+ row3l = row3h; \
+ row3h = t0; \
+ \
+ t0 = _mm_alignr_epi8(row4h, row4l, 8); \
+ t1 = _mm_alignr_epi8(row4l, row4h, 8); \
+ row4l = t1; \
+ row4h = t0;
+
+#define UNDIAGONALIZE(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h) \
+ t0 = _mm_alignr_epi8(row2l, row2h, 8); \
+ t1 = _mm_alignr_epi8(row2h, row2l, 8); \
+ row2l = t0; \
+ row2h = t1; \
+ \
+ t0 = row3l; \
+ row3l = row3h; \
+ row3h = t0; \
+ \
+ t0 = _mm_alignr_epi8(row4l, row4h, 8); \
+ t1 = _mm_alignr_epi8(row4h, row4l, 8); \
+ row4l = t1; \
+ row4h = t0;
+
+#define BLAKE2_ROUND(row1l,row1h,row2l,row2h,row3l,row3h,row4l,row4h) \
+ G1(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h); \
+ G2(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h); \
+ \
+ DIAGONALIZE(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h); \
+ \
+ G1(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h); \
+ G2(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h); \
+ \
+ UNDIAGONALIZE(row1l,row2l,row3l,row4l,row1h,row2h,row3h,row4h);
+
+/*
+Here we implement an abstraction layer for the simpĺe requirements
+of the Argon2 code. We only require 3 primitives---thread creation,
+joining, and termination---so full emulation of the pthreads API
+is unwarranted. Currently we wrap pthreads and Win32 threads.
+
+The API defines 2 types: the function pointer type,
+argon2_thread_func_t,
+and the type of the thread handle---argon2_thread_handle_t.
+*/
+#if defined(_WIN32)
+#include
+typedef unsigned(__stdcall *argon2_thread_func_t)(void *);
+typedef uintptr_t argon2_thread_handle_t;
+#else
+#include
+typedef void *(*argon2_thread_func_t)(void *);
+typedef pthread_t argon2_thread_handle_t;
+#endif
+
+#define SecureZeroMemory RtlSecureZeroMemory
+
+/* Symbols visibility control */
+#ifdef A2_VISCTL
+#define ARGON2_PUBLIC __attribute__((visibility("default")))
+#elif _MSC_VER
+#define ARGON2_PUBLIC __declspec(dllexport)
+#else
+#define ARGON2_PUBLIC
+#endif
+
+/*
+* Argon2 input parameter restrictions
+*/
+
+/* Minimum and maximum number of lanes (degree of parallelism) */
+#define ARGON2_MIN_LANES UINT32_C(1)
+#define ARGON2_MAX_LANES UINT32_C(0xFFFFFF)
+
+/* Minimum and maximum number of threads */
+#define ARGON2_MIN_THREADS UINT32_C(1)
+#define ARGON2_MAX_THREADS UINT32_C(0xFFFFFF)
+
+/* Number of synchronization points between lanes per pass */
+#define ARGON2_SYNC_POINTS UINT32_C(4)
+
+/* Minimum and maximum digest size in bytes */
+#define ARGON2_MIN_OUTLEN UINT32_C(4)
+#define ARGON2_MAX_OUTLEN UINT32_C(0xFFFFFFFF)
+
+/* Minimum and maximum number of memory blocks (each of BLOCK_SIZE bytes) */
+#define ARGON2_MIN_MEMORY (2 * ARGON2_SYNC_POINTS) /* 2 blocks per slice */
+
+#define ARGON2_MIN(a, b) ((a) < (b) ? (a) : (b))
+/* Max memory size is addressing-space/2, topping at 2^32 blocks (4 TB) */
+#define ARGON2_MAX_MEMORY_BITS \
+ ARGON2_MIN(UINT32_C(32), (sizeof(void *) * CHAR_BIT - 10 - 1))
+#define ARGON2_MAX_MEMORY \
+ ARGON2_MIN(UINT32_C(0xFFFFFFFF), UINT64_C(1) << ARGON2_MAX_MEMORY_BITS)
+
+/* Minimum and maximum number of passes */
+#define ARGON2_MIN_TIME UINT32_C(1)
+#define ARGON2_MAX_TIME UINT32_C(0xFFFFFFFF)
+
+/* Minimum and maximum password length in bytes */
+#define ARGON2_MIN_PWD_LENGTH UINT32_C(0)
+#define ARGON2_MAX_PWD_LENGTH UINT32_C(0xFFFFFFFF)
+
+/* Minimum and maximum associated data length in bytes */
+#define ARGON2_MIN_AD_LENGTH UINT32_C(0)
+#define ARGON2_MAX_AD_LENGTH UINT32_C(0xFFFFFFFF)
+
+/* Minimum and maximum salt length in bytes */
+#define ARGON2_MIN_SALT_LENGTH UINT32_C(8)
+#define ARGON2_MAX_SALT_LENGTH UINT32_C(0xFFFFFFFF)
+
+/* Minimum and maximum key length in bytes */
+#define ARGON2_MIN_SECRET UINT32_C(0)
+#define ARGON2_MAX_SECRET UINT32_C(0xFFFFFFFF)
+
+/* Flags to determine which fields are securely wiped (default = no wipe). */
+#define ARGON2_DEFAULT_FLAGS UINT32_C(0)
+#define ARGON2_FLAG_CLEAR_PASSWORD (UINT32_C(1) << 0)
+#define ARGON2_FLAG_CLEAR_SECRET (UINT32_C(1) << 1)
+
+/* Global flag to determine if we are wiping internal memory buffers. This flag
+* is defined in core.c and deafults to 1 (wipe internal memory). */
+extern int FLAG_clear_internal_memory;
+
+/* Error codes */
+typedef enum Argon2_ErrorCodes {
+ ARGON2_OK = 0,
+
+ ARGON2_OUTPUT_PTR_NULL = -1,
+
+ ARGON2_OUTPUT_TOO_SHORT = -2,
+ ARGON2_OUTPUT_TOO_LONG = -3,
+
+ ARGON2_PWD_TOO_SHORT = -4,
+ ARGON2_PWD_TOO_LONG = -5,
+
+ ARGON2_SALT_TOO_SHORT = -6,
+ ARGON2_SALT_TOO_LONG = -7,
+
+ ARGON2_AD_TOO_SHORT = -8,
+ ARGON2_AD_TOO_LONG = -9,
+
+ ARGON2_SECRET_TOO_SHORT = -10,
+ ARGON2_SECRET_TOO_LONG = -11,
+
+ ARGON2_TIME_TOO_SMALL = -12,
+ ARGON2_TIME_TOO_LARGE = -13,
+
+ ARGON2_MEMORY_TOO_LITTLE = -14,
+ ARGON2_MEMORY_TOO_MUCH = -15,
+
+ ARGON2_LANES_TOO_FEW = -16,
+ ARGON2_LANES_TOO_MANY = -17,
+
+ ARGON2_PWD_PTR_MISMATCH = -18, /* NULL ptr with non-zero length */
+ ARGON2_SALT_PTR_MISMATCH = -19, /* NULL ptr with non-zero length */
+ ARGON2_SECRET_PTR_MISMATCH = -20, /* NULL ptr with non-zero length */
+ ARGON2_AD_PTR_MISMATCH = -21, /* NULL ptr with non-zero length */
+
+ ARGON2_MEMORY_ALLOCATION_ERROR = -22,
+
+ ARGON2_FREE_MEMORY_CBK_NULL = -23,
+ ARGON2_ALLOCATE_MEMORY_CBK_NULL = -24,
+
+ ARGON2_INCORRECT_PARAMETER = -25,
+ ARGON2_INCORRECT_TYPE = -26,
+
+ ARGON2_OUT_PTR_MISMATCH = -27,
+
+ ARGON2_THREADS_TOO_FEW = -28,
+ ARGON2_THREADS_TOO_MANY = -29,
+
+ ARGON2_MISSING_ARGS = -30,
+
+ ARGON2_ENCODING_FAIL = -31,
+
+ ARGON2_DECODING_FAIL = -32,
+
+ ARGON2_THREAD_FAIL = -33,
+
+ ARGON2_DECODING_LENGTH_FAIL = -34,
+
+ ARGON2_VERIFY_MISMATCH = -35
+} argon2_error_codes;
+
+/* Memory allocator types --- for external allocation */
+typedef int(*allocate_fptr)(uint8_t **memory, size_t bytes_to_allocate);
+typedef void(*deallocate_fptr)(uint8_t *memory, size_t bytes_to_allocate);
+
+/* Argon2 external data structures */
+
+/*
+*****
+* Context: structure to hold Argon2 inputs:
+* output array and its length,
+* password and its length,
+* salt and its length,
+* secret and its length,
+* associated data and its length,
+* number of passes, amount of used memory (in KBytes, can be rounded up a bit)
+* number of parallel threads that will be run.
+* All the parameters above affect the output hash value.
+* Additionally, two function pointers can be provided to allocate and
+* deallocate the memory (if NULL, memory will be allocated internally).
+* Also, three flags indicate whether to erase password, secret as soon as they
+* are pre-hashed (and thus not needed anymore), and the entire memory
+*****
+* Simplest situation: you have output array out[8], password is stored in
+* pwd[32], salt is stored in salt[16], you do not have keys nor associated
+* data. You need to spend 1 GB of RAM and you run 5 passes of Argon2d with
+* 4 parallel lanes.
+* You want to erase the password, but you're OK with last pass not being
+* erased. You want to use the default memory allocator.
+* Then you initialize:
+Argon2_Context(out,8,pwd,32,salt,16,NULL,0,NULL,0,5,1<<20,4,4,NULL,NULL,true,false,false,false)
+*/
+typedef struct Argon2_Context {
+ uint8_t *out; /* output array */
+ uint32_t outlen; /* digest length */
+
+ uint8_t *pwd; /* password array */
+ uint32_t pwdlen; /* password length */
+
+ uint8_t *salt; /* salt array */
+ uint32_t saltlen; /* salt length */
+
+ uint8_t *secret; /* key array */
+ uint32_t secretlen; /* key length */
+
+ uint8_t *ad; /* associated data array */
+ uint32_t adlen; /* associated data length */
+
+ uint32_t t_cost; /* number of passes */
+ uint32_t m_cost; /* amount of memory requested (KB) */
+ uint32_t lanes; /* number of lanes */
+ uint32_t threads; /* maximum number of threads */
+
+ uint32_t version; /* version number */
+
+ allocate_fptr allocate_cbk; /* pointer to memory allocator */
+ deallocate_fptr free_cbk; /* pointer to memory deallocator */
+
+ uint32_t flags; /* array of bool options */
+} argon2_context;
+
+
+
+/* Argon2 primitive type */
+typedef enum Argon2_type {
+ Argon2_d = 0,
+ Argon2_i = 1,
+ Argon2_id = 2
+} argon2_type;
+
+/* Version of the algorithm */
+typedef enum Argon2_version {
+ ARGON2_VERSION_10 = 0x10,
+ ARGON2_VERSION_13 = 0x13,
+ ARGON2_VERSION_NUMBER = ARGON2_VERSION_13
+} argon2_version;
+
+/*
+* Function that gives the string representation of an argon2_type.
+* @param type The argon2_type that we want the string for
+* @param uppercase Whether the string should have the first letter uppercase
+* @return NULL if invalid type, otherwise the string representation.
+*/
+ARGON2_PUBLIC const char *argon2_type2string(argon2_type type, int uppercase);
+
+/*
+* Function that performs memory-hard hashing with certain degree of parallelism
+* @param context Pointer to the Argon2 internal structure
+* @return Error code if smth is wrong, ARGON2_OK otherwise
+*/
+ARGON2_PUBLIC int argon2_ctx(argon2_context *context, argon2_type type);
+
+/**
+* Hashes a password with Argon2i, producing an encoded hash
+* @param t_cost Number of iterations
+* @param m_cost Sets memory usage to m_cost kibibytes
+* @param parallelism Number of threads and compute lanes
+* @param pwd Pointer to password
+* @param pwdlen Password size in bytes
+* @param salt Pointer to salt
+* @param saltlen Salt size in bytes
+* @param hashlen Desired length of the hash in bytes
+* @param encoded Buffer where to write the encoded hash
+* @param encodedlen Size of the buffer (thus max size of the encoded hash)
+* @pre Different parallelism levels will give different results
+* @pre Returns ARGON2_OK if successful
+*/
+ARGON2_PUBLIC int argon2i_hash_encoded(const uint32_t t_cost,
+ const uint32_t m_cost,
+ const uint32_t parallelism,
+ const void *pwd, const size_t pwdlen,
+ const void *salt, const size_t saltlen,
+ const size_t hashlen, char *encoded,
+ const size_t encodedlen);
+
+/**
+* Hashes a password with Argon2i, producing a raw hash by allocating memory at
+* @hash
+* @param t_cost Number of iterations
+* @param m_cost Sets memory usage to m_cost kibibytes
+* @param parallelism Number of threads and compute lanes
+* @param pwd Pointer to password
+* @param pwdlen Password size in bytes
+* @param salt Pointer to salt
+* @param saltlen Salt size in bytes
+* @param hash Buffer where to write the raw hash - updated by the function
+* @param hashlen Desired length of the hash in bytes
+* @pre Different parallelism levels will give different results
+* @pre Returns ARGON2_OK if successful
+*/
+ARGON2_PUBLIC int argon2i_hash_raw(const uint32_t t_cost, const uint32_t m_cost,
+ const uint32_t parallelism, const void *pwd,
+ const size_t pwdlen, const void *salt,
+ const size_t saltlen, void *hash,
+ const size_t hashlen);
+
+ARGON2_PUBLIC int argon2d_hash_encoded(const uint32_t t_cost,
+ const uint32_t m_cost,
+ const uint32_t parallelism,
+ const void *pwd, const size_t pwdlen,
+ const void *salt, const size_t saltlen,
+ const size_t hashlen, char *encoded,
+ const size_t encodedlen);
+
+ARGON2_PUBLIC int argon2d_hash_raw(const uint32_t t_cost, const uint32_t m_cost,
+ const uint32_t parallelism, const void *pwd,
+ const size_t pwdlen, const void *salt,
+ const size_t saltlen, void *hash,
+ const size_t hashlen);
+
+ARGON2_PUBLIC int argon2id_hash_encoded(const uint32_t t_cost,
+ const uint32_t m_cost,
+ const uint32_t parallelism,
+ const void *pwd, const size_t pwdlen,
+ const void *salt, const size_t saltlen,
+ const size_t hashlen, char *encoded,
+ const size_t encodedlen);
+
+ARGON2_PUBLIC int argon2id_hash_raw(const uint32_t t_cost,
+ const uint32_t m_cost,
+ const uint32_t parallelism, const void *pwd,
+ const size_t pwdlen, const void *salt,
+ const size_t saltlen, void *hash,
+ const size_t hashlen);
+
+/* generic function underlying the above ones */
+ARGON2_PUBLIC int argon2_hash(const uint32_t t_cost, const uint32_t m_cost,
+ const uint32_t parallelism, const void *pwd,
+ const size_t pwdlen, const void *salt,
+ const size_t saltlen, void *hash,
+ const size_t hashlen, char *encoded,
+ const size_t encodedlen, argon2_type type,
+ const uint32_t version);
+
+/**
+* Verifies a password against an encoded string
+* Encoded string is restricted as in validate_inputs()
+* @param encoded String encoding parameters, salt, hash
+* @param pwd Pointer to password
+* @pre Returns ARGON2_OK if successful
+*/
+ARGON2_PUBLIC int argon2i_verify(const char *encoded, const void *pwd,
+ const size_t pwdlen);
+
+ARGON2_PUBLIC int argon2d_verify(const char *encoded, const void *pwd,
+ const size_t pwdlen);
+
+ARGON2_PUBLIC int argon2id_verify(const char *encoded, const void *pwd,
+ const size_t pwdlen);
+
+/* generic function underlying the above ones */
+ARGON2_PUBLIC int argon2_verify(const char *encoded, const void *pwd,
+ const size_t pwdlen, argon2_type type);
+
+/**
+* Argon2d: Version of Argon2 that picks memory blocks depending
+* on the password and salt. Only for side-channel-free
+* environment!!
+*****
+* @param context Pointer to current Argon2 context
+* @return Zero if successful, a non zero error code otherwise
+*/
+ARGON2_PUBLIC int argon2d_ctx(argon2_context *context);
+
+/**
+* Argon2i: Version of Argon2 that picks memory blocks
+* independent on the password and salt. Good for side-channels,
+* but worse w.r.t. tradeoff attacks if only one pass is used.
+*****
+* @param context Pointer to current Argon2 context
+* @return Zero if successful, a non zero error code otherwise
+*/
+ARGON2_PUBLIC int argon2i_ctx(argon2_context *context);
+
+/**
+* Argon2id: Version of Argon2 where the first half-pass over memory is
+* password-independent, the rest are password-dependent (on the password and
+* salt). OK against side channels (they reduce to 1/2-pass Argon2i), and
+* better with w.r.t. tradeoff attacks (similar to Argon2d).
+*****
+* @param context Pointer to current Argon2 context
+* @return Zero if successful, a non zero error code otherwise
+*/
+ARGON2_PUBLIC int argon2id_ctx(argon2_context *context);
+
+/**
+* Verify if a given password is correct for Argon2d hashing
+* @param context Pointer to current Argon2 context
+* @param hash The password hash to verify. The length of the hash is
+* specified by the context outlen member
+* @return Zero if successful, a non zero error code otherwise
+*/
+ARGON2_PUBLIC int argon2d_verify_ctx(argon2_context *context, const char *hash);
+
+/**
+* Verify if a given password is correct for Argon2i hashing
+* @param context Pointer to current Argon2 context
+* @param hash The password hash to verify. The length of the hash is
+* specified by the context outlen member
+* @return Zero if successful, a non zero error code otherwise
+*/
+ARGON2_PUBLIC int argon2i_verify_ctx(argon2_context *context, const char *hash);
+
+/**
+* Verify if a given password is correct for Argon2id hashing
+* @param context Pointer to current Argon2 context
+* @param hash The password hash to verify. The length of the hash is
+* specified by the context outlen member
+* @return Zero if successful, a non zero error code otherwise
+*/
+ARGON2_PUBLIC int argon2id_verify_ctx(argon2_context *context,
+ const char *hash);
+
+/* generic function underlying the above ones */
+ARGON2_PUBLIC int argon2_verify_ctx(argon2_context *context, const char *hash,
+ argon2_type type);
+
+/**
+* Get the associated error message for given error code
+* @return The error message associated with the given error code
+*/
+ARGON2_PUBLIC const char *argon2_error_message(int error_code);
+
+/**
+* Returns the encoded hash length for the given input parameters
+* @param t_cost Number of iterations
+* @param m_cost Memory usage in kibibytes
+* @param parallelism Number of threads; used to compute lanes
+* @param saltlen Salt size in bytes
+* @param hashlen Hash size in bytes
+* @param type The argon2_type that we want the encoded length for
+* @return The encoded hash length in bytes
+*/
+ARGON2_PUBLIC size_t argon2_encodedlen(uint32_t t_cost, uint32_t m_cost,
+ uint32_t parallelism, uint32_t saltlen,
+ uint32_t hashlen, argon2_type type);
+
+
+
+int validate_inputs(const argon2_context *context) {
+ if (NULL == context) {
+ return ARGON2_INCORRECT_PARAMETER;
+ }
+
+ if (NULL == context->out) {
+ return ARGON2_OUTPUT_PTR_NULL;
+ }
+
+ /* Validate output length */
+ if (ARGON2_MIN_OUTLEN > context->outlen) {
+ return ARGON2_OUTPUT_TOO_SHORT;
+ }
+
+ if (ARGON2_MAX_OUTLEN < context->outlen) {
+ return ARGON2_OUTPUT_TOO_LONG;
+ }
+
+ /* Validate password (required param) */
+ if (NULL == context->pwd) {
+ if (0 != context->pwdlen) {
+ return ARGON2_PWD_PTR_MISMATCH;
+ }
+ }
+
+ if (ARGON2_MIN_PWD_LENGTH > context->pwdlen) {
+ return ARGON2_PWD_TOO_SHORT;
+ }
+
+ if (ARGON2_MAX_PWD_LENGTH < context->pwdlen) {
+ return ARGON2_PWD_TOO_LONG;
+ }
+
+ /* Validate salt (required param) */
+ if (NULL == context->salt) {
+ if (0 != context->saltlen) {
+ return ARGON2_SALT_PTR_MISMATCH;
+ }
+ }
+
+ if (ARGON2_MIN_SALT_LENGTH > context->saltlen) {
+ return ARGON2_SALT_TOO_SHORT;
+ }
+
+ if (ARGON2_MAX_SALT_LENGTH < context->saltlen) {
+ return ARGON2_SALT_TOO_LONG;
+ }
+
+ /* Validate secret (optional param) */
+ if (NULL == context->secret) {
+ if (0 != context->secretlen) {
+ return ARGON2_SECRET_PTR_MISMATCH;
+ }
+ }
+ else {
+ if (ARGON2_MIN_SECRET > context->secretlen) {
+ return ARGON2_SECRET_TOO_SHORT;
+ }
+ if (ARGON2_MAX_SECRET < context->secretlen) {
+ return ARGON2_SECRET_TOO_LONG;
+ }
+ }
+
+ /* Validate associated data (optional param) */
+ if (NULL == context->ad) {
+ if (0 != context->adlen) {
+ return ARGON2_AD_PTR_MISMATCH;
+ }
+ }
+ else {
+ if (ARGON2_MIN_AD_LENGTH > context->adlen) {
+ return ARGON2_AD_TOO_SHORT;
+ }
+ if (ARGON2_MAX_AD_LENGTH < context->adlen) {
+ return ARGON2_AD_TOO_LONG;
+ }
+ }
+
+ /* Validate memory cost */
+ if (ARGON2_MIN_MEMORY > context->m_cost) {
+ return ARGON2_MEMORY_TOO_LITTLE;
+ }
+
+ if (ARGON2_MAX_MEMORY < context->m_cost) {
+ return ARGON2_MEMORY_TOO_MUCH;
+ }
+
+ if (context->m_cost < 8 * context->lanes) {
+ return ARGON2_MEMORY_TOO_LITTLE;
+ }
+
+ /* Validate time cost */
+ if (ARGON2_MIN_TIME > context->t_cost) {
+ return ARGON2_TIME_TOO_SMALL;
+ }
+
+ if (ARGON2_MAX_TIME < context->t_cost) {
+ return ARGON2_TIME_TOO_LARGE;
+ }
+
+ /* Validate lanes */
+ if (ARGON2_MIN_LANES > context->lanes) {
+ return ARGON2_LANES_TOO_FEW;
+ }
+
+ if (ARGON2_MAX_LANES < context->lanes) {
+ return ARGON2_LANES_TOO_MANY;
+ }
+
+ /* Validate threads */
+ if (ARGON2_MIN_THREADS > context->threads) {
+ return ARGON2_THREADS_TOO_FEW;
+ }
+
+ if (ARGON2_MAX_THREADS < context->threads) {
+ return ARGON2_THREADS_TOO_MANY;
+ }
+
+ if (NULL != context->allocate_cbk && NULL == context->free_cbk) {
+ return ARGON2_FREE_MEMORY_CBK_NULL;
+ }
+
+ if (NULL == context->allocate_cbk && NULL != context->free_cbk) {
+ return ARGON2_ALLOCATE_MEMORY_CBK_NULL;
+ }
+
+ return ARGON2_OK;
+}
+
+/**********************Argon2 internal constants*******************************/
+
+enum argon2_core_constants {
+ /* Memory block size in bytes */
+ ARGON2_BLOCK_SIZE = 1024,
+ ARGON2_QWORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 8,
+ ARGON2_OWORDS_IN_BLOCK = ARGON2_BLOCK_SIZE / 16,
+
+ /* Number of pseudo-random values generated by one call to Blake in Argon2i
+ to
+ generate reference block positions */
+ ARGON2_ADDRESSES_IN_BLOCK = 128,
+
+ /* Pre-hashing digest length and its extension*/
+ ARGON2_PREHASH_DIGEST_LENGTH = 64,
+ ARGON2_PREHASH_SEED_LENGTH = 72
+};
+
+/*
+* Structure for the (1KB) memory block implemented as 128 64-bit words.
+* Memory blocks can be copied, XORed. Internal words can be accessed by [] (no
+* bounds checking).
+*/
+typedef struct block_ { uint64_t v[ARGON2_QWORDS_IN_BLOCK]; } block;
+
+
+/*
+* Argon2 instance: memory pointer, number of passes, amount of memory, type,
+* and derived values.
+* Used to evaluate the number and location of blocks to construct in each
+* thread
+*/
+typedef struct Argon2_instance_t {
+ block *memory; /* Memory pointer */
+ uint32_t version;
+ uint32_t passes; /* Number of passes */
+ uint32_t memory_blocks; /* Number of blocks in memory */
+ uint32_t segment_length;
+ uint32_t lane_length;
+ uint32_t lanes;
+ uint32_t threads;
+ argon2_type type;
+ int print_internals; /* whether to print the memory blocks */
+ argon2_context *context_ptr; /* points back to original context */
+} argon2_instance_t;
+
+
+const char *argon2_type2string(argon2_type type, int uppercase) {
+ switch (type) {
+ case Argon2_d:
+ return uppercase ? "Argon2d" : "argon2d";
+ case Argon2_i:
+ return uppercase ? "Argon2i" : "argon2i";
+ case Argon2_id:
+ return uppercase ? "Argon2id" : "argon2id";
+ }
+
+ return NULL;
+}
+
+void initial_kat(const uint8_t *blockhash, const argon2_context *context,
+ argon2_type type) {
+ unsigned i;
+
+ if (blockhash != NULL && context != NULL) {
+ printf("=======================================\n");
+
+ printf("%s version number %d\n", argon2_type2string(type, 1),
+ context->version);
+
+ printf("=======================================\n");
+
+
+ printf("Memory: %u KiB, Iterations: %u, Parallelism: %u lanes, Tag "
+ "length: %u bytes\n",
+ context->m_cost, context->t_cost, context->lanes,
+ context->outlen);
+
+ printf("Password[%u]: ", context->pwdlen);
+
+ if (context->flags & ARGON2_FLAG_CLEAR_PASSWORD) {
+ printf("CLEARED\n");
+ }
+ else {
+ for (i = 0; i < context->pwdlen; ++i) {
+ printf("%2.2x ", ((unsigned char *)context->pwd)[i]);
+ }
+
+ printf("\n");
+ }
+
+ printf("Salt[%u]: ", context->saltlen);
+
+ for (i = 0; i < context->saltlen; ++i) {
+ printf("%2.2x ", ((unsigned char *)context->salt)[i]);
+ }
+
+ printf("\n");
+
+ printf("Secret[%u]: ", context->secretlen);
+
+ if (context->flags & ARGON2_FLAG_CLEAR_SECRET) {
+ printf("CLEARED\n");
+ }
+ else {
+ for (i = 0; i < context->secretlen; ++i) {
+ printf("%2.2x ", ((unsigned char *)context->secret)[i]);
+ }
+
+ printf("\n");
+ }
+
+ printf("Associated data[%u]: ", context->adlen);
+
+ for (i = 0; i < context->adlen; ++i) {
+ printf("%2.2x ", ((unsigned char *)context->ad)[i]);
+ }
+
+ printf("\n");
+
+ printf("Pre-hashing digest: ");
+
+ for (i = 0; i < ARGON2_PREHASH_DIGEST_LENGTH; ++i) {
+ printf("%2.2x ", ((unsigned char *)blockhash)[i]);
+ }
+
+ printf("\n");
+ }
+}
+
+void print_tag(const void *out, uint32_t outlen) {
+ unsigned i;
+ if (out != NULL) {
+ printf("Tag: ");
+
+ for (i = 0; i < outlen; ++i) {
+ printf("%2.2x ", ((uint8_t *)out)[i]);
+ }
+
+ printf("\n");
+ }
+}
+
+
+
+void internal_kat(const argon2_instance_t *instance, uint32_t pass) {
+
+ if (instance != NULL) {
+ uint32_t i, j;
+ printf("\n After pass %u:\n", pass);
+
+ for (i = 0; i < instance->memory_blocks; ++i) {
+ uint32_t how_many_words =
+ (instance->memory_blocks > ARGON2_QWORDS_IN_BLOCK)
+ ? 1
+ : ARGON2_QWORDS_IN_BLOCK;
+
+ for (j = 0; j < how_many_words; ++j)
+ printf("Block %.4u [%3u]: %016" PRIx64 "\n", i, j,
+ instance->memory[i].v[j]);
+ }
+ }
+}
+
+
+static void fatal(const char *error) {
+ fprintf(stderr, "Error: %s\n", error);
+ exit(1);
+}
+
+
+
+/***************Memory functions*****************/
+
+int allocate_memory(const argon2_context *context, uint8_t **memory,
+ size_t num, size_t size) {
+ size_t memory_size = num*size;
+ if (memory == NULL) {
+ return ARGON2_MEMORY_ALLOCATION_ERROR;
+ }
+
+ /* 1. Check for multiplication overflow */
+ if (size != 0 && memory_size / size != num) {
+ return ARGON2_MEMORY_ALLOCATION_ERROR;
+ }
+
+ /* 2. Try to allocate with appropriate allocator */
+ if (context->allocate_cbk) {
+ (context->allocate_cbk)(memory, memory_size);
+ }
+ else {
+ *memory = (uint8_t*)malloc(memory_size);
+ }
+
+ if (*memory == NULL) {
+ return ARGON2_MEMORY_ALLOCATION_ERROR;
+ }
+
+ return ARGON2_OK;
+}
+
+enum blake2b_constant {
+ BLAKE2B_BLOCKBYTES = 128,
+ BLAKE2B_OUTBYTES = 64,
+ BLAKE2B_KEYBYTES = 64,
+ BLAKE2B_SALTBYTES = 16,
+ BLAKE2B_PERSONALBYTES = 16
+};
+
+typedef struct __blake2b_state {
+ uint64_t h[8];
+ uint64_t t[2];
+ uint64_t f[2];
+ uint8_t buf[BLAKE2B_BLOCKBYTES];
+ unsigned buflen;
+ unsigned outlen;
+ uint8_t last_node;
+} blake2b_state;
+
+typedef struct __blake2b_param {
+ uint8_t digest_length; /* 1 */
+ uint8_t key_length; /* 2 */
+ uint8_t fanout; /* 3 */
+ uint8_t depth; /* 4 */
+ uint32_t leaf_length; /* 8 */
+ uint64_t node_offset; /* 16 */
+ uint8_t node_depth; /* 17 */
+ uint8_t inner_length; /* 18 */
+ uint8_t reserved[14]; /* 32 */
+ uint8_t salt[BLAKE2B_SALTBYTES]; /* 48 */
+ uint8_t personal[BLAKE2B_PERSONALBYTES]; /* 64 */
+} blake2b_param;
+
+
+void NOT_OPTIMIZED secure_wipe_memory(void *v, size_t n) {
+#if defined(_MSC_VER) && VC_GE_2005(_MSC_VER)
+ SecureZeroMemory(v, n);
+#elif defined memset_s
+ memset_s(v, n, 0, n);
+#elif defined(__OpenBSD__)
+ explicit_bzero(v, n);
+#else
+ static void *(*const volatile memset_sec)(void *, int, size_t) = &memset;
+ memset_sec(v, 0, n);
+#endif
+}
+
+
+/* Memory clear flag defaults to true. */
+int FLAG_clear_internal_memory = 1;
+void clear_internal_memory(void *v, size_t n) {
+ if (FLAG_clear_internal_memory && v) {
+ secure_wipe_memory(v, n);
+ }
+}
+
+
+static BLAKE2_INLINE void blake2b_set_lastnode(blake2b_state *S) {
+ S->f[1] = (uint64_t)-1;
+}
+
+static BLAKE2_INLINE void blake2b_set_lastblock(blake2b_state *S) {
+ if (S->last_node) {
+ blake2b_set_lastnode(S);
+ }
+ S->f[0] = (uint64_t)-1;
+}
+
+static BLAKE2_INLINE void blake2b_invalidate_state(blake2b_state *S) {
+ clear_internal_memory(S, sizeof(*S)); /* wipe */
+ blake2b_set_lastblock(S); /* invalidate for further use */
+}
+
+static const uint64_t blake2b_IV[8] = {
+ UINT64_C(0x6a09e667f3bcc908), UINT64_C(0xbb67ae8584caa73b),
+ UINT64_C(0x3c6ef372fe94f82b), UINT64_C(0xa54ff53a5f1d36f1),
+ UINT64_C(0x510e527fade682d1), UINT64_C(0x9b05688c2b3e6c1f),
+ UINT64_C(0x1f83d9abfb41bd6b), UINT64_C(0x5be0cd19137e2179) };
+
+static BLAKE2_INLINE void blake2b_init0(blake2b_state *S) {
+ memset(S, 0, sizeof(*S));
+ memcpy(S->h, blake2b_IV, sizeof(S->h));
+}
+
+static BLAKE2_INLINE uint64_t load64(const void *src) {
+#if defined(NATIVE_LITTLE_ENDIAN)
+ uint64_t w;
+ memcpy(&w, src, sizeof w);
+ return w;
+#else
+ const uint8_t *p = (const uint8_t *)src;
+ uint64_t w = *p++;
+ w |= (uint64_t)(*p++) << 8;
+ w |= (uint64_t)(*p++) << 16;
+ w |= (uint64_t)(*p++) << 24;
+ w |= (uint64_t)(*p++) << 32;
+ w |= (uint64_t)(*p++) << 40;
+ w |= (uint64_t)(*p++) << 48;
+ w |= (uint64_t)(*p++) << 56;
+ return w;
+#endif
+}
+
+
+int blake2b_init_param(blake2b_state *S, const blake2b_param *P) {
+ const unsigned char *p = (const unsigned char *)P;
+ unsigned int i;
+
+ if (NULL == P || NULL == S) {
+ return -1;
+ }
+
+ blake2b_init0(S);
+ /* IV XOR Parameter Block */
+ for (i = 0; i < 8; ++i) {
+ S->h[i] ^= load64(&p[i * sizeof(S->h[i])]);
+ }
+ S->outlen = P->digest_length;
+ return 0;
+}
+
+/* Sequential blake2b initialization */
+int blake2b_init(blake2b_state *S, size_t outlen) {
+ blake2b_param P;
+
+ if (S == NULL) {
+ return -1;
+ }
+
+ if ((outlen == 0) || (outlen > BLAKE2B_OUTBYTES)) {
+ blake2b_invalidate_state(S);
+ return -1;
+ }
+
+ /* Setup Parameter Block for unkeyed BLAKE2 */
+ P.digest_length = (uint8_t)outlen;
+ P.key_length = 0;
+ P.fanout = 1;
+ P.depth = 1;
+ P.leaf_length = 0;
+ P.node_offset = 0;
+ P.node_depth = 0;
+ P.inner_length = 0;
+ memset(P.reserved, 0, sizeof(P.reserved));
+ memset(P.salt, 0, sizeof(P.salt));
+ memset(P.personal, 0, sizeof(P.personal));
+
+ return blake2b_init_param(S, &P);
+}
+
+
+static const unsigned int blake2b_sigma[12][16] = {
+ { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
+ { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
+ { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },
+ { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
+ { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },
+ { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },
+ { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 },
+ { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },
+ { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 },
+ { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 },
+ { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
+ { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
+};
+
+static BLAKE2_INLINE uint32_t rotr32(const uint32_t w, const unsigned c) {
+ return (w >> c) | (w << (32 - c));
+}
+
+static BLAKE2_INLINE uint64_t rotr64(const uint64_t w, const unsigned c) {
+ return (w >> c) | (w << (64 - c));
+}
+
+static void blake2b_compress(blake2b_state *S, const uint8_t *block) {
+ uint64_t m[16];
+ uint64_t v[16];
+ unsigned int i, r;
+
+ for (i = 0; i < 16; ++i) {
+ m[i] = load64(block + i * sizeof(m[i]));
+ }
+
+ for (i = 0; i < 8; ++i) {
+ v[i] = S->h[i];
+ }
+
+ v[8] = blake2b_IV[0];
+ v[9] = blake2b_IV[1];
+ v[10] = blake2b_IV[2];
+ v[11] = blake2b_IV[3];
+ v[12] = blake2b_IV[4] ^ S->t[0];
+ v[13] = blake2b_IV[5] ^ S->t[1];
+ v[14] = blake2b_IV[6] ^ S->f[0];
+ v[15] = blake2b_IV[7] ^ S->f[1];
+
+#define G(r, i, a, b, c, d) \
+ do { \
+ a = a + b + m[blake2b_sigma[r][2 * i + 0]]; \
+ d = rotr64(d ^ a, 32); \
+ c = c + d; \
+ b = rotr64(b ^ c, 24); \
+ a = a + b + m[blake2b_sigma[r][2 * i + 1]]; \
+ d = rotr64(d ^ a, 16); \
+ c = c + d; \
+ b = rotr64(b ^ c, 63); \
+ } while ((void)0, 0)
+
+#define ROUND(r) \
+ do { \
+ G(r, 0, v[0], v[4], v[8], v[12]); \
+ G(r, 1, v[1], v[5], v[9], v[13]); \
+ G(r, 2, v[2], v[6], v[10], v[14]); \
+ G(r, 3, v[3], v[7], v[11], v[15]); \
+ G(r, 4, v[0], v[5], v[10], v[15]); \
+ G(r, 5, v[1], v[6], v[11], v[12]); \
+ G(r, 6, v[2], v[7], v[8], v[13]); \
+ G(r, 7, v[3], v[4], v[9], v[14]); \
+ } while ((void)0, 0)
+
+ for (r = 0; r < 12; ++r) {
+ ROUND(r);
+ }
+
+ for (i = 0; i < 8; ++i) {
+ S->h[i] = S->h[i] ^ v[i] ^ v[i + 8];
+ }
+
+#undef G
+#undef ROUND
+}
+
+
+
+static BLAKE2_INLINE void blake2b_increment_counter(blake2b_state *S,
+ uint64_t inc) {
+ S->t[0] += inc;
+ S->t[1] += (S->t[0] < inc);
+}
+
+
+static BLAKE2_INLINE void store64(void *dst, uint64_t w) {
+#if defined(NATIVE_LITTLE_ENDIAN)
+ memcpy(dst, &w, sizeof w);
+#else
+ uint8_t *p = (uint8_t *)dst;
+ *p++ = (uint8_t)w;
+ w >>= 8;
+ *p++ = (uint8_t)w;
+ w >>= 8;
+ *p++ = (uint8_t)w;
+ w >>= 8;
+ *p++ = (uint8_t)w;
+ w >>= 8;
+ *p++ = (uint8_t)w;
+ w >>= 8;
+ *p++ = (uint8_t)w;
+ w >>= 8;
+ *p++ = (uint8_t)w;
+ w >>= 8;
+ *p++ = (uint8_t)w;
+#endif
+}
+
+int blake2b_final(blake2b_state *S, void *out, size_t outlen) {
+ uint8_t buffer[BLAKE2B_OUTBYTES] = { 0 };
+ unsigned int i;
+
+ /* Sanity checks */
+ if (S == NULL || out == NULL || outlen < S->outlen) {
+ return -1;
+ }
+
+ /* Is this a reused state? */
+ if (S->f[0] != 0) {
+ return -1;
+ }
+
+ blake2b_increment_counter(S, S->buflen);
+ blake2b_set_lastblock(S);
+ memset(&S->buf[S->buflen], 0, BLAKE2B_BLOCKBYTES - S->buflen); /* Padding */
+ blake2b_compress(S, S->buf);
+
+ for (i = 0; i < 8; ++i) { /* Output full hash to temp buffer */
+ store64(buffer + sizeof(S->h[i]) * i, S->h[i]);
+ }
+
+ memcpy(out, buffer, S->outlen);
+ clear_internal_memory(buffer, sizeof(buffer));
+ clear_internal_memory(S->buf, sizeof(S->buf));
+ clear_internal_memory(S->h, sizeof(S->h));
+ return 0;
+}
+
+
+static BLAKE2_INLINE void store32(void *dst, uint32_t w) {
+#if defined(NATIVE_LITTLE_ENDIAN)
+ memcpy(dst, &w, sizeof w);
+#else
+ uint8_t *p = (uint8_t *)dst;
+ *p++ = (uint8_t)w;
+ w >>= 8;
+ *p++ = (uint8_t)w;
+ w >>= 8;
+ *p++ = (uint8_t)w;
+ w >>= 8;
+ *p++ = (uint8_t)w;
+#endif
+}
+
+
+int blake2b_update(blake2b_state *S, const void *in, size_t inlen) {
+ const uint8_t *pin = (const uint8_t *)in;
+
+ if (inlen == 0) {
+ return 0;
+ }
+
+ /* Sanity check */
+ if (S == NULL || in == NULL) {
+ return -1;
+ }
+
+ /* Is this a reused state? */
+ if (S->f[0] != 0) {
+ return -1;
+ }
+
+ if (S->buflen + inlen > BLAKE2B_BLOCKBYTES) {
+ /* Complete current block */
+ size_t left = S->buflen;
+ size_t fill = BLAKE2B_BLOCKBYTES - left;
+ memcpy(&S->buf[left], pin, fill);
+ blake2b_increment_counter(S, BLAKE2B_BLOCKBYTES);
+ blake2b_compress(S, S->buf);
+ S->buflen = 0;
+ inlen -= fill;
+ pin += fill;
+ /* Avoid buffer copies when possible */
+ while (inlen > BLAKE2B_BLOCKBYTES) {
+ blake2b_increment_counter(S, BLAKE2B_BLOCKBYTES);
+ blake2b_compress(S, pin);
+ inlen -= BLAKE2B_BLOCKBYTES;
+ pin += BLAKE2B_BLOCKBYTES;
+ }
+ }
+ memcpy(&S->buf[S->buflen], pin, inlen);
+ S->buflen += (unsigned int)inlen;
+ return 0;
+}
+
+
+void initial_hash(uint8_t *blockhash, argon2_context *context,
+ argon2_type type) {
+ blake2b_state BlakeHash;
+ uint8_t value[sizeof(uint32_t)];
+
+ if (NULL == context || NULL == blockhash) {
+ return;
+ }
+
+ blake2b_init(&BlakeHash, ARGON2_PREHASH_DIGEST_LENGTH);
+
+ store32(&value, context->lanes);
+ blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
+
+ store32(&value, context->outlen);
+ blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
+
+ store32(&value, context->m_cost);
+ blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
+
+ store32(&value, context->t_cost);
+ blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
+
+ store32(&value, context->version);
+ blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
+
+ store32(&value, (uint32_t)type);
+ blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
+
+ store32(&value, context->pwdlen);
+ blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
+
+ if (context->pwd != NULL) {
+ blake2b_update(&BlakeHash, (const uint8_t *)context->pwd,
+ context->pwdlen);
+
+ if (context->flags & ARGON2_FLAG_CLEAR_PASSWORD) {
+ secure_wipe_memory(context->pwd, context->pwdlen);
+ context->pwdlen = 0;
+ }
+ }
+
+ store32(&value, context->saltlen);
+ blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
+
+ if (context->salt != NULL) {
+ blake2b_update(&BlakeHash, (const uint8_t *)context->salt,
+ context->saltlen);
+ }
+
+ store32(&value, context->secretlen);
+ blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
+
+ if (context->secret != NULL) {
+ blake2b_update(&BlakeHash, (const uint8_t *)context->secret,
+ context->secretlen);
+
+ if (context->flags & ARGON2_FLAG_CLEAR_SECRET) {
+ secure_wipe_memory(context->secret, context->secretlen);
+ context->secretlen = 0;
+ }
+ }
+
+ store32(&value, context->adlen);
+ blake2b_update(&BlakeHash, (const uint8_t *)&value, sizeof(value));
+
+ if (context->ad != NULL) {
+ blake2b_update(&BlakeHash, (const uint8_t *)context->ad,
+ context->adlen);
+ }
+
+ blake2b_final(&BlakeHash, blockhash, ARGON2_PREHASH_DIGEST_LENGTH);
+}
+
+
+int blake2b_init_key(blake2b_state *S, size_t outlen, const void *key,
+ size_t keylen) {
+ blake2b_param P;
+
+ if (S == NULL) {
+ return -1;
+ }
+
+ if ((outlen == 0) || (outlen > BLAKE2B_OUTBYTES)) {
+ blake2b_invalidate_state(S);
+ return -1;
+ }
+
+ if ((key == 0) || (keylen == 0) || (keylen > BLAKE2B_KEYBYTES)) {
+ blake2b_invalidate_state(S);
+ return -1;
+ }
+
+ /* Setup Parameter Block for keyed BLAKE2 */
+ P.digest_length = (uint8_t)outlen;
+ P.key_length = (uint8_t)keylen;
+ P.fanout = 1;
+ P.depth = 1;
+ P.leaf_length = 0;
+ P.node_offset = 0;
+ P.node_depth = 0;
+ P.inner_length = 0;
+ memset(P.reserved, 0, sizeof(P.reserved));
+ memset(P.salt, 0, sizeof(P.salt));
+ memset(P.personal, 0, sizeof(P.personal));
+
+ if (blake2b_init_param(S, &P) < 0) {
+ blake2b_invalidate_state(S);
+ return -1;
+ }
+
+ {
+ uint8_t block[BLAKE2B_BLOCKBYTES];
+ memset(block, 0, BLAKE2B_BLOCKBYTES);
+ memcpy(block, key, keylen);
+ blake2b_update(S, block, BLAKE2B_BLOCKBYTES);
+ /* Burn the key from stack */
+ clear_internal_memory(block, BLAKE2B_BLOCKBYTES);
+ }
+ return 0;
+}
+
+int blake2b(void *out, size_t outlen, const void *in, size_t inlen,
+ const void *key, size_t keylen) {
+ blake2b_state S;
+ int ret = -1;
+
+ /* Verify parameters */
+ if (NULL == in && inlen > 0) {
+ goto fail;
+ }
+
+ if (NULL == out || outlen == 0 || outlen > BLAKE2B_OUTBYTES) {
+ goto fail;
+ }
+
+ if ((NULL == key && keylen > 0) || keylen > BLAKE2B_KEYBYTES) {
+ goto fail;
+ }
+
+ if (keylen > 0) {
+ if (blake2b_init_key(&S, outlen, key, keylen) < 0) {
+ goto fail;
+ }
+ }
+ else {
+ if (blake2b_init(&S, outlen) < 0) {
+ goto fail;
+ }
+ }
+
+ if (blake2b_update(&S, in, inlen) < 0) {
+ goto fail;
+ }
+ ret = blake2b_final(&S, out, outlen);
+
+fail:
+ clear_internal_memory(&S, sizeof(S));
+ return ret;
+}
+
+/* Argon2 Team - Begin Code */
+int blake2b_long(void *pout, size_t outlen, const void *in, size_t inlen) {
+ uint8_t *out = (uint8_t *)pout;
+ blake2b_state blake_state;
+ uint8_t outlen_bytes[sizeof(uint32_t)] = { 0 };
+ int ret = -1;
+
+ if (outlen > UINT32_MAX) {
+ goto fail;
+ }
+
+ /* Ensure little-endian byte order! */
+ store32(outlen_bytes, (uint32_t)outlen);
+
+#define TRY(statement) \
+ do { \
+ ret = statement; \
+ if (ret < 0) { \
+ goto fail; \
+ } \
+ } while ((void)0, 0)
+
+ if (outlen <= BLAKE2B_OUTBYTES) {
+ TRY(blake2b_init(&blake_state, outlen));
+ TRY(blake2b_update(&blake_state, outlen_bytes, sizeof(outlen_bytes)));
+ TRY(blake2b_update(&blake_state, in, inlen));
+ TRY(blake2b_final(&blake_state, out, outlen));
+ }
+ else {
+ uint32_t toproduce;
+ uint8_t out_buffer[BLAKE2B_OUTBYTES];
+ uint8_t in_buffer[BLAKE2B_OUTBYTES];
+ TRY(blake2b_init(&blake_state, BLAKE2B_OUTBYTES));
+ TRY(blake2b_update(&blake_state, outlen_bytes, sizeof(outlen_bytes)));
+ TRY(blake2b_update(&blake_state, in, inlen));
+ TRY(blake2b_final(&blake_state, out_buffer, BLAKE2B_OUTBYTES));
+ memcpy(out, out_buffer, BLAKE2B_OUTBYTES / 2);
+ out += BLAKE2B_OUTBYTES / 2;
+ toproduce = (uint32_t)outlen - BLAKE2B_OUTBYTES / 2;
+
+ while (toproduce > BLAKE2B_OUTBYTES) {
+ memcpy(in_buffer, out_buffer, BLAKE2B_OUTBYTES);
+ TRY(blake2b(out_buffer, BLAKE2B_OUTBYTES, in_buffer,
+ BLAKE2B_OUTBYTES, NULL, 0));
+ memcpy(out, out_buffer, BLAKE2B_OUTBYTES / 2);
+ out += BLAKE2B_OUTBYTES / 2;
+ toproduce -= BLAKE2B_OUTBYTES / 2;
+ }
+
+ memcpy(in_buffer, out_buffer, BLAKE2B_OUTBYTES);
+ TRY(blake2b(out_buffer, toproduce, in_buffer, BLAKE2B_OUTBYTES, NULL,
+ 0));
+ memcpy(out, out_buffer, toproduce);
+ }
+fail:
+ clear_internal_memory(&blake_state, sizeof(blake_state));
+ return ret;
+#undef TRY
+}
+/* Argon2 Team - End Code */
+
+
+static void load_block(block *dst, const void *input) {
+ unsigned i;
+ for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) {
+ dst->v[i] = load64((const uint8_t *)input + i * sizeof(dst->v[i]));
+ }
+}
+
+
+void fill_first_blocks(uint8_t *blockhash, const argon2_instance_t *instance) {
+ uint32_t l;
+ /* Make the first and second block in each lane as G(H0||i||0) or
+ G(H0||i||1) */
+ uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE];
+ for (l = 0; l < instance->lanes; ++l) {
+
+ store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 0);
+ store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH + 4, l);
+ blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash,
+ ARGON2_PREHASH_SEED_LENGTH);
+ load_block(&instance->memory[l * instance->lane_length + 0],
+ blockhash_bytes);
+
+ store32(blockhash + ARGON2_PREHASH_DIGEST_LENGTH, 1);
+ blake2b_long(blockhash_bytes, ARGON2_BLOCK_SIZE, blockhash,
+ ARGON2_PREHASH_SEED_LENGTH);
+ load_block(&instance->memory[l * instance->lane_length + 1],
+ blockhash_bytes);
+ }
+ clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE);
+}
+
+
+
+
+int initialize(argon2_instance_t *instance, argon2_context *context) {
+ uint8_t blockhash[ARGON2_PREHASH_SEED_LENGTH];
+ int result = ARGON2_OK;
+
+ if (instance == NULL || context == NULL)
+ return ARGON2_INCORRECT_PARAMETER;
+ instance->context_ptr = context;
+
+ /* 1. Memory allocation */
+ result = allocate_memory(context, (uint8_t **)&(instance->memory),
+ instance->memory_blocks, sizeof(block));
+ if (result != ARGON2_OK) {
+ return result;
+ }
+
+ /* 2. Initial hashing */
+ /* H_0 + 8 extra bytes to produce the first blocks */
+ /* uint8_t blockhash[ARGON2_PREHASH_SEED_LENGTH]; */
+ /* Hashing all inputs */
+ initial_hash(blockhash, context, instance->type);
+ /* Zeroing 8 extra bytes */
+ clear_internal_memory(blockhash + ARGON2_PREHASH_DIGEST_LENGTH,
+ ARGON2_PREHASH_SEED_LENGTH -
+ ARGON2_PREHASH_DIGEST_LENGTH);
+
+#ifdef GENKAT
+ initial_kat(blockhash, context, instance->type);
+#endif
+
+ /* 3. Creating first blocks, we always have at least two blocks in a slice
+ */
+ fill_first_blocks(blockhash, instance);
+ /* Clearing the hash */
+ clear_internal_memory(blockhash, ARGON2_PREHASH_SEED_LENGTH);
+
+ return ARGON2_OK;
+}
+
+/*
+* Argon2 position: where we construct the block right now. Used to distribute
+* work between threads.
+*/
+typedef struct Argon2_position_t {
+ uint32_t pass;
+ uint32_t lane;
+ uint8_t slice;
+ uint32_t index;
+} argon2_position_t;
+
+/*Struct that holds the inputs for thread handling FillSegment*/
+typedef struct Argon2_thread_data {
+ argon2_instance_t *instance_ptr;
+ argon2_position_t pos;
+} argon2_thread_data;
+
+int argon2_thread_join(argon2_thread_handle_t handle) {
+#if defined(_WIN32)
+ if (WaitForSingleObject((HANDLE)handle, INFINITE) == WAIT_OBJECT_0) {
+ return CloseHandle((HANDLE)handle) != 0 ? 0 : -1;
+ }
+ return -1;
+#else
+ return pthread_join(handle, NULL);
+#endif
+}
+
+int argon2_thread_create(argon2_thread_handle_t *handle,
+ argon2_thread_func_t func, void *args) {
+ if (NULL == handle || func == NULL) {
+ return -1;
+ }
+#if defined(_WIN32)
+ *handle = _beginthreadex(NULL, 0, func, args, 0, NULL);
+ return *handle != 0 ? 0 : -1;
+#else
+ return pthread_create(handle, NULL, func, args);
+#endif
+}
+
+void init_block_value(block *b, uint8_t in) { memset(b->v, in, sizeof(b->v)); }
+
+
+
+void fill_block(__m128i *state, const block *ref_block, block *next_block,
+ int with_xor) {
+ __m128i block_XY[ARGON2_OWORDS_IN_BLOCK];
+ unsigned int i;
+
+ if (with_xor) {
+ for (i = 0; i < ARGON2_OWORDS_IN_BLOCK; i++) {
+ state[i] = _mm_xor_si128(
+ state[i], _mm_loadu_si128((const __m128i *)ref_block->v + i));
+ block_XY[i] = _mm_xor_si128(
+ state[i], _mm_loadu_si128((const __m128i *)next_block->v + i));
+ }
+ }
+ else {
+ for (i = 0; i < ARGON2_OWORDS_IN_BLOCK; i++) {
+ block_XY[i] = state[i] = _mm_xor_si128(
+ state[i], _mm_loadu_si128((const __m128i *)ref_block->v + i));
+ }
+ }
+
+ for (i = 0; i < 8; ++i) {
+ BLAKE2_ROUND(state[8 * i + 0], state[8 * i + 1], state[8 * i + 2],
+ state[8 * i + 3], state[8 * i + 4], state[8 * i + 5],
+ state[8 * i + 6], state[8 * i + 7]);
+ }
+
+ for (i = 0; i < 8; ++i) {
+ BLAKE2_ROUND(state[8 * 0 + i], state[8 * 1 + i], state[8 * 2 + i],
+ state[8 * 3 + i], state[8 * 4 + i], state[8 * 5 + i],
+ state[8 * 6 + i], state[8 * 7 + i]);
+ }
+
+ for (i = 0; i < ARGON2_OWORDS_IN_BLOCK; i++) {
+ state[i] = _mm_xor_si128(state[i], block_XY[i]);
+ _mm_storeu_si128((__m128i *)next_block->v + i, state[i]);
+ }
+}
+
+static void next_addresses(block *address_block, block *input_block) {
+ /*Temporary zero-initialized blocks*/
+ __m128i zero_block[ARGON2_OWORDS_IN_BLOCK];
+ __m128i zero2_block[ARGON2_OWORDS_IN_BLOCK];
+
+ memset(zero_block, 0, sizeof(zero_block));
+ memset(zero2_block, 0, sizeof(zero2_block));
+
+ /*Increasing index counter*/
+ input_block->v[6]++;
+
+ /*First iteration of G*/
+ fill_block(zero_block, input_block, address_block, 0);
+
+ /*Second iteration of G*/
+ fill_block(zero2_block, address_block, address_block, 0);
+}
+
+
+uint32_t index_alpha(const argon2_instance_t *instance,
+ const argon2_position_t *position, uint32_t pseudo_rand,
+ int same_lane) {
+ /*
+ * Pass 0:
+ * This lane : all already finished segments plus already constructed
+ * blocks in this segment
+ * Other lanes : all already finished segments
+ * Pass 1+:
+ * This lane : (SYNC_POINTS - 1) last segments plus already constructed
+ * blocks in this segment
+ * Other lanes : (SYNC_POINTS - 1) last segments
+ */
+ uint32_t reference_area_size;
+ uint64_t relative_position;
+ uint32_t start_position, absolute_position;
+
+ if (0 == position->pass) {
+ /* First pass */
+ if (0 == position->slice) {
+ /* First slice */
+ reference_area_size =
+ position->index - 1; /* all but the previous */
+ }
+ else {
+ if (same_lane) {
+ /* The same lane => add current segment */
+ reference_area_size =
+ position->slice * instance->segment_length +
+ position->index - 1;
+ }
+ else {
+ reference_area_size =
+ position->slice * instance->segment_length +
+ ((position->index == 0) ? (-1) : 0);
+ }
+ }
+ }
+ else {
+ /* Second pass */
+ if (same_lane) {
+ reference_area_size = instance->lane_length -
+ instance->segment_length + position->index -
+ 1;
+ }
+ else {
+ reference_area_size = instance->lane_length -
+ instance->segment_length +
+ ((position->index == 0) ? (-1) : 0);
+ }
+ }
+
+ /* 1.2.4. Mapping pseudo_rand to 0.. and produce
+ * relative position */
+ relative_position = pseudo_rand;
+ relative_position = relative_position * relative_position >> 32;
+ relative_position = reference_area_size - 1 -
+ (reference_area_size * relative_position >> 32);
+
+ /* 1.2.5 Computing starting position */
+ start_position = 0;
+
+ if (0 != position->pass) {
+ start_position = (position->slice == ARGON2_SYNC_POINTS - 1)
+ ? 0
+ : (position->slice + 1) * instance->segment_length;
+ }
+
+ /* 1.2.6. Computing absolute position */
+ absolute_position = (start_position + relative_position) %
+ instance->lane_length; /* absolute position */
+ return absolute_position;
+}
+
+void fill_segment(const argon2_instance_t *instance,
+ argon2_position_t position) {
+ block *ref_block = NULL, *curr_block = NULL;
+ block address_block, input_block;
+ uint64_t pseudo_rand, ref_index, ref_lane;
+ uint32_t prev_offset, curr_offset;
+ uint32_t starting_index, i;
+ __m128i state[64];
+ int data_independent_addressing;
+
+ if (instance == NULL) {
+ return;
+ }
+
+ data_independent_addressing =
+ (instance->type == Argon2_i) ||
+ (instance->type == Argon2_id && (position.pass == 0) &&
+ (position.slice < ARGON2_SYNC_POINTS / 2));
+
+ if (data_independent_addressing) {
+ init_block_value(&input_block, 0);
+
+ input_block.v[0] = position.pass;
+ input_block.v[1] = position.lane;
+ input_block.v[2] = position.slice;
+ input_block.v[3] = instance->memory_blocks;
+ input_block.v[4] = instance->passes;
+ input_block.v[5] = instance->type;
+ }
+
+ starting_index = 0;
+
+ if ((0 == position.pass) && (0 == position.slice)) {
+ starting_index = 2; /* we have already generated the first two blocks */
+
+ /* Don't forget to generate the first block of addresses: */
+ if (data_independent_addressing) {
+ next_addresses(&address_block, &input_block);
+ }
+ }
+
+ /* Offset of the current block */
+ curr_offset = position.lane * instance->lane_length +
+ position.slice * instance->segment_length + starting_index;
+
+ if (0 == curr_offset % instance->lane_length) {
+ /* Last block in this lane */
+ prev_offset = curr_offset + instance->lane_length - 1;
+ }
+ else {
+ /* Previous block */
+ prev_offset = curr_offset - 1;
+ }
+
+ memcpy(state, ((instance->memory + prev_offset)->v), ARGON2_BLOCK_SIZE);
+
+ for (i = starting_index; i < instance->segment_length;
+ ++i, ++curr_offset, ++prev_offset) {
+ /*1.1 Rotating prev_offset if needed */
+ if (curr_offset % instance->lane_length == 1) {
+ prev_offset = curr_offset - 1;
+ }
+
+ /* 1.2 Computing the index of the reference block */
+ /* 1.2.1 Taking pseudo-random value from the previous block */
+ if (data_independent_addressing) {
+ if (i % ARGON2_ADDRESSES_IN_BLOCK == 0) {
+ next_addresses(&address_block, &input_block);
+ }
+ pseudo_rand = address_block.v[i % ARGON2_ADDRESSES_IN_BLOCK];
+ }
+ else {
+ pseudo_rand = instance->memory[prev_offset].v[0];
+ }
+
+ /* 1.2.2 Computing the lane of the reference block */
+ ref_lane = ((pseudo_rand >> 32)) % instance->lanes;
+
+ if ((position.pass == 0) && (position.slice == 0)) {
+ /* Can not reference other lanes yet */
+ ref_lane = position.lane;
+ }
+
+ /* 1.2.3 Computing the number of possible reference block within the
+ * lane.
+ */
+ position.index = i;
+ ref_index = index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF,
+ ref_lane == position.lane);
+
+ /* 2 Creating a new block */
+ ref_block =
+ instance->memory + instance->lane_length * ref_lane + ref_index;
+ curr_block = instance->memory + curr_offset;
+ if (ARGON2_VERSION_10 == instance->version) {
+ /* version 1.2.1 and earlier: overwrite, not XOR */
+ fill_block(state, ref_block, curr_block, 0);
+ }
+ else {
+ if (0 == position.pass) {
+ fill_block(state, ref_block, curr_block, 0);
+ }
+ else {
+ fill_block(state, ref_block, curr_block, 1);
+ }
+ }
+ }
+}
+
+void argon2_thread_exit(void) {
+#if defined(_WIN32)
+ _endthreadex(0);
+#else
+ pthread_exit(NULL);
+#endif
+}
+
+#ifdef _WIN32
+static unsigned __stdcall fill_segment_thr(void *thread_data)
+#else
+static void *fill_segment_thr(void *thread_data)
+#endif
+{
+ argon2_thread_data *my_data = (argon2_thread_data*)thread_data;
+ fill_segment(my_data->instance_ptr, my_data->pos);
+ argon2_thread_exit();
+ return 0;
+}
+
+
+int fill_memory_blocks(argon2_instance_t *instance) {
+ uint32_t r, s;
+ argon2_thread_handle_t *thread = NULL;
+ argon2_thread_data *thr_data = NULL;
+ int rc = ARGON2_OK;
+
+ if (instance == NULL || instance->lanes == 0) {
+ rc = ARGON2_THREAD_FAIL;
+ goto fail;
+ }
+
+ /* 1. Allocating space for threads */
+ thread = (argon2_thread_handle_t*)calloc(instance->lanes, sizeof(argon2_thread_handle_t));
+ if (thread == NULL) {
+ rc = ARGON2_MEMORY_ALLOCATION_ERROR;
+ goto fail;
+ }
+
+ thr_data = (argon2_thread_data*)calloc(instance->lanes, sizeof(argon2_thread_data));
+ if (thr_data == NULL) {
+ rc = ARGON2_MEMORY_ALLOCATION_ERROR;
+ goto fail;
+ }
+
+ for (r = 0; r < instance->passes; ++r) {
+ for (s = 0; s < ARGON2_SYNC_POINTS; ++s) {
+ uint32_t l;
+
+ /* 2. Calling threads */
+ for (l = 0; l < instance->lanes; ++l) {
+ argon2_position_t position;
+
+ /* 2.1 Join a thread if limit is exceeded */
+ if (l >= instance->threads) {
+ if (argon2_thread_join(thread[l - instance->threads])) {
+ rc = ARGON2_THREAD_FAIL;
+ goto fail;
+ }
+ }
+
+ /* 2.2 Create thread */
+ position.pass = r;
+ position.lane = l;
+ position.slice = (uint8_t)s;
+ position.index = 0;
+ thr_data[l].instance_ptr =
+ instance; /* preparing the thread input */
+ memcpy(&(thr_data[l].pos), &position,
+ sizeof(argon2_position_t));
+ if (argon2_thread_create(&thread[l], &fill_segment_thr,
+ (void *)&thr_data[l])) {
+ rc = ARGON2_THREAD_FAIL;
+ goto fail;
+ }
+
+ /* fill_segment(instance, position); */
+ /*Non-thread equivalent of the lines above */
+ }
+
+ /* 3. Joining remaining threads */
+ for (l = instance->lanes - instance->threads; l < instance->lanes;
+ ++l) {
+ if (argon2_thread_join(thread[l])) {
+ rc = ARGON2_THREAD_FAIL;
+ goto fail;
+ }
+ }
+ }
+
+
+ //internal_kat(instance, r); /* Print all memory blocks */
+
+
+ if (instance != NULL) {
+ uint32_t i, j;
+ std::vector leaves;
+
+ for (i = 0; i < instance->memory_blocks; ++i) {
+ uint32_t how_many_words =
+ (instance->memory_blocks > ARGON2_QWORDS_IN_BLOCK)
+ ? 1
+ : ARGON2_QWORDS_IN_BLOCK;
+
+ for (j = 0; j < how_many_words; ++j) {
+ printf("Block %.4u [%3u]: %016" PRIx64 "\n", i, j, instance->memory[i].v[j]);
+
+ char temp[16];
+ sprintf(temp, "%z", instance->memory[i].v[j]);
+
+ uint256 rv;
+ rv.SetHex(temp);
+ leaves.push_back(rv);
+ }
+
+
+ }
+
+ uint256 resultMerkelRoot = ComputeMerkleRoot(leaves);
+ std::cout << resultMerkelRoot.GetHex() << std::endl;
+ }
+
+ }
+
+fail:
+ if (thread != NULL) {
+ free(thread);
+ }
+ if (thr_data != NULL) {
+ free(thr_data);
+ }
+ return rc;
+}
+
+void xor_block(block *dst, const block *src) {
+ int i;
+ for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) {
+ dst->v[i] ^= src->v[i];
+ }
+}
+
+
+void copy_block(block *dst, const block *src) {
+ memcpy(dst->v, src->v, sizeof(uint64_t) * ARGON2_QWORDS_IN_BLOCK);
+}
+
+
+static void store_block(void *output, const block *src) {
+ unsigned i;
+ for (i = 0; i < ARGON2_QWORDS_IN_BLOCK; ++i) {
+ store64((uint8_t *)output + i * sizeof(src->v[i]), src->v[i]);
+ }
+}
+
+void free_memory(const argon2_context *context, uint8_t *memory,
+ size_t num, size_t size) {
+ size_t memory_size = num*size;
+ clear_internal_memory(memory, memory_size);
+ if (context->free_cbk) {
+ (context->free_cbk)(memory, memory_size);
+ }
+ else {
+ free(memory);
+ }
+}
+
+void finalize(const argon2_context *context, argon2_instance_t *instance) {
+ if (context != NULL && instance != NULL) {
+ block blockhash;
+ uint32_t l;
+
+ copy_block(&blockhash, instance->memory + instance->lane_length - 1);
+
+ /* XOR the last blocks */
+ for (l = 1; l < instance->lanes; ++l) {
+ uint32_t last_block_in_lane =
+ l * instance->lane_length + (instance->lane_length - 1);
+ xor_block(&blockhash, instance->memory + last_block_in_lane);
+ }
+
+ /* Hash the result */
+ {
+ uint8_t blockhash_bytes[ARGON2_BLOCK_SIZE];
+ store_block(blockhash_bytes, &blockhash);
+ blake2b_long(context->out, context->outlen, blockhash_bytes,
+ ARGON2_BLOCK_SIZE);
+ /* clear blockhash and blockhash_bytes */
+ clear_internal_memory(blockhash.v, ARGON2_BLOCK_SIZE);
+ clear_internal_memory(blockhash_bytes, ARGON2_BLOCK_SIZE);
+ }
+
+#ifdef GENKAT
+ print_tag(context->out, context->outlen);
+#endif
+
+ free_memory(context, (uint8_t *)instance->memory,
+ instance->memory_blocks, sizeof(block));
+ }
+}
+
+int argon2_ctx(argon2_context *context, argon2_type type) {
+ /* 1. Validate all inputs */
+ int result = validate_inputs(context);
+ uint32_t memory_blocks, segment_length;
+ argon2_instance_t instance;
+
+ if (ARGON2_OK != result) {
+ return result;
+ }
+
+ if (Argon2_d != type && Argon2_i != type && Argon2_id != type) {
+ return ARGON2_INCORRECT_TYPE;
+ }
+
+ /* 2. Align memory size */
+ /* Minimum memory_blocks = 8L blocks, where L is the number of lanes */
+ memory_blocks = context->m_cost;
+
+ if (memory_blocks < 2 * ARGON2_SYNC_POINTS * context->lanes) {
+ memory_blocks = 2 * ARGON2_SYNC_POINTS * context->lanes;
+ }
+
+ segment_length = memory_blocks / (context->lanes * ARGON2_SYNC_POINTS);
+ /* Ensure that all segments have equal length */
+ memory_blocks = segment_length * (context->lanes * ARGON2_SYNC_POINTS);
+
+ instance.version = context->version;
+ instance.memory = NULL;
+ instance.passes = context->t_cost;
+ instance.memory_blocks = memory_blocks;
+ instance.segment_length = segment_length;
+ instance.lane_length = segment_length * ARGON2_SYNC_POINTS;
+ instance.lanes = context->lanes;
+ instance.threads = context->threads;
+ instance.type = type;
+
+ /* 3. Initialization: Hashing inputs, allocating memory, filling first
+ * blocks
+ */
+ result = initialize(&instance, context);
+
+ if (ARGON2_OK != result) {
+ return result;
+ }
+
+ /* 4. Filling memory */
+ result = fill_memory_blocks(&instance);
+
+ if (ARGON2_OK != result) {
+ return result;
+ }
+ /* 5. Finalization */
+ finalize(context, &instance);
+
+ return ARGON2_OK;
+}
+
+
+static void generate_testvectors(argon2_type type, const uint32_t version) {
+
+#define TEST_OUTLEN 32
+#define TEST_PWDLEN 32
+#define TEST_SALTLEN 16
+#define TEST_SECRETLEN 8
+#define TEST_ADLEN 12
+ argon2_context context;
+
+ unsigned char out[TEST_OUTLEN];
+ unsigned char pwd[TEST_PWDLEN];
+ unsigned char salt[TEST_SALTLEN];
+ unsigned char secret[TEST_SECRETLEN];
+ unsigned char ad[TEST_ADLEN];
+ const allocate_fptr myown_allocator = NULL;
+ const deallocate_fptr myown_deallocator = NULL;
+
+ unsigned t_cost = 1;
+ unsigned m_cost = 2097152;
+ unsigned lanes = 4;
+
+ memset(pwd, 1, TEST_OUTLEN);
+ memset(salt, 2, TEST_SALTLEN);
+ memset(secret, 3, TEST_SECRETLEN);
+ memset(ad, 4, TEST_ADLEN);
+
+ context.out = out;
+ context.outlen = TEST_OUTLEN;
+ context.version = version;
+ context.pwd = pwd;
+ context.pwdlen = TEST_PWDLEN;
+ context.salt = salt;
+ context.saltlen = TEST_SALTLEN;
+ context.secret = secret;
+ context.secretlen = TEST_SECRETLEN;
+ context.ad = ad;
+ context.adlen = TEST_ADLEN;
+ context.t_cost = t_cost;
+ context.m_cost = m_cost;
+ context.lanes = lanes;
+ context.threads = lanes;
+ context.allocate_cbk = myown_allocator;
+ context.free_cbk = myown_deallocator;
+ context.flags = ARGON2_DEFAULT_FLAGS;
+
+#undef TEST_OUTLEN
+#undef TEST_PWDLEN
+#undef TEST_SALTLEN
+#undef TEST_SECRETLEN
+#undef TEST_ADLEN
+
+ argon2_ctx(&context, type);
+}
+
+
+
+int main(int argc, char *argv[]) {
+ /* Get and check Argon2 type */
+ const char *type_str = (argc > 1) ? argv[1] : "d";
+ argon2_type type = Argon2_i;
+ uint32_t version = ARGON2_VERSION_NUMBER;
+ if (!strcmp(type_str, "d")) {
+ type = Argon2_d;
+ }
+ else if (!strcmp(type_str, "i")) {
+ type = Argon2_i;
+ }
+ else if (!strcmp(type_str, "id")) {
+ type = Argon2_id;
+ }
+ else {
+ fatal("wrong Argon2 type");
+ }
+
+ /* Get and check Argon2 version number */
+ if (argc > 2) {
+ version = strtoul(argv[2], NULL, 10);
+ }
+ if (ARGON2_VERSION_10 != version && ARGON2_VERSION_NUMBER != version) {
+ fatal("wrong Argon2 version number");
+ }
+
+ generate_testvectors(type, version);
+ return ARGON2_OK;
+}
\ No newline at end of file
diff --git a/Project1/merkle.cpp b/Project1/merkle.cpp
new file mode 100644
index 0000000..9d1a675
--- /dev/null
+++ b/Project1/merkle.cpp
@@ -0,0 +1,190 @@
+// Copyright (c) 2015 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include "merkle.h"
+#include "hash.h"
+#include "utilstrencodings.h"
+
+/* WARNING! If you're reading this because you're learning about crypto
+and/or designing a new system that will use merkle trees, keep in mind
+that the following merkle tree algorithm has a serious flaw related to
+duplicate txids, resulting in a vulnerability (CVE-2012-2459).
+
+The reason is that if the number of hashes in the list at a given time
+is odd, the last one is duplicated before computing the next level (which
+is unusual in Merkle trees). This results in certain sequences of
+transactions leading to the same merkle root. For example, these two
+trees:
+
+A A
+/ \ / \
+B C B C
+/ \ | / \ / \
+D E F D E F F
+/ \ / \ / \ / \ / \ / \ / \
+1 2 3 4 5 6 1 2 3 4 5 6 5 6
+
+for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
+6 are repeated) result in the same root hash A (because the hash of both
+of (F) and (F,F) is C).
+
+The vulnerability results from being able to send a block with such a
+transaction list, with the same merkle root, and the same block hash as
+the original without duplication, resulting in failed validation. If the
+receiving node proceeds to mark that block as permanently invalid
+however, it will fail to accept further unmodified (and thus potentially
+valid) versions of the same block. We defend against this by detecting
+the case where we would hash two identical hashes at the end of the list
+together, and treating that identically to the block having an invalid
+merkle root. Assuming no double-SHA256 collisions, this will detect all
+known ways of changing the transactions without affecting the merkle
+root.
+*/
+
+/* This implements a constant-space merkle root/path calculator, limited to 2^32 leaves. */
+static void MerkleComputation(const std::vector& leaves, uint256* proot, bool* pmutated, uint32_t branchpos, std::vector* pbranch) {
+ if (pbranch) pbranch->clear();
+ if (leaves.size() == 0) {
+ if (pmutated) *pmutated = false;
+ if (proot) *proot = uint256();
+ return;
+ }
+ bool mutated = false;
+ // count is the number of leaves processed so far.
+ uint32_t count = 0;
+ // inner is an array of eagerly computed subtree hashes, indexed by tree
+ // level (0 being the leaves).
+ // For example, when count is 25 (11001 in binary), inner[4] is the hash of
+ // the first 16 leaves, inner[3] of the next 8 leaves, and inner[0] equal to
+ // the last leaf. The other inner entries are undefined.
+ uint256 inner[32];
+ // Which position in inner is a hash that depends on the matching leaf.
+ int matchlevel = -1;
+ // First process all leaves into 'inner' values.
+ while (count < leaves.size()) {
+ uint256 h = leaves[count];
+ bool matchh = count == branchpos;
+ count++;
+ int level;
+ // For each of the lower bits in count that are 0, do 1 step. Each
+ // corresponds to an inner value that existed before processing the
+ // current leaf, and each needs a hash to combine it.
+ for (level = 0; !(count & (((uint32_t)1) << level)); level++) {
+ if (pbranch) {
+ if (matchh) {
+ pbranch->push_back(inner[level]);
+ }
+ else if (matchlevel == level) {
+ pbranch->push_back(h);
+ matchh = true;
+ }
+ }
+ mutated |= (inner[level] == h);
+ CHash256().Write(inner[level].begin(), 32).Write(h.begin(), 32).Finalize(h.begin());
+ }
+ // Store the resulting hash at inner position level.
+ inner[level] = h;
+ if (matchh) {
+ matchlevel = level;
+ }
+ }
+ // Do a final 'sweep' over the rightmost branch of the tree to process
+ // odd levels, and reduce everything to a single top value.
+ // Level is the level (counted from the bottom) up to which we've sweeped.
+ int level = 0;
+ // As long as bit number level in count is zero, skip it. It means there
+ // is nothing left at this level.
+ while (!(count & (((uint32_t)1) << level))) {
+ level++;
+ }
+ uint256 h = inner[level];
+ bool matchh = matchlevel == level;
+ while (count != (((uint32_t)1) << level)) {
+ // If we reach this point, h is an inner value that is not the top.
+ // We combine it with itself (Bitcoin's special rule for odd levels in
+ // the tree) to produce a higher level one.
+ if (pbranch && matchh) {
+ pbranch->push_back(h);
+ }
+ CHash256().Write(h.begin(), 32).Write(h.begin(), 32).Finalize(h.begin());
+ // Increment count to the value it would have if two entries at this
+ // level had existed.
+ count += (((uint32_t)1) << level);
+ level++;
+ // And propagate the result upwards accordingly.
+ while (!(count & (((uint32_t)1) << level))) {
+ if (pbranch) {
+ if (matchh) {
+ pbranch->push_back(inner[level]);
+ }
+ else if (matchlevel == level) {
+ pbranch->push_back(h);
+ matchh = true;
+ }
+ }
+ CHash256().Write(inner[level].begin(), 32).Write(h.begin(), 32).Finalize(h.begin());
+ level++;
+ }
+ }
+ // Return result.
+ if (pmutated) *pmutated = mutated;
+ if (proot) *proot = h;
+}
+
+uint256 ComputeMerkleRoot(const std::vector& leaves, bool* mutated) {
+ uint256 hash;
+ MerkleComputation(leaves, &hash, mutated, -1, NULL);
+ return hash;
+}
+
+std::vector ComputeMerkleBranch(const std::vector& leaves, uint32_t position) {
+ std::vector ret;
+ MerkleComputation(leaves, NULL, NULL, position, &ret);
+ return ret;
+}
+
+uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vector& vMerkleBranch, uint32_t nIndex) {
+ uint256 hash = leaf;
+ for (std::vector::const_iterator it = vMerkleBranch.begin(); it != vMerkleBranch.end(); ++it) {
+ if (nIndex & 1) {
+ hash = Hash(BEGIN(*it), END(*it), BEGIN(hash), END(hash));
+ }
+ else {
+ hash = Hash(BEGIN(hash), END(hash), BEGIN(*it), END(*it));
+ }
+ nIndex >>= 1;
+ }
+ return hash;
+}
+
+uint256 BlockMerkleRoot(const CBlock& block, bool* mutated)
+{
+ std::vector leaves;
+ leaves.resize(block.vtx.size());
+ for (size_t s = 0; s < block.vtx.size(); s++) {
+ leaves[s] = block.vtx[s].GetHash();
+ }
+ return ComputeMerkleRoot(leaves, mutated);
+}
+
+uint256 BlockWitnessMerkleRoot(const CBlock& block, bool* mutated)
+{
+ std::vector leaves;
+ leaves.resize(block.vtx.size());
+ leaves[0].SetNull(); // The witness hash of the coinbase is 0.
+ for (size_t s = 1; s < block.vtx.size(); s++) {
+ leaves[s] = block.vtx[s].GetWitnessHash();
+ }
+ return ComputeMerkleRoot(leaves, mutated);
+}
+
+std::vector BlockMerkleBranch(const CBlock& block, uint32_t position)
+{
+ std::vector leaves;
+ leaves.resize(block.vtx.size());
+ for (size_t s = 0; s < block.vtx.size(); s++) {
+ leaves[s] = block.vtx[s].GetHash();
+ }
+ return ComputeMerkleBranch(leaves, position);
+}
\ No newline at end of file
diff --git a/Project1/merkle.h b/Project1/merkle.h
new file mode 100644
index 0000000..827a8dc
--- /dev/null
+++ b/Project1/merkle.h
@@ -0,0 +1,38 @@
+// Copyright (c) 2015 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_MERKLE
+#define BITCOIN_MERKLE
+
+#include
+#include
+
+#include "transaction.h"
+#include "block.h"
+#include "uint256.h"
+
+uint256 ComputeMerkleRoot(const std::vector& leaves, bool* mutated = NULL);
+std::vector ComputeMerkleBranch(const std::vector& leaves, uint32_t position);
+uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vector& branch, uint32_t position);
+
+/*
+* Compute the Merkle root of the transactions in a block.
+* *mutated is set to true if a duplicated subtree was found.
+*/
+uint256 BlockMerkleRoot(const CBlock& block, bool* mutated = NULL);
+
+/*
+* Compute the Merkle root of the witness transactions in a block.
+* *mutated is set to true if a duplicated subtree was found.
+*/
+uint256 BlockWitnessMerkleRoot(const CBlock& block, bool* mutated = NULL);
+
+/*
+* Compute the Merkle branch for the tree of transactions in a block, for a
+* given position.
+* This can be verified using ComputeMerkleRootFromBranch.
+*/
+std::vector BlockMerkleBranch(const CBlock& block, uint32_t position);
+
+#endif
\ No newline at end of file
diff --git a/Project1/prevector.h b/Project1/prevector.h
new file mode 100644
index 0000000..aacfe91
--- /dev/null
+++ b/Project1/prevector.h
@@ -0,0 +1,493 @@
+// Copyright (c) 2015 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef _BITCOIN_PREVECTOR_H_
+#define _BITCOIN_PREVECTOR_H_
+
+#include
+#include
+#include
+
+#include
+
+#pragma pack(push, 1)
+/** Implements a drop-in replacement for std::vector which stores up to N
+* elements directly (without heap allocation). The types Size and Diff are
+* used to store element counts, and can be any unsigned + signed type.
+*
+* Storage layout is either:
+* - Direct allocation:
+* - Size _size: the number of used elements (between 0 and N)
+* - T direct[N]: an array of N elements of type T
+* (only the first _size are initialized).
+* - Indirect allocation:
+* - Size _size: the number of used elements plus N + 1
+* - Size capacity: the number of allocated elements
+* - T* indirect: a pointer to an array of capacity elements of type T
+* (only the first _size are initialized).
+*
+* The data type T must be movable by memmove/realloc(). Once we switch to C++,
+* move constructors can be used instead.
+*/
+template
+class prevector {
+public:
+ typedef Size size_type;
+ typedef Diff difference_type;
+ typedef T value_type;
+ typedef value_type& reference;
+ typedef const value_type& const_reference;
+ typedef value_type* pointer;
+ typedef const value_type* const_pointer;
+
+ class iterator {
+ T* ptr;
+ public:
+ typedef Diff difference_type;
+ typedef T value_type;
+ typedef T* pointer;
+ typedef T& reference;
+ typedef std::random_access_iterator_tag iterator_category;
+ iterator(T* ptr_) : ptr(ptr_) {}
+ T& operator*() const { return *ptr; }
+ T* operator->() const { return ptr; }
+ T& operator[](size_type pos) { return ptr[pos]; }
+ const T& operator[](size_type pos) const { return ptr[pos]; }
+ iterator& operator++() { ptr++; return *this; }
+ iterator& operator--() { ptr--; return *this; }
+ iterator operator++(int) { iterator copy(*this); ++(*this); return copy; }
+ iterator operator--(int) { iterator copy(*this); --(*this); return copy; }
+ difference_type friend operator-(iterator a, iterator b) { return (&(*a) - &(*b)); }
+ iterator operator+(size_type n) { return iterator(ptr + n); }
+ iterator& operator+=(size_type n) { ptr += n; return *this; }
+ iterator operator-(size_type n) { return iterator(ptr - n); }
+ iterator& operator-=(size_type n) { ptr -= n; return *this; }
+ bool operator==(iterator x) const { return ptr == x.ptr; }
+ bool operator!=(iterator x) const { return ptr != x.ptr; }
+ bool operator>=(iterator x) const { return ptr >= x.ptr; }
+ bool operator<=(iterator x) const { return ptr <= x.ptr; }
+ bool operator>(iterator x) const { return ptr > x.ptr; }
+ bool operator<(iterator x) const { return ptr < x.ptr; }
+ };
+
+ class reverse_iterator {
+ T* ptr;
+ public:
+ typedef Diff difference_type;
+ typedef T value_type;
+ typedef T* pointer;
+ typedef T& reference;
+ typedef std::bidirectional_iterator_tag iterator_category;
+ reverse_iterator(T* ptr_) : ptr(ptr_) {}
+ T& operator*() { return *ptr; }
+ const T& operator*() const { return *ptr; }
+ T* operator->() { return ptr; }
+ const T* operator->() const { return ptr; }
+ reverse_iterator& operator--() { ptr++; return *this; }
+ reverse_iterator& operator++() { ptr--; return *this; }
+ reverse_iterator operator++(int) { reverse_iterator copy(*this); ++(*this); return copy; }
+ reverse_iterator operator--(int) { reverse_iterator copy(*this); --(*this); return copy; }
+ bool operator==(reverse_iterator x) const { return ptr == x.ptr; }
+ bool operator!=(reverse_iterator x) const { return ptr != x.ptr; }
+ };
+
+ class const_iterator {
+ const T* ptr;
+ public:
+ typedef Diff difference_type;
+ typedef const T value_type;
+ typedef const T* pointer;
+ typedef const T& reference;
+ typedef std::random_access_iterator_tag iterator_category;
+ const_iterator(const T* ptr_) : ptr(ptr_) {}
+ const_iterator(iterator x) : ptr(&(*x)) {}
+ const T& operator*() const { return *ptr; }
+ const T* operator->() const { return ptr; }
+ const T& operator[](size_type pos) const { return ptr[pos]; }
+ const_iterator& operator++() { ptr++; return *this; }
+ const_iterator& operator--() { ptr--; return *this; }
+ const_iterator operator++(int) { const_iterator copy(*this); ++(*this); return copy; }
+ const_iterator operator--(int) { const_iterator copy(*this); --(*this); return copy; }
+ difference_type friend operator-(const_iterator a, const_iterator b) { return (&(*a) - &(*b)); }
+ const_iterator operator+(size_type n) { return const_iterator(ptr + n); }
+ const_iterator& operator+=(size_type n) { ptr += n; return *this; }
+ const_iterator operator-(size_type n) { return const_iterator(ptr - n); }
+ const_iterator& operator-=(size_type n) { ptr -= n; return *this; }
+ bool operator==(const_iterator x) const { return ptr == x.ptr; }
+ bool operator!=(const_iterator x) const { return ptr != x.ptr; }
+ bool operator>=(const_iterator x) const { return ptr >= x.ptr; }
+ bool operator<=(const_iterator x) const { return ptr <= x.ptr; }
+ bool operator>(const_iterator x) const { return ptr > x.ptr; }
+ bool operator<(const_iterator x) const { return ptr < x.ptr; }
+ };
+
+ class const_reverse_iterator {
+ const T* ptr;
+ public:
+ typedef Diff difference_type;
+ typedef const T value_type;
+ typedef const T* pointer;
+ typedef const T& reference;
+ typedef std::bidirectional_iterator_tag iterator_category;
+ const_reverse_iterator(T* ptr_) : ptr(ptr_) {}
+ const_reverse_iterator(reverse_iterator x) : ptr(&(*x)) {}
+ const T& operator*() const { return *ptr; }
+ const T* operator->() const { return ptr; }
+ const_reverse_iterator& operator--() { ptr++; return *this; }
+ const_reverse_iterator& operator++() { ptr--; return *this; }
+ const_reverse_iterator operator++(int) { const_reverse_iterator copy(*this); ++(*this); return copy; }
+ const_reverse_iterator operator--(int) { const_reverse_iterator copy(*this); --(*this); return copy; }
+ bool operator==(const_reverse_iterator x) const { return ptr == x.ptr; }
+ bool operator!=(const_reverse_iterator x) const { return ptr != x.ptr; }
+ };
+
+private:
+ size_type _size;
+ union direct_or_indirect {
+ char direct[sizeof(T) * N];
+ struct {
+ size_type capacity;
+ char* indirect;
+ };
+ } _union;
+
+ T* direct_ptr(difference_type pos) { return reinterpret_cast(_union.direct) + pos; }
+ const T* direct_ptr(difference_type pos) const { return reinterpret_cast(_union.direct) + pos; }
+ T* indirect_ptr(difference_type pos) { return reinterpret_cast(_union.indirect) + pos; }
+ const T* indirect_ptr(difference_type pos) const { return reinterpret_cast(_union.indirect) + pos; }
+ bool is_direct() const { return _size <= N; }
+
+ void change_capacity(size_type new_capacity) {
+ if (new_capacity <= N) {
+ if (!is_direct()) {
+ T* indirect = indirect_ptr(0);
+ T* src = indirect;
+ T* dst = direct_ptr(0);
+ memcpy(dst, src, size() * sizeof(T));
+ free(indirect);
+ _size -= N + 1;
+ }
+ }
+ else {
+ if (!is_direct()) {
+ _union.indirect = static_cast(realloc(_union.indirect, ((size_t)sizeof(T)) * new_capacity));
+ _union.capacity = new_capacity;
+ }
+ else {
+ char* new_indirect = static_cast(malloc(((size_t)sizeof(T)) * new_capacity));
+ T* src = direct_ptr(0);
+ T* dst = reinterpret_cast(new_indirect);
+ memcpy(dst, src, size() * sizeof(T));
+ _union.indirect = new_indirect;
+ _union.capacity = new_capacity;
+ _size += N + 1;
+ }
+ }
+ }
+
+ T* item_ptr(difference_type pos) { return is_direct() ? direct_ptr(pos) : indirect_ptr(pos); }
+ const T* item_ptr(difference_type pos) const { return is_direct() ? direct_ptr(pos) : indirect_ptr(pos); }
+
+public:
+ void assign(size_type n, const T& val) {
+ clear();
+ if (capacity() < n) {
+ change_capacity(n);
+ }
+ while (size() < n) {
+ _size++;
+ new(static_cast(item_ptr(size() - 1))) T(val);
+ }
+ }
+
+ template
+ void assign(InputIterator first, InputIterator last) {
+ size_type n = last - first;
+ clear();
+ if (capacity() < n) {
+ change_capacity(n);
+ }
+ while (first != last) {
+ _size++;
+ new(static_cast(item_ptr(size() - 1))) T(*first);
+ ++first;
+ }
+ }
+
+ prevector() : _size(0) {}
+
+ explicit prevector(size_type n) : _size(0) {
+ resize(n);
+ }
+
+ explicit prevector(size_type n, const T& val = T()) : _size(0) {
+ change_capacity(n);
+ while (size() < n) {
+ _size++;
+ new(static_cast(item_ptr(size() - 1))) T(val);
+ }
+ }
+
+ template
+ prevector(InputIterator first, InputIterator last) : _size(0) {
+ size_type n = last - first;
+ change_capacity(n);
+ while (first != last) {
+ _size++;
+ new(static_cast(item_ptr(size() - 1))) T(*first);
+ ++first;
+ }
+ }
+
+ prevector(const prevector& other) : _size(0) {
+ change_capacity(other.size());
+ const_iterator it = other.begin();
+ while (it != other.end()) {
+ _size++;
+ new(static_cast(item_ptr(size() - 1))) T(*it);
+ ++it;
+ }
+ }
+
+ prevector& operator=(const prevector& other) {
+ if (&other == this) {
+ return *this;
+ }
+ resize(0);
+ change_capacity(other.size());
+ const_iterator it = other.begin();
+ while (it != other.end()) {
+ _size++;
+ new(static_cast(item_ptr(size() - 1))) T(*it);
+ ++it;
+ }
+ return *this;
+ }
+
+ size_type size() const {
+ return is_direct() ? _size : _size - N - 1;
+ }
+
+ bool empty() const {
+ return size() == 0;
+ }
+
+ iterator begin() { return iterator(item_ptr(0)); }
+ const_iterator begin() const { return const_iterator(item_ptr(0)); }
+ iterator end() { return iterator(item_ptr(size())); }
+ const_iterator end() const { return const_iterator(item_ptr(size())); }
+
+ reverse_iterator rbegin() { return reverse_iterator(item_ptr(size() - 1)); }
+ const_reverse_iterator rbegin() const { return const_reverse_iterator(item_ptr(size() - 1)); }
+ reverse_iterator rend() { return reverse_iterator(item_ptr(-1)); }
+ const_reverse_iterator rend() const { return const_reverse_iterator(item_ptr(-1)); }
+
+ size_t capacity() const {
+ if (is_direct()) {
+ return N;
+ }
+ else {
+ return _union.capacity;
+ }
+ }
+
+ T& operator[](size_type pos) {
+ return *item_ptr(pos);
+ }
+
+ const T& operator[](size_type pos) const {
+ return *item_ptr(pos);
+ }
+
+ void resize(size_type new_size) {
+ if (size() > new_size) {
+ erase(item_ptr(new_size), end());
+ }
+ if (new_size > capacity()) {
+ change_capacity(new_size);
+ }
+ while (size() < new_size) {
+ _size++;
+ new(static_cast(item_ptr(size() - 1))) T();
+ }
+ }
+
+ void reserve(size_type new_capacity) {
+ if (new_capacity > capacity()) {
+ change_capacity(new_capacity);
+ }
+ }
+
+ void shrink_to_fit() {
+ change_capacity(size());
+ }
+
+ void clear() {
+ resize(0);
+ }
+
+ iterator insert(iterator pos, const T& value) {
+ size_type p = pos - begin();
+ size_type new_size = size() + 1;
+ if (capacity() < new_size) {
+ change_capacity(new_size + (new_size >> 1));
+ }
+ memmove(item_ptr(p + 1), item_ptr(p), (size() - p) * sizeof(T));
+ _size++;
+ new(static_cast(item_ptr(p))) T(value);
+ return iterator(item_ptr(p));
+ }
+
+ void insert(iterator pos, size_type count, const T& value) {
+ size_type p = pos - begin();
+ size_type new_size = size() + count;
+ if (capacity() < new_size) {
+ change_capacity(new_size + (new_size >> 1));
+ }
+ memmove(item_ptr(p + count), item_ptr(p), (size() - p) * sizeof(T));
+ _size += count;
+ for (size_type i = 0; i < count; i++) {
+ new(static_cast(item_ptr(p + i))) T(value);
+ }
+ }
+
+ template
+ void insert(iterator pos, InputIterator first, InputIterator last) {
+ size_type p = pos - begin();
+ difference_type count = last - first;
+ size_type new_size = size() + count;
+ if (capacity() < new_size) {
+ change_capacity(new_size + (new_size >> 1));
+ }
+ memmove(item_ptr(p + count), item_ptr(p), (size() - p) * sizeof(T));
+ _size += count;
+ while (first != last) {
+ new(static_cast(item_ptr(p))) T(*first);
+ ++p;
+ ++first;
+ }
+ }
+
+ iterator erase(iterator pos) {
+ return erase(pos, pos + 1);
+ }
+
+ iterator erase(iterator first, iterator last) {
+ iterator p = first;
+ char* endp = (char*)&(*end());
+ while (p != last) {
+ (*p).~T();
+ _size--;
+ ++p;
+ }
+ memmove(&(*first), &(*last), endp - ((char*)(&(*last))));
+ return first;
+ }
+
+ void push_back(const T& value) {
+ size_type new_size = size() + 1;
+ if (capacity() < new_size) {
+ change_capacity(new_size + (new_size >> 1));
+ }
+ new(item_ptr(size())) T(value);
+ _size++;
+ }
+
+ void pop_back() {
+ erase(end() - 1, end());
+ }
+
+ T& front() {
+ return *item_ptr(0);
+ }
+
+ const T& front() const {
+ return *item_ptr(0);
+ }
+
+ T& back() {
+ return *item_ptr(size() - 1);
+ }
+
+ const T& back() const {
+ return *item_ptr(size() - 1);
+ }
+
+ void swap(prevector& other) {
+ std::swap(_union, other._union);
+ std::swap(_size, other._size);
+ }
+
+ ~prevector() {
+ clear();
+ if (!is_direct()) {
+ free(_union.indirect);
+ _union.indirect = NULL;
+ }
+ }
+
+ bool operator==(const prevector& other) const {
+ if (other.size() != size()) {
+ return false;
+ }
+ const_iterator b1 = begin();
+ const_iterator b2 = other.begin();
+ const_iterator e1 = end();
+ while (b1 != e1) {
+ if ((*b1) != (*b2)) {
+ return false;
+ }
+ ++b1;
+ ++b2;
+ }
+ return true;
+ }
+
+ bool operator!=(const prevector& other) const {
+ return !(*this == other);
+ }
+
+ bool operator<(const prevector& other) const {
+ if (size() < other.size()) {
+ return true;
+ }
+ if (size() > other.size()) {
+ return false;
+ }
+ const_iterator b1 = begin();
+ const_iterator b2 = other.begin();
+ const_iterator e1 = end();
+ while (b1 != e1) {
+ if ((*b1) < (*b2)) {
+ return true;
+ }
+ if ((*b2) < (*b1)) {
+ return false;
+ }
+ ++b1;
+ ++b2;
+ }
+ return false;
+ }
+
+ size_t allocated_memory() const {
+ if (is_direct()) {
+ return 0;
+ }
+ else {
+ return ((size_t)(sizeof(T))) * _union.capacity;
+ }
+ }
+
+ value_type* data() {
+ return item_ptr(0);
+ }
+
+ const value_type* data() const {
+ return item_ptr(0);
+ }
+};
+#pragma pack(pop)
+
+#endif
\ No newline at end of file
diff --git a/Project1/ripemd160.cpp b/Project1/ripemd160.cpp
new file mode 100644
index 0000000..0ea294c
--- /dev/null
+++ b/Project1/ripemd160.cpp
@@ -0,0 +1,292 @@
+// Copyright (c) 2014 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include "ripemd160.h"
+
+#include "common.h"
+
+#include
+
+// Internal implementation code.
+namespace
+{
+ /// Internal RIPEMD-160 implementation.
+ namespace ripemd160
+ {
+ uint32_t inline f1(uint32_t x, uint32_t y, uint32_t z) { return x ^ y ^ z; }
+ uint32_t inline f2(uint32_t x, uint32_t y, uint32_t z) { return (x & y) | (~x & z); }
+ uint32_t inline f3(uint32_t x, uint32_t y, uint32_t z) { return (x | ~y) ^ z; }
+ uint32_t inline f4(uint32_t x, uint32_t y, uint32_t z) { return (x & z) | (y & ~z); }
+ uint32_t inline f5(uint32_t x, uint32_t y, uint32_t z) { return x ^ (y | ~z); }
+
+ /** Initialize RIPEMD-160 state. */
+ void inline Initialize(uint32_t* s)
+ {
+ s[0] = 0x67452301ul;
+ s[1] = 0xEFCDAB89ul;
+ s[2] = 0x98BADCFEul;
+ s[3] = 0x10325476ul;
+ s[4] = 0xC3D2E1F0ul;
+ }
+
+ uint32_t inline rol(uint32_t x, int i) { return (x << i) | (x >> (32 - i)); }
+
+ void inline Round(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t f, uint32_t x, uint32_t k, int r)
+ {
+ a = rol(a + f + x + k, r) + e;
+ c = rol(c, 10);
+ }
+
+ void inline R11(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f1(b, c, d), x, 0, r); }
+ void inline R21(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f2(b, c, d), x, 0x5A827999ul, r); }
+ void inline R31(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f3(b, c, d), x, 0x6ED9EBA1ul, r); }
+ void inline R41(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f4(b, c, d), x, 0x8F1BBCDCul, r); }
+ void inline R51(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f5(b, c, d), x, 0xA953FD4Eul, r); }
+
+ void inline R12(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f5(b, c, d), x, 0x50A28BE6ul, r); }
+ void inline R22(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f4(b, c, d), x, 0x5C4DD124ul, r); }
+ void inline R32(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f3(b, c, d), x, 0x6D703EF3ul, r); }
+ void inline R42(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f2(b, c, d), x, 0x7A6D76E9ul, r); }
+ void inline R52(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f1(b, c, d), x, 0, r); }
+
+ /** Perform a RIPEMD-160 transformation, processing a 64-byte chunk. */
+ void Transform(uint32_t* s, const unsigned char* chunk)
+ {
+ uint32_t a1 = s[0], b1 = s[1], c1 = s[2], d1 = s[3], e1 = s[4];
+ uint32_t a2 = a1, b2 = b1, c2 = c1, d2 = d1, e2 = e1;
+ uint32_t w0 = ReadLE32(chunk + 0), w1 = ReadLE32(chunk + 4), w2 = ReadLE32(chunk + 8), w3 = ReadLE32(chunk + 12);
+ uint32_t w4 = ReadLE32(chunk + 16), w5 = ReadLE32(chunk + 20), w6 = ReadLE32(chunk + 24), w7 = ReadLE32(chunk + 28);
+ uint32_t w8 = ReadLE32(chunk + 32), w9 = ReadLE32(chunk + 36), w10 = ReadLE32(chunk + 40), w11 = ReadLE32(chunk + 44);
+ uint32_t w12 = ReadLE32(chunk + 48), w13 = ReadLE32(chunk + 52), w14 = ReadLE32(chunk + 56), w15 = ReadLE32(chunk + 60);
+
+ R11(a1, b1, c1, d1, e1, w0, 11);
+ R12(a2, b2, c2, d2, e2, w5, 8);
+ R11(e1, a1, b1, c1, d1, w1, 14);
+ R12(e2, a2, b2, c2, d2, w14, 9);
+ R11(d1, e1, a1, b1, c1, w2, 15);
+ R12(d2, e2, a2, b2, c2, w7, 9);
+ R11(c1, d1, e1, a1, b1, w3, 12);
+ R12(c2, d2, e2, a2, b2, w0, 11);
+ R11(b1, c1, d1, e1, a1, w4, 5);
+ R12(b2, c2, d2, e2, a2, w9, 13);
+ R11(a1, b1, c1, d1, e1, w5, 8);
+ R12(a2, b2, c2, d2, e2, w2, 15);
+ R11(e1, a1, b1, c1, d1, w6, 7);
+ R12(e2, a2, b2, c2, d2, w11, 15);
+ R11(d1, e1, a1, b1, c1, w7, 9);
+ R12(d2, e2, a2, b2, c2, w4, 5);
+ R11(c1, d1, e1, a1, b1, w8, 11);
+ R12(c2, d2, e2, a2, b2, w13, 7);
+ R11(b1, c1, d1, e1, a1, w9, 13);
+ R12(b2, c2, d2, e2, a2, w6, 7);
+ R11(a1, b1, c1, d1, e1, w10, 14);
+ R12(a2, b2, c2, d2, e2, w15, 8);
+ R11(e1, a1, b1, c1, d1, w11, 15);
+ R12(e2, a2, b2, c2, d2, w8, 11);
+ R11(d1, e1, a1, b1, c1, w12, 6);
+ R12(d2, e2, a2, b2, c2, w1, 14);
+ R11(c1, d1, e1, a1, b1, w13, 7);
+ R12(c2, d2, e2, a2, b2, w10, 14);
+ R11(b1, c1, d1, e1, a1, w14, 9);
+ R12(b2, c2, d2, e2, a2, w3, 12);
+ R11(a1, b1, c1, d1, e1, w15, 8);
+ R12(a2, b2, c2, d2, e2, w12, 6);
+
+ R21(e1, a1, b1, c1, d1, w7, 7);
+ R22(e2, a2, b2, c2, d2, w6, 9);
+ R21(d1, e1, a1, b1, c1, w4, 6);
+ R22(d2, e2, a2, b2, c2, w11, 13);
+ R21(c1, d1, e1, a1, b1, w13, 8);
+ R22(c2, d2, e2, a2, b2, w3, 15);
+ R21(b1, c1, d1, e1, a1, w1, 13);
+ R22(b2, c2, d2, e2, a2, w7, 7);
+ R21(a1, b1, c1, d1, e1, w10, 11);
+ R22(a2, b2, c2, d2, e2, w0, 12);
+ R21(e1, a1, b1, c1, d1, w6, 9);
+ R22(e2, a2, b2, c2, d2, w13, 8);
+ R21(d1, e1, a1, b1, c1, w15, 7);
+ R22(d2, e2, a2, b2, c2, w5, 9);
+ R21(c1, d1, e1, a1, b1, w3, 15);
+ R22(c2, d2, e2, a2, b2, w10, 11);
+ R21(b1, c1, d1, e1, a1, w12, 7);
+ R22(b2, c2, d2, e2, a2, w14, 7);
+ R21(a1, b1, c1, d1, e1, w0, 12);
+ R22(a2, b2, c2, d2, e2, w15, 7);
+ R21(e1, a1, b1, c1, d1, w9, 15);
+ R22(e2, a2, b2, c2, d2, w8, 12);
+ R21(d1, e1, a1, b1, c1, w5, 9);
+ R22(d2, e2, a2, b2, c2, w12, 7);
+ R21(c1, d1, e1, a1, b1, w2, 11);
+ R22(c2, d2, e2, a2, b2, w4, 6);
+ R21(b1, c1, d1, e1, a1, w14, 7);
+ R22(b2, c2, d2, e2, a2, w9, 15);
+ R21(a1, b1, c1, d1, e1, w11, 13);
+ R22(a2, b2, c2, d2, e2, w1, 13);
+ R21(e1, a1, b1, c1, d1, w8, 12);
+ R22(e2, a2, b2, c2, d2, w2, 11);
+
+ R31(d1, e1, a1, b1, c1, w3, 11);
+ R32(d2, e2, a2, b2, c2, w15, 9);
+ R31(c1, d1, e1, a1, b1, w10, 13);
+ R32(c2, d2, e2, a2, b2, w5, 7);
+ R31(b1, c1, d1, e1, a1, w14, 6);
+ R32(b2, c2, d2, e2, a2, w1, 15);
+ R31(a1, b1, c1, d1, e1, w4, 7);
+ R32(a2, b2, c2, d2, e2, w3, 11);
+ R31(e1, a1, b1, c1, d1, w9, 14);
+ R32(e2, a2, b2, c2, d2, w7, 8);
+ R31(d1, e1, a1, b1, c1, w15, 9);
+ R32(d2, e2, a2, b2, c2, w14, 6);
+ R31(c1, d1, e1, a1, b1, w8, 13);
+ R32(c2, d2, e2, a2, b2, w6, 6);
+ R31(b1, c1, d1, e1, a1, w1, 15);
+ R32(b2, c2, d2, e2, a2, w9, 14);
+ R31(a1, b1, c1, d1, e1, w2, 14);
+ R32(a2, b2, c2, d2, e2, w11, 12);
+ R31(e1, a1, b1, c1, d1, w7, 8);
+ R32(e2, a2, b2, c2, d2, w8, 13);
+ R31(d1, e1, a1, b1, c1, w0, 13);
+ R32(d2, e2, a2, b2, c2, w12, 5);
+ R31(c1, d1, e1, a1, b1, w6, 6);
+ R32(c2, d2, e2, a2, b2, w2, 14);
+ R31(b1, c1, d1, e1, a1, w13, 5);
+ R32(b2, c2, d2, e2, a2, w10, 13);
+ R31(a1, b1, c1, d1, e1, w11, 12);
+ R32(a2, b2, c2, d2, e2, w0, 13);
+ R31(e1, a1, b1, c1, d1, w5, 7);
+ R32(e2, a2, b2, c2, d2, w4, 7);
+ R31(d1, e1, a1, b1, c1, w12, 5);
+ R32(d2, e2, a2, b2, c2, w13, 5);
+
+ R41(c1, d1, e1, a1, b1, w1, 11);
+ R42(c2, d2, e2, a2, b2, w8, 15);
+ R41(b1, c1, d1, e1, a1, w9, 12);
+ R42(b2, c2, d2, e2, a2, w6, 5);
+ R41(a1, b1, c1, d1, e1, w11, 14);
+ R42(a2, b2, c2, d2, e2, w4, 8);
+ R41(e1, a1, b1, c1, d1, w10, 15);
+ R42(e2, a2, b2, c2, d2, w1, 11);
+ R41(d1, e1, a1, b1, c1, w0, 14);
+ R42(d2, e2, a2, b2, c2, w3, 14);
+ R41(c1, d1, e1, a1, b1, w8, 15);
+ R42(c2, d2, e2, a2, b2, w11, 14);
+ R41(b1, c1, d1, e1, a1, w12, 9);
+ R42(b2, c2, d2, e2, a2, w15, 6);
+ R41(a1, b1, c1, d1, e1, w4, 8);
+ R42(a2, b2, c2, d2, e2, w0, 14);
+ R41(e1, a1, b1, c1, d1, w13, 9);
+ R42(e2, a2, b2, c2, d2, w5, 6);
+ R41(d1, e1, a1, b1, c1, w3, 14);
+ R42(d2, e2, a2, b2, c2, w12, 9);
+ R41(c1, d1, e1, a1, b1, w7, 5);
+ R42(c2, d2, e2, a2, b2, w2, 12);
+ R41(b1, c1, d1, e1, a1, w15, 6);
+ R42(b2, c2, d2, e2, a2, w13, 9);
+ R41(a1, b1, c1, d1, e1, w14, 8);
+ R42(a2, b2, c2, d2, e2, w9, 12);
+ R41(e1, a1, b1, c1, d1, w5, 6);
+ R42(e2, a2, b2, c2, d2, w7, 5);
+ R41(d1, e1, a1, b1, c1, w6, 5);
+ R42(d2, e2, a2, b2, c2, w10, 15);
+ R41(c1, d1, e1, a1, b1, w2, 12);
+ R42(c2, d2, e2, a2, b2, w14, 8);
+
+ R51(b1, c1, d1, e1, a1, w4, 9);
+ R52(b2, c2, d2, e2, a2, w12, 8);
+ R51(a1, b1, c1, d1, e1, w0, 15);
+ R52(a2, b2, c2, d2, e2, w15, 5);
+ R51(e1, a1, b1, c1, d1, w5, 5);
+ R52(e2, a2, b2, c2, d2, w10, 12);
+ R51(d1, e1, a1, b1, c1, w9, 11);
+ R52(d2, e2, a2, b2, c2, w4, 9);
+ R51(c1, d1, e1, a1, b1, w7, 6);
+ R52(c2, d2, e2, a2, b2, w1, 12);
+ R51(b1, c1, d1, e1, a1, w12, 8);
+ R52(b2, c2, d2, e2, a2, w5, 5);
+ R51(a1, b1, c1, d1, e1, w2, 13);
+ R52(a2, b2, c2, d2, e2, w8, 14);
+ R51(e1, a1, b1, c1, d1, w10, 12);
+ R52(e2, a2, b2, c2, d2, w7, 6);
+ R51(d1, e1, a1, b1, c1, w14, 5);
+ R52(d2, e2, a2, b2, c2, w6, 8);
+ R51(c1, d1, e1, a1, b1, w1, 12);
+ R52(c2, d2, e2, a2, b2, w2, 13);
+ R51(b1, c1, d1, e1, a1, w3, 13);
+ R52(b2, c2, d2, e2, a2, w13, 6);
+ R51(a1, b1, c1, d1, e1, w8, 14);
+ R52(a2, b2, c2, d2, e2, w14, 5);
+ R51(e1, a1, b1, c1, d1, w11, 11);
+ R52(e2, a2, b2, c2, d2, w0, 15);
+ R51(d1, e1, a1, b1, c1, w6, 8);
+ R52(d2, e2, a2, b2, c2, w3, 13);
+ R51(c1, d1, e1, a1, b1, w15, 5);
+ R52(c2, d2, e2, a2, b2, w9, 11);
+ R51(b1, c1, d1, e1, a1, w13, 6);
+ R52(b2, c2, d2, e2, a2, w11, 11);
+
+ uint32_t t = s[0];
+ s[0] = s[1] + c1 + d2;
+ s[1] = s[2] + d1 + e2;
+ s[2] = s[3] + e1 + a2;
+ s[3] = s[4] + a1 + b2;
+ s[4] = t + b1 + c2;
+ }
+
+ } // namespace ripemd160
+
+} // namespace
+
+ ////// RIPEMD160
+
+CRIPEMD160::CRIPEMD160() : bytes(0)
+{
+ ripemd160::Initialize(s);
+}
+
+CRIPEMD160& CRIPEMD160::Write(const unsigned char* data, size_t len)
+{
+ const unsigned char* end = data + len;
+ size_t bufsize = bytes % 64;
+ if (bufsize && bufsize + len >= 64) {
+ // Fill the buffer, and process it.
+ memcpy(buf + bufsize, data, 64 - bufsize);
+ bytes += 64 - bufsize;
+ data += 64 - bufsize;
+ ripemd160::Transform(s, buf);
+ bufsize = 0;
+ }
+ while (end >= data + 64) {
+ // Process full chunks directly from the source.
+ ripemd160::Transform(s, data);
+ bytes += 64;
+ data += 64;
+ }
+ if (end > data) {
+ // Fill the buffer with what remains.
+ memcpy(buf + bufsize, data, end - data);
+ bytes += end - data;
+ }
+ return *this;
+}
+
+void CRIPEMD160::Finalize(unsigned char hash[OUTPUT_SIZE])
+{
+ static const unsigned char pad[64] = { 0x80 };
+ unsigned char sizedesc[8];
+ WriteLE64(sizedesc, bytes << 3);
+ Write(pad, 1 + ((119 - (bytes % 64)) % 64));
+ Write(sizedesc, 8);
+ WriteLE32(hash, s[0]);
+ WriteLE32(hash + 4, s[1]);
+ WriteLE32(hash + 8, s[2]);
+ WriteLE32(hash + 12, s[3]);
+ WriteLE32(hash + 16, s[4]);
+}
+
+CRIPEMD160& CRIPEMD160::Reset()
+{
+ bytes = 0;
+ ripemd160::Initialize(s);
+ return *this;
+}
\ No newline at end of file
diff --git a/Project1/ripemd160.h b/Project1/ripemd160.h
new file mode 100644
index 0000000..061ccf2
--- /dev/null
+++ b/Project1/ripemd160.h
@@ -0,0 +1,28 @@
+// Copyright (c) 2014 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_CRYPTO_RIPEMD160_H
+#define BITCOIN_CRYPTO_RIPEMD160_H
+
+#include
+#include
+
+/** A hasher class for RIPEMD-160. */
+class CRIPEMD160
+{
+private:
+ uint32_t s[5];
+ unsigned char buf[64];
+ uint64_t bytes;
+
+public:
+ static const size_t OUTPUT_SIZE = 20;
+
+ CRIPEMD160();
+ CRIPEMD160& Write(const unsigned char* data, size_t len);
+ void Finalize(unsigned char hash[OUTPUT_SIZE]);
+ CRIPEMD160& Reset();
+};
+
+#endif // BITCOIN_CRYPTO_RIPEMD160_H
\ No newline at end of file
diff --git a/Project1/script.cpp b/Project1/script.cpp
new file mode 100644
index 0000000..f7dc956
--- /dev/null
+++ b/Project1/script.cpp
@@ -0,0 +1,271 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2009-2015 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include "script.h"
+
+#include "tinyformat.h"
+#include "utilstrencodings.h"
+
+using namespace std;
+
+const char* GetOpName(opcodetype opcode)
+{
+ switch (opcode)
+ {
+ // push value
+ case OP_0: return "0";
+ case OP_PUSHDATA1: return "OP_PUSHDATA1";
+ case OP_PUSHDATA2: return "OP_PUSHDATA2";
+ case OP_PUSHDATA4: return "OP_PUSHDATA4";
+ case OP_1NEGATE: return "-1";
+ case OP_RESERVED: return "OP_RESERVED";
+ case OP_1: return "1";
+ case OP_2: return "2";
+ case OP_3: return "3";
+ case OP_4: return "4";
+ case OP_5: return "5";
+ case OP_6: return "6";
+ case OP_7: return "7";
+ case OP_8: return "8";
+ case OP_9: return "9";
+ case OP_10: return "10";
+ case OP_11: return "11";
+ case OP_12: return "12";
+ case OP_13: return "13";
+ case OP_14: return "14";
+ case OP_15: return "15";
+ case OP_16: return "16";
+
+ // control
+ case OP_NOP: return "OP_NOP";
+ case OP_VER: return "OP_VER";
+ case OP_IF: return "OP_IF";
+ case OP_NOTIF: return "OP_NOTIF";
+ case OP_VERIF: return "OP_VERIF";
+ case OP_VERNOTIF: return "OP_VERNOTIF";
+ case OP_ELSE: return "OP_ELSE";
+ case OP_ENDIF: return "OP_ENDIF";
+ case OP_VERIFY: return "OP_VERIFY";
+ case OP_RETURN: return "OP_RETURN";
+
+ // stack ops
+ case OP_TOALTSTACK: return "OP_TOALTSTACK";
+ case OP_FROMALTSTACK: return "OP_FROMALTSTACK";
+ case OP_2DROP: return "OP_2DROP";
+ case OP_2DUP: return "OP_2DUP";
+ case OP_3DUP: return "OP_3DUP";
+ case OP_2OVER: return "OP_2OVER";
+ case OP_2ROT: return "OP_2ROT";
+ case OP_2SWAP: return "OP_2SWAP";
+ case OP_IFDUP: return "OP_IFDUP";
+ case OP_DEPTH: return "OP_DEPTH";
+ case OP_DROP: return "OP_DROP";
+ case OP_DUP: return "OP_DUP";
+ case OP_NIP: return "OP_NIP";
+ case OP_OVER: return "OP_OVER";
+ case OP_PICK: return "OP_PICK";
+ case OP_ROLL: return "OP_ROLL";
+ case OP_ROT: return "OP_ROT";
+ case OP_SWAP: return "OP_SWAP";
+ case OP_TUCK: return "OP_TUCK";
+
+ // splice ops
+ case OP_CAT: return "OP_CAT";
+ case OP_SUBSTR: return "OP_SUBSTR";
+ case OP_LEFT: return "OP_LEFT";
+ case OP_RIGHT: return "OP_RIGHT";
+ case OP_SIZE: return "OP_SIZE";
+
+ // bit logic
+ case OP_INVERT: return "OP_INVERT";
+ case OP_AND: return "OP_AND";
+ case OP_OR: return "OP_OR";
+ case OP_XOR: return "OP_XOR";
+ case OP_EQUAL: return "OP_EQUAL";
+ case OP_EQUALVERIFY: return "OP_EQUALVERIFY";
+ case OP_RESERVED1: return "OP_RESERVED1";
+ case OP_RESERVED2: return "OP_RESERVED2";
+
+ // numeric
+ case OP_1ADD: return "OP_1ADD";
+ case OP_1SUB: return "OP_1SUB";
+ case OP_2MUL: return "OP_2MUL";
+ case OP_2DIV: return "OP_2DIV";
+ case OP_NEGATE: return "OP_NEGATE";
+ case OP_ABS: return "OP_ABS";
+ case OP_NOT: return "OP_NOT";
+ case OP_0NOTEQUAL: return "OP_0NOTEQUAL";
+ case OP_ADD: return "OP_ADD";
+ case OP_SUB: return "OP_SUB";
+ case OP_MUL: return "OP_MUL";
+ case OP_DIV: return "OP_DIV";
+ case OP_MOD: return "OP_MOD";
+ case OP_LSHIFT: return "OP_LSHIFT";
+ case OP_RSHIFT: return "OP_RSHIFT";
+ case OP_BOOLAND: return "OP_BOOLAND";
+ case OP_BOOLOR: return "OP_BOOLOR";
+ case OP_NUMEQUAL: return "OP_NUMEQUAL";
+ case OP_NUMEQUALVERIFY: return "OP_NUMEQUALVERIFY";
+ case OP_NUMNOTEQUAL: return "OP_NUMNOTEQUAL";
+ case OP_LESSTHAN: return "OP_LESSTHAN";
+ case OP_GREATERTHAN: return "OP_GREATERTHAN";
+ case OP_LESSTHANOREQUAL: return "OP_LESSTHANOREQUAL";
+ case OP_GREATERTHANOREQUAL: return "OP_GREATERTHANOREQUAL";
+ case OP_MIN: return "OP_MIN";
+ case OP_MAX: return "OP_MAX";
+ case OP_WITHIN: return "OP_WITHIN";
+
+ // crypto
+ case OP_RIPEMD160: return "OP_RIPEMD160";
+ case OP_SHA1: return "OP_SHA1";
+ case OP_SHA256: return "OP_SHA256";
+ case OP_HASH160: return "OP_HASH160";
+ case OP_HASH256: return "OP_HASH256";
+ case OP_CODESEPARATOR: return "OP_CODESEPARATOR";
+ case OP_CHECKSIG: return "OP_CHECKSIG";
+ case OP_CHECKSIGVERIFY: return "OP_CHECKSIGVERIFY";
+ case OP_CHECKMULTISIG: return "OP_CHECKMULTISIG";
+ case OP_CHECKMULTISIGVERIFY: return "OP_CHECKMULTISIGVERIFY";
+
+ // expanson
+ case OP_NOP1: return "OP_NOP1";
+ case OP_CHECKLOCKTIMEVERIFY: return "OP_CHECKLOCKTIMEVERIFY";
+ case OP_CHECKSEQUENCEVERIFY: return "OP_CHECKSEQUENCEVERIFY";
+ case OP_NOP4: return "OP_NOP4";
+ case OP_NOP5: return "OP_NOP5";
+ case OP_NOP6: return "OP_NOP6";
+ case OP_NOP7: return "OP_NOP7";
+ case OP_NOP8: return "OP_NOP8";
+ case OP_NOP9: return "OP_NOP9";
+ case OP_NOP10: return "OP_NOP10";
+
+ case OP_INVALIDOPCODE: return "OP_INVALIDOPCODE";
+
+ // Note:
+ // The template matching params OP_SMALLINTEGER/etc are defined in opcodetype enum
+ // as kind of implementation hack, they are *NOT* real opcodes. If found in real
+ // Script, just let the default: case deal with them.
+
+ default:
+ return "OP_UNKNOWN";
+ }
+}
+
+unsigned int CScript::GetSigOpCount(bool fAccurate) const
+{
+ unsigned int n = 0;
+ const_iterator pc = begin();
+ opcodetype lastOpcode = OP_INVALIDOPCODE;
+ while (pc < end())
+ {
+ opcodetype opcode;
+ if (!GetOp(pc, opcode))
+ break;
+ if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
+ n++;
+ else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
+ {
+ if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
+ n += DecodeOP_N(lastOpcode);
+ else
+ n += MAX_PUBKEYS_PER_MULTISIG;
+ }
+ lastOpcode = opcode;
+ }
+ return n;
+}
+
+unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
+{
+ if (!IsPayToScriptHash())
+ return GetSigOpCount(true);
+
+ // This is a pay-to-script-hash scriptPubKey;
+ // get the last item that the scriptSig
+ // pushes onto the stack:
+ const_iterator pc = scriptSig.begin();
+ vector data;
+ while (pc < scriptSig.end())
+ {
+ opcodetype opcode;
+ if (!scriptSig.GetOp(pc, opcode, data))
+ return 0;
+ if (opcode > OP_16)
+ return 0;
+ }
+
+ /// ... and return its opcount:
+ CScript subscript(data.begin(), data.end());
+ return subscript.GetSigOpCount(true);
+}
+
+bool CScript::IsPayToScriptHash() const
+{
+ // Extra-fast test for pay-to-script-hash CScripts:
+ return (this->size() == 23 &&
+ (*this)[0] == OP_HASH160 &&
+ (*this)[1] == 0x14 &&
+ (*this)[22] == OP_EQUAL);
+}
+
+bool CScript::IsPayToWitnessScriptHash() const
+{
+ // Extra-fast test for pay-to-witness-script-hash CScripts:
+ return (this->size() == 34 &&
+ (*this)[0] == OP_0 &&
+ (*this)[1] == 0x20);
+}
+
+// A witness program is any valid CScript that consists of a 1-byte push opcode
+// followed by a data push between 2 and 40 bytes.
+bool CScript::IsWitnessProgram(int& version, std::vector& program) const
+{
+ if (this->size() < 4 || this->size() > 42) {
+ return false;
+ }
+ if ((*this)[0] != OP_0 && ((*this)[0] < OP_1 || (*this)[0] > OP_16)) {
+ return false;
+ }
+ if ((size_t)((*this)[1] + 2) == this->size()) {
+ version = DecodeOP_N((opcodetype)(*this)[0]);
+ program = std::vector(this->begin() + 2, this->end());
+ return true;
+ }
+ return false;
+}
+
+bool CScript::IsPushOnly(const_iterator pc) const
+{
+ while (pc < end())
+ {
+ opcodetype opcode;
+ if (!GetOp(pc, opcode))
+ return false;
+ // Note that IsPushOnly() *does* consider OP_RESERVED to be a
+ // push-type opcode, however execution of OP_RESERVED fails, so
+ // it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to
+ // the P2SH special validation code being executed.
+ if (opcode > OP_16)
+ return false;
+ }
+ return true;
+}
+
+bool CScript::IsPushOnly() const
+{
+ return this->IsPushOnly(begin());
+}
+
+std::string CScriptWitness::ToString() const
+{
+ std::string ret = "CScriptWitness(";
+ for (unsigned int i = 0; i < stack.size(); i++) {
+ if (i) {
+ ret += ", ";
+ }
+ ret += HexStr(stack[i]);
+ }
+ return ret + ")";
+}
\ No newline at end of file
diff --git a/Project1/script.h b/Project1/script.h
new file mode 100644
index 0000000..f53e5e5
--- /dev/null
+++ b/Project1/script.h
@@ -0,0 +1,670 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2009-2015 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_SCRIPT_SCRIPT_H
+#define BITCOIN_SCRIPT_SCRIPT_H
+
+#include "common.h"
+#include "prevector.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+// Maximum number of bytes pushable to the stack
+static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520;
+
+// Maximum number of non-push operations per script
+static const int MAX_OPS_PER_SCRIPT = 201;
+
+// Maximum number of public keys per multisig
+static const int MAX_PUBKEYS_PER_MULTISIG = 20;
+
+// Maximum script length in bytes
+static const int MAX_SCRIPT_SIZE = 10000;
+
+// Threshold for nLockTime: below this value it is interpreted as block number,
+// otherwise as UNIX timestamp.
+static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
+
+template
+std::vector ToByteVector(const T& in)
+{
+ return std::vector(in.begin(), in.end());
+}
+
+/** Script opcodes */
+enum opcodetype
+{
+ // push value
+ OP_0 = 0x00,
+ OP_FALSE = OP_0,
+ OP_PUSHDATA1 = 0x4c,
+ OP_PUSHDATA2 = 0x4d,
+ OP_PUSHDATA4 = 0x4e,
+ OP_1NEGATE = 0x4f,
+ OP_RESERVED = 0x50,
+ OP_1 = 0x51,
+ OP_TRUE = OP_1,
+ OP_2 = 0x52,
+ OP_3 = 0x53,
+ OP_4 = 0x54,
+ OP_5 = 0x55,
+ OP_6 = 0x56,
+ OP_7 = 0x57,
+ OP_8 = 0x58,
+ OP_9 = 0x59,
+ OP_10 = 0x5a,
+ OP_11 = 0x5b,
+ OP_12 = 0x5c,
+ OP_13 = 0x5d,
+ OP_14 = 0x5e,
+ OP_15 = 0x5f,
+ OP_16 = 0x60,
+
+ // control
+ OP_NOP = 0x61,
+ OP_VER = 0x62,
+ OP_IF = 0x63,
+ OP_NOTIF = 0x64,
+ OP_VERIF = 0x65,
+ OP_VERNOTIF = 0x66,
+ OP_ELSE = 0x67,
+ OP_ENDIF = 0x68,
+ OP_VERIFY = 0x69,
+ OP_RETURN = 0x6a,
+
+ // stack ops
+ OP_TOALTSTACK = 0x6b,
+ OP_FROMALTSTACK = 0x6c,
+ OP_2DROP = 0x6d,
+ OP_2DUP = 0x6e,
+ OP_3DUP = 0x6f,
+ OP_2OVER = 0x70,
+ OP_2ROT = 0x71,
+ OP_2SWAP = 0x72,
+ OP_IFDUP = 0x73,
+ OP_DEPTH = 0x74,
+ OP_DROP = 0x75,
+ OP_DUP = 0x76,
+ OP_NIP = 0x77,
+ OP_OVER = 0x78,
+ OP_PICK = 0x79,
+ OP_ROLL = 0x7a,
+ OP_ROT = 0x7b,
+ OP_SWAP = 0x7c,
+ OP_TUCK = 0x7d,
+
+ // splice ops
+ OP_CAT = 0x7e,
+ OP_SUBSTR = 0x7f,
+ OP_LEFT = 0x80,
+ OP_RIGHT = 0x81,
+ OP_SIZE = 0x82,
+
+ // bit logic
+ OP_INVERT = 0x83,
+ OP_AND = 0x84,
+ OP_OR = 0x85,
+ OP_XOR = 0x86,
+ OP_EQUAL = 0x87,
+ OP_EQUALVERIFY = 0x88,
+ OP_RESERVED1 = 0x89,
+ OP_RESERVED2 = 0x8a,
+
+ // numeric
+ OP_1ADD = 0x8b,
+ OP_1SUB = 0x8c,
+ OP_2MUL = 0x8d,
+ OP_2DIV = 0x8e,
+ OP_NEGATE = 0x8f,
+ OP_ABS = 0x90,
+ OP_NOT = 0x91,
+ OP_0NOTEQUAL = 0x92,
+
+ OP_ADD = 0x93,
+ OP_SUB = 0x94,
+ OP_MUL = 0x95,
+ OP_DIV = 0x96,
+ OP_MOD = 0x97,
+ OP_LSHIFT = 0x98,
+ OP_RSHIFT = 0x99,
+
+ OP_BOOLAND = 0x9a,
+ OP_BOOLOR = 0x9b,
+ OP_NUMEQUAL = 0x9c,
+ OP_NUMEQUALVERIFY = 0x9d,
+ OP_NUMNOTEQUAL = 0x9e,
+ OP_LESSTHAN = 0x9f,
+ OP_GREATERTHAN = 0xa0,
+ OP_LESSTHANOREQUAL = 0xa1,
+ OP_GREATERTHANOREQUAL = 0xa2,
+ OP_MIN = 0xa3,
+ OP_MAX = 0xa4,
+
+ OP_WITHIN = 0xa5,
+
+ // crypto
+ OP_RIPEMD160 = 0xa6,
+ OP_SHA1 = 0xa7,
+ OP_SHA256 = 0xa8,
+ OP_HASH160 = 0xa9,
+ OP_HASH256 = 0xaa,
+ OP_CODESEPARATOR = 0xab,
+ OP_CHECKSIG = 0xac,
+ OP_CHECKSIGVERIFY = 0xad,
+ OP_CHECKMULTISIG = 0xae,
+ OP_CHECKMULTISIGVERIFY = 0xaf,
+
+ // expansion
+ OP_NOP1 = 0xb0,
+ OP_CHECKLOCKTIMEVERIFY = 0xb1,
+ OP_NOP2 = OP_CHECKLOCKTIMEVERIFY,
+ OP_CHECKSEQUENCEVERIFY = 0xb2,
+ OP_NOP3 = OP_CHECKSEQUENCEVERIFY,
+ OP_NOP4 = 0xb3,
+ OP_NOP5 = 0xb4,
+ OP_NOP6 = 0xb5,
+ OP_NOP7 = 0xb6,
+ OP_NOP8 = 0xb7,
+ OP_NOP9 = 0xb8,
+ OP_NOP10 = 0xb9,
+
+
+ // template matching params
+ OP_SMALLINTEGER = 0xfa,
+ OP_PUBKEYS = 0xfb,
+ OP_PUBKEYHASH = 0xfd,
+ OP_PUBKEY = 0xfe,
+
+ OP_INVALIDOPCODE = 0xff,
+};
+
+const char* GetOpName(opcodetype opcode);
+
+class scriptnum_error : public std::runtime_error
+{
+public:
+ explicit scriptnum_error(const std::string& str) : std::runtime_error(str) {}
+};
+
+class CScriptNum
+{
+ /**
+ * Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers.
+ * The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1],
+ * but results may overflow (and are valid as long as they are not used in a subsequent
+ * numeric operation). CScriptNum enforces those semantics by storing results as
+ * an int64 and allowing out-of-range values to be returned as a vector of bytes but
+ * throwing an exception if arithmetic is done or the result is interpreted as an integer.
+ */
+public:
+
+ explicit CScriptNum(const int64_t& n)
+ {
+ m_value = n;
+ }
+
+ static const size_t nDefaultMaxNumSize = 4;
+
+ explicit CScriptNum(const std::vector& vch, bool fRequireMinimal,
+ const size_t nMaxNumSize = nDefaultMaxNumSize)
+ {
+ if (vch.size() > nMaxNumSize) {
+ throw scriptnum_error("script number overflow");
+ }
+ if (fRequireMinimal && vch.size() > 0) {
+ // Check that the number is encoded with the minimum possible
+ // number of bytes.
+ //
+ // If the most-significant-byte - excluding the sign bit - is zero
+ // then we're not minimal. Note how this test also rejects the
+ // negative-zero encoding, 0x80.
+ if ((vch.back() & 0x7f) == 0) {
+ // One exception: if there's more than one byte and the most
+ // significant bit of the second-most-significant-byte is set
+ // it would conflict with the sign bit. An example of this case
+ // is +-255, which encode to 0xff00 and 0xff80 respectively.
+ // (big-endian).
+ if (vch.size() <= 1 || (vch[vch.size() - 2] & 0x80) == 0) {
+ throw scriptnum_error("non-minimally encoded script number");
+ }
+ }
+ }
+ m_value = set_vch(vch);
+ }
+
+ inline bool operator==(const int64_t& rhs) const { return m_value == rhs; }
+ inline bool operator!=(const int64_t& rhs) const { return m_value != rhs; }
+ inline bool operator<=(const int64_t& rhs) const { return m_value <= rhs; }
+ inline bool operator< (const int64_t& rhs) const { return m_value < rhs; }
+ inline bool operator>=(const int64_t& rhs) const { return m_value >= rhs; }
+ inline bool operator> (const int64_t& rhs) const { return m_value > rhs; }
+
+ inline bool operator==(const CScriptNum& rhs) const { return operator==(rhs.m_value); }
+ inline bool operator!=(const CScriptNum& rhs) const { return operator!=(rhs.m_value); }
+ inline bool operator<=(const CScriptNum& rhs) const { return operator<=(rhs.m_value); }
+ inline bool operator< (const CScriptNum& rhs) const { return operator< (rhs.m_value); }
+ inline bool operator>=(const CScriptNum& rhs) const { return operator>=(rhs.m_value); }
+ inline bool operator> (const CScriptNum& rhs) const { return operator> (rhs.m_value); }
+
+ inline CScriptNum operator+(const int64_t& rhs) const { return CScriptNum(m_value + rhs); }
+ inline CScriptNum operator-(const int64_t& rhs) const { return CScriptNum(m_value - rhs); }
+ inline CScriptNum operator+(const CScriptNum& rhs) const { return operator+(rhs.m_value); }
+ inline CScriptNum operator-(const CScriptNum& rhs) const { return operator-(rhs.m_value); }
+
+ inline CScriptNum& operator+=(const CScriptNum& rhs) { return operator+=(rhs.m_value); }
+ inline CScriptNum& operator-=(const CScriptNum& rhs) { return operator-=(rhs.m_value); }
+
+ inline CScriptNum operator&(const int64_t& rhs) const { return CScriptNum(m_value & rhs); }
+ inline CScriptNum operator&(const CScriptNum& rhs) const { return operator&(rhs.m_value); }
+
+ inline CScriptNum& operator&=(const CScriptNum& rhs) { return operator&=(rhs.m_value); }
+
+ inline CScriptNum operator-() const
+ {
+ assert(m_value != std::numeric_limits::min());
+ return CScriptNum(-m_value);
+ }
+
+ inline CScriptNum& operator=(const int64_t& rhs)
+ {
+ m_value = rhs;
+ return *this;
+ }
+
+ inline CScriptNum& operator+=(const int64_t& rhs)
+ {
+ assert(rhs == 0 || (rhs > 0 && m_value <= std::numeric_limits::max() - rhs) ||
+ (rhs < 0 && m_value >= std::numeric_limits::min() - rhs));
+ m_value += rhs;
+ return *this;
+ }
+
+ inline CScriptNum& operator-=(const int64_t& rhs)
+ {
+ assert(rhs == 0 || (rhs > 0 && m_value >= std::numeric_limits::min() + rhs) ||
+ (rhs < 0 && m_value <= std::numeric_limits::max() + rhs));
+ m_value -= rhs;
+ return *this;
+ }
+
+ inline CScriptNum& operator&=(const int64_t& rhs)
+ {
+ m_value &= rhs;
+ return *this;
+ }
+
+ int getint() const
+ {
+ if (m_value > std::numeric_limits::max())
+ return std::numeric_limits::max();
+ else if (m_value < std::numeric_limits::min())
+ return std::numeric_limits::min();
+ return m_value;
+ }
+
+ std::vector getvch() const
+ {
+ return serialize(m_value);
+ }
+
+ static std::vector serialize(const int64_t& value)
+ {
+ if (value == 0)
+ return std::vector();
+
+ std::vector result;
+ const bool neg = value < 0;
+ uint64_t absvalue = neg ? -value : value;
+
+ while (absvalue)
+ {
+ result.push_back(absvalue & 0xff);
+ absvalue >>= 8;
+ }
+
+ // - If the most significant byte is >= 0x80 and the value is positive, push a
+ // new zero-byte to make the significant byte < 0x80 again.
+
+ // - If the most significant byte is >= 0x80 and the value is negative, push a
+ // new 0x80 byte that will be popped off when converting to an integral.
+
+ // - If the most significant byte is < 0x80 and the value is negative, add
+ // 0x80 to it, since it will be subtracted and interpreted as a negative when
+ // converting to an integral.
+
+ if (result.back() & 0x80)
+ result.push_back(neg ? 0x80 : 0);
+ else if (neg)
+ result.back() |= 0x80;
+
+ return result;
+ }
+
+private:
+ static int64_t set_vch(const std::vector& vch)
+ {
+ if (vch.empty())
+ return 0;
+
+ int64_t result = 0;
+ for (size_t i = 0; i != vch.size(); ++i)
+ result |= static_cast(vch[i]) << 8 * i;
+
+ // If the input vector's most significant byte is 0x80, remove it from
+ // the result's msb and return a negative.
+ if (vch.back() & 0x80)
+ return -((int64_t)(result & ~(0x80ULL << (8 * (vch.size() - 1)))));
+
+ return result;
+ }
+
+ int64_t m_value;
+};
+
+typedef prevector<28, unsigned char> CScriptBase;
+
+/** Serialized script, used inside transaction inputs and outputs */
+class CScript : public CScriptBase
+{
+protected:
+ CScript& push_int64(int64_t n)
+ {
+ if (n == -1 || (n >= 1 && n <= 16))
+ {
+ push_back(n + (OP_1 - 1));
+ }
+ else if (n == 0)
+ {
+ push_back(OP_0);
+ }
+ else
+ {
+ *this << CScriptNum::serialize(n);
+ }
+ return *this;
+ }
+public:
+ CScript() { }
+ CScript(const CScript& b) : CScriptBase(b.begin(), b.end()) { }
+ CScript(const_iterator pbegin, const_iterator pend) : CScriptBase(pbegin, pend) { }
+ CScript(std::vector::const_iterator pbegin, std::vector::const_iterator pend) : CScriptBase(pbegin, pend) { }
+ CScript(const unsigned char* pbegin, const unsigned char* pend) : CScriptBase(pbegin, pend) { }
+
+ CScript& operator+=(const CScript& b)
+ {
+ insert(end(), b.begin(), b.end());
+ return *this;
+ }
+
+ friend CScript operator+(const CScript& a, const CScript& b)
+ {
+ CScript ret = a;
+ ret += b;
+ return ret;
+ }
+
+ CScript(int64_t b) { operator<<(b); }
+
+ explicit CScript(opcodetype b) { operator<<(b); }
+ explicit CScript(const CScriptNum& b) { operator<<(b); }
+ explicit CScript(const std::vector& b) { operator<<(b); }
+
+
+ CScript& operator<<(int64_t b) { return push_int64(b); }
+
+ CScript& operator<<(opcodetype opcode)
+ {
+ if (opcode < 0 || opcode > 0xff)
+ throw std::runtime_error("CScript::operator<<(): invalid opcode");
+ insert(end(), (unsigned char)opcode);
+ return *this;
+ }
+
+ CScript& operator<<(const CScriptNum& b)
+ {
+ *this << b.getvch();
+ return *this;
+ }
+
+ CScript& operator<<(const std::vector& b)
+ {
+ if (b.size() < OP_PUSHDATA1)
+ {
+ insert(end(), (unsigned char)b.size());
+ }
+ else if (b.size() <= 0xff)
+ {
+ insert(end(), OP_PUSHDATA1);
+ insert(end(), (unsigned char)b.size());
+ }
+ else if (b.size() <= 0xffff)
+ {
+ insert(end(), OP_PUSHDATA2);
+ uint8_t data[2];
+ WriteLE16(data, b.size());
+ insert(end(), data, data + sizeof(data));
+ }
+ else
+ {
+ insert(end(), OP_PUSHDATA4);
+ uint8_t data[4];
+ WriteLE32(data, b.size());
+ insert(end(), data, data + sizeof(data));
+ }
+ insert(end(), b.begin(), b.end());
+ return *this;
+ }
+
+ CScript& operator<<(const CScript& b)
+ {
+ // I'm not sure if this should push the script or concatenate scripts.
+ // If there's ever a use for pushing a script onto a script, delete this member fn
+ assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
+ return *this;
+ }
+
+
+ bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector& vchRet)
+ {
+ // Wrapper so it can be called with either iterator or const_iterator
+ const_iterator pc2 = pc;
+ bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
+ pc = begin() + (pc2 - begin());
+ return fRet;
+ }
+
+ bool GetOp(iterator& pc, opcodetype& opcodeRet)
+ {
+ const_iterator pc2 = pc;
+ bool fRet = GetOp2(pc2, opcodeRet, NULL);
+ pc = begin() + (pc2 - begin());
+ return fRet;
+ }
+
+ bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector& vchRet) const
+ {
+ return GetOp2(pc, opcodeRet, &vchRet);
+ }
+
+ bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
+ {
+ return GetOp2(pc, opcodeRet, NULL);
+ }
+
+ bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector* pvchRet) const
+ {
+ opcodeRet = OP_INVALIDOPCODE;
+ if (pvchRet)
+ pvchRet->clear();
+ if (pc >= end())
+ return false;
+
+ // Read instruction
+ if (end() - pc < 1)
+ return false;
+ unsigned int opcode = *pc++;
+
+ // Immediate operand
+ if (opcode <= OP_PUSHDATA4)
+ {
+ unsigned int nSize = 0;
+ if (opcode < OP_PUSHDATA1)
+ {
+ nSize = opcode;
+ }
+ else if (opcode == OP_PUSHDATA1)
+ {
+ if (end() - pc < 1)
+ return false;
+ nSize = *pc++;
+ }
+ else if (opcode == OP_PUSHDATA2)
+ {
+ if (end() - pc < 2)
+ return false;
+ nSize = ReadLE16(&pc[0]);
+ pc += 2;
+ }
+ else if (opcode == OP_PUSHDATA4)
+ {
+ if (end() - pc < 4)
+ return false;
+ nSize = ReadLE32(&pc[0]);
+ pc += 4;
+ }
+ if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
+ return false;
+ if (pvchRet)
+ pvchRet->assign(pc, pc + nSize);
+ pc += nSize;
+ }
+
+ opcodeRet = (opcodetype)opcode;
+ return true;
+ }
+
+ /** Encode/decode small integers: */
+ static int DecodeOP_N(opcodetype opcode)
+ {
+ if (opcode == OP_0)
+ return 0;
+ assert(opcode >= OP_1 && opcode <= OP_16);
+ return (int)opcode - (int)(OP_1 - 1);
+ }
+ static opcodetype EncodeOP_N(int n)
+ {
+ assert(n >= 0 && n <= 16);
+ if (n == 0)
+ return OP_0;
+ return (opcodetype)(OP_1 + n - 1);
+ }
+
+ int FindAndDelete(const CScript& b)
+ {
+ int nFound = 0;
+ if (b.empty())
+ return nFound;
+ CScript result;
+ iterator pc = begin(), pc2 = begin();
+ opcodetype opcode;
+ do
+ {
+ result.insert(result.end(), pc2, pc);
+ while (static_cast(end() - pc) >= b.size() && std::equal(b.begin(), b.end(), pc))
+ {
+ pc = pc + b.size();
+ ++nFound;
+ }
+ pc2 = pc;
+ } while (GetOp(pc, opcode));
+
+ if (nFound > 0) {
+ result.insert(result.end(), pc2, end());
+ *this = result;
+ }
+
+ return nFound;
+ }
+ int Find(opcodetype op) const
+ {
+ int nFound = 0;
+ opcodetype opcode;
+ for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
+ if (opcode == op)
+ ++nFound;
+ return nFound;
+ }
+
+ /**
+ * Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
+ * as 20 sigops. With pay-to-script-hash, that changed:
+ * CHECKMULTISIGs serialized in scriptSigs are
+ * counted more accurately, assuming they are of the form
+ * ... OP_N CHECKMULTISIG ...
+ */
+ unsigned int GetSigOpCount(bool fAccurate) const;
+
+ /**
+ * Accurately count sigOps, including sigOps in
+ * pay-to-script-hash transactions:
+ */
+ unsigned int GetSigOpCount(const CScript& scriptSig) const;
+
+ bool IsPayToScriptHash() const;
+ bool IsPayToWitnessScriptHash() const;
+ bool IsWitnessProgram(int& version, std::vector& program) const;
+
+ /** Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical). */
+ bool IsPushOnly(const_iterator pc) const;
+ bool IsPushOnly() const;
+
+ /**
+ * Returns whether the script is guaranteed to fail at execution,
+ * regardless of the initial stack. This allows outputs to be pruned
+ * instantly when entering the UTXO set.
+ */
+ bool IsUnspendable() const
+ {
+ return (size() > 0 && *begin() == OP_RETURN) || (size() > MAX_SCRIPT_SIZE);
+ }
+
+ void clear()
+ {
+ // The default std::vector::clear() does not release memory.
+ CScriptBase().swap(*this);
+ }
+};
+
+struct CScriptWitness
+{
+ // Note that this encodes the data elements being pushed, rather than
+ // encoding them as a CScript that pushes them.
+ std::vector > stack;
+
+ // Some compilers complain without a default constructor
+ CScriptWitness() { }
+
+ bool IsNull() const { return stack.empty(); }
+
+ std::string ToString() const;
+};
+
+class CReserveScript
+{
+public:
+ CScript reserveScript;
+ virtual void KeepScript() {}
+ CReserveScript() {}
+ virtual ~CReserveScript() {}
+};
+
+#endif // BITCOIN_SCRIPT_SCRIPT_H
\ No newline at end of file
diff --git a/Project1/serialize.h b/Project1/serialize.h
new file mode 100644
index 0000000..949d4c1
--- /dev/null
+++ b/Project1/serialize.h
@@ -0,0 +1,928 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2009-2015 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_SERIALIZE_H
+#define BITCOIN_SERIALIZE_H
+
+#include "endian.h"
+
+#include
+#include
+#include
+#include
+#include